]> gerrit.simantics Code Review - simantics/sysdyn.git/commitdiff
Created Simantics System Dynamics 1.8 branch at /sysdyn/branches/1.8.
authorlehtonen <lehtonen@ac1ea38d-2e2b-0410-8846-a27921b304fc>
Mon, 23 Jun 2014 05:22:31 +0000 (05:22 +0000)
committerlehtonen <lehtonen@ac1ea38d-2e2b-0410-8846-a27921b304fc>
Mon, 23 Jun 2014 05:22:31 +0000 (05:22 +0000)
Tag this as 1.8.1 when its done.

refs #4984

git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/branches@29679 ac1ea38d-2e2b-0410-8846-a27921b304fc

1843 files changed:
1.8/fi.semantum.sysdyn.solver/.classpath [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/.project [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/build.properties [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Activator.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Addition.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/And.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Application.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Argument.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ArgumentList.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Array.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ArraySliceExpression.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Assignment.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Constant.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Declaration.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Derivate.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Derivative.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Division.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwiseDivision.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwisePower.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwiseProduct.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/EnumElementsVariableBase.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/EnumSizeVariableBase.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Environment.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Equals.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForArray.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForIndex.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForStatement.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Frame.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Function.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/GreaterOrEqualThan.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/GreaterThan.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IEnvironment.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IExpression.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IFrame.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IStatement.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ISystem.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IfStatement.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IfThenElse.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LessOrEqualThan.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LessThan.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LineReader.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Model.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/MultiStatement.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Multiplication.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Negation.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NodeCache.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NodeClass.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NotEquals.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NullModification.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Or.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ParameterDeclaration.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Parser.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Power.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Solver.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/SolverUtils.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Statement.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/StatementList.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Subtraction.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/TimeVariable.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/UnassignedVariableException.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Utils.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Variable.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/VariableBase.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/VariableDeclaration.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/While.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/JJTModelParserState.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParser.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserConstants.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserTokenManager.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserTreeConstants.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelicaParser.jj [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelicaParser.jjt [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/Node.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ParseException.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/SimpleCharStream.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/SimpleNode.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/Token.java [new file with mode: 0644]
1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/TokenMgrError.java [new file with mode: 0644]
1.8/installer/.project [new file with mode: 0644]
1.8/installer/7za/7-zip.chm [new file with mode: 0644]
1.8/installer/7za/7z.sfx [new file with mode: 0644]
1.8/installer/7za/7zS.sfx [new file with mode: 0644]
1.8/installer/7za/7zSD.sfx [new file with mode: 0644]
1.8/installer/7za/7za.dll [new file with mode: 0644]
1.8/installer/7za/7za.exe [new file with mode: 0644]
1.8/installer/7za/7zr.exe [new file with mode: 0644]
1.8/installer/7za/7zxa.dll [new file with mode: 0644]
1.8/installer/7za/Installer/config.txt [new file with mode: 0644]
1.8/installer/7za/Installer/cr.bat [new file with mode: 0644]
1.8/installer/7za/Installer/readme.txt [new file with mode: 0644]
1.8/installer/7za/copying.txt [new file with mode: 0644]
1.8/installer/7za/history.txt [new file with mode: 0644]
1.8/installer/7za/license.txt [new file with mode: 0644]
1.8/installer/7za/readme.txt [new file with mode: 0644]
1.8/installer/7za/upx.exe [new file with mode: 0644]
1.8/installer/CustomLangpack_eng.xml [new file with mode: 0644]
1.8/installer/EPL.html [new file with mode: 0644]
1.8/installer/TargetDir.txt.unix [new file with mode: 0644]
1.8/installer/TargetDir.txt.windows [new file with mode: 0644]
1.8/installer/build.properties.unix [new file with mode: 0644]
1.8/installer/build.properties.windows [new file with mode: 0644]
1.8/installer/build.xml [new file with mode: 0644]
1.8/installer/custom/NonBlankTargetPanel.java [new file with mode: 0644]
1.8/installer/custom/build.xml [new file with mode: 0644]
1.8/installer/custom/izpack-src-build.xml [new file with mode: 0644]
1.8/installer/default_shortcut_specification.xml [new file with mode: 0644]
1.8/installer/download [new file with mode: 0755]
1.8/installer/download.bat [new file with mode: 0644]
1.8/installer/files/Microsoft.VC90.CRT.setup.exe [new file with mode: 0644]
1.8/installer/files/install_msvcrt.bat [new file with mode: 0644]
1.8/installer/files/jre-6u29-windows-i586-iftw.exe [new file with mode: 0644]
1.8/installer/installer.xml [new file with mode: 0644]
1.8/installer/side.png [new file with mode: 0644]
1.8/installer/side.svg [new file with mode: 0644]
1.8/installer/unzip.exe [new file with mode: 0644]
1.8/installer/userInputSpec.xml [new file with mode: 0644]
1.8/installer/wget.exe [new file with mode: 0644]
1.8/org.simantics.fmu.me.win32/.classpath [new file with mode: 0644]
1.8/org.simantics.fmu.me.win32/.project [new file with mode: 0644]
1.8/org.simantics.fmu.me.win32/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.fmu.me.win32/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.fmu.me.win32/build.properties [new file with mode: 0644]
1.8/org.simantics.fmu.me.win32/libraries/FMUSimulator.dll [new file with mode: 0644]
1.8/org.simantics.fmu.me.win32/libraries/miniunz.dll [new file with mode: 0644]
1.8/org.simantics.fmu.me.win32/libraries/zlibwapi.dll [new file with mode: 0644]
1.8/org.simantics.fmu/.classpath [new file with mode: 0644]
1.8/org.simantics.fmu/.project [new file with mode: 0644]
1.8/org.simantics.fmu/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/7z.dll [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/7z.exe [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/License.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/fmusim_cs.exe [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/fmusim_me.exe [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/FmuSdk_reference.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/bouncingBallCalc.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmu10-xml-schema.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmus.jpg [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmusdk_license.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/Model.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/bouncingBall.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/dq.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/inc.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/values.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/vanDerPol.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/bouncingBall.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/dq.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/inc.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/values.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/vanDerPol.fmu [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmusdk.zip [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/fmusim.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/run_all.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_all.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_fmusim_cs.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_fmusim_me.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/fmusim_cs/fmi_cs.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/fmusim_cs/main.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/include/fmiFunctions.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/include/fmiPlatformTypes.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/fmusim_me/fmi_me.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/fmusim_me/main.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/include/fmiModelFunctions.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/include/fmiModelTypes.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/bouncingBall.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/plot_h.PNG [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/build_fmu.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/cs.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/dq.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/plot_x.PNG [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/fmuTemplate.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/fmuTemplate.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/inc.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/plot_counter.PNG [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/me.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/values.PNG [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/values.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/plot_states.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/vanDerPol.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/COPYING.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/expat.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/expat_external.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/libexpatMT.lib [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/sim_support.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/sim_support.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/stack.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/stack.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/xml_parser.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/xml_parser.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_all.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_fmusim_cs.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_fmusim_me.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/fmusim_cs/fmi_cs.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/fmusim_cs/main.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/include/fmiFunctions.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/include/fmiPlatformTypes.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/fmusim_me/fmi_me.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/fmusim_me/main.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/include/fmiModelFunctions.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/include/fmiModelTypes.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/bouncingBall.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/plot_h.PNG [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/build_fmu.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/cs.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/dq.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/plot_x.PNG [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/fmuTemplate.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/fmuTemplate.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/inc.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/plot_counter.PNG [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/me.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/values.PNG [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/values.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/_main.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/model.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/plot_states.png [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/vanDerPol.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/COPYING.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/expat.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/expat_external.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/libexpatMT.lib [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/sim_support.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/sim_support.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/stack.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/stack.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/xml_parser.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/xml_parser.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/FMUSimulator.vcxproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/FMUSimulator.vcxproj.filters [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/COPYING.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat.lib [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat_external.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmiModelFunctions.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmiModelTypes.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmi_me.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inffixed.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inflate.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inftrees.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/jni.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/jni_md.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/libexpatMT.lib [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/org_simantics_fmu_FMUControlJNI.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/sim_support.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/stack.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/trees.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/xml_parser.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/zutil.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/fmu_control.cpp [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/sim_support.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/stack.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/xml_parser.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/FMUSolution.sln [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/x64/Release/libexpat-1.dll [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/CMakeLists.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/ChangeLog [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/FAQ [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/INDEX [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/Makefile [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/Makefile.in [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/README [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/adler32.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/amiga/Makefile.pup [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/amiga/Makefile.sas [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/bndsrc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/compile.clp [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/zlib.inc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/compress.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/configure [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/README.contrib [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/buffer_demo.adb [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/mtest.adb [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/read.adb [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/test.adb [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-streams.adb [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-streams.ads [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-thin.adb [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-thin.ads [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.adb [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.ads [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.gpr [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/amd64/amd64-match.S [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/bndsrc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/compile.clp [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/zlib.inc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/asm686/README.686 [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/asm686/match.S [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/Makefile [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/README [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/blast.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/blast.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/test.pk [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/test.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/ZLib.pas [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/ZLibConst.pas [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/zlibd32.mak [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.build [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.chm [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.sln [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/AssemblyInfo.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/ChecksumImpl.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/CircularBuffer.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/CodecBase.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/Deflater.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/DotZLib.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/DotZLib.csproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/GZipStream.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/Inflater.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/UnitTests.cs [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/LICENSE_1_0.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/gcc_gvmat64/gvmat64.S [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/README [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/infback9.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/infback9.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inffix9.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inflate9.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inftree9.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inftree9.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/inflate86/inffas86.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/inflate86/inffast.S [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/test.cpp [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/zfstream.cpp [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/zfstream.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream2/zstream.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream2/zstream_test.cpp [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/README [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/TODO [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/test.cc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/zfstream.cc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/zfstream.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/bld_ml64.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.asm [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.lst [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.obj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffas8664.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.asm [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.lst [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.obj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/bld_ml32.bat [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/inffas32.asm [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/inffas32.lst [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/match686.asm [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/match686.lst [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/Makefile [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/Makefile.am [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/MiniZip64_Changes.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/MiniZip64_info.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/configure.ac [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/crypt.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/fmuExtract.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/ioapi.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/ioapi.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/iowin32.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/iowin32.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/make_vms.com [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/miniunz.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.pc.in [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/mztools.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/mztools.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/unzip.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/unzip.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/zip.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/zip.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/example.pas [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/zlibd32.mak [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/zlibpas.pas [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/Makefile [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/README [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/puff.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/puff.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/pufftest.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/zeros.raw [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/testzlib/testzlib.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/testzlib/testzlib.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/Makefile [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/Makefile.msc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/untgz.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/readme.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/FMITest.dll [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/FMITest.lib [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/libexpat-1.dll [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/miniunz.vcxproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/miniunz.vcxproj.filters [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/minizip.vcxproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/minizip.vcxproj.filters [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_FMU.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_functions.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_functions.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_records.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/_FMITest.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlib.vcxproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlib.vcxproj.filters [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlibdll.vcxproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlibdll.vcxproj.filters [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlib.rc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibstat.vcxproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibstat.vcxproj.filters [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.def [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.sln [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.vcxproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.vcxproj.filters [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/miniunz.vcproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/minizip.vcproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/testzlib.vcproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/testzlibdll.vcproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlib.rc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibstat.vcproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.def [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.sln [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.vcproj [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/crc32.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/crc32.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/deflate.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/deflate.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/algorithm.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1950.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1951.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1952.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/txtvsbin.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/README.examples [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/enough.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/fitblk.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gun.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzappend.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzjoin.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzlog.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzlog.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zlib_how.html [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zpipe.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zran.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzclose.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzguts.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzlib.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzread.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzwrite.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/infback.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffast.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffast.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffixed.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inflate.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inflate.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inftrees.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inftrees.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/make_vms.com [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.bor [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.dj2 [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.emx [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.msc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.tc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/nintendods/Makefile [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/nintendods/README [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/Makefile.riscos [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/README [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/descrip.mms [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/os2/Makefile.os2 [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/os2/zlib.def [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/visual-basic.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/qnx/package.qpg [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/example.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/infcover.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/minigzip.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/treebuild.xml [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/trees.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/trees.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/uncompr.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/watcom/watcom_f.mak [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/watcom/watcom_l.mak [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/DLL_FAQ.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.bor [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.emx [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.gcc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.msc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/README-WIN32.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/VisualC.txt [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/zlib.def [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/zlib1.rc [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h.cmakein [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h.in [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.3 [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.3.pdf [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.h [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.map [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.pc.in [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib2ansi [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zutil.c [new file with mode: 0644]
1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zutil.h [new file with mode: 0644]
1.8/org.simantics.fmu/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.fmu/build.properties [new file with mode: 0644]
1.8/org.simantics.fmu/src/org/simantics/fmu/Activator.java [new file with mode: 0644]
1.8/org.simantics.fmu/src/org/simantics/fmu/FMUControlJNI.java [new file with mode: 0644]
1.8/org.simantics.fmu/src/org/simantics/fmu/FMUJNIException.java [new file with mode: 0644]
1.8/org.simantics.fmu/src/org_simantics_fmu_FMUControlJNI.h [new file with mode: 0644]
1.8/org.simantics.h2d/.classpath [new file with mode: 0644]
1.8/org.simantics.h2d/.hgignore [new file with mode: 0644]
1.8/org.simantics.h2d/.project [new file with mode: 0644]
1.8/org.simantics.h2d/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.h2d/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.h2d/build.properties [new file with mode: 0644]
1.8/org.simantics.h2d/doc/manual.mediawiki [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/action/IAction.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/canvas/EditorCanvas.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/Diagram.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/IDiagram.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/IDiagramListener.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/editor/IDiagramEditor.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/editor/ISelection.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/editor/ISelectionListener.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/DiagramEditor.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/EventHandlerManager.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/SceneGraphManager.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/Selection.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/ChainingElementListener.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/Element.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/IElement.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/IElementListener.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Connectable.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/IElementHandler.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Movable.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Rotatable.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/ShadowDrawable.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/ClickEvent.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/DragEvent.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/DragEventPhase.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/IDragHandler.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/IEvent.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/ILocatableEvent.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/KeyboardEvent.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/Modifiers.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/ReleaseEvent.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/WheelEvent.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/BoxSelection.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/DefaultEventHandlers.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Delete.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/DragEventHandler.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ElementEventDelegator.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/EventPrinter.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/IEventHandler.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/MoveSelected.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Pan.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/PickSelection.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/RotateClockwise.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/RotateCounterclockwise.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ToggleSelection.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Zoom.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ZoomToFit.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/node/FilledShapeNode.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/node/ITextListener.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/node/LineNode.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/node/RectangleNode.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/node/ShapeNode.java [new file with mode: 0644]
1.8/org.simantics.h2d/src/org/simantics/h2d/node/TextNode.java [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/.classpath [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/.project [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/build.properties [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/graph.tg [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/graph/ChartViewpoints.pgraph [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/graph/JFreeChart.pgraph [new file with mode: 0644]
1.8/org.simantics.jfreechart.ontology/src/org/simantics/sysdyn/JFreeChartResource.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/.classpath [new file with mode: 0644]
1.8/org.simantics.jfreechart/.project [new file with mode: 0644]
1.8/org.simantics.jfreechart/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.jfreechart/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.jfreechart/adapters.xml [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-1.7.zip [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-awt-util.jar [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-dom.jar [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-ext.jar [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-src-1.7.zip [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-svg-dom.jar [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-svggen.jar [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-util.jar [new file with mode: 0644]
1.8/org.simantics.jfreechart/batik/batik-xml.jar [new file with mode: 0644]
1.8/org.simantics.jfreechart/build.properties [new file with mode: 0644]
1.8/org.simantics.jfreechart/icons/chart_bar_light.png [new file with mode: 0644]
1.8/org.simantics.jfreechart/icons/chart_line_light.png [new file with mode: 0644]
1.8/org.simantics.jfreechart/icons/chart_pie_light.png [new file with mode: 0644]
1.8/org.simantics.jfreechart/icons/close.gif [new file with mode: 0644]
1.8/org.simantics.jfreechart/icons/maximize.gif [new file with mode: 0644]
1.8/org.simantics.jfreechart/icons/minimize.gif [new file with mode: 0644]
1.8/org.simantics.jfreechart/plugin.xml [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartDropTarget.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanel.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelElement.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelHeader.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelSeparator.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPropertyOptions.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartSelectionTabContributor.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ElementContainer.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractAxis.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractDataset.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractPlot.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractRenderer.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/BarRenderer.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryAxis.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryDataset.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryPlot.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite2.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartUtils.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/DeviationRenderer.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ExtendedNumberAxis.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteredDataset.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteringCategoryDataset.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteringPieDataset.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IAxis.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IDataset.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IJFreeChart.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IJFreeChartComponent.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IPlot.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IRenderer.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ITitle.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/JFreeChart.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/NumberAxis.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/PieDataset.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/PiePlot.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/StackedBarRenderer.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/TextTitle.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYAreaRenderer.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYDataset.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYLineRenderer.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYPlot.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartBoundsOutline.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartElementFactory.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartElementWriter.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartNode.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartSceneGraph.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/PopulateChartDropParticipant.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ResizeListener.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisChildRule.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisDropAction.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisLabelRule.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesChildRule.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesDropAction.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesLabelDecorationRule.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesLabelRule.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/VariableChildRule.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AdjustableTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AllVariablesOfModel.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AxisHidePropertyComposite.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/BooleanPropertyFactory.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/BooleanSelectionListener.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariable.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariableFactory.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariableModifier.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ColorPicker.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoublePropertyFactory2.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoublePropertyModifier2.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoubleValidator.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/IAllVariablesOfModel.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/JFreeChartPropertyColorProvider.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/LabelPropertyTabContributor.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RVIFactory.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RVIModifier.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RangeComposite.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RangeHandlerFactory.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooser.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyEvent.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyListener.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyListenerImpl.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TitleFactory.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TitleModifier.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TrackedSpinner.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableExistsValidator.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableProposalProvider.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarAxisTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarGeneralPropertiesTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesPropertyComposite.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesPropertyComposite2.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesTab2.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieGeneralPropertiesTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesPropertyComposite.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesPropertyComposite2.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesTab2.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisAndVariablesExplorerComposite.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisPropertyComposite.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/SeriesPropertyComposite.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineAxisAndVariablesTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineGeneralPropertiesTab.java [new file with mode: 0644]
1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/internal/Activator.java [new file with mode: 0644]
1.8/org.simantics.modelica/.classpath [new file with mode: 0644]
1.8/org.simantics.modelica/.project [new file with mode: 0644]
1.8/org.simantics.modelica/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.modelica/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.modelica/build.properties [new file with mode: 0644]
1.8/org.simantics.modelica/plugin.xml [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/Activator.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/IModelicaMonitor.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/InitWriter.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaException.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaKeys.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaManager.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/SimulationLocation.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/CSVSimulationResult.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/DataSet.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/DoubleMatrix.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/IntMatrix.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/Mat4Reader.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/MatSimulationResult.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/Matrix.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/SimulationResult.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/data/StringMatrix.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/preferences/ModelicaPreferenceInitializer.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/preferences/OpenModelicaPreferences.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/reader/MatFileReader.java [new file with mode: 0644]
1.8/org.simantics.modelica/src/org/simantics/modelica/reader/ResultFileReader.java [new file with mode: 0644]
1.8/org.simantics.objmap/.classpath [new file with mode: 0644]
1.8/org.simantics.objmap/.hgignore [new file with mode: 0644]
1.8/org.simantics.objmap/.project [new file with mode: 0644]
1.8/org.simantics.objmap/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.objmap/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.objmap/build.properties [new file with mode: 0644]
1.8/org.simantics.objmap/doc/bidirectionalModel.graphml [new file with mode: 0644]
1.8/org.simantics.objmap/doc/bidirectionalModel.png [new file with mode: 0644]
1.8/org.simantics.objmap/doc/main.mediawiki [new file with mode: 0644]
1.8/org.simantics.objmap/doc/manual.mediawiki [new file with mode: 0644]
1.8/org.simantics.objmap/doc/objectMappingTerminology.graphml [new file with mode: 0644]
1.8/org.simantics.objmap/doc/objectMappingTerminology.png [new file with mode: 0644]
1.8/org.simantics.objmap/doc/triangleModel.graphml [new file with mode: 0644]
1.8/org.simantics.objmap/doc/triangleModel.png [new file with mode: 0644]
1.8/org.simantics.objmap/examples/org/simantics/objmap/examples/SysdynExample.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/IFunction.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/ILinkType.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/IMapping.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingListener.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingRule.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingSchema.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/MappingException.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/Mappings.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/Composition.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/GraphType.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/OptionalRelatedElements.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedElement.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedElements.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedListElements.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedOrderedSetElements.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedValue.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/UpdateMethod.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/DataTypeUtils.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/OptionalRelatedElementsRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedElementRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedElementsRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedListElementsRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedOrderedSetElementsRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedValueRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/UpdateMethodFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasClassRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasFieldRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasMethodRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/impl/Link.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/impl/Mapping.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/impl/RangeUpdateRequest.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/impl/UnidirectionalMapping.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/MappedElementRule.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/MappedElementsRule.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/ValueRule.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/adapters/IdentityAdapter.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/adapters/ValueAdapter.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/IDomainAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/MappingUtils.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedListElementsAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedObjectAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedObjectsAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedOrderedSetElementsAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedValueAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IClassRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IFieldRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IMethodRuleFactory.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/AdaptedRangeAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/FieldAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/FieldAccessorWithDefault.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/IRangeAccessor.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/schema/MappingSchemas.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/schema/SimpleLinkType.java [new file with mode: 0644]
1.8/org.simantics.objmap/src/org/simantics/objmap/schema/SimpleSchema.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/.project [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/build.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/feature.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Bathtub.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Bathtub.sysdynModule [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Ceiling.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Decay.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Decay.sysdynModule [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Extrapolation.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Extrapolation.sysdynModule [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Floor.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/MoleculeFunctions.sysdynFunctions [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Multivariate Anchoring And Adjustment.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Protected Sea Ancoring And Adjustment.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Sea Anchoring And Adjustment.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Smooth.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Smooth.sysdynModule [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/SmoothThirdOrder.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/SmoothThirdOrder.sysdynModule [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Tester For Molecules.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Trend.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Trend.sysdynModule [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Univariate Anchoring And Adjustment.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/WeighedAverage.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/molecules/references.txt [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/msvcr100.dll [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/puzzle_green.ico [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Discovery And Exploitation Of Resources.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Global Carbon Cycle.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Predator And Limited Prey.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Resource Exploitation Use Recycling.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Tourists Environments And Hotel Facilities.sysdyn [new file with mode: 0644]
1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/references.txt [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/.classpath [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/.project [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/Sysdyn ontolgy changes.doc [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/build.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph.tg [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/Charts.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/CommentSymbols.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/Migration.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/ModelicaArrayFunctions.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/ModelicaFunctions.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/Profiles.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/PropertyViewpoints.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/SysdynFunctions.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/SysdynModelingViewpoint.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/Validation.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/VensimFunctions.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/WorkModel.pgraph [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/graph/svg/loop.svg [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/mdl2pgraph.pl [new file with mode: 0755]
1.8/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/testGraph.tg [new file with mode: 0644]
1.8/org.simantics.sysdyn.ontology/testGraph/Cancer.pgraph.keep [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/.credentials.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/.project [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/Resources.rmap [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/buckminster.cspex [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/buckminster.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/build.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/build/product.ant [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/feature.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/jenkins.buckminster.script [new file with mode: 0644]
1.8/org.simantics.sysdyn.product.site.feature/site.cquery [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/.classpath [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/.project [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFMU.fmu [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFile.fmu [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFile.txt [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTest.mo [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTest.mos [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.dll [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.fmu [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.lib [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_FMU.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_functions.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_functions.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_records.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/_FMUAllTypesOfVariablesTestModel.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTest.mo [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTest.mos [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.dll [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.fmu [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.lib [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_FMU.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_functions.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_functions.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_records.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/_FMUBooleanTestModel.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTest.mo [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTest.mos [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.dll [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.fmu [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.lib [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_FMU.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_functions.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_functions.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_records.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/_FMUCallBeforeInitializationTestModel.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTest.mo [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTest.mos [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.dll [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.fmu [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.lib [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_FMU.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_functions.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_functions.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_records.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/_FMUIntegerTestModel.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTest.mo [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTest.mos [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.dll [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.fmu [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.lib [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_FMU.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_functions.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_functions.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_records.c [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/_FMURealTestModel.h [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/modelDescription.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUUnitTestModel.fmu [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/SCLTests.launch [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/build.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/Activator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/CallFMUBeforeInitializationTests.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUBooleanTest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUControlTestSuite.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUIntegerTest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMURealTest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUResultFilterTest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/LoadFMUFileFailTests.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/MultipleSimultaneousFMUSimulationsTest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scl/SCLTestScripts.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scl/SCLTests.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_DiscoveryAndExploitationOfResources.sts [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_GlobalCarbonCycle.sts [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_PredatorAndLimitedPrey.sts [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_ResourceExploitationUseRecycling.sts [new file with mode: 0644]
1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_TouristsEnvironmentsAndHotelFacilities.sts [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/.classpath [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/.project [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/adapters.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/build.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/plugin.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/Activator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/SysdynResource.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/adapters/VariableClassFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/adapters/VariableElementWriter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/DiagramEditorFacade.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/DrawableElementClass.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/SysdynDiagramEditor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/Drawable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/IDrawable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/ITransformable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/PositionableDrawable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/TestDrawable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/.classpath [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/.hgignore [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/.project [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/Splash.xcf [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/adapters.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/build.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/box.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/brick.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/brick_link.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/bricks.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/bullet_gray.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/bullet_green.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_bar.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_bar_3.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_bar_3_blackAndWhite.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_bar_blackAndWhite.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_bar_light.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_line.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_line_light.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_organisation.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_pie.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/chart_pie_light.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/close.gif [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/control_fastforward.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/control_fastforward_blue.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/control_pause.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/control_pause_blue.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/control_play.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/control_play_blue.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/control_step.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/control_step_blue.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/cursor.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/dependency.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/dependency_old.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/equalizer.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/error.svg [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/error_decoration.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/fatal.svg [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/fatal_decoration.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/flow.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/flow_old.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/folder.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/folder_link.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/function.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/functionLink.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/maximize.gif [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/minimize.gif [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/modelicaArrayFunction.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/modelicaFunction.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/page_white_text.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/page_white_text_width.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/rainbow.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/save_as.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.xcf [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn16.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn32.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn48.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn64.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/sysdyn.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/sysdyn32.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/sysdynFunction.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/table.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/table_multiple.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/table_multiple_pinned.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/time.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/time_go.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/time_rainbow.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/timeline_marker.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/variable.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/variableGray.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/vensimFunction.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/warning.svg [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/icons/warning_decoration.png [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/plugin.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/plugin.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/plugin_customization.ini [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/splash.bmp [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/Activator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ActivateExperimentAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ConsumeUnnecessaryEntersAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ShowInstantiatedModuleAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/SysdynVariableRemover.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/BrowserSelection.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynBrowser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynModelBrowser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ActivateResultDatasetAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ActivateResultSetDatasetAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenSheetAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/ChartDropAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/FunctionDropAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewBarChartAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewEnumerationAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewExperimentAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionLibraryAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewHistoryDataAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewLineChartAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewModuleTypeAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewPieChartAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSharedFunctionLibraryAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSheetAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSimulationPlaybackExperimentAction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleTypeRemover.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/ModuleContentChildRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/ModuleTypeChildRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/VariableChildRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AbstractNodeImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AbstractNodeLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution2.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationTypeImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationTypeLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationValueImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationValueLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Book.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/BookLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Charts.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartsImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartsLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Configuration.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ConfigurationLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Experiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentLabelDecorator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentsLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraryLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionsLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditionLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditions.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditionsLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InputLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryContribution.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryFunctions.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Model.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModelLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleType.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleTypeLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Modules.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModulesLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/OperatingInterfacesLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Project.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModuleLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModules.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModulesLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedFunctionLibraries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedFunctionsLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SheetLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultDecorator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSet.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetDecorator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SysdynProject.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/VariableLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/ChartImageRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/ResultImageRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/VariableImageRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/ModuleTypeLabelRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/VariableNameLabelRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodeTypes/ModuleSymbolNodeType.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AbstractChartNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationType.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationValue.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BarChartNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BookNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ChartsFolder.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ConfigurationNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/EnumerationNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentsFolder.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExportTester.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionLibraryNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionsFolder.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/HistoryDataNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialCondition.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialConditionsFolder.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InputNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/Library.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/LineChartNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModelNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleTypeNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModulesNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/OperatingInterfacesFolder.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/PieChartNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModulesFolder.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SensitivityChartNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedFunctionLibraryNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedFunctionsFolder.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedOntologyNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SheetNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultSetNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SymbolNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/VariableNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/DiagramToCompositeMapping3.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/DiagramViewer.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromComponentAdapter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromConfigurationAdapter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynConnectionAdvisor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynCreationInstruction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorInput.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorNamingService.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/CreateVariablesShortcutParticipant.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SelectionUpdaterParticipant.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynComponentCopyAdvisor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectTool.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectionBuilder.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynCopyPasteStrategy.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynElementClassProviders.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynPointerInteractor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynPopulateElementDropParticipant.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynSpecialComponentCopyAdvisor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/DependencyRouter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/FlowRouter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/SysdynLocalRouter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/AuxiliaryFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/BorderSceneGraph.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/CloudFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ComponentNameSynchronizer.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ConfigurationDiagramClassAdapter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/HoverShapeNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Input.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/InputFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopClockwise.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ModuleFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ModuleNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/MultilineTextElementFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Orientation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/RectangleNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceDialogRunnable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceRequest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Size.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/StockFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementClasses.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementHints.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementNoBounds.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveOutline.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveTextLocation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/WholeElementTerminals.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/Arcs.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/ConnectionClasses.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyConnectionFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyEdgeClass.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyEdgeFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowArrowLineStyle.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowConnectionStyle.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/Flows.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowConnectionFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowEdgeClass.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowEdgeFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/SysdynConnectionClass.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/IssueDecorationStyle.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/ShadowStyle.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/SimulationPlaybackStyle.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/function/ModulesSearchFunction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/AssignIC.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ChartPanelOrientationHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DiagramToolHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DisposeExperiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/EnumerationPasteHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExportSharedOntologyHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExtendedCopyPasteHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindReplaceDialog.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindReplaceHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindSearchTrim.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationValueHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewSCLModuleHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/PasteSpecialDialog.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/PasteSpecialHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RemoveNodeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RenameNodeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryDialog.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveICHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveResultsHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ShowModuleHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SynthesisSimulation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SysdynExperimentActivator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultActivation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultSetActivation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleSimulation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/UnlinkNodeHandler2.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportExternalFunctionFilesHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportFunctionLibrary.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelAsButtonHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelButtonHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModuleHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/ReloadGameExperimentHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/StepHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportExternalFunctionFilesHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportFunctionLibrary.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportMdlHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModelHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModuleHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportSharedLibraryHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewBarChartHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewEnumerationNodeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewExperimentNodeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionLibraryHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewGameExperimentNodeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewHistoryDataHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModelHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModuleNodeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPieChartHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPlaybackExperimentNodeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityAnalysisExperimentNodeHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityChartHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSharedFunctionLibraryHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSpreadSheetHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewXYLineChartHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/RunSensitivityAnalysisExperiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/SaveResultsHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/ToggleSimulation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/FastSpeedHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/NormalSpeedHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackExperimentHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackReloadHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackResetHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SlowSpeedHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SpeedHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynExperimentListener.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynExperimentManagerListener.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynPlaybackExperimentListener.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/FontContextMenuContribution.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/GameStepDurationContribution.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/ModelicaSourceViewerConfiguration.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/SysdynModelicaEditor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/TextEditorActionBarContributor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/ModelicaPreferencePage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SolverPreferencePage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferencePage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferences.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferencesInitializer.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertyExternalRead.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertySubscription.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertySupport.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynEquationPerspectiveFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynPerspectiveFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynProject.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynTrendPerspectiveFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayDependencyTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayFlowTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayIndexesTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/CommentTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ConfigurationTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/DependencyTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EnumerationTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExperimentTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExternalFilesTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FlowTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FunctionLibraryTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FunctionTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/GameExperimentTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/HistoryDataTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/InputVariableTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LookupTableTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LoopTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleInputTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleOutputTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleParameterTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleTypeTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/PlaybackExperimentTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ReferenceDependencyTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/RemoveFocusBeforeExperimentComposite.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ResourceSelectionProcessor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ResultTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SensitivityAnalysisExperimentTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SysdynBasicColorProvider.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SysdynPropertyPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/VariableInformationTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrayExpressionCombo.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrowHeadWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartTableWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ColumnKeys.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/CustomFontDialog.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/DelayMarkWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/EquivalentUnitsWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionTypes.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FontModifyListener.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FontSelectionComposite.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FunctionLabelFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/IsOutputWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ShortcutTabWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/UnitComboWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ValveOrientationGroup.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ValveTextLocationGroup.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/AvailableEnumerations.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ComboBoxModifier.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ConflictingEnumerationLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ConflictingEnumerationNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexes.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/NameAndArrayRangeModifyListener.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/RedeclarationNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableEnumerations.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableEnumerationsLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableIndexesWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ShowInChartsCheckBox.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/UsedEnumerations.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/UsedEnumerationsManyVariables.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/AuxiliaryExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/BasicExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ColorManager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/CompletionProcessor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ConstantExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/DelayExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/EmptyExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionComposite.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionField.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionFieldConfiguration.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionWidgetInput.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/IExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupChartPanel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupInputOutputTable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ParameterExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/StockExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/WithLookupExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileImager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFiles.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ComboStringPropertyModifier.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/DoublePropertyFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/DoublePropertyModifier.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/FunctionLibraryNameInputValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/FunctionNameInputValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/IntegerPropertyFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/IntegerPropertyModifier.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ModelNameInputValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ModuleTypeNameInputValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/VariableNameInputValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/VariableNamePropertyModifier.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/FunctionCodeWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/SelectedSharedFunctionLibraries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/SharedFunctionLibraries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/historyDataset/VariableChildRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/historyDataset/VariableLabelRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleInputEditingSupport.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleOutputEditingSupport.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleParameterOverrideUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterChildRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterLabelDecorationRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterLabelRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterModifierRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterSorter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterSorterRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRow.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRowLabelProvider.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceTable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/RowProvider.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/DistributionPropertyWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/IDistributionProperties.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/IntervalProperties.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/NormalDistributionProperties.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterChildRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterLabelRule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterProposalProvider.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/SensitivityDistributionKeys.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/SensitivityRangeHandlerFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/UniformDistributionProperties.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/VariableNameModifier.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Dependencies.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/DependencyGraphRequest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/LoopGraphRequest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Loops.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructure.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructureGraphRequest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/StructureTabItem.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/StructureView.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllParametersOfModel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllVariablesOfModel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/CategoryDataset.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBound.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBoundWidget.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PieDataset.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PinTrend.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityChartAxisAndVariablesTab.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDataset.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDatasetProperties.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivitySeriesPropertyComposite.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SysdynRangeHandlerFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendEditor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendToPng.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendToSvg.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendView.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDataset.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDatasetRequest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDatasetTempSeries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ArrayVariableUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/FunctionLibraryNameValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/FunctionNameValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/HandlerUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ModelNameValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ModuleTypeNameValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/NameValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/OldTransferableGraph1.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SharedFunctionLibraryNameValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SheetNameValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SyntaxError.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SysdynWorkbenchUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/VariableNameValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/ImportUtilsUI.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/DependencyFunction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/EnumerationFunction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ExpressionIssueFunction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/Functions.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/IssueWithStringContext.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ModuleStandardIssue.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/NoSuchVariableException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ParameterExistsValidator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/References.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/SyntaxErrorException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UndefinedExpressionException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UnitFunction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UnsupportedCharactersException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ValidationUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/values/ValueView.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/viewUtils/SysdynDatasetSelectionListener.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/Preferences.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/ExportWizardFunction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeFunctionLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeLibraries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeModelLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeModels.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedFolderLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedLibraries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedLibraryLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSubLibraries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/ImportWizardFunction.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/SharedFunctionsFolderNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/ImportWizardMdl.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/WizardMdlImportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynExportModel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynImportModel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelExportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelExportWizard.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelImportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelImportWizard.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/ExportWizardModel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/ImportWizardModel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsImportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ExportWizardModule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ImportWizardModule.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleComponentTypeNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModels.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModules.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModulesLabeler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java [new file with mode: 0644]
1.8/org.simantics.sysdyn.ui/sysdyn.product [new file with mode: 0644]
1.8/org.simantics.sysdyn/.classpath [new file with mode: 0644]
1.8/org.simantics.sysdyn/.hgignore [new file with mode: 0644]
1.8/org.simantics.sysdyn/.project [new file with mode: 0644]
1.8/org.simantics.sysdyn/.settings/org.eclipse.jdt.core.prefs [new file with mode: 0644]
1.8/org.simantics.sysdyn/META-INF/MANIFEST.MF [new file with mode: 0644]
1.8/org.simantics.sysdyn/ModelicaParser.html [new file with mode: 0644]
1.8/org.simantics.sysdyn/adapters.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn/build.properties [new file with mode: 0644]
1.8/org.simantics.sysdyn/plugin.xml [new file with mode: 0644]
1.8/org.simantics.sysdyn/scl/Sysdyn.scl [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/Functions.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/TestParser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ActiveDatasetsIndexVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/CustomMigrationStep.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/IndexVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/NamesIndexVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/SensitivityExperimentParameter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimesIndexVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableI.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableValueSubscription.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/IDistribution.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/Interval.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/NormalDistribution.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/UniformDistribution.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/HaltonSequenceGenerator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/IGenerator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/RandomGenerator.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/AdjacencyList.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/ElementaryCyclesSearch.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/SCCResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/StrongConnectedComponents.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/TestCycles.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/license.txt [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.jj [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserConstants.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserTokenManager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ParseException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/SimpleCharStream.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TestExpressionParser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/Token.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TokenMgrError.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/ActiveResults.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FileResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FunctionUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultJob.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultSetJob.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynConsole.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynDataSet.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiments.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynSensitivityAnalysisExperiment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/VariableSubscriptionManager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/ExportConstants.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/SysdynModelExporter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlParser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlUtil.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Declaration.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Lookup.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/MdlModel.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/MdlVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Sketch.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchComment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchConnection.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchElement.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchObject.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchValve.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Subscript.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SubscriptVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Auxiliary.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Cloud.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Comment.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Connection.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Dependency.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Flow.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/IWriteableObject.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Model.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Shadow.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Stock.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Symbol.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Valve.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Variable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/WriteContext.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/DelayExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/EnumerationExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/Expression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/IntegralExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/LookupExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/NormalExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Enumeration.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Function.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Range.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParserConstants.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParserTokenManager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelicaParser.jj [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ParseException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/SimpleCharStream.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/Token.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/TokenMgrError.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelica/ModelicaWriter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/refactoring/TGRefactoring.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/refactoring/mappingSpec.txt [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Auxiliary.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Book.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Cloud.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Configuration.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Dependency.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/DiagramContainerDummy.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Entity.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Enumeration.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/EnumerationIndex.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Flow.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Function.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/FunctionLibrary.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/IElement.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/IndependentVariable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Input.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/LibraryDummy.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/LoadRepresentation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Loop.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Model.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Module.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/ModuleType.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/ParameterOverride.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Redeclaration.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Shadow.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/SharedFunctionLibrary.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Sheet.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Stock.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/SysdynSchema.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Valve.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variability.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variable.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctions.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctionsAccessor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctionsFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ConstantExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/DelayExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/Expression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/IExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/LookupExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/NormalExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ParameterExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/StockExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/WithLookupExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/FormatUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/IndexUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/RepresentationUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/SheetFormatUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/UnitUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/visitors/ElementVisitorVoidAdapter.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/visitors/IElementVisitorVoid.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationScheduler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolver.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolverMonitor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolver.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolverResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ModelicaSolver.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SolverParameters.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SolverSettings.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SysdynSimulationJob.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/ParseException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/SimpleCharStream.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParser.jj [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParserConstants.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParserTokenManager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/Token.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TokenMgrError.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/JJTUnitParserState.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/Node.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/ParseException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/SimpleCharStream.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/SimpleNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/Token.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/TokenMgrError.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingException.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingNode.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingNodeFactory.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.jj [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.jjt [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserConstants.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserTokenManager.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserTreeConstants.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/AddOp.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Arithmetic.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ArrayDefinition.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentIdentity.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentReference.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentReferenceFull.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Condition.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Divide.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Expression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Factor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ForIndex.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/FunctionArguments.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/FunctionCall.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/IfThenElse.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Multiplication.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/NamedArguments.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ParenthesisExpression.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Power.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/RelOp.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Relation.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Term.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/UnitResult.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Value.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/DocumentationUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/Function.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/GetConfigurationRequest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/LoopUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModelUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModuleSummary.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModuleSummaryRequest.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ProfileEntries.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SheetUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/ImportUtils.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/SysdynFunctionLibraryImportAdvisor.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/SysdynImportFormatHandler.java [new file with mode: 0644]
1.8/org.simantics.sysdyn/testModels/MaintenanceModel_2012-12-03.tg [new file with mode: 0644]
1.8/org.simantics.sysdyn/testModels/Model1412Health.tg [new file with mode: 0644]
1.8/org.simantics.sysdyn/testModels/WorkModel_2012-12-03.tg [new file with mode: 0644]
1.8/org.simantics.sysdyn/testModels/openprod_demo_2012-12-03.tg [new file with mode: 0644]
1.8/org.simantics.sysdyn/testModels/references.txt [new file with mode: 0644]
1.8/setup/sysdyn.ism [new file with mode: 0644]
1.8/setup/sysdyn/Script Files/FeatureEvents.rul [new file with mode: 0644]
1.8/setup/sysdyn/Script Files/Setup.Rul [new file with mode: 0644]
1.8/setup/sysdyn/Script Files/my.rul [new file with mode: 0644]
1.8/setup/sysdyn/String1033.txt [new file with mode: 0644]

diff --git a/1.8/fi.semantum.sysdyn.solver/.classpath b/1.8/fi.semantum.sysdyn.solver/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/fi.semantum.sysdyn.solver/.project b/1.8/fi.semantum.sysdyn.solver/.project
new file mode 100644 (file)
index 0000000..f2296ce
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>fi.semantum.sysdyn.solver</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/fi.semantum.sysdyn.solver/.settings/org.eclipse.jdt.core.prefs b/1.8/fi.semantum.sysdyn.solver/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..f287d53
--- /dev/null
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/fi.semantum.sysdyn.solver/META-INF/MANIFEST.MF b/1.8/fi.semantum.sysdyn.solver/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..b1284b6
--- /dev/null
@@ -0,0 +1,15 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Solver
+Bundle-SymbolicName: fi.semantum.sysdyn.solver
+Bundle-Version: 0.1.0.qualifier
+Bundle-Activator: fi.semantum.sysdyn.solver.Activator
+Bundle-Vendor: Semantum Oy
+Require-Bundle: org.eclipse.core.runtime,
+ org.simantics.utils;bundle-version="1.1.0",
+ org.simantics.databoard;bundle-version="0.6.5",
+ org.simantics.utils.datastructures;bundle-version="1.1.0",
+ gnu.trove3;bundle-version="3.0.3"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-ActivationPolicy: lazy
+Export-Package: fi.semantum.sysdyn.solver
diff --git a/1.8/fi.semantum.sysdyn.solver/build.properties b/1.8/fi.semantum.sysdyn.solver/build.properties
new file mode 100644 (file)
index 0000000..4bc054f
--- /dev/null
@@ -0,0 +1,14 @@
+###############################################################################\r
+# Copyright (c) 2013 Semantum Oy.\r
+# All rights reserved. This program and the accompanying materials\r
+# are made available under the terms of the Eclipse Public License v1.0\r
+# which accompanies this distribution, and is available at\r
+# http://www.eclipse.org/legal/epl-v10.html\r
+#\r
+# Contributors:\r
+#     Semantum Oy - initial API and implementation\r
+###############################################################################\r
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Activator.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Activator.java
new file mode 100644 (file)
index 0000000..e784713
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import org.osgi.framework.BundleActivator;\r
+import org.osgi.framework.BundleContext;\r
+\r
+public class Activator implements BundleActivator {\r
+\r
+       private static BundleContext context;\r
+\r
+       static BundleContext getContext() {\r
+               return context;\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)\r
+        */\r
+       public void start(BundleContext bundleContext) throws Exception {\r
+               Activator.context = bundleContext;\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)\r
+        */\r
+       public void stop(BundleContext bundleContext) throws Exception {\r
+               Activator.context = null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Addition.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Addition.java
new file mode 100644 (file)
index 0000000..8c09ab6
--- /dev/null
@@ -0,0 +1,70 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Addition implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public Addition(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " + " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object o1 = exp1.evaluate(environment);\r
+               Object o2 = exp2.evaluate(environment);\r
+               if(o1 == null || o2 == null) return null; \r
+               if(o1 instanceof Double && o2 instanceof Double) {\r
+                       return (Double)o1 + (Double)o2;\r
+               }\r
+               if(o1 instanceof Array && o2 instanceof Array) {\r
+                       Array la = (Array)o1;\r
+                       Array ra = (Array)o2;\r
+                       return la.add(ra);\r
+               }\r
+               throw new IllegalStateException();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Addition(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/And.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/And.java
new file mode 100644 (file)
index 0000000..2cee385
--- /dev/null
@@ -0,0 +1,68 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Map;\r
+\r
+public class And implements IExpression {\r
+       \r
+    public IExpression[] exps;\r
+    \r
+    public And(ArrayList<IExpression> exps) {\r
+       this.exps = exps.toArray(new IExpression[exps.size()]);\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       StringBuilder b = new StringBuilder();\r
+       b.append(exps[0]);\r
+       for(int i=1;i<exps.length;i++) {\r
+               b.append(" and ");\r
+               b.append(exps[i]);\r
+       }\r
+       return b.toString();\r
+    }\r
\r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               for(IExpression e : exps) \r
+                       if(!(Boolean)e.evaluate(environment)) return false;\r
+               return true;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               ArrayList<IExpression> ne = new ArrayList<IExpression>();\r
+               for(IExpression e : exps) ne.add(e.withBase(frame, prefix));\r
+               return new And(ne);\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               for(int i=0;i<exps.length;i++) {\r
+                       exps[i] = exps[i].rewrite(frame, copies);\r
+               }\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               for(IExpression exp : exps) exp.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Application.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Application.java
new file mode 100644 (file)
index 0000000..8f1987a
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Application implements IExpression {\r
+\r
+       public String name;\r
+       public ArgumentList args;\r
+       \r
+       public Application(String name, ArgumentList args) {\r
+               this.name = name;\r
+               this.args = args;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return name + args;\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               return environment.getSystem().evaluateFunction(environment, name, args);\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Application(name, args.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               args = args.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               for(Argument a : args.args)\r
+                       a.modification.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Argument.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Argument.java
new file mode 100644 (file)
index 0000000..cf5fe67
--- /dev/null
@@ -0,0 +1,56 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Argument implements IExpression {\r
+\r
+       public String name;\r
+       public IExpression modification;\r
+       \r
+       public Argument(String name, IExpression modification) {\r
+               this.name = name;\r
+               this.modification = modification;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return name + "=" + modification;\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Argument(prefix+name, modification.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       public Argument rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               modification = modification.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               modification.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ArgumentList.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ArgumentList.java
new file mode 100644 (file)
index 0000000..02d4d43
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Map;\r
+\r
+public class ArgumentList {\r
+       \r
+    public Argument[] args;\r
+    public String op;\r
+    \r
+    public ArgumentList(ArrayList<Argument> args) {\r
+       this.args = args.toArray(new Argument[args.size()]);\r
+       this.op = "";\r
+    }\r
+\r
+    public ArgumentList(ArrayList<Argument> args, String op) {\r
+       this.args = args.toArray(new Argument[args.size()]);\r
+       this.op = op;\r
+    }\r
+\r
+    public ArgumentList(String op) {\r
+       this.args = new Argument[0];\r
+       this.op = op;\r
+    }\r
+\r
+    @Override\r
+    public String toString() {\r
+       if(args.length == 0) return "()";\r
+       StringBuilder b = new StringBuilder();\r
+       b.append("(" + args[0]);\r
+       for(int i=1;i<args.length;i++) {\r
+               b.append(", ");\r
+               b.append(args[i]);\r
+       }\r
+       b.append(")");\r
+       return b.toString();\r
+    }\r
+    \r
+    public ArgumentList withBase(IFrame frame, String prefix) {\r
+       ArrayList<Argument> a2 = new ArrayList<Argument>();\r
+       for(Argument a : args) a2.add((Argument)a.withBase(frame, prefix));\r
+       return new ArgumentList(a2, op);\r
+    }\r
+    \r
+       public ArgumentList rewrite(IFrame frame, Map<String,VariableBase> copies) {\r
+               for(int i=0;i<args.length;i++)\r
+                       args[i] = args[i].rewrite(frame, copies);\r
+               return this;\r
+       }\r
+    \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Array.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Array.java
new file mode 100644 (file)
index 0000000..db00150
--- /dev/null
@@ -0,0 +1,377 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+public class Array implements IExpression {\r
+\r
+       public static final Array FULL = new Array();\r
+       \r
+       private ArrayList<Object> elements = new ArrayList<Object>();\r
+\r
+       public Array() {\r
+               \r
+       }\r
+       \r
+       public Array addElement(Object element) {\r
+               if(element instanceof Constant) addElement(((Constant)element).value);\r
+               else elements.add(element);\r
+               return this;\r
+       }\r
+       \r
+       public void setElement(int index, Object element) {\r
+               elements.set(index, element);\r
+       }\r
+\r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               return evaluated(environment);\r
+       }\r
+       \r
+       public Array evaluated(IEnvironment environment) {\r
+               Array result = new Array();\r
+               for(Object o : elements) {\r
+                       if(o instanceof Array) {\r
+                               result.addElement(((Array)o).evaluated(environment));\r
+                       } else {\r
+                               if(o instanceof IExpression) {\r
+                                       IExpression exp = (IExpression)o;\r
+                                       result.addElement(exp.evaluate(environment));\r
+                               } else {\r
+                                       result.addElement(o);\r
+                               }\r
+                       }\r
+               }\r
+               return result;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return elements.toString();\r
+       }\r
+       \r
+       public int size(int col) {\r
+               return elements.size();\r
+       }\r
+       \r
+       public Object element(int index) {\r
+               return elements.get(index);\r
+       }\r
+       \r
+       public Collection<Object> elements() {\r
+               return elements;\r
+       }\r
+       \r
+       public void ensureIndex(int index, boolean subArray) {\r
+               int needed = (index+1-elements.size());\r
+               for(int i=0;i<needed;i++) addElement(subArray ? new Array() : null);\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               Array result = new Array();\r
+               for(Object o : elements) {\r
+                       if(o instanceof Array) {\r
+                               result.addElement(((Array)o).withBase(frame, prefix));\r
+                       } else {\r
+                               if(o instanceof IExpression) {\r
+                                       IExpression exp = (IExpression)o;\r
+                                       result.addElement(exp.withBase(frame, prefix));\r
+                               } else {\r
+                                       result.addElement(o);\r
+                               }\r
+                       }\r
+               }\r
+               return result;\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               for(int i=0;i<elements.size();i++) {\r
+                       Object element = elements.get(i);\r
+                       if(element instanceof IExpression) {\r
+                               elements.set(i, ((IExpression)element).rewrite(frame, copies));\r
+                       }\r
+               }\r
+               return this;\r
+       }\r
+       \r
+       public int dimension() {\r
+               int result = 0;\r
+               for(int i=0;i<elements.size();i++) {\r
+                       Object element = elements.get(i);\r
+                       if(element instanceof Array) {\r
+                               result += ((Array)element).dimension();\r
+                       } else {\r
+                               result++;\r
+                       }\r
+               }\r
+               return result;\r
+       }\r
+       \r
+       public Array mul(double d) {\r
+               Array result = new Array();\r
+               for(Object o : elements) {\r
+               if(o instanceof Double) {\r
+                       result.addElement((Double)o*d);\r
+               } else if (o instanceof Array) {\r
+                       result.addElement(((Array)o).mul(d));\r
+               } else {\r
+                       throw new IllegalStateException();\r
+               }\r
+               }\r
+               return result;\r
+       }\r
+\r
+       public Array pow(double d) {\r
+               Array result = new Array();\r
+               for(Object o : elements) {\r
+               if(o instanceof Double) {\r
+                       result.addElement(Math.pow((Double)o,d));\r
+               } else if (o instanceof Array) {\r
+                       result.addElement(((Array)o).pow(d));\r
+               } else {\r
+                       throw new IllegalStateException();\r
+               }\r
+               }\r
+               return result;\r
+       }\r
+       \r
+       public boolean validateDimensions(int[] dimensions, int index) {\r
+               if(elements.size() != dimensions[index]) return false;\r
+               if(index < dimensions.length-1) {\r
+                       for(Object o : elements) {\r
+                               if(!(o instanceof Array)) return false;\r
+                               Array arr = (Array)o;\r
+                               if(!arr.validateDimensions(dimensions, index+1)) return false;\r
+                       }\r
+               } else {\r
+                       for(Object o : elements) {\r
+                               if((o instanceof Array)) return false;\r
+                       }\r
+               }\r
+               return true;\r
+       }\r
+\r
+       public boolean isScalar(Array index) {\r
+               if(index == Array.FULL) return false;\r
+               return index.elements.size() == 1;\r
+       }\r
+       \r
+       public Array slice(Array[] indices) {\r
+               \r
+               if(indices.length == 1) {\r
+                       if(indices[0] == Array.FULL) {\r
+                               return this;\r
+                       } else {\r
+                               Array result = new Array();\r
+                               for(Object r : indices[0].elements) {\r
+                                       Double d = (Double)r;\r
+                                       int index = d.intValue();\r
+                                       result.addElement(element(index));\r
+                               }\r
+                               return result;\r
+                       }\r
+               }\r
+               \r
+               if(indices.length == 2) {\r
+                       \r
+                       if(indices[0] == Array.FULL && indices[1] == Array.FULL) return this;\r
+                       \r
+                       if(isScalar(indices[0])) {\r
+                               \r
+                               Double d = (Double)indices[0].element(0);\r
+                               int index = d.intValue();\r
+                               Array arr = (Array)elements.get(index);\r
+                               \r
+                               if(indices[1] == Array.FULL) {\r
+                                       return arr;\r
+                               } else {\r
+                                       Array result = new Array();\r
+                                       for(Object r : indices[1].elements) {\r
+                                               d = (Double)r;\r
+                                               index = d.intValue();\r
+                                               result.addElement(arr.element(index));\r
+                                       }\r
+                                       return result;\r
+                               }\r
+                               \r
+                       }\r
+                       \r
+                       if(isScalar(indices[1])) {\r
+\r
+                               Double d = (Double)indices[1].element(0);\r
+                               int index1 = d.intValue();\r
+\r
+                               Array result = new Array();\r
+                               if(indices[0] == Array.FULL) {\r
+                                       for(Object r : elements) {\r
+                                               Array arr = (Array)r;\r
+                                               result.addElement(arr.element(index1));\r
+                                       }\r
+                               } else {\r
+                                       for(Object r : indices[0].elements) {\r
+                                               d = (Double)r;\r
+                                               int index = d.intValue();\r
+                                               Array arr = (Array)element(index);\r
+                                               result.addElement(arr.element(index1));\r
+                                       }\r
+                               }\r
+                               return result;\r
+                               \r
+                       }\r
+                       \r
+                       Array result = new Array();\r
+                       for(Object r : indices[0].elements) {\r
+                               Double d = (Double)r;\r
+                               int index = d.intValue();\r
+                               Array result0 = new Array();\r
+                               Array arr = (Array)element(index);\r
+                               for(Object r2 : indices[1].elements) {\r
+                                       d = (Double)r2;\r
+                                       index = d.intValue();\r
+                                       result0.addElement(arr.element(index));\r
+                               }\r
+                               result.addElement(result0);\r
+                       }\r
+                       return result;\r
+                       \r
+               }\r
+               \r
+               if(indices.length == 3) {\r
+                       Array result = new Array();\r
+                       for(int i=0;i<indices[0].dimension();i++) {\r
+                               Double d0 = (Double)indices[0].element(i);\r
+                               int index0 = d0.intValue();\r
+                               Array a0 = (Array)element(index0);\r
+                               for(int j=0;j<indices[1].dimension();j++) {\r
+                                       Double d1 = (Double)indices[1].element(j);\r
+                                       int index1 = d1.intValue();\r
+                                       Array a1 = (Array)a0.element(index1);\r
+                                       for(int k=0;k<indices[2].dimension();k++) {\r
+                                               Double d2 = (Double)indices[2].element(k);\r
+                                               int index2 = d2.intValue();\r
+                                               result.addElement(a1.element(index2));\r
+                                       }\r
+                               }\r
+                       }\r
+                       return result;\r
+               }\r
+               \r
+               throw new IllegalStateException();\r
+               \r
+       }\r
+       \r
+       public Array add(Array other) {\r
+               Array result = new Array();\r
+               Collection<Object> lae = elements();\r
+               Collection<Object> rae = other.elements();\r
+               if(lae.size() != rae.size()) throw new IllegalStateException();\r
+               Iterator<Object> li = lae.iterator();\r
+               Iterator<Object> ri = rae.iterator();\r
+               for(int i=0;i<lae.size();i++) {\r
+                       Object l = li.next();\r
+                       Object r = ri.next();\r
+                       if(l instanceof Double && r instanceof Double) {\r
+                               result.addElement(((Double)l)+((Double)r));\r
+                       } else if (l instanceof Array && r instanceof Array) {\r
+                               Array arr = (Array)l;\r
+                               Array otherArr = (Array)r;\r
+                               result.addElement(arr.add(otherArr));\r
+                       } else {\r
+                               throw new IllegalStateException();\r
+                       }\r
+               }\r
+               return result;\r
+       }\r
+\r
+       public Array mul(Array other) {\r
+               Array result = new Array();\r
+               Collection<Object> lae = elements();\r
+               Collection<Object> rae = other.elements();\r
+               if(lae.size() != rae.size()) throw new IllegalStateException();\r
+               Iterator<Object> li = lae.iterator();\r
+               Iterator<Object> ri = rae.iterator();\r
+               for(int i=0;i<lae.size();i++) {\r
+                       Object l = li.next();\r
+                       Object r = ri.next();\r
+                       if(l instanceof Double && r instanceof Double) {\r
+                               result.addElement(((Double)l)*((Double)r));\r
+                       } else if (l instanceof Array && r instanceof Array) {\r
+                               Array arr = (Array)l;\r
+                               Array otherArr = (Array)r;\r
+                               result.addElement(arr.mul(otherArr));\r
+                       } else {\r
+                               throw new IllegalStateException();\r
+                       }\r
+               }\r
+               return result;\r
+       }\r
+\r
+       public Array pow(Array other) {\r
+               Array result = new Array();\r
+               Collection<Object> lae = elements();\r
+               Collection<Object> rae = other.elements();\r
+               if(lae.size() != rae.size()) throw new IllegalStateException();\r
+               Iterator<Object> li = lae.iterator();\r
+               Iterator<Object> ri = rae.iterator();\r
+               for(int i=0;i<lae.size();i++) {\r
+                       Object l = li.next();\r
+                       Object r = ri.next();\r
+                       if(l instanceof Double && r instanceof Double) {\r
+                               result.addElement(Math.pow(((Double)l),((Double)r)));\r
+                       } else if (l instanceof Array && r instanceof Array) {\r
+                               Array arr = (Array)l;\r
+                               Array otherArr = (Array)r;\r
+                               result.addElement(arr.pow(otherArr));\r
+                       } else {\r
+                               throw new IllegalStateException();\r
+                       }\r
+               }\r
+               return result;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               for(int i=0;i<elements.size();i++) {\r
+                       Object element = elements.get(i);\r
+                       if(element instanceof IExpression) {\r
+                               ((IExpression)element).accept(visitor);\r
+                       }\r
+               }\r
+       }\r
+       \r
+       public static Array singleton(double value) {\r
+               Array result = new Array();\r
+               result.addElement(value);\r
+               return result;\r
+       }\r
+\r
+       public static Array slice(int start, int end) {\r
+               Array result = new Array();\r
+               for(int i=start;i<=end;i++) {\r
+                       double d = i;\r
+                       result.addElement(d);\r
+               }\r
+               return result;\r
+       }\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ArraySliceExpression.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ArraySliceExpression.java
new file mode 100644 (file)
index 0000000..24d313d
--- /dev/null
@@ -0,0 +1,64 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class ArraySliceExpression implements IExpression {\r
+\r
+       public IExpression start;\r
+       public IExpression end;\r
+       \r
+       public ArraySliceExpression(IExpression start, IExpression end) {\r
+               this.start = start;\r
+               this.end = end;\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               return start + ":" + end;\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Double s = (Double)start.evaluate(environment);\r
+               Double e = (Double)end.evaluate(environment);\r
+               Array result = new Array();\r
+               for(int i=s.intValue();i<=e.intValue();i++)\r
+                       result.addElement(Double.valueOf(i));\r
+               return result;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new ArraySliceExpression(start.withBase(frame, prefix), end.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               start = start.rewrite(frame, copies);\r
+               end = end.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               start.accept(visitor);\r
+               end.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Assignment.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Assignment.java
new file mode 100644 (file)
index 0000000..6607c19
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+\r
+public class Assignment {\r
+       \r
+       public Variable target;\r
+       public IExpression[] subscripts;\r
+    public IExpression expression;\r
+    public boolean assigned = false;\r
+    public boolean isConstant = false;\r
+    \r
+    public Assignment(Variable target, IExpression[] subscripts, IExpression expression) {\r
+       this.target = target;\r
+       this.subscripts = subscripts;\r
+       this.expression = expression;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return target + " = " + expression;\r
+    }\r
+    \r
+    public Assignment withBase(IFrame frame, String prefix) {\r
+       if(subscripts != null) {\r
+               IExpression[] subscripts2 = new IExpression[subscripts.length];\r
+               for(int i=0;i<subscripts.length;i++)\r
+                       subscripts2[i] = subscripts[i].withBase(frame, prefix);\r
+               return new Assignment(target.withBase(frame, prefix), subscripts2, expression.withBase(frame, prefix));\r
+       } else {\r
+               return new Assignment(target.withBase(frame, prefix), null, expression.withBase(frame, prefix));\r
+       }\r
+    }\r
+    \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Constant.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Constant.java
new file mode 100644 (file)
index 0000000..3c56e26
--- /dev/null
@@ -0,0 +1,63 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Constant implements IExpression {\r
+\r
+       public Object value;\r
+       \r
+       public Constant(String name) {\r
+               try {\r
+                       value = Double.parseDouble(name);\r
+               } catch (NumberFormatException e) {\r
+                       if("true".equals(name))\r
+                               value = Boolean.TRUE;\r
+                       else if("false".equals(name))\r
+                               value = Boolean.FALSE;\r
+                       else\r
+                               value = name;\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return value.toString();\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               return value;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return this;\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+       }\r
+       \r
+}\r
+\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Declaration.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Declaration.java
new file mode 100644 (file)
index 0000000..b7b1678
--- /dev/null
@@ -0,0 +1,56 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland - #4488\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Declaration implements IExpression {\r
+\r
+       public Variable variable;\r
+       public Object modification;\r
+       \r
+       public Declaration(Variable variable, Object modification) {\r
+               this.variable = variable;\r
+               this.modification = modification;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return variable + " " + modification;\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Derivate.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Derivate.java
new file mode 100644 (file)
index 0000000..7d26af5
--- /dev/null
@@ -0,0 +1,79 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Derivate implements IExpression {\r
+\r
+       private Variable variable;\r
+       private IExpression[] subscripts;\r
+       public IExpression e;\r
+       \r
+       public Derivate(Variable variable, IExpression[] subscripts, IExpression e) {\r
+               this.variable = variable;\r
+               this.subscripts = subscripts;\r
+               this.e = e;\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment _environment) {\r
+               Environment environment = (Environment)_environment;\r
+//             Double old = (Double)environment.getValue(variable.name + variable.subscriptKey());\r
+               Double old = (Double)environment.getValue(variable.base.index(_environment, subscripts));\r
+               // FIXME: should not be fixed like this\r
+               if(old == null) old = 0.0;\r
+               return old+environment.step*(Double)e.evaluate(environment);\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return e.toString();\r
+       }       \r
+\r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               if(subscripts != null) {\r
+               IExpression[] subscripts2 = new IExpression[subscripts.length];\r
+               for(int i=0;i<subscripts.length;i++)\r
+                       subscripts2[i] = subscripts[i].withBase(frame, prefix);\r
+                       return new Derivate((Variable)variable.withBase(frame, prefix), subscripts2, e.withBase(frame, prefix));\r
+               } else {\r
+                       return new Derivate((Variable)variable.withBase(frame, prefix), null, e.withBase(frame, prefix));\r
+               }\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               if(subscripts != null) {\r
+                       for(int i=0;i<subscripts.length;i++)\r
+                               subscripts[i] = subscripts[i].rewrite(frame, copies);\r
+               }\r
+               e = e.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               if(subscripts != null) {\r
+                       for(int i=0;i<subscripts.length;i++)\r
+                               subscripts[i].accept(visitor);\r
+               }\r
+               e.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Derivative.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Derivative.java
new file mode 100644 (file)
index 0000000..037a174
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Derivative implements IExpression {\r
+\r
+       Variable variable;\r
+       \r
+       public Derivative(Variable variable) {\r
+               this.variable = variable;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return "der(" + variable.toString() + ")";\r
+       }\r
+\r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Division.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Division.java
new file mode 100644 (file)
index 0000000..d8d357f
--- /dev/null
@@ -0,0 +1,77 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Division implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public Division(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " / " + exp2;\r
+    }\r
+    \r
+    private Array arrayDiv(Array a, Double d) {\r
+       Array result = new Array();\r
+       for(Object o : a.elements()) {\r
+               if(o instanceof Double) {\r
+                       result.addElement((Double)o/d);\r
+               } else {\r
+                       throw new IllegalStateException();\r
+               }\r
+       }\r
+       return result;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object left = exp1.evaluate(environment);\r
+               Object right = exp2.evaluate(environment);\r
+               if(left == null || right == null) return null;\r
+               if(left instanceof Double && right instanceof Double) return ((Double)left)/((Double)right);\r
+               else if (left instanceof Array && right instanceof Double) return arrayDiv((Array)left, (Double)right);\r
+               else if (left instanceof Double && right instanceof Array) return arrayDiv((Array)right, (Double)left);\r
+               else throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Division(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwiseDivision.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwiseDivision.java
new file mode 100644 (file)
index 0000000..77362aa
--- /dev/null
@@ -0,0 +1,91 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Collection;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+public class ElementwiseDivision implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public ElementwiseDivision(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " / " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object left = exp1.evaluate(environment);\r
+               Object right = exp2.evaluate(environment);\r
+               if(left instanceof Array && right instanceof Array) {\r
+                       Array la = (Array)left;\r
+                       Array ra = (Array)right;\r
+                       Collection<Object> lae = la.elements();\r
+                       Collection<Object> rae = ra.elements();\r
+                       if(lae.size() != rae.size()) throw new UnsupportedOperationException();\r
+                       Iterator<Object> li = lae.iterator();\r
+                       Iterator<Object> ri = rae.iterator();\r
+                       Array result = new Array();\r
+                       for(int i=0;i<lae.size();i++) {\r
+                               double ld = (Double)li.next();\r
+                               double rd = (Double)ri.next();\r
+                               result.addElement(ld/rd);\r
+                       }\r
+                       return result;\r
+               } else if(left instanceof Array && right instanceof Double) {\r
+                       Array la = (Array)left;\r
+                       double rd = (Double)right;\r
+                       Collection<Object> lae = la.elements();\r
+                       Iterator<Object> li = lae.iterator();\r
+                       Array result = new Array();\r
+                       for(int i=0;i<lae.size();i++) {\r
+                               double ld = (Double)li.next();\r
+                               result.addElement(ld/rd);\r
+                       }\r
+                       return result;\r
+               } else {\r
+                       throw new UnsupportedOperationException();\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new ElementwiseDivision(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+\r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwisePower.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwisePower.java
new file mode 100644 (file)
index 0000000..6fac728
--- /dev/null
@@ -0,0 +1,78 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Collection;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+public class ElementwisePower implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public ElementwisePower(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " ^ " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object left = exp1.evaluate(environment);\r
+               Object right = exp2.evaluate(environment);\r
+               if(left instanceof Array && right instanceof Array) {\r
+                       Array la = (Array)left;\r
+                       Array ra = (Array)right;\r
+                       Collection<Object> lae = la.elements();\r
+                       Collection<Object> rae = ra.elements();\r
+                       if(lae.size() != rae.size()) throw new UnsupportedOperationException();\r
+                       Iterator<Object> li = lae.iterator();\r
+                       Iterator<Object> ri = rae.iterator();\r
+                       Array result = new Array();\r
+                       for(int i=0;i<lae.size();i++) {\r
+                               double ld = (Double)li.next();\r
+                               double rd = (Double)ri.next();\r
+                               result.addElement(Math.pow(ld,rd));\r
+                       }\r
+                       return result;\r
+               } else throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new ElementwisePower(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+\r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwiseProduct.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ElementwiseProduct.java
new file mode 100644 (file)
index 0000000..e3198cf
--- /dev/null
@@ -0,0 +1,91 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Collection;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+public class ElementwiseProduct implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public ElementwiseProduct(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " * " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object left = exp1.evaluate(environment);\r
+               Object right = exp2.evaluate(environment);\r
+               if(left instanceof Array && right instanceof Array) {\r
+                       Array la = (Array)left;\r
+                       Array ra = (Array)right;\r
+                       Collection<Object> lae = la.elements();\r
+                       Collection<Object> rae = ra.elements();\r
+                       if(lae.size() != rae.size()) throw new UnsupportedOperationException();\r
+                       Iterator<Object> li = lae.iterator();\r
+                       Iterator<Object> ri = rae.iterator();\r
+                       Array result = new Array();\r
+                       for(int i=0;i<lae.size();i++) {\r
+                               double ld = (Double)li.next();\r
+                               double rd = (Double)ri.next();\r
+                               result.addElement(ld*rd);\r
+                       }\r
+                       return result;\r
+               } else if (left instanceof Array && right instanceof Double) {\r
+                       Array la = (Array)left;\r
+                       Double rd = (Double)right;\r
+                       Collection<Object> lae = la.elements();\r
+                       Iterator<Object> li = lae.iterator();\r
+                       Array result = new Array();\r
+                       for(int i=0;i<lae.size();i++) {\r
+                               double ld = (Double)li.next();\r
+                               result.addElement(ld*rd);\r
+                       }\r
+                       return result;\r
+               } else {\r
+                       throw new UnsupportedOperationException();\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new ElementwiseProduct(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+\r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/EnumElementsVariableBase.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/EnumElementsVariableBase.java
new file mode 100644 (file)
index 0000000..4ef4da1
--- /dev/null
@@ -0,0 +1,46 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 VTT Technical Research Centre of Finland.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public class EnumElementsVariableBase extends VariableBase {\r
+\r
+       private Array result;\r
+       \r
+       public EnumElementsVariableBase(Model clazz) {\r
+               super("elements");\r
+               result = new Array();\r
+               for(VariableDeclaration vd : clazz.variables) {\r
+                       Constant c = (Constant)vd.modification.args[0].modification;\r
+                       result.addElement(c.value);\r
+               }\r
+       }\r
+\r
+       public EnumElementsVariableBase(String name, Array result) {\r
+               super(name);\r
+               this.result = result;\r
+       }\r
+\r
+       @Override\r
+       public Object evaluate(IEnvironment environment, IExpression[] subscripts, int constantIndex) {\r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       VariableBase withBase(String prefix) {\r
+               return new EnumElementsVariableBase(prefix+name, result);\r
+       }\r
+       \r
+       @Override\r
+       public IExpression getPossibleConstant() {\r
+               return result;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/EnumSizeVariableBase.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/EnumSizeVariableBase.java
new file mode 100644 (file)
index 0000000..63db718
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 VTT Technical Research Centre of Finland.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public class EnumSizeVariableBase extends VariableBase {\r
+\r
+       private Double value;\r
+       \r
+       public EnumSizeVariableBase(Model clazz) {\r
+               super("size");\r
+               value = (double)clazz.variables.size();\r
+       }\r
+\r
+       public EnumSizeVariableBase(String name, double value) {\r
+               super(name);\r
+               this.value = value;\r
+       }\r
+\r
+       @Override\r
+       public Object evaluate(IEnvironment environment, IExpression[] subscripts, int constantIndex) {\r
+               return value;\r
+       }       \r
+\r
+       @Override\r
+       VariableBase withBase(String prefix) {\r
+               return new EnumSizeVariableBase(prefix+name, value);\r
+       }\r
+       \r
+       @Override\r
+       public IExpression getPossibleConstant() {\r
+               return new Constant(value.toString());\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Environment.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Environment.java
new file mode 100644 (file)
index 0000000..a8c875d
--- /dev/null
@@ -0,0 +1,579 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland - #4488\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import gnu.trove.list.array.TIntArrayList;\r
+import gnu.trove.map.hash.TObjectIntHashMap;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import java.util.TreeMap;\r
+\r
+interface Fn {\r
+       public Object evaluate(IEnvironment environment, int argc);\r
+       public Object evaluateInput(IEnvironment environment, int argPosition);\r
+       public void setLocals(IEnvironment environment);\r
+       public int offset();\r
+       public Variable[] parameters();\r
+}\r
+\r
+abstract class Fn1 implements Fn {\r
+\r
+       Variable[] parameters;\r
+       \r
+       public Fn1(int pCount) {\r
+               parameters = new Variable[pCount];\r
+               for(int i=0;i<pCount;i++)\r
+                       parameters[i] = new Variable(new VariableBase("", i));\r
+       }\r
+       \r
+       public int offset() {\r
+               return 0;\r
+       }\r
+       \r
+       public Variable[] parameters() {\r
+               return parameters;\r
+       }\r
+       \r
+       @Override\r
+       public void setLocals(IEnvironment environment) {\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluateInput(IEnvironment environment, int argPosition) {\r
+               // Function frame size is constant - this is called when padding is needed\r
+               return null;\r
+       }\r
+       \r
+}\r
+\r
+final public class Environment implements IEnvironment, ISystem {\r
+       \r
+       final Map<String,Object> named = new HashMap<String,Object>();\r
+\r
+       public Model model;\r
+       public double step;\r
+       public double time;\r
+       public boolean initial = true;\r
+       public int size;\r
+       \r
+       public Object[] valueTable;\r
+       \r
+       public TObjectIntHashMap<String> keyIndexMap = new TObjectIntHashMap<String>(); \r
+\r
+       HashMap<String,TreeMap<Double,Double>> history = new HashMap<String,TreeMap<Double,Double>>();\r
+\r
+       public Environment(Model model, double step, double start) {\r
+               this.model = model;\r
+               this.step = step;\r
+               this.time = start;\r
+               \r
+               model.functions.put("size", new Fn1(2) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Array array = (Array)environment.getValue(0);\r
+                               Double col = (Double)environment.getValue(1);\r
+                               return Double.valueOf(array.size(col.intValue()));\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("exp", new Fn1(2) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Double x = (Double)environment.getValue(0);\r
+                               return Math.exp(x);\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("zidz", new Fn1(2) {\r
+\r
+                       private Object evaluate(Double p1, Double p2) {\r
+                               if(Math.abs(p2) < 1e-12) return 0.0;\r
+                               else return p1 / p2;\r
+                       }\r
+                       \r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Object o1 = environment.getValue(0);\r
+                               Object o2 = environment.getValue(1);\r
+                               \r
+                               if(o1 instanceof Double && o2 instanceof Double) {\r
+                                       return evaluate((Double)o1, (Double)o2);\r
+                               }\r
+                               if(o1 instanceof Array && o2 instanceof Array) {\r
+                                       Array la = (Array)o1;\r
+                                       Array ra = (Array)o2;\r
+                                       Collection<Object> lae = la.elements();\r
+                                       Collection<Object> rae = ra.elements();\r
+                                       if(lae.size() != rae.size()) throw new UnsupportedOperationException();\r
+                                       Iterator<Object> li = lae.iterator();\r
+                                       Iterator<Object> ri = rae.iterator();\r
+                                       Array result = new Array();\r
+                                       for(int i=0;i<lae.size();i++) {\r
+                                               double ld = (Double)li.next();\r
+                                               double rd = (Double)ri.next();\r
+                                               result.addElement(evaluate(ld,rd));\r
+                                       }\r
+                                       return result;\r
+                               }\r
+                               throw new IllegalStateException();\r
+                               \r
+                               \r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("xidz", new Fn1(3) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Double p1 = (Double)environment.getValue(0);\r
+                               Double p2 = (Double)environment.getValue(1);\r
+                               Double x = (Double)environment.getValue(2);\r
+                               if(Math.abs(p2) < 1e-12) return x;\r
+                               else return p1 / p2;\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("availabilityExternal", new Fn1(4) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Double numberOfDays = (Double)environment.getValue(0);\r
+                               Double numberOfDesigners = (Double)environment.getValue(1);\r
+                               Double rseed = (Double)environment.getValue(2);\r
+                               Array availability = (Array)environment.getValue(3);\r
+                               Array result = new Array();\r
+                               for(int i=0;i<numberOfDays.intValue()*numberOfDesigners.intValue();i++) {\r
+                                       result.addElement(Math.random());\r
+                               }\r
+                               return result;\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("pre", new Fn1(1) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               \r
+                               return (Double)environment.getValue(0);\r
+                               \r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("fill", new Fn1(3) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Double value = (Double)environment.getValue(0);\r
+                               Double dim1 = (Double)environment.getValue(1);\r
+                               if(argc == 2) {\r
+                                       Array result = new Array();\r
+                                       for(int i=0;i<dim1.intValue();i++) {\r
+                                               result.addElement(value);\r
+                                       }\r
+                                       return result;\r
+                               } else if(argc == 3) {\r
+                                       Double dim2 = (Double)environment.getValue(2);\r
+                                       Array result = new Array();\r
+                                       for(int i=0;i<dim1.intValue();i++) {\r
+                                               Array array = new Array();\r
+                                               for(int j=0;j<dim2.intValue();j++) {\r
+                                                       array.addElement(value);\r
+                                               }\r
+                                               result.addElement(array);\r
+                                       }\r
+                                       return result;\r
+                               } else throw new UnsupportedOperationException();\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("randomNumber", new Fn1(2) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Double seed = (Double)environment.getValue(0);\r
+                               Double time = (Double)environment.getValue(1);\r
+                               return Math.random();\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("initial", new Fn1(0) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment _environment, int argc) {\r
+                               return _environment.getSystem().initial();\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("noEvent", new Fn1(1) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               \r
+                               return environment.getValue(0);\r
+                               \r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("min", new Fn1(5) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Double result = (Double)environment.getValue(0);\r
+                               for(int i=1;i<argc;i++) {\r
+                                       Double d = (Double)environment.getValue(i);\r
+                                       if(d < result) result = d;\r
+                               }\r
+                               return result;\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("max", new Fn1(5) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Double result = (Double)environment.getValue(0);\r
+                               for(int i=1;i<argc;i++) {\r
+                                       Double d = (Double)environment.getValue(i);\r
+                                       if(d > result) result = d;\r
+                               }\r
+                               return result;\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("integer", new Fn1(1) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Object value = environment.getValue(0);\r
+                               Double result = (Double)value;\r
+                               double res = result.intValue(); \r
+                               return res;\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("sum", new Fn1(1) {\r
+\r
+                       @Override\r
+                       public Object evaluate(IEnvironment environment, int argc) {\r
+                               Object value = environment.getValue(0);\r
+                               Array arr = (Array)value;\r
+                               double res = 0;\r
+                               for(Object o : arr.elements())\r
+                                       res += (Double)o;\r
+                               return res;\r
+                       }\r
+                       \r
+               });\r
+               model.functions.put("delay", new Fn1(4) {\r
+                       \r
+                       @Override\r
+                       public Object evaluate(IEnvironment _environment, int argc) {\r
+                       \r
+                               String ident = (String)_environment.getValue(0);\r
+                               Double value = (Double)_environment.getValue(1);\r
+                               Double p1 = (Double)_environment.getValue(2);\r
+                               \r
+                               ISystem system = _environment.getSystem();\r
+                               \r
+                               TreeMap<Double,Double> history = system.getHistory(ident);\r
+                               double time = system.time();\r
+                               \r
+                               history.put(time, value);\r
+                               \r
+                               Double key = history.ceilingKey(time-p1);\r
+                               \r
+                               return history.get(key);\r
+                               \r
+                       }\r
+                       \r
+               });             \r
+               model.functions.put("cat", new Fn1(10) {\r
+                       \r
+                       @Override\r
+                       public Object evaluate(IEnvironment _environment, int argc) {\r
+                       \r
+                               Double dim = (Double)_environment.getValue(0);\r
+                               \r
+                               Array array = new Array();\r
+                               for(int i=1;i<argc;i++) {\r
+                                       Object ar = _environment.getValue(i);\r
+                                       if (ar instanceof Array) {\r
+                                               Array a = (Array)ar;\r
+                                               for(Object o : a.elements())\r
+                                                       array.addElement(o);\r
+                                       } else {\r
+                                               throw new IllegalStateException();\r
+                                       }\r
+                               }\r
+                               \r
+                               return array;\r
+                               \r
+                       }\r
+                       \r
+               });             \r
+       }\r
+       \r
+       public TreeMap<Double,Double> getHistory(String ident) {\r
+               TreeMap<Double,Double> result = history.get(ident);\r
+               if(result == null) {\r
+                       result = new TreeMap<Double,Double>();\r
+                       history.put(ident, result);\r
+               }\r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public Object getValue(int key) {\r
+               return valueTable[key];\r
+       }\r
+       \r
+       @Override\r
+       public void put(int key, Object value) {\r
+               valueTable[key] = value;\r
+       }\r
+       \r
+       public void put(String key, Object value) {\r
+               named.put(key, value);\r
+       }\r
+\r
+       public void setSize(int size) {\r
+               this.size = size;\r
+       }\r
+       \r
+       @Override\r
+       public int offset() {\r
+               return size;\r
+       }\r
+       \r
+       @Override\r
+       public ISystem getSystem() {\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public boolean initial() {\r
+               return initial;\r
+       }\r
+       \r
+       public Object evaluateFunction(IEnvironment environment, String name, ArgumentList args) {\r
+               return model.evaluateFunction(environment, name, args);\r
+       }\r
+       \r
+       @Override\r
+       public double time() {\r
+               return time;\r
+       }\r
+\r
+       double[] valueArray;\r
+       int[] valueIndices;\r
+       \r
+       public void addIndexed(int dimensions[], ArrayList<String> keys, String prefix, int d) {\r
+\r
+               if(d == dimensions.length) {\r
+                       keys.add(prefix);\r
+                       return;\r
+               }\r
+\r
+               String prefix2 = prefix;\r
+               if(d== 0) prefix2 += "[";\r
+               if(d>0) prefix2 += ",";\r
+\r
+               for(int i=0;i<dimensions[d];i++) {\r
+                       String prefix3 = prefix2 + (i+1);\r
+                       if(d+1 == dimensions.length) prefix3 += "]";\r
+                       addIndexed(dimensions, keys, prefix3, d+1);\r
+               }\r
+               \r
+       }\r
+       \r
+       public int length(int[] dimension) {\r
+               int result = 1;\r
+               for(int d : dimension) result *=d;\r
+               return result;\r
+       }\r
+       \r
+       public void addVariable(String name, int index, int[] dimensions, ArrayList<String> keys, TIntArrayList indices, Set<String> used) {\r
+\r
+               if(!used.add(name)) return;\r
+               \r
+               if(dimensions == null) {\r
+                       keys.add(name);\r
+                       indices.add(index);\r
+               } else {\r
+                       addIndexed(dimensions, keys, name, 0);\r
+                       for(int i=0;i<length(dimensions);i++)\r
+                               indices.add(index+i);\r
+               }\r
+\r
+       }\r
+       \r
+       public void addVariable(Variable var, ArrayList<String> keys, TIntArrayList indices, Set<String> used) {\r
+               addVariable(var.base.name, var.base.index, var.base.dimensions, keys, indices, used);\r
+       }\r
+\r
+       public String[] getValueKeyArray() {\r
+               \r
+               ArrayList<String> keys = new ArrayList<String>();\r
+               TIntArrayList indices = new TIntArrayList();\r
+               Set<String> used = new HashSet<String>();\r
+               \r
+               for (int i = 0; i < model.assignmentArray.length; i++) {\r
+                       addVariable(model.assignmentArray[i].target, keys, indices, used);\r
+               }\r
+               \r
+               for (int i = 0; i < model.derivativeArray.length; i++) {\r
+                       addVariable(model.derivativeArray[i].target, keys, indices, used);\r
+               }\r
+               \r
+               // NOTE: there is room for optimization as parameter values that do not\r
+               // change should only be obtained once (and parameter values that do\r
+               // change are (possibly) included in assignments or derivatives)\r
+               for(int i = 0; i < model.parameterArray.length; i++) {\r
+                       addVariable(model.parameterArray[i].variable, keys, indices, used);\r
+               }\r
+               \r
+               for(Map.Entry<String,VariableBase> entry : model.copies.entrySet()) {\r
+                       addVariable(entry.getKey(), entry.getValue().index, entry.getValue().dimensions, keys, indices, used);\r
+               }\r
+               \r
+               valueArray = new double[keys.size()];\r
+               \r
+               keyIndexMap.clear();\r
+               for(int i=0;i<keys.size();i++) {\r
+                       String key = keys.get(i);\r
+                       int index = indices.get(i);\r
+                       keyIndexMap.put(key, index);\r
+               }\r
+               \r
+               valueIndices = new int[keys.size()];\r
+               getValueIndices();\r
+               \r
+               return keys.toArray(new String[keys.size()]);\r
+               \r
+       }\r
+       \r
+       public int[] getValueIndices() {\r
+\r
+               int offset = 0;\r
+\r
+               Set<String> used = new HashSet<String>();\r
+\r
+               for (int i = 0; i < model.assignmentArray.length; i++) {\r
+                       Variable v = model.assignmentArray[i].target;\r
+                       if(!used.add(v.base.name)) continue;\r
+                       for(int index=0;index<v.base.dimension();index++)\r
+                               valueIndices[offset++] = v.base.index(this, null)+index;\r
+               }\r
+               \r
+               for (int i = 0; i < model.derivativeArray.length; i++) {\r
+                       Variable v = model.derivativeArray[i].target;\r
+                       if(!used.add(v.base.name)) continue;\r
+                       for(int index=0;index<v.base.dimension();index++) {\r
+                               valueIndices[offset++] = v.base.index(this, null)+index;\r
+                       }\r
+               }\r
+               \r
+               // NOTE: there is room for optimization as parameter values that do not\r
+               // change should only be obtained once (and parameter values that do\r
+               // change are (possibly) included in assignments or derivatives)\r
+               for(int i = 0; i < model.parameterArray.length; i++) {\r
+                       Variable v = model.parameterArray[i].variable;\r
+                       if(!used.add(v.base.name)) continue;\r
+                       for(int index=0;index<v.base.dimension();index++)\r
+                               valueIndices[offset++] = v.base.index(this, null)+index;\r
+               }\r
+\r
+               for(Map.Entry<String,VariableBase> entry : model.copies.entrySet()) {\r
+                       VariableBase base = entry.getValue();\r
+                       if(!used.add(entry.getKey())) continue;\r
+                       for(int index=0;index<base.dimension();index++)\r
+                               valueIndices[offset++] = base.index(this, null)+index;\r
+               }\r
+               \r
+               return valueIndices;\r
+               \r
+       }\r
+\r
+       // TODO: this is probably not smart at all, figure out a better way to obtain results\r
+       public double[] getValueArray() {\r
+\r
+               for(int i=0;i<valueArray.length;i++) {\r
+                       Double value = (Double)getValue(valueIndices[i]);\r
+                       // FIXME: should not be fixed like this\r
+                       if(value == null) value = 0.0;\r
+                       valueArray[i] = value;\r
+               }\r
+               \r
+               return valueArray;\r
+               \r
+//             int offset = 0;\r
+//\r
+//             Set<String> used = new HashSet<String>();\r
+//\r
+//             for (int i = 0; i < model.assignmentArray.length; i++) {\r
+//                     Variable v = model.assignmentArray[i].target;\r
+//                     if(!used.add(v.base.name)) continue;\r
+//                     for(int index=0;index<v.base.dimension();index++)\r
+//                             valueArray[offset++] = (Double)getValue(v.base.index(this, null)+index);\r
+//             }\r
+//             \r
+//             for (int i = 0; i < model.derivativeArray.length; i++) {\r
+//                     Variable v = model.derivativeArray[i].target;\r
+//                     if(!used.add(v.base.name)) continue;\r
+//                     for(int index=0;index<v.base.dimension();index++) {\r
+//                             Double value = (Double)getValue(v.base.index(this, null)+index);\r
+//                             // FIXME: should not be fixed like this\r
+//                             if(value == null) value = 0.0;\r
+//                             valueArray[offset++] = value;\r
+//                     }\r
+//             }\r
+//             \r
+//             // NOTE: there is room for optimization as parameter values that do not\r
+//             // change should only be obtained once (and parameter values that do\r
+//             // change are (possibly) included in assignments or derivatives)\r
+//             for(int i = 0; i < model.parameterArray.length; i++) {\r
+//                     Variable v = model.parameterArray[i].variable;\r
+//                     if(!used.add(v.base.name)) continue;\r
+//                     for(int index=0;index<v.base.dimension();index++)\r
+//                             valueArray[offset++] = (Double)getValue(v.base.index(this, null)+index);\r
+//             }\r
+//\r
+//             for(Map.Entry<String,VariableBase> entry : model.copies.entrySet()) {\r
+//                     VariableBase base = entry.getValue();\r
+//                     if(!used.add(entry.getKey())) continue;\r
+//                     for(int index=0;index<base.dimension();index++)\r
+//                             valueArray[offset++] = (Double)getValue(base.index(this, null)+index);\r
+//             }\r
+//             \r
+//             return valueArray;\r
+               \r
+       }\r
+\r
+       @Override\r
+       public Object getNamedValue(String key) {\r
+               return named.get(key);\r
+       }\r
+\r
+       public void setValue(String key, double value) {\r
+               int index = keyIndexMap.get(key);\r
+               put(index, value);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Equals.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Equals.java
new file mode 100644 (file)
index 0000000..5113479
--- /dev/null
@@ -0,0 +1,65 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Equals implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public Equals(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " == " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object v1 = exp1.evaluate(environment);\r
+               Object v2 = exp2.evaluate(environment);\r
+               if(!(v1 instanceof Double))\r
+                       throw new IllegalStateException();\r
+               if(!(v2 instanceof Double))\r
+                       throw new IllegalStateException();\r
+               return (v1.equals(v2));\r
+       }\r
+\r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Equals(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+\r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForArray.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForArray.java
new file mode 100644 (file)
index 0000000..bf7b7be
--- /dev/null
@@ -0,0 +1,124 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Map;\r
+\r
+public class ForArray implements IExpression {\r
+\r
+       private ArrayList<Object> elements = new ArrayList<Object>();\r
+\r
+       public ForArray() {\r
+               \r
+       }\r
+\r
+       public ForArray(ArrayList<Object> elements) {\r
+               this.elements = elements;\r
+       }\r
+\r
+       public void addElement(Object element) {\r
+               if(element instanceof Constant) addElement(((Constant)element).value);\r
+               else elements.add(element);\r
+       }\r
+       \r
+       public void setElement(int index, Object element) {\r
+               elements.set(index, element);\r
+       }\r
+\r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               return evaluated(environment);\r
+       }\r
+       \r
+       public Array evaluated(IEnvironment environment) {\r
+               \r
+               Array result = new Array();\r
+               \r
+               IExpression exp = (IExpression)elements.get(0);\r
+               Argument arg = (Argument)elements.get(1);\r
+               \r
+               Array indices = (Array)arg.modification.evaluate(environment);\r
+               for(Object o : indices.elements()) {\r
+                       environment.put(arg.name, o);\r
+//                     Frame f = new Frame(environment, 1);\r
+//                     f.put(arg.name, o);\r
+                       result.addElement(exp.evaluate(environment));\r
+               }\r
+               \r
+               return result;\r
+               \r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return elements.toString();\r
+       }\r
+       \r
+       public int size(int col) {\r
+               return elements.size();\r
+       }\r
+       \r
+       public Object element(int index) {\r
+               return elements.get(index);\r
+       }\r
+       \r
+       public Collection<Object> elements() {\r
+               return elements;\r
+       }\r
+       \r
+       public void ensureIndex(int index, boolean subArray) {\r
+               int needed = (index+1-elements.size());\r
+               for(int i=0;i<needed;i++) addElement(subArray ? new ForArray() : null);\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               ArrayList<Object> e = new ArrayList<Object>();\r
+               for(Object o : elements) {\r
+                       if(o instanceof IExpression) {\r
+                               e.add(((IExpression)o).withBase(frame, prefix));\r
+                       } else {\r
+                               e.add(o);\r
+                       }\r
+               }\r
+               return new ForArray(e);\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               for(int i=0;i<elements.size();i++) {\r
+                       Object o = elements.get(i);\r
+                       if(o instanceof IExpression) {\r
+                               elements.set(i, ((IExpression)o).rewrite(frame, copies));\r
+                       }\r
+               }\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               for(int i=0;i<elements.size();i++) {\r
+                       Object o = elements.get(i);\r
+                       if(o instanceof IExpression) {\r
+                               ((IExpression)o).accept(visitor);\r
+                       }\r
+               }\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForIndex.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForIndex.java
new file mode 100644 (file)
index 0000000..9195081
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public class ForIndex {\r
+       \r
+       public String name;\r
+       public VariableBase base;\r
+       public IExpression expression;\r
+       \r
+       public ForIndex(Function function, String name, IExpression expression) {\r
+               this.expression = expression;\r
+               this.name = name;\r
+               if(function != null)\r
+                       this.base = function.addIndex(name, this);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForStatement.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ForStatement.java
new file mode 100644 (file)
index 0000000..5dedd79
--- /dev/null
@@ -0,0 +1,49 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class ForStatement implements IStatement {\r
+\r
+       public ArrayList<ForIndex> indices;\r
+       public IStatement statement;\r
+       \r
+       public ForStatement(ArrayList<ForIndex> indices, IStatement statement) {\r
+               this.indices = indices;\r
+               this.statement = statement;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return "for " + indices + " loop "+ statement + " end for";\r
+       }\r
+       \r
+       private void loop(IEnvironment environment, int i) {\r
+               if(i == indices.size()) {\r
+                       statement.evaluate(environment);\r
+                       return;\r
+               } else {\r
+                       ForIndex index = indices.get(i);\r
+                       Array array = (Array)index.expression.evaluate(environment);\r
+                       for(Object element : array.elements()) {\r
+                               environment.put(index.base.index, element);\r
+                               loop(environment, i+1);\r
+                       }\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public void evaluate(IEnvironment environment) {\r
+               loop(environment, 0);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Frame.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Frame.java
new file mode 100644 (file)
index 0000000..178bf2a
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+public class Frame implements IEnvironment {\r
+       \r
+       final public IEnvironment parent;\r
+       final private int offset;\r
+       Map<String,Object> named;\r
+       \r
+       public Frame(IEnvironment parent, int offset) {\r
+               this.parent = parent;\r
+               this.offset = offset;\r
+       }\r
+       \r
+       @Override\r
+       public int offset() {\r
+               return offset;\r
+       }\r
+       \r
+       @Override\r
+       public void put(int index, Object value) {\r
+               parent.put(parent.offset() + index, value);\r
+       }\r
+\r
+       public void put(String key, Object value) {\r
+               if(named == null) named = new HashMap<String,Object>();\r
+               named.put(key, value);\r
+       }\r
+       \r
+       @Override\r
+       public Object getValue(int index) {\r
+               return parent.getValue(parent.offset() + index);\r
+       }\r
+\r
+       @Override\r
+       public Object getNamedValue(String key) {\r
+               if(named == null) return null;\r
+               return named.get(key);\r
+       }\r
+       \r
+       @Override\r
+       public ISystem getSystem() {\r
+               return parent.getSystem();\r
+       }\r
+       \r
+}\r
+       
\ No newline at end of file
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Function.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Function.java
new file mode 100644 (file)
index 0000000..3c32e6e
--- /dev/null
@@ -0,0 +1,124 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+final public class Function implements Fn, IFrame {\r
+       \r
+       public static final boolean PRINT = false;\r
+       \r
+       final public String name;\r
+       final public IStatement statement;\r
+       \r
+       public ArrayList<VariableDeclaration> inputs = new ArrayList<VariableDeclaration>();\r
+       public ArrayList<VariableDeclaration> outputs = new ArrayList<VariableDeclaration>();\r
+       public ArrayList<VariableDeclaration> internals = new ArrayList<VariableDeclaration>();\r
+       \r
+       public Variable[] parameters;\r
+       \r
+       public ArrayList<ForIndex> indices = new ArrayList<ForIndex>();\r
+\r
+       public Function(String name, IStatement statement) {\r
+               this.name = name;\r
+               this.statement = statement;\r
+       }\r
+       \r
+       public Object evaluate(IEnvironment environment, int argc) {\r
+               statement.evaluate(environment);\r
+               VariableDeclaration out = outputs.get(0);\r
+               return environment.getValue(out.variable.base.index);\r
+       }\r
+       \r
+       @Override\r
+       public void setLocals(IEnvironment environment) {\r
+               for(int i=0;i<outputs.size();i++) {\r
+                       VariableDeclaration decl = outputs.get(i);\r
+                       decl.variable.assignPlain(environment, null);\r
+               }\r
+               for(int i=0;i<internals.size();i++) {\r
+                       VariableDeclaration decl = internals.get(i);\r
+                       decl.variable.assignPlain(environment, null);\r
+               }\r
+       }\r
+       \r
+       public VariableBase addIndex(String name, ForIndex index) {\r
+               indices.add(index);\r
+               return getBase(name);\r
+       }\r
+       \r
+       public HashMap<String,VariableBase> names = new HashMap<String,VariableBase>();\r
+       \r
+       public VariableBase getBase(String name) {\r
+               VariableBase base = names.get(name);\r
+               if(base == null) {\r
+                       base = new VariableBase(name);\r
+                       names.put(name, base);\r
+               }\r
+               return base;\r
+       }\r
+       \r
+       @Override\r
+       public VariableBase getBase(VariableBase base, String prefix) {\r
+               throw new IllegalStateException();\r
+       }\r
+       \r
+       public void prepare() {\r
+               int nextIndex = 0;\r
+               if(PRINT)\r
+                       System.err.println("Preparing function '" + name + "':");\r
+               for(Map.Entry<String, VariableBase> entry : names.entrySet()) {\r
+                       VariableBase base = entry.getValue();\r
+                       base.index = nextIndex;\r
+                       if(PRINT)\r
+                               System.err.println("Variable: " + entry.getKey() + ", index=" + base.index + ", size=" + base.dimension());\r
+                       nextIndex += base.dimension();\r
+               }\r
+               parameters = new Variable[inputs.size()];\r
+               for(int i=0;i<inputs.size();i++) {\r
+                       VariableDeclaration decl = inputs.get(i);\r
+                       parameters[i] = decl.variable;\r
+                       decl.variable.base.tellSubscripts(decl.variable.subscripts, null);\r
+               }\r
+               for(int i=0;i<outputs.size();i++) {\r
+                       VariableDeclaration decl = outputs.get(i);\r
+                       decl.variable.base.tellSubscripts(decl.variable.subscripts, null);\r
+               }\r
+               for(int i=0;i<internals.size();i++) {\r
+                       VariableDeclaration decl = internals.get(i);\r
+                       decl.variable.base.tellSubscripts(decl.variable.subscripts, null);\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public int offset() {\r
+               return names.size();\r
+       }\r
+       \r
+       @Override\r
+       public Variable[] parameters() {\r
+               return parameters;\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluateInput(IEnvironment environment, int argPosition) {\r
+               VariableDeclaration decl = inputs.get(argPosition);\r
+               return decl.modification.args[0].modification.evaluate(environment);\r
+       }\r
+       \r
+       @Override\r
+       public Model getClass(String name) {\r
+               return null;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/GreaterOrEqualThan.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/GreaterOrEqualThan.java
new file mode 100644 (file)
index 0000000..e9f8cdc
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class GreaterOrEqualThan implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public GreaterOrEqualThan(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " >= " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               return ((Double)exp1.evaluate(environment)) >= ((Double)exp2.evaluate(environment));\r
+       }\r
+\r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new GreaterOrEqualThan(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/GreaterThan.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/GreaterThan.java
new file mode 100644 (file)
index 0000000..e91f0ff
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class GreaterThan implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public GreaterThan(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " > " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               return ((Double)exp1.evaluate(environment)) > ((Double)exp2.evaluate(environment));\r
+       }\r
+\r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new GreaterThan(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IEnvironment.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IEnvironment.java
new file mode 100644 (file)
index 0000000..036c1e9
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public interface IEnvironment {\r
+\r
+//     Object getValue(String key);\r
+       Object getNamedValue(String key);\r
+       Object getValue(int index);\r
+       void put(String key, Object value);\r
+       void put(int index, Object value);\r
+//     Object evaluateFunction(IEnvironment parent, String name, ArgumentList args);\r
+       \r
+       int offset();\r
+       \r
+       ISystem getSystem();\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IExpression.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IExpression.java
new file mode 100644 (file)
index 0000000..5d58d7f
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public interface IExpression {\r
+\r
+       public interface ExpressionVisitor {\r
+               void visit(IExpression expression);\r
+       }\r
+       \r
+       public Object evaluate(IEnvironment environment);\r
+       public IExpression withBase(IFrame frame, String prefix);\r
+       public Object getPossibleConstant();\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies);\r
+       public void accept(ExpressionVisitor visitor);\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IFrame.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IFrame.java
new file mode 100644 (file)
index 0000000..805ef55
--- /dev/null
@@ -0,0 +1,17 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public interface IFrame {\r
+       public VariableBase getBase(String name);\r
+       public VariableBase getBase(VariableBase base, String prefix);\r
+       public Model getClass(String name);\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IStatement.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IStatement.java
new file mode 100644 (file)
index 0000000..e50a09b
--- /dev/null
@@ -0,0 +1,17 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public interface IStatement {\r
+\r
+       public void evaluate(IEnvironment environment);\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ISystem.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ISystem.java
new file mode 100644 (file)
index 0000000..8f01d10
--- /dev/null
@@ -0,0 +1,23 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.TreeMap;\r
+\r
+public interface ISystem {\r
+\r
+       boolean initial();\r
+       public Object evaluateFunction(IEnvironment environment, String name, ArgumentList args);\r
+       \r
+       TreeMap<Double,Double> getHistory(String ident);\r
+       double time();\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IfStatement.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IfStatement.java
new file mode 100644 (file)
index 0000000..37dc2af
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public class IfStatement implements IStatement {\r
+       \r
+    public IExpression exp;\r
+    public IStatement t;\r
+    public IStatement e;\r
+    \r
+    public IfStatement(IExpression exp, IStatement t, IStatement e) {\r
+       this.exp = exp;\r
+       this.t = t;\r
+       this.e = e;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return "if " + exp + " then " + t + " else "+ e;\r
+    }\r
+    \r
+       @Override\r
+       public void evaluate(IEnvironment environment) {\r
+               if((Boolean)exp.evaluate(environment)) {\r
+                       t.evaluate(environment);\r
+               } else {\r
+                       e.evaluate(environment);\r
+               }\r
+       }\r
+    \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IfThenElse.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/IfThenElse.java
new file mode 100644 (file)
index 0000000..d8511d7
--- /dev/null
@@ -0,0 +1,67 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class IfThenElse implements IExpression {\r
+       \r
+    public IExpression exp;\r
+    public IExpression t;\r
+    public IExpression e;\r
+    \r
+    public IfThenElse(IExpression exp, IExpression t, IExpression e) {\r
+       this.exp = exp;\r
+       this.t = t;\r
+       this.e = e;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return "if " + exp + " then " + t + " else "+ e;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               if((Boolean)exp.evaluate(environment)) {\r
+                       return t.evaluate(environment);\r
+               } else {\r
+                       return e.evaluate(environment);\r
+               }\r
+       }\r
+    \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new IfThenElse(exp.withBase(frame, prefix), t.withBase(frame, prefix), e.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp = exp.rewrite(frame, copies);\r
+               t = t.rewrite(frame, copies);\r
+               e = e.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp.accept(visitor);\r
+               t.accept(visitor);\r
+               e.accept(visitor);\r
+       }\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LessOrEqualThan.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LessOrEqualThan.java
new file mode 100644 (file)
index 0000000..d45163e
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class LessOrEqualThan implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public LessOrEqualThan(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " <= " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Double d1 = (Double)exp1.evaluate(environment);\r
+               Double d2 = (Double)exp2.evaluate(environment);\r
+               return d1 <= d2;\r
+       }\r
+\r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new LessOrEqualThan(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LessThan.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LessThan.java
new file mode 100644 (file)
index 0000000..d66d63a
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class LessThan implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public LessThan(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " < " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object left = exp1.evaluate(environment);\r
+               Object right = exp2.evaluate(environment);\r
+               return ((Double)left) < ((Double)right);\r
+       }\r
+    \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new LessThan(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LineReader.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/LineReader.java
new file mode 100644 (file)
index 0000000..4b2da14
--- /dev/null
@@ -0,0 +1,185 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.io.StringReader;\r
+\r
+import fi.semantum.sysdyn.solver.Model.Globals;\r
+import fi.semantum.sysdyn.solver.parser.ModelParser;\r
+import fi.semantum.sysdyn.solver.parser.Node;\r
+import fi.semantum.sysdyn.solver.parser.SimpleNode;\r
+\r
+public class LineReader {\r
+\r
+       public static final boolean PRINT = false;\r
+       \r
+       enum State {\r
+               FUNCTIONS,PARAMETERS,INITIALS,EQUATIONS,STOP\r
+       }\r
+       \r
+       private State state = State.FUNCTIONS;\r
+\r
+       StringBuilder functions = new StringBuilder();\r
+       \r
+       int startPos = 0;\r
+       int pos = 0;\r
+       final char[] chars;\r
+       final NodeCache cache;\r
+       final Model model;\r
+       final Parser parser;\r
+       \r
+       public LineReader(String input, NodeCache cache) {\r
+               chars = input.toCharArray();\r
+               this.cache = cache;\r
+               model = new Model(new Globals(), "", false);\r
+               parser = new Parser();\r
+       }\r
+       \r
+       public void parseFunctions(String line) throws Exception {\r
+               \r
+               if(line.startsWith("class")) {\r
+\r
+                       String text = functions.toString();\r
+                       \r
+                       Node node = cache.getNode(text);\r
+                       if(node == null) {\r
+                               StringReader reader = new StringReader(functions.toString());\r
+                               ModelParser modelParser = new ModelParser(reader);\r
+                               node = modelParser.parse();\r
+                               cache.store(text, (SimpleNode)node);\r
+                       }\r
+                       \r
+                       parser.walk((SimpleNode)node, 0, model);\r
+                       \r
+                       state = State.PARAMETERS;\r
+                       return;\r
+               }\r
+               \r
+               functions.append(line);\r
+               functions.append("\n");\r
+               \r
+       }\r
+       \r
+       public void parseParameters(String line) throws Exception {\r
+\r
+               if("initial equation".equals(line)) {\r
+                       state = State.INITIALS;\r
+                       return;\r
+               }\r
+\r
+               if("equation".equals(line)) {\r
+                       state = State.EQUATIONS;\r
+                       return;\r
+               }\r
+\r
+               if(PRINT) System.err.println("parameter: '" + line + "'");\r
+\r
+               Node node = cache.getNode(line);\r
+               if(node == null) {\r
+                       StringReader reader = new StringReader(line);\r
+                       ModelParser modelParser = new ModelParser(reader);\r
+                       node = modelParser.element();\r
+                       cache.store(line, (SimpleNode)node);\r
+               }               \r
+               \r
+               parser.walk((SimpleNode)node, 0, model);\r
+               \r
+       }\r
+\r
+       public void parseInitials(String line) throws Exception {\r
+               \r
+               if(line.startsWith("equation")) {\r
+                       state = State.EQUATIONS;\r
+                       return;\r
+               }\r
+\r
+               if(line.startsWith("end")) {\r
+                       state = State.STOP;\r
+                       return;\r
+               }\r
+               \r
+               model.initial = true;\r
+               \r
+               if(PRINT) System.err.println("initial: '" + line + "'");\r
+\r
+               Node node = cache.getNode(line);\r
+               if(node == null) {\r
+                       StringReader reader = new StringReader(line);\r
+                       ModelParser modelParser = new ModelParser(reader);\r
+                       node = modelParser.equation();\r
+                       cache.store(line, (SimpleNode)node);\r
+               }               \r
+               \r
+               parser.walk((SimpleNode)node, 0, model);\r
+               \r
+       }\r
+       \r
+       public void parseEquations(String line) throws Exception {\r
+               \r
+               if(line.startsWith("end")) {\r
+                       state = State.STOP;\r
+                       return;\r
+               }\r
+               \r
+               if(PRINT) System.err.println("equation: '" + line + "'");\r
+\r
+               model.initial = false;\r
+\r
+               Node node = cache.getNode(line);\r
+               if(node == null) {\r
+                       StringReader reader = new StringReader(line);\r
+                       ModelParser modelParser = new ModelParser(reader);\r
+                       node = modelParser.equation();\r
+                       cache.store(line, (SimpleNode)node);\r
+               }               \r
+               \r
+               parser.walk((SimpleNode)node, 0, model);\r
+               \r
+       }\r
+\r
+       public void parseLine(String line) throws Exception {\r
+               //System.err.println("PARSE "+line);\r
+               switch(state) {\r
+               case FUNCTIONS:\r
+                       parseFunctions(line);\r
+                       break;\r
+               case PARAMETERS:\r
+                       parseParameters(line);\r
+                       break;\r
+               case INITIALS:\r
+                       parseInitials(line);\r
+                       break;\r
+               case EQUATIONS:\r
+                       parseEquations(line);\r
+                       break;\r
+               case STOP:\r
+                       break;\r
+               }\r
+       }       \r
+\r
+       public void parse() throws Exception {\r
+\r
+               //long start = System.nanoTime();\r
+               \r
+               for(;pos<chars.length;pos++) {\r
+                       if(chars[pos] == '\r') {\r
+                               String line = new String(chars, startPos, pos-startPos);\r
+                               parseLine(line);\r
+                               pos++;\r
+                               startPos = pos+1;\r
+                       }\r
+               }\r
+\r
+               //long duration = System.nanoTime() - start;\r
+               //System.err.println("LineReader parse in " + 1e-9*duration + "s.");            \r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Model.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Model.java
new file mode 100644 (file)
index 0000000..e4b1337
--- /dev/null
@@ -0,0 +1,336 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+import java.util.TreeMap;\r
+\r
+class Model implements IFrame {\r
+       \r
+       static class Globals {\r
+               public Map<String,Model> classes = new HashMap<String,Model>();\r
+       }\r
+       \r
+       final public static boolean PRINT = false;\r
+       \r
+       public boolean initial = false;\r
+       public ArrayList<Assignment> initials = new ArrayList<Assignment>();\r
+       public ArrayList<Assignment> assignments = new ArrayList<Assignment>();\r
+       public ArrayList<Assignment> derivatives = new ArrayList<Assignment>();\r
+       public ArrayList<ParameterDeclaration> parameters = new ArrayList<ParameterDeclaration>();\r
+       public ArrayList<VariableDeclaration> variables = new ArrayList<VariableDeclaration>();\r
+       public Map<String,Fn> functions = new HashMap<String,Fn>();\r
+       public Map<String,VariableBase> copies;\r
+       \r
+       public Assignment[] assignmentArray;\r
+       public Assignment[] derivativeArray;\r
+       public ParameterDeclaration[] parameterArray;\r
+       \r
+       public final Globals globals;\r
+       \r
+       public String name;\r
+       public boolean isEnumClass;\r
+       \r
+       public Model(Globals globals, String name, boolean isEnumClass) {\r
+               this.globals = globals;\r
+               this.name = name;\r
+               this.isEnumClass = isEnumClass;\r
+       }\r
+       \r
+       public void addVariable(VariableDeclaration vd) {\r
+               this.variables.add(vd);\r
+       }\r
+       \r
+       public Fn getFunction(String name) {\r
+               return functions.get(name);\r
+       }\r
+       \r
+       public HashMap<String,VariableBase> names = new HashMap<String,VariableBase>();\r
+       \r
+       public VariableBase getBase(VariableBase original, String prefix) {\r
+               VariableBase base = names.get(prefix+original.name);\r
+               if(base != null) return base;\r
+               base = original.withBase(prefix);\r
+               names.put(base.name, base);\r
+               return base;\r
+       }\r
+       \r
+       public VariableBase getBase(String name) {\r
+               VariableBase base = names.get(name);\r
+               if(base == null) {\r
+                       \r
+                       if(isEnumClass) {\r
+                               if("size".equals(name)) base = new EnumSizeVariableBase(this);\r
+                               else if("elements".equals(name)) base = new EnumElementsVariableBase(this);\r
+                       } \r
+                       \r
+                       if(base == null) base = new VariableBase(name);\r
+                       names.put(name, base);\r
+               }\r
+               return base;\r
+       }\r
+       \r
+       public Object evaluateFunction(IEnvironment environment, String name, ArgumentList args) {\r
+               Fn fn = getFunction(name);\r
+               if(fn == null) {\r
+                       fn = functions.get(name);\r
+                       if(fn == null) throw new RuntimeException("Undefined function '" + name + "'");\r
+               }\r
+               // knife!\r
+               if("delay".equals(name)) {\r
+                       \r
+                       Frame frame = new Frame(environment, fn.offset());\r
+\r
+                       ArrayList<Object> argh = new ArrayList<Object>();\r
+                       argh.add(args.args[0].modification.toString());\r
+                       for(int i=0;i<args.args.length;i++) {\r
+                               argh.add(args.args[i].modification.evaluate(environment));\r
+                       }\r
+                       \r
+                       Variable[] parameters = fn.parameters();\r
+                       \r
+                       for(int i=0;i<args.args.length+1;i++) {\r
+                               Variable var = parameters[i];\r
+                               Object value = argh.get(i);\r
+                               var.assignPlain(frame, value);\r
+                       }\r
+\r
+                       fn.setLocals(frame);\r
+                       \r
+                       return fn.evaluate(frame, args.args.length+1);\r
+                       \r
+               } else {\r
+                       \r
+                       Frame frame = new Frame(environment, fn.offset());\r
+                       \r
+                       ArrayList<Object> argh = new ArrayList<Object>();\r
+                       for(int i=0;i<args.args.length;i++) {\r
+                               Object arg = args.args[i].modification.evaluate(environment);\r
+                               if(arg == null) throw new IllegalStateException("No value for " + args.args[i].modification);\r
+                               argh.add(arg);\r
+                       }\r
+                       \r
+                       Variable[] parameters = fn.parameters();\r
+                       \r
+                       for(int i=0;i<parameters.length;i++) {\r
+                               Variable var = parameters[i];\r
+                               if(i < argh.size()) {\r
+                                       Object value = argh.get(i);\r
+                                       var.assignPlain(frame, value);\r
+                               } else {\r
+                                       Object value = fn.evaluateInput(environment, i);\r
+                                       var.assignPlain(frame, value);\r
+                               }\r
+                       }\r
+                       \r
+                       fn.setLocals(frame);\r
+                       return fn.evaluate(frame, args.args.length);\r
+                       \r
+               }\r
+                       \r
+       }\r
+       \r
+       private VariableBase resolveCopy(Map<String,VariableBase> work, VariableBase target) {\r
+               VariableBase deep = work.get(target.name);\r
+               if(deep == null) return target;\r
+               return resolveCopy(work, deep);\r
+       }\r
+       \r
+       private void rewrite() {\r
+\r
+               ArrayList<ParameterDeclaration> parameterCopies = new ArrayList<ParameterDeclaration>();\r
+               ArrayList<Assignment> variableCopies = new ArrayList<Assignment>();\r
+\r
+               HashMap<String,VariableBase> work = new HashMap<String,VariableBase>();\r
+               \r
+               for(ParameterDeclaration pd : parameters) {\r
+                       if(pd.modification instanceof Variable) {\r
+                               Variable var = (Variable)pd.modification;\r
+                               if(!SolverUtils.isFullSubscript(var.subscripts)) continue;\r
+                               if(!SolverUtils.isFullSubscript(pd.variable.subscripts)) continue;\r
+                               parameterCopies.add(pd);\r
+                               work.put(pd.variable.base.name, var.base);\r
+                       }\r
+               }\r
+               for(Assignment ass : assignments) {\r
+                       if(ass.expression instanceof Variable) {\r
+                               Variable var = (Variable)ass.expression;\r
+                               if(!SolverUtils.isFullSubscript(var.subscripts)) continue;\r
+                               if(!SolverUtils.isFullSubscript(ass.target.subscripts)) continue;\r
+                               variableCopies.add(ass);\r
+                               work.put(ass.target.base.name, var.base);\r
+                       }\r
+               }\r
+\r
+               parameters.removeAll(parameterCopies);\r
+               assignments.removeAll(variableCopies);\r
+\r
+               copies = new TreeMap<String,VariableBase>();\r
+               for(String key : work.keySet()) {\r
+                       VariableBase b = resolveCopy(work, work.get(key));\r
+                       copies.put(key, b);\r
+               }\r
+\r
+               for(VariableDeclaration vd : variables) {\r
+                       vd.modification = vd.modification.rewrite(this, copies);\r
+                       vd.variable = (Variable)vd.variable.rewrite(this, copies);\r
+               }\r
+               for(ParameterDeclaration pd : parameters) {\r
+                       pd.modification = pd.modification.rewrite(this, copies);\r
+               }\r
+               for(Assignment ass : assignments) {\r
+                       ass.expression = ass.expression.rewrite(this, copies);\r
+               }\r
+               for(Assignment ass : derivatives) {\r
+                       ass.expression = ass.expression.rewrite(this, copies);\r
+               }\r
+               for(Assignment ass : initials) {\r
+                       ass.expression = ass.expression.rewrite(this, copies);\r
+               }\r
+               \r
+       }\r
+       \r
+       public int prepare() {\r
+\r
+               if(PRINT) {\r
+                       System.err.println("Prepare model:");\r
+                       System.err.println("==================");\r
+               }\r
+               \r
+               rewrite();\r
+               \r
+               boolean done = true;\r
+               \r
+               for(int i=0;i<50;i++) {\r
+                       done = true;\r
+                       for(VariableDeclaration vd : variables) {\r
+                               done &= vd.variable.base.tellSubscripts(vd.variable.subscripts, null);\r
+                       }\r
+                       for(ParameterDeclaration pd : parameters) {\r
+                               done &= pd.variable.base.tellSubscripts(pd.variable.subscripts, pd.modification);\r
+                       }\r
+                       if(done) break;\r
+               }\r
+               \r
+               if(!done) throw new IllegalStateException();\r
+               \r
+               int nextIndex = 0;\r
+               for(Map.Entry<String, VariableBase> entry : names.entrySet()) {\r
+                       VariableBase base = entry.getValue();\r
+                       base.index = nextIndex;\r
+                       if(PRINT)\r
+                               System.err.println("Variable: " + entry.getKey() + " " + base.index + " " + Arrays.toString(base.dimensions));\r
+                       int dim = base.dimension();\r
+                       if(dim == -1) dim = 1;\r
+                       nextIndex += dim;\r
+               }\r
+               \r
+               if(PRINT)\r
+                       System.err.println("==================");\r
+               \r
+               return nextIndex;\r
+               \r
+       }\r
+       \r
+       public void prettyPrint() {\r
+\r
+               System.err.println("initials");\r
+               for(Assignment a : initials) {\r
+                       System.err.println("-"+a);\r
+               }\r
+               System.err.println("assignments");\r
+               for(Assignment a : assignments) {\r
+                       System.err.println("-"+a);\r
+               }\r
+               System.err.println("derivatives");\r
+               for(Assignment a : derivatives) {\r
+                       System.err.println("-"+a);\r
+               }\r
+               System.err.println("parameters");\r
+               for(ParameterDeclaration a : parameters) {\r
+                       System.err.println("-"+a);\r
+               }\r
+               System.err.println("variables");\r
+               for(VariableDeclaration a : variables) {\r
+                       System.err.println("-"+a);\r
+               }\r
+               System.err.println("functions");\r
+               for(Map.Entry<String, Fn> a : functions.entrySet()) {\r
+                       System.err.println("-"+a.getKey() + " " + a.getValue());\r
+               }\r
+               \r
+       }\r
+       \r
+       @Override\r
+       public Model getClass(String name) {\r
+               return globals.classes.get(name);\r
+       }\r
+       \r
+       public boolean instantiateClass(String type_specifier, Declaration decl, IFrame currentFrame) {\r
+               \r
+               Model clazz = globals.classes.get(type_specifier);\r
+               if(clazz == null) return false;\r
+\r
+               Map<String,IExpression> modifications = new HashMap<String,IExpression>();\r
+               if(decl.modification instanceof ArgumentList) {\r
+                       ArgumentList args = (ArgumentList)decl.modification;\r
+                       for(Argument a : args.args) {\r
+                               modifications.put(a.name, a.modification);\r
+                       }\r
+               }\r
+               \r
+               for(VariableDeclaration vd : clazz.variables) {\r
+                       String base = decl.variable.base.name + ".";\r
+                       Variable var2 = vd.variable.withBase(currentFrame, base);\r
+                       VariableDeclaration vd2 = new VariableDeclaration(var2, vd.direction, vd.type, vd.modification.withBase(currentFrame, base));\r
+                       variables.add(vd2);\r
+               }\r
+               for(ParameterDeclaration pd : clazz.parameters) {\r
+                       IExpression modi = modifications.get(pd.variable.base.name);\r
+                       if(modi != null) {\r
+                               String base = decl.variable.base.name + ".";\r
+                               Variable var2 = pd.variable.withBase(currentFrame, base);\r
+                               var2.subscripts = null;\r
+                               ParameterDeclaration pd2 = new ParameterDeclaration(var2, modi);\r
+                               parameters.add(pd2);\r
+                               modifications.remove(pd.variable.base.name);\r
+                       } else {\r
+                               String base = decl.variable.base.name + ".";\r
+                               Variable var2 = pd.variable.withBase(currentFrame, base);\r
+                               ParameterDeclaration pd2 = new ParameterDeclaration(var2, pd.modification.withBase(currentFrame, base));\r
+                               parameters.add(pd2);\r
+                       }\r
+               }\r
+               \r
+               if(!modifications.isEmpty())\r
+                       throw new IllegalStateException();\r
+               \r
+               for(Assignment ass : clazz.assignments) {\r
+                       Assignment ass2 = ass.withBase(currentFrame, decl.variable.base.name + ".");\r
+                       assignments.add(ass2);\r
+               }\r
+               for(Assignment ass : clazz.initials) {\r
+                       Assignment ass2 = ass.withBase(currentFrame, decl.variable.base.name + ".");\r
+                       initials.add(ass2);\r
+               }\r
+               for(Assignment ass : clazz.derivatives) {\r
+                       Assignment ass2 = ass.withBase(currentFrame, decl.variable.base.name + ".");\r
+                       derivatives.add(ass2);\r
+               }\r
+               \r
+               return true;\r
+               \r
+       }\r
+       \r
+}
\ No newline at end of file
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/MultiStatement.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/MultiStatement.java
new file mode 100644 (file)
index 0000000..ff33037
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class MultiStatement implements IStatement {\r
+       \r
+       public ArrayList<Variable> targets;\r
+       public Variable fn;\r
+    public ArgumentList args;\r
+    \r
+    public MultiStatement(ArrayList<Variable> targets, Variable fn, ArgumentList args) {\r
+       this.targets = targets;\r
+       this.fn = fn;\r
+       this.args = args;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return targets + " := " + fn + " " + args;\r
+    }\r
+    \r
+    @Override\r
+    public void evaluate(IEnvironment environment) {\r
+       @SuppressWarnings("unchecked")\r
+       ArrayList<Object> values = (ArrayList<Object>)environment.getSystem().evaluateFunction(environment, fn.base.name, args);\r
+       for(int i=0;i<targets.size();i++) {\r
+               targets.get(i).assignPlain(environment, values.get(i));\r
+       }\r
+    }\r
+    \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Multiplication.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Multiplication.java
new file mode 100644 (file)
index 0000000..e4d29b2
--- /dev/null
@@ -0,0 +1,73 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Multiplication implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public Multiplication(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " * " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object left = exp1.evaluate(environment);\r
+               Object right = exp2.evaluate(environment);\r
+               if(left == null || right == null) return null;\r
+               if(left instanceof Double && right instanceof Double) {\r
+                       return ((Double)left)*((Double)right);\r
+               } \r
+               else if(left instanceof Array && right instanceof Array) {\r
+                       Array la = (Array)left;\r
+                       Array ra = (Array)right;\r
+                       return la.mul(ra);\r
+               }\r
+               else if (left instanceof Array && right instanceof Double) return ((Array)left).mul((Double)right);\r
+               else if (left instanceof Double && right instanceof Array) return ((Array)right).mul((Double)left);\r
+               throw new IllegalStateException();\r
+               \r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Multiplication(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Negation.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Negation.java
new file mode 100644 (file)
index 0000000..8cdad84
--- /dev/null
@@ -0,0 +1,57 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Negation implements IExpression {\r
+       \r
+    public IExpression exp;\r
+    \r
+    public Negation(IExpression exp) {\r
+       this.exp = exp;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return "-" + exp;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Double d = (Double)exp.evaluate(environment);\r
+               if(d == null) return null;\r
+               return -d;\r
+       }\r
+    \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Negation(exp.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp = exp.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NodeCache.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NodeCache.java
new file mode 100644 (file)
index 0000000..3a49e98
--- /dev/null
@@ -0,0 +1,30 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import fi.semantum.sysdyn.solver.parser.SimpleNode;\r
+\r
+public class NodeCache {\r
+       \r
+       Map<String,SimpleNode> cache = new HashMap<String,SimpleNode>();\r
+       \r
+       public SimpleNode getNode(String line) {\r
+               return cache.get(line);\r
+       }\r
+       \r
+       public void store(String line, SimpleNode node) {\r
+               cache.put(line, node);\r
+       }\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NodeClass.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NodeClass.java
new file mode 100644 (file)
index 0000000..81b86df
--- /dev/null
@@ -0,0 +1,66 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public enum NodeClass {\r
+\r
+       assignment,\r
+       equation_section,\r
+       composition,\r
+       for_index,\r
+       for_indices,\r
+       for_statement,\r
+       if_statement,\r
+       while_statement,\r
+       statement,\r
+       name,\r
+       element,\r
+       element_list,\r
+       element_modification,\r
+       function_arguments,\r
+       argument_list,\r
+       type_prefix,\r
+       algorithm_section,\r
+       subscript,\r
+       subscript_2,\r
+       component_clause,\r
+       component_declaration,\r
+       array_subscripts,\r
+       declaration,\r
+       class_definition,\r
+       array,\r
+       primary,\r
+       component_reference,\r
+       relation,\r
+       simple_expression,\r
+       logical_expression,\r
+       logical_term,\r
+       arithmetic_expression,\r
+       term,\r
+       factor,\r
+       if_expression,\r
+       add_op,\r
+       mul_op,\r
+       factor_op,\r
+       rel_op,\r
+       der_initial,\r
+       output_expression_list,\r
+       extends_clause;\r
+       \r
+       private NodeClass() {\r
+               Parser.nodeNameMap.put(toString(), this);\r
+       }\r
+       \r
+       public static NodeClass of(String name) {\r
+               return Parser.nodeNameMap.get(name);\r
+       }\r
+       \r
+}
\ No newline at end of file
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NotEquals.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NotEquals.java
new file mode 100644 (file)
index 0000000..9a526c3
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class NotEquals implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public NotEquals(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " <> " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               return ((Double)exp1.evaluate(environment)) != ((Double)exp2.evaluate(environment));\r
+       }\r
+\r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new NotEquals(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NullModification.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/NullModification.java
new file mode 100644 (file)
index 0000000..cbafd0d
--- /dev/null
@@ -0,0 +1,32 @@
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class NullModification implements IExpression {\r
+\r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return this;\r
+       }\r
+\r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+       }\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Or.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Or.java
new file mode 100644 (file)
index 0000000..315a78a
--- /dev/null
@@ -0,0 +1,68 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Map;\r
+\r
+public class Or implements IExpression {\r
+       \r
+    public IExpression[] exps;\r
+    \r
+    public Or(ArrayList<IExpression> exps) {\r
+       this.exps = exps.toArray(new IExpression[exps.size()]);\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       StringBuilder b = new StringBuilder();\r
+       b.append(exps[0]);\r
+       for(int i=1;i<exps.length;i++) {\r
+               b.append(" or ");\r
+               b.append(exps[i]);\r
+       }\r
+       return b.toString();\r
+    }\r
\r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               for(IExpression e : exps) \r
+                       if((Boolean)e.evaluate(environment)) return true;\r
+               return false;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               ArrayList<IExpression> ne = new ArrayList<IExpression>();\r
+               for(IExpression e : exps) ne.add(e.withBase(frame, prefix));\r
+               return new Or(ne);\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               for(int i=0;i<exps.length;i++) {\r
+                       exps[i] = exps[i].rewrite(frame, copies);\r
+               }\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               for(IExpression exp : exps) exp.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ParameterDeclaration.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/ParameterDeclaration.java
new file mode 100644 (file)
index 0000000..72cbab5
--- /dev/null
@@ -0,0 +1,57 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+\r
+public class ParameterDeclaration implements IExpression {\r
+\r
+       public Variable variable;\r
+       public IExpression modification;\r
+       public boolean assigned = false;\r
+\r
+       public ParameterDeclaration(Variable variable, IExpression modification) {\r
+               this.variable = variable;\r
+               this.modification = modification;\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               return variable + " = " + modification;\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Parser.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Parser.java
new file mode 100644 (file)
index 0000000..bd6fc87
--- /dev/null
@@ -0,0 +1,648 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland - #4488\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.io.File;\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.utils.FileUtils;\r
+\r
+import fi.semantum.sysdyn.solver.Model.Globals;\r
+import fi.semantum.sysdyn.solver.parser.ModelParser;\r
+import fi.semantum.sysdyn.solver.parser.SimpleNode;\r
+\r
+public class Parser {\r
+       \r
+//     public IFrame currentFrame;\r
+\r
+       private int PRINT = 0;\r
+       \r
+       public Object walk(SimpleNode n, int indent, IFrame model) {\r
+               Object result = walk_(n, indent, model);\r
+               if(PRINT > 0) {\r
+                       for(int i=0;i<indent;i++) System.err.print(" ");\r
+                       System.err.println(n + " " + n.op + " " + result);\r
+               }\r
+               return result;\r
+       }\r
+       \r
+       static Map<String, NodeClass> nodeNameMap = new HashMap<String, NodeClass>();\r
+       \r
+       public Object walk_(SimpleNode n, int indent, IFrame frame) {\r
+\r
+               Model model = frame instanceof Model ? (Model)frame : null;\r
+               \r
+               // TODO: most of this should probably be implemented in the parser\r
+               \r
+               NodeClass nc = NodeClass.of(n.toString());\r
+               \r
+               if (nc == null) {\r
+                       if(n.jjtGetNumChildren() == 1) return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       // not sure if this is ever called\r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               walk((SimpleNode)n.jjtGetChild(i),indent+2, frame);\r
+                       }\r
+                       return null;\r
+               }\r
+               \r
+               switch(nc) {\r
+               case assignment:\r
+                       Object v = (Object)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       IExpression exp = (IExpression)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                       if(v instanceof Derivative) {\r
+                               Derivative der = (Derivative)v;\r
+                               Assignment eq = new Assignment(der.variable, der.variable.subscripts, new Derivate(der.variable, der.variable.subscripts, exp));\r
+                               model.derivatives.add(eq);\r
+                               return eq;\r
+                       } else {\r
+                               Variable var = (Variable)v;\r
+                               Assignment eq = new Assignment(var, var.subscripts, exp);\r
+                               if(model.initial)\r
+                                       model.initials.add(eq);\r
+                               else\r
+                                       model.assignments.add(eq);\r
+                               return eq;\r
+                       }\r
+               case equation_section:\r
+                       if("initial".equals(n.op)) {\r
+                               model.initial = true;\r
+                               for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                                       walk((SimpleNode)n.jjtGetChild(i),indent+2, frame);\r
+                               }\r
+                       } else {\r
+                               model.initial = false;\r
+                               for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                                       walk((SimpleNode)n.jjtGetChild(i),indent+2, frame);\r
+                               }\r
+                       }\r
+                       return null;\r
+               case composition:\r
+                       if(n.jjtGetNumChildren() == 1) return walk((SimpleNode)n.jjtGetChild(0),indent+2, frame);\r
+                       ArrayList<Object> comps = new ArrayList<Object>();\r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               comps.add(walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                       }\r
+                       return comps;\r
+               case for_index:\r
+                       if(frame instanceof Function)\r
+                               return new ForIndex((Function)frame, n.op, (IExpression)walk((SimpleNode)n.jjtGetChild(0),indent+2, frame));\r
+                       else\r
+                               return new ForIndex(null, n.op, (IExpression)walk((SimpleNode)n.jjtGetChild(0),indent+2, frame));\r
+               case for_indices:\r
+                       ArrayList<ForIndex> indices = new ArrayList<ForIndex>();\r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               indices.add((ForIndex)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                       }\r
+                       return indices;\r
+               case for_statement:\r
+                       ArrayList<ForIndex> indices2 = (ArrayList<ForIndex>)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       ArrayList<IStatement> stms = new ArrayList<IStatement>();\r
+                       for(int i=1;i<n.jjtGetNumChildren();i++) {\r
+                               stms.add((IStatement)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                       }\r
+                       return new ForStatement(indices2, new StatementList(stms));\r
+               case if_statement:\r
+                       IExpression condition = (IExpression)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       ArrayList<IStatement> thens = new ArrayList<IStatement>();\r
+                       ArrayList<IStatement> elses = new ArrayList<IStatement>();\r
+                       for(int i=1;i<n.jjtGetNumChildren();i++) {\r
+                               SimpleNode child = (SimpleNode)n.jjtGetChild(i);\r
+                               if("then_statement".equals(child.toString())) thens.add((IStatement)walk(child, indent+2, frame));\r
+                               else if("else_statement".equals(child.toString())) elses.add((IStatement)walk(child, indent+2, frame));\r
+                       }\r
+                       return new IfStatement(condition, new StatementList(thens), new StatementList(elses));\r
+               case while_statement:\r
+                       IExpression expression = (IExpression)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       ArrayList<IStatement> whiles = new ArrayList<IStatement>();\r
+                       for(int i=1;i<n.jjtGetNumChildren();i++) {\r
+                               whiles.add((IStatement)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                       }\r
+                       return new While(expression, new StatementList(whiles));\r
+               case statement:\r
+                       \r
+//                     ( component_reference() ( ":=" expression() | function_call_args() )\r
+//                                     | "(" output_expression_list() ")" ":=" component_reference() function_call_args()\r
+//                                     | "break"\r
+//                                     | "return"\r
+//                                     | if_statement()\r
+//                                     | for_statement()\r
+//                                     | while_statement()\r
+//                                     | when_statement() )\r
+//                             comment() \r
+                       \r
+                       if(n.jjtGetNumChildren() == 1) {\r
+                               return (IStatement)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       } else if (n.jjtGetNumChildren() == 2) {\r
+                               SimpleNode n0 = (SimpleNode)n.jjtGetChild(1);\r
+                               if(n0.toString().equals("expression")) {\r
+                                       Variable variable = (Variable)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                                       IExpression expression2 = (IExpression)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                                       return new Statement(variable, variable.subscripts, expression2);\r
+                               } else if (n0.toString().equals("function_call_args")) {\r
+                                       throw new IllegalStateException();\r
+                               } else {\r
+                                       throw new IllegalStateException();\r
+                               }\r
+                       } else if (n.jjtGetNumChildren() == 3) {\r
+                               ArrayList<Variable> vars = (ArrayList<Variable>)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               Variable fn = (Variable)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                               ArgumentList args = (ArgumentList)walk((SimpleNode)n.jjtGetChild(2), indent+2, frame);\r
+                               return new MultiStatement(vars, fn, args);\r
+                       } else {\r
+                               throw new IllegalStateException();\r
+                       }\r
+               case output_expression_list:\r
+                       ArrayList<Variable> vars = new ArrayList<Variable>();\r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               vars.add((Variable)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                       }\r
+                       return vars;\r
+               case name:\r
+                       return n.op;\r
+               case element_list:\r
+                       ArrayList<Object> elements = new ArrayList<Object>();\r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               elements.add(walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                       }\r
+                       return elements;\r
+               case element:\r
+//                     if("inner".equals(n.op)) {\r
+//                             return null;\r
+//                     } else {\r
+                               return walk((SimpleNode)n.jjtGetChild(0),indent+2, frame);\r
+//                     }\r
+               case element_modification:\r
+                       if(n.jjtGetNumChildren() == 2) {\r
+                               String name = (String)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               IExpression modification = (IExpression)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                               return new Argument(name, modification);\r
+                       }\r
+                       break;\r
+               case function_arguments:\r
+                       //ArgumentList arguments = new ArgumentList(n.op);\r
+                       \r
+                       ArrayList<Argument> arguments = new ArrayList<Argument>();\r
+                       \r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               Object o = walk((SimpleNode)n.jjtGetChild(i),indent+2, frame);\r
+                               if(o instanceof ArgumentList) {\r
+                                       for(Argument a : ((ArgumentList)o).args)\r
+                                               arguments.add(a);\r
+                               } else if (o instanceof IExpression) {\r
+                                       arguments.add(new Argument("", (IExpression)o));\r
+                               } else if (o instanceof ArrayList) {\r
+                                       ArrayList list = (ArrayList)o;\r
+                                       for(Object o2 : list) {\r
+                                               if(o2 instanceof Argument) {\r
+                                                       arguments.add((Argument)o2);\r
+                                               } else if (o2 instanceof ForIndex) {\r
+                                                       ForIndex fi = (ForIndex)o2;\r
+                                                       arguments.add(new Argument(fi.name, fi.expression));\r
+                                               }\r
+                                       }\r
+                               } else {\r
+                                       return null;\r
+                               }\r
+                       }\r
+                       return new ArgumentList(arguments, n.op);\r
+               case argument_list:\r
+                       ArrayList<Argument> args = new ArrayList<Argument>();\r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               args.add((Argument)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                       }\r
+                       return new ArgumentList(args);\r
+               case type_prefix:\r
+                       return n.op;\r
+               case algorithm_section:\r
+                       ArrayList<IStatement> statements = new ArrayList<IStatement>();\r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               statements.add((IStatement)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                       }\r
+                       return new StatementList(statements);\r
+               case subscript:\r
+                       if(n.jjtGetNumChildren() == 0)\r
+                               return new Constant("-1.0");\r
+                       if(n.jjtGetNumChildren() == 1)\r
+                               return walk((SimpleNode)n.jjtGetChild(0),indent+2, frame);\r
+                       throw new IllegalStateException();\r
+               case subscript_2:\r
+                       throw new IllegalStateException();\r
+               case component_clause:\r
+                       String type_prefix = (String)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       String type_specifier = (String)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                       Object third = walk((SimpleNode)n.jjtGetChild(2), indent+2, frame);\r
+                       IExpression[] subscripts = (third instanceof IExpression[])? (IExpression[])third : null;\r
+                       int declarationStart = (third instanceof IExpression[]) ? 3 : 2;\r
+                       ArrayList<Object> clauses = new ArrayList<Object>();\r
+                       for(int i=declarationStart;i<n.jjtGetNumChildren();i++) {\r
+                               \r
+                               Declaration decl = (Declaration)walk((SimpleNode)n.jjtGetChild(i), indent+2, frame);\r
+                               if(subscripts != null)\r
+                                       decl.variable.subscripts = subscripts;\r
+                               \r
+                               if("parameter".equals(type_prefix)) {\r
+                                       \r
+                                       ParameterDeclaration pd = new ParameterDeclaration(decl.variable, (IExpression)decl.modification);\r
+                                       model.parameters.add(pd);\r
+                                       clauses.add(pd);\r
+                                       \r
+                               } else {\r
+                                       \r
+                                       boolean wasClass = model == null ? false : model.instantiateClass(type_specifier, decl, frame);\r
+                                       if(!wasClass) {\r
+                                               \r
+                                               if(decl.modification instanceof ArgumentList) {\r
+                                                       VariableDeclaration vd = new VariableDeclaration(decl.variable, type_prefix, type_specifier, (ArgumentList)decl.modification);\r
+                                                       if(model != null)\r
+                                                               model.addVariable(vd);\r
+                                                       clauses.add(vd);\r
+                                               } else if (decl.modification instanceof IExpression) {\r
+                                                       ArrayList<Argument> as = new ArrayList<Argument>();\r
+                                                       as.add(new Argument("", (IExpression)decl.modification));\r
+                                                       ArgumentList al = new ArgumentList(as);\r
+                                                       VariableDeclaration vd = new VariableDeclaration(decl.variable, type_prefix, type_specifier, al);\r
+                                                       if(model != null)\r
+                                                               model.addVariable(vd);\r
+                                                       clauses.add(vd);\r
+                                               } else  {\r
+                                                       VariableDeclaration vd = new VariableDeclaration(decl.variable, type_prefix, type_specifier, new ArgumentList(new ArrayList<Argument>()));\r
+                                                       if(model != null)\r
+                                                               model.addVariable(vd);\r
+                                                       clauses.add(vd);\r
+                                               }\r
+                                               \r
+                                       }\r
+                                       \r
+                               }\r
+                       }\r
+                       return clauses;\r
+               case component_declaration:\r
+                       return (Declaration)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+               case array_subscripts:\r
+                       IExpression[] subs = new IExpression[n.jjtGetNumChildren()];\r
+                       for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                               subs[i] = (IExpression)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame);\r
+                       }\r
+                       return subs;\r
+               case declaration:\r
+                       if(n.jjtGetNumChildren() == 0) {\r
+                               return new Declaration(new Variable(frame, n.op, null), null);\r
+                       } else if(n.jjtGetNumChildren() == 1) {\r
+                               Object o = walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               if(o instanceof IExpression[]) {\r
+                                       return new Declaration(new Variable(frame, n.op, (IExpression[])o), null);\r
+                               } else {\r
+                                       return new Declaration(new Variable(frame, n.op, null), o);\r
+                               }\r
+                       } else if(n.jjtGetNumChildren() == 2) {\r
+                               IExpression[] subscripts2 = (IExpression[])walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               Object modification = walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                               return new Declaration(new Variable(frame, n.op,subscripts2), modification);\r
+                       } else {\r
+                               StringBuilder b = new StringBuilder();\r
+                               b.append("declaration: ");\r
+                               for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                                       b.append(" " + n.jjtGetChild(i));\r
+                               }\r
+                               return b.toString();\r
+                       }\r
+               case class_definition:\r
+                       if("function".equals(n.op)) {\r
+                               SimpleNode child = (SimpleNode)n.jjtGetChild(0);\r
+                               String functionName = child.op;\r
+                               ArrayList<IStatement> stms2 = new ArrayList<IStatement>();\r
+                               Function function = new Function(functionName, new StatementList(stms2));\r
+                               ArrayList<Object> composition = (ArrayList<Object>)walk(child, indent+2, function);\r
+                               for(int i=1;i<composition.size();i++) {\r
+                                       Object comp = composition.get(i);\r
+                                       if(comp instanceof IStatement) {\r
+                                               stms2.add((IStatement)comp);\r
+                                       } else if(comp instanceof ArrayList) {\r
+                                               ArrayList<Object> declarations = (ArrayList<Object>)composition.get(i);\r
+                                               for(Object os_ : declarations) {\r
+                                                       if(os_ instanceof VariableDeclaration) {\r
+                                                               VariableDeclaration decl = (VariableDeclaration)os_;\r
+                                                               if("input".equals(decl.direction)) function.inputs.add(decl);\r
+                                                               else if ("output".equals(decl.direction)) function.outputs.add(decl);\r
+                                                               else throw new IllegalStateException();\r
+                                                       } else {\r
+                                                               ArrayList<Object> os = (ArrayList<Object>)os_;\r
+                                                               for(Object o : os) {\r
+                                                                       VariableDeclaration decl = (VariableDeclaration)o;\r
+                                                                       function.internals.add(decl);\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                               }\r
+                               ArrayList<Object> declarations = (ArrayList<Object>)composition.get(0);\r
+                               for(Object os_ : declarations) {\r
+                                       if(os_ instanceof VariableDeclaration) {\r
+                                               VariableDeclaration decl = (VariableDeclaration)os_;\r
+                                               if("input".equals(decl.direction)) function.inputs.add(decl);\r
+                                               else if ("output".equals(decl.direction)) function.outputs.add(decl);\r
+                                               else throw new IllegalStateException();\r
+                                       } else {\r
+                                               ArrayList<Object> os = (ArrayList<Object>)os_;\r
+                                               for(Object o : os) {\r
+                                                       VariableDeclaration decl = (VariableDeclaration)o;\r
+                                                       if("input".equals(decl.direction)) function.inputs.add(decl);\r
+                                                       else if ("output".equals(decl.direction)) function.outputs.add(decl);\r
+                                                       else throw new IllegalStateException();\r
+                                               }\r
+                                       }\r
+                               }\r
+                               model.functions.put(functionName, function);\r
+                               return function;\r
+                               \r
+                       } else if("model".equals(n.op)) {\r
+\r
+                               if(n.jjtGetNumChildren() == 1) {\r
+                                       return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               } else {\r
+                                       System.err.println("undefined children for class_definition model");    \r
+                               }\r
+                               return null;\r
+                               \r
+                       } else if("class".equals(n.op)) {\r
+                               \r
+                               SimpleNode specifier = (SimpleNode)n.jjtGetChild(0); \r
+                               Model clazz = new Model(model.globals, specifier.op, false);\r
+                               model.globals.classes.put(specifier.op, clazz);\r
+                               walk(specifier, indent+2, clazz);\r
+                               \r
+                               if(clazz.isEnumClass) {\r
+                                       Variable sizeVariable = new Variable(clazz, "size", null);\r
+                                       Variable elementsVariable = new Variable(clazz, "elements", new IExpression[] { new Constant(""+clazz.variables.size()) });\r
+                                       clazz.parameters.add(new ParameterDeclaration(sizeVariable, sizeVariable.getPossibleConstant()));\r
+                                       clazz.parameters.add(new ParameterDeclaration(elementsVariable, elementsVariable.getPossibleConstant()));\r
+                               }\r
+                               \r
+                               return null;\r
+                               \r
+                       } else {\r
+                               System.err.println("class_definition " + n.op);\r
+                       }\r
+                       break;\r
+               case array:\r
+                       if(n.jjtGetNumChildren() == 1) {\r
+                               ArgumentList al = (ArgumentList)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               if("for".equals(al.op)) {\r
+                                       ForArray array = new ForArray();\r
+                                       array.addElement(al.args[0].modification);\r
+                                       array.addElement(al.args[1]);\r
+                                       return array;\r
+                               } else {\r
+                                       Array array = new Array();\r
+                                       for(Argument arg : al.args) array.addElement(arg.modification);\r
+                                       return array;\r
+                               }\r
+                       }\r
+               case primary:\r
+                       if(n.op != null) {\r
+                               return Utils.parsePrimitive(n.op);\r
+                       } else {\r
+                               return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       }\r
+               case component_reference:\r
+                       if(n.jjtGetNumChildren() == 1) {\r
+                               return Variable.make(frame, n.op, (IExpression[])walk((SimpleNode)n.jjtGetChild(0), indent+2, frame));\r
+                       } else {\r
+                               if ("time".equals(n.op)) {\r
+                                       return new TimeVariable();\r
+                               }\r
+                               return Variable.make(frame, n.op, null);\r
+                       }\r
+               case relation:\r
+                       if(n.jjtGetNumChildren() == 3) {\r
+                               IExpression exp1 = (IExpression)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               String op = (String)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                               IExpression exp2 = (IExpression)walk((SimpleNode)n.jjtGetChild(2), indent+2, frame);\r
+                               String trimmed = op != null ? op.trim() : null;\r
+                               if("<".equals(trimmed)) {\r
+                                       return new LessThan(exp1, exp2);\r
+                               } else if(">".equals(trimmed)) {\r
+                                       return new GreaterThan(exp1, exp2);\r
+                               } else if(">=".equals(trimmed)) {\r
+                                       return new GreaterOrEqualThan(exp1, exp2);\r
+                               } else if("<=".equals(trimmed)) {\r
+                                       return new LessOrEqualThan(exp1, exp2);\r
+                               } else if("==".equals(trimmed)) {\r
+                                       return new Equals(exp1, exp2);\r
+                               } else if("<>".equals(trimmed)) {\r
+                                       return new NotEquals(exp1, exp2);\r
+                               }\r
+                               else return null;\r
+                       } else {\r
+                               return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       }\r
+               case simple_expression:\r
+                       if(n.jjtGetNumChildren() == 1) return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       else if(n.jjtGetNumChildren() == 2) {\r
+                               IExpression start = (IExpression)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame); \r
+                               IExpression end = (IExpression)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                               return new ArraySliceExpression(start, end);\r
+                       } else {\r
+                               throw new UnsupportedOperationException();\r
+                       }\r
+               case logical_expression:\r
+                       if(n.jjtGetNumChildren() > 1) {\r
+                               ArrayList<IExpression> logs = new ArrayList<IExpression>();\r
+                               for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                                       logs.add((IExpression)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                               }\r
+                               return new Or(logs);\r
+                       } else {\r
+                               return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       }\r
+               case logical_term:\r
+                       if(n.jjtGetNumChildren() > 1) {\r
+                               ArrayList<IExpression> terms = new ArrayList<IExpression>();\r
+                               for(int i=0;i<n.jjtGetNumChildren();i++) {\r
+                                       terms.add((IExpression)walk((SimpleNode)n.jjtGetChild(i),indent+2, frame));\r
+                               }\r
+                               return new And(terms);\r
+                       } else {\r
+                               return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       }\r
+               case arithmetic_expression:\r
+               {\r
+                       int i=0;\r
+                       IExpression left;\r
+                       if(n.jjtGetNumChildren() % 2 == 0) {\r
+                               String op = ((String)walk((SimpleNode)n.jjtGetChild(0), indent+2, model)).trim();\r
+                               left = (IExpression)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                               if("-".equals(op)) {\r
+                                       left = new Negation(left);\r
+                               }\r
+                               i=2;\r
+                       } else {\r
+                               left = (IExpression)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               i=1;\r
+                       }\r
+\r
+                       for(;i<n.jjtGetNumChildren();i+=2) {\r
+                               String op = ((String)walk((SimpleNode)n.jjtGetChild(i), indent+2, model)).trim();\r
+                               IExpression exp2 = (IExpression)walk((SimpleNode)n.jjtGetChild(i+1), indent+2, frame);\r
+                               if("+".equals(op)) left = new Addition(left, exp2);\r
+                               else if("-".equals(op)) left = new Subtraction(left, exp2);\r
+                       }\r
+\r
+                       return left;\r
+               }\r
+                       \r
+               case term:\r
+                       if(n.jjtGetNumChildren() > 1) {\r
+                               IExpression term = (IExpression)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               for(int i=1;i<n.jjtGetNumChildren();i+=2) {\r
+                                       String op = ((String)walk((SimpleNode)n.jjtGetChild(i), indent+2, model)).trim();\r
+                                       IExpression exp2 = (IExpression)walk((SimpleNode)n.jjtGetChild(i+1), indent+2, frame);\r
+                                       if("*".equals(op)) term = new Multiplication(term, exp2);\r
+                                       else if(".*".equals(op)) term = new ElementwiseProduct(term, exp2);\r
+                                       else if("./".equals(op)) term = new ElementwiseDivision(term, exp2);\r
+                                       else if("/".equals(op)) term = new Division(term, exp2);\r
+                               }\r
+                               return term;\r
+                       } else {\r
+                               return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       }\r
+               case factor:\r
+                       if(n.jjtGetNumChildren() > 1) {\r
+                               IExpression term = (IExpression)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               for(int i=1;i<n.jjtGetNumChildren();i+=2) {\r
+                                       String op = ((String)walk((SimpleNode)n.jjtGetChild(i), indent+2, model)).trim();\r
+                                       IExpression exp2 = (IExpression)walk((SimpleNode)n.jjtGetChild(i+1), indent+2, frame);\r
+                                       if("^".equals(op)) term = new Power(term, exp2);\r
+                                       else if(".^".equals(op)) term = new ElementwisePower(term, exp2);\r
+                               }\r
+                               return term;\r
+                       } else {\r
+                               return walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       }                       \r
+               case if_expression:\r
+                       if(n.jjtGetNumChildren() == 3) {\r
+                               IExpression exp1 = (IExpression)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               IExpression exp2 = (IExpression)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                               IExpression exp3 = (IExpression)walk((SimpleNode)n.jjtGetChild(2), indent+2, frame);\r
+                               return new IfThenElse(exp1, exp2, exp3);\r
+                       }\r
+               case add_op:\r
+                       return n.op;\r
+               case mul_op:\r
+                       return n.op;\r
+               case factor_op:\r
+                       return n.op;\r
+               case rel_op:\r
+                       return n.op;\r
+               case der_initial:\r
+                       if("der".equals(n.op)) {\r
+                               ArgumentList args2 = (ArgumentList)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               if(args2.args.length == 1) {\r
+                                       return new Derivative((Variable)args2.args[0].modification);\r
+                               }\r
+                       } else if("initial".equals(n.op)) {\r
+                               return new Application("initial", new ArgumentList(""));\r
+                       } else if("application".equals(n.op)) {\r
+                               String name = (String)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                               ArgumentList args2 = (ArgumentList)walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                               return new Application(name, args2);\r
+                       }\r
+               case extends_clause:\r
+                       String extendsName = (String)walk((SimpleNode)n.jjtGetChild(0), indent+2, frame);\r
+                       walk((SimpleNode)n.jjtGetChild(1), indent+2, frame);\r
+                       model.isEnumClass = extendsName.equals("Enumeration_class");\r
+                       return null;\r
+               }\r
+                       \r
+               System.err.println("fall-through " + n);\r
+               \r
+               // should not get this far\r
+               return null;\r
+       }\r
+       \r
+       public static final boolean WAIT = false;\r
+       \r
+       public static void main(String[] args) throws Exception {\r
+               \r
+               if(WAIT) {\r
+                       for(int i=0;i<1e12;i++) {\r
+                               int k = System.in.read();\r
+                               if(k==13) break;\r
+                               Thread.sleep(10);\r
+                       }\r
+               }\r
+               \r
+//             NodeCache cache = new NodeCache();\r
+//\r
+////           long start = System.nanoTime();\r
+//\r
+//             File f = new File("C:/Users/Antti Villberg/Downloads/isomalli.txt");\r
+//             String contents = FileUtils.getContents(f);\r
+//             LineReader reader = new LineReader(contents, cache);\r
+//             reader.parse();\r
+//\r
+////           long duration = System.nanoTime()-start;\r
+////           System.err.println("complete parse file in " + 1e-9*duration + "s.");\r
+//\r
+////           start = System.nanoTime();\r
+//\r
+//             if(WAIT) {\r
+//                     for(int i=0;i<1e12;i++) {\r
+//                             int k = System.in.read();\r
+//                             if(k==13) break;\r
+//                             Thread.sleep(10);\r
+//                     }\r
+//             }\r
+\r
+               \r
+\r
+               \r
+               File f1 = new File("d:/sysdynfn.txt");\r
+               String contents1 = FileUtils.getContents(f1);\r
+               File f2 = new File("d:/sysdyntest.txt");\r
+               String contents2 = contents1 + FileUtils.getContents(f2);\r
+               \r
+               StringReader reader = new StringReader(contents2);\r
+               ModelParser modelParser = new ModelParser(reader);\r
+               SimpleNode n = (SimpleNode)modelParser.stored_definition();\r
+           Parser parser = new Parser();\r
+           Model m = new Model(new Globals(), "", false);\r
+               parser.walk(n, 0, m);\r
+               \r
+               m.prettyPrint();\r
+               \r
+               Solver solver = new Solver();\r
+               solver.prepare(contents2);\r
+               \r
+//\r
+//             if(WAIT) {\r
+//                     for(int i=0;i<1e12;i++) {\r
+//                             int k = System.in.read();\r
+//                             if(k==13) break;\r
+//                             Thread.sleep(10);\r
+//                     }\r
+//             }\r
+//\r
+//             long start = System.nanoTime();\r
+               for(int i=0;i<50;i++) {\r
+                       solver.step();\r
+                       solver.printEnvironment();\r
+               }\r
+//             long duration = System.nanoTime()-start;\r
+//             System.err.println("stepped simulation in " + 1e-9*duration + "s.");\r
+               \r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Power.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Power.java
new file mode 100644 (file)
index 0000000..aa98c9e
--- /dev/null
@@ -0,0 +1,72 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Power implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public Power(IExpression exp1, IExpression exp2) {\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " ^ " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Object left = exp1.evaluate(environment);\r
+               Object right = exp2.evaluate(environment);\r
+               if(left instanceof Double && right instanceof Double) {\r
+                       return Math.pow(((Double)left),((Double)right));\r
+               } \r
+               else if(left instanceof Array && right instanceof Array) {\r
+                       Array la = (Array)left;\r
+                       Array ra = (Array)right;\r
+                       return la.pow(ra);\r
+               }\r
+               else if (left instanceof Array && right instanceof Double) return ((Array)left).pow((Double)right);\r
+               else if (left instanceof Double && right instanceof Array) return ((Array)right).pow((Double)left);\r
+               throw new IllegalStateException();\r
+               \r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Power(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Solver.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Solver.java
new file mode 100644 (file)
index 0000000..b65afaf
--- /dev/null
@@ -0,0 +1,312 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland - #4488\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.Comparator;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.utils.datastructures.MapList;\r
+\r
+import fi.semantum.sysdyn.solver.IExpression.ExpressionVisitor;\r
+import fi.semantum.sysdyn.solver.Model.Globals;\r
+import fi.semantum.sysdyn.solver.parser.ModelParser;\r
+import fi.semantum.sysdyn.solver.parser.SimpleNode;\r
+\r
+public class Solver {\r
+\r
+       private static final boolean PRINT_EXCEPTIONS = false;  \r
+       private static final int STACK_SIZE = 1000;\r
+\r
+       private Model model;\r
+       private Environment env;\r
+\r
+       private Object[] newValues;\r
+       private Object[] derivatives;\r
+       \r
+       private double defaultStep;\r
+       private double start;\r
+       private NodeCache cache;\r
+       private boolean ready;\r
+       \r
+       public Solver() {\r
+               defaultStep = 0.1;\r
+               start = 0;\r
+               // is it okay to store the cache with the solver instance?\r
+               cache = new NodeCache();\r
+               ready = false;\r
+       }\r
+       \r
+       public void setStep(double step) {\r
+               this.defaultStep = step;\r
+               if(env != null) env.step = step;\r
+       }\r
+       \r
+       public void setStart(double start) {\r
+               this.start = start;\r
+               ready = false;\r
+       }\r
+       \r
+       private void sortAssignments() {\r
+\r
+               final MapList<String,Assignment> asses = new MapList<String,Assignment>();\r
+               for(Assignment ass : model.assignments) asses.add(ass.target.base.name, ass);\r
+               \r
+               final List<VariableBase> found = new ArrayList<VariableBase>();\r
+               final Set<String> visited = new HashSet<String>();\r
+\r
+               ExpressionVisitor sortVisitor = new ExpressionVisitor() {\r
+                       @Override\r
+                       public void visit(IExpression expression) {\r
+                               if(expression instanceof Variable) {\r
+                                       Variable var = (Variable)expression;\r
+                                       if(visited.add(var.base.name)) {\r
+                                               for(Assignment ass : asses.getValues(var.base.name)) {\r
+                                                       ass.expression.accept(this);\r
+                                                       if(ass.subscripts != null)\r
+                                                               for(IExpression e : ass.subscripts) e.accept(this);\r
+                                               }\r
+                                               found.add(var.base);\r
+                                       }\r
+                               }\r
+                       }\r
+               };\r
+               \r
+               // Sort assignments\r
+               for(Assignment ass : model.assignments) {\r
+                       ass.target.accept(sortVisitor);\r
+               }\r
+\r
+               Collections.sort(model.assignments, new Comparator<Assignment>() {\r
+\r
+                       @Override\r
+                       public int compare(Assignment o1, Assignment o2) {\r
+                               int i1 = found.indexOf(o1.target.base); \r
+                               int i2 = found.indexOf(o2.target.base);\r
+                               if(i1 < i2) return -1;\r
+                               else if (i1 > i2) return 1;\r
+                               return 0;\r
+                       }\r
+\r
+                       \r
+               });\r
+               \r
+       }\r
+       \r
+       public void prepare(String input) throws Exception {\r
+               \r
+               long startNanos = System.nanoTime();\r
+               \r
+//             LineReader reader = new LineReader(input, cache);\r
+//             reader.parse();\r
+//             \r
+//             model = reader.model;\r
+               \r
+               StringReader reader = new StringReader(input);\r
+               ModelParser modelParser = new ModelParser(reader);\r
+               SimpleNode n = (SimpleNode)modelParser.stored_definition();\r
+           Parser parser = new Parser();\r
+           model = new Model(new Globals(), "", false);\r
+               parser.walk(n, 0, model);\r
+               \r
+               env = new Environment(model, defaultStep, start);\r
+               \r
+               int size = model.prepare();\r
+               env.setSize(size);\r
+               \r
+               for(Fn fn : model.functions.values()) {\r
+                       if(fn instanceof Function)\r
+                               ((Function)fn).prepare();\r
+               }\r
+               \r
+               env.valueTable = new Object[size+STACK_SIZE];\r
+               \r
+               sortAssignments();\r
+               \r
+               model.assignmentArray = model.assignments.toArray(new Assignment[model.assignments.size()]);\r
+               model.derivativeArray = model.derivatives.toArray(new Assignment[model.derivatives.size()]);\r
+               model.parameterArray = model.parameters.toArray(new ParameterDeclaration[model.parameters.size()]);\r
+               \r
+               newValues = new Object[Math.max(model.assignments.size(),model.derivatives.size())];\r
+               derivatives = new Object[model.derivatives.size()];\r
+               \r
+               int condition = 1;\r
+               int loops = 0;\r
+               \r
+               while(condition > 0 && loops++ < 50) {\r
+\r
+                       if(PRINT_EXCEPTIONS) {\r
+                               System.err.println("== LOOP " + loops + " ==");\r
+                       }\r
+                       \r
+                       condition = 0;\r
+\r
+                       for(ParameterDeclaration pd : model.parameters) {\r
+                               try {\r
+                                       if(!pd.assigned) {\r
+                                               pd.variable.assign(env, null, pd.modification.evaluate(env));\r
+                                               pd.assigned = true;\r
+                                       }\r
+                               } catch (Exception e) {\r
+                                       condition++;\r
+                                       if(PRINT_EXCEPTIONS) {\r
+                                               e.printStackTrace();\r
+                                               System.err.println("failed to assign " + pd.variable.toString());\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       ArrayList<Assignment> assignments = new ArrayList<Assignment>();\r
+                       assignments.addAll(model.assignments);\r
+                       assignments.addAll(model.initials);\r
+\r
+                       for(VariableDeclaration vd : model.variables) {\r
+                               try {\r
+                                       if(!vd.assigned) {\r
+                                               for(Argument arg : vd.modification.args) {\r
+                                                       if(arg.name.endsWith("start")) {\r
+                                                               Object value = arg.modification.evaluate(env);\r
+                                                               if(vd.variable.base.dimension() == 1) {\r
+                                                                       vd.variable.assign(env, null, value);\r
+                                                               } else {\r
+                                                                       if(value instanceof Double) {\r
+                                                                               Array array = new Array();\r
+                                                                               for(int i=0;i<vd.variable.base.dimension();i++) array.addElement(value);\r
+                                                                               vd.variable.assign(env, null, array);\r
+                                                                       } else {\r
+                                                                               throw new IllegalStateException();\r
+                                                                       }\r
+                                                               }\r
+                                                               // make sure the variable is not initialized \r
+                                                               // twice, this is probably not the most \r
+                                                               // efficient way\r
+                                                               for (Assignment a : assignments) {\r
+                                                                       if (vd.variable.base.equals(a.target.base)) {\r
+                                                                               a.assigned = true;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                               } catch (Exception e) {\r
+                                       condition++;\r
+                                       if(PRINT_EXCEPTIONS) {\r
+                                               e.printStackTrace();\r
+                                               System.err.println("failed to assign " + vd.variable.toString());\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       for(Assignment ass : assignments) {\r
+                               try {\r
+                                       if(!ass.assigned) {\r
+                                               Object value = ass.expression.evaluate(env);\r
+                                               if(value != null) {\r
+                                                       ass.target.assign(env, ass.subscripts, value);\r
+                                                       ass.assigned = true;\r
+                                               }\r
+                                       }\r
+                               } catch (Exception e) {\r
+                                       condition++;\r
+                                       if(PRINT_EXCEPTIONS) {\r
+                                               e.printStackTrace();\r
+                                               System.err.println("failed to assign " + ass.target.toString());\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               for(Assignment ass : model.assignments) {\r
+                       if(ass.expression instanceof Constant)\r
+                               ass.isConstant = true;\r
+               }\r
+               \r
+               env.initial = false;\r
+               \r
+               ready = true;\r
+               \r
+               long endNanos = System.nanoTime();\r
+               \r
+               System.err.println("Prepared model in " + 1e-6*(endNanos-startNanos) + "ms.");\r
+               \r
+       }\r
+       \r
+       public String[] keys() {\r
+               return env.getValueKeyArray();\r
+       }\r
+       \r
+       public double[] values() {\r
+               return env.getValueArray();\r
+       }\r
+       \r
+       public void step() {\r
+               \r
+//             printEnvironment();\r
+//             \r
+//             new Exception().printStackTrace();\r
+\r
+               // TODO: do something more sensible if the solver is not ready\r
+               if (!ready) return;\r
+               \r
+               Assignment[] assignments = model.assignmentArray;\r
+               Assignment[] derivatives = model.derivativeArray;\r
+               \r
+               // first we evaluate, integrate and assign derivatives at previous time step\r
+               for(int i=0;i<model.derivatives.size();i++) {\r
+                       newValues[i] = derivatives[i].expression.evaluate(env);\r
+               }\r
+               for(int i=0;i<model.derivatives.size();i++) {\r
+                       derivatives[i].target.assign(env, derivatives[i].subscripts, newValues[i]);\r
+               }\r
+\r
+               // Increment time\r
+               // should probably be wrapped inside a method or something\r
+               env.time += env.step;\r
+               \r
+               VariableBase base = model.names.get("time");\r
+               if(base != null) {\r
+                       env.put(base.index, env.time);\r
+               }\r
+               \r
+               // Next solve algebraic equations\r
+               for(int i=0;i<assignments.length;i++) {\r
+                       if(assignments[i].isConstant) continue;\r
+                       Object value = assignments[i].expression.evaluate(env);\r
+                       assignments[i].target.assign(env, assignments[i].subscripts, value);\r
+               }\r
+\r
+       }\r
+       \r
+       // TODO: implement some on the fly parameter change stuff for different experiment types\r
+       \r
+       public void printEnvironment() {\r
+               String[] keys = keys();\r
+               double[] values = values();\r
+               System.err.println("Environment " + keys.length + " " + values.length);\r
+               for(int i=0;i<keys.length;i++) {\r
+                       System.err.println(keys[i] + " = " + values[i]);\r
+               }\r
+       }\r
+       \r
+       public double getTime() {\r
+               return env.time;\r
+       }\r
+       \r
+       public void setValue(String key, double value) {\r
+               env.setValue(key, value);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/SolverUtils.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/SolverUtils.java
new file mode 100644 (file)
index 0000000..05534e4
--- /dev/null
@@ -0,0 +1,68 @@
+package fi.semantum.sysdyn.solver;\r
+\r
+public class SolverUtils {\r
+\r
+       public static class Slice {\r
+               public static final Slice FULL = new Slice(-2,-1);\r
+               public int start;\r
+               public int end;\r
+               public Slice(int start, int end) {\r
+                       this.start = start;\r
+                       this.end = end;\r
+               }\r
+       }\r
+       \r
+       public static boolean isFullSubscript(IExpression[] subscripts) {\r
+               if(subscripts == null) return true;\r
+               for(int i=0;i<subscripts.length;i++) {\r
+                       if(subscripts[i] instanceof Constant) {\r
+                               Constant c = (Constant)subscripts[i];\r
+                               if(c.value instanceof Double) {\r
+                                       Double d = (Double)c.value;\r
+                                       if(d == -1.0) continue;\r
+                               }\r
+                       }\r
+                       return false;\r
+               }\r
+               return true;\r
+       }\r
+       \r
+       public static boolean isArray(int[] dimensions) {\r
+               return dimensions != null && dimensions != VariableBase.UNINIT;\r
+       }\r
+       \r
+       public static Array[] parseSubscripts(IEnvironment env, IExpression[] subscripts) {\r
+               Array[] result = new Array[subscripts.length];\r
+               for(int i=0;i<subscripts.length;i++) {\r
+                       IExpression e = subscripts[i];\r
+                       if(e instanceof ArraySliceExpression) {\r
+                               ArraySliceExpression ase = (ArraySliceExpression)e;\r
+                               Double start = (Double)ase.start.evaluate(env);\r
+                               Double end = (Double)ase.end.evaluate(env);\r
+                               result[i] = Array.slice(start.intValue()-1, end.intValue()-1);\r
+                       } else if (e instanceof Array) {\r
+                               Array array = (Array)e;\r
+                               Array r = new Array();\r
+                               for(Object o : array.elements()) {\r
+                                       Double d = (Double)o;\r
+                                       r.addElement(d-1);\r
+                               }\r
+                               result[i] = r;\r
+                       } else {\r
+                               Double v = (Double)e.evaluate(env);\r
+                               int index = v.intValue()-1;\r
+                               if(index == -2) result[i] = Array.FULL;\r
+                               else result[i] = Array.singleton(index);\r
+                       }\r
+               }\r
+               return result;\r
+       }\r
+       \r
+       public static boolean isSlice(Array[] subs) {\r
+               for(Array s : subs) {\r
+                       if(s.dimension() != 1) return true;\r
+               }\r
+               return false;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Statement.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Statement.java
new file mode 100644 (file)
index 0000000..a3dcd40
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public class Statement implements IStatement {\r
+       \r
+       public Variable target;\r
+       public IExpression[] subscripts;\r
+    public IExpression expression;\r
+    \r
+    public Statement(Variable target, IExpression[] subscripts, IExpression expression) {\r
+       this.target = target;\r
+       this.subscripts = subscripts;\r
+       this.expression = expression;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return target + " := " + expression;\r
+    }\r
+    \r
+    @Override\r
+    public void evaluate(IEnvironment environment) {\r
+               Object value = expression.evaluate(environment);\r
+               target.assign(environment, subscripts, value);\r
+    }\r
+    \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/StatementList.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/StatementList.java
new file mode 100644 (file)
index 0000000..b8c17f8
--- /dev/null
@@ -0,0 +1,33 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class StatementList implements IStatement {\r
+       \r
+       public ArrayList<IStatement> statements;\r
+    \r
+    public StatementList(ArrayList<IStatement> statements) {\r
+       this.statements = statements;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return statements.toString();\r
+    }\r
+    \r
+    @Override\r
+    public void evaluate(IEnvironment environment) {\r
+       for(IStatement stm : statements) stm.evaluate(environment);\r
+    }\r
+    \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Subtraction.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Subtraction.java
new file mode 100644 (file)
index 0000000..7534d1f
--- /dev/null
@@ -0,0 +1,63 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class Subtraction implements IExpression {\r
+       \r
+    public IExpression exp1;\r
+    public IExpression exp2;\r
+    \r
+    public Subtraction(IExpression exp1, IExpression exp2) {\r
+       if(exp1 == null) exp1 = new Constant("0");\r
+       this.exp1 = exp1;\r
+       this.exp2 = exp2;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return exp1 + " - " + exp2;\r
+    }\r
+    \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               Double d1 = (Double)exp1.evaluate(environment);\r
+               Double d2 = (Double)exp2.evaluate(environment);\r
+               if(d1 == null || d2 == null) return null;\r
+               return d1-d2;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return new Subtraction(exp1.withBase(frame, prefix), exp2.withBase(frame, prefix));\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+    \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               exp1 = exp1.rewrite(frame, copies);\r
+               exp2 = exp2.rewrite(frame, copies);\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+               exp1.accept(visitor);\r
+               exp2.accept(visitor);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/TimeVariable.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/TimeVariable.java
new file mode 100644 (file)
index 0000000..509824b
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 VTT Technical Research Centre of Finland.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+public class TimeVariable implements IExpression {\r
+\r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               // possibly a bit ugly\r
+               return environment.getSystem().time();\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               return "time";\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               return this;\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               return this;\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/UnassignedVariableException.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/UnassignedVariableException.java
new file mode 100644 (file)
index 0000000..d9d827f
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public class UnassignedVariableException extends RuntimeException {\r
+\r
+       private static final long serialVersionUID = -4515223797912269515L;\r
+\r
+       public UnassignedVariableException(String message) {\r
+               super(message);\r
+       }\r
+       \r
+       @Override\r
+       public synchronized Throwable fillInStackTrace() {\r
+               return null;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Utils.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Utils.java
new file mode 100644 (file)
index 0000000..70508e4
--- /dev/null
@@ -0,0 +1,29 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public class Utils {\r
+\r
+       public static int getIndex(Object value) {\r
+               if(value instanceof Double) {\r
+                       return ((Double)value).intValue()-1;\r
+               } else if (value instanceof Constant) {\r
+                       return getIndex(((Constant)value).value);\r
+               } else {\r
+                       throw new IllegalStateException();\r
+               }\r
+       }\r
+\r
+       public static Object parsePrimitive(String value) {\r
+               return new Constant(value);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Variable.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Variable.java
new file mode 100644 (file)
index 0000000..9335f68
--- /dev/null
@@ -0,0 +1,259 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland - #4488\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+\r
+\r
+public class Variable implements IExpression {\r
+\r
+       public VariableBase base;\r
+       public IExpression[] subscripts = null;\r
+       \r
+       public Variable(IFrame frame, String name, IExpression[] subscripts) {\r
+               base = frame.getBase(name);\r
+               this.subscripts = subscripts;\r
+       }\r
+       \r
+       public static Object make(IFrame frame, String name, IExpression[] subscripts) {\r
+//             Array enumElements = enumerationElements(frame, name);\r
+//             if(enumElements != null) return enumElements;\r
+//             Constant enumSize = enumerationSize(frame, name);\r
+//             if(enumSize != null) return enumSize;\r
+               return new Variable(frame, name, subscripts);\r
+       }\r
+       \r
+       public Variable(VariableBase base) {\r
+               this.base = base;\r
+       }\r
+\r
+       public Variable(VariableBase base, IExpression[] subscripts) {\r
+               this.base = base;\r
+               this.subscripts = subscripts;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               // updated to print the double value as an integer value in subscripts\r
+               // to make the string representation of the variable directly usable \r
+               // as the variable identifier in results\r
+               return base.name + subscriptString();\r
+               //return base.name + (subscripts != null ? Arrays.toString(subscripts) : "");\r
+       }\r
+       \r
+       // not sure if this is the correct format, verify for multidimensional \r
+       // (> 2) variables\r
+       private String subscriptString() {\r
+               if (subscripts == null || subscripts.length < 1) {\r
+                       return "";\r
+               }\r
+               \r
+               StringBuilder str = new StringBuilder();\r
+               str.append('[');\r
+               for (int i = 0; i < subscripts.length; i++) {\r
+                       if (i > 0) {\r
+                               str.append(", ");\r
+                       }\r
+                       // is the expression inside subscript always a constant?\r
+                       Object sub = subscripts[i];\r
+                       if(sub instanceof Constant) {\r
+                               str.append(((Double)((Constant)sub).value).intValue());\r
+                       } else if (sub instanceof Variable) {\r
+                               str.append(((Variable)sub).base.name);\r
+                       }\r
+               }\r
+               str.append(']');\r
+               return str.toString();\r
+       }\r
+       \r
+       public int assignArray(IEnvironment env, int index, Array value, int asd) {\r
+               for(int i=0;i<value.elements().size();i++) {\r
+                       Object element = value.element(i);\r
+                       if(element instanceof Double) {\r
+                               env.put(index+asd++, (Double)element);\r
+                       } else if(element instanceof Constant) {\r
+                               Constant c = (Constant)element;\r
+                               env.put(index+asd++, (Double)c.value);\r
+                       } else if(element instanceof Array) {\r
+                               asd = assignArray(env, index, (Array)element, asd);\r
+                       } else {\r
+                               throw new UnsupportedOperationException();\r
+                       }\r
+               }\r
+               return asd;\r
+       }\r
+       \r
+       public void setArrayIndex(IEnvironment environment, Array array, Object value) {\r
+               \r
+               for(int i=0;i<subscripts.length-1;i++) {\r
+                       IExpression e = subscripts[i];\r
+                       int index = Utils.getIndex(e.evaluate(environment));\r
+                       array.ensureIndex(index, true);\r
+                       array = (Array)array.element(index);\r
+               }\r
+\r
+               IExpression e = subscripts[subscripts.length-1];\r
+               int index = Utils.getIndex(e.evaluate(environment));\r
+               array.ensureIndex(index, false);\r
+               if(value instanceof IExpression) {\r
+                       IExpression exp = (IExpression)value;\r
+                       array.setElement(index, exp.evaluate(environment));\r
+               } else {\r
+                       array.setElement(index, value);\r
+               }\r
+               \r
+               \r
+       }\r
+       \r
+       public void assignPlain(IEnvironment env, Object value) {\r
+               env.put(base.index, value);\r
+       }\r
+       \r
+       private void validateSize(IEnvironment env, IExpression[] subscripts, Object value) {\r
+               \r
+               if(value == null) return;\r
+               \r
+               if(base.isStoredAsArray()) return;\r
+               \r
+               int fullDimension = base.dimension();\r
+               if(fullDimension == 1) {\r
+                       if(!(value instanceof Double)) {\r
+                               Array arr = (Array)value;\r
+                               if(arr.size(0) != 1)\r
+                                       throw new IllegalStateException();\r
+                       }\r
+               } else {\r
+                       if(subscripts == null) {\r
+                               if(base.dimensions.length == this.subscripts.length && value instanceof Double) \r
+                                       return;\r
+                               if(!(value instanceof Array))\r
+                                       throw new IllegalStateException();\r
+                               Array arr = (Array)value;\r
+                               int arrDim = arr.dimension();\r
+                               if(arrDim != fullDimension)\r
+                                       throw new IllegalStateException();\r
+                       } else {\r
+                               if(value instanceof Array) {\r
+                                       Array arr = (Array)value;\r
+                                       if(!arr.validateDimensions(base.dimensions, 0))\r
+                                               throw new IllegalStateException();\r
+                               } else {\r
+                                       if(base.dimensions.length == subscripts.length) {\r
+                                               if(value instanceof Double) return;\r
+                                       }\r
+                                       throw new IllegalStateException();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               \r
+       }\r
+       \r
+       public void assign(IEnvironment env, IExpression[] subscripts, Object value) {\r
+               \r
+               validateSize(env, subscripts, value);\r
+               \r
+               if(value instanceof Array) {\r
+                       if(base.isStoredAsArray()) {\r
+                               env.put(base.index(env, subscripts), value);\r
+                       } else {\r
+                               assignArray(env, base.index(env, subscripts), (Array)value, 0);\r
+                       }\r
+               } else {\r
+                       if(base.isStoredAsArray()) {\r
+                               Object _existing = env.getValue(base.index);\r
+                               Array existing = (Array)_existing;\r
+                               if(existing == null) {\r
+                                       existing = new Array();\r
+                                       env.put(base.index, existing);\r
+                               }\r
+                               setArrayIndex(env, existing, value);\r
+                       } else {\r
+                               env.put(base.index(env, subscripts), value);\r
+                       }\r
+               }\r
+       }\r
+       \r
+       // -2 == undefined\r
+       // -1 == not constant\r
+       public int constantIndex = -2;\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               \r
+               if(constantIndex == -2) constantIndex = base.getConstantIndex(environment, subscripts);\r
+               \r
+               return base.evaluate(environment, subscripts, constantIndex);\r
+               \r
+       }\r
+\r
+       \r
+//     static Array enumerationElements(IFrame frame, String name) {\r
+//             if(!name.endsWith(".elements")) return null;\r
+//             String prefix = name.replace(".elements", "");\r
+//             Model m = frame.getClass(prefix + "_class");\r
+//             if(m == null) return null;\r
+//             Array result = new Array();\r
+//             for(VariableDeclaration vd : m.variables) {\r
+//                     Constant c = (Constant)vd.modification.args.get(0).modification;\r
+//                     result.addElement(c.value);\r
+//             }\r
+//             return result;\r
+//     }\r
+//     \r
+//     static Constant enumerationSize(IFrame frame, String name) {\r
+//             if(!name.endsWith(".size")) return null;\r
+//             String prefix = name.replace(".size", "");\r
+//             Model m = frame.getClass(prefix + "_class");\r
+//             if(m == null) return null;\r
+//             return new Constant("" + m.variables.size());\r
+//     }\r
+\r
+       public Variable withBase(IFrame frame, String prefix) {\r
+               \r
+               if(subscripts != null) {\r
+                       IExpression[] subscripts2 = new IExpression[subscripts.length];\r
+                       for(int i=0;i<subscripts.length;i++)\r
+                               subscripts2[i] = subscripts[i].withBase(frame, prefix);\r
+                       return new Variable(frame.getBase(base, prefix), subscripts2);\r
+               } else {\r
+                       return new Variable(frame.getBase(base, prefix), null);\r
+               }\r
+       }\r
+    \r
+       @Override\r
+       public IExpression getPossibleConstant() {\r
+               return base.getPossibleConstant();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               VariableBase copy = copies.get(base.name);\r
+               if(copy == null) {\r
+                       if(subscripts != null) {\r
+                               for(int i=0;i<subscripts.length;i++)\r
+                                       subscripts[i] = subscripts[i].rewrite(frame, copies);\r
+                       }\r
+                       return this;\r
+               }\r
+\r
+               return new Variable(frame.getBase(copy.name), subscripts).rewrite(frame, copies);\r
+               \r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               visitor.visit(this);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/VariableBase.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/VariableBase.java
new file mode 100644 (file)
index 0000000..842cb93
--- /dev/null
@@ -0,0 +1,263 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+\r
+public class VariableBase {\r
+\r
+       static final int[] UNINIT = new int[0];\r
+       \r
+       public String name;\r
+       public int index;\r
+       public int[] dimensions = UNINIT;\r
+       public VariableBase(String name) {\r
+               this.name = name;\r
+       }\r
+       public VariableBase(String name, int index) {\r
+               this.name = name;\r
+               this.index = index;\r
+       }\r
+       public VariableBase(String name, int index, int[] dimensions) {\r
+               this.name = name;\r
+               this.index = index;\r
+               this.dimensions = dimensions;\r
+       }\r
+       public boolean tellSubscripts(IExpression[] e, IExpression modification) {\r
+               \r
+               if(dimensions != UNINIT) return true;\r
+               \r
+               if(e != null) {\r
+                       \r
+                       if(dimensions == UNINIT) \r
+                               dimensions = new int[e.length];\r
+                       \r
+                       if(e.length == 0)\r
+                               throw new IllegalStateException();\r
+                       \r
+                       for(int i=0;i<e.length;i++) {\r
+                               \r
+                               IExpression exp = e[i];\r
+                               Object constant = exp.getPossibleConstant();\r
+                               if(constant != null) exp = (IExpression)constant;\r
+                               \r
+                               if(!(exp instanceof Constant)) {\r
+                                       dimensions[i] = -1;\r
+                               } else {\r
+                                       Constant c = (Constant)exp;\r
+                                       int index = ((Double)c.value).intValue();\r
+                                       if(index == -1) {\r
+                                               if(modification instanceof Array) {\r
+                                                       Array array = (Array)modification;\r
+                                                       dimensions[i] = array.size(i);\r
+                                               } else {\r
+                                                       dimensions[i] = -1;\r
+                                               }\r
+                                       }\r
+                                       else if(index > dimensions[i]) dimensions[i] = index;\r
+                               }\r
+                       }\r
+                       \r
+               } else {\r
+                       \r
+                       dimensions = null;\r
+                       \r
+               }\r
+               \r
+               return dimensions != UNINIT;\r
+               \r
+       }\r
+       public int dimension() {\r
+               if(dimensions == null) return 1;\r
+               int result = 1;\r
+               for(int d : dimensions) result *= d;\r
+               return result;\r
+       }\r
+       public boolean isStoredAsArray() {\r
+               if(dimensions == null) return false;\r
+               for(int d : dimensions) if(d == -1) return true;\r
+               return false;\r
+       }\r
+       \r
+       VariableBase withBase(String prefix) {\r
+               return new VariableBase(prefix+name, index, dimensions);\r
+       }\r
+\r
+       private int makeSubscriptIndex(IEnvironment env, IExpression[] subscripts) {\r
+               if(dimensions == null) return 0;\r
+               int result = 0;\r
+               for(int i=0;i<subscripts.length;i++) {\r
+                       int factor = 1;\r
+                       for(int j=i+1;j<subscripts.length;j++) factor *= dimensions[j];\r
+                       IExpression e = subscripts[i];\r
+                       Double v = (Double)e.evaluate(env);\r
+                       int index = v.intValue()-1;\r
+                       if(index == -2) return 0;\r
+                       result += factor*index;\r
+               }\r
+               if(result == -1) throw new IllegalStateException();\r
+               return result;\r
+       }\r
+       \r
+       public int subscriptIndex(IEnvironment env, IExpression[] subscripts) {\r
+               if(subscripts == null) return 0;\r
+               return makeSubscriptIndex(env, subscripts);\r
+       }\r
+       \r
+       public int index(IEnvironment env, IExpression[] subscripts) {\r
+               return index + subscriptIndex(env, subscripts);\r
+       }\r
+       \r
+       public Object getArrayIndex(IEnvironment environment, IExpression[] subscripts, Array array) {\r
+               Object result = array;\r
+               for(IExpression e : subscripts) {\r
+                       int index = Utils.getIndex(e.evaluate(environment));\r
+                       result = ((Array)result).element(index);\r
+               }\r
+               if(result instanceof IExpression) {\r
+                       IExpression exp = (IExpression)result;\r
+                       return exp.evaluate(environment);\r
+               }\r
+               if(result instanceof Array)\r
+                       throw new IllegalStateException();\r
+               return result;\r
+       }\r
+       \r
+       private boolean hasScalarSubscript(IExpression[] subscripts) {\r
+               if(subscripts == null) return false;\r
+               else return true;\r
+       }\r
+       \r
+       public int intoArray(IEnvironment env, int index, int d, Array target) {\r
+\r
+               if(d == dimensions.length-1) {\r
+                       for(int i=0;i<dimensions[d];i++) {\r
+                               Object value = env.getValue(index);\r
+                               if(value == null) {\r
+                                       throw new UnassignedVariableException("No value for " + name);\r
+                               }\r
+                               target.addElement(value);\r
+                               index++;\r
+                       }\r
+                       return index;\r
+               }\r
+               \r
+               for(int i=0;i<dimensions[d];i++) {\r
+                       Array array = new Array();\r
+                       index = intoArray(env, index, d+1, array);\r
+                       target.addElement(array);\r
+               }\r
+               \r
+               return index;\r
+               \r
+       }\r
+       \r
+       public int getConstantIndex(IEnvironment environment, IExpression[] subscripts) {\r
+\r
+               if(isStoredAsArray()) {\r
+                       return -1;\r
+               } else {\r
+                       \r
+                       if(dimension() > 1) {\r
+                               \r
+                               if(subscripts != null) {\r
+                                       \r
+                                       Array[] sub = SolverUtils.parseSubscripts(environment, subscripts);\r
+                                       if(!SolverUtils.isSlice(sub) && areSubscriptsConstant(subscripts)) return index(environment, subscripts);\r
+                                       \r
+                               }\r
+                               \r
+                               return -1;\r
+                               \r
+                       }\r
+                       \r
+                       Object result = environment.getNamedValue(name);\r
+                       if(result != null) return -1;\r
+                       \r
+                       if(!areSubscriptsConstant(subscripts)) return -1;\r
+                       \r
+                       return index(environment, subscripts);\r
+                       \r
+               }\r
+               \r
+       }\r
+       \r
+       boolean areSubscriptsConstant(IExpression[] subscripts) {\r
+               if(subscripts == null) return true;\r
+               for(IExpression e : subscripts) {\r
+                       if(!(e instanceof Constant)) return false;\r
+               }\r
+               return true;\r
+       }\r
+       \r
+       public Object evaluate(IEnvironment environment, IExpression[] subscripts, int constantIndex) {\r
+               \r
+               if(constantIndex >= 0 && environment instanceof Environment) {\r
+                       Double result = (Double)environment.getValue(constantIndex);\r
+                       if(result == null)\r
+                               throw new UnassignedVariableException("No value for " + name);\r
+                       if(SolverUtils.isArray(dimensions) && subscripts == null) {\r
+                               return new Array().addElement(result);\r
+                       } else {\r
+                               return result;\r
+                       }\r
+               }\r
+               \r
+               if(isStoredAsArray()) {\r
+                       \r
+                       Array array = (Array)environment.getValue(index);\r
+                       if(hasScalarSubscript(subscripts)) {\r
+                               Object o = getArrayIndex(environment, subscripts, array);\r
+                               if(o instanceof Variable) throw new IllegalStateException();\r
+                               if(o instanceof Array)\r
+                                       throw new IllegalStateException();\r
+                               return o;\r
+                       }\r
+                       else return array;\r
+                       \r
+               } else {\r
+                       \r
+                       if(dimension() > 1) {\r
+                               if(subscripts != null) {\r
+                                       \r
+                                       Array[] sub = SolverUtils.parseSubscripts(environment, subscripts);\r
+                                       if(SolverUtils.isSlice(sub)) {\r
+                                               Array arr = new Array();\r
+                                               intoArray(environment, index, 0, arr);\r
+                                               return arr.slice(sub);\r
+                                       } else { \r
+                                               return environment.getValue(index(environment, subscripts));\r
+                                       }\r
+                                       \r
+                               } else {\r
+                                       Array array = new Array();\r
+                                       intoArray(environment, index, 0, array);\r
+                                       return array;\r
+                               }\r
+                       }\r
+                       \r
+                       Object result = environment.getNamedValue(name);\r
+                       if(result == null) result = environment.getValue(index(environment, subscripts));\r
+                       if(result == null) throw new UnassignedVariableException("No value for " + name);\r
+\r
+                       if(SolverUtils.isArray(dimensions) && subscripts == null) {\r
+                               return new Array().addElement(result);\r
+                       } else {\r
+                               return result;\r
+                       }\r
+                       \r
+               }\r
+       }\r
+       \r
+       public IExpression getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/VariableDeclaration.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/VariableDeclaration.java
new file mode 100644 (file)
index 0000000..83958d3
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+import java.util.Map;\r
+\r
+\r
+public class VariableDeclaration implements IExpression {\r
+\r
+       public Variable variable;\r
+       public String direction;\r
+       public String type;\r
+       public ArgumentList modification;\r
+       public boolean assigned = false;\r
+\r
+       public VariableDeclaration(Variable variable, String direction, String type, ArgumentList modification) {\r
+               this.variable = variable;\r
+               this.direction = direction;\r
+               this.type = type;\r
+               this.modification = modification;\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               return direction + " " + type + " " + variable + " " + modification;\r
+       }\r
+       \r
+       @Override\r
+       public Object evaluate(IEnvironment environment) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public IExpression withBase(IFrame frame, String prefix) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+    \r
+       @Override\r
+       public Object getPossibleConstant() {\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public IExpression rewrite(IFrame frame, Map<String, VariableBase> copies) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public void accept(ExpressionVisitor visitor) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/While.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/While.java
new file mode 100644 (file)
index 0000000..47e94c8
--- /dev/null
@@ -0,0 +1,34 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Semantum Oy.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package fi.semantum.sysdyn.solver;\r
+\r
+public class While implements IStatement {\r
+\r
+       public IExpression expression;\r
+       public IStatement statement;\r
+       \r
+       public While(IExpression expression, IStatement statement) {\r
+               this.expression = expression;\r
+               this.statement = statement;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return "while " + expression + " then "+ statement + " end";\r
+       }\r
+       \r
+       @Override\r
+       public void evaluate(IEnvironment environment) {\r
+               while ((Boolean)expression.evaluate(environment))\r
+                       statement.evaluate(environment);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/JJTModelParserState.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/JJTModelParserState.java
new file mode 100644 (file)
index 0000000..6d43b87
--- /dev/null
@@ -0,0 +1,123 @@
+/* Generated By:JavaCC: Do not edit this line. JJTModelParserState.java Version 5.0 */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+public class JJTModelParserState {\r
+  private java.util.List<Node> nodes;\r
+  private java.util.List<Integer> marks;\r
+\r
+  private int sp;        // number of nodes on stack\r
+  private int mk;        // current mark\r
+  private boolean node_created;\r
+\r
+  public JJTModelParserState() {\r
+    nodes = new java.util.ArrayList<Node>();\r
+    marks = new java.util.ArrayList<Integer>();\r
+    sp = 0;\r
+    mk = 0;\r
+  }\r
+\r
+  /* Determines whether the current node was actually closed and\r
+     pushed.  This should only be called in the final user action of a\r
+     node scope.  */\r
+  public boolean nodeCreated() {\r
+    return node_created;\r
+  }\r
+\r
+  /* Call this to reinitialize the node stack.  It is called\r
+     automatically by the parser's ReInit() method. */\r
+  public void reset() {\r
+    nodes.clear();\r
+    marks.clear();\r
+    sp = 0;\r
+    mk = 0;\r
+  }\r
+\r
+  /* Returns the root node of the AST.  It only makes sense to call\r
+     this after a successful parse. */\r
+  public Node rootNode() {\r
+    return nodes.get(0);\r
+  }\r
+\r
+  /* Pushes a node on to the stack. */\r
+  public void pushNode(Node n) {\r
+    nodes.add(n);\r
+    ++sp;\r
+  }\r
+\r
+  /* Returns the node on the top of the stack, and remove it from the\r
+     stack.  */\r
+  public Node popNode() {\r
+    if (--sp < mk) {\r
+      mk = marks.remove(marks.size()-1);\r
+    }\r
+    return nodes.remove(nodes.size()-1);\r
+  }\r
+\r
+  /* Returns the node currently on the top of the stack. */\r
+  public Node peekNode() {\r
+    return nodes.get(nodes.size()-1);\r
+  }\r
+\r
+  /* Returns the number of children on the stack in the current node\r
+     scope. */\r
+  public int nodeArity() {\r
+    return sp - mk;\r
+  }\r
+\r
+\r
+  public void clearNodeScope(Node n) {\r
+    while (sp > mk) {\r
+      popNode();\r
+    }\r
+    mk = marks.remove(marks.size()-1);\r
+  }\r
+\r
+\r
+  public void openNodeScope(Node n) {\r
+    marks.add(mk);\r
+    mk = sp;\r
+    n.jjtOpen();\r
+  }\r
+\r
+\r
+  /* A definite node is constructed from a specified number of\r
+     children.  That number of nodes are popped from the stack and\r
+     made the children of the definite node.  Then the definite node\r
+     is pushed on to the stack. */\r
+  public void closeNodeScope(Node n, int num) {\r
+    mk = marks.remove(marks.size()-1);\r
+    while (num-- > 0) {\r
+      Node c = popNode();\r
+      c.jjtSetParent(n);\r
+      n.jjtAddChild(c, num);\r
+    }\r
+    n.jjtClose();\r
+    pushNode(n);\r
+    node_created = true;\r
+  }\r
+\r
+\r
+  /* A conditional node is constructed if its condition is true.  All\r
+     the nodes that have been pushed since the node was opened are\r
+     made children of the conditional node, which is then pushed\r
+     on to the stack.  If the condition is false the node is not\r
+     constructed and they are left on the stack. */\r
+  public void closeNodeScope(Node n, boolean condition) {\r
+    if (condition) {\r
+      int a = nodeArity();\r
+      mk = marks.remove(marks.size()-1);\r
+      while (a-- > 0) {\r
+        Node c = popNode();\r
+        c.jjtSetParent(n);\r
+        n.jjtAddChild(c, a);\r
+      }\r
+      n.jjtClose();\r
+      pushNode(n);\r
+      node_created = true;\r
+    } else {\r
+      mk = marks.remove(marks.size()-1);\r
+      node_created = false;\r
+    }\r
+  }\r
+}\r
+/* JavaCC - OriginalChecksum=6281595a71622ddc7d1a230278358c63 (do not edit this line) */\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParser.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParser.java
new file mode 100644 (file)
index 0000000..de6a2b2
--- /dev/null
@@ -0,0 +1,6045 @@
+/* Generated By:JJTree&JavaCC: Do not edit this line. ModelParser.java */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class ModelParser/*@bgen(jjtree)*/implements ModelParserTreeConstants, ModelParserConstants {/*@bgen(jjtree)*/\r
+  protected JJTModelParserState jjtree = new JJTModelParserState();\r
+  private ArrayList<Parameter> inputs = new ArrayList<Parameter>();\r
+  private ArrayList<Parameter> outputs = new ArrayList<Parameter>();\r
+\r
+  private enum InterfaceVariableType\r
+  {\r
+    INPUT, OUTPUT, OTHER\r
+  }\r
+\r
+  public class Parameter\r
+  {\r
+    public String name;\r
+    public boolean optional;\r
+    public String description;\r
+    public String type;\r
+\r
+    public Parameter()\r
+    {\r
+      name = new String("");\r
+      optional = false;\r
+      description = null;\r
+      type = null;\r
+    }\r
+  }\r
+\r
+  public ArrayList<Parameter> getInputs()\r
+  {\r
+    return inputs;\r
+  }\r
+\r
+  public ArrayList<Parameter> getOutputs()\r
+  {\r
+    return outputs;\r
+  }\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+  final public Node parse() throws ParseException {\r
+                /*@bgen(jjtree) parse */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTPARSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      stored_definition();\r
+      jj_consume_token(0);\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+      {if (true) return jjtn000;}\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+/*** Stored Definition - Within ************************************/\r
+  final public Node stored_definition() throws ParseException {\r
+                                    /*@bgen(jjtree) STORED */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSTORED);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 53:\r
+        jj_consume_token(53);\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 68:\r
+        case IDENT:\r
+          name();\r
+          break;\r
+        default:\r
+          jj_la1[0] = jj_gen;\r
+          ;\r
+        }\r
+        jj_consume_token(70);\r
+        break;\r
+      default:\r
+        jj_la1[1] = jj_gen;\r
+        ;\r
+      }\r
+      label_1:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 7:\r
+        case 11:\r
+        case 17:\r
+        case 24:\r
+        case 26:\r
+        case 30:\r
+        case 34:\r
+        case 37:\r
+        case 38:\r
+        case 44:\r
+        case 47:\r
+        case 50:\r
+        case 61:\r
+        case 95:\r
+        case 96:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[2] = jj_gen;\r
+          break label_1;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 11:\r
+          jj_consume_token(11);\r
+          break;\r
+        default:\r
+          jj_la1[3] = jj_gen;\r
+          ;\r
+        }\r
+        class_definition();\r
+        jj_consume_token(70);\r
+      }\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+      {if (true) return jjtn000;}\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+/*** Class Definition **********************************************/\r
+  final public void class_definition() throws ParseException {\r
+                           /*@bgen(jjtree) class_definition */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCLASS_DEFINITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 30:\r
+        jj_consume_token(30);\r
+        break;\r
+      default:\r
+        jj_la1[4] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 47:\r
+        jj_consume_token(47);\r
+        break;\r
+      default:\r
+        jj_la1[5] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 34:\r
+        jj_consume_token(34);\r
+                jjtn000.op = "class";\r
+        break;\r
+      case 7:\r
+        jj_consume_token(7);\r
+                                                    jjtn000.op = "model";\r
+        break;\r
+      case 61:\r
+        jj_consume_token(61);\r
+        break;\r
+      case 24:\r
+        jj_consume_token(24);\r
+        break;\r
+      case 44:\r
+      case 50:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 50:\r
+          jj_consume_token(50);\r
+          break;\r
+        default:\r
+          jj_la1[6] = jj_gen;\r
+          ;\r
+        }\r
+        jj_consume_token(44);\r
+        break;\r
+      case 38:\r
+        jj_consume_token(38);\r
+        break;\r
+      case 37:\r
+        jj_consume_token(37);\r
+        break;\r
+      case 26:\r
+        jj_consume_token(26);\r
+                             jjtn000.op = "function";\r
+        break;\r
+      case 17:\r
+        jj_consume_token(17);\r
+        break;\r
+      case 95:\r
+        jj_consume_token(95);\r
+        break;\r
+      case 96:\r
+        jj_consume_token(96);\r
+        break;\r
+      default:\r
+        jj_la1[7] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      class_specifier();\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void class_specifier() throws ParseException {\r
+                          /*@bgen(jjtree) class_specifier */\r
+                           SimpleNode jjtn000 = new SimpleNode(JJTCLASS_SPECIFIER);\r
+                           boolean jjtc000 = true;\r
+                           jjtree.openNodeScope(jjtn000);Token t;\r
+    try {\r
+      if (jj_2_1(2)) {\r
+        t = jj_consume_token(IDENT);\r
+                             jjtn000.op = t.image;\r
+        string_comment();\r
+        composition();\r
+        jj_consume_token(35);\r
+        jj_consume_token(IDENT);\r
+      } else if (jj_2_2(2)) {\r
+        jj_consume_token(IDENT);\r
+        jj_consume_token(88);\r
+        base_prefix();\r
+        name();\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 66:\r
+          array_subscripts();\r
+          break;\r
+        default:\r
+          jj_la1[8] = jj_gen;\r
+          ;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 62:\r
+          class_modification();\r
+          break;\r
+        default:\r
+          jj_la1[9] = jj_gen;\r
+          ;\r
+        }\r
+        comment();\r
+      } else if (jj_2_3(3)) {\r
+        jj_consume_token(IDENT);\r
+        jj_consume_token(88);\r
+        jj_consume_token(58);\r
+        jj_consume_token(62);\r
+        name();\r
+        jj_consume_token(71);\r
+        jj_consume_token(IDENT);\r
+        label_2:\r
+        while (true) {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 71:\r
+            ;\r
+            break;\r
+          default:\r
+            jj_la1[10] = jj_gen;\r
+            break label_2;\r
+          }\r
+          jj_consume_token(71);\r
+          jj_consume_token(IDENT);\r
+        }\r
+        jj_consume_token(63);\r
+        comment();\r
+      } else if (jj_2_4(3)) {\r
+        jj_consume_token(IDENT);\r
+        jj_consume_token(88);\r
+        jj_consume_token(40);\r
+        jj_consume_token(62);\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case IDENT:\r
+          enum_list();\r
+          break;\r
+        default:\r
+          jj_la1[11] = jj_gen;\r
+          ;\r
+        }\r
+        jj_consume_token(63);\r
+        comment();\r
+      } else {\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void base_prefix() throws ParseException {\r
+                      /*@bgen(jjtree) base_prefix */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTBASE_PREFIX);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      type_prefix();\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void enum_list() throws ParseException {\r
+                    /*@bgen(jjtree) enum_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTENUM_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      enumeration_literal();\r
+      label_3:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[12] = jj_gen;\r
+          break label_3;\r
+        }\r
+        jj_consume_token(71);\r
+        enumeration_literal();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void enumeration_literal() throws ParseException {\r
+                              /*@bgen(jjtree) enumeration_literal */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTENUMERATION_LITERAL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(IDENT);\r
+      comment();\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void parse_composition() throws ParseException {\r
+                            /*@bgen(jjtree) parse_composition */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTPARSE_COMPOSITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      composition();\r
+      jj_consume_token(0);\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void composition() throws ParseException {\r
+                      /*@bgen(jjtree) composition */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCOMPOSITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      element_list();\r
+      label_4:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 4:\r
+        case 45:\r
+        case 46:\r
+        case 52:\r
+        case 57:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[13] = jj_gen;\r
+          break label_4;\r
+        }\r
+        if (jj_2_5(2)) {\r
+          jj_consume_token(57);\r
+          element_list();\r
+        } else {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 52:\r
+            jj_consume_token(52);\r
+            element_list();\r
+            break;\r
+          case 45:\r
+          case 46:\r
+            equation_section();\r
+            break;\r
+          case 4:\r
+            algorithm_section();\r
+            break;\r
+          default:\r
+            jj_la1[14] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+        }\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 59:\r
+        jj_consume_token(59);\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case STRING:\r
+          language_specification();\r
+          break;\r
+        default:\r
+          jj_la1[15] = jj_gen;\r
+          ;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 68:\r
+        case IDENT:\r
+          external_function_call();\r
+          break;\r
+        default:\r
+          jj_la1[16] = jj_gen;\r
+          ;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 14:\r
+          annotation();\r
+          break;\r
+        default:\r
+          jj_la1[17] = jj_gen;\r
+          ;\r
+        }\r
+        jj_consume_token(70);\r
+        break;\r
+      default:\r
+        jj_la1[18] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 14:\r
+        annotation();\r
+        jj_consume_token(70);\r
+        break;\r
+      default:\r
+        jj_la1[19] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void language_specification() throws ParseException {\r
+                                 /*@bgen(jjtree) language_specification */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTLANGUAGE_SPECIFICATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(STRING);\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void external_function_call() throws ParseException {\r
+                                 /*@bgen(jjtree) external_function_call */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXTERNAL_FUNCTION_CALL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+      case IDENT:\r
+        component_reference();\r
+        jj_consume_token(88);\r
+        break;\r
+      default:\r
+        jj_la1[20] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(IDENT);\r
+      jj_consume_token(62);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        expression_list();\r
+        break;\r
+      default:\r
+        jj_la1[21] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(63);\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void element_list() throws ParseException {\r
+                       /*@bgen(jjtree) element_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      label_5:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 5:\r
+        case 7:\r
+        case 8:\r
+        case 11:\r
+        case 13:\r
+        case 16:\r
+        case 17:\r
+        case 23:\r
+        case 24:\r
+        case 26:\r
+        case 27:\r
+        case 30:\r
+        case 32:\r
+        case 34:\r
+        case 36:\r
+        case 37:\r
+        case 38:\r
+        case 42:\r
+        case 44:\r
+        case 47:\r
+        case 49:\r
+        case 50:\r
+        case 51:\r
+        case 55:\r
+        case 56:\r
+        case 61:\r
+        case 68:\r
+        case IDENT:\r
+        case 95:\r
+        case 96:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[22] = jj_gen;\r
+          break label_5;\r
+        }\r
+        element();\r
+        jj_consume_token(70);\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public Node element() throws ParseException {\r
+                  /*@bgen(jjtree) element */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 36:\r
+        import_clause();\r
+                      jjtree.closeNodeScope(jjtn000, true);\r
+                      jjtc000 = false;\r
+                      {if (true) return jjtn000;}\r
+        break;\r
+      case 55:\r
+        extends_clause();\r
+                       jjtree.closeNodeScope(jjtn000, true);\r
+                       jjtc000 = false;\r
+                       {if (true) return jjtn000;}\r
+        break;\r
+      case 5:\r
+      case 7:\r
+      case 8:\r
+      case 11:\r
+      case 13:\r
+      case 16:\r
+      case 17:\r
+      case 23:\r
+      case 24:\r
+      case 26:\r
+      case 27:\r
+      case 30:\r
+      case 32:\r
+      case 34:\r
+      case 37:\r
+      case 38:\r
+      case 42:\r
+      case 44:\r
+      case 47:\r
+      case 49:\r
+      case 50:\r
+      case 51:\r
+      case 56:\r
+      case 61:\r
+      case 68:\r
+      case IDENT:\r
+      case 95:\r
+      case 96:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 8:\r
+          jj_consume_token(8);\r
+          break;\r
+        default:\r
+          jj_la1[23] = jj_gen;\r
+          ;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 11:\r
+          jj_consume_token(11);\r
+          break;\r
+        default:\r
+          jj_la1[24] = jj_gen;\r
+          ;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 51:\r
+          jj_consume_token(51);\r
+                jjtn000.op = "inner";\r
+          break;\r
+        default:\r
+          jj_la1[25] = jj_gen;\r
+          ;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 27:\r
+          jj_consume_token(27);\r
+                                                       jjtn000.op = "outer";\r
+          break;\r
+        default:\r
+          jj_la1[26] = jj_gen;\r
+          ;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 5:\r
+        case 7:\r
+        case 16:\r
+        case 17:\r
+        case 23:\r
+        case 24:\r
+        case 26:\r
+        case 30:\r
+        case 32:\r
+        case 34:\r
+        case 37:\r
+        case 38:\r
+        case 42:\r
+        case 44:\r
+        case 47:\r
+        case 49:\r
+        case 50:\r
+        case 56:\r
+        case 61:\r
+        case 68:\r
+        case IDENT:\r
+        case 95:\r
+        case 96:\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 7:\r
+          case 17:\r
+          case 24:\r
+          case 26:\r
+          case 30:\r
+          case 34:\r
+          case 37:\r
+          case 38:\r
+          case 44:\r
+          case 47:\r
+          case 50:\r
+          case 61:\r
+          case 95:\r
+          case 96:\r
+            class_definition();\r
+            break;\r
+          case 5:\r
+          case 16:\r
+          case 23:\r
+          case 32:\r
+          case 42:\r
+          case 49:\r
+          case 56:\r
+          case 68:\r
+          case IDENT:\r
+            component_clause();\r
+            break;\r
+          default:\r
+            jj_la1[27] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+          break;\r
+        case 13:\r
+          jj_consume_token(13);\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 7:\r
+          case 17:\r
+          case 24:\r
+          case 26:\r
+          case 30:\r
+          case 34:\r
+          case 37:\r
+          case 38:\r
+          case 44:\r
+          case 47:\r
+          case 50:\r
+          case 61:\r
+          case 95:\r
+          case 96:\r
+            class_definition();\r
+            break;\r
+          case 5:\r
+          case 16:\r
+          case 23:\r
+          case 32:\r
+          case 42:\r
+          case 49:\r
+          case 56:\r
+          case 68:\r
+          case IDENT:\r
+            component_clause();\r
+            break;\r
+          default:\r
+            jj_la1[28] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 54:\r
+            constraining_clause();\r
+            comment();\r
+            break;\r
+          default:\r
+            jj_la1[29] = jj_gen;\r
+            ;\r
+          }\r
+          break;\r
+        default:\r
+          jj_la1[30] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+      {if (true) return jjtn000;}\r
+        break;\r
+      default:\r
+        jj_la1[31] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void import_clause() throws ParseException {\r
+                        /*@bgen(jjtree) import_clause */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTIMPORT_CLAUSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(36);\r
+      if (jj_2_6(2)) {\r
+        jj_consume_token(IDENT);\r
+        jj_consume_token(88);\r
+        name();\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 68:\r
+        case IDENT:\r
+          name();\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 68:\r
+            jj_consume_token(68);\r
+            jj_consume_token(82);\r
+            break;\r
+          default:\r
+            jj_la1[32] = jj_gen;\r
+            ;\r
+          }\r
+          break;\r
+        default:\r
+          jj_la1[33] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+      comment();\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+/*** Extends *******************************************************/\r
+  final public void extends_clause() throws ParseException {\r
+                         /*@bgen(jjtree) extends_clause */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXTENDS_CLAUSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(55);\r
+      name();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 62:\r
+        class_modification();\r
+        break;\r
+      default:\r
+        jj_la1[34] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 14:\r
+        annotation();\r
+        break;\r
+      default:\r
+        jj_la1[35] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void constraining_clause() throws ParseException {\r
+                              /*@bgen(jjtree) constraining_clause */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCONSTRAINING_CLAUSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(54);\r
+      name();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 62:\r
+        class_modification();\r
+        break;\r
+      default:\r
+        jj_la1[36] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+/*** Component Clause **********************************************/\r
+  final public void component_clause() throws ParseException {\r
+                           /*@bgen(jjtree) component_clause */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_CLAUSE);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);InterfaceVariableType ioType = InterfaceVariableType.OTHER;\r
+    String typeSpecifier = "";\r
+    //String arraySubscripts = null;\r
+    ArrayList<Parameter> componentList = new ArrayList<Parameter>();\r
+    try {\r
+      ioType = type_prefix();\r
+      typeSpecifier = type_specifier();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 66:\r
+        array_subscripts();\r
+        break;\r
+      default:\r
+        jj_la1[37] = jj_gen;\r
+        ;\r
+      }\r
+      componentList = component_list();\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+        if (ioType == InterfaceVariableType.INPUT) {\r
+            for (Parameter input : componentList) {\r
+                input.type = typeSpecifier;\r
+                inputs.add(input);\r
+            }\r
+        } else if (ioType == InterfaceVariableType.OUTPUT) {\r
+            for (Parameter output : componentList) {\r
+                output.type = typeSpecifier;\r
+                outputs.add(output);\r
+            }\r
+        }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public InterfaceVariableType type_prefix() throws ParseException {\r
+                                       /*@bgen(jjtree) type_prefix */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTTYPE_PREFIX);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);InterfaceVariableType type = InterfaceVariableType.OTHER;\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 16:\r
+      case 23:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 16:\r
+          jj_consume_token(16);\r
+          break;\r
+        case 23:\r
+          jj_consume_token(23);\r
+          break;\r
+        default:\r
+          jj_la1[38] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[39] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 5:\r
+      case 42:\r
+      case 49:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 5:\r
+          jj_consume_token(5);\r
+                   jjtn000.op = "discrete";\r
+          break;\r
+        case 42:\r
+          jj_consume_token(42);\r
+                                                             jjtn000.op = "parameter";\r
+          break;\r
+        case 49:\r
+          jj_consume_token(49);\r
+                                                                                                       jjtn000.op = "constant";\r
+          break;\r
+        default:\r
+          jj_la1[40] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[41] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 32:\r
+      case 56:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 32:\r
+          jj_consume_token(32);\r
+                 type = InterfaceVariableType.OUTPUT; jjtn000.op = "output";\r
+          break;\r
+        case 56:\r
+          jj_consume_token(56);\r
+                    type = InterfaceVariableType.INPUT; jjtn000.op = "input";\r
+          break;\r
+        default:\r
+          jj_la1[42] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[43] = jj_gen;\r
+        ;\r
+      }\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+        {if (true) return type;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public String type_specifier() throws ParseException {\r
+                           /*@bgen(jjtree) type_specifier */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTTYPE_SPECIFIER);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);String ret = new String("");\r
+    try {\r
+      ret = name();\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+            jjtn000.op = ret;\r
+        {if (true) return ret;}\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public ArrayList<Parameter> component_list() throws ParseException {\r
+                                         /*@bgen(jjtree) component_list */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_LIST);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);ArrayList<Parameter> ret = new ArrayList<Parameter>();\r
+    Parameter temp;\r
+    try {\r
+      //       component_declaration { "," component_declaration }\r
+              temp = component_declaration();\r
+                                         ret.add(temp);\r
+      label_6:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[44] = jj_gen;\r
+          break label_6;\r
+        }\r
+        jj_consume_token(71);\r
+        temp = component_declaration();\r
+                                           ret.add(temp);\r
+      }\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+            {if (true) return ret;}\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public Parameter component_declaration() throws ParseException {\r
+                                     /*@bgen(jjtree) component_declaration */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_DECLARATION);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);Parameter ret;\r
+    String temp = "";\r
+    try {\r
+      //       declaration [ conditional_attribute ] comment\r
+              ret = declaration();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 31:\r
+        conditional_attribute();\r
+        break;\r
+      default:\r
+        jj_la1[45] = jj_gen;\r
+        ;\r
+      }\r
+      ret.description = comment();\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+        {if (true) return ret;}\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void conditional_attribute() throws ParseException {\r
+                                /*@bgen(jjtree) conditional_attribute */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCONDITIONAL_ATTRIBUTE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(31);\r
+      expression();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public Parameter declaration() throws ParseException {\r
+                           /*@bgen(jjtree) declaration */\r
+                            SimpleNode jjtn000 = new SimpleNode(JJTDECLARATION);\r
+                            boolean jjtc000 = true;\r
+                            jjtree.openNodeScope(jjtn000);Token t;\r
+    // Parameter here without comment yet.\r
+    Parameter ret = new Parameter();\r
+    try {\r
+      jj_consume_token(IDENT);\r
+                  ret.name = new String(token.image); jjtn000.op = token.image;\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 66:\r
+        array_subscripts();\r
+        break;\r
+      default:\r
+        jj_la1[46] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 62:\r
+      case 88:\r
+      case 89:\r
+        ret.optional = modification();\r
+        break;\r
+      default:\r
+        jj_la1[47] = jj_gen;\r
+        ;\r
+      }\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+                {if (true) return ret;}\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+/*** Modification **********************************************/\r
+  final public boolean modification() throws ParseException {\r
+                          /*@bgen(jjtree) modification */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTMODIFICATION);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);boolean optional = false;\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 62:\r
+        class_modification();\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 88:\r
+          jj_consume_token(88);\r
+          expression();\r
+          break;\r
+        default:\r
+          jj_la1[48] = jj_gen;\r
+          ;\r
+        }\r
+        break;\r
+      case 88:\r
+        jj_consume_token(88);\r
+        expression();\r
+                             optional = true;\r
+        break;\r
+      case 89:\r
+        jj_consume_token(89);\r
+        expression();\r
+                              optional = true;\r
+        break;\r
+      default:\r
+        jj_la1[49] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+            {if (true) return optional;}\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void class_modification() throws ParseException {\r
+                             /*@bgen(jjtree) class_modification */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCLASS_MODIFICATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(62);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 8:\r
+      case 10:\r
+      case 11:\r
+      case 13:\r
+      case 68:\r
+      case IDENT:\r
+        argument_list();\r
+        break;\r
+      default:\r
+        jj_la1[50] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(63);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void argument_list() throws ParseException {\r
+                        /*@bgen(jjtree) argument_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARGUMENT_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      argument();\r
+      label_7:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[51] = jj_gen;\r
+          break label_7;\r
+        }\r
+        jj_consume_token(71);\r
+        argument();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void argument() throws ParseException {\r
+                   /*@bgen(jjtree) argument */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARGUMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 10:\r
+      case 11:\r
+      case 13:\r
+      case 68:\r
+      case IDENT:\r
+        element_modification_or_replaceable();\r
+        break;\r
+      case 8:\r
+        element_redeclaration();\r
+        break;\r
+      default:\r
+        jj_la1[52] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void element_modification_or_replaceable() throws ParseException {\r
+                                              /*@bgen(jjtree) element_modification_or_replaceable */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_MODIFICATION_OR_REPLACEABLE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 10:\r
+        jj_consume_token(10);\r
+        break;\r
+      default:\r
+        jj_la1[53] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 11:\r
+        jj_consume_token(11);\r
+        break;\r
+      default:\r
+        jj_la1[54] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+      case IDENT:\r
+        element_modification();\r
+        break;\r
+      case 13:\r
+        element_replaceable();\r
+        break;\r
+      default:\r
+        jj_la1[55] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void element_modification() throws ParseException {\r
+                               /*@bgen(jjtree) element_modification */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_MODIFICATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      name();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 62:\r
+      case 88:\r
+      case 89:\r
+        modification();\r
+        break;\r
+      default:\r
+        jj_la1[56] = jj_gen;\r
+        ;\r
+      }\r
+      string_comment();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void element_redeclaration() throws ParseException {\r
+                                /*@bgen(jjtree) element_redeclaration */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_REDECLARATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(8);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 10:\r
+        jj_consume_token(10);\r
+        break;\r
+      default:\r
+        jj_la1[57] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 11:\r
+        jj_consume_token(11);\r
+        break;\r
+      default:\r
+        jj_la1[58] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 5:\r
+      case 7:\r
+      case 16:\r
+      case 17:\r
+      case 23:\r
+      case 24:\r
+      case 26:\r
+      case 30:\r
+      case 32:\r
+      case 34:\r
+      case 37:\r
+      case 38:\r
+      case 42:\r
+      case 44:\r
+      case 47:\r
+      case 49:\r
+      case 50:\r
+      case 56:\r
+      case 61:\r
+      case 68:\r
+      case IDENT:\r
+      case 95:\r
+      case 96:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 7:\r
+        case 17:\r
+        case 24:\r
+        case 26:\r
+        case 30:\r
+        case 34:\r
+        case 37:\r
+        case 38:\r
+        case 44:\r
+        case 47:\r
+        case 50:\r
+        case 61:\r
+        case 95:\r
+        case 96:\r
+          class_definition();\r
+          break;\r
+        case 5:\r
+        case 16:\r
+        case 23:\r
+        case 32:\r
+        case 42:\r
+        case 49:\r
+        case 56:\r
+        case 68:\r
+        case IDENT:\r
+          component_clause1();\r
+          break;\r
+        default:\r
+          jj_la1[59] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        break;\r
+      case 13:\r
+        element_replaceable();\r
+        break;\r
+      default:\r
+        jj_la1[60] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void element_replaceable() throws ParseException {\r
+                              /*@bgen(jjtree) element_replaceable */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_REPLACEABLE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(13);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 7:\r
+      case 17:\r
+      case 24:\r
+      case 26:\r
+      case 30:\r
+      case 34:\r
+      case 37:\r
+      case 38:\r
+      case 44:\r
+      case 47:\r
+      case 50:\r
+      case 61:\r
+      case 95:\r
+      case 96:\r
+        class_definition();\r
+        break;\r
+      case 5:\r
+      case 16:\r
+      case 23:\r
+      case 32:\r
+      case 42:\r
+      case 49:\r
+      case 56:\r
+      case 68:\r
+      case IDENT:\r
+        component_clause1();\r
+        break;\r
+      default:\r
+        jj_la1[61] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 54:\r
+        constraining_clause();\r
+        break;\r
+      default:\r
+        jj_la1[62] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void component_clause1() throws ParseException {\r
+                            /*@bgen(jjtree) component_clause1 */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_CLAUSE1);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      type_prefix();\r
+      type_specifier();\r
+      component_declaration1();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void component_declaration1() throws ParseException {\r
+                                 /*@bgen(jjtree) component_declaration1 */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_DECLARATION1);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      declaration();\r
+      comment();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+/*** Equations *************************************************/\r
+  final public void equation_section() throws ParseException {\r
+                           /*@bgen(jjtree) equation_section */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEQUATION_SECTION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 46:\r
+        jj_consume_token(46);\r
+                      jjtn000.op = "initial";\r
+        break;\r
+      default:\r
+        jj_la1[63] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(45);\r
+      label_8:\r
+      while (true) {\r
+        if (jj_2_7(2)) {\r
+          ;\r
+        } else {\r
+          break label_8;\r
+        }\r
+        equation();\r
+        jj_consume_token(70);\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void algorithm_section() throws ParseException {\r
+                            /*@bgen(jjtree) algorithm_section */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTALGORITHM_SECTION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 46:\r
+        jj_consume_token(46);\r
+        break;\r
+      default:\r
+        jj_la1[64] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(4);\r
+      label_9:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 18:\r
+        case 21:\r
+        case 29:\r
+        case 31:\r
+        case 43:\r
+        case 48:\r
+        case 62:\r
+        case 68:\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[65] = jj_gen;\r
+          break label_9;\r
+        }\r
+        statement();\r
+        jj_consume_token(70);\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void assignment() throws ParseException {\r
+                     /*@bgen(jjtree) assignment */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTASSIGNMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      simple_expression();\r
+      jj_consume_token(88);\r
+      expression();\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+    }\r
+  }\r
+\r
+  final public Node equation() throws ParseException {\r
+                   /*@bgen(jjtree) equation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEQUATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      if (jj_2_8(3)) {\r
+        assignment();\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 31:\r
+          if_equation();\r
+          break;\r
+        case 21:\r
+          for_equation();\r
+          break;\r
+        case 39:\r
+          connect_clause();\r
+          break;\r
+        case 43:\r
+          when_equation();\r
+          break;\r
+        case IDENT:\r
+          jj_consume_token(IDENT);\r
+          function_call_args();\r
+          break;\r
+        default:\r
+          jj_la1[66] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+      comment();\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+      {if (true) return jjtn000;}\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void statement() throws ParseException {\r
+                    /*@bgen(jjtree) statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSTATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+      case IDENT:\r
+        component_reference();\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 89:\r
+          jj_consume_token(89);\r
+          expression();\r
+          break;\r
+        case 62:\r
+          function_call_args();\r
+          break;\r
+        default:\r
+          jj_la1[67] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        break;\r
+      case 62:\r
+        jj_consume_token(62);\r
+        output_expression_list();\r
+        jj_consume_token(63);\r
+        jj_consume_token(89);\r
+        component_reference();\r
+        function_call_args();\r
+        break;\r
+      case 29:\r
+        jj_consume_token(29);\r
+        break;\r
+      case 18:\r
+        jj_consume_token(18);\r
+        break;\r
+      case 31:\r
+        if_statement();\r
+        break;\r
+      case 21:\r
+        for_statement();\r
+        break;\r
+      case 48:\r
+        while_statement();\r
+        break;\r
+      case 43:\r
+        when_statement();\r
+        break;\r
+      default:\r
+        jj_la1[68] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      comment();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void if_equation() throws ParseException {\r
+                      /*@bgen(jjtree) if_equation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTIF_EQUATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(31);\r
+      expression();\r
+      jj_consume_token(28);\r
+      label_10:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 21:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 39:\r
+        case 43:\r
+        case 46:\r
+        case 58:\r
+        case 62:\r
+        case 64:\r
+        case 66:\r
+        case 68:\r
+        case 78:\r
+        case 79:\r
+        case 80:\r
+        case 81:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[69] = jj_gen;\r
+          break label_10;\r
+        }\r
+        equation();\r
+        jj_consume_token(70);\r
+      }\r
+      label_11:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 20:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[70] = jj_gen;\r
+          break label_11;\r
+        }\r
+        jj_consume_token(20);\r
+        expression();\r
+        jj_consume_token(28);\r
+        label_12:\r
+        while (true) {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 6:\r
+          case 12:\r
+          case 21:\r
+          case 31:\r
+          case 33:\r
+          case 35:\r
+          case 39:\r
+          case 43:\r
+          case 46:\r
+          case 58:\r
+          case 62:\r
+          case 64:\r
+          case 66:\r
+          case 68:\r
+          case 78:\r
+          case 79:\r
+          case 80:\r
+          case 81:\r
+          case IDENT:\r
+          case STRING:\r
+          case UNSIGNED_INTEGER:\r
+          case UNSIGNED_NUMBER:\r
+            ;\r
+            break;\r
+          default:\r
+            jj_la1[71] = jj_gen;\r
+            break label_12;\r
+          }\r
+          equation();\r
+          jj_consume_token(70);\r
+        }\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 15:\r
+        jj_consume_token(15);\r
+        label_13:\r
+        while (true) {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 6:\r
+          case 12:\r
+          case 21:\r
+          case 31:\r
+          case 33:\r
+          case 35:\r
+          case 39:\r
+          case 43:\r
+          case 46:\r
+          case 58:\r
+          case 62:\r
+          case 64:\r
+          case 66:\r
+          case 68:\r
+          case 78:\r
+          case 79:\r
+          case 80:\r
+          case 81:\r
+          case IDENT:\r
+          case STRING:\r
+          case UNSIGNED_INTEGER:\r
+          case UNSIGNED_NUMBER:\r
+            ;\r
+            break;\r
+          default:\r
+            jj_la1[72] = jj_gen;\r
+            break label_13;\r
+          }\r
+          equation();\r
+          jj_consume_token(70);\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[73] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(35);\r
+      jj_consume_token(31);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void then_statement() throws ParseException {\r
+                         /*@bgen(jjtree) then_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTTHEN_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      statement();\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void elseif_statement() throws ParseException {\r
+                           /*@bgen(jjtree) elseif_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELSEIF_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      statement();\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void else_statement() throws ParseException {\r
+                         /*@bgen(jjtree) else_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELSE_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      statement();\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void if_statement() throws ParseException {\r
+                       /*@bgen(jjtree) if_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTIF_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(31);\r
+      expression();\r
+      jj_consume_token(28);\r
+      label_14:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 18:\r
+        case 21:\r
+        case 29:\r
+        case 31:\r
+        case 43:\r
+        case 48:\r
+        case 62:\r
+        case 68:\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[74] = jj_gen;\r
+          break label_14;\r
+        }\r
+        then_statement();\r
+        jj_consume_token(70);\r
+      }\r
+      label_15:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 20:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[75] = jj_gen;\r
+          break label_15;\r
+        }\r
+        jj_consume_token(20);\r
+        expression();\r
+        jj_consume_token(28);\r
+        label_16:\r
+        while (true) {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 18:\r
+          case 21:\r
+          case 29:\r
+          case 31:\r
+          case 43:\r
+          case 48:\r
+          case 62:\r
+          case 68:\r
+          case IDENT:\r
+            ;\r
+            break;\r
+          default:\r
+            jj_la1[76] = jj_gen;\r
+            break label_16;\r
+          }\r
+          elseif_statement();\r
+          jj_consume_token(70);\r
+        }\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 15:\r
+        jj_consume_token(15);\r
+        label_17:\r
+        while (true) {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 18:\r
+          case 21:\r
+          case 29:\r
+          case 31:\r
+          case 43:\r
+          case 48:\r
+          case 62:\r
+          case 68:\r
+          case IDENT:\r
+            ;\r
+            break;\r
+          default:\r
+            jj_la1[77] = jj_gen;\r
+            break label_17;\r
+          }\r
+          else_statement();\r
+          jj_consume_token(70);\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[78] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(35);\r
+      jj_consume_token(31);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void for_equation() throws ParseException {\r
+                       /*@bgen(jjtree) for_equation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFOR_EQUATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(21);\r
+      for_indices();\r
+      jj_consume_token(60);\r
+      label_18:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 21:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 39:\r
+        case 43:\r
+        case 46:\r
+        case 58:\r
+        case 62:\r
+        case 64:\r
+        case 66:\r
+        case 68:\r
+        case 78:\r
+        case 79:\r
+        case 80:\r
+        case 81:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[79] = jj_gen;\r
+          break label_18;\r
+        }\r
+        equation();\r
+        jj_consume_token(70);\r
+      }\r
+      jj_consume_token(35);\r
+      jj_consume_token(21);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void for_statement() throws ParseException {\r
+                        /*@bgen(jjtree) for_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFOR_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(21);\r
+      for_indices();\r
+      jj_consume_token(60);\r
+      label_19:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 18:\r
+        case 21:\r
+        case 29:\r
+        case 31:\r
+        case 43:\r
+        case 48:\r
+        case 62:\r
+        case 68:\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[80] = jj_gen;\r
+          break label_19;\r
+        }\r
+        statement();\r
+        jj_consume_token(70);\r
+      }\r
+      jj_consume_token(35);\r
+      jj_consume_token(21);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void for_indices() throws ParseException {\r
+                      /*@bgen(jjtree) for_indices */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFOR_INDICES);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      for_index();\r
+      label_20:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[81] = jj_gen;\r
+          break label_20;\r
+        }\r
+        jj_consume_token(71);\r
+        for_index();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void for_index() throws ParseException {\r
+                    /*@bgen(jjtree) for_index */\r
+                     SimpleNode jjtn000 = new SimpleNode(JJTFOR_INDEX);\r
+                     boolean jjtc000 = true;\r
+                     jjtree.openNodeScope(jjtn000);Token t;\r
+    try {\r
+      //IDENT [ in expression ]\r
+              t = jj_consume_token(IDENT);\r
+                    jjtn000.op = t.image;\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 41:\r
+        jj_consume_token(41);\r
+        expression();\r
+        break;\r
+      default:\r
+        jj_la1[82] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void while_statement() throws ParseException {\r
+                          /*@bgen(jjtree) while_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTWHILE_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(48);\r
+      expression();\r
+      jj_consume_token(60);\r
+      label_21:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 18:\r
+        case 21:\r
+        case 29:\r
+        case 31:\r
+        case 43:\r
+        case 48:\r
+        case 62:\r
+        case 68:\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[83] = jj_gen;\r
+          break label_21;\r
+        }\r
+        statement();\r
+        jj_consume_token(70);\r
+      }\r
+      jj_consume_token(35);\r
+      jj_consume_token(48);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void when_equation() throws ParseException {\r
+                        /*@bgen(jjtree) when_equation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTWHEN_EQUATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(43);\r
+      expression();\r
+      jj_consume_token(28);\r
+      label_22:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 21:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 39:\r
+        case 43:\r
+        case 46:\r
+        case 58:\r
+        case 62:\r
+        case 64:\r
+        case 66:\r
+        case 68:\r
+        case 78:\r
+        case 79:\r
+        case 80:\r
+        case 81:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[84] = jj_gen;\r
+          break label_22;\r
+        }\r
+        equation();\r
+        jj_consume_token(70);\r
+      }\r
+      label_23:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 25:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[85] = jj_gen;\r
+          break label_23;\r
+        }\r
+        jj_consume_token(25);\r
+        expression();\r
+        jj_consume_token(28);\r
+        label_24:\r
+        while (true) {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 6:\r
+          case 12:\r
+          case 21:\r
+          case 31:\r
+          case 33:\r
+          case 35:\r
+          case 39:\r
+          case 43:\r
+          case 46:\r
+          case 58:\r
+          case 62:\r
+          case 64:\r
+          case 66:\r
+          case 68:\r
+          case 78:\r
+          case 79:\r
+          case 80:\r
+          case 81:\r
+          case IDENT:\r
+          case STRING:\r
+          case UNSIGNED_INTEGER:\r
+          case UNSIGNED_NUMBER:\r
+            ;\r
+            break;\r
+          default:\r
+            jj_la1[86] = jj_gen;\r
+            break label_24;\r
+          }\r
+          equation();\r
+          jj_consume_token(70);\r
+        }\r
+      }\r
+      jj_consume_token(35);\r
+      jj_consume_token(43);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void when_statement() throws ParseException {\r
+                         /*@bgen(jjtree) when_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTWHEN_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(43);\r
+      expression();\r
+      jj_consume_token(28);\r
+      label_25:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 18:\r
+        case 21:\r
+        case 29:\r
+        case 31:\r
+        case 43:\r
+        case 48:\r
+        case 62:\r
+        case 68:\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[87] = jj_gen;\r
+          break label_25;\r
+        }\r
+        statement();\r
+        jj_consume_token(70);\r
+      }\r
+      label_26:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 25:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[88] = jj_gen;\r
+          break label_26;\r
+        }\r
+        jj_consume_token(25);\r
+        expression();\r
+        jj_consume_token(28);\r
+        label_27:\r
+        while (true) {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 18:\r
+          case 21:\r
+          case 29:\r
+          case 31:\r
+          case 43:\r
+          case 48:\r
+          case 62:\r
+          case 68:\r
+          case IDENT:\r
+            ;\r
+            break;\r
+          default:\r
+            jj_la1[89] = jj_gen;\r
+            break label_27;\r
+          }\r
+          statement();\r
+          jj_consume_token(70);\r
+        }\r
+      }\r
+      jj_consume_token(35);\r
+      jj_consume_token(43);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void connect_clause() throws ParseException {\r
+                         /*@bgen(jjtree) connect_clause */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCONNECT_CLAUSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(39);\r
+      jj_consume_token(62);\r
+      component_reference();\r
+      jj_consume_token(71);\r
+      component_reference();\r
+      jj_consume_token(63);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+/*** Expressions ***************************************************/\r
+  final public void expr() throws ParseException {\r
+               /*@bgen(jjtree) expr */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXPR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 33:\r
+      case 35:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        simple_expression();\r
+        jj_consume_token(0);\r
+        break;\r
+      case 31:\r
+        jj_consume_token(31);\r
+        expression();\r
+        jj_consume_token(28);\r
+        expression();\r
+        label_28:\r
+        while (true) {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 20:\r
+            ;\r
+            break;\r
+          default:\r
+            jj_la1[90] = jj_gen;\r
+            break label_28;\r
+          }\r
+          jj_consume_token(20);\r
+          expression();\r
+          jj_consume_token(28);\r
+          expression();\r
+        }\r
+        jj_consume_token(15);\r
+        expression();\r
+        jj_consume_token(0);\r
+        break;\r
+      default:\r
+        jj_la1[91] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void if_expression() throws ParseException {\r
+                        /*@bgen(jjtree) if_expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTIF_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(31);\r
+      expression();\r
+      jj_consume_token(28);\r
+      expression();\r
+      label_29:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 20:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[92] = jj_gen;\r
+          break label_29;\r
+        }\r
+        jj_consume_token(20);\r
+        expression();\r
+        jj_consume_token(28);\r
+        expression();\r
+      }\r
+      jj_consume_token(15);\r
+      expression();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void expression() throws ParseException {\r
+                     /*@bgen(jjtree) expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 33:\r
+      case 35:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        simple_expression();\r
+        break;\r
+      case 31:\r
+        if_expression();\r
+        break;\r
+      default:\r
+        jj_la1[93] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void simple_expression() throws ParseException {\r
+                            /*@bgen(jjtree) simple_expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSIMPLE_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      logical_expression();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        jj_consume_token(69);\r
+        logical_expression();\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 69:\r
+          jj_consume_token(69);\r
+          logical_expression();\r
+          break;\r
+        default:\r
+          jj_la1[94] = jj_gen;\r
+          ;\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[95] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void logical_expression() throws ParseException {\r
+                             /*@bgen(jjtree) logical_expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTLOGICAL_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      logical_term();\r
+      label_30:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 22:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[96] = jj_gen;\r
+          break label_30;\r
+        }\r
+        jj_consume_token(22);\r
+        logical_term();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void logical_term() throws ParseException {\r
+                       /*@bgen(jjtree) logical_term */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTLOGICAL_TERM);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      logical_factor();\r
+      label_31:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 9:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[97] = jj_gen;\r
+          break label_31;\r
+        }\r
+        jj_consume_token(9);\r
+        logical_factor();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void logical_factor() throws ParseException {\r
+                         /*@bgen(jjtree) logical_factor */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTLOGICAL_FACTOR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 12:\r
+        jj_consume_token(12);\r
+        break;\r
+      default:\r
+        jj_la1[98] = jj_gen;\r
+        ;\r
+      }\r
+      relation();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void relation() throws ParseException {\r
+                   /*@bgen(jjtree) relation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTRELATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      arithmetic_expression();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 72:\r
+      case 73:\r
+      case 74:\r
+      case 75:\r
+      case 76:\r
+      case 77:\r
+        rel_op();\r
+        arithmetic_expression();\r
+        break;\r
+      default:\r
+        jj_la1[99] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void rel_op() throws ParseException {\r
+                 /*@bgen(jjtree) rel_op */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTREL_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 72:\r
+        jj_consume_token(72);\r
+              jjtree.closeNodeScope(jjtn000, true);\r
+              jjtc000 = false;\r
+              jjtn000.op = "< ";\r
+        break;\r
+      case 73:\r
+        jj_consume_token(73);\r
+                                           jjtree.closeNodeScope(jjtn000, true);\r
+                                           jjtc000 = false;\r
+                                           jjtn000.op = "<=";\r
+        break;\r
+      case 74:\r
+        jj_consume_token(74);\r
+                                                                       jjtree.closeNodeScope(jjtn000, true);\r
+                                                                       jjtc000 = false;\r
+                                                                       jjtn000.op = " >";\r
+        break;\r
+      case 75:\r
+        jj_consume_token(75);\r
+                                                                                                    jjtree.closeNodeScope(jjtn000, true);\r
+                                                                                                    jjtc000 = false;\r
+                                                                                                    jjtn000.op = " >=";\r
+        break;\r
+      case 76:\r
+        jj_consume_token(76);\r
+                                                                                                                                  jjtree.closeNodeScope(jjtn000, true);\r
+                                                                                                                                  jjtc000 = false;\r
+                                                                                                                                  jjtn000.op = "==";\r
+        break;\r
+      case 77:\r
+        jj_consume_token(77);\r
+                                                                                                                                                               jjtree.closeNodeScope(jjtn000, true);\r
+                                                                                                                                                               jjtc000 = false;\r
+                                                                                                                                                               jjtn000.op = "<>";\r
+        break;\r
+      default:\r
+        jj_la1[100] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void arithmetic_expression() throws ParseException {\r
+                                /*@bgen(jjtree) arithmetic_expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARITHMETIC_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+        add_op();\r
+        break;\r
+      default:\r
+        jj_la1[101] = jj_gen;\r
+        ;\r
+      }\r
+      term();\r
+      label_32:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 78:\r
+        case 79:\r
+        case 80:\r
+        case 81:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[102] = jj_gen;\r
+          break label_32;\r
+        }\r
+        add_op();\r
+        term();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void add_op() throws ParseException {\r
+                 /*@bgen(jjtree) add_op */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTADD_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 78:\r
+        jj_consume_token(78);\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+          jjtn000.op = "+";\r
+        break;\r
+      case 79:\r
+        jj_consume_token(79);\r
+                                     jjtree.closeNodeScope(jjtn000, true);\r
+                                     jjtc000 = false;\r
+                                     jjtn000.op = "-";\r
+        break;\r
+      case 80:\r
+        jj_consume_token(80);\r
+        break;\r
+      case 81:\r
+        jj_consume_token(81);\r
+        break;\r
+      default:\r
+        jj_la1[103] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void term() throws ParseException {\r
+               /*@bgen(jjtree) term */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTTERM);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      factor();\r
+      label_33:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 82:\r
+        case 83:\r
+        case 84:\r
+        case 85:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[104] = jj_gen;\r
+          break label_33;\r
+        }\r
+        mul_op();\r
+        factor();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void mul_op() throws ParseException {\r
+                 /*@bgen(jjtree) mul_op */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTMUL_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 82:\r
+        jj_consume_token(82);\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+          jjtn000.op = "*";\r
+        break;\r
+      case 83:\r
+        jj_consume_token(83);\r
+                                     jjtree.closeNodeScope(jjtn000, true);\r
+                                     jjtc000 = false;\r
+                                     jjtn000.op = "/";\r
+        break;\r
+      case 84:\r
+        jj_consume_token(84);\r
+                                                                 jjtree.closeNodeScope(jjtn000, true);\r
+                                                                 jjtc000 = false;\r
+                                                                 jjtn000.op = ".*";\r
+        break;\r
+      case 85:\r
+        jj_consume_token(85);\r
+                                                                                               jjtree.closeNodeScope(jjtn000, true);\r
+                                                                                               jjtc000 = false;\r
+                                                                                               jjtn000.op = "./";\r
+        break;\r
+      default:\r
+        jj_la1[105] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void factor() throws ParseException {\r
+                 /*@bgen(jjtree) factor */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFACTOR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      primary();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 86:\r
+      case 87:\r
+        factor_op();\r
+        primary();\r
+        break;\r
+      default:\r
+        jj_la1[106] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void factor_op() throws ParseException {\r
+                    /*@bgen(jjtree) factor_op */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFACTOR_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 86:\r
+        jj_consume_token(86);\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+          jjtn000.op = "^";\r
+        break;\r
+      case 87:\r
+        jj_consume_token(87);\r
+                                      jjtree.closeNodeScope(jjtn000, true);\r
+                                      jjtc000 = false;\r
+                                      jjtn000.op = ".^";\r
+        break;\r
+      default:\r
+        jj_la1[107] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void der_initial() throws ParseException {\r
+                      /*@bgen(jjtree) der_initial */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTDER_INITIAL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+      case IDENT:\r
+        name();\r
+               jjtn000.op = "application";\r
+        break;\r
+      case 58:\r
+        jj_consume_token(58);\r
+                                                      jjtn000.op = "der";\r
+        break;\r
+      case 46:\r
+        jj_consume_token(46);\r
+                                                                                        jjtn000.op = "initial";\r
+        break;\r
+      default:\r
+        jj_la1[108] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      function_call_args();\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void subscript_2() throws ParseException {\r
+                      /*@bgen(jjtree) subscript_2 */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSUBSCRIPT_2);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      expression_list();\r
+      label_34:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 70:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[109] = jj_gen;\r
+          break label_34;\r
+        }\r
+        jj_consume_token(70);\r
+        expression_list();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void array() throws ParseException {\r
+                /*@bgen(jjtree) array */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARRAY);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(64);\r
+      function_arguments();\r
+      jj_consume_token(65);\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void primary() throws ParseException {\r
+                  /*@bgen(jjtree) primary */\r
+                   SimpleNode jjtn000 = new SimpleNode(JJTPRIMARY);\r
+                   boolean jjtc000 = true;\r
+                   jjtree.openNodeScope(jjtn000);Token t;\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case UNSIGNED_NUMBER:\r
+        t = jj_consume_token(UNSIGNED_NUMBER);\r
+                               jjtree.closeNodeScope(jjtn000, true);\r
+                               jjtc000 = false;\r
+                               jjtn000.op = token.image;\r
+        break;\r
+      case UNSIGNED_INTEGER:\r
+        t = jj_consume_token(UNSIGNED_INTEGER);\r
+                            jjtree.closeNodeScope(jjtn000, true);\r
+                            jjtc000 = false;\r
+                            jjtn000.op = token.image;\r
+        break;\r
+      case STRING:\r
+        t = jj_consume_token(STRING);\r
+                  jjtree.closeNodeScope(jjtn000, true);\r
+                  jjtc000 = false;\r
+                  jjtn000.op = token.image;\r
+        break;\r
+      case 6:\r
+        t = jj_consume_token(6);\r
+                 jjtree.closeNodeScope(jjtn000, true);\r
+                 jjtc000 = false;\r
+                 jjtn000.op = token.image;\r
+        break;\r
+      case 33:\r
+        t = jj_consume_token(33);\r
+               jjtree.closeNodeScope(jjtn000, true);\r
+               jjtc000 = false;\r
+               jjtn000.op = token.image;\r
+        break;\r
+      default:\r
+        jj_la1[110] = jj_gen;\r
+        if (jj_2_9(2147483647)) {\r
+          der_initial();\r
+        } else {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 68:\r
+          case IDENT:\r
+            component_reference();\r
+            break;\r
+          case 62:\r
+            jj_consume_token(62);\r
+            expression();\r
+            jj_consume_token(63);\r
+            break;\r
+          case 66:\r
+            jj_consume_token(66);\r
+            subscript_2();\r
+            jj_consume_token(67);\r
+            break;\r
+          case 64:\r
+            array();\r
+            break;\r
+          case 35:\r
+            jj_consume_token(35);\r
+            break;\r
+          default:\r
+            jj_la1[111] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public String name() throws ParseException {\r
+                 /*@bgen(jjtree) name */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTNAME);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);String ret = new String("");\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+        jj_consume_token(68);\r
+                ret += ".";\r
+        break;\r
+      default:\r
+        jj_la1[112] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(IDENT);\r
+                     ret += token.image; jjtn000.op = token.image;\r
+      label_35:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 68:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[113] = jj_gen;\r
+          break label_35;\r
+        }\r
+        jj_consume_token(68);\r
+                   ret += ".";\r
+        jj_consume_token(IDENT);\r
+                     ret += token.image; jjtn000.op = token.image;\r
+      }\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        {if (true) return ret;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void component_reference() throws ParseException {\r
+                              /*@bgen(jjtree) component_reference */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_REFERENCE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);Token t;\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+        jj_consume_token(68);\r
+        break;\r
+      default:\r
+        jj_la1[114] = jj_gen;\r
+        ;\r
+      }\r
+      t = jj_consume_token(IDENT);\r
+                             jjtn000.op = t.image;\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 66:\r
+        array_subscripts();\r
+        break;\r
+      default:\r
+        jj_la1[115] = jj_gen;\r
+        ;\r
+      }\r
+      label_36:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 68:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[116] = jj_gen;\r
+          break label_36;\r
+        }\r
+        jj_consume_token(68);\r
+        jj_consume_token(IDENT);\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 66:\r
+          array_subscripts();\r
+          break;\r
+        default:\r
+          jj_la1[117] = jj_gen;\r
+          ;\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void function_call_args() throws ParseException {\r
+                             /*@bgen(jjtree) function_call_args */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFUNCTION_CALL_ARGS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(62);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        function_arguments();\r
+        break;\r
+      default:\r
+        jj_la1[118] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(63);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void function_arguments() throws ParseException {\r
+                             /*@bgen(jjtree) function_arguments */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFUNCTION_ARGUMENTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      if (jj_2_10(2)) {\r
+        expression();\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 21:\r
+        case 71:\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 71:\r
+            jj_consume_token(71);\r
+            function_arguments();\r
+            break;\r
+          case 21:\r
+            jj_consume_token(21);\r
+            for_indices();\r
+                                                                                      jjtn000.op = "for";\r
+            break;\r
+          default:\r
+            jj_la1[119] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+          break;\r
+        default:\r
+          jj_la1[120] = jj_gen;\r
+          ;\r
+        }\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case IDENT:\r
+          named_arguments();\r
+          break;\r
+        default:\r
+          jj_la1[121] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+           if (jjtc000) {\r
+             jjtree.clearNodeScope(jjtn000);\r
+             jjtc000 = false;\r
+           } else {\r
+             jjtree.popNode();\r
+           }\r
+           if (jjte000 instanceof RuntimeException) {\r
+             {if (true) throw (RuntimeException)jjte000;}\r
+           }\r
+           if (jjte000 instanceof ParseException) {\r
+             {if (true) throw (ParseException)jjte000;}\r
+           }\r
+           {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+           if (jjtc000) {\r
+             jjtree.closeNodeScope(jjtn000, true);\r
+           }\r
+    }\r
+  }\r
+\r
+  final public void named_arguments() throws ParseException {\r
+                          /*@bgen(jjtree) named_arguments */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTNAMED_ARGUMENTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      named_argument();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        jj_consume_token(71);\r
+        named_arguments();\r
+        break;\r
+      default:\r
+        jj_la1[122] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void named_argument() throws ParseException {\r
+                         /*@bgen(jjtree) named_argument */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTNAMED_ARGUMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(IDENT);\r
+      jj_consume_token(88);\r
+      expression();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void output_expression_list() throws ParseException {\r
+                                 /*@bgen(jjtree) output_expression_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTOUTPUT_EXPRESSION_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        expression();\r
+        break;\r
+      default:\r
+        jj_la1[123] = jj_gen;\r
+        ;\r
+      }\r
+      label_37:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[124] = jj_gen;\r
+          break label_37;\r
+        }\r
+        jj_consume_token(71);\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 46:\r
+        case 58:\r
+        case 62:\r
+        case 64:\r
+        case 66:\r
+        case 68:\r
+        case 78:\r
+        case 79:\r
+        case 80:\r
+        case 81:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          expression();\r
+          break;\r
+        default:\r
+          jj_la1[125] = jj_gen;\r
+          ;\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void expression_list() throws ParseException {\r
+                          /*@bgen(jjtree) expression_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXPRESSION_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      expression();\r
+      label_38:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[126] = jj_gen;\r
+          break label_38;\r
+        }\r
+        jj_consume_token(71);\r
+        expression();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void array_subscripts() throws ParseException {\r
+                           /*@bgen(jjtree) array_subscripts */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARRAY_SUBSCRIPTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(66);\r
+      subscript();\r
+      label_39:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[127] = jj_gen;\r
+          break label_39;\r
+        }\r
+        jj_consume_token(71);\r
+        subscript();\r
+      }\r
+      jj_consume_token(67);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void subscript() throws ParseException {\r
+                    /*@bgen(jjtree) subscript */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSUBSCRIPT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        jj_consume_token(69);\r
+              jjtree.closeNodeScope(jjtn000, true);\r
+              jjtc000 = false;\r
+              jjtn000.op = "all";\r
+        break;\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        expression();\r
+        break;\r
+      default:\r
+        jj_la1[128] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  final public String comment() throws ParseException {\r
+    String ret;\r
+    // string_comment [ annotation ]\r
+            ret = string_comment();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 14:\r
+      annotation();\r
+      break;\r
+    default:\r
+      jj_la1[129] = jj_gen;\r
+      ;\r
+    }\r
+            {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public String string_comment() throws ParseException {\r
+    String ret = null;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case STRING:\r
+      jj_consume_token(STRING);\r
+                     ret = new String(token.image);\r
+      label_40:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 78:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[130] = jj_gen;\r
+          break label_40;\r
+        }\r
+        jj_consume_token(78);\r
+                    ret += "+";\r
+        jj_consume_token(STRING);\r
+                           ret += token.image;\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[131] = jj_gen;\r
+      ;\r
+    }\r
+            {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void annotation() throws ParseException {\r
+                     /*@bgen(jjtree) annotation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTANNOTATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+    try {\r
+      jj_consume_token(14);\r
+      class_modification();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+    }\r
+  }\r
+\r
+  private boolean jj_2_1(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_1(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(0, xla); }\r
+  }\r
+\r
+  private boolean jj_2_2(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_2(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(1, xla); }\r
+  }\r
+\r
+  private boolean jj_2_3(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_3(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(2, xla); }\r
+  }\r
+\r
+  private boolean jj_2_4(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_4(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(3, xla); }\r
+  }\r
+\r
+  private boolean jj_2_5(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_5(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(4, xla); }\r
+  }\r
+\r
+  private boolean jj_2_6(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_6(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(5, xla); }\r
+  }\r
+\r
+  private boolean jj_2_7(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_7(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(6, xla); }\r
+  }\r
+\r
+  private boolean jj_2_8(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_8(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(7, xla); }\r
+  }\r
+\r
+  private boolean jj_2_9(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_9(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(8, xla); }\r
+  }\r
+\r
+  private boolean jj_2_10(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_10(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(9, xla); }\r
+  }\r
+\r
+  private boolean jj_3R_74() {\r
+    if (jj_scan_token(62)) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_166()) jj_scanpos = xsp;\r
+    if (jj_scan_token(63)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_129() {\r
+    if (jj_scan_token(49)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_124() {\r
+    if (jj_scan_token(75)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_153() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(68)) jj_scanpos = xsp;\r
+    if (jj_scan_token(IDENT)) return true;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_161()) jj_scanpos = xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_162()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_78() {\r
+    if (jj_scan_token(68)) return true;\r
+    if (jj_scan_token(IDENT)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_159() {\r
+    if (jj_scan_token(58)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_77() {\r
+    if (jj_scan_token(68)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_150() {\r
+    if (jj_scan_token(84)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_60() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_77()) jj_scanpos = xsp;\r
+    if (jj_scan_token(IDENT)) return true;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_78()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_46() {\r
+    if (jj_3R_60()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_9() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_46()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(58)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(46)) return true;\r
+    }\r
+    }\r
+    if (jj_scan_token(62)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_123() {\r
+    if (jj_scan_token(74)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_146() {\r
+    if (jj_3R_155()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_164() {\r
+    if (jj_scan_token(70)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_145() {\r
+    if (jj_scan_token(66)) return true;\r
+    if (jj_3R_154()) return true;\r
+    if (jj_scan_token(67)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_144() {\r
+    if (jj_scan_token(62)) return true;\r
+    if (jj_3R_47()) return true;\r
+    if (jj_scan_token(63)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_142() {\r
+    if (jj_3R_152()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_157() {\r
+    if (jj_scan_token(87)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_143() {\r
+    if (jj_3R_153()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_134() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_137()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_138()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_139()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_140()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_141()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_142()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_143()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_144()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_145()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_146()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(35)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_137() {\r
+    if (jj_scan_token(UNSIGNED_NUMBER)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_141() {\r
+    if (jj_scan_token(33)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_140() {\r
+    if (jj_scan_token(6)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_139() {\r
+    if (jj_scan_token(STRING)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_138() {\r
+    if (jj_scan_token(UNSIGNED_INTEGER)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_149() {\r
+    if (jj_scan_token(83)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_128() {\r
+    if (jj_scan_token(42)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_155() {\r
+    if (jj_scan_token(64)) return true;\r
+    if (jj_3R_165()) return true;\r
+    if (jj_scan_token(65)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_135() {\r
+    if (jj_3R_147()) return true;\r
+    if (jj_3R_134()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_154() {\r
+    if (jj_3R_163()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_164()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_158() {\r
+    if (jj_3R_60()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_133() {\r
+    if (jj_scan_token(79)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_152() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_158()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_159()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_160()) return true;\r
+    }\r
+    }\r
+    if (jj_3R_74()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_122() {\r
+    if (jj_scan_token(73)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_147() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_156()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_157()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_156() {\r
+    if (jj_scan_token(86)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_119() {\r
+    if (jj_3R_134()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_135()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_120() {\r
+    if (jj_3R_136()) return true;\r
+    if (jj_3R_119()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_104() {\r
+    if (jj_3R_114()) return true;\r
+    if (jj_3R_103()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_113() {\r
+    if (jj_3R_118()) return true;\r
+    if (jj_3R_112()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_136() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_148()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_149()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_150()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_151()) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_148() {\r
+    if (jj_scan_token(82)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_110() {\r
+    if (jj_3R_60()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_112() {\r
+    if (jj_3R_119()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_120()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_131() {\r
+    if (jj_scan_token(56)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_118() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_132()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_133()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(80)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(81)) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_132() {\r
+    if (jj_scan_token(78)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_97() {\r
+    if (jj_scan_token(9)) return true;\r
+    if (jj_3R_96()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_117() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_130()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_131()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_130() {\r
+    if (jj_scan_token(32)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_111() {\r
+    if (jj_3R_118()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_116() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_127()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_128()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_129()) return true;\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_127() {\r
+    if (jj_scan_token(5)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_103() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_111()) jj_scanpos = xsp;\r
+    if (jj_3R_112()) return true;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_113()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_115() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(16)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(23)) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_114() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_121()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_122()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_123()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_124()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_125()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_126()) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_121() {\r
+    if (jj_scan_token(72)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_76() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_75()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_87() {\r
+    if (jj_scan_token(22)) return true;\r
+    if (jj_3R_86()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_109() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_115()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_116()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_117()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_100() {\r
+    if (jj_3R_103()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_104()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_67() {\r
+    if (jj_3R_81()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_62() {\r
+    if (jj_3R_79()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_96() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(12)) jj_scanpos = xsp;\r
+    if (jj_3R_100()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_86() {\r
+    if (jj_3R_96()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_97()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_92() {\r
+    if (jj_scan_token(27)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_75() {\r
+    if (jj_3R_86()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_87()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_59() {\r
+    if (jj_3R_75()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_76()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_66() {\r
+    if (jj_3R_80()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_102() {\r
+    if (jj_3R_109()) return true;\r
+    if (jj_3R_110()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_47() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_61()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_62()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_61() {\r
+    if (jj_3R_59()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_99() {\r
+    if (jj_3R_102()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_79() {\r
+    if (jj_scan_token(31)) return true;\r
+    if (jj_3R_47()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_6() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_90() {\r
+    if (jj_scan_token(55)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_89() {\r
+    if (jj_scan_token(36)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_72() {\r
+    if (jj_scan_token(39)) return true;\r
+    if (jj_scan_token(62)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_94() {\r
+    if (jj_scan_token(13)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_98() {\r
+    if (jj_3R_101()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_65() {\r
+    if (jj_scan_token(52)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_93() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_98()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_99()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_91() {\r
+    if (jj_scan_token(51)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_107() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(50)) jj_scanpos = xsp;\r
+    if (jj_scan_token(44)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_84() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(8)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(11)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_91()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_92()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_93()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_94()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_83() {\r
+    if (jj_3R_90()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_82() {\r
+    if (jj_3R_89()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_69() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_82()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_83()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_84()) return true;\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_53() {\r
+    if (jj_3R_69()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_43() {\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_53()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_73() {\r
+    if (jj_scan_token(43)) return true;\r
+    if (jj_3R_47()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_52() {\r
+    if (jj_3R_68()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_51() {\r
+    if (jj_scan_token(59)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_5() {\r
+    if (jj_scan_token(57)) return true;\r
+    if (jj_3R_43()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_50() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3_5()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_65()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_66()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_67()) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_95() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_85() {\r
+    if (jj_3R_95()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_42() {\r
+    if (jj_3R_43()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_50()) { jj_scanpos = xsp; break; }\r
+    }\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_51()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_52()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_106() {\r
+    if (jj_scan_token(7)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_71() {\r
+    if (jj_scan_token(21)) return true;\r
+    if (jj_3R_85()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_4() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    if (jj_scan_token(40)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_3() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    if (jj_scan_token(58)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_2() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_1() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_3R_41()) return true;\r
+    if (jj_3R_42()) return true;\r
+    if (jj_scan_token(35)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_108() {\r
+    if (jj_scan_token(26)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_105() {\r
+    if (jj_scan_token(34)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_101() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(30)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(47)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_105()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_106()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(61)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(24)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_107()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(38)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(37)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_108()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(17)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(95)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(96)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_70() {\r
+    if (jj_scan_token(31)) return true;\r
+    if (jj_3R_47()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_7() {\r
+    if (jj_3R_44()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_58() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_3R_74()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_57() {\r
+    if (jj_3R_73()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_56() {\r
+    if (jj_3R_72()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_55() {\r
+    if (jj_3R_71()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_54() {\r
+    if (jj_3R_70()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_8() {\r
+    if (jj_3R_45()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_173() {\r
+    if (jj_3R_47()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_68() {\r
+    if (jj_scan_token(14)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_44() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3_8()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_54()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_55()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_56()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_57()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_58()) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_162() {\r
+    if (jj_scan_token(68)) return true;\r
+    if (jj_scan_token(IDENT)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_64() {\r
+    if (jj_scan_token(21)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_49() {\r
+    if (jj_scan_token(STRING)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_41() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_49()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_81() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(46)) jj_scanpos = xsp;\r
+    if (jj_scan_token(4)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_45() {\r
+    if (jj_3R_59()) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    if (jj_3R_47()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_126() {\r
+    if (jj_scan_token(77)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_88() {\r
+    if (jj_scan_token(46)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_80() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_88()) jj_scanpos = xsp;\r
+    if (jj_scan_token(45)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_172() {\r
+    if (jj_scan_token(69)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_168() {\r
+    if (jj_scan_token(71)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_170() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_172()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_173()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_161() {\r
+    if (jj_3R_167()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_48() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_63()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_64()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_63() {\r
+    if (jj_scan_token(71)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_167() {\r
+    if (jj_scan_token(66)) return true;\r
+    if (jj_3R_170()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_125() {\r
+    if (jj_scan_token(76)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_163() {\r
+    if (jj_3R_47()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_168()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_174() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_160() {\r
+    if (jj_scan_token(46)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_171() {\r
+    if (jj_3R_174()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_151() {\r
+    if (jj_scan_token(85)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_169() {\r
+    if (jj_3R_171()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_10() {\r
+    if (jj_3R_47()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_48()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_165() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3_10()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_169()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_166() {\r
+    if (jj_3R_165()) return true;\r
+    return false;\r
+  }\r
+\r
+  /** Generated Token Manager. */\r
+  public ModelParserTokenManager token_source;\r
+  SimpleCharStream jj_input_stream;\r
+  /** Current token. */\r
+  public Token token;\r
+  /** Next token. */\r
+  public Token jj_nt;\r
+  private int jj_ntk;\r
+  private Token jj_scanpos, jj_lastpos;\r
+  private int jj_la;\r
+  private int jj_gen;\r
+  final private int[] jj_la1 = new int[132];\r
+  static private int[] jj_la1_0;\r
+  static private int[] jj_la1_1;\r
+  static private int[] jj_la1_2;\r
+  static private int[] jj_la1_3;\r
+  static {\r
+      jj_la1_init_0();\r
+      jj_la1_init_1();\r
+      jj_la1_init_2();\r
+      jj_la1_init_3();\r
+   }\r
+   private static void jj_la1_init_0() {\r
+      jj_la1_0 = new int[] {0x0,0x0,0x45020880,0x800,0x40000000,0x0,0x0,0x5020080,0x0,0x0,0x0,0x0,0x0,0x10,0x10,0x0,0x0,0x4000,0x0,0x4000,0x0,0x80001040,0x4d8329a0,0x100,0x800,0x0,0x8000000,0x458300a0,0x458300a0,0x0,0x458320a0,0x4d8329a0,0x0,0x0,0x0,0x4000,0x0,0x0,0x810000,0x810000,0x20,0x20,0x0,0x0,0x0,0x80000000,0x0,0x0,0x0,0x0,0x2d00,0x0,0x2d00,0x400,0x800,0x2000,0x0,0x400,0x800,0x458300a0,0x458320a0,0x458300a0,0x0,0x0,0x0,0xa0240000,0x80200000,0x0,0xa0240000,0x80201040,0x100000,0x80201040,0x80201040,0x8000,0xa0240000,0x100000,0xa0240000,0xa0240000,0x8000,0x80201040,0xa0240000,0x0,0x0,0xa0240000,0x80201040,0x2000000,0x80201040,0xa0240000,0x2000000,0xa0240000,0x100000,0x80001040,0x100000,0x80001040,0x0,0x0,0x400000,0x200,0x1000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80001040,0x200000,0x200000,0x0,0x0,0x80001040,0x0,0x80001040,0x0,0x0,0x80001040,0x4000,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_1() {\r
+      jj_la1_1 = new int[] {0x0,0x200000,0x20049064,0x0,0x0,0x8000,0x40000,0x20041064,0x0,0x40000000,0x0,0x0,0x0,0x2106000,0x106000,0x0,0x0,0x0,0x8000000,0x0,0x0,0x4400400a,0x218e9475,0x0,0x0,0x80000,0x0,0x21069465,0x21069465,0x400000,0x21069465,0x218e9475,0x0,0x0,0x40000000,0x0,0x40000000,0x0,0x0,0x0,0x20400,0x20400,0x1000001,0x1000001,0x0,0x0,0x0,0x40000000,0x0,0x40000000,0x0,0x0,0x0,0x0,0x0,0x0,0x40000000,0x0,0x0,0x21069465,0x21069465,0x21069465,0x400000,0x4000,0x4000,0x40010800,0x880,0x40000000,0x40010800,0x4400488a,0x0,0x4400488a,0x4400488a,0x0,0x40010800,0x0,0x40010800,0x40010800,0x0,0x4400488a,0x40010800,0x0,0x200,0x40010800,0x4400488a,0x0,0x4400488a,0x40010800,0x0,0x40010800,0x0,0x4400400a,0x0,0x4400400a,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4004000,0x0,0x2,0x40000008,0x0,0x0,0x0,0x0,0x0,0x0,0x4400400a,0x0,0x0,0x0,0x0,0x4400400a,0x0,0x4400400a,0x0,0x0,0x4400400a,0x0,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_2() {\r
+      jj_la1_2 = new int[] {0x4000010,0x0,0x80000000,0x0,0x0,0x0,0x0,0x80000000,0x4,0x0,0x80,0x4000000,0x80,0x0,0x0,0x8000000,0x4000010,0x0,0x0,0x0,0x4000010,0x6c03c015,0x84000010,0x0,0x0,0x0,0x0,0x84000010,0x84000010,0x0,0x84000010,0x84000010,0x10,0x4000010,0x0,0x0,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x80,0x0,0x4,0x3000000,0x1000000,0x3000000,0x4000010,0x80,0x4000010,0x0,0x0,0x4000010,0x3000000,0x0,0x0,0x84000010,0x84000010,0x84000010,0x0,0x0,0x0,0x4000010,0x4000000,0x2000000,0x4000010,0x6c03c015,0x0,0x6c03c015,0x6c03c015,0x0,0x4000010,0x0,0x4000010,0x4000010,0x0,0x6c03c015,0x4000010,0x80,0x0,0x4000010,0x6c03c015,0x0,0x6c03c015,0x4000010,0x0,0x4000010,0x0,0x6c03c015,0x0,0x6c03c015,0x20,0x20,0x0,0x0,0x0,0x3f00,0x3f00,0x3c000,0x3c000,0x3c000,0x3c0000,0x3c0000,0xc00000,0xc00000,0x4000010,0x40,0x68000000,0x4000015,0x10,0x10,0x10,0x4,0x10,0x4,0x6c03c015,0x80,0x80,0x4000000,0x80,0x6c03c015,0x80,0x6c03c015,0x80,0x80,0x6c03c035,0x0,0x4000,0x8000000,};\r
+   }\r
+   private static void jj_la1_init_3() {\r
+      jj_la1_3 = new int[] {0x0,0x0,0x1,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,0x1,0x1,0x0,0x1,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0x1,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,};\r
+   }\r
+  final private JJCalls[] jj_2_rtns = new JJCalls[10];\r
+  private boolean jj_rescan = false;\r
+  private int jj_gc = 0;\r
+\r
+  /** Constructor with InputStream. */\r
+  public ModelParser(java.io.InputStream stream) {\r
+     this(stream, null);\r
+  }\r
+  /** Constructor with InputStream and supplied encoding */\r
+  public ModelParser(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source = new ModelParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 132; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream) {\r
+     ReInit(stream, null);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jjtree.reset();\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 132; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Constructor. */\r
+  public ModelParser(java.io.Reader stream) {\r
+    jj_input_stream = new SimpleCharStream(stream, 1, 1);\r
+    token_source = new ModelParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 132; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader stream) {\r
+    jj_input_stream.ReInit(stream, 1, 1);\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jjtree.reset();\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 132; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Constructor with generated Token Manager. */\r
+  public ModelParser(ModelParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 132; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(ModelParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jjtree.reset();\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 132; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  private Token jj_consume_token(int kind) throws ParseException {\r
+    Token oldToken;\r
+    if ((oldToken = token).next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    if (token.kind == kind) {\r
+      jj_gen++;\r
+      if (++jj_gc > 100) {\r
+        jj_gc = 0;\r
+        for (int i = 0; i < jj_2_rtns.length; i++) {\r
+          JJCalls c = jj_2_rtns[i];\r
+          while (c != null) {\r
+            if (c.gen < jj_gen) c.first = null;\r
+            c = c.next;\r
+          }\r
+        }\r
+      }\r
+      return token;\r
+    }\r
+    token = oldToken;\r
+    jj_kind = kind;\r
+    throw generateParseException();\r
+  }\r
+\r
+  static private final class LookaheadSuccess extends java.lang.Error { }\r
+  final private LookaheadSuccess jj_ls = new LookaheadSuccess();\r
+  private boolean jj_scan_token(int kind) {\r
+    if (jj_scanpos == jj_lastpos) {\r
+      jj_la--;\r
+      if (jj_scanpos.next == null) {\r
+        jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();\r
+      } else {\r
+        jj_lastpos = jj_scanpos = jj_scanpos.next;\r
+      }\r
+    } else {\r
+      jj_scanpos = jj_scanpos.next;\r
+    }\r
+    if (jj_rescan) {\r
+      int i = 0; Token tok = token;\r
+      while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }\r
+      if (tok != null) jj_add_error_token(kind, i);\r
+    }\r
+    if (jj_scanpos.kind != kind) return true;\r
+    if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;\r
+    return false;\r
+  }\r
+\r
+\r
+/** Get the next Token. */\r
+  final public Token getNextToken() {\r
+    if (token.next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    jj_gen++;\r
+    return token;\r
+  }\r
+\r
+/** Get the specific Token. */\r
+  final public Token getToken(int index) {\r
+    Token t = token;\r
+    for (int i = 0; i < index; i++) {\r
+      if (t.next != null) t = t.next;\r
+      else t = t.next = token_source.getNextToken();\r
+    }\r
+    return t;\r
+  }\r
+\r
+  private int jj_ntk() {\r
+    if ((jj_nt=token.next) == null)\r
+      return (jj_ntk = (token.next=token_source.getNextToken()).kind);\r
+    else\r
+      return (jj_ntk = jj_nt.kind);\r
+  }\r
+\r
+  private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();\r
+  private int[] jj_expentry;\r
+  private int jj_kind = -1;\r
+  private int[] jj_lasttokens = new int[100];\r
+  private int jj_endpos;\r
+\r
+  private void jj_add_error_token(int kind, int pos) {\r
+    if (pos >= 100) return;\r
+    if (pos == jj_endpos + 1) {\r
+      jj_lasttokens[jj_endpos++] = kind;\r
+    } else if (jj_endpos != 0) {\r
+      jj_expentry = new int[jj_endpos];\r
+      for (int i = 0; i < jj_endpos; i++) {\r
+        jj_expentry[i] = jj_lasttokens[i];\r
+      }\r
+      jj_entries_loop: for (java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();) {\r
+        int[] oldentry = (int[])(it.next());\r
+        if (oldentry.length == jj_expentry.length) {\r
+          for (int i = 0; i < jj_expentry.length; i++) {\r
+            if (oldentry[i] != jj_expentry[i]) {\r
+              continue jj_entries_loop;\r
+            }\r
+          }\r
+          jj_expentries.add(jj_expentry);\r
+          break jj_entries_loop;\r
+        }\r
+      }\r
+      if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;\r
+    }\r
+  }\r
+\r
+  /** Generate ParseException. */\r
+  public ParseException generateParseException() {\r
+    jj_expentries.clear();\r
+    boolean[] la1tokens = new boolean[97];\r
+    if (jj_kind >= 0) {\r
+      la1tokens[jj_kind] = true;\r
+      jj_kind = -1;\r
+    }\r
+    for (int i = 0; i < 132; i++) {\r
+      if (jj_la1[i] == jj_gen) {\r
+        for (int j = 0; j < 32; j++) {\r
+          if ((jj_la1_0[i] & (1<<j)) != 0) {\r
+            la1tokens[j] = true;\r
+          }\r
+          if ((jj_la1_1[i] & (1<<j)) != 0) {\r
+            la1tokens[32+j] = true;\r
+          }\r
+          if ((jj_la1_2[i] & (1<<j)) != 0) {\r
+            la1tokens[64+j] = true;\r
+          }\r
+          if ((jj_la1_3[i] & (1<<j)) != 0) {\r
+            la1tokens[96+j] = true;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    for (int i = 0; i < 97; i++) {\r
+      if (la1tokens[i]) {\r
+        jj_expentry = new int[1];\r
+        jj_expentry[0] = i;\r
+        jj_expentries.add(jj_expentry);\r
+      }\r
+    }\r
+    jj_endpos = 0;\r
+    jj_rescan_token();\r
+    jj_add_error_token(0, 0);\r
+    int[][] exptokseq = new int[jj_expentries.size()][];\r
+    for (int i = 0; i < jj_expentries.size(); i++) {\r
+      exptokseq[i] = jj_expentries.get(i);\r
+    }\r
+    return new ParseException(token, exptokseq, tokenImage);\r
+  }\r
+\r
+  /** Enable tracing. */\r
+  final public void enable_tracing() {\r
+  }\r
+\r
+  /** Disable tracing. */\r
+  final public void disable_tracing() {\r
+  }\r
+\r
+  private void jj_rescan_token() {\r
+    jj_rescan = true;\r
+    for (int i = 0; i < 10; i++) {\r
+    try {\r
+      JJCalls p = jj_2_rtns[i];\r
+      do {\r
+        if (p.gen > jj_gen) {\r
+          jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;\r
+          switch (i) {\r
+            case 0: jj_3_1(); break;\r
+            case 1: jj_3_2(); break;\r
+            case 2: jj_3_3(); break;\r
+            case 3: jj_3_4(); break;\r
+            case 4: jj_3_5(); break;\r
+            case 5: jj_3_6(); break;\r
+            case 6: jj_3_7(); break;\r
+            case 7: jj_3_8(); break;\r
+            case 8: jj_3_9(); break;\r
+            case 9: jj_3_10(); break;\r
+          }\r
+        }\r
+        p = p.next;\r
+      } while (p != null);\r
+      } catch(LookaheadSuccess ls) { }\r
+    }\r
+    jj_rescan = false;\r
+  }\r
+\r
+  private void jj_save(int index, int xla) {\r
+    JJCalls p = jj_2_rtns[index];\r
+    while (p.gen > jj_gen) {\r
+      if (p.next == null) { p = p.next = new JJCalls(); break; }\r
+      p = p.next;\r
+    }\r
+    p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;\r
+  }\r
+\r
+  static final class JJCalls {\r
+    int gen;\r
+    Token first;\r
+    int arg;\r
+    JJCalls next;\r
+  }\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserConstants.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserConstants.java
new file mode 100644 (file)
index 0000000..0407262
--- /dev/null
@@ -0,0 +1,134 @@
+/* Generated By:JJTree&JavaCC: Do not edit this line. ModelParserConstants.java */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+\r
+/**\r
+ * Token literal values and constants.\r
+ * Generated by org.javacc.parser.OtherFilesGen#start()\r
+ */\r
+public interface ModelParserConstants {\r
+\r
+  /** End of File. */\r
+  int EOF = 0;\r
+  /** RegularExpression Id. */\r
+  int WHITESPACE = 1;\r
+  /** RegularExpression Id. */\r
+  int COMMENT1 = 2;\r
+  /** RegularExpression Id. */\r
+  int COMMENT2 = 3;\r
+  /** RegularExpression Id. */\r
+  int IDENT = 90;\r
+  /** RegularExpression Id. */\r
+  int STRING = 91;\r
+  /** RegularExpression Id. */\r
+  int EXP = 92;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_INTEGER = 93;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_NUMBER = 94;\r
+\r
+  /** Lexical state. */\r
+  int DEFAULT = 0;\r
+\r
+  /** Literal token values. */\r
+  String[] tokenImage = {\r
+    "<EOF>",\r
+    "<WHITESPACE>",\r
+    "<COMMENT1>",\r
+    "<COMMENT2>",\r
+    "\"algorithm\"",\r
+    "\"discrete\"",\r
+    "\"false\"",\r
+    "\"model\"",\r
+    "\"redeclare\"",\r
+    "\"and\"",\r
+    "\"each\"",\r
+    "\"final\"",\r
+    "\"not\"",\r
+    "\"replaceable\"",\r
+    "\"annotation\"",\r
+    "\"else\"",\r
+    "\"flow\"",\r
+    "\"operator\"",\r
+    "\"return\"",\r
+    "\"assert\"",\r
+    "\"elseif\"",\r
+    "\"for\"",\r
+    "\"or\"",\r
+    "\"stream\"",\r
+    "\"block\"",\r
+    "\"elsewhen\"",\r
+    "\"function\"",\r
+    "\"outer\"",\r
+    "\"then\"",\r
+    "\"break\"",\r
+    "\"encapsulated\"",\r
+    "\"if\"",\r
+    "\"output\"",\r
+    "\"true\"",\r
+    "\"class\"",\r
+    "\"end\"",\r
+    "\"import\"",\r
+    "\"package\"",\r
+    "\"type\"",\r
+    "\"connect\"",\r
+    "\"enumeration\"",\r
+    "\"in\"",\r
+    "\"parameter\"",\r
+    "\"when\"",\r
+    "\"connector\"",\r
+    "\"equation\"",\r
+    "\"initial\"",\r
+    "\"partial\"",\r
+    "\"while\"",\r
+    "\"constant\"",\r
+    "\"expandable\"",\r
+    "\"inner\"",\r
+    "\"protected\"",\r
+    "\"within\"",\r
+    "\"constrainedby\"",\r
+    "\"extends\"",\r
+    "\"input\"",\r
+    "\"public\"",\r
+    "\"der\"",\r
+    "\"external\"",\r
+    "\"loop\"",\r
+    "\"record\"",\r
+    "\"(\"",\r
+    "\")\"",\r
+    "\"{\"",\r
+    "\"}\"",\r
+    "\"[\"",\r
+    "\"]\"",\r
+    "\".\"",\r
+    "\":\"",\r
+    "\";\"",\r
+    "\",\"",\r
+    "\"<\"",\r
+    "\"<=\"",\r
+    "\">\"",\r
+    "\">=\"",\r
+    "\"==\"",\r
+    "\"<>\"",\r
+    "\"+\"",\r
+    "\"-\"",\r
+    "\".+\"",\r
+    "\".-\"",\r
+    "\"*\"",\r
+    "\"/\"",\r
+    "\".*\"",\r
+    "\"./\"",\r
+    "\"^\"",\r
+    "\".^\"",\r
+    "\"=\"",\r
+    "\":=\"",\r
+    "<IDENT>",\r
+    "<STRING>",\r
+    "<EXP>",\r
+    "<UNSIGNED_INTEGER>",\r
+    "<UNSIGNED_NUMBER>",\r
+    "\"operator function\"",\r
+    "\"operator record\"",\r
+  };\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserTokenManager.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserTokenManager.java
new file mode 100644 (file)
index 0000000..5aa460e
--- /dev/null
@@ -0,0 +1,1530 @@
+/* Generated By:JJTree&JavaCC: Do not edit this line. ModelParserTokenManager.java */\r
+package fi.semantum.sysdyn.solver.parser;\r
+import java.util.ArrayList;\r
+\r
+/** Token Manager. */\r
+public class ModelParserTokenManager implements ModelParserConstants\r
+{\r
+\r
+  /** Debug output. */\r
+  public  java.io.PrintStream debugStream = System.out;\r
+  /** Set debug output. */\r
+  public  void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }\r
+private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1)
+{\r
+   switch (pos)
+   {\r
+      case 0:\r
+         if ((active1 & 0x80000L) != 0L)\r
+            return 20;\r
+         if ((active0 & 0x377bdef7bdef7bf0L) != 0L || (active1 & 0x180000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            return 2;\r
+         }\r
+         if ((active1 & 0xb30010L) != 0L)\r
+            return 13;\r
+         if ((active0 & 0x884210842108400L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            return 44;\r
+         }\r
+         return -1;\r
+      case 1:\r
+         if ((active0 & 0x108420080400000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x3ef7bdff7fbffff0L) != 0L || (active1 & 0x180000000L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 1)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 1;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 2:\r
+         if ((active0 & 0x400000800201200L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x3bfffdf77f9fedf0L) != 0L || (active1 & 0x180000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 2;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 3:\r
+         if ((active0 & 0x1000084212118400L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x2bfff5b56d8e69f0L) != 0L || (active1 & 0x180000000L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 3)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 3;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 4:\r
+         if ((active0 & 0x1090004290008c0L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x2af6f5b1469e6130L) != 0L || (active1 & 0x180000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 4;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 5:\r
+         if ((active0 & 0x22200011009c0000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x8d6f5a046026130L) != 0L || (active1 & 0x180000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 5;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 6:\r
+         if ((active0 & 0x80d0a000000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x856250046026130L) != 0L || (active1 & 0x180000000L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 6)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 6;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 7:\r
+         if ((active0 & 0x54150040006110L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 7)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 7;\r
+            }\r
+            return 2;\r
+         }\r
+         if ((active0 & 0x802200006020020L) != 0L || (active1 & 0x180000000L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      case 8:\r
+         if ((active0 & 0x10140000000110L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x44010040006000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 8;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 9:\r
+         if ((active0 & 0x40010040002000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 9;\r
+            return 2;\r
+         }\r
+         if ((active0 & 0x4000000004000L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      case 10:\r
+         if ((active0 & 0x10000002000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x40000040000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 10;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 11:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 11;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 12:\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      default :\r
+         return -1;\r
+   }\r
+}\r
+private final int jjStartNfa_0(int pos, long active0, long active1)
+{\r
+   return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1);\r
+}\r
+private int jjStopAtPos(int pos, int kind)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   return pos + 1;\r
+}\r
+private int jjMoveStringLiteralDfa0_0()\r
+{\r
+   switch(curChar)\r
+   {\r
+      case 40:\r
+         return jjStopAtPos(0, 62);\r
+      case 41:\r
+         return jjStopAtPos(0, 63);\r
+      case 42:\r
+         return jjStopAtPos(0, 82);\r
+      case 43:\r
+         return jjStopAtPos(0, 78);\r
+      case 44:\r
+         return jjStopAtPos(0, 71);\r
+      case 45:\r
+         return jjStopAtPos(0, 79);\r
+      case 46:\r
+         jjmatchedKind = 68;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0xb30000L);\r
+      case 47:\r
+         return jjStartNfaWithStates_0(0, 83, 20);\r
+      case 58:\r
+         jjmatchedKind = 69;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x2000000L);\r
+      case 59:\r
+         return jjStopAtPos(0, 70);\r
+      case 60:\r
+         jjmatchedKind = 72;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x2200L);\r
+      case 61:\r
+         jjmatchedKind = 88;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x1000L);\r
+      case 62:\r
+         jjmatchedKind = 74;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x800L);\r
+      case 91:\r
+         return jjStopAtPos(0, 66);\r
+      case 93:\r
+         return jjStopAtPos(0, 67);\r
+      case 94:\r
+         return jjStopAtPos(0, 86);\r
+      case 97:\r
+         return jjMoveStringLiteralDfa1_0(0x84210L, 0x0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa1_0(0x21000000L, 0x0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa1_0(0x42108400000000L, 0x0L);\r
+      case 100:\r
+         return jjMoveStringLiteralDfa1_0(0x400000000000020L, 0x0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa1_0(0x884210842108400L, 0x0L);\r
+      case 102:\r
+         return jjMoveStringLiteralDfa1_0(0x4210840L, 0x0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa1_0(0x108421080000000L, 0x0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa1_0(0x1000000000000000L, 0x0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa1_0(0x80L, 0x0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa1_0(0x1000L, 0x0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa1_0(0x108420000L, 0x180000000L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa1_0(0x210842000000000L, 0x0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa1_0(0x2000000000042100L, 0x0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa1_0(0x800000L, 0x0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa1_0(0x4210000000L, 0x0L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa1_0(0x21080000000000L, 0x0L);\r
+      case 123:\r
+         return jjStopAtPos(0, 64);\r
+      case 125:\r
+         return jjStopAtPos(0, 65);\r
+      default :\r
+         return jjMoveNfa_0(0, 0);\r
+   }\r
+}\r
+private int jjMoveStringLiteralDfa1_0(long active0, long active1)\r
+{\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(0, active0, active1);\r
+      return 1;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 42:\r
+         if ((active1 & 0x100000L) != 0L)\r
+            return jjStopAtPos(1, 84);\r
+         break;\r
+      case 43:\r
+         if ((active1 & 0x10000L) != 0L)\r
+            return jjStopAtPos(1, 80);\r
+         break;\r
+      case 45:\r
+         if ((active1 & 0x20000L) != 0L)\r
+            return jjStopAtPos(1, 81);\r
+         break;\r
+      case 47:\r
+         if ((active1 & 0x200000L) != 0L)\r
+            return jjStopAtPos(1, 85);\r
+         break;\r
+      case 61:\r
+         if ((active1 & 0x200L) != 0L)\r
+            return jjStopAtPos(1, 73);\r
+         else if ((active1 & 0x800L) != 0L)\r
+            return jjStopAtPos(1, 75);\r
+         else if ((active1 & 0x1000L) != 0L)\r
+            return jjStopAtPos(1, 76);\r
+         else if ((active1 & 0x2000000L) != 0L)\r
+            return jjStopAtPos(1, 89);\r
+         break;\r
+      case 62:\r
+         if ((active1 & 0x2000L) != 0L)\r
+            return jjStopAtPos(1, 77);\r
+         break;\r
+      case 94:\r
+         if ((active1 & 0x800000L) != 0L)\r
+            return jjStopAtPos(1, 87);\r
+         break;\r
+      case 97:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x842000000440L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x2400000000042100L, active1, 0L);\r
+      case 102:\r
+         if ((active0 & 0x80000000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 31, 2);\r
+         break;\r
+      case 104:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1080010000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000000000820L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x403118010L, active1, 0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1000000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x20000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 41;\r
+            jjmatchedPos = 1;\r
+         }\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x108410840004200L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1042108000201080L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000L, active1, 0x180000000L);\r
+      case 113:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x200000000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x400000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 22, 2);\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x10000220000000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x80000L, active1, 0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x800000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000010c000000L, active1, 0L);\r
+      case 120:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x884000000000000L, active1, 0L);\r
+      case 121:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x4000000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(0, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(0, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(1, active0, active1);\r
+      return 2;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x400000000L, active1, 0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x200000000000000L, active1, 0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x2000002040000400L, active1, 0L);\r
+      case 100:\r
+         if ((active0 & 0x200L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 9, 2);\r
+         else if ((active0 & 0x800000000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 35, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x180L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x80030020000L, active1, 0x180000000L);\r
+      case 103:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x10L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x1400000000000L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x40L, active1, 0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x4a108004004800L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x1010000001010000L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x104005000002000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x200000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 21, 2);\r
+         else if ((active0 & 0x400000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 58, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x840000800000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x2188020L, active1, 0L);\r
+      case 116:\r
+         if ((active0 & 0x1000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 12, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x8a0000108040000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x210200000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(1, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa3_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(1, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(2, active0, active1);\r
+      return 3;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x4240060000800L, active1, 0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x5000020L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x8000L) != 0L)\r
+         {\r
+            jjmatchedKind = 15;\r
+            jjmatchedPos = 3;\r
+         }\r
+         else if ((active0 & 0x200000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 33, 2);\r
+         else if ((active0 & 0x4000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 38, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x88800000a980180L, active1, 0L);\r
+      case 104:\r
+         if ((active0 & 0x400L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 10, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x20000000000000L, active1, 0L);\r
+      case 107:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2000000000L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x201000000002000L, active1, 0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10000000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x10000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 28, 2);\r
+         else if ((active0 & 0x80000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 43, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x108000000000L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2000001000004010L, active1, 0L);\r
+      case 112:\r
+         if ((active0 & 0x1000000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 60, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100000000L, active1, 0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x20000L, active1, 0x180000000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x42000400000040L, active1, 0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10c00000000000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100000000040000L, active1, 0L);\r
+      case 119:\r
+         if ((active0 & 0x10000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 16, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(2, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa4_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(2, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(3, active0, active1);\r
+      return 4;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000822000L, active1, 0x180000000L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x40L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 6, 2);\r
+         else if ((active0 & 0x1000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 48, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x10118000000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x220c00000100000L, active1, 0L);\r
+      case 107:\r
+         if ((active0 & 0x1000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 24, 2);\r
+         else if ((active0 & 0x20000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 29, 2);\r
+         break;\r
+      case 108:\r
+         if ((active0 & 0x80L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 7, 2);\r
+         else if ((active0 & 0x800L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 11, 2);\r
+         break;\r
+      case 109:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L, active1, 0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x84000000000000L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x8000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 27, 2);\r
+         else if ((active0 & 0x8000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 51, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x28000010000c0030L, active1, 0L);\r
+      case 115:\r
+         if ((active0 & 0x400000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 34, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x100000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 56, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x42200004004000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100000000L, active1, 0L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(3, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa5_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(3, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(4, active0, active1);\r
+      return 5;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2c00000004000L, active1, 0L);\r
+      case 99:\r
+         if ((active0 & 0x200000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 57, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x10108000002000L, active1, 0L);\r
+      case 100:\r
+         if ((active0 & 0x2000000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 61, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x84000000000000L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000020L, active1, 0L);\r
+      case 102:\r
+         if ((active0 & 0x100000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 20, 2);\r
+         break;\r
+      case 103:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000000L, active1, 0L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x200004000010L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x100L, active1, 0L);\r
+      case 109:\r
+         if ((active0 & 0x800000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 23, 2);\r
+         break;\r
+      case 110:\r
+         if ((active0 & 0x40000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 18, 2);\r
+         else if ((active0 & 0x20000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 53, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x800000000000000L, active1, 0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40010000000000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000L, active1, 0L);\r
+      case 116:\r
+         if ((active0 & 0x80000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 19, 2);\r
+         else if ((active0 & 0x100000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 32, 2);\r
+         else if ((active0 & 0x1000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 36, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x20000L, active1, 0x180000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(4, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa6_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(4, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(5, active0, active1);\r
+      return 6;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x844010000000100L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x2000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 37, 2);\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x2002000L, active1, 0L);\r
+      case 108:\r
+         if ((active0 & 0x400000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 46, 2);\r
+         else if ((active0 & 0x800000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 47, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x2000000000000L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x200004020000L, active1, 0x180000000L);\r
+      case 115:\r
+         if ((active0 & 0x80000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 55, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x8000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 39;\r
+            jjmatchedPos = 6;\r
+         }\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x10140000004030L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x40000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(5, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa7_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(5, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(6, active0, active1);\r
+      return 7;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x2000L, active1, 0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x4000000000000L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x20L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 5, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10040000000000L, active1, 0L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x40000000004000L, active1, 0L);\r
+      case 108:\r
+         if ((active0 & 0x800000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 59, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x40000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x2000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 25, 2);\r
+         else if ((active0 & 0x4000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 26, 2);\r
+         else if ((active0 & 0x200000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 45, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100000000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x20000L) != 0L)\r
+         {\r
+            jjmatchedKind = 17;\r
+            jjmatchedPos = 7;\r
+         }\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100L, active1, 0x180000000L);\r
+      case 116:\r
+         if ((active0 & 0x2000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 49, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10000000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(6, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa8_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(6, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(7, active0, active1);\r
+      return 8;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 32:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0x180000000L);\r
+      case 97:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x40000000L, active1, 0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x2000L, active1, 0L);\r
+      case 100:\r
+         if ((active0 & 0x10000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 52, 2);\r
+         break;\r
+      case 101:\r
+         if ((active0 & 0x100L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 8, 2);\r
+         break;\r
+      case 105:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x10000000000L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x4000000000000L, active1, 0L);\r
+      case 109:\r
+         if ((active0 & 0x10L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 4, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x40000000000000L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x4000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x40000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 42, 2);\r
+         else if ((active0 & 0x100000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 44, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(7, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa9_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(7, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(8, active0, active1);\r
+      return 9;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 101:\r
+         if ((active0 & 0x4000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 50, 2);\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x40000000000000L, active1, 0L);\r
+      case 102:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x80000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x2000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x4000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 14, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x10000000000L, active1, 0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x100000000L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x40000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(8, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa10_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(8, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(9, active0, active1);\r
+      return 10;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 100:\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x40000000000000L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x2000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 13, 2);\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x40000000L, active1, 0x100000000L);\r
+      case 110:\r
+         if ((active0 & 0x10000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 40, 2);\r
+         break;\r
+      case 117:\r
+         return jjMoveStringLiteralDfa11_0(active0, 0L, active1, 0x80000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(9, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa11_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(9, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(10, active0, active1);\r
+      return 11;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 98:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0x40000000000000L, active1, 0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0L, active1, 0x100000000L);\r
+      case 100:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return jjStartNfaWithStates_0(11, 30, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0L, active1, 0x80000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(10, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa12_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(10, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(11, active0, active1);\r
+      return 12;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 99:\r
+         return jjMoveStringLiteralDfa13_0(active0, 0L, active1, 0x80000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa13_0(active0, 0L, active1, 0x100000000L);\r
+      case 121:\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(12, 54, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(11, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa13_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(11, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(12, 0L, active1);\r
+      return 13;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 114:\r
+         return jjMoveStringLiteralDfa14_0(active1, 0x100000000L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa14_0(active1, 0x80000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(12, 0L, active1);\r
+}\r
+private int jjMoveStringLiteralDfa14_0(long old1, long active1)\r
+{\r
+   if (((active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(12, 0L, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(13, 0L, active1);\r
+      return 14;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 100:\r
+         if ((active1 & 0x100000000L) != 0L)\r
+            return jjStopAtPos(14, 96);\r
+         break;\r
+      case 105:\r
+         return jjMoveStringLiteralDfa15_0(active1, 0x80000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(13, 0L, active1);\r
+}\r
+private int jjMoveStringLiteralDfa15_0(long old1, long active1)\r
+{\r
+   if (((active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(13, 0L, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(14, 0L, active1);\r
+      return 15;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 111:\r
+         return jjMoveStringLiteralDfa16_0(active1, 0x80000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(14, 0L, active1);\r
+}\r
+private int jjMoveStringLiteralDfa16_0(long old1, long active1)\r
+{\r
+   if (((active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(14, 0L, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(15, 0L, active1);\r
+      return 16;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 110:\r
+         if ((active1 & 0x80000000L) != 0L)\r
+            return jjStopAtPos(16, 95);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(15, 0L, active1);\r
+}\r
+private int jjStartNfaWithStates_0(int pos, int kind, int state)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) { return pos + 1; }\r
+   return jjMoveNfa_0(state, pos + 1);\r
+}\r
+static final long[] jjbitVec0 = {
+   0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+};\r
+private int jjMoveNfa_0(int startState, int curPos)\r
+{\r
+   int startsAt = 0;\r
+   jjnewStateCnt = 44;\r
+   int i = 1;\r
+   jjstateSet[0] = startState;\r
+   int kind = 0x7fffffff;\r
+   for (;;)\r
+   {\r
+      if (++jjround == 0x7fffffff)\r
+         ReInitRounds();\r
+      if (curChar < 64)\r
+      {\r
+         long l = 1L << curChar;\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 0:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 93)\r
+                        kind = 93;\r
+                     jjCheckNAddStates(0, 6);\r
+                  }\r
+                  else if ((0x100002600L & l) != 0L)\r
+                  {\r
+                     if (kind > 1)\r
+                        kind = 1;\r
+                  }\r
+                  else if (curChar == 47)\r
+                     jjAddStates(7, 8);\r
+                  else if (curChar == 46)\r
+                     jjCheckNAdd(13);\r
+                  else if (curChar == 34)\r
+                     jjCheckNAddStates(9, 11);\r
+                  break;\r
+               case 44:\r
+                  if ((0x3ff400000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 90)\r
+                        kind = 90;\r
+                     jjCheckNAdd(2);\r
+                  }\r
+                  else if (curChar == 45)\r
+                  {\r
+                     if (kind > 92)\r
+                        kind = 92;\r
+                  }\r
+                  break;\r
+               case 20:\r
+                  if (curChar == 47)\r
+                  {\r
+                     if (kind > 3)\r
+                        kind = 3;\r
+                     jjCheckNAdd(27);\r
+                  }\r
+                  else if (curChar == 42)\r
+                     jjCheckNAddStates(12, 14);\r
+                  break;\r
+               case 2:\r
+                  if ((0x3ff400000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 3:\r
+                  if (curChar == 34)\r
+                     jjCheckNAddStates(9, 11);\r
+                  break;\r
+               case 4:\r
+                  if ((0xfffffffbfffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(9, 11);\r
+                  break;\r
+               case 6:\r
+                  if ((0xfffffffffffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(9, 11);\r
+                  break;\r
+               case 7:\r
+                  if (curChar == 34 && kind > 91)\r
+                     kind = 91;\r
+                  break;\r
+               case 9:\r
+                  if (curChar == 45 && kind > 92)\r
+                     kind = 92;\r
+                  break;\r
+               case 12:\r
+                  if (curChar == 46)\r
+                     jjCheckNAdd(13);\r
+                  break;\r
+               case 13:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAddStates(15, 18);\r
+                  break;\r
+               case 15:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAdd(15);\r
+                  break;\r
+               case 16:\r
+                  if (curChar == 45)\r
+                     jjCheckNAdd(15);\r
+                  break;\r
+               case 19:\r
+                  if (curChar == 47)\r
+                     jjAddStates(7, 8);\r
+                  break;\r
+               case 21:\r
+                  if ((0xfffffbffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(12, 14);\r
+                  break;\r
+               case 22:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 23;\r
+                  break;\r
+               case 23:\r
+                  if ((0xffff7fffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(12, 14);\r
+                  break;\r
+               case 24:\r
+                  if (curChar == 47 && kind > 2)\r
+                     kind = 2;\r
+                  break;\r
+               case 25:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 24;\r
+                  break;\r
+               case 26:\r
+                  if (curChar != 47)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(27);\r
+                  break;\r
+               case 27:\r
+                  if ((0xfffffffffffffbffL & l) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(27);\r
+                  break;\r
+               case 28:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAddStates(0, 6);\r
+                  break;\r
+               case 29:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAdd(29);\r
+                  break;\r
+               case 30:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(30, 31);\r
+                  break;\r
+               case 31:\r
+                  if (curChar != 46)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAddStates(19, 22);\r
+                  break;\r
+               case 32:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAddStates(19, 22);\r
+                  break;\r
+               case 34:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAdd(34);\r
+                  break;\r
+               case 35:\r
+                  if (curChar == 45)\r
+                     jjCheckNAdd(34);\r
+                  break;\r
+               case 38:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddStates(23, 26);\r
+                  break;\r
+               case 40:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAdd(40);\r
+                  break;\r
+               case 41:\r
+                  if (curChar == 45)\r
+                     jjCheckNAdd(40);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else if (curChar < 128)\r
+      {\r
+         long l = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 0:\r
+                  if ((0x7fffffe87fffffeL & l) != 0L)\r
+                  {\r
+                     if (kind > 90)\r
+                        kind = 90;\r
+                     jjCheckNAdd(2);\r
+                  }\r
+                  if ((0x2000000020L & l) != 0L)\r
+                  {\r
+                     if (kind > 92)\r
+                        kind = 92;\r
+                  }\r
+                  if (curChar == 69)\r
+                     jjCheckNAdd(9);\r
+                  else if (curChar == 101)\r
+                     jjCheckNAdd(9);\r
+                  break;\r
+               case 44:\r
+               case 2:\r
+                  if ((0x7fffffe87fffffeL & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 1:\r
+                  if ((0x7fffffe87fffffeL & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 4:\r
+                  if ((0xffffffffefffffffL & l) != 0L)\r
+                     jjCheckNAddStates(9, 11);\r
+                  break;\r
+               case 5:\r
+                  if (curChar == 92)\r
+                     jjstateSet[jjnewStateCnt++] = 6;\r
+                  break;\r
+               case 6:\r
+                  jjCheckNAddStates(9, 11);\r
+                  break;\r
+               case 8:\r
+                  if ((0x2000000020L & l) != 0L && kind > 92)\r
+                     kind = 92;\r
+                  break;\r
+               case 10:\r
+                  if (curChar == 101)\r
+                     jjCheckNAdd(9);\r
+                  break;\r
+               case 11:\r
+                  if (curChar == 69)\r
+                     jjCheckNAdd(9);\r
+                  break;\r
+               case 14:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjstateSet[jjnewStateCnt++] = 15;\r
+                  break;\r
+               case 17:\r
+                  if (curChar == 101)\r
+                     jjCheckNAdd(16);\r
+                  break;\r
+               case 18:\r
+                  if (curChar == 69)\r
+                     jjCheckNAdd(16);\r
+                  break;\r
+               case 21:\r
+               case 23:\r
+                  jjCheckNAddStates(12, 14);\r
+                  break;\r
+               case 27:\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 27;\r
+                  break;\r
+               case 33:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjstateSet[jjnewStateCnt++] = 34;\r
+                  break;\r
+               case 36:\r
+                  if (curChar == 101)\r
+                     jjCheckNAdd(35);\r
+                  break;\r
+               case 37:\r
+                  if (curChar == 69)\r
+                     jjCheckNAdd(35);\r
+                  break;\r
+               case 39:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjstateSet[jjnewStateCnt++] = 40;\r
+                  break;\r
+               case 42:\r
+                  if (curChar == 101)\r
+                     jjCheckNAdd(41);\r
+                  break;\r
+               case 43:\r
+                  if (curChar == 69)\r
+                     jjCheckNAdd(41);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else\r
+      {\r
+         int i2 = (curChar & 0xff) >> 6;\r
+         long l2 = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 4:\r
+               case 6:\r
+                  if ((jjbitVec0[i2] & l2) != 0L)\r
+                     jjCheckNAddStates(9, 11);\r
+                  break;\r
+               case 21:\r
+               case 23:\r
+                  if ((jjbitVec0[i2] & l2) != 0L)\r
+                     jjCheckNAddStates(12, 14);\r
+                  break;\r
+               case 27:\r
+                  if ((jjbitVec0[i2] & l2) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 27;\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      if (kind != 0x7fffffff)\r
+      {\r
+         jjmatchedKind = kind;\r
+         jjmatchedPos = curPos;\r
+         kind = 0x7fffffff;\r
+      }\r
+      ++curPos;\r
+      if ((i = jjnewStateCnt) == (startsAt = 44 - (jjnewStateCnt = startsAt)))\r
+         return curPos;\r
+      try { curChar = input_stream.readChar(); }\r
+      catch(java.io.IOException e) { return curPos; }\r
+   }\r
+}\r
+static final int[] jjnextStates = {
+   29, 30, 31, 38, 39, 42, 43, 20, 26, 4, 5, 7, 21, 22, 25, 13, 
+   14, 17, 18, 32, 33, 36, 37, 38, 39, 42, 43, 
+};\r
+\r
+/** Token literal values. */\r
+public static final String[] jjstrLiteralImages = {\r
+"", null, null, null, "\141\154\147\157\162\151\164\150\155", \r
+"\144\151\163\143\162\145\164\145", "\146\141\154\163\145", "\155\157\144\145\154", \r
+"\162\145\144\145\143\154\141\162\145", "\141\156\144", "\145\141\143\150", "\146\151\156\141\154", "\156\157\164", \r
+"\162\145\160\154\141\143\145\141\142\154\145", "\141\156\156\157\164\141\164\151\157\156", "\145\154\163\145", \r
+"\146\154\157\167", "\157\160\145\162\141\164\157\162", "\162\145\164\165\162\156", \r
+"\141\163\163\145\162\164", "\145\154\163\145\151\146", "\146\157\162", "\157\162", \r
+"\163\164\162\145\141\155", "\142\154\157\143\153", "\145\154\163\145\167\150\145\156", \r
+"\146\165\156\143\164\151\157\156", "\157\165\164\145\162", "\164\150\145\156", "\142\162\145\141\153", \r
+"\145\156\143\141\160\163\165\154\141\164\145\144", "\151\146", "\157\165\164\160\165\164", "\164\162\165\145", \r
+"\143\154\141\163\163", "\145\156\144", "\151\155\160\157\162\164", "\160\141\143\153\141\147\145", \r
+"\164\171\160\145", "\143\157\156\156\145\143\164", \r
+"\145\156\165\155\145\162\141\164\151\157\156", "\151\156", "\160\141\162\141\155\145\164\145\162", "\167\150\145\156", \r
+"\143\157\156\156\145\143\164\157\162", "\145\161\165\141\164\151\157\156", "\151\156\151\164\151\141\154", \r
+"\160\141\162\164\151\141\154", "\167\150\151\154\145", "\143\157\156\163\164\141\156\164", \r
+"\145\170\160\141\156\144\141\142\154\145", "\151\156\156\145\162", "\160\162\157\164\145\143\164\145\144", \r
+"\167\151\164\150\151\156", "\143\157\156\163\164\162\141\151\156\145\144\142\171", \r
+"\145\170\164\145\156\144\163", "\151\156\160\165\164", "\160\165\142\154\151\143", "\144\145\162", \r
+"\145\170\164\145\162\156\141\154", "\154\157\157\160", "\162\145\143\157\162\144", "\50", "\51", "\173", "\175", \r
+"\133", "\135", "\56", "\72", "\73", "\54", "\74", "\74\75", "\76", "\76\75", \r
+"\75\75", "\74\76", "\53", "\55", "\56\53", "\56\55", "\52", "\57", "\56\52", "\56\57", \r
+"\136", "\56\136", "\75", "\72\75", null, null, null, null, null, \r
+"\157\160\145\162\141\164\157\162\40\146\165\156\143\164\151\157\156", "\157\160\145\162\141\164\157\162\40\162\145\143\157\162\144", };\r
+\r
+/** Lexer state names. */\r
+public static final String[] lexStateNames = {\r
+   "DEFAULT",\r
+};\r
+static final long[] jjtoToken = {
+   0xfffffffffffffff1L, 0x1ffffffffL, 
+};\r
+static final long[] jjtoSkip = {
+   0xeL, 0x0L, 
+};\r
+protected SimpleCharStream input_stream;\r
+private final int[] jjrounds = new int[44];\r
+private final int[] jjstateSet = new int[88];\r
+private final StringBuilder jjimage = new StringBuilder();\r
+private StringBuilder image = jjimage;\r
+private int jjimageLen;\r
+private int lengthOfMatch;\r
+protected char curChar;\r
+/** Constructor. */\r
+public ModelParserTokenManager(SimpleCharStream stream){\r
+   if (SimpleCharStream.staticFlag)\r
+      throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");\r
+   input_stream = stream;\r
+}\r
+\r
+/** Constructor. */\r
+public ModelParserTokenManager(SimpleCharStream stream, int lexState){\r
+   this(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream)\r
+{\r
+   jjmatchedPos = jjnewStateCnt = 0;\r
+   curLexState = defaultLexState;\r
+   input_stream = stream;\r
+   ReInitRounds();\r
+}\r
+private void ReInitRounds()\r
+{\r
+   int i;\r
+   jjround = 0x80000001;\r
+   for (i = 44; i-- > 0;)\r
+      jjrounds[i] = 0x80000000;\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream, int lexState)\r
+{\r
+   ReInit(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Switch to specified lex state. */\r
+public void SwitchTo(int lexState)\r
+{\r
+   if (lexState >= 1 || lexState < 0)\r
+      throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);\r
+   else\r
+      curLexState = lexState;\r
+}\r
+\r
+protected Token jjFillToken()\r
+{\r
+   final Token t;\r
+   final String curTokenImage;\r
+   final int beginLine;\r
+   final int endLine;\r
+   final int beginColumn;\r
+   final int endColumn;\r
+   String im = jjstrLiteralImages[jjmatchedKind];\r
+   curTokenImage = (im == null) ? input_stream.GetImage() : im;\r
+   beginLine = input_stream.getBeginLine();\r
+   beginColumn = input_stream.getBeginColumn();\r
+   endLine = input_stream.getEndLine();\r
+   endColumn = input_stream.getEndColumn();\r
+   t = Token.newToken(jjmatchedKind, curTokenImage);\r
+\r
+   t.beginLine = beginLine;\r
+   t.endLine = endLine;\r
+   t.beginColumn = beginColumn;\r
+   t.endColumn = endColumn;\r
+\r
+   return t;\r
+}\r
+\r
+int curLexState = 0;\r
+int defaultLexState = 0;\r
+int jjnewStateCnt;\r
+int jjround;\r
+int jjmatchedPos;\r
+int jjmatchedKind;\r
+\r
+/** Get the next Token. */\r
+public Token getNextToken() \r
+{\r
+  Token matchedToken;\r
+  int curPos = 0;\r
+\r
+  EOFLoop :
+  for (;;)\r
+  {\r
+   try\r
+   {\r
+      curChar = input_stream.BeginToken();\r
+   }\r
+   catch(java.io.IOException e)\r
+   {\r
+      jjmatchedKind = 0;\r
+      matchedToken = jjFillToken();\r
+      return matchedToken;\r
+   }\r
+   image = jjimage;\r
+   image.setLength(0);\r
+   jjimageLen = 0;\r
+\r
+   jjmatchedKind = 0x7fffffff;\r
+   jjmatchedPos = 0;\r
+   curPos = jjMoveStringLiteralDfa0_0();\r
+   if (jjmatchedKind != 0x7fffffff)\r
+   {\r
+      if (jjmatchedPos + 1 < curPos)\r
+         input_stream.backup(curPos - jjmatchedPos - 1);\r
+      if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)\r
+      {\r
+         matchedToken = jjFillToken();\r
+         TokenLexicalActions(matchedToken);\r
+         return matchedToken;\r
+      }\r
+      else\r
+      {\r
+         continue EOFLoop;\r
+      }\r
+   }\r
+   int error_line = input_stream.getEndLine();\r
+   int error_column = input_stream.getEndColumn();\r
+   String error_after = null;\r
+   boolean EOFSeen = false;\r
+   try { input_stream.readChar(); input_stream.backup(1); }\r
+   catch (java.io.IOException e1) {\r
+      EOFSeen = true;\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+      if (curChar == '\n' || curChar == '\r') {\r
+         error_line++;\r
+         error_column = 0;\r
+      }\r
+      else\r
+         error_column++;\r
+   }\r
+   if (!EOFSeen) {\r
+      input_stream.backup(1);\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+   }\r
+   throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);\r
+  }\r
+}\r
+\r
+void TokenLexicalActions(Token matchedToken)\r
+{\r
+   switch(jjmatchedKind)\r
+   {\r
+      case 91 :\r
+        image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)));\r
+      matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+}\r
+private void jjCheckNAdd(int state)\r
+{\r
+   if (jjrounds[state] != jjround)\r
+   {\r
+      jjstateSet[jjnewStateCnt++] = state;\r
+      jjrounds[state] = jjround;\r
+   }\r
+}\r
+private void jjAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjstateSet[jjnewStateCnt++] = jjnextStates[start];\r
+   } while (start++ != end);\r
+}\r
+private void jjCheckNAddTwoStates(int state1, int state2)\r
+{\r
+   jjCheckNAdd(state1);\r
+   jjCheckNAdd(state2);\r
+}\r
+\r
+private void jjCheckNAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjCheckNAdd(jjnextStates[start]);\r
+   } while (start++ != end);\r
+}\r
+\r
+}\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserTreeConstants.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelParserTreeConstants.java
new file mode 100644 (file)
index 0000000..8539a49
--- /dev/null
@@ -0,0 +1,175 @@
+/* Generated By:JavaCC: Do not edit this line. ModelParserTreeConstants.java Version 5.0 */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+public interface ModelParserTreeConstants\r
+{\r
+  public int JJTPARSE = 0;\r
+  public int JJTSTORED = 1;\r
+  public int JJTCLASS_DEFINITION = 2;\r
+  public int JJTCLASS_SPECIFIER = 3;\r
+  public int JJTBASE_PREFIX = 4;\r
+  public int JJTENUM_LIST = 5;\r
+  public int JJTENUMERATION_LITERAL = 6;\r
+  public int JJTPARSE_COMPOSITION = 7;\r
+  public int JJTCOMPOSITION = 8;\r
+  public int JJTLANGUAGE_SPECIFICATION = 9;\r
+  public int JJTEXTERNAL_FUNCTION_CALL = 10;\r
+  public int JJTELEMENT_LIST = 11;\r
+  public int JJTELEMENT = 12;\r
+  public int JJTIMPORT_CLAUSE = 13;\r
+  public int JJTEXTENDS_CLAUSE = 14;\r
+  public int JJTCONSTRAINING_CLAUSE = 15;\r
+  public int JJTCOMPONENT_CLAUSE = 16;\r
+  public int JJTTYPE_PREFIX = 17;\r
+  public int JJTTYPE_SPECIFIER = 18;\r
+  public int JJTCOMPONENT_LIST = 19;\r
+  public int JJTCOMPONENT_DECLARATION = 20;\r
+  public int JJTCONDITIONAL_ATTRIBUTE = 21;\r
+  public int JJTDECLARATION = 22;\r
+  public int JJTMODIFICATION = 23;\r
+  public int JJTCLASS_MODIFICATION = 24;\r
+  public int JJTARGUMENT_LIST = 25;\r
+  public int JJTARGUMENT = 26;\r
+  public int JJTELEMENT_MODIFICATION_OR_REPLACEABLE = 27;\r
+  public int JJTELEMENT_MODIFICATION = 28;\r
+  public int JJTELEMENT_REDECLARATION = 29;\r
+  public int JJTELEMENT_REPLACEABLE = 30;\r
+  public int JJTCOMPONENT_CLAUSE1 = 31;\r
+  public int JJTCOMPONENT_DECLARATION1 = 32;\r
+  public int JJTEQUATION_SECTION = 33;\r
+  public int JJTALGORITHM_SECTION = 34;\r
+  public int JJTASSIGNMENT = 35;\r
+  public int JJTEQUATION = 36;\r
+  public int JJTSTATEMENT = 37;\r
+  public int JJTIF_EQUATION = 38;\r
+  public int JJTTHEN_STATEMENT = 39;\r
+  public int JJTELSEIF_STATEMENT = 40;\r
+  public int JJTELSE_STATEMENT = 41;\r
+  public int JJTIF_STATEMENT = 42;\r
+  public int JJTFOR_EQUATION = 43;\r
+  public int JJTFOR_STATEMENT = 44;\r
+  public int JJTFOR_INDICES = 45;\r
+  public int JJTFOR_INDEX = 46;\r
+  public int JJTWHILE_STATEMENT = 47;\r
+  public int JJTWHEN_EQUATION = 48;\r
+  public int JJTWHEN_STATEMENT = 49;\r
+  public int JJTCONNECT_CLAUSE = 50;\r
+  public int JJTEXPR = 51;\r
+  public int JJTIF_EXPRESSION = 52;\r
+  public int JJTEXPRESSION = 53;\r
+  public int JJTSIMPLE_EXPRESSION = 54;\r
+  public int JJTLOGICAL_EXPRESSION = 55;\r
+  public int JJTLOGICAL_TERM = 56;\r
+  public int JJTLOGICAL_FACTOR = 57;\r
+  public int JJTRELATION = 58;\r
+  public int JJTREL_OP = 59;\r
+  public int JJTARITHMETIC_EXPRESSION = 60;\r
+  public int JJTADD_OP = 61;\r
+  public int JJTTERM = 62;\r
+  public int JJTMUL_OP = 63;\r
+  public int JJTFACTOR = 64;\r
+  public int JJTFACTOR_OP = 65;\r
+  public int JJTDER_INITIAL = 66;\r
+  public int JJTSUBSCRIPT_2 = 67;\r
+  public int JJTARRAY = 68;\r
+  public int JJTPRIMARY = 69;\r
+  public int JJTNAME = 70;\r
+  public int JJTCOMPONENT_REFERENCE = 71;\r
+  public int JJTFUNCTION_CALL_ARGS = 72;\r
+  public int JJTFUNCTION_ARGUMENTS = 73;\r
+  public int JJTNAMED_ARGUMENTS = 74;\r
+  public int JJTNAMED_ARGUMENT = 75;\r
+  public int JJTOUTPUT_EXPRESSION_LIST = 76;\r
+  public int JJTEXPRESSION_LIST = 77;\r
+  public int JJTARRAY_SUBSCRIPTS = 78;\r
+  public int JJTSUBSCRIPT = 79;\r
+  public int JJTVOID = 80;\r
+  public int JJTANNOTATION = 81;\r
+\r
+\r
+  public String[] jjtNodeName = {\r
+    "parse",\r
+    "STORED",\r
+    "class_definition",\r
+    "class_specifier",\r
+    "base_prefix",\r
+    "enum_list",\r
+    "enumeration_literal",\r
+    "parse_composition",\r
+    "composition",\r
+    "language_specification",\r
+    "external_function_call",\r
+    "element_list",\r
+    "element",\r
+    "import_clause",\r
+    "extends_clause",\r
+    "constraining_clause",\r
+    "component_clause",\r
+    "type_prefix",\r
+    "type_specifier",\r
+    "component_list",\r
+    "component_declaration",\r
+    "conditional_attribute",\r
+    "declaration",\r
+    "modification",\r
+    "class_modification",\r
+    "argument_list",\r
+    "argument",\r
+    "element_modification_or_replaceable",\r
+    "element_modification",\r
+    "element_redeclaration",\r
+    "element_replaceable",\r
+    "component_clause1",\r
+    "component_declaration1",\r
+    "equation_section",\r
+    "algorithm_section",\r
+    "assignment",\r
+    "equation",\r
+    "statement",\r
+    "if_equation",\r
+    "then_statement",\r
+    "elseif_statement",\r
+    "else_statement",\r
+    "if_statement",\r
+    "for_equation",\r
+    "for_statement",\r
+    "for_indices",\r
+    "for_index",\r
+    "while_statement",\r
+    "when_equation",\r
+    "when_statement",\r
+    "connect_clause",\r
+    "expr",\r
+    "if_expression",\r
+    "expression",\r
+    "simple_expression",\r
+    "logical_expression",\r
+    "logical_term",\r
+    "logical_factor",\r
+    "relation",\r
+    "rel_op",\r
+    "arithmetic_expression",\r
+    "add_op",\r
+    "term",\r
+    "mul_op",\r
+    "factor",\r
+    "factor_op",\r
+    "der_initial",\r
+    "subscript_2",\r
+    "array",\r
+    "primary",\r
+    "name",\r
+    "component_reference",\r
+    "function_call_args",\r
+    "function_arguments",\r
+    "named_arguments",\r
+    "named_argument",\r
+    "output_expression_list",\r
+    "expression_list",\r
+    "array_subscripts",\r
+    "subscript",\r
+    "void",\r
+    "annotation",\r
+  };\r
+}\r
+/* JavaCC - OriginalChecksum=c86e9178ecd31c01eb2447d79ce33b0f (do not edit this line) */\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelicaParser.jj b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelicaParser.jj
new file mode 100644 (file)
index 0000000..190ea2f
--- /dev/null
@@ -0,0 +1,2970 @@
+/*@bgen(jjtree) Generated By:JJTree: Do not edit this line. ModelicaParser.jj */\r
+/*@egen*/options {\r
+  JDK_VERSION = "1.6";\r
+  STATIC = false;\r
+}\r
+\r
+PARSER_BEGIN(ModelParser)\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class ModelParser/*@bgen(jjtree)*/implements ModelParserTreeConstants/*@egen*/ {/*@bgen(jjtree)*/\r
+  protected JJTModelParserState jjtree = new JJTModelParserState();\r
+\r
+/*@egen*/\r
+\r
+  private ArrayList<Parameter> inputs = new ArrayList<Parameter>();\r
+  private ArrayList<Parameter> outputs = new ArrayList<Parameter>();\r
+  \r
+  private enum InterfaceVariableType\r  {\r    INPUT, OUTPUT, OTHER\r
+  }\r
+\r
+  public class Parameter\r  {\r
+    public String name;\r
+    public boolean optional;\r
+    public String description;\r
+    public String type;\r
+    \r
+    public Parameter()\r    {\r
+      name = new String("");\r
+      optional = false;\r
+      description = null;\r
+      type = null;\r
+    }\r  }\r
+\r
+  public ArrayList<Parameter> getInputs()\r
+  {\r
+    return inputs;\r
+  }\r
+    \r
+  public ArrayList<Parameter> getOutputs()\r
+  {\r
+    return outputs;\r
+  }\r
+    \r
+}\r
+\r
+PARSER_END(ModelParser)\r
+\r
+/*** Lexer *********************************************************/\r
+\r
+SKIP:\r
+{ <WHITESPACE: " " | "\n" | "\r" | "\t" > \r
+| <COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/" >  \r
+| <COMMENT2: "//" (~["\n"])* >\r
+}\r
+\r
+TOKEN:\r
+{\r
+"algorithm"     | "discrete"    | "false"   | "model"   | "redeclare"\r
+| "and"         | "each"        | "final"   | "not"     | "replaceable"\r
+| "annotation" | "else"         | "flow"    | "operator" | "return"\r
+|"assert"       | "elseif"      | "for"     | "or"      | "stream"\r
+| "block"       | "elsewhen"    | "function" | "outer"  | "then"\r
+| "break"       | "encapsulated" | "if"     | "output"  | "true"\r
+| "class"       | "end"         | "import"  | "package" | "type"\r
+| "connect"     | "enumeration" | "in"      | "parameter" | "when"\r
+| "connector"   | "equation"    | "initial" | "partial" | "while"\r
+| "constant"    | "expandable"  | "inner"   | "protected" | "within"\r
+| "constrainedby" | "extends"   | "input"   | "public"\r
+| "der"         | "external"    | "loop"    | "record"\r
+| "(" | ")" | "{" | "}" | "[" | "]" | "." | ":" | ";" | ","\r
+| "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+| "+" | "-" | ".+" | ".-"\r
+| "*" | "/" | ".*" | "./"\r
+| "^" | ".^"\r
+| "=" | ":=" \r
+| <IDENT: ["a"-"z","A"-"Z","_"] (["a"-"z","A"-"Z","_",".", "0"-"9"])* >\r
+| <STRING: "\"" (~["\"", "\\", "\n"] | "\\" ~["\n"])* "\"">\r
+    { matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); }\r
+| <EXP: "e" | "e-" | "E" | "E-" >\r
+| <UNSIGNED_INTEGER: (["0"-"9"])+ >\r
+| <UNSIGNED_NUMBER:  \r
+    ( <UNSIGNED_INTEGER> "." (<UNSIGNED_INTEGER>)? (<EXP> <UNSIGNED_INTEGER>)?\r
+    | "." <UNSIGNED_INTEGER> (<EXP> <UNSIGNED_INTEGER>)?\r
+    | <UNSIGNED_INTEGER> <EXP> <UNSIGNED_INTEGER>\r
+    ) >\r
+}\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+\r
+Node parse() : {/*@bgen(jjtree) parse */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTPARSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) parse */\r
+    try {\r
+/*@egen*/\r
+    stored_definition() <EOF>/*@bgen(jjtree)*/\r
+    {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+    }\r
+/*@egen*/\r
+    { return jjtn000; }/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+/*** Stored Definition - Within ************************************/\r
+\r
+Node stored_definition()         : {/*@bgen(jjtree) STORED */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSTORED);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) STORED */\r
+    try {\r
+/*@egen*/\r
+//  stored_definition:\r
+//  [ within [ name ] ";" ]\r
+//  { [ final ] class_definition ";" }\r
+    ( "within" ( name() )? ";" )?\r
+    ( ( "final" )? class_definition() ";" )*/*@bgen(jjtree)*/\r
+    {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+    }\r
+/*@egen*/\r
+    { return jjtn000; }/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r  \r      \r
+}\r
+\r
+/*** Class Definition **********************************************/\r
+  \r
+void class_definition() : {/*@bgen(jjtree) class_definition */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCLASS_DEFINITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) class_definition */\r
+    try {\r
+/*@egen*/\r
+//  class_definition :\r
+//  [ encapsulated ]\r
+//  [ partial\r
+//  ] ( class modelrecordblock expandableconnectortype\r
+//  | | | | [ ] | | package | function | operator | operator function | operator record )\r
+//  class_specifier\r
+    ( "encapsulated" )?\r
+    ( "partial" )?\r
+    ( "class" { jjtn000.op = "class"; } | "model" { jjtn000.op = "model"; } | "record" | "block" | ( "expandable" )? "connector" | "type" |\r
+    "package" | "function" { jjtn000.op = "function"; } | "operator" | "operator function" | "operator record" )\r
+    class_specifier()/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+\r
+void class_specifier() : {/*@bgen(jjtree) class_specifier */\r
+                           SimpleNode jjtn000 = new SimpleNode(JJTCLASS_SPECIFIER);\r
+                           boolean jjtc000 = true;\r
+                           jjtree.openNodeScope(jjtn000);\r
+/*@egen*/ Token t;\r
+} {/*@bgen(jjtree) class_specifier */\r
+    try {\r
+/*@egen*/\r
+//  class_specifier :\r
+//  IDENT string_comment composition end IDENT\r
+//  | IDENT "=" base_prefix name [ array_subscripts ]\r
+//  [ class_modification ] comment\r
+//  | IDENT "=" enumeration "(" ( [enum_list] | ":" ) ")" comment\r
+//  | IDENT "=" der "(" name "," IDENT { "," IDENT } ")" comment\r
+//  | extends IDENT [ class_modification ] string_comment composition\r
+//  end IDENT  \r
+    LOOKAHEAD(2) t=<IDENT> { jjtn000.op = t.image; } string_comment() composition() "end" <IDENT>\r
+    | LOOKAHEAD(2) <IDENT> "=" base_prefix() name() ( array_subscripts() )? ( class_modification() )? comment()\r
+    | LOOKAHEAD(3)  <IDENT> "=" "der" "(" name() "," <IDENT> ( "," <IDENT> )* ")" comment()\r
+    | LOOKAHEAD(3) <IDENT> "=" "enumeration" "(" ( ( enum_list() )? | ":" ) ")" comment()/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+    //| "extends" <IDENT> ( class_modification() )? string_comment() composition() "end" <IDENT> \r
+}\r
+\r
+void base_prefix() : {/*@bgen(jjtree) base_prefix */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTBASE_PREFIX);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) base_prefix */\r
+    try {\r
+/*@egen*/\r
+    type_prefix()/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void enum_list() : {/*@bgen(jjtree) enum_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTENUM_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) enum_list */\r
+    try {\r
+/*@egen*/\r
+//  enumeration_literal { "," enumeration_literal}\r
+    enumeration_literal() ( "," enumeration_literal() )*/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/ \r
+}\r
+\r
+void enumeration_literal() : {/*@bgen(jjtree) enumeration_literal */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTENUMERATION_LITERAL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) enumeration_literal */\r
+    try {\r
+/*@egen*/\r
+    <IDENT> comment()/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void parse_composition() : {/*@bgen(jjtree) parse_composition */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTPARSE_COMPOSITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) parse_composition */\r
+    try {\r
+/*@egen*/\r
+    composition() <EOF>/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void composition() : {/*@bgen(jjtree) composition */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCOMPOSITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) composition */\r
+    try {\r
+/*@egen*/\r
+//  element_list\r
+//  { public element_list |\r
+//  protected element_list |\r
+//  equation_section |\r
+//  algorithm_section\r
+//  }\r
+//  [ external [ language_specification ]\r
+//  [ external_function_call ] [ annotation ] ";" ]\r
+//  [ annotation ";" ]\r
+    element_list()\r
+    ( LOOKAHEAD(2) "public" element_list() | "protected" element_list() | equation_section() | algorithm_section() )*\r
+    ( "external" ( language_specification() )? ( external_function_call() )? ( annotation() )? ";" )?\r
+    ( annotation() ";" )?/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void language_specification() : {/*@bgen(jjtree) language_specification */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTLANGUAGE_SPECIFICATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) language_specification */\r
+    try {\r
+/*@egen*/\r
+    <STRING>/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void external_function_call() : {/*@bgen(jjtree) external_function_call */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXTERNAL_FUNCTION_CALL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) external_function_call */\r
+    try {\r
+/*@egen*/\r
+//  [ component_reference "=" ]\r
+//  IDENT "(" [ expression_list ] ")"\r
+    ( component_reference() "=" )?\r
+    <IDENT> "(" ( expression_list() )? ")"/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void element_list() : {/*@bgen(jjtree) element_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) element_list */\r
+    try {\r
+/*@egen*/\r
+    ( element() ";" )*/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+Node element() : {/*@bgen(jjtree) element */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) element */\r
+    try {\r
+/*@egen*/\r
+//  import_clause |\r
+//  extends_clause |\r
+//  [ redeclare ]\r
+//  [ final ]\r
+//  [ inner ] [ outer ]\r
+//  ( ( class_definition | component_clause) |\r
+//  replaceable ( class_definition | component_clause)\r
+//  [constraining_clause comment])\r
+    import_clause()/*@bgen(jjtree)*/\r
+                    {\r
+                      jjtree.closeNodeScope(jjtn000, true);\r
+                      jjtc000 = false;\r
+                    }\r
+/*@egen*/ { return jjtn000; } |\r
+    extends_clause()/*@bgen(jjtree)*/\r
+                     {\r
+                       jjtree.closeNodeScope(jjtn000, true);\r
+                       jjtc000 = false;\r
+                     }\r
+/*@egen*/ { return jjtn000; } |\r
+    ( "redeclare" )?\r
+    ( "final" )?\r
+    ( "inner" { jjtn000.op = "inner"; } )? ( "outer" { jjtn000.op = "outer"; } )?\r
+    ( (class_definition() | component_clause()) |\r
+        "replaceable" (class_definition() | component_clause())\r
+        (constraining_clause() comment())?)/*@bgen(jjtree)*/\r
+    {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+    }\r
+/*@egen*/\r
+    { return jjtn000; }/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void import_clause() : {/*@bgen(jjtree) import_clause */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTIMPORT_CLAUSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) import_clause */\r
+    try {\r
+/*@egen*/\r
+//  import ( IDENT "=" name | name ["." "*"] ) comment\r
+    "import" (LOOKAHEAD(2) <IDENT> "=" name() | name() ("." "*")? ) comment()/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+/*** Extends *******************************************************/\r
+void extends_clause() : {/*@bgen(jjtree) extends_clause */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXTENDS_CLAUSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) extends_clause */\r
+    try {\r
+/*@egen*/\r
+//  extends name [ class_modification ] [annotation]\r
+    "extends" name() ( class_modification() )? ( annotation() )?/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void constraining_clause() : {/*@bgen(jjtree) constraining_clause */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCONSTRAINING_CLAUSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) constraining_clause */\r
+    try {\r
+/*@egen*/\r
+//  constrainedby name [ class_modification ]\r
+    "constrainedby" name() ( class_modification() )?/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+/*** Component Clause **********************************************/\r
+void component_clause() : {/*@bgen(jjtree) component_clause */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_CLAUSE);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+    InterfaceVariableType ioType = InterfaceVariableType.OTHER;\r
+    String typeSpecifier = "";\r
+    //String arraySubscripts = null;\r
+    ArrayList<Parameter> componentList = new ArrayList<Parameter>();\r
+} {/*@bgen(jjtree) component_clause */\r
+    try {\r
+/*@egen*/\r
+  \r
+//  type_prefix type_specifier [ array_subscripts ] component_list\r
+    ( ioType = type_prefix() )\r
+    ( typeSpecifier = type_specifier() )\r
+    ( /*arraySubscripts =*/ array_subscripts() )?\r
+    ( componentList = component_list() )/*@bgen(jjtree)*/\r
+    {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+    }\r
+/*@egen*/\r
+    {\r
+        if (ioType == InterfaceVariableType.INPUT) {\r
+            for (Parameter input : componentList) {\r
+                input.type = typeSpecifier;\r
+                inputs.add(input);\r            }\r
+        } else if (ioType == InterfaceVariableType.OUTPUT) {\r
+            for (Parameter output : componentList) {\r
+                output.type = typeSpecifier;          \r
+                outputs.add(output);\r
+            }\r
+        }\r
+    }/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+InterfaceVariableType type_prefix() : {/*@bgen(jjtree) type_prefix */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTTYPE_PREFIX);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+    InterfaceVariableType type = InterfaceVariableType.OTHER;\r
+} {/*@bgen(jjtree) type_prefix */\r
+    try {\r
+/*@egen*/\r
+//  [ flow | stream ]\r
+//  [ discrete | parameter | constant ] [ input | output ]\r
+    ( "flow" | "stream" )?\r
+    ( "discrete" { jjtn000.op = "discrete"; }| "parameter" { jjtn000.op = "parameter"; }| "constant" { jjtn000.op = "constant"; })?\r
+    ( "output" { type = InterfaceVariableType.OUTPUT; jjtn000.op = "output"; }\r
+        | "input" { type = InterfaceVariableType.INPUT; jjtn000.op = "input"; }\r
+    )?/*@bgen(jjtree)*/\r
+    {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+    }\r
+/*@egen*/\r
+    {\r
+        return type;\r
+    }/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+String type_specifier() : {/*@bgen(jjtree) type_specifier */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTTYPE_SPECIFIER);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+    String ret = new String("");\r
+} {/*@bgen(jjtree) type_specifier */\r
+        try {\r
+/*@egen*/\r
+       ret = name()/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        }\r
+/*@egen*/\r
+       {\r
+           jjtn000.op = ret;\r        return ret;\r
+    }/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+ArrayList<Parameter> component_list() : {/*@bgen(jjtree) component_list */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_LIST);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+    ArrayList<Parameter> ret = new ArrayList<Parameter>();\r
+    Parameter temp;\r
+} {/*@bgen(jjtree) component_list */\r
+        try {\r
+/*@egen*/\r
+//     component_declaration { "," component_declaration }\r
+       temp = component_declaration() { ret.add(temp); }\r    ( "," temp = component_declaration() { ret.add(temp); } )*/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        }\r
+/*@egen*/\r
+       {\r          return ret;\r
+       }/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+Parameter component_declaration() : {/*@bgen(jjtree) component_declaration */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_DECLARATION);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+    Parameter ret;\r
+    String temp = "";\r
+} {/*@bgen(jjtree) component_declaration */\r
+        try {\r
+/*@egen*/\r
+//     declaration [ conditional_attribute ] comment\r
+       ret = declaration() ( conditional_attribute() )? ret.description = comment()/*@bgen(jjtree)*/\r
+    {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+    }\r
+/*@egen*/\r
+    {\r
+        return ret;\r
+    }/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void conditional_attribute() : {/*@bgen(jjtree) conditional_attribute */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCONDITIONAL_ATTRIBUTE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) conditional_attribute */\r
+        try {\r
+/*@egen*/\r
+       "if" expression()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+Parameter declaration() : {/*@bgen(jjtree) declaration */\r
+                            SimpleNode jjtn000 = new SimpleNode(JJTDECLARATION);\r
+                            boolean jjtc000 = true;\r
+                            jjtree.openNodeScope(jjtn000);\r
+/*@egen*/ Token t;\r
+    // Parameter here without comment yet.\r
+    Parameter ret = new Parameter();\r
+} {/*@bgen(jjtree) declaration */\r
+        try {\r
+/*@egen*/\r
+//     IDENT [ array_subscripts ] [ modification ]\r
+       <IDENT> { ret.name = new String(token.image); jjtn000.op = token.image; }\r
+       ( array_subscripts() )?\r
+       ( ret.optional = modification() )?/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        }\r
+/*@egen*/\r
+       {\r              return ret;\r    }/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+/*** Modification **********************************************/\r
+boolean modification() : {/*@bgen(jjtree) modification */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTMODIFICATION);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+    boolean optional = false;\r
+} {/*@bgen(jjtree) modification */\r
+        try {\r
+/*@egen*/\r
+//     class_modification [ "=" expression ]\r
+//     | "=" expression\r
+//     | ":=" expression\r
+       ( class_modification() ( "=" expression() )?\r
+       | "=" expression() { optional = true; }\r
+       | ":=" expression() { optional = true; } )/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        }\r
+/*@egen*/\r
+       {\r          return optional;\r
+       }/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/ \r
+}\r
+\r
+void class_modification() : {/*@bgen(jjtree) class_modification */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCLASS_MODIFICATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) class_modification */\r
+        try {\r
+/*@egen*/\r
+//     "(" [ argument_list ] ")"\r
+       "(" ( argument_list() )? ")"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void argument_list() : {/*@bgen(jjtree) argument_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARGUMENT_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) argument_list */\r
+        try {\r
+/*@egen*/\r
+// argument { "," argument }\r
+       argument() ( "," argument() )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void argument() : {/*@bgen(jjtree) argument */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARGUMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) argument */\r
+        try {\r
+/*@egen*/\r
+//     element_modification_or_replaceable\r
+//     | element_redeclaration\r
+       element_modification_or_replaceable() |\r
+       element_redeclaration()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void element_modification_or_replaceable() : {/*@bgen(jjtree) element_modification_or_replaceable */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_MODIFICATION_OR_REPLACEABLE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) element_modification_or_replaceable */\r
+        try {\r
+/*@egen*/\r
+//     [ each ] [ final ] ( element_modification | element_replaceable)\r
+       ( "each" )? ( "final" )? ( element_modification() | element_replaceable() )/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void element_modification() : {/*@bgen(jjtree) element_modification */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_MODIFICATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) element_modification */\r
+        try {\r
+/*@egen*/\r
+//     name [ modification ] string_comment\r
+       name() ( modification() )? string_comment()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void element_redeclaration() : {/*@bgen(jjtree) element_redeclaration */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_REDECLARATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) element_redeclaration */\r
+        try {\r
+/*@egen*/\r
+//     redeclare [ each ] [ final ]\r
+//     ( ( class_definition | component_clause1) | element_replaceable )\r
+       "redeclare" ( "each" )? ( "final" )?\r
+       ( ( class_definition() | component_clause1() ) | element_replaceable() )/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void element_replaceable() : {/*@bgen(jjtree) element_replaceable */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELEMENT_REPLACEABLE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) element_replaceable */\r
+        try {\r
+/*@egen*/\r
+//     replaceable ( class_definition | component_clause1)\r
+//     [constraining_clause]\r
+       "replaceable" ( class_definition() | component_clause1() ) ( constraining_clause() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void component_clause1() : {/*@bgen(jjtree) component_clause1 */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_CLAUSE1);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) component_clause1 */\r
+        try {\r
+/*@egen*/\r
+//     type_prefix type_specifier component_declaration1\r
+       type_prefix() type_specifier() component_declaration1()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void component_declaration1() : {/*@bgen(jjtree) component_declaration1 */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_DECLARATION1);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) component_declaration1 */\r
+        try {\r
+/*@egen*/\r
+       declaration() comment()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+\r
+/*** Equations *************************************************/\r
+void equation_section() : {/*@bgen(jjtree) equation_section */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEQUATION_SECTION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) equation_section */\r
+        try {\r
+/*@egen*/\r
+//     [ initial ] equation { equation ";" }\r
+       ( "initial" { jjtn000.op = "initial"; } )? "equation" ( LOOKAHEAD(2) equation() ";" )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void algorithm_section() : {/*@bgen(jjtree) algorithm_section */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTALGORITHM_SECTION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) algorithm_section */\r
+        try {\r
+/*@egen*/\r
+//     [ initial ] algorithm { statement ";" }\r
+       ( "initial" )? "algorithm" ( statement() ";" )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void assignment() : {/*@bgen(jjtree) assignment */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTASSIGNMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) assignment */\r
+  try {\r
+/*@egen*/\r
+  ( simple_expression() "=" expression() )/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r  \r\r
+\r
+Node equation() : {/*@bgen(jjtree) equation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEQUATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) equation */\r
+        try {\r
+/*@egen*/\r
+//     ( simple_expression "=" expression\r
+//     | if_equation\r
+//     | for_equation\r
+//     | connect_clause\r
+//     | when_equation\r
+//     | IDENT function_call_args )\r
+//     comment\r
+       ( LOOKAHEAD(3) assignment()\r
+               | if_equation()\r
+               | for_equation()\r
+               | connect_clause()\r
+               | when_equation()\r
+               | <IDENT> function_call_args() )\r
+       comment()/*@bgen(jjtree)*/\r
+    {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtc000 = false;\r
+    }\r
+/*@egen*/\r    { return jjtn000; }/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void statement() : {/*@bgen(jjtree) statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSTATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) statement */\r
+        try {\r
+/*@egen*/\r
+//     ( component_reference ( ":=" expression | function_call_args )\r
+//     | "(" output_expression_list ")" ":=" component_reference function_call_args\r
+//     | break\r
+//     | return\r
+//     | if_statement\r
+//     | for_statement\r
+//     | while_statement\r
+//     | when_statement )\r
+//     comment\r
+       ( component_reference() ( ":=" expression() | function_call_args() )\r
+               | "(" output_expression_list() ")" ":=" component_reference() function_call_args()\r
+               | "break"\r
+               | "return"\r
+               | if_statement()\r
+               | for_statement()\r
+               | while_statement()\r
+               | when_statement() )\r
+       comment()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/ \r      \r
+}\r
+\r
+void if_equation() : {/*@bgen(jjtree) if_equation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTIF_EQUATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) if_equation */\r
+        try {\r
+/*@egen*/\r
+//     if expression then\r
+//     { equation ";" }\r
+//     { elseif expression then\r
+//     { equation ";" }\r
+//     }\r
+//     [ else\r
+//     { equation ";" }\r
+//     ]\r
+//     end if\r
+       "if" expression() "then"\r
+               ( equation() ";" )*\r
+       ( "elseif" expression() "then"\r
+               ( equation() ";" )*\r
+       )*\r
+       ( "else"\r
+               ( equation() ";" )*\r
+       )?\r
+       "end" "if"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void then_statement() : {/*@bgen(jjtree) then_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTTHEN_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) then_statement */\r
+  try {\r
+/*@egen*/\r
+  ( statement() )/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+  }\r
+/*@egen*/\r}\r
+\r
+void elseif_statement() : {/*@bgen(jjtree) elseif_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELSEIF_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) elseif_statement */\r
+  try {\r
+/*@egen*/\r
+  ( statement() )/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r
+\r
+void else_statement() : {/*@bgen(jjtree) else_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTELSE_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) else_statement */\r
+  try {\r
+/*@egen*/\r
+  ( statement() )/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r
+\r
+void if_statement() : {/*@bgen(jjtree) if_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTIF_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) if_statement */\r
+        try {\r
+/*@egen*/\r
+//     if expression then\r
+//     { statement ";" }\r
+//     { elseif expression then\r
+//     { statement ";" }\r
+//     }\r
+//     [ else\r
+//     { statement ";" }\r
+//     ]\r
+//     end if\r
+       "if" expression() "then"\r
+               ( then_statement() ";" )*\r
+       ( "elseif" expression() "then"\r
+               ( elseif_statement() ";" )*\r
+       )*\r
+       ( "else"\r
+               ( else_statement() ";" )*\r
+       )?\r
+       "end" "if"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void for_equation() : {/*@bgen(jjtree) for_equation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFOR_EQUATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) for_equation */\r
+        try {\r
+/*@egen*/\r
+//     for for_indices loop\r
+//     { equation ";" }\r
+//     end for\r
+       "for" for_indices() "loop"\r
+               ( equation() ";" )*\r
+       "end" "for"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void for_statement() : {/*@bgen(jjtree) for_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFOR_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) for_statement */\r
+        try {\r
+/*@egen*/\r
+//     for for_indices loop\r
+//     { equation ";" }\r
+//     end for\r
+       "for" for_indices() "loop"\r
+               ( statement() ";" )*\r
+       "end" "for"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void for_indices() : {/*@bgen(jjtree) for_indices */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFOR_INDICES);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) for_indices */\r
+        try {\r
+/*@egen*/\r
+       //for_index {"," for_index}\r
+       for_index() ("," for_index())*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void for_index() : {/*@bgen(jjtree) for_index */\r
+                     SimpleNode jjtn000 = new SimpleNode(JJTFOR_INDEX);\r
+                     boolean jjtc000 = true;\r
+                     jjtree.openNodeScope(jjtn000);\r
+/*@egen*/ Token t;\r
+} {/*@bgen(jjtree) for_index */\r
+        try {\r
+/*@egen*/\r
+       //IDENT [ in expression ]\r
+       t=<IDENT> { jjtn000.op = t.image; } ( "in" expression() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void while_statement() : {/*@bgen(jjtree) while_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTWHILE_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) while_statement */\r
+        try {\r
+/*@egen*/\r
+//     while expression loop\r
+//     { statement ";" }\r
+//     end while\r
+       "while" expression() "loop"\r
+               ( statement() ";" )*\r
+       "end" "while"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void when_equation() : {/*@bgen(jjtree) when_equation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTWHEN_EQUATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) when_equation */\r
+        try {\r
+/*@egen*/\r
+//     when expression then\r
+//     { equation ";" }\r
+//     { elsewhen expression then\r
+//     { equation ";" } }\r
+//     end when\r
+       "when" expression() "then"\r
+               ( equation() ";" )*\r
+       ( "elsewhen" expression() "then"\r
+               ( equation() ";" )*\r
+       )*\r
+       "end" "when"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void when_statement() : {/*@bgen(jjtree) when_statement */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTWHEN_STATEMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) when_statement */\r
+        try {\r
+/*@egen*/\r
+//     when expression then\r
+//     { statement ";" }\r
+//     { elsewhen expression then\r
+//     { statement ";" } }\r
+//     end when\r
+       "when" expression() "then"\r
+               ( statement() ";" )*\r
+       ( "elsewhen" expression() "then"\r
+               ( statement() ";" )*\r
+       )*\r
+       "end" "when"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r}\r
+\r
+void connect_clause() : {/*@bgen(jjtree) connect_clause */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCONNECT_CLAUSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) connect_clause */\r
+        try {\r
+/*@egen*/\r
+//     connect "(" component_reference "," component_reference ")"\r
+       "connect" "(" component_reference() "," component_reference() ")"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+/*** Expressions ***************************************************/\r
+void expr() : {/*@bgen(jjtree) expr */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXPR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) expr */\r
+        try {\r
+/*@egen*/\r
+       simple_expression() <EOF>\r
+       |\r
+       "if" expression() "then" expression() ( "elseif" expression() "then" expression() )*\r
+       "else" expression() <EOF>/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void if_expression() : {/*@bgen(jjtree) if_expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTIF_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) if_expression */\r
+        try {\r
+/*@egen*/\r
+       "if" expression() "then" expression() ( "elseif" expression() "then" expression() )*\r
+       "else" expression()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+\r
+void expression() : {/*@bgen(jjtree) expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) expression */\r
+        try {\r
+/*@egen*/\r
+       simple_expression() | if_expression()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void simple_expression() : {/*@bgen(jjtree) simple_expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSIMPLE_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) simple_expression */\r
+        try {\r
+/*@egen*/\r
+       logical_expression() ( ":" logical_expression() ( ":" logical_expression() )? )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}      \r
+\r
+void logical_expression() : {/*@bgen(jjtree) logical_expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTLOGICAL_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) logical_expression */\r
+        try {\r
+/*@egen*/\r
+       logical_term() ( "or" logical_term() )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}      \r
+\r
+void logical_term() : {/*@bgen(jjtree) logical_term */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTLOGICAL_TERM);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) logical_term */\r
+        try {\r
+/*@egen*/\r
+       logical_factor() ( "and" logical_factor() )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void logical_factor() : {/*@bgen(jjtree) logical_factor */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTLOGICAL_FACTOR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) logical_factor */\r
+        try {\r
+/*@egen*/\r
+       ( "not" )? relation()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void relation() : {/*@bgen(jjtree) relation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTRELATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) relation */\r
+        try {\r
+/*@egen*/\r
+       arithmetic_expression() ( rel_op() arithmetic_expression() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void rel_op() : {/*@bgen(jjtree) rel_op */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTREL_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) rel_op */\r
+        try {\r
+/*@egen*/\r
+       "<"/*@bgen(jjtree)*/\r
+            {\r
+              jjtree.closeNodeScope(jjtn000, true);\r
+              jjtc000 = false;\r
+            }\r
+/*@egen*/ { jjtn000.op = "< ";} | "<="/*@bgen(jjtree)*/\r
+                                         {\r
+                                           jjtree.closeNodeScope(jjtn000, true);\r
+                                           jjtc000 = false;\r
+                                         }\r
+/*@egen*/ { jjtn000.op = "<=";} | ">"/*@bgen(jjtree)*/\r
+                                                                     {\r
+                                                                       jjtree.closeNodeScope(jjtn000, true);\r
+                                                                       jjtc000 = false;\r
+                                                                     }\r
+/*@egen*/ { jjtn000.op = " >";} | ">="/*@bgen(jjtree)*/\r
+                                                                                                  {\r
+                                                                                                    jjtree.closeNodeScope(jjtn000, true);\r
+                                                                                                    jjtc000 = false;\r
+                                                                                                  }\r
+/*@egen*/ { jjtn000.op = " >=";} | "=="/*@bgen(jjtree)*/\r
+                                                                                                                                {\r
+                                                                                                                                  jjtree.closeNodeScope(jjtn000, true);\r
+                                                                                                                                  jjtc000 = false;\r
+                                                                                                                                }\r
+/*@egen*/ { jjtn000.op = "==";} | "<>"/*@bgen(jjtree)*/\r
+                                                                                                                                                             {\r
+                                                                                                                                                               jjtree.closeNodeScope(jjtn000, true);\r
+                                                                                                                                                               jjtc000 = false;\r
+                                                                                                                                                             }\r
+/*@egen*/ { jjtn000.op = "<>";}/*@bgen(jjtree)*/\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void arithmetic_expression() : {/*@bgen(jjtree) arithmetic_expression */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARITHMETIC_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) arithmetic_expression */\r
+    try {\r
+/*@egen*/\r
+    (add_op())? term() (add_op() term())*/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void add_op() : {/*@bgen(jjtree) add_op */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTADD_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) add_op */\r
+    try {\r
+/*@egen*/\r
+    "+"/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        }\r
+/*@egen*/ { jjtn000.op = "+";} | "-"/*@bgen(jjtree)*/\r
+                                   {\r
+                                     jjtree.closeNodeScope(jjtn000, true);\r
+                                     jjtc000 = false;\r
+                                   }\r
+/*@egen*/ { jjtn000.op = "-";} | ".+" | ".-"/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+\r
+void term() : {/*@bgen(jjtree) term */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTTERM);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) term */\r
+    try {\r
+/*@egen*/\r
+    factor() ( mul_op() factor() )*/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void mul_op() : {/*@bgen(jjtree) mul_op */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTMUL_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) mul_op */\r
+    try {\r
+/*@egen*/\r
+    "*"/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        }\r
+/*@egen*/ { jjtn000.op = "*";} | "/"/*@bgen(jjtree)*/\r
+                                   {\r
+                                     jjtree.closeNodeScope(jjtn000, true);\r
+                                     jjtc000 = false;\r
+                                   }\r
+/*@egen*/ { jjtn000.op = "/";} | ".*"/*@bgen(jjtree)*/\r
+                                                               {\r
+                                                                 jjtree.closeNodeScope(jjtn000, true);\r
+                                                                 jjtc000 = false;\r
+                                                               }\r
+/*@egen*/ { jjtn000.op = ".*";} | "./"/*@bgen(jjtree)*/\r
+                                                                                             {\r
+                                                                                               jjtree.closeNodeScope(jjtn000, true);\r
+                                                                                               jjtc000 = false;\r
+                                                                                             }\r
+/*@egen*/  { jjtn000.op = "./";}/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void factor() : {/*@bgen(jjtree) factor */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFACTOR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) factor */\r
+        try {\r
+/*@egen*/\r
+       primary() ( factor_op() primary() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void factor_op() : {/*@bgen(jjtree) factor_op */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFACTOR_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) factor_op */\r
+    try {\r
+/*@egen*/\r
+    "^"/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        }\r
+/*@egen*/ { jjtn000.op = "^";} | ".^"/*@bgen(jjtree)*/\r
+                                    {\r
+                                      jjtree.closeNodeScope(jjtn000, true);\r
+                                      jjtc000 = false;\r
+                                    }\r
+/*@egen*/ { jjtn000.op = ".^";}/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void der_initial() : {/*@bgen(jjtree) der_initial */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTDER_INITIAL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/ \r
+} {/*@bgen(jjtree) der_initial */\r
+  try {\r
+/*@egen*/\r
+  (  (name() { jjtn000.op = "application"; } |"der" { jjtn000.op = "der";} |"initial" { jjtn000.op = "initial";} ) function_call_args() )/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r
+\r
+void subscript_2() : {/*@bgen(jjtree) subscript_2 */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSUBSCRIPT_2);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) subscript_2 */\r
+  try {\r
+/*@egen*/\r
+  ( expression_list() ( ";" expression_list() )* )/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r
+\r
+void array() : {/*@bgen(jjtree) array */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARRAY);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r} {/*@bgen(jjtree) array */\r
+  try {\r
+/*@egen*/\r
+  ( "{" function_arguments() "}" )/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+    }\r
+  }\r
+/*@egen*/\r}\r
+\r
+void primary() : {/*@bgen(jjtree) primary */\r
+                   SimpleNode jjtn000 = new SimpleNode(JJTPRIMARY);\r
+                   boolean jjtc000 = true;\r
+                   jjtree.openNodeScope(jjtn000);\r
+/*@egen*/ Token t;\r
+} {/*@bgen(jjtree) primary */\r
+        try {\r
+/*@egen*/\r
+       t=<UNSIGNED_NUMBER>/*@bgen(jjtree)*/\r
+                             {\r
+                               jjtree.closeNodeScope(jjtn000, true);\r
+                               jjtc000 = false;\r
+                             }\r
+/*@egen*/  { jjtn000.op = token.image; }\r
+  | t=<UNSIGNED_INTEGER>/*@bgen(jjtree)*/\r
+                          {\r
+                            jjtree.closeNodeScope(jjtn000, true);\r
+                            jjtc000 = false;\r
+                          }\r
+/*@egen*/  { jjtn000.op = token.image; }\r
+  | t=<STRING>/*@bgen(jjtree)*/\r
+                {\r
+                  jjtree.closeNodeScope(jjtn000, true);\r
+                  jjtc000 = false;\r
+                }\r
+/*@egen*/  { jjtn000.op = token.image; }\r
+  | t="false"/*@bgen(jjtree)*/\r
+               {\r
+                 jjtree.closeNodeScope(jjtn000, true);\r
+                 jjtc000 = false;\r
+               }\r
+/*@egen*/  { jjtn000.op = token.image; }\r
+  | t="true"/*@bgen(jjtree)*/\r
+             {\r
+               jjtree.closeNodeScope(jjtn000, true);\r
+               jjtc000 = false;\r
+             }\r
+/*@egen*/ { jjtn000.op = token.image; } \r
+  |   LOOKAHEAD( (name()|"der"|"initial") "(" ) der_initial()\r  | component_reference()\r
+  /* | "(" output_expression_list() ")" */ // Not needed, replaced with following:\r
+  | "(" expression() ")"\r
+  | "[" subscript_2() "]"\r
+  | array()\r
+  | "end"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+String name() : {/*@bgen(jjtree) name */\r
+    SimpleNode jjtn000 = new SimpleNode(JJTNAME);\r
+    boolean jjtc000 = true;\r
+    jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+    String ret = new String("");\r
+} {/*@bgen(jjtree) name */\r
+        try {\r
+/*@egen*/\r
+//     [ "." ] IDENT { "." IDENT }\r
+       ( "." { ret += "."; } )?\r
+          <IDENT> { ret += token.image; jjtn000.op = token.image;}\r
+          ( "." { ret += "."; }\r
+          <IDENT> { ret += token.image; jjtn000.op = token.image;}\r
+       )*/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+        }\r
+/*@egen*/\r
+       {\r        return ret;\r
+    }/*@bgen(jjtree)*/\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void component_reference() : {/*@bgen(jjtree) component_reference */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTCOMPONENT_REFERENCE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+  Token t;\r
+} {/*@bgen(jjtree) component_reference */\r
+        try {\r
+/*@egen*/\r
+//     [ "." ] IDENT [ array_subscripts ] { "." IDENT [ array_subscripts ] }\r
+       ( "." )? t=<IDENT> { jjtn000.op = t.image; } ( array_subscripts() )? ( "." <IDENT> ( array_subscripts() )? )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void function_call_args() : {/*@bgen(jjtree) function_call_args */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFUNCTION_CALL_ARGS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) function_call_args */\r
+        try {\r
+/*@egen*/\r
+//     "(" [ function_arguments ] ")"\r
+       "(" ( function_arguments() )? ")"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void function_arguments() : {/*@bgen(jjtree) function_arguments */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTFUNCTION_ARGUMENTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) function_arguments */\r
+         try {\r
+/*@egen*/\r
+       //expression [ "," function_arguments | for for_indices ]\r
+       //| named_arguments\r
+        LOOKAHEAD(2) expression() ( "," function_arguments() | "for" for_indices() { jjtn000.op = "for"; } )?\r
+       | named_arguments()/*@bgen(jjtree)*/\r
+         } catch (Throwable jjte000) {\r
+           if (jjtc000) {\r
+             jjtree.clearNodeScope(jjtn000);\r
+             jjtc000 = false;\r
+           } else {\r
+             jjtree.popNode();\r
+           }\r
+           if (jjte000 instanceof RuntimeException) {\r
+             throw (RuntimeException)jjte000;\r
+           }\r
+           if (jjte000 instanceof ParseException) {\r
+             throw (ParseException)jjte000;\r
+           }\r
+           throw (Error)jjte000;\r
+         } finally {\r
+           if (jjtc000) {\r
+             jjtree.closeNodeScope(jjtn000, true);\r
+           }\r
+         }\r
+/*@egen*/\r
+}\r
+\r
+void named_arguments() : {/*@bgen(jjtree) named_arguments */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTNAMED_ARGUMENTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) named_arguments */\r
+        try {\r
+/*@egen*/\r
+//     named_argument [ "," named_arguments ]  \r
+       named_argument() ( "," named_arguments() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void named_argument() : {/*@bgen(jjtree) named_argument */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTNAMED_ARGUMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) named_argument */\r
+        try {\r
+/*@egen*/      \r
+       <IDENT> "=" expression()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void output_expression_list() : {/*@bgen(jjtree) output_expression_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTOUTPUT_EXPRESSION_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) output_expression_list */\r
+        try {\r
+/*@egen*/\r
+//     [ expression ] { "," [ expression ] }  \r
+       ( expression() )? ( "," ( expression() )? )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void expression_list() : {/*@bgen(jjtree) expression_list */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTEXPRESSION_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) expression_list */\r
+    try {\r
+/*@egen*/\r
+//     expression { "," expression }\r
+    expression() ( "," expression() )*/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void array_subscripts() : {/*@bgen(jjtree) array_subscripts */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTARRAY_SUBSCRIPTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) array_subscripts */\r
+        try {\r
+/*@egen*/\r
+//     "[" subscript { "," subscript } "]" \r
+       "["     subscript()     ( "," subscript() )* "]"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void subscript() : {/*@bgen(jjtree) subscript */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTSUBSCRIPT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) subscript */\r
+        try {\r
+/*@egen*/\r
+//     ":" | expression  \r     ":"/*@bgen(jjtree)*/\r
+            {\r
+              jjtree.closeNodeScope(jjtn000, true);\r
+              jjtc000 = false;\r
+            }\r
+/*@egen*/ { jjtn000.op = "all"; } | expression()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/ \r
+}\r
+\r
+String comment()       : {\r
+    String ret;\r} {\r// string_comment [ annotation ]\r
+       ret = string_comment() ( annotation() )?\r
+       {\r          return ret;\r
+       }\r
+}\r
+\r
+String string_comment()       : {\r
+    String ret = null;\r
+} {\r
+//     [ STRING { "+" STRING } ]  \r
+       ( <STRING> { ret = new String(token.image); }\r
+           ( "+" { ret += "+"; }\r
+               <STRING> { ret += token.image; }\r
+           )*\r
+       )?\r
+       {\r          return ret;\r
+       } \r}\r
+\r
+void annotation() : {/*@bgen(jjtree) annotation */\r
+  SimpleNode jjtn000 = new SimpleNode(JJTANNOTATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+/*@egen*/\r
+} {/*@bgen(jjtree) annotation */\r
+        try {\r
+/*@egen*/\r
+//     annotation class_modification\r
+       "annotation" class_modification()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+          }\r
+        }\r
+/*@egen*/  \r
+}\r  \r
+\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelicaParser.jjt b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ModelicaParser.jjt
new file mode 100644 (file)
index 0000000..2fc5f9c
--- /dev/null
@@ -0,0 +1,788 @@
+options {\r
+  JDK_VERSION = "1.6";\r
+  STATIC = false;\r
+}\r
+\r
+PARSER_BEGIN(ModelParser)\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class ModelParser {\r
+\r
+  private ArrayList<Parameter> inputs = new ArrayList<Parameter>();\r
+  private ArrayList<Parameter> outputs = new ArrayList<Parameter>();\r
+  \r
+  private enum InterfaceVariableType\r  {\r    INPUT, OUTPUT, OTHER\r
+  }\r
+\r
+  public class Parameter\r  {\r
+    public String name;\r
+    public boolean optional;\r
+    public String description;\r
+    public String type;\r
+    \r
+    public Parameter()\r    {\r
+      name = new String("");\r
+      optional = false;\r
+      description = null;\r
+      type = null;\r
+    }\r  }\r
+\r
+  public ArrayList<Parameter> getInputs()\r
+  {\r
+    return inputs;\r
+  }\r
+    \r
+  public ArrayList<Parameter> getOutputs()\r
+  {\r
+    return outputs;\r
+  }\r
+    \r
+}\r
+\r
+PARSER_END(ModelParser)\r
+\r
+/*** Lexer *********************************************************/\r
+\r
+SKIP:\r
+{ <WHITESPACE: " " | "\n" | "\r" | "\t" > \r
+| <COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/" >  \r
+| <COMMENT2: "//" (~["\n"])* >\r
+}\r
+\r
+TOKEN:\r
+{\r
+"algorithm"     | "discrete"    | "false"   | "model"   | "redeclare"\r
+| "and"         | "each"        | "final"   | "not"     | "replaceable"\r
+| "annotation" | "else"         | "flow"    | "operator" | "return"\r
+|"assert"       | "elseif"      | "for"     | "or"      | "stream"\r
+| "block"       | "elsewhen"    | "function" | "outer"  | "then"\r
+| "break"       | "encapsulated" | "if"     | "output"  | "true"\r
+| "class"       | "end"         | "import"  | "package" | "type"\r
+| "connect"     | "enumeration" | "in"      | "parameter" | "when"\r
+| "connector"   | "equation"    | "initial" | "partial" | "while"\r
+| "constant"    | "expandable"  | "inner"   | "protected" | "within"\r
+| "constrainedby" | "extends"   | "input"   | "public"\r
+| "der"         | "external"    | "loop"    | "record"\r
+| "(" | ")" | "{" | "}" | "[" | "]" | "." | ":" | ";" | ","\r
+| "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+| "+" | "-" | ".+" | ".-"\r
+| "*" | "/" | ".*" | "./"\r
+| "^" | ".^"\r
+| "=" | ":=" \r
+| <IDENT: ["a"-"z","A"-"Z","_"] (["a"-"z","A"-"Z","_",".", "0"-"9"])* >\r
+| <STRING: "\"" (~["\"", "\\", "\n"] | "\\" ~["\n"])* "\"">\r
+    { matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); }\r
+| <EXP: "e" | "e-" | "E" | "E-" >\r
+| <UNSIGNED_INTEGER: (["0"-"9"])+ >\r
+| <UNSIGNED_NUMBER:  \r
+    ( <UNSIGNED_INTEGER> "." (<UNSIGNED_INTEGER>)? (<EXP> <UNSIGNED_INTEGER>)?\r
+    | "." <UNSIGNED_INTEGER> (<EXP> <UNSIGNED_INTEGER>)?\r
+    | <UNSIGNED_INTEGER> <EXP> <UNSIGNED_INTEGER>\r
+    ) >\r
+}\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+\r
+Node parse() : {\r
+} {\r
+    stored_definition() <EOF>\r
+    { return jjtThis; }\r
+}\r
+\r
+/*** Stored Definition - Within ************************************/\r
+\r
+Node stored_definition() #STORED : {\r
+} {\r
+//  stored_definition:\r
+//  [ within [ name ] ";" ]\r
+//  { [ final ] class_definition ";" }\r
+    ( "within" ( name() )? ";" )?\r
+    ( ( "final" )? class_definition() ";" )*\r
+    { return jjtThis; }\r  \r      \r
+}\r
+\r
+/*** Class Definition **********************************************/\r
+  \r
+void class_definition() : {\r
+} {\r
+//  class_definition :\r
+//  [ encapsulated ]\r
+//  [ partial\r
+//  ] ( class modelrecordblock expandableconnectortype\r
+//  | | | | [ ] | | package | function | operator | operator function | operator record )\r
+//  class_specifier\r
+    ( "encapsulated" )?\r
+    ( "partial" )?\r
+    ( "class" { jjtThis.op = "class"; } | "model" { jjtThis.op = "model"; } | "record" | "block" | ( "expandable" )? "connector" | "type" |\r
+    "package" | "function" { jjtThis.op = "function"; } | "operator" | "operator function" | "operator record" )\r
+    class_specifier()\r
+}\r
+\r
+\r
+void class_specifier() : { Token t;\r
+} {\r
+//  class_specifier :\r
+//  IDENT string_comment composition end IDENT\r
+//  | IDENT "=" base_prefix name [ array_subscripts ]\r
+//  [ class_modification ] comment\r
+//  | IDENT "=" enumeration "(" ( [enum_list] | ":" ) ")" comment\r
+//  | IDENT "=" der "(" name "," IDENT { "," IDENT } ")" comment\r
+//  | extends IDENT [ class_modification ] string_comment composition\r
+//  end IDENT  \r
+    LOOKAHEAD(2) t=<IDENT> { jjtThis.op = t.image; } string_comment() composition() "end" <IDENT>\r
+    | LOOKAHEAD(2) <IDENT> "=" base_prefix() name() ( array_subscripts() )? ( class_modification() )? comment()\r
+    | LOOKAHEAD(3)  <IDENT> "=" "der" "(" name() "," <IDENT> ( "," <IDENT> )* ")" comment()\r
+    | LOOKAHEAD(3) <IDENT> "=" "enumeration" "(" ( ( enum_list() )? | ":" ) ")" comment()\r
+    //| "extends" <IDENT> ( class_modification() )? string_comment() composition() "end" <IDENT> \r
+}\r
+\r
+void base_prefix() : {\r
+} {\r
+    type_prefix()\r
+}\r
+\r
+void enum_list() : {\r
+} {\r
+//  enumeration_literal { "," enumeration_literal}\r
+    enumeration_literal() ( "," enumeration_literal() )* \r
+}\r
+\r
+void enumeration_literal() : {\r
+} {\r
+    <IDENT> comment()\r
+}\r
+\r
+void parse_composition() : {\r
+} {\r
+    composition() <EOF>\r
+}\r
+\r
+void composition() : {\r
+} {\r
+//  element_list\r
+//  { public element_list |\r
+//  protected element_list |\r
+//  equation_section |\r
+//  algorithm_section\r
+//  }\r
+//  [ external [ language_specification ]\r
+//  [ external_function_call ] [ annotation ] ";" ]\r
+//  [ annotation ";" ]\r
+    element_list()\r
+    ( LOOKAHEAD(2) "public" element_list() | "protected" element_list() | equation_section() | algorithm_section() )*\r
+    ( "external" ( language_specification() )? ( external_function_call() )? ( annotation() )? ";" )?\r
+    ( annotation() ";" )?\r
+}\r
+\r
+void language_specification() : {\r
+} {\r
+    <STRING>\r
+}\r
+\r
+void external_function_call() : {\r
+} {\r
+//  [ component_reference "=" ]\r
+//  IDENT "(" [ expression_list ] ")"\r
+    ( component_reference() "=" )?\r
+    <IDENT> "(" ( expression_list() )? ")"\r
+}\r
+\r
+void element_list() : {\r
+} {\r
+    ( element() ";" )*\r
+}\r
+\r
+Node element() : {\r
+} {\r
+//  import_clause |\r
+//  extends_clause |\r
+//  [ redeclare ]\r
+//  [ final ]\r
+//  [ inner ] [ outer ]\r
+//  ( ( class_definition | component_clause) |\r
+//  replaceable ( class_definition | component_clause)\r
+//  [constraining_clause comment])\r
+    import_clause() { return jjtThis; } |\r
+    extends_clause() { return jjtThis; } |\r
+    ( "redeclare" )?\r
+    ( "final" )?\r
+    ( "inner" { jjtThis.op = "inner"; } )? ( "outer" { jjtThis.op = "outer"; } )?\r
+    ( (class_definition() | component_clause()) |\r
+        "replaceable" (class_definition() | component_clause())\r
+        (constraining_clause() comment())?)\r
+    { return jjtThis; }\r
+}\r
+\r
+void import_clause() : {\r
+} {\r
+//  import ( IDENT "=" name | name ["." "*"] ) comment\r
+    "import" (LOOKAHEAD(2) <IDENT> "=" name() | name() ("." "*")? ) comment()\r
+}\r
+\r
+/*** Extends *******************************************************/\r
+void extends_clause() : {\r
+} {\r
+//  extends name [ class_modification ] [annotation]\r
+    "extends" name() ( class_modification() )? ( annotation() )?\r
+}\r
+\r
+void constraining_clause() : {\r
+} {\r
+//  constrainedby name [ class_modification ]\r
+    "constrainedby" name() ( class_modification() )?\r
+}\r
+\r
+/*** Component Clause **********************************************/\r
+void component_clause() : {\r
+    InterfaceVariableType ioType = InterfaceVariableType.OTHER;\r
+    String typeSpecifier = "";\r
+    //String arraySubscripts = null;\r
+    ArrayList<Parameter> componentList = new ArrayList<Parameter>();\r
+} {\r
+  \r
+//  type_prefix type_specifier [ array_subscripts ] component_list\r
+    ( ioType = type_prefix() )\r
+    ( typeSpecifier = type_specifier() )\r
+    ( /*arraySubscripts =*/ array_subscripts() )?\r
+    ( componentList = component_list() )\r
+    {\r
+        if (ioType == InterfaceVariableType.INPUT) {\r
+            for (Parameter input : componentList) {\r
+                input.type = typeSpecifier;\r
+                inputs.add(input);\r            }\r
+        } else if (ioType == InterfaceVariableType.OUTPUT) {\r
+            for (Parameter output : componentList) {\r
+                output.type = typeSpecifier;          \r
+                outputs.add(output);\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+InterfaceVariableType type_prefix() : {\r
+    InterfaceVariableType type = InterfaceVariableType.OTHER;\r
+} {\r
+//  [ flow | stream ]\r
+//  [ discrete | parameter | constant ] [ input | output ]\r
+    ( "flow" | "stream" )?\r
+    ( "discrete" { jjtThis.op = "discrete"; }| "parameter" { jjtThis.op = "parameter"; }| "constant" { jjtThis.op = "constant"; })?\r
+    ( "output" { type = InterfaceVariableType.OUTPUT; jjtThis.op = "output"; }\r
+        | "input" { type = InterfaceVariableType.INPUT; jjtThis.op = "input"; }\r
+    )?\r
+    {\r
+        return type;\r
+    }\r
+}\r
+String type_specifier() : {\r
+    String ret = new String("");\r
+} {\r
+       ret = name()\r
+       {\r
+           jjtThis.op = ret;\r        return ret;\r
+    }\r
+}\r
+\r
+ArrayList<Parameter> component_list() : {\r
+    ArrayList<Parameter> ret = new ArrayList<Parameter>();\r
+    Parameter temp;\r
+} {\r
+//     component_declaration { "," component_declaration }\r
+       temp = component_declaration() { ret.add(temp); }\r    ( "," temp = component_declaration() { ret.add(temp); } )*\r
+       {\r          return ret;\r
+       }\r
+}\r
+\r
+Parameter component_declaration() : {\r
+    Parameter ret;\r
+    String temp = "";\r
+} {\r
+//     declaration [ conditional_attribute ] comment\r
+       ret = declaration() ( conditional_attribute() )? ret.description = comment()\r
+    {\r
+        return ret;\r
+    }\r
+}\r
+\r
+void conditional_attribute() : {\r
+} {\r
+       "if" expression()\r
+}\r
+\r
+Parameter declaration() : { Token t;\r
+    // Parameter here without comment yet.\r
+    Parameter ret = new Parameter();\r
+} {\r
+//     IDENT [ array_subscripts ] [ modification ]\r
+       <IDENT> { ret.name = new String(token.image); jjtThis.op = token.image; }\r
+       ( array_subscripts() )?\r
+       ( ret.optional = modification() )?\r
+       {\r              return ret;\r    }\r
+}\r
+\r
+/*** Modification **********************************************/\r
+boolean modification() : {\r
+    boolean optional = false;\r
+} {\r
+//     class_modification [ "=" expression ]\r
+//     | "=" expression\r
+//     | ":=" expression\r
+       ( class_modification() ( "=" expression() )?\r
+       | "=" expression() { optional = true; }\r
+       | ":=" expression() { optional = true; } )\r
+       {\r          return optional;\r
+       } \r
+}\r
+\r
+void class_modification() : {\r
+} {\r
+//     "(" [ argument_list ] ")"\r
+       "(" ( argument_list() )? ")"\r
+}\r
+\r
+void argument_list() : {\r
+} {\r
+// argument { "," argument }\r
+       argument() ( "," argument() )*\r
+}\r
+\r
+void argument() : {\r
+} {\r
+//     element_modification_or_replaceable\r
+//     | element_redeclaration\r
+       element_modification_or_replaceable() |\r
+       element_redeclaration()\r
+}\r
+\r
+void element_modification_or_replaceable() : {\r
+} {\r
+//     [ each ] [ final ] ( element_modification | element_replaceable)\r
+       ( "each" )? ( "final" )? ( element_modification() | element_replaceable() )\r}\r
+\r
+void element_modification() : {\r
+} {\r
+//     name [ modification ] string_comment\r
+       name() ( modification() )? string_comment()\r
+}\r
+\r
+void element_redeclaration() : {\r
+} {\r
+//     redeclare [ each ] [ final ]\r
+//     ( ( class_definition | component_clause1) | element_replaceable )\r
+       "redeclare" ( "each" )? ( "final" )?\r
+       ( ( class_definition() | component_clause1() ) | element_replaceable() )\r}\r
+\r
+void element_replaceable() : {\r
+} {\r
+//     replaceable ( class_definition | component_clause1)\r
+//     [constraining_clause]\r
+       "replaceable" ( class_definition() | component_clause1() ) ( constraining_clause() )?\r
+}\r
+\r
+void component_clause1() : {\r
+} {\r
+//     type_prefix type_specifier component_declaration1\r
+       type_prefix() type_specifier() component_declaration1()\r
+}\r
+\r
+void component_declaration1() : {\r
+} {\r
+       declaration() comment()\r
+}\r
+\r
+\r
+/*** Equations *************************************************/\r
+void equation_section() : {\r
+} {\r
+//     [ initial ] equation { equation ";" }\r
+       ( "initial" { jjtThis.op = "initial"; } )? "equation" ( LOOKAHEAD(2) equation() ";" )*\r
+}\r
+\r
+void algorithm_section() : {\r
+} {\r
+//     [ initial ] algorithm { statement ";" }\r
+       ( "initial" )? "algorithm" ( statement() ";" )*\r}\r
+\r
+void assignment() : {\r
+} {\r
+  ( simple_expression() "=" expression() )\r
+}\r  \r\r
+\r
+Node equation() : {\r
+} {\r
+//     ( simple_expression "=" expression\r
+//     | if_equation\r
+//     | for_equation\r
+//     | connect_clause\r
+//     | when_equation\r
+//     | IDENT function_call_args )\r
+//     comment\r
+       ( LOOKAHEAD(3) assignment()\r
+               | if_equation()\r
+               | for_equation()\r
+               | connect_clause()\r
+               | when_equation()\r
+               | <IDENT> function_call_args() )\r
+       comment()\r    { return jjtThis; }\r
+}\r
+\r
+void statement() : {\r
+} {\r
+//     ( component_reference ( ":=" expression | function_call_args )\r
+//     | "(" output_expression_list ")" ":=" component_reference function_call_args\r
+//     | break\r
+//     | return\r
+//     | if_statement\r
+//     | for_statement\r
+//     | while_statement\r
+//     | when_statement )\r
+//     comment\r
+       ( component_reference() ( ":=" expression() | function_call_args() )\r
+               | "(" output_expression_list() ")" ":=" component_reference() function_call_args()\r
+               | "break"\r
+               | "return"\r
+               | if_statement()\r
+               | for_statement()\r
+               | while_statement()\r
+               | when_statement() )\r
+       comment() \r       \r
+}\r
+\r
+void if_equation() : {\r
+} {\r
+//     if expression then\r
+//     { equation ";" }\r
+//     { elseif expression then\r
+//     { equation ";" }\r
+//     }\r
+//     [ else\r
+//     { equation ";" }\r
+//     ]\r
+//     end if\r
+       "if" expression() "then"\r
+               ( equation() ";" )*\r
+       ( "elseif" expression() "then"\r
+               ( equation() ";" )*\r
+       )*\r
+       ( "else"\r
+               ( equation() ";" )*\r
+       )?\r
+       "end" "if"\r}\r
+\r
+void then_statement() : {\r
+} {\r
+  ( statement() )\r}\r
+\r
+void elseif_statement() : {\r
+} {\r
+  ( statement() )\r
+}\r
+\r
+void else_statement() : {\r
+} {\r
+  ( statement() )\r
+}\r
+\r
+void if_statement() : {\r
+} {\r
+//     if expression then\r
+//     { statement ";" }\r
+//     { elseif expression then\r
+//     { statement ";" }\r
+//     }\r
+//     [ else\r
+//     { statement ";" }\r
+//     ]\r
+//     end if\r
+       "if" expression() "then"\r
+               ( then_statement() ";" )*\r
+       ( "elseif" expression() "then"\r
+               ( elseif_statement() ";" )*\r
+       )*\r
+       ( "else"\r
+               ( else_statement() ";" )*\r
+       )?\r
+       "end" "if"\r}\r
+\r
+void for_equation() : {\r
+} {\r
+//     for for_indices loop\r
+//     { equation ";" }\r
+//     end for\r
+       "for" for_indices() "loop"\r
+               ( equation() ";" )*\r
+       "end" "for"\r}\r
+\r
+void for_statement() : {\r
+} {\r
+//     for for_indices loop\r
+//     { equation ";" }\r
+//     end for\r
+       "for" for_indices() "loop"\r
+               ( statement() ";" )*\r
+       "end" "for"\r}\r
+\r
+void for_indices() : {\r
+} {\r
+       //for_index {"," for_index}\r
+       for_index() ("," for_index())*\r
+}\r
+\r
+void for_index() : { Token t;\r
+} {\r
+       //IDENT [ in expression ]\r
+       t=<IDENT> { jjtThis.op = t.image; } ( "in" expression() )?\r
+}\r
+\r
+void while_statement() : {\r
+} {\r
+//     while expression loop\r
+//     { statement ";" }\r
+//     end while\r
+       "while" expression() "loop"\r
+               ( statement() ";" )*\r
+       "end" "while"\r}\r
+\r
+void when_equation() : {\r
+} {\r
+//     when expression then\r
+//     { equation ";" }\r
+//     { elsewhen expression then\r
+//     { equation ";" } }\r
+//     end when\r
+       "when" expression() "then"\r
+               ( equation() ";" )*\r
+       ( "elsewhen" expression() "then"\r
+               ( equation() ";" )*\r
+       )*\r
+       "end" "when"\r}\r
+\r
+void when_statement() : {\r
+} {\r
+//     when expression then\r
+//     { statement ";" }\r
+//     { elsewhen expression then\r
+//     { statement ";" } }\r
+//     end when\r
+       "when" expression() "then"\r
+               ( statement() ";" )*\r
+       ( "elsewhen" expression() "then"\r
+               ( statement() ";" )*\r
+       )*\r
+       "end" "when"\r}\r
+\r
+void connect_clause() : {\r
+} {\r
+//     connect "(" component_reference "," component_reference ")"\r
+       "connect" "(" component_reference() "," component_reference() ")"\r
+}\r
+\r
+/*** Expressions ***************************************************/\r
+void expr() : {\r
+} {\r
+       simple_expression() <EOF>\r
+       |\r
+       "if" expression() "then" expression() ( "elseif" expression() "then" expression() )*\r
+       "else" expression() <EOF>\r
+}\r
+\r
+void if_expression() : {\r
+} {\r
+       "if" expression() "then" expression() ( "elseif" expression() "then" expression() )*\r
+       "else" expression()\r
+}\r
+\r
+\r
+void expression() : {\r
+} {\r
+       simple_expression() | if_expression()\r
+}\r
+\r
+void simple_expression() : {\r
+} {\r
+       logical_expression() ( ":" logical_expression() ( ":" logical_expression() )? )?\r
+}      \r
+\r
+void logical_expression() : {\r
+} {\r
+       logical_term() ( "or" logical_term() )*\r
+}      \r
+\r
+void logical_term() : {\r
+} {\r
+       logical_factor() ( "and" logical_factor() )*\r
+}\r
+\r
+void logical_factor() : {\r
+} {\r
+       ( "not" )? relation()\r
+}\r
+\r
+void relation() : {\r
+} {\r
+       arithmetic_expression() ( rel_op() arithmetic_expression() )?\r
+}\r
+\r
+void rel_op() : {\r
+} {\r
+       "<" { jjtThis.op = "< ";} | "<=" { jjtThis.op = "<=";} | ">" { jjtThis.op = " >";} | ">=" { jjtThis.op = " >=";} | "==" { jjtThis.op = "==";} | "<>" { jjtThis.op = "<>";}\r
+}\r
+\r
+void arithmetic_expression() : {\r
+} {\r
+    (add_op())? term() (add_op() term())*\r
+}\r
+\r
+void add_op() : {\r
+} {\r
+    "+" { jjtThis.op = "+";} | "-" { jjtThis.op = "-";} | ".+" | ".-"\r
+}\r
+\r
+\r
+void term() : {\r
+} {\r
+    factor() ( mul_op() factor() )*\r
+}\r
+\r
+void mul_op() : {\r
+} {\r
+    "*" { jjtThis.op = "*";} | "/" { jjtThis.op = "/";} | ".*" { jjtThis.op = ".*";} | "./"  { jjtThis.op = "./";}\r
+}\r
+\r
+void factor() : {\r
+} {\r
+       primary() ( factor_op() primary() )?\r
+}\r
+\r
+void factor_op() : {\r
+} {\r
+    "^" { jjtThis.op = "^";} | ".^" { jjtThis.op = ".^";}\r
+}\r
+\r
+void der_initial() : { \r
+} {\r
+  (  (name() { jjtThis.op = "application"; } |"der" { jjtThis.op = "der";} |"initial" { jjtThis.op = "initial";} ) function_call_args() )\r
+}\r
+\r
+void subscript_2() : {\r
+} {\r
+  ( expression_list() ( ";" expression_list() )* )\r
+}\r
+\r
+void array() : {\r} {\r
+  ( "{" function_arguments() "}" )\r}\r
+\r
+void primary() : { Token t;\r
+} {\r
+       t=<UNSIGNED_NUMBER>  { jjtThis.op = token.image; }\r
+  | t=<UNSIGNED_INTEGER>  { jjtThis.op = token.image; }\r
+  | t=<STRING>  { jjtThis.op = token.image; }\r
+  | t="false"  { jjtThis.op = token.image; }\r
+  | t="true" { jjtThis.op = token.image; } \r
+  |   LOOKAHEAD( (name()|"der"|"initial") "(" ) der_initial()\r  | component_reference()\r
+  /* | "(" output_expression_list() ")" */ // Not needed, replaced with following:\r
+  | "(" expression() ")"\r
+  | "[" subscript_2() "]"\r
+  | array()\r
+  | "end"\r
+}\r
+\r
+String name() : {\r
+    String ret = new String("");\r
+} {\r
+//     [ "." ] IDENT { "." IDENT }\r
+       ( "." { ret += "."; } )?\r
+          <IDENT> { ret += token.image; jjtThis.op = token.image;}\r
+          ( "." { ret += "."; }\r
+          <IDENT> { ret += token.image; jjtThis.op = token.image;}\r
+       )*\r
+       {\r        return ret;\r
+    }\r
+}\r
+\r
+void component_reference() : {\r
+  Token t;\r
+} {\r
+//     [ "." ] IDENT [ array_subscripts ] { "." IDENT [ array_subscripts ] }\r
+       ( "." )? t=<IDENT> { jjtThis.op = t.image; } ( array_subscripts() )? ( "." <IDENT> ( array_subscripts() )? )*\r
+}\r
+\r
+void function_call_args() : {\r
+} {\r
+//     "(" [ function_arguments ] ")"\r
+       "(" ( function_arguments() )? ")"\r
+}\r
+\r
+void function_arguments() : {\r
+} {\r
+       //expression [ "," function_arguments | for for_indices ]\r
+       //| named_arguments\r
+        LOOKAHEAD(2) expression() ( "," function_arguments() | "for" for_indices() { jjtThis.op = "for"; } )?\r
+       | named_arguments()\r
+}\r
+\r
+void named_arguments() : {\r
+} {\r
+//     named_argument [ "," named_arguments ]  \r
+       named_argument() ( "," named_arguments() )?\r
+}\r
+\r
+void named_argument() : {\r
+} {    \r
+       <IDENT> "=" expression()\r
+}\r
+\r
+void output_expression_list() : {\r
+} {\r
+//     [ expression ] { "," [ expression ] }  \r
+       ( expression() )? ( "," ( expression() )? )*\r
+}\r
+\r
+void expression_list() : {\r
+} {\r
+//     expression { "," expression }\r
+    expression() ( "," expression() )*\r
+}\r
+\r
+void array_subscripts() : {\r
+} {\r
+//     "[" subscript { "," subscript } "]" \r
+       "["     subscript()     ( "," subscript() )* "]"\r
+}\r
+\r
+void subscript() : {\r
+} {\r
+//     ":" | expression  \r     ":" { jjtThis.op = "all"; } | expression() \r
+}\r
+\r
+String comment() #void : {\r
+    String ret;\r} {\r// string_comment [ annotation ]\r
+       ret = string_comment() ( annotation() )?\r
+       {\r          return ret;\r
+       }\r
+}\r
+\r
+String string_comment() #void : {\r
+    String ret = null;\r
+} {\r
+//     [ STRING { "+" STRING } ]  \r
+       ( <STRING> { ret = new String(token.image); }\r
+           ( "+" { ret += "+"; }\r
+               <STRING> { ret += token.image; }\r
+           )*\r
+       )?\r
+       {\r          return ret;\r
+       } \r}\r
+\r
+void annotation() : {\r
+} {\r
+//     annotation class_modification\r
+       "annotation" class_modification()  \r
+}\r  \r
+\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/Node.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/Node.java
new file mode 100644 (file)
index 0000000..862f65f
--- /dev/null
@@ -0,0 +1,36 @@
+/* Generated By:JJTree: Do not edit this line. Node.java Version 4.3 */\r
+/* JavaCCOptions:MULTI=false,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+/* All AST nodes must implement this interface.  It provides basic\r
+   machinery for constructing the parent and child relationships\r
+   between nodes. */\r
+\r
+public\r
+interface Node {\r
+\r
+  /** This method is called after the node has been made the current\r
+    node.  It indicates that child nodes can now be added to it. */\r
+  public void jjtOpen();\r
+\r
+  /** This method is called after all the child nodes have been\r
+    added. */\r
+  public void jjtClose();\r
+\r
+  /** This pair of methods are used to inform the node of its\r
+    parent. */\r
+  public void jjtSetParent(Node n);\r
+  public Node jjtGetParent();\r
+\r
+  /** This method tells the node to add its argument to the node's\r
+    list of children.  */\r
+  public void jjtAddChild(Node n, int i);\r
+\r
+  /** This method returns a child node.  The children are numbered\r
+     from zero, left to right. */\r
+  public Node jjtGetChild(int i);\r
+\r
+  /** Return the number of children the node has. */\r
+  public int jjtGetNumChildren();\r
+}\r
+/* JavaCC - OriginalChecksum=3ac4c20d0d1bb5d97b8317a16454eef1 (do not edit this line) */\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ParseException.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/ParseException.java
new file mode 100644 (file)
index 0000000..de4ad46
--- /dev/null
@@ -0,0 +1,187 @@
+/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */\r
+/* JavaCCOptions:KEEP_LINE_COL=null */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+/**\r
+ * This exception is thrown when parse errors are encountered.\r
+ * You can explicitly create objects of this exception type by\r
+ * calling the method generateParseException in the generated\r
+ * parser.\r
+ *\r
+ * You can modify this class to customize your error reporting\r
+ * mechanisms so long as you retain the public fields.\r
+ */\r
+public class ParseException extends Exception {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * This constructor is used by the method "generateParseException"\r
+   * in the generated parser.  Calling this constructor generates\r
+   * a new object of this type with the fields "currentToken",\r
+   * "expectedTokenSequences", and "tokenImage" set.\r
+   */\r
+  public ParseException(Token currentTokenVal,\r
+                        int[][] expectedTokenSequencesVal,\r
+                        String[] tokenImageVal\r
+                       )\r
+  {\r
+    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));\r
+    currentToken = currentTokenVal;\r
+    expectedTokenSequences = expectedTokenSequencesVal;\r
+    tokenImage = tokenImageVal;\r
+  }\r
+\r
+  /**\r
+   * The following constructors are for use by you for whatever\r
+   * purpose you can think of.  Constructing the exception in this\r
+   * manner makes the exception behave in the normal way - i.e., as\r
+   * documented in the class "Throwable".  The fields "errorToken",\r
+   * "expectedTokenSequences", and "tokenImage" do not contain\r
+   * relevant information.  The JavaCC generated code does not use\r
+   * these constructors.\r
+   */\r
+\r
+  public ParseException() {\r
+    super();\r
+  }\r
+\r
+  /** Constructor with message. */\r
+  public ParseException(String message) {\r
+    super(message);\r
+  }\r
+\r
+\r
+  /**\r
+   * This is the last token that has been consumed successfully.  If\r
+   * this object has been created due to a parse error, the token\r
+   * followng this token will (therefore) be the first error token.\r
+   */\r
+  public Token currentToken;\r
+\r
+  /**\r
+   * Each entry in this array is an array of integers.  Each array\r
+   * of integers represents a sequence of tokens (by their ordinal\r
+   * values) that is expected at this point of the parse.\r
+   */\r
+  public int[][] expectedTokenSequences;\r
+\r
+  /**\r
+   * This is a reference to the "tokenImage" array of the generated\r
+   * parser within which the parse error occurred.  This array is\r
+   * defined in the generated ...Constants interface.\r
+   */\r
+  public String[] tokenImage;\r
+\r
+  /**\r
+   * It uses "currentToken" and "expectedTokenSequences" to generate a parse\r
+   * error message and returns it.  If this object has been created\r
+   * due to a parse error, and you do not catch it (it gets thrown\r
+   * from the parser) the correct error message\r
+   * gets displayed.\r
+   */\r
+  private static String initialise(Token currentToken,\r
+                           int[][] expectedTokenSequences,\r
+                           String[] tokenImage) {\r
+    String eol = System.getProperty("line.separator", "\n");\r
+    StringBuffer expected = new StringBuffer();\r
+    int maxSize = 0;\r
+    for (int i = 0; i < expectedTokenSequences.length; i++) {\r
+      if (maxSize < expectedTokenSequences[i].length) {\r
+        maxSize = expectedTokenSequences[i].length;\r
+      }\r
+      for (int j = 0; j < expectedTokenSequences[i].length; j++) {\r
+        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');\r
+      }\r
+      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {\r
+        expected.append("...");\r
+      }\r
+      expected.append(eol).append("    ");\r
+    }\r
+    String retval = "Encountered \"";\r
+    Token tok = currentToken.next;\r
+    for (int i = 0; i < maxSize; i++) {\r
+      if (i != 0) retval += " ";\r
+      if (tok.kind == 0) {\r
+        retval += tokenImage[0];\r
+        break;\r
+      }\r
+      retval += " " + tokenImage[tok.kind];\r
+      retval += " \"";\r
+      retval += add_escapes(tok.image);\r
+      retval += " \"";\r
+      tok = tok.next;\r
+    }\r
+    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;\r
+    retval += "." + eol;\r
+    if (expectedTokenSequences.length == 1) {\r
+      retval += "Was expecting:" + eol + "    ";\r
+    } else {\r
+      retval += "Was expecting one of:" + eol + "    ";\r
+    }\r
+    retval += expected.toString();\r
+    return retval;\r
+  }\r
+\r
+  /**\r
+   * The end of line string for this machine.\r
+   */\r
+  protected String eol = System.getProperty("line.separator", "\n");\r
+\r
+  /**\r
+   * Used to convert raw characters to their escaped version\r
+   * when these raw version cannot be used as part of an ASCII\r
+   * string literal.\r
+   */\r
+  static String add_escapes(String str) {\r
+      StringBuffer retval = new StringBuffer();\r
+      char ch;\r
+      for (int i = 0; i < str.length(); i++) {\r
+        switch (str.charAt(i))\r
+        {\r
+           case 0 :\r
+              continue;\r
+           case '\b':\r
+              retval.append("\\b");\r
+              continue;\r
+           case '\t':\r
+              retval.append("\\t");\r
+              continue;\r
+           case '\n':\r
+              retval.append("\\n");\r
+              continue;\r
+           case '\f':\r
+              retval.append("\\f");\r
+              continue;\r
+           case '\r':\r
+              retval.append("\\r");\r
+              continue;\r
+           case '\"':\r
+              retval.append("\\\"");\r
+              continue;\r
+           case '\'':\r
+              retval.append("\\\'");\r
+              continue;\r
+           case '\\':\r
+              retval.append("\\\\");\r
+              continue;\r
+           default:\r
+              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+                 String s = "0000" + Integer.toString(ch, 16);\r
+                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+              } else {\r
+                 retval.append(ch);\r
+              }\r
+              continue;\r
+        }\r
+      }\r
+      return retval.toString();\r
+   }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=b5f58e7b423243b1bf84726ed111c7e8 (do not edit this line) */\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/SimpleCharStream.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/SimpleCharStream.java
new file mode 100644 (file)
index 0000000..14ba621
--- /dev/null
@@ -0,0 +1,471 @@
+/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */\r
+/* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+/**\r
+ * An implementation of interface CharStream, where the stream is assumed to\r
+ * contain only ASCII characters (without unicode processing).\r
+ */\r
+\r
+public class SimpleCharStream\r
+{\r
+/** Whether parser is static. */\r
+  public static final boolean staticFlag = false;\r
+  int bufsize;\r
+  int available;\r
+  int tokenBegin;\r
+/** Position in buffer. */\r
+  public int bufpos = -1;\r
+  protected int bufline[];\r
+  protected int bufcolumn[];\r
+\r
+  protected int column = 0;\r
+  protected int line = 1;\r
+\r
+  protected boolean prevCharIsCR = false;\r
+  protected boolean prevCharIsLF = false;\r
+\r
+  protected java.io.Reader inputStream;\r
+\r
+  protected char[] buffer;\r
+  protected int maxNextCharInd = 0;\r
+  protected int inBuf = 0;\r
+  protected int tabSize = 8;\r
+\r
+  protected void setTabSize(int i) { tabSize = i; }\r
+  protected int getTabSize(int i) { return tabSize; }\r
+\r
+\r
+  protected void ExpandBuff(boolean wrapAround)\r
+  {\r
+    char[] newbuffer = new char[bufsize + 2048];\r
+    int newbufline[] = new int[bufsize + 2048];\r
+    int newbufcolumn[] = new int[bufsize + 2048];\r
+\r
+    try\r
+    {\r
+      if (wrapAround)\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos += (bufsize - tokenBegin));\r
+      }\r
+      else\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos -= tokenBegin);\r
+      }\r
+    }\r
+    catch (Throwable t)\r
+    {\r
+      throw new Error(t.getMessage());\r
+    }\r
+\r
+\r
+    bufsize += 2048;\r
+    available = bufsize;\r
+    tokenBegin = 0;\r
+  }\r
+\r
+  protected void FillBuff() throws java.io.IOException\r
+  {\r
+    if (maxNextCharInd == available)\r
+    {\r
+      if (available == bufsize)\r
+      {\r
+        if (tokenBegin > 2048)\r
+        {\r
+          bufpos = maxNextCharInd = 0;\r
+          available = tokenBegin;\r
+        }\r
+        else if (tokenBegin < 0)\r
+          bufpos = maxNextCharInd = 0;\r
+        else\r
+          ExpandBuff(false);\r
+      }\r
+      else if (available > tokenBegin)\r
+        available = bufsize;\r
+      else if ((tokenBegin - available) < 2048)\r
+        ExpandBuff(true);\r
+      else\r
+        available = tokenBegin;\r
+    }\r
+\r
+    int i;\r
+    try {\r
+      if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)\r
+      {\r
+        inputStream.close();\r
+        throw new java.io.IOException();\r
+      }\r
+      else\r
+        maxNextCharInd += i;\r
+      return;\r
+    }\r
+    catch(java.io.IOException e) {\r
+      --bufpos;\r
+      backup(0);\r
+      if (tokenBegin == -1)\r
+        tokenBegin = bufpos;\r
+      throw e;\r
+    }\r
+  }\r
+\r
+/** Start. */\r
+  public char BeginToken() throws java.io.IOException\r
+  {\r
+    tokenBegin = -1;\r
+    char c = readChar();\r
+    tokenBegin = bufpos;\r
+\r
+    return c;\r
+  }\r
+\r
+  protected void UpdateLineColumn(char c)\r
+  {\r
+    column++;\r
+\r
+    if (prevCharIsLF)\r
+    {\r
+      prevCharIsLF = false;\r
+      line += (column = 1);\r
+    }\r
+    else if (prevCharIsCR)\r
+    {\r
+      prevCharIsCR = false;\r
+      if (c == '\n')\r
+      {\r
+        prevCharIsLF = true;\r
+      }\r
+      else\r
+        line += (column = 1);\r
+    }\r
+\r
+    switch (c)\r
+    {\r
+      case '\r' :\r
+        prevCharIsCR = true;\r
+        break;\r
+      case '\n' :\r
+        prevCharIsLF = true;\r
+        break;\r
+      case '\t' :\r
+        column--;\r
+        column += (tabSize - (column % tabSize));\r
+        break;\r
+      default :\r
+        break;\r
+    }\r
+\r
+    bufline[bufpos] = line;\r
+    bufcolumn[bufpos] = column;\r
+  }\r
+\r
+/** Read a character. */\r
+  public char readChar() throws java.io.IOException\r
+  {\r
+    if (inBuf > 0)\r
+    {\r
+      --inBuf;\r
+\r
+      if (++bufpos == bufsize)\r
+        bufpos = 0;\r
+\r
+      return buffer[bufpos];\r
+    }\r
+\r
+    if (++bufpos >= maxNextCharInd)\r
+      FillBuff();\r
+\r
+    char c = buffer[bufpos];\r
+\r
+    UpdateLineColumn(c);\r
+    return c;\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndColumn\r
+   */\r
+\r
+  public int getColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndLine\r
+   */\r
+\r
+  public int getLine() {\r
+    return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token end column number. */\r
+  public int getEndColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  /** Get token end line number. */\r
+  public int getEndLine() {\r
+     return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token beginning column number. */\r
+  public int getBeginColumn() {\r
+    return bufcolumn[tokenBegin];\r
+  }\r
+\r
+  /** Get token beginning line number. */\r
+  public int getBeginLine() {\r
+    return bufline[tokenBegin];\r
+  }\r
+\r
+/** Backup a number of characters. */\r
+  public void backup(int amount) {\r
+\r
+    inBuf += amount;\r
+    if ((bufpos -= amount) < 0)\r
+      bufpos += bufsize;\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    available = bufsize = buffersize;\r
+    buffer = new char[buffersize];\r
+    bufline = new int[buffersize];\r
+    bufcolumn = new int[buffersize];\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    if (buffer == null || buffersize != buffer.length)\r
+    {\r
+      available = bufsize = buffersize;\r
+      buffer = new char[buffersize];\r
+      bufline = new int[buffersize];\r
+      bufcolumn = new int[buffersize];\r
+    }\r
+    prevCharIsLF = prevCharIsCR = false;\r
+    tokenBegin = inBuf = maxNextCharInd = 0;\r
+    bufpos = -1;\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+  int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                          int startcolumn, int buffersize)\r
+  {\r
+    ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                     int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+  /** Get token literal value. */\r
+  public String GetImage()\r
+  {\r
+    if (bufpos >= tokenBegin)\r
+      return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);\r
+    else\r
+      return new String(buffer, tokenBegin, bufsize - tokenBegin) +\r
+                            new String(buffer, 0, bufpos + 1);\r
+  }\r
+\r
+  /** Get the suffix. */\r
+  public char[] GetSuffix(int len)\r
+  {\r
+    char[] ret = new char[len];\r
+\r
+    if ((bufpos + 1) >= len)\r
+      System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);\r
+    else\r
+    {\r
+      System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,\r
+                                                        len - bufpos - 1);\r
+      System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);\r
+    }\r
+\r
+    return ret;\r
+  }\r
+\r
+  /** Reset buffer when finished. */\r
+  public void Done()\r
+  {\r
+    buffer = null;\r
+    bufline = null;\r
+    bufcolumn = null;\r
+  }\r
+\r
+  /**\r
+   * Method to adjust line and column numbers for the start of a token.\r
+   */\r
+  public void adjustBeginLineColumn(int newLine, int newCol)\r
+  {\r
+    int start = tokenBegin;\r
+    int len;\r
+\r
+    if (bufpos >= tokenBegin)\r
+    {\r
+      len = bufpos - tokenBegin + inBuf + 1;\r
+    }\r
+    else\r
+    {\r
+      len = bufsize - tokenBegin + bufpos + 1 + inBuf;\r
+    }\r
+\r
+    int i = 0, j = 0, k = 0;\r
+    int nextColDiff = 0, columnDiff = 0;\r
+\r
+    while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])\r
+    {\r
+      bufline[j] = newLine;\r
+      nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];\r
+      bufcolumn[j] = newCol + columnDiff;\r
+      columnDiff = nextColDiff;\r
+      i++;\r
+    }\r
+\r
+    if (i < len)\r
+    {\r
+      bufline[j] = newLine++;\r
+      bufcolumn[j] = newCol + columnDiff;\r
+\r
+      while (i++ < len)\r
+      {\r
+        if (bufline[j = start % bufsize] != bufline[++start % bufsize])\r
+          bufline[j] = newLine++;\r
+        else\r
+          bufline[j] = newLine;\r
+      }\r
+    }\r
+\r
+    line = bufline[j];\r
+    column = bufcolumn[j];\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=ca8536fa0e367b808d68ae76a4e5e3a7 (do not edit this line) */\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/SimpleNode.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/SimpleNode.java
new file mode 100644 (file)
index 0000000..b399a88
--- /dev/null
@@ -0,0 +1,81 @@
+/* Generated By:JJTree: Do not edit this line. SimpleNode.java Version 4.3 */\r
+/* JavaCCOptions:MULTI=false,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+public\r
+class SimpleNode implements Node {\r
+\r
+  protected Node parent;\r
+  protected Node[] children;\r
+  protected int id;\r
+  protected Object value;\r
+  protected ModelParser parser;\r
+  \r
+  public String op;\r
+\r
+  public SimpleNode(int i) {\r
+    id = i;\r
+  }\r
+\r
+  public SimpleNode(ModelParser p, int i) {\r
+    this(i);\r
+    parser = p;\r
+  }\r
+\r
+  public void jjtOpen() {\r
+  }\r
+\r
+  public void jjtClose() {\r
+  }\r
+\r
+  public void jjtSetParent(Node n) { parent = n; }\r
+  public Node jjtGetParent() { return parent; }\r
+\r
+  public void jjtAddChild(Node n, int i) {\r
+    if (children == null) {\r
+      children = new Node[i + 1];\r
+    } else if (i >= children.length) {\r
+      Node c[] = new Node[i + 1];\r
+      System.arraycopy(children, 0, c, 0, children.length);\r
+      children = c;\r
+    }\r
+    children[i] = n;\r
+  }\r
+\r
+  public Node jjtGetChild(int i) {\r
+    return children[i];\r
+  }\r
+\r
+  public int jjtGetNumChildren() {\r
+    return (children == null) ? 0 : children.length;\r
+  }\r
+\r
+  public void jjtSetValue(Object value) { this.value = value; }\r
+  public Object jjtGetValue() { return value; }\r
+\r
+  /* You can override these two methods in subclasses of SimpleNode to\r
+     customize the way the node appears when the tree is dumped.  If\r
+     your output uses more than one line you should override\r
+     toString(String), otherwise overriding toString() is probably all\r
+     you need to do. */\r
+\r
+  public String toString() { return ModelParserTreeConstants.jjtNodeName[id]; }\r
+  public String toString(String prefix) { return prefix + toString(); }\r
+\r
+  /* Override this method if you want to customize how the node dumps\r
+     out its children. */\r
+\r
+  public void dump(String prefix) {\r
+    System.out.println(toString(prefix));\r
+    if (children != null) {\r
+      for (int i = 0; i < children.length; ++i) {\r
+        SimpleNode n = (SimpleNode)children[i];\r
+        if (n != null) {\r
+          n.dump(prefix + " ");\r
+        }\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+/* JavaCC - OriginalChecksum=77b52cae8f60a97f6e484f498134f167 (do not edit this line) */\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/Token.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/Token.java
new file mode 100644 (file)
index 0000000..0cfda20
--- /dev/null
@@ -0,0 +1,131 @@
+/* Generated By:JavaCC: Do not edit this line. Token.java Version 5.0 */\r
+/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+/**\r
+ * Describes the input token stream.\r
+ */\r
+\r
+public class Token implements java.io.Serializable {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * An integer that describes the kind of this token.  This numbering\r
+   * system is determined by JavaCCParser, and a table of these numbers is\r
+   * stored in the file ...Constants.java.\r
+   */\r
+  public int kind;\r
+\r
+  /** The line number of the first character of this Token. */\r
+  public int beginLine;\r
+  /** The column number of the first character of this Token. */\r
+  public int beginColumn;\r
+  /** The line number of the last character of this Token. */\r
+  public int endLine;\r
+  /** The column number of the last character of this Token. */\r
+  public int endColumn;\r
+\r
+  /**\r
+   * The string image of the token.\r
+   */\r
+  public String image;\r
+\r
+  /**\r
+   * A reference to the next regular (non-special) token from the input\r
+   * stream.  If this is the last token from the input stream, or if the\r
+   * token manager has not read tokens beyond this one, this field is\r
+   * set to null.  This is true only if this token is also a regular\r
+   * token.  Otherwise, see below for a description of the contents of\r
+   * this field.\r
+   */\r
+  public Token next;\r
+\r
+  /**\r
+   * This field is used to access special tokens that occur prior to this\r
+   * token, but after the immediately preceding regular (non-special) token.\r
+   * If there are no such special tokens, this field is set to null.\r
+   * When there are more than one such special token, this field refers\r
+   * to the last of these special tokens, which in turn refers to the next\r
+   * previous special token through its specialToken field, and so on\r
+   * until the first special token (whose specialToken field is null).\r
+   * The next fields of special tokens refer to other special tokens that\r
+   * immediately follow it (without an intervening regular token).  If there\r
+   * is no such token, this field is null.\r
+   */\r
+  public Token specialToken;\r
+\r
+  /**\r
+   * An optional attribute value of the Token.\r
+   * Tokens which are not used as syntactic sugar will often contain\r
+   * meaningful values that will be used later on by the compiler or\r
+   * interpreter. This attribute value is often different from the image.\r
+   * Any subclass of Token that actually wants to return a non-null value can\r
+   * override this method as appropriate.\r
+   */\r
+  public Object getValue() {\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * No-argument constructor\r
+   */\r
+  public Token() {}\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image.\r
+   */\r
+  public Token(int kind)\r
+  {\r
+    this(kind, null);\r
+  }\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image and Kind.\r
+   */\r
+  public Token(int kind, String image)\r
+  {\r
+    this.kind = kind;\r
+    this.image = image;\r
+  }\r
+\r
+  /**\r
+   * Returns the image.\r
+   */\r
+  public String toString()\r
+  {\r
+    return image;\r
+  }\r
+\r
+  /**\r
+   * Returns a new Token object, by default. However, if you want, you\r
+   * can create and return subclass objects based on the value of ofKind.\r
+   * Simply add the cases to the switch for all those special cases.\r
+   * For example, if you have a subclass of Token called IDToken that\r
+   * you want to create if ofKind is ID, simply add something like :\r
+   *\r
+   *    case MyParserConstants.ID : return new IDToken(ofKind, image);\r
+   *\r
+   * to the following switch statement. Then you can cast matchedToken\r
+   * variable to the appropriate type and use sit in your lexical actions.\r
+   */\r
+  public static Token newToken(int ofKind, String image)\r
+  {\r
+    switch(ofKind)\r
+    {\r
+      default : return new Token(ofKind, image);\r
+    }\r
+  }\r
+\r
+  public static Token newToken(int ofKind)\r
+  {\r
+    return newToken(ofKind, null);\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=849435840a0a4c85d87a2152b704b03b (do not edit this line) */\r
diff --git a/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/TokenMgrError.java b/1.8/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/parser/TokenMgrError.java
new file mode 100644 (file)
index 0000000..f33980d
--- /dev/null
@@ -0,0 +1,147 @@
+/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 5.0 */\r
+/* JavaCCOptions: */\r
+package fi.semantum.sysdyn.solver.parser;\r
+\r
+/** Token Manager Error. */\r
+public class TokenMgrError extends Error\r
+{\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /*\r
+   * Ordinals for various reasons why an Error of this type can be thrown.\r
+   */\r
+\r
+  /**\r
+   * Lexical error occurred.\r
+   */\r
+  static final int LEXICAL_ERROR = 0;\r
+\r
+  /**\r
+   * An attempt was made to create a second instance of a static token manager.\r
+   */\r
+  static final int STATIC_LEXER_ERROR = 1;\r
+\r
+  /**\r
+   * Tried to change to an invalid lexical state.\r
+   */\r
+  static final int INVALID_LEXICAL_STATE = 2;\r
+\r
+  /**\r
+   * Detected (and bailed out of) an infinite loop in the token manager.\r
+   */\r
+  static final int LOOP_DETECTED = 3;\r
+\r
+  /**\r
+   * Indicates the reason why the exception is thrown. It will have\r
+   * one of the above 4 values.\r
+   */\r
+  int errorCode;\r
+\r
+  /**\r
+   * Replaces unprintable characters by their escaped (or unicode escaped)\r
+   * equivalents in the given string\r
+   */\r
+  protected static final String addEscapes(String str) {\r
+    StringBuffer retval = new StringBuffer();\r
+    char ch;\r
+    for (int i = 0; i < str.length(); i++) {\r
+      switch (str.charAt(i))\r
+      {\r
+        case 0 :\r
+          continue;\r
+        case '\b':\r
+          retval.append("\\b");\r
+          continue;\r
+        case '\t':\r
+          retval.append("\\t");\r
+          continue;\r
+        case '\n':\r
+          retval.append("\\n");\r
+          continue;\r
+        case '\f':\r
+          retval.append("\\f");\r
+          continue;\r
+        case '\r':\r
+          retval.append("\\r");\r
+          continue;\r
+        case '\"':\r
+          retval.append("\\\"");\r
+          continue;\r
+        case '\'':\r
+          retval.append("\\\'");\r
+          continue;\r
+        case '\\':\r
+          retval.append("\\\\");\r
+          continue;\r
+        default:\r
+          if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+            String s = "0000" + Integer.toString(ch, 16);\r
+            retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+          } else {\r
+            retval.append(ch);\r
+          }\r
+          continue;\r
+      }\r
+    }\r
+    return retval.toString();\r
+  }\r
+\r
+  /**\r
+   * Returns a detailed message for the Error when it is thrown by the\r
+   * token manager to indicate a lexical error.\r
+   * Parameters :\r
+   *    EOFSeen     : indicates if EOF caused the lexical error\r
+   *    curLexState : lexical state in which this error occurred\r
+   *    errorLine   : line number when the error occurred\r
+   *    errorColumn : column number when the error occurred\r
+   *    errorAfter  : prefix that was seen before this error occurred\r
+   *    curchar     : the offending character\r
+   * Note: You can customize the lexical error message by modifying this method.\r
+   */\r
+  protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {\r
+    return("Lexical error at line " +\r
+          errorLine + ", column " +\r
+          errorColumn + ".  Encountered: " +\r
+          (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +\r
+          "after : \"" + addEscapes(errorAfter) + "\"");\r
+  }\r
+\r
+  /**\r
+   * You can also modify the body of this method to customize your error messages.\r
+   * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not\r
+   * of end-users concern, so you can return something like :\r
+   *\r
+   *     "Internal Error : Please file a bug report .... "\r
+   *\r
+   * from this method for such cases in the release version of your parser.\r
+   */\r
+  public String getMessage() {\r
+    return super.getMessage();\r
+  }\r
+\r
+  /*\r
+   * Constructors of various flavors follow.\r
+   */\r
+\r
+  /** No arg constructor. */\r
+  public TokenMgrError() {\r
+  }\r
+\r
+  /** Constructor with message and reason. */\r
+  public TokenMgrError(String message, int reason) {\r
+    super(message);\r
+    errorCode = reason;\r
+  }\r
+\r
+  /** Full Constructor. */\r
+  public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {\r
+    this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);\r
+  }\r
+}\r
+/* JavaCC - OriginalChecksum=e56f34a3810aefee801894d03cfcfd89 (do not edit this line) */\r
diff --git a/1.8/installer/.project b/1.8/installer/.project
new file mode 100644 (file)
index 0000000..dd9ed4e
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>sysdyn-installer</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+       </buildSpec>\r
+       <natures>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/installer/7za/7-zip.chm b/1.8/installer/7za/7-zip.chm
new file mode 100644 (file)
index 0000000..eee875e
Binary files /dev/null and b/1.8/installer/7za/7-zip.chm differ
diff --git a/1.8/installer/7za/7z.sfx b/1.8/installer/7za/7z.sfx
new file mode 100644 (file)
index 0000000..97ff605
Binary files /dev/null and b/1.8/installer/7za/7z.sfx differ
diff --git a/1.8/installer/7za/7zS.sfx b/1.8/installer/7za/7zS.sfx
new file mode 100644 (file)
index 0000000..f37714d
Binary files /dev/null and b/1.8/installer/7za/7zS.sfx differ
diff --git a/1.8/installer/7za/7zSD.sfx b/1.8/installer/7za/7zSD.sfx
new file mode 100644 (file)
index 0000000..ad3915d
Binary files /dev/null and b/1.8/installer/7za/7zSD.sfx differ
diff --git a/1.8/installer/7za/7za.dll b/1.8/installer/7za/7za.dll
new file mode 100644 (file)
index 0000000..dcd0d3d
Binary files /dev/null and b/1.8/installer/7za/7za.dll differ
diff --git a/1.8/installer/7za/7za.exe b/1.8/installer/7za/7za.exe
new file mode 100644 (file)
index 0000000..12b9499
Binary files /dev/null and b/1.8/installer/7za/7za.exe differ
diff --git a/1.8/installer/7za/7zr.exe b/1.8/installer/7za/7zr.exe
new file mode 100644 (file)
index 0000000..08acdc0
Binary files /dev/null and b/1.8/installer/7za/7zr.exe differ
diff --git a/1.8/installer/7za/7zxa.dll b/1.8/installer/7za/7zxa.dll
new file mode 100644 (file)
index 0000000..fa5aa01
Binary files /dev/null and b/1.8/installer/7za/7zxa.dll differ
diff --git a/1.8/installer/7za/Installer/config.txt b/1.8/installer/7za/Installer/config.txt
new file mode 100644 (file)
index 0000000..4200104
--- /dev/null
@@ -0,0 +1,5 @@
+;!@Install@!UTF-8!\r
+Title="Software 5.00"\r
+BeginPrompt="Do you want to install the Software 5.00?"\r
+RunProgram="7zr.exe"\r
+;!@InstallEnd@!\r
diff --git a/1.8/installer/7za/Installer/cr.bat b/1.8/installer/7za/Installer/cr.bat
new file mode 100644 (file)
index 0000000..aa34797
--- /dev/null
@@ -0,0 +1,4 @@
+del archive.7z\r
+del archive.exe\r
+..\7zr a archive.7z ..\7zr.exe -m0=BCJ2 -m1=LZMA:d25:fb255 -m2=LZMA:d19 -m3=LZMA:d19 -mb0:1 -mb0s1:2 -mb0s2:3 -mx\r
+copy /b ..\7zSD.sfx + config.txt + archive.7z archive.exe\r
diff --git a/1.8/installer/7za/Installer/readme.txt b/1.8/installer/7za/Installer/readme.txt
new file mode 100644 (file)
index 0000000..0da060d
--- /dev/null
@@ -0,0 +1,98 @@
+7-Zip for installers 4.65\r
+-------------------------\r
+\r
+7-Zip is a file archiver for Windows 98/ME/NT/2000/2003/XP. \r
+\r
+7-Zip Copyright (C) 1999-2009 Igor Pavlov.\r
+\r
+This library is free software; you can redistribute it and/or\r
+modify it under the terms of the GNU Lesser General Public\r
+License as published by the Free Software Foundation; either\r
+version 2.1 of the License, or (at your option) any later version.\r
+\r
+7zr.exe is reduced version of 7za.exe of 7-Zip.\r
+7zr.exe supports only 7z format with this codecs: LZMA, BCJ, BCJ2, Copy.\r
+\r
+Example of compressing command for installation packages:\r
+\r
+7zr a -t7z archive.7z * -m0=BCJ2 -m1=LZMA:d25:fb255 -m2=LZMA:d19 -m3=LZMA:d19 -mb0:1 -mb0s1:2 -mb0s2:3 -mx\r
+\r
+\r
+7zSD.sfx is SFX module for installers (it uses msvcrt.dll)\r
+\r
+SFX modules for installers (7zS.sfx and 7zSD.sfx) allow to create installation program. \r
+Such module extracts archive to temp folder and then runs specified program and removes \r
+temp files after program finishing. Self-extract archive for installers must be created \r
+as joining 3 files: SFX_Module, Installer_Config, 7z_Archive. \r
+Installer_Config is optional file. You can use the following command to create installer \r
+self-extract archive:\r
+\r
+copy /b 7zSD.sfx + config.txt + archive.7z archive.exe\r
+\r
+The smallest installation package size can be achivied, if installation files was \r
+uncompressed before including to 7z archive.\r
+\r
+-y switch for installer module (at runtime) specifies quiet mode for extracting.\r
+\r
+Installer Config file format\r
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r
+Config file contains commands for Installer. File begins from string \r
+;!@Install@!UTF-8! and ends with ;!@InstallEnd@!. File must be written \r
+in UTF-8 encoding. File contains string pairs: \r
+\r
+ID_String="Value"\r
+\r
+ID_String          Description \r
+\r
+Title              Title for messages \r
+BeginPrompt        Begin Prompt message \r
+Progress           Value can be "yes" or "no". Default value is "yes". \r
+RunProgram         Command for executing. Default value is "setup.exe". \r
+                   Substring %%T will be replaced with path to temporary \r
+                   folder, where files were extracted \r
+Directory          Directory prefix for "RunProgram". Default value is ".\\" \r
+ExecuteFile        Name of file for executing \r
+ExecuteParameters  Parameters for "ExecuteFile" \r
+\r
+\r
+You can omit any values.\r
+\r
+There are two ways to run program: RunProgram and ExecuteFile. \r
+Use RunProgram, if you want to run some program from .7z archive. \r
+Use ExecuteFile, if you want to open some document from .7z archive or \r
+if you want to execute some command from Windows.\r
+\r
+If you use RunProgram and if you specify empty directory prefix: Directory="", \r
+the system searches for the executable file in the following sequence:\r
+\r
+1. The directory from which the application (installer) loaded. \r
+2. The temporary folder, where files were extracted. \r
+3. The Windows system directory. \r
+\r
+\r
+Config file Examples\r
+~~~~~~~~~~~~~~~~~~~~\r
+\r
+;!@Install@!UTF-8!\r
+Title="7-Zip 4.00"\r
+BeginPrompt="Do you want to install the 7-Zip 4.00?"\r
+RunProgram="setup.exe"\r
+;!@InstallEnd@!\r
+\r
+\r
+\r
+;!@Install@!UTF-8!\r
+Title="7-Zip 4.00"\r
+BeginPrompt="Do you want to install the 7-Zip 4.00?"\r
+ExecuteFile="7zip.msi"\r
+;!@InstallEnd@!\r
+\r
+\r
+\r
+;!@Install@!UTF-8!\r
+Title="7-Zip 4.01 Update"\r
+BeginPrompt="Do you want to install the 7-Zip 4.01 Update?"\r
+ExecuteFile="msiexec.exe"\r
+ExecuteParameters="/i 7zip.msi REINSTALL=ALL REINSTALLMODE=vomus"\r
+;!@InstallEnd@!\r
+\r
diff --git a/1.8/installer/7za/copying.txt b/1.8/installer/7za/copying.txt
new file mode 100644 (file)
index 0000000..f3926a6
--- /dev/null
@@ -0,0 +1,504 @@
+      GNU LESSER GENERAL PUBLIC LICENSE\r
+           Version 2.1, February 1999\r
+\r
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.\r
+     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ Everyone is permitted to copy and distribute verbatim copies\r
+ of this license document, but changing it is not allowed.\r
+\r
+[This is the first released version of the Lesser GPL.  It also counts\r
+ as the successor of the GNU Library Public License, version 2, hence\r
+ the version number 2.1.]\r
+\r
+          Preamble\r
+\r
+  The licenses for most software are designed to take away your\r
+freedom to share and change it.  By contrast, the GNU General Public\r
+Licenses are intended to guarantee your freedom to share and change\r
+free software--to make sure the software is free for all its users.\r
+\r
+  This license, the Lesser General Public License, applies to some\r
+specially designated software packages--typically libraries--of the\r
+Free Software Foundation and other authors who decide to use it.  You\r
+can use it too, but we suggest you first think carefully about whether\r
+this license or the ordinary General Public License is the better\r
+strategy to use in any particular case, based on the explanations below.\r
+\r
+  When we speak of free software, we are referring to freedom of use,\r
+not price.  Our General Public Licenses are designed to make sure that\r
+you have the freedom to distribute copies of free software (and charge\r
+for this service if you wish); that you receive source code or can get\r
+it if you want it; that you can change the software and use pieces of\r
+it in new free programs; and that you are informed that you can do\r
+these things.\r
+\r
+  To protect your rights, we need to make restrictions that forbid\r
+distributors to deny you these rights or to ask you to surrender these\r
+rights.  These restrictions translate to certain responsibilities for\r
+you if you distribute copies of the library or if you modify it.\r
+\r
+  For example, if you distribute copies of the library, whether gratis\r
+or for a fee, you must give the recipients all the rights that we gave\r
+you.  You must make sure that they, too, receive or can get the source\r
+code.  If you link other code with the library, you must provide\r
+complete object files to the recipients, so that they can relink them\r
+with the library after making changes to the library and recompiling\r
+it.  And you must show them these terms so they know their rights.\r
+\r
+  We protect your rights with a two-step method: (1) we copyright the\r
+library, and (2) we offer you this license, which gives you legal\r
+permission to copy, distribute and/or modify the library.\r
+\r
+  To protect each distributor, we want to make it very clear that\r
+there is no warranty for the free library.  Also, if the library is\r
+modified by someone else and passed on, the recipients should know\r
+that what they have is not the original version, so that the original\r
+author's reputation will not be affected by problems that might be\r
+introduced by others.\r
+\f\r
+  Finally, software patents pose a constant threat to the existence of\r
+any free program.  We wish to make sure that a company cannot\r
+effectively restrict the users of a free program by obtaining a\r
+restrictive license from a patent holder.  Therefore, we insist that\r
+any patent license obtained for a version of the library must be\r
+consistent with the full freedom of use specified in this license.\r
+\r
+  Most GNU software, including some libraries, is covered by the\r
+ordinary GNU General Public License.  This license, the GNU Lesser\r
+General Public License, applies to certain designated libraries, and\r
+is quite different from the ordinary General Public License.  We use\r
+this license for certain libraries in order to permit linking those\r
+libraries into non-free programs.\r
+\r
+  When a program is linked with a library, whether statically or using\r
+a shared library, the combination of the two is legally speaking a\r
+combined work, a derivative of the original library.  The ordinary\r
+General Public License therefore permits such linking only if the\r
+entire combination fits its criteria of freedom.  The Lesser General\r
+Public License permits more lax criteria for linking other code with\r
+the library.\r
+\r
+  We call this license the "Lesser" General Public License because it\r
+does Less to protect the user's freedom than the ordinary General\r
+Public License.  It also provides other free software developers Less\r
+of an advantage over competing non-free programs.  These disadvantages\r
+are the reason we use the ordinary General Public License for many\r
+libraries.  However, the Lesser license provides advantages in certain\r
+special circumstances.\r
+\r
+  For example, on rare occasions, there may be a special need to\r
+encourage the widest possible use of a certain library, so that it becomes\r
+a de-facto standard.  To achieve this, non-free programs must be\r
+allowed to use the library.  A more frequent case is that a free\r
+library does the same job as widely used non-free libraries.  In this\r
+case, there is little to gain by limiting the free library to free\r
+software only, so we use the Lesser General Public License.\r
+\r
+  In other cases, permission to use a particular library in non-free\r
+programs enables a greater number of people to use a large body of\r
+free software.  For example, permission to use the GNU C Library in\r
+non-free programs enables many more people to use the whole GNU\r
+operating system, as well as its variant, the GNU/Linux operating\r
+system.\r
+\r
+  Although the Lesser General Public License is Less protective of the\r
+users' freedom, it does ensure that the user of a program that is\r
+linked with the Library has the freedom and the wherewithal to run\r
+that program using a modified version of the Library.\r
+\r
+  The precise terms and conditions for copying, distribution and\r
+modification follow.  Pay close attention to the difference between a\r
+"work based on the library" and a "work that uses the library".  The\r
+former contains code derived from the library, whereas the latter must\r
+be combined with the library in order to run.\r
+\f\r
+      GNU LESSER GENERAL PUBLIC LICENSE\r
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\r
+\r
+  0. This License Agreement applies to any software library or other\r
+program which contains a notice placed by the copyright holder or\r
+other authorized party saying it may be distributed under the terms of\r
+this Lesser General Public License (also called "this License").\r
+Each licensee is addressed as "you".\r
+\r
+  A "library" means a collection of software functions and/or data\r
+prepared so as to be conveniently linked with application programs\r
+(which use some of those functions and data) to form executables.\r
+\r
+  The "Library", below, refers to any such software library or work\r
+which has been distributed under these terms.  A "work based on the\r
+Library" means either the Library or any derivative work under\r
+copyright law: that is to say, a work containing the Library or a\r
+portion of it, either verbatim or with modifications and/or translated\r
+straightforwardly into another language.  (Hereinafter, translation is\r
+included without limitation in the term "modification".)\r
+\r
+  "Source code" for a work means the preferred form of the work for\r
+making modifications to it.  For a library, complete source code means\r
+all the source code for all modules it contains, plus any associated\r
+interface definition files, plus the scripts used to control compilation\r
+and installation of the library.\r
+\r
+  Activities other than copying, distribution and modification are not\r
+covered by this License; they are outside its scope.  The act of\r
+running a program using the Library is not restricted, and output from\r
+such a program is covered only if its contents constitute a work based\r
+on the Library (independent of the use of the Library in a tool for\r
+writing it).  Whether that is true depends on what the Library does\r
+and what the program that uses the Library does.\r
+  \r
+  1. You may copy and distribute verbatim copies of the Library's\r
+complete source code as you receive it, in any medium, provided that\r
+you conspicuously and appropriately publish on each copy an\r
+appropriate copyright notice and disclaimer of warranty; keep intact\r
+all the notices that refer to this License and to the absence of any\r
+warranty; and distribute a copy of this License along with the\r
+Library.\r
+\r
+  You may charge a fee for the physical act of transferring a copy,\r
+and you may at your option offer warranty protection in exchange for a\r
+fee.\r
+\f\r
+  2. You may modify your copy or copies of the Library or any portion\r
+of it, thus forming a work based on the Library, and copy and\r
+distribute such modifications or work under the terms of Section 1\r
+above, provided that you also meet all of these conditions:\r
+\r
+    a) The modified work must itself be a software library.\r
+\r
+    b) You must cause the files modified to carry prominent notices\r
+    stating that you changed the files and the date of any change.\r
+\r
+    c) You must cause the whole of the work to be licensed at no\r
+    charge to all third parties under the terms of this License.\r
+\r
+    d) If a facility in the modified Library refers to a function or a\r
+    table of data to be supplied by an application program that uses\r
+    the facility, other than as an argument passed when the facility\r
+    is invoked, then you must make a good faith effort to ensure that,\r
+    in the event an application does not supply such function or\r
+    table, the facility still operates, and performs whatever part of\r
+    its purpose remains meaningful.\r
+\r
+    (For example, a function in a library to compute square roots has\r
+    a purpose that is entirely well-defined independent of the\r
+    application.  Therefore, Subsection 2d requires that any\r
+    application-supplied function or table used by this function must\r
+    be optional: if the application does not supply it, the square\r
+    root function must still compute square roots.)\r
+\r
+These requirements apply to the modified work as a whole.  If\r
+identifiable sections of that work are not derived from the Library,\r
+and can be reasonably considered independent and separate works in\r
+themselves, then this License, and its terms, do not apply to those\r
+sections when you distribute them as separate works.  But when you\r
+distribute the same sections as part of a whole which is a work based\r
+on the Library, the distribution of the whole must be on the terms of\r
+this License, whose permissions for other licensees extend to the\r
+entire whole, and thus to each and every part regardless of who wrote\r
+it.\r
+\r
+Thus, it is not the intent of this section to claim rights or contest\r
+your rights to work written entirely by you; rather, the intent is to\r
+exercise the right to control the distribution of derivative or\r
+collective works based on the Library.\r
+\r
+In addition, mere aggregation of another work not based on the Library\r
+with the Library (or with a work based on the Library) on a volume of\r
+a storage or distribution medium does not bring the other work under\r
+the scope of this License.\r
+\r
+  3. You may opt to apply the terms of the ordinary GNU General Public\r
+License instead of this License to a given copy of the Library.  To do\r
+this, you must alter all the notices that refer to this License, so\r
+that they refer to the ordinary GNU General Public License, version 2,\r
+instead of to this License.  (If a newer version than version 2 of the\r
+ordinary GNU General Public License has appeared, then you can specify\r
+that version instead if you wish.)  Do not make any other change in\r
+these notices.\r
+\f\r
+  Once this change is made in a given copy, it is irreversible for\r
+that copy, so the ordinary GNU General Public License applies to all\r
+subsequent copies and derivative works made from that copy.\r
+\r
+  This option is useful when you wish to copy part of the code of\r
+the Library into a program that is not a library.\r
+\r
+  4. You may copy and distribute the Library (or a portion or\r
+derivative of it, under Section 2) in object code or executable form\r
+under the terms of Sections 1 and 2 above provided that you accompany\r
+it with the complete corresponding machine-readable source code, which\r
+must be distributed under the terms of Sections 1 and 2 above on a\r
+medium customarily used for software interchange.\r
+\r
+  If distribution of object code is made by offering access to copy\r
+from a designated place, then offering equivalent access to copy the\r
+source code from the same place satisfies the requirement to\r
+distribute the source code, even though third parties are not\r
+compelled to copy the source along with the object code.\r
+\r
+  5. A program that contains no derivative of any portion of the\r
+Library, but is designed to work with the Library by being compiled or\r
+linked with it, is called a "work that uses the Library".  Such a\r
+work, in isolation, is not a derivative work of the Library, and\r
+therefore falls outside the scope of this License.\r
+\r
+  However, linking a "work that uses the Library" with the Library\r
+creates an executable that is a derivative of the Library (because it\r
+contains portions of the Library), rather than a "work that uses the\r
+library".  The executable is therefore covered by this License.\r
+Section 6 states terms for distribution of such executables.\r
+\r
+  When a "work that uses the Library" uses material from a header file\r
+that is part of the Library, the object code for the work may be a\r
+derivative work of the Library even though the source code is not.\r
+Whether this is true is especially significant if the work can be\r
+linked without the Library, or if the work is itself a library.  The\r
+threshold for this to be true is not precisely defined by law.\r
+\r
+  If such an object file uses only numerical parameters, data\r
+structure layouts and accessors, and small macros and small inline\r
+functions (ten lines or less in length), then the use of the object\r
+file is unrestricted, regardless of whether it is legally a derivative\r
+work.  (Executables containing this object code plus portions of the\r
+Library will still fall under Section 6.)\r
+\r
+  Otherwise, if the work is a derivative of the Library, you may\r
+distribute the object code for the work under the terms of Section 6.\r
+Any executables containing that work also fall under Section 6,\r
+whether or not they are linked directly with the Library itself.\r
+\f\r
+  6. As an exception to the Sections above, you may also combine or\r
+link a "work that uses the Library" with the Library to produce a\r
+work containing portions of the Library, and distribute that work\r
+under terms of your choice, provided that the terms permit\r
+modification of the work for the customer's own use and reverse\r
+engineering for debugging such modifications.\r
+\r
+  You must give prominent notice with each copy of the work that the\r
+Library is used in it and that the Library and its use are covered by\r
+this License.  You must supply a copy of this License.  If the work\r
+during execution displays copyright notices, you must include the\r
+copyright notice for the Library among them, as well as a reference\r
+directing the user to the copy of this License.  Also, you must do one\r
+of these things:\r
+\r
+    a) Accompany the work with the complete corresponding\r
+    machine-readable source code for the Library including whatever\r
+    changes were used in the work (which must be distributed under\r
+    Sections 1 and 2 above); and, if the work is an executable linked\r
+    with the Library, with the complete machine-readable "work that\r
+    uses the Library", as object code and/or source code, so that the\r
+    user can modify the Library and then relink to produce a modified\r
+    executable containing the modified Library.  (It is understood\r
+    that the user who changes the contents of definitions files in the\r
+    Library will not necessarily be able to recompile the application\r
+    to use the modified definitions.)\r
+\r
+    b) Use a suitable shared library mechanism for linking with the\r
+    Library.  A suitable mechanism is one that (1) uses at run time a\r
+    copy of the library already present on the user's computer system,\r
+    rather than copying library functions into the executable, and (2)\r
+    will operate properly with a modified version of the library, if\r
+    the user installs one, as long as the modified version is\r
+    interface-compatible with the version that the work was made with.\r
+\r
+    c) Accompany the work with a written offer, valid for at\r
+    least three years, to give the same user the materials\r
+    specified in Subsection 6a, above, for a charge no more\r
+    than the cost of performing this distribution.\r
+\r
+    d) If distribution of the work is made by offering access to copy\r
+    from a designated place, offer equivalent access to copy the above\r
+    specified materials from the same place.\r
+\r
+    e) Verify that the user has already received a copy of these\r
+    materials or that you have already sent this user a copy.\r
+\r
+  For an executable, the required form of the "work that uses the\r
+Library" must include any data and utility programs needed for\r
+reproducing the executable from it.  However, as a special exception,\r
+the materials to be distributed need not include anything that is\r
+normally distributed (in either source or binary form) with the major\r
+components (compiler, kernel, and so on) of the operating system on\r
+which the executable runs, unless that component itself accompanies\r
+the executable.\r
+\r
+  It may happen that this requirement contradicts the license\r
+restrictions of other proprietary libraries that do not normally\r
+accompany the operating system.  Such a contradiction means you cannot\r
+use both them and the Library together in an executable that you\r
+distribute.\r
+\f\r
+  7. You may place library facilities that are a work based on the\r
+Library side-by-side in a single library together with other library\r
+facilities not covered by this License, and distribute such a combined\r
+library, provided that the separate distribution of the work based on\r
+the Library and of the other library facilities is otherwise\r
+permitted, and provided that you do these two things:\r
+\r
+    a) Accompany the combined library with a copy of the same work\r
+    based on the Library, uncombined with any other library\r
+    facilities.  This must be distributed under the terms of the\r
+    Sections above.\r
+\r
+    b) Give prominent notice with the combined library of the fact\r
+    that part of it is a work based on the Library, and explaining\r
+    where to find the accompanying uncombined form of the same work.\r
+\r
+  8. You may not copy, modify, sublicense, link with, or distribute\r
+the Library except as expressly provided under this License.  Any\r
+attempt otherwise to copy, modify, sublicense, link with, or\r
+distribute the Library is void, and will automatically terminate your\r
+rights under this License.  However, parties who have received copies,\r
+or rights, from you under this License will not have their licenses\r
+terminated so long as such parties remain in full compliance.\r
+\r
+  9. You are not required to accept this License, since you have not\r
+signed it.  However, nothing else grants you permission to modify or\r
+distribute the Library or its derivative works.  These actions are\r
+prohibited by law if you do not accept this License.  Therefore, by\r
+modifying or distributing the Library (or any work based on the\r
+Library), you indicate your acceptance of this License to do so, and\r
+all its terms and conditions for copying, distributing or modifying\r
+the Library or works based on it.\r
+\r
+  10. Each time you redistribute the Library (or any work based on the\r
+Library), the recipient automatically receives a license from the\r
+original licensor to copy, distribute, link with or modify the Library\r
+subject to these terms and conditions.  You may not impose any further\r
+restrictions on the recipients' exercise of the rights granted herein.\r
+You are not responsible for enforcing compliance by third parties with\r
+this License.\r
+\f\r
+  11. If, as a consequence of a court judgment or allegation of patent\r
+infringement or for any other reason (not limited to patent issues),\r
+conditions are imposed on you (whether by court order, agreement or\r
+otherwise) that contradict the conditions of this License, they do not\r
+excuse you from the conditions of this License.  If you cannot\r
+distribute so as to satisfy simultaneously your obligations under this\r
+License and any other pertinent obligations, then as a consequence you\r
+may not distribute the Library at all.  For example, if a patent\r
+license would not permit royalty-free redistribution of the Library by\r
+all those who receive copies directly or indirectly through you, then\r
+the only way you could satisfy both it and this License would be to\r
+refrain entirely from distribution of the Library.\r
+\r
+If any portion of this section is held invalid or unenforceable under any\r
+particular circumstance, the balance of the section is intended to apply,\r
+and the section as a whole is intended to apply in other circumstances.\r
+\r
+It is not the purpose of this section to induce you to infringe any\r
+patents or other property right claims or to contest validity of any\r
+such claims; this section has the sole purpose of protecting the\r
+integrity of the free software distribution system which is\r
+implemented by public license practices.  Many people have made\r
+generous contributions to the wide range of software distributed\r
+through that system in reliance on consistent application of that\r
+system; it is up to the author/donor to decide if he or she is willing\r
+to distribute software through any other system and a licensee cannot\r
+impose that choice.\r
+\r
+This section is intended to make thoroughly clear what is believed to\r
+be a consequence of the rest of this License.\r
+\r
+  12. If the distribution and/or use of the Library is restricted in\r
+certain countries either by patents or by copyrighted interfaces, the\r
+original copyright holder who places the Library under this License may add\r
+an explicit geographical distribution limitation excluding those countries,\r
+so that distribution is permitted only in or among countries not thus\r
+excluded.  In such case, this License incorporates the limitation as if\r
+written in the body of this License.\r
+\r
+  13. The Free Software Foundation may publish revised and/or new\r
+versions of the Lesser General Public License from time to time.\r
+Such new versions will be similar in spirit to the present version,\r
+but may differ in detail to address new problems or concerns.\r
+\r
+Each version is given a distinguishing version number.  If the Library\r
+specifies a version number of this License which applies to it and\r
+"any later version", you have the option of following the terms and\r
+conditions either of that version or of any later version published by\r
+the Free Software Foundation.  If the Library does not specify a\r
+license version number, you may choose any version ever published by\r
+the Free Software Foundation.\r
+\f\r
+  14. If you wish to incorporate parts of the Library into other free\r
+programs whose distribution conditions are incompatible with these,\r
+write to the author to ask for permission.  For software which is\r
+copyrighted by the Free Software Foundation, write to the Free\r
+Software Foundation; we sometimes make exceptions for this.  Our\r
+decision will be guided by the two goals of preserving the free status\r
+of all derivatives of our free software and of promoting the sharing\r
+and reuse of software generally.\r
+\r
+          NO WARRANTY\r
+\r
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\r
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\r
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\r
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY\r
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\r
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\r
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\r
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\r
+\r
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\r
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\r
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\r
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\r
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\r
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\r
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\r
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\r
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\r
+DAMAGES.\r
+\r
+         END OF TERMS AND CONDITIONS\r
+\f\r
+           How to Apply These Terms to Your New Libraries\r
+\r
+  If you develop a new library, and you want it to be of the greatest\r
+possible use to the public, we recommend making it free software that\r
+everyone can redistribute and change.  You can do so by permitting\r
+redistribution under these terms (or, alternatively, under the terms of the\r
+ordinary General Public License).\r
+\r
+  To apply these terms, attach the following notices to the library.  It is\r
+safest to attach them to the start of each source file to most effectively\r
+convey the exclusion of warranty; and each file should have at least the\r
+"copyright" line and a pointer to where the full notice is found.\r
+\r
+    <one line to give the library's name and a brief idea of what it does.>\r
+    Copyright (C) <year>  <name of author>\r
+\r
+    This library is free software; you can redistribute it and/or\r
+    modify it under the terms of the GNU Lesser General Public\r
+    License as published by the Free Software Foundation; either\r
+    version 2.1 of the License, or (at your option) any later version.\r
+\r
+    This library is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
+    Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public\r
+    License along with this library; if not, write to the Free Software\r
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+\r
+Also add information on how to contact you by electronic and paper mail.\r
+\r
+You should also get your employer (if you work as a programmer) or your\r
+school, if any, to sign a "copyright disclaimer" for the library, if\r
+necessary.  Here is a sample; alter the names:\r
+\r
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the\r
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.\r
+\r
+  <signature of Ty Coon>, 1 April 1990\r
+  Ty Coon, President of Vice\r
+\r
+That's all there is to it!\r
+\r
+\r
diff --git a/1.8/installer/7za/history.txt b/1.8/installer/7za/history.txt
new file mode 100644 (file)
index 0000000..c4afdb9
--- /dev/null
@@ -0,0 +1,44 @@
+7-Zip Extra history\r
+-------------------\r
+\r
+4.65                2009-02-03\r
+------------------------------\r
+  - Some bugs were fixed.\r
+\r
+\r
+4.38 beta           2006-04-13\r
+------------------------------\r
+  - SFX for installers now supports new properties in config file:\r
+    Progress, Directory, ExecuteFile, ExecuteParameters.\r
+\r
+\r
+4.34 beta           2006-02-27\r
+------------------------------\r
+  - ISetProperties::SetProperties:\r
+      it's possible to specify desirable number of CPU threads: \r
+           PROPVARIANT: name=L"mt", vt = VT_UI4, ulVal = NumberOfThreads\r
+      If "mt" is not defined, 7za.dll will check number of processors in system to set \r
+      number of desirable threads. \r
+      Now 7za.dll can use:\r
+        2 threads for LZMA compressing\r
+        N threads for BZip2 compressing\r
+        4 threads for BZip2 decompressing\r
+      Other codecs use only one thread. \r
+      Note: 7za.dll can use additional "small" threads with low CPU load.\r
+  - It's possible to call ISetProperties::SetProperties to specify "mt" property for decoder.\r
+\r
+\r
+4.33 beta           2006-02-05\r
+------------------------------\r
+  - Compressing speed and Memory requirements were increased.\r
+    Default dictionary size was increased: Fastest: 64 KB, Fast: 1 MB, \r
+    Normal: 4 MB, Max: 16 MB, Ultra: 64 MB.\r
+  - 7z/LZMA now can use only these match finders: HC4, BT2, BT3, BT4\r
+\r
+\r
+4.27                2005-09-21\r
+------------------------------\r
+ - Some GUIDs/interfaces were changed.\r
+   IStream.h:\r
+     ISequentialInStream::Read now works as old ReadPart\r
+     ISequentialOutStream::Write now works as old WritePart\r
diff --git a/1.8/installer/7za/license.txt b/1.8/installer/7za/license.txt
new file mode 100644 (file)
index 0000000..7b66cf7
--- /dev/null
@@ -0,0 +1,30 @@
+      7-Zip Command line version\r
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~\r
+      License for use and distribution\r
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r
+\r
+      7-Zip Copyright (C) 1999-2009 Igor Pavlov.\r
+\r
+      7za.exe is distributed under the GNU LGPL license\r
+\r
+      Notes: \r
+        You can use 7-Zip on any computer, including a computer in a commercial \r
+        organization. You don't need to register or pay for 7-Zip.\r
+\r
+\r
+      GNU LGPL information\r
+      --------------------\r
+\r
+        This library is free software; you can redistribute it and/or\r
+        modify it under the terms of the GNU Lesser General Public\r
+        License as published by the Free Software Foundation; either\r
+        version 2.1 of the License, or (at your option) any later version.\r
+\r
+        This library is distributed in the hope that it will be useful,\r
+        but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
+        Lesser General Public License for more details.\r
+\r
+        You should have received a copy of the GNU Lesser General Public\r
+        License along with this library; if not, write to the Free Software\r
+        Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
diff --git a/1.8/installer/7za/readme.txt b/1.8/installer/7za/readme.txt
new file mode 100644 (file)
index 0000000..782494a
--- /dev/null
@@ -0,0 +1,42 @@
+7-Zip Command line version 4.65\r
+-------------------------------\r
+\r
+7-Zip is a file archiver with high compression ratio.\r
+7za.exe is a standalone command line version of 7-Zip.\r
+\r
+7-Zip Copyright (C) 1999-2009 Igor Pavlov.\r
+\r
+Features of 7za.exe: \r
+  - High compression ratio in new 7z format\r
+  - Supported formats:\r
+      - Packing / unpacking: 7z, ZIP, GZIP, BZIP2 and TAR \r
+      - Unpacking only: Z\r
+  - Highest compression ratio for ZIP and GZIP formats.\r
+  - Fast compression and decompression\r
+  - Strong AES-256 encryption in 7z and ZIP formats.\r
+\r
+7za.exe is a free software distributed under the GNU LGPL.\r
+Read license.txt for more information.\r
+\r
+Source code of 7za.exe and 7-Zip can be found at\r
+http://www.7-zip.org/\r
+\r
+7za.exe can work in Windows 95/98/ME/NT/2000/XP/2003/Vista.\r
+\r
+There is also port of 7za.exe for POSIX systems like Unix (Linux, Solaris, OpenBSD, \r
+FreeBSD, Cygwin, AIX, ...), MacOS X and BeOS:\r
+\r
+http://p7zip.sourceforge.net/\r
+\r
+\r
+  This distributive packet contains the following files:\r
+\r
+  7za.exe       - 7-Zip standalone command line version.\r
+  readme.txt    - This file.\r
+  copying.txt   - GNU LGPL license.\r
+  license.txt   - License information.\r
+  7-zip.chm     - User's Manual in HTML Help format.\r
+\r
+\r
+---\r
+End of document\r
diff --git a/1.8/installer/7za/upx.exe b/1.8/installer/7za/upx.exe
new file mode 100644 (file)
index 0000000..6266213
Binary files /dev/null and b/1.8/installer/7za/upx.exe differ
diff --git a/1.8/installer/CustomLangpack_eng.xml b/1.8/installer/CustomLangpack_eng.xml
new file mode 100644 (file)
index 0000000..7d66c45
--- /dev/null
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
+
+<!-- The English langpack -->
+
+<langpack>
+
+    <!-- NonBlankTargetPanel strings -->
+    <str id="NonBlankTargetPanel.noBlanks">
+ Sorry, the target directory cannot currently contain
+ spaces due to limitations imposed by the MinGW
+ C compiler used by OpenModelica.
+ For more information on the issue, see
+ http://www.mingw.org/wiki/Getting_Started.
+    </str>
+
+    <!-- SummaryPanel strings -->
+    <str id="NonBlankTargetPanel.summaryCaption" txt="Installation Path"/>
+
+</langpack>
diff --git a/1.8/installer/EPL.html b/1.8/installer/EPL.html
new file mode 100644 (file)
index 0000000..eae8395
--- /dev/null
@@ -0,0 +1,266 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<!-- saved from url=(0041)http://www.eclipse.org/legal/epl-v10.html -->
+<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+
+<TITLE>Eclipse Public License - Version 1.0</TITLE>
+<STYLE type="text/css">
+  body {
+    size: 8.5in 11.0in;
+    margin: 0.25in 0.5in 0.25in 0.5in;
+    tab-interval: 0.5in;
+    }
+  p {          
+    margin-left: auto;
+    margin-top:  0.5em;
+    margin-bottom: 0.5em;
+    }
+  p.list {
+       margin-left: 0.5in;
+    margin-top:  0.05em;
+    margin-bottom: 0.05em;
+    }
+  </STYLE>
+
+</HEAD><BODY lang="EN-US">
+
+<H2>Licenses</H2>
+
+<p><em>Simantics System Dynamics</em> product consists of two main components: <em>Simantics</em> and <em>Open Modelica</em>.</p>
+<p>Simantics is distributed under Eclipse Public License (EPL), see below.</p>
+<p>Open Modelica is distributed under Open Source Modelica Consortium Public License (OSMC-PL), see http://www.openmodelica.org/index.php/home/license/140.</p>
+<p>You are not allowed to redistribute OpenModelica integrated with Simantics, as in the System Dynamics Tool, without a membership in OSMC or without a separate contract with a level 2 member of OSMC.</p>
+
+<hr />
+
+<H2>Eclipse Public License - v 1.0</H2>
+
+<P>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
+PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
+DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
+AGREEMENT.</P>
+
+<P><B>1. DEFINITIONS</B></P>
+
+<P>"Contribution" means:</P>
+
+<P class="list">a) in the case of the initial Contributor, the initial
+code and documentation distributed under this Agreement, and</P>
+<P class="list">b) in the case of each subsequent Contributor:</P>
+<P class="list">i) changes to the Program, and</P>
+<P class="list">ii) additions to the Program;</P>
+<P class="list">where such changes and/or additions to the Program
+originate from and are distributed by that particular Contributor. A
+Contribution 'originates' from a Contributor if it was added to the
+Program by such Contributor itself or anyone acting on such
+Contributor's behalf. Contributions do not include additions to the
+Program which: (i) are separate modules of software distributed in
+conjunction with the Program under their own license agreement, and (ii)
+are not derivative works of the Program.</P>
+
+<P>"Contributor" means any person or entity that distributes
+the Program.</P>
+
+<P>"Licensed Patents" mean patent claims licensable by a
+Contributor which are necessarily infringed by the use or sale of its
+Contribution alone or when combined with the Program.</P>
+
+<P>"Program" means the Contributions distributed in accordance
+with this Agreement.</P>
+
+<P>"Recipient" means anyone who receives the Program under
+this Agreement, including all Contributors.</P>
+
+<P><B>2. GRANT OF RIGHTS</B></P>
+
+<P class="list">a) Subject to the terms of this Agreement, each
+Contributor hereby grants Recipient a non-exclusive, worldwide,
+royalty-free copyright license to reproduce, prepare derivative works
+of, publicly display, publicly perform, distribute and sublicense the
+Contribution of such Contributor, if any, and such derivative works, in
+source code and object code form.</P>
+
+<P class="list">b) Subject to the terms of this Agreement, each
+Contributor hereby grants Recipient a non-exclusive, worldwide,
+royalty-free patent license under Licensed Patents to make, use, sell,
+offer to sell, import and otherwise transfer the Contribution of such
+Contributor, if any, in source code and object code form. This patent
+license shall apply to the combination of the Contribution and the
+Program if, at the time the Contribution is added by the Contributor,
+such addition of the Contribution causes such combination to be covered
+by the Licensed Patents. The patent license shall not apply to any other
+combinations which include the Contribution. No hardware per se is
+licensed hereunder.</P>
+
+<P class="list">c) Recipient understands that although each Contributor
+grants the licenses to its Contributions set forth herein, no assurances
+are provided by any Contributor that the Program does not infringe the
+patent or other intellectual property rights of any other entity. Each
+Contributor disclaims any liability to Recipient for claims brought by
+any other entity based on infringement of intellectual property rights
+or otherwise. As a condition to exercising the rights and licenses
+granted hereunder, each Recipient hereby assumes sole responsibility to
+secure any other intellectual property rights needed, if any. For
+example, if a third party patent license is required to allow Recipient
+to distribute the Program, it is Recipient's responsibility to acquire
+that license before distributing the Program.</P>
+
+<P class="list">d) Each Contributor represents that to its knowledge it
+has sufficient copyright rights in its Contribution, if any, to grant
+the copyright license set forth in this Agreement.</P>
+
+<P><B>3. REQUIREMENTS</B></P>
+
+<P>A Contributor may choose to distribute the Program in object code
+form under its own license agreement, provided that:</P>
+
+<P class="list">a) it complies with the terms and conditions of this
+Agreement; and</P>
+
+<P class="list">b) its license agreement:</P>
+
+<P class="list">i) effectively disclaims on behalf of all Contributors
+all warranties and conditions, express and implied, including warranties
+or conditions of title and non-infringement, and implied warranties or
+conditions of merchantability and fitness for a particular purpose;</P>
+
+<P class="list">ii) effectively excludes on behalf of all Contributors
+all liability for damages, including direct, indirect, special,
+incidental and consequential damages, such as lost profits;</P>
+
+<P class="list">iii) states that any provisions which differ from this
+Agreement are offered by that Contributor alone and not by any other
+party; and</P>
+
+<P class="list">iv) states that source code for the Program is available
+from such Contributor, and informs licensees how to obtain it in a
+reasonable manner on or through a medium customarily used for software
+exchange.</P>
+
+<P>When the Program is made available in source code form:</P>
+
+<P class="list">a) it must be made available under this Agreement; and</P>
+
+<P class="list">b) a copy of this Agreement must be included with each
+copy of the Program.</P>
+
+<P>Contributors may not remove or alter any copyright notices contained
+within the Program.</P>
+
+<P>Each Contributor must identify itself as the originator of its
+Contribution, if any, in a manner that reasonably allows subsequent
+Recipients to identify the originator of the Contribution.</P>
+
+<P><B>4. COMMERCIAL DISTRIBUTION</B></P>
+
+<P>Commercial distributors of software may accept certain
+responsibilities with respect to end users, business partners and the
+like. While this license is intended to facilitate the commercial use of
+the Program, the Contributor who includes the Program in a commercial
+product offering should do so in a manner which does not create
+potential liability for other Contributors. Therefore, if a Contributor
+includes the Program in a commercial product offering, such Contributor
+("Commercial Contributor") hereby agrees to defend and
+indemnify every other Contributor ("Indemnified Contributor")
+against any losses, damages and costs (collectively "Losses")
+arising from claims, lawsuits and other legal actions brought by a third
+party against the Indemnified Contributor to the extent caused by the
+acts or omissions of such Commercial Contributor in connection with its
+distribution of the Program in a commercial product offering. The
+obligations in this section do not apply to any claims or Losses
+relating to any actual or alleged intellectual property infringement. In
+order to qualify, an Indemnified Contributor must: a) promptly notify
+the Commercial Contributor in writing of such claim, and b) allow the
+Commercial Contributor to control, and cooperate with the Commercial
+Contributor in, the defense and any related settlement negotiations. The
+Indemnified Contributor may participate in any such claim at its own
+expense.</P>
+
+<P>For example, a Contributor might include the Program in a commercial
+product offering, Product X. That Contributor is then a Commercial
+Contributor. If that Commercial Contributor then makes performance
+claims, or offers warranties related to Product X, those performance
+claims and warranties are such Commercial Contributor's responsibility
+alone. Under this section, the Commercial Contributor would have to
+defend claims against the other Contributors related to those
+performance claims and warranties, and if a court requires any other
+Contributor to pay any damages as a result, the Commercial Contributor
+must pay those damages.</P>
+
+<P><B>5. NO WARRANTY</B></P>
+
+<P>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
+PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
+ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
+OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and
+distributing the Program and assumes all risks associated with its
+exercise of rights under this Agreement , including but not limited to
+the risks and costs of program errors, compliance with applicable laws,
+damage to or loss of data, programs or equipment, and unavailability or
+interruption of operations.</P>
+
+<P><B>6. DISCLAIMER OF LIABILITY</B></P>
+
+<P>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
+NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
+WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
+DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
+HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</P>
+
+<P><B>7. GENERAL</B></P>
+
+<P>If any provision of this Agreement is invalid or unenforceable under
+applicable law, it shall not affect the validity or enforceability of
+the remainder of the terms of this Agreement, and without further action
+by the parties hereto, such provision shall be reformed to the minimum
+extent necessary to make such provision valid and enforceable.</P>
+
+<P>If Recipient institutes patent litigation against any entity
+(including a cross-claim or counterclaim in a lawsuit) alleging that the
+Program itself (excluding combinations of the Program with other
+software or hardware) infringes such Recipient's patent(s), then such
+Recipient's rights granted under Section 2(b) shall terminate as of the
+date such litigation is filed.</P>
+
+<P>All Recipient's rights under this Agreement shall terminate if it
+fails to comply with any of the material terms or conditions of this
+Agreement and does not cure such failure in a reasonable period of time
+after becoming aware of such noncompliance. If all Recipient's rights
+under this Agreement terminate, Recipient agrees to cease use and
+distribution of the Program as soon as reasonably practicable. However,
+Recipient's obligations under this Agreement and any licenses granted by
+Recipient relating to the Program shall continue and survive.</P>
+
+<P>Everyone is permitted to copy and distribute copies of this
+Agreement, but in order to avoid inconsistency the Agreement is
+copyrighted and may only be modified in the following manner. The
+Agreement Steward reserves the right to publish new versions (including
+revisions) of this Agreement from time to time. No one other than the
+Agreement Steward has the right to modify this Agreement. The Eclipse
+Foundation is the initial Agreement Steward. The Eclipse Foundation may
+assign the responsibility to serve as the Agreement Steward to a
+suitable separate entity. Each new version of the Agreement will be
+given a distinguishing version number. The Program (including
+Contributions) may always be distributed subject to the version of the
+Agreement under which it was received. In addition, after a new version
+of the Agreement is published, Contributor may elect to distribute the
+Program (including its Contributions) under the new version. Except as
+expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
+rights or licenses to the intellectual property of any Contributor under
+this Agreement, whether expressly, by implication, estoppel or
+otherwise. All rights in the Program not expressly granted under this
+Agreement are reserved.</P>
+
+<P>This Agreement is governed by the laws of the State of New York and
+the intellectual property laws of the United States of America. No party
+to this Agreement will bring a legal action under this Agreement more
+than one year after the cause of action arose. Each party waives its
+rights to a jury trial in any resulting litigation.</P>
+
+
+
+</BODY></HTML>
\ No newline at end of file
diff --git a/1.8/installer/TargetDir.txt.unix b/1.8/installer/TargetDir.txt.unix
new file mode 100644 (file)
index 0000000..55c2335
--- /dev/null
@@ -0,0 +1 @@
+${USER_HOME}/Simantics/Sysdyn/$APP_VER
\ No newline at end of file
diff --git a/1.8/installer/TargetDir.txt.windows b/1.8/installer/TargetDir.txt.windows
new file mode 100644 (file)
index 0000000..ccd8200
--- /dev/null
@@ -0,0 +1 @@
+C:\Simantics\Sysdyn\$APP_VER
\ No newline at end of file
diff --git a/1.8/installer/build.properties.unix b/1.8/installer/build.properties.unix
new file mode 100644 (file)
index 0000000..7183335
--- /dev/null
@@ -0,0 +1,7 @@
+izpack.home=/opt/IzPack\r
+izpack.src=${izpack.home}/src\r
+izpack.compiler=${izpack.home}/bin/compile\r
+izpack2exe.home=${izpack.home}/utils/wrappers/izpack2exe\r
+izpack2exe=${izpack2exe.home}/izpack2exe.py\r
+sevenzip.executable=/usr/bin/7za\r
+upx.executable=/usr/bin/upx\r
diff --git a/1.8/installer/build.properties.windows b/1.8/installer/build.properties.windows
new file mode 100644 (file)
index 0000000..4d6a283
--- /dev/null
@@ -0,0 +1,7 @@
+izpack.home=C:/Program Files/IzPack\r
+izpack.src=${izpack.home}/src\r
+izpack.compiler=${izpack.home}/bin/compile.bat\r
+izpack2exe.home=${izpack.home}/utils/wrappers/izpack2exe\r
+izpack2exe=${izpack2exe.home}/izpack2exe.exe\r
+sevenzip.executable=${basedir}\\7za\\7za.exe\r
+upx.executable=${basedir}\\7za\\upx.exe
\ No newline at end of file
diff --git a/1.8/installer/build.xml b/1.8/installer/build.xml
new file mode 100644 (file)
index 0000000..7ac10e3
--- /dev/null
@@ -0,0 +1,35 @@
+<project name="Installer" default="compile" basedir=".">
+
+    <property name="installer.file" value="installer.xml"/>
+
+    <condition property="is.windows">
+        <os family="windows"/>
+    </condition>
+    <condition property="is.unix">
+        <os family="unix"/>
+    </condition>
+
+    <target name="properties.windows" if="is.windows">
+        <property file="build.properties.windows"/>
+    </target>
+    <target name="properties.unix" if="is.unix">
+        <property file="build.properties.unix"/>
+    </target>
+
+    <target name="compile" depends="properties.unix,properties.windows">
+        <exec executable="${izpack.compiler}">
+            <arg value="${installer.file}"/>
+            <arg value="-o"/>
+            <arg value="${output}"/>
+        </exec>
+        <!--
+        <exec executable="${izpack2exe}" >
+            <arg value="- -file=&quot;${output}&quot;"/>
+            <arg value="- -output=&quot;${output}.exe&quot;"/>
+            <arg value="- -with-7z=&quot;${sevenzip.executable}&quot;"/>
+            <arg value="- -with-upx=&quot;${upx.executable}&quot;"/>
+        </exec>
+        -->
+    </target>
+
+</project>
diff --git a/1.8/installer/custom/NonBlankTargetPanel.java b/1.8/installer/custom/NonBlankTargetPanel.java
new file mode 100644 (file)
index 0000000..5a0f937
--- /dev/null
@@ -0,0 +1,51 @@
+\r
+/*\r
+ * Created on 29.06.2005\r
+ *\r
+ * TODO To change the template for this generated file go to\r
+ * Window - Preferences - Java - Code Style - Code Templates\r
+ */\r
+package com.izforge.izpack.panels;\r
+\r
+import com.izforge.izpack.installer.InstallData;\r
+import com.izforge.izpack.installer.InstallerFrame;\r
+\r
+\r
+/**\r
+ * @author fabrice mirabile\r
+ */\r
+public class NonBlankTargetPanel extends TargetPanel\r
+{\r
+    private static final long serialVersionUID = 3248705610571943817L;\r
+\r
+    public NonBlankTargetPanel(InstallerFrame parent, InstallData idata)\r
+    {\r
+        super(parent, idata);\r
+    }\r
+\r
+    public boolean isValidated()\r
+    {\r
+      String chosenPath = pathSelectionPanel.getPath();\r
+      if(chosenPath == null || chosenPath.length() < 1 )\r
+        return( false );\r
+      if( chosenPath.indexOf(" ") >= 0 )\r
+      {\r
+        emitError(parent.langpack.getString("installer.error"),\r
+          parent.langpack.getString("NonBlankTargetPanel.noBlanks"));\r
+        return( false );\r
+      }\r
+      return(super.isValidated() );\r
+    }\r
+\r
+    public void panelActivate()\r
+    {\r
+      super.panelActivate();\r
+      String chosenPath = pathSelectionPanel.getPath();\r
+      if(chosenPath == null || chosenPath.length() < 1 )\r
+        return;\r
+      if( chosenPath.indexOf(" ") >= 0 )\r
+          pathSelectionPanel.setPath("");\r
+    }\r
+\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/installer/custom/build.xml b/1.8/installer/custom/build.xml
new file mode 100644 (file)
index 0000000..35c193f
--- /dev/null
@@ -0,0 +1,24 @@
+<!-- INSTRUCTIONS TAKEN FROM: http://izpack.org/community/berlios-lists-archives/izpack-users/2006-March/000409.html -->
+<project name="Install Custom IzPack Panels" default="install" basedir="..">
+
+    <condition property="is.windows">
+        <os family="windows"/>
+    </condition>
+    <condition property="is.unix">
+        <os family="unix"/>
+    </condition>
+
+    <target name="properties.windows" if="is.windows">
+        <property file="build.properties.windows"/>
+    </target>
+    <target name="properties.unix" if="is.unix">
+        <property file="build.properties.unix"/>
+    </target>
+
+    <target name="install" depends="properties.windows,properties.unix">
+        <copy file="custom/izpack-src-build.xml" toFile="${izpack.src}/build.xml"/>
+        <copy file="custom/NonBlankTargetPanel.java" toDir="${izpack.src}/lib/com/izforge/izpack/panels"/>
+        <ant antfile="${izpack.src}/build.xml" target="all" dir="${izpack.home}" />
+    </target>
+
+</project>
diff --git a/1.8/installer/custom/izpack-src-build.xml b/1.8/installer/custom/izpack-src-build.xml
new file mode 100644 (file)
index 0000000..436cc5c
--- /dev/null
@@ -0,0 +1,1346 @@
+<project name="IzPack" default="all" basedir="..">
+    <!--
+  $Id$
+
+  build.xml first written by Pierre Dittgen (pierre.dittgen@criltelecom.com)
+  This file is intended to be used with ant (http://jakarta.apache.org/ant),
+  a java/xml makefile utility.
+
+    14.8.2001: (by Pierre Dittgen)
+  Creation of the build.xml. It only compile all the src files.
+
+    16.8.2001: (by Pierre Dittgen)
+  Added creation of compiler.jar, installer.jar and compilation of the
+  panels.
+
+    28.8.2001: (by Pierre Dittgen)
+  Added compile.uninstaller and build.uninstaller targets to create the
+  uninstaller.jar jar file.
+
+    02.9.2001: (by Julien Ponge)
+        Improved compilation options (optimizations, deprecation warnings) and
+        changed the build dir to src/build. Fixed the compiling/building of the
+        uninstaller.
+
+    12.9.2001: (by Julien Ponge)
+        Added creation/compilation of the frontend and its associated jar file.
+
+    22.9.2001: (by Julien Ponge)
+        Small fix in the all target that caused an error if the build dir was
+        not yet created.
+
+    14.10.2001: (by Julien Ponge)
+        Added the XPanel compilation call.
+
+    12.12.2001: (by Julien Ponge)
+        Removed the 'clean' dependency for the 'all' target.
+
+    12.02.2002: (by Julien Ponge)
+        Moved the 'build' directory out of the src/ scope (usefull for my CVS
+        files moving scripts).
+        Added a markup to specify IBM Jikes as the compiler (just comment out to
+        use another one).
+
+    21.02.2002: (by Paul Wilkinson)
+        Added tasks to compiler.compiler and build.compiler to build ant task class.
+
+    02.03.2002: (by Julien Ponge)
+        Modified the building of the panels so that the inner classes can be copied
+        too.
+
+    18.04.2002: (by Julien Ponge)
+        Added the new com.izforge.izpack.util & com.izforge.izpack.util.os
+        packages to the installer.jar build process.
+
+    19.04.2002: (by Olexij Tkatchenko & Julien Ponge)
+        Added "dist" target for bootstrapped IzPack package creation.
+
+    01.06.2002: (by Julien Ponge)
+        Changed the panels building process in order to enable the ShortcutData
+        classes to be move in the same directory as the ShortcutPanel classes.
+
+    15.06.2002: (by Julien Ponge)
+        Added the ant-generated manifests in the clean target scope.
+
+    03.07.2002: (by Julien Ponge)
+        Added a target to generate some javadoc.
+
+    12.01.2003: (by Julien Ponge)
+        Separated the installer generation from the dist target so that it is
+        much cleaner.
+
+    13.01.2003: (by Julien Ponge)
+        Enhanced the clean target.
+
+    27.02.2003: (by Julien Ponge)
+        Fixed the UserInputPanel building process to include all the required
+        files.
+
+    30.04.2003: (by Jonathan Halliday)
+        Change to panel compilation target, for panel automation
+        (silent install) support.
+
+    05.07.2003: (by Julien Ponge)
+        Added a target to fix the files encoding and cr/lf (fix.crlf).
+
+    10.09.2003: (by Julien Ponge)
+        Reformatting, 4 spaces tabs, got rid of residual hard tabs.
+
+    19.09.2003: (by Julien Ponge)
+        Added a run.installer target to test an installer.
+
+    06.12.2003: (by Julien Ponge)
+        Removed the frontend-related sections.
+
+    16.12.2003: (by Julien Ponge)
+        Added the SudoPanel building call.
+
+    18.02.2004: (by Julien Ponge)
+        New installer naming scheme (IzPack-install-{version}.jar).
+
+    29.05.2004: (by Julien Ponge)
+        New SimpleFinishPanel.
+
+    30.07.2004: (by Klaus Bartz)
+        Simple CustomAction stuff added.
+
+    09.09.2004: (by Klaus Bartz)
+        Clean up of CustomActions added.
+        New uninstaller-ext.jar with native helper stuff for native libs
+           in uninstaller.
+
+    14.10.2004: (by Klaus Bartz)
+        New izevent.jar with the base classes of the custom action stuff
+          to support creation of custom action jars without IzPack source tree
+
+    25.10.2004: (by Klaus Bartz)
+        "Standard" CustomActions AntActionInstallerListener and
+        AntActionUninstallerListener added
+
+    03.05.2005: (by Klaus Bartz)
+        Target generated.installer-reg added:
+        Creates an installer for IzPack with registry support
+
+    09.05.2005: (by Marc Eppelman)
+        Target dist+run added:
+        convenient :) makes a complete dist an installer and run them
+
+    11.05.2005: (by Fabrice Mirabile)
+        Target cleandistreg added:
+        Clean, Regenerate installer and installer with reg support. Avoid use of bad jars during installation.
+
+    18.07.2005: (by Julien Ponge)
+       Enforce source / target compatibility, now 1.4 / 1.4.
+
+    02.09.2005: (by Klaus Bartz)
+       Unicode support of ShellLink.
+
+    09.09.2005: (Marc.Eppelmann)
+               Added start.sh to the shipped files in bin-folder.
+
+       10.01.2006: (by Fabrice Mirabile)
+               Added the splashscreen to the cleandistreg target
+
+       06.04.2006: (Marc Eppelmann)
+           Inserted the fix.crlf target in the depends-list of target "all" to prevent encoding problems.
+
+       26.06.2006: (Marc Eppelmann)
+           Extracted / Reordered some dist related targets to prevent double copy actions.
+        Also fixed the fix.crlf basedir
+
+       27.08.2006: (Marc Eppelmann)
+      Embedd ShortcutPanel*.java
+
+  14.09.2006: (Marc Eppelmann)
+      Added target src.tar.gz and clean.src.tar.gz
+
+  19.10.2006: (Fabrice Mirabile & Hal Vaughan)
+      Added DataCheckPanel
+
+  10.10.2006: (Fabrice Mirabile)
+         Fixed target src.tar.gz and clean.src.tar.gz
+
+  11.02.2007: (Ari Voutilainen)
+     Added 'preservelastmodified="true"' to all 'copy todir' commands to keep original file date
+     and time. This will effect in directory _dist. This won't effect to compiled files and
+     other files which are manipulated during the process.
+
+  08.11.2007: (Julien Ponge)
+     Call the new docutils-based documentation build system.
+
+
+  Mini-HowTo:
+
+  To compile and package the compiler.jar jar file, type:
+    ant build.compiler
+
+  To compile and package the installer.jar jar file, type:
+    ant build.installer
+
+  To compile and package the uninstaller.jar jar file, type:
+    ant build.uninstaller
+
+  To compile the panels and put them in the bin/panels directory, type:
+    ant build.panels
+
+    To compile and package the frontend.jar jar file, type:
+        ant build.frontend
+
+  To make all, type:
+    ant all
+  or
+    ant
+  (this is the default target)
+
+    To compile and create IzPack distribution package type:
+    ant dist
+
+    To delete the classes directory after packaging, just type:
+    ant clean
+  -->
+
+    <!-- Compiler to use put your own here (jikes, modern, gcj, ...) -->
+    <!--<property name="build.compiler" value="jikes" />-->
+
+    <!-- Define directories -->
+    <property name="cwd" value="${basedir}"/>
+
+    <property file="src/ant.properties"/>
+    <property name="ver" value="4.3"/>
+    <property name="rel" value="3"/>
+    <property name="build.number" value="${ver}.${rel}"/>
+
+    <property name="src.dir" value="${basedir}/src/lib"/>
+    <property name="img.dir" value="${basedir}/src/img"/>
+    <property name="bin.dir" value="${basedir}/bin"/>
+    <property name="doc.dir" value="${basedir}/doc"/>
+
+    <property name="langpacks.subdir" value="langpacks"/>
+    <property name="langpacks.dir" value="${basedir}/bin/${langpacks.subdir}"/>
+
+    <property name="build.subdir" value="_build"/>
+    <property name="build.dir" value="${basedir}/${build.subdir}"/>
+                                          
+    <property name="dist.subdir" value="_dist"/>
+    <property name="dist.dir" value="${basedir}/${dist.subdir}"/>
+    <property name="dist-files.dir" value="${basedir}/src/dist-files"/>
+
+    <!-- Define Main-Classes -->
+    <property name="compiler.class" value="com.izforge.izpack.compiler.Compiler"/>
+    <property name="installer.class" value="com.izforge.izpack.installer.Installer"/>
+    <property name="uninstaller.class" value="com.izforge.izpack.uninstaller.Uninstaller"/>
+
+    <!-- Define file paths -->
+    <property name="compiler.jar" value="${basedir}/lib/compiler.jar"/>
+    <property name="standalone-compiler.jar" value="${basedir}/lib/standalone-compiler.jar"/>
+    <property name="installer.jar" value="${basedir}/lib/installer.jar"/>
+    <property name="uninstaller.jar" value="${basedir}/lib/uninstaller.jar"/>
+    <property name="uninstaller-ext.jar" value="${basedir}/lib/uninstaller-ext.jar"/>
+    <property name="izevent.jar" value="${basedir}/lib/izevent.jar"/>
+
+    <!-- Compilation parameters -->
+    <property name="debug" value="off"/>
+    <property name="debuglevel" value=""/>
+    <!--<property name="debug" value="true"/>
+    <property name="debuglevel" value="lines,vars,source"/>-->
+    <property name="compat.source" value="1.5"/>
+    <property name="compat.target" value="1.5"/>
+
+
+    <!-- paths -->
+    <path id="classpath">
+        <fileset id="ext.libs" dir="${basedir}/lib">
+            <!-- older ant jar, which izpack distributes and uses for fileset behavior -->
+            <include name="ant.jar"/>
+            <include name="jakarta-regexp-1.3.jar"/>
+        </fileset>
+        <!-- current ant jar, for compiling IzPackTask which uses modern ant features -->
+        <fileset dir="${ant.home}/lib" includes="ant.jar"/>
+    </path>
+
+    <!-- Checking target -->
+    <target name="check">
+        <echo message="basedir=${basedir}"/>
+        <echo message="dist.dir=${dist.dir}"/>
+        <echo message="build.dir=${build.dir}"/>
+        <echo message="debug=${debug}"/>
+    </target>
+
+    <!-- Creates the classes directory -->
+    <target name="prepare" depends="time">
+        <mkdir dir="${build.dir}"/>
+        <mkdir dir="${basedir}/lib"/>
+        <mkdir dir="${dist.dir}"/>
+    </target>
+
+    <!-- Compiles the compiler src files -->
+    <target name="compile.compiler" depends="prepare">
+        <javac srcdir="${src.dir}"
+               classpath="${basedir}/lib/jakarta-regexp-1.3.jar"
+               destdir="${build.dir}"
+               optimize="on"
+               source="${compat.source}"
+               target="${compat.target}"
+               deprecation="on"
+               debug="${debug}"
+               debuglevel="${debuglevel}">
+            <include name="com/izforge/izpack/*.java"/>
+            <include name="com/izforge/izpack/io/*.java"/>
+            <include name="com/izforge/izpack/compiler/*.java"/>
+            <include name="com/izforge/izpack/compressor/*.java"/>
+            <include name="com/izforge/izpack/ant/*.java"/>
+            <include name="com/izforge/izpack/util/Debug.java"/>
+            <include name="com/izforge/izpack/util/OsConstraint.java"/>
+            <include name="com/izforge/izpack/util/JarOutputStream.java"/>
+            <include name="com/izforge/izpack/rules/*.java"/>
+            <!--<include name="net/n3/nanoxml/*.java"/>-->
+            <include name="com/izforge/izpack/adaptator/**/*.java"/>
+            <include name="com/izforge/izpack/adaptator/*.java"/>
+        </javac>
+        <copy todir="${build.dir}/com/izforge/izpack/ant/langpacks">
+            <fileset dir="${src.dir}/com/izforge/izpack/ant/langpacks"/>
+        </copy>
+        <copy todir="${build.dir}/com/izforge/izpack/adaptator">
+            <fileset dir="${src.dir}/com/izforge/izpack/adaptator"/>
+        </copy>
+    </target>
+
+    <!-- Package compiler.jar -->
+    <target name="build.compiler" depends="compile.compiler">
+        <jar jarfile="${compiler.jar}">
+            <manifest>
+                <attribute name="Built-By" value="IzPack"/>
+                <attribute name="Class-Path" value="ant.jar"/>
+                <attribute name="Main-Class" value="${compiler.class}"/>
+            </manifest>
+            <fileset dir="${build.dir}">
+                <include name="com/izforge/izpack/*.class"/>
+                <include name="com/izforge/izpack/io/*.class"/>
+                <include name="com/izforge/izpack/compiler/*.class"/>
+                <include name="com/izforge/izpack/compressor/*.class"/>
+                <include name="com/izforge/izpack/util/OsConstraint.class"/>
+                <include name="com/izforge/izpack/util/Debug.class"/>
+                <include name="com/izforge/izpack/util/*Validator.class"/>
+                <include name="com/izforge/izpack/util/*Processor.class"/>
+                <include name="com/izforge/izpack/util/VariableSubstitutor.class"/>
+                <include name="com/izforge/izpack/util/JarOutputStream.class"/>
+                <include name="com/izforge/izpack/util/FileUtil.class"/>
+                <include name="com/izforge/izpack/ant/*.class"/>
+                <include name="com/izforge/izpack/ant/langpacks/*.properties"/>
+                <include name="com/izforge/izpack/adaptator/*.xsl"/>
+                <include name="com/izforge/izpack/event/CompilerListener.class"/>
+                <include name="com/izforge/izpack/event/SimpleCompilerListener.class"/>
+                <include name="com/izforge/izpack/rules/*.class"/>
+                <include name="com/izforge/izpack/installer/*.class"/>
+                <include name="com/izforge/izpack/adaptator/**/*.class"/>
+                <include name="com/izforge/izpack/adaptator/*.class"/>
+            </fileset>
+        </jar>
+    </target>
+
+    <!-- Package standalone-compiler.jar -->
+    <target name="build.standalone-compiler"
+            depends="compile.compiler, build.installer, build.uninstaller, build.uninstaller-ext, build.panels, build.listeners">
+        <jar jarfile="${standalone-compiler.jar}" duplicate="preserve">
+            <manifest>
+                <attribute name="Built-By" value="IzPack"/>
+                <attribute name="Class-Path" value="ant.jar"/>
+                <attribute name="Main-Class" value="${compiler.class}"/>
+            </manifest>
+                       <fileset dir="${build.dir}">
+                <include name="**/*.class"/>
+                       </fileset>
+            <zipfileset src="lib/ant.jar"/>
+            <fileset dir="${basedir}">
+                <include name="bin/langpacks/flags/*"/>
+                <include name="bin/langpacks/installer/*"/>
+                <include name="bin/native/izpack/*"/>
+                <include name="bin/native/3rdparty/*"/>
+                <include name="bin/panels/*Panel.jar"/>
+                <include name="bin/customActions/*.jar"/>
+                <include name="lib/*.jar"/>
+                               <exclude name="lib/standalone-compiler.jar"/>
+            </fileset>
+             <fileset dir="${src.dir}">
+                <include name="**/*"/>
+                <exclude name="**/*.java"/> 
+            </fileset>
+        </jar>
+    </target>
+
+    <!-- Compiles the installer src files -->
+    <target name="compile.installer" depends="prepare">
+        <javac srcdir="${src.dir}"
+               classpath="${basedir}/lib/jakarta-regexp-1.3.jar"
+               destdir="${build.dir}"
+               optimize="on"
+               source="${compat.source}"
+               target="${compat.target}"
+               deprecation="on"
+               debug="${debug}"
+               debuglevel="${debuglevel}">
+            <include name="com/izforge/izpack/panels/PathSelectionPanel.java"/>
+            <include name="com/izforge/izpack/*.java"/>
+            <include name="com/izforge/izpack/gui/*.java"/>
+            <include name="com/izforge/izpack/io/*.java"/>
+            <include name="com/izforge/izpack/installer/*.java"/>
+            <include name="com/izforge/izpack/panels/NextMedia*.java"/>
+            <include name="com/izforge/izpack/util/*.java"/>
+            <include name="com/izforge/izpack/util/os/*.java"/>
+            <include name="com/izforge/izpack/rules/*.java"/>
+            <include name="com/izforge/izpack/uninstaller/SelfModifier*.java"/>
+            <include name="com/izforge/izpack/rules/*.java"/>
+            <include name="com/izforge/izpack/compiler/DynamicVariable.java"/>
+            <!--<include name="net/n3/nanoxml/*.java"/>-->
+            <include name="com/izforge/izpack/panels/HelpWindow.java" />
+            <include name="com/izforge/izpack/adaptator/**/*.java"/>
+            <include name="com/izforge/izpack/adaptator/*.java"/>
+        </javac>
+    </target>
+
+    <!-- Package installer.jar -->
+    <target name="build.installer" depends="compile.installer, build.listener-base">
+        <jar jarfile="${installer.jar}">
+            <manifest>
+                <attribute name="Built-By" value="IzPack"/>
+                <attribute name="Class-Path" value=""/>
+                <attribute name="Main-Class" value="${installer.class}"/>
+            </manifest>
+            <fileset dir="${build.dir}">
+                <include name="com/izforge/izpack/panels/PathSelectionPanel.class"/>
+                <include name="com/izforge/izpack/*.class"/>
+                <include name="com/izforge/izpack/gui/*.class"/>
+                <include name="com/izforge/izpack/io/*.class"/>
+                <include name="com/izforge/izpack/installer/*.class"/>
+                <include name="com/izforge/izpack/util/*.class"/>
+                <include name="com/izforge/izpack/util/**/*.class"/>
+                <include name="com/izforge/izpack/panels/NextMedia*.class"/>
+                <include name="com/izforge/izpack/rules/*.class"/>
+                <include name="com/izforge/izpack/uninstaller/SelfModifier*.class"/>
+                <include name="com/izforge/izpack/rules/*.class"/>
+                <include name="com/izforge/izpack/compiler/DynamicVariable.class"/>
+                <include name="com/izforge/izpack/compiler/CompilerException.class"/>
+                <include name="com/izforge/izpack/panels/Validator*.class"/>
+                <!--<include name="net/n3/nanoxml/*.class"/>-->
+               <include name="com/izforge/izpack/adaptator/**/*.class"/>
+               <include name="com/izforge/izpack/adaptator/*.class"/>
+                <include name="com/izforge/izpack/panels/HelpWindow.class" />                
+            </fileset>
+            <zipfileset src="${basedir}/lib/jakarta-regexp-1.3.jar">
+                <include name="org/apache/regexp/*.class"/>
+            </zipfileset>
+            <fileset dir="${src.dir}">
+                <include name="com/izforge/izpack/installer/*.xml"/>
+                <include name="com/izforge/izpack/installer/*.properties"/>
+                <include name="com/izforge/izpack/installer/run-with-privileges-on-osx"/>
+                <include name="com/izforge/izpack/installer/elevate.js"/>
+               <include name="com/izforge/izpack/util/**/*.sh"/>
+               <include name="com/izforge/izpack/adaptator/styleSheet.xsl"/>
+            </fileset>
+            <fileset dir="${img.dir}/installer"/>
+            <zipfileset src="${izevent.jar}">
+                <include name="com/izforge/izpack/event/*InstallerListener.class"/>
+            </zipfileset>
+        </jar>
+    </target>
+
+    <!-- Compiles the uninstaller src files -->
+    <target name="compile.uninstaller" depends="prepare">
+        <javac srcdir="${src.dir}"
+               destdir="${build.dir}"
+               optimize="on"
+               source="${compat.source}"
+               target="${compat.target}"
+               deprecation="on"
+               debug="${debug}"
+               debuglevel="${debuglevel}">
+            <include name="com/izforge/izpack/LocaleDatabase.java"/>
+            <include name="com/izforge/izpack/gui/*.java"/>
+
+            <include name="com/izforge/izpack/util/*.java"/>
+            <include name="com/izforge/izpack/util/os/*.java"/>
+            <include name="com/izforge/izpack/util/os/unix/*.java"/>
+
+            <include name="com/izforge/izpack/uninstaller/*.java"/>
+            <exclude name="com/izforge/izpack/gui/IzPackKMetalTheme.java"/>
+            <!--<include name="net/n3/nanoxml/*.java"/>-->
+            <include name="com/izforge/izpack/adaptator/**/*.java"/>
+            <include name="com/izforge/izpack/adaptator/*.java"/>
+        </javac>
+    </target>
+
+    <!-- Package uninstaller.jar -->
+    <target name="build.uninstaller" depends="compile.uninstaller">
+        <jar jarfile="${uninstaller.jar}">
+            <manifest>
+                <attribute name="Built-By" value="IzPack"/>
+                <attribute name="Class-Path" value=""/>
+                <attribute name="Main-Class" value="${uninstaller.class}"/>
+            </manifest>
+            <fileset dir="${build.dir}">
+                <include name="com/izforge/izpack/LocaleDatabase.class"/>
+                <include name="com/izforge/izpack/gui/*.class"/>
+                <include name="com/izforge/izpack/uninstaller/*.class"/>
+                <include name="com/izforge/izpack/ExecutableFile.class"/>
+                <exclude name="com/izforge/izpack/gui/IzPackKMetalTheme.class"/>
+                <!--<include name="net/n3/nanoxml/*.class"/>-->
+               <include name="com/izforge/izpack/adaptator/**/*.class"/>
+               <include name="com/izforge/izpack/adaptator/*.class"/>
+                <include name="com/izforge/izpack/installer/PrivilegedRunner.class"/>          
+            </fileset>
+            <fileset dir="${src.dir}">
+                <include name="com/izforge/izpack/installer/run-with-privileges-on-osx"/>
+                <include name="com/izforge/izpack/installer/elevate.js"/>
+               <include name="com/izforge/izpack/adaptator/styleSheet.xsl"/>
+                <include name="com/izforge/izpack/util/**/*.sh"/>
+            </fileset>
+            <fileset dir="${build.dir}">
+                <include name="com/izforge/izpack/util/**/*.class"/>
+            </fileset>
+            <fileset dir="${img.dir}/uninstaller">
+                <include name="**/*"/>
+            </fileset>
+            <zipfileset src="${izevent.jar}">
+                <include name="com/izforge/izpack/event/*UninstallerListener.class"/>
+            </zipfileset>
+        </jar>
+    </target>
+
+    <!-- Compiles the extended uninstaller src files -->
+    <target name="compile.uninstaller-ext" depends="prepare">
+        <javac srcdir="${src.dir}"
+               destdir="${build.dir}"
+               optimize="on"
+               source="${compat.source}"
+               target="${compat.target}"
+               deprecation="on"
+               debug="${debug}"
+               debuglevel="${debuglevel}">
+            <include name="com/izforge/izpack/util/*.java"/>
+            <include name="com/izforge/izpack/util/os/*.java"/>
+            <include name="com/izforge/izpack/util/os/unix/*.java"/>
+            <include name="com/izforge/izpack/util/xml/*.java"/>
+
+            <exclude name="com/izforge/izpack/gui/IzPackKMetalTheme.java"/>
+            <!--<include name="net/n3/nanoxml/*.java"/>-->
+            <include name="com/izforge/izpack/adaptator/**/*.java"/>
+            <include name="com/izforge/izpack/adaptator/*.java"/>
+        </javac>
+    </target>
+    <!-- Package extended uninstaller.jar used if one ore more native libs are
+         declared for uninstallation -->
+    <target name="build.uninstaller-ext" depends="compile.uninstaller-ext">
+        <jar jarfile="${uninstaller-ext.jar}">
+            <fileset dir="${build.dir}">
+                <include name="com/izforge/izpack/util/**/*.class"/>
+            </fileset>
+        </jar>
+    </target>
+
+    <!--
+         ======================================================================
+           Create Panel Modules
+         ======================================================================
+    -->
+
+    <!-- Macro to compile a panel's classes and create it's jar file -->
+    <macrodef name="build-panel">
+        <attribute name="name" description="The panels jar will get this name"/>
+        <attribute name="srcdir"
+                   default="${src.dir}"
+                   description="Source directory. Defaults to izpack src dir"/>
+        <element name="panel-fileset"
+                 implicit="yes"
+                 description="include and exclude elements indicating panel sources"/>
+        <sequential>
+            <echo message="build-panel: @{name}"/>
+            <mkdir dir="${bin.dir}/panels/@{name}"/>
+            <!-- sourcepath is cleared so there's no mistaking what goes into the Panel -->
+            <javac srcdir="@{srcdir}"
+                   destdir="${bin.dir}/panels/@{name}"
+                   classpath="${installer.jar}"
+                   sourcepath=""
+                   optimize="on"
+                   deprecation="on"
+                   debug="${debug}"
+                   source="${compat.source}"
+                   target="${compat.target}"
+                   debuglevel="${debuglevel}">
+                <panel-fileset/>
+            </javac>
+            <jar jarfile="${bin.dir}/panels/@{name}.jar" basedir="${bin.dir}/panels/@{name}"/>
+        </sequential>
+    </macrodef>
+
+    <!-- Compile all panels and put them at the right location -->
+    <!--
+         If you add a another, and the build fails because it can't find a class,
+         be sure to explicitly include the .java file in the nested fileset.
+         This also acts as a check to help limit dependancies.
+    -->
+    <target name="build.panels" depends="build.installer">
+        <mkdir dir="${bin.dir}/panels"/>
+
+        <build-panel name="FinishPanel">
+            <include name="com/izforge/izpack/panels/FinishPanel.java"/>
+               <include name="com/izforge/izpack/panels/FinishPanelConsoleHelper.java" />
+        </build-panel>
+        <build-panel name="HelloPanel">
+            <include name="com/izforge/izpack/panels/HelloPanel.java"/>
+               <include name="com/izforge/izpack/panels/HelloPanelConsoleHelper.java" />
+        </build-panel>
+        <build-panel name="SelectPrinterPanel">
+            <include name="com/izforge/izpack/panels/SelectPrinterPanel.java"/>
+        </build-panel>
+        <build-panel name="DataCheckPanel">
+            <include name="com/izforge/izpack/panels/DataCheckPanel.java"/>
+        </build-panel>
+        <build-panel name="CheckedHelloPanel">
+            <include name="com/izforge/izpack/panels/CheckedHelloPanel.java"/>
+            <include name="com/izforge/izpack/panels/HelloPanel.java"/>
+            <include name="com/izforge/izpack/util/os/*RegistryHandler.java"/>
+            <include name="com/izforge/izpack/util/OSClassHelper.java"/>
+            <include name="com/izforge/izpack/util/os/WrappedNativeLibException.java"/>
+            <include name="com/coi/tools/os/win/*.java"/>
+            <include name="com/coi/tools/os/win/resources/NativeLibErr*.java"/>
+            <include name="com/coi/tools/os/izpack/Registry.java"/>
+            <include name="com/coi/tools/os/izpack/COIOSHelper.java"/>
+        </build-panel>
+        <build-panel name="InfoPanel">
+            <include name="com/izforge/izpack/panels/InfoPanel.java"/>
+        </build-panel>
+        <build-panel name="InstallPanel">
+            <include name="com/izforge/izpack/panels/InstallPanel.java"/>
+            <include name="com/izforge/izpack/panels/InstallPanelAutomationHelper.java"/>
+               <include name="com/izforge/izpack/panels/InstallPanelConsoleHelper.java" />
+        </build-panel>
+        <build-panel name="ExtendedInstallPanel">
+            <include name="com/izforge/izpack/panels/ExtendedInstallPanel.java"/>
+            <include name="com/izforge/izpack/panels/ExtendedInstallPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/InstallPanel.java"/>
+        </build-panel>
+        <build-panel name="LicencePanel">
+            <include name="com/izforge/izpack/panels/LicencePanel.java"/>
+            <include name="com/izforge/izpack/panels/LicencePanelConsoleHelper.java"/>
+        </build-panel>
+        <build-panel name="PacksPanel">
+            <include name="com/izforge/izpack/panels/ImgPacksPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/ImgPacksPanelBase.java"/>
+            <include name="com/izforge/izpack/panels/PacksModel.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanel.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelBase.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelInterface.java"/>
+        </build-panel>
+        <build-panel name="ImgPacksPanel">
+            <include name="com/izforge/izpack/panels/ImgPacksPanel.java"/>
+            <include name="com/izforge/izpack/panels/ImgPacksPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/PacksModel.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelBase.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelInterface.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelAutomationHelper.java"/>
+        </build-panel>
+        <build-panel name="HTMLLicencePanel">
+            <include name="com/izforge/izpack/panels/HTMLLicencePanel.java"/>
+            <include name="com/izforge/izpack/panels/HTMLLicencePanelConsoleHelper.java"/>
+        </build-panel>
+        <build-panel name="HTMLInfoPanel">
+            <include name="com/izforge/izpack/panels/HTMLInfoPanel.java"/>
+        </build-panel>
+        <build-panel name="TargetPanel">
+            <include name="com/izforge/izpack/panels/PathInputPanel.java"/>
+            <include name="com/izforge/izpack/panels/PathSelectionPanel.java"/>
+            <include name="com/izforge/izpack/panels/TargetPanel.java"/>
+            <include name="com/izforge/izpack/panels/TargetPanelAutomationHelper.java"/>
+               <include name="com/izforge/izpack/panels/TargetPanelConsoleHelper.java" />
+        </build-panel>
+        <build-panel name="DefaultTargetPanel">
+            <include name="com/izforge/izpack/panels/PathInputPanel.java"/>
+            <include name="com/izforge/izpack/panels/PathSelectionPanel.java"/>
+            <include name="com/izforge/izpack/panels/DefaultTargetPanel.java"/>
+            <include name="com/izforge/izpack/panels/DefaultTargetPanelAutomationHelper.java"/>
+        </build-panel>
+        <build-panel name="JDKPathPanel">
+            <include name="com/izforge/izpack/panels/JDKPathPanel.java"/>
+            <include name="com/izforge/izpack/panels/PathInputPanel.java"/>
+            <include name="com/izforge/izpack/panels/PathSelectionPanel.java"/>
+            <include name="com/izforge/izpack/util/os/*RegistryHandler.java"/>
+            <include name="com/izforge/izpack/util/OSClassHelper.java"/>
+            <include name="com/izforge/izpack/util/os/WrappedNativeLibException.java"/>
+            <include name="com/coi/tools/os/win/*.java"/>
+            <include name="com/coi/tools/os/win/resources/NativeLibErr*.java"/>
+            <include name="com/coi/tools/os/izpack/Registry.java"/>
+            <include name="com/coi/tools/os/izpack/COIOSHelper.java"/>
+        </build-panel>
+        <build-panel name="XInfoPanel">
+            <include name="com/izforge/izpack/panels/XInfoPanel.java"/>
+        </build-panel>
+        <build-panel name="ShortcutPanel">
+            <include name="com/izforge/izpack/panels/ShortcutData.java"/>
+            <include name="com/izforge/izpack/panels/ShortcutPanel*.java"/>
+            <include name="com/izforge/izpack/util/xml/*.java"/>
+        </build-panel>
+        <build-panel name="UserInputPanel">
+            <include name="com/izforge/izpack/panels/PasswordGroup.java"/>
+            <include name="com/izforge/izpack/panels/ProcessingClient.java"/>
+               <include name="com/izforge/izpack/panels/StringInputProcessingClient.java"/>
+            <include name="com/izforge/izpack/panels/Processor.java"/>
+            <include name="com/izforge/izpack/panels/RuleInputField.java"/>
+            <include name="com/izforge/izpack/panels/RuleTextField.java"/>
+            <include name="com/izforge/izpack/panels/TextInputField.java"/>
+               <include name="com/izforge/izpack/panels/FileInputField.java"/>
+               <include name="com/izforge/izpack/panels/DirInputField.java"/>
+               <include name="com/izforge/izpack/panels/MultipleFileInputField.java"/>
+            <include name="com/izforge/izpack/panels/UserInputPanel.java"/>            
+            <include name="com/izforge/izpack/panels/UserInputPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/Validator.java"/>
+            <include name="com/izforge/izpack/panels/ValidatorContainer.java"/>
+               <include name="com/izforge/izpack/panels/UIElementType.java"/>
+            <include name="com/izforge/izpack/panels/UIElement.java"/>
+            <include name="com/izforge/izpack/panels/RadioButtonUIElement.java"/>
+            <include name="com/izforge/izpack/panels/PasswordUIElement.java"/>   
+               <include name="com/izforge/izpack/panels/UserInputPanelConsoleHelper.java" />
+        </build-panel>
+        <build-panel name="UserPathPanel">
+            <include name="com/izforge/izpack/panels/UserPathInputPanel.java"/>
+            <include name="com/izforge/izpack/panels/UserPathSelectionPanel.java"/>
+            <include name="com/izforge/izpack/panels/UserPathPanel.java"/>
+            <include name="com/izforge/izpack/panels/UserPathPanelAutomationHelper.java"/>
+        </build-panel>
+        <build-panel name="ConditionalUserInputPanel">
+            <include name="com/izforge/izpack/panels/ConditionalUserInputPanel.java"/>
+            <include name="com/izforge/izpack/panels/PasswordGroup.java"/>
+            <include name="com/izforge/izpack/panels/ProcessingClient.java"/>
+               <include name="com/izforge/izpack/panels/StringInputProcessingClient.java"/>
+            <include name="com/izforge/izpack/panels/Processor.java"/>
+            <include name="com/izforge/izpack/panels/RuleInputField.java"/>
+            <include name="com/izforge/izpack/panels/RuleTextField.java"/>
+               <include name="com/izforge/izpack/panels/FileInputField.java"/>
+               <include name="com/izforge/izpack/panels/DirInputField.java"/>
+               <include name="com/izforge/izpack/panels/MultipleFileInputField.java"/>
+            <include name="com/izforge/izpack/panels/TextInputField.java"/>
+            <include name="com/izforge/izpack/panels/UserInputPanel.java"/>
+            <include name="com/izforge/izpack/panels/UserInputPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/Validator.java"/>
+            <include name="com/izforge/izpack/panels/ValidatorContainer.java"/>
+               <include name="com/izforge/izpack/panels/UIElementType.java"/>
+            <include name="com/izforge/izpack/panels/UIElement.java"/>
+            <include name="com/izforge/izpack/panels/RadioButtonUIElement.java"/>
+            <include name="com/izforge/izpack/panels/PasswordUIElement.java"/>                 
+        </build-panel>
+        <build-panel name="CompilePanel">
+            <include name="com/izforge/izpack/panels/CompilePanel.java"/>
+            <include name="com/izforge/izpack/panels/CompilePanelAutomationHelper.java"/>
+        </build-panel>
+        <build-panel name="ProcessPanel">
+            <include name="com/izforge/izpack/panels/ProcessPanel.java"/>
+            <include name="com/izforge/izpack/panels/ProcessPanelAutomationHelper.java"/>
+        </build-panel>
+        <build-panel name="SudoPanel">
+            <include name="com/izforge/izpack/panels/SudoPanel.java"/>
+        </build-panel>
+        <build-panel name="SimpleFinishPanel">
+            <include name="com/izforge/izpack/panels/SimpleFinishPanel.java"/>
+        </build-panel>
+        <build-panel name="SummaryPanel">
+            <include name="com/izforge/izpack/panels/SummaryPanel.java"/>
+        </build-panel>
+        <build-panel name="InstallationGroupPanel">
+            <include name="com/izforge/izpack/panels/InstallationGroupPanel.java"/>
+            <include name="com/izforge/izpack/panels/InstallationGroupPanelAutomationHelper.java"/>
+        </build-panel>
+        <build-panel name="TreePacksPanel">
+            <include name="com/izforge/izpack/panels/TreePacksPanel.java"/>
+            <include name="com/izforge/izpack/panels/TreePacksPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/ImgPacksPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/ImgPacksPanelBase.java"/>
+            <include name="com/izforge/izpack/panels/PacksModel.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelAutomationHelper.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelBase.java"/>
+            <include name="com/izforge/izpack/panels/PacksPanelInterface.java"/>
+        </build-panel>
+        <build-panel name="InstallationTypePanel">
+            <include name="com/izforge/izpack/panels/InstallationTypePanel.java"/>
+        </build-panel>
+        <build-panel name="HTMLHelloPanel">
+            <include name="com/izforge/izpack/panels/HTMLHelloPanel.java"/>
+            <include name="com/izforge/izpack/panels/HTMLInfoPanel.java"/>
+        </build-panel>
+               <build-panel name="NonBlankTargetPanel">
+           <include name="com/izforge/izpack/panels/PathInputPanel.java"/>
+           <include name="com/izforge/izpack/panels/PathSelectionPanel.java"/>
+           <include name="com/izforge/izpack/panels/TargetPanel.java"/>
+           <include name="com/izforge/izpack/panels/TargetPanelAutomationHelper.java"/>
+           <include name="com/izforge/izpack/panels/NonBlankTargetPanel.java"/>
+               </build-panel>
+    </target>
+
+    <!--
+         ======================================================================
+           Create Listener Modules
+         ======================================================================
+    -->
+
+    <!-- Compiles the base custom action classes which should placed into
+         izevent.jar  -->
+    <target name="compile.listener-base">
+        <javac srcdir="${src.dir}"
+               destdir="${build.dir}"
+               optimize="on"
+               source="${compat.source}"
+               target="${compat.target}"
+               deprecation="on"
+               debug="${debug}"
+               debuglevel="${debuglevel}"
+               classpath="${installer.jar};${compiler.jar}">
+            <include name="com/izforge/izpack/event/ActionBase.java"/>
+            <include name="com/izforge/izpack/event/Simple*nstallerListener.java"/>
+            <include name="com/izforge/izpack/event/SimpleCompilerListener.java"/>
+            <include name="com/izforge/izpack/event/InstallerListener.java"/>
+            <include name="com/izforge/izpack/event/ProgressBarInstallerListener.java"/>
+            <include name="com/izforge/izpack/event/CompilerListener.java"/>
+            <include name="com/izforge/izpack/event/UninstallerListener.java"/>
+            <include name="com/izforge/izpack/util/IoHelper.java"/>
+        </javac>
+    </target>
+    <!-- Package izevent.jar  -->
+    <target name="build.listener-base" depends="compile.listener-base">
+        <jar jarfile="${izevent.jar}">
+            <fileset dir="${build.dir}">
+                <include name="com/izforge/izpack/event/*.class"/>
+                <include name="com/izforge/izpack/util/IoHelper.class"/>
+            </fileset>
+        </jar>
+    </target>
+
+
+    <!-- Macro to compile a listener's classes and create its jar file -->
+    <macrodef name="build-listener">
+        <attribute name="name" description="The listener jar will get this name"/>
+        <attribute name="classpath-ext" description="An extension of the classpath required to build the listener"
+                   default=""/>
+        <attribute name="srcdir"
+                   default="${src.dir}"
+                   description="Source directory. Defaults to izpack src dir"/>
+        <attribute name="izeventExcludes"
+                   description="excludes patter for files in the ${izevent.jar} file"/>
+        <element name="listener-fileset"
+                 implicit="yes"
+                 description="include and exclude elements indicating listener sources"/>
+        <sequential>
+            <echo message="build-listener: @{name}"/>
+            <mkdir dir="${bin.dir}/customActions/@{name}"/>
+            <!-- sourcepath is cleared so there's no mistaking what goes into the Listener -->
+            <javac srcdir="@{srcdir}"
+                   destdir="${bin.dir}/customActions/@{name}"
+                   classpath="${installer.jar};${compiler.jar};${izevent.jar};@{classpath-ext}"
+                   sourcepath=""
+                   optimize="on"
+                   deprecation="on"
+                   debug="${debug}"
+                   source="${compat.source}"
+                   target="${compat.target}"
+                   debuglevel="${debuglevel}">
+                <listener-fileset/>
+            </javac>
+            <jar jarfile="${bin.dir}/customActions/@{name}.jar"
+                 basedir="${bin.dir}/customActions/@{name}">
+                <!-- also include files from the previously built ${izevent.jar} -->
+                <zipfileset src="${izevent.jar}" excludes="@{izeventExcludes}"/>
+            </jar>
+        </sequential>
+    </macrodef>
+
+    <!-- Convenience macro to call build-listener for compiler listeners -->
+    <macrodef name="build-compiler-listener">
+        <attribute name="name"/>
+        <attribute name="srcdir" default="${src.dir}"/>
+        <element name="compiler-fileset"
+                 implicit="yes"
+                 description="include and exclude elements indicating listener sources"/>
+        <sequential>
+            <build-listener name="@{name}"
+                            srcdir="@{srcdir}"
+                            izeventExcludes="**/*Installer*,**/*Uninstaller*">
+                <compiler-fileset/>
+            </build-listener>
+        </sequential>
+    </macrodef>
+
+    <!-- Convenience macro to call build-listener for installer listeners -->
+    <macrodef name="build-installer-listener">
+        <attribute name="name"/>
+        <attribute name="classpath-ext" description="An extension of the classpath required to build the listener"
+                   default=""/>
+        <attribute name="srcdir" default="${src.dir}"/>
+        <element name="installer-fileset"
+                 implicit="yes"
+                 description="include and exclude elements indicating listener sources"/>
+        <sequential>
+            <build-listener name="@{name}" srcdir="@{srcdir}" izeventExcludes="**/*Uninstaller*,**/*Compiler*"
+                            classpath-ext="@{classpath-ext}">
+                <installer-fileset/>
+            </build-listener>
+        </sequential>
+    </macrodef>
+
+    <!-- Convenience macro to call build-listener for uninstaller listeners -->
+    <macrodef name="build-uninstaller-listener">
+        <attribute name="name"/>
+        <attribute name="srcdir" default="${src.dir}"/>
+        <attribute name="classpath-ext" description="An extension of the classpath required to build the listener"
+                   default=""/>
+        <element name="uninstaller-fileset"
+                 implicit="yes"
+                 description="include and exclude elements indicating listener sources"/>
+        <sequential>
+            <build-listener name="@{name}" srcdir="@{srcdir}" izeventExcludes="**/*Installer*,**/*Compiler*"
+                            classpath-ext="@{classpath-ext}">
+                <uninstaller-fileset/>
+            </build-listener>
+        </sequential>
+    </macrodef>
+
+    <!-- Compile all custom actions (listener) and put them at the right location -->
+    <!--
+         If you add a another, and the build fails because it can't find a class,
+         be sure to explicitly include the .java file in the nested fileset.
+         This also acts as a check to help limit dependancies.
+    -->
+    <target name="build.listeners" depends="build.compiler,build.installer,build.listener-base">
+        <!-- This dependency is mandatory -->
+        <build-installer-listener name="LateShortcutInstallListener"
+                                  classpath-ext="${bin.dir}/panels/ShortcutPanel.jar">
+            <include name="com/izforge/izpack/event/LateShortcutInstallListener.java"/>
+        </build-installer-listener>
+
+        <build-installer-listener name="AntActionInstallerListener">
+            <include name="com/izforge/izpack/event/AntActionInstallerListener.java"/>
+            <include name="com/izforge/izpack/event/AntAction.java"/>
+        </build-installer-listener>
+
+        <build-uninstaller-listener name="AntActionUninstallerListener">
+            <include name="com/izforge/izpack/event/AntActionUninstallerListener.java"/>
+            <include name="com/izforge/izpack/event/AntAction.java"/>
+        </build-uninstaller-listener>
+
+        <build-installer-listener name="SummaryLoggerInstallerListener">
+            <include name="com/izforge/izpack/event/SummaryLoggerInstallerListener.java"/>
+        </build-installer-listener>
+
+        <build-installer-listener name="RegistryInstallerListener">
+            <include name="com/izforge/izpack/event/RegistryInstallerListener.java"/>
+            <include name="com/izforge/izpack/event/NativeInstallerListener.java"/>
+            <include name="com/izforge/izpack/util/os/*RegistryHandler.java"/>
+            <include name="com/izforge/izpack/util/OSClassHelper.java"/>
+            <include name="com/izforge/izpack/util/os/WrappedNativeLibException.java"/>
+            <include name="com/coi/tools/os/win/*.java"/>
+            <include name="com/coi/tools/os/win/resources/NativeLibErr*.java"/>
+            <include name="com/coi/tools/os/izpack/Registry.java"/>
+            <include name="com/coi/tools/os/izpack/COIOSHelper.java"/>
+        </build-installer-listener>
+
+        <build-uninstaller-listener name="RegistryUninstallerListener">
+            <include name="com/izforge/izpack/event/RegistryUninstallerListener.java"/>
+            <include name="com/izforge/izpack/event/NativeUninstallerListener.java"/>
+            <include name="com/izforge/izpack/util/os/*RegistryHandler.java"/>
+            <include name="com/izforge/izpack/util/OSClassHelper.java"/>
+            <include name="com/izforge/izpack/util/os/WrappedNativeLibException.java"/>
+            <include name="com/coi/tools/os/win/*.java"/>
+            <include name="com/coi/tools/os/win/resources/NativeLibErr*.java"/>
+            <include name="com/coi/tools/os/izpack/Registry.java"/>
+            <include name="com/coi/tools/os/izpack/COIOSHelper.java"/>
+        </build-uninstaller-listener>
+
+        <build-installer-listener name="BSFInstallerListener" classpath-ext="$${basedir}/lib/bsf.jar">
+            <include name="com/izforge/izpack/event/BSFInstallerListener.java" />
+            <include name="com/izforge/izpack/event/BSFAction.java" />
+        </build-installer-listener>
+        
+        <build-installer-listener name="ProgressBarInstallerListener">
+            <include name="com/izforge/izpack/event/ProgressBarInstallerListener.java"/>
+        </build-installer-listener>
+
+        <build-uninstaller-listener name="BSFUninstallerListener" classpath-ext="$${basedir}/lib/bsf.jar">
+            <include name="com/izforge/izpack/event/BSFUninstallerListener.java" />
+            <include name="com/izforge/izpack/event/BSFAction.java" />
+        </build-uninstaller-listener>
+
+        <!-- CUSTOM ACTION test START
+        <build-compiler-listener name="ChmodCompilerListener">
+            <include name="com/myCompany/tools/install/listener/ChmodCompilerListener.java"/>
+        </build-compiler-listener>
+
+        <build-installer-listener name="ChmodInstallerListener">
+            <include name="com/myCompany/tools/install/listener/ChmodInstallerListener.java"/>
+        </build-installer-listener>
+        COSTOM ACTION test END -->
+    </target>
+
+    <!-- ====================================================================== -->
+
+    <!-- Performs some cleanups -->
+    <target name="clean" description="cleans up the dist">
+        <echo message="Cleaning-up"/>
+        <delete includeEmptyDirs="true" quiet="true">
+            <fileset dir="${build.dir}"/>
+            <fileset dir="${dist.dir}"/>
+            <fileset dir="${basedir}/bin/panels/">
+                <include name="**/*"/>
+            </fileset>
+            <fileset dir="${basedir}/bin/customActions/">
+                <include name="**/*"/>
+            </fileset>
+            <fileset dir="${basedir}/lib/">
+                <include name="compiler.jar"/>
+                <include name="izevent.jar"/>
+                <include name="standalone-compiler.jar"/>
+                <include name="frontend.jar"/>
+                <include name="installer.jar"/>
+                <include name="uninstaller.jar"/>
+                <include name="uninstaller-ext.jar"/>
+            </fileset>
+        </delete>
+        <delete file="bin/native/3rdparty/COIOSHelper.dll"/>
+        <delete dir="${basedir}/bin/native/izpack"/>
+        <delete dir="${basedir}/src/doc-reST/html"/>
+        <delete dir="${basedir}/src/doc-reST/pdf"/>
+        <delete includeEmptyDirs="true" dir="${basedir}/doc/izpack"/>
+        <delete dir="${basedir}/_src${dist.subdir}"/>
+    </target>
+
+    <!-- Builds all compilation targets -->
+    <target name="all"
+            depends="splashscreen, copy.dist.natives,build.compiler, build.compiler, build.installer, build.uninstaller, build.uninstaller-ext, build.panels, build.listeners, build.standalone-compiler"
+            description="base: compiles a developer version"/>
+
+    <!-- Builds the Javadoc -->
+    <target name="build.javadoc" depends="prepare" description="Builds the javadoc">
+        <mkdir dir="${build.dir}/javadoc"/>
+        <javadoc destdir="${build.dir}/javadoc" access="private" classpathref="classpath">
+            <packageset dir="${src.dir}">
+                <exclude name="**/CVS"/>
+            </packageset>
+        </javadoc>
+        <copy todir="${doc.dir}/izpack/javadoc" preservelastmodified="true">
+            <fileset dir="${build.dir}/javadoc">
+                <include name="**/*"/>
+            </fileset>
+        </copy>
+    </target>
+
+    <target name="build.docu" description="Builds the customer documentation">
+        <exec executable="${basedir}/src/doc-reST/build.py" dir="${basedir}/src/doc-reST">
+            <arg value="build.py"/>
+        </exec>
+
+        <mkdir dir="${doc.dir}/izpack/html"/>
+        <copy todir="${doc.dir}/izpack/html" preservelastmodified="true">
+            <fileset dir="${basedir}/src/doc-reST/html">
+                <include name="**/*"/>
+            </fileset>
+        </copy>
+        <mkdir dir="${doc.dir}/izpack/pdf"/>
+        <copy todir="${doc.dir}/izpack/pdf" preservelastmodified="true">
+            <fileset dir="${basedir}/src/doc-reST/pdf">
+                <include name="manual.pdf"/>
+            </fileset>
+        </copy>
+
+        <delete file="${basedir}/src/texput.log"/>
+        <delete dir="${basedir}/src/doc-reST/html"/>
+        <delete dir="${basedir}/src/doc-reST/pdf"/>
+    </target>
+
+    <target name="create.docu"
+            depends="build.javadoc, build.docu"
+            description="Creates the javadoc-api and customer documentation">
+
+    </target>
+
+
+    <!-- - - - - - - - - - - - - - - - - -
+          target: taskdef
+         - - - - - - - - - - - - - - - - - -->
+    <target name="taskdef.dist">
+        <!-- Allows us to use the IzPack Ant task -->
+        <taskdef name="izpack"
+                 classpath="${basedir}/lib/compiler.jar"
+                 classname="com.izforge.izpack.ant.IzPackTask"/>
+    </target>
+
+
+    <!-- - - - - - - - - - - - - - - - - -
+          target: copy.natives
+         - - - - - - - - - - - - - - - - - -->
+    <target name="copy.dist.natives">
+        <echo message="Copies the recent changed native files to the ${basedir}/bin directory"/>
+
+        <mkdir dir="${basedir}/bin/native/izpack"/>
+        <copy todir="${basedir}/bin/native/izpack"
+              file="${basedir}/src/native/ShellLink/src/lib/ShellLink.dll"
+              verbose="true"
+              overwrite="yes"
+              preservelastmodified="true"/>
+        <copy todir="${basedir}/bin/native/izpack"
+              file="${basedir}/src/native/ShellLink/src/lib/ShellLink_x64.dll"
+              verbose="true"
+              overwrite="yes"
+              preservelastmodified="true"/>
+        <copy todir="${basedir}/bin/native/3rdparty"
+              file="${basedir}/src/native/COIOSHelper/src/lib/COIOSHelper.dll"
+              verbose="true"
+              overwrite="yes"
+              preservelastmodified="true"/>
+       <copy todir="${basedir}/bin/native/3rdparty"
+                   file="${basedir}/src/native/COIOSHelper/src/lib/COIOSHelper_x64.dll"
+                 verbose="true"
+               overwrite="yes"
+               preservelastmodified="true"/>
+    </target>
+
+
+    <!-- - - - - - - - - - - - - - - - - -
+          target: copy.distfiles
+         - - - - - - - - - - - - - - - - - -->
+    <target name="copy.dist.files">
+        <echo message="Copies the general files to the dist directory"/>
+        <copy todir="${dist.dir}" includeEmptyDirs="yes" preservelastmodified="true">
+            <fileset dir="${basedir}">
+                <include name="bin/**"/>
+                <include name="utils/**"/>
+                <include name="lib/*.jar"/>
+                <include name="doc/**"/>
+                <include name="legal/**"/>
+                <include name="src/**"/>
+                <include name="sample/**"/>
+                <include name="*.txt"/>
+                <include name="*.html"/>
+            </fileset>
+        </copy>
+        <echo message="Copies the langpacks to the dist directory"/>
+        <copy todir="${dist.dir}/bin" includeEmptyDirs="yes" preservelastmodified="true">
+            <fileset dir="${basedir}">
+                <include name="langpacks/**"/>
+            </fileset>
+        </copy>
+        <echo message="Copies the license images and specs to the dist directory"/>
+        <copy todir="${dist.dir}" includeEmptyDirs="yes" preservelastmodified="true">
+            <fileset dir="${dist-files.dir}">
+                <include name="useNativeLAF"/>
+                <include name="*.jpg"/>
+                <include name="*.png"/>
+                <include name="*.html"/>
+                <include name="Licence.txt"/>
+                <include name="IzPack-install*.xml"/>
+                <include name="shortcutSpec.xml"/>
+                <include name="Unix_shortcutSpec.xml"/>
+                <include name="RegistrySpec.xml"/>
+                <include name="conditions.xml"/>
+            </fileset>
+        </copy>
+        <echo message="Copies the bin files to the dist directory"/>
+        <copy todir="${dist.dir}/bin" includeEmptyDirs="yes" overwrite="yes" preservelastmodified="true">
+            <fileset dir="${dist-files.dir}">
+                <include name="compile*"/>
+                <include name="lcp.bat"/>
+                <include name="start.sh"/>
+            </fileset>
+        </copy>
+    </target>
+
+
+    <!-- - - - - - - - - - - - - - - - - -
+          target: replace.dist.buildnumber
+         - - - - - - - - - - - - - - - - - -->
+    <target name="replace.dist.buildnumber">
+        <replace file="${dist.dir}/shortcutSpec.xml"
+                 token="@build.number@"
+                 value="${build.number}"
+                 summary="yes"/>
+        <replace file="${dist.dir}/shortcutSpec.xml" token="@ver@" value="${ver}" summary="yes"/>
+
+        <replace file="${dist.dir}/Unix_shortcutSpec.xml"
+                 token="@build.number@"
+                 value="${build.number}"
+                 summary="yes"/>
+        <replace file="${dist.dir}/Unix_shortcutSpec.xml"
+                 token="@ver@"
+                 value="${ver}"
+                 summary="yes"/>
+    </target>
+
+    <!-- Creates an installer for IzPack -->
+    <target name="exec.izpack.compiler">
+
+        <!-- We call IzPack -->
+        <echo message="Makes the installer using IzPack" level="verbose"/>
+        <izpack input="${dist.dir}/${installer.xmlfile}"
+                output="${dist.dir}/${installer.name}${ver}.${rel}.jar"
+                installerType="standard"
+                basedir="${dist.dir}"
+                izPackDir="${dist.dir}/"
+                compression="deflate"
+                compressionlevel="9"/>
+        <echo>
+            sucessfully created:
+            ${dist.dir}/${installer.name}${ver}.${rel}.jar
+        </echo>
+    </target>
+
+
+    <!-- - - - - - - - - - - - - - - - - -
+          target: prepare.install.dist
+         - - - - - - - - - - - - - - - - - -->
+    <target name="prepare.install.dist"
+            depends="taskdef.dist, copy.dist.natives, copy.dist.files, replace.dist.buildnumber, fix.crlf">
+
+    </target>
+
+    <!-- =================================
+          Creates a normal installer for IzPack
+         ================================= -->
+    <target name="generate.installer" depends="prepare.install.dist">
+        <antcall target="exec.izpack.compiler">
+            <param name="installer.xmlfile" value="IzPack-install.xml"/>
+            <param name="installer.name" value="${product}-install-"/>
+        </antcall>
+    </target>
+
+    <!--
+        Fixes CR/LF by applying the Unix convention (\n for endlines).
+        It also fixes the encoding problems by moving it to UTF-8.
+    -->
+    <target name="fix.crlf">
+        <property name="dist.src.dir" location="${dist.dir}/src"/>
+        <property name="dist.bin.dir" location="${dist.dir}/bin"/>
+        <echo>
+            Fixing linefeeds for several files in:
+            "${dist.src.dir}"
+            and
+            "${dist.bin.dir}"
+        </echo>
+        <fixcrlf srcDir="${dist.src.dir}" eol="lf" eof="remove" encoding="UTF-8">
+            <include name="**/*.java"/>
+            <include name="**/*.xml"/>
+            <include name="**/*.properties"/>
+        </fixcrlf>
+        <fixcrlf srcdir="${dist.dir}" eol="unix" eof="remove">
+            <include name="**/*.sh"/>
+            <include name="dist-files/compile"/>
+        </fixcrlf>
+        <fixcrlf srcdir="${dist.bin.dir}" eol="unix" eof="remove">
+            <include name="**/*.sh"/>
+            <include name="compile"/>
+        </fixcrlf>
+        <fixcrlf srcdir="${dist.dir}" eol="dos" eof="add">
+            <include name="**/*.bat"/>
+        </fixcrlf>
+        <fixcrlf srcdir="${dist.bin.dir}" eol="dos" eof="add">
+            <include name="**/*.bat"/>
+        </fixcrlf>
+    </target>
+
+    <!-- Runs a testing installer. -->
+    <target name="run.installer">
+        <java jar="${basedir}/_dist/IzPack-install-${build.number}.jar" fork="true"/>
+    </target>
+
+    <!-- Makes everything, from compilation to generating an installer. -->
+    <target name="quickdist"
+            depends="all, generate.installer"
+            description="makes a installer without docu"/>
+
+    <!-- Makes everything, from compilation, customer and javadoc to generating an installer. -->
+    <target name="dist"
+            depends="src.tar.gz, all, create.docu, generate.installer"
+            description="makes a complete installer"/>
+
+    <!-- Makes everything, from Cleaning to generating both installers: normal and reg support. -->
+    <target name="cleandistreg"
+            depends="clean, splashscreen, dist, generate.installer"
+            description="creates a full dist with Win32 uninstall registry support"/>
+
+    <!-- =================================
+          target: clean.src.tar.gz
+         ================================= -->
+    <target name="clean.src.tar.gz" depends="clean, src.tar.gz" description="--> creates a src.tar.gz after clean up">
+    </target>
+
+
+    <!-- =================================
+          target: src.tar.gz
+         ================================= -->
+    <target name="src.tar.gz" description="--> creates a src.tar.gz ">
+        <mkdir dir="${basedir}/_src${dist.subdir}"/>
+        <property name="src.tar.gz" value="${basedir}/_src${dist.subdir}/${product}-src-${ver}.${rel}.tar.gz"/>
+        <tar compression="gzip" destfile="${src.tar.gz}" basedir="${basedir}"
+             excludes="_src${dist.subdir}/**, _dist/**, _build/**, bin/panels/**, bin/customActions/**, doc/izpack/**, eclipse-bin/**, lib/standalone-compiler.jar, lib/izevent.jar, lib/uninstaller*, lib/installer.jar, lib/compiler.jar"/>
+    </target>
+
+
+    <!-- convenient :) makes a quick dist (w/o docu), an installer and run them. -->
+    <target name="quickdist+run"
+            depends="quickdist, run.installer"
+            description="makes a quickdist installer and runs them"/>
+
+    <!-- convenient :) makes a complete dist an installer and run them. -->
+    <target name="dist+run"
+            depends="dist, run.installer"
+            description="makes a complete installer and runs them"/>
+
+    <!-- ** splashscreen **
+         shows some ANT specific- and JAVA-
+         but Platform and Project-independed Properties.
+       ================================================================ -->
+    <target name="splashscreen"
+            depends="time"
+            description="shows the used environment and project settings">
+
+        <property name="console_line" value="**************************************************"/>
+        <echo message="${console_line}"/>
+        <echo message="* ${ant.version}"/>
+        <echo message="*   Java JRE version ${ant.java.version} ${java.vm.vendor}"/>
+        <exec executable="${java.home}/bin/java">
+            <arg line="-version"/>
+        </exec>
+        <echo message="${console_line}"/>
+        <echo message="*  processing file ....... '${ant.file}'"/>
+        <echo message="*  in base-directory ..... '${basedir}'"/>
+        <echo message="*  building project ...... '${ant.project.name}'"/>
+        <echo message="*  working in directory .. '${cwd}'"/>
+        <echo message="${console_line}"/>
+    </target>
+
+
+    <!-- =================================
+          target: ShellLink.Javah
+         ================================= -->
+    <target name="ShellLink.Javah"
+            depends="compile.installer"
+            description="--> rebuilds the shelllink jni *.h header file">
+        <javah class="com.izforge.izpack.util.os.ShellLink"
+               destdir="${basedir}/src/native/ShellLink">
+            <classpath path="${build.dir}"/>
+        </javah>
+    </target>
+
+
+    <!-- =================================
+         target: time - takes a timestamp
+        ================================= -->
+    <target name="time">
+        <tstamp/>
+    </target>
+
+
+    <!-- =================================
+          target: dump.properties - dumps the curent properties into the $os_$timestamp.properties file
+         ================================= -->
+    <target name="dump.properties" depends="time" description="dump.environment (for debug)">
+        <echoproperties
+                destfile="${basedir}/ant_properties_at_${os.name}-${os.arch}-${os.version}_at_${DSTAMP}-${TSTAMP}.txt"/>
+    </target>
+
+
+</project>
diff --git a/1.8/installer/default_shortcut_specification.xml b/1.8/installer/default_shortcut_specification.xml
new file mode 100644 (file)
index 0000000..091dca9
--- /dev/null
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes"?>\r
+<shortcuts>\r
+\r
+  <programGroup defaultName="Simantics/System Dynamics" location="applications"/>\r
+\r
+  <shortcut\r
+    name="Start Simantics System Dynamics"\r
+    target="$INSTALL_PATH\simantics-sysdyn\Simantics-Sysdyn.exe"\r
+    commandLine=""\r
+    workingDirectory="$INSTALL_PATH\simantics-sysdyn"\r
+    description="Starts Simantics System Dynamics"\r
+    initialState="normal"\r
+    iconFile="$INSTALL_PATH\simantics-sysdyn\puzzle_green.ico"\r
+    iconIndex="0"\r
+    programGroup="yes"\r
+    desktop="yes"\r
+    applications="no"\r
+    startMenu="yes"\r
+    startup="no">\r
+    <createForPack name="Simantics System Dynamics"/>\r
+  </shortcut>\r
+\r
+  <shortcut\r
+     name="Simantics System Dynamics Documentation"\r
+     programGroup="yes"\r
+     desktop="no"\r
+     applications="no"\r
+     startMenu="yes"\r
+     startup="no"\r
+     target="explorer"\r
+     workingDirectory=""\r
+     commandLine=""\r
+     initialState="noShow"\r
+     iconFile="help"\r
+     iconIndex="0"\r
+     url="https://www.simantics.org/end_user_wiki/index.php/Simantics_System_Dynamics"\r
+     type="Link"\r
+     encoding="UTF-8"\r
+     description="User documentation">\r
+    <createForPack name="Simantics System Dynamics"/>\r
+  </shortcut>\r
+\r
+  <shortcut\r
+     name="Uninstall Simantics System Dynamics"\r
+     programGroup="yes"\r
+     desktop="yes"\r
+     applications="no"\r
+     startMenu="no"\r
+     startup="no"\r
+     target="java"\r
+     commandLine="-jar\r
+     &quot;$INSTALL_PATH/Uninstaller/uninstaller.jar&quot;"\r
+     initialState="noShow"\r
+     iconFile="trashcan_full"\r
+     iconIndex="0"\r
+     workingDirectory=""\r
+     type="Application"\r
+     encoding="UTF-8"\r
+     description="Simantics System Dynamics Uninstaller">\r
+    <createForPack name="Simantics System Dynamics"/>\r
+  </shortcut>\r
+\r
+</shortcuts>
\ No newline at end of file
diff --git a/1.8/installer/download b/1.8/installer/download
new file mode 100755 (executable)
index 0000000..4288e4e
--- /dev/null
@@ -0,0 +1,10 @@
+#!/bin/bash
+
+pushd .
+cd `dirname $0`
+BUILD=$1
+
+rm -f files/dist.zip
+cp -v /var/lib/jenkins/jobs/${BUILD} files/dist.zip || exit -1
+
+popd > /dev/null
diff --git a/1.8/installer/download.bat b/1.8/installer/download.bat
new file mode 100644 (file)
index 0000000..7375250
--- /dev/null
@@ -0,0 +1,17 @@
+@echo off\r
+\r
+setlocal\r
+pushd .\r
+cd %~dp0\r
+set BUILD=%1\r
+set JOB_NAME=%2\r
+\r
+del /s /q dist\r
+wget -O dist.zip "http://www.simantics.org/hudson/job/%JOB_NAME%/%BUILD%/artifact/build/dist/*zip*/dist.zip"\r
+unzip -o dist.zip\r
+del files\dist.zip\r
+copy dist\*sdk*.zip files\dist.zip\r
+del /s /q dist.zip dist\r
+\r
+popd\r
+endlocal\r
diff --git a/1.8/installer/files/Microsoft.VC90.CRT.setup.exe b/1.8/installer/files/Microsoft.VC90.CRT.setup.exe
new file mode 100644 (file)
index 0000000..823345d
Binary files /dev/null and b/1.8/installer/files/Microsoft.VC90.CRT.setup.exe differ
diff --git a/1.8/installer/files/install_msvcrt.bat b/1.8/installer/files/install_msvcrt.bat
new file mode 100644 (file)
index 0000000..7d56bad
--- /dev/null
@@ -0,0 +1,2 @@
+@echo off\r
+"%~dp0Microsoft.VC90.CRT.setup.exe" /q
\ No newline at end of file
diff --git a/1.8/installer/files/jre-6u29-windows-i586-iftw.exe b/1.8/installer/files/jre-6u29-windows-i586-iftw.exe
new file mode 100644 (file)
index 0000000..39a0d7b
Binary files /dev/null and b/1.8/installer/files/jre-6u29-windows-i586-iftw.exe differ
diff --git a/1.8/installer/installer.xml b/1.8/installer/installer.xml
new file mode 100644 (file)
index 0000000..db16f51
--- /dev/null
@@ -0,0 +1,104 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes"?>
+<installation version="1.0">
+    <info>
+        <appname>Simantics System Dynamics</appname>
+        <appsubpath>Sysdyn</appsubpath>
+        <appversion>1.6</appversion>
+        <authors>
+            <author email="simantics-developers@simantics.org" name="VTT Technical Research Centre of Finland"/>
+        </authors>
+        <url>http://www.simantics.org</url>
+        <uninstaller name="Uninstaller.jar" write="yes"/>
+        <javaversion>1.6</javaversion>
+        <requiresjdk>no</requiresjdk>
+        <writeinstallationinformation>yes</writeinstallationinformation>
+    </info>
+    <installerrequirements>
+        <installerrequirement condition="izpack.windowsinstall" message="This installer only supports Windows operating systems."/>
+    </installerrequirements>
+       <guiprefs width="640" height="570" resizable="yes">
+               <laf name="substance">
+                       <param name="variant" value="business"/>
+                       <os family="windows"/>
+                       <os family="unix"/>
+                       <os family="mac"/>
+               </laf>
+        <modifier key="langDisplayType" value="default"/>
+        <modifier key="useHeadingPanel" value="yes"/>
+        <modifier key="headingImageOnLeft" value="yes"/>
+        <modifier key="useFlags" value="yes"/>
+        <modifier key="labelGap" value="2"/>
+        <!--<modifier key="layoutAnchor" value="NORTHWEST"/>-->
+        <modifier key="useButtonIcons" value="no"/>
+        <modifier key="useLabelIcons" value="no"/>
+        <modifier key="useHeadingForSummary" value="yes"/>
+        <modifier key="headingLineCount" value="1"/>
+        <modifier key="headingFontSize" value="1.5"/>
+        <modifier key="headingBackgroundColor" value="0x00ffffff"/>
+        <modifier key="headingPanelCounter" value="progressbar"/>
+        <modifier key="headingPanelCounterPos" value="inNavigationPanel"/>
+       </guiprefs>
+       <locale>
+               <langpack iso3="eng"/>
+       </locale>
+       <resources>
+               <res id="HTMLLicencePanel.licence" parse="yes" src="EPL.html"/>
+               <res id="Installer.image" src="side.png"/>
+               <res id="userInputSpec.xml" src="userInputSpec.xml" />
+        <res id="TargetPanel.dir.windows" src="TargetDir.txt.windows" />
+        <res id="TargetPanel.dir.unix" src="TargetDir.txt.unix" />
+        <res id="CustomLangpack.xml_eng" src="CustomLangpack_eng.xml" />
+        <res id="shortcutSpec.xml" src="default_shortcut_specification.xml" />
+       </resources>
+       <panels>
+               <panel classname="CheckedHelloPanel"/>
+               <panel classname="HTMLLicencePanel"/>
+               <panel classname="PacksPanel"/>
+               <panel classname="NonBlankTargetPanel"/>
+               <panel classname="SummaryPanel"/>
+        <panel classname="InstallPanel"/>
+        <!--<panel classname="ShortcutPanel"/>-->
+               <panel classname="FinishPanel"/>
+       </panels>
+       <variables>
+               <variable name="DesktopShortcutCheckboxEnabled" value="true"/>
+               <variable name="InstallerFrame.logfilePath" value="default"/>
+       </variables>
+       <packs>
+               <pack name="Java Runtime Environment 6" preselected="no" required="no">
+                       <os family="windows"/>
+                       <description>Simantics SDK requires an up-to-date version of the Java Runtime Environment version 6.
+If your JRE is old, you can install JRE 6 update 29 by selecting this.
+NOTE: Installing this will require network access for downloading Java components.
+Other Java installers are available at http://www.java.com/en/download/manual.jsp.</description>
+                       <file override="update"
+                               src="files/jre-6u29-windows-i586-iftw.exe" targetdir="$INSTALL_PATH"/>
+                       <executable failure="ask" keep="false" stage="postinstall" targetfile="$INSTALL_PATH/jre-6u29-windows-i586-iftw.exe">
+                               <os family="windows"/>
+                       </executable>
+        </pack>
+               <pack name="Microsoft Visual C++ Run-Time" preselected="yes" required="yes">
+                       <os family="windows"/>
+                       <description>Microsoft Visual C++ Run-Time 9.0 libraries.
+These are required by native Simantics components.
+Nothing is done if these are already installed on your system.</description>
+                       <file override="update"
+                               src="files/Microsoft.VC90.CRT.setup.exe" targetdir="$INSTALL_PATH/external"/>
+                       <file override="update"
+                               src="files/install_msvcrt.bat" targetdir="$INSTALL_PATH/external"/>
+                       <executable failure="ask" keep="true" stage="postinstall" targetfile="$INSTALL_PATH/external/install_msvcrt.bat">
+                               <os family="windows"/>
+                       </executable>
+               </pack>
+               <pack name="Simantics System Dynamics" preselected="yes" required="yes">
+                       <os family="windows"/>
+                       <description>The Simantics System Dynamics application.</description>
+                       <depends packname="Microsoft Visual C++ Run-Time"/>
+                       <file override="true" unpack="true"
+                               src="files/dist.zip" targetdir="$INSTALL_PATH"/>
+               </pack>
+       </packs>
+       <native type="izpack" name="ShellLink.dll">
+        <os family="windows"/>
+    </native>
+</installation>
diff --git a/1.8/installer/side.png b/1.8/installer/side.png
new file mode 100644 (file)
index 0000000..e543804
Binary files /dev/null and b/1.8/installer/side.png differ
diff --git a/1.8/installer/side.svg b/1.8/installer/side.svg
new file mode 100644 (file)
index 0000000..ffb16f8
--- /dev/null
@@ -0,0 +1,99 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   width="744.09448819"
+   height="1052.3622047"
+   id="svg2"
+   version="1.1"
+   inkscape:version="0.47 r22583"
+   sodipodi:docname="New document 1">
+  <defs
+     id="defs4">
+    <linearGradient
+       id="linearGradient5042">
+      <stop
+         style="stop-color:#000000;stop-opacity:1;"
+         offset="0"
+         id="stop5044" />
+      <stop
+         style="stop-color:#8caed8;stop-opacity:1"
+         offset="1"
+         id="stop5046" />
+    </linearGradient>
+    <inkscape:perspective
+       sodipodi:type="inkscape:persp3d"
+       inkscape:vp_x="0 : 526.18109 : 1"
+       inkscape:vp_y="0 : 1000 : 0"
+       inkscape:vp_z="744.09448 : 526.18109 : 1"
+       inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
+       id="perspective10" />
+    <radialGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient5042"
+       id="radialGradient5048"
+       cx="-538.94128"
+       cy="344.05646"
+       fx="-538.94128"
+       fy="344.05646"
+       r="347.30859"
+       gradientTransform="matrix(1.578967,0.43290519,-0.11724864,0.42764955,352.36941,430.23135)"
+       gradientUnits="userSpaceOnUse" />
+  </defs>
+  <sodipodi:namedview
+     id="base"
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1.0"
+     inkscape:pageopacity="0.0"
+     inkscape:pageshadow="2"
+     inkscape:zoom="0.35"
+     inkscape:cx="-70.714286"
+     inkscape:cy="520"
+     inkscape:document-units="px"
+     inkscape:current-layer="layer1"
+     showgrid="false"
+     inkscape:window-width="1051"
+     inkscape:window-height="790"
+     inkscape:window-x="89"
+     inkscape:window-y="115"
+     inkscape:window-maximized="0" />
+  <metadata
+     id="metadata7">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+        <dc:title></dc:title>
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <g
+     inkscape:label="Layer 1"
+     inkscape:groupmode="layer"
+     id="layer1">
+    <text
+       xml:space="preserve"
+       style="font-size:144px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:100%;writing-mode:lr-tb;text-anchor:start;fill:url(#radialGradient5048);fill-opacity:1;stroke:none;font-family:Segoe Print;-inkscape-font-specification:Segoe Print"
+       x="-892.578"
+       y="399.04083"
+       id="text2816"
+       sodipodi:linespacing="100%"
+       transform="matrix(0,-1,1,0,0,0)"><tspan
+         sodipodi:role="line"
+         id="tspan2818"
+         x="-892.578"
+         y="399.04083"
+         style="fill-opacity:1;fill:url(#radialGradient5048)">Simantics</tspan></text>
+  </g>
+</svg>
diff --git a/1.8/installer/unzip.exe b/1.8/installer/unzip.exe
new file mode 100644 (file)
index 0000000..1e94719
Binary files /dev/null and b/1.8/installer/unzip.exe differ
diff --git a/1.8/installer/userInputSpec.xml b/1.8/installer/userInputSpec.xml
new file mode 100644 (file)
index 0000000..200fb9d
--- /dev/null
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes"?>\r
+<userInput>\r
+       <!-- Install -->\r
+    <panel order="0" layout="center">\r
+        <createForPack name="Simantics System Dynamics" />\r
+        <field type="title" txt="Select Installation Target" bold="true" size="1" />\r
+        <field type="staticText" align="left" txt="Select the installation path:"/>\r
+        <field type="dir" align="left" variable="TargetPanel.dir">\r
+                   <spec txt="" size="35" set="$INSTALL_PATH$FILE_SEPARATOR$APP_VER" mustExist="false" />\r
+                       <validator\r
+                               class="com.izforge.izpack.util.RegularExpressionValidator"\r
+                               txt="Sorry, installation path cannot contain spaces. Limited by OpenModelica and MinGW compiler.">\r
+                               <param\r
+                                       name="pattern"\r
+                                       value="^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$"\r
+                               />\r
+                       </validator>                    \r
+        </field>\r
+    </panel>\r
+</userInput>
\ No newline at end of file
diff --git a/1.8/installer/wget.exe b/1.8/installer/wget.exe
new file mode 100644 (file)
index 0000000..1b15a04
Binary files /dev/null and b/1.8/installer/wget.exe differ
diff --git a/1.8/org.simantics.fmu.me.win32/.classpath b/1.8/org.simantics.fmu.me.win32/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.fmu.me.win32/.project b/1.8/org.simantics.fmu.me.win32/.project
new file mode 100644 (file)
index 0000000..e22d663
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.fmu.me.win32</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.fmu.me.win32/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.fmu.me.win32/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..f287d53
--- /dev/null
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.fmu.me.win32/META-INF/MANIFEST.MF b/1.8/org.simantics.fmu.me.win32/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..a08acbb
--- /dev/null
@@ -0,0 +1,9 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Win32 binaries for FMI model exchange
+Bundle-SymbolicName: org.simantics.fmu.me.win32
+Bundle-Version: 1.1.0.qualifier
+Bundle-Vendor: Semantum Oy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: org.eclipse.core.runtime;bundle-version="3.7.0",
+ org.simantics.utils;bundle-version="1.1.0"
diff --git a/1.8/org.simantics.fmu.me.win32/build.properties b/1.8/org.simantics.fmu.me.win32/build.properties
new file mode 100644 (file)
index 0000000..150031b
--- /dev/null
@@ -0,0 +1,5 @@
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               libraries/\r
diff --git a/1.8/org.simantics.fmu.me.win32/libraries/FMUSimulator.dll b/1.8/org.simantics.fmu.me.win32/libraries/FMUSimulator.dll
new file mode 100644 (file)
index 0000000..6db0c3f
Binary files /dev/null and b/1.8/org.simantics.fmu.me.win32/libraries/FMUSimulator.dll differ
diff --git a/1.8/org.simantics.fmu.me.win32/libraries/miniunz.dll b/1.8/org.simantics.fmu.me.win32/libraries/miniunz.dll
new file mode 100644 (file)
index 0000000..312a60b
Binary files /dev/null and b/1.8/org.simantics.fmu.me.win32/libraries/miniunz.dll differ
diff --git a/1.8/org.simantics.fmu.me.win32/libraries/zlibwapi.dll b/1.8/org.simantics.fmu.me.win32/libraries/zlibwapi.dll
new file mode 100644 (file)
index 0000000..fa49411
Binary files /dev/null and b/1.8/org.simantics.fmu.me.win32/libraries/zlibwapi.dll differ
diff --git a/1.8/org.simantics.fmu/.classpath b/1.8/org.simantics.fmu/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.fmu/.project b/1.8/org.simantics.fmu/.project
new file mode 100644 (file)
index 0000000..9b34bda
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.fmu</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.fmu/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.fmu/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..f287d53
--- /dev/null
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/7z.dll b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/7z.dll
new file mode 100644 (file)
index 0000000..7e62921
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/7z.dll differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/7z.exe b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/7z.exe
new file mode 100644 (file)
index 0000000..f1f56e3
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/7z.exe differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/License.txt b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/License.txt
new file mode 100644 (file)
index 0000000..44802a8
--- /dev/null
@@ -0,0 +1,57 @@
+  7-Zip\r
+  ~~~~~\r
+  License for use and distribution\r
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r
+\r
+  7-Zip Copyright (C) 1999-2007 Igor Pavlov.\r
+\r
+  Licenses for files are:\r
+\r
+    1) 7z.dll: GNU LGPL + unRAR restriction\r
+    2) All other files:  GNU LGPL\r
+\r
+  The GNU LGPL + unRAR restriction means that you must follow both \r
+  GNU LGPL rules and unRAR restriction rules.\r
+\r
+\r
+  Note: \r
+    You can use 7-Zip on any computer, including a computer in a commercial \r
+    organization. You don't need to register or pay for 7-Zip.\r
+\r
+\r
+  GNU LGPL information\r
+  --------------------\r
+\r
+    This library is free software; you can redistribute it and/or\r
+    modify it under the terms of the GNU Lesser General Public\r
+    License as published by the Free Software Foundation; either\r
+    version 2.1 of the License, or (at your option) any later version.\r
+\r
+    This library is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
+    Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public\r
+    License along with this library; if not, write to the Free Software\r
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+\r
+\r
+  unRAR restriction\r
+  -----------------\r
+\r
+    The decompression engine for RAR archives was developed using source \r
+    code of unRAR program.\r
+    All copyrights to original unRAR code are owned by Alexander Roshal.\r
+\r
+    The license for original unRAR code has the following restriction:\r
+\r
+      The unRAR sources cannot be used to re-create the RAR compression algorithm, \r
+      which is proprietary. Distribution of modified unRAR sources in separate form \r
+      or as a part of other software is permitted, provided that it is clearly\r
+      stated in the documentation and source comments that the code may\r
+      not be used to develop a RAR (WinRAR) compatible archiver.\r
+\r
+\r
+  --\r
+  Igor Pavlov\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/fmusim_cs.exe b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/fmusim_cs.exe
new file mode 100644 (file)
index 0000000..7020fea
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/fmusim_cs.exe differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/fmusim_me.exe b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/fmusim_me.exe
new file mode 100644 (file)
index 0000000..41999ee
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/bin/fmusim_me.exe differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/FmuSdk_reference.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/FmuSdk_reference.html
new file mode 100644 (file)
index 0000000..5f2e531
--- /dev/null
@@ -0,0 +1,210 @@
+<html>\r
+<head>\r
+    <title>Documentation for FMU SDK 1.0.2</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1,h2,h3  { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+  <h1>FMU SDK 1.0.2</h1>\r
+  The FMU SDK is a free software development kit provided by\r
+    <a href="http://www.qtronic.de" target="_blank">QTronic</a>.\r
+    The FMU SDK demonstrates basic use of Functional Mockup Units (FMUs)\r
+    as defined by the following specifications\r
+    <ul>\r
+    <li>Functional Mock-up Interface for <a href=\r
+    "http://www.functional-mockup-interface.org/specifications/FMI_for_ModelExchange_v1.0.pdf" \r
+    target="_blank">Model Exchange 1.0</a> (January 26, 2010)</li>\r
+    <li>Functional Mock-up Interface for <a href=\r
+    "http://www.functional-mockup-interface.org/specifications/FMI_for_CoSimulation_v1.0.pdf" \r
+    target="_blank">Co-Simulation 1.0</a> (October 12, 2010)</li>\r
+    </ul>\r
+    The FMI specifications are available from \r
+    <a href="http://www.functional-mockup-interface.org/fmi.html" target="_blank">here</a>.\r
+    A short overview on FMUs and the FMI specification can be found\r
+    <a href="http://www.qtronic.de/doc/fmi_overview.pdf" taget="_blank">here</a>.\r
+    The FMU SDK can also serve as starting point for developing applications \r
+    that create or process FMUs.\r
+    <p>\r
+    The FMU SDK contains the C sources for various discrete and continuous \r
+    FMU models, a batch file for compiling and zip'ing these models, \r
+    an XML parser for parsing the model description of an FMU and two simple \r
+    simulation programs that run a given FMU and output the result as CSV file.\r
+    <p>\r
+    The FMU SDK can be downloaded from \r
+    <a href="http://www.qtronic.de/doc/fmusdk.zip">\r
+        http://www.qtronic.de/doc/fmusdk.zip</a>. \r
+    For bug reports, questions or comments regarding the FMU SDK, please\r
+    mail to <a href="mailto:fmu@qtronic.de">fmu@qtronic.de</a>.\r
+    Questions or comments regarding the FMU specification should be sent to \r
+    <a href="mailto:info@functional-mockup-interface.org">info@functional-mockup-interface.org</a>.\r
+    <img src="fmus.jpg">\r
+\r
+    <hr />\r
+\r
+<h2>Table of Contents</h2>\r
+<ul>\r
+    <li><a href="#installation">Building and Installing the FMU SDK</a></li>\r
+    <li><a href="#simulation">Simulating an FMU</a></li>\r
+    <li><a href="#creating_fmus">Creating your own FMUs</a></li>\r
+    <li><a href="#license">License conditions</a></li>\r
+</ul>\r
+\r
+<hr />\r
+<h2><a name="installation">Building and Installing the FMU SDK</a></h2>\r
+Downwload the FMU SDK from <a href="http://www.qtronic.de/doc/fmusdk.zip">here</a>, \r
+and unzip in a directory where you have write access. \r
+That directory is called FMUSDK_HOME below and may contain white space, such as in "C:\Program Files\fmusdk". \r
+The FMU SDK contains only the C sources of the FMUs and the simulator, not the executables, \r
+and should compile on all Windows platforms.\r
+<p/>\r
+To build the FMUs and the simulator, double click on FMUSDK_HOME\src\build_all.bat.\r
+This should create fmu files in FMUSDK_HOME\fmu\me and FMUSDK_HOME\fmu\cs, as well as two\r
+simulators fmusim_me.exe and fmusim_cs.exe in FMUSDK_HOME\bin. \r
+Compilation using build_all.bat requires that you have installed \r
+Microsoft Visual Studio 2005 (VS8) or 2008 (VS9), for example the free Express Edition. \r
+To compile with another compiler, adapt file build_all.bat.\r
+<hr />\r
+<h2><a name="simulation">Simulating an FMU</a></h2>\r
+To run a given FMU, open a command shell in directory FMUSDK_HOME and run the command fmusim\r
+<pre>\r
+fmusim fmi model.fmu tEnd h loggingOn csvSeparator\r
+  fmi ........... cs for co-simulation or me for model exchange, required\r
+  model.fmu ..... path to FMU, relative to current dir or absolute, required\r
+  tEnd .......... end  time of simulation, optional, defaults to 1.0 sec\r
+  h ............. step size of simulation, optional, defaults to 0.1 sec\r
+  loggingOn ..... 1 to activate logging,   optional, defaults to 0\r
+  csvSeparator .. c for comma, s for semicolon, optional, defaults to c\r
+</pre>\r
+This unzips the given FMU, parses the contained modelDescription.xml file, simulates\r
+the FMU from t=0 to t=tEnd, and writes the solution to file 'result.csv'. The file\r
+is written in CSV format (comma-separated values), using ';' to separate columns and\r
+using ',' instead of '.' as decimal dot to print floating-point numbers.\r
+To change the result file format, use the 'csv separator' option.\r
+The logging option activates logging of the simulated FMU. The FMI specification does\r
+not specify, what exactly to log in this case. However, when logging is switched on,\r
+the sample FMUs of the FMU SDK log every single FMU function call. Moreover, the\r
+fmusim simulators logs every step and every event that is detected.\r
+<p/>\r
+Example command:\r
+<pre>\r
+&gt; fmusim me fmu/me/bouncingBall.fmu 5 0.1 0 s\r
+FMU Simulator: run 'fmu/bouncingBall.fmu' from t=0..5 with step size h=0.1, loggingOn=0, csv separator=';'\r
+Simulation from 0 to 5 terminated successful\r
+  steps ............ 51\r
+  fixed step size .. 0.1\r
+  time events ...... 0\r
+  state events ..... 14\r
+  step events ...... 0\r
+CSV file 'result.csv' written\r
+</pre>\r
+To plot the result file, open it e.g. in a spread-sheet program, such as Miscrosoft Excel or OpenOffice Calc.\r
+The figure below shows the result of the above simulation when plotted using OpenOffice Calc 3.0.\r
+Note that the height h of the bouncing ball as computed by fmusim becomes negative at the contact points, \r
+while the true solution of the FMU does actually not contain negative height values. \r
+This is not a limitation of the FMU, but of fmusim_me, which does not attempt to locate the \r
+exact time of state events. \r
+To improve this, either reduce the step size or add your own procedure for state-event location to fmusim_me.\r
+<p/>\r
+<img src="bouncingBallCalc.png">\r
+\r
+<hr />\r
+<h2><a name="creating_fmus">Creating your own FMUs</a></h2>\r
+The FMU SDK contains a few sample FMUs\r
+<ul>\r
+    <li><a href="../src/models/dq/_main.html">dq</a> the Dahlquist test function x = -k der(x)</li>\r
+    <li><a href="../src/models/inc/_main.html">inc</a> increments an integer counter every second</li>\r
+    <li><a href="../src/models/values/_main.html">values</a> demonstrates the use of all scalar FMU data types</li>\r
+    <li><a href="../src/models/vanDerPol/_main.html">vanDerPol</a> ODE with 2 continuous states</li>\r
+    <li><a href="../src/models/bouncingBall/_main.html">bouncingBall</a> a bouncing ball that defines state events</li>\r
+</ul>\r
+To implement your own FMU using the FMU SDK, create a directory - say xy - in FMUSDK_HOME\src\models, and create\r
+files modelDescription.xml and xy.c there.\r
+The names of the new directory and the .c file must be the same. The content of the .c file should \r
+follow the existing FMU examples, see the comments in the example code. \r
+The XML file must not contain the <code>&lt;implementation&gt;</code>\r
+element and the closing <code>&lt/fmiModelDescription&gt;</code> tag, because this is added automatically during build.\r
+When done with editing the xml file and xy.c, open a command shell in FMUSDK_HOME\src\model and run the \r
+command <code>build_fmu me xy</code> to build an FMU for model exchange, or <code>build_fmu cs xy</code> to build an FMU for co-simulation. \r
+This should create the FMU file xy.fmu in directory FMUSDK_HOME\fmu\me or FMUSDK_HOME\fmu\cs.\r
+<p>\r
+The figure below might help to create or process the XML file modelDescription.xml. \r
+It shows all XML elements (without attributes) used in the schema files (XSD) for \r
+model exchange and co-simulation. Notation: UML class diagram.\r
+<img src="fmu10-xml-schema.png">\r
+\r
+<hr />\r
+\r
+<h2>FMU SDK Revision history</h2>\r
+<ul>\r
+<li>07.02.2010, Version 1.0\r
+    <ul>\r
+    <li>First release</li>\r
+    <li>demo FMI for Model Exchange 1.0</li>\r
+    </ul>\r
+</li>\r
+<li>05.03.2010, Version 1.0.1\r
+    <ul>\r
+    <li>demo FMI for Model Exchange 1.0</li>\r
+    <li>bug-fix in fmuTemplate.c: fmiSetString now copies the passed\r
+       string argument and fmiFreeModelInstance frees all string copies\r
+    </li> \r
+    <li>fmusim/main.c: removed strerror(GetLastError()) from error messages\r
+    </li>\r
+    </ul>\r
+</li>\r
+<li>22.08.2011, Version 1.0.2\r
+    <ul>\r
+    <li>demo FMI for Model Exchange 1.0 and FMI for Co-Simulation 1.0</li>\r
+    <li>added support for FMI for Co-Simulation 1.0 (standalone, no tool coupling)</li>\r
+    <li>bug-fix in fmusim/main.c: added missing calls to fmiTerminate and fmiFreeModelInstance</li> \r
+    </ul>\r
+</li>\r
+</ul>\r
+\r
+<h2><a name="license">License conditions</a></h2>\r
+The FMU SDK is provided by QTronic under the\r
+<a href="http://www.opensource.org/licenses/bsd-license.html">BSD License</a>.\r
+<hr/>\r
+<pre>\r
+FMU SDK license \r
+\r
+Copyright Â© 2008-2011, QTronic GmbH. All rights reserved.\r
+The FmuSdk is licensed by the copyright holder under the BSD License\r
+(http://www.opensource.org/licenses/bsd-license.html):\r
+Redistribution and use in source and binary forms, with or without\r
+modification, are permitted provided that the following conditions are met:\r
+- Redistributions of source code must retain the above copyright notice,\r
+  this list of conditions and the following disclaimer.\r
+- Redistributions in binary form must reproduce the above copyright notice,\r
+  this list of conditions and the following disclaimer in the documentation\r
+  and/or other materials provided with the distribution.\r
+\r
+THIS SOFTWARE IS PROVIDED BY QTRONIC GMBH "AS IS" AND ANY EXPRESS OR \r
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES \r
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \r
+IN NO EVENT SHALL QTRONIC GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, \r
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\r
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \r
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \r
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \r
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF \r
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+</pre>\r
+<hr/>\r
+\r
+The following additional tools are distributed with the FMU SDK under their \r
+respective licenses\r
+<ul>\r
+    <li><a href="http://www.7-zip.org" target="_blank">7z 4.57</a> \r
+     by Igor Pavlov. Used here to zip and unzip FMUs, \r
+     license is <a href="../bin/license.txt">here</a>.</li>\r
+    <li><a href="http://sourceforge.net/projects/expat/" target="_blank">eXpat 2.0.1</a> \r
+     by James Clark. Used here to parse the modelDescription.xml file of an FMU,  \r
+     license is <a href="../source/fmusim/COPYING.txt">here</a>.</li> \r
+</ul>\r
+<hr />\r
+\r
+</body>\r
+</html>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/bouncingBallCalc.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/bouncingBallCalc.png
new file mode 100644 (file)
index 0000000..1944a62
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/bouncingBallCalc.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmu10-xml-schema.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmu10-xml-schema.png
new file mode 100644 (file)
index 0000000..772eaf6
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmu10-xml-schema.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmus.jpg b/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmus.jpg
new file mode 100644 (file)
index 0000000..d7eec87
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmus.jpg differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmusdk_license.txt b/1.8/org.simantics.fmu/FMUSolution/FMISDK/doc/fmusdk_license.txt
new file mode 100644 (file)
index 0000000..e1ac0aa
--- /dev/null
@@ -0,0 +1,24 @@
+\r
+FMU SDK license \r
+\r
+Copyright Â© 2008-2011, QTronic GmbH. All rights reserved.\r
+The FmuSdk is licensed by the copyright holder under the BSD License\r
+(http://www.opensource.org/licenses/bsd-license.html):\r
+Redistribution and use in source and binary forms, with or without\r
+modification, are permitted provided that the following conditions are met:\r
+- Redistributions of source code must retain the above copyright notice,\r
+  this list of conditions and the following disclaimer.\r
+- Redistributions in binary form must reproduce the above copyright notice,\r
+  this list of conditions and the following disclaimer in the documentation\r
+  and/or other materials provided with the distribution.\r
+\r
+THIS SOFTWARE IS PROVIDED BY QTRONIC GMBH "AS IS" AND ANY EXPRESS OR \r
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES \r
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \r
+IN NO EVENT SHALL QTRONIC GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, \r
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\r
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \r
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \r
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \r
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF \r
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/Model.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/Model.fmu
new file mode 100644 (file)
index 0000000..ad3b03e
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/Model.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/bouncingBall.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/bouncingBall.fmu
new file mode 100644 (file)
index 0000000..7f009f6
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/bouncingBall.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/dq.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/dq.fmu
new file mode 100644 (file)
index 0000000..38e5c2b
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/dq.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/inc.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/inc.fmu
new file mode 100644 (file)
index 0000000..fbbd449
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/inc.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/values.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/values.fmu
new file mode 100644 (file)
index 0000000..7b03aa4
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/values.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/vanDerPol.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/vanDerPol.fmu
new file mode 100644 (file)
index 0000000..f36f4c2
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/cs/vanDerPol.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/bouncingBall.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/bouncingBall.fmu
new file mode 100644 (file)
index 0000000..f084744
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/bouncingBall.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/dq.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/dq.fmu
new file mode 100644 (file)
index 0000000..821fb56
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/dq.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/inc.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/inc.fmu
new file mode 100644 (file)
index 0000000..d9a5b7d
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/inc.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/values.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/values.fmu
new file mode 100644 (file)
index 0000000..a450894
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/values.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/vanDerPol.fmu b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/vanDerPol.fmu
new file mode 100644 (file)
index 0000000..e694c54
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmu/me/vanDerPol.fmu differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmusdk.zip b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmusdk.zip
new file mode 100644 (file)
index 0000000..519bf01
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmusdk.zip differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmusim.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/fmusim.bat
new file mode 100644 (file)
index 0000000..c9e575c
--- /dev/null
@@ -0,0 +1,9 @@
+@echo off \r
+rem ------------------------------------------------------------\r
+rem To run a simulation, start this batch in this directory. \r
+rem Example: fmusim me fmu/me/dq.fmu 0.3 0.1 1 c\r
+rem To build simulators bin\*.exe and FMUs, run src\build_all.bat\r
+rem ------------------------------------------------------------\r
+\r
+set FMUSDK_HOME=.\r
+if %1==me (bin\fmusim_me.exe %2 %3 %4 %5 %6) else bin\fmusim_cs.exe %2 %3 %4 %5 %6\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/run_all.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/run_all.bat
new file mode 100644 (file)
index 0000000..8de848b
--- /dev/null
@@ -0,0 +1,50 @@
+@echo off \r
+\r
+rem ------------------------------------------------------------\r
+rem This batch simulates all FMUs of the FmuSDK and stores\r
+rem simulation results in CSV files, one per simulation run.\r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+echo -----------------------------------------------------------\r
+echo Runnig all FMUs of the FmuSDK ...\r
+\r
+echo -----------------------------------------------------------\r
+call fmusim me fmu\me\bouncingBall.fmu 4 0.01 0 c\r
+move /Y result.csv result_me_bouncingBall.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim cs fmu\cs\bouncingBall.fmu 4 0.01 0 c\r
+move /Y result.csv result_cs_bouncingBall.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim me fmu\me\vanDerPol.fmu 5 0.1 0 c\r
+move /Y result.csv result_me_vanDerPol.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim cs fmu\cs\vanDerPol.fmu 5 0.1 0 c\r
+move /Y result.csv result_cs_vanDerPol.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim me fmu\me\dq.fmu 1 0.1 0 c\r
+move /Y result.csv result_me_dq.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim cs fmu\cs\dq.fmu 1 0.1 0 c\r
+move /Y result.csv result_cs_dq.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim me fmu\me\inc.fmu 15 15 0 c\r
+move /Y result.csv result_me_inc.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim cs fmu\cs\inc.fmu 15 0.5 0 c\r
+move /Y result.csv result_cs_inc.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim me fmu\me\values.fmu 12 12 0 c\r
+move /Y result.csv result_me_values.csv \r
+\r
+echo -----------------------------------------------------------\r
+call fmusim cs fmu\cs\values.fmu 12 0.3 0 c\r
+move /Y result.csv result_cs_values.csv \r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_all.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_all.bat
new file mode 100644 (file)
index 0000000..cdd7515
--- /dev/null
@@ -0,0 +1,28 @@
+@echo off \r
+\r
+rem ------------------------------------------------------------\r
+rem This batch builds both simulators and all FMUs of the FmuSDK\r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+call build_fmusim_me\r
+call build_fmusim_cs\r
+echo -----------------------------------------------------------\r
+echo Making the FMUs of the FmuSDK ...\r
+pushd models\r
+\r
+call build_fmu me dq \r
+call build_fmu me inc\r
+call build_fmu me values\r
+call build_fmu me vanDerPol\r
+call build_fmu me bouncingBall\r
+\r
+call build_fmu cs dq\r
+call build_fmu cs inc\r
+call build_fmu cs values\r
+call build_fmu cs vanDerPol\r
+call build_fmu cs bouncingBall\r
+\r
+popd\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_fmusim_cs.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_fmusim_cs.bat
new file mode 100644 (file)
index 0000000..6e90292
--- /dev/null
@@ -0,0 +1,48 @@
+@echo off \r
+rem ------------------------------------------------------------\r
+rem This batch builds the FMU simulator fmusim_cs.exe\r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+echo -----------------------------------------------------------\r
+echo building fmusim_cs.exe - FMI for Co-Simulation 1.0\r
+echo -----------------------------------------------------------\r
+\r
+rem save env variable settings\r
+set PREV_PATH=%PATH%\r
+if defined INCLUDE set PREV_INCLUDE=%INLUDE%\r
+if defined LIB     set PREV_LIB=%LIB%\r
+if defined LIBPATH set PREV_LIBPATH=%LIBPATH%\r
+\r
+rem setup the compiler\r
+if defined VS90COMNTOOLS (call "%VS90COMNTOOLS%\vsvars32.bat") else ^\r
+if defined VS80COMNTOOLS (call "%VS80COMNTOOLS%\vsvars32.bat") else ^\r
+goto noCompiler\r
+\r
+set SRC=fmusim_cs\main.c ..\shared\xml_parser.c ..\shared\stack.c ..\shared\sim_support.c\r
+set INC=/Iinclude /I../shared /Ifmusim_cs\r
+set OPTIONS=/DFMI_COSIMULATION /wd4090 /nologo\r
+\r
+rem create fmusim_cs.exe in the fmusim_cs dir\r
+rem /wd4090 to disable warnings about different 'const' qualifiers\r
+pushd co_simulation\r
+cl %SRC% %INC% %OPTIONS% /Fefmusim_cs.exe /link ..\shared\libexpatMT.lib  \r
+del *.obj\r
+popd\r
+if not exist co_simulation\fmusim_cs.exe goto compileError\r
+move /Y co_simulation\fmusim_cs.exe ..\bin\r
+goto done\r
+\r
+:noCompiler\r
+echo No Microsoft Visual C compiler found\r
+\r
+:compileError\r
+echo build of fmusim_cs.exe failed\r
+\r
+:done\r
+rem undo variable settings performed by vsvars32.bat\r
+set PATH=%PREV_PATH%\r
+if defined PREV_INCLUDE set INCLUDE=%PREV_INLUDE%\r
+if defined PREV_LIB     set LIB=%PREV_LIB%\r
+if defined PREV_LIBPATH set LIBPATH=%PREV_LIBPATH%\r
+echo done.\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_fmusim_me.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/build_fmusim_me.bat
new file mode 100644 (file)
index 0000000..0828428
--- /dev/null
@@ -0,0 +1,51 @@
+@echo off \r
+rem ------------------------------------------------------------\r
+rem This batch builds the FMU simulator fmusim_me.exe\r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+echo -----------------------------------------------------------\r
+echo building fmusim_me.exe - FMI for Model Exchange 1.0\r
+echo -----------------------------------------------------------\r
+\r
+rem save env variable settings\r
+set PREV_PATH=%PATH%\r
+if defined INCLUDE set PREV_INCLUDE=%INLUDE%\r
+if defined LIB     set PREV_LIB=%LIB%\r
+if defined LIBPATH set PREV_LIBPATH=%LIBPATH%\r
+\r
+rem setup the compiler\r
+if defined VS90COMNTOOLS (call "%VS90COMNTOOLS%\vsvars32.bat") else ^\r
+if defined VS80COMNTOOLS (call "%VS80COMNTOOLS%\vsvars32.bat") else ^\r
+goto noCompiler\r
+\r
+set SRC=fmusim_me\main.c ..\shared\xml_parser.c ..\shared\stack.c ..\shared\sim_support.c\r
+set INC=/Iinclude /I../shared /Ifmusim_me\r
+set OPTIONS=/wd4090 /nologo\r
+\r
+rem create fmusim_me.exe in the fmusim_me dir\r
+rem /wd4090 to disable warnings about different 'const' qualifiers\r
+pushd model_exchange\r
+cl %SRC% %INC% %OPTIONS% /Fefmusim_me.exe /link ..\shared\libexpatMT.lib  \r
+del *.obj\r
+popd\r
+if not exist model_exchange\fmusim_me.exe goto compileError\r
+move /Y model_exchange\fmusim_me.exe ..\bin\r
+goto done\r
+\r
+:noCompiler\r
+echo No Microsoft Visual C compiler found\r
+\r
+:compileError\r
+echo build of fmusim_me.exe failed\r
+\r
+:done\r
+rem undo variable settings performed by vsvars32.bat\r
+set PATH=%PREV_PATH%\r
+if defined PREV_INCLUDE set INCLUDE=%PREV_INLUDE%\r
+if defined PREV_LIB     set LIB=%PREV_LIB%\r
+if defined PREV_LIBPATH set LIBPATH=%PREV_LIBPATH%\r
+echo done.\r
+\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/fmusim_cs/fmi_cs.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/fmusim_cs/fmi_cs.h
new file mode 100644 (file)
index 0000000..f446eac
--- /dev/null
@@ -0,0 +1,78 @@
+/* ------------------------------------------------------------------------- \r
+ * fmi_cs.h\r
+ * Function types for all function of the "FMI for Co-Simulation 1.0"\r
+ * and a struct with the corresponding function pointers. \r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#ifndef FMI_CS_H\r
+#define FMI_CS_H\r
+\r
+#include <windows.h>\r
+#include "fmiFunctions.h"\r
+#include "xml_parser.h"\r
+\r
+typedef const char* (*fGetTypesPlatform)();\r
+typedef const char* (*fGetVersion)();\r
+typedef fmiStatus (*fSetDebugLogging)    (fmiComponent c, fmiBoolean loggingOn);\r
+typedef fmiStatus (*fSetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+typedef fmiStatus (*fSetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+typedef fmiStatus (*fSetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+typedef fmiStatus (*fSetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+typedef fmiStatus (*fGetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+typedef fmiStatus (*fGetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+typedef fmiStatus (*fGetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+typedef fmiStatus (*fGetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+typedef fmiComponent (*fInstantiateSlave)  (fmiString  instanceName, fmiString  fmuGUID, fmiString  fmuLocation, \r
+        fmiString  mimeType, fmiReal timeout, fmiBoolean visible, fmiBoolean interactive, \r
+        fmiCallbackFunctions functions, fmiBoolean loggingOn);\r
+typedef fmiStatus (*fInitializeSlave)(fmiComponent c, fmiReal tStart, fmiBoolean StopTimeDefined, fmiReal tStop);\r
+typedef fmiStatus (*fTerminateSlave)   (fmiComponent c);\r
+typedef fmiStatus (*fResetSlave)       (fmiComponent c);\r
+typedef void      (*fFreeSlaveInstance)(fmiComponent c);\r
+typedef fmiStatus (*fSetRealInputDerivatives)(fmiComponent c, const  fmiValueReference vr[], size_t nvr,\r
+        const fmiInteger order[], const  fmiReal value[]);                                                  \r
+typedef fmiStatus (*fGetRealOutputDerivatives)(fmiComponent c, const fmiValueReference vr[], size_t  nvr,\r
+        const fmiInteger order[], fmiReal value[]);                                              \r
+typedef fmiStatus (*fCancelStep)(fmiComponent c);\r
+typedef fmiStatus (*fDoStep)(fmiComponent c, fmiReal currentCommunicationPoint, \r
+        fmiReal communicationStepSize, fmiBoolean newStep);\r
+typedef fmiStatus (*fGetStatus)       (fmiComponent c, const fmiStatusKind s, fmiStatus*  value);\r
+typedef fmiStatus (*fGetRealStatus)   (fmiComponent c, const fmiStatusKind s, fmiReal*    value);\r
+typedef fmiStatus (*fGetIntegerStatus)(fmiComponent c, const fmiStatusKind s, fmiInteger* value);\r
+typedef fmiStatus (*fGetBooleanStatus)(fmiComponent c, const fmiStatusKind s, fmiBoolean* value);\r
+typedef fmiStatus (*fGetStringStatus) (fmiComponent c, const fmiStatusKind s, fmiString*  value);\r
+\r
+typedef struct {\r
+    ModelDescription* modelDescription;\r
+    HANDLE dllHandle;\r
+    fGetTypesPlatform getTypesPlatform;\r
+    fGetVersion getVersion;\r
+    fSetDebugLogging setDebugLogging;\r
+    fSetReal setReal;\r
+    fSetInteger setInteger;\r
+    fSetBoolean setBoolean;\r
+    fSetString setString;\r
+    fGetReal getReal;\r
+    fGetInteger getInteger;\r
+    fGetBoolean getBoolean;\r
+    fGetString getString;\r
+    fInstantiateSlave instantiateSlave;\r
+    fInitializeSlave initializeSlave;\r
+    fTerminateSlave terminateSlave;\r
+    fResetSlave resetSlave;\r
+    fFreeSlaveInstance freeSlaveInstance;\r
+    fGetRealOutputDerivatives getRealOutputDerivatives;\r
+    fSetRealInputDerivatives setRealInputDerivatives;\r
+    fDoStep doStep;\r
+    fCancelStep cancelStep;\r
+    fGetStatus getStatus;\r
+    fGetRealStatus getRealStatus;\r
+    fGetIntegerStatus getIntegerStatus;\r
+    fGetBooleanStatus getBooleanStatus;\r
+    fGetStringStatus getStringStatus;\r
+} FMU;\r
+\r
+#endif // FMI_CS_H\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/fmusim_cs/main.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/fmusim_cs/main.c
new file mode 100644 (file)
index 0000000..f0673d1
--- /dev/null
@@ -0,0 +1,127 @@
+/* ------------------------------------------------------------------------- \r
+ * main.c\r
+ * Implements simulation of a single FMU instance \r
+ * that implements the "FMI for Co-Simulation 1.0" interface.\r
+ * Command syntax: see printHelp()\r
+ * Simulates the given FMU from t = 0 .. tEnd with fixed step size h and \r
+ * writes the computed solution to file 'result.csv'.\r
+ * The CSV file (comma-separated values) may e.g. be plotted using \r
+ * OpenOffice Calc or Microsoft Excel. \r
+ * This progamm demonstrates basic use of an FMU.\r
+ * Real applications may use advanced master algorithms to cosimulate \r
+ * many FMUs, limit the numerical error using error estimation\r
+ * and back-stepping, provide graphical plotting utilities, debug support, \r
+ * and user control of parameter and start values, or perform a clean\r
+ * error handling (e.g. call freeSlaveInstance when a call to the fmu\r
+ * returns with error). All this is missing here.\r
+ *\r
+ * Revision history\r
+ *  22.08.2011 initial version released in FMU SDK 1.0.2\r
+ *     \r
+ * Free libraries and tools used to implement this simulator:\r
+ *  - header files from the FMU specification\r
+ *  - eXpat 2.0.1 XML parser, see http://expat.sourceforge.net\r
+ *  - 7z.exe 4.57 zip and unzip tool, see http://www.7-zip.org\r
+ * Author: Jakob Mauss\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include "fmi_cs.h"\r
+#include "sim_support.h"\r
+\r
+FMU fmu; // the fmu to simulate\r
+\r
+// simulate the given FMU using the forward euler method.\r
+// time events are processed by reducing step size to exactly hit tNext.\r
+// state events are checked and fired only at the end of an Euler step. \r
+// the simulator may therefore miss state events and fires state events typically too late.\r
+static int simulate(FMU* fmu, double tEnd, double h, fmiBoolean loggingOn, char separator) {\r
+    double time;\r
+    double tStart = 0;               // start time\r
+    const char* guid;                // global unique id of the fmu\r
+    fmiComponent c;                  // instance of the fmu \r
+    fmiStatus fmiFlag;               // return code of the fmu functions\r
+    const char* fmuLocation = NULL;  // path to the fmu as URL, "file://C:\QTronic\sales"\r
+    const char* mimeType = "application/x-fmu-sharedlibrary"; // denotes tool in case of tool coupling\r
+    fmiReal timeout = 1000;          // wait period in milli seconds, 0 for unlimited wait period"\r
+    fmiBoolean visible = fmiFalse;   // no simulator user interface\r
+    fmiBoolean interactive = fmiFalse; // simulation run without user interaction\r
+    fmiCallbackFunctions callbacks;  // called by the model during simulation\r
+    ModelDescription* md;            // handle to the parsed XML file   \r
+    int nSteps = 0;\r
+    FILE* file;\r
+        \r
+    // instantiate the fmu \r
+    md = fmu->modelDescription;\r
+    guid = getString(md, att_guid);\r
+    callbacks.logger = fmuLogger;\r
+    callbacks.allocateMemory = calloc;\r
+    callbacks.freeMemory = free;\r
+    callbacks.stepFinished = NULL; // fmiDoStep has to be carried out synchronously\r
+    c = fmu->instantiateSlave(getModelIdentifier(md), guid, fmuLocation, mimeType, \r
+                              timeout, visible, interactive, callbacks, loggingOn);\r
+    if (!c) return error("could not instantiate model");\r
+\r
+    // open result file\r
+    if (!(file=fopen(RESULT_FILE, "w"))) {\r
+        printf("could not write %s because:\n", RESULT_FILE);\r
+        printf("    %s\n", strerror(errno));\r
+        return 0; // failure\r
+    }\r
+    \r
+    // StopTimeDefined=fmiFalse means: ignore value of tEnd\r
+    fmiFlag = fmu->initializeSlave(c, tStart, fmiTrue, tEnd);\r
+    if (fmiFlag > fmiWarning)  return error("could not initialize model");\r
+    \r
+    // output solution for time t0\r
+    outputRow(fmu, c, tStart, file, separator, TRUE);  // output column names\r
+    outputRow(fmu, c, tStart, file, separator, FALSE); // output values\r
+\r
+    // enter the simulation loop    \r
+    time = tStart;\r
+    while (time < tEnd) {\r
+        fmiFlag = fmu->doStep(c, time, h, fmiTrue);\r
+        if (fmiFlag != fmiOK)  return error("could not complete simulation of the model");\r
+        time += h;\r
+        outputRow(fmu, c, time, file, separator, FALSE); // output values for this step\r
+        nSteps++;\r
+    }\r
+    \r
+    // end simulation\r
+    fmiFlag = fmu->terminateSlave(c);\r
+    fmu->freeSlaveInstance(c);\r
+  \r
+    // print simulation summary \r
+    printf("Simulation from %g to %g terminated successful\n", tStart, tEnd);\r
+    printf("  steps ............ %d\n", nSteps);\r
+    printf("  fixed step size .. %g\n", h);\r
+    return 1; // success\r
+}\r
+\r
+int main(int argc, char *argv[]) {\r
+    const char* fmuFileName;\r
+    \r
+    // parse command line arguments and load the FMU\r
+    double tEnd = 1.0;\r
+    double h=0.1;\r
+    int loggingOn = 0;\r
+    char csv_separator = ';';\r
+    parseArguments(argc, argv, &fmuFileName, &tEnd, &h, &loggingOn, &csv_separator);\r
+    loadFMU(fmuFileName);\r
+\r
+    // run the simulation\r
+    printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c'\n", \r
+            fmuFileName, tEnd, h, loggingOn, csv_separator);\r
+    simulate(&fmu, tEnd, h, loggingOn, csv_separator);\r
+    printf("CSV file '%s' written\n", RESULT_FILE);\r
+\r
+    // release FMU \r
+    FreeLibrary(fmu.dllHandle);\r
+    freeElement(fmu.modelDescription);\r
+    return EXIT_SUCCESS;\r
+}\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/include/fmiFunctions.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/include/fmiFunctions.h
new file mode 100644 (file)
index 0000000..f434102
--- /dev/null
@@ -0,0 +1,231 @@
+#ifndef fmiFunctions_h\r
+#define fmiFunctions_h\r
+\r
+/* This header file must be utilized when compiling a FMU.\r
+   It defines all functions of Co-Simulation Interface.\r
+   In order to have unique function names even if several FMUs\r
+   are compiled together (e.g. for embedded systems), every "real" function name\r
+   is constructed by prepending the function name by\r
+   "MODEL_IDENTIFIER" + "_" where "MODEL_IDENTIFIER" is the short name\r
+   of the model used as the name of the zip-file where the model is stored.\r
+   Therefore, the typical usage is:\r
+\r
+      #define MODEL_IDENTIFIER MyModel\r
+      #include "fmiFunctions.h"\r
+\r
+   As a result, a function that is defined as "fmiGetDerivatives" in this header file,\r
+   is actually getting the name "MyModel_fmiGetDerivatives".\r
+\r
+   Revisions:\r
+   - November 4, 2010: Adapted to specification text:\r
+                       o fmiGetModelTypesPlatform renamed to fmiGetTypesPlatform\r
+                       o fmiInstantiateSlave: Argument GUID     replaced by fmuGUID\r
+                                              Argument mimetype replaced by mimeType\r
+                       o tabs replaced by spaces\r
+   - October 16, 2010: First public Version\r
+\r
+\r
+   Copyright Â© 2008-2010, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html):\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+*/\r
+\r
+#include "fmiPlatformTypes.h"\r
+#include <stdlib.h>\r
+\r
+/* Export fmi functions on Windows */\r
+#ifdef _MSC_VER\r
+#define DllExport __declspec( dllexport )\r
+#else\r
+#define DllExport\r
+#endif\r
+\r
+/* Macros to construct the real function name\r
+   (prepend function name by MODEL_IDENTIFIER + "_") */\r
+\r
+#define fmiPaste(a,b)     a ## b\r
+#define fmiPasteB(a,b)    fmiPaste(a,b)\r
+#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)\r
+\r
+/***************************************************\r
+Common Functions\r
+****************************************************/\r
+#define fmiGetTypesPlatform fmiFullName(_fmiGetTypesPlatform)\r
+#define fmiGetVersion       fmiFullName(_fmiGetVersion)\r
+#define fmiSetDebugLogging  fmiFullName(_fmiSetDebugLogging)\r
+\r
+/*Data Exchange*/\r
+#define fmiSetReal               fmiFullName(_fmiSetReal)\r
+#define fmiSetInteger            fmiFullName(_fmiSetInteger)\r
+#define fmiSetBoolean            fmiFullName(_fmiSetBoolean)\r
+#define fmiSetString             fmiFullName(_fmiSetString)\r
+\r
+#define fmiGetReal               fmiFullName(_fmiGetReal)\r
+#define fmiGetInteger            fmiFullName(_fmiGetInteger)\r
+#define fmiGetBoolean            fmiFullName(_fmiGetBoolean)\r
+#define fmiGetString             fmiFullName(_fmiGetString)\r
+\r
+/***************************************************\r
+Functions for FMI for Co-Simulation\r
+****************************************************/\r
+#define fmiInstantiateSlave         fmiFullName(_fmiInstantiateSlave)\r
+#define fmiInitializeSlave          fmiFullName(_fmiInitializeSlave)\r
+#define fmiTerminateSlave           fmiFullName(_fmiTerminateSlave)\r
+#define fmiResetSlave               fmiFullName(_fmiResetSlave)\r
+#define fmiFreeSlaveInstance        fmiFullName(_fmiFreeSlaveInstance)\r
+#define fmiSetRealInputDerivatives  fmiFullName(_fmiSetRealInputDerivatives)\r
+#define fmiGetRealOutputDerivatives fmiFullName(_fmiGetRealOutputDerivatives)\r
+#define fmiDoStep                   fmiFullName(_fmiDoStep)\r
+#define fmiCancelStep               fmiFullName(_fmiCancelStep)\r
+#define fmiGetStatus                fmiFullName(_fmiGetStatus)\r
+#define fmiGetRealStatus            fmiFullName(_fmiGetRealStatus)\r
+#define fmiGetIntegerStatus         fmiFullName(_fmiGetIntegerStatus)\r
+#define fmiGetBooleanStatus         fmiFullName(_fmiGetBooleanStatus)\r
+#define fmiGetStringStatus          fmiFullName(_fmiGetStringStatus)\r
+\r
+/* Version number */\r
+#define fmiVersion "1.0"\r
+\r
+/* make sure all compiler use the same alignment policies for structures */\r
+#ifdef WIN32\r
+#pragma pack(push,8)\r
+#endif\r
+\r
+\r
+/* Type definitions */\r
+     typedef enum {fmiOK,\r
+                   fmiWarning,\r
+                   fmiDiscard,\r
+                   fmiError,\r
+                   fmiFatal,\r
+                   fmiPending} fmiStatus;\r
+\r
+     typedef void  (*fmiCallbackLogger) (fmiComponent c, fmiString instanceName, fmiStatus status,\r
+                                         fmiString category, fmiString message, ...);\r
+     typedef void* (*fmiCallbackAllocateMemory)(size_t nobj, size_t size);\r
+     typedef void  (*fmiCallbackFreeMemory)    (void* obj);\r
+     typedef void  (*fmiStepFinished)          (fmiComponent c, fmiStatus status);\r
+\r
+     typedef struct {\r
+     fmiCallbackLogger         logger;\r
+     fmiCallbackAllocateMemory allocateMemory;\r
+     fmiCallbackFreeMemory     freeMemory;\r
+     fmiStepFinished           stepFinished;\r
+     } fmiCallbackFunctions;\r
+\r
+   typedef struct {\r
+      fmiBoolean iterationConverged;\r
+      fmiBoolean stateValueReferencesChanged;\r
+      fmiBoolean stateValuesChanged;\r
+      fmiBoolean terminateSimulation;\r
+      fmiBoolean upcomingTimeEvent;\r
+      fmiReal    nextEventTime;\r
+   } fmiEventInfo;\r
+\r
+/* reset alignment policy to the one set before reading this file */\r
+#ifdef WIN32\r
+#pragma pack(pop)\r
+#endif\r
+\r
+/***************************************************\r
+Common Functions\r
+****************************************************/\r
+\r
+/* Inquire version numbers of header files */\r
+   DllExport const char* fmiGetTypesPlatform();\r
+   DllExport const char* fmiGetVersion();\r
+\r
+   DllExport fmiStatus fmiSetDebugLogging  (fmiComponent c, fmiBoolean loggingOn);\r
+\r
+/* Data Exchange Functions*/\r
+   DllExport fmiStatus fmiGetReal   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+   DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+   DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+   DllExport fmiStatus fmiGetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+\r
+   DllExport fmiStatus fmiSetReal    (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+   DllExport fmiStatus fmiSetInteger (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+   DllExport fmiStatus fmiSetBoolean (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+   DllExport fmiStatus fmiSetString  (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+\r
+/***************************************************\r
+Functions for FMI for Co-Simulation\r
+****************************************************/\r
+\r
+/* Creation and destruction of slave instances and setting debug status */\r
+   DllExport fmiComponent fmiInstantiateSlave(fmiString  instanceName,\r
+                                              fmiString  fmuGUID,\r
+                                              fmiString  fmuLocation,\r
+                                              fmiString  mimeType,\r
+                                              fmiReal    timeout,\r
+                                              fmiBoolean visible,\r
+                                              fmiBoolean interactive,\r
+                                              fmiCallbackFunctions functions,\r
+                                              fmiBoolean loggingOn);\r
+\r
+   DllExport fmiStatus fmiInitializeSlave(fmiComponent c,\r
+                                          fmiReal      tStart,\r
+                                          fmiBoolean   StopTimeDefined,\r
+                                          fmiReal      tStop);\r
+\r
+   DllExport fmiStatus fmiTerminateSlave   (fmiComponent c);\r
+   DllExport fmiStatus fmiResetSlave       (fmiComponent c);\r
+   DllExport void      fmiFreeSlaveInstance(fmiComponent c);\r
+\r
+   DllExport fmiStatus fmiSetRealInputDerivatives(fmiComponent c,\r
+                                                  const  fmiValueReference vr[],\r
+                                                  size_t nvr,\r
+                                                  const  fmiInteger order[],\r
+                                                  const  fmiReal value[]);\r
+\r
+   DllExport fmiStatus fmiGetRealOutputDerivatives(fmiComponent c,\r
+                                                   const   fmiValueReference vr[],\r
+                                                   size_t  nvr,\r
+                                                   const   fmiInteger order[],\r
+                                                   fmiReal value[]);\r
+\r
+   DllExport fmiStatus fmiCancelStep(fmiComponent c);\r
+   DllExport fmiStatus fmiDoStep    (fmiComponent c,\r
+                                     fmiReal      currentCommunicationPoint,\r
+                                     fmiReal      communicationStepSize,\r
+                                     fmiBoolean   newStep);\r
+\r
+\r
+   typedef enum {fmiDoStepStatus,\r
+                 fmiPendingStatus,\r
+                 fmiLastSuccessfulTime} fmiStatusKind;\r
+\r
+   DllExport fmiStatus fmiGetStatus       (fmiComponent c, const fmiStatusKind s, fmiStatus*  value);\r
+   DllExport fmiStatus fmiGetRealStatus   (fmiComponent c, const fmiStatusKind s, fmiReal*    value);\r
+   DllExport fmiStatus fmiGetIntegerStatus(fmiComponent c, const fmiStatusKind s, fmiInteger* value);\r
+   DllExport fmiStatus fmiGetBooleanStatus(fmiComponent c, const fmiStatusKind s, fmiBoolean* value);\r
+   DllExport fmiStatus fmiGetStringStatus (fmiComponent c, const fmiStatusKind s, fmiString*  value);\r
+\r
+\r
+#endif // fmiFunctions_h\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/include/fmiPlatformTypes.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/co_simulation/include/fmiPlatformTypes.h
new file mode 100644 (file)
index 0000000..7916f79
--- /dev/null
@@ -0,0 +1,73 @@
+#ifndef fmiPlatformTypes_h\r
+#define fmiPlatformTypes_h\r
+\r
+/* Standard header file to define the argument types of the\r
+   functions of the Model Execution Interface.\r
+   This header file must be utilized both by the model and\r
+   by the simulation engine.\r
+\r
+   Revisions:\r
+   - October 2010: First public Version\r
+\r
+\r
+   Copyright Â© 2008-2010, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html):\r
+\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+*/\r
+\r
+/* Platform (combination of machine, compiler, operating system) */\r
+#define fmiPlatform "standard32"\r
+\r
+/* Type definitions of variables passed as arguments\r
+   Version "standard32" means:\r
+\r
+   fmiComponent     : 32 bit pointer\r
+   fmiValueReference: 32 bit\r
+   fmiReal          : 64 bit\r
+   fmiInteger       : 32 bit\r
+   fmiBoolean       :  8 bit\r
+   fmiString        : 32 bit pointer\r
+\r
+*/\r
+   typedef void*        fmiComponent;\r
+   typedef unsigned int fmiValueReference;\r
+   typedef double       fmiReal   ;\r
+   typedef int          fmiInteger;\r
+   typedef char         fmiBoolean;\r
+   typedef const char*  fmiString ;\r
+\r
+/* Values for fmiBoolean  */\r
+#define fmiTrue  1\r
+#define fmiFalse 0\r
+\r
+/* Undefined value for fmiValueReference (largest unsigned int value) */\r
+#define fmiUndefinedValueReference (fmiValueReference)(-1)\r
+\r
+#endif\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/fmusim_me/fmi_me.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/fmusim_me/fmi_me.h
new file mode 100644 (file)
index 0000000..f115245
--- /dev/null
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------------- \r
+ * fmi_me.h\r
+ * Function types for all function of the "FMI for Model Exchange 1.0"\r
+ * and a struct with the corresponding function pointers. \r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#ifndef FMI_ME_H\r
+#define FMI_ME_H\r
+\r
+#include <windows.h>\r
+#include "fmiModelFunctions.h"\r
+#include "xml_parser.h"\r
+\r
+typedef const char* (*fGetModelTypesPlatform)();\r
+typedef const char* (*fGetVersion)();\r
+typedef fmiComponent (*fInstantiateModel)(fmiString instanceName, fmiString GUID,\r
+                                        fmiCallbackFunctions functions, fmiBoolean loggingOn);\r
+typedef void      (*fFreeModelInstance)  (fmiComponent c);\r
+typedef fmiStatus (*fSetDebugLogging)    (fmiComponent c, fmiBoolean loggingOn);\r
+typedef fmiStatus (*fSetTime)            (fmiComponent c, fmiReal time);\r
+typedef fmiStatus (*fSetContinuousStates)(fmiComponent c, const fmiReal x[], size_t nx);\r
+typedef fmiStatus (*fCompletedIntegratorStep)(fmiComponent c, fmiBoolean* callEventUpdate);\r
+typedef fmiStatus (*fSetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+typedef fmiStatus (*fSetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+typedef fmiStatus (*fSetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+typedef fmiStatus (*fSetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+typedef fmiStatus (*fInitialize)(fmiComponent c, fmiBoolean toleranceControlled, \r
+                               fmiReal relativeTolerance, fmiEventInfo* eventInfo);\r
+typedef fmiStatus (*fGetDerivatives)    (fmiComponent c, fmiReal derivatives[]    , size_t nx);\r
+typedef fmiStatus (*fGetEventIndicators)(fmiComponent c, fmiReal eventIndicators[], size_t ni);\r
+typedef fmiStatus (*fGetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+typedef fmiStatus (*fGetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+typedef fmiStatus (*fGetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+typedef fmiStatus (*fGetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+typedef fmiStatus (*fEventUpdate)               (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo);\r
+typedef fmiStatus (*fGetContinuousStates)       (fmiComponent c, fmiReal states[], size_t nx);\r
+typedef fmiStatus (*fGetNominalContinuousStates)(fmiComponent c, fmiReal x_nominal[], size_t nx);\r
+typedef fmiStatus (*fGetStateValueReferences)   (fmiComponent c, fmiValueReference vrx[], size_t nx);\r
+typedef fmiStatus (*fTerminate)                 (fmiComponent c);    \r
+\r
+typedef struct {\r
+    ModelDescription* modelDescription;\r
+    HANDLE dllHandle;\r
+    fGetModelTypesPlatform getModelTypesPlatform;\r
+    fGetVersion getVersion;\r
+    fInstantiateModel instantiateModel;\r
+    fFreeModelInstance freeModelInstance;\r
+    fSetDebugLogging setDebugLogging;\r
+    fSetTime setTime;\r
+    fSetContinuousStates setContinuousStates;\r
+    fCompletedIntegratorStep completedIntegratorStep;\r
+    fSetReal setReal;\r
+    fSetInteger setInteger;\r
+    fSetBoolean setBoolean;\r
+    fSetString setString;\r
+    fInitialize initialize;\r
+    fGetDerivatives getDerivatives;\r
+    fGetEventIndicators getEventIndicators;\r
+    fGetReal getReal;\r
+    fGetInteger getInteger;\r
+    fGetBoolean getBoolean;\r
+    fGetString getString;\r
+    fEventUpdate eventUpdate;\r
+    fGetContinuousStates getContinuousStates;\r
+    fGetNominalContinuousStates getNominalContinuousStates;\r
+    fGetStateValueReferences getStateValueReferences;\r
+    fTerminate terminate; \r
+/*   \r
+    fInstantiateSlave instantiateSlave;\r
+    fInitializeSlave initializeSlave;\r
+    fTerminateSlave terminateSlave;\r
+    fResetSlave resetSlave;\r
+    fFreeSlaveInstance freeSlaveInstance;\r
+    fGetRealOutputDerivatives getRealOutputDerivatives;\r
+    fSetRealInputDerivatives setRealInputDerivatives;\r
+    fDoStep doStep;\r
+    fCancelStep cancelStep;\r
+    fGetStatus getStatus;\r
+    fGetRealStatus getRealStatus;\r
+    fGetIntegerStatus getIntegerStatus;\r
+    fGetBooleanStatus getBooleanStatus;\r
+    fGetStringStatus getStringStatus;\r
+*/\r
+} FMU;\r
+\r
+#endif // FMI_ME_H\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/fmusim_me/main.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/fmusim_me/main.c
new file mode 100644 (file)
index 0000000..d911fa9
--- /dev/null
@@ -0,0 +1,233 @@
+/* ------------------------------------------------------------------------- \r
+ * main.c\r
+ * Implements simulation of a single FMU instance using the forward Euler\r
+ * method for numerical integration.\r
+ * Command syntax: see printHelp()\r
+ * Simulates the given FMU from t = 0 .. tEnd with fixed step size h and \r
+ * writes the computed solution to file 'result.csv'.\r
+ * The CSV file (comma-separated values) may e.g. be plotted using \r
+ * OpenOffice Calc or Microsoft Excel. \r
+ * This progamm demonstrates basic use of an FMU.\r
+ * Real applications may use advanced numerical solvers instead, means to \r
+ * exactly locate state events in time, graphical plotting utilities, support \r
+ * for coexecution of many FMUs, stepping and debug support, user control\r
+ * of parameter and start values etc. \r
+ * All this is missing here.\r
+ *\r
+ * Revision history\r
+ *  07.02.2010 initial version released in FMU SDK 1.0\r
+ *  05.03.2010 bug fix: removed strerror(GetLastError()) from error messages\r
+ *  11.06.2010 bug fix: replaced win32 API call to OpenFile in getFmuPath \r
+ *    which restricted path length to FMU to 128 chars. New limit is MAX_PATH.\r
+ *  15.07.2010 fixed wrong label in xml parser: deault instead of default\r
+ *  13.12.2010 added check for undefined 'declared type' to xml parser\r
+ *  31.07.2011 bug fix: added missing freeModelInstance(c)\r
+ *  31.07.2011 bug fix: added missing terminate(c)\r
+ *     \r
+ * Free libraries and tools used to implement this simulator:\r
+ *  - header files from the FMU specification\r
+ *  - eXpat 2.0.1 XML parser, see http://expat.sourceforge.net\r
+ *  - 7z.exe 4.57 zip and unzip tool, see http://www.7-zip.org\r
+ * Author: Jakob Mauss\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include "fmi_me.h"\r
+#include "sim_support.h"\r
+\r
+FMU fmu; // the fmu to simulate\r
+\r
+// simulate the given FMU using the forward euler method.\r
+// time events are processed by reducing step size to exactly hit tNext.\r
+// state events are checked and fired only at the end of an Euler step. \r
+// the simulator may therefore miss state events and fires state events typically too late.\r
+static int simulate(FMU* fmu, double tEnd, double h, fmiBoolean loggingOn, char separator) {\r
+    int i, n;\r
+    double dt, tPre;\r
+    fmiBoolean timeEvent, stateEvent, stepEvent;\r
+    double time;  \r
+    int nx;                          // number of state variables\r
+    int nz;                          // number of state event indicators\r
+    double *x;                       // continuous states\r
+    double *xdot;                    // the crresponding derivatives in same order\r
+    double *z = NULL;                // state event indicators\r
+    double *prez = NULL;             // previous values of state event indicators\r
+    fmiEventInfo eventInfo;          // updated by calls to initialize and eventUpdate\r
+    ModelDescription* md;            // handle to the parsed XML file        \r
+    const char* guid;                // global unique id of the fmu\r
+    fmiCallbackFunctions callbacks;  // called by the model during simulation\r
+    fmiComponent c;                  // instance of the fmu \r
+    fmiStatus fmiFlag;               // return code of the fmu functions\r
+    fmiReal t0 = 0;                  // start time\r
+    fmiBoolean toleranceControlled = fmiFalse;\r
+    int nSteps = 0;\r
+    int nTimeEvents = 0;\r
+    int nStepEvents = 0;\r
+    int nStateEvents = 0;\r
+    FILE* file;\r
+\r
+    // instantiate the fmu\r
+    md = fmu->modelDescription;\r
+    guid = getString(md, att_guid);\r
+    callbacks.logger = fmuLogger;\r
+    callbacks.allocateMemory = calloc;\r
+    callbacks.freeMemory = free;\r
+    c = fmu->instantiateModel(getModelIdentifier(md), guid, callbacks, loggingOn);\r
+    if (!c) return error("could not instantiate model");\r
+    \r
+    // allocate memory \r
+    nx = getNumberOfStates(md);\r
+    nz = getNumberOfEventIndicators(md);\r
+    x    = (double *) calloc(nx, sizeof(double));\r
+    xdot = (double *) calloc(nx, sizeof(double));\r
+    if (nz>0) {\r
+        z    =  (double *) calloc(nz, sizeof(double));\r
+        prez =  (double *) calloc(nz, sizeof(double));\r
+    }\r
+    if (!x || !xdot || nz>0 && (!z || !prez)) return error("out of memory");\r
+\r
+    // open result file\r
+    if (!(file=fopen(RESULT_FILE, "w"))) {\r
+        printf("could not write %s because:\n", RESULT_FILE);\r
+        printf("    %s\n", strerror(errno));\r
+        return 0; // failure\r
+    }\r
+        \r
+    // set the start time and initialize\r
+    time = t0;\r
+    fmiFlag =  fmu->setTime(c, t0);\r
+    if (fmiFlag > fmiWarning) return error("could not set time");\r
+    fmiFlag =  fmu->initialize(c, toleranceControlled, t0, &eventInfo);\r
+    if (fmiFlag > fmiWarning)  return error("could not initialize model");\r
+    if (eventInfo.terminateSimulation) {\r
+        printf("model requested termination at init");\r
+        tEnd = time;\r
+    }\r
+  \r
+    // output solution for time t0\r
+    outputRow(fmu, c, t0, file, separator, TRUE);  // output column names\r
+    outputRow(fmu, c, t0, file, separator, FALSE); // output values\r
+\r
+    // enter the simulation loop\r
+    while (time < tEnd) {\r
+     // get current state and derivatives\r
+     fmiFlag = fmu->getContinuousStates(c, x, nx);\r
+     if (fmiFlag > fmiWarning) return error("could not retrieve states");\r
+     fmiFlag = fmu->getDerivatives(c, xdot, nx);\r
+     if (fmiFlag > fmiWarning) return error("could not retrieve derivatives");\r
+\r
+     // advance time\r
+     tPre = time;\r
+     time = min(time+h, tEnd);\r
+     timeEvent = eventInfo.upcomingTimeEvent && eventInfo.nextEventTime < time;     \r
+     if (timeEvent) time = eventInfo.nextEventTime;\r
+     dt = time - tPre; \r
+     fmiFlag = fmu->setTime(c, time);\r
+     if (fmiFlag > fmiWarning) error("could not set time");\r
+\r
+     // perform one step\r
+     for (i=0; i<nx; i++) x[i] += dt*xdot[i]; // forward Euler method\r
+     fmiFlag = fmu->setContinuousStates(c, x, nx);\r
+     if (fmiFlag > fmiWarning) return error("could not set states");\r
+     if (loggingOn) printf("Step %d to t=%.16g\n", nSteps, time);\r
+    \r
+     // Check for step event, e.g. dynamic state selection\r
+     fmiFlag = fmu->completedIntegratorStep(c, &stepEvent);\r
+     if (fmiFlag > fmiWarning) return error("could not complete intgrator step");\r
+\r
+     // Check for state event\r
+     for (i=0; i<nz; i++) prez[i] = z[i]; \r
+     fmiFlag = fmu->getEventIndicators(c, z, nz);\r
+     if (fmiFlag > fmiWarning) return error("could not retrieve event indicators");\r
+     stateEvent = FALSE;\r
+     for (i=0; i<nz; i++) \r
+         stateEvent = stateEvent || (prez[i] * z[i] < 0);  \r
+     \r
+     // handle events\r
+     if (timeEvent || stateEvent || stepEvent) {\r
+        \r
+        if (timeEvent) {\r
+            nTimeEvents++;\r
+            if (loggingOn) printf("time event at t=%.16g\n", time);\r
+        }\r
+        if (stateEvent) {\r
+            nStateEvents++;\r
+            if (loggingOn) for (i=0; i<nz; i++)\r
+                printf("state event %s z[%d] at t=%.16g\n", \r
+                        (prez[i]>0 && z[i]<0) ? "-\\-" : "-/-", i, time);\r
+        }\r
+        if (stepEvent) {\r
+            nStepEvents++;\r
+            if (loggingOn) printf("step event at t=%.16g\n", time);\r
+        }\r
+\r
+        // event iteration in one step, ignoring intermediate results\r
+        fmiFlag = fmu->eventUpdate(c, fmiFalse, &eventInfo);\r
+        if (fmiFlag > fmiWarning) return error("could not perform event update");\r
+        \r
+        // terminate simulation, if requested by the model\r
+        if (eventInfo.terminateSimulation) {\r
+            printf("model requested termination at t=%.16g\n", time);\r
+            break; // success\r
+        }\r
+\r
+        // check for change of value of states\r
+        if (eventInfo.stateValuesChanged && loggingOn) {\r
+            printf("state values changed at t=%.16g\n", time);\r
+        }\r
+        \r
+        // check for selection of new state variables\r
+        if (eventInfo.stateValueReferencesChanged && loggingOn) {\r
+            printf("new state variables selected at t=%.16g\n", time);\r
+        }\r
+       \r
+     } // if event\r
+     outputRow(fmu, c, time, file, separator, FALSE); // output values for this step\r
+     nSteps++;\r
+  } // while  \r
+\r
+  // cleanup\r
+  if(! eventInfo.terminateSimulation) fmu->terminate(c);\r
+  fmu->freeModelInstance(c);\r
+  fclose(file);\r
+  if (x!=NULL) free(x);\r
+  if (xdot!= NULL) free(xdot);\r
+  if (z!= NULL) free(z);\r
+  if (prez!= NULL) free(prez);\r
+\r
+  // print simulation summary \r
+  printf("Simulation from %g to %g terminated successful\n", t0, tEnd);\r
+  printf("  steps ............ %d\n", nSteps);\r
+  printf("  fixed step size .. %g\n", h);\r
+  printf("  time events ...... %d\n", nTimeEvents);\r
+  printf("  state events ..... %d\n", nStateEvents);\r
+  printf("  step events ...... %d\n", nStepEvents);\r
+\r
+  return 1; // success\r
+}\r
+\r
+int main(int argc, char *argv[]) {\r
+    const char* fmuFileName;\r
+    \r
+    // parse command line arguments and load the FMU\r
+    double tEnd = 1.0;\r
+    double h=0.1;\r
+    int loggingOn = 0;\r
+    char csv_separator = ';';\r
+    parseArguments(argc, argv, &fmuFileName, &tEnd, &h, &loggingOn, &csv_separator);\r
+    loadFMU(fmuFileName);\r
+\r
+    // run the simulation\r
+    printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c'\n", \r
+            fmuFileName, tEnd, h, loggingOn, csv_separator);\r
+    simulate(&fmu, tEnd, h, loggingOn, csv_separator);\r
+    printf("CSV file '%s' written\n", RESULT_FILE);\r
+\r
+    // release FMU \r
+    FreeLibrary(fmu.dllHandle);\r
+    freeElement(fmu.modelDescription);\r
+    return EXIT_SUCCESS;\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/include/fmiModelFunctions.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/include/fmiModelFunctions.h
new file mode 100644 (file)
index 0000000..e204772
--- /dev/null
@@ -0,0 +1,210 @@
+#ifndef fmiModelFunctions_h\r
+#define fmiModelFunctions_h\r
+\r
+/* This header file must be utilized when compiling a model.\r
+   It defines all functions of the Model Execution Interface.\r
+   In order to have unique function names even if several models\r
+   are compiled together (e.g. for embedded systems), every "real" function name\r
+   is constructed by prepending the function name by\r
+   "MODEL_IDENTIFIER" + "_" where "MODEL_IDENTIFIER" is the short name\r
+   of the model used as the name of the zip-file where the model is stored.\r
+   Therefore, the typical usage is:\r
+\r
+      #define MODEL_IDENTIFIER MyModel\r
+      #include "fmiModelFunctions.h"\r
+\r
+   As a result, a function that is defined as "fmiGetDerivatives" in this header file,\r
+   is actually getting the name "MyModel_fmiGetDerivatives".\r
+\r
+   Revisions:\r
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)\r
+                    (by M. Otter, DLR)\r
+                    Added WIN32 pragma to define the struct layout (ticket #34)\r
+                    (by J. Mauss, QTronic)\r
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize\r
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion\r
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion\r
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel\r
+                    (by J. Mauss, QTronic)\r
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).\r
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added\r
+                    meGetNominalContinuousStates (by Martin Otter, DLR)\r
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)\r
+                    (by A. Junghanns, QTronic)\r
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:\r
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform\r
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion\r
+                    meSetStates                    -> meSetContinuousStates\r
+                    meGetStates                    -> meGetContinuousStates\r
+                    removal of meInitializeModelClass\r
+                    removal of meGetTime\r
+                    change of arguments of meInstantiateModel\r
+                    change of arguments of meCompletedIntegratorStep\r
+                    (by Martin Otter, DLR):\r
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).\r
+   - March 2, 2009: Changed function definitions according to the last design\r
+                    meeting with additional improvements (by Martin Otter, DLR).\r
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).\r
+\r
+\r
+   Copyright Â© 2008-2009, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html):\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+\r
+   with the extension:\r
+\r
+   You may distribute or publicly perform any modification only under the\r
+   terms of this license.\r
+*/\r
+\r
+#include "fmiModelTypes.h"\r
+#include <stdlib.h>\r
+\r
+/* Export fmi functions on Windows */\r
+#ifdef _MSC_VER\r
+#define DllExport __declspec( dllexport )\r
+#else\r
+#define DllExport\r
+#endif\r
+\r
+/* Macros to construct the real function name\r
+   (prepend function name by MODEL_IDENTIFIER + "_") */\r
+\r
+#define fmiPaste(a,b)     a ## b\r
+#define fmiPasteB(a,b)    fmiPaste(a,b)\r
+#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)\r
+\r
+#define fmiGetModelTypesPlatform      fmiFullName(_fmiGetModelTypesPlatform)\r
+#define fmiGetVersion                 fmiFullName(_fmiGetVersion)\r
+#define fmiInstantiateModel           fmiFullName(_fmiInstantiateModel)\r
+#define fmiFreeModelInstance          fmiFullName(_fmiFreeModelInstance)\r
+#define fmiSetDebugLogging            fmiFullName(_fmiSetDebugLogging)\r
+#define fmiSetTime                    fmiFullName(_fmiSetTime)\r
+#define fmiSetContinuousStates        fmiFullName(_fmiSetContinuousStates)\r
+#define fmiCompletedIntegratorStep    fmiFullName(_fmiCompletedIntegratorStep)\r
+#define fmiSetReal                    fmiFullName(_fmiSetReal)\r
+#define fmiSetInteger                 fmiFullName(_fmiSetInteger)\r
+#define fmiSetBoolean                 fmiFullName(_fmiSetBoolean)\r
+#define fmiSetString                  fmiFullName(_fmiSetString)\r
+#define fmiInitialize                 fmiFullName(_fmiInitialize)\r
+#define fmiGetDerivatives             fmiFullName(_fmiGetDerivatives)\r
+#define fmiGetEventIndicators         fmiFullName(_fmiGetEventIndicators)\r
+#define fmiGetReal                    fmiFullName(_fmiGetReal)\r
+#define fmiGetInteger                 fmiFullName(_fmiGetInteger)\r
+#define fmiGetBoolean                 fmiFullName(_fmiGetBoolean)\r
+#define fmiGetString                  fmiFullName(_fmiGetString)\r
+#define fmiEventUpdate                fmiFullName(_fmiEventUpdate)\r
+#define fmiGetContinuousStates        fmiFullName(_fmiGetContinuousStates)\r
+#define fmiGetNominalContinuousStates fmiFullName(_fmiGetNominalContinuousStates)\r
+#define fmiGetStateValueReferences    fmiFullName(_fmiGetStateValueReferences)\r
+#define fmiTerminate                  fmiFullName(_fmiTerminate)\r
+\r
+\r
+/* Version number */\r
+#define fmiVersion "1.0"\r
+\r
+/* Inquire version numbers of header files */\r
+   DllExport const char* fmiGetModelTypesPlatform();\r
+   DllExport const char* fmiGetVersion();\r
+\r
+/* make sure all compiler use the same alignment policies for structures */\r
+#ifdef WIN32\r
+#pragma pack(push,8)\r
+#endif\r
+\r
+/* Type definitions */\r
+   typedef enum  {fmiOK,\r
+                  fmiWarning,\r
+                  fmiDiscard,\r
+                  fmiError,\r
+                  fmiFatal} fmiStatus;\r
+\r
+   typedef void  (*fmiCallbackLogger)        (fmiComponent c, fmiString instanceName, fmiStatus status,\r
+                                              fmiString category, fmiString message, ...);\r
+   typedef void* (*fmiCallbackAllocateMemory)(size_t nobj, size_t size);\r
+   typedef void  (*fmiCallbackFreeMemory)    (void* obj);\r
+\r
+   typedef struct {\r
+     fmiCallbackLogger         logger;\r
+     fmiCallbackAllocateMemory allocateMemory;\r
+     fmiCallbackFreeMemory     freeMemory;\r
+   } fmiCallbackFunctions;\r
+\r
+   typedef struct {\r
+      fmiBoolean iterationConverged;\r
+      fmiBoolean stateValueReferencesChanged;\r
+      fmiBoolean stateValuesChanged;\r
+      fmiBoolean terminateSimulation;\r
+      fmiBoolean upcomingTimeEvent;\r
+      fmiReal    nextEventTime;\r
+   } fmiEventInfo;\r
+\r
+/* reset alignment policy to the one set before reading this file */\r
+#ifdef WIN32\r
+#pragma pack(pop)\r
+#endif\r
+\r
+/* Creation and destruction of model instances and setting debug status */\r
+   DllExport fmiComponent fmiInstantiateModel (fmiString            instanceName,\r
+                                               fmiString            GUID,\r
+                                               fmiCallbackFunctions functions,\r
+                                               fmiBoolean           loggingOn);\r
+   DllExport void      fmiFreeModelInstance(fmiComponent c);\r
+   DllExport fmiStatus fmiSetDebugLogging  (fmiComponent c, fmiBoolean loggingOn);\r
+\r
+\r
+/* Providing independent variables and re-initialization of caching */\r
+   DllExport fmiStatus fmiSetTime                (fmiComponent c, fmiReal time);\r
+   DllExport fmiStatus fmiSetContinuousStates    (fmiComponent c, const fmiReal x[], size_t nx);\r
+   DllExport fmiStatus fmiCompletedIntegratorStep(fmiComponent c, fmiBoolean* callEventUpdate);\r
+   DllExport fmiStatus fmiSetReal                (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+   DllExport fmiStatus fmiSetInteger             (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+   DllExport fmiStatus fmiSetBoolean             (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+   DllExport fmiStatus fmiSetString              (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+\r
+\r
+/* Evaluation of the model equations */\r
+   DllExport fmiStatus fmiInitialize(fmiComponent c, fmiBoolean toleranceControlled,\r
+                                     fmiReal relativeTolerance, fmiEventInfo* eventInfo);\r
+\r
+   DllExport fmiStatus fmiGetDerivatives    (fmiComponent c, fmiReal derivatives[]    , size_t nx);\r
+   DllExport fmiStatus fmiGetEventIndicators(fmiComponent c, fmiReal eventIndicators[], size_t ni);\r
+\r
+   DllExport fmiStatus fmiGetReal   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+   DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+   DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+   DllExport fmiStatus fmiGetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+\r
+   DllExport fmiStatus fmiEventUpdate               (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo);\r
+   DllExport fmiStatus fmiGetContinuousStates       (fmiComponent c, fmiReal states[], size_t nx);\r
+   DllExport fmiStatus fmiGetNominalContinuousStates(fmiComponent c, fmiReal x_nominal[], size_t nx);\r
+   DllExport fmiStatus fmiGetStateValueReferences   (fmiComponent c, fmiValueReference vrx[], size_t nx);\r
+   DllExport fmiStatus fmiTerminate                 (fmiComponent c);\r
+\r
+#endif // fmiModelFunctions_h\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/include/fmiModelTypes.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/model_exchange/include/fmiModelTypes.h
new file mode 100644 (file)
index 0000000..17e9e30
--- /dev/null
@@ -0,0 +1,91 @@
+#ifndef fmiModelTypes_h\r
+#define fmiModelTypes_h\r
+\r
+/* Standard header file to define the argument types of the\r
+   functions of the Model Execution Interface.\r
+   This header file must be utilized both by the model and\r
+   by the simulation engine.\r
+\r
+   Revisions:\r
+   - Jan.  4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)\r
+   - Dec. 21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"\r
+                    according to meeting on Dec. 18 (by Martin Otter, DLR)\r
+   - Dec.  6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)\r
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:\r
+                    Changed "version" to "platform", "standard" to "standard32",\r
+                    Added a precise definition of "standard32" as comment\r
+                    (by Martin Otter, DLR)\r
+   - July 19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,\r
+                    and changed meValueReferenced from int to unsigned int\r
+                    (by Martin Otter, DLR).\r
+   - March 2, 2009: Moved enums and function pointer definitions to\r
+                    ModelFunctions.h (by Martin Otter, DLR).\r
+   - Dec. 3, 2008 : First version by Martin Otter (DLR) and\r
+                    Hans Olsson (Dynasim).\r
+\r
+\r
+   Copyright Â© 2008-2010, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html)\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+\r
+   with the extension:\r
+\r
+   You may distribute or publicly perform any modification only under the\r
+   terms of this license.\r
+*/\r
+\r
+/* Platform (combination of machine, compiler, operating system) */\r
+#define fmiModelTypesPlatform "standard32"\r
+\r
+/* Type definitions of variables passed as arguments\r
+   Version "standard32" means:\r
+\r
+   fmiComponent     : 32 bit pointer\r
+   fmiValueReference: 32 bit\r
+   fmiReal          : 64 bit\r
+   fmiInteger       : 32 bit\r
+   fmiBoolean       :  8 bit\r
+   fmiString        : 32 bit pointer\r
+\r
+*/\r
+   typedef void*        fmiComponent;\r
+   typedef unsigned int fmiValueReference;\r
+   typedef double       fmiReal   ;\r
+   typedef int          fmiInteger;\r
+   typedef char         fmiBoolean;\r
+   typedef const char*  fmiString ;\r
+\r
+/* Values for fmiBoolean  */\r
+#define fmiTrue  1\r
+#define fmiFalse 0\r
+\r
+/* Undefined value for fmiValueReference (largest unsigned int value) */\r
+#define fmiUndefinedValueReference (fmiValueReference)(-1)\r
+\r
+#endif\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/_main.html
new file mode 100644 (file)
index 0000000..fff15c6
--- /dev/null
@@ -0,0 +1,52 @@
+<html>\r
+<head>\r
+    <title>Documentation for bouncingBall.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+<h1>bouncingBall.fmu</h1>\r
+The bouncingBall implements the following equation: \r
+<ul>\r
+<li> der(h) = v;\r
+<li> der(v) = -g;\r
+<li> when h<0 then v := -e* v\r
+</ul>\r
+with start values h=1, e=0.7, g = 9.81 and\r
+<ul>\r
+<li> h: height [m], used as state\r
+<li> v: velocity of ball [m/s], used as state\r
+<li> der(h): velocity of ball [m/s]\r
+<li> der(v): acceleration of ball [m/s2]\r
+<li> g: acceleration of gravity [m/s2], a parameter\r
+<li> e: a dimensionless parameter\r
+</ul>\r
+\r
+<br>\r
+<img src="plot_h.png">\r
+<br>\r
+The figure shows the solution computed with Silver \r
+for height h of the ball for the start values given above.\r
+\r
+<p>\r
+The chain of events during simulation is as follows\r
+<ol>\r
+<li> intitially h>0 and pos(0)=true </li>\r
+<li> continuous integration until a state event is detected, i.e.\r
+     until h + EPS_INDICATORS = 0.\r
+     At this time h < 0, the EPS_INDICATORS adds hysteresis.</li>\r
+<li> the simulator calls eventUpdate once which reverses the speed direction\r
+     v of the ball: v = -e * v, and sets pos(0)=false</li>\r
+<li> continuous integration until state event is detected, i.e.\r
+     until h - EPS_INDICATORS = 0.\r
+     At this time h > 0, the EPS_INDICATORS adds hysteresis.</li>\r
+<li> the simulator calls  eventUpdate once more which sets pos(0)=true.</li>\r
+<li> goto 2</li>\r
+</ol>\r
+The above description refers to the variables used \r
+in file <code>bouncingBall.c</code>.\r
+\r
+</body>\r
+</html>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/bouncingBall.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/bouncingBall.c
new file mode 100644 (file)
index 0000000..7f6c303
--- /dev/null
@@ -0,0 +1,103 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU - a bouncing ball. \r
+ * This demonstrates the use of state events and reinit of states.\r
+ * Equations:\r
+ *  der(h) = v;\r
+ *  der(v) = -g;\r
+ *  when h<0 then v := -e * v;  \r
+ *  where\r
+ *    h      height [m], used as state, start = 1\r
+ *    v      velocity of ball [m/s], used as state\r
+ *    der(h) velocity of ball [m/s] \r
+ *    der(v) acceleration of ball [m/s2] \r
+ *    g      acceleration of gravity [m/s2], a parameter, start = 9.81 \r
+ *    e      a dimensionless parameter, start = 0.7\r
+ *    \r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER bouncingBall\r
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f003}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 5\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_STATES 2\r
+#define NUMBER_OF_EVENT_INDICATORS 1\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define h_      0\r
+#define der_h_  1\r
+#define v_      2\r
+#define der_v_  3\r
+#define g_      3 // negated alias\r
+#define e_      4\r
+\r
+// define initial state vector as vector of value references\r
+#define STATES { h_, v_ }\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    r(h_)     =  1;\r
+    r(v_)     =  0;\r
+    r(der_v_) = -9.81;\r
+    r(e_)     =  0.7;\r
+    pos(0) = r(h_) > 0;\r
+}\r
+\r
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives\r
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){\r
+    switch (vr) {\r
+        case h_     : return r(h_);\r
+        case der_h_ : return r(v_);\r
+        case v_     : return r(v_);\r
+        case der_v_ : return r(der_v_);\r
+        case e_     : return r(e_);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+// offset for event indicator, adds hysteresis and prevents z=0 at restart \r
+#define EPS_INDICATORS 1e-14\r
+\r
+fmiReal getEventIndicator(ModelInstance* comp, int z) {\r
+    switch (z) {\r
+        case 0 : return r(h_) + (pos(0) ? EPS_INDICATORS : -EPS_INDICATORS);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    if (pos(0)) {\r
+        r(v_) = - r(e_) * r(v_);\r
+    }\r
+    pos(0) = r(h_) > 0;\r
+    eventInfo->iterationConverged  = fmiTrue;\r
+    eventInfo->stateValueReferencesChanged = fmiFalse;\r
+    eventInfo->stateValuesChanged  = fmiTrue;\r
+    eventInfo->terminateSimulation = fmiFalse;\r
+    eventInfo->upcomingTimeEvent   = fmiFalse;\r
+ } \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/modelDescription.xml
new file mode 100644 (file)
index 0000000..4cb345e
--- /dev/null
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="bouncingBall"\r
+  modelIdentifier="bouncingBall"\r
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f003}"\r
+  numberOfContinuousStates="2"\r
+  numberOfEventIndicators="1">\r
+<ModelVariables>\r
+  <ScalarVariable name="h" valueReference="0" description="height, used as state">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(h)" valueReference="1" description="velocity of ball">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="v" valueReference="2" description="velocity of ball, used as state">\r
+     <Real/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(v)" valueReference="3" description="acceleration of ball">\r
+     <Real/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="g" valueReference="3" description="acceleration of gravity" \r
+                  variability="parameter" alias="negatedAlias">\r
+     <Real start="9.81" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="e" valueReference="4" description="dimensionless parameter" \r
+                  variability="parameter">\r
+     <Real start="0.7" fixed="true"/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/plot_h.PNG b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/plot_h.PNG
new file mode 100644 (file)
index 0000000..ced85c4
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/bouncingBall/plot_h.PNG differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/build_fmu.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/build_fmu.bat
new file mode 100644 (file)
index 0000000..9d01458
--- /dev/null
@@ -0,0 +1,80 @@
+@echo off \r
+rem ------------------------------------------------------------\r
+rem This batch builds an FMU of the FMU SDK\r
+rem Usage: build_fmu (me|cs) <fmu_dir_name> \r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+echo -----------------------------------------------------------\r
+if %1==cs (^\r
+echo building FMU %2 - FMI for Co-Simulation 1.0) else ^\r
+echo building FMU %2 - FMI for Model Exchange 1.0\r
+\r
+rem save env variable settings\r
+set PREV_PATH=%PATH%\r
+if defined INCLUDE set PREV_INCLUDE=%INLUDE%\r
+if defined LIB     set PREV_LIB=%LIB%\r
+if defined LIBPATH set PREV_LIBPATH=%LIBPATH%\r
+\r
+rem setup the compiler\r
+if defined VS90COMNTOOLS (call "%VS90COMNTOOLS%\vsvars32.bat") else ^\r
+if defined VS80COMNTOOLS (call "%VS80COMNTOOLS%\vsvars32.bat") else ^\r
+goto noCompiler\r
+\r
+rem create the %2.dll in the temp dir\r
+if not exist temp mkdir temp \r
+pushd temp\r
+if exist *.dll del /Q *.dll\r
+\r
+rem /wd4090 disables warnings about different 'const' qualifiers\r
+if %1==cs (set FMI_DIR=co_simulation) else set FMI_DIR=model_exchange\r
+if %1==cs (set DEF=/DFMI_COSIMULATION) else set DEF=\r
+cl /LD /wd4090 /nologo %DEF% ..\%2\%2.c /I ..\. /I ..\..\%FMI_DIR%\include\r
+if not exist %2.dll goto compileError\r
+\r
+rem create FMU dir structure with root 'fmu'\r
+set BIN_DIR=fmu\binaries\win32\r
+set SRC_DIR=fmu\sources\r
+set DOC_DIR=fmu\documentation\r
+if not exist %BIN_DIR% mkdir %BIN_DIR%\r
+if not exist %SRC_DIR% mkdir %SRC_DIR%\r
+if not exist %DOC_DIR% mkdir %DOC_DIR%\r
+move /Y %2.dll %BIN_DIR%\r
+if exist ..\%2\*~ del /Q ..\%2\*~\r
+copy ..\%2\%2.c %SRC_DIR% \r
+type ..\%2\modelDescription.xml ..\%1.xml > fmu\modelDescription.xml\r
+copy ..\%2\model.png fmu\r
+copy ..\fmuTemplate.c %SRC_DIR%\r
+copy ..\fmuTemplate.h %SRC_DIR%\r
+copy ..\%2\*.html %DOC_DIR%\r
+copy ..\%2\*.png  %DOC_DIR%\r
+del %DOC_DIR%\model.png \r
+\r
+rem zip the directory tree and move to fmu directory \r
+cd fmu\r
+set FMU_FILE=..\..\..\..\fmu\%1\%2.fmu\r
+if exist %ZIP_FILE% del %FMU_FILE%\r
+..\..\..\..\bin\7z.exe a -tzip -xr!.svn %FMU_FILE% ^\r
+  modelDescription.xml model.png binaries sources documentation\r
+goto cleanup\r
+\r
+:noCompiler\r
+echo No Microsoft Visual C compiler found\r
+exit\r
+\r
+:compileError\r
+echo build of %2 failed\r
+\r
+:cleanup\r
+popd\r
+if exist temp rmdir /S /Q temp\r
+\r
+rem undo variable settings performed by vsvars32.bat\r
+set PATH=%PREV_PATH%\r
+if defined PREV_INCLUDE set INCLUDE=%PREV_INLUDE%\r
+if defined PREV_LIB     set LIB=%PREV_LIB%\r
+if defined PREV_LIBPATH set LIBPATH=%PREV_LIBPATH%\r
+echo done.\r
+\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/cs.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/cs.xml
new file mode 100644 (file)
index 0000000..9e38bc4
--- /dev/null
@@ -0,0 +1,8 @@
+<Implementation>\r
+  <CoSimulation_StandAlone>\r
+    <Capabilities\r
+      canHandleVariableCommunicationStepSize="true"\r
+      canHandleEvents="true"/>\r
+  </CoSimulation_StandAlone>\r
+</Implementation>\r
+</fmiModelDescription>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/_main.html
new file mode 100644 (file)
index 0000000..f981d0f
--- /dev/null
@@ -0,0 +1,29 @@
+<html>\r
+<head>\r
+<title>Documentation for dq.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+<h1>dq.fmu</h1>\r
+This FMU implements the equation \r
+<ul>\r
+<li> der(x) = -k * x </li>\r
+</ul>\r
+The analytical solution of this system is \r
+<ul>\r
+<li> x(t) = exp(-k*t) </li>\r
+</ul>\r
+The above equation is also known as \r
+<a href="http://en.wikipedia.org/wiki/Germund_Dahlquist" target="_blank">Dahlquist</a> \r
+test equation.\r
+<br/>\r
+<img src="plot_x.png">\r
+<br/>\r
+The figure shows the solution for x computed with Silver \r
+for start values k = 1 and x = 1.\r
+</body>\r
+</html>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/dq.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/dq.c
new file mode 100644 (file)
index 0000000..bb8df47
--- /dev/null
@@ -0,0 +1,67 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU - the Dahlquist test equation. \r
+ *\r
+ *   der(x) = - k * x and x(0) = 1. \r
+ *   Analytical solution: x(t) = exp(-k*t).\r
+ *\r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER dq\r
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f000}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 3\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_STATES 1\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define x_     0\r
+#define der_x_ 1\r
+#define k_     2\r
+\r
+// define state vector as vector of value references\r
+#define STATES { x_ }\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    r(x_) = 1;\r
+    r(k_) = 1;\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives\r
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){\r
+    switch (vr) {\r
+        case x_     : return r(x_);\r
+        case der_x_ : return - r(k_) * r(x_);\r
+        case k_     : return r(k_);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// Used to set the next time event, if any.\r
+void eventUpdate(fmiComponent comp, fmiEventInfo* eventInfo) {\r
+} \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/modelDescription.xml
new file mode 100644 (file)
index 0000000..daf9fbf
--- /dev/null
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="dq"\r
+  modelIdentifier="dq"\r
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f000}"\r
+  numberOfContinuousStates="1"\r
+  numberOfEventIndicators="0">\r
+<ModelVariables>\r
+  <ScalarVariable name="x" valueReference="0" description="the only state">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(x)" valueReference="1">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="k" valueReference="2" variability="parameter">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/plot_x.PNG b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/plot_x.PNG
new file mode 100644 (file)
index 0000000..b28fa66
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/dq/plot_x.PNG differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/fmuTemplate.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/fmuTemplate.c
new file mode 100644 (file)
index 0000000..e64b47e
--- /dev/null
@@ -0,0 +1,765 @@
+/* ---------------------------------------------------------------------------*\r
+ * Implementation of the FMI interface based on functions and macros to\r
+ * be defined by the includer of this file. \r
+ * If FMI_COSIMULATION is defined, this implements "FMI for Co-Simulation 1.0",\r
+ * otherwise "FMI for Model Exchange 1.0".\r
+ * The "FMI for Co-Simulation 1.0", implementation assumes that exactly the \r
+ * following capability flags are set to fmiTrue:\r
+ *    canHandleVariableCommunicationStepSize, i.e. fmiDoStep step size can vary\r
+ *    canHandleEvents, i.e. fmiDoStep step size can be zero\r
+ * and all other capability flags are set to default, i.e. to fmiFalse or 0.\r
+ *\r
+ * Revision history\r
+ *  07.02.2010 initial version for "Model Exchange 1.0" released in FMU SDK 1.0\r
+ *  05.03.2010 bug fix: fmiSetString now copies the passed string argument\r
+ *     and fmiFreeModelInstance frees all string copies\r
+ *  11.12.2010 replaced calloc by functions.allocateMemory in fmiInstantiateModel\r
+ *  04.08.2011 added support for "FMI for Co-Simulation 1.0"\r
+ *  \r
+ * (c) 2011 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// array of value references of states\r
+#if NUMBER_OF_REALS>0\r
+fmiValueReference vrStates[NUMBER_OF_STATES] = STATES; \r
+#endif\r
+\r
+// ---------------------------------------------------------------------------\r
+// Private helpers used below to validate function arguments\r
+// ---------------------------------------------------------------------------\r
+\r
+static fmiBoolean invalidNumber(ModelInstance* comp, const char* f, const char* arg, int n, int nExpected){\r
+    if (n != nExpected) {\r
+        comp->state = modelError;\r
+        comp->functions.logger(comp, comp->instanceName, fmiError, "error", \r
+                "%s: Invalid argument %s = %d. Expected %d.", f, arg, n, nExpected);\r
+        return fmiTrue;\r
+    }\r
+    return fmiFalse;\r
+}\r
+\r
+static fmiBoolean invalidState(ModelInstance* comp, const char* f, int statesExpected){\r
+    if (!comp) \r
+        return fmiTrue;\r
+    if (!(comp->state & statesExpected)) {\r
+        comp->state = modelError;\r
+        comp->functions.logger(comp, comp->instanceName, fmiError, "error", \r
+                "%s: Illegal call sequence.", f);\r
+        return fmiTrue;\r
+    }\r
+    return fmiFalse;\r
+}\r
+\r
+static fmiBoolean nullPointer(ModelInstance* comp, const char* f, const char* arg, const void* p){\r
+    if (!p) {\r
+        comp->state = modelError;\r
+        comp->functions.logger(comp, comp->instanceName, fmiError, "error", \r
+                "%s: Invalid argument %s = NULL.", f, arg);\r
+        return fmiTrue;\r
+    }\r
+    return fmiFalse;\r
+}\r
+\r
+static fmiBoolean vrOutOfRange(ModelInstance* comp, const char* f, fmiValueReference vr, int end) {\r
+    if (vr >= end) {\r
+        comp->functions.logger(comp, comp->instanceName, fmiError, "error",\r
+                "%s: Illegal value reference %u.", f, vr);\r
+        comp->state = fmiError;\r
+        return fmiTrue;\r
+    }\r
+    return fmiFalse;\r
+}  \r
+\r
+// ---------------------------------------------------------------------------\r
+// Private helpers used below to implement functions\r
+// ---------------------------------------------------------------------------\r
+\r
+fmiStatus setString(fmiComponent comp, fmiValueReference vr, fmiString value){\r
+    return fmiSetString(comp, &vr, 1, &value);\r
+}\r
+\r
+// fname is fmiInstantiateModel or fmiInstantiateSlave\r
+static fmiComponent instantiateModel(char* fname, fmiString instanceName, fmiString GUID, \r
+        fmiCallbackFunctions functions, fmiBoolean loggingOn) {\r
+    ModelInstance* comp;\r
+    if (!functions.logger) \r
+        return NULL;\r
+    if (!functions.allocateMemory || !functions.freeMemory){ \r
+        functions.logger(NULL, instanceName, fmiError, "error", \r
+                "%s: Missing callback function.", fname);\r
+        return NULL;\r
+    }\r
+    if (!instanceName || strlen(instanceName)==0) { \r
+        functions.logger(NULL, instanceName, fmiError, "error", \r
+                "%s: Missing instance name.", fname);\r
+        return NULL;\r
+    }\r
+    if (strcmp(GUID, MODEL_GUID)) {\r
+        functions.logger(NULL, instanceName, fmiError, "error", \r
+                "%s: Wrong GUID %s. Expected %s.", fname, GUID, MODEL_GUID);\r
+        return NULL;\r
+    }\r
+    comp = (ModelInstance *)functions.allocateMemory(1, sizeof(ModelInstance));\r
+    if (comp) {\r
+        comp->r = functions.allocateMemory(NUMBER_OF_REALS,    sizeof(fmiReal));\r
+        comp->i = functions.allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmiInteger));\r
+        comp->b = functions.allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmiBoolean));\r
+        comp->s = functions.allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmiString));\r
+        comp->isPositive = functions.allocateMemory(NUMBER_OF_EVENT_INDICATORS, sizeof(fmiBoolean));\r
+    }\r
+    if (!comp || !comp->r || !comp->i || !comp->b || !comp->s || !comp->isPositive) {\r
+        functions.logger(NULL, instanceName, fmiError, "error", \r
+                "%s: Out of memory.", fname);\r
+        return NULL;\r
+    }\r
+    if (comp->loggingOn) comp->functions.logger(NULL, instanceName, fmiOK, "log", \r
+            "%s: GUID=%s", fname, GUID);\r
+    comp->instanceName = instanceName;\r
+    comp->GUID = GUID;\r
+    comp->functions = functions;\r
+    comp->loggingOn = loggingOn;\r
+    comp->state = modelInstantiated;\r
+    setStartValues(comp); // to be implemented by the includer of this file\r
+    return comp;\r
+}\r
+\r
+// fname is fmiInitialize or fmiInitializeSlave\r
+static fmiStatus init(char* fname, fmiComponent c, fmiBoolean toleranceControlled, fmiReal relativeTolerance,\r
+    fmiEventInfo* eventInfo) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, fname, modelInstantiated))\r
+         return fmiError;\r
+    if (nullPointer(comp, fname, "eventInfo", eventInfo))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+        "%s: toleranceControlled=%d relativeTolerance=%g", \r
+        fname, toleranceControlled, relativeTolerance);\r
+    eventInfo->iterationConverged  = fmiTrue;\r
+    eventInfo->stateValueReferencesChanged = fmiFalse;\r
+    eventInfo->stateValuesChanged  = fmiFalse;\r
+    eventInfo->terminateSimulation = fmiFalse;\r
+    eventInfo->upcomingTimeEvent   = fmiFalse;\r
+    initialize(comp, eventInfo); // to be implemented by the includer of this file\r
+    comp->state = modelInitialized;\r
+    return fmiOK;\r
+}\r
+\r
+// fname is fmiTerminate or fmiTerminateSlave\r
+static fmiStatus terminate(char* fname, fmiComponent c){\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, fname, modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", fname);\r
+    comp->state = modelTerminated;\r
+    return fmiOK;\r
+}\r
+\r
+// fname is freeModelInstance of freeSlaveInstance\r
+void freeInstance(char* fname, fmiComponent c) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (!comp) return;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", fname);\r
+    if (comp->r) comp->functions.freeMemory(comp->r);\r
+    if (comp->i) comp->functions.freeMemory(comp->i);\r
+    if (comp->b) comp->functions.freeMemory(comp->b);\r
+    if (comp->s) {\r
+        int i;\r
+        for (i=0; i<NUMBER_OF_STRINGS; i++){\r
+            if (comp->s[i]) comp->functions.freeMemory(comp->s[i]);\r
+        }\r
+        comp->functions.freeMemory(comp->s);\r
+    }\r
+    comp->functions.freeMemory(comp);\r
+}\r
+\r
+// ---------------------------------------------------------------------------\r
+// FMI functions: class methods not depending of a specific model instance\r
+// ---------------------------------------------------------------------------\r
+\r
+const char* fmiGetVersion() {\r
+    return fmiVersion;\r
+}\r
+\r
+// ---------------------------------------------------------------------------\r
+// FMI functions: for FMI Model Exchange 1.0 and for FMI Co-Simulation 1.0\r
+// logging control, setters and getters for Real, Integer, Boolean, String\r
+// ---------------------------------------------------------------------------\r
+\r
+fmiStatus fmiSetDebugLogging(fmiComponent c, fmiBoolean loggingOn) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetDebugLogging", not_modelError))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetDebugLogging: loggingOn=%d", loggingOn);\r
+    comp->loggingOn = loggingOn;\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetReal", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetReal", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetReal", "value[]", value))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetReal: nvr = %d", nvr);\r
+    // no check wether setting the value is allowed in the current state\r
+    for (i=0; i<nvr; i++) {\r
+       if (vrOutOfRange(comp, "fmiSetReal", vr[i], NUMBER_OF_REALS))\r
+           return fmiError;\r
+       if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetReal: #r%d# = %.16g", vr[i], value[i]);\r
+       comp->r[vr[i]] = value[i];\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetInteger", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetInteger", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetInteger", "value[]", value))\r
+         return fmiError;\r
+    if (comp->loggingOn)\r
+        comp->functions.logger(c, comp->instanceName, fmiOK, "log", "fmiSetInteger: nvr = %d",  nvr);\r
+    for (i=0; i<nvr; i++) {\r
+       if (vrOutOfRange(comp, "fmiSetInteger", vr[i], NUMBER_OF_INTEGERS))\r
+           return fmiError;\r
+       if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetInteger: #i%d# = %d", vr[i], value[i]);\r
+        comp->i[vr[i]] = value[i]; \r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetBoolean", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetBoolean", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetBoolean", "value[]", value))\r
+         return fmiError;\r
+    if (comp->loggingOn)\r
+        comp->functions.logger(c, comp->instanceName, fmiOK, "log", "fmiSetBoolean: nvr = %d",  nvr);\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiSetBoolean", vr[i], NUMBER_OF_BOOLEANS))\r
+            return fmiError;\r
+       if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetBoolean: #b%d# = %s", vr[i], value[i] ? "true" : "false");\r
+        comp->b[vr[i]] = value[i]; \r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]){\r
+    int i, n;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetString", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetString", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetString", "value[]", value))\r
+         return fmiError;\r
+    if (comp->loggingOn)\r
+        comp->functions.logger(c, comp->instanceName, fmiOK, "log", "fmiSetString: nvr = %d",  nvr);\r
+    for (i=0; i<nvr; i++) {\r
+        char* string = comp->s[vr[i]];\r
+        if (vrOutOfRange(comp, "fmiSetString", vr[i], NUMBER_OF_STRINGS))\r
+            return fmiError;\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetString: #s%d# = '%s'", vr[i], value[i]);\r
+        if (nullPointer(comp, "fmiSetString", "value[i]", value[i]))\r
+            return fmiError;\r
+        if (string==NULL || strlen(string) < strlen(value[i])) {\r
+            if (string) comp->functions.freeMemory(string);\r
+            comp->s[vr[i]] = comp->functions.allocateMemory(1+strlen(value[i]), sizeof(char));\r
+            if (!comp->s[vr[i]]) {\r
+                comp->state = modelError;\r
+                comp->functions.logger(NULL, comp->instanceName, fmiError, "error", "fmiSetString: Out of memory.");\r
+                return fmiError;\r
+            }\r
+        }\r
+        strcpy(comp->s[vr[i]], value[i]);\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetReal", not_modelError))\r
+        return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetReal", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetReal", "value[]", value))\r
+         return fmiError;\r
+#if NUMBER_OF_REALS>0\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiGetReal", vr[i], NUMBER_OF_REALS)) \r
+            return fmiError;\r
+        value[i] = getReal(comp, vr[i]); // to be implemented by the includer of this file\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiGetReal: #r%u# = %.16g", vr[i], value[i]);\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetInteger", not_modelError))\r
+        return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetInteger", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetInteger", "value[]", value))\r
+         return fmiError;\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiGetInteger", vr[i], NUMBER_OF_INTEGERS))\r
+           return fmiError;\r
+        value[i] = comp->i[vr[i]];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiGetInteger: #i%u# = %d", vr[i], value[i]);\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetBoolean", not_modelError))\r
+        return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetBoolean", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetBoolean", "value[]", value))\r
+         return fmiError;\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiGetBoolean", vr[i], NUMBER_OF_BOOLEANS))\r
+           return fmiError;\r
+        value[i] = comp->b[vr[i]];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiGetBoolean: #b%u# = %s", vr[i], value[i]? "true" : "false");\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetString", not_modelError))\r
+        return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetString", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetString", "value[]", value))\r
+         return fmiError;\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiGetString", vr[i], NUMBER_OF_STRINGS))\r
+           return fmiError;\r
+        value[i] = comp->s[vr[i]];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiGetString: #s%u# = '%s'", vr[i], value[i]);\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+#ifdef FMI_COSIMULATION\r
+// ---------------------------------------------------------------------------\r
+// FMI functions: only for FMI Co-Simulation 1.0\r
+// ---------------------------------------------------------------------------\r
+\r
+const char* fmiGetTypesPlatform() {\r
+    return fmiPlatform;\r
+}\r
+\r
+fmiComponent fmiInstantiateSlave(fmiString  instanceName, fmiString  GUID,\r
+    fmiString  fmuLocation, fmiString  mimeType, fmiReal timeout, fmiBoolean visible,\r
+    fmiBoolean interactive, fmiCallbackFunctions functions, fmiBoolean loggingOn) {\r
+    // ignoring arguments: fmuLocation, mimeType, timeout, visible, interactive\r
+    return instantiateModel("fmiInstantiateSlave", instanceName, GUID, functions, loggingOn);\r
+}\r
+\r
+fmiStatus fmiInitializeSlave(fmiComponent c, fmiReal tStart, fmiBoolean StopTimeDefined, fmiReal tStop) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiBoolean toleranceControlled = fmiFalse;\r
+    fmiReal relativeTolerance = 0;\r
+    fmiStatus flag = fmiOK;\r
+    comp->eventInfo.iterationConverged = 0;\r
+    while (flag==fmiOK && !comp->eventInfo.iterationConverged) {\r
+        // ignoring arguments: tStart, StopTimeDefined, tStop\r
+        flag = init("fmiInitializeSlave", c, toleranceControlled, relativeTolerance, &comp->eventInfo);\r
+    }\r
+    return flag;\r
+}\r
+\r
+fmiStatus fmiTerminateSlave(fmiComponent c) {\r
+    return terminate("fmiTerminateSlave", c);\r
+}\r
+\r
+fmiStatus fmiResetSlave(fmiComponent c) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiResetSlave", modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", "fmiResetSlave");\r
+    comp->state = modelInstantiated;\r
+    setStartValues(comp); // to be implemented by the includer of this file\r
+    return fmiOK;\r
+}\r
+\r
+void fmiFreeSlaveInstance(fmiComponent c) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiFreeSlaveInstance", modelTerminated))\r
+         return;\r
+    freeInstance("fmiFreeSlaveInstance", c);\r
+}\r
+\r
+fmiStatus fmiSetRealInputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t nvr,\r
+    const fmiInteger order[], const fmiReal value[]) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    if (invalidState(comp, "fmiSetRealInputDerivatives", modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "fmiSetRealInputDerivatives: nvr= %d", nvr);\r
+    log(NULL, comp->instanceName, fmiError, "warning", "fmiSetRealInputDerivatives: ignoring function call." \r
+      " This model cannot interpolate inputs: canInterpolateInputs=\"fmiFalse\"");\r
+    return fmiWarning;\r
+}\r
+\r
+fmiStatus fmiGetRealOutputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t  nvr,\r
+    const fmiInteger order[], fmiReal value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    if (invalidState(comp, "fmiGetRealOutputDerivatives", modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "fmiGetRealOutputDerivatives: nvr= %d", nvr);\r
+    log(NULL, comp->instanceName, fmiError, "warning", "fmiGetRealOutputDerivatives: ignoring function call." \r
+      " This model cannot compute derivatives of outputs: MaxOutputDerivativeOrder=\"0\"");\r
+    for (i=0; i<nvr; i++) value[i] = 0;\r
+    return fmiWarning;\r
+}\r
+\r
+fmiStatus fmiCancelStep(fmiComponent c) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    if (invalidState(comp, "fmiCancelStep", modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "fmiCancelStep");\r
+    log(NULL, comp->instanceName, fmiError, "error", \r
+        "fmiCancelStep: Can be called when fmiDoStep returned fmiPending."\r
+        " This is not the case."); \r
+    return fmiError;\r
+}\r
+\r
+fmiStatus fmiDoStep(fmiComponent c, fmiReal currentCommunicationPoint, \r
+    fmiReal communicationStepSize, fmiBoolean newStep) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    double h = communicationStepSize / 10;\r
+    int k,i;\r
+    const int n = 10; // how many Euler steps to perform for one do step\r
+    double prevState[max(NUMBER_OF_STATES, 1)];\r
+    double prevEventIndicators[max(NUMBER_OF_EVENT_INDICATORS, 1)];\r
+    int stateEvent = 0;\r
+\r
+    if (invalidState(comp, "fmiDoStep", modelInitialized))\r
+         return fmiError;\r
+\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "fmiDoStep: "\r
+       "currentCommunicationPoint = %g, ", \r
+       "communicationStepSize = %g, ", \r
+       "newStep = fmi%s", \r
+       currentCommunicationPoint, communicationStepSize, newStep ? "True" : "False");\r
+    \r
+    // Treat also case of zero step, i.e. during an event iteration\r
+    if (communicationStepSize == 0) {\r
+        return fmiOK;\r
+    }\r
+           \r
+#if NUMBER_OF_EVENT_INDICATORS>0\r
+    // initialize previous event indcators with current values\r
+    for (i=0; i<NUMBER_OF_EVENT_INDICATORS; i++) {\r
+        prevEventIndicators[i] = getEventIndicator(comp, i);\r
+    }\r
+#endif\r
+\r
+    // break the step into n steps and do forward Euler. \r
+    comp->time = currentCommunicationPoint;\r
+    for (k=0; k<n; k++) {\r
+        comp->time += h;\r
+\r
+#if NUMBER_OF_REALS>0\r
+        for (i=0; i<NUMBER_OF_STATES; i++) {\r
+            prevState[i] = r(vrStates[i]);\r
+        }\r
+        for (i=0; i<NUMBER_OF_STATES; i++) {\r
+            fmiValueReference vr = vrStates[i];\r
+            r(vr) += h * getReal(comp, vr+1); // forward Euler step\r
+        }\r
+#endif        \r
+\r
+#if NUMBER_OF_EVENT_INDICATORS>0\r
+        // check for state event\r
+        for (i=0; i<NUMBER_OF_EVENT_INDICATORS; i++) {\r
+            double ei = getEventIndicator(comp, i);\r
+            if (ei * prevEventIndicators[i] < 0) {\r
+                if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                    "fmiDoStep: state event at %g, z%d crosses zero -%c-", comp->time, i, ei<0 ? '\\' : '/');\r
+                stateEvent++;\r
+            }\r
+            prevEventIndicators[i] = ei;\r
+        }\r
+        if (stateEvent) {\r
+            eventUpdate(comp, &comp->eventInfo);\r
+            stateEvent = 0;\r
+        } \r
+#endif\r
+        // check for time event\r
+        if (comp->eventInfo.upcomingTimeEvent && comp->time > comp->eventInfo.nextEventTime) {\r
+            if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiDoStep: time event detected at %g", comp->time);\r
+            eventUpdate(comp, &comp->eventInfo);\r
+        }\r
+\r
+        // terminate simulation, if requested by the model\r
+        if (comp->eventInfo.terminateSimulation) {\r
+            comp->functions.logger(c, comp->instanceName, fmiOK, "log",\r
+              "fmiDoStep: model requested termination at t=%g", comp->time);\r
+            return fmiError; // enforce termination of the simulation loop\r
+        }        \r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+static fmiStatus getStatus(char* fname, fmiComponent c, const fmiStatusKind s) {\r
+    const char* statusKind[3] = {"fmiDoStepStatus","fmiPendingStatus","fmiLastSuccessfulTime"};\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    if (invalidState(comp, fname, modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "$s: fmiStatusKind = %s", fname, statusKind[s]);\r
+    switch(s) {\r
+        case fmiDoStepStatus:  log(NULL, comp->instanceName, fmiError, "error", \r
+           "%s: Can be called with fmiDoStepStatus when fmiDoStep returned fmiPending."\r
+           " This is not the case.", fname); \r
+           break;\r
+        case fmiPendingStatus:  log(NULL, comp->instanceName, fmiError, "error", \r
+           "%s: Can be called with fmiPendingStatus when fmiDoStep returned fmiPending."\r
+           " This is not the case.", fname); \r
+           break;\r
+        case fmiLastSuccessfulTime:  log(NULL, comp->instanceName, fmiError, "error", \r
+           "%s: Can be called with fmiLastSuccessfulTime when fmiDoStep returned fmiDiscard."\r
+           " This is not the case.", fname); \r
+           break;\r
+    }\r
+    return fmiError;\r
+}\r
+\r
+fmiStatus fmiGetStatus(fmiComponent c, const fmiStatusKind s, fmiStatus* value) {\r
+    return getStatus("fmiGetStatus", c, s);\r
+}\r
+\r
+fmiStatus fmiGetRealStatus(fmiComponent c, const fmiStatusKind s, fmiReal* value){\r
+    return getStatus("fmiGetRealStatus", c, s);\r
+}\r
+\r
+fmiStatus fmiGetIntegerStatus(fmiComponent c, const fmiStatusKind s, fmiInteger* value){\r
+    return getStatus("fmiGetIntegerStatus", c, s);\r
+}\r
+\r
+fmiStatus fmiGetBooleanStatus(fmiComponent c, const fmiStatusKind s, fmiBoolean* value){\r
+    return getStatus("fmiGetBooleanStatus", c, s);\r
+}\r
+\r
+fmiStatus fmiGetStringStatus(fmiComponent c, const fmiStatusKind s, fmiString*  value){\r
+    return getStatus("fmiGetStringStatus", c, s);\r
+}\r
+\r
+#else\r
+// ---------------------------------------------------------------------------\r
+// FMI functions: only for Model Exchange 1.0\r
+// ---------------------------------------------------------------------------\r
+\r
+const char* fmiGetModelTypesPlatform() {\r
+    return fmiModelTypesPlatform;\r
+}\r
+\r
+fmiComponent fmiInstantiateModel(fmiString instanceName, fmiString GUID, \r
+        fmiCallbackFunctions functions, fmiBoolean loggingOn) {\r
+    return instantiateModel("fmiInstantiateModel", instanceName, GUID, functions, loggingOn);\r
+}\r
+\r
+fmiStatus fmiInitialize(fmiComponent c, fmiBoolean toleranceControlled, fmiReal relativeTolerance,\r
+    fmiEventInfo* eventInfo) {\r
+    return init("fmiInitialize", c, toleranceControlled, relativeTolerance, eventInfo);\r
+}\r
+\r
+fmiStatus fmiSetTime(fmiComponent c, fmiReal time) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetTime", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetTime: time=%.16g", time);\r
+    comp->time = time;\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetContinuousStates(fmiComponent c, const fmiReal x[], size_t nx){\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    int i;\r
+    if (invalidState(comp, "fmiSetContinuousStates", modelInitialized))\r
+         return fmiError;\r
+    if (invalidNumber(comp, "fmiSetContinuousStates", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiSetContinuousStates", "x[]", x))\r
+         return fmiError;\r
+#if NUMBER_OF_REALS>0\r
+    for (i=0; i<nx; i++) {\r
+        fmiValueReference vr = vrStates[i];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetContinuousStates: #r%d#=%.16g", vr, x[i]);\r
+        assert(vr>=0 && vr<NUMBER_OF_REALS);\r
+        comp->r[vr] = x[i];\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiEventUpdate(fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiEventUpdate", modelInitialized))\r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiEventUpdate", "eventInfo", eventInfo))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+        "fmiEventUpdate: intermediateResults = %d", intermediateResults);\r
+    eventInfo->iterationConverged  = fmiTrue;\r
+    eventInfo->stateValueReferencesChanged = fmiFalse;\r
+    eventInfo->stateValuesChanged  = fmiFalse;\r
+    eventInfo->terminateSimulation = fmiFalse;\r
+    eventInfo->upcomingTimeEvent   = fmiFalse;\r
+    eventUpdate(comp, eventInfo); // to be implemented by the includer of this file\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiCompletedIntegratorStep(fmiComponent c, fmiBoolean* callEventUpdate){\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiCompletedIntegratorStep", modelInitialized))\r
+         return fmiError;\r
+    if (nullPointer(comp, "fmiCompletedIntegratorStep", "callEventUpdate", callEventUpdate))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiCompletedIntegratorStep");\r
+    *callEventUpdate = fmiFalse;\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetStateValueReferences(fmiComponent c, fmiValueReference vrx[], size_t nx){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetStateValueReferences", not_modelError))\r
+        return fmiError;\r
+    if (invalidNumber(comp, "fmiGetStateValueReferences", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiGetStateValueReferences", "vrx[]", vrx))\r
+         return fmiError;\r
+#if NUMBER_OF_REALS>0\r
+    for (i=0; i<nx; i++) {\r
+        vrx[i] = vrStates[i];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiGetStateValueReferences: vrx[%d] = %d", i, vrx[i]);\r
+    }\r
+#endif \r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetContinuousStates(fmiComponent c, fmiReal states[], size_t nx){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetContinuousStates", not_modelError))\r
+        return fmiError;\r
+    if (invalidNumber(comp, "fmiGetContinuousStates", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiGetContinuousStates", "states[]", states))\r
+         return fmiError;\r
+#if NUMBER_OF_REALS>0\r
+    for (i=0; i<nx; i++) {\r
+        fmiValueReference vr = vrStates[i];\r
+        states[i] = getReal(comp, vr); // to be implemented by the includer of this file\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiGetContinuousStates: #r%u# = %.16g", vr, states[i]);\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetNominalContinuousStates(fmiComponent c, fmiReal x_nominal[], size_t nx){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetNominalContinuousStates", not_modelError))\r
+        return fmiError;\r
+    if (invalidNumber(comp, "fmiGetNominalContinuousStates", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiGetNominalContinuousStates", "x_nominal[]", x_nominal))\r
+         return fmiError;\r
+    x_nominal[0] = 1;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+        "fmiGetNominalContinuousStates: x_nominal[0..%d] = 1.0", nx-1);\r
+    for (i=0; i<nx; i++) \r
+        x_nominal[i] = 1;\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetDerivatives(fmiComponent c, fmiReal derivatives[], size_t nx) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetDerivatives", not_modelError))\r
+         return fmiError;\r
+    if (invalidNumber(c, "fmiGetDerivatives", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiGetDerivatives", "derivatives[]", derivatives))\r
+         return fmiError;\r
+#if NUMBER_OF_STATES>0\r
+    for (i=0; i<nx; i++) {\r
+        fmiValueReference vr = vrStates[i] + 1;\r
+        derivatives[i] = getReal(comp, vr); // to be implemented by the includer of this file\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiGetDerivatives: #r%d# = %.16g", vr, derivatives[i]);\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetEventIndicators(fmiComponent c, fmiReal eventIndicators[], size_t ni) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetEventIndicators", not_modelError))\r
+        return fmiError;\r
+    if (invalidNumber(comp, "fmiGetEventIndicators", "ni", ni, NUMBER_OF_EVENT_INDICATORS)) \r
+        return fmiError;\r
+#if NUMBER_OF_EVENT_INDICATORS>0\r
+    for (i=0; i<ni; i++) {\r
+        eventIndicators[i] = getEventIndicator(comp, i); // to be implemented by the includer of this file\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiGetEventIndicators: z%d = %.16g", i, eventIndicators[i]);\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiTerminate(fmiComponent c){\r
+    return terminate("fmiTerminate", c);\r
+}\r
+\r
+void fmiFreeModelInstance(fmiComponent c) {\r
+    freeInstance("fmiFreeModelInstance", c);\r
+}\r
+\r
+#endif // Model Exchange 1.0\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/fmuTemplate.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/fmuTemplate.h
new file mode 100644 (file)
index 0000000..486bd40
--- /dev/null
@@ -0,0 +1,49 @@
+/* ---------------------------------------------------------------------------*\r
+ * fmuTemplate.h\r
+ * Definitions used in fmiModelFunctions.c and by the includer of this file\r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+\r
+#ifdef FMI_COSIMULATION\r
+#include "fmiFunctions.h"\r
+#else\r
+#include "fmiModelFunctions.h"\r
+#endif\r
+\r
+// macros used to define variables\r
+#define  r(vr) comp->r[vr]\r
+#define  i(vr) comp->i[vr]\r
+#define  b(vr) comp->b[vr]\r
+#define  s(vr) comp->s[vr]\r
+#define pos(z) comp->isPositive[z]\r
+#define copy(vr, value) setString(comp, vr, value)\r
+\r
+#define not_modelError (modelInstantiated|modelInitialized|modelTerminated)\r
+\r
+typedef enum {\r
+    modelInstantiated = 1<<0,\r
+    modelInitialized  = 1<<1,\r
+    modelTerminated   = 1<<2,\r
+    modelError        = 1<<3\r
+} ModelState;\r
+\r
+typedef struct {\r
+    fmiReal    *r;\r
+    fmiInteger *i;\r
+    fmiBoolean *b;\r
+    fmiString  *s;\r
+    fmiBoolean *isPositive;\r
+    fmiReal time;\r
+    fmiString instanceName;\r
+    fmiString GUID;\r
+    fmiCallbackFunctions functions;\r
+    fmiBoolean loggingOn;\r
+    ModelState state;\r
+#ifdef FMI_COSIMULATION\r
+    fmiEventInfo eventInfo;\r
+#endif\r
+} ModelInstance;\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/_main.html
new file mode 100644 (file)
index 0000000..8850b0d
--- /dev/null
@@ -0,0 +1,18 @@
+<html>\r
+<head>\r
+    <title>Documentation for inc.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+<h1>inc.fmu</h1>\r
+This FMU generates time events to increment an integer counter every second and terminates simulation at t=12 sec.\r
+<br/>    \r
+<img src="plot_counter.PNG">\r
+<br/>\r
+The figure shows the solution computed with Silver.\r
+</body>\r
+</html>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/inc.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/inc.c
new file mode 100644 (file)
index 0000000..8440dcd
--- /dev/null
@@ -0,0 +1,56 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU - increments an int counter every second.\r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER inc\r
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f008}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 0\r
+#define NUMBER_OF_INTEGERS 1\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_STATES 0\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define counter_ 0\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    i(counter_) = 1;\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    eventInfo->upcomingTimeEvent   = fmiTrue;\r
+    eventInfo->nextEventTime       = 1 + comp->time;\r
+}\r
+\r
+// called by fmiEventUpdate() after setting eventInfo to defaults\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    i(counter_) += 1;\r
+    if (i(counter_) == 13) \r
+        eventInfo->terminateSimulation = fmiTrue;\r
+    else {\r
+        eventInfo->upcomingTimeEvent   = fmiTrue;\r
+        eventInfo->nextEventTime       = 1 + comp->time;\r
+    }\r
+} \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/modelDescription.xml
new file mode 100644 (file)
index 0000000..58ce6f8
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="inc"\r
+  modelIdentifier="inc"\r
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f008}"\r
+  numberOfContinuousStates="0"\r
+  numberOfEventIndicators="0">\r
+<ModelVariables>\r
+  <ScalarVariable name="counter" valueReference="0" description="counts the seconds" causality = "output">\r
+     <Integer start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/plot_counter.PNG b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/plot_counter.PNG
new file mode 100644 (file)
index 0000000..d3ec25d
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/inc/plot_counter.PNG differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/me.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/me.xml
new file mode 100644 (file)
index 0000000..5ecace6
--- /dev/null
@@ -0,0 +1 @@
+</fmiModelDescription>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/_main.html
new file mode 100644 (file)
index 0000000..082d514
--- /dev/null
@@ -0,0 +1,19 @@
+<html>\r
+<head>\r
+    <title>Documentation for values.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+    <h1>values.fmu</h1>\r
+    This FMU demonstrates the use of all four scalar FMU data types \r
+    and terminates simulation at t=12 sec.\r
+    <img src="values.PNG">\r
+<br>\r
+The figure shows the solution computed with fmusim using the command \r
+<code>fmusim me fmu\me\values.fmu 12 12</code>.\r
+</body>\r
+</html>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/modelDescription.xml
new file mode 100644 (file)
index 0000000..3673a61
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="values"\r
+  modelIdentifier="values"\r
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f004}"\r
+  numberOfContinuousStates="1"\r
+  numberOfEventIndicators="0">\r
+<ModelVariables>\r
+  <ScalarVariable name="x" valueReference="0" description="used as continuous state">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(x)" valueReference="1" description="time derivative of x">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="int_in" valueReference="0" description="integer input" causality = "input">\r
+     <Integer start="2"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="int_out" valueReference="1" description="index in string array 'month'" causality = "output">\r
+     <Integer start="0" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="bool_in" valueReference="0" description="boolean input" causality = "input">\r
+     <Boolean start="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="bool_out" valueReference="1" description="boolean output" causality = "output">\r
+     <Boolean/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="string_in" valueReference="0" description="string input" causality = "input">\r
+     <String start="QTronic"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="string_out" valueReference="1" description="the string month[int_out]" causality = "output">\r
+     <String/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/values.PNG b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/values.PNG
new file mode 100644 (file)
index 0000000..45eaf96
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/values.PNG differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/values.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/values/values.c
new file mode 100644 (file)
index 0000000..536a290
--- /dev/null
@@ -0,0 +1,85 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU \r
+ * This demonstrates the use of all FMU variable types.\r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER values\r
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f004}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 2\r
+#define NUMBER_OF_INTEGERS 2\r
+#define NUMBER_OF_BOOLEANS 2\r
+#define NUMBER_OF_STRINGS 2\r
+#define NUMBER_OF_STATES 1\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define x_          0\r
+#define der_x_      1\r
+#define int_in_     0\r
+#define int_out_    1\r
+#define bool_in_    0\r
+#define bool_out_   1\r
+#define string_in_  0\r
+#define string_out_ 1\r
+\r
+// define state vector as vector of value references\r
+#define STATES { x_ }\r
+\r
+const char* month[] = {\r
+    "jan","feb","march","april","may","june","july",\r
+    "august","sept","october","november","december"\r
+};\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    r(x_) = 1;\r
+    i(int_in_) = 2;\r
+    i(int_out_) = 0;\r
+    b(bool_in_) = fmiTrue;\r
+    b(bool_out_) = fmiFalse;\r
+    copy(string_in_, "a string");\r
+    copy(string_out_, month[0]);\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    eventInfo->upcomingTimeEvent   = fmiTrue;\r
+    eventInfo->nextEventTime       = 1 + comp->time;\r
+}\r
+\r
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives\r
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){\r
+    switch (vr) {\r
+        case x_     : return   r(x_);\r
+        case der_x_ : return - r(x_);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// called by fmiEventUpdate() after setting eventInfo to defaults\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    eventInfo->upcomingTimeEvent   = fmiTrue;\r
+    eventInfo->nextEventTime       = 1 + comp->time;\r
+    i(int_out_) += 1;\r
+    b(bool_out_) = !b(bool_out_);\r
+    if (i(int_out_)<12) copy(string_out_, month[i(int_out_)]);\r
+    else eventInfo->terminateSimulation = fmiTrue;\r
+} \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/_main.html
new file mode 100644 (file)
index 0000000..07875f4
--- /dev/null
@@ -0,0 +1,23 @@
+<html>\r
+<head>\r
+<title>Documentation for vanDerPol.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+<h1>vanDerPol.fmu</h1>\r
+This FMU implements the famous\r
+<a href="http://en.wikipedia.org/wiki/Van_der_Pol_oscillator" target="_blank">Van der Pol oscillator</a>.\r
+<ul>\r
+<li> der(x0) = x1 </li>\r
+<li> der(x1) = mu * ((1 - x0 * x0) * x1) - x0</li>\r
+</ul>\r
+<img src="plot_states.png">\r
+<br/>\r
+The figure shows the solution computed with Silver \r
+for start values x0 = 2, x1 = 0, mu = 1.\r
+</body>\r
+</html>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/modelDescription.xml
new file mode 100644 (file)
index 0000000..ca44c3f
--- /dev/null
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="van der Pol oscillator"\r
+  modelIdentifier="vanDerPol"\r
+  guid="{8c4e810f-3da3-4a00-8276-176fa3c9f000}"\r
+  numberOfContinuousStates="2"\r
+  numberOfEventIndicators="0">\r
+<ModelVariables>\r
+  <ScalarVariable name="x0" valueReference="0" description="the first state">\r
+     <Real start="2" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(x0)" valueReference="1">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="x1" valueReference="2" description="the second state">\r
+     <Real start="0" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(x1)" valueReference="3">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="mu" valueReference="4" variability="parameter">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/plot_states.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/plot_states.png
new file mode 100644 (file)
index 0000000..05761cd
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/plot_states.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/vanDerPol.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/models/vanDerPol/vanDerPol.c
new file mode 100644 (file)
index 0000000..c494520
--- /dev/null
@@ -0,0 +1,75 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU - the Van der Pol oscillator. \r
+ * See http://en.wikipedia.org/wiki/Van_der_Pol_oscillator\r
+ *  \r
+ *   der(x0) = x1\r
+ *   der(x1) = mu * ((1 - x0 ^ 2) * x1) - x0;\r
+ *\r
+ *   start values: x0=2, x1=0, mue=1\r
+ *\r
+ * (c) 2011 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER vanDerPol\r
+#define MODEL_GUID "{8c4e810f-3da3-4a00-8276-176fa3c9f000}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 5\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_STATES 2\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define x0_     0\r
+#define der_x0_ 1\r
+#define x1_     2\r
+#define der_x1_ 3\r
+#define mu_     4\r
+\r
+// define state vector as vector of value references\r
+#define STATES { x0_, x1_ }\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    r(x0_) = 2;\r
+    r(x1_) = 0;\r
+    r(mu_) = 1;\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives\r
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){\r
+    switch (vr) {\r
+        case x0_     : return r(x0_);\r
+        case x1_     : return r(x1_);\r
+        case der_x0_ : return r(x1_);\r
+        case der_x1_ : return r(mu_) * ((1.0-r(x0_)*r(x0_))*r(x1_)) - r(x0_);\r
+        case mu_     : return r(mu_);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// Used to set the next time event, if any.\r
+void eventUpdate(fmiComponent comp, fmiEventInfo* eventInfo) {\r
+} \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/COPYING.txt b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/COPYING.txt
new file mode 100644 (file)
index 0000000..9042217
--- /dev/null
@@ -0,0 +1,24 @@
+Files expat.h, expat_external.h and libexpatMT.lib\r
+\r
+Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+                               and Clark Cooper\r
+Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining\r
+a copy of this software and associated documentation files (the\r
+"Software"), to deal in the Software without restriction, including\r
+without limitation the rights to use, copy, modify, merge, publish,\r
+distribute, sublicense, and/or sell copies of the Software, and to\r
+permit persons to whom the Software is furnished to do so, subject to\r
+the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included\r
+in all copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\r
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\r
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/expat.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/expat.h
new file mode 100644 (file)
index 0000000..6c2b6ff
--- /dev/null
@@ -0,0 +1,1014 @@
+/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+   See the file COPYING for copying permission.\r
+*/\r
+\r
+#ifndef Expat_INCLUDED\r
+#define Expat_INCLUDED 1\r
+\r
+#ifdef __VMS\r
+/*      0        1         2         3      0        1         2         3\r
+        1234567890123456789012345678901     1234567890123456789012345678901 */\r
+#define XML_SetProcessingInstructionHandler XML_SetProcessingInstrHandler\r
+#define XML_SetUnparsedEntityDeclHandler    XML_SetUnparsedEntDeclHandler\r
+#define XML_SetStartNamespaceDeclHandler    XML_SetStartNamespcDeclHandler\r
+#define XML_SetExternalEntityRefHandlerArg  XML_SetExternalEntRefHandlerArg\r
+#endif\r
+\r
+#include <stdlib.h>\r
+#include "expat_external.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+struct XML_ParserStruct;\r
+typedef struct XML_ParserStruct *XML_Parser;\r
+\r
+/* Should this be defined using stdbool.h when C99 is available? */\r
+typedef unsigned char XML_Bool;\r
+#define XML_TRUE   ((XML_Bool) 1)\r
+#define XML_FALSE  ((XML_Bool) 0)\r
+\r
+/* The XML_Status enum gives the possible return values for several\r
+   API functions.  The preprocessor #defines are included so this\r
+   stanza can be added to code that still needs to support older\r
+   versions of Expat 1.95.x:\r
+\r
+   #ifndef XML_STATUS_OK\r
+   #define XML_STATUS_OK    1\r
+   #define XML_STATUS_ERROR 0\r
+   #endif\r
+\r
+   Otherwise, the #define hackery is quite ugly and would have been\r
+   dropped.\r
+*/\r
+enum XML_Status {\r
+  XML_STATUS_ERROR = 0,\r
+#define XML_STATUS_ERROR XML_STATUS_ERROR\r
+  XML_STATUS_OK = 1,\r
+#define XML_STATUS_OK XML_STATUS_OK\r
+  XML_STATUS_SUSPENDED = 2\r
+#define XML_STATUS_SUSPENDED XML_STATUS_SUSPENDED\r
+};\r
+\r
+enum XML_Error {\r
+  XML_ERROR_NONE,\r
+  XML_ERROR_NO_MEMORY,\r
+  XML_ERROR_SYNTAX,\r
+  XML_ERROR_NO_ELEMENTS,\r
+  XML_ERROR_INVALID_TOKEN,\r
+  XML_ERROR_UNCLOSED_TOKEN,\r
+  XML_ERROR_PARTIAL_CHAR,\r
+  XML_ERROR_TAG_MISMATCH,\r
+  XML_ERROR_DUPLICATE_ATTRIBUTE,\r
+  XML_ERROR_JUNK_AFTER_DOC_ELEMENT,\r
+  XML_ERROR_PARAM_ENTITY_REF,\r
+  XML_ERROR_UNDEFINED_ENTITY,\r
+  XML_ERROR_RECURSIVE_ENTITY_REF,\r
+  XML_ERROR_ASYNC_ENTITY,\r
+  XML_ERROR_BAD_CHAR_REF,\r
+  XML_ERROR_BINARY_ENTITY_REF,\r
+  XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF,\r
+  XML_ERROR_MISPLACED_XML_PI,\r
+  XML_ERROR_UNKNOWN_ENCODING,\r
+  XML_ERROR_INCORRECT_ENCODING,\r
+  XML_ERROR_UNCLOSED_CDATA_SECTION,\r
+  XML_ERROR_EXTERNAL_ENTITY_HANDLING,\r
+  XML_ERROR_NOT_STANDALONE,\r
+  XML_ERROR_UNEXPECTED_STATE,\r
+  XML_ERROR_ENTITY_DECLARED_IN_PE,\r
+  XML_ERROR_FEATURE_REQUIRES_XML_DTD,\r
+  XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING,\r
+  /* Added in 1.95.7. */\r
+  XML_ERROR_UNBOUND_PREFIX,\r
+  /* Added in 1.95.8. */\r
+  XML_ERROR_UNDECLARING_PREFIX,\r
+  XML_ERROR_INCOMPLETE_PE,\r
+  XML_ERROR_XML_DECL,\r
+  XML_ERROR_TEXT_DECL,\r
+  XML_ERROR_PUBLICID,\r
+  XML_ERROR_SUSPENDED,\r
+  XML_ERROR_NOT_SUSPENDED,\r
+  XML_ERROR_ABORTED,\r
+  XML_ERROR_FINISHED,\r
+  XML_ERROR_SUSPEND_PE,\r
+  /* Added in 2.0. */\r
+  XML_ERROR_RESERVED_PREFIX_XML,\r
+  XML_ERROR_RESERVED_PREFIX_XMLNS,\r
+  XML_ERROR_RESERVED_NAMESPACE_URI\r
+};\r
+\r
+enum XML_Content_Type {\r
+  XML_CTYPE_EMPTY = 1,\r
+  XML_CTYPE_ANY,\r
+  XML_CTYPE_MIXED,\r
+  XML_CTYPE_NAME,\r
+  XML_CTYPE_CHOICE,\r
+  XML_CTYPE_SEQ\r
+};\r
+\r
+enum XML_Content_Quant {\r
+  XML_CQUANT_NONE,\r
+  XML_CQUANT_OPT,\r
+  XML_CQUANT_REP,\r
+  XML_CQUANT_PLUS\r
+};\r
+\r
+/* If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be\r
+   XML_CQUANT_NONE, and the other fields will be zero or NULL.\r
+   If type == XML_CTYPE_MIXED, then quant will be NONE or REP and\r
+   numchildren will contain number of elements that may be mixed in\r
+   and children point to an array of XML_Content cells that will be\r
+   all of XML_CTYPE_NAME type with no quantification.\r
+\r
+   If type == XML_CTYPE_NAME, then the name points to the name, and\r
+   the numchildren field will be zero and children will be NULL. The\r
+   quant fields indicates any quantifiers placed on the name.\r
+\r
+   CHOICE and SEQ will have name NULL, the number of children in\r
+   numchildren and children will point, recursively, to an array\r
+   of XML_Content cells.\r
+\r
+   The EMPTY, ANY, and MIXED types will only occur at top level.\r
+*/\r
+\r
+typedef struct XML_cp XML_Content;\r
+\r
+struct XML_cp {\r
+  enum XML_Content_Type         type;\r
+  enum XML_Content_Quant        quant;\r
+  XML_Char *                    name;\r
+  unsigned int                  numchildren;\r
+  XML_Content *                 children;\r
+};\r
+\r
+\r
+/* This is called for an element declaration. See above for\r
+   description of the model argument. It's the caller's responsibility\r
+   to free model when finished with it.\r
+*/\r
+typedef void (XMLCALL *XML_ElementDeclHandler) (void *userData,\r
+                                                const XML_Char *name,\r
+                                                XML_Content *model);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetElementDeclHandler(XML_Parser parser,\r
+                          XML_ElementDeclHandler eldecl);\r
+\r
+/* The Attlist declaration handler is called for *each* attribute. So\r
+   a single Attlist declaration with multiple attributes declared will\r
+   generate multiple calls to this handler. The "default" parameter\r
+   may be NULL in the case of the "#IMPLIED" or "#REQUIRED"\r
+   keyword. The "isrequired" parameter will be true and the default\r
+   value will be NULL in the case of "#REQUIRED". If "isrequired" is\r
+   true and default is non-NULL, then this is a "#FIXED" default.\r
+*/\r
+typedef void (XMLCALL *XML_AttlistDeclHandler) (\r
+                                    void            *userData,\r
+                                    const XML_Char  *elname,\r
+                                    const XML_Char  *attname,\r
+                                    const XML_Char  *att_type,\r
+                                    const XML_Char  *dflt,\r
+                                    int              isrequired);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetAttlistDeclHandler(XML_Parser parser,\r
+                          XML_AttlistDeclHandler attdecl);\r
+\r
+/* The XML declaration handler is called for *both* XML declarations\r
+   and text declarations. The way to distinguish is that the version\r
+   parameter will be NULL for text declarations. The encoding\r
+   parameter may be NULL for XML declarations. The standalone\r
+   parameter will be -1, 0, or 1 indicating respectively that there\r
+   was no standalone parameter in the declaration, that it was given\r
+   as no, or that it was given as yes.\r
+*/\r
+typedef void (XMLCALL *XML_XmlDeclHandler) (void           *userData,\r
+                                            const XML_Char *version,\r
+                                            const XML_Char *encoding,\r
+                                            int             standalone);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetXmlDeclHandler(XML_Parser parser,\r
+                      XML_XmlDeclHandler xmldecl);\r
+\r
+\r
+typedef struct {\r
+  void *(*malloc_fcn)(size_t size);\r
+  void *(*realloc_fcn)(void *ptr, size_t size);\r
+  void (*free_fcn)(void *ptr);\r
+} XML_Memory_Handling_Suite;\r
+\r
+/* Constructs a new parser; encoding is the encoding specified by the\r
+   external protocol or NULL if there is none specified.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreate(const XML_Char *encoding);\r
+\r
+/* Constructs a new parser and namespace processor.  Element type\r
+   names and attribute names that belong to a namespace will be\r
+   expanded; unprefixed attribute names are never expanded; unprefixed\r
+   element type names are expanded only if there is a default\r
+   namespace. The expanded name is the concatenation of the namespace\r
+   URI, the namespace separator character, and the local part of the\r
+   name.  If the namespace separator is '\0' then the namespace URI\r
+   and the local part will be concatenated without any separator.\r
+   It is a programming error to use the separator '\0' with namespace\r
+   triplets (see XML_SetReturnNSTriplet).\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator);\r
+\r
+\r
+/* Constructs a new parser using the memory management suite referred to\r
+   by memsuite. If memsuite is NULL, then use the standard library memory\r
+   suite. If namespaceSeparator is non-NULL it creates a parser with\r
+   namespace processing as described above. The character pointed at\r
+   will serve as the namespace separator.\r
+\r
+   All further memory operations used for the created parser will come from\r
+   the given suite.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreate_MM(const XML_Char *encoding,\r
+                    const XML_Memory_Handling_Suite *memsuite,\r
+                    const XML_Char *namespaceSeparator);\r
+\r
+/* Prepare a parser object to be re-used.  This is particularly\r
+   valuable when memory allocation overhead is disproportionatly high,\r
+   such as when a large number of small documnents need to be parsed.\r
+   All handlers are cleared from the parser, except for the\r
+   unknownEncodingHandler. The parser's external state is re-initialized\r
+   except for the values of ns and ns_triplets.\r
+\r
+   Added in Expat 1.95.3.\r
+*/\r
+XMLPARSEAPI(XML_Bool)\r
+XML_ParserReset(XML_Parser parser, const XML_Char *encoding);\r
+\r
+/* atts is array of name/value pairs, terminated by 0;\r
+   names and values are 0 terminated.\r
+*/\r
+typedef void (XMLCALL *XML_StartElementHandler) (void *userData,\r
+                                                 const XML_Char *name,\r
+                                                 const XML_Char **atts);\r
+\r
+typedef void (XMLCALL *XML_EndElementHandler) (void *userData,\r
+                                               const XML_Char *name);\r
+\r
+\r
+/* s is not 0 terminated. */\r
+typedef void (XMLCALL *XML_CharacterDataHandler) (void *userData,\r
+                                                  const XML_Char *s,\r
+                                                  int len);\r
+\r
+/* target and data are 0 terminated */\r
+typedef void (XMLCALL *XML_ProcessingInstructionHandler) (\r
+                                                void *userData,\r
+                                                const XML_Char *target,\r
+                                                const XML_Char *data);\r
+\r
+/* data is 0 terminated */\r
+typedef void (XMLCALL *XML_CommentHandler) (void *userData,\r
+                                            const XML_Char *data);\r
+\r
+typedef void (XMLCALL *XML_StartCdataSectionHandler) (void *userData);\r
+typedef void (XMLCALL *XML_EndCdataSectionHandler) (void *userData);\r
+\r
+/* This is called for any characters in the XML document for which\r
+   there is no applicable handler.  This includes both characters that\r
+   are part of markup which is of a kind that is not reported\r
+   (comments, markup declarations), or characters that are part of a\r
+   construct which could be reported but for which no handler has been\r
+   supplied. The characters are passed exactly as they were in the XML\r
+   document except that they will be encoded in UTF-8 or UTF-16.\r
+   Line boundaries are not normalized. Note that a byte order mark\r
+   character is not passed to the default handler. There are no\r
+   guarantees about how characters are divided between calls to the\r
+   default handler: for example, a comment might be split between\r
+   multiple calls.\r
+*/\r
+typedef void (XMLCALL *XML_DefaultHandler) (void *userData,\r
+                                            const XML_Char *s,\r
+                                            int len);\r
+\r
+/* This is called for the start of the DOCTYPE declaration, before\r
+   any DTD or internal subset is parsed.\r
+*/\r
+typedef void (XMLCALL *XML_StartDoctypeDeclHandler) (\r
+                                            void *userData,\r
+                                            const XML_Char *doctypeName,\r
+                                            const XML_Char *sysid,\r
+                                            const XML_Char *pubid,\r
+                                            int has_internal_subset);\r
+\r
+/* This is called for the start of the DOCTYPE declaration when the\r
+   closing > is encountered, but after processing any external\r
+   subset.\r
+*/\r
+typedef void (XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);\r
+\r
+/* This is called for entity declarations. The is_parameter_entity\r
+   argument will be non-zero if the entity is a parameter entity, zero\r
+   otherwise.\r
+\r
+   For internal entities (<!ENTITY foo "bar">), value will\r
+   be non-NULL and systemId, publicID, and notationName will be NULL.\r
+   The value string is NOT nul-terminated; the length is provided in\r
+   the value_length argument. Since it is legal to have zero-length\r
+   values, do not use this argument to test for internal entities.\r
+\r
+   For external entities, value will be NULL and systemId will be\r
+   non-NULL. The publicId argument will be NULL unless a public\r
+   identifier was provided. The notationName argument will have a\r
+   non-NULL value only for unparsed entity declarations.\r
+\r
+   Note that is_parameter_entity can't be changed to XML_Bool, since\r
+   that would break binary compatibility.\r
+*/\r
+typedef void (XMLCALL *XML_EntityDeclHandler) (\r
+                              void *userData,\r
+                              const XML_Char *entityName,\r
+                              int is_parameter_entity,\r
+                              const XML_Char *value,\r
+                              int value_length,\r
+                              const XML_Char *base,\r
+                              const XML_Char *systemId,\r
+                              const XML_Char *publicId,\r
+                              const XML_Char *notationName);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEntityDeclHandler(XML_Parser parser,\r
+                         XML_EntityDeclHandler handler);\r
+\r
+/* OBSOLETE -- OBSOLETE -- OBSOLETE\r
+   This handler has been superceded by the EntityDeclHandler above.\r
+   It is provided here for backward compatibility.\r
+\r
+   This is called for a declaration of an unparsed (NDATA) entity.\r
+   The base argument is whatever was set by XML_SetBase. The\r
+   entityName, systemId and notationName arguments will never be\r
+   NULL. The other arguments may be.\r
+*/\r
+typedef void (XMLCALL *XML_UnparsedEntityDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *entityName,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId,\r
+                                    const XML_Char *notationName);\r
+\r
+/* This is called for a declaration of notation.  The base argument is\r
+   whatever was set by XML_SetBase. The notationName will never be\r
+   NULL.  The other arguments can be.\r
+*/\r
+typedef void (XMLCALL *XML_NotationDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *notationName,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId);\r
+\r
+/* When namespace processing is enabled, these are called once for\r
+   each namespace declaration. The call to the start and end element\r
+   handlers occur between the calls to the start and end namespace\r
+   declaration handlers. For an xmlns attribute, prefix will be\r
+   NULL.  For an xmlns="" attribute, uri will be NULL.\r
+*/\r
+typedef void (XMLCALL *XML_StartNamespaceDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *prefix,\r
+                                    const XML_Char *uri);\r
+\r
+typedef void (XMLCALL *XML_EndNamespaceDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *prefix);\r
+\r
+/* This is called if the document is not standalone, that is, it has an\r
+   external subset or a reference to a parameter entity, but does not\r
+   have standalone="yes". If this handler returns XML_STATUS_ERROR,\r
+   then processing will not continue, and the parser will return a\r
+   XML_ERROR_NOT_STANDALONE error.\r
+   If parameter entity parsing is enabled, then in addition to the\r
+   conditions above this handler will only be called if the referenced\r
+   entity was actually read.\r
+*/\r
+typedef int (XMLCALL *XML_NotStandaloneHandler) (void *userData);\r
+\r
+/* This is called for a reference to an external parsed general\r
+   entity.  The referenced entity is not automatically parsed.  The\r
+   application can parse it immediately or later using\r
+   XML_ExternalEntityParserCreate.\r
+\r
+   The parser argument is the parser parsing the entity containing the\r
+   reference; it can be passed as the parser argument to\r
+   XML_ExternalEntityParserCreate.  The systemId argument is the\r
+   system identifier as specified in the entity declaration; it will\r
+   not be NULL.\r
+\r
+   The base argument is the system identifier that should be used as\r
+   the base for resolving systemId if systemId was relative; this is\r
+   set by XML_SetBase; it may be NULL.\r
+\r
+   The publicId argument is the public identifier as specified in the\r
+   entity declaration, or NULL if none was specified; the whitespace\r
+   in the public identifier will have been normalized as required by\r
+   the XML spec.\r
+\r
+   The context argument specifies the parsing context in the format\r
+   expected by the context argument to XML_ExternalEntityParserCreate;\r
+   context is valid only until the handler returns, so if the\r
+   referenced entity is to be parsed later, it must be copied.\r
+   context is NULL only when the entity is a parameter entity.\r
+\r
+   The handler should return XML_STATUS_ERROR if processing should not\r
+   continue because of a fatal error in the handling of the external\r
+   entity.  In this case the calling parser will return an\r
+   XML_ERROR_EXTERNAL_ENTITY_HANDLING error.\r
+\r
+   Note that unlike other handlers the first argument is the parser,\r
+   not userData.\r
+*/\r
+typedef int (XMLCALL *XML_ExternalEntityRefHandler) (\r
+                                    XML_Parser parser,\r
+                                    const XML_Char *context,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId);\r
+\r
+/* This is called in two situations:\r
+   1) An entity reference is encountered for which no declaration\r
+      has been read *and* this is not an error.\r
+   2) An internal entity reference is read, but not expanded, because\r
+      XML_SetDefaultHandler has been called.\r
+   Note: skipped parameter entities in declarations and skipped general\r
+         entities in attribute values cannot be reported, because\r
+         the event would be out of sync with the reporting of the\r
+         declarations or attribute values\r
+*/\r
+typedef void (XMLCALL *XML_SkippedEntityHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *entityName,\r
+                                    int is_parameter_entity);\r
+\r
+/* This structure is filled in by the XML_UnknownEncodingHandler to\r
+   provide information to the parser about encodings that are unknown\r
+   to the parser.\r
+\r
+   The map[b] member gives information about byte sequences whose\r
+   first byte is b.\r
+\r
+   If map[b] is c where c is >= 0, then b by itself encodes the\r
+   Unicode scalar value c.\r
+\r
+   If map[b] is -1, then the byte sequence is malformed.\r
+\r
+   If map[b] is -n, where n >= 2, then b is the first byte of an\r
+   n-byte sequence that encodes a single Unicode scalar value.\r
+\r
+   The data member will be passed as the first argument to the convert\r
+   function.\r
+\r
+   The convert function is used to convert multibyte sequences; s will\r
+   point to a n-byte sequence where map[(unsigned char)*s] == -n.  The\r
+   convert function must return the Unicode scalar value represented\r
+   by this byte sequence or -1 if the byte sequence is malformed.\r
+\r
+   The convert function may be NULL if the encoding is a single-byte\r
+   encoding, that is if map[b] >= -1 for all bytes b.\r
+\r
+   When the parser is finished with the encoding, then if release is\r
+   not NULL, it will call release passing it the data member; once\r
+   release has been called, the convert function will not be called\r
+   again.\r
+\r
+   Expat places certain restrictions on the encodings that are supported\r
+   using this mechanism.\r
+\r
+   1. Every ASCII character that can appear in a well-formed XML document,\r
+      other than the characters\r
+\r
+      $@\^`{}~\r
+\r
+      must be represented by a single byte, and that byte must be the\r
+      same byte that represents that character in ASCII.\r
+\r
+   2. No character may require more than 4 bytes to encode.\r
+\r
+   3. All characters encoded must have Unicode scalar values <=\r
+      0xFFFF, (i.e., characters that would be encoded by surrogates in\r
+      UTF-16 are  not allowed).  Note that this restriction doesn't\r
+      apply to the built-in support for UTF-8 and UTF-16.\r
+\r
+   4. No Unicode character may be encoded by more than one distinct\r
+      sequence of bytes.\r
+*/\r
+typedef struct {\r
+  int map[256];\r
+  void *data;\r
+  int (XMLCALL *convert)(void *data, const char *s);\r
+  void (XMLCALL *release)(void *data);\r
+} XML_Encoding;\r
+\r
+/* This is called for an encoding that is unknown to the parser.\r
+\r
+   The encodingHandlerData argument is that which was passed as the\r
+   second argument to XML_SetUnknownEncodingHandler.\r
+\r
+   The name argument gives the name of the encoding as specified in\r
+   the encoding declaration.\r
+\r
+   If the callback can provide information about the encoding, it must\r
+   fill in the XML_Encoding structure, and return XML_STATUS_OK.\r
+   Otherwise it must return XML_STATUS_ERROR.\r
+\r
+   If info does not describe a suitable encoding, then the parser will\r
+   return an XML_UNKNOWN_ENCODING error.\r
+*/\r
+typedef int (XMLCALL *XML_UnknownEncodingHandler) (\r
+                                    void *encodingHandlerData,\r
+                                    const XML_Char *name,\r
+                                    XML_Encoding *info);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetElementHandler(XML_Parser parser,\r
+                      XML_StartElementHandler start,\r
+                      XML_EndElementHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartElementHandler(XML_Parser parser,\r
+                           XML_StartElementHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndElementHandler(XML_Parser parser,\r
+                         XML_EndElementHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetCharacterDataHandler(XML_Parser parser,\r
+                            XML_CharacterDataHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetProcessingInstructionHandler(XML_Parser parser,\r
+                                    XML_ProcessingInstructionHandler handler);\r
+XMLPARSEAPI(void)\r
+XML_SetCommentHandler(XML_Parser parser,\r
+                      XML_CommentHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetCdataSectionHandler(XML_Parser parser,\r
+                           XML_StartCdataSectionHandler start,\r
+                           XML_EndCdataSectionHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartCdataSectionHandler(XML_Parser parser,\r
+                                XML_StartCdataSectionHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndCdataSectionHandler(XML_Parser parser,\r
+                              XML_EndCdataSectionHandler end);\r
+\r
+/* This sets the default handler and also inhibits expansion of\r
+   internal entities. These entity references will be passed to the\r
+   default handler, or to the skipped entity handler, if one is set.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetDefaultHandler(XML_Parser parser,\r
+                      XML_DefaultHandler handler);\r
+\r
+/* This sets the default handler but does not inhibit expansion of\r
+   internal entities.  The entity reference will not be passed to the\r
+   default handler.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetDefaultHandlerExpand(XML_Parser parser,\r
+                            XML_DefaultHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetDoctypeDeclHandler(XML_Parser parser,\r
+                          XML_StartDoctypeDeclHandler start,\r
+                          XML_EndDoctypeDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartDoctypeDeclHandler(XML_Parser parser,\r
+                               XML_StartDoctypeDeclHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndDoctypeDeclHandler(XML_Parser parser,\r
+                             XML_EndDoctypeDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetUnparsedEntityDeclHandler(XML_Parser parser,\r
+                                 XML_UnparsedEntityDeclHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNotationDeclHandler(XML_Parser parser,\r
+                           XML_NotationDeclHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNamespaceDeclHandler(XML_Parser parser,\r
+                            XML_StartNamespaceDeclHandler start,\r
+                            XML_EndNamespaceDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartNamespaceDeclHandler(XML_Parser parser,\r
+                                 XML_StartNamespaceDeclHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndNamespaceDeclHandler(XML_Parser parser,\r
+                               XML_EndNamespaceDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNotStandaloneHandler(XML_Parser parser,\r
+                            XML_NotStandaloneHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetExternalEntityRefHandler(XML_Parser parser,\r
+                                XML_ExternalEntityRefHandler handler);\r
+\r
+/* If a non-NULL value for arg is specified here, then it will be\r
+   passed as the first argument to the external entity ref handler\r
+   instead of the parser object.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetExternalEntityRefHandlerArg(XML_Parser parser,\r
+                                   void *arg);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetSkippedEntityHandler(XML_Parser parser,\r
+                            XML_SkippedEntityHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetUnknownEncodingHandler(XML_Parser parser,\r
+                              XML_UnknownEncodingHandler handler,\r
+                              void *encodingHandlerData);\r
+\r
+/* This can be called within a handler for a start element, end\r
+   element, processing instruction or character data.  It causes the\r
+   corresponding markup to be passed to the default handler.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_DefaultCurrent(XML_Parser parser);\r
+\r
+/* If do_nst is non-zero, and namespace processing is in effect, and\r
+   a name has a prefix (i.e. an explicit namespace qualifier) then\r
+   that name is returned as a triplet in a single string separated by\r
+   the separator character specified when the parser was created: URI\r
+   + sep + local_name + sep + prefix.\r
+\r
+   If do_nst is zero, then namespace information is returned in the\r
+   default manner (URI + sep + local_name) whether or not the name\r
+   has a prefix.\r
+\r
+   Note: Calling XML_SetReturnNSTriplet after XML_Parse or\r
+     XML_ParseBuffer has no effect.\r
+*/\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetReturnNSTriplet(XML_Parser parser, int do_nst);\r
+\r
+/* This value is passed as the userData argument to callbacks. */\r
+XMLPARSEAPI(void)\r
+XML_SetUserData(XML_Parser parser, void *userData);\r
+\r
+/* Returns the last value set by XML_SetUserData or NULL. */\r
+#define XML_GetUserData(parser) (*(void **)(parser))\r
+\r
+/* This is equivalent to supplying an encoding argument to\r
+   XML_ParserCreate. On success XML_SetEncoding returns non-zero,\r
+   zero otherwise.\r
+   Note: Calling XML_SetEncoding after XML_Parse or XML_ParseBuffer\r
+     has no effect and returns XML_STATUS_ERROR.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_SetEncoding(XML_Parser parser, const XML_Char *encoding);\r
+\r
+/* If this function is called, then the parser will be passed as the\r
+   first argument to callbacks instead of userData.  The userData will\r
+   still be accessible using XML_GetUserData.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_UseParserAsHandlerArg(XML_Parser parser);\r
+\r
+/* If useDTD == XML_TRUE is passed to this function, then the parser\r
+   will assume that there is an external subset, even if none is\r
+   specified in the document. In such a case the parser will call the\r
+   externalEntityRefHandler with a value of NULL for the systemId\r
+   argument (the publicId and context arguments will be NULL as well).\r
+   Note: For the purpose of checking WFC: Entity Declared, passing\r
+     useDTD == XML_TRUE will make the parser behave as if the document\r
+     had a DTD with an external subset.\r
+   Note: If this function is called, then this must be done before\r
+     the first call to XML_Parse or XML_ParseBuffer, since it will\r
+     have no effect after that.  Returns\r
+     XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING.\r
+   Note: If the document does not have a DOCTYPE declaration at all,\r
+     then startDoctypeDeclHandler and endDoctypeDeclHandler will not\r
+     be called, despite an external subset being parsed.\r
+   Note: If XML_DTD is not defined when Expat is compiled, returns\r
+     XML_ERROR_FEATURE_REQUIRES_XML_DTD.\r
+*/\r
+XMLPARSEAPI(enum XML_Error)\r
+XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);\r
+\r
+\r
+/* Sets the base to be used for resolving relative URIs in system\r
+   identifiers in declarations.  Resolving relative identifiers is\r
+   left to the application: this value will be passed through as the\r
+   base argument to the XML_ExternalEntityRefHandler,\r
+   XML_NotationDeclHandler and XML_UnparsedEntityDeclHandler. The base\r
+   argument will be copied.  Returns XML_STATUS_ERROR if out of memory,\r
+   XML_STATUS_OK otherwise.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_SetBase(XML_Parser parser, const XML_Char *base);\r
+\r
+XMLPARSEAPI(const XML_Char *)\r
+XML_GetBase(XML_Parser parser);\r
+\r
+/* Returns the number of the attribute/value pairs passed in last call\r
+   to the XML_StartElementHandler that were specified in the start-tag\r
+   rather than defaulted. Each attribute/value pair counts as 2; thus\r
+   this correspondds to an index into the atts array passed to the\r
+   XML_StartElementHandler.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetSpecifiedAttributeCount(XML_Parser parser);\r
+\r
+/* Returns the index of the ID attribute passed in the last call to\r
+   XML_StartElementHandler, or -1 if there is no ID attribute.  Each\r
+   attribute/value pair counts as 2; thus this correspondds to an\r
+   index into the atts array passed to the XML_StartElementHandler.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetIdAttributeIndex(XML_Parser parser);\r
+\r
+/* Parses some input. Returns XML_STATUS_ERROR if a fatal error is\r
+   detected.  The last call to XML_Parse must have isFinal true; len\r
+   may be zero for this call (or any other).\r
+\r
+   Though the return values for these functions has always been\r
+   described as a Boolean value, the implementation, at least for the\r
+   1.95.x series, has always returned exactly one of the XML_Status\r
+   values.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_Parse(XML_Parser parser, const char *s, int len, int isFinal);\r
+\r
+XMLPARSEAPI(void *)\r
+XML_GetBuffer(XML_Parser parser, int len);\r
+\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_ParseBuffer(XML_Parser parser, int len, int isFinal);\r
+\r
+/* Stops parsing, causing XML_Parse() or XML_ParseBuffer() to return.\r
+   Must be called from within a call-back handler, except when aborting\r
+   (resumable = 0) an already suspended parser. Some call-backs may\r
+   still follow because they would otherwise get lost. Examples:\r
+   - endElementHandler() for empty elements when stopped in\r
+     startElementHandler(), \r
+   - endNameSpaceDeclHandler() when stopped in endElementHandler(), \r
+   and possibly others.\r
+\r
+   Can be called from most handlers, including DTD related call-backs,\r
+   except when parsing an external parameter entity and resumable != 0.\r
+   Returns XML_STATUS_OK when successful, XML_STATUS_ERROR otherwise.\r
+   Possible error codes: \r
+   - XML_ERROR_SUSPENDED: when suspending an already suspended parser.\r
+   - XML_ERROR_FINISHED: when the parser has already finished.\r
+   - XML_ERROR_SUSPEND_PE: when suspending while parsing an external PE.\r
+\r
+   When resumable != 0 (true) then parsing is suspended, that is, \r
+   XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED. \r
+   Otherwise, parsing is aborted, that is, XML_Parse() and XML_ParseBuffer()\r
+   return XML_STATUS_ERROR with error code XML_ERROR_ABORTED.\r
+\r
+   *Note*:\r
+   This will be applied to the current parser instance only, that is, if\r
+   there is a parent parser then it will continue parsing when the\r
+   externalEntityRefHandler() returns. It is up to the implementation of\r
+   the externalEntityRefHandler() to call XML_StopParser() on the parent\r
+   parser (recursively), if one wants to stop parsing altogether.\r
+\r
+   When suspended, parsing can be resumed by calling XML_ResumeParser(). \r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_StopParser(XML_Parser parser, XML_Bool resumable);\r
+\r
+/* Resumes parsing after it has been suspended with XML_StopParser().\r
+   Must not be called from within a handler call-back. Returns same\r
+   status codes as XML_Parse() or XML_ParseBuffer().\r
+   Additional error code XML_ERROR_NOT_SUSPENDED possible.   \r
+\r
+   *Note*:\r
+   This must be called on the most deeply nested child parser instance\r
+   first, and on its parent parser only after the child parser has finished,\r
+   to be applied recursively until the document entity's parser is restarted.\r
+   That is, the parent parser will not resume by itself and it is up to the\r
+   application to call XML_ResumeParser() on it at the appropriate moment.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_ResumeParser(XML_Parser parser);\r
+\r
+enum XML_Parsing {\r
+  XML_INITIALIZED,\r
+  XML_PARSING,\r
+  XML_FINISHED,\r
+  XML_SUSPENDED\r
+};\r
+\r
+typedef struct {\r
+  enum XML_Parsing parsing;\r
+  XML_Bool finalBuffer;\r
+} XML_ParsingStatus;\r
+\r
+/* Returns status of parser with respect to being initialized, parsing,\r
+   finished, or suspended and processing the final buffer.\r
+   XXX XML_Parse() and XML_ParseBuffer() should return XML_ParsingStatus,\r
+   XXX with XML_FINISHED_OK or XML_FINISHED_ERROR replacing XML_FINISHED\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status);\r
+\r
+/* Creates an XML_Parser object that can parse an external general\r
+   entity; context is a '\0'-terminated string specifying the parse\r
+   context; encoding is a '\0'-terminated string giving the name of\r
+   the externally specified encoding, or NULL if there is no\r
+   externally specified encoding.  The context string consists of a\r
+   sequence of tokens separated by formfeeds (\f); a token consisting\r
+   of a name specifies that the general entity of the name is open; a\r
+   token of the form prefix=uri specifies the namespace for a\r
+   particular prefix; a token of the form =uri specifies the default\r
+   namespace.  This can be called at any point after the first call to\r
+   an ExternalEntityRefHandler so longer as the parser has not yet\r
+   been freed.  The new parser is completely independent and may\r
+   safely be used in a separate thread.  The handlers and userData are\r
+   initialized from the parser argument.  Returns NULL if out of memory.\r
+   Otherwise returns a new XML_Parser object.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ExternalEntityParserCreate(XML_Parser parser,\r
+                               const XML_Char *context,\r
+                               const XML_Char *encoding);\r
+\r
+enum XML_ParamEntityParsing {\r
+  XML_PARAM_ENTITY_PARSING_NEVER,\r
+  XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE,\r
+  XML_PARAM_ENTITY_PARSING_ALWAYS\r
+};\r
+\r
+/* Controls parsing of parameter entities (including the external DTD\r
+   subset). If parsing of parameter entities is enabled, then\r
+   references to external parameter entities (including the external\r
+   DTD subset) will be passed to the handler set with\r
+   XML_SetExternalEntityRefHandler.  The context passed will be 0.\r
+\r
+   Unlike external general entities, external parameter entities can\r
+   only be parsed synchronously.  If the external parameter entity is\r
+   to be parsed, it must be parsed during the call to the external\r
+   entity ref handler: the complete sequence of\r
+   XML_ExternalEntityParserCreate, XML_Parse/XML_ParseBuffer and\r
+   XML_ParserFree calls must be made during this call.  After\r
+   XML_ExternalEntityParserCreate has been called to create the parser\r
+   for the external parameter entity (context must be 0 for this\r
+   call), it is illegal to make any calls on the old parser until\r
+   XML_ParserFree has been called on the newly created parser.\r
+   If the library has been compiled without support for parameter\r
+   entity parsing (ie without XML_DTD being defined), then\r
+   XML_SetParamEntityParsing will return 0 if parsing of parameter\r
+   entities is requested; otherwise it will return non-zero.\r
+   Note: If XML_SetParamEntityParsing is called after XML_Parse or\r
+      XML_ParseBuffer, then it has no effect and will always return 0.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_SetParamEntityParsing(XML_Parser parser,\r
+                          enum XML_ParamEntityParsing parsing);\r
+\r
+/* If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then\r
+   XML_GetErrorCode returns information about the error.\r
+*/\r
+XMLPARSEAPI(enum XML_Error)\r
+XML_GetErrorCode(XML_Parser parser);\r
+\r
+/* These functions return information about the current parse\r
+   location.  They may be called from any callback called to report\r
+   some parse event; in this case the location is the location of the\r
+   first of the sequence of characters that generated the event.  When\r
+   called from callbacks generated by declarations in the document\r
+   prologue, the location identified isn't as neatly defined, but will\r
+   be within the relevant markup.  When called outside of the callback\r
+   functions, the position indicated will be just past the last parse\r
+   event (regardless of whether there was an associated callback).\r
+   \r
+   They may also be called after returning from a call to XML_Parse\r
+   or XML_ParseBuffer.  If the return value is XML_STATUS_ERROR then\r
+   the location is the location of the character at which the error\r
+   was detected; otherwise the location is the location of the last\r
+   parse event, as described above.\r
+*/\r
+XMLPARSEAPI(XML_Size) XML_GetCurrentLineNumber(XML_Parser parser);\r
+XMLPARSEAPI(XML_Size) XML_GetCurrentColumnNumber(XML_Parser parser);\r
+XMLPARSEAPI(XML_Index) XML_GetCurrentByteIndex(XML_Parser parser);\r
+\r
+/* Return the number of bytes in the current event.\r
+   Returns 0 if the event is in an internal entity.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetCurrentByteCount(XML_Parser parser);\r
+\r
+/* If XML_CONTEXT_BYTES is defined, returns the input buffer, sets\r
+   the integer pointed to by offset to the offset within this buffer\r
+   of the current parse position, and sets the integer pointed to by size\r
+   to the size of this buffer (the number of input bytes). Otherwise\r
+   returns a NULL pointer. Also returns a NULL pointer if a parse isn't\r
+   active.\r
+\r
+   NOTE: The character pointer returned should not be used outside\r
+   the handler that makes the call.\r
+*/\r
+XMLPARSEAPI(const char *)\r
+XML_GetInputContext(XML_Parser parser,\r
+                    int *offset,\r
+                    int *size);\r
+\r
+/* For backwards compatibility with previous versions. */\r
+#define XML_GetErrorLineNumber   XML_GetCurrentLineNumber\r
+#define XML_GetErrorColumnNumber XML_GetCurrentColumnNumber\r
+#define XML_GetErrorByteIndex    XML_GetCurrentByteIndex\r
+\r
+/* Frees the content model passed to the element declaration handler */\r
+XMLPARSEAPI(void)\r
+XML_FreeContentModel(XML_Parser parser, XML_Content *model);\r
+\r
+/* Exposing the memory handling functions used in Expat */\r
+XMLPARSEAPI(void *)\r
+XML_MemMalloc(XML_Parser parser, size_t size);\r
+\r
+XMLPARSEAPI(void *)\r
+XML_MemRealloc(XML_Parser parser, void *ptr, size_t size);\r
+\r
+XMLPARSEAPI(void)\r
+XML_MemFree(XML_Parser parser, void *ptr);\r
+\r
+/* Frees memory used by the parser. */\r
+XMLPARSEAPI(void)\r
+XML_ParserFree(XML_Parser parser);\r
+\r
+/* Returns a string describing the error. */\r
+XMLPARSEAPI(const XML_LChar *)\r
+XML_ErrorString(enum XML_Error code);\r
+\r
+/* Return a string containing the version number of this expat */\r
+XMLPARSEAPI(const XML_LChar *)\r
+XML_ExpatVersion(void);\r
+\r
+typedef struct {\r
+  int major;\r
+  int minor;\r
+  int micro;\r
+} XML_Expat_Version;\r
+\r
+/* Return an XML_Expat_Version structure containing numeric version\r
+   number information for this version of expat.\r
+*/\r
+XMLPARSEAPI(XML_Expat_Version)\r
+XML_ExpatVersionInfo(void);\r
+\r
+/* Added in Expat 1.95.5. */\r
+enum XML_FeatureEnum {\r
+  XML_FEATURE_END = 0,\r
+  XML_FEATURE_UNICODE,\r
+  XML_FEATURE_UNICODE_WCHAR_T,\r
+  XML_FEATURE_DTD,\r
+  XML_FEATURE_CONTEXT_BYTES,\r
+  XML_FEATURE_MIN_SIZE,\r
+  XML_FEATURE_SIZEOF_XML_CHAR,\r
+  XML_FEATURE_SIZEOF_XML_LCHAR,\r
+  XML_FEATURE_NS,\r
+  XML_FEATURE_LARGE_SIZE\r
+  /* Additional features must be added to the end of this enum. */\r
+};\r
+\r
+typedef struct {\r
+  enum XML_FeatureEnum  feature;\r
+  const XML_LChar       *name;\r
+  long int              value;\r
+} XML_Feature;\r
+\r
+XMLPARSEAPI(const XML_Feature *)\r
+XML_GetFeatureList(void);\r
+\r
+\r
+/* Expat follows the GNU/Linux convention of odd number minor version for\r
+   beta/development releases and even number minor version for stable\r
+   releases. Micro is bumped with each release, and set to 0 with each\r
+   change to major or minor version.\r
+*/\r
+#define XML_MAJOR_VERSION 2\r
+#define XML_MINOR_VERSION 0\r
+#define XML_MICRO_VERSION 1\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* not Expat_INCLUDED */\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/expat_external.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/expat_external.h
new file mode 100644 (file)
index 0000000..bb83a99
--- /dev/null
@@ -0,0 +1,115 @@
+/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+   See the file COPYING for copying permission.\r
+*/\r
+\r
+#ifndef Expat_External_INCLUDED\r
+#define Expat_External_INCLUDED 1\r
+\r
+/* External API definitions */\r
+\r
+#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)\r
+#define XML_USE_MSC_EXTENSIONS 1\r
+#endif\r
+\r
+/* Expat tries very hard to make the API boundary very specifically\r
+   defined.  There are two macros defined to control this boundary;\r
+   each of these can be defined before including this header to\r
+   achieve some different behavior, but doing so it not recommended or\r
+   tested frequently.\r
+\r
+   XMLCALL    - The calling convention to use for all calls across the\r
+                "library boundary."  This will default to cdecl, and\r
+                try really hard to tell the compiler that's what we\r
+                want.\r
+\r
+   XMLIMPORT  - Whatever magic is needed to note that a function is\r
+                to be imported from a dynamically loaded library\r
+                (.dll, .so, or .sl, depending on your platform).\r
+\r
+   The XMLCALL macro was added in Expat 1.95.7.  The only one which is\r
+   expected to be directly useful in client code is XMLCALL.\r
+\r
+   Note that on at least some Unix versions, the Expat library must be\r
+   compiled with the cdecl calling convention as the default since\r
+   system headers may assume the cdecl convention.\r
+*/\r
+#ifndef XMLCALL\r
+#if defined(_MSC_VER)\r
+#define XMLCALL __cdecl\r
+#elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)\r
+#define XMLCALL __attribute__((cdecl))\r
+#else\r
+/* For any platform which uses this definition and supports more than\r
+   one calling convention, we need to extend this definition to\r
+   declare the convention used on that platform, if it's possible to\r
+   do so.\r
+\r
+   If this is the case for your platform, please file a bug report\r
+   with information on how to identify your platform via the C\r
+   pre-processor and how to specify the same calling convention as the\r
+   platform's malloc() implementation.\r
+*/\r
+#define XMLCALL\r
+#endif\r
+#endif  /* not defined XMLCALL */\r
+\r
+\r
+#if !defined(XML_STATIC) && !defined(XMLIMPORT)\r
+#ifndef XML_BUILDING_EXPAT\r
+/* using Expat from an application */\r
+\r
+#ifdef XML_USE_MSC_EXTENSIONS\r
+#define XMLIMPORT __declspec(dllimport)\r
+#endif\r
+\r
+#endif\r
+#endif  /* not defined XML_STATIC */\r
+\r
+\r
+/* If we didn't define it above, define it away: */\r
+#ifndef XMLIMPORT\r
+#define XMLIMPORT\r
+#endif\r
+\r
+\r
+#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#ifdef XML_UNICODE_WCHAR_T\r
+#define XML_UNICODE\r
+#endif\r
+\r
+#ifdef XML_UNICODE     /* Information is UTF-16 encoded. */\r
+#ifdef XML_UNICODE_WCHAR_T\r
+typedef wchar_t XML_Char;\r
+typedef wchar_t XML_LChar;\r
+#else\r
+typedef unsigned short XML_Char;\r
+typedef char XML_LChar;\r
+#endif /* XML_UNICODE_WCHAR_T */\r
+#else                  /* Information is UTF-8 encoded. */\r
+typedef char XML_Char;\r
+typedef char XML_LChar;\r
+#endif /* XML_UNICODE */\r
+\r
+#ifdef XML_LARGE_SIZE  /* Use large integers for file/stream positions. */\r
+#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400\r
+typedef __int64 XML_Index; \r
+typedef unsigned __int64 XML_Size;\r
+#else\r
+typedef long long XML_Index;\r
+typedef unsigned long long XML_Size;\r
+#endif\r
+#else\r
+typedef long XML_Index;\r
+typedef unsigned long XML_Size;\r
+#endif /* XML_LARGE_SIZE */\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* not Expat_External_INCLUDED */\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/libexpatMT.lib b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/libexpatMT.lib
new file mode 100644 (file)
index 0000000..2436f61
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/libexpatMT.lib differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/sim_support.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/sim_support.c
new file mode 100644 (file)
index 0000000..32b5439
--- /dev/null
@@ -0,0 +1,476 @@
+/* ------------------------------------------------------------------------- \r
+ * sim_support.c\r
+ * Functions used by both FMU simulators fmusim_me and fmusim_cs\r
+ * to parse command-line arguments, to unzip and load an fmu, \r
+ * to write CSV file, and more.\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+\r
+#ifdef FMI_COSIMULATION\r
+#include "fmi_cs.h"\r
+#else\r
+#include "fmi_me.h"\r
+#endif\r
+\r
+#include "sim_support.h"\r
+\r
+extern FMU fmu;\r
+\r
+int unzip(const char *zipPath, const char *outPath) {\r
+    int code;\r
+    char cwd[BUFSIZE];\r
+    char binPath[BUFSIZE];\r
+    int n = strlen(UNZIP_CMD) + strlen(outPath) + 1 +  strlen(zipPath) + 9;\r
+    char* cmd = (char*)calloc(sizeof(char), n);\r
+\r
+    // remember current directory\r
+    if (!GetCurrentDirectory(BUFSIZE, cwd)) {\r
+        printf ("error: Could not get current directory\n");\r
+        return 0; // error\r
+    }\r
+        \r
+    // change to %FMUSDK_HOME%\bin to find 7z.dll and 7z.exe\r
+    if (!GetEnvironmentVariable("FMUSDK_HOME", binPath, BUFSIZE)) {\r
+        if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {\r
+            printf ("error: Environment variable FMUSDK_HOME not defined\n");\r
+        }\r
+        else {\r
+            printf ("error: Could not get value of FMUSDK_HOME\n");\r
+        }\r
+        return 0; // error       \r
+    }\r
+    strcat(binPath, "\\bin");\r
+    if (!SetCurrentDirectory(binPath)) {\r
+        printf ("error: could not change to directory '%s'\n", binPath); \r
+        return 0; // error        \r
+    }\r
+   \r
+    // run the unzip command\r
+    // remove "> NUL" to see the unzip protocol\r
+    sprintf(cmd, "%s%s \"%s\" > NUL", UNZIP_CMD, outPath, zipPath); \r
+    // printf("cmd='%s'\n", cmd);\r
+    code = system(cmd);\r
+    free(cmd);\r
+    if (code!=SEVEN_ZIP_NO_ERROR) {\r
+        switch (code) {\r
+            printf("7z: ");\r
+            case SEVEN_ZIP_WARNING:            printf("warning\n"); break;\r
+            case SEVEN_ZIP_ERROR:              printf("error\n"); break;\r
+            case SEVEN_ZIP_COMMAND_LINE_ERROR: printf("command line error\n"); break;\r
+            case SEVEN_ZIP_OUT_OF_MEMORY:      printf("out of memory\n"); break;\r
+            case SEVEN_ZIP_STOPPED_BY_USER:    printf("stopped by user\n"); break;\r
+            default: printf("unknown problem\n");\r
+        }\r
+    }\r
+    \r
+    // restore current directory\r
+    SetCurrentDirectory(cwd);\r
+    \r
+    return (code==SEVEN_ZIP_NO_ERROR || code==SEVEN_ZIP_WARNING) ? 1 : 0;  \r
+}\r
+\r
+// fileName is an absolute path, e.g. C:\test\a.fmu\r
+// or relative to the current dir, e.g. ..\test\a.fmu\r
+// Does not check for existence of the file\r
+static char* getFmuPath(const char* fileName){\r
+    char pathName[MAX_PATH];\r
+    int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL);\r
+    return n ? strdup(pathName) : NULL;\r
+}\r
+\r
+static char* getTmpPath() {\r
+    char tmpPath[BUFSIZE];\r
+    if(! GetTempPath(BUFSIZE, tmpPath)) {\r
+        printf ("error: Could not find temporary disk space\n");\r
+        return NULL;\r
+    }\r
+    strcat(tmpPath, "fmu\\");\r
+    return strdup(tmpPath);\r
+}\r
+\r
+static void* getAdr(int* s, FMU *fmu, const char* functionName){\r
+    char name[BUFSIZE];\r
+    void* fp;\r
+    sprintf(name, "%s_%s", getModelIdentifier(fmu->modelDescription), functionName);\r
+    fp = GetProcAddress(fmu->dllHandle, name);\r
+    if (!fp) {\r
+        printf ("warning: Function %s not found in dll\n", name);\r
+        *s = 0; // mark dll load as 'failed'        \r
+    }\r
+    return fp;\r
+}\r
+\r
+// Load the given dll and set function pointers in fmu\r
+// Return 0 to indicate failure\r
+static int loadDll(const char* dllPath, FMU *fmu) {\r
+    int x = 1, s = 1;\r
+    HANDLE h = LoadLibrary(dllPath);\r
+    if (!h) {\r
+        printf("error: Could not load %s\n", dllPath);\r
+        return 0; // failure\r
+    }\r
+    fmu->dllHandle = h;\r
+\r
+#ifdef FMI_COSIMULATION   \r
+    fmu->getTypesPlatform        = (fGetTypesPlatform)   getAdr(&s, fmu, "fmiGetTypesPlatform");\r
+    if (s==0) { \r
+        s = 1; // work around bug for FMUs exported using Dymola 2012 and SimulationX 3.x\r
+        fmu->getTypesPlatform    = (fGetTypesPlatform)   getAdr(&s, fmu, "fmiGetModelTypesPlatform");\r
+        if (s==1) printf("  using fmiGetModelTypesPlatform instead\n", dllPath);\r
+    }\r
+    fmu->instantiateSlave        = (fInstantiateSlave)   getAdr(&s, fmu, "fmiInstantiateSlave");\r
+    fmu->initializeSlave         = (fInitializeSlave)    getAdr(&s, fmu, "fmiInitializeSlave");    \r
+    fmu->terminateSlave          = (fTerminateSlave)     getAdr(&s, fmu, "fmiTerminateSlave");\r
+    fmu->resetSlave              = (fResetSlave)         getAdr(&s, fmu, "fmiResetSlave");\r
+    fmu->freeSlaveInstance       = (fFreeSlaveInstance)  getAdr(&s, fmu, "fmiFreeSlaveInstance");\r
+    fmu->setRealInputDerivatives = (fSetRealInputDerivatives) getAdr(&s, fmu, "fmiSetRealInputDerivatives");\r
+    fmu->getRealOutputDerivatives = (fGetRealOutputDerivatives) getAdr(&s, fmu, "fmiGetRealOutputDerivatives");\r
+    fmu->cancelStep              = (fCancelStep)         getAdr(&s, fmu, "fmiCancelStep");\r
+    fmu->doStep                  = (fDoStep)             getAdr(&s, fmu, "fmiDoStep");\r
+    // SimulationX 3.4 and 3.5 do not yet export getStatus and getXStatus: do not count this as failure here\r
+    fmu->getStatus               = (fGetStatus)          getAdr(&x, fmu, "fmiGetStatus");\r
+    fmu->getRealStatus           = (fGetRealStatus)      getAdr(&x, fmu, "fmiGetRealStatus");\r
+    fmu->getIntegerStatus        = (fGetIntegerStatus)   getAdr(&x, fmu, "fmiGetIntegerStatus");\r
+    fmu->getBooleanStatus        = (fGetBooleanStatus)   getAdr(&x, fmu, "fmiGetBooleanStatus");\r
+    fmu->getStringStatus         = (fGetStringStatus)    getAdr(&x, fmu, "fmiGetStringStatus");    \r
+\r
+#else // FMI for Model Exchange 1.0\r
+    fmu->getModelTypesPlatform   = (fGetModelTypesPlatform) getAdr(&s, fmu, "fmiGetModelTypesPlatform");\r
+    fmu->instantiateModel        = (fInstantiateModel)   getAdr(&s, fmu, "fmiInstantiateModel");\r
+    fmu->freeModelInstance       = (fFreeModelInstance)  getAdr(&s, fmu, "fmiFreeModelInstance");\r
+    fmu->setTime                 = (fSetTime)            getAdr(&s, fmu, "fmiSetTime");\r
+    fmu->setContinuousStates     = (fSetContinuousStates)getAdr(&s, fmu, "fmiSetContinuousStates");\r
+    fmu->completedIntegratorStep = (fCompletedIntegratorStep)getAdr(&s, fmu, "fmiCompletedIntegratorStep");\r
+    fmu->initialize              = (fInitialize)         getAdr(&s, fmu, "fmiInitialize");\r
+    fmu->getDerivatives          = (fGetDerivatives)     getAdr(&s, fmu, "fmiGetDerivatives");\r
+    fmu->getEventIndicators      = (fGetEventIndicators) getAdr(&s, fmu, "fmiGetEventIndicators");\r
+    fmu->eventUpdate             = (fEventUpdate)        getAdr(&s, fmu, "fmiEventUpdate");\r
+    fmu->getContinuousStates     = (fGetContinuousStates)getAdr(&s, fmu, "fmiGetContinuousStates");\r
+    fmu->getNominalContinuousStates = (fGetNominalContinuousStates)getAdr(&s, fmu, "fmiGetNominalContinuousStates");\r
+    fmu->getStateValueReferences = (fGetStateValueReferences)getAdr(&s, fmu, "fmiGetStateValueReferences");\r
+    fmu->terminate               = (fTerminate)          getAdr(&s, fmu, "fmiTerminate");\r
+#endif \r
+    fmu->getVersion              = (fGetVersion)         getAdr(&s, fmu, "fmiGetVersion");\r
+    fmu->setDebugLogging         = (fSetDebugLogging)    getAdr(&s, fmu, "fmiSetDebugLogging");\r
+    fmu->setReal                 = (fSetReal)            getAdr(&s, fmu, "fmiSetReal");\r
+    fmu->setInteger              = (fSetInteger)         getAdr(&s, fmu, "fmiSetInteger");\r
+    fmu->setBoolean              = (fSetBoolean)         getAdr(&s, fmu, "fmiSetBoolean");\r
+    fmu->setString               = (fSetString)          getAdr(&s, fmu, "fmiSetString");\r
+    fmu->getReal                 = (fGetReal)            getAdr(&s, fmu, "fmiGetReal");\r
+    fmu->getInteger              = (fGetInteger)         getAdr(&s, fmu, "fmiGetInteger");\r
+    fmu->getBoolean              = (fGetBoolean)         getAdr(&s, fmu, "fmiGetBoolean");\r
+    fmu->getString               = (fGetString)          getAdr(&s, fmu, "fmiGetString");\r
+    return s; \r
+}\r
+\r
+static void printModelDescription(ModelDescription* md){\r
+    Element* e = (Element*)md;  \r
+    int i;\r
+    printf("%s\n", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf("  %s=%s\n", e->attributes[i], e->attributes[i+1]);\r
+#ifdef FMI_COSIMULATION   \r
+    if (!md->cosimulation) {\r
+        printf("error: No Implementation element found in model description. This FMU is not for Co-Simulation.\n");\r
+        exit(EXIT_FAILURE);\r
+    }\r
+    e = md->cosimulation->capabilities;\r
+    printf("%s\n", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf("  %s=%s\n", e->attributes[i], e->attributes[i+1]);\r
+#endif // FMI_COSIMULATION  \r
+}\r
+\r
+void loadFMU(const char* fmuFileName) {\r
+    char* fmuPath;\r
+    char* tmpPath;\r
+    char* xmlPath;\r
+    char* dllPath;\r
+    \r
+    // get absolute path to FMU, NULL if not found\r
+    fmuPath = getFmuPath(fmuFileName);\r
+    if (!fmuPath) exit(EXIT_FAILURE);\r
+\r
+    // unzip the FMU to the tmpPath directory\r
+    tmpPath = getTmpPath();\r
+    if (!unzip(fmuPath, tmpPath)) exit(EXIT_FAILURE);\r
+\r
+    // parse tmpPath\modelDescription.xml\r
+    xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1);\r
+    sprintf(xmlPath, "%s%s", tmpPath, XML_FILE);\r
+    fmu.modelDescription = parse(xmlPath);\r
+    free(xmlPath);\r
+    if (!fmu.modelDescription) exit(EXIT_FAILURE);\r
+    printModelDescription(fmu.modelDescription);\r
+\r
+    // load the FMU dll\r
+    dllPath = calloc(sizeof(char), strlen(tmpPath) + strlen(DLL_DIR) \r
+            + strlen( getModelIdentifier(fmu.modelDescription)) +  strlen(".dll") + 1);\r
+    sprintf(dllPath,"%s%s%s.dll", tmpPath, DLL_DIR, getModelIdentifier(fmu.modelDescription));\r
+    if (!loadDll(dllPath, &fmu)) exit(EXIT_FAILURE); \r
+    free(dllPath);\r
+    free(fmuPath);\r
+    free(tmpPath);\r
+}\r
+\r
+static void doubleToCommaString(char* buffer, double r){\r
+    char* comma;\r
+    sprintf(buffer, "%.16g", r);\r
+    comma = strchr(buffer, '.');\r
+    if (comma) *comma = ',';\r
+}\r
+\r
+// output time and all non-alias variables in CSV format\r
+// if separator is ',', columns are separated by ',' and '.' is used for floating-point numbers.\r
+// otherwise, the given separator (e.g. ';' or '\t') is to separate columns, and ',' is used \r
+// as decimal dot in floating-point numbers.\r
+void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, boolean header) {\r
+    int k;\r
+    fmiReal r;\r
+    fmiInteger i;\r
+    fmiBoolean b;\r
+    fmiString s;\r
+    fmiValueReference vr;\r
+    ScalarVariable** vars = fmu->modelDescription->modelVariables;\r
+    char buffer[32];\r
+    \r
+    // print first column\r
+    if (header) \r
+        fprintf(file, "time"); \r
+    else {\r
+        if (separator==',') \r
+            fprintf(file, "%.16g", time);\r
+        else {\r
+            // separator is e.g. ';' or '\t'\r
+            doubleToCommaString(buffer, time);\r
+            fprintf(file, "%s", buffer);       \r
+        }\r
+    }\r
+    \r
+    // print all other columns\r
+    for (k=0; vars[k]; k++) {\r
+        ScalarVariable* sv = vars[k];\r
+        if (getAlias(sv)!=enu_noAlias) continue;\r
+        if (header) {\r
+            // output names only\r
+            if (separator==',') {\r
+                // treat array element, e.g. print a[1, 2] as a[1.2]\r
+                char* s = getName(sv);\r
+                fprintf(file, "%c", separator);\r
+                while (*s) {\r
+                   if (*s!=' ') fprintf(file, "%c", *s==',' ? '.' : *s);\r
+                   s++;\r
+                }\r
+             }\r
+            else\r
+                fprintf(file, "%c%s", separator, getName(sv));\r
+        }\r
+        else {\r
+            // output values\r
+            vr = getValueReference(sv);\r
+            switch (sv->typeSpec->type){\r
+                case elm_Real:\r
+                    fmu->getReal(c, &vr, 1, &r);\r
+                    if (separator==',') \r
+                        fprintf(file, ",%.16g", r);\r
+                    else {\r
+                        // separator is e.g. ';' or '\t'\r
+                        doubleToCommaString(buffer, r);\r
+                        fprintf(file, "%c%s", separator, buffer);       \r
+                    }\r
+                    break;\r
+                case elm_Integer:\r
+                case elm_Enumeration:\r
+                    fmu->getInteger(c, &vr, 1, &i);\r
+                    fprintf(file, "%c%d", separator, i);\r
+                    break;\r
+                case elm_Boolean:\r
+                    fmu->getBoolean(c, &vr, 1, &b);\r
+                    fprintf(file, "%c%d", separator, b);\r
+                    break;\r
+                case elm_String:\r
+                    fmu->getString(c, &vr, 1, &s);\r
+                    fprintf(file, "%c%s", separator, s);\r
+                    break;\r
+                default: \r
+                    fprintf(file, "%cNoValueForType=%d", separator,sv->typeSpec->type);\r
+            }\r
+        }\r
+    } // for\r
+    \r
+    // terminate this row\r
+    fprintf(file, "\n"); \r
+}\r
+\r
+static const char* fmiStatusToString(fmiStatus status){\r
+    switch (status){\r
+        case fmiOK:      return "ok";\r
+        case fmiWarning: return "warning";\r
+        case fmiDiscard: return "discard";\r
+        case fmiError:   return "error";\r
+        case fmiFatal:   return "fatal";\r
+#ifdef FMI_COSIMULATION\r
+        case fmiPending: return "fmiPending";\r
+#endif\r
+        default:         return "?";\r
+    }\r
+}\r
+\r
+// search a fmu for the given variable\r
+// return NULL if not found or vr = fmiUndefinedValueReference\r
+static ScalarVariable* getSV(FMU* fmu, char type, fmiValueReference vr) {\r
+    int i;\r
+    Elm tp;\r
+    ScalarVariable** vars = fmu->modelDescription->modelVariables;\r
+    if (vr==fmiUndefinedValueReference) return NULL;\r
+    switch (type) {\r
+        case 'r': tp = elm_Real;    break;\r
+        case 'i': tp = elm_Integer; break;\r
+        case 'b': tp = elm_Boolean; break;\r
+        case 's': tp = elm_String;  break;                \r
+    }\r
+    for (i=0; vars[i]; i++) {\r
+        ScalarVariable* sv = vars[i];\r
+        if (vr==getValueReference(sv) && tp==sv->typeSpec->type) \r
+            return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+// replace e.g. #r1365# by variable name and ## by # in message\r
+// copies the result to buffer\r
+static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU* fmu){\r
+    int i=0; // position in msg\r
+    int k=0; // position in buffer\r
+    int n;\r
+    char c = msg[i];\r
+    while (c!='\0' && k < nBuffer) {\r
+        if (c!='#') {\r
+            buffer[k++]=c;\r
+            i++;\r
+            c = msg[i];\r
+        }\r
+        else {\r
+            char* end = strchr(msg+i+1, '#');\r
+            if (!end) {\r
+                printf("unmatched '#' in '%s'\n", msg);\r
+                buffer[k++]='#';\r
+                break;\r
+            }\r
+            n = end - (msg+i);\r
+            if (n==1) {\r
+                // ## detected, output #\r
+                buffer[k++]='#';\r
+                i += 2;\r
+                c = msg[i];\r
+            }\r
+            else {\r
+                char type = msg[i+1]; // one of ribs\r
+                fmiValueReference vr;\r
+                int nvr = sscanf(msg+i+2, "%u", &vr);\r
+                if (nvr==1) {\r
+                    // vr of type detected, e.g. #r12#\r
+                    ScalarVariable* sv = getSV(fmu, type, vr);\r
+                    const char* name = sv ? getName(sv) : "?";\r
+                    sprintf(buffer+k, "%s", name);\r
+                    k += strlen(name);\r
+                    i += (n+1);\r
+                    c = msg[i]; \r
+                }\r
+                else {\r
+                    // could not parse the number\r
+                    printf("illegal value reference at position %d in '%s'\n", i+2, msg);\r
+                    buffer[k++]='#';\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+    } // while\r
+    buffer[k] = '\0';\r
+}\r
+\r
+#define MAX_MSG_SIZE 1000\r
+void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status,\r
+               fmiString category, fmiString message, ...) {\r
+    char msg[MAX_MSG_SIZE];\r
+    char* copy;\r
+    va_list argp;\r
+\r
+    // replace C format strings\r
+         va_start(argp, message);\r
+    vsprintf(msg, message, argp);\r
+\r
+    // replace e.g. ## and #r12#  \r
+    copy = strdup(msg);\r
+    replaceRefsInMessage(copy, msg, MAX_MSG_SIZE, &fmu);\r
+    free(copy);\r
+    \r
+    // print the final message\r
+    if (!instanceName) instanceName = "?";\r
+    if (!category) category = "?";\r
+    printf("%s %s (%s): %s\n", fmiStatusToString(status), instanceName, category, msg);\r
+}\r
+\r
+int error(const char* message){\r
+    printf("%s\n", message);\r
+    return 0;\r
+}\r
+\r
+void parseArguments(int argc, char *argv[], char** fmuFileName, double* tEnd, double* h, int* loggingOn, char* csv_separator) {\r
+    // parse command line arguments\r
+    if (argc>1) {\r
+        *fmuFileName = argv[1];\r
+    }\r
+    else {\r
+        printf("error: no fmu file\n");\r
+        printHelp(argv[0]);\r
+        exit(EXIT_FAILURE);\r
+    }\r
+    if (argc>2) {\r
+        if (sscanf(argv[2],"%lf", tEnd) != 1) {\r
+            printf("error: The given end time (%s) is not a number\n", argv[2]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>3) {\r
+        if (sscanf(argv[3],"%lf", h) != 1) {\r
+            printf("error: The given stepsize (%s) is not a number\n", argv[3]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>4) {\r
+        if (sscanf(argv[4],"%d", loggingOn) != 1 || *loggingOn<0 || *loggingOn>1) {\r
+            printf("error: The given logging flag (%s) is not boolean\n", argv[4]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>5) {\r
+        if (strlen(argv[5]) != 1) {\r
+            printf("error: The given CSV separator char (%s) is not valid\n", argv[5]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+        switch (argv[5][0]) {\r
+            case 'c': *csv_separator = ','; break; // comma\r
+            case 's': *csv_separator = ';'; break; // semicolon\r
+            default:  *csv_separator = argv[5][0]; break; // any other char\r
+        }\r
+    }\r
+    if (argc>6) {\r
+        printf("warning: Ignoring %d additional arguments: %s ...\n", argc-6, argv[6]);\r
+        printHelp(argv[0]);\r
+    }\r
+}\r
+\r
+void printHelp(const char* fmusim) {\r
+    printf("command syntax: %s <model.fmu> <tEnd> <h> <loggingOn> <csv separator>\n", fmusim);\r
+    printf("   <model.fmu> .... path to FMU, relative to current dir or absolute, required\n");\r
+    printf("   <tEnd> ......... end  time of simulation, optional, defaults to 1.0 sec\n");\r
+    printf("   <h> ............ step size of simulation, optional, defaults to 0.1 sec\n");\r
+    printf("   <loggingOn> .... 1 to activate logging,   optional, defaults to 0\n");\r
+    printf("   <csv separator>. separator in csv file,   optional, c for ';', s for';', defaults to c\n");\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/sim_support.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/sim_support.h
new file mode 100644 (file)
index 0000000..648c8b5
--- /dev/null
@@ -0,0 +1,31 @@
+/* ------------------------------------------------------------------------- \r
+ * sim_support.h\r
+ * Functions used by the FMU simulatios fmusim_me and fmusim_cs.\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+// Used 7z options, version 4.57:\r
+// -x   Extracts files from an archive with their full paths in the current dir, or in an output dir if specified\r
+// -aoa Overwrite All existing files without prompt\r
+// -o   Specifies a destination directory where files are to be extracted\r
+#define UNZIP_CMD "7z x -aoa -o"\r
+#define XML_FILE  "modelDescription.xml"\r
+#define DLL_DIR   "binaries\\win32\\"\r
+#define RESULT_FILE "result.csv"\r
+#define BUFSIZE 4096\r
+\r
+// return codes of the 7z command line tool\r
+#define SEVEN_ZIP_NO_ERROR 0 // success\r
+#define SEVEN_ZIP_WARNING 1  // e.g., one or more files were locked during zip\r
+#define SEVEN_ZIP_ERROR 2\r
+#define SEVEN_ZIP_COMMAND_LINE_ERROR 7\r
+#define SEVEN_ZIP_OUT_OF_MEMORY 8\r
+#define SEVEN_ZIP_STOPPED_BY_USER 255\r
+\r
+void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status, fmiString category, fmiString message, ...);\r
+int unzip(const char *zipPath, const char *outPath);\r
+void parseArguments(int argc, char *argv[], char** fmuFileName, double* tEnd, double* h, int* loggingOn, char* csv_separator);\r
+void loadFMU(const char* fmuFileName);\r
+void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, boolean header);\r
+int error(const char* message);\r
+void printHelp(const char* fmusim);\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/stack.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/stack.c
new file mode 100644 (file)
index 0000000..042b796
--- /dev/null
@@ -0,0 +1,85 @@
+/* ------------------------------------------------------------------------- \r
+ * stack.c\r
+ * A stack of pointers. \r
+ * Copyright 2010 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <assert.h>\r
+#include "stack.h"\r
+\r
+Stack* stackNew(int initialSize, int inc){\r
+    Stack* s = (Stack*)malloc(sizeof(Stack));\r
+    s->stack = NULL;\r
+    s->stackSize = 0;\r
+    s->stackPos = -1;\r
+    s->initialSize = initialSize;\r
+    s->inc = inc;\r
+    return s;\r
+}\r
+\r
+int stackIsEmpty(Stack* s) {\r
+    return s->stackPos == -1;\r
+}\r
+\r
+// add an element to stack and grow stack if required\r
+// returns 1 to indicate success and 0 for error\r
+int stackPush(Stack* s, void* e) {\r
+    s->stackPos++;\r
+    if (s->stackPos==s->stackSize){\r
+               s->stackSize += (s->stack ? s->inc: s->initialSize);\r
+        s->stack = (void**) realloc(s->stack, s->stackSize * sizeof(void*));\r
+        if (!s->stack) return 0; // error;\r
+    }\r
+    s->stack[s->stackPos] = e;\r
+    return 1; // success\r
+}\r
+\r
+// return top element (possibly NULL), if stack not empty\r
+// runtime error if stack is empty\r
+void* stackPeek(Stack* s){\r
+    assert(!stackIsEmpty(s));\r
+    return s->stack[s->stackPos];\r
+}\r
+\r
+// remove top element (possibly NULL) from stack and return it\r
+// runtime error if stack is empty\r
+void* stackPop(Stack* s){\r
+    assert(!stackIsEmpty(s));\r
+    return s->stack[s->stackPos--];\r
+}\r
+\r
+// return the last n elements as null terminated array, \r
+// or NULL if memory allocation fails\r
+void** stackLastPopedAsArray0(Stack* s, int n){\r
+    int i;\r
+    void** array = (void**)malloc((n + 1)*sizeof(void*));\r
+    if (! array) return NULL; // failure\r
+    for (i=0; i<n; i++) {\r
+        array[i] = s->stack[i+ s->stackPos + 1];\r
+    }\r
+    array[n]=NULL; // terminating NULL\r
+    return array;\r
+}\r
+\r
+// return stack as possibly empty array, or NULL if memory allocation fails\r
+// On sucessful return, the stack is empty.\r
+void** stackPopAllAsArray(Stack* s, int *size) {\r
+    int i;\r
+    void** array = (void**)malloc((s->stackPos + 1)*sizeof(void*));\r
+    if (! array) return NULL; // failure\r
+    *size = s->stackPos + 1;\r
+    for (i=0; i<*size; i++) \r
+        array[i] = s->stack[i];\r
+    s->stackPos = -1;\r
+    return array; \r
+}\r
+\r
+// release the given stack\r
+void stackFree(Stack* s){\r
+    if (s->stack) free(s->stack);\r
+    free(s);\r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/stack.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/stack.h
new file mode 100644 (file)
index 0000000..a52977f
--- /dev/null
@@ -0,0 +1,28 @@
+/* ------------------------------------------------------------------------- \r
+ * stack.c\r
+ * A stack of pointers. \r
+ * Copyright 2010 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#ifndef STACK_H\r
+#define STACK_H\r
+\r
+typedef struct {\r
+    void** stack;\r
+    int stackSize;    // allocated size of stack\r
+    int stackPos;     // array index of top element, -1 if stack is empty.\r
+    int initialSize;  // how many element to allocate initially\r
+    int inc;          // how many elements to allocate when stack gets full\r
+} Stack;\r
+\r
+Stack* stackNew(int initialSize, int inc);\r
+int stackIsEmpty(Stack* s);\r
+int stackPush(Stack* s, void* e);\r
+void* stackPeek(Stack* s);\r
+void* stackPop(Stack* s);\r
+void** stackPopAllAsArray(Stack* s, int *size);\r
+void** stackLastPopedAsArray0(Stack* s, int n);\r
+void stackFree(Stack* s);\r
+\r
+#endif // STACK_H\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/xml_parser.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/xml_parser.c
new file mode 100644 (file)
index 0000000..93e6216
--- /dev/null
@@ -0,0 +1,860 @@
+/* ------------------------------------------------------------------------- \r
+ * xml_Parser.c\r
+ * A parser for file modelVariables.xml of an FMU.\r
+ * The parser creates an AST (abstract syntax tree) for a given XML file.\r
+ * The root node of the AST is of type ModelDescription.\r
+ * Validation already performed by this parser\r
+ * - check for match of open/close elements (performed by Expat)\r
+ * - ceck element, attribute and enum value names, all case sensitive\r
+ * - check for each element that is has the expected parent element\r
+ * - check for correct sequence of elements\r
+ * - check that all decalaredType values reference an existing Type\r
+ * Validation to be performed by this parser\r
+ * - check for each attribute value that it is of the expected type \r
+ * - check that required attributes are present  \r
+ * - check that dependencies are only declared for outputs and\r
+ *   refer only to inputs\r
+ * Author: Jakob Mauss\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/\r
+\r
+#include <stdio.h>\r
+#include <assert.h>\r
+#include <string.h>\r
+#include "xml_parser.h"\r
+\r
+const char *elmNames[SIZEOF_ELM] = { \r
+    "fmiModelDescription","UnitDefinitions","BaseUnit","DisplayUnitDefinition","TypeDefinitions",\r
+    "Type","RealType","IntegerType","BooleanType","StringType","EnumerationType","Item",\r
+     "DefaultExperiment","VendorAnnotations","Tool","Annotation", "ModelVariables","ScalarVariable",\r
+     "DirectDependency","Name","Real","Integer","Boolean","String","Enumeration",\r
+     "Implementation","CoSimulation_StandAlone","CoSimulation_Tool","Model","File","Capabilities"\r
+};\r
+\r
+const char *attNames[SIZEOF_ATT] = {\r
+    "fmiVersion","displayUnit","gain","offset","unit","name","description","quantity", "relativeQuantity",\r
+    "min","max","nominal","declaredType","start","fixed","startTime","stopTime","tolerance","value",\r
+    "valueReference","variability","causality","alias", "modelName","modelIdentifier","guid","author",\r
+    "version","generationTool","generationDateAndTime","variableNamingConvention","numberOfContinuousStates",\r
+    "numberOfEventIndicators","input",\r
+    "canHandleVariableCommunicationStepSize","canHandleEvents","canRejectSteps","canInterpolateInputs",\r
+    "maxOutputDerivativeOrder","canRunAsynchronuously","canSignalEvents","canBeInstantiatedOnlyOncePerProcess",\r
+    "canNotUseMemoryManagementFunctions","file","entryPoint","manualStart","type"\r
+};\r
+\r
+const char *enuNames[SIZEOF_ENU] = {\r
+    "flat","structured","constant","parameter","discrete","continuous",\r
+    "input","output", "internal","none","noAlias","alias","negatedAlias"\r
+};\r
+\r
+#define ANY_TYPE -1\r
+#define XMLBUFSIZE 1024\r
+char text[XMLBUFSIZE];       // XML file is parsed in chunks of length XMLBUFZIZE\r
+XML_Parser parser = NULL;    // non-NULL during parsing\r
+Stack* stack = NULL;         // the parser stack\r
+char* data = NULL;           // buffer that holds element content, see handleData\r
+int skipData=0;              // 1 to ignore element content, 0 when recordig content\r
+\r
+// ------------------------------------------------------------------------- \r
+// Low-level functions for inspecting the model description \r
+\r
+const char* getString(void* element, Att a){\r
+    Element* e = (Element*)element;\r
+    const char** attr = e->attributes;\r
+    int i;\r
+    for (i=0; i<e->n; i+=2)\r
+        if (attr[i]==attNames[a]) return attr[i+1];\r
+    return NULL;\r
+}\r
+\r
+double getDouble(void* element, Att a, ValueStatus* vs){\r
+    double d = 0;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return d; }\r
+    *vs = (1==sscanf(value, "%lf", &d)) ? valueDefined : valueIllegal;\r
+    return d;    \r
+}\r
+\r
+// getInt() is also used to retrieve Enumeration values from XML,\r
+// e.g. the start value for a variable of user-defined enumeration type.\r
+int getInt(void* element, Att a, ValueStatus* vs){\r
+    int n = 0;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return n; }\r
+    *vs = (1==sscanf(value, "%d", &n)) ? valueDefined : valueIllegal;\r
+    return n;    \r
+}\r
+\r
+unsigned int getUInt(void* element, Att a, ValueStatus* vs){\r
+    unsigned int u = -1;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return u; }\r
+    *vs = (1==sscanf(value, "%u", &u)) ? valueDefined : valueIllegal;\r
+    return u;    \r
+}\r
+\r
+char getBoolean(void* element, Att a, ValueStatus* vs){\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return 0; };\r
+    *vs = valueDefined;\r
+    if (!strcmp(value, "true")) return 1;\r
+    if (!strcmp(value, "false")) return 0;\r
+    *vs = valueIllegal;    \r
+    return 0;\r
+}\r
+\r
+static int checkEnumValue(const char* enu);\r
+\r
+// Retrieve the value of the given built-in enum attribute.\r
+// If the value is missing, this is marked in the ValueStatus\r
+// and the corresponding default is returned.\r
+// Returns -1 or a globally unique id for the value such that\r
+// enuNames[id] is the string representation of the enum value. \r
+Enu getEnumValue(void* element, Att a, ValueStatus* vs) {\r
+    const char* value = getString(element, a);\r
+    Enu id = valueDefined;\r
+    if (!value) { \r
+        *vs = valueMissing;\r
+        switch (a) {\r
+            case att_variableNamingConvention: return enu_flat;\r
+            case att_variability: return enu_continuous;\r
+            case att_causality: return enu_internal;\r
+            case att_alias: return enu_noAlias;\r
+            default: return -1;\r
+        }\r
+    }\r
+    id = checkEnumValue(value);\r
+    if (id==-1) *vs = valueIllegal; \r
+    return id;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Convenience methods for accessing the model description. \r
+// Use is only safe after the ast has been successfuly validated.\r
+\r
+const char* getModelIdentifier(ModelDescription* md) {\r
+    const char* modelId = getString(md, att_modelIdentifier);\r
+    assert(modelId); // this is a required attribute\r
+    return modelId;\r
+}\r
+\r
+int getNumberOfStates(ModelDescription* md) {\r
+    ValueStatus vs;\r
+    int n = getUInt(md, att_numberOfContinuousStates, &vs);\r
+    assert(vs==valueDefined); // this is a required attribute\r
+    return n;\r
+}\r
+\r
+int getNumberOfEventIndicators(ModelDescription* md) {\r
+    ValueStatus vs;\r
+    int n = getInt(md, att_numberOfEventIndicators, &vs);\r
+    assert(vs==valueDefined); // this is a required attribute\r
+    return n;\r
+}\r
+\r
+// name is a required attribute of ScalarVariable, Type, Item, Annotation, and Tool\r
+const char* getName(void* element) { \r
+    const char* name = getString(element, att_name);\r
+    assert(name); // this is a required attribute\r
+    return name;\r
+}\r
+\r
+// returns one of: input, output, internal, none\r
+// if value is missing, the default internal is returned\r
+Enu getCausality(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_causality, &vs);\r
+}\r
+\r
+// returns one of constant, parameter, discrete, continuous\r
+// if value is missing, the default continuous is returned\r
+Enu getVariability(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_variability, &vs);\r
+}\r
+\r
+// returns one of noAlias, alias, negatedAlias\r
+// if value is missing, the default noAlias is returned \r
+Enu getAlias(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_alias, &vs);\r
+}\r
+\r
+// the vr is unique only for one of the 4 base data types r,i,b,s and\r
+// may also be fmiUndefinedValueReference = 4294967295 = 0xFFFFFFFF\r
+// here, i means integer or enumeration\r
+fmiValueReference getValueReference(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    fmiValueReference vr = getUInt(scalarVariable, att_valueReference, &vs);\r
+    assert(((Element*)scalarVariable)->type == elm_ScalarVariable);\r
+    assert(vs==valueDefined); // this is a reqired attribute\r
+    return vr;\r
+}\r
+\r
+// the name is unique within a fmu\r
+ScalarVariable* getVariableByName(ModelDescription* md, const char* name) {\r
+    int i;\r
+    if (md->modelVariables)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        if (!strcmp(getName(sv), name)) return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+// Enumeration and Integer have the same base type while \r
+// Real, String, Boolean define own base types.\r
+int sameBaseType(Elm t1, Elm t2){\r
+    return t1==t2 || \r
+           t1==elm_Enumeration && t2==elm_Integer || \r
+           t2==elm_Enumeration && t1==elm_Integer;\r
+}\r
+\r
+// returns NULL if variable not found or vr==fmiUndefinedValueReference\r
+ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type){\r
+    int i;\r
+    if (md->modelVariables && vr!=fmiUndefinedValueReference)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        if (sameBaseType(type, sv->typeSpec->type) && getValueReference(sv) == vr) \r
+            return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+Type* getDeclaredType(ModelDescription* md, const char* declaredType){\r
+    int i;\r
+    if (declaredType && md->typeDefinitions)\r
+    for (i=0; md->typeDefinitions[i]; i++){\r
+        Type* tp = (Type*)md->typeDefinitions[i];\r
+        if (!strcmp(declaredType, getName(tp))) return tp;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+const char* getString2(ModelDescription* md, void* tp, Att a) {\r
+    Type* type;\r
+    const char* value = getString(tp, a);\r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    type = getDeclaredType(md, getString(tp, att_declaredType));\r
+    return type ? getString(type->typeSpec, a) : NULL;\r
+}\r
+\r
+// Get description from variable or from declared type, or NULL.\r
+const char * getDescription(ModelDescription* md, ScalarVariable* sv) {\r
+    const char* value = getString(sv, att_description);\r
+    Type* type; \r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    type = getDeclaredType(md, getString(sv->typeSpec, att_declaredType));\r
+    return type ? getString(type, att_description) : NULL;\r
+}\r
+\r
+// Get attribute value from scalar variable given by vr and type, \r
+// incl. default value provided by declared type, if any.\r
+const char * getVariableAttributeString(ModelDescription* md, \r
+        fmiValueReference vr, Elm type, Att a){\r
+    const char* value;\r
+    const char* declaredType;\r
+    Type* tp; \r
+    ScalarVariable* sv = getVariable(md, vr, type);\r
+    if (!sv) return NULL;\r
+    value = getString(sv->typeSpec, a);\r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    tp = getDeclaredType(md, getString(sv->typeSpec, att_declaredType));\r
+    return tp ? getString(tp->typeSpec, a) : NULL;\r
+}\r
+\r
+// Get attribute value from scalar variable given by vr and type, \r
+// incl. default value provided by declared type, if any.\r
+double getVariableAttributeDouble(ModelDescription* md, \r
+        fmiValueReference vr, Elm type, Att a, ValueStatus* vs){\r
+    double d = 0;\r
+    const char* value = getVariableAttributeString(md, vr, type, a);\r
+    if (!value) { *vs = valueMissing; return d; }\r
+    *vs = (1==sscanf(value, "%lf", &d)) ? valueDefined : valueIllegal;\r
+    return d;    \r
+}\r
+\r
+// Get nominal value from real variable or its declared type.\r
+// Return 1, if no nominal value is defined.\r
+double getNominal(ModelDescription* md, fmiValueReference vr){\r
+    ValueStatus vs;\r
+    double nominal = getVariableAttributeDouble(md, vr, elm_Real, att_nominal, &vs);\r
+    return vs==valueDefined ? nominal : 1.0;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Various checks that log an error and stop the parser \r
+\r
+// Returns 0 to indicate error\r
+static int checkPointer(const void* ptr){\r
+    if (! ptr) {\r
+        printf("Out of memory\n");\r
+        if (parser) XML_StopParser(parser, XML_FALSE);\r
+        return 0; // error \r
+    }\r
+    return 1; // success\r
+}\r
+\r
+static int checkName(const char* name, const char* kind, const char* array[], int n){\r
+    int i;\r
+    for (i=0; i<n; i++) {\r
+        if (!strcmp(name, array[i])) return i;\r
+    }\r
+    printf("Illegal %s %s\n", kind, name);\r
+    XML_StopParser(parser, XML_FALSE);\r
+    return -1;\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkElement(const char* elm){\r
+    return checkName(elm, "element", elmNames, SIZEOF_ELM);\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkAttribute(const char* att){\r
+    return checkName(att, "attribute", attNames, SIZEOF_ATT);\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkEnumValue(const char* enu){\r
+    return checkName(enu, "enum value", enuNames, SIZEOF_ENU);\r
+}\r
+\r
+static void logFatalTypeError(const char* expected, Elm found) {\r
+    printf("Wrong element type, expected %s, found %s\n", \r
+            expected, elmNames[found]);\r
+    XML_StopParser(parser, XML_FALSE);\r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Verify that Element elm is of the given type\r
+static int checkElementType(void* element, Elm e) {\r
+    Element* elm = (Element* )element;\r
+    if (elm->type == e) return 1; // success\r
+    logFatalTypeError(elmNames[e], elm->type);\r
+    return 0; // error    \r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Verify that the next stack element exists and is of the given type\r
+// If e==ANY_TYPE, the type check is ommited \r
+static int checkPeek(Elm e) {\r
+    if (stackIsEmpty(stack)){\r
+        printf("Illegal document structure, expected %s\n", elmNames[e]);\r
+        XML_StopParser(parser, XML_FALSE);\r
+        return 0; // error\r
+    }\r
+    return e==ANY_TYPE ? 1 : checkElementType(stackPeek(stack), e);\r
+}\r
+\r
+// Returns NULL to indicate error\r
+// Get the next stack element, it is of the given type.\r
+// If e==ANY_TYPE, the type check is ommited \r
+static void* checkPop(Elm e){\r
+    return checkPeek(e) ? stackPop(stack) : NULL;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Helper \r
+\r
+AstNodeType getAstNodeType(Elm e){\r
+    switch (e) {\r
+    case elm_fmiModelDescription: \r
+        return astModelDescription;\r
+    case elm_Type:\r
+        return astType;\r
+    case elm_ScalarVariable:\r
+        return astScalarVariable;\r
+    case elm_CoSimulation_StandAlone:\r
+    case elm_CoSimulation_Tool:\r
+        return astCoSimulation;\r
+    case elm_BaseUnit:\r
+    case elm_EnumerationType:\r
+    case elm_Tool:\r
+    case elm_UnitDefinitions:\r
+    case elm_TypeDefinitions:\r
+    case elm_VendorAnnotations:\r
+    case elm_ModelVariables:\r
+    case elm_DirectDependency:\r
+    case elm_Model:\r
+        return astListElement;\r
+    default:\r
+        return astElement; \r
+    }\r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Copies the attr array and all values.\r
+// Replaces all attribute names by constant literal strings.\r
+// Converts the null-terminated array into an array of known size n.\r
+int addAttributes(Element* el, const char** attr) {\r
+    int n, a;\r
+    const char** att = NULL;\r
+    for (n=0; attr[n]; n+=2);\r
+    if (n>0) {\r
+        att = calloc(n, sizeof(char*));\r
+        if (!checkPointer(att)) return 0;\r
+    } \r
+    for (n=0; attr[n]; n+=2) {\r
+        char* value = strdup(attr[n+1]);\r
+        if (!checkPointer(value)) return 0;\r
+        a = checkAttribute(attr[n]);\r
+        if (a == -1) return 0;  // illegal attribute error\r
+        att[n  ] = attNames[a]; // no heap memory\r
+        att[n+1] = value;       // heap memory\r
+    }\r
+    el->attributes = att; // NULL if n=0\r
+    el->n = n;\r
+    return 1; // success\r
+}\r
+\r
+// Returns NULL to indicate error\r
+Element* newElement(Elm type, int size, const char** attr) {\r
+    Element* e = (Element*)calloc(1, size);\r
+    if (!checkPointer(e)) return NULL; \r
+    e->type = type;\r
+    e->attributes = NULL;\r
+    e->n=0;\r
+    if (!addAttributes(e, attr)) return NULL;\r
+    return e;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// callback functions called by the XML parser \r
+\r
+// Create and push a new element node\r
+static void XMLCALL startElement(void *context, const char *elm, const char **attr) {\r
+    Elm el;\r
+    void* e;\r
+    int size;\r
+    el = checkElement(elm);\r
+    if (el==-1) return; // error\r
+    skipData = (el != elm_Name); // skip element content for all elements but Name\r
+    switch(getAstNodeType(el)){\r
+        case astElement:          size = sizeof(Element); break;\r
+        case astListElement:      size = sizeof(ListElement); break;\r
+        case astType:             size = sizeof(Type); break;\r
+        case astScalarVariable:   size = sizeof(ScalarVariable); break;\r
+        case astCoSimulation:     size = sizeof(CoSimulation); break;\r
+        case astModelDescription: size = sizeof(ModelDescription); break;\r
+               default: assert(0);\r
+    }\r
+    e = newElement(el, size, attr);\r
+    checkPointer(e); \r
+    stackPush(stack, e);\r
+}\r
+\r
+// Pop all elements of the given type from stack and \r
+// add it to the ListElement that follows.\r
+// The ListElement remains on the stack.\r
+static void popList(Elm e) {\r
+    int n = 0;\r
+    Element** array;\r
+    Element* elm = stackPop(stack);\r
+    while (elm->type == e) {\r
+        elm = stackPop(stack);\r
+        n++;\r
+    }\r
+    stackPush(stack, elm); // push ListElement back to stack\r
+    array = (Element**)stackLastPopedAsArray0(stack, n); // NULL terminated list\r
+    if (getAstNodeType(elm->type)!=astListElement) return; // failure\r
+    ((ListElement*)elm)->list = array;\r
+    return; // success only if list!=NULL    \r
+}\r
+\r
+// Pop the children from the stack and\r
+// check for correct type and sequence of children\r
+static void XMLCALL endElement(void *context, const char *elm) {\r
+    Elm el;\r
+    el = checkElement(elm);\r
+    switch(el) { \r
+        case elm_fmiModelDescription: \r
+            {\r
+                 ModelDescription* md;\r
+                 ListElement** ud = NULL;     // NULL or list of BaseUnits\r
+                 Type**        td = NULL;     // NULL or list of Types \r
+                 Element*      de = NULL;     // NULL or DefaultExperiment\r
+                 ListElement** va = NULL;     // NULL or list of Tools\r
+                 ScalarVariable** mv = NULL;  // NULL or list of ScalarVariable\r
+                 CoSimulation *cs = NULL;     // NULL or CoSimulation\r
+                 ListElement* child;\r
+\r
+                 child = checkPop(ANY_TYPE);\r
+                 if (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool) {\r
+                     cs = (CoSimulation*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_ModelVariables){\r
+                     mv = (ScalarVariable**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_VendorAnnotations){\r
+                     va = (ListElement**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_DefaultExperiment){\r
+                     de = (Element*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_TypeDefinitions){\r
+                     td = (Type**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_UnitDefinitions){\r
+                     ud = (ListElement**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 // work around bug of SimulationX 3.4 and 3.5 which places Implementation at wrong location \r
+                 if (!cs && (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool)) {\r
+                     cs = (CoSimulation*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (!checkElementType(child, elm_fmiModelDescription)) return;\r
+                 md = (ModelDescription*)child;\r
+                 md->modelVariables = mv;\r
+                 md->vendorAnnotations = va;\r
+                 md->defaultExperiment = de;\r
+                 md->typeDefinitions = td;\r
+                 md->unitDefinitions = ud;\r
+                 md->cosimulation = cs;\r
+                 stackPush(stack, md);\r
+                 break;\r
+            }\r
+        case elm_Implementation:\r
+            {\r
+                 // replace Implementation element\r
+                 void* cs = checkPop(ANY_TYPE);\r
+                 void* im = checkPop(elm_Implementation);\r
+                 stackPush(stack, cs);\r
+                 free(im);\r
+                 el = ((Element*)cs)->type;\r
+                 break;\r
+            }\r
+        case elm_CoSimulation_StandAlone:  \r
+            {\r
+                 Element* ca = checkPop(elm_Capabilities);\r
+                 CoSimulation* cs = checkPop(elm_CoSimulation_StandAlone);\r
+                 if (!ca || !cs) return;\r
+                 cs->capabilities = ca;\r
+                 stackPush(stack, cs);\r
+                 break;\r
+            }   \r
+        case elm_CoSimulation_Tool:\r
+            {\r
+                 ListElement* mo = checkPop(elm_Model);\r
+                 Element* ca = checkPop(elm_Capabilities);\r
+                 CoSimulation* cs = checkPop(elm_CoSimulation_Tool);\r
+                 if (!ca || !mo || !cs) return;\r
+                 cs->capabilities = ca;\r
+                 cs->model = mo;\r
+                 stackPush(stack, cs);\r
+                 break;\r
+            }   \r
+        case elm_Type:\r
+            {\r
+                Type* tp;\r
+                Element* ts = checkPop(ANY_TYPE);\r
+                if (!ts) return;\r
+                if (!checkPeek(elm_Type)) return;\r
+                tp = (Type*)stackPeek(stack);\r
+                switch (ts->type) {\r
+                    case elm_RealType:\r
+                    case elm_IntegerType:\r
+                    case elm_BooleanType:\r
+                    case elm_StringType:\r
+                    case elm_EnumerationType:\r
+                        break;\r
+                    default:\r
+                         logFatalTypeError("RealType or similar", ts->type);\r
+                         return;\r
+                }\r
+                tp->typeSpec = ts;\r
+                break;\r
+            }\r
+        case elm_ScalarVariable:\r
+            {\r
+                ScalarVariable* sv;\r
+                Element** list = NULL;\r
+                Element* child = checkPop(ANY_TYPE);\r
+                if (!child) return;\r
+                if (child->type==elm_DirectDependency){\r
+                    list = ((ListElement*)child)->list;\r
+                    free(child);\r
+                    child = checkPop(ANY_TYPE);\r
+                    if (!child) return;\r
+                }\r
+                if (!checkPeek(elm_ScalarVariable)) return;\r
+                sv = (ScalarVariable*)stackPeek(stack);\r
+                switch (child->type) {\r
+                    case elm_Real:\r
+                    case elm_Integer:\r
+                    case elm_Boolean:\r
+                    case elm_String:\r
+                    case elm_Enumeration:\r
+                        break;\r
+                    default:\r
+                         logFatalTypeError("Real or similar", child->type);\r
+                         return;\r
+                }\r
+                sv->directDependencies = list;\r
+                sv->typeSpec = child;\r
+                break;\r
+            }\r
+        case elm_ModelVariables:    popList(elm_ScalarVariable); break;\r
+        case elm_VendorAnnotations: popList(elm_Tool);break;\r
+        case elm_Tool:              popList(elm_Annotation); break;\r
+        case elm_TypeDefinitions:   popList(elm_Type); break;\r
+        case elm_EnumerationType:   popList(elm_Item); break;\r
+        case elm_UnitDefinitions:   popList(elm_BaseUnit); break;\r
+        case elm_BaseUnit:          popList(elm_DisplayUnitDefinition); break;\r
+        case elm_DirectDependency:  popList(elm_Name); break;\r
+        case elm_Model:             popList(elm_File); break;\r
+        case elm_Name:\r
+            {\r
+                 // Exception: the name value is represented as element content.\r
+                 // All other values of the XML file are represented using attributes.\r
+                 Element* name = checkPop(elm_Name);\r
+                 if (!name) return;\r
+                 name->n = 2;\r
+                 name->attributes = malloc(2*sizeof(char*));\r
+                 name->attributes[0] = attNames[att_input];\r
+                 name->attributes[1] = data;\r
+                 data = NULL;\r
+                 skipData = 1; // stop recording element content\r
+                 stackPush(stack, name);\r
+                 break;\r
+            }\r
+        case -1: return; // illegal element error\r
+        default: // must be a leaf Element\r
+                 assert(getAstNodeType(el)==astElement);\r
+                 break;\r
+    }\r
+    // All children of el removed from the stack.\r
+    // The top element must be of type el now.\r
+    checkPeek(el);\r
+}\r
+\r
+// Called to handle element data, e.g. "xy" in <Name>xy</Name>\r
+// Can be called many times, e.g. with "x" and then with "y" in the example above.\r
+// Feature in expat:\r
+// For some reason, if the element data is the empty string (Eg. <a></a>)\r
+// instead of an empty string with len == 0 we get "\n". The workaround is\r
+// to replace this with the empty string whenever we encounter "\n".\r
+void XMLCALL handleData(void *context, const XML_Char *s, int len) {\r
+    int n;\r
+    if (skipData) return;\r
+    if (!data) {\r
+        // start a new data string\r
+        if (len == 1 && s[0] == '\n') {\r
+            data = strdup("");\r
+        } else {\r
+            data = malloc(len + 1);\r
+            strncpy(data, s, len);\r
+            data[len] = '\0';\r
+        }\r
+    }\r
+    else {\r
+        // continue existing string\r
+        n = strlen(data) + len;\r
+        data = realloc(data, n+1);\r
+        strncat(data, s, len);\r
+        data[n] = '\0';\r
+    }\r
+    return;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// printing\r
\r
+static void printList(int indent, void** list);\r
+\r
+void printElement(int indent, void* element){\r
+    int i;\r
+    Element* e = (Element*)element;\r
+    if (!e) return;\r
+    // print attributes\r
+    for (i=0; i<indent; i++) printf(" ");\r
+    printf("%s", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf(" %s=%s", e->attributes[i], e->attributes[i+1]);\r
+    printf("\n");\r
+    // print child nodes\r
+    indent += 2;\r
+    switch (getAstNodeType(e->type)) {\r
+        case astListElement:\r
+            printList(indent, ((ListElement*)e)->list);\r
+            break;\r
+        case astScalarVariable:\r
+            printElement(indent, ((Type*)e)->typeSpec);\r
+            printList(indent, ((ScalarVariable*)e)->directDependencies);\r
+            break;\r
+        case astType:\r
+            printElement(indent, ((Type*)e)->typeSpec);\r
+            break;\r
+        case astCoSimulation: {\r
+            CoSimulation* cs = (CoSimulation*)e;\r
+            printElement(indent, cs->capabilities);\r
+            printElement(indent, cs->model);\r
+            break;\r
+        }\r
+        case astModelDescription: {\r
+            ModelDescription *md = (ModelDescription*)e;\r
+            printList(indent, md->unitDefinitions);\r
+            printList(indent, md->typeDefinitions);\r
+            printElement(indent, md->defaultExperiment);\r
+            printList(indent, md->vendorAnnotations);\r
+            printList(indent, md->modelVariables);\r
+            printElement(indent, md->cosimulation);\r
+            break;\r
+        }\r
+    }\r
+}\r
+\r
+static void printList(int indent, void** list){\r
+    int i;\r
+    if (list) for (i=0; list[i]; i++) \r
+       printElement(indent, list[i]);\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// free memory of the AST\r
+\r
+static void freeList(void** list);\r
+\r
+void freeElement(void* element){\r
+    int i;\r
+    Element* e = (Element*)element;\r
+    if (!e) return;\r
+    // free attributes\r
+    for (i=0; i<e->n; i+=2) \r
+        free(e->attributes[i+1]);\r
+    if (e->attributes) free(e->attributes);\r
+    // free child nodes\r
+    switch (getAstNodeType(e->type)) {\r
+        case astListElement:\r
+            freeList(((ListElement*)e)->list);\r
+            break;\r
+        case astScalarVariable:\r
+            freeList(((ScalarVariable*)e)->directDependencies);\r
+        case astType:\r
+            freeElement(((Type*)e)->typeSpec);\r
+            break;\r
+        case astCoSimulation: {\r
+            CoSimulation* cs = (CoSimulation*)e;\r
+            freeElement(cs->capabilities);\r
+            freeElement(cs->model);\r
+            break;\r
+        }\r
+        case astModelDescription: {\r
+            ModelDescription* md = (ModelDescription*)e;\r
+            freeList(md->unitDefinitions);\r
+            freeList(md->typeDefinitions);\r
+            freeElement(md->defaultExperiment);\r
+            freeList(md->vendorAnnotations);\r
+            freeList(md->modelVariables);\r
+            freeElement(md->cosimulation);\r
+            break;\r
+       }\r
+    }\r
+    // free the struct\r
+    free(e);\r
+}\r
+\r
+static void freeList(void** list){\r
+    int i;\r
+    if (!list) return;\r
+    for (i=0; list[i]; i++) \r
+        freeElement(list[i]);\r
+    free(list);\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Validation - done after parsing to report all errors \r
+\r
+ModelDescription* validate(ModelDescription* md) {\r
+    int error = 0;\r
+    int i;\r
+    if (md->modelVariables)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        char* declaredType = getString(sv->typeSpec, att_declaredType);\r
+        Type* decltype = getDeclaredType(md, declaredType);\r
+        if (declaredType && decltype==NULL) {\r
+            printf("Warning: Declared type %s of variable %s not found in modelDescription.xml\n", declaredType, getName(sv));\r
+            error++;\r
+        }\r
+    }\r
+    if (error) {\r
+        printf("Error: Found %d error in modelDescription.xml\n", error);\r
+        return NULL;\r
+    }\r
+    return md;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Entry function parse() of the XML parser \r
+\r
+static void cleanup(FILE *file) {\r
+    stackFree(stack);\r
+    stack = NULL;\r
+    XML_ParserFree(parser);\r
+    parser = NULL;\r
+    fclose(file);\r
+}\r
+\r
+// Returns NULL to indicate failure\r
+// Otherwise, return the root node md of the AST.\r
+// The receiver must call freeElement(md) to release AST memory.\r
+ModelDescription* parse(const char* xmlPath) {\r
+    ModelDescription* md = NULL;\r
+    FILE *file;\r
+    int done = 0;\r
+    stack = stackNew(100, 10);\r
+    if (!checkPointer(stack)) return NULL;  // failure\r
+    parser = XML_ParserCreate(NULL);\r
+    if (!checkPointer(parser)) return NULL;  // failure\r
+    XML_SetElementHandler(parser, startElement, endElement);\r
+    XML_SetCharacterDataHandler(parser, handleData);\r
+       file = fopen(xmlPath, "rb");\r
+       if (file == NULL) {\r
+        printf("Cannot open file '%s'\n", xmlPath);\r
+       XML_ParserFree(parser);\r
+        return NULL; // failure\r
+    }\r
+    while (!done) {\r
+        int n = fread(text, sizeof(char), XMLBUFSIZE, file);\r
+           if (n != XMLBUFSIZE) done = 1;\r
+        if (!XML_Parse(parser, text, n, done)){\r
+             printf("Parse error in file %s at line %d:\n%s\n", \r
+                     xmlPath,\r
+                        XML_GetCurrentLineNumber(parser),\r
+                        XML_ErrorString(XML_GetErrorCode(parser)));\r
+             while (! stackIsEmpty(stack)) md = stackPop(stack);\r
+             if (md) freeElement(md);\r
+             cleanup(file);\r
+             return NULL; // failure\r
+        }\r
+    }\r
+    md = stackPop(stack);\r
+    assert(stackIsEmpty(stack));\r
+    cleanup(file);\r
+    //printElement(1, md); // debug\r
+    return validate(md); // success if all refs are valid    \r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/xml_parser.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src _original/shared/xml_parser.h
new file mode 100644 (file)
index 0000000..0730d56
--- /dev/null
@@ -0,0 +1,159 @@
+/* ------------------------------------------------------------------------- \r
+ * xml_parser.h\r
+ * A parser for file modelVariables.xml of an FMU.\r
+ * Supports "FMI for Model Exchange 1.0" and "FMI for Co-Simulation 1.0".\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/\r
+\r
+#ifndef xml_parser_h\r
+#define xml_parser_h\r
+\r
+// define XML_STATIC before including expat.h\r
+// to prevent error when linking with libexpatMT.lib\r
+#define XML_STATIC \r
+#include "expat.h"\r
+#include "stack.h"\r
+\r
+typedef unsigned int fmiValueReference;\r
+#define fmiUndefinedValueReference (fmiValueReference)(-1)\r
+\r
+#define SIZEOF_ELM 31\r
+extern const char *elmNames[SIZEOF_ELM];\r
+\r
+#define SIZEOF_ATT 47\r
+extern const char *attNames[SIZEOF_ATT];\r
+\r
+#define SIZEOF_ENU 13\r
+extern const char *enuNames[SIZEOF_ENU];\r
+\r
+// Elements\r
+typedef enum {\r
+    elm_fmiModelDescription,elm_UnitDefinitions,elm_BaseUnit,elm_DisplayUnitDefinition,elm_TypeDefinitions,\r
+    elm_Type,elm_RealType,elm_IntegerType,elm_BooleanType,elm_StringType,elm_EnumerationType,elm_Item,\r
+    elm_DefaultExperiment,elm_VendorAnnotations,elm_Tool,elm_Annotation,elm_ModelVariables,elm_ScalarVariable,\r
+    elm_DirectDependency,elm_Name,elm_Real,elm_Integer,elm_Boolean,elm_String,elm_Enumeration,\r
+    elm_Implementation,elm_CoSimulation_StandAlone,elm_CoSimulation_Tool,elm_Model,elm_File,elm_Capabilities\r
+} Elm;\r
+\r
+// Attributes\r
+typedef enum { \r
+  att_fmiVersion,att_displayUnit,att_gain,att_offset,att_unit,att_name,att_description,att_quantity,att_relativeQuantity,\r
+  att_min,att_max,att_nominal,att_declaredType,att_start,att_fixed,att_startTime,att_stopTime,att_tolerance,att_value,\r
+  att_valueReference,att_variability,att_causality,att_alias,att_modelName,att_modelIdentifier,att_guid,att_author,\r
+  att_version,att_generationTool,att_generationDateAndTime,att_variableNamingConvention,att_numberOfContinuousStates,\r
+  att_numberOfEventIndicators,att_input,\r
+  att_canHandleVariableCommunicationStepSize,att_canHandleEvents,att_canRejectSteps,att_canInterpolateInputs,\r
+  att_maxOutputDerivativeOrder,att_canRunAsynchronuously,att_canSignalEvents,att_canBeInstantiatedOnlyOncePerProcess,\r
+  att_canNotUseMemoryManagementFunctions,att_entryPoint,att_manualStart,att_type\r
+} Att;\r
+\r
+// Enumeration values\r
+typedef enum {\r
+    enu_flat,enu_structured,enu_constant,enu_parameter,enu_discrete,enu_continuous,\r
+    enu_input,enu_output,enu_internal,enu_none,enu_noAlias,enu_alias,enu_negatedAlias    \r
+} Enu;\r
+\r
+// AST node for element \r
+// DisplayUnitDefinition, RealType, IntegerType, BooleanType, StringType, DefaultExperiment, \r
+// Item, Annotation, Name, Real, Integer, Boolean, String, Enumeration, Capabilities, File\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+} Element;\r
+\r
+// AST node for element that has a list of elements \r
+// BaseUnit, EnumerationType, Tool, DirectDependency, Model\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    Element** list;    // null-terminated array of pointers to elements, not null\r
+} ListElement;\r
+\r
+// AST node for element Type\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, an even number\r
+    Element* typeSpec; // one of RealType, IntegerType etc. \r
+} Type;\r
+\r
+// AST node for element ScalarVariable\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    Element* typeSpec; // one of Real, Integer, etc\r
+    Element** directDependencies; // null or null-terminated list of Name\r
+} ScalarVariable;\r
+\r
+// AST node for element CoSimulation_StandAlone and CoSimulation_Tool\r
+typedef struct {\r
+    Elm type; // one of elm_CoSimulation_StandAlone and elm_CoSimulation_Tool\r
+    const char** attributes; // null or n attribute value strings\r
+    int n;                   // size of attributes, even number\r
+    Element* capabilities;   // a set of capability attributes\r
+    ListElement* model;      // non-NULL to support tool coupling, NULL for standalone \r
+} CoSimulation;\r
+\r
+// AST node for element ModelDescription\r
+typedef struct {\r
+    Elm type;          // element type\r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    ListElement** unitDefinitions;    // NULL or null-terminated list of BaseUnits\r
+    Type**        typeDefinitions;    // NULL or null-terminated list of Types \r
+    Element*      defaultExperiment;  // NULL or DefaultExperiment\r
+    ListElement** vendorAnnotations;  // NULL or null-terminated list of Tools\r
+    ScalarVariable** modelVariables;  // NULL or null-terminated list of ScalarVariable\r
+    CoSimulation* cosimulation;       // NULL if this ModelDescription is for model exchange only\r
+} ModelDescription;\r
+\r
+// types of AST nodes used to represent an element\r
+typedef enum { \r
+    astElement, \r
+    astListElement,\r
+    astType,\r
+    astScalarVariable,\r
+    astCoSimulation,\r
+    astModelDescription\r
+} AstNodeType;\r
+\r
+// Possible results when retrieving an attribute value from an element\r
+typedef enum { \r
+    valueMissing,\r
+    valueDefined,\r
+    valueIllegal\r
+} ValueStatus;\r
+\r
+// Public methods: Parsing and low-level AST access\r
+ModelDescription* parse(const char* xmlPath);\r
+const char* getString(void* element, Att a);\r
+double getDouble     (void* element, Att a, ValueStatus* vs);\r
+int getInt           (void* element, Att a, ValueStatus* vs);\r
+unsigned int getUInt (void* element, Att a, ValueStatus* vs);\r
+char getBoolean      (void* element, Att a, ValueStatus* vs);\r
+Enu getEnumValue     (void* element, Att a, ValueStatus* vs);\r
+void freeElement     (void* element);\r
+\r
+// Convenience methods for AST access. To be used afer successful validation only.\r
+const char* getModelIdentifier(ModelDescription* md);\r
+int getNumberOfStates(ModelDescription* md);\r
+int getNumberOfEventIndicators(ModelDescription* md);\r
+const char* getName(void* element);\r
+Enu getCausality(void* scalarVariable);\r
+Enu getVariability(void* scalarVariable);\r
+Enu getAlias(void* scalarVariable);\r
+fmiValueReference getValueReference(void* scalarVariable);\r
+ScalarVariable* getVariableByName(ModelDescription* md, const char* name);\r
+ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type);\r
+Type* getDeclaredType(ModelDescription* md, const char* declaredType);\r
+const char* getString2(ModelDescription* md, void* sv, Att a);\r
+const char * getDescription(ModelDescription* md, ScalarVariable* sv);\r
+const char * getVariableAttributeString(ModelDescription* md, fmiValueReference vr, Elm type, Att a);\r
+double getVariableAttributeDouble(ModelDescription* md, fmiValueReference vr, Elm type, Att a, ValueStatus* vs);\r
+double getNominal(ModelDescription* md, fmiValueReference vr);\r
+\r
+#endif // xml_parser_h\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_all.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_all.bat
new file mode 100644 (file)
index 0000000..cdd7515
--- /dev/null
@@ -0,0 +1,28 @@
+@echo off \r
+\r
+rem ------------------------------------------------------------\r
+rem This batch builds both simulators and all FMUs of the FmuSDK\r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+call build_fmusim_me\r
+call build_fmusim_cs\r
+echo -----------------------------------------------------------\r
+echo Making the FMUs of the FmuSDK ...\r
+pushd models\r
+\r
+call build_fmu me dq \r
+call build_fmu me inc\r
+call build_fmu me values\r
+call build_fmu me vanDerPol\r
+call build_fmu me bouncingBall\r
+\r
+call build_fmu cs dq\r
+call build_fmu cs inc\r
+call build_fmu cs values\r
+call build_fmu cs vanDerPol\r
+call build_fmu cs bouncingBall\r
+\r
+popd\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_fmusim_cs.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_fmusim_cs.bat
new file mode 100644 (file)
index 0000000..6e90292
--- /dev/null
@@ -0,0 +1,48 @@
+@echo off \r
+rem ------------------------------------------------------------\r
+rem This batch builds the FMU simulator fmusim_cs.exe\r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+echo -----------------------------------------------------------\r
+echo building fmusim_cs.exe - FMI for Co-Simulation 1.0\r
+echo -----------------------------------------------------------\r
+\r
+rem save env variable settings\r
+set PREV_PATH=%PATH%\r
+if defined INCLUDE set PREV_INCLUDE=%INLUDE%\r
+if defined LIB     set PREV_LIB=%LIB%\r
+if defined LIBPATH set PREV_LIBPATH=%LIBPATH%\r
+\r
+rem setup the compiler\r
+if defined VS90COMNTOOLS (call "%VS90COMNTOOLS%\vsvars32.bat") else ^\r
+if defined VS80COMNTOOLS (call "%VS80COMNTOOLS%\vsvars32.bat") else ^\r
+goto noCompiler\r
+\r
+set SRC=fmusim_cs\main.c ..\shared\xml_parser.c ..\shared\stack.c ..\shared\sim_support.c\r
+set INC=/Iinclude /I../shared /Ifmusim_cs\r
+set OPTIONS=/DFMI_COSIMULATION /wd4090 /nologo\r
+\r
+rem create fmusim_cs.exe in the fmusim_cs dir\r
+rem /wd4090 to disable warnings about different 'const' qualifiers\r
+pushd co_simulation\r
+cl %SRC% %INC% %OPTIONS% /Fefmusim_cs.exe /link ..\shared\libexpatMT.lib  \r
+del *.obj\r
+popd\r
+if not exist co_simulation\fmusim_cs.exe goto compileError\r
+move /Y co_simulation\fmusim_cs.exe ..\bin\r
+goto done\r
+\r
+:noCompiler\r
+echo No Microsoft Visual C compiler found\r
+\r
+:compileError\r
+echo build of fmusim_cs.exe failed\r
+\r
+:done\r
+rem undo variable settings performed by vsvars32.bat\r
+set PATH=%PREV_PATH%\r
+if defined PREV_INCLUDE set INCLUDE=%PREV_INLUDE%\r
+if defined PREV_LIB     set LIB=%PREV_LIB%\r
+if defined PREV_LIBPATH set LIBPATH=%PREV_LIBPATH%\r
+echo done.\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_fmusim_me.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/build_fmusim_me.bat
new file mode 100644 (file)
index 0000000..0828428
--- /dev/null
@@ -0,0 +1,51 @@
+@echo off \r
+rem ------------------------------------------------------------\r
+rem This batch builds the FMU simulator fmusim_me.exe\r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+echo -----------------------------------------------------------\r
+echo building fmusim_me.exe - FMI for Model Exchange 1.0\r
+echo -----------------------------------------------------------\r
+\r
+rem save env variable settings\r
+set PREV_PATH=%PATH%\r
+if defined INCLUDE set PREV_INCLUDE=%INLUDE%\r
+if defined LIB     set PREV_LIB=%LIB%\r
+if defined LIBPATH set PREV_LIBPATH=%LIBPATH%\r
+\r
+rem setup the compiler\r
+if defined VS90COMNTOOLS (call "%VS90COMNTOOLS%\vsvars32.bat") else ^\r
+if defined VS80COMNTOOLS (call "%VS80COMNTOOLS%\vsvars32.bat") else ^\r
+goto noCompiler\r
+\r
+set SRC=fmusim_me\main.c ..\shared\xml_parser.c ..\shared\stack.c ..\shared\sim_support.c\r
+set INC=/Iinclude /I../shared /Ifmusim_me\r
+set OPTIONS=/wd4090 /nologo\r
+\r
+rem create fmusim_me.exe in the fmusim_me dir\r
+rem /wd4090 to disable warnings about different 'const' qualifiers\r
+pushd model_exchange\r
+cl %SRC% %INC% %OPTIONS% /Fefmusim_me.exe /link ..\shared\libexpatMT.lib  \r
+del *.obj\r
+popd\r
+if not exist model_exchange\fmusim_me.exe goto compileError\r
+move /Y model_exchange\fmusim_me.exe ..\bin\r
+goto done\r
+\r
+:noCompiler\r
+echo No Microsoft Visual C compiler found\r
+\r
+:compileError\r
+echo build of fmusim_me.exe failed\r
+\r
+:done\r
+rem undo variable settings performed by vsvars32.bat\r
+set PATH=%PREV_PATH%\r
+if defined PREV_INCLUDE set INCLUDE=%PREV_INLUDE%\r
+if defined PREV_LIB     set LIB=%PREV_LIB%\r
+if defined PREV_LIBPATH set LIBPATH=%PREV_LIBPATH%\r
+echo done.\r
+\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/fmusim_cs/fmi_cs.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/fmusim_cs/fmi_cs.h
new file mode 100644 (file)
index 0000000..f446eac
--- /dev/null
@@ -0,0 +1,78 @@
+/* ------------------------------------------------------------------------- \r
+ * fmi_cs.h\r
+ * Function types for all function of the "FMI for Co-Simulation 1.0"\r
+ * and a struct with the corresponding function pointers. \r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#ifndef FMI_CS_H\r
+#define FMI_CS_H\r
+\r
+#include <windows.h>\r
+#include "fmiFunctions.h"\r
+#include "xml_parser.h"\r
+\r
+typedef const char* (*fGetTypesPlatform)();\r
+typedef const char* (*fGetVersion)();\r
+typedef fmiStatus (*fSetDebugLogging)    (fmiComponent c, fmiBoolean loggingOn);\r
+typedef fmiStatus (*fSetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+typedef fmiStatus (*fSetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+typedef fmiStatus (*fSetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+typedef fmiStatus (*fSetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+typedef fmiStatus (*fGetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+typedef fmiStatus (*fGetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+typedef fmiStatus (*fGetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+typedef fmiStatus (*fGetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+typedef fmiComponent (*fInstantiateSlave)  (fmiString  instanceName, fmiString  fmuGUID, fmiString  fmuLocation, \r
+        fmiString  mimeType, fmiReal timeout, fmiBoolean visible, fmiBoolean interactive, \r
+        fmiCallbackFunctions functions, fmiBoolean loggingOn);\r
+typedef fmiStatus (*fInitializeSlave)(fmiComponent c, fmiReal tStart, fmiBoolean StopTimeDefined, fmiReal tStop);\r
+typedef fmiStatus (*fTerminateSlave)   (fmiComponent c);\r
+typedef fmiStatus (*fResetSlave)       (fmiComponent c);\r
+typedef void      (*fFreeSlaveInstance)(fmiComponent c);\r
+typedef fmiStatus (*fSetRealInputDerivatives)(fmiComponent c, const  fmiValueReference vr[], size_t nvr,\r
+        const fmiInteger order[], const  fmiReal value[]);                                                  \r
+typedef fmiStatus (*fGetRealOutputDerivatives)(fmiComponent c, const fmiValueReference vr[], size_t  nvr,\r
+        const fmiInteger order[], fmiReal value[]);                                              \r
+typedef fmiStatus (*fCancelStep)(fmiComponent c);\r
+typedef fmiStatus (*fDoStep)(fmiComponent c, fmiReal currentCommunicationPoint, \r
+        fmiReal communicationStepSize, fmiBoolean newStep);\r
+typedef fmiStatus (*fGetStatus)       (fmiComponent c, const fmiStatusKind s, fmiStatus*  value);\r
+typedef fmiStatus (*fGetRealStatus)   (fmiComponent c, const fmiStatusKind s, fmiReal*    value);\r
+typedef fmiStatus (*fGetIntegerStatus)(fmiComponent c, const fmiStatusKind s, fmiInteger* value);\r
+typedef fmiStatus (*fGetBooleanStatus)(fmiComponent c, const fmiStatusKind s, fmiBoolean* value);\r
+typedef fmiStatus (*fGetStringStatus) (fmiComponent c, const fmiStatusKind s, fmiString*  value);\r
+\r
+typedef struct {\r
+    ModelDescription* modelDescription;\r
+    HANDLE dllHandle;\r
+    fGetTypesPlatform getTypesPlatform;\r
+    fGetVersion getVersion;\r
+    fSetDebugLogging setDebugLogging;\r
+    fSetReal setReal;\r
+    fSetInteger setInteger;\r
+    fSetBoolean setBoolean;\r
+    fSetString setString;\r
+    fGetReal getReal;\r
+    fGetInteger getInteger;\r
+    fGetBoolean getBoolean;\r
+    fGetString getString;\r
+    fInstantiateSlave instantiateSlave;\r
+    fInitializeSlave initializeSlave;\r
+    fTerminateSlave terminateSlave;\r
+    fResetSlave resetSlave;\r
+    fFreeSlaveInstance freeSlaveInstance;\r
+    fGetRealOutputDerivatives getRealOutputDerivatives;\r
+    fSetRealInputDerivatives setRealInputDerivatives;\r
+    fDoStep doStep;\r
+    fCancelStep cancelStep;\r
+    fGetStatus getStatus;\r
+    fGetRealStatus getRealStatus;\r
+    fGetIntegerStatus getIntegerStatus;\r
+    fGetBooleanStatus getBooleanStatus;\r
+    fGetStringStatus getStringStatus;\r
+} FMU;\r
+\r
+#endif // FMI_CS_H\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/fmusim_cs/main.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/fmusim_cs/main.c
new file mode 100644 (file)
index 0000000..f0673d1
--- /dev/null
@@ -0,0 +1,127 @@
+/* ------------------------------------------------------------------------- \r
+ * main.c\r
+ * Implements simulation of a single FMU instance \r
+ * that implements the "FMI for Co-Simulation 1.0" interface.\r
+ * Command syntax: see printHelp()\r
+ * Simulates the given FMU from t = 0 .. tEnd with fixed step size h and \r
+ * writes the computed solution to file 'result.csv'.\r
+ * The CSV file (comma-separated values) may e.g. be plotted using \r
+ * OpenOffice Calc or Microsoft Excel. \r
+ * This progamm demonstrates basic use of an FMU.\r
+ * Real applications may use advanced master algorithms to cosimulate \r
+ * many FMUs, limit the numerical error using error estimation\r
+ * and back-stepping, provide graphical plotting utilities, debug support, \r
+ * and user control of parameter and start values, or perform a clean\r
+ * error handling (e.g. call freeSlaveInstance when a call to the fmu\r
+ * returns with error). All this is missing here.\r
+ *\r
+ * Revision history\r
+ *  22.08.2011 initial version released in FMU SDK 1.0.2\r
+ *     \r
+ * Free libraries and tools used to implement this simulator:\r
+ *  - header files from the FMU specification\r
+ *  - eXpat 2.0.1 XML parser, see http://expat.sourceforge.net\r
+ *  - 7z.exe 4.57 zip and unzip tool, see http://www.7-zip.org\r
+ * Author: Jakob Mauss\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include "fmi_cs.h"\r
+#include "sim_support.h"\r
+\r
+FMU fmu; // the fmu to simulate\r
+\r
+// simulate the given FMU using the forward euler method.\r
+// time events are processed by reducing step size to exactly hit tNext.\r
+// state events are checked and fired only at the end of an Euler step. \r
+// the simulator may therefore miss state events and fires state events typically too late.\r
+static int simulate(FMU* fmu, double tEnd, double h, fmiBoolean loggingOn, char separator) {\r
+    double time;\r
+    double tStart = 0;               // start time\r
+    const char* guid;                // global unique id of the fmu\r
+    fmiComponent c;                  // instance of the fmu \r
+    fmiStatus fmiFlag;               // return code of the fmu functions\r
+    const char* fmuLocation = NULL;  // path to the fmu as URL, "file://C:\QTronic\sales"\r
+    const char* mimeType = "application/x-fmu-sharedlibrary"; // denotes tool in case of tool coupling\r
+    fmiReal timeout = 1000;          // wait period in milli seconds, 0 for unlimited wait period"\r
+    fmiBoolean visible = fmiFalse;   // no simulator user interface\r
+    fmiBoolean interactive = fmiFalse; // simulation run without user interaction\r
+    fmiCallbackFunctions callbacks;  // called by the model during simulation\r
+    ModelDescription* md;            // handle to the parsed XML file   \r
+    int nSteps = 0;\r
+    FILE* file;\r
+        \r
+    // instantiate the fmu \r
+    md = fmu->modelDescription;\r
+    guid = getString(md, att_guid);\r
+    callbacks.logger = fmuLogger;\r
+    callbacks.allocateMemory = calloc;\r
+    callbacks.freeMemory = free;\r
+    callbacks.stepFinished = NULL; // fmiDoStep has to be carried out synchronously\r
+    c = fmu->instantiateSlave(getModelIdentifier(md), guid, fmuLocation, mimeType, \r
+                              timeout, visible, interactive, callbacks, loggingOn);\r
+    if (!c) return error("could not instantiate model");\r
+\r
+    // open result file\r
+    if (!(file=fopen(RESULT_FILE, "w"))) {\r
+        printf("could not write %s because:\n", RESULT_FILE);\r
+        printf("    %s\n", strerror(errno));\r
+        return 0; // failure\r
+    }\r
+    \r
+    // StopTimeDefined=fmiFalse means: ignore value of tEnd\r
+    fmiFlag = fmu->initializeSlave(c, tStart, fmiTrue, tEnd);\r
+    if (fmiFlag > fmiWarning)  return error("could not initialize model");\r
+    \r
+    // output solution for time t0\r
+    outputRow(fmu, c, tStart, file, separator, TRUE);  // output column names\r
+    outputRow(fmu, c, tStart, file, separator, FALSE); // output values\r
+\r
+    // enter the simulation loop    \r
+    time = tStart;\r
+    while (time < tEnd) {\r
+        fmiFlag = fmu->doStep(c, time, h, fmiTrue);\r
+        if (fmiFlag != fmiOK)  return error("could not complete simulation of the model");\r
+        time += h;\r
+        outputRow(fmu, c, time, file, separator, FALSE); // output values for this step\r
+        nSteps++;\r
+    }\r
+    \r
+    // end simulation\r
+    fmiFlag = fmu->terminateSlave(c);\r
+    fmu->freeSlaveInstance(c);\r
+  \r
+    // print simulation summary \r
+    printf("Simulation from %g to %g terminated successful\n", tStart, tEnd);\r
+    printf("  steps ............ %d\n", nSteps);\r
+    printf("  fixed step size .. %g\n", h);\r
+    return 1; // success\r
+}\r
+\r
+int main(int argc, char *argv[]) {\r
+    const char* fmuFileName;\r
+    \r
+    // parse command line arguments and load the FMU\r
+    double tEnd = 1.0;\r
+    double h=0.1;\r
+    int loggingOn = 0;\r
+    char csv_separator = ';';\r
+    parseArguments(argc, argv, &fmuFileName, &tEnd, &h, &loggingOn, &csv_separator);\r
+    loadFMU(fmuFileName);\r
+\r
+    // run the simulation\r
+    printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c'\n", \r
+            fmuFileName, tEnd, h, loggingOn, csv_separator);\r
+    simulate(&fmu, tEnd, h, loggingOn, csv_separator);\r
+    printf("CSV file '%s' written\n", RESULT_FILE);\r
+\r
+    // release FMU \r
+    FreeLibrary(fmu.dllHandle);\r
+    freeElement(fmu.modelDescription);\r
+    return EXIT_SUCCESS;\r
+}\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/include/fmiFunctions.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/include/fmiFunctions.h
new file mode 100644 (file)
index 0000000..f434102
--- /dev/null
@@ -0,0 +1,231 @@
+#ifndef fmiFunctions_h\r
+#define fmiFunctions_h\r
+\r
+/* This header file must be utilized when compiling a FMU.\r
+   It defines all functions of Co-Simulation Interface.\r
+   In order to have unique function names even if several FMUs\r
+   are compiled together (e.g. for embedded systems), every "real" function name\r
+   is constructed by prepending the function name by\r
+   "MODEL_IDENTIFIER" + "_" where "MODEL_IDENTIFIER" is the short name\r
+   of the model used as the name of the zip-file where the model is stored.\r
+   Therefore, the typical usage is:\r
+\r
+      #define MODEL_IDENTIFIER MyModel\r
+      #include "fmiFunctions.h"\r
+\r
+   As a result, a function that is defined as "fmiGetDerivatives" in this header file,\r
+   is actually getting the name "MyModel_fmiGetDerivatives".\r
+\r
+   Revisions:\r
+   - November 4, 2010: Adapted to specification text:\r
+                       o fmiGetModelTypesPlatform renamed to fmiGetTypesPlatform\r
+                       o fmiInstantiateSlave: Argument GUID     replaced by fmuGUID\r
+                                              Argument mimetype replaced by mimeType\r
+                       o tabs replaced by spaces\r
+   - October 16, 2010: First public Version\r
+\r
+\r
+   Copyright Â© 2008-2010, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html):\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+*/\r
+\r
+#include "fmiPlatformTypes.h"\r
+#include <stdlib.h>\r
+\r
+/* Export fmi functions on Windows */\r
+#ifdef _MSC_VER\r
+#define DllExport __declspec( dllexport )\r
+#else\r
+#define DllExport\r
+#endif\r
+\r
+/* Macros to construct the real function name\r
+   (prepend function name by MODEL_IDENTIFIER + "_") */\r
+\r
+#define fmiPaste(a,b)     a ## b\r
+#define fmiPasteB(a,b)    fmiPaste(a,b)\r
+#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)\r
+\r
+/***************************************************\r
+Common Functions\r
+****************************************************/\r
+#define fmiGetTypesPlatform fmiFullName(_fmiGetTypesPlatform)\r
+#define fmiGetVersion       fmiFullName(_fmiGetVersion)\r
+#define fmiSetDebugLogging  fmiFullName(_fmiSetDebugLogging)\r
+\r
+/*Data Exchange*/\r
+#define fmiSetReal               fmiFullName(_fmiSetReal)\r
+#define fmiSetInteger            fmiFullName(_fmiSetInteger)\r
+#define fmiSetBoolean            fmiFullName(_fmiSetBoolean)\r
+#define fmiSetString             fmiFullName(_fmiSetString)\r
+\r
+#define fmiGetReal               fmiFullName(_fmiGetReal)\r
+#define fmiGetInteger            fmiFullName(_fmiGetInteger)\r
+#define fmiGetBoolean            fmiFullName(_fmiGetBoolean)\r
+#define fmiGetString             fmiFullName(_fmiGetString)\r
+\r
+/***************************************************\r
+Functions for FMI for Co-Simulation\r
+****************************************************/\r
+#define fmiInstantiateSlave         fmiFullName(_fmiInstantiateSlave)\r
+#define fmiInitializeSlave          fmiFullName(_fmiInitializeSlave)\r
+#define fmiTerminateSlave           fmiFullName(_fmiTerminateSlave)\r
+#define fmiResetSlave               fmiFullName(_fmiResetSlave)\r
+#define fmiFreeSlaveInstance        fmiFullName(_fmiFreeSlaveInstance)\r
+#define fmiSetRealInputDerivatives  fmiFullName(_fmiSetRealInputDerivatives)\r
+#define fmiGetRealOutputDerivatives fmiFullName(_fmiGetRealOutputDerivatives)\r
+#define fmiDoStep                   fmiFullName(_fmiDoStep)\r
+#define fmiCancelStep               fmiFullName(_fmiCancelStep)\r
+#define fmiGetStatus                fmiFullName(_fmiGetStatus)\r
+#define fmiGetRealStatus            fmiFullName(_fmiGetRealStatus)\r
+#define fmiGetIntegerStatus         fmiFullName(_fmiGetIntegerStatus)\r
+#define fmiGetBooleanStatus         fmiFullName(_fmiGetBooleanStatus)\r
+#define fmiGetStringStatus          fmiFullName(_fmiGetStringStatus)\r
+\r
+/* Version number */\r
+#define fmiVersion "1.0"\r
+\r
+/* make sure all compiler use the same alignment policies for structures */\r
+#ifdef WIN32\r
+#pragma pack(push,8)\r
+#endif\r
+\r
+\r
+/* Type definitions */\r
+     typedef enum {fmiOK,\r
+                   fmiWarning,\r
+                   fmiDiscard,\r
+                   fmiError,\r
+                   fmiFatal,\r
+                   fmiPending} fmiStatus;\r
+\r
+     typedef void  (*fmiCallbackLogger) (fmiComponent c, fmiString instanceName, fmiStatus status,\r
+                                         fmiString category, fmiString message, ...);\r
+     typedef void* (*fmiCallbackAllocateMemory)(size_t nobj, size_t size);\r
+     typedef void  (*fmiCallbackFreeMemory)    (void* obj);\r
+     typedef void  (*fmiStepFinished)          (fmiComponent c, fmiStatus status);\r
+\r
+     typedef struct {\r
+     fmiCallbackLogger         logger;\r
+     fmiCallbackAllocateMemory allocateMemory;\r
+     fmiCallbackFreeMemory     freeMemory;\r
+     fmiStepFinished           stepFinished;\r
+     } fmiCallbackFunctions;\r
+\r
+   typedef struct {\r
+      fmiBoolean iterationConverged;\r
+      fmiBoolean stateValueReferencesChanged;\r
+      fmiBoolean stateValuesChanged;\r
+      fmiBoolean terminateSimulation;\r
+      fmiBoolean upcomingTimeEvent;\r
+      fmiReal    nextEventTime;\r
+   } fmiEventInfo;\r
+\r
+/* reset alignment policy to the one set before reading this file */\r
+#ifdef WIN32\r
+#pragma pack(pop)\r
+#endif\r
+\r
+/***************************************************\r
+Common Functions\r
+****************************************************/\r
+\r
+/* Inquire version numbers of header files */\r
+   DllExport const char* fmiGetTypesPlatform();\r
+   DllExport const char* fmiGetVersion();\r
+\r
+   DllExport fmiStatus fmiSetDebugLogging  (fmiComponent c, fmiBoolean loggingOn);\r
+\r
+/* Data Exchange Functions*/\r
+   DllExport fmiStatus fmiGetReal   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+   DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+   DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+   DllExport fmiStatus fmiGetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+\r
+   DllExport fmiStatus fmiSetReal    (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+   DllExport fmiStatus fmiSetInteger (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+   DllExport fmiStatus fmiSetBoolean (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+   DllExport fmiStatus fmiSetString  (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+\r
+/***************************************************\r
+Functions for FMI for Co-Simulation\r
+****************************************************/\r
+\r
+/* Creation and destruction of slave instances and setting debug status */\r
+   DllExport fmiComponent fmiInstantiateSlave(fmiString  instanceName,\r
+                                              fmiString  fmuGUID,\r
+                                              fmiString  fmuLocation,\r
+                                              fmiString  mimeType,\r
+                                              fmiReal    timeout,\r
+                                              fmiBoolean visible,\r
+                                              fmiBoolean interactive,\r
+                                              fmiCallbackFunctions functions,\r
+                                              fmiBoolean loggingOn);\r
+\r
+   DllExport fmiStatus fmiInitializeSlave(fmiComponent c,\r
+                                          fmiReal      tStart,\r
+                                          fmiBoolean   StopTimeDefined,\r
+                                          fmiReal      tStop);\r
+\r
+   DllExport fmiStatus fmiTerminateSlave   (fmiComponent c);\r
+   DllExport fmiStatus fmiResetSlave       (fmiComponent c);\r
+   DllExport void      fmiFreeSlaveInstance(fmiComponent c);\r
+\r
+   DllExport fmiStatus fmiSetRealInputDerivatives(fmiComponent c,\r
+                                                  const  fmiValueReference vr[],\r
+                                                  size_t nvr,\r
+                                                  const  fmiInteger order[],\r
+                                                  const  fmiReal value[]);\r
+\r
+   DllExport fmiStatus fmiGetRealOutputDerivatives(fmiComponent c,\r
+                                                   const   fmiValueReference vr[],\r
+                                                   size_t  nvr,\r
+                                                   const   fmiInteger order[],\r
+                                                   fmiReal value[]);\r
+\r
+   DllExport fmiStatus fmiCancelStep(fmiComponent c);\r
+   DllExport fmiStatus fmiDoStep    (fmiComponent c,\r
+                                     fmiReal      currentCommunicationPoint,\r
+                                     fmiReal      communicationStepSize,\r
+                                     fmiBoolean   newStep);\r
+\r
+\r
+   typedef enum {fmiDoStepStatus,\r
+                 fmiPendingStatus,\r
+                 fmiLastSuccessfulTime} fmiStatusKind;\r
+\r
+   DllExport fmiStatus fmiGetStatus       (fmiComponent c, const fmiStatusKind s, fmiStatus*  value);\r
+   DllExport fmiStatus fmiGetRealStatus   (fmiComponent c, const fmiStatusKind s, fmiReal*    value);\r
+   DllExport fmiStatus fmiGetIntegerStatus(fmiComponent c, const fmiStatusKind s, fmiInteger* value);\r
+   DllExport fmiStatus fmiGetBooleanStatus(fmiComponent c, const fmiStatusKind s, fmiBoolean* value);\r
+   DllExport fmiStatus fmiGetStringStatus (fmiComponent c, const fmiStatusKind s, fmiString*  value);\r
+\r
+\r
+#endif // fmiFunctions_h\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/include/fmiPlatformTypes.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/co_simulation/include/fmiPlatformTypes.h
new file mode 100644 (file)
index 0000000..7916f79
--- /dev/null
@@ -0,0 +1,73 @@
+#ifndef fmiPlatformTypes_h\r
+#define fmiPlatformTypes_h\r
+\r
+/* Standard header file to define the argument types of the\r
+   functions of the Model Execution Interface.\r
+   This header file must be utilized both by the model and\r
+   by the simulation engine.\r
+\r
+   Revisions:\r
+   - October 2010: First public Version\r
+\r
+\r
+   Copyright Â© 2008-2010, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html):\r
+\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+*/\r
+\r
+/* Platform (combination of machine, compiler, operating system) */\r
+#define fmiPlatform "standard32"\r
+\r
+/* Type definitions of variables passed as arguments\r
+   Version "standard32" means:\r
+\r
+   fmiComponent     : 32 bit pointer\r
+   fmiValueReference: 32 bit\r
+   fmiReal          : 64 bit\r
+   fmiInteger       : 32 bit\r
+   fmiBoolean       :  8 bit\r
+   fmiString        : 32 bit pointer\r
+\r
+*/\r
+   typedef void*        fmiComponent;\r
+   typedef unsigned int fmiValueReference;\r
+   typedef double       fmiReal   ;\r
+   typedef int          fmiInteger;\r
+   typedef char         fmiBoolean;\r
+   typedef const char*  fmiString ;\r
+\r
+/* Values for fmiBoolean  */\r
+#define fmiTrue  1\r
+#define fmiFalse 0\r
+\r
+/* Undefined value for fmiValueReference (largest unsigned int value) */\r
+#define fmiUndefinedValueReference (fmiValueReference)(-1)\r
+\r
+#endif\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/fmusim_me/fmi_me.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/fmusim_me/fmi_me.h
new file mode 100644 (file)
index 0000000..f115245
--- /dev/null
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------------- \r
+ * fmi_me.h\r
+ * Function types for all function of the "FMI for Model Exchange 1.0"\r
+ * and a struct with the corresponding function pointers. \r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#ifndef FMI_ME_H\r
+#define FMI_ME_H\r
+\r
+#include <windows.h>\r
+#include "fmiModelFunctions.h"\r
+#include "xml_parser.h"\r
+\r
+typedef const char* (*fGetModelTypesPlatform)();\r
+typedef const char* (*fGetVersion)();\r
+typedef fmiComponent (*fInstantiateModel)(fmiString instanceName, fmiString GUID,\r
+                                        fmiCallbackFunctions functions, fmiBoolean loggingOn);\r
+typedef void      (*fFreeModelInstance)  (fmiComponent c);\r
+typedef fmiStatus (*fSetDebugLogging)    (fmiComponent c, fmiBoolean loggingOn);\r
+typedef fmiStatus (*fSetTime)            (fmiComponent c, fmiReal time);\r
+typedef fmiStatus (*fSetContinuousStates)(fmiComponent c, const fmiReal x[], size_t nx);\r
+typedef fmiStatus (*fCompletedIntegratorStep)(fmiComponent c, fmiBoolean* callEventUpdate);\r
+typedef fmiStatus (*fSetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+typedef fmiStatus (*fSetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+typedef fmiStatus (*fSetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+typedef fmiStatus (*fSetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+typedef fmiStatus (*fInitialize)(fmiComponent c, fmiBoolean toleranceControlled, \r
+                               fmiReal relativeTolerance, fmiEventInfo* eventInfo);\r
+typedef fmiStatus (*fGetDerivatives)    (fmiComponent c, fmiReal derivatives[]    , size_t nx);\r
+typedef fmiStatus (*fGetEventIndicators)(fmiComponent c, fmiReal eventIndicators[], size_t ni);\r
+typedef fmiStatus (*fGetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+typedef fmiStatus (*fGetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+typedef fmiStatus (*fGetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+typedef fmiStatus (*fGetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+typedef fmiStatus (*fEventUpdate)               (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo);\r
+typedef fmiStatus (*fGetContinuousStates)       (fmiComponent c, fmiReal states[], size_t nx);\r
+typedef fmiStatus (*fGetNominalContinuousStates)(fmiComponent c, fmiReal x_nominal[], size_t nx);\r
+typedef fmiStatus (*fGetStateValueReferences)   (fmiComponent c, fmiValueReference vrx[], size_t nx);\r
+typedef fmiStatus (*fTerminate)                 (fmiComponent c);    \r
+\r
+typedef struct {\r
+    ModelDescription* modelDescription;\r
+    HANDLE dllHandle;\r
+    fGetModelTypesPlatform getModelTypesPlatform;\r
+    fGetVersion getVersion;\r
+    fInstantiateModel instantiateModel;\r
+    fFreeModelInstance freeModelInstance;\r
+    fSetDebugLogging setDebugLogging;\r
+    fSetTime setTime;\r
+    fSetContinuousStates setContinuousStates;\r
+    fCompletedIntegratorStep completedIntegratorStep;\r
+    fSetReal setReal;\r
+    fSetInteger setInteger;\r
+    fSetBoolean setBoolean;\r
+    fSetString setString;\r
+    fInitialize initialize;\r
+    fGetDerivatives getDerivatives;\r
+    fGetEventIndicators getEventIndicators;\r
+    fGetReal getReal;\r
+    fGetInteger getInteger;\r
+    fGetBoolean getBoolean;\r
+    fGetString getString;\r
+    fEventUpdate eventUpdate;\r
+    fGetContinuousStates getContinuousStates;\r
+    fGetNominalContinuousStates getNominalContinuousStates;\r
+    fGetStateValueReferences getStateValueReferences;\r
+    fTerminate terminate; \r
+/*   \r
+    fInstantiateSlave instantiateSlave;\r
+    fInitializeSlave initializeSlave;\r
+    fTerminateSlave terminateSlave;\r
+    fResetSlave resetSlave;\r
+    fFreeSlaveInstance freeSlaveInstance;\r
+    fGetRealOutputDerivatives getRealOutputDerivatives;\r
+    fSetRealInputDerivatives setRealInputDerivatives;\r
+    fDoStep doStep;\r
+    fCancelStep cancelStep;\r
+    fGetStatus getStatus;\r
+    fGetRealStatus getRealStatus;\r
+    fGetIntegerStatus getIntegerStatus;\r
+    fGetBooleanStatus getBooleanStatus;\r
+    fGetStringStatus getStringStatus;\r
+*/\r
+} FMU;\r
+\r
+#endif // FMI_ME_H\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/fmusim_me/main.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/fmusim_me/main.c
new file mode 100644 (file)
index 0000000..39b3957
--- /dev/null
@@ -0,0 +1,286 @@
+/* ------------------------------------------------------------------------- \r
+ * main.c\r
+ * Implements simulation of a single FMU instance using the forward Euler\r
+ * method for numerical integration.\r
+ * Command syntax: see printHelp()\r
+ * Simulates the given FMU from t = 0 .. tEnd with fixed step size h and \r
+ * writes the computed solution to file 'result.csv'.\r
+ * The CSV file (comma-separated values) may e.g. be plotted using \r
+ * OpenOffice Calc or Microsoft Excel. \r
+ * This progamm demonstrates basic use of an FMU.\r
+ * Real applications may use advanced numerical solvers instead, means to \r
+ * exactly locate state events in time, graphical plotting utilities, support \r
+ * for coexecution of many FMUs, stepping and debug support, user control\r
+ * of parameter and start values etc. \r
+ * All this is missing here.\r
+ *\r
+ * Revision history\r
+ *  07.02.2010 initial version released in FMU SDK 1.0\r
+ *  05.03.2010 bug fix: removed strerror(GetLastError()) from error messages\r
+ *  11.06.2010 bug fix: replaced win32 API call to OpenFile in getFmuPath \r
+ *    which restricted path length to FMU to 128 chars. New limit is MAX_PATH.\r
+ *  15.07.2010 fixed wrong label in xml parser: deault instead of default\r
+ *  13.12.2010 added check for undefined 'declared type' to xml parser\r
+ *  31.07.2011 bug fix: added missing freeModelInstance(c)\r
+ *  31.07.2011 bug fix: added missing terminate(c)\r
+ *     \r
+ * Free libraries and tools used to implement this simulator:\r
+ *  - header files from the FMU specification\r
+ *  - eXpat 2.0.1 XML parser, see http://expat.sourceforge.net\r
+ *  - 7z.exe 4.57 zip and unzip tool, see http://www.7-zip.org\r
+ * Author: Jakob Mauss\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include "fmi_me.h"\r
+#include "sim_support.h"\r
+\r
+FMU fmu; // the fmu to simulate\r
+\r
+// simulate the given FMU using the forward euler method.\r
+// time events are processed by reducing step size to exactly hit tNext.\r
+// state events are checked and fired only at the end of an Euler step. \r
+// the simulator may therefore miss state events and fires state events typically too late.\r
+static int simulate(FMU* fmu, double tEnd, double h, fmiBoolean loggingOn, char separator) {\r
+    int i, n;\r
+    double dt, tPre;\r
+    fmiBoolean timeEvent, stateEvent, stepEvent;\r
+    double time;  \r
+    int nx;                          // number of state variables\r
+    int nz;                          // number of state event indicators\r
+    double *x;                       // continuous states\r
+    double *xdot;                    // the crresponding derivatives in same order\r
+    double *z = NULL;                // state event indicators\r
+    double *prez = NULL;             // previous values of state event indicators\r
+    fmiEventInfo eventInfo;          // updated by calls to initialize and eventUpdate\r
+    ModelDescription* md;            // handle to the parsed XML file        \r
+    const char* guid;                // global unique id of the fmu\r
+    fmiCallbackFunctions callbacks;  // called by the model during simulation\r
+    fmiComponent c;                  // instance of the fmu \r
+    fmiStatus fmiFlag;               // return code of the fmu functions\r
+    fmiReal t0 = 0;                  // start time\r
+    fmiBoolean toleranceControlled = fmiFalse;\r
+    int nSteps = 0;\r
+    int nTimeEvents = 0;\r
+    int nStepEvents = 0;\r
+    int nStateEvents = 0;\r
+    FILE* file;\r
+       \r
+       double nextTime, step, value, currval;\r
+       char *par = "Auxiliary1";\r
+       char *var = "Stock1";\r
+       char* s;\r
+       int k;\r
+       ScalarVariable** vars = fmu->modelDescription->modelVariables;\r
+       fmiValueReference vr;\r
+\r
+\r
+    // instantiate the fmu\r
+    md = fmu->modelDescription;\r
+    guid = getString(md, att_guid);\r
+    callbacks.logger = fmuLogger;\r
+    callbacks.allocateMemory = calloc;\r
+    callbacks.freeMemory = free;\r
+    c = fmu->instantiateModel(getModelIdentifier(md), guid, callbacks, loggingOn);\r
+    if (!c) return error("could not instantiate model");\r
+    \r
+    // allocate memory \r
+    nx = getNumberOfStates(md);\r
+    nz = getNumberOfEventIndicators(md);\r
+    x    = (double *) calloc(nx, sizeof(double));\r
+    xdot = (double *) calloc(nx, sizeof(double));\r
+    if (nz>0) {\r
+        z    =  (double *) calloc(nz, sizeof(double));\r
+        prez =  (double *) calloc(nz, sizeof(double));\r
+    }\r
+    if (!x || !xdot || nz>0 && (!z || !prez)) return error("out of memory");\r
+\r
+    // open result file\r
+    if (!(file=fopen(RESULT_FILE, "w"))) {\r
+        printf("could not write %s because:\n", RESULT_FILE);\r
+        printf("    %s\n", strerror(errno));\r
+        return 0; // failure\r
+    }\r
+        \r
+    // set the start time and initialize\r
+    time = t0;\r
+    fmiFlag =  fmu->setTime(c, t0);\r
+    if (fmiFlag > fmiWarning) return error("could not set time");\r
+    fmiFlag =  fmu->initialize(c, toleranceControlled, t0, &eventInfo);\r
+    if (fmiFlag > fmiWarning)  return error("could not initialize model");\r
+    if (eventInfo.terminateSimulation) {\r
+        printf("model requested termination at init");\r
+        tEnd = time;\r
+    }\r
+  \r
+    // output solution for time t0\r
+    outputRow(fmu, c, t0, file, separator, TRUE);  // output column names\r
+    outputRow(fmu, c, t0, file, separator, FALSE); // output values\r
+\r
+       nextTime = time;\r
+    // enter the simulation loop\r
+    while (time < tEnd) {\r
+       \r
+       if(time >= nextTime) { \r
+                       // change variable value\r
+               for (k=0; vars[k]; k++) {\r
+                       ScalarVariable* sv = vars[k];\r
+                       if (getAlias(sv)!=enu_noAlias) continue;\r
+\r
+                       s = getName(sv);\r
+\r
+                       if(strcmp(s,par) == 0) {\r
+                               printf("Value for %s: ", s);\r
+                               scanf("%lf", &value);\r
+                               \r
+                               vr = getValueReference(sv);\r
+                               fmu->setReal(c, &vr, 1, &value);\r
+                               \r
+                       }\r
+               }\r
+               \r
+               printf("Give step: ");\r
+               scanf("%lf", &step);\r
+               nextTime = time + step;\r
+       }\r
+       \r
+       \r
+     // get current state and derivatives\r
+     fmiFlag = fmu->getContinuousStates(c, x, nx);\r
+     if (fmiFlag > fmiWarning) return error("could not retrieve states");\r
+     fmiFlag = fmu->getDerivatives(c, xdot, nx);\r
+     if (fmiFlag > fmiWarning) return error("could not retrieve derivatives");\r
+\r
+     // advance time\r
+     tPre = time;\r
+        \r
+     time = min(time+h, tEnd);\r
+     timeEvent = eventInfo.upcomingTimeEvent && eventInfo.nextEventTime < time;     \r
+     if (timeEvent) time = eventInfo.nextEventTime;\r
+     dt = time - tPre; \r
+        printf("Actual time: %lf\n", time);\r
+     fmiFlag = fmu->setTime(c, time);\r
+     if (fmiFlag > fmiWarning) error("could not set time");\r
+\r
+     // perform one step\r
+     for (i=0; i<nx; i++) x[i] += dt*xdot[i]; // forward Euler method\r
+     fmiFlag = fmu->setContinuousStates(c, x, nx);\r
+     if (fmiFlag > fmiWarning) return error("could not set states");\r
+     if (loggingOn) printf("Step %d to t=%.16g\n", nSteps, time);\r
+    \r
+     // Check for step event, e.g. dynamic state selection\r
+     fmiFlag = fmu->completedIntegratorStep(c, &stepEvent);\r
+     if (fmiFlag > fmiWarning) return error("could not complete intgrator step");\r
+\r
+     // Check for state event\r
+     for (i=0; i<nz; i++) prez[i] = z[i]; \r
+     fmiFlag = fmu->getEventIndicators(c, z, nz);\r
+     if (fmiFlag > fmiWarning) return error("could not retrieve event indicators");\r
+     stateEvent = FALSE;\r
+     for (i=0; i<nz; i++) \r
+         stateEvent = stateEvent || (prez[i] * z[i] < 0);  \r
+     \r
+     // handle events\r
+     if (timeEvent || stateEvent || stepEvent) {\r
+        \r
+        if (timeEvent) {\r
+            nTimeEvents++;\r
+            if (loggingOn) printf("time event at t=%.16g\n", time);\r
+        }\r
+        if (stateEvent) {\r
+            nStateEvents++;\r
+            if (loggingOn) for (i=0; i<nz; i++)\r
+                printf("state event %s z[%d] at t=%.16g\n", \r
+                        (prez[i]>0 && z[i]<0) ? "-\\-" : "-/-", i, time);\r
+        }\r
+        if (stepEvent) {\r
+            nStepEvents++;\r
+            if (loggingOn) printf("step event at t=%.16g\n", time);\r
+        }\r
+\r
+        // event iteration in one step, ignoring intermediate results\r
+        fmiFlag = fmu->eventUpdate(c, fmiFalse, &eventInfo);\r
+        if (fmiFlag > fmiWarning) return error("could not perform event update");\r
+        \r
+        // terminate simulation, if requested by the model\r
+        if (eventInfo.terminateSimulation) {\r
+            printf("model requested termination at t=%.16g\n", time);\r
+            break; // success\r
+        }\r
+\r
+        // check for change of value of states\r
+        if (eventInfo.stateValuesChanged && loggingOn) {\r
+            printf("state values changed at t=%.16g\n", time);\r
+        }\r
+        \r
+        // check for selection of new state variables\r
+        if (eventInfo.stateValueReferencesChanged && loggingOn) {\r
+            printf("new state variables selected at t=%.16g\n", time);\r
+        }\r
+       \r
+     } // if event\r
+     outputRow(fmu, c, time, file, separator, FALSE); // output values for this step\r
+        \r
+                               // change variable value\r
+    for (k=0; vars[k]; k++) {\r
+        ScalarVariable* sv = vars[k];\r
+        if (getAlias(sv)!=enu_noAlias) continue;\r
+\r
+               s = getName(sv);\r
+\r
+               if(strcmp(s,var) == 0) {\r
+                       vr = getValueReference(sv);\r
+                       fmu->getReal(c, &vr, 1, &currval);\r
+                       printf("Value for %s: %lf\n", s, currval);\r
+               }\r
+       }\r
+        \r
+     nSteps++;\r
+  } // while  \r
+\r
+  // cleanup\r
+  if(! eventInfo.terminateSimulation) fmu->terminate(c);\r
+  fmu->freeModelInstance(c);\r
+  fclose(file);\r
+  if (x!=NULL) free(x);\r
+  if (xdot!= NULL) free(xdot);\r
+  if (z!= NULL) free(z);\r
+  if (prez!= NULL) free(prez);\r
+\r
+  // print simulation summary \r
+  printf("Simulation from %g to %g terminated successful\n", t0, tEnd);\r
+  printf("  steps ............ %d\n", nSteps);\r
+  printf("  fixed step size .. %g\n", h);\r
+  printf("  time events ...... %d\n", nTimeEvents);\r
+  printf("  state events ..... %d\n", nStateEvents);\r
+  printf("  step events ...... %d\n", nStepEvents);\r
+\r
+  return 1; // success\r
+}\r
+\r
+int main(int argc, char *argv[]) {\r
+    const char* fmuFileName;\r
+    \r
+    // parse command line arguments and load the FMU\r
+    double tEnd = 1.0;\r
+    double h=0.1;\r
+    int loggingOn = 0;\r
+    char csv_separator = ';';\r
+    parseArguments(argc, argv, &fmuFileName, &tEnd, &h, &loggingOn, &csv_separator);\r
+    loadFMU(fmuFileName);\r
+\r
+    // run the simulation\r
+    printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c'\n", \r
+            fmuFileName, tEnd, h, loggingOn, csv_separator);\r
+    simulate(&fmu, tEnd, h, loggingOn, csv_separator);\r
+    printf("CSV file '%s' written\n", RESULT_FILE);\r
+\r
+    // release FMU \r
+    FreeLibrary(fmu.dllHandle);\r
+    freeElement(fmu.modelDescription);\r
+    return EXIT_SUCCESS;\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/include/fmiModelFunctions.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/include/fmiModelFunctions.h
new file mode 100644 (file)
index 0000000..e204772
--- /dev/null
@@ -0,0 +1,210 @@
+#ifndef fmiModelFunctions_h\r
+#define fmiModelFunctions_h\r
+\r
+/* This header file must be utilized when compiling a model.\r
+   It defines all functions of the Model Execution Interface.\r
+   In order to have unique function names even if several models\r
+   are compiled together (e.g. for embedded systems), every "real" function name\r
+   is constructed by prepending the function name by\r
+   "MODEL_IDENTIFIER" + "_" where "MODEL_IDENTIFIER" is the short name\r
+   of the model used as the name of the zip-file where the model is stored.\r
+   Therefore, the typical usage is:\r
+\r
+      #define MODEL_IDENTIFIER MyModel\r
+      #include "fmiModelFunctions.h"\r
+\r
+   As a result, a function that is defined as "fmiGetDerivatives" in this header file,\r
+   is actually getting the name "MyModel_fmiGetDerivatives".\r
+\r
+   Revisions:\r
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)\r
+                    (by M. Otter, DLR)\r
+                    Added WIN32 pragma to define the struct layout (ticket #34)\r
+                    (by J. Mauss, QTronic)\r
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize\r
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion\r
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion\r
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel\r
+                    (by J. Mauss, QTronic)\r
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).\r
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added\r
+                    meGetNominalContinuousStates (by Martin Otter, DLR)\r
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)\r
+                    (by A. Junghanns, QTronic)\r
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:\r
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform\r
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion\r
+                    meSetStates                    -> meSetContinuousStates\r
+                    meGetStates                    -> meGetContinuousStates\r
+                    removal of meInitializeModelClass\r
+                    removal of meGetTime\r
+                    change of arguments of meInstantiateModel\r
+                    change of arguments of meCompletedIntegratorStep\r
+                    (by Martin Otter, DLR):\r
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).\r
+   - March 2, 2009: Changed function definitions according to the last design\r
+                    meeting with additional improvements (by Martin Otter, DLR).\r
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).\r
+\r
+\r
+   Copyright Â© 2008-2009, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html):\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+\r
+   with the extension:\r
+\r
+   You may distribute or publicly perform any modification only under the\r
+   terms of this license.\r
+*/\r
+\r
+#include "fmiModelTypes.h"\r
+#include <stdlib.h>\r
+\r
+/* Export fmi functions on Windows */\r
+#ifdef _MSC_VER\r
+#define DllExport __declspec( dllexport )\r
+#else\r
+#define DllExport\r
+#endif\r
+\r
+/* Macros to construct the real function name\r
+   (prepend function name by MODEL_IDENTIFIER + "_") */\r
+\r
+#define fmiPaste(a,b)     a ## b\r
+#define fmiPasteB(a,b)    fmiPaste(a,b)\r
+#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)\r
+\r
+#define fmiGetModelTypesPlatform      fmiFullName(_fmiGetModelTypesPlatform)\r
+#define fmiGetVersion                 fmiFullName(_fmiGetVersion)\r
+#define fmiInstantiateModel           fmiFullName(_fmiInstantiateModel)\r
+#define fmiFreeModelInstance          fmiFullName(_fmiFreeModelInstance)\r
+#define fmiSetDebugLogging            fmiFullName(_fmiSetDebugLogging)\r
+#define fmiSetTime                    fmiFullName(_fmiSetTime)\r
+#define fmiSetContinuousStates        fmiFullName(_fmiSetContinuousStates)\r
+#define fmiCompletedIntegratorStep    fmiFullName(_fmiCompletedIntegratorStep)\r
+#define fmiSetReal                    fmiFullName(_fmiSetReal)\r
+#define fmiSetInteger                 fmiFullName(_fmiSetInteger)\r
+#define fmiSetBoolean                 fmiFullName(_fmiSetBoolean)\r
+#define fmiSetString                  fmiFullName(_fmiSetString)\r
+#define fmiInitialize                 fmiFullName(_fmiInitialize)\r
+#define fmiGetDerivatives             fmiFullName(_fmiGetDerivatives)\r
+#define fmiGetEventIndicators         fmiFullName(_fmiGetEventIndicators)\r
+#define fmiGetReal                    fmiFullName(_fmiGetReal)\r
+#define fmiGetInteger                 fmiFullName(_fmiGetInteger)\r
+#define fmiGetBoolean                 fmiFullName(_fmiGetBoolean)\r
+#define fmiGetString                  fmiFullName(_fmiGetString)\r
+#define fmiEventUpdate                fmiFullName(_fmiEventUpdate)\r
+#define fmiGetContinuousStates        fmiFullName(_fmiGetContinuousStates)\r
+#define fmiGetNominalContinuousStates fmiFullName(_fmiGetNominalContinuousStates)\r
+#define fmiGetStateValueReferences    fmiFullName(_fmiGetStateValueReferences)\r
+#define fmiTerminate                  fmiFullName(_fmiTerminate)\r
+\r
+\r
+/* Version number */\r
+#define fmiVersion "1.0"\r
+\r
+/* Inquire version numbers of header files */\r
+   DllExport const char* fmiGetModelTypesPlatform();\r
+   DllExport const char* fmiGetVersion();\r
+\r
+/* make sure all compiler use the same alignment policies for structures */\r
+#ifdef WIN32\r
+#pragma pack(push,8)\r
+#endif\r
+\r
+/* Type definitions */\r
+   typedef enum  {fmiOK,\r
+                  fmiWarning,\r
+                  fmiDiscard,\r
+                  fmiError,\r
+                  fmiFatal} fmiStatus;\r
+\r
+   typedef void  (*fmiCallbackLogger)        (fmiComponent c, fmiString instanceName, fmiStatus status,\r
+                                              fmiString category, fmiString message, ...);\r
+   typedef void* (*fmiCallbackAllocateMemory)(size_t nobj, size_t size);\r
+   typedef void  (*fmiCallbackFreeMemory)    (void* obj);\r
+\r
+   typedef struct {\r
+     fmiCallbackLogger         logger;\r
+     fmiCallbackAllocateMemory allocateMemory;\r
+     fmiCallbackFreeMemory     freeMemory;\r
+   } fmiCallbackFunctions;\r
+\r
+   typedef struct {\r
+      fmiBoolean iterationConverged;\r
+      fmiBoolean stateValueReferencesChanged;\r
+      fmiBoolean stateValuesChanged;\r
+      fmiBoolean terminateSimulation;\r
+      fmiBoolean upcomingTimeEvent;\r
+      fmiReal    nextEventTime;\r
+   } fmiEventInfo;\r
+\r
+/* reset alignment policy to the one set before reading this file */\r
+#ifdef WIN32\r
+#pragma pack(pop)\r
+#endif\r
+\r
+/* Creation and destruction of model instances and setting debug status */\r
+   DllExport fmiComponent fmiInstantiateModel (fmiString            instanceName,\r
+                                               fmiString            GUID,\r
+                                               fmiCallbackFunctions functions,\r
+                                               fmiBoolean           loggingOn);\r
+   DllExport void      fmiFreeModelInstance(fmiComponent c);\r
+   DllExport fmiStatus fmiSetDebugLogging  (fmiComponent c, fmiBoolean loggingOn);\r
+\r
+\r
+/* Providing independent variables and re-initialization of caching */\r
+   DllExport fmiStatus fmiSetTime                (fmiComponent c, fmiReal time);\r
+   DllExport fmiStatus fmiSetContinuousStates    (fmiComponent c, const fmiReal x[], size_t nx);\r
+   DllExport fmiStatus fmiCompletedIntegratorStep(fmiComponent c, fmiBoolean* callEventUpdate);\r
+   DllExport fmiStatus fmiSetReal                (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+   DllExport fmiStatus fmiSetInteger             (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+   DllExport fmiStatus fmiSetBoolean             (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+   DllExport fmiStatus fmiSetString              (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+\r
+\r
+/* Evaluation of the model equations */\r
+   DllExport fmiStatus fmiInitialize(fmiComponent c, fmiBoolean toleranceControlled,\r
+                                     fmiReal relativeTolerance, fmiEventInfo* eventInfo);\r
+\r
+   DllExport fmiStatus fmiGetDerivatives    (fmiComponent c, fmiReal derivatives[]    , size_t nx);\r
+   DllExport fmiStatus fmiGetEventIndicators(fmiComponent c, fmiReal eventIndicators[], size_t ni);\r
+\r
+   DllExport fmiStatus fmiGetReal   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+   DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+   DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+   DllExport fmiStatus fmiGetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+\r
+   DllExport fmiStatus fmiEventUpdate               (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo);\r
+   DllExport fmiStatus fmiGetContinuousStates       (fmiComponent c, fmiReal states[], size_t nx);\r
+   DllExport fmiStatus fmiGetNominalContinuousStates(fmiComponent c, fmiReal x_nominal[], size_t nx);\r
+   DllExport fmiStatus fmiGetStateValueReferences   (fmiComponent c, fmiValueReference vrx[], size_t nx);\r
+   DllExport fmiStatus fmiTerminate                 (fmiComponent c);\r
+\r
+#endif // fmiModelFunctions_h\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/include/fmiModelTypes.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/model_exchange/include/fmiModelTypes.h
new file mode 100644 (file)
index 0000000..17e9e30
--- /dev/null
@@ -0,0 +1,91 @@
+#ifndef fmiModelTypes_h\r
+#define fmiModelTypes_h\r
+\r
+/* Standard header file to define the argument types of the\r
+   functions of the Model Execution Interface.\r
+   This header file must be utilized both by the model and\r
+   by the simulation engine.\r
+\r
+   Revisions:\r
+   - Jan.  4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)\r
+   - Dec. 21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"\r
+                    according to meeting on Dec. 18 (by Martin Otter, DLR)\r
+   - Dec.  6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)\r
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:\r
+                    Changed "version" to "platform", "standard" to "standard32",\r
+                    Added a precise definition of "standard32" as comment\r
+                    (by Martin Otter, DLR)\r
+   - July 19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,\r
+                    and changed meValueReferenced from int to unsigned int\r
+                    (by Martin Otter, DLR).\r
+   - March 2, 2009: Moved enums and function pointer definitions to\r
+                    ModelFunctions.h (by Martin Otter, DLR).\r
+   - Dec. 3, 2008 : First version by Martin Otter (DLR) and\r
+                    Hans Olsson (Dynasim).\r
+\r
+\r
+   Copyright Â© 2008-2010, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html)\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+\r
+   with the extension:\r
+\r
+   You may distribute or publicly perform any modification only under the\r
+   terms of this license.\r
+*/\r
+\r
+/* Platform (combination of machine, compiler, operating system) */\r
+#define fmiModelTypesPlatform "standard32"\r
+\r
+/* Type definitions of variables passed as arguments\r
+   Version "standard32" means:\r
+\r
+   fmiComponent     : 32 bit pointer\r
+   fmiValueReference: 32 bit\r
+   fmiReal          : 64 bit\r
+   fmiInteger       : 32 bit\r
+   fmiBoolean       :  8 bit\r
+   fmiString        : 32 bit pointer\r
+\r
+*/\r
+   typedef void*        fmiComponent;\r
+   typedef unsigned int fmiValueReference;\r
+   typedef double       fmiReal   ;\r
+   typedef int          fmiInteger;\r
+   typedef char         fmiBoolean;\r
+   typedef const char*  fmiString ;\r
+\r
+/* Values for fmiBoolean  */\r
+#define fmiTrue  1\r
+#define fmiFalse 0\r
+\r
+/* Undefined value for fmiValueReference (largest unsigned int value) */\r
+#define fmiUndefinedValueReference (fmiValueReference)(-1)\r
+\r
+#endif\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/_main.html
new file mode 100644 (file)
index 0000000..fff15c6
--- /dev/null
@@ -0,0 +1,52 @@
+<html>\r
+<head>\r
+    <title>Documentation for bouncingBall.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+<h1>bouncingBall.fmu</h1>\r
+The bouncingBall implements the following equation: \r
+<ul>\r
+<li> der(h) = v;\r
+<li> der(v) = -g;\r
+<li> when h<0 then v := -e* v\r
+</ul>\r
+with start values h=1, e=0.7, g = 9.81 and\r
+<ul>\r
+<li> h: height [m], used as state\r
+<li> v: velocity of ball [m/s], used as state\r
+<li> der(h): velocity of ball [m/s]\r
+<li> der(v): acceleration of ball [m/s2]\r
+<li> g: acceleration of gravity [m/s2], a parameter\r
+<li> e: a dimensionless parameter\r
+</ul>\r
+\r
+<br>\r
+<img src="plot_h.png">\r
+<br>\r
+The figure shows the solution computed with Silver \r
+for height h of the ball for the start values given above.\r
+\r
+<p>\r
+The chain of events during simulation is as follows\r
+<ol>\r
+<li> intitially h>0 and pos(0)=true </li>\r
+<li> continuous integration until a state event is detected, i.e.\r
+     until h + EPS_INDICATORS = 0.\r
+     At this time h < 0, the EPS_INDICATORS adds hysteresis.</li>\r
+<li> the simulator calls eventUpdate once which reverses the speed direction\r
+     v of the ball: v = -e * v, and sets pos(0)=false</li>\r
+<li> continuous integration until state event is detected, i.e.\r
+     until h - EPS_INDICATORS = 0.\r
+     At this time h > 0, the EPS_INDICATORS adds hysteresis.</li>\r
+<li> the simulator calls  eventUpdate once more which sets pos(0)=true.</li>\r
+<li> goto 2</li>\r
+</ol>\r
+The above description refers to the variables used \r
+in file <code>bouncingBall.c</code>.\r
+\r
+</body>\r
+</html>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/bouncingBall.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/bouncingBall.c
new file mode 100644 (file)
index 0000000..7f6c303
--- /dev/null
@@ -0,0 +1,103 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU - a bouncing ball. \r
+ * This demonstrates the use of state events and reinit of states.\r
+ * Equations:\r
+ *  der(h) = v;\r
+ *  der(v) = -g;\r
+ *  when h<0 then v := -e * v;  \r
+ *  where\r
+ *    h      height [m], used as state, start = 1\r
+ *    v      velocity of ball [m/s], used as state\r
+ *    der(h) velocity of ball [m/s] \r
+ *    der(v) acceleration of ball [m/s2] \r
+ *    g      acceleration of gravity [m/s2], a parameter, start = 9.81 \r
+ *    e      a dimensionless parameter, start = 0.7\r
+ *    \r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER bouncingBall\r
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f003}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 5\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_STATES 2\r
+#define NUMBER_OF_EVENT_INDICATORS 1\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define h_      0\r
+#define der_h_  1\r
+#define v_      2\r
+#define der_v_  3\r
+#define g_      3 // negated alias\r
+#define e_      4\r
+\r
+// define initial state vector as vector of value references\r
+#define STATES { h_, v_ }\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    r(h_)     =  1;\r
+    r(v_)     =  0;\r
+    r(der_v_) = -9.81;\r
+    r(e_)     =  0.7;\r
+    pos(0) = r(h_) > 0;\r
+}\r
+\r
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives\r
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){\r
+    switch (vr) {\r
+        case h_     : return r(h_);\r
+        case der_h_ : return r(v_);\r
+        case v_     : return r(v_);\r
+        case der_v_ : return r(der_v_);\r
+        case e_     : return r(e_);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+// offset for event indicator, adds hysteresis and prevents z=0 at restart \r
+#define EPS_INDICATORS 1e-14\r
+\r
+fmiReal getEventIndicator(ModelInstance* comp, int z) {\r
+    switch (z) {\r
+        case 0 : return r(h_) + (pos(0) ? EPS_INDICATORS : -EPS_INDICATORS);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    if (pos(0)) {\r
+        r(v_) = - r(e_) * r(v_);\r
+    }\r
+    pos(0) = r(h_) > 0;\r
+    eventInfo->iterationConverged  = fmiTrue;\r
+    eventInfo->stateValueReferencesChanged = fmiFalse;\r
+    eventInfo->stateValuesChanged  = fmiTrue;\r
+    eventInfo->terminateSimulation = fmiFalse;\r
+    eventInfo->upcomingTimeEvent   = fmiFalse;\r
+ } \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/modelDescription.xml
new file mode 100644 (file)
index 0000000..4cb345e
--- /dev/null
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="bouncingBall"\r
+  modelIdentifier="bouncingBall"\r
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f003}"\r
+  numberOfContinuousStates="2"\r
+  numberOfEventIndicators="1">\r
+<ModelVariables>\r
+  <ScalarVariable name="h" valueReference="0" description="height, used as state">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(h)" valueReference="1" description="velocity of ball">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="v" valueReference="2" description="velocity of ball, used as state">\r
+     <Real/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(v)" valueReference="3" description="acceleration of ball">\r
+     <Real/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="g" valueReference="3" description="acceleration of gravity" \r
+                  variability="parameter" alias="negatedAlias">\r
+     <Real start="9.81" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="e" valueReference="4" description="dimensionless parameter" \r
+                  variability="parameter">\r
+     <Real start="0.7" fixed="true"/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/plot_h.PNG b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/plot_h.PNG
new file mode 100644 (file)
index 0000000..ced85c4
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/bouncingBall/plot_h.PNG differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/build_fmu.bat b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/build_fmu.bat
new file mode 100644 (file)
index 0000000..9d01458
--- /dev/null
@@ -0,0 +1,80 @@
+@echo off \r
+rem ------------------------------------------------------------\r
+rem This batch builds an FMU of the FMU SDK\r
+rem Usage: build_fmu (me|cs) <fmu_dir_name> \r
+rem (c) 2011 QTronic GmbH\r
+rem ------------------------------------------------------------\r
+\r
+echo -----------------------------------------------------------\r
+if %1==cs (^\r
+echo building FMU %2 - FMI for Co-Simulation 1.0) else ^\r
+echo building FMU %2 - FMI for Model Exchange 1.0\r
+\r
+rem save env variable settings\r
+set PREV_PATH=%PATH%\r
+if defined INCLUDE set PREV_INCLUDE=%INLUDE%\r
+if defined LIB     set PREV_LIB=%LIB%\r
+if defined LIBPATH set PREV_LIBPATH=%LIBPATH%\r
+\r
+rem setup the compiler\r
+if defined VS90COMNTOOLS (call "%VS90COMNTOOLS%\vsvars32.bat") else ^\r
+if defined VS80COMNTOOLS (call "%VS80COMNTOOLS%\vsvars32.bat") else ^\r
+goto noCompiler\r
+\r
+rem create the %2.dll in the temp dir\r
+if not exist temp mkdir temp \r
+pushd temp\r
+if exist *.dll del /Q *.dll\r
+\r
+rem /wd4090 disables warnings about different 'const' qualifiers\r
+if %1==cs (set FMI_DIR=co_simulation) else set FMI_DIR=model_exchange\r
+if %1==cs (set DEF=/DFMI_COSIMULATION) else set DEF=\r
+cl /LD /wd4090 /nologo %DEF% ..\%2\%2.c /I ..\. /I ..\..\%FMI_DIR%\include\r
+if not exist %2.dll goto compileError\r
+\r
+rem create FMU dir structure with root 'fmu'\r
+set BIN_DIR=fmu\binaries\win32\r
+set SRC_DIR=fmu\sources\r
+set DOC_DIR=fmu\documentation\r
+if not exist %BIN_DIR% mkdir %BIN_DIR%\r
+if not exist %SRC_DIR% mkdir %SRC_DIR%\r
+if not exist %DOC_DIR% mkdir %DOC_DIR%\r
+move /Y %2.dll %BIN_DIR%\r
+if exist ..\%2\*~ del /Q ..\%2\*~\r
+copy ..\%2\%2.c %SRC_DIR% \r
+type ..\%2\modelDescription.xml ..\%1.xml > fmu\modelDescription.xml\r
+copy ..\%2\model.png fmu\r
+copy ..\fmuTemplate.c %SRC_DIR%\r
+copy ..\fmuTemplate.h %SRC_DIR%\r
+copy ..\%2\*.html %DOC_DIR%\r
+copy ..\%2\*.png  %DOC_DIR%\r
+del %DOC_DIR%\model.png \r
+\r
+rem zip the directory tree and move to fmu directory \r
+cd fmu\r
+set FMU_FILE=..\..\..\..\fmu\%1\%2.fmu\r
+if exist %ZIP_FILE% del %FMU_FILE%\r
+..\..\..\..\bin\7z.exe a -tzip -xr!.svn %FMU_FILE% ^\r
+  modelDescription.xml model.png binaries sources documentation\r
+goto cleanup\r
+\r
+:noCompiler\r
+echo No Microsoft Visual C compiler found\r
+exit\r
+\r
+:compileError\r
+echo build of %2 failed\r
+\r
+:cleanup\r
+popd\r
+if exist temp rmdir /S /Q temp\r
+\r
+rem undo variable settings performed by vsvars32.bat\r
+set PATH=%PREV_PATH%\r
+if defined PREV_INCLUDE set INCLUDE=%PREV_INLUDE%\r
+if defined PREV_LIB     set LIB=%PREV_LIB%\r
+if defined PREV_LIBPATH set LIBPATH=%PREV_LIBPATH%\r
+echo done.\r
+\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/cs.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/cs.xml
new file mode 100644 (file)
index 0000000..9e38bc4
--- /dev/null
@@ -0,0 +1,8 @@
+<Implementation>\r
+  <CoSimulation_StandAlone>\r
+    <Capabilities\r
+      canHandleVariableCommunicationStepSize="true"\r
+      canHandleEvents="true"/>\r
+  </CoSimulation_StandAlone>\r
+</Implementation>\r
+</fmiModelDescription>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/_main.html
new file mode 100644 (file)
index 0000000..f981d0f
--- /dev/null
@@ -0,0 +1,29 @@
+<html>\r
+<head>\r
+<title>Documentation for dq.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+<h1>dq.fmu</h1>\r
+This FMU implements the equation \r
+<ul>\r
+<li> der(x) = -k * x </li>\r
+</ul>\r
+The analytical solution of this system is \r
+<ul>\r
+<li> x(t) = exp(-k*t) </li>\r
+</ul>\r
+The above equation is also known as \r
+<a href="http://en.wikipedia.org/wiki/Germund_Dahlquist" target="_blank">Dahlquist</a> \r
+test equation.\r
+<br/>\r
+<img src="plot_x.png">\r
+<br/>\r
+The figure shows the solution for x computed with Silver \r
+for start values k = 1 and x = 1.\r
+</body>\r
+</html>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/dq.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/dq.c
new file mode 100644 (file)
index 0000000..bb8df47
--- /dev/null
@@ -0,0 +1,67 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU - the Dahlquist test equation. \r
+ *\r
+ *   der(x) = - k * x and x(0) = 1. \r
+ *   Analytical solution: x(t) = exp(-k*t).\r
+ *\r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER dq\r
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f000}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 3\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_STATES 1\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define x_     0\r
+#define der_x_ 1\r
+#define k_     2\r
+\r
+// define state vector as vector of value references\r
+#define STATES { x_ }\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    r(x_) = 1;\r
+    r(k_) = 1;\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives\r
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){\r
+    switch (vr) {\r
+        case x_     : return r(x_);\r
+        case der_x_ : return - r(k_) * r(x_);\r
+        case k_     : return r(k_);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// Used to set the next time event, if any.\r
+void eventUpdate(fmiComponent comp, fmiEventInfo* eventInfo) {\r
+} \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/modelDescription.xml
new file mode 100644 (file)
index 0000000..daf9fbf
--- /dev/null
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="dq"\r
+  modelIdentifier="dq"\r
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f000}"\r
+  numberOfContinuousStates="1"\r
+  numberOfEventIndicators="0">\r
+<ModelVariables>\r
+  <ScalarVariable name="x" valueReference="0" description="the only state">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(x)" valueReference="1">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="k" valueReference="2" variability="parameter">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/plot_x.PNG b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/plot_x.PNG
new file mode 100644 (file)
index 0000000..b28fa66
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/dq/plot_x.PNG differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/fmuTemplate.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/fmuTemplate.c
new file mode 100644 (file)
index 0000000..e64b47e
--- /dev/null
@@ -0,0 +1,765 @@
+/* ---------------------------------------------------------------------------*\r
+ * Implementation of the FMI interface based on functions and macros to\r
+ * be defined by the includer of this file. \r
+ * If FMI_COSIMULATION is defined, this implements "FMI for Co-Simulation 1.0",\r
+ * otherwise "FMI for Model Exchange 1.0".\r
+ * The "FMI for Co-Simulation 1.0", implementation assumes that exactly the \r
+ * following capability flags are set to fmiTrue:\r
+ *    canHandleVariableCommunicationStepSize, i.e. fmiDoStep step size can vary\r
+ *    canHandleEvents, i.e. fmiDoStep step size can be zero\r
+ * and all other capability flags are set to default, i.e. to fmiFalse or 0.\r
+ *\r
+ * Revision history\r
+ *  07.02.2010 initial version for "Model Exchange 1.0" released in FMU SDK 1.0\r
+ *  05.03.2010 bug fix: fmiSetString now copies the passed string argument\r
+ *     and fmiFreeModelInstance frees all string copies\r
+ *  11.12.2010 replaced calloc by functions.allocateMemory in fmiInstantiateModel\r
+ *  04.08.2011 added support for "FMI for Co-Simulation 1.0"\r
+ *  \r
+ * (c) 2011 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// array of value references of states\r
+#if NUMBER_OF_REALS>0\r
+fmiValueReference vrStates[NUMBER_OF_STATES] = STATES; \r
+#endif\r
+\r
+// ---------------------------------------------------------------------------\r
+// Private helpers used below to validate function arguments\r
+// ---------------------------------------------------------------------------\r
+\r
+static fmiBoolean invalidNumber(ModelInstance* comp, const char* f, const char* arg, int n, int nExpected){\r
+    if (n != nExpected) {\r
+        comp->state = modelError;\r
+        comp->functions.logger(comp, comp->instanceName, fmiError, "error", \r
+                "%s: Invalid argument %s = %d. Expected %d.", f, arg, n, nExpected);\r
+        return fmiTrue;\r
+    }\r
+    return fmiFalse;\r
+}\r
+\r
+static fmiBoolean invalidState(ModelInstance* comp, const char* f, int statesExpected){\r
+    if (!comp) \r
+        return fmiTrue;\r
+    if (!(comp->state & statesExpected)) {\r
+        comp->state = modelError;\r
+        comp->functions.logger(comp, comp->instanceName, fmiError, "error", \r
+                "%s: Illegal call sequence.", f);\r
+        return fmiTrue;\r
+    }\r
+    return fmiFalse;\r
+}\r
+\r
+static fmiBoolean nullPointer(ModelInstance* comp, const char* f, const char* arg, const void* p){\r
+    if (!p) {\r
+        comp->state = modelError;\r
+        comp->functions.logger(comp, comp->instanceName, fmiError, "error", \r
+                "%s: Invalid argument %s = NULL.", f, arg);\r
+        return fmiTrue;\r
+    }\r
+    return fmiFalse;\r
+}\r
+\r
+static fmiBoolean vrOutOfRange(ModelInstance* comp, const char* f, fmiValueReference vr, int end) {\r
+    if (vr >= end) {\r
+        comp->functions.logger(comp, comp->instanceName, fmiError, "error",\r
+                "%s: Illegal value reference %u.", f, vr);\r
+        comp->state = fmiError;\r
+        return fmiTrue;\r
+    }\r
+    return fmiFalse;\r
+}  \r
+\r
+// ---------------------------------------------------------------------------\r
+// Private helpers used below to implement functions\r
+// ---------------------------------------------------------------------------\r
+\r
+fmiStatus setString(fmiComponent comp, fmiValueReference vr, fmiString value){\r
+    return fmiSetString(comp, &vr, 1, &value);\r
+}\r
+\r
+// fname is fmiInstantiateModel or fmiInstantiateSlave\r
+static fmiComponent instantiateModel(char* fname, fmiString instanceName, fmiString GUID, \r
+        fmiCallbackFunctions functions, fmiBoolean loggingOn) {\r
+    ModelInstance* comp;\r
+    if (!functions.logger) \r
+        return NULL;\r
+    if (!functions.allocateMemory || !functions.freeMemory){ \r
+        functions.logger(NULL, instanceName, fmiError, "error", \r
+                "%s: Missing callback function.", fname);\r
+        return NULL;\r
+    }\r
+    if (!instanceName || strlen(instanceName)==0) { \r
+        functions.logger(NULL, instanceName, fmiError, "error", \r
+                "%s: Missing instance name.", fname);\r
+        return NULL;\r
+    }\r
+    if (strcmp(GUID, MODEL_GUID)) {\r
+        functions.logger(NULL, instanceName, fmiError, "error", \r
+                "%s: Wrong GUID %s. Expected %s.", fname, GUID, MODEL_GUID);\r
+        return NULL;\r
+    }\r
+    comp = (ModelInstance *)functions.allocateMemory(1, sizeof(ModelInstance));\r
+    if (comp) {\r
+        comp->r = functions.allocateMemory(NUMBER_OF_REALS,    sizeof(fmiReal));\r
+        comp->i = functions.allocateMemory(NUMBER_OF_INTEGERS, sizeof(fmiInteger));\r
+        comp->b = functions.allocateMemory(NUMBER_OF_BOOLEANS, sizeof(fmiBoolean));\r
+        comp->s = functions.allocateMemory(NUMBER_OF_STRINGS,  sizeof(fmiString));\r
+        comp->isPositive = functions.allocateMemory(NUMBER_OF_EVENT_INDICATORS, sizeof(fmiBoolean));\r
+    }\r
+    if (!comp || !comp->r || !comp->i || !comp->b || !comp->s || !comp->isPositive) {\r
+        functions.logger(NULL, instanceName, fmiError, "error", \r
+                "%s: Out of memory.", fname);\r
+        return NULL;\r
+    }\r
+    if (comp->loggingOn) comp->functions.logger(NULL, instanceName, fmiOK, "log", \r
+            "%s: GUID=%s", fname, GUID);\r
+    comp->instanceName = instanceName;\r
+    comp->GUID = GUID;\r
+    comp->functions = functions;\r
+    comp->loggingOn = loggingOn;\r
+    comp->state = modelInstantiated;\r
+    setStartValues(comp); // to be implemented by the includer of this file\r
+    return comp;\r
+}\r
+\r
+// fname is fmiInitialize or fmiInitializeSlave\r
+static fmiStatus init(char* fname, fmiComponent c, fmiBoolean toleranceControlled, fmiReal relativeTolerance,\r
+    fmiEventInfo* eventInfo) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, fname, modelInstantiated))\r
+         return fmiError;\r
+    if (nullPointer(comp, fname, "eventInfo", eventInfo))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+        "%s: toleranceControlled=%d relativeTolerance=%g", \r
+        fname, toleranceControlled, relativeTolerance);\r
+    eventInfo->iterationConverged  = fmiTrue;\r
+    eventInfo->stateValueReferencesChanged = fmiFalse;\r
+    eventInfo->stateValuesChanged  = fmiFalse;\r
+    eventInfo->terminateSimulation = fmiFalse;\r
+    eventInfo->upcomingTimeEvent   = fmiFalse;\r
+    initialize(comp, eventInfo); // to be implemented by the includer of this file\r
+    comp->state = modelInitialized;\r
+    return fmiOK;\r
+}\r
+\r
+// fname is fmiTerminate or fmiTerminateSlave\r
+static fmiStatus terminate(char* fname, fmiComponent c){\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, fname, modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", fname);\r
+    comp->state = modelTerminated;\r
+    return fmiOK;\r
+}\r
+\r
+// fname is freeModelInstance of freeSlaveInstance\r
+void freeInstance(char* fname, fmiComponent c) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (!comp) return;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", fname);\r
+    if (comp->r) comp->functions.freeMemory(comp->r);\r
+    if (comp->i) comp->functions.freeMemory(comp->i);\r
+    if (comp->b) comp->functions.freeMemory(comp->b);\r
+    if (comp->s) {\r
+        int i;\r
+        for (i=0; i<NUMBER_OF_STRINGS; i++){\r
+            if (comp->s[i]) comp->functions.freeMemory(comp->s[i]);\r
+        }\r
+        comp->functions.freeMemory(comp->s);\r
+    }\r
+    comp->functions.freeMemory(comp);\r
+}\r
+\r
+// ---------------------------------------------------------------------------\r
+// FMI functions: class methods not depending of a specific model instance\r
+// ---------------------------------------------------------------------------\r
+\r
+const char* fmiGetVersion() {\r
+    return fmiVersion;\r
+}\r
+\r
+// ---------------------------------------------------------------------------\r
+// FMI functions: for FMI Model Exchange 1.0 and for FMI Co-Simulation 1.0\r
+// logging control, setters and getters for Real, Integer, Boolean, String\r
+// ---------------------------------------------------------------------------\r
+\r
+fmiStatus fmiSetDebugLogging(fmiComponent c, fmiBoolean loggingOn) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetDebugLogging", not_modelError))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetDebugLogging: loggingOn=%d", loggingOn);\r
+    comp->loggingOn = loggingOn;\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetReal", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetReal", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetReal", "value[]", value))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetReal: nvr = %d", nvr);\r
+    // no check wether setting the value is allowed in the current state\r
+    for (i=0; i<nvr; i++) {\r
+       if (vrOutOfRange(comp, "fmiSetReal", vr[i], NUMBER_OF_REALS))\r
+           return fmiError;\r
+       if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetReal: #r%d# = %.16g", vr[i], value[i]);\r
+       comp->r[vr[i]] = value[i];\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetInteger", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetInteger", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetInteger", "value[]", value))\r
+         return fmiError;\r
+    if (comp->loggingOn)\r
+        comp->functions.logger(c, comp->instanceName, fmiOK, "log", "fmiSetInteger: nvr = %d",  nvr);\r
+    for (i=0; i<nvr; i++) {\r
+       if (vrOutOfRange(comp, "fmiSetInteger", vr[i], NUMBER_OF_INTEGERS))\r
+           return fmiError;\r
+       if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetInteger: #i%d# = %d", vr[i], value[i]);\r
+        comp->i[vr[i]] = value[i]; \r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetBoolean", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetBoolean", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetBoolean", "value[]", value))\r
+         return fmiError;\r
+    if (comp->loggingOn)\r
+        comp->functions.logger(c, comp->instanceName, fmiOK, "log", "fmiSetBoolean: nvr = %d",  nvr);\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiSetBoolean", vr[i], NUMBER_OF_BOOLEANS))\r
+            return fmiError;\r
+       if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetBoolean: #b%d# = %s", vr[i], value[i] ? "true" : "false");\r
+        comp->b[vr[i]] = value[i]; \r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]){\r
+    int i, n;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetString", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetString", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiSetString", "value[]", value))\r
+         return fmiError;\r
+    if (comp->loggingOn)\r
+        comp->functions.logger(c, comp->instanceName, fmiOK, "log", "fmiSetString: nvr = %d",  nvr);\r
+    for (i=0; i<nvr; i++) {\r
+        char* string = comp->s[vr[i]];\r
+        if (vrOutOfRange(comp, "fmiSetString", vr[i], NUMBER_OF_STRINGS))\r
+            return fmiError;\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetString: #s%d# = '%s'", vr[i], value[i]);\r
+        if (nullPointer(comp, "fmiSetString", "value[i]", value[i]))\r
+            return fmiError;\r
+        if (string==NULL || strlen(string) < strlen(value[i])) {\r
+            if (string) comp->functions.freeMemory(string);\r
+            comp->s[vr[i]] = comp->functions.allocateMemory(1+strlen(value[i]), sizeof(char));\r
+            if (!comp->s[vr[i]]) {\r
+                comp->state = modelError;\r
+                comp->functions.logger(NULL, comp->instanceName, fmiError, "error", "fmiSetString: Out of memory.");\r
+                return fmiError;\r
+            }\r
+        }\r
+        strcpy(comp->s[vr[i]], value[i]);\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetReal", not_modelError))\r
+        return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetReal", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetReal", "value[]", value))\r
+         return fmiError;\r
+#if NUMBER_OF_REALS>0\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiGetReal", vr[i], NUMBER_OF_REALS)) \r
+            return fmiError;\r
+        value[i] = getReal(comp, vr[i]); // to be implemented by the includer of this file\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiGetReal: #r%u# = %.16g", vr[i], value[i]);\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetInteger", not_modelError))\r
+        return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetInteger", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetInteger", "value[]", value))\r
+         return fmiError;\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiGetInteger", vr[i], NUMBER_OF_INTEGERS))\r
+           return fmiError;\r
+        value[i] = comp->i[vr[i]];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiGetInteger: #i%u# = %d", vr[i], value[i]);\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetBoolean", not_modelError))\r
+        return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetBoolean", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetBoolean", "value[]", value))\r
+         return fmiError;\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiGetBoolean", vr[i], NUMBER_OF_BOOLEANS))\r
+           return fmiError;\r
+        value[i] = comp->b[vr[i]];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiGetBoolean: #b%u# = %s", vr[i], value[i]? "true" : "false");\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetString", not_modelError))\r
+        return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetString", "vr[]", vr))\r
+         return fmiError;\r
+    if (nvr>0 && nullPointer(comp, "fmiGetString", "value[]", value))\r
+         return fmiError;\r
+    for (i=0; i<nvr; i++) {\r
+        if (vrOutOfRange(comp, "fmiGetString", vr[i], NUMBER_OF_STRINGS))\r
+           return fmiError;\r
+        value[i] = comp->s[vr[i]];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiGetString: #s%u# = '%s'", vr[i], value[i]);\r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+#ifdef FMI_COSIMULATION\r
+// ---------------------------------------------------------------------------\r
+// FMI functions: only for FMI Co-Simulation 1.0\r
+// ---------------------------------------------------------------------------\r
+\r
+const char* fmiGetTypesPlatform() {\r
+    return fmiPlatform;\r
+}\r
+\r
+fmiComponent fmiInstantiateSlave(fmiString  instanceName, fmiString  GUID,\r
+    fmiString  fmuLocation, fmiString  mimeType, fmiReal timeout, fmiBoolean visible,\r
+    fmiBoolean interactive, fmiCallbackFunctions functions, fmiBoolean loggingOn) {\r
+    // ignoring arguments: fmuLocation, mimeType, timeout, visible, interactive\r
+    return instantiateModel("fmiInstantiateSlave", instanceName, GUID, functions, loggingOn);\r
+}\r
+\r
+fmiStatus fmiInitializeSlave(fmiComponent c, fmiReal tStart, fmiBoolean StopTimeDefined, fmiReal tStop) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiBoolean toleranceControlled = fmiFalse;\r
+    fmiReal relativeTolerance = 0;\r
+    fmiStatus flag = fmiOK;\r
+    comp->eventInfo.iterationConverged = 0;\r
+    while (flag==fmiOK && !comp->eventInfo.iterationConverged) {\r
+        // ignoring arguments: tStart, StopTimeDefined, tStop\r
+        flag = init("fmiInitializeSlave", c, toleranceControlled, relativeTolerance, &comp->eventInfo);\r
+    }\r
+    return flag;\r
+}\r
+\r
+fmiStatus fmiTerminateSlave(fmiComponent c) {\r
+    return terminate("fmiTerminateSlave", c);\r
+}\r
+\r
+fmiStatus fmiResetSlave(fmiComponent c) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiResetSlave", modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", "fmiResetSlave");\r
+    comp->state = modelInstantiated;\r
+    setStartValues(comp); // to be implemented by the includer of this file\r
+    return fmiOK;\r
+}\r
+\r
+void fmiFreeSlaveInstance(fmiComponent c) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiFreeSlaveInstance", modelTerminated))\r
+         return;\r
+    freeInstance("fmiFreeSlaveInstance", c);\r
+}\r
+\r
+fmiStatus fmiSetRealInputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t nvr,\r
+    const fmiInteger order[], const fmiReal value[]) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    if (invalidState(comp, "fmiSetRealInputDerivatives", modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "fmiSetRealInputDerivatives: nvr= %d", nvr);\r
+    log(NULL, comp->instanceName, fmiError, "warning", "fmiSetRealInputDerivatives: ignoring function call." \r
+      " This model cannot interpolate inputs: canInterpolateInputs=\"fmiFalse\"");\r
+    return fmiWarning;\r
+}\r
+\r
+fmiStatus fmiGetRealOutputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t  nvr,\r
+    const fmiInteger order[], fmiReal value[]) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    if (invalidState(comp, "fmiGetRealOutputDerivatives", modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "fmiGetRealOutputDerivatives: nvr= %d", nvr);\r
+    log(NULL, comp->instanceName, fmiError, "warning", "fmiGetRealOutputDerivatives: ignoring function call." \r
+      " This model cannot compute derivatives of outputs: MaxOutputDerivativeOrder=\"0\"");\r
+    for (i=0; i<nvr; i++) value[i] = 0;\r
+    return fmiWarning;\r
+}\r
+\r
+fmiStatus fmiCancelStep(fmiComponent c) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    if (invalidState(comp, "fmiCancelStep", modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "fmiCancelStep");\r
+    log(NULL, comp->instanceName, fmiError, "error", \r
+        "fmiCancelStep: Can be called when fmiDoStep returned fmiPending."\r
+        " This is not the case."); \r
+    return fmiError;\r
+}\r
+\r
+fmiStatus fmiDoStep(fmiComponent c, fmiReal currentCommunicationPoint, \r
+    fmiReal communicationStepSize, fmiBoolean newStep) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    double h = communicationStepSize / 10;\r
+    int k,i;\r
+    const int n = 10; // how many Euler steps to perform for one do step\r
+    double prevState[max(NUMBER_OF_STATES, 1)];\r
+    double prevEventIndicators[max(NUMBER_OF_EVENT_INDICATORS, 1)];\r
+    int stateEvent = 0;\r
+\r
+    if (invalidState(comp, "fmiDoStep", modelInitialized))\r
+         return fmiError;\r
+\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "fmiDoStep: "\r
+       "currentCommunicationPoint = %g, ", \r
+       "communicationStepSize = %g, ", \r
+       "newStep = fmi%s", \r
+       currentCommunicationPoint, communicationStepSize, newStep ? "True" : "False");\r
+    \r
+    // Treat also case of zero step, i.e. during an event iteration\r
+    if (communicationStepSize == 0) {\r
+        return fmiOK;\r
+    }\r
+           \r
+#if NUMBER_OF_EVENT_INDICATORS>0\r
+    // initialize previous event indcators with current values\r
+    for (i=0; i<NUMBER_OF_EVENT_INDICATORS; i++) {\r
+        prevEventIndicators[i] = getEventIndicator(comp, i);\r
+    }\r
+#endif\r
+\r
+    // break the step into n steps and do forward Euler. \r
+    comp->time = currentCommunicationPoint;\r
+    for (k=0; k<n; k++) {\r
+        comp->time += h;\r
+\r
+#if NUMBER_OF_REALS>0\r
+        for (i=0; i<NUMBER_OF_STATES; i++) {\r
+            prevState[i] = r(vrStates[i]);\r
+        }\r
+        for (i=0; i<NUMBER_OF_STATES; i++) {\r
+            fmiValueReference vr = vrStates[i];\r
+            r(vr) += h * getReal(comp, vr+1); // forward Euler step\r
+        }\r
+#endif        \r
+\r
+#if NUMBER_OF_EVENT_INDICATORS>0\r
+        // check for state event\r
+        for (i=0; i<NUMBER_OF_EVENT_INDICATORS; i++) {\r
+            double ei = getEventIndicator(comp, i);\r
+            if (ei * prevEventIndicators[i] < 0) {\r
+                if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                    "fmiDoStep: state event at %g, z%d crosses zero -%c-", comp->time, i, ei<0 ? '\\' : '/');\r
+                stateEvent++;\r
+            }\r
+            prevEventIndicators[i] = ei;\r
+        }\r
+        if (stateEvent) {\r
+            eventUpdate(comp, &comp->eventInfo);\r
+            stateEvent = 0;\r
+        } \r
+#endif\r
+        // check for time event\r
+        if (comp->eventInfo.upcomingTimeEvent && comp->time > comp->eventInfo.nextEventTime) {\r
+            if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+                "fmiDoStep: time event detected at %g", comp->time);\r
+            eventUpdate(comp, &comp->eventInfo);\r
+        }\r
+\r
+        // terminate simulation, if requested by the model\r
+        if (comp->eventInfo.terminateSimulation) {\r
+            comp->functions.logger(c, comp->instanceName, fmiOK, "log",\r
+              "fmiDoStep: model requested termination at t=%g", comp->time);\r
+            return fmiError; // enforce termination of the simulation loop\r
+        }        \r
+    }\r
+    return fmiOK;\r
+}\r
+\r
+static fmiStatus getStatus(char* fname, fmiComponent c, const fmiStatusKind s) {\r
+    const char* statusKind[3] = {"fmiDoStepStatus","fmiPendingStatus","fmiLastSuccessfulTime"};\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    fmiCallbackLogger log = comp->functions.logger;\r
+    if (invalidState(comp, fname, modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) log(c, comp->instanceName, fmiOK, "log", "$s: fmiStatusKind = %s", fname, statusKind[s]);\r
+    switch(s) {\r
+        case fmiDoStepStatus:  log(NULL, comp->instanceName, fmiError, "error", \r
+           "%s: Can be called with fmiDoStepStatus when fmiDoStep returned fmiPending."\r
+           " This is not the case.", fname); \r
+           break;\r
+        case fmiPendingStatus:  log(NULL, comp->instanceName, fmiError, "error", \r
+           "%s: Can be called with fmiPendingStatus when fmiDoStep returned fmiPending."\r
+           " This is not the case.", fname); \r
+           break;\r
+        case fmiLastSuccessfulTime:  log(NULL, comp->instanceName, fmiError, "error", \r
+           "%s: Can be called with fmiLastSuccessfulTime when fmiDoStep returned fmiDiscard."\r
+           " This is not the case.", fname); \r
+           break;\r
+    }\r
+    return fmiError;\r
+}\r
+\r
+fmiStatus fmiGetStatus(fmiComponent c, const fmiStatusKind s, fmiStatus* value) {\r
+    return getStatus("fmiGetStatus", c, s);\r
+}\r
+\r
+fmiStatus fmiGetRealStatus(fmiComponent c, const fmiStatusKind s, fmiReal* value){\r
+    return getStatus("fmiGetRealStatus", c, s);\r
+}\r
+\r
+fmiStatus fmiGetIntegerStatus(fmiComponent c, const fmiStatusKind s, fmiInteger* value){\r
+    return getStatus("fmiGetIntegerStatus", c, s);\r
+}\r
+\r
+fmiStatus fmiGetBooleanStatus(fmiComponent c, const fmiStatusKind s, fmiBoolean* value){\r
+    return getStatus("fmiGetBooleanStatus", c, s);\r
+}\r
+\r
+fmiStatus fmiGetStringStatus(fmiComponent c, const fmiStatusKind s, fmiString*  value){\r
+    return getStatus("fmiGetStringStatus", c, s);\r
+}\r
+\r
+#else\r
+// ---------------------------------------------------------------------------\r
+// FMI functions: only for Model Exchange 1.0\r
+// ---------------------------------------------------------------------------\r
+\r
+const char* fmiGetModelTypesPlatform() {\r
+    return fmiModelTypesPlatform;\r
+}\r
+\r
+fmiComponent fmiInstantiateModel(fmiString instanceName, fmiString GUID, \r
+        fmiCallbackFunctions functions, fmiBoolean loggingOn) {\r
+    return instantiateModel("fmiInstantiateModel", instanceName, GUID, functions, loggingOn);\r
+}\r
+\r
+fmiStatus fmiInitialize(fmiComponent c, fmiBoolean toleranceControlled, fmiReal relativeTolerance,\r
+    fmiEventInfo* eventInfo) {\r
+    return init("fmiInitialize", c, toleranceControlled, relativeTolerance, eventInfo);\r
+}\r
+\r
+fmiStatus fmiSetTime(fmiComponent c, fmiReal time) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiSetTime", modelInstantiated|modelInitialized))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetTime: time=%.16g", time);\r
+    comp->time = time;\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiSetContinuousStates(fmiComponent c, const fmiReal x[], size_t nx){\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    int i;\r
+    if (invalidState(comp, "fmiSetContinuousStates", modelInitialized))\r
+         return fmiError;\r
+    if (invalidNumber(comp, "fmiSetContinuousStates", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiSetContinuousStates", "x[]", x))\r
+         return fmiError;\r
+#if NUMBER_OF_REALS>0\r
+    for (i=0; i<nx; i++) {\r
+        fmiValueReference vr = vrStates[i];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiSetContinuousStates: #r%d#=%.16g", vr, x[i]);\r
+        assert(vr>=0 && vr<NUMBER_OF_REALS);\r
+        comp->r[vr] = x[i];\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiEventUpdate(fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo) {\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiEventUpdate", modelInitialized))\r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiEventUpdate", "eventInfo", eventInfo))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+        "fmiEventUpdate: intermediateResults = %d", intermediateResults);\r
+    eventInfo->iterationConverged  = fmiTrue;\r
+    eventInfo->stateValueReferencesChanged = fmiFalse;\r
+    eventInfo->stateValuesChanged  = fmiFalse;\r
+    eventInfo->terminateSimulation = fmiFalse;\r
+    eventInfo->upcomingTimeEvent   = fmiFalse;\r
+    eventUpdate(comp, eventInfo); // to be implemented by the includer of this file\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiCompletedIntegratorStep(fmiComponent c, fmiBoolean* callEventUpdate){\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiCompletedIntegratorStep", modelInitialized))\r
+         return fmiError;\r
+    if (nullPointer(comp, "fmiCompletedIntegratorStep", "callEventUpdate", callEventUpdate))\r
+         return fmiError;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiCompletedIntegratorStep");\r
+    *callEventUpdate = fmiFalse;\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetStateValueReferences(fmiComponent c, fmiValueReference vrx[], size_t nx){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetStateValueReferences", not_modelError))\r
+        return fmiError;\r
+    if (invalidNumber(comp, "fmiGetStateValueReferences", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiGetStateValueReferences", "vrx[]", vrx))\r
+         return fmiError;\r
+#if NUMBER_OF_REALS>0\r
+    for (i=0; i<nx; i++) {\r
+        vrx[i] = vrStates[i];\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiGetStateValueReferences: vrx[%d] = %d", i, vrx[i]);\r
+    }\r
+#endif \r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetContinuousStates(fmiComponent c, fmiReal states[], size_t nx){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetContinuousStates", not_modelError))\r
+        return fmiError;\r
+    if (invalidNumber(comp, "fmiGetContinuousStates", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiGetContinuousStates", "states[]", states))\r
+         return fmiError;\r
+#if NUMBER_OF_REALS>0\r
+    for (i=0; i<nx; i++) {\r
+        fmiValueReference vr = vrStates[i];\r
+        states[i] = getReal(comp, vr); // to be implemented by the includer of this file\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiGetContinuousStates: #r%u# = %.16g", vr, states[i]);\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetNominalContinuousStates(fmiComponent c, fmiReal x_nominal[], size_t nx){\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetNominalContinuousStates", not_modelError))\r
+        return fmiError;\r
+    if (invalidNumber(comp, "fmiGetNominalContinuousStates", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiGetNominalContinuousStates", "x_nominal[]", x_nominal))\r
+         return fmiError;\r
+    x_nominal[0] = 1;\r
+    if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+        "fmiGetNominalContinuousStates: x_nominal[0..%d] = 1.0", nx-1);\r
+    for (i=0; i<nx; i++) \r
+        x_nominal[i] = 1;\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetDerivatives(fmiComponent c, fmiReal derivatives[], size_t nx) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetDerivatives", not_modelError))\r
+         return fmiError;\r
+    if (invalidNumber(c, "fmiGetDerivatives", "nx", nx, NUMBER_OF_STATES)) \r
+        return fmiError;\r
+    if (nullPointer(comp, "fmiGetDerivatives", "derivatives[]", derivatives))\r
+         return fmiError;\r
+#if NUMBER_OF_STATES>0\r
+    for (i=0; i<nx; i++) {\r
+        fmiValueReference vr = vrStates[i] + 1;\r
+        derivatives[i] = getReal(comp, vr); // to be implemented by the includer of this file\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiGetDerivatives: #r%d# = %.16g", vr, derivatives[i]);\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiGetEventIndicators(fmiComponent c, fmiReal eventIndicators[], size_t ni) {\r
+    int i;\r
+    ModelInstance* comp = (ModelInstance *)c;\r
+    if (invalidState(comp, "fmiGetEventIndicators", not_modelError))\r
+        return fmiError;\r
+    if (invalidNumber(comp, "fmiGetEventIndicators", "ni", ni, NUMBER_OF_EVENT_INDICATORS)) \r
+        return fmiError;\r
+#if NUMBER_OF_EVENT_INDICATORS>0\r
+    for (i=0; i<ni; i++) {\r
+        eventIndicators[i] = getEventIndicator(comp, i); // to be implemented by the includer of this file\r
+        if (comp->loggingOn) comp->functions.logger(c, comp->instanceName, fmiOK, "log", \r
+            "fmiGetEventIndicators: z%d = %.16g", i, eventIndicators[i]);\r
+    }\r
+#endif\r
+    return fmiOK;\r
+}\r
+\r
+fmiStatus fmiTerminate(fmiComponent c){\r
+    return terminate("fmiTerminate", c);\r
+}\r
+\r
+void fmiFreeModelInstance(fmiComponent c) {\r
+    freeInstance("fmiFreeModelInstance", c);\r
+}\r
+\r
+#endif // Model Exchange 1.0\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/fmuTemplate.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/fmuTemplate.h
new file mode 100644 (file)
index 0000000..486bd40
--- /dev/null
@@ -0,0 +1,49 @@
+/* ---------------------------------------------------------------------------*\r
+ * fmuTemplate.h\r
+ * Definitions used in fmiModelFunctions.c and by the includer of this file\r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+\r
+#ifdef FMI_COSIMULATION\r
+#include "fmiFunctions.h"\r
+#else\r
+#include "fmiModelFunctions.h"\r
+#endif\r
+\r
+// macros used to define variables\r
+#define  r(vr) comp->r[vr]\r
+#define  i(vr) comp->i[vr]\r
+#define  b(vr) comp->b[vr]\r
+#define  s(vr) comp->s[vr]\r
+#define pos(z) comp->isPositive[z]\r
+#define copy(vr, value) setString(comp, vr, value)\r
+\r
+#define not_modelError (modelInstantiated|modelInitialized|modelTerminated)\r
+\r
+typedef enum {\r
+    modelInstantiated = 1<<0,\r
+    modelInitialized  = 1<<1,\r
+    modelTerminated   = 1<<2,\r
+    modelError        = 1<<3\r
+} ModelState;\r
+\r
+typedef struct {\r
+    fmiReal    *r;\r
+    fmiInteger *i;\r
+    fmiBoolean *b;\r
+    fmiString  *s;\r
+    fmiBoolean *isPositive;\r
+    fmiReal time;\r
+    fmiString instanceName;\r
+    fmiString GUID;\r
+    fmiCallbackFunctions functions;\r
+    fmiBoolean loggingOn;\r
+    ModelState state;\r
+#ifdef FMI_COSIMULATION\r
+    fmiEventInfo eventInfo;\r
+#endif\r
+} ModelInstance;\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/_main.html
new file mode 100644 (file)
index 0000000..8850b0d
--- /dev/null
@@ -0,0 +1,18 @@
+<html>\r
+<head>\r
+    <title>Documentation for inc.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+<h1>inc.fmu</h1>\r
+This FMU generates time events to increment an integer counter every second and terminates simulation at t=12 sec.\r
+<br/>    \r
+<img src="plot_counter.PNG">\r
+<br/>\r
+The figure shows the solution computed with Silver.\r
+</body>\r
+</html>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/inc.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/inc.c
new file mode 100644 (file)
index 0000000..8440dcd
--- /dev/null
@@ -0,0 +1,56 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU - increments an int counter every second.\r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER inc\r
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f008}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 0\r
+#define NUMBER_OF_INTEGERS 1\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_STATES 0\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define counter_ 0\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    i(counter_) = 1;\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    eventInfo->upcomingTimeEvent   = fmiTrue;\r
+    eventInfo->nextEventTime       = 1 + comp->time;\r
+}\r
+\r
+// called by fmiEventUpdate() after setting eventInfo to defaults\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    i(counter_) += 1;\r
+    if (i(counter_) == 13) \r
+        eventInfo->terminateSimulation = fmiTrue;\r
+    else {\r
+        eventInfo->upcomingTimeEvent   = fmiTrue;\r
+        eventInfo->nextEventTime       = 1 + comp->time;\r
+    }\r
+} \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/modelDescription.xml
new file mode 100644 (file)
index 0000000..58ce6f8
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="inc"\r
+  modelIdentifier="inc"\r
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f008}"\r
+  numberOfContinuousStates="0"\r
+  numberOfEventIndicators="0">\r
+<ModelVariables>\r
+  <ScalarVariable name="counter" valueReference="0" description="counts the seconds" causality = "output">\r
+     <Integer start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/plot_counter.PNG b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/plot_counter.PNG
new file mode 100644 (file)
index 0000000..d3ec25d
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/inc/plot_counter.PNG differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/me.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/me.xml
new file mode 100644 (file)
index 0000000..5ecace6
--- /dev/null
@@ -0,0 +1 @@
+</fmiModelDescription>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/_main.html
new file mode 100644 (file)
index 0000000..082d514
--- /dev/null
@@ -0,0 +1,19 @@
+<html>\r
+<head>\r
+    <title>Documentation for values.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+    <h1>values.fmu</h1>\r
+    This FMU demonstrates the use of all four scalar FMU data types \r
+    and terminates simulation at t=12 sec.\r
+    <img src="values.PNG">\r
+<br>\r
+The figure shows the solution computed with fmusim using the command \r
+<code>fmusim me fmu\me\values.fmu 12 12</code>.\r
+</body>\r
+</html>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/modelDescription.xml
new file mode 100644 (file)
index 0000000..3673a61
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="values"\r
+  modelIdentifier="values"\r
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f004}"\r
+  numberOfContinuousStates="1"\r
+  numberOfEventIndicators="0">\r
+<ModelVariables>\r
+  <ScalarVariable name="x" valueReference="0" description="used as continuous state">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(x)" valueReference="1" description="time derivative of x">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="int_in" valueReference="0" description="integer input" causality = "input">\r
+     <Integer start="2"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="int_out" valueReference="1" description="index in string array 'month'" causality = "output">\r
+     <Integer start="0" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="bool_in" valueReference="0" description="boolean input" causality = "input">\r
+     <Boolean start="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="bool_out" valueReference="1" description="boolean output" causality = "output">\r
+     <Boolean/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="string_in" valueReference="0" description="string input" causality = "input">\r
+     <String start="QTronic"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="string_out" valueReference="1" description="the string month[int_out]" causality = "output">\r
+     <String/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/values.PNG b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/values.PNG
new file mode 100644 (file)
index 0000000..45eaf96
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/values.PNG differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/values.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/values/values.c
new file mode 100644 (file)
index 0000000..536a290
--- /dev/null
@@ -0,0 +1,85 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU \r
+ * This demonstrates the use of all FMU variable types.\r
+ * (c) 2010 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER values\r
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f004}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 2\r
+#define NUMBER_OF_INTEGERS 2\r
+#define NUMBER_OF_BOOLEANS 2\r
+#define NUMBER_OF_STRINGS 2\r
+#define NUMBER_OF_STATES 1\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define x_          0\r
+#define der_x_      1\r
+#define int_in_     0\r
+#define int_out_    1\r
+#define bool_in_    0\r
+#define bool_out_   1\r
+#define string_in_  0\r
+#define string_out_ 1\r
+\r
+// define state vector as vector of value references\r
+#define STATES { x_ }\r
+\r
+const char* month[] = {\r
+    "jan","feb","march","april","may","june","july",\r
+    "august","sept","october","november","december"\r
+};\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    r(x_) = 1;\r
+    i(int_in_) = 2;\r
+    i(int_out_) = 0;\r
+    b(bool_in_) = fmiTrue;\r
+    b(bool_out_) = fmiFalse;\r
+    copy(string_in_, "a string");\r
+    copy(string_out_, month[0]);\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    eventInfo->upcomingTimeEvent   = fmiTrue;\r
+    eventInfo->nextEventTime       = 1 + comp->time;\r
+}\r
+\r
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives\r
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){\r
+    switch (vr) {\r
+        case x_     : return   r(x_);\r
+        case der_x_ : return - r(x_);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// called by fmiEventUpdate() after setting eventInfo to defaults\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+    eventInfo->upcomingTimeEvent   = fmiTrue;\r
+    eventInfo->nextEventTime       = 1 + comp->time;\r
+    i(int_out_) += 1;\r
+    b(bool_out_) = !b(bool_out_);\r
+    if (i(int_out_)<12) copy(string_out_, month[i(int_out_)]);\r
+    else eventInfo->terminateSimulation = fmiTrue;\r
+} \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/_main.html b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/_main.html
new file mode 100644 (file)
index 0000000..07875f4
--- /dev/null
@@ -0,0 +1,23 @@
+<html>\r
+<head>\r
+<title>Documentation for vanDerPol.fmu</title>\r
+<style type="text/css">\r
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }\r
+  h1   { color: #000066; }\r
+</style>\r
+</head>\r
+<body>\r
+<h1>vanDerPol.fmu</h1>\r
+This FMU implements the famous\r
+<a href="http://en.wikipedia.org/wiki/Van_der_Pol_oscillator" target="_blank">Van der Pol oscillator</a>.\r
+<ul>\r
+<li> der(x0) = x1 </li>\r
+<li> der(x1) = mu * ((1 - x0 * x0) * x1) - x0</li>\r
+</ul>\r
+<img src="plot_states.png">\r
+<br/>\r
+The figure shows the solution computed with Silver \r
+for start values x0 = 2, x1 = 0, mu = 1.\r
+</body>\r
+</html>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/model.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/model.png
new file mode 100644 (file)
index 0000000..8d23e9a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/model.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/modelDescription.xml
new file mode 100644 (file)
index 0000000..ca44c3f
--- /dev/null
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="van der Pol oscillator"\r
+  modelIdentifier="vanDerPol"\r
+  guid="{8c4e810f-3da3-4a00-8276-176fa3c9f000}"\r
+  numberOfContinuousStates="2"\r
+  numberOfEventIndicators="0">\r
+<ModelVariables>\r
+  <ScalarVariable name="x0" valueReference="0" description="the first state">\r
+     <Real start="2" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(x0)" valueReference="1">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="x1" valueReference="2" description="the second state">\r
+     <Real start="0" fixed="true"/>\r
+  </ScalarVariable>\r
+  <ScalarVariable name="der(x1)" valueReference="3">\r
+     <Real/>\r
+  </ScalarVariable> \r
+  <ScalarVariable name="mu" valueReference="4" variability="parameter">\r
+     <Real start="1" fixed="true"/>\r
+  </ScalarVariable>\r
+</ModelVariables>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/plot_states.png b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/plot_states.png
new file mode 100644 (file)
index 0000000..05761cd
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/plot_states.png differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/vanDerPol.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/models/vanDerPol/vanDerPol.c
new file mode 100644 (file)
index 0000000..c494520
--- /dev/null
@@ -0,0 +1,75 @@
+/* ---------------------------------------------------------------------------*\r
+ * Sample implementation of an FMU - the Van der Pol oscillator. \r
+ * See http://en.wikipedia.org/wiki/Van_der_Pol_oscillator\r
+ *  \r
+ *   der(x0) = x1\r
+ *   der(x1) = mu * ((1 - x0 ^ 2) * x1) - x0;\r
+ *\r
+ *   start values: x0=2, x1=0, mue=1\r
+ *\r
+ * (c) 2011 QTronic GmbH \r
+ * ---------------------------------------------------------------------------*/\r
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER vanDerPol\r
+#define MODEL_GUID "{8c4e810f-3da3-4a00-8276-176fa3c9f000}"\r
+\r
+// define model size\r
+#define NUMBER_OF_REALS 5\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_STATES 2\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+\r
+// include fmu header files, typedefs and macros\r
+#include "fmuTemplate.h"\r
+\r
+// define all model variables and their value references\r
+// conventions used here:\r
+// - if x is a variable, then macro x_ is its variable reference\r
+// - the vr of a variable is its index in array  r, i, b or s\r
+// - if k is the vr of a real state, then k+1 is the vr of its derivative\r
+#define x0_     0\r
+#define der_x0_ 1\r
+#define x1_     2\r
+#define der_x1_ 3\r
+#define mu_     4\r
+\r
+// define state vector as vector of value references\r
+#define STATES { x0_, x1_ }\r
+\r
+// called by fmiInstantiateModel\r
+// Set values for all variables that define a start value\r
+// Settings used unless changed by fmiSetX before fmiInitialize\r
+void setStartValues(ModelInstance *comp) {\r
+    r(x0_) = 2;\r
+    r(x1_) = 0;\r
+    r(mu_) = 1;\r
+}\r
+\r
+// called by fmiInitialize() after setting eventInfo to defaults\r
+// Used to set the first time event, if any.\r
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives\r
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){\r
+    switch (vr) {\r
+        case x0_     : return r(x0_);\r
+        case x1_     : return r(x1_);\r
+        case der_x0_ : return r(x1_);\r
+        case der_x1_ : return r(mu_) * ((1.0-r(x0_)*r(x0_))*r(x1_)) - r(x0_);\r
+        case mu_     : return r(mu_);\r
+        default: return 0;\r
+    }\r
+}\r
+\r
+// Used to set the next time event, if any.\r
+void eventUpdate(fmiComponent comp, fmiEventInfo* eventInfo) {\r
+} \r
+\r
+// include code that implements the FMI based on the above definitions\r
+#include "fmuTemplate.c"\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/COPYING.txt b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/COPYING.txt
new file mode 100644 (file)
index 0000000..9042217
--- /dev/null
@@ -0,0 +1,24 @@
+Files expat.h, expat_external.h and libexpatMT.lib\r
+\r
+Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+                               and Clark Cooper\r
+Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining\r
+a copy of this software and associated documentation files (the\r
+"Software"), to deal in the Software without restriction, including\r
+without limitation the rights to use, copy, modify, merge, publish,\r
+distribute, sublicense, and/or sell copies of the Software, and to\r
+permit persons to whom the Software is furnished to do so, subject to\r
+the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included\r
+in all copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\r
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\r
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/expat.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/expat.h
new file mode 100644 (file)
index 0000000..6c2b6ff
--- /dev/null
@@ -0,0 +1,1014 @@
+/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+   See the file COPYING for copying permission.\r
+*/\r
+\r
+#ifndef Expat_INCLUDED\r
+#define Expat_INCLUDED 1\r
+\r
+#ifdef __VMS\r
+/*      0        1         2         3      0        1         2         3\r
+        1234567890123456789012345678901     1234567890123456789012345678901 */\r
+#define XML_SetProcessingInstructionHandler XML_SetProcessingInstrHandler\r
+#define XML_SetUnparsedEntityDeclHandler    XML_SetUnparsedEntDeclHandler\r
+#define XML_SetStartNamespaceDeclHandler    XML_SetStartNamespcDeclHandler\r
+#define XML_SetExternalEntityRefHandlerArg  XML_SetExternalEntRefHandlerArg\r
+#endif\r
+\r
+#include <stdlib.h>\r
+#include "expat_external.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+struct XML_ParserStruct;\r
+typedef struct XML_ParserStruct *XML_Parser;\r
+\r
+/* Should this be defined using stdbool.h when C99 is available? */\r
+typedef unsigned char XML_Bool;\r
+#define XML_TRUE   ((XML_Bool) 1)\r
+#define XML_FALSE  ((XML_Bool) 0)\r
+\r
+/* The XML_Status enum gives the possible return values for several\r
+   API functions.  The preprocessor #defines are included so this\r
+   stanza can be added to code that still needs to support older\r
+   versions of Expat 1.95.x:\r
+\r
+   #ifndef XML_STATUS_OK\r
+   #define XML_STATUS_OK    1\r
+   #define XML_STATUS_ERROR 0\r
+   #endif\r
+\r
+   Otherwise, the #define hackery is quite ugly and would have been\r
+   dropped.\r
+*/\r
+enum XML_Status {\r
+  XML_STATUS_ERROR = 0,\r
+#define XML_STATUS_ERROR XML_STATUS_ERROR\r
+  XML_STATUS_OK = 1,\r
+#define XML_STATUS_OK XML_STATUS_OK\r
+  XML_STATUS_SUSPENDED = 2\r
+#define XML_STATUS_SUSPENDED XML_STATUS_SUSPENDED\r
+};\r
+\r
+enum XML_Error {\r
+  XML_ERROR_NONE,\r
+  XML_ERROR_NO_MEMORY,\r
+  XML_ERROR_SYNTAX,\r
+  XML_ERROR_NO_ELEMENTS,\r
+  XML_ERROR_INVALID_TOKEN,\r
+  XML_ERROR_UNCLOSED_TOKEN,\r
+  XML_ERROR_PARTIAL_CHAR,\r
+  XML_ERROR_TAG_MISMATCH,\r
+  XML_ERROR_DUPLICATE_ATTRIBUTE,\r
+  XML_ERROR_JUNK_AFTER_DOC_ELEMENT,\r
+  XML_ERROR_PARAM_ENTITY_REF,\r
+  XML_ERROR_UNDEFINED_ENTITY,\r
+  XML_ERROR_RECURSIVE_ENTITY_REF,\r
+  XML_ERROR_ASYNC_ENTITY,\r
+  XML_ERROR_BAD_CHAR_REF,\r
+  XML_ERROR_BINARY_ENTITY_REF,\r
+  XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF,\r
+  XML_ERROR_MISPLACED_XML_PI,\r
+  XML_ERROR_UNKNOWN_ENCODING,\r
+  XML_ERROR_INCORRECT_ENCODING,\r
+  XML_ERROR_UNCLOSED_CDATA_SECTION,\r
+  XML_ERROR_EXTERNAL_ENTITY_HANDLING,\r
+  XML_ERROR_NOT_STANDALONE,\r
+  XML_ERROR_UNEXPECTED_STATE,\r
+  XML_ERROR_ENTITY_DECLARED_IN_PE,\r
+  XML_ERROR_FEATURE_REQUIRES_XML_DTD,\r
+  XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING,\r
+  /* Added in 1.95.7. */\r
+  XML_ERROR_UNBOUND_PREFIX,\r
+  /* Added in 1.95.8. */\r
+  XML_ERROR_UNDECLARING_PREFIX,\r
+  XML_ERROR_INCOMPLETE_PE,\r
+  XML_ERROR_XML_DECL,\r
+  XML_ERROR_TEXT_DECL,\r
+  XML_ERROR_PUBLICID,\r
+  XML_ERROR_SUSPENDED,\r
+  XML_ERROR_NOT_SUSPENDED,\r
+  XML_ERROR_ABORTED,\r
+  XML_ERROR_FINISHED,\r
+  XML_ERROR_SUSPEND_PE,\r
+  /* Added in 2.0. */\r
+  XML_ERROR_RESERVED_PREFIX_XML,\r
+  XML_ERROR_RESERVED_PREFIX_XMLNS,\r
+  XML_ERROR_RESERVED_NAMESPACE_URI\r
+};\r
+\r
+enum XML_Content_Type {\r
+  XML_CTYPE_EMPTY = 1,\r
+  XML_CTYPE_ANY,\r
+  XML_CTYPE_MIXED,\r
+  XML_CTYPE_NAME,\r
+  XML_CTYPE_CHOICE,\r
+  XML_CTYPE_SEQ\r
+};\r
+\r
+enum XML_Content_Quant {\r
+  XML_CQUANT_NONE,\r
+  XML_CQUANT_OPT,\r
+  XML_CQUANT_REP,\r
+  XML_CQUANT_PLUS\r
+};\r
+\r
+/* If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be\r
+   XML_CQUANT_NONE, and the other fields will be zero or NULL.\r
+   If type == XML_CTYPE_MIXED, then quant will be NONE or REP and\r
+   numchildren will contain number of elements that may be mixed in\r
+   and children point to an array of XML_Content cells that will be\r
+   all of XML_CTYPE_NAME type with no quantification.\r
+\r
+   If type == XML_CTYPE_NAME, then the name points to the name, and\r
+   the numchildren field will be zero and children will be NULL. The\r
+   quant fields indicates any quantifiers placed on the name.\r
+\r
+   CHOICE and SEQ will have name NULL, the number of children in\r
+   numchildren and children will point, recursively, to an array\r
+   of XML_Content cells.\r
+\r
+   The EMPTY, ANY, and MIXED types will only occur at top level.\r
+*/\r
+\r
+typedef struct XML_cp XML_Content;\r
+\r
+struct XML_cp {\r
+  enum XML_Content_Type         type;\r
+  enum XML_Content_Quant        quant;\r
+  XML_Char *                    name;\r
+  unsigned int                  numchildren;\r
+  XML_Content *                 children;\r
+};\r
+\r
+\r
+/* This is called for an element declaration. See above for\r
+   description of the model argument. It's the caller's responsibility\r
+   to free model when finished with it.\r
+*/\r
+typedef void (XMLCALL *XML_ElementDeclHandler) (void *userData,\r
+                                                const XML_Char *name,\r
+                                                XML_Content *model);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetElementDeclHandler(XML_Parser parser,\r
+                          XML_ElementDeclHandler eldecl);\r
+\r
+/* The Attlist declaration handler is called for *each* attribute. So\r
+   a single Attlist declaration with multiple attributes declared will\r
+   generate multiple calls to this handler. The "default" parameter\r
+   may be NULL in the case of the "#IMPLIED" or "#REQUIRED"\r
+   keyword. The "isrequired" parameter will be true and the default\r
+   value will be NULL in the case of "#REQUIRED". If "isrequired" is\r
+   true and default is non-NULL, then this is a "#FIXED" default.\r
+*/\r
+typedef void (XMLCALL *XML_AttlistDeclHandler) (\r
+                                    void            *userData,\r
+                                    const XML_Char  *elname,\r
+                                    const XML_Char  *attname,\r
+                                    const XML_Char  *att_type,\r
+                                    const XML_Char  *dflt,\r
+                                    int              isrequired);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetAttlistDeclHandler(XML_Parser parser,\r
+                          XML_AttlistDeclHandler attdecl);\r
+\r
+/* The XML declaration handler is called for *both* XML declarations\r
+   and text declarations. The way to distinguish is that the version\r
+   parameter will be NULL for text declarations. The encoding\r
+   parameter may be NULL for XML declarations. The standalone\r
+   parameter will be -1, 0, or 1 indicating respectively that there\r
+   was no standalone parameter in the declaration, that it was given\r
+   as no, or that it was given as yes.\r
+*/\r
+typedef void (XMLCALL *XML_XmlDeclHandler) (void           *userData,\r
+                                            const XML_Char *version,\r
+                                            const XML_Char *encoding,\r
+                                            int             standalone);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetXmlDeclHandler(XML_Parser parser,\r
+                      XML_XmlDeclHandler xmldecl);\r
+\r
+\r
+typedef struct {\r
+  void *(*malloc_fcn)(size_t size);\r
+  void *(*realloc_fcn)(void *ptr, size_t size);\r
+  void (*free_fcn)(void *ptr);\r
+} XML_Memory_Handling_Suite;\r
+\r
+/* Constructs a new parser; encoding is the encoding specified by the\r
+   external protocol or NULL if there is none specified.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreate(const XML_Char *encoding);\r
+\r
+/* Constructs a new parser and namespace processor.  Element type\r
+   names and attribute names that belong to a namespace will be\r
+   expanded; unprefixed attribute names are never expanded; unprefixed\r
+   element type names are expanded only if there is a default\r
+   namespace. The expanded name is the concatenation of the namespace\r
+   URI, the namespace separator character, and the local part of the\r
+   name.  If the namespace separator is '\0' then the namespace URI\r
+   and the local part will be concatenated without any separator.\r
+   It is a programming error to use the separator '\0' with namespace\r
+   triplets (see XML_SetReturnNSTriplet).\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator);\r
+\r
+\r
+/* Constructs a new parser using the memory management suite referred to\r
+   by memsuite. If memsuite is NULL, then use the standard library memory\r
+   suite. If namespaceSeparator is non-NULL it creates a parser with\r
+   namespace processing as described above. The character pointed at\r
+   will serve as the namespace separator.\r
+\r
+   All further memory operations used for the created parser will come from\r
+   the given suite.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreate_MM(const XML_Char *encoding,\r
+                    const XML_Memory_Handling_Suite *memsuite,\r
+                    const XML_Char *namespaceSeparator);\r
+\r
+/* Prepare a parser object to be re-used.  This is particularly\r
+   valuable when memory allocation overhead is disproportionatly high,\r
+   such as when a large number of small documnents need to be parsed.\r
+   All handlers are cleared from the parser, except for the\r
+   unknownEncodingHandler. The parser's external state is re-initialized\r
+   except for the values of ns and ns_triplets.\r
+\r
+   Added in Expat 1.95.3.\r
+*/\r
+XMLPARSEAPI(XML_Bool)\r
+XML_ParserReset(XML_Parser parser, const XML_Char *encoding);\r
+\r
+/* atts is array of name/value pairs, terminated by 0;\r
+   names and values are 0 terminated.\r
+*/\r
+typedef void (XMLCALL *XML_StartElementHandler) (void *userData,\r
+                                                 const XML_Char *name,\r
+                                                 const XML_Char **atts);\r
+\r
+typedef void (XMLCALL *XML_EndElementHandler) (void *userData,\r
+                                               const XML_Char *name);\r
+\r
+\r
+/* s is not 0 terminated. */\r
+typedef void (XMLCALL *XML_CharacterDataHandler) (void *userData,\r
+                                                  const XML_Char *s,\r
+                                                  int len);\r
+\r
+/* target and data are 0 terminated */\r
+typedef void (XMLCALL *XML_ProcessingInstructionHandler) (\r
+                                                void *userData,\r
+                                                const XML_Char *target,\r
+                                                const XML_Char *data);\r
+\r
+/* data is 0 terminated */\r
+typedef void (XMLCALL *XML_CommentHandler) (void *userData,\r
+                                            const XML_Char *data);\r
+\r
+typedef void (XMLCALL *XML_StartCdataSectionHandler) (void *userData);\r
+typedef void (XMLCALL *XML_EndCdataSectionHandler) (void *userData);\r
+\r
+/* This is called for any characters in the XML document for which\r
+   there is no applicable handler.  This includes both characters that\r
+   are part of markup which is of a kind that is not reported\r
+   (comments, markup declarations), or characters that are part of a\r
+   construct which could be reported but for which no handler has been\r
+   supplied. The characters are passed exactly as they were in the XML\r
+   document except that they will be encoded in UTF-8 or UTF-16.\r
+   Line boundaries are not normalized. Note that a byte order mark\r
+   character is not passed to the default handler. There are no\r
+   guarantees about how characters are divided between calls to the\r
+   default handler: for example, a comment might be split between\r
+   multiple calls.\r
+*/\r
+typedef void (XMLCALL *XML_DefaultHandler) (void *userData,\r
+                                            const XML_Char *s,\r
+                                            int len);\r
+\r
+/* This is called for the start of the DOCTYPE declaration, before\r
+   any DTD or internal subset is parsed.\r
+*/\r
+typedef void (XMLCALL *XML_StartDoctypeDeclHandler) (\r
+                                            void *userData,\r
+                                            const XML_Char *doctypeName,\r
+                                            const XML_Char *sysid,\r
+                                            const XML_Char *pubid,\r
+                                            int has_internal_subset);\r
+\r
+/* This is called for the start of the DOCTYPE declaration when the\r
+   closing > is encountered, but after processing any external\r
+   subset.\r
+*/\r
+typedef void (XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);\r
+\r
+/* This is called for entity declarations. The is_parameter_entity\r
+   argument will be non-zero if the entity is a parameter entity, zero\r
+   otherwise.\r
+\r
+   For internal entities (<!ENTITY foo "bar">), value will\r
+   be non-NULL and systemId, publicID, and notationName will be NULL.\r
+   The value string is NOT nul-terminated; the length is provided in\r
+   the value_length argument. Since it is legal to have zero-length\r
+   values, do not use this argument to test for internal entities.\r
+\r
+   For external entities, value will be NULL and systemId will be\r
+   non-NULL. The publicId argument will be NULL unless a public\r
+   identifier was provided. The notationName argument will have a\r
+   non-NULL value only for unparsed entity declarations.\r
+\r
+   Note that is_parameter_entity can't be changed to XML_Bool, since\r
+   that would break binary compatibility.\r
+*/\r
+typedef void (XMLCALL *XML_EntityDeclHandler) (\r
+                              void *userData,\r
+                              const XML_Char *entityName,\r
+                              int is_parameter_entity,\r
+                              const XML_Char *value,\r
+                              int value_length,\r
+                              const XML_Char *base,\r
+                              const XML_Char *systemId,\r
+                              const XML_Char *publicId,\r
+                              const XML_Char *notationName);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEntityDeclHandler(XML_Parser parser,\r
+                         XML_EntityDeclHandler handler);\r
+\r
+/* OBSOLETE -- OBSOLETE -- OBSOLETE\r
+   This handler has been superceded by the EntityDeclHandler above.\r
+   It is provided here for backward compatibility.\r
+\r
+   This is called for a declaration of an unparsed (NDATA) entity.\r
+   The base argument is whatever was set by XML_SetBase. The\r
+   entityName, systemId and notationName arguments will never be\r
+   NULL. The other arguments may be.\r
+*/\r
+typedef void (XMLCALL *XML_UnparsedEntityDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *entityName,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId,\r
+                                    const XML_Char *notationName);\r
+\r
+/* This is called for a declaration of notation.  The base argument is\r
+   whatever was set by XML_SetBase. The notationName will never be\r
+   NULL.  The other arguments can be.\r
+*/\r
+typedef void (XMLCALL *XML_NotationDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *notationName,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId);\r
+\r
+/* When namespace processing is enabled, these are called once for\r
+   each namespace declaration. The call to the start and end element\r
+   handlers occur between the calls to the start and end namespace\r
+   declaration handlers. For an xmlns attribute, prefix will be\r
+   NULL.  For an xmlns="" attribute, uri will be NULL.\r
+*/\r
+typedef void (XMLCALL *XML_StartNamespaceDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *prefix,\r
+                                    const XML_Char *uri);\r
+\r
+typedef void (XMLCALL *XML_EndNamespaceDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *prefix);\r
+\r
+/* This is called if the document is not standalone, that is, it has an\r
+   external subset or a reference to a parameter entity, but does not\r
+   have standalone="yes". If this handler returns XML_STATUS_ERROR,\r
+   then processing will not continue, and the parser will return a\r
+   XML_ERROR_NOT_STANDALONE error.\r
+   If parameter entity parsing is enabled, then in addition to the\r
+   conditions above this handler will only be called if the referenced\r
+   entity was actually read.\r
+*/\r
+typedef int (XMLCALL *XML_NotStandaloneHandler) (void *userData);\r
+\r
+/* This is called for a reference to an external parsed general\r
+   entity.  The referenced entity is not automatically parsed.  The\r
+   application can parse it immediately or later using\r
+   XML_ExternalEntityParserCreate.\r
+\r
+   The parser argument is the parser parsing the entity containing the\r
+   reference; it can be passed as the parser argument to\r
+   XML_ExternalEntityParserCreate.  The systemId argument is the\r
+   system identifier as specified in the entity declaration; it will\r
+   not be NULL.\r
+\r
+   The base argument is the system identifier that should be used as\r
+   the base for resolving systemId if systemId was relative; this is\r
+   set by XML_SetBase; it may be NULL.\r
+\r
+   The publicId argument is the public identifier as specified in the\r
+   entity declaration, or NULL if none was specified; the whitespace\r
+   in the public identifier will have been normalized as required by\r
+   the XML spec.\r
+\r
+   The context argument specifies the parsing context in the format\r
+   expected by the context argument to XML_ExternalEntityParserCreate;\r
+   context is valid only until the handler returns, so if the\r
+   referenced entity is to be parsed later, it must be copied.\r
+   context is NULL only when the entity is a parameter entity.\r
+\r
+   The handler should return XML_STATUS_ERROR if processing should not\r
+   continue because of a fatal error in the handling of the external\r
+   entity.  In this case the calling parser will return an\r
+   XML_ERROR_EXTERNAL_ENTITY_HANDLING error.\r
+\r
+   Note that unlike other handlers the first argument is the parser,\r
+   not userData.\r
+*/\r
+typedef int (XMLCALL *XML_ExternalEntityRefHandler) (\r
+                                    XML_Parser parser,\r
+                                    const XML_Char *context,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId);\r
+\r
+/* This is called in two situations:\r
+   1) An entity reference is encountered for which no declaration\r
+      has been read *and* this is not an error.\r
+   2) An internal entity reference is read, but not expanded, because\r
+      XML_SetDefaultHandler has been called.\r
+   Note: skipped parameter entities in declarations and skipped general\r
+         entities in attribute values cannot be reported, because\r
+         the event would be out of sync with the reporting of the\r
+         declarations or attribute values\r
+*/\r
+typedef void (XMLCALL *XML_SkippedEntityHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *entityName,\r
+                                    int is_parameter_entity);\r
+\r
+/* This structure is filled in by the XML_UnknownEncodingHandler to\r
+   provide information to the parser about encodings that are unknown\r
+   to the parser.\r
+\r
+   The map[b] member gives information about byte sequences whose\r
+   first byte is b.\r
+\r
+   If map[b] is c where c is >= 0, then b by itself encodes the\r
+   Unicode scalar value c.\r
+\r
+   If map[b] is -1, then the byte sequence is malformed.\r
+\r
+   If map[b] is -n, where n >= 2, then b is the first byte of an\r
+   n-byte sequence that encodes a single Unicode scalar value.\r
+\r
+   The data member will be passed as the first argument to the convert\r
+   function.\r
+\r
+   The convert function is used to convert multibyte sequences; s will\r
+   point to a n-byte sequence where map[(unsigned char)*s] == -n.  The\r
+   convert function must return the Unicode scalar value represented\r
+   by this byte sequence or -1 if the byte sequence is malformed.\r
+\r
+   The convert function may be NULL if the encoding is a single-byte\r
+   encoding, that is if map[b] >= -1 for all bytes b.\r
+\r
+   When the parser is finished with the encoding, then if release is\r
+   not NULL, it will call release passing it the data member; once\r
+   release has been called, the convert function will not be called\r
+   again.\r
+\r
+   Expat places certain restrictions on the encodings that are supported\r
+   using this mechanism.\r
+\r
+   1. Every ASCII character that can appear in a well-formed XML document,\r
+      other than the characters\r
+\r
+      $@\^`{}~\r
+\r
+      must be represented by a single byte, and that byte must be the\r
+      same byte that represents that character in ASCII.\r
+\r
+   2. No character may require more than 4 bytes to encode.\r
+\r
+   3. All characters encoded must have Unicode scalar values <=\r
+      0xFFFF, (i.e., characters that would be encoded by surrogates in\r
+      UTF-16 are  not allowed).  Note that this restriction doesn't\r
+      apply to the built-in support for UTF-8 and UTF-16.\r
+\r
+   4. No Unicode character may be encoded by more than one distinct\r
+      sequence of bytes.\r
+*/\r
+typedef struct {\r
+  int map[256];\r
+  void *data;\r
+  int (XMLCALL *convert)(void *data, const char *s);\r
+  void (XMLCALL *release)(void *data);\r
+} XML_Encoding;\r
+\r
+/* This is called for an encoding that is unknown to the parser.\r
+\r
+   The encodingHandlerData argument is that which was passed as the\r
+   second argument to XML_SetUnknownEncodingHandler.\r
+\r
+   The name argument gives the name of the encoding as specified in\r
+   the encoding declaration.\r
+\r
+   If the callback can provide information about the encoding, it must\r
+   fill in the XML_Encoding structure, and return XML_STATUS_OK.\r
+   Otherwise it must return XML_STATUS_ERROR.\r
+\r
+   If info does not describe a suitable encoding, then the parser will\r
+   return an XML_UNKNOWN_ENCODING error.\r
+*/\r
+typedef int (XMLCALL *XML_UnknownEncodingHandler) (\r
+                                    void *encodingHandlerData,\r
+                                    const XML_Char *name,\r
+                                    XML_Encoding *info);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetElementHandler(XML_Parser parser,\r
+                      XML_StartElementHandler start,\r
+                      XML_EndElementHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartElementHandler(XML_Parser parser,\r
+                           XML_StartElementHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndElementHandler(XML_Parser parser,\r
+                         XML_EndElementHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetCharacterDataHandler(XML_Parser parser,\r
+                            XML_CharacterDataHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetProcessingInstructionHandler(XML_Parser parser,\r
+                                    XML_ProcessingInstructionHandler handler);\r
+XMLPARSEAPI(void)\r
+XML_SetCommentHandler(XML_Parser parser,\r
+                      XML_CommentHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetCdataSectionHandler(XML_Parser parser,\r
+                           XML_StartCdataSectionHandler start,\r
+                           XML_EndCdataSectionHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartCdataSectionHandler(XML_Parser parser,\r
+                                XML_StartCdataSectionHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndCdataSectionHandler(XML_Parser parser,\r
+                              XML_EndCdataSectionHandler end);\r
+\r
+/* This sets the default handler and also inhibits expansion of\r
+   internal entities. These entity references will be passed to the\r
+   default handler, or to the skipped entity handler, if one is set.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetDefaultHandler(XML_Parser parser,\r
+                      XML_DefaultHandler handler);\r
+\r
+/* This sets the default handler but does not inhibit expansion of\r
+   internal entities.  The entity reference will not be passed to the\r
+   default handler.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetDefaultHandlerExpand(XML_Parser parser,\r
+                            XML_DefaultHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetDoctypeDeclHandler(XML_Parser parser,\r
+                          XML_StartDoctypeDeclHandler start,\r
+                          XML_EndDoctypeDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartDoctypeDeclHandler(XML_Parser parser,\r
+                               XML_StartDoctypeDeclHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndDoctypeDeclHandler(XML_Parser parser,\r
+                             XML_EndDoctypeDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetUnparsedEntityDeclHandler(XML_Parser parser,\r
+                                 XML_UnparsedEntityDeclHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNotationDeclHandler(XML_Parser parser,\r
+                           XML_NotationDeclHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNamespaceDeclHandler(XML_Parser parser,\r
+                            XML_StartNamespaceDeclHandler start,\r
+                            XML_EndNamespaceDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartNamespaceDeclHandler(XML_Parser parser,\r
+                                 XML_StartNamespaceDeclHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndNamespaceDeclHandler(XML_Parser parser,\r
+                               XML_EndNamespaceDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNotStandaloneHandler(XML_Parser parser,\r
+                            XML_NotStandaloneHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetExternalEntityRefHandler(XML_Parser parser,\r
+                                XML_ExternalEntityRefHandler handler);\r
+\r
+/* If a non-NULL value for arg is specified here, then it will be\r
+   passed as the first argument to the external entity ref handler\r
+   instead of the parser object.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetExternalEntityRefHandlerArg(XML_Parser parser,\r
+                                   void *arg);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetSkippedEntityHandler(XML_Parser parser,\r
+                            XML_SkippedEntityHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetUnknownEncodingHandler(XML_Parser parser,\r
+                              XML_UnknownEncodingHandler handler,\r
+                              void *encodingHandlerData);\r
+\r
+/* This can be called within a handler for a start element, end\r
+   element, processing instruction or character data.  It causes the\r
+   corresponding markup to be passed to the default handler.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_DefaultCurrent(XML_Parser parser);\r
+\r
+/* If do_nst is non-zero, and namespace processing is in effect, and\r
+   a name has a prefix (i.e. an explicit namespace qualifier) then\r
+   that name is returned as a triplet in a single string separated by\r
+   the separator character specified when the parser was created: URI\r
+   + sep + local_name + sep + prefix.\r
+\r
+   If do_nst is zero, then namespace information is returned in the\r
+   default manner (URI + sep + local_name) whether or not the name\r
+   has a prefix.\r
+\r
+   Note: Calling XML_SetReturnNSTriplet after XML_Parse or\r
+     XML_ParseBuffer has no effect.\r
+*/\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetReturnNSTriplet(XML_Parser parser, int do_nst);\r
+\r
+/* This value is passed as the userData argument to callbacks. */\r
+XMLPARSEAPI(void)\r
+XML_SetUserData(XML_Parser parser, void *userData);\r
+\r
+/* Returns the last value set by XML_SetUserData or NULL. */\r
+#define XML_GetUserData(parser) (*(void **)(parser))\r
+\r
+/* This is equivalent to supplying an encoding argument to\r
+   XML_ParserCreate. On success XML_SetEncoding returns non-zero,\r
+   zero otherwise.\r
+   Note: Calling XML_SetEncoding after XML_Parse or XML_ParseBuffer\r
+     has no effect and returns XML_STATUS_ERROR.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_SetEncoding(XML_Parser parser, const XML_Char *encoding);\r
+\r
+/* If this function is called, then the parser will be passed as the\r
+   first argument to callbacks instead of userData.  The userData will\r
+   still be accessible using XML_GetUserData.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_UseParserAsHandlerArg(XML_Parser parser);\r
+\r
+/* If useDTD == XML_TRUE is passed to this function, then the parser\r
+   will assume that there is an external subset, even if none is\r
+   specified in the document. In such a case the parser will call the\r
+   externalEntityRefHandler with a value of NULL for the systemId\r
+   argument (the publicId and context arguments will be NULL as well).\r
+   Note: For the purpose of checking WFC: Entity Declared, passing\r
+     useDTD == XML_TRUE will make the parser behave as if the document\r
+     had a DTD with an external subset.\r
+   Note: If this function is called, then this must be done before\r
+     the first call to XML_Parse or XML_ParseBuffer, since it will\r
+     have no effect after that.  Returns\r
+     XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING.\r
+   Note: If the document does not have a DOCTYPE declaration at all,\r
+     then startDoctypeDeclHandler and endDoctypeDeclHandler will not\r
+     be called, despite an external subset being parsed.\r
+   Note: If XML_DTD is not defined when Expat is compiled, returns\r
+     XML_ERROR_FEATURE_REQUIRES_XML_DTD.\r
+*/\r
+XMLPARSEAPI(enum XML_Error)\r
+XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);\r
+\r
+\r
+/* Sets the base to be used for resolving relative URIs in system\r
+   identifiers in declarations.  Resolving relative identifiers is\r
+   left to the application: this value will be passed through as the\r
+   base argument to the XML_ExternalEntityRefHandler,\r
+   XML_NotationDeclHandler and XML_UnparsedEntityDeclHandler. The base\r
+   argument will be copied.  Returns XML_STATUS_ERROR if out of memory,\r
+   XML_STATUS_OK otherwise.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_SetBase(XML_Parser parser, const XML_Char *base);\r
+\r
+XMLPARSEAPI(const XML_Char *)\r
+XML_GetBase(XML_Parser parser);\r
+\r
+/* Returns the number of the attribute/value pairs passed in last call\r
+   to the XML_StartElementHandler that were specified in the start-tag\r
+   rather than defaulted. Each attribute/value pair counts as 2; thus\r
+   this correspondds to an index into the atts array passed to the\r
+   XML_StartElementHandler.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetSpecifiedAttributeCount(XML_Parser parser);\r
+\r
+/* Returns the index of the ID attribute passed in the last call to\r
+   XML_StartElementHandler, or -1 if there is no ID attribute.  Each\r
+   attribute/value pair counts as 2; thus this correspondds to an\r
+   index into the atts array passed to the XML_StartElementHandler.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetIdAttributeIndex(XML_Parser parser);\r
+\r
+/* Parses some input. Returns XML_STATUS_ERROR if a fatal error is\r
+   detected.  The last call to XML_Parse must have isFinal true; len\r
+   may be zero for this call (or any other).\r
+\r
+   Though the return values for these functions has always been\r
+   described as a Boolean value, the implementation, at least for the\r
+   1.95.x series, has always returned exactly one of the XML_Status\r
+   values.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_Parse(XML_Parser parser, const char *s, int len, int isFinal);\r
+\r
+XMLPARSEAPI(void *)\r
+XML_GetBuffer(XML_Parser parser, int len);\r
+\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_ParseBuffer(XML_Parser parser, int len, int isFinal);\r
+\r
+/* Stops parsing, causing XML_Parse() or XML_ParseBuffer() to return.\r
+   Must be called from within a call-back handler, except when aborting\r
+   (resumable = 0) an already suspended parser. Some call-backs may\r
+   still follow because they would otherwise get lost. Examples:\r
+   - endElementHandler() for empty elements when stopped in\r
+     startElementHandler(), \r
+   - endNameSpaceDeclHandler() when stopped in endElementHandler(), \r
+   and possibly others.\r
+\r
+   Can be called from most handlers, including DTD related call-backs,\r
+   except when parsing an external parameter entity and resumable != 0.\r
+   Returns XML_STATUS_OK when successful, XML_STATUS_ERROR otherwise.\r
+   Possible error codes: \r
+   - XML_ERROR_SUSPENDED: when suspending an already suspended parser.\r
+   - XML_ERROR_FINISHED: when the parser has already finished.\r
+   - XML_ERROR_SUSPEND_PE: when suspending while parsing an external PE.\r
+\r
+   When resumable != 0 (true) then parsing is suspended, that is, \r
+   XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED. \r
+   Otherwise, parsing is aborted, that is, XML_Parse() and XML_ParseBuffer()\r
+   return XML_STATUS_ERROR with error code XML_ERROR_ABORTED.\r
+\r
+   *Note*:\r
+   This will be applied to the current parser instance only, that is, if\r
+   there is a parent parser then it will continue parsing when the\r
+   externalEntityRefHandler() returns. It is up to the implementation of\r
+   the externalEntityRefHandler() to call XML_StopParser() on the parent\r
+   parser (recursively), if one wants to stop parsing altogether.\r
+\r
+   When suspended, parsing can be resumed by calling XML_ResumeParser(). \r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_StopParser(XML_Parser parser, XML_Bool resumable);\r
+\r
+/* Resumes parsing after it has been suspended with XML_StopParser().\r
+   Must not be called from within a handler call-back. Returns same\r
+   status codes as XML_Parse() or XML_ParseBuffer().\r
+   Additional error code XML_ERROR_NOT_SUSPENDED possible.   \r
+\r
+   *Note*:\r
+   This must be called on the most deeply nested child parser instance\r
+   first, and on its parent parser only after the child parser has finished,\r
+   to be applied recursively until the document entity's parser is restarted.\r
+   That is, the parent parser will not resume by itself and it is up to the\r
+   application to call XML_ResumeParser() on it at the appropriate moment.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_ResumeParser(XML_Parser parser);\r
+\r
+enum XML_Parsing {\r
+  XML_INITIALIZED,\r
+  XML_PARSING,\r
+  XML_FINISHED,\r
+  XML_SUSPENDED\r
+};\r
+\r
+typedef struct {\r
+  enum XML_Parsing parsing;\r
+  XML_Bool finalBuffer;\r
+} XML_ParsingStatus;\r
+\r
+/* Returns status of parser with respect to being initialized, parsing,\r
+   finished, or suspended and processing the final buffer.\r
+   XXX XML_Parse() and XML_ParseBuffer() should return XML_ParsingStatus,\r
+   XXX with XML_FINISHED_OK or XML_FINISHED_ERROR replacing XML_FINISHED\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status);\r
+\r
+/* Creates an XML_Parser object that can parse an external general\r
+   entity; context is a '\0'-terminated string specifying the parse\r
+   context; encoding is a '\0'-terminated string giving the name of\r
+   the externally specified encoding, or NULL if there is no\r
+   externally specified encoding.  The context string consists of a\r
+   sequence of tokens separated by formfeeds (\f); a token consisting\r
+   of a name specifies that the general entity of the name is open; a\r
+   token of the form prefix=uri specifies the namespace for a\r
+   particular prefix; a token of the form =uri specifies the default\r
+   namespace.  This can be called at any point after the first call to\r
+   an ExternalEntityRefHandler so longer as the parser has not yet\r
+   been freed.  The new parser is completely independent and may\r
+   safely be used in a separate thread.  The handlers and userData are\r
+   initialized from the parser argument.  Returns NULL if out of memory.\r
+   Otherwise returns a new XML_Parser object.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ExternalEntityParserCreate(XML_Parser parser,\r
+                               const XML_Char *context,\r
+                               const XML_Char *encoding);\r
+\r
+enum XML_ParamEntityParsing {\r
+  XML_PARAM_ENTITY_PARSING_NEVER,\r
+  XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE,\r
+  XML_PARAM_ENTITY_PARSING_ALWAYS\r
+};\r
+\r
+/* Controls parsing of parameter entities (including the external DTD\r
+   subset). If parsing of parameter entities is enabled, then\r
+   references to external parameter entities (including the external\r
+   DTD subset) will be passed to the handler set with\r
+   XML_SetExternalEntityRefHandler.  The context passed will be 0.\r
+\r
+   Unlike external general entities, external parameter entities can\r
+   only be parsed synchronously.  If the external parameter entity is\r
+   to be parsed, it must be parsed during the call to the external\r
+   entity ref handler: the complete sequence of\r
+   XML_ExternalEntityParserCreate, XML_Parse/XML_ParseBuffer and\r
+   XML_ParserFree calls must be made during this call.  After\r
+   XML_ExternalEntityParserCreate has been called to create the parser\r
+   for the external parameter entity (context must be 0 for this\r
+   call), it is illegal to make any calls on the old parser until\r
+   XML_ParserFree has been called on the newly created parser.\r
+   If the library has been compiled without support for parameter\r
+   entity parsing (ie without XML_DTD being defined), then\r
+   XML_SetParamEntityParsing will return 0 if parsing of parameter\r
+   entities is requested; otherwise it will return non-zero.\r
+   Note: If XML_SetParamEntityParsing is called after XML_Parse or\r
+      XML_ParseBuffer, then it has no effect and will always return 0.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_SetParamEntityParsing(XML_Parser parser,\r
+                          enum XML_ParamEntityParsing parsing);\r
+\r
+/* If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then\r
+   XML_GetErrorCode returns information about the error.\r
+*/\r
+XMLPARSEAPI(enum XML_Error)\r
+XML_GetErrorCode(XML_Parser parser);\r
+\r
+/* These functions return information about the current parse\r
+   location.  They may be called from any callback called to report\r
+   some parse event; in this case the location is the location of the\r
+   first of the sequence of characters that generated the event.  When\r
+   called from callbacks generated by declarations in the document\r
+   prologue, the location identified isn't as neatly defined, but will\r
+   be within the relevant markup.  When called outside of the callback\r
+   functions, the position indicated will be just past the last parse\r
+   event (regardless of whether there was an associated callback).\r
+   \r
+   They may also be called after returning from a call to XML_Parse\r
+   or XML_ParseBuffer.  If the return value is XML_STATUS_ERROR then\r
+   the location is the location of the character at which the error\r
+   was detected; otherwise the location is the location of the last\r
+   parse event, as described above.\r
+*/\r
+XMLPARSEAPI(XML_Size) XML_GetCurrentLineNumber(XML_Parser parser);\r
+XMLPARSEAPI(XML_Size) XML_GetCurrentColumnNumber(XML_Parser parser);\r
+XMLPARSEAPI(XML_Index) XML_GetCurrentByteIndex(XML_Parser parser);\r
+\r
+/* Return the number of bytes in the current event.\r
+   Returns 0 if the event is in an internal entity.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetCurrentByteCount(XML_Parser parser);\r
+\r
+/* If XML_CONTEXT_BYTES is defined, returns the input buffer, sets\r
+   the integer pointed to by offset to the offset within this buffer\r
+   of the current parse position, and sets the integer pointed to by size\r
+   to the size of this buffer (the number of input bytes). Otherwise\r
+   returns a NULL pointer. Also returns a NULL pointer if a parse isn't\r
+   active.\r
+\r
+   NOTE: The character pointer returned should not be used outside\r
+   the handler that makes the call.\r
+*/\r
+XMLPARSEAPI(const char *)\r
+XML_GetInputContext(XML_Parser parser,\r
+                    int *offset,\r
+                    int *size);\r
+\r
+/* For backwards compatibility with previous versions. */\r
+#define XML_GetErrorLineNumber   XML_GetCurrentLineNumber\r
+#define XML_GetErrorColumnNumber XML_GetCurrentColumnNumber\r
+#define XML_GetErrorByteIndex    XML_GetCurrentByteIndex\r
+\r
+/* Frees the content model passed to the element declaration handler */\r
+XMLPARSEAPI(void)\r
+XML_FreeContentModel(XML_Parser parser, XML_Content *model);\r
+\r
+/* Exposing the memory handling functions used in Expat */\r
+XMLPARSEAPI(void *)\r
+XML_MemMalloc(XML_Parser parser, size_t size);\r
+\r
+XMLPARSEAPI(void *)\r
+XML_MemRealloc(XML_Parser parser, void *ptr, size_t size);\r
+\r
+XMLPARSEAPI(void)\r
+XML_MemFree(XML_Parser parser, void *ptr);\r
+\r
+/* Frees memory used by the parser. */\r
+XMLPARSEAPI(void)\r
+XML_ParserFree(XML_Parser parser);\r
+\r
+/* Returns a string describing the error. */\r
+XMLPARSEAPI(const XML_LChar *)\r
+XML_ErrorString(enum XML_Error code);\r
+\r
+/* Return a string containing the version number of this expat */\r
+XMLPARSEAPI(const XML_LChar *)\r
+XML_ExpatVersion(void);\r
+\r
+typedef struct {\r
+  int major;\r
+  int minor;\r
+  int micro;\r
+} XML_Expat_Version;\r
+\r
+/* Return an XML_Expat_Version structure containing numeric version\r
+   number information for this version of expat.\r
+*/\r
+XMLPARSEAPI(XML_Expat_Version)\r
+XML_ExpatVersionInfo(void);\r
+\r
+/* Added in Expat 1.95.5. */\r
+enum XML_FeatureEnum {\r
+  XML_FEATURE_END = 0,\r
+  XML_FEATURE_UNICODE,\r
+  XML_FEATURE_UNICODE_WCHAR_T,\r
+  XML_FEATURE_DTD,\r
+  XML_FEATURE_CONTEXT_BYTES,\r
+  XML_FEATURE_MIN_SIZE,\r
+  XML_FEATURE_SIZEOF_XML_CHAR,\r
+  XML_FEATURE_SIZEOF_XML_LCHAR,\r
+  XML_FEATURE_NS,\r
+  XML_FEATURE_LARGE_SIZE\r
+  /* Additional features must be added to the end of this enum. */\r
+};\r
+\r
+typedef struct {\r
+  enum XML_FeatureEnum  feature;\r
+  const XML_LChar       *name;\r
+  long int              value;\r
+} XML_Feature;\r
+\r
+XMLPARSEAPI(const XML_Feature *)\r
+XML_GetFeatureList(void);\r
+\r
+\r
+/* Expat follows the GNU/Linux convention of odd number minor version for\r
+   beta/development releases and even number minor version for stable\r
+   releases. Micro is bumped with each release, and set to 0 with each\r
+   change to major or minor version.\r
+*/\r
+#define XML_MAJOR_VERSION 2\r
+#define XML_MINOR_VERSION 0\r
+#define XML_MICRO_VERSION 1\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* not Expat_INCLUDED */\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/expat_external.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/expat_external.h
new file mode 100644 (file)
index 0000000..bb83a99
--- /dev/null
@@ -0,0 +1,115 @@
+/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+   See the file COPYING for copying permission.\r
+*/\r
+\r
+#ifndef Expat_External_INCLUDED\r
+#define Expat_External_INCLUDED 1\r
+\r
+/* External API definitions */\r
+\r
+#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)\r
+#define XML_USE_MSC_EXTENSIONS 1\r
+#endif\r
+\r
+/* Expat tries very hard to make the API boundary very specifically\r
+   defined.  There are two macros defined to control this boundary;\r
+   each of these can be defined before including this header to\r
+   achieve some different behavior, but doing so it not recommended or\r
+   tested frequently.\r
+\r
+   XMLCALL    - The calling convention to use for all calls across the\r
+                "library boundary."  This will default to cdecl, and\r
+                try really hard to tell the compiler that's what we\r
+                want.\r
+\r
+   XMLIMPORT  - Whatever magic is needed to note that a function is\r
+                to be imported from a dynamically loaded library\r
+                (.dll, .so, or .sl, depending on your platform).\r
+\r
+   The XMLCALL macro was added in Expat 1.95.7.  The only one which is\r
+   expected to be directly useful in client code is XMLCALL.\r
+\r
+   Note that on at least some Unix versions, the Expat library must be\r
+   compiled with the cdecl calling convention as the default since\r
+   system headers may assume the cdecl convention.\r
+*/\r
+#ifndef XMLCALL\r
+#if defined(_MSC_VER)\r
+#define XMLCALL __cdecl\r
+#elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)\r
+#define XMLCALL __attribute__((cdecl))\r
+#else\r
+/* For any platform which uses this definition and supports more than\r
+   one calling convention, we need to extend this definition to\r
+   declare the convention used on that platform, if it's possible to\r
+   do so.\r
+\r
+   If this is the case for your platform, please file a bug report\r
+   with information on how to identify your platform via the C\r
+   pre-processor and how to specify the same calling convention as the\r
+   platform's malloc() implementation.\r
+*/\r
+#define XMLCALL\r
+#endif\r
+#endif  /* not defined XMLCALL */\r
+\r
+\r
+#if !defined(XML_STATIC) && !defined(XMLIMPORT)\r
+#ifndef XML_BUILDING_EXPAT\r
+/* using Expat from an application */\r
+\r
+#ifdef XML_USE_MSC_EXTENSIONS\r
+#define XMLIMPORT __declspec(dllimport)\r
+#endif\r
+\r
+#endif\r
+#endif  /* not defined XML_STATIC */\r
+\r
+\r
+/* If we didn't define it above, define it away: */\r
+#ifndef XMLIMPORT\r
+#define XMLIMPORT\r
+#endif\r
+\r
+\r
+#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#ifdef XML_UNICODE_WCHAR_T\r
+#define XML_UNICODE\r
+#endif\r
+\r
+#ifdef XML_UNICODE     /* Information is UTF-16 encoded. */\r
+#ifdef XML_UNICODE_WCHAR_T\r
+typedef wchar_t XML_Char;\r
+typedef wchar_t XML_LChar;\r
+#else\r
+typedef unsigned short XML_Char;\r
+typedef char XML_LChar;\r
+#endif /* XML_UNICODE_WCHAR_T */\r
+#else                  /* Information is UTF-8 encoded. */\r
+typedef char XML_Char;\r
+typedef char XML_LChar;\r
+#endif /* XML_UNICODE */\r
+\r
+#ifdef XML_LARGE_SIZE  /* Use large integers for file/stream positions. */\r
+#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400\r
+typedef __int64 XML_Index; \r
+typedef unsigned __int64 XML_Size;\r
+#else\r
+typedef long long XML_Index;\r
+typedef unsigned long long XML_Size;\r
+#endif\r
+#else\r
+typedef long XML_Index;\r
+typedef unsigned long XML_Size;\r
+#endif /* XML_LARGE_SIZE */\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* not Expat_External_INCLUDED */\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/libexpatMT.lib b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/libexpatMT.lib
new file mode 100644 (file)
index 0000000..2436f61
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/libexpatMT.lib differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/sim_support.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/sim_support.c
new file mode 100644 (file)
index 0000000..32b5439
--- /dev/null
@@ -0,0 +1,476 @@
+/* ------------------------------------------------------------------------- \r
+ * sim_support.c\r
+ * Functions used by both FMU simulators fmusim_me and fmusim_cs\r
+ * to parse command-line arguments, to unzip and load an fmu, \r
+ * to write CSV file, and more.\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+\r
+#ifdef FMI_COSIMULATION\r
+#include "fmi_cs.h"\r
+#else\r
+#include "fmi_me.h"\r
+#endif\r
+\r
+#include "sim_support.h"\r
+\r
+extern FMU fmu;\r
+\r
+int unzip(const char *zipPath, const char *outPath) {\r
+    int code;\r
+    char cwd[BUFSIZE];\r
+    char binPath[BUFSIZE];\r
+    int n = strlen(UNZIP_CMD) + strlen(outPath) + 1 +  strlen(zipPath) + 9;\r
+    char* cmd = (char*)calloc(sizeof(char), n);\r
+\r
+    // remember current directory\r
+    if (!GetCurrentDirectory(BUFSIZE, cwd)) {\r
+        printf ("error: Could not get current directory\n");\r
+        return 0; // error\r
+    }\r
+        \r
+    // change to %FMUSDK_HOME%\bin to find 7z.dll and 7z.exe\r
+    if (!GetEnvironmentVariable("FMUSDK_HOME", binPath, BUFSIZE)) {\r
+        if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {\r
+            printf ("error: Environment variable FMUSDK_HOME not defined\n");\r
+        }\r
+        else {\r
+            printf ("error: Could not get value of FMUSDK_HOME\n");\r
+        }\r
+        return 0; // error       \r
+    }\r
+    strcat(binPath, "\\bin");\r
+    if (!SetCurrentDirectory(binPath)) {\r
+        printf ("error: could not change to directory '%s'\n", binPath); \r
+        return 0; // error        \r
+    }\r
+   \r
+    // run the unzip command\r
+    // remove "> NUL" to see the unzip protocol\r
+    sprintf(cmd, "%s%s \"%s\" > NUL", UNZIP_CMD, outPath, zipPath); \r
+    // printf("cmd='%s'\n", cmd);\r
+    code = system(cmd);\r
+    free(cmd);\r
+    if (code!=SEVEN_ZIP_NO_ERROR) {\r
+        switch (code) {\r
+            printf("7z: ");\r
+            case SEVEN_ZIP_WARNING:            printf("warning\n"); break;\r
+            case SEVEN_ZIP_ERROR:              printf("error\n"); break;\r
+            case SEVEN_ZIP_COMMAND_LINE_ERROR: printf("command line error\n"); break;\r
+            case SEVEN_ZIP_OUT_OF_MEMORY:      printf("out of memory\n"); break;\r
+            case SEVEN_ZIP_STOPPED_BY_USER:    printf("stopped by user\n"); break;\r
+            default: printf("unknown problem\n");\r
+        }\r
+    }\r
+    \r
+    // restore current directory\r
+    SetCurrentDirectory(cwd);\r
+    \r
+    return (code==SEVEN_ZIP_NO_ERROR || code==SEVEN_ZIP_WARNING) ? 1 : 0;  \r
+}\r
+\r
+// fileName is an absolute path, e.g. C:\test\a.fmu\r
+// or relative to the current dir, e.g. ..\test\a.fmu\r
+// Does not check for existence of the file\r
+static char* getFmuPath(const char* fileName){\r
+    char pathName[MAX_PATH];\r
+    int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL);\r
+    return n ? strdup(pathName) : NULL;\r
+}\r
+\r
+static char* getTmpPath() {\r
+    char tmpPath[BUFSIZE];\r
+    if(! GetTempPath(BUFSIZE, tmpPath)) {\r
+        printf ("error: Could not find temporary disk space\n");\r
+        return NULL;\r
+    }\r
+    strcat(tmpPath, "fmu\\");\r
+    return strdup(tmpPath);\r
+}\r
+\r
+static void* getAdr(int* s, FMU *fmu, const char* functionName){\r
+    char name[BUFSIZE];\r
+    void* fp;\r
+    sprintf(name, "%s_%s", getModelIdentifier(fmu->modelDescription), functionName);\r
+    fp = GetProcAddress(fmu->dllHandle, name);\r
+    if (!fp) {\r
+        printf ("warning: Function %s not found in dll\n", name);\r
+        *s = 0; // mark dll load as 'failed'        \r
+    }\r
+    return fp;\r
+}\r
+\r
+// Load the given dll and set function pointers in fmu\r
+// Return 0 to indicate failure\r
+static int loadDll(const char* dllPath, FMU *fmu) {\r
+    int x = 1, s = 1;\r
+    HANDLE h = LoadLibrary(dllPath);\r
+    if (!h) {\r
+        printf("error: Could not load %s\n", dllPath);\r
+        return 0; // failure\r
+    }\r
+    fmu->dllHandle = h;\r
+\r
+#ifdef FMI_COSIMULATION   \r
+    fmu->getTypesPlatform        = (fGetTypesPlatform)   getAdr(&s, fmu, "fmiGetTypesPlatform");\r
+    if (s==0) { \r
+        s = 1; // work around bug for FMUs exported using Dymola 2012 and SimulationX 3.x\r
+        fmu->getTypesPlatform    = (fGetTypesPlatform)   getAdr(&s, fmu, "fmiGetModelTypesPlatform");\r
+        if (s==1) printf("  using fmiGetModelTypesPlatform instead\n", dllPath);\r
+    }\r
+    fmu->instantiateSlave        = (fInstantiateSlave)   getAdr(&s, fmu, "fmiInstantiateSlave");\r
+    fmu->initializeSlave         = (fInitializeSlave)    getAdr(&s, fmu, "fmiInitializeSlave");    \r
+    fmu->terminateSlave          = (fTerminateSlave)     getAdr(&s, fmu, "fmiTerminateSlave");\r
+    fmu->resetSlave              = (fResetSlave)         getAdr(&s, fmu, "fmiResetSlave");\r
+    fmu->freeSlaveInstance       = (fFreeSlaveInstance)  getAdr(&s, fmu, "fmiFreeSlaveInstance");\r
+    fmu->setRealInputDerivatives = (fSetRealInputDerivatives) getAdr(&s, fmu, "fmiSetRealInputDerivatives");\r
+    fmu->getRealOutputDerivatives = (fGetRealOutputDerivatives) getAdr(&s, fmu, "fmiGetRealOutputDerivatives");\r
+    fmu->cancelStep              = (fCancelStep)         getAdr(&s, fmu, "fmiCancelStep");\r
+    fmu->doStep                  = (fDoStep)             getAdr(&s, fmu, "fmiDoStep");\r
+    // SimulationX 3.4 and 3.5 do not yet export getStatus and getXStatus: do not count this as failure here\r
+    fmu->getStatus               = (fGetStatus)          getAdr(&x, fmu, "fmiGetStatus");\r
+    fmu->getRealStatus           = (fGetRealStatus)      getAdr(&x, fmu, "fmiGetRealStatus");\r
+    fmu->getIntegerStatus        = (fGetIntegerStatus)   getAdr(&x, fmu, "fmiGetIntegerStatus");\r
+    fmu->getBooleanStatus        = (fGetBooleanStatus)   getAdr(&x, fmu, "fmiGetBooleanStatus");\r
+    fmu->getStringStatus         = (fGetStringStatus)    getAdr(&x, fmu, "fmiGetStringStatus");    \r
+\r
+#else // FMI for Model Exchange 1.0\r
+    fmu->getModelTypesPlatform   = (fGetModelTypesPlatform) getAdr(&s, fmu, "fmiGetModelTypesPlatform");\r
+    fmu->instantiateModel        = (fInstantiateModel)   getAdr(&s, fmu, "fmiInstantiateModel");\r
+    fmu->freeModelInstance       = (fFreeModelInstance)  getAdr(&s, fmu, "fmiFreeModelInstance");\r
+    fmu->setTime                 = (fSetTime)            getAdr(&s, fmu, "fmiSetTime");\r
+    fmu->setContinuousStates     = (fSetContinuousStates)getAdr(&s, fmu, "fmiSetContinuousStates");\r
+    fmu->completedIntegratorStep = (fCompletedIntegratorStep)getAdr(&s, fmu, "fmiCompletedIntegratorStep");\r
+    fmu->initialize              = (fInitialize)         getAdr(&s, fmu, "fmiInitialize");\r
+    fmu->getDerivatives          = (fGetDerivatives)     getAdr(&s, fmu, "fmiGetDerivatives");\r
+    fmu->getEventIndicators      = (fGetEventIndicators) getAdr(&s, fmu, "fmiGetEventIndicators");\r
+    fmu->eventUpdate             = (fEventUpdate)        getAdr(&s, fmu, "fmiEventUpdate");\r
+    fmu->getContinuousStates     = (fGetContinuousStates)getAdr(&s, fmu, "fmiGetContinuousStates");\r
+    fmu->getNominalContinuousStates = (fGetNominalContinuousStates)getAdr(&s, fmu, "fmiGetNominalContinuousStates");\r
+    fmu->getStateValueReferences = (fGetStateValueReferences)getAdr(&s, fmu, "fmiGetStateValueReferences");\r
+    fmu->terminate               = (fTerminate)          getAdr(&s, fmu, "fmiTerminate");\r
+#endif \r
+    fmu->getVersion              = (fGetVersion)         getAdr(&s, fmu, "fmiGetVersion");\r
+    fmu->setDebugLogging         = (fSetDebugLogging)    getAdr(&s, fmu, "fmiSetDebugLogging");\r
+    fmu->setReal                 = (fSetReal)            getAdr(&s, fmu, "fmiSetReal");\r
+    fmu->setInteger              = (fSetInteger)         getAdr(&s, fmu, "fmiSetInteger");\r
+    fmu->setBoolean              = (fSetBoolean)         getAdr(&s, fmu, "fmiSetBoolean");\r
+    fmu->setString               = (fSetString)          getAdr(&s, fmu, "fmiSetString");\r
+    fmu->getReal                 = (fGetReal)            getAdr(&s, fmu, "fmiGetReal");\r
+    fmu->getInteger              = (fGetInteger)         getAdr(&s, fmu, "fmiGetInteger");\r
+    fmu->getBoolean              = (fGetBoolean)         getAdr(&s, fmu, "fmiGetBoolean");\r
+    fmu->getString               = (fGetString)          getAdr(&s, fmu, "fmiGetString");\r
+    return s; \r
+}\r
+\r
+static void printModelDescription(ModelDescription* md){\r
+    Element* e = (Element*)md;  \r
+    int i;\r
+    printf("%s\n", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf("  %s=%s\n", e->attributes[i], e->attributes[i+1]);\r
+#ifdef FMI_COSIMULATION   \r
+    if (!md->cosimulation) {\r
+        printf("error: No Implementation element found in model description. This FMU is not for Co-Simulation.\n");\r
+        exit(EXIT_FAILURE);\r
+    }\r
+    e = md->cosimulation->capabilities;\r
+    printf("%s\n", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf("  %s=%s\n", e->attributes[i], e->attributes[i+1]);\r
+#endif // FMI_COSIMULATION  \r
+}\r
+\r
+void loadFMU(const char* fmuFileName) {\r
+    char* fmuPath;\r
+    char* tmpPath;\r
+    char* xmlPath;\r
+    char* dllPath;\r
+    \r
+    // get absolute path to FMU, NULL if not found\r
+    fmuPath = getFmuPath(fmuFileName);\r
+    if (!fmuPath) exit(EXIT_FAILURE);\r
+\r
+    // unzip the FMU to the tmpPath directory\r
+    tmpPath = getTmpPath();\r
+    if (!unzip(fmuPath, tmpPath)) exit(EXIT_FAILURE);\r
+\r
+    // parse tmpPath\modelDescription.xml\r
+    xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1);\r
+    sprintf(xmlPath, "%s%s", tmpPath, XML_FILE);\r
+    fmu.modelDescription = parse(xmlPath);\r
+    free(xmlPath);\r
+    if (!fmu.modelDescription) exit(EXIT_FAILURE);\r
+    printModelDescription(fmu.modelDescription);\r
+\r
+    // load the FMU dll\r
+    dllPath = calloc(sizeof(char), strlen(tmpPath) + strlen(DLL_DIR) \r
+            + strlen( getModelIdentifier(fmu.modelDescription)) +  strlen(".dll") + 1);\r
+    sprintf(dllPath,"%s%s%s.dll", tmpPath, DLL_DIR, getModelIdentifier(fmu.modelDescription));\r
+    if (!loadDll(dllPath, &fmu)) exit(EXIT_FAILURE); \r
+    free(dllPath);\r
+    free(fmuPath);\r
+    free(tmpPath);\r
+}\r
+\r
+static void doubleToCommaString(char* buffer, double r){\r
+    char* comma;\r
+    sprintf(buffer, "%.16g", r);\r
+    comma = strchr(buffer, '.');\r
+    if (comma) *comma = ',';\r
+}\r
+\r
+// output time and all non-alias variables in CSV format\r
+// if separator is ',', columns are separated by ',' and '.' is used for floating-point numbers.\r
+// otherwise, the given separator (e.g. ';' or '\t') is to separate columns, and ',' is used \r
+// as decimal dot in floating-point numbers.\r
+void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, boolean header) {\r
+    int k;\r
+    fmiReal r;\r
+    fmiInteger i;\r
+    fmiBoolean b;\r
+    fmiString s;\r
+    fmiValueReference vr;\r
+    ScalarVariable** vars = fmu->modelDescription->modelVariables;\r
+    char buffer[32];\r
+    \r
+    // print first column\r
+    if (header) \r
+        fprintf(file, "time"); \r
+    else {\r
+        if (separator==',') \r
+            fprintf(file, "%.16g", time);\r
+        else {\r
+            // separator is e.g. ';' or '\t'\r
+            doubleToCommaString(buffer, time);\r
+            fprintf(file, "%s", buffer);       \r
+        }\r
+    }\r
+    \r
+    // print all other columns\r
+    for (k=0; vars[k]; k++) {\r
+        ScalarVariable* sv = vars[k];\r
+        if (getAlias(sv)!=enu_noAlias) continue;\r
+        if (header) {\r
+            // output names only\r
+            if (separator==',') {\r
+                // treat array element, e.g. print a[1, 2] as a[1.2]\r
+                char* s = getName(sv);\r
+                fprintf(file, "%c", separator);\r
+                while (*s) {\r
+                   if (*s!=' ') fprintf(file, "%c", *s==',' ? '.' : *s);\r
+                   s++;\r
+                }\r
+             }\r
+            else\r
+                fprintf(file, "%c%s", separator, getName(sv));\r
+        }\r
+        else {\r
+            // output values\r
+            vr = getValueReference(sv);\r
+            switch (sv->typeSpec->type){\r
+                case elm_Real:\r
+                    fmu->getReal(c, &vr, 1, &r);\r
+                    if (separator==',') \r
+                        fprintf(file, ",%.16g", r);\r
+                    else {\r
+                        // separator is e.g. ';' or '\t'\r
+                        doubleToCommaString(buffer, r);\r
+                        fprintf(file, "%c%s", separator, buffer);       \r
+                    }\r
+                    break;\r
+                case elm_Integer:\r
+                case elm_Enumeration:\r
+                    fmu->getInteger(c, &vr, 1, &i);\r
+                    fprintf(file, "%c%d", separator, i);\r
+                    break;\r
+                case elm_Boolean:\r
+                    fmu->getBoolean(c, &vr, 1, &b);\r
+                    fprintf(file, "%c%d", separator, b);\r
+                    break;\r
+                case elm_String:\r
+                    fmu->getString(c, &vr, 1, &s);\r
+                    fprintf(file, "%c%s", separator, s);\r
+                    break;\r
+                default: \r
+                    fprintf(file, "%cNoValueForType=%d", separator,sv->typeSpec->type);\r
+            }\r
+        }\r
+    } // for\r
+    \r
+    // terminate this row\r
+    fprintf(file, "\n"); \r
+}\r
+\r
+static const char* fmiStatusToString(fmiStatus status){\r
+    switch (status){\r
+        case fmiOK:      return "ok";\r
+        case fmiWarning: return "warning";\r
+        case fmiDiscard: return "discard";\r
+        case fmiError:   return "error";\r
+        case fmiFatal:   return "fatal";\r
+#ifdef FMI_COSIMULATION\r
+        case fmiPending: return "fmiPending";\r
+#endif\r
+        default:         return "?";\r
+    }\r
+}\r
+\r
+// search a fmu for the given variable\r
+// return NULL if not found or vr = fmiUndefinedValueReference\r
+static ScalarVariable* getSV(FMU* fmu, char type, fmiValueReference vr) {\r
+    int i;\r
+    Elm tp;\r
+    ScalarVariable** vars = fmu->modelDescription->modelVariables;\r
+    if (vr==fmiUndefinedValueReference) return NULL;\r
+    switch (type) {\r
+        case 'r': tp = elm_Real;    break;\r
+        case 'i': tp = elm_Integer; break;\r
+        case 'b': tp = elm_Boolean; break;\r
+        case 's': tp = elm_String;  break;                \r
+    }\r
+    for (i=0; vars[i]; i++) {\r
+        ScalarVariable* sv = vars[i];\r
+        if (vr==getValueReference(sv) && tp==sv->typeSpec->type) \r
+            return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+// replace e.g. #r1365# by variable name and ## by # in message\r
+// copies the result to buffer\r
+static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU* fmu){\r
+    int i=0; // position in msg\r
+    int k=0; // position in buffer\r
+    int n;\r
+    char c = msg[i];\r
+    while (c!='\0' && k < nBuffer) {\r
+        if (c!='#') {\r
+            buffer[k++]=c;\r
+            i++;\r
+            c = msg[i];\r
+        }\r
+        else {\r
+            char* end = strchr(msg+i+1, '#');\r
+            if (!end) {\r
+                printf("unmatched '#' in '%s'\n", msg);\r
+                buffer[k++]='#';\r
+                break;\r
+            }\r
+            n = end - (msg+i);\r
+            if (n==1) {\r
+                // ## detected, output #\r
+                buffer[k++]='#';\r
+                i += 2;\r
+                c = msg[i];\r
+            }\r
+            else {\r
+                char type = msg[i+1]; // one of ribs\r
+                fmiValueReference vr;\r
+                int nvr = sscanf(msg+i+2, "%u", &vr);\r
+                if (nvr==1) {\r
+                    // vr of type detected, e.g. #r12#\r
+                    ScalarVariable* sv = getSV(fmu, type, vr);\r
+                    const char* name = sv ? getName(sv) : "?";\r
+                    sprintf(buffer+k, "%s", name);\r
+                    k += strlen(name);\r
+                    i += (n+1);\r
+                    c = msg[i]; \r
+                }\r
+                else {\r
+                    // could not parse the number\r
+                    printf("illegal value reference at position %d in '%s'\n", i+2, msg);\r
+                    buffer[k++]='#';\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+    } // while\r
+    buffer[k] = '\0';\r
+}\r
+\r
+#define MAX_MSG_SIZE 1000\r
+void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status,\r
+               fmiString category, fmiString message, ...) {\r
+    char msg[MAX_MSG_SIZE];\r
+    char* copy;\r
+    va_list argp;\r
+\r
+    // replace C format strings\r
+         va_start(argp, message);\r
+    vsprintf(msg, message, argp);\r
+\r
+    // replace e.g. ## and #r12#  \r
+    copy = strdup(msg);\r
+    replaceRefsInMessage(copy, msg, MAX_MSG_SIZE, &fmu);\r
+    free(copy);\r
+    \r
+    // print the final message\r
+    if (!instanceName) instanceName = "?";\r
+    if (!category) category = "?";\r
+    printf("%s %s (%s): %s\n", fmiStatusToString(status), instanceName, category, msg);\r
+}\r
+\r
+int error(const char* message){\r
+    printf("%s\n", message);\r
+    return 0;\r
+}\r
+\r
+void parseArguments(int argc, char *argv[], char** fmuFileName, double* tEnd, double* h, int* loggingOn, char* csv_separator) {\r
+    // parse command line arguments\r
+    if (argc>1) {\r
+        *fmuFileName = argv[1];\r
+    }\r
+    else {\r
+        printf("error: no fmu file\n");\r
+        printHelp(argv[0]);\r
+        exit(EXIT_FAILURE);\r
+    }\r
+    if (argc>2) {\r
+        if (sscanf(argv[2],"%lf", tEnd) != 1) {\r
+            printf("error: The given end time (%s) is not a number\n", argv[2]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>3) {\r
+        if (sscanf(argv[3],"%lf", h) != 1) {\r
+            printf("error: The given stepsize (%s) is not a number\n", argv[3]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>4) {\r
+        if (sscanf(argv[4],"%d", loggingOn) != 1 || *loggingOn<0 || *loggingOn>1) {\r
+            printf("error: The given logging flag (%s) is not boolean\n", argv[4]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>5) {\r
+        if (strlen(argv[5]) != 1) {\r
+            printf("error: The given CSV separator char (%s) is not valid\n", argv[5]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+        switch (argv[5][0]) {\r
+            case 'c': *csv_separator = ','; break; // comma\r
+            case 's': *csv_separator = ';'; break; // semicolon\r
+            default:  *csv_separator = argv[5][0]; break; // any other char\r
+        }\r
+    }\r
+    if (argc>6) {\r
+        printf("warning: Ignoring %d additional arguments: %s ...\n", argc-6, argv[6]);\r
+        printHelp(argv[0]);\r
+    }\r
+}\r
+\r
+void printHelp(const char* fmusim) {\r
+    printf("command syntax: %s <model.fmu> <tEnd> <h> <loggingOn> <csv separator>\n", fmusim);\r
+    printf("   <model.fmu> .... path to FMU, relative to current dir or absolute, required\n");\r
+    printf("   <tEnd> ......... end  time of simulation, optional, defaults to 1.0 sec\n");\r
+    printf("   <h> ............ step size of simulation, optional, defaults to 0.1 sec\n");\r
+    printf("   <loggingOn> .... 1 to activate logging,   optional, defaults to 0\n");\r
+    printf("   <csv separator>. separator in csv file,   optional, c for ';', s for';', defaults to c\n");\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/sim_support.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/sim_support.h
new file mode 100644 (file)
index 0000000..648c8b5
--- /dev/null
@@ -0,0 +1,31 @@
+/* ------------------------------------------------------------------------- \r
+ * sim_support.h\r
+ * Functions used by the FMU simulatios fmusim_me and fmusim_cs.\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+// Used 7z options, version 4.57:\r
+// -x   Extracts files from an archive with their full paths in the current dir, or in an output dir if specified\r
+// -aoa Overwrite All existing files without prompt\r
+// -o   Specifies a destination directory where files are to be extracted\r
+#define UNZIP_CMD "7z x -aoa -o"\r
+#define XML_FILE  "modelDescription.xml"\r
+#define DLL_DIR   "binaries\\win32\\"\r
+#define RESULT_FILE "result.csv"\r
+#define BUFSIZE 4096\r
+\r
+// return codes of the 7z command line tool\r
+#define SEVEN_ZIP_NO_ERROR 0 // success\r
+#define SEVEN_ZIP_WARNING 1  // e.g., one or more files were locked during zip\r
+#define SEVEN_ZIP_ERROR 2\r
+#define SEVEN_ZIP_COMMAND_LINE_ERROR 7\r
+#define SEVEN_ZIP_OUT_OF_MEMORY 8\r
+#define SEVEN_ZIP_STOPPED_BY_USER 255\r
+\r
+void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status, fmiString category, fmiString message, ...);\r
+int unzip(const char *zipPath, const char *outPath);\r
+void parseArguments(int argc, char *argv[], char** fmuFileName, double* tEnd, double* h, int* loggingOn, char* csv_separator);\r
+void loadFMU(const char* fmuFileName);\r
+void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, boolean header);\r
+int error(const char* message);\r
+void printHelp(const char* fmusim);\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/stack.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/stack.c
new file mode 100644 (file)
index 0000000..042b796
--- /dev/null
@@ -0,0 +1,85 @@
+/* ------------------------------------------------------------------------- \r
+ * stack.c\r
+ * A stack of pointers. \r
+ * Copyright 2010 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <assert.h>\r
+#include "stack.h"\r
+\r
+Stack* stackNew(int initialSize, int inc){\r
+    Stack* s = (Stack*)malloc(sizeof(Stack));\r
+    s->stack = NULL;\r
+    s->stackSize = 0;\r
+    s->stackPos = -1;\r
+    s->initialSize = initialSize;\r
+    s->inc = inc;\r
+    return s;\r
+}\r
+\r
+int stackIsEmpty(Stack* s) {\r
+    return s->stackPos == -1;\r
+}\r
+\r
+// add an element to stack and grow stack if required\r
+// returns 1 to indicate success and 0 for error\r
+int stackPush(Stack* s, void* e) {\r
+    s->stackPos++;\r
+    if (s->stackPos==s->stackSize){\r
+               s->stackSize += (s->stack ? s->inc: s->initialSize);\r
+        s->stack = (void**) realloc(s->stack, s->stackSize * sizeof(void*));\r
+        if (!s->stack) return 0; // error;\r
+    }\r
+    s->stack[s->stackPos] = e;\r
+    return 1; // success\r
+}\r
+\r
+// return top element (possibly NULL), if stack not empty\r
+// runtime error if stack is empty\r
+void* stackPeek(Stack* s){\r
+    assert(!stackIsEmpty(s));\r
+    return s->stack[s->stackPos];\r
+}\r
+\r
+// remove top element (possibly NULL) from stack and return it\r
+// runtime error if stack is empty\r
+void* stackPop(Stack* s){\r
+    assert(!stackIsEmpty(s));\r
+    return s->stack[s->stackPos--];\r
+}\r
+\r
+// return the last n elements as null terminated array, \r
+// or NULL if memory allocation fails\r
+void** stackLastPopedAsArray0(Stack* s, int n){\r
+    int i;\r
+    void** array = (void**)malloc((n + 1)*sizeof(void*));\r
+    if (! array) return NULL; // failure\r
+    for (i=0; i<n; i++) {\r
+        array[i] = s->stack[i+ s->stackPos + 1];\r
+    }\r
+    array[n]=NULL; // terminating NULL\r
+    return array;\r
+}\r
+\r
+// return stack as possibly empty array, or NULL if memory allocation fails\r
+// On sucessful return, the stack is empty.\r
+void** stackPopAllAsArray(Stack* s, int *size) {\r
+    int i;\r
+    void** array = (void**)malloc((s->stackPos + 1)*sizeof(void*));\r
+    if (! array) return NULL; // failure\r
+    *size = s->stackPos + 1;\r
+    for (i=0; i<*size; i++) \r
+        array[i] = s->stack[i];\r
+    s->stackPos = -1;\r
+    return array; \r
+}\r
+\r
+// release the given stack\r
+void stackFree(Stack* s){\r
+    if (s->stack) free(s->stack);\r
+    free(s);\r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/stack.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/stack.h
new file mode 100644 (file)
index 0000000..a52977f
--- /dev/null
@@ -0,0 +1,28 @@
+/* ------------------------------------------------------------------------- \r
+ * stack.c\r
+ * A stack of pointers. \r
+ * Copyright 2010 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#ifndef STACK_H\r
+#define STACK_H\r
+\r
+typedef struct {\r
+    void** stack;\r
+    int stackSize;    // allocated size of stack\r
+    int stackPos;     // array index of top element, -1 if stack is empty.\r
+    int initialSize;  // how many element to allocate initially\r
+    int inc;          // how many elements to allocate when stack gets full\r
+} Stack;\r
+\r
+Stack* stackNew(int initialSize, int inc);\r
+int stackIsEmpty(Stack* s);\r
+int stackPush(Stack* s, void* e);\r
+void* stackPeek(Stack* s);\r
+void* stackPop(Stack* s);\r
+void** stackPopAllAsArray(Stack* s, int *size);\r
+void** stackLastPopedAsArray0(Stack* s, int n);\r
+void stackFree(Stack* s);\r
+\r
+#endif // STACK_H\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/xml_parser.c b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/xml_parser.c
new file mode 100644 (file)
index 0000000..93e6216
--- /dev/null
@@ -0,0 +1,860 @@
+/* ------------------------------------------------------------------------- \r
+ * xml_Parser.c\r
+ * A parser for file modelVariables.xml of an FMU.\r
+ * The parser creates an AST (abstract syntax tree) for a given XML file.\r
+ * The root node of the AST is of type ModelDescription.\r
+ * Validation already performed by this parser\r
+ * - check for match of open/close elements (performed by Expat)\r
+ * - ceck element, attribute and enum value names, all case sensitive\r
+ * - check for each element that is has the expected parent element\r
+ * - check for correct sequence of elements\r
+ * - check that all decalaredType values reference an existing Type\r
+ * Validation to be performed by this parser\r
+ * - check for each attribute value that it is of the expected type \r
+ * - check that required attributes are present  \r
+ * - check that dependencies are only declared for outputs and\r
+ *   refer only to inputs\r
+ * Author: Jakob Mauss\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/\r
+\r
+#include <stdio.h>\r
+#include <assert.h>\r
+#include <string.h>\r
+#include "xml_parser.h"\r
+\r
+const char *elmNames[SIZEOF_ELM] = { \r
+    "fmiModelDescription","UnitDefinitions","BaseUnit","DisplayUnitDefinition","TypeDefinitions",\r
+    "Type","RealType","IntegerType","BooleanType","StringType","EnumerationType","Item",\r
+     "DefaultExperiment","VendorAnnotations","Tool","Annotation", "ModelVariables","ScalarVariable",\r
+     "DirectDependency","Name","Real","Integer","Boolean","String","Enumeration",\r
+     "Implementation","CoSimulation_StandAlone","CoSimulation_Tool","Model","File","Capabilities"\r
+};\r
+\r
+const char *attNames[SIZEOF_ATT] = {\r
+    "fmiVersion","displayUnit","gain","offset","unit","name","description","quantity", "relativeQuantity",\r
+    "min","max","nominal","declaredType","start","fixed","startTime","stopTime","tolerance","value",\r
+    "valueReference","variability","causality","alias", "modelName","modelIdentifier","guid","author",\r
+    "version","generationTool","generationDateAndTime","variableNamingConvention","numberOfContinuousStates",\r
+    "numberOfEventIndicators","input",\r
+    "canHandleVariableCommunicationStepSize","canHandleEvents","canRejectSteps","canInterpolateInputs",\r
+    "maxOutputDerivativeOrder","canRunAsynchronuously","canSignalEvents","canBeInstantiatedOnlyOncePerProcess",\r
+    "canNotUseMemoryManagementFunctions","file","entryPoint","manualStart","type"\r
+};\r
+\r
+const char *enuNames[SIZEOF_ENU] = {\r
+    "flat","structured","constant","parameter","discrete","continuous",\r
+    "input","output", "internal","none","noAlias","alias","negatedAlias"\r
+};\r
+\r
+#define ANY_TYPE -1\r
+#define XMLBUFSIZE 1024\r
+char text[XMLBUFSIZE];       // XML file is parsed in chunks of length XMLBUFZIZE\r
+XML_Parser parser = NULL;    // non-NULL during parsing\r
+Stack* stack = NULL;         // the parser stack\r
+char* data = NULL;           // buffer that holds element content, see handleData\r
+int skipData=0;              // 1 to ignore element content, 0 when recordig content\r
+\r
+// ------------------------------------------------------------------------- \r
+// Low-level functions for inspecting the model description \r
+\r
+const char* getString(void* element, Att a){\r
+    Element* e = (Element*)element;\r
+    const char** attr = e->attributes;\r
+    int i;\r
+    for (i=0; i<e->n; i+=2)\r
+        if (attr[i]==attNames[a]) return attr[i+1];\r
+    return NULL;\r
+}\r
+\r
+double getDouble(void* element, Att a, ValueStatus* vs){\r
+    double d = 0;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return d; }\r
+    *vs = (1==sscanf(value, "%lf", &d)) ? valueDefined : valueIllegal;\r
+    return d;    \r
+}\r
+\r
+// getInt() is also used to retrieve Enumeration values from XML,\r
+// e.g. the start value for a variable of user-defined enumeration type.\r
+int getInt(void* element, Att a, ValueStatus* vs){\r
+    int n = 0;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return n; }\r
+    *vs = (1==sscanf(value, "%d", &n)) ? valueDefined : valueIllegal;\r
+    return n;    \r
+}\r
+\r
+unsigned int getUInt(void* element, Att a, ValueStatus* vs){\r
+    unsigned int u = -1;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return u; }\r
+    *vs = (1==sscanf(value, "%u", &u)) ? valueDefined : valueIllegal;\r
+    return u;    \r
+}\r
+\r
+char getBoolean(void* element, Att a, ValueStatus* vs){\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return 0; };\r
+    *vs = valueDefined;\r
+    if (!strcmp(value, "true")) return 1;\r
+    if (!strcmp(value, "false")) return 0;\r
+    *vs = valueIllegal;    \r
+    return 0;\r
+}\r
+\r
+static int checkEnumValue(const char* enu);\r
+\r
+// Retrieve the value of the given built-in enum attribute.\r
+// If the value is missing, this is marked in the ValueStatus\r
+// and the corresponding default is returned.\r
+// Returns -1 or a globally unique id for the value such that\r
+// enuNames[id] is the string representation of the enum value. \r
+Enu getEnumValue(void* element, Att a, ValueStatus* vs) {\r
+    const char* value = getString(element, a);\r
+    Enu id = valueDefined;\r
+    if (!value) { \r
+        *vs = valueMissing;\r
+        switch (a) {\r
+            case att_variableNamingConvention: return enu_flat;\r
+            case att_variability: return enu_continuous;\r
+            case att_causality: return enu_internal;\r
+            case att_alias: return enu_noAlias;\r
+            default: return -1;\r
+        }\r
+    }\r
+    id = checkEnumValue(value);\r
+    if (id==-1) *vs = valueIllegal; \r
+    return id;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Convenience methods for accessing the model description. \r
+// Use is only safe after the ast has been successfuly validated.\r
+\r
+const char* getModelIdentifier(ModelDescription* md) {\r
+    const char* modelId = getString(md, att_modelIdentifier);\r
+    assert(modelId); // this is a required attribute\r
+    return modelId;\r
+}\r
+\r
+int getNumberOfStates(ModelDescription* md) {\r
+    ValueStatus vs;\r
+    int n = getUInt(md, att_numberOfContinuousStates, &vs);\r
+    assert(vs==valueDefined); // this is a required attribute\r
+    return n;\r
+}\r
+\r
+int getNumberOfEventIndicators(ModelDescription* md) {\r
+    ValueStatus vs;\r
+    int n = getInt(md, att_numberOfEventIndicators, &vs);\r
+    assert(vs==valueDefined); // this is a required attribute\r
+    return n;\r
+}\r
+\r
+// name is a required attribute of ScalarVariable, Type, Item, Annotation, and Tool\r
+const char* getName(void* element) { \r
+    const char* name = getString(element, att_name);\r
+    assert(name); // this is a required attribute\r
+    return name;\r
+}\r
+\r
+// returns one of: input, output, internal, none\r
+// if value is missing, the default internal is returned\r
+Enu getCausality(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_causality, &vs);\r
+}\r
+\r
+// returns one of constant, parameter, discrete, continuous\r
+// if value is missing, the default continuous is returned\r
+Enu getVariability(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_variability, &vs);\r
+}\r
+\r
+// returns one of noAlias, alias, negatedAlias\r
+// if value is missing, the default noAlias is returned \r
+Enu getAlias(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_alias, &vs);\r
+}\r
+\r
+// the vr is unique only for one of the 4 base data types r,i,b,s and\r
+// may also be fmiUndefinedValueReference = 4294967295 = 0xFFFFFFFF\r
+// here, i means integer or enumeration\r
+fmiValueReference getValueReference(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    fmiValueReference vr = getUInt(scalarVariable, att_valueReference, &vs);\r
+    assert(((Element*)scalarVariable)->type == elm_ScalarVariable);\r
+    assert(vs==valueDefined); // this is a reqired attribute\r
+    return vr;\r
+}\r
+\r
+// the name is unique within a fmu\r
+ScalarVariable* getVariableByName(ModelDescription* md, const char* name) {\r
+    int i;\r
+    if (md->modelVariables)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        if (!strcmp(getName(sv), name)) return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+// Enumeration and Integer have the same base type while \r
+// Real, String, Boolean define own base types.\r
+int sameBaseType(Elm t1, Elm t2){\r
+    return t1==t2 || \r
+           t1==elm_Enumeration && t2==elm_Integer || \r
+           t2==elm_Enumeration && t1==elm_Integer;\r
+}\r
+\r
+// returns NULL if variable not found or vr==fmiUndefinedValueReference\r
+ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type){\r
+    int i;\r
+    if (md->modelVariables && vr!=fmiUndefinedValueReference)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        if (sameBaseType(type, sv->typeSpec->type) && getValueReference(sv) == vr) \r
+            return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+Type* getDeclaredType(ModelDescription* md, const char* declaredType){\r
+    int i;\r
+    if (declaredType && md->typeDefinitions)\r
+    for (i=0; md->typeDefinitions[i]; i++){\r
+        Type* tp = (Type*)md->typeDefinitions[i];\r
+        if (!strcmp(declaredType, getName(tp))) return tp;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+const char* getString2(ModelDescription* md, void* tp, Att a) {\r
+    Type* type;\r
+    const char* value = getString(tp, a);\r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    type = getDeclaredType(md, getString(tp, att_declaredType));\r
+    return type ? getString(type->typeSpec, a) : NULL;\r
+}\r
+\r
+// Get description from variable or from declared type, or NULL.\r
+const char * getDescription(ModelDescription* md, ScalarVariable* sv) {\r
+    const char* value = getString(sv, att_description);\r
+    Type* type; \r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    type = getDeclaredType(md, getString(sv->typeSpec, att_declaredType));\r
+    return type ? getString(type, att_description) : NULL;\r
+}\r
+\r
+// Get attribute value from scalar variable given by vr and type, \r
+// incl. default value provided by declared type, if any.\r
+const char * getVariableAttributeString(ModelDescription* md, \r
+        fmiValueReference vr, Elm type, Att a){\r
+    const char* value;\r
+    const char* declaredType;\r
+    Type* tp; \r
+    ScalarVariable* sv = getVariable(md, vr, type);\r
+    if (!sv) return NULL;\r
+    value = getString(sv->typeSpec, a);\r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    tp = getDeclaredType(md, getString(sv->typeSpec, att_declaredType));\r
+    return tp ? getString(tp->typeSpec, a) : NULL;\r
+}\r
+\r
+// Get attribute value from scalar variable given by vr and type, \r
+// incl. default value provided by declared type, if any.\r
+double getVariableAttributeDouble(ModelDescription* md, \r
+        fmiValueReference vr, Elm type, Att a, ValueStatus* vs){\r
+    double d = 0;\r
+    const char* value = getVariableAttributeString(md, vr, type, a);\r
+    if (!value) { *vs = valueMissing; return d; }\r
+    *vs = (1==sscanf(value, "%lf", &d)) ? valueDefined : valueIllegal;\r
+    return d;    \r
+}\r
+\r
+// Get nominal value from real variable or its declared type.\r
+// Return 1, if no nominal value is defined.\r
+double getNominal(ModelDescription* md, fmiValueReference vr){\r
+    ValueStatus vs;\r
+    double nominal = getVariableAttributeDouble(md, vr, elm_Real, att_nominal, &vs);\r
+    return vs==valueDefined ? nominal : 1.0;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Various checks that log an error and stop the parser \r
+\r
+// Returns 0 to indicate error\r
+static int checkPointer(const void* ptr){\r
+    if (! ptr) {\r
+        printf("Out of memory\n");\r
+        if (parser) XML_StopParser(parser, XML_FALSE);\r
+        return 0; // error \r
+    }\r
+    return 1; // success\r
+}\r
+\r
+static int checkName(const char* name, const char* kind, const char* array[], int n){\r
+    int i;\r
+    for (i=0; i<n; i++) {\r
+        if (!strcmp(name, array[i])) return i;\r
+    }\r
+    printf("Illegal %s %s\n", kind, name);\r
+    XML_StopParser(parser, XML_FALSE);\r
+    return -1;\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkElement(const char* elm){\r
+    return checkName(elm, "element", elmNames, SIZEOF_ELM);\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkAttribute(const char* att){\r
+    return checkName(att, "attribute", attNames, SIZEOF_ATT);\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkEnumValue(const char* enu){\r
+    return checkName(enu, "enum value", enuNames, SIZEOF_ENU);\r
+}\r
+\r
+static void logFatalTypeError(const char* expected, Elm found) {\r
+    printf("Wrong element type, expected %s, found %s\n", \r
+            expected, elmNames[found]);\r
+    XML_StopParser(parser, XML_FALSE);\r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Verify that Element elm is of the given type\r
+static int checkElementType(void* element, Elm e) {\r
+    Element* elm = (Element* )element;\r
+    if (elm->type == e) return 1; // success\r
+    logFatalTypeError(elmNames[e], elm->type);\r
+    return 0; // error    \r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Verify that the next stack element exists and is of the given type\r
+// If e==ANY_TYPE, the type check is ommited \r
+static int checkPeek(Elm e) {\r
+    if (stackIsEmpty(stack)){\r
+        printf("Illegal document structure, expected %s\n", elmNames[e]);\r
+        XML_StopParser(parser, XML_FALSE);\r
+        return 0; // error\r
+    }\r
+    return e==ANY_TYPE ? 1 : checkElementType(stackPeek(stack), e);\r
+}\r
+\r
+// Returns NULL to indicate error\r
+// Get the next stack element, it is of the given type.\r
+// If e==ANY_TYPE, the type check is ommited \r
+static void* checkPop(Elm e){\r
+    return checkPeek(e) ? stackPop(stack) : NULL;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Helper \r
+\r
+AstNodeType getAstNodeType(Elm e){\r
+    switch (e) {\r
+    case elm_fmiModelDescription: \r
+        return astModelDescription;\r
+    case elm_Type:\r
+        return astType;\r
+    case elm_ScalarVariable:\r
+        return astScalarVariable;\r
+    case elm_CoSimulation_StandAlone:\r
+    case elm_CoSimulation_Tool:\r
+        return astCoSimulation;\r
+    case elm_BaseUnit:\r
+    case elm_EnumerationType:\r
+    case elm_Tool:\r
+    case elm_UnitDefinitions:\r
+    case elm_TypeDefinitions:\r
+    case elm_VendorAnnotations:\r
+    case elm_ModelVariables:\r
+    case elm_DirectDependency:\r
+    case elm_Model:\r
+        return astListElement;\r
+    default:\r
+        return astElement; \r
+    }\r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Copies the attr array and all values.\r
+// Replaces all attribute names by constant literal strings.\r
+// Converts the null-terminated array into an array of known size n.\r
+int addAttributes(Element* el, const char** attr) {\r
+    int n, a;\r
+    const char** att = NULL;\r
+    for (n=0; attr[n]; n+=2);\r
+    if (n>0) {\r
+        att = calloc(n, sizeof(char*));\r
+        if (!checkPointer(att)) return 0;\r
+    } \r
+    for (n=0; attr[n]; n+=2) {\r
+        char* value = strdup(attr[n+1]);\r
+        if (!checkPointer(value)) return 0;\r
+        a = checkAttribute(attr[n]);\r
+        if (a == -1) return 0;  // illegal attribute error\r
+        att[n  ] = attNames[a]; // no heap memory\r
+        att[n+1] = value;       // heap memory\r
+    }\r
+    el->attributes = att; // NULL if n=0\r
+    el->n = n;\r
+    return 1; // success\r
+}\r
+\r
+// Returns NULL to indicate error\r
+Element* newElement(Elm type, int size, const char** attr) {\r
+    Element* e = (Element*)calloc(1, size);\r
+    if (!checkPointer(e)) return NULL; \r
+    e->type = type;\r
+    e->attributes = NULL;\r
+    e->n=0;\r
+    if (!addAttributes(e, attr)) return NULL;\r
+    return e;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// callback functions called by the XML parser \r
+\r
+// Create and push a new element node\r
+static void XMLCALL startElement(void *context, const char *elm, const char **attr) {\r
+    Elm el;\r
+    void* e;\r
+    int size;\r
+    el = checkElement(elm);\r
+    if (el==-1) return; // error\r
+    skipData = (el != elm_Name); // skip element content for all elements but Name\r
+    switch(getAstNodeType(el)){\r
+        case astElement:          size = sizeof(Element); break;\r
+        case astListElement:      size = sizeof(ListElement); break;\r
+        case astType:             size = sizeof(Type); break;\r
+        case astScalarVariable:   size = sizeof(ScalarVariable); break;\r
+        case astCoSimulation:     size = sizeof(CoSimulation); break;\r
+        case astModelDescription: size = sizeof(ModelDescription); break;\r
+               default: assert(0);\r
+    }\r
+    e = newElement(el, size, attr);\r
+    checkPointer(e); \r
+    stackPush(stack, e);\r
+}\r
+\r
+// Pop all elements of the given type from stack and \r
+// add it to the ListElement that follows.\r
+// The ListElement remains on the stack.\r
+static void popList(Elm e) {\r
+    int n = 0;\r
+    Element** array;\r
+    Element* elm = stackPop(stack);\r
+    while (elm->type == e) {\r
+        elm = stackPop(stack);\r
+        n++;\r
+    }\r
+    stackPush(stack, elm); // push ListElement back to stack\r
+    array = (Element**)stackLastPopedAsArray0(stack, n); // NULL terminated list\r
+    if (getAstNodeType(elm->type)!=astListElement) return; // failure\r
+    ((ListElement*)elm)->list = array;\r
+    return; // success only if list!=NULL    \r
+}\r
+\r
+// Pop the children from the stack and\r
+// check for correct type and sequence of children\r
+static void XMLCALL endElement(void *context, const char *elm) {\r
+    Elm el;\r
+    el = checkElement(elm);\r
+    switch(el) { \r
+        case elm_fmiModelDescription: \r
+            {\r
+                 ModelDescription* md;\r
+                 ListElement** ud = NULL;     // NULL or list of BaseUnits\r
+                 Type**        td = NULL;     // NULL or list of Types \r
+                 Element*      de = NULL;     // NULL or DefaultExperiment\r
+                 ListElement** va = NULL;     // NULL or list of Tools\r
+                 ScalarVariable** mv = NULL;  // NULL or list of ScalarVariable\r
+                 CoSimulation *cs = NULL;     // NULL or CoSimulation\r
+                 ListElement* child;\r
+\r
+                 child = checkPop(ANY_TYPE);\r
+                 if (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool) {\r
+                     cs = (CoSimulation*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_ModelVariables){\r
+                     mv = (ScalarVariable**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_VendorAnnotations){\r
+                     va = (ListElement**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_DefaultExperiment){\r
+                     de = (Element*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_TypeDefinitions){\r
+                     td = (Type**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_UnitDefinitions){\r
+                     ud = (ListElement**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 // work around bug of SimulationX 3.4 and 3.5 which places Implementation at wrong location \r
+                 if (!cs && (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool)) {\r
+                     cs = (CoSimulation*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (!checkElementType(child, elm_fmiModelDescription)) return;\r
+                 md = (ModelDescription*)child;\r
+                 md->modelVariables = mv;\r
+                 md->vendorAnnotations = va;\r
+                 md->defaultExperiment = de;\r
+                 md->typeDefinitions = td;\r
+                 md->unitDefinitions = ud;\r
+                 md->cosimulation = cs;\r
+                 stackPush(stack, md);\r
+                 break;\r
+            }\r
+        case elm_Implementation:\r
+            {\r
+                 // replace Implementation element\r
+                 void* cs = checkPop(ANY_TYPE);\r
+                 void* im = checkPop(elm_Implementation);\r
+                 stackPush(stack, cs);\r
+                 free(im);\r
+                 el = ((Element*)cs)->type;\r
+                 break;\r
+            }\r
+        case elm_CoSimulation_StandAlone:  \r
+            {\r
+                 Element* ca = checkPop(elm_Capabilities);\r
+                 CoSimulation* cs = checkPop(elm_CoSimulation_StandAlone);\r
+                 if (!ca || !cs) return;\r
+                 cs->capabilities = ca;\r
+                 stackPush(stack, cs);\r
+                 break;\r
+            }   \r
+        case elm_CoSimulation_Tool:\r
+            {\r
+                 ListElement* mo = checkPop(elm_Model);\r
+                 Element* ca = checkPop(elm_Capabilities);\r
+                 CoSimulation* cs = checkPop(elm_CoSimulation_Tool);\r
+                 if (!ca || !mo || !cs) return;\r
+                 cs->capabilities = ca;\r
+                 cs->model = mo;\r
+                 stackPush(stack, cs);\r
+                 break;\r
+            }   \r
+        case elm_Type:\r
+            {\r
+                Type* tp;\r
+                Element* ts = checkPop(ANY_TYPE);\r
+                if (!ts) return;\r
+                if (!checkPeek(elm_Type)) return;\r
+                tp = (Type*)stackPeek(stack);\r
+                switch (ts->type) {\r
+                    case elm_RealType:\r
+                    case elm_IntegerType:\r
+                    case elm_BooleanType:\r
+                    case elm_StringType:\r
+                    case elm_EnumerationType:\r
+                        break;\r
+                    default:\r
+                         logFatalTypeError("RealType or similar", ts->type);\r
+                         return;\r
+                }\r
+                tp->typeSpec = ts;\r
+                break;\r
+            }\r
+        case elm_ScalarVariable:\r
+            {\r
+                ScalarVariable* sv;\r
+                Element** list = NULL;\r
+                Element* child = checkPop(ANY_TYPE);\r
+                if (!child) return;\r
+                if (child->type==elm_DirectDependency){\r
+                    list = ((ListElement*)child)->list;\r
+                    free(child);\r
+                    child = checkPop(ANY_TYPE);\r
+                    if (!child) return;\r
+                }\r
+                if (!checkPeek(elm_ScalarVariable)) return;\r
+                sv = (ScalarVariable*)stackPeek(stack);\r
+                switch (child->type) {\r
+                    case elm_Real:\r
+                    case elm_Integer:\r
+                    case elm_Boolean:\r
+                    case elm_String:\r
+                    case elm_Enumeration:\r
+                        break;\r
+                    default:\r
+                         logFatalTypeError("Real or similar", child->type);\r
+                         return;\r
+                }\r
+                sv->directDependencies = list;\r
+                sv->typeSpec = child;\r
+                break;\r
+            }\r
+        case elm_ModelVariables:    popList(elm_ScalarVariable); break;\r
+        case elm_VendorAnnotations: popList(elm_Tool);break;\r
+        case elm_Tool:              popList(elm_Annotation); break;\r
+        case elm_TypeDefinitions:   popList(elm_Type); break;\r
+        case elm_EnumerationType:   popList(elm_Item); break;\r
+        case elm_UnitDefinitions:   popList(elm_BaseUnit); break;\r
+        case elm_BaseUnit:          popList(elm_DisplayUnitDefinition); break;\r
+        case elm_DirectDependency:  popList(elm_Name); break;\r
+        case elm_Model:             popList(elm_File); break;\r
+        case elm_Name:\r
+            {\r
+                 // Exception: the name value is represented as element content.\r
+                 // All other values of the XML file are represented using attributes.\r
+                 Element* name = checkPop(elm_Name);\r
+                 if (!name) return;\r
+                 name->n = 2;\r
+                 name->attributes = malloc(2*sizeof(char*));\r
+                 name->attributes[0] = attNames[att_input];\r
+                 name->attributes[1] = data;\r
+                 data = NULL;\r
+                 skipData = 1; // stop recording element content\r
+                 stackPush(stack, name);\r
+                 break;\r
+            }\r
+        case -1: return; // illegal element error\r
+        default: // must be a leaf Element\r
+                 assert(getAstNodeType(el)==astElement);\r
+                 break;\r
+    }\r
+    // All children of el removed from the stack.\r
+    // The top element must be of type el now.\r
+    checkPeek(el);\r
+}\r
+\r
+// Called to handle element data, e.g. "xy" in <Name>xy</Name>\r
+// Can be called many times, e.g. with "x" and then with "y" in the example above.\r
+// Feature in expat:\r
+// For some reason, if the element data is the empty string (Eg. <a></a>)\r
+// instead of an empty string with len == 0 we get "\n". The workaround is\r
+// to replace this with the empty string whenever we encounter "\n".\r
+void XMLCALL handleData(void *context, const XML_Char *s, int len) {\r
+    int n;\r
+    if (skipData) return;\r
+    if (!data) {\r
+        // start a new data string\r
+        if (len == 1 && s[0] == '\n') {\r
+            data = strdup("");\r
+        } else {\r
+            data = malloc(len + 1);\r
+            strncpy(data, s, len);\r
+            data[len] = '\0';\r
+        }\r
+    }\r
+    else {\r
+        // continue existing string\r
+        n = strlen(data) + len;\r
+        data = realloc(data, n+1);\r
+        strncat(data, s, len);\r
+        data[n] = '\0';\r
+    }\r
+    return;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// printing\r
\r
+static void printList(int indent, void** list);\r
+\r
+void printElement(int indent, void* element){\r
+    int i;\r
+    Element* e = (Element*)element;\r
+    if (!e) return;\r
+    // print attributes\r
+    for (i=0; i<indent; i++) printf(" ");\r
+    printf("%s", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf(" %s=%s", e->attributes[i], e->attributes[i+1]);\r
+    printf("\n");\r
+    // print child nodes\r
+    indent += 2;\r
+    switch (getAstNodeType(e->type)) {\r
+        case astListElement:\r
+            printList(indent, ((ListElement*)e)->list);\r
+            break;\r
+        case astScalarVariable:\r
+            printElement(indent, ((Type*)e)->typeSpec);\r
+            printList(indent, ((ScalarVariable*)e)->directDependencies);\r
+            break;\r
+        case astType:\r
+            printElement(indent, ((Type*)e)->typeSpec);\r
+            break;\r
+        case astCoSimulation: {\r
+            CoSimulation* cs = (CoSimulation*)e;\r
+            printElement(indent, cs->capabilities);\r
+            printElement(indent, cs->model);\r
+            break;\r
+        }\r
+        case astModelDescription: {\r
+            ModelDescription *md = (ModelDescription*)e;\r
+            printList(indent, md->unitDefinitions);\r
+            printList(indent, md->typeDefinitions);\r
+            printElement(indent, md->defaultExperiment);\r
+            printList(indent, md->vendorAnnotations);\r
+            printList(indent, md->modelVariables);\r
+            printElement(indent, md->cosimulation);\r
+            break;\r
+        }\r
+    }\r
+}\r
+\r
+static void printList(int indent, void** list){\r
+    int i;\r
+    if (list) for (i=0; list[i]; i++) \r
+       printElement(indent, list[i]);\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// free memory of the AST\r
+\r
+static void freeList(void** list);\r
+\r
+void freeElement(void* element){\r
+    int i;\r
+    Element* e = (Element*)element;\r
+    if (!e) return;\r
+    // free attributes\r
+    for (i=0; i<e->n; i+=2) \r
+        free(e->attributes[i+1]);\r
+    if (e->attributes) free(e->attributes);\r
+    // free child nodes\r
+    switch (getAstNodeType(e->type)) {\r
+        case astListElement:\r
+            freeList(((ListElement*)e)->list);\r
+            break;\r
+        case astScalarVariable:\r
+            freeList(((ScalarVariable*)e)->directDependencies);\r
+        case astType:\r
+            freeElement(((Type*)e)->typeSpec);\r
+            break;\r
+        case astCoSimulation: {\r
+            CoSimulation* cs = (CoSimulation*)e;\r
+            freeElement(cs->capabilities);\r
+            freeElement(cs->model);\r
+            break;\r
+        }\r
+        case astModelDescription: {\r
+            ModelDescription* md = (ModelDescription*)e;\r
+            freeList(md->unitDefinitions);\r
+            freeList(md->typeDefinitions);\r
+            freeElement(md->defaultExperiment);\r
+            freeList(md->vendorAnnotations);\r
+            freeList(md->modelVariables);\r
+            freeElement(md->cosimulation);\r
+            break;\r
+       }\r
+    }\r
+    // free the struct\r
+    free(e);\r
+}\r
+\r
+static void freeList(void** list){\r
+    int i;\r
+    if (!list) return;\r
+    for (i=0; list[i]; i++) \r
+        freeElement(list[i]);\r
+    free(list);\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Validation - done after parsing to report all errors \r
+\r
+ModelDescription* validate(ModelDescription* md) {\r
+    int error = 0;\r
+    int i;\r
+    if (md->modelVariables)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        char* declaredType = getString(sv->typeSpec, att_declaredType);\r
+        Type* decltype = getDeclaredType(md, declaredType);\r
+        if (declaredType && decltype==NULL) {\r
+            printf("Warning: Declared type %s of variable %s not found in modelDescription.xml\n", declaredType, getName(sv));\r
+            error++;\r
+        }\r
+    }\r
+    if (error) {\r
+        printf("Error: Found %d error in modelDescription.xml\n", error);\r
+        return NULL;\r
+    }\r
+    return md;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Entry function parse() of the XML parser \r
+\r
+static void cleanup(FILE *file) {\r
+    stackFree(stack);\r
+    stack = NULL;\r
+    XML_ParserFree(parser);\r
+    parser = NULL;\r
+    fclose(file);\r
+}\r
+\r
+// Returns NULL to indicate failure\r
+// Otherwise, return the root node md of the AST.\r
+// The receiver must call freeElement(md) to release AST memory.\r
+ModelDescription* parse(const char* xmlPath) {\r
+    ModelDescription* md = NULL;\r
+    FILE *file;\r
+    int done = 0;\r
+    stack = stackNew(100, 10);\r
+    if (!checkPointer(stack)) return NULL;  // failure\r
+    parser = XML_ParserCreate(NULL);\r
+    if (!checkPointer(parser)) return NULL;  // failure\r
+    XML_SetElementHandler(parser, startElement, endElement);\r
+    XML_SetCharacterDataHandler(parser, handleData);\r
+       file = fopen(xmlPath, "rb");\r
+       if (file == NULL) {\r
+        printf("Cannot open file '%s'\n", xmlPath);\r
+       XML_ParserFree(parser);\r
+        return NULL; // failure\r
+    }\r
+    while (!done) {\r
+        int n = fread(text, sizeof(char), XMLBUFSIZE, file);\r
+           if (n != XMLBUFSIZE) done = 1;\r
+        if (!XML_Parse(parser, text, n, done)){\r
+             printf("Parse error in file %s at line %d:\n%s\n", \r
+                     xmlPath,\r
+                        XML_GetCurrentLineNumber(parser),\r
+                        XML_ErrorString(XML_GetErrorCode(parser)));\r
+             while (! stackIsEmpty(stack)) md = stackPop(stack);\r
+             if (md) freeElement(md);\r
+             cleanup(file);\r
+             return NULL; // failure\r
+        }\r
+    }\r
+    md = stackPop(stack);\r
+    assert(stackIsEmpty(stack));\r
+    cleanup(file);\r
+    //printElement(1, md); // debug\r
+    return validate(md); // success if all refs are valid    \r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/xml_parser.h b/1.8/org.simantics.fmu/FMUSolution/FMISDK/src/shared/xml_parser.h
new file mode 100644 (file)
index 0000000..0730d56
--- /dev/null
@@ -0,0 +1,159 @@
+/* ------------------------------------------------------------------------- \r
+ * xml_parser.h\r
+ * A parser for file modelVariables.xml of an FMU.\r
+ * Supports "FMI for Model Exchange 1.0" and "FMI for Co-Simulation 1.0".\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/\r
+\r
+#ifndef xml_parser_h\r
+#define xml_parser_h\r
+\r
+// define XML_STATIC before including expat.h\r
+// to prevent error when linking with libexpatMT.lib\r
+#define XML_STATIC \r
+#include "expat.h"\r
+#include "stack.h"\r
+\r
+typedef unsigned int fmiValueReference;\r
+#define fmiUndefinedValueReference (fmiValueReference)(-1)\r
+\r
+#define SIZEOF_ELM 31\r
+extern const char *elmNames[SIZEOF_ELM];\r
+\r
+#define SIZEOF_ATT 47\r
+extern const char *attNames[SIZEOF_ATT];\r
+\r
+#define SIZEOF_ENU 13\r
+extern const char *enuNames[SIZEOF_ENU];\r
+\r
+// Elements\r
+typedef enum {\r
+    elm_fmiModelDescription,elm_UnitDefinitions,elm_BaseUnit,elm_DisplayUnitDefinition,elm_TypeDefinitions,\r
+    elm_Type,elm_RealType,elm_IntegerType,elm_BooleanType,elm_StringType,elm_EnumerationType,elm_Item,\r
+    elm_DefaultExperiment,elm_VendorAnnotations,elm_Tool,elm_Annotation,elm_ModelVariables,elm_ScalarVariable,\r
+    elm_DirectDependency,elm_Name,elm_Real,elm_Integer,elm_Boolean,elm_String,elm_Enumeration,\r
+    elm_Implementation,elm_CoSimulation_StandAlone,elm_CoSimulation_Tool,elm_Model,elm_File,elm_Capabilities\r
+} Elm;\r
+\r
+// Attributes\r
+typedef enum { \r
+  att_fmiVersion,att_displayUnit,att_gain,att_offset,att_unit,att_name,att_description,att_quantity,att_relativeQuantity,\r
+  att_min,att_max,att_nominal,att_declaredType,att_start,att_fixed,att_startTime,att_stopTime,att_tolerance,att_value,\r
+  att_valueReference,att_variability,att_causality,att_alias,att_modelName,att_modelIdentifier,att_guid,att_author,\r
+  att_version,att_generationTool,att_generationDateAndTime,att_variableNamingConvention,att_numberOfContinuousStates,\r
+  att_numberOfEventIndicators,att_input,\r
+  att_canHandleVariableCommunicationStepSize,att_canHandleEvents,att_canRejectSteps,att_canInterpolateInputs,\r
+  att_maxOutputDerivativeOrder,att_canRunAsynchronuously,att_canSignalEvents,att_canBeInstantiatedOnlyOncePerProcess,\r
+  att_canNotUseMemoryManagementFunctions,att_entryPoint,att_manualStart,att_type\r
+} Att;\r
+\r
+// Enumeration values\r
+typedef enum {\r
+    enu_flat,enu_structured,enu_constant,enu_parameter,enu_discrete,enu_continuous,\r
+    enu_input,enu_output,enu_internal,enu_none,enu_noAlias,enu_alias,enu_negatedAlias    \r
+} Enu;\r
+\r
+// AST node for element \r
+// DisplayUnitDefinition, RealType, IntegerType, BooleanType, StringType, DefaultExperiment, \r
+// Item, Annotation, Name, Real, Integer, Boolean, String, Enumeration, Capabilities, File\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+} Element;\r
+\r
+// AST node for element that has a list of elements \r
+// BaseUnit, EnumerationType, Tool, DirectDependency, Model\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    Element** list;    // null-terminated array of pointers to elements, not null\r
+} ListElement;\r
+\r
+// AST node for element Type\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, an even number\r
+    Element* typeSpec; // one of RealType, IntegerType etc. \r
+} Type;\r
+\r
+// AST node for element ScalarVariable\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    Element* typeSpec; // one of Real, Integer, etc\r
+    Element** directDependencies; // null or null-terminated list of Name\r
+} ScalarVariable;\r
+\r
+// AST node for element CoSimulation_StandAlone and CoSimulation_Tool\r
+typedef struct {\r
+    Elm type; // one of elm_CoSimulation_StandAlone and elm_CoSimulation_Tool\r
+    const char** attributes; // null or n attribute value strings\r
+    int n;                   // size of attributes, even number\r
+    Element* capabilities;   // a set of capability attributes\r
+    ListElement* model;      // non-NULL to support tool coupling, NULL for standalone \r
+} CoSimulation;\r
+\r
+// AST node for element ModelDescription\r
+typedef struct {\r
+    Elm type;          // element type\r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    ListElement** unitDefinitions;    // NULL or null-terminated list of BaseUnits\r
+    Type**        typeDefinitions;    // NULL or null-terminated list of Types \r
+    Element*      defaultExperiment;  // NULL or DefaultExperiment\r
+    ListElement** vendorAnnotations;  // NULL or null-terminated list of Tools\r
+    ScalarVariable** modelVariables;  // NULL or null-terminated list of ScalarVariable\r
+    CoSimulation* cosimulation;       // NULL if this ModelDescription is for model exchange only\r
+} ModelDescription;\r
+\r
+// types of AST nodes used to represent an element\r
+typedef enum { \r
+    astElement, \r
+    astListElement,\r
+    astType,\r
+    astScalarVariable,\r
+    astCoSimulation,\r
+    astModelDescription\r
+} AstNodeType;\r
+\r
+// Possible results when retrieving an attribute value from an element\r
+typedef enum { \r
+    valueMissing,\r
+    valueDefined,\r
+    valueIllegal\r
+} ValueStatus;\r
+\r
+// Public methods: Parsing and low-level AST access\r
+ModelDescription* parse(const char* xmlPath);\r
+const char* getString(void* element, Att a);\r
+double getDouble     (void* element, Att a, ValueStatus* vs);\r
+int getInt           (void* element, Att a, ValueStatus* vs);\r
+unsigned int getUInt (void* element, Att a, ValueStatus* vs);\r
+char getBoolean      (void* element, Att a, ValueStatus* vs);\r
+Enu getEnumValue     (void* element, Att a, ValueStatus* vs);\r
+void freeElement     (void* element);\r
+\r
+// Convenience methods for AST access. To be used afer successful validation only.\r
+const char* getModelIdentifier(ModelDescription* md);\r
+int getNumberOfStates(ModelDescription* md);\r
+int getNumberOfEventIndicators(ModelDescription* md);\r
+const char* getName(void* element);\r
+Enu getCausality(void* scalarVariable);\r
+Enu getVariability(void* scalarVariable);\r
+Enu getAlias(void* scalarVariable);\r
+fmiValueReference getValueReference(void* scalarVariable);\r
+ScalarVariable* getVariableByName(ModelDescription* md, const char* name);\r
+ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type);\r
+Type* getDeclaredType(ModelDescription* md, const char* declaredType);\r
+const char* getString2(ModelDescription* md, void* sv, Att a);\r
+const char * getDescription(ModelDescription* md, ScalarVariable* sv);\r
+const char * getVariableAttributeString(ModelDescription* md, fmiValueReference vr, Elm type, Att a);\r
+double getVariableAttributeDouble(ModelDescription* md, fmiValueReference vr, Elm type, Att a, ValueStatus* vs);\r
+double getNominal(ModelDescription* md, fmiValueReference vr);\r
+\r
+#endif // xml_parser_h\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/FMUSimulator.vcxproj b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/FMUSimulator.vcxproj
new file mode 100644 (file)
index 0000000..774e369
--- /dev/null
@@ -0,0 +1,184 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup Label="ProjectConfigurations">\r
+    <ProjectConfiguration Include="Debug|Win32">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|x64">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Win32">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|x64">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+  </ItemGroup>\r
+  <PropertyGroup Label="Globals">\r
+    <ProjectGuid>{9838038D-09A3-43A5-AB97-B5B5C763DF43}</ProjectGuid>\r
+    <Keyword>Win32Proj</Keyword>\r
+    <RootNamespace>FMUSimulator</RootNamespace>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseDebugLibraries>true</UseDebugLibraries>\r
+    <CharacterSet>NotSet</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseDebugLibraries>true</UseDebugLibraries>\r
+    <CharacterSet>NotSet</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseDebugLibraries>false</UseDebugLibraries>\r
+    <WholeProgramOptimization>false</WholeProgramOptimization>\r
+    <CharacterSet>NotSet</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseDebugLibraries>false</UseDebugLibraries>\r
+    <WholeProgramOptimization>false</WholeProgramOptimization>\r
+    <CharacterSet>NotSet</CharacterSet>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\r
+  <ImportGroup Label="ExtensionSettings">\r
+  </ImportGroup>\r
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <PropertyGroup Label="UserMacros" />\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <LinkIncremental>false</LinkIncremental>\r
+    <IncludePath>$(SolutionDir)zlib-1.2.6\contrib\minizip;$(OutDir);$(ProjectDir)include;$(IncludePath)</IncludePath>\r
+    <LibraryPath>$(OutDir);$(ProjectDir)include;$(LibraryPath)</LibraryPath>\r
+    <SourcePath>$(SourcePath)</SourcePath>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\r
+    <LinkIncremental>false</LinkIncremental>\r
+    <IncludePath>$(SolutionDir)zlib-1.2.6\contrib\minizip;$(OutDir);$(ProjectDir)include;$(IncludePath)</IncludePath>\r
+    <LibraryPath>$(OutDir);$(ProjectDir)include;$(LibraryPath)</LibraryPath>\r
+    <SourcePath>$(SourcePath)</SourcePath>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <LinkIncremental>false</LinkIncremental>\r
+    <IncludePath>$(SolutionDir)zlib-1.2.6\contrib\minizip;$(OutDir);$(ProjectDir)include;$(IncludePath)</IncludePath>\r
+    <LibraryPath>$(OutDir);$(ProjectDir)include;$(LibraryPath)</LibraryPath>\r
+    <SourcePath>$(SourcePath)</SourcePath>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\r
+    <LinkIncremental>false</LinkIncremental>\r
+    <IncludePath>$(SolutionDir)zlib-1.2.6\contrib\minizip;$(OutDir);$(ProjectDir)include;$(IncludePath)</IncludePath>\r
+    <LibraryPath>$(OutDir);$(ProjectDir)include;$(LibraryPath)</LibraryPath>\r
+    <SourcePath>$(SourcePath)</SourcePath>\r
+  </PropertyGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <ClCompile>\r
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <Optimization>Disabled</Optimization>\r
+      <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;FMUSIMULATOR_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r
+    </ClCompile>\r
+    <Link>\r
+      <SubSystem>Windows</SubSystem>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <AdditionalDependencies>$(OutDir)zlibwapi.lib;$(OutDir)miniunz.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\r
+    <ClCompile>\r
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <Optimization>Disabled</Optimization>\r
+      <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;FMUSIMULATOR_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r
+    </ClCompile>\r
+    <Link>\r
+      <SubSystem>Windows</SubSystem>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <AdditionalDependencies>$(OutDir)zlibwapi.lib;$(OutDir)miniunz.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <ClCompile>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <FunctionLevelLinking>\r
+      </FunctionLevelLinking>\r
+      <IntrinsicFunctions>false</IntrinsicFunctions>\r
+      <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;FMUSIMULATOR_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <AdditionalIncludeDirectories>\r
+      </AdditionalIncludeDirectories>\r
+    </ClCompile>\r
+    <Link>\r
+      <SubSystem>Windows</SubSystem>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <AdditionalDependencies>$(OutDir)zlibwapi.lib;$(OutDir)miniunz.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\r
+    <ClCompile>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <FunctionLevelLinking>\r
+      </FunctionLevelLinking>\r
+      <IntrinsicFunctions>false</IntrinsicFunctions>\r
+      <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;FMUSIMULATOR_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <AdditionalIncludeDirectories>\r
+      </AdditionalIncludeDirectories>\r
+    </ClCompile>\r
+    <Link>\r
+      <SubSystem>Windows</SubSystem>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <AdditionalDependencies>$(OutDir)zlibwapi.lib;$(OutDir)miniunz.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+    </Link>\r
+    <Manifest>\r
+      <InputResourceManifests>\r
+      </InputResourceManifests>\r
+    </Manifest>\r
+  </ItemDefinitionGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="src\fmu_control.cpp" />\r
+    <ClCompile Include="src\sim_support.c" />\r
+    <ClCompile Include="src\stack.c" />\r
+    <ClCompile Include="src\xml_parser.c" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClInclude Include="include\fmiModelFunctions.h" />\r
+    <ClInclude Include="include\fmiModelTypes.h" />\r
+    <ClInclude Include="include\fmi_me.h" />\r
+    <ClInclude Include="include\org_simantics_fmu_FMUControlJNI.h" />\r
+    <ClInclude Include="include\sim_support.h" />\r
+    <ClInclude Include="include\xml_parser.h" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <Library Include="..\x64\Release\expat.lib" />\r
+    <Library Include="include\libexpatMT.lib" />\r
+  </ItemGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\r
+  <ImportGroup Label="ExtensionTargets">\r
+  </ImportGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/FMUSimulator.vcxproj.filters b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/FMUSimulator.vcxproj.filters
new file mode 100644 (file)
index 0000000..33d44c1
--- /dev/null
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup>\r
+    <Filter Include="Source Files">\r
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\r
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\r
+    </Filter>\r
+    <Filter Include="Header Files">\r
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\r
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>\r
+    </Filter>\r
+    <Filter Include="Resource Files">\r
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\r
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\r
+    </Filter>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="src\fmu_control.cpp">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="src\sim_support.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="src\stack.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="src\xml_parser.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClInclude Include="include\sim_support.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="include\fmiModelFunctions.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="include\fmiModelTypes.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="include\fmi_me.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="include\xml_parser.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="include\org_simantics_fmu_FMUControlJNI.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <Library Include="include\libexpatMT.lib">\r
+      <Filter>Resource Files</Filter>\r
+    </Library>\r
+    <Library Include="..\x64\Release\expat.lib">\r
+      <Filter>Resource Files</Filter>\r
+    </Library>\r
+  </ItemGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/COPYING.txt b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/COPYING.txt
new file mode 100644 (file)
index 0000000..9042217
--- /dev/null
@@ -0,0 +1,24 @@
+Files expat.h, expat_external.h and libexpatMT.lib\r
+\r
+Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+                               and Clark Cooper\r
+Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining\r
+a copy of this software and associated documentation files (the\r
+"Software"), to deal in the Software without restriction, including\r
+without limitation the rights to use, copy, modify, merge, publish,\r
+distribute, sublicense, and/or sell copies of the Software, and to\r
+permit persons to whom the Software is furnished to do so, subject to\r
+the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included\r
+in all copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\r
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\r
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat.h
new file mode 100644 (file)
index 0000000..6c2b6ff
--- /dev/null
@@ -0,0 +1,1014 @@
+/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+   See the file COPYING for copying permission.\r
+*/\r
+\r
+#ifndef Expat_INCLUDED\r
+#define Expat_INCLUDED 1\r
+\r
+#ifdef __VMS\r
+/*      0        1         2         3      0        1         2         3\r
+        1234567890123456789012345678901     1234567890123456789012345678901 */\r
+#define XML_SetProcessingInstructionHandler XML_SetProcessingInstrHandler\r
+#define XML_SetUnparsedEntityDeclHandler    XML_SetUnparsedEntDeclHandler\r
+#define XML_SetStartNamespaceDeclHandler    XML_SetStartNamespcDeclHandler\r
+#define XML_SetExternalEntityRefHandlerArg  XML_SetExternalEntRefHandlerArg\r
+#endif\r
+\r
+#include <stdlib.h>\r
+#include "expat_external.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+struct XML_ParserStruct;\r
+typedef struct XML_ParserStruct *XML_Parser;\r
+\r
+/* Should this be defined using stdbool.h when C99 is available? */\r
+typedef unsigned char XML_Bool;\r
+#define XML_TRUE   ((XML_Bool) 1)\r
+#define XML_FALSE  ((XML_Bool) 0)\r
+\r
+/* The XML_Status enum gives the possible return values for several\r
+   API functions.  The preprocessor #defines are included so this\r
+   stanza can be added to code that still needs to support older\r
+   versions of Expat 1.95.x:\r
+\r
+   #ifndef XML_STATUS_OK\r
+   #define XML_STATUS_OK    1\r
+   #define XML_STATUS_ERROR 0\r
+   #endif\r
+\r
+   Otherwise, the #define hackery is quite ugly and would have been\r
+   dropped.\r
+*/\r
+enum XML_Status {\r
+  XML_STATUS_ERROR = 0,\r
+#define XML_STATUS_ERROR XML_STATUS_ERROR\r
+  XML_STATUS_OK = 1,\r
+#define XML_STATUS_OK XML_STATUS_OK\r
+  XML_STATUS_SUSPENDED = 2\r
+#define XML_STATUS_SUSPENDED XML_STATUS_SUSPENDED\r
+};\r
+\r
+enum XML_Error {\r
+  XML_ERROR_NONE,\r
+  XML_ERROR_NO_MEMORY,\r
+  XML_ERROR_SYNTAX,\r
+  XML_ERROR_NO_ELEMENTS,\r
+  XML_ERROR_INVALID_TOKEN,\r
+  XML_ERROR_UNCLOSED_TOKEN,\r
+  XML_ERROR_PARTIAL_CHAR,\r
+  XML_ERROR_TAG_MISMATCH,\r
+  XML_ERROR_DUPLICATE_ATTRIBUTE,\r
+  XML_ERROR_JUNK_AFTER_DOC_ELEMENT,\r
+  XML_ERROR_PARAM_ENTITY_REF,\r
+  XML_ERROR_UNDEFINED_ENTITY,\r
+  XML_ERROR_RECURSIVE_ENTITY_REF,\r
+  XML_ERROR_ASYNC_ENTITY,\r
+  XML_ERROR_BAD_CHAR_REF,\r
+  XML_ERROR_BINARY_ENTITY_REF,\r
+  XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF,\r
+  XML_ERROR_MISPLACED_XML_PI,\r
+  XML_ERROR_UNKNOWN_ENCODING,\r
+  XML_ERROR_INCORRECT_ENCODING,\r
+  XML_ERROR_UNCLOSED_CDATA_SECTION,\r
+  XML_ERROR_EXTERNAL_ENTITY_HANDLING,\r
+  XML_ERROR_NOT_STANDALONE,\r
+  XML_ERROR_UNEXPECTED_STATE,\r
+  XML_ERROR_ENTITY_DECLARED_IN_PE,\r
+  XML_ERROR_FEATURE_REQUIRES_XML_DTD,\r
+  XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING,\r
+  /* Added in 1.95.7. */\r
+  XML_ERROR_UNBOUND_PREFIX,\r
+  /* Added in 1.95.8. */\r
+  XML_ERROR_UNDECLARING_PREFIX,\r
+  XML_ERROR_INCOMPLETE_PE,\r
+  XML_ERROR_XML_DECL,\r
+  XML_ERROR_TEXT_DECL,\r
+  XML_ERROR_PUBLICID,\r
+  XML_ERROR_SUSPENDED,\r
+  XML_ERROR_NOT_SUSPENDED,\r
+  XML_ERROR_ABORTED,\r
+  XML_ERROR_FINISHED,\r
+  XML_ERROR_SUSPEND_PE,\r
+  /* Added in 2.0. */\r
+  XML_ERROR_RESERVED_PREFIX_XML,\r
+  XML_ERROR_RESERVED_PREFIX_XMLNS,\r
+  XML_ERROR_RESERVED_NAMESPACE_URI\r
+};\r
+\r
+enum XML_Content_Type {\r
+  XML_CTYPE_EMPTY = 1,\r
+  XML_CTYPE_ANY,\r
+  XML_CTYPE_MIXED,\r
+  XML_CTYPE_NAME,\r
+  XML_CTYPE_CHOICE,\r
+  XML_CTYPE_SEQ\r
+};\r
+\r
+enum XML_Content_Quant {\r
+  XML_CQUANT_NONE,\r
+  XML_CQUANT_OPT,\r
+  XML_CQUANT_REP,\r
+  XML_CQUANT_PLUS\r
+};\r
+\r
+/* If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be\r
+   XML_CQUANT_NONE, and the other fields will be zero or NULL.\r
+   If type == XML_CTYPE_MIXED, then quant will be NONE or REP and\r
+   numchildren will contain number of elements that may be mixed in\r
+   and children point to an array of XML_Content cells that will be\r
+   all of XML_CTYPE_NAME type with no quantification.\r
+\r
+   If type == XML_CTYPE_NAME, then the name points to the name, and\r
+   the numchildren field will be zero and children will be NULL. The\r
+   quant fields indicates any quantifiers placed on the name.\r
+\r
+   CHOICE and SEQ will have name NULL, the number of children in\r
+   numchildren and children will point, recursively, to an array\r
+   of XML_Content cells.\r
+\r
+   The EMPTY, ANY, and MIXED types will only occur at top level.\r
+*/\r
+\r
+typedef struct XML_cp XML_Content;\r
+\r
+struct XML_cp {\r
+  enum XML_Content_Type         type;\r
+  enum XML_Content_Quant        quant;\r
+  XML_Char *                    name;\r
+  unsigned int                  numchildren;\r
+  XML_Content *                 children;\r
+};\r
+\r
+\r
+/* This is called for an element declaration. See above for\r
+   description of the model argument. It's the caller's responsibility\r
+   to free model when finished with it.\r
+*/\r
+typedef void (XMLCALL *XML_ElementDeclHandler) (void *userData,\r
+                                                const XML_Char *name,\r
+                                                XML_Content *model);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetElementDeclHandler(XML_Parser parser,\r
+                          XML_ElementDeclHandler eldecl);\r
+\r
+/* The Attlist declaration handler is called for *each* attribute. So\r
+   a single Attlist declaration with multiple attributes declared will\r
+   generate multiple calls to this handler. The "default" parameter\r
+   may be NULL in the case of the "#IMPLIED" or "#REQUIRED"\r
+   keyword. The "isrequired" parameter will be true and the default\r
+   value will be NULL in the case of "#REQUIRED". If "isrequired" is\r
+   true and default is non-NULL, then this is a "#FIXED" default.\r
+*/\r
+typedef void (XMLCALL *XML_AttlistDeclHandler) (\r
+                                    void            *userData,\r
+                                    const XML_Char  *elname,\r
+                                    const XML_Char  *attname,\r
+                                    const XML_Char  *att_type,\r
+                                    const XML_Char  *dflt,\r
+                                    int              isrequired);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetAttlistDeclHandler(XML_Parser parser,\r
+                          XML_AttlistDeclHandler attdecl);\r
+\r
+/* The XML declaration handler is called for *both* XML declarations\r
+   and text declarations. The way to distinguish is that the version\r
+   parameter will be NULL for text declarations. The encoding\r
+   parameter may be NULL for XML declarations. The standalone\r
+   parameter will be -1, 0, or 1 indicating respectively that there\r
+   was no standalone parameter in the declaration, that it was given\r
+   as no, or that it was given as yes.\r
+*/\r
+typedef void (XMLCALL *XML_XmlDeclHandler) (void           *userData,\r
+                                            const XML_Char *version,\r
+                                            const XML_Char *encoding,\r
+                                            int             standalone);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetXmlDeclHandler(XML_Parser parser,\r
+                      XML_XmlDeclHandler xmldecl);\r
+\r
+\r
+typedef struct {\r
+  void *(*malloc_fcn)(size_t size);\r
+  void *(*realloc_fcn)(void *ptr, size_t size);\r
+  void (*free_fcn)(void *ptr);\r
+} XML_Memory_Handling_Suite;\r
+\r
+/* Constructs a new parser; encoding is the encoding specified by the\r
+   external protocol or NULL if there is none specified.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreate(const XML_Char *encoding);\r
+\r
+/* Constructs a new parser and namespace processor.  Element type\r
+   names and attribute names that belong to a namespace will be\r
+   expanded; unprefixed attribute names are never expanded; unprefixed\r
+   element type names are expanded only if there is a default\r
+   namespace. The expanded name is the concatenation of the namespace\r
+   URI, the namespace separator character, and the local part of the\r
+   name.  If the namespace separator is '\0' then the namespace URI\r
+   and the local part will be concatenated without any separator.\r
+   It is a programming error to use the separator '\0' with namespace\r
+   triplets (see XML_SetReturnNSTriplet).\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator);\r
+\r
+\r
+/* Constructs a new parser using the memory management suite referred to\r
+   by memsuite. If memsuite is NULL, then use the standard library memory\r
+   suite. If namespaceSeparator is non-NULL it creates a parser with\r
+   namespace processing as described above. The character pointed at\r
+   will serve as the namespace separator.\r
+\r
+   All further memory operations used for the created parser will come from\r
+   the given suite.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ParserCreate_MM(const XML_Char *encoding,\r
+                    const XML_Memory_Handling_Suite *memsuite,\r
+                    const XML_Char *namespaceSeparator);\r
+\r
+/* Prepare a parser object to be re-used.  This is particularly\r
+   valuable when memory allocation overhead is disproportionatly high,\r
+   such as when a large number of small documnents need to be parsed.\r
+   All handlers are cleared from the parser, except for the\r
+   unknownEncodingHandler. The parser's external state is re-initialized\r
+   except for the values of ns and ns_triplets.\r
+\r
+   Added in Expat 1.95.3.\r
+*/\r
+XMLPARSEAPI(XML_Bool)\r
+XML_ParserReset(XML_Parser parser, const XML_Char *encoding);\r
+\r
+/* atts is array of name/value pairs, terminated by 0;\r
+   names and values are 0 terminated.\r
+*/\r
+typedef void (XMLCALL *XML_StartElementHandler) (void *userData,\r
+                                                 const XML_Char *name,\r
+                                                 const XML_Char **atts);\r
+\r
+typedef void (XMLCALL *XML_EndElementHandler) (void *userData,\r
+                                               const XML_Char *name);\r
+\r
+\r
+/* s is not 0 terminated. */\r
+typedef void (XMLCALL *XML_CharacterDataHandler) (void *userData,\r
+                                                  const XML_Char *s,\r
+                                                  int len);\r
+\r
+/* target and data are 0 terminated */\r
+typedef void (XMLCALL *XML_ProcessingInstructionHandler) (\r
+                                                void *userData,\r
+                                                const XML_Char *target,\r
+                                                const XML_Char *data);\r
+\r
+/* data is 0 terminated */\r
+typedef void (XMLCALL *XML_CommentHandler) (void *userData,\r
+                                            const XML_Char *data);\r
+\r
+typedef void (XMLCALL *XML_StartCdataSectionHandler) (void *userData);\r
+typedef void (XMLCALL *XML_EndCdataSectionHandler) (void *userData);\r
+\r
+/* This is called for any characters in the XML document for which\r
+   there is no applicable handler.  This includes both characters that\r
+   are part of markup which is of a kind that is not reported\r
+   (comments, markup declarations), or characters that are part of a\r
+   construct which could be reported but for which no handler has been\r
+   supplied. The characters are passed exactly as they were in the XML\r
+   document except that they will be encoded in UTF-8 or UTF-16.\r
+   Line boundaries are not normalized. Note that a byte order mark\r
+   character is not passed to the default handler. There are no\r
+   guarantees about how characters are divided between calls to the\r
+   default handler: for example, a comment might be split between\r
+   multiple calls.\r
+*/\r
+typedef void (XMLCALL *XML_DefaultHandler) (void *userData,\r
+                                            const XML_Char *s,\r
+                                            int len);\r
+\r
+/* This is called for the start of the DOCTYPE declaration, before\r
+   any DTD or internal subset is parsed.\r
+*/\r
+typedef void (XMLCALL *XML_StartDoctypeDeclHandler) (\r
+                                            void *userData,\r
+                                            const XML_Char *doctypeName,\r
+                                            const XML_Char *sysid,\r
+                                            const XML_Char *pubid,\r
+                                            int has_internal_subset);\r
+\r
+/* This is called for the start of the DOCTYPE declaration when the\r
+   closing > is encountered, but after processing any external\r
+   subset.\r
+*/\r
+typedef void (XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);\r
+\r
+/* This is called for entity declarations. The is_parameter_entity\r
+   argument will be non-zero if the entity is a parameter entity, zero\r
+   otherwise.\r
+\r
+   For internal entities (<!ENTITY foo "bar">), value will\r
+   be non-NULL and systemId, publicID, and notationName will be NULL.\r
+   The value string is NOT nul-terminated; the length is provided in\r
+   the value_length argument. Since it is legal to have zero-length\r
+   values, do not use this argument to test for internal entities.\r
+\r
+   For external entities, value will be NULL and systemId will be\r
+   non-NULL. The publicId argument will be NULL unless a public\r
+   identifier was provided. The notationName argument will have a\r
+   non-NULL value only for unparsed entity declarations.\r
+\r
+   Note that is_parameter_entity can't be changed to XML_Bool, since\r
+   that would break binary compatibility.\r
+*/\r
+typedef void (XMLCALL *XML_EntityDeclHandler) (\r
+                              void *userData,\r
+                              const XML_Char *entityName,\r
+                              int is_parameter_entity,\r
+                              const XML_Char *value,\r
+                              int value_length,\r
+                              const XML_Char *base,\r
+                              const XML_Char *systemId,\r
+                              const XML_Char *publicId,\r
+                              const XML_Char *notationName);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEntityDeclHandler(XML_Parser parser,\r
+                         XML_EntityDeclHandler handler);\r
+\r
+/* OBSOLETE -- OBSOLETE -- OBSOLETE\r
+   This handler has been superceded by the EntityDeclHandler above.\r
+   It is provided here for backward compatibility.\r
+\r
+   This is called for a declaration of an unparsed (NDATA) entity.\r
+   The base argument is whatever was set by XML_SetBase. The\r
+   entityName, systemId and notationName arguments will never be\r
+   NULL. The other arguments may be.\r
+*/\r
+typedef void (XMLCALL *XML_UnparsedEntityDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *entityName,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId,\r
+                                    const XML_Char *notationName);\r
+\r
+/* This is called for a declaration of notation.  The base argument is\r
+   whatever was set by XML_SetBase. The notationName will never be\r
+   NULL.  The other arguments can be.\r
+*/\r
+typedef void (XMLCALL *XML_NotationDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *notationName,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId);\r
+\r
+/* When namespace processing is enabled, these are called once for\r
+   each namespace declaration. The call to the start and end element\r
+   handlers occur between the calls to the start and end namespace\r
+   declaration handlers. For an xmlns attribute, prefix will be\r
+   NULL.  For an xmlns="" attribute, uri will be NULL.\r
+*/\r
+typedef void (XMLCALL *XML_StartNamespaceDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *prefix,\r
+                                    const XML_Char *uri);\r
+\r
+typedef void (XMLCALL *XML_EndNamespaceDeclHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *prefix);\r
+\r
+/* This is called if the document is not standalone, that is, it has an\r
+   external subset or a reference to a parameter entity, but does not\r
+   have standalone="yes". If this handler returns XML_STATUS_ERROR,\r
+   then processing will not continue, and the parser will return a\r
+   XML_ERROR_NOT_STANDALONE error.\r
+   If parameter entity parsing is enabled, then in addition to the\r
+   conditions above this handler will only be called if the referenced\r
+   entity was actually read.\r
+*/\r
+typedef int (XMLCALL *XML_NotStandaloneHandler) (void *userData);\r
+\r
+/* This is called for a reference to an external parsed general\r
+   entity.  The referenced entity is not automatically parsed.  The\r
+   application can parse it immediately or later using\r
+   XML_ExternalEntityParserCreate.\r
+\r
+   The parser argument is the parser parsing the entity containing the\r
+   reference; it can be passed as the parser argument to\r
+   XML_ExternalEntityParserCreate.  The systemId argument is the\r
+   system identifier as specified in the entity declaration; it will\r
+   not be NULL.\r
+\r
+   The base argument is the system identifier that should be used as\r
+   the base for resolving systemId if systemId was relative; this is\r
+   set by XML_SetBase; it may be NULL.\r
+\r
+   The publicId argument is the public identifier as specified in the\r
+   entity declaration, or NULL if none was specified; the whitespace\r
+   in the public identifier will have been normalized as required by\r
+   the XML spec.\r
+\r
+   The context argument specifies the parsing context in the format\r
+   expected by the context argument to XML_ExternalEntityParserCreate;\r
+   context is valid only until the handler returns, so if the\r
+   referenced entity is to be parsed later, it must be copied.\r
+   context is NULL only when the entity is a parameter entity.\r
+\r
+   The handler should return XML_STATUS_ERROR if processing should not\r
+   continue because of a fatal error in the handling of the external\r
+   entity.  In this case the calling parser will return an\r
+   XML_ERROR_EXTERNAL_ENTITY_HANDLING error.\r
+\r
+   Note that unlike other handlers the first argument is the parser,\r
+   not userData.\r
+*/\r
+typedef int (XMLCALL *XML_ExternalEntityRefHandler) (\r
+                                    XML_Parser parser,\r
+                                    const XML_Char *context,\r
+                                    const XML_Char *base,\r
+                                    const XML_Char *systemId,\r
+                                    const XML_Char *publicId);\r
+\r
+/* This is called in two situations:\r
+   1) An entity reference is encountered for which no declaration\r
+      has been read *and* this is not an error.\r
+   2) An internal entity reference is read, but not expanded, because\r
+      XML_SetDefaultHandler has been called.\r
+   Note: skipped parameter entities in declarations and skipped general\r
+         entities in attribute values cannot be reported, because\r
+         the event would be out of sync with the reporting of the\r
+         declarations or attribute values\r
+*/\r
+typedef void (XMLCALL *XML_SkippedEntityHandler) (\r
+                                    void *userData,\r
+                                    const XML_Char *entityName,\r
+                                    int is_parameter_entity);\r
+\r
+/* This structure is filled in by the XML_UnknownEncodingHandler to\r
+   provide information to the parser about encodings that are unknown\r
+   to the parser.\r
+\r
+   The map[b] member gives information about byte sequences whose\r
+   first byte is b.\r
+\r
+   If map[b] is c where c is >= 0, then b by itself encodes the\r
+   Unicode scalar value c.\r
+\r
+   If map[b] is -1, then the byte sequence is malformed.\r
+\r
+   If map[b] is -n, where n >= 2, then b is the first byte of an\r
+   n-byte sequence that encodes a single Unicode scalar value.\r
+\r
+   The data member will be passed as the first argument to the convert\r
+   function.\r
+\r
+   The convert function is used to convert multibyte sequences; s will\r
+   point to a n-byte sequence where map[(unsigned char)*s] == -n.  The\r
+   convert function must return the Unicode scalar value represented\r
+   by this byte sequence or -1 if the byte sequence is malformed.\r
+\r
+   The convert function may be NULL if the encoding is a single-byte\r
+   encoding, that is if map[b] >= -1 for all bytes b.\r
+\r
+   When the parser is finished with the encoding, then if release is\r
+   not NULL, it will call release passing it the data member; once\r
+   release has been called, the convert function will not be called\r
+   again.\r
+\r
+   Expat places certain restrictions on the encodings that are supported\r
+   using this mechanism.\r
+\r
+   1. Every ASCII character that can appear in a well-formed XML document,\r
+      other than the characters\r
+\r
+      $@\^`{}~\r
+\r
+      must be represented by a single byte, and that byte must be the\r
+      same byte that represents that character in ASCII.\r
+\r
+   2. No character may require more than 4 bytes to encode.\r
+\r
+   3. All characters encoded must have Unicode scalar values <=\r
+      0xFFFF, (i.e., characters that would be encoded by surrogates in\r
+      UTF-16 are  not allowed).  Note that this restriction doesn't\r
+      apply to the built-in support for UTF-8 and UTF-16.\r
+\r
+   4. No Unicode character may be encoded by more than one distinct\r
+      sequence of bytes.\r
+*/\r
+typedef struct {\r
+  int map[256];\r
+  void *data;\r
+  int (XMLCALL *convert)(void *data, const char *s);\r
+  void (XMLCALL *release)(void *data);\r
+} XML_Encoding;\r
+\r
+/* This is called for an encoding that is unknown to the parser.\r
+\r
+   The encodingHandlerData argument is that which was passed as the\r
+   second argument to XML_SetUnknownEncodingHandler.\r
+\r
+   The name argument gives the name of the encoding as specified in\r
+   the encoding declaration.\r
+\r
+   If the callback can provide information about the encoding, it must\r
+   fill in the XML_Encoding structure, and return XML_STATUS_OK.\r
+   Otherwise it must return XML_STATUS_ERROR.\r
+\r
+   If info does not describe a suitable encoding, then the parser will\r
+   return an XML_UNKNOWN_ENCODING error.\r
+*/\r
+typedef int (XMLCALL *XML_UnknownEncodingHandler) (\r
+                                    void *encodingHandlerData,\r
+                                    const XML_Char *name,\r
+                                    XML_Encoding *info);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetElementHandler(XML_Parser parser,\r
+                      XML_StartElementHandler start,\r
+                      XML_EndElementHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartElementHandler(XML_Parser parser,\r
+                           XML_StartElementHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndElementHandler(XML_Parser parser,\r
+                         XML_EndElementHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetCharacterDataHandler(XML_Parser parser,\r
+                            XML_CharacterDataHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetProcessingInstructionHandler(XML_Parser parser,\r
+                                    XML_ProcessingInstructionHandler handler);\r
+XMLPARSEAPI(void)\r
+XML_SetCommentHandler(XML_Parser parser,\r
+                      XML_CommentHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetCdataSectionHandler(XML_Parser parser,\r
+                           XML_StartCdataSectionHandler start,\r
+                           XML_EndCdataSectionHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartCdataSectionHandler(XML_Parser parser,\r
+                                XML_StartCdataSectionHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndCdataSectionHandler(XML_Parser parser,\r
+                              XML_EndCdataSectionHandler end);\r
+\r
+/* This sets the default handler and also inhibits expansion of\r
+   internal entities. These entity references will be passed to the\r
+   default handler, or to the skipped entity handler, if one is set.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetDefaultHandler(XML_Parser parser,\r
+                      XML_DefaultHandler handler);\r
+\r
+/* This sets the default handler but does not inhibit expansion of\r
+   internal entities.  The entity reference will not be passed to the\r
+   default handler.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetDefaultHandlerExpand(XML_Parser parser,\r
+                            XML_DefaultHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetDoctypeDeclHandler(XML_Parser parser,\r
+                          XML_StartDoctypeDeclHandler start,\r
+                          XML_EndDoctypeDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartDoctypeDeclHandler(XML_Parser parser,\r
+                               XML_StartDoctypeDeclHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndDoctypeDeclHandler(XML_Parser parser,\r
+                             XML_EndDoctypeDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetUnparsedEntityDeclHandler(XML_Parser parser,\r
+                                 XML_UnparsedEntityDeclHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNotationDeclHandler(XML_Parser parser,\r
+                           XML_NotationDeclHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNamespaceDeclHandler(XML_Parser parser,\r
+                            XML_StartNamespaceDeclHandler start,\r
+                            XML_EndNamespaceDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetStartNamespaceDeclHandler(XML_Parser parser,\r
+                                 XML_StartNamespaceDeclHandler start);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetEndNamespaceDeclHandler(XML_Parser parser,\r
+                               XML_EndNamespaceDeclHandler end);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetNotStandaloneHandler(XML_Parser parser,\r
+                            XML_NotStandaloneHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetExternalEntityRefHandler(XML_Parser parser,\r
+                                XML_ExternalEntityRefHandler handler);\r
+\r
+/* If a non-NULL value for arg is specified here, then it will be\r
+   passed as the first argument to the external entity ref handler\r
+   instead of the parser object.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_SetExternalEntityRefHandlerArg(XML_Parser parser,\r
+                                   void *arg);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetSkippedEntityHandler(XML_Parser parser,\r
+                            XML_SkippedEntityHandler handler);\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetUnknownEncodingHandler(XML_Parser parser,\r
+                              XML_UnknownEncodingHandler handler,\r
+                              void *encodingHandlerData);\r
+\r
+/* This can be called within a handler for a start element, end\r
+   element, processing instruction or character data.  It causes the\r
+   corresponding markup to be passed to the default handler.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_DefaultCurrent(XML_Parser parser);\r
+\r
+/* If do_nst is non-zero, and namespace processing is in effect, and\r
+   a name has a prefix (i.e. an explicit namespace qualifier) then\r
+   that name is returned as a triplet in a single string separated by\r
+   the separator character specified when the parser was created: URI\r
+   + sep + local_name + sep + prefix.\r
+\r
+   If do_nst is zero, then namespace information is returned in the\r
+   default manner (URI + sep + local_name) whether or not the name\r
+   has a prefix.\r
+\r
+   Note: Calling XML_SetReturnNSTriplet after XML_Parse or\r
+     XML_ParseBuffer has no effect.\r
+*/\r
+\r
+XMLPARSEAPI(void)\r
+XML_SetReturnNSTriplet(XML_Parser parser, int do_nst);\r
+\r
+/* This value is passed as the userData argument to callbacks. */\r
+XMLPARSEAPI(void)\r
+XML_SetUserData(XML_Parser parser, void *userData);\r
+\r
+/* Returns the last value set by XML_SetUserData or NULL. */\r
+#define XML_GetUserData(parser) (*(void **)(parser))\r
+\r
+/* This is equivalent to supplying an encoding argument to\r
+   XML_ParserCreate. On success XML_SetEncoding returns non-zero,\r
+   zero otherwise.\r
+   Note: Calling XML_SetEncoding after XML_Parse or XML_ParseBuffer\r
+     has no effect and returns XML_STATUS_ERROR.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_SetEncoding(XML_Parser parser, const XML_Char *encoding);\r
+\r
+/* If this function is called, then the parser will be passed as the\r
+   first argument to callbacks instead of userData.  The userData will\r
+   still be accessible using XML_GetUserData.\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_UseParserAsHandlerArg(XML_Parser parser);\r
+\r
+/* If useDTD == XML_TRUE is passed to this function, then the parser\r
+   will assume that there is an external subset, even if none is\r
+   specified in the document. In such a case the parser will call the\r
+   externalEntityRefHandler with a value of NULL for the systemId\r
+   argument (the publicId and context arguments will be NULL as well).\r
+   Note: For the purpose of checking WFC: Entity Declared, passing\r
+     useDTD == XML_TRUE will make the parser behave as if the document\r
+     had a DTD with an external subset.\r
+   Note: If this function is called, then this must be done before\r
+     the first call to XML_Parse or XML_ParseBuffer, since it will\r
+     have no effect after that.  Returns\r
+     XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING.\r
+   Note: If the document does not have a DOCTYPE declaration at all,\r
+     then startDoctypeDeclHandler and endDoctypeDeclHandler will not\r
+     be called, despite an external subset being parsed.\r
+   Note: If XML_DTD is not defined when Expat is compiled, returns\r
+     XML_ERROR_FEATURE_REQUIRES_XML_DTD.\r
+*/\r
+XMLPARSEAPI(enum XML_Error)\r
+XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);\r
+\r
+\r
+/* Sets the base to be used for resolving relative URIs in system\r
+   identifiers in declarations.  Resolving relative identifiers is\r
+   left to the application: this value will be passed through as the\r
+   base argument to the XML_ExternalEntityRefHandler,\r
+   XML_NotationDeclHandler and XML_UnparsedEntityDeclHandler. The base\r
+   argument will be copied.  Returns XML_STATUS_ERROR if out of memory,\r
+   XML_STATUS_OK otherwise.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_SetBase(XML_Parser parser, const XML_Char *base);\r
+\r
+XMLPARSEAPI(const XML_Char *)\r
+XML_GetBase(XML_Parser parser);\r
+\r
+/* Returns the number of the attribute/value pairs passed in last call\r
+   to the XML_StartElementHandler that were specified in the start-tag\r
+   rather than defaulted. Each attribute/value pair counts as 2; thus\r
+   this correspondds to an index into the atts array passed to the\r
+   XML_StartElementHandler.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetSpecifiedAttributeCount(XML_Parser parser);\r
+\r
+/* Returns the index of the ID attribute passed in the last call to\r
+   XML_StartElementHandler, or -1 if there is no ID attribute.  Each\r
+   attribute/value pair counts as 2; thus this correspondds to an\r
+   index into the atts array passed to the XML_StartElementHandler.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetIdAttributeIndex(XML_Parser parser);\r
+\r
+/* Parses some input. Returns XML_STATUS_ERROR if a fatal error is\r
+   detected.  The last call to XML_Parse must have isFinal true; len\r
+   may be zero for this call (or any other).\r
+\r
+   Though the return values for these functions has always been\r
+   described as a Boolean value, the implementation, at least for the\r
+   1.95.x series, has always returned exactly one of the XML_Status\r
+   values.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_Parse(XML_Parser parser, const char *s, int len, int isFinal);\r
+\r
+XMLPARSEAPI(void *)\r
+XML_GetBuffer(XML_Parser parser, int len);\r
+\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_ParseBuffer(XML_Parser parser, int len, int isFinal);\r
+\r
+/* Stops parsing, causing XML_Parse() or XML_ParseBuffer() to return.\r
+   Must be called from within a call-back handler, except when aborting\r
+   (resumable = 0) an already suspended parser. Some call-backs may\r
+   still follow because they would otherwise get lost. Examples:\r
+   - endElementHandler() for empty elements when stopped in\r
+     startElementHandler(), \r
+   - endNameSpaceDeclHandler() when stopped in endElementHandler(), \r
+   and possibly others.\r
+\r
+   Can be called from most handlers, including DTD related call-backs,\r
+   except when parsing an external parameter entity and resumable != 0.\r
+   Returns XML_STATUS_OK when successful, XML_STATUS_ERROR otherwise.\r
+   Possible error codes: \r
+   - XML_ERROR_SUSPENDED: when suspending an already suspended parser.\r
+   - XML_ERROR_FINISHED: when the parser has already finished.\r
+   - XML_ERROR_SUSPEND_PE: when suspending while parsing an external PE.\r
+\r
+   When resumable != 0 (true) then parsing is suspended, that is, \r
+   XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED. \r
+   Otherwise, parsing is aborted, that is, XML_Parse() and XML_ParseBuffer()\r
+   return XML_STATUS_ERROR with error code XML_ERROR_ABORTED.\r
+\r
+   *Note*:\r
+   This will be applied to the current parser instance only, that is, if\r
+   there is a parent parser then it will continue parsing when the\r
+   externalEntityRefHandler() returns. It is up to the implementation of\r
+   the externalEntityRefHandler() to call XML_StopParser() on the parent\r
+   parser (recursively), if one wants to stop parsing altogether.\r
+\r
+   When suspended, parsing can be resumed by calling XML_ResumeParser(). \r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_StopParser(XML_Parser parser, XML_Bool resumable);\r
+\r
+/* Resumes parsing after it has been suspended with XML_StopParser().\r
+   Must not be called from within a handler call-back. Returns same\r
+   status codes as XML_Parse() or XML_ParseBuffer().\r
+   Additional error code XML_ERROR_NOT_SUSPENDED possible.   \r
+\r
+   *Note*:\r
+   This must be called on the most deeply nested child parser instance\r
+   first, and on its parent parser only after the child parser has finished,\r
+   to be applied recursively until the document entity's parser is restarted.\r
+   That is, the parent parser will not resume by itself and it is up to the\r
+   application to call XML_ResumeParser() on it at the appropriate moment.\r
+*/\r
+XMLPARSEAPI(enum XML_Status)\r
+XML_ResumeParser(XML_Parser parser);\r
+\r
+enum XML_Parsing {\r
+  XML_INITIALIZED,\r
+  XML_PARSING,\r
+  XML_FINISHED,\r
+  XML_SUSPENDED\r
+};\r
+\r
+typedef struct {\r
+  enum XML_Parsing parsing;\r
+  XML_Bool finalBuffer;\r
+} XML_ParsingStatus;\r
+\r
+/* Returns status of parser with respect to being initialized, parsing,\r
+   finished, or suspended and processing the final buffer.\r
+   XXX XML_Parse() and XML_ParseBuffer() should return XML_ParsingStatus,\r
+   XXX with XML_FINISHED_OK or XML_FINISHED_ERROR replacing XML_FINISHED\r
+*/\r
+XMLPARSEAPI(void)\r
+XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status);\r
+\r
+/* Creates an XML_Parser object that can parse an external general\r
+   entity; context is a '\0'-terminated string specifying the parse\r
+   context; encoding is a '\0'-terminated string giving the name of\r
+   the externally specified encoding, or NULL if there is no\r
+   externally specified encoding.  The context string consists of a\r
+   sequence of tokens separated by formfeeds (\f); a token consisting\r
+   of a name specifies that the general entity of the name is open; a\r
+   token of the form prefix=uri specifies the namespace for a\r
+   particular prefix; a token of the form =uri specifies the default\r
+   namespace.  This can be called at any point after the first call to\r
+   an ExternalEntityRefHandler so longer as the parser has not yet\r
+   been freed.  The new parser is completely independent and may\r
+   safely be used in a separate thread.  The handlers and userData are\r
+   initialized from the parser argument.  Returns NULL if out of memory.\r
+   Otherwise returns a new XML_Parser object.\r
+*/\r
+XMLPARSEAPI(XML_Parser)\r
+XML_ExternalEntityParserCreate(XML_Parser parser,\r
+                               const XML_Char *context,\r
+                               const XML_Char *encoding);\r
+\r
+enum XML_ParamEntityParsing {\r
+  XML_PARAM_ENTITY_PARSING_NEVER,\r
+  XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE,\r
+  XML_PARAM_ENTITY_PARSING_ALWAYS\r
+};\r
+\r
+/* Controls parsing of parameter entities (including the external DTD\r
+   subset). If parsing of parameter entities is enabled, then\r
+   references to external parameter entities (including the external\r
+   DTD subset) will be passed to the handler set with\r
+   XML_SetExternalEntityRefHandler.  The context passed will be 0.\r
+\r
+   Unlike external general entities, external parameter entities can\r
+   only be parsed synchronously.  If the external parameter entity is\r
+   to be parsed, it must be parsed during the call to the external\r
+   entity ref handler: the complete sequence of\r
+   XML_ExternalEntityParserCreate, XML_Parse/XML_ParseBuffer and\r
+   XML_ParserFree calls must be made during this call.  After\r
+   XML_ExternalEntityParserCreate has been called to create the parser\r
+   for the external parameter entity (context must be 0 for this\r
+   call), it is illegal to make any calls on the old parser until\r
+   XML_ParserFree has been called on the newly created parser.\r
+   If the library has been compiled without support for parameter\r
+   entity parsing (ie without XML_DTD being defined), then\r
+   XML_SetParamEntityParsing will return 0 if parsing of parameter\r
+   entities is requested; otherwise it will return non-zero.\r
+   Note: If XML_SetParamEntityParsing is called after XML_Parse or\r
+      XML_ParseBuffer, then it has no effect and will always return 0.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_SetParamEntityParsing(XML_Parser parser,\r
+                          enum XML_ParamEntityParsing parsing);\r
+\r
+/* If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then\r
+   XML_GetErrorCode returns information about the error.\r
+*/\r
+XMLPARSEAPI(enum XML_Error)\r
+XML_GetErrorCode(XML_Parser parser);\r
+\r
+/* These functions return information about the current parse\r
+   location.  They may be called from any callback called to report\r
+   some parse event; in this case the location is the location of the\r
+   first of the sequence of characters that generated the event.  When\r
+   called from callbacks generated by declarations in the document\r
+   prologue, the location identified isn't as neatly defined, but will\r
+   be within the relevant markup.  When called outside of the callback\r
+   functions, the position indicated will be just past the last parse\r
+   event (regardless of whether there was an associated callback).\r
+   \r
+   They may also be called after returning from a call to XML_Parse\r
+   or XML_ParseBuffer.  If the return value is XML_STATUS_ERROR then\r
+   the location is the location of the character at which the error\r
+   was detected; otherwise the location is the location of the last\r
+   parse event, as described above.\r
+*/\r
+XMLPARSEAPI(XML_Size) XML_GetCurrentLineNumber(XML_Parser parser);\r
+XMLPARSEAPI(XML_Size) XML_GetCurrentColumnNumber(XML_Parser parser);\r
+XMLPARSEAPI(XML_Index) XML_GetCurrentByteIndex(XML_Parser parser);\r
+\r
+/* Return the number of bytes in the current event.\r
+   Returns 0 if the event is in an internal entity.\r
+*/\r
+XMLPARSEAPI(int)\r
+XML_GetCurrentByteCount(XML_Parser parser);\r
+\r
+/* If XML_CONTEXT_BYTES is defined, returns the input buffer, sets\r
+   the integer pointed to by offset to the offset within this buffer\r
+   of the current parse position, and sets the integer pointed to by size\r
+   to the size of this buffer (the number of input bytes). Otherwise\r
+   returns a NULL pointer. Also returns a NULL pointer if a parse isn't\r
+   active.\r
+\r
+   NOTE: The character pointer returned should not be used outside\r
+   the handler that makes the call.\r
+*/\r
+XMLPARSEAPI(const char *)\r
+XML_GetInputContext(XML_Parser parser,\r
+                    int *offset,\r
+                    int *size);\r
+\r
+/* For backwards compatibility with previous versions. */\r
+#define XML_GetErrorLineNumber   XML_GetCurrentLineNumber\r
+#define XML_GetErrorColumnNumber XML_GetCurrentColumnNumber\r
+#define XML_GetErrorByteIndex    XML_GetCurrentByteIndex\r
+\r
+/* Frees the content model passed to the element declaration handler */\r
+XMLPARSEAPI(void)\r
+XML_FreeContentModel(XML_Parser parser, XML_Content *model);\r
+\r
+/* Exposing the memory handling functions used in Expat */\r
+XMLPARSEAPI(void *)\r
+XML_MemMalloc(XML_Parser parser, size_t size);\r
+\r
+XMLPARSEAPI(void *)\r
+XML_MemRealloc(XML_Parser parser, void *ptr, size_t size);\r
+\r
+XMLPARSEAPI(void)\r
+XML_MemFree(XML_Parser parser, void *ptr);\r
+\r
+/* Frees memory used by the parser. */\r
+XMLPARSEAPI(void)\r
+XML_ParserFree(XML_Parser parser);\r
+\r
+/* Returns a string describing the error. */\r
+XMLPARSEAPI(const XML_LChar *)\r
+XML_ErrorString(enum XML_Error code);\r
+\r
+/* Return a string containing the version number of this expat */\r
+XMLPARSEAPI(const XML_LChar *)\r
+XML_ExpatVersion(void);\r
+\r
+typedef struct {\r
+  int major;\r
+  int minor;\r
+  int micro;\r
+} XML_Expat_Version;\r
+\r
+/* Return an XML_Expat_Version structure containing numeric version\r
+   number information for this version of expat.\r
+*/\r
+XMLPARSEAPI(XML_Expat_Version)\r
+XML_ExpatVersionInfo(void);\r
+\r
+/* Added in Expat 1.95.5. */\r
+enum XML_FeatureEnum {\r
+  XML_FEATURE_END = 0,\r
+  XML_FEATURE_UNICODE,\r
+  XML_FEATURE_UNICODE_WCHAR_T,\r
+  XML_FEATURE_DTD,\r
+  XML_FEATURE_CONTEXT_BYTES,\r
+  XML_FEATURE_MIN_SIZE,\r
+  XML_FEATURE_SIZEOF_XML_CHAR,\r
+  XML_FEATURE_SIZEOF_XML_LCHAR,\r
+  XML_FEATURE_NS,\r
+  XML_FEATURE_LARGE_SIZE\r
+  /* Additional features must be added to the end of this enum. */\r
+};\r
+\r
+typedef struct {\r
+  enum XML_FeatureEnum  feature;\r
+  const XML_LChar       *name;\r
+  long int              value;\r
+} XML_Feature;\r
+\r
+XMLPARSEAPI(const XML_Feature *)\r
+XML_GetFeatureList(void);\r
+\r
+\r
+/* Expat follows the GNU/Linux convention of odd number minor version for\r
+   beta/development releases and even number minor version for stable\r
+   releases. Micro is bumped with each release, and set to 0 with each\r
+   change to major or minor version.\r
+*/\r
+#define XML_MAJOR_VERSION 2\r
+#define XML_MINOR_VERSION 0\r
+#define XML_MICRO_VERSION 1\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* not Expat_INCLUDED */\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat.lib b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat.lib
new file mode 100644 (file)
index 0000000..08ee750
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat.lib differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat_external.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/expat_external.h
new file mode 100644 (file)
index 0000000..bb83a99
--- /dev/null
@@ -0,0 +1,115 @@
+/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd\r
+   See the file COPYING for copying permission.\r
+*/\r
+\r
+#ifndef Expat_External_INCLUDED\r
+#define Expat_External_INCLUDED 1\r
+\r
+/* External API definitions */\r
+\r
+#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)\r
+#define XML_USE_MSC_EXTENSIONS 1\r
+#endif\r
+\r
+/* Expat tries very hard to make the API boundary very specifically\r
+   defined.  There are two macros defined to control this boundary;\r
+   each of these can be defined before including this header to\r
+   achieve some different behavior, but doing so it not recommended or\r
+   tested frequently.\r
+\r
+   XMLCALL    - The calling convention to use for all calls across the\r
+                "library boundary."  This will default to cdecl, and\r
+                try really hard to tell the compiler that's what we\r
+                want.\r
+\r
+   XMLIMPORT  - Whatever magic is needed to note that a function is\r
+                to be imported from a dynamically loaded library\r
+                (.dll, .so, or .sl, depending on your platform).\r
+\r
+   The XMLCALL macro was added in Expat 1.95.7.  The only one which is\r
+   expected to be directly useful in client code is XMLCALL.\r
+\r
+   Note that on at least some Unix versions, the Expat library must be\r
+   compiled with the cdecl calling convention as the default since\r
+   system headers may assume the cdecl convention.\r
+*/\r
+#ifndef XMLCALL\r
+#if defined(_MSC_VER)\r
+#define XMLCALL __cdecl\r
+#elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)\r
+#define XMLCALL __attribute__((cdecl))\r
+#else\r
+/* For any platform which uses this definition and supports more than\r
+   one calling convention, we need to extend this definition to\r
+   declare the convention used on that platform, if it's possible to\r
+   do so.\r
+\r
+   If this is the case for your platform, please file a bug report\r
+   with information on how to identify your platform via the C\r
+   pre-processor and how to specify the same calling convention as the\r
+   platform's malloc() implementation.\r
+*/\r
+#define XMLCALL\r
+#endif\r
+#endif  /* not defined XMLCALL */\r
+\r
+\r
+#if !defined(XML_STATIC) && !defined(XMLIMPORT)\r
+#ifndef XML_BUILDING_EXPAT\r
+/* using Expat from an application */\r
+\r
+#ifdef XML_USE_MSC_EXTENSIONS\r
+#define XMLIMPORT __declspec(dllimport)\r
+#endif\r
+\r
+#endif\r
+#endif  /* not defined XML_STATIC */\r
+\r
+\r
+/* If we didn't define it above, define it away: */\r
+#ifndef XMLIMPORT\r
+#define XMLIMPORT\r
+#endif\r
+\r
+\r
+#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#ifdef XML_UNICODE_WCHAR_T\r
+#define XML_UNICODE\r
+#endif\r
+\r
+#ifdef XML_UNICODE     /* Information is UTF-16 encoded. */\r
+#ifdef XML_UNICODE_WCHAR_T\r
+typedef wchar_t XML_Char;\r
+typedef wchar_t XML_LChar;\r
+#else\r
+typedef unsigned short XML_Char;\r
+typedef char XML_LChar;\r
+#endif /* XML_UNICODE_WCHAR_T */\r
+#else                  /* Information is UTF-8 encoded. */\r
+typedef char XML_Char;\r
+typedef char XML_LChar;\r
+#endif /* XML_UNICODE */\r
+\r
+#ifdef XML_LARGE_SIZE  /* Use large integers for file/stream positions. */\r
+#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400\r
+typedef __int64 XML_Index; \r
+typedef unsigned __int64 XML_Size;\r
+#else\r
+typedef long long XML_Index;\r
+typedef unsigned long long XML_Size;\r
+#endif\r
+#else\r
+typedef long XML_Index;\r
+typedef unsigned long XML_Size;\r
+#endif /* XML_LARGE_SIZE */\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* not Expat_External_INCLUDED */\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmiModelFunctions.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmiModelFunctions.h
new file mode 100644 (file)
index 0000000..e204772
--- /dev/null
@@ -0,0 +1,210 @@
+#ifndef fmiModelFunctions_h\r
+#define fmiModelFunctions_h\r
+\r
+/* This header file must be utilized when compiling a model.\r
+   It defines all functions of the Model Execution Interface.\r
+   In order to have unique function names even if several models\r
+   are compiled together (e.g. for embedded systems), every "real" function name\r
+   is constructed by prepending the function name by\r
+   "MODEL_IDENTIFIER" + "_" where "MODEL_IDENTIFIER" is the short name\r
+   of the model used as the name of the zip-file where the model is stored.\r
+   Therefore, the typical usage is:\r
+\r
+      #define MODEL_IDENTIFIER MyModel\r
+      #include "fmiModelFunctions.h"\r
+\r
+   As a result, a function that is defined as "fmiGetDerivatives" in this header file,\r
+   is actually getting the name "MyModel_fmiGetDerivatives".\r
+\r
+   Revisions:\r
+   - Jan. 20, 2010: stateValueReferencesChanged added to struct fmiEventInfo (ticket #27)\r
+                    (by M. Otter, DLR)\r
+                    Added WIN32 pragma to define the struct layout (ticket #34)\r
+                    (by J. Mauss, QTronic)\r
+   - Jan.  4, 2010: Removed argument intermediateResults from fmiInitialize\r
+                    Renamed macro fmiGetModelFunctionsVersion to fmiGetVersion\r
+                    Renamed macro fmiModelFunctionsVersion to fmiVersion\r
+                    Replaced fmiModel by fmiComponent in decl of fmiInstantiateModel\r
+                    (by J. Mauss, QTronic)\r
+   - Dec. 17, 2009: Changed extension "me" to "fmi" (by Martin Otter, DLR).\r
+   - Dez. 14, 2009: Added eventInfo to meInitialize and added\r
+                    meGetNominalContinuousStates (by Martin Otter, DLR)\r
+   - Sept. 9, 2009: Added DllExport (according to Peter Nilsson's suggestion)\r
+                    (by A. Junghanns, QTronic)\r
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:\r
+                    meInquireModelTypesVersion     -> meGetModelTypesPlatform\r
+                    meInquireModelFunctionsVersion -> meGetModelFunctionsVersion\r
+                    meSetStates                    -> meSetContinuousStates\r
+                    meGetStates                    -> meGetContinuousStates\r
+                    removal of meInitializeModelClass\r
+                    removal of meGetTime\r
+                    change of arguments of meInstantiateModel\r
+                    change of arguments of meCompletedIntegratorStep\r
+                    (by Martin Otter, DLR):\r
+   - July 19, 2009: Added "me" as prefix to file names (by Martin Otter, DLR).\r
+   - March 2, 2009: Changed function definitions according to the last design\r
+                    meeting with additional improvements (by Martin Otter, DLR).\r
+   - Dec. 3 , 2008: First version by Martin Otter (DLR) and Hans Olsson (Dynasim).\r
+\r
+\r
+   Copyright Â© 2008-2009, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html):\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+\r
+   with the extension:\r
+\r
+   You may distribute or publicly perform any modification only under the\r
+   terms of this license.\r
+*/\r
+\r
+#include "fmiModelTypes.h"\r
+#include <stdlib.h>\r
+\r
+/* Export fmi functions on Windows */\r
+#ifdef _MSC_VER\r
+#define DllExport __declspec( dllexport )\r
+#else\r
+#define DllExport\r
+#endif\r
+\r
+/* Macros to construct the real function name\r
+   (prepend function name by MODEL_IDENTIFIER + "_") */\r
+\r
+#define fmiPaste(a,b)     a ## b\r
+#define fmiPasteB(a,b)    fmiPaste(a,b)\r
+#define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name)\r
+\r
+#define fmiGetModelTypesPlatform      fmiFullName(_fmiGetModelTypesPlatform)\r
+#define fmiGetVersion                 fmiFullName(_fmiGetVersion)\r
+#define fmiInstantiateModel           fmiFullName(_fmiInstantiateModel)\r
+#define fmiFreeModelInstance          fmiFullName(_fmiFreeModelInstance)\r
+#define fmiSetDebugLogging            fmiFullName(_fmiSetDebugLogging)\r
+#define fmiSetTime                    fmiFullName(_fmiSetTime)\r
+#define fmiSetContinuousStates        fmiFullName(_fmiSetContinuousStates)\r
+#define fmiCompletedIntegratorStep    fmiFullName(_fmiCompletedIntegratorStep)\r
+#define fmiSetReal                    fmiFullName(_fmiSetReal)\r
+#define fmiSetInteger                 fmiFullName(_fmiSetInteger)\r
+#define fmiSetBoolean                 fmiFullName(_fmiSetBoolean)\r
+#define fmiSetString                  fmiFullName(_fmiSetString)\r
+#define fmiInitialize                 fmiFullName(_fmiInitialize)\r
+#define fmiGetDerivatives             fmiFullName(_fmiGetDerivatives)\r
+#define fmiGetEventIndicators         fmiFullName(_fmiGetEventIndicators)\r
+#define fmiGetReal                    fmiFullName(_fmiGetReal)\r
+#define fmiGetInteger                 fmiFullName(_fmiGetInteger)\r
+#define fmiGetBoolean                 fmiFullName(_fmiGetBoolean)\r
+#define fmiGetString                  fmiFullName(_fmiGetString)\r
+#define fmiEventUpdate                fmiFullName(_fmiEventUpdate)\r
+#define fmiGetContinuousStates        fmiFullName(_fmiGetContinuousStates)\r
+#define fmiGetNominalContinuousStates fmiFullName(_fmiGetNominalContinuousStates)\r
+#define fmiGetStateValueReferences    fmiFullName(_fmiGetStateValueReferences)\r
+#define fmiTerminate                  fmiFullName(_fmiTerminate)\r
+\r
+\r
+/* Version number */\r
+#define fmiVersion "1.0"\r
+\r
+/* Inquire version numbers of header files */\r
+   DllExport const char* fmiGetModelTypesPlatform();\r
+   DllExport const char* fmiGetVersion();\r
+\r
+/* make sure all compiler use the same alignment policies for structures */\r
+#ifdef WIN32\r
+#pragma pack(push,8)\r
+#endif\r
+\r
+/* Type definitions */\r
+   typedef enum  {fmiOK,\r
+                  fmiWarning,\r
+                  fmiDiscard,\r
+                  fmiError,\r
+                  fmiFatal} fmiStatus;\r
+\r
+   typedef void  (*fmiCallbackLogger)        (fmiComponent c, fmiString instanceName, fmiStatus status,\r
+                                              fmiString category, fmiString message, ...);\r
+   typedef void* (*fmiCallbackAllocateMemory)(size_t nobj, size_t size);\r
+   typedef void  (*fmiCallbackFreeMemory)    (void* obj);\r
+\r
+   typedef struct {\r
+     fmiCallbackLogger         logger;\r
+     fmiCallbackAllocateMemory allocateMemory;\r
+     fmiCallbackFreeMemory     freeMemory;\r
+   } fmiCallbackFunctions;\r
+\r
+   typedef struct {\r
+      fmiBoolean iterationConverged;\r
+      fmiBoolean stateValueReferencesChanged;\r
+      fmiBoolean stateValuesChanged;\r
+      fmiBoolean terminateSimulation;\r
+      fmiBoolean upcomingTimeEvent;\r
+      fmiReal    nextEventTime;\r
+   } fmiEventInfo;\r
+\r
+/* reset alignment policy to the one set before reading this file */\r
+#ifdef WIN32\r
+#pragma pack(pop)\r
+#endif\r
+\r
+/* Creation and destruction of model instances and setting debug status */\r
+   DllExport fmiComponent fmiInstantiateModel (fmiString            instanceName,\r
+                                               fmiString            GUID,\r
+                                               fmiCallbackFunctions functions,\r
+                                               fmiBoolean           loggingOn);\r
+   DllExport void      fmiFreeModelInstance(fmiComponent c);\r
+   DllExport fmiStatus fmiSetDebugLogging  (fmiComponent c, fmiBoolean loggingOn);\r
+\r
+\r
+/* Providing independent variables and re-initialization of caching */\r
+   DllExport fmiStatus fmiSetTime                (fmiComponent c, fmiReal time);\r
+   DllExport fmiStatus fmiSetContinuousStates    (fmiComponent c, const fmiReal x[], size_t nx);\r
+   DllExport fmiStatus fmiCompletedIntegratorStep(fmiComponent c, fmiBoolean* callEventUpdate);\r
+   DllExport fmiStatus fmiSetReal                (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+   DllExport fmiStatus fmiSetInteger             (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+   DllExport fmiStatus fmiSetBoolean             (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+   DllExport fmiStatus fmiSetString              (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+\r
+\r
+/* Evaluation of the model equations */\r
+   DllExport fmiStatus fmiInitialize(fmiComponent c, fmiBoolean toleranceControlled,\r
+                                     fmiReal relativeTolerance, fmiEventInfo* eventInfo);\r
+\r
+   DllExport fmiStatus fmiGetDerivatives    (fmiComponent c, fmiReal derivatives[]    , size_t nx);\r
+   DllExport fmiStatus fmiGetEventIndicators(fmiComponent c, fmiReal eventIndicators[], size_t ni);\r
+\r
+   DllExport fmiStatus fmiGetReal   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+   DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+   DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+   DllExport fmiStatus fmiGetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+\r
+   DllExport fmiStatus fmiEventUpdate               (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo);\r
+   DllExport fmiStatus fmiGetContinuousStates       (fmiComponent c, fmiReal states[], size_t nx);\r
+   DllExport fmiStatus fmiGetNominalContinuousStates(fmiComponent c, fmiReal x_nominal[], size_t nx);\r
+   DllExport fmiStatus fmiGetStateValueReferences   (fmiComponent c, fmiValueReference vrx[], size_t nx);\r
+   DllExport fmiStatus fmiTerminate                 (fmiComponent c);\r
+\r
+#endif // fmiModelFunctions_h\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmiModelTypes.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmiModelTypes.h
new file mode 100644 (file)
index 0000000..17e9e30
--- /dev/null
@@ -0,0 +1,91 @@
+#ifndef fmiModelTypes_h\r
+#define fmiModelTypes_h\r
+\r
+/* Standard header file to define the argument types of the\r
+   functions of the Model Execution Interface.\r
+   This header file must be utilized both by the model and\r
+   by the simulation engine.\r
+\r
+   Revisions:\r
+   - Jan.  4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)\r
+   - Dec. 21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"\r
+                    according to meeting on Dec. 18 (by Martin Otter, DLR)\r
+   - Dec.  6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)\r
+   - Sept. 9, 2009: Changes according to FMI-meeting on July 21:\r
+                    Changed "version" to "platform", "standard" to "standard32",\r
+                    Added a precise definition of "standard32" as comment\r
+                    (by Martin Otter, DLR)\r
+   - July 19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,\r
+                    and changed meValueReferenced from int to unsigned int\r
+                    (by Martin Otter, DLR).\r
+   - March 2, 2009: Moved enums and function pointer definitions to\r
+                    ModelFunctions.h (by Martin Otter, DLR).\r
+   - Dec. 3, 2008 : First version by Martin Otter (DLR) and\r
+                    Hans Olsson (Dynasim).\r
+\r
+\r
+   Copyright Â© 2008-2010, MODELISAR consortium. All rights reserved.\r
+   This file is licensed by the copyright holders under the BSD License\r
+   (http://www.opensource.org/licenses/bsd-license.html)\r
+\r
+   ----------------------------------------------------------------------------\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   - Redistributions of source code must retain the above copyright notice,\r
+     this list of conditions and the following disclaimer.\r
+   - Redistributions in binary form must reproduce the above copyright notice,\r
+     this list of conditions and the following disclaimer in the documentation\r
+     and/or other materials provided with the distribution.\r
+   - Neither the name of the copyright holders nor the names of its\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r
+   TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
+   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r
+   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\r
+   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
+   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+   ----------------------------------------------------------------------------\r
+\r
+   with the extension:\r
+\r
+   You may distribute or publicly perform any modification only under the\r
+   terms of this license.\r
+*/\r
+\r
+/* Platform (combination of machine, compiler, operating system) */\r
+#define fmiModelTypesPlatform "standard32"\r
+\r
+/* Type definitions of variables passed as arguments\r
+   Version "standard32" means:\r
+\r
+   fmiComponent     : 32 bit pointer\r
+   fmiValueReference: 32 bit\r
+   fmiReal          : 64 bit\r
+   fmiInteger       : 32 bit\r
+   fmiBoolean       :  8 bit\r
+   fmiString        : 32 bit pointer\r
+\r
+*/\r
+   typedef void*        fmiComponent;\r
+   typedef unsigned int fmiValueReference;\r
+   typedef double       fmiReal   ;\r
+   typedef int          fmiInteger;\r
+   typedef char         fmiBoolean;\r
+   typedef const char*  fmiString ;\r
+\r
+/* Values for fmiBoolean  */\r
+#define fmiTrue  1\r
+#define fmiFalse 0\r
+\r
+/* Undefined value for fmiValueReference (largest unsigned int value) */\r
+#define fmiUndefinedValueReference (fmiValueReference)(-1)\r
+\r
+#endif\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmi_me.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/fmi_me.h
new file mode 100644 (file)
index 0000000..f115245
--- /dev/null
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------------- \r
+ * fmi_me.h\r
+ * Function types for all function of the "FMI for Model Exchange 1.0"\r
+ * and a struct with the corresponding function pointers. \r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#ifndef FMI_ME_H\r
+#define FMI_ME_H\r
+\r
+#include <windows.h>\r
+#include "fmiModelFunctions.h"\r
+#include "xml_parser.h"\r
+\r
+typedef const char* (*fGetModelTypesPlatform)();\r
+typedef const char* (*fGetVersion)();\r
+typedef fmiComponent (*fInstantiateModel)(fmiString instanceName, fmiString GUID,\r
+                                        fmiCallbackFunctions functions, fmiBoolean loggingOn);\r
+typedef void      (*fFreeModelInstance)  (fmiComponent c);\r
+typedef fmiStatus (*fSetDebugLogging)    (fmiComponent c, fmiBoolean loggingOn);\r
+typedef fmiStatus (*fSetTime)            (fmiComponent c, fmiReal time);\r
+typedef fmiStatus (*fSetContinuousStates)(fmiComponent c, const fmiReal x[], size_t nx);\r
+typedef fmiStatus (*fCompletedIntegratorStep)(fmiComponent c, fmiBoolean* callEventUpdate);\r
+typedef fmiStatus (*fSetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal    value[]);\r
+typedef fmiStatus (*fSetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]);\r
+typedef fmiStatus (*fSetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]);\r
+typedef fmiStatus (*fSetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString  value[]);\r
+typedef fmiStatus (*fInitialize)(fmiComponent c, fmiBoolean toleranceControlled, \r
+                               fmiReal relativeTolerance, fmiEventInfo* eventInfo);\r
+typedef fmiStatus (*fGetDerivatives)    (fmiComponent c, fmiReal derivatives[]    , size_t nx);\r
+typedef fmiStatus (*fGetEventIndicators)(fmiComponent c, fmiReal eventIndicators[], size_t ni);\r
+typedef fmiStatus (*fGetReal)   (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal    value[]);\r
+typedef fmiStatus (*fGetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]);\r
+typedef fmiStatus (*fGetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]);\r
+typedef fmiStatus (*fGetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString  value[]);\r
+typedef fmiStatus (*fEventUpdate)               (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo);\r
+typedef fmiStatus (*fGetContinuousStates)       (fmiComponent c, fmiReal states[], size_t nx);\r
+typedef fmiStatus (*fGetNominalContinuousStates)(fmiComponent c, fmiReal x_nominal[], size_t nx);\r
+typedef fmiStatus (*fGetStateValueReferences)   (fmiComponent c, fmiValueReference vrx[], size_t nx);\r
+typedef fmiStatus (*fTerminate)                 (fmiComponent c);    \r
+\r
+typedef struct {\r
+    ModelDescription* modelDescription;\r
+    HANDLE dllHandle;\r
+    fGetModelTypesPlatform getModelTypesPlatform;\r
+    fGetVersion getVersion;\r
+    fInstantiateModel instantiateModel;\r
+    fFreeModelInstance freeModelInstance;\r
+    fSetDebugLogging setDebugLogging;\r
+    fSetTime setTime;\r
+    fSetContinuousStates setContinuousStates;\r
+    fCompletedIntegratorStep completedIntegratorStep;\r
+    fSetReal setReal;\r
+    fSetInteger setInteger;\r
+    fSetBoolean setBoolean;\r
+    fSetString setString;\r
+    fInitialize initialize;\r
+    fGetDerivatives getDerivatives;\r
+    fGetEventIndicators getEventIndicators;\r
+    fGetReal getReal;\r
+    fGetInteger getInteger;\r
+    fGetBoolean getBoolean;\r
+    fGetString getString;\r
+    fEventUpdate eventUpdate;\r
+    fGetContinuousStates getContinuousStates;\r
+    fGetNominalContinuousStates getNominalContinuousStates;\r
+    fGetStateValueReferences getStateValueReferences;\r
+    fTerminate terminate; \r
+/*   \r
+    fInstantiateSlave instantiateSlave;\r
+    fInitializeSlave initializeSlave;\r
+    fTerminateSlave terminateSlave;\r
+    fResetSlave resetSlave;\r
+    fFreeSlaveInstance freeSlaveInstance;\r
+    fGetRealOutputDerivatives getRealOutputDerivatives;\r
+    fSetRealInputDerivatives setRealInputDerivatives;\r
+    fDoStep doStep;\r
+    fCancelStep cancelStep;\r
+    fGetStatus getStatus;\r
+    fGetRealStatus getRealStatus;\r
+    fGetIntegerStatus getIntegerStatus;\r
+    fGetBooleanStatus getBooleanStatus;\r
+    fGetStringStatus getStringStatus;\r
+*/\r
+} FMU;\r
+\r
+#endif // FMI_ME_H\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inffixed.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inffixed.h
new file mode 100644 (file)
index 0000000..d628327
--- /dev/null
@@ -0,0 +1,94 @@
+    /* inffixed.h -- table for decoding fixed codes
+     * Generated automatically by makefixed().
+     */
+
+    /* WARNING: this file should *not* be used by applications.
+       It is part of the implementation of this library and is
+       subject to change. Applications should only use zlib.h.
+     */
+
+    static const code lenfix[512] = {
+        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
+        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
+        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
+        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
+        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
+        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
+        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
+        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
+        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
+        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
+        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
+        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
+        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
+        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
+        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
+        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
+        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
+        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
+        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
+        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
+        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
+        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
+        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
+        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
+        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
+        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
+        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
+        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
+        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
+        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
+        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
+        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
+        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
+        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
+        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
+        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
+        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
+        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
+        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
+        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
+        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
+        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
+        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
+        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
+        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
+        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
+        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
+        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
+        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
+        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
+        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
+        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
+        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
+        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
+        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
+        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
+        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
+        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
+        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
+        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
+        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
+        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
+        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
+        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
+        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
+        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
+        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
+        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
+        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
+        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
+        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
+        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
+        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
+        {0,9,255}
+    };
+
+    static const code distfix[32] = {
+        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
+        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
+        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
+        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
+        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
+        {22,5,193},{64,5,0}
+    };
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inflate.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inflate.h
new file mode 100644 (file)
index 0000000..95f4986
--- /dev/null
@@ -0,0 +1,122 @@
+/* inflate.h -- internal inflate state definition
+ * Copyright (C) 1995-2009 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* define NO_GZIP when compiling if you want to disable gzip header and
+   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in
+   the crc code when it is not needed.  For shared libraries, gzip decoding
+   should be left enabled. */
+#ifndef NO_GZIP
+#  define GUNZIP
+#endif
+
+/* Possible inflate modes between inflate() calls */
+typedef enum {
+    HEAD,       /* i: waiting for magic header */
+    FLAGS,      /* i: waiting for method and flags (gzip) */
+    TIME,       /* i: waiting for modification time (gzip) */
+    OS,         /* i: waiting for extra flags and operating system (gzip) */
+    EXLEN,      /* i: waiting for extra length (gzip) */
+    EXTRA,      /* i: waiting for extra bytes (gzip) */
+    NAME,       /* i: waiting for end of file name (gzip) */
+    COMMENT,    /* i: waiting for end of comment (gzip) */
+    HCRC,       /* i: waiting for header crc (gzip) */
+    DICTID,     /* i: waiting for dictionary check value */
+    DICT,       /* waiting for inflateSetDictionary() call */
+        TYPE,       /* i: waiting for type bits, including last-flag bit */
+        TYPEDO,     /* i: same, but skip check to exit inflate on new block */
+        STORED,     /* i: waiting for stored size (length and complement) */
+        COPY_,      /* i/o: same as COPY below, but only first time in */
+        COPY,       /* i/o: waiting for input or output to copy stored block */
+        TABLE,      /* i: waiting for dynamic block table lengths */
+        LENLENS,    /* i: waiting for code length code lengths */
+        CODELENS,   /* i: waiting for length/lit and distance code lengths */
+            LEN_,       /* i: same as LEN below, but only first time in */
+            LEN,        /* i: waiting for length/lit/eob code */
+            LENEXT,     /* i: waiting for length extra bits */
+            DIST,       /* i: waiting for distance code */
+            DISTEXT,    /* i: waiting for distance extra bits */
+            MATCH,      /* o: waiting for output space to copy string */
+            LIT,        /* o: waiting for output space to write literal */
+    CHECK,      /* i: waiting for 32-bit check value */
+    LENGTH,     /* i: waiting for 32-bit length (gzip) */
+    DONE,       /* finished check, done -- remain here until reset */
+    BAD,        /* got a data error -- remain here until reset */
+    MEM,        /* got an inflate() memory error -- remain here until reset */
+    SYNC        /* looking for synchronization bytes to restart inflate() */
+} inflate_mode;
+
+/*
+    State transitions between above modes -
+
+    (most modes can go to BAD or MEM on error -- not shown for clarity)
+
+    Process header:
+        HEAD -> (gzip) or (zlib) or (raw)
+        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
+                  HCRC -> TYPE
+        (zlib) -> DICTID or TYPE
+        DICTID -> DICT -> TYPE
+        (raw) -> TYPEDO
+    Read deflate blocks:
+            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
+            STORED -> COPY_ -> COPY -> TYPE
+            TABLE -> LENLENS -> CODELENS -> LEN_
+            LEN_ -> LEN
+    Read deflate codes in fixed or dynamic block:
+                LEN -> LENEXT or LIT or TYPE
+                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
+                LIT -> LEN
+    Process trailer:
+        CHECK -> LENGTH -> DONE
+ */
+
+/* state maintained between inflate() calls.  Approximately 10K bytes. */
+struct inflate_state {
+    inflate_mode mode;          /* current inflate mode */
+    int last;                   /* true if processing last block */
+    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip */
+    int havedict;               /* true if dictionary provided */
+    int flags;                  /* gzip header method and flags (0 if zlib) */
+    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */
+    unsigned long check;        /* protected copy of check value */
+    unsigned long total;        /* protected copy of output count */
+    gz_headerp head;            /* where to save gzip header information */
+        /* sliding window */
+    unsigned wbits;             /* log base 2 of requested window size */
+    unsigned wsize;             /* window size or zero if not using window */
+    unsigned whave;             /* valid bytes in the window */
+    unsigned wnext;             /* window write index */
+    unsigned char FAR *window;  /* allocated sliding window, if needed */
+        /* bit accumulator */
+    unsigned long hold;         /* input bit accumulator */
+    unsigned bits;              /* number of bits in "in" */
+        /* for string and stored block copying */
+    unsigned length;            /* literal or length of data to copy */
+    unsigned offset;            /* distance back to copy string from */
+        /* for table and code decoding */
+    unsigned extra;             /* extra bits needed */
+        /* fixed and dynamic code tables */
+    code const FAR *lencode;    /* starting table for length/literal codes */
+    code const FAR *distcode;   /* starting table for distance codes */
+    unsigned lenbits;           /* index bits for lencode */
+    unsigned distbits;          /* index bits for distcode */
+        /* dynamic table building */
+    unsigned ncode;             /* number of code length code lengths */
+    unsigned nlen;              /* number of length code lengths */
+    unsigned ndist;             /* number of distance code lengths */
+    unsigned have;              /* number of code lengths in lens[] */
+    code FAR *next;             /* next available space in codes[] */
+    unsigned short lens[320];   /* temporary storage for code lengths */
+    unsigned short work[288];   /* work area for code table building */
+    code codes[ENOUGH];         /* space for code tables */
+    int sane;                   /* if false, allow invalid distance too far */
+    int back;                   /* bits back of last unprocessed length/lit */
+    unsigned was;               /* initial length of match */
+};
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inftrees.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/inftrees.h
new file mode 100644 (file)
index 0000000..baa53a0
--- /dev/null
@@ -0,0 +1,62 @@
+/* inftrees.h -- header to use inftrees.c
+ * Copyright (C) 1995-2005, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* Structure for decoding tables.  Each entry provides either the
+   information needed to do the operation requested by the code that
+   indexed that table entry, or it provides a pointer to another
+   table that indexes more bits of the code.  op indicates whether
+   the entry is a pointer to another table, a literal, a length or
+   distance, an end-of-block, or an invalid code.  For a table
+   pointer, the low four bits of op is the number of index bits of
+   that table.  For a length or distance, the low four bits of op
+   is the number of extra bits to get after the code.  bits is
+   the number of bits in this code or part of the code to drop off
+   of the bit buffer.  val is the actual byte to output in the case
+   of a literal, the base length or distance, or the offset from
+   the current table to the next table.  Each entry is four bytes. */
+typedef struct {
+    unsigned char op;           /* operation, extra bits, table bits */
+    unsigned char bits;         /* bits in this part of the code */
+    unsigned short val;         /* offset in table or code value */
+} code;
+
+/* op values as set by inflate_table():
+    00000000 - literal
+    0000tttt - table link, tttt != 0 is the number of table index bits
+    0001eeee - length or distance, eeee is the number of extra bits
+    01100000 - end of block
+    01000000 - invalid code
+ */
+
+/* Maximum size of the dynamic table.  The maximum number of code structures is
+   1444, which is the sum of 852 for literal/length codes and 592 for distance
+   codes.  These values were found by exhaustive searches using the program
+   examples/enough.c found in the zlib distribtution.  The arguments to that
+   program are the number of symbols, the initial root table size, and the
+   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
+   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
+   The initial root table size (9 or 6) is found in the fifth argument of the
+   inflate_table() calls in inflate.c and infback.c.  If the root table size is
+   changed, then these maximum sizes would be need to be recalculated and
+   updated. */
+#define ENOUGH_LENS 852
+#define ENOUGH_DISTS 592
+#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
+
+/* Type of code to build for inflate_table() */
+typedef enum {
+    CODES,
+    LENS,
+    DISTS
+} codetype;
+
+int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
+                             unsigned codes, code FAR * FAR *table,
+                             unsigned FAR *bits, unsigned short FAR *work));
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/jni.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/jni.h
new file mode 100644 (file)
index 0000000..8ed7366
--- /dev/null
@@ -0,0 +1,1944 @@
+/*
+ * %W% %E%
+ *
+ * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL.  Use is subject to license terms.
+ */
+
+/*
+ * We used part of Netscape's Java Runtime Interface (JRI) as the starting
+ * point of our design and implementation.
+ */
+
+/******************************************************************************
+ * Java Runtime Interface
+ * Copyright (c) 1996 Netscape Communications Corporation. All rights reserved.
+ *****************************************************************************/
+
+#ifndef _JAVASOFT_JNI_H_
+#define _JAVASOFT_JNI_H_
+
+#include <stdio.h>
+#include <stdarg.h>
+
+/* jni_md.h contains the machine-dependent typedefs for jbyte, jint
+   and jlong */
+
+#include "jni_md.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * JNI Types
+ */
+
+#ifndef JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H
+
+typedef unsigned char  jboolean;
+typedef unsigned short jchar;
+typedef short          jshort;
+typedef float          jfloat;
+typedef double         jdouble;
+
+typedef jint            jsize;
+
+#ifdef __cplusplus
+
+class _jobject {};
+class _jclass : public _jobject {};
+class _jthrowable : public _jobject {};
+class _jstring : public _jobject {};
+class _jarray : public _jobject {};
+class _jbooleanArray : public _jarray {};
+class _jbyteArray : public _jarray {};
+class _jcharArray : public _jarray {};
+class _jshortArray : public _jarray {};
+class _jintArray : public _jarray {};
+class _jlongArray : public _jarray {};
+class _jfloatArray : public _jarray {};
+class _jdoubleArray : public _jarray {};
+class _jobjectArray : public _jarray {};
+
+typedef _jobject *jobject;
+typedef _jclass *jclass;
+typedef _jthrowable *jthrowable;
+typedef _jstring *jstring;
+typedef _jarray *jarray;
+typedef _jbooleanArray *jbooleanArray;
+typedef _jbyteArray *jbyteArray;
+typedef _jcharArray *jcharArray;
+typedef _jshortArray *jshortArray;
+typedef _jintArray *jintArray;
+typedef _jlongArray *jlongArray;
+typedef _jfloatArray *jfloatArray;
+typedef _jdoubleArray *jdoubleArray;
+typedef _jobjectArray *jobjectArray;
+
+#else
+
+struct _jobject;
+
+typedef struct _jobject *jobject;
+typedef jobject jclass;
+typedef jobject jthrowable;
+typedef jobject jstring;
+typedef jobject jarray;
+typedef jarray jbooleanArray;
+typedef jarray jbyteArray;
+typedef jarray jcharArray;
+typedef jarray jshortArray;
+typedef jarray jintArray;
+typedef jarray jlongArray;
+typedef jarray jfloatArray;
+typedef jarray jdoubleArray;
+typedef jarray jobjectArray;
+
+#endif
+
+typedef jobject jweak;
+
+typedef union jvalue {
+    jboolean z;
+    jbyte    b;
+    jchar    c;
+    jshort   s;
+    jint     i;
+    jlong    j;
+    jfloat   f;
+    jdouble  d;
+    jobject  l;
+} jvalue;
+
+struct _jfieldID;
+typedef struct _jfieldID *jfieldID;
+
+struct _jmethodID;
+typedef struct _jmethodID *jmethodID;
+
+/* Return values from jobjectRefType */
+typedef enum _jobjectType {
+     JNIInvalidRefType    = 0,
+     JNILocalRefType      = 1,
+     JNIGlobalRefType     = 2,
+     JNIWeakGlobalRefType = 3 
+} jobjectRefType;
+
+
+#endif /* JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H */
+
+/*
+ * jboolean constants
+ */
+
+#define JNI_FALSE 0
+#define JNI_TRUE 1
+
+/*
+ * possible return values for JNI functions.
+ */
+
+#define JNI_OK           0                 /* success */
+#define JNI_ERR          (-1)              /* unknown error */
+#define JNI_EDETACHED    (-2)              /* thread detached from the VM */
+#define JNI_EVERSION     (-3)              /* JNI version error */
+#define JNI_ENOMEM       (-4)              /* not enough memory */
+#define JNI_EEXIST       (-5)              /* VM already created */
+#define JNI_EINVAL       (-6)              /* invalid arguments */
+
+/*
+ * used in ReleaseScalarArrayElements
+ */
+
+#define JNI_COMMIT 1
+#define JNI_ABORT 2
+
+/*
+ * used in RegisterNatives to describe native method name, signature,
+ * and function pointer.
+ */
+
+typedef struct {
+    char *name;
+    char *signature;
+    void *fnPtr;
+} JNINativeMethod;
+
+/*
+ * JNI Native Method Interface.
+ */
+
+struct JNINativeInterface_;
+
+struct JNIEnv_;
+
+#ifdef __cplusplus
+typedef JNIEnv_ JNIEnv;
+#else
+typedef const struct JNINativeInterface_ *JNIEnv;
+#endif
+
+/*
+ * JNI Invocation Interface.
+ */
+
+struct JNIInvokeInterface_;
+
+struct JavaVM_;
+
+#ifdef __cplusplus
+typedef JavaVM_ JavaVM;
+#else
+typedef const struct JNIInvokeInterface_ *JavaVM;
+#endif
+
+struct JNINativeInterface_ {
+    void *reserved0;
+    void *reserved1;
+    void *reserved2;
+
+    void *reserved3;
+    jint (JNICALL *GetVersion)(JNIEnv *env);
+
+    jclass (JNICALL *DefineClass)
+      (JNIEnv *env, const char *name, jobject loader, const jbyte *buf,
+       jsize len);
+    jclass (JNICALL *FindClass)
+      (JNIEnv *env, const char *name);
+
+    jmethodID (JNICALL *FromReflectedMethod)
+      (JNIEnv *env, jobject method);
+    jfieldID (JNICALL *FromReflectedField)
+      (JNIEnv *env, jobject field);
+
+    jobject (JNICALL *ToReflectedMethod)
+      (JNIEnv *env, jclass cls, jmethodID methodID, jboolean isStatic);
+
+    jclass (JNICALL *GetSuperclass)
+      (JNIEnv *env, jclass sub);
+    jboolean (JNICALL *IsAssignableFrom)
+      (JNIEnv *env, jclass sub, jclass sup);
+
+    jobject (JNICALL *ToReflectedField)
+      (JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic);
+
+    jint (JNICALL *Throw)
+      (JNIEnv *env, jthrowable obj);
+    jint (JNICALL *ThrowNew)
+      (JNIEnv *env, jclass clazz, const char *msg);
+    jthrowable (JNICALL *ExceptionOccurred)
+      (JNIEnv *env);
+    void (JNICALL *ExceptionDescribe)
+      (JNIEnv *env);
+    void (JNICALL *ExceptionClear)
+      (JNIEnv *env);
+    void (JNICALL *FatalError)
+      (JNIEnv *env, const char *msg);
+
+    jint (JNICALL *PushLocalFrame)
+      (JNIEnv *env, jint capacity);
+    jobject (JNICALL *PopLocalFrame)
+      (JNIEnv *env, jobject result);
+
+    jobject (JNICALL *NewGlobalRef)
+      (JNIEnv *env, jobject lobj);
+    void (JNICALL *DeleteGlobalRef)
+      (JNIEnv *env, jobject gref);
+    void (JNICALL *DeleteLocalRef)
+      (JNIEnv *env, jobject obj);
+    jboolean (JNICALL *IsSameObject)
+      (JNIEnv *env, jobject obj1, jobject obj2);
+    jobject (JNICALL *NewLocalRef)
+      (JNIEnv *env, jobject ref);
+    jint (JNICALL *EnsureLocalCapacity)
+      (JNIEnv *env, jint capacity);
+
+    jobject (JNICALL *AllocObject)
+      (JNIEnv *env, jclass clazz);
+    jobject (JNICALL *NewObject)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jobject (JNICALL *NewObjectV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jobject (JNICALL *NewObjectA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jclass (JNICALL *GetObjectClass)
+      (JNIEnv *env, jobject obj);
+    jboolean (JNICALL *IsInstanceOf)
+      (JNIEnv *env, jobject obj, jclass clazz);
+
+    jmethodID (JNICALL *GetMethodID)
+      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
+
+    jobject (JNICALL *CallObjectMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jobject (JNICALL *CallObjectMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jobject (JNICALL *CallObjectMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
+
+    jboolean (JNICALL *CallBooleanMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jboolean (JNICALL *CallBooleanMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jboolean (JNICALL *CallBooleanMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
+
+    jbyte (JNICALL *CallByteMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jbyte (JNICALL *CallByteMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jbyte (JNICALL *CallByteMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
+
+    jchar (JNICALL *CallCharMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jchar (JNICALL *CallCharMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jchar (JNICALL *CallCharMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
+
+    jshort (JNICALL *CallShortMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jshort (JNICALL *CallShortMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jshort (JNICALL *CallShortMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
+
+    jint (JNICALL *CallIntMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jint (JNICALL *CallIntMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jint (JNICALL *CallIntMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
+
+    jlong (JNICALL *CallLongMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jlong (JNICALL *CallLongMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jlong (JNICALL *CallLongMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
+
+    jfloat (JNICALL *CallFloatMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jfloat (JNICALL *CallFloatMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jfloat (JNICALL *CallFloatMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
+
+    jdouble (JNICALL *CallDoubleMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    jdouble (JNICALL *CallDoubleMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    jdouble (JNICALL *CallDoubleMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
+
+    void (JNICALL *CallVoidMethod)
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
+    void (JNICALL *CallVoidMethodV)
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
+    void (JNICALL *CallVoidMethodA)
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
+
+    jobject (JNICALL *CallNonvirtualObjectMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jobject (JNICALL *CallNonvirtualObjectMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jobject (JNICALL *CallNonvirtualObjectMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue * args);
+
+    jboolean (JNICALL *CallNonvirtualBooleanMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jboolean (JNICALL *CallNonvirtualBooleanMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jboolean (JNICALL *CallNonvirtualBooleanMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue * args);
+
+    jbyte (JNICALL *CallNonvirtualByteMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jbyte (JNICALL *CallNonvirtualByteMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jbyte (JNICALL *CallNonvirtualByteMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue *args);
+
+    jchar (JNICALL *CallNonvirtualCharMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jchar (JNICALL *CallNonvirtualCharMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jchar (JNICALL *CallNonvirtualCharMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue *args);
+
+    jshort (JNICALL *CallNonvirtualShortMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jshort (JNICALL *CallNonvirtualShortMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jshort (JNICALL *CallNonvirtualShortMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue *args);
+
+    jint (JNICALL *CallNonvirtualIntMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jint (JNICALL *CallNonvirtualIntMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jint (JNICALL *CallNonvirtualIntMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue *args);
+
+    jlong (JNICALL *CallNonvirtualLongMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jlong (JNICALL *CallNonvirtualLongMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jlong (JNICALL *CallNonvirtualLongMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue *args);
+
+    jfloat (JNICALL *CallNonvirtualFloatMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jfloat (JNICALL *CallNonvirtualFloatMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jfloat (JNICALL *CallNonvirtualFloatMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue *args);
+
+    jdouble (JNICALL *CallNonvirtualDoubleMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    jdouble (JNICALL *CallNonvirtualDoubleMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    jdouble (JNICALL *CallNonvirtualDoubleMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue *args);
+
+    void (JNICALL *CallNonvirtualVoidMethod)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
+    void (JNICALL *CallNonvirtualVoidMethodV)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       va_list args);
+    void (JNICALL *CallNonvirtualVoidMethodA)
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
+       const jvalue * args);
+
+    jfieldID (JNICALL *GetFieldID)
+      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
+
+    jobject (JNICALL *GetObjectField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+    jboolean (JNICALL *GetBooleanField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+    jbyte (JNICALL *GetByteField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+    jchar (JNICALL *GetCharField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+    jshort (JNICALL *GetShortField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+    jint (JNICALL *GetIntField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+    jlong (JNICALL *GetLongField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+    jfloat (JNICALL *GetFloatField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+    jdouble (JNICALL *GetDoubleField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID);
+
+    void (JNICALL *SetObjectField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jobject val);
+    void (JNICALL *SetBooleanField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jboolean val);
+    void (JNICALL *SetByteField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jbyte val);
+    void (JNICALL *SetCharField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jchar val);
+    void (JNICALL *SetShortField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jshort val);
+    void (JNICALL *SetIntField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jint val);
+    void (JNICALL *SetLongField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jlong val);
+    void (JNICALL *SetFloatField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jfloat val);
+    void (JNICALL *SetDoubleField)
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jdouble val);
+
+    jmethodID (JNICALL *GetStaticMethodID)
+      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
+
+    jobject (JNICALL *CallStaticObjectMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jobject (JNICALL *CallStaticObjectMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jobject (JNICALL *CallStaticObjectMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jboolean (JNICALL *CallStaticBooleanMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jboolean (JNICALL *CallStaticBooleanMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jboolean (JNICALL *CallStaticBooleanMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jbyte (JNICALL *CallStaticByteMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jbyte (JNICALL *CallStaticByteMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jbyte (JNICALL *CallStaticByteMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jchar (JNICALL *CallStaticCharMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jchar (JNICALL *CallStaticCharMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jchar (JNICALL *CallStaticCharMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jshort (JNICALL *CallStaticShortMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jshort (JNICALL *CallStaticShortMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jshort (JNICALL *CallStaticShortMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jint (JNICALL *CallStaticIntMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jint (JNICALL *CallStaticIntMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jint (JNICALL *CallStaticIntMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jlong (JNICALL *CallStaticLongMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jlong (JNICALL *CallStaticLongMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jlong (JNICALL *CallStaticLongMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jfloat (JNICALL *CallStaticFloatMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jfloat (JNICALL *CallStaticFloatMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jfloat (JNICALL *CallStaticFloatMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    jdouble (JNICALL *CallStaticDoubleMethod)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
+    jdouble (JNICALL *CallStaticDoubleMethodV)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
+    jdouble (JNICALL *CallStaticDoubleMethodA)
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
+
+    void (JNICALL *CallStaticVoidMethod)
+      (JNIEnv *env, jclass cls, jmethodID methodID, ...);
+    void (JNICALL *CallStaticVoidMethodV)
+      (JNIEnv *env, jclass cls, jmethodID methodID, va_list args);
+    void (JNICALL *CallStaticVoidMethodA)
+      (JNIEnv *env, jclass cls, jmethodID methodID, const jvalue * args);
+
+    jfieldID (JNICALL *GetStaticFieldID)
+      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
+    jobject (JNICALL *GetStaticObjectField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+    jboolean (JNICALL *GetStaticBooleanField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+    jbyte (JNICALL *GetStaticByteField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+    jchar (JNICALL *GetStaticCharField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+    jshort (JNICALL *GetStaticShortField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+    jint (JNICALL *GetStaticIntField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+    jlong (JNICALL *GetStaticLongField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+    jfloat (JNICALL *GetStaticFloatField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+    jdouble (JNICALL *GetStaticDoubleField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);
+
+    void (JNICALL *SetStaticObjectField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value);
+    void (JNICALL *SetStaticBooleanField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jboolean value);
+    void (JNICALL *SetStaticByteField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jbyte value);
+    void (JNICALL *SetStaticCharField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jchar value);
+    void (JNICALL *SetStaticShortField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jshort value);
+    void (JNICALL *SetStaticIntField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jint value);
+    void (JNICALL *SetStaticLongField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jlong value);
+    void (JNICALL *SetStaticFloatField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jfloat value);
+    void (JNICALL *SetStaticDoubleField)
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jdouble value);
+
+    jstring (JNICALL *NewString)
+      (JNIEnv *env, const jchar *unicode, jsize len);
+    jsize (JNICALL *GetStringLength)
+      (JNIEnv *env, jstring str);
+    const jchar *(JNICALL *GetStringChars)
+      (JNIEnv *env, jstring str, jboolean *isCopy);
+    void (JNICALL *ReleaseStringChars)
+      (JNIEnv *env, jstring str, const jchar *chars);
+
+    jstring (JNICALL *NewStringUTF)
+      (JNIEnv *env, const char *utf);
+    jsize (JNICALL *GetStringUTFLength)
+      (JNIEnv *env, jstring str);
+    const char* (JNICALL *GetStringUTFChars)
+      (JNIEnv *env, jstring str, jboolean *isCopy);
+    void (JNICALL *ReleaseStringUTFChars)
+      (JNIEnv *env, jstring str, const char* chars);
+
+
+    jsize (JNICALL *GetArrayLength)
+      (JNIEnv *env, jarray array);
+
+    jobjectArray (JNICALL *NewObjectArray)
+      (JNIEnv *env, jsize len, jclass clazz, jobject init);
+    jobject (JNICALL *GetObjectArrayElement)
+      (JNIEnv *env, jobjectArray array, jsize index);
+    void (JNICALL *SetObjectArrayElement)
+      (JNIEnv *env, jobjectArray array, jsize index, jobject val);
+
+    jbooleanArray (JNICALL *NewBooleanArray)
+      (JNIEnv *env, jsize len);
+    jbyteArray (JNICALL *NewByteArray)
+      (JNIEnv *env, jsize len);
+    jcharArray (JNICALL *NewCharArray)
+      (JNIEnv *env, jsize len);
+    jshortArray (JNICALL *NewShortArray)
+      (JNIEnv *env, jsize len);
+    jintArray (JNICALL *NewIntArray)
+      (JNIEnv *env, jsize len);
+    jlongArray (JNICALL *NewLongArray)
+      (JNIEnv *env, jsize len);
+    jfloatArray (JNICALL *NewFloatArray)
+      (JNIEnv *env, jsize len);
+    jdoubleArray (JNICALL *NewDoubleArray)
+      (JNIEnv *env, jsize len);
+
+    jboolean * (JNICALL *GetBooleanArrayElements)
+      (JNIEnv *env, jbooleanArray array, jboolean *isCopy);
+    jbyte * (JNICALL *GetByteArrayElements)
+      (JNIEnv *env, jbyteArray array, jboolean *isCopy);
+    jchar * (JNICALL *GetCharArrayElements)
+      (JNIEnv *env, jcharArray array, jboolean *isCopy);
+    jshort * (JNICALL *GetShortArrayElements)
+      (JNIEnv *env, jshortArray array, jboolean *isCopy);
+    jint * (JNICALL *GetIntArrayElements)
+      (JNIEnv *env, jintArray array, jboolean *isCopy);
+    jlong * (JNICALL *GetLongArrayElements)
+      (JNIEnv *env, jlongArray array, jboolean *isCopy);
+    jfloat * (JNICALL *GetFloatArrayElements)
+      (JNIEnv *env, jfloatArray array, jboolean *isCopy);
+    jdouble * (JNICALL *GetDoubleArrayElements)
+      (JNIEnv *env, jdoubleArray array, jboolean *isCopy);
+
+    void (JNICALL *ReleaseBooleanArrayElements)
+      (JNIEnv *env, jbooleanArray array, jboolean *elems, jint mode);
+    void (JNICALL *ReleaseByteArrayElements)
+      (JNIEnv *env, jbyteArray array, jbyte *elems, jint mode);
+    void (JNICALL *ReleaseCharArrayElements)
+      (JNIEnv *env, jcharArray array, jchar *elems, jint mode);
+    void (JNICALL *ReleaseShortArrayElements)
+      (JNIEnv *env, jshortArray array, jshort *elems, jint mode);
+    void (JNICALL *ReleaseIntArrayElements)
+      (JNIEnv *env, jintArray array, jint *elems, jint mode);
+    void (JNICALL *ReleaseLongArrayElements)
+      (JNIEnv *env, jlongArray array, jlong *elems, jint mode);
+    void (JNICALL *ReleaseFloatArrayElements)
+      (JNIEnv *env, jfloatArray array, jfloat *elems, jint mode);
+    void (JNICALL *ReleaseDoubleArrayElements)
+      (JNIEnv *env, jdoubleArray array, jdouble *elems, jint mode);
+
+    void (JNICALL *GetBooleanArrayRegion)
+      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, jboolean *buf);
+    void (JNICALL *GetByteArrayRegion)
+      (JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
+    void (JNICALL *GetCharArrayRegion)
+      (JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf);
+    void (JNICALL *GetShortArrayRegion)
+      (JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf);
+    void (JNICALL *GetIntArrayRegion)
+      (JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);
+    void (JNICALL *GetLongArrayRegion)
+      (JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);
+    void (JNICALL *GetFloatArrayRegion)
+      (JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);
+    void (JNICALL *GetDoubleArrayRegion)
+      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);
+
+    void (JNICALL *SetBooleanArrayRegion)
+      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, const jboolean *buf);
+    void (JNICALL *SetByteArrayRegion)
+      (JNIEnv *env, jbyteArray array, jsize start, jsize len, const jbyte *buf);
+    void (JNICALL *SetCharArrayRegion)
+      (JNIEnv *env, jcharArray array, jsize start, jsize len, const jchar *buf);
+    void (JNICALL *SetShortArrayRegion)
+      (JNIEnv *env, jshortArray array, jsize start, jsize len, const jshort *buf);
+    void (JNICALL *SetIntArrayRegion)
+      (JNIEnv *env, jintArray array, jsize start, jsize len, const jint *buf);
+    void (JNICALL *SetLongArrayRegion)
+      (JNIEnv *env, jlongArray array, jsize start, jsize len, const jlong *buf);
+    void (JNICALL *SetFloatArrayRegion)
+      (JNIEnv *env, jfloatArray array, jsize start, jsize len, const jfloat *buf);
+    void (JNICALL *SetDoubleArrayRegion)
+      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, const jdouble *buf);
+
+    jint (JNICALL *RegisterNatives)
+      (JNIEnv *env, jclass clazz, const JNINativeMethod *methods,
+       jint nMethods);
+    jint (JNICALL *UnregisterNatives)
+      (JNIEnv *env, jclass clazz);
+
+    jint (JNICALL *MonitorEnter)
+      (JNIEnv *env, jobject obj);
+    jint (JNICALL *MonitorExit)
+      (JNIEnv *env, jobject obj);
+
+    jint (JNICALL *GetJavaVM)
+      (JNIEnv *env, JavaVM **vm);
+
+    void (JNICALL *GetStringRegion)
+      (JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);
+    void (JNICALL *GetStringUTFRegion)
+      (JNIEnv *env, jstring str, jsize start, jsize len, char *buf);
+
+    void * (JNICALL *GetPrimitiveArrayCritical)
+      (JNIEnv *env, jarray array, jboolean *isCopy);
+    void (JNICALL *ReleasePrimitiveArrayCritical)
+      (JNIEnv *env, jarray array, void *carray, jint mode);
+
+    const jchar * (JNICALL *GetStringCritical)
+      (JNIEnv *env, jstring string, jboolean *isCopy);
+    void (JNICALL *ReleaseStringCritical)
+      (JNIEnv *env, jstring string, const jchar *cstring);
+
+    jweak (JNICALL *NewWeakGlobalRef)
+       (JNIEnv *env, jobject obj);
+    void (JNICALL *DeleteWeakGlobalRef)
+       (JNIEnv *env, jweak ref);
+
+    jboolean (JNICALL *ExceptionCheck)
+       (JNIEnv *env);
+
+    jobject (JNICALL *NewDirectByteBuffer)
+       (JNIEnv* env, void* address, jlong capacity);
+    void* (JNICALL *GetDirectBufferAddress)
+       (JNIEnv* env, jobject buf);
+    jlong (JNICALL *GetDirectBufferCapacity)
+       (JNIEnv* env, jobject buf);
+
+    /* New JNI 1.6 Features */
+
+    jobjectRefType (JNICALL *GetObjectRefType)
+        (JNIEnv* env, jobject obj);
+};
+
+/*
+ * We use inlined functions for C++ so that programmers can write:
+ *
+ *    env->FindClass("java/lang/String")
+ *
+ * in C++ rather than:
+ *
+ *    (*env)->FindClass(env, "java/lang/String")
+ *
+ * in C.
+ */
+
+struct JNIEnv_ {
+    const struct JNINativeInterface_ *functions;
+#ifdef __cplusplus
+
+    jint GetVersion() {
+        return functions->GetVersion(this);
+    }
+    jclass DefineClass(const char *name, jobject loader, const jbyte *buf,
+                      jsize len) {
+        return functions->DefineClass(this, name, loader, buf, len);
+    }
+    jclass FindClass(const char *name) {
+        return functions->FindClass(this, name);
+    }
+    jmethodID FromReflectedMethod(jobject method) {
+        return functions->FromReflectedMethod(this,method);
+    }
+    jfieldID FromReflectedField(jobject field) {
+        return functions->FromReflectedField(this,field);
+    }
+
+    jobject ToReflectedMethod(jclass cls, jmethodID methodID, jboolean isStatic) {
+        return functions->ToReflectedMethod(this, cls, methodID, isStatic);
+    }
+
+    jclass GetSuperclass(jclass sub) {
+        return functions->GetSuperclass(this, sub);
+    }
+    jboolean IsAssignableFrom(jclass sub, jclass sup) {
+        return functions->IsAssignableFrom(this, sub, sup);
+    }
+
+    jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) {
+        return functions->ToReflectedField(this,cls,fieldID,isStatic);
+    }
+
+    jint Throw(jthrowable obj) {
+        return functions->Throw(this, obj);
+    }
+    jint ThrowNew(jclass clazz, const char *msg) {
+        return functions->ThrowNew(this, clazz, msg);
+    }
+    jthrowable ExceptionOccurred() {
+        return functions->ExceptionOccurred(this);
+    }
+    void ExceptionDescribe() {
+        functions->ExceptionDescribe(this);
+    }
+    void ExceptionClear() {
+        functions->ExceptionClear(this);
+    }
+    void FatalError(const char *msg) {
+        functions->FatalError(this, msg);
+    }
+
+    jint PushLocalFrame(jint capacity) {
+        return functions->PushLocalFrame(this,capacity);
+    }
+    jobject PopLocalFrame(jobject result) {
+        return functions->PopLocalFrame(this,result);
+    }
+
+    jobject NewGlobalRef(jobject lobj) {
+        return functions->NewGlobalRef(this,lobj);
+    }
+    void DeleteGlobalRef(jobject gref) {
+        functions->DeleteGlobalRef(this,gref);
+    }
+    void DeleteLocalRef(jobject obj) {
+        functions->DeleteLocalRef(this, obj);
+    }
+
+    jboolean IsSameObject(jobject obj1, jobject obj2) {
+        return functions->IsSameObject(this,obj1,obj2);
+    }
+
+    jobject NewLocalRef(jobject ref) {
+        return functions->NewLocalRef(this,ref);
+    }
+    jint EnsureLocalCapacity(jint capacity) {
+        return functions->EnsureLocalCapacity(this,capacity);
+    }
+
+    jobject AllocObject(jclass clazz) {
+        return functions->AllocObject(this,clazz);
+    }
+    jobject NewObject(jclass clazz, jmethodID methodID, ...) {
+        va_list args;
+       jobject result;
+       va_start(args, methodID);
+        result = functions->NewObjectV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jobject NewObjectV(jclass clazz, jmethodID methodID,
+                      va_list args) {
+        return functions->NewObjectV(this,clazz,methodID,args);
+    }
+    jobject NewObjectA(jclass clazz, jmethodID methodID,
+                      const jvalue *args) {
+        return functions->NewObjectA(this,clazz,methodID,args);
+    }
+
+    jclass GetObjectClass(jobject obj) {
+        return functions->GetObjectClass(this,obj);
+    }
+    jboolean IsInstanceOf(jobject obj, jclass clazz) {
+        return functions->IsInstanceOf(this,obj,clazz);
+    }
+
+    jmethodID GetMethodID(jclass clazz, const char *name,
+                         const char *sig) {
+        return functions->GetMethodID(this,clazz,name,sig);
+    }
+
+    jobject CallObjectMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       jobject result;
+       va_start(args,methodID);
+       result = functions->CallObjectMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jobject CallObjectMethodV(jobject obj, jmethodID methodID,
+                       va_list args) {
+        return functions->CallObjectMethodV(this,obj,methodID,args);
+    }
+    jobject CallObjectMethodA(jobject obj, jmethodID methodID,
+                       const jvalue * args) {
+        return functions->CallObjectMethodA(this,obj,methodID,args);
+    }
+
+    jboolean CallBooleanMethod(jobject obj,
+                              jmethodID methodID, ...) {
+        va_list args;
+       jboolean result;
+       va_start(args,methodID);
+       result = functions->CallBooleanMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jboolean CallBooleanMethodV(jobject obj, jmethodID methodID,
+                               va_list args) {
+        return functions->CallBooleanMethodV(this,obj,methodID,args);
+    }
+    jboolean CallBooleanMethodA(jobject obj, jmethodID methodID,
+                               const jvalue * args) {
+        return functions->CallBooleanMethodA(this,obj,methodID, args);
+    }
+
+    jbyte CallByteMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       jbyte result;
+       va_start(args,methodID);
+       result = functions->CallByteMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jbyte CallByteMethodV(jobject obj, jmethodID methodID,
+                         va_list args) {
+        return functions->CallByteMethodV(this,obj,methodID,args);
+    }
+    jbyte CallByteMethodA(jobject obj, jmethodID methodID,
+                         const jvalue * args) {
+        return functions->CallByteMethodA(this,obj,methodID,args);
+    }
+
+    jchar CallCharMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       jchar result;
+       va_start(args,methodID);
+       result = functions->CallCharMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jchar CallCharMethodV(jobject obj, jmethodID methodID,
+                         va_list args) {
+        return functions->CallCharMethodV(this,obj,methodID,args);
+    }
+    jchar CallCharMethodA(jobject obj, jmethodID methodID,
+                         const jvalue * args) {
+        return functions->CallCharMethodA(this,obj,methodID,args);
+    }
+
+    jshort CallShortMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       jshort result;
+       va_start(args,methodID);
+       result = functions->CallShortMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jshort CallShortMethodV(jobject obj, jmethodID methodID,
+                           va_list args) {
+        return functions->CallShortMethodV(this,obj,methodID,args);
+    }
+    jshort CallShortMethodA(jobject obj, jmethodID methodID,
+                           const jvalue * args) {
+        return functions->CallShortMethodA(this,obj,methodID,args);
+    }
+
+    jint CallIntMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       jint result;
+       va_start(args,methodID);
+       result = functions->CallIntMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jint CallIntMethodV(jobject obj, jmethodID methodID,
+                       va_list args) {
+        return functions->CallIntMethodV(this,obj,methodID,args);
+    }
+    jint CallIntMethodA(jobject obj, jmethodID methodID,
+                       const jvalue * args) {
+        return functions->CallIntMethodA(this,obj,methodID,args);
+    }
+
+    jlong CallLongMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       jlong result;
+       va_start(args,methodID);
+       result = functions->CallLongMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jlong CallLongMethodV(jobject obj, jmethodID methodID,
+                         va_list args) {
+        return functions->CallLongMethodV(this,obj,methodID,args);
+    }
+    jlong CallLongMethodA(jobject obj, jmethodID methodID,
+                         const jvalue * args) {
+        return functions->CallLongMethodA(this,obj,methodID,args);
+    }
+
+    jfloat CallFloatMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       jfloat result;
+       va_start(args,methodID);
+       result = functions->CallFloatMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jfloat CallFloatMethodV(jobject obj, jmethodID methodID,
+                           va_list args) {
+        return functions->CallFloatMethodV(this,obj,methodID,args);
+    }
+    jfloat CallFloatMethodA(jobject obj, jmethodID methodID,
+                           const jvalue * args) {
+        return functions->CallFloatMethodA(this,obj,methodID,args);
+    }
+
+    jdouble CallDoubleMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       jdouble result;
+       va_start(args,methodID);
+       result = functions->CallDoubleMethodV(this,obj,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jdouble CallDoubleMethodV(jobject obj, jmethodID methodID,
+                       va_list args) {
+        return functions->CallDoubleMethodV(this,obj,methodID,args);
+    }
+    jdouble CallDoubleMethodA(jobject obj, jmethodID methodID,
+                       const jvalue * args) {
+        return functions->CallDoubleMethodA(this,obj,methodID,args);
+    }
+
+    void CallVoidMethod(jobject obj, jmethodID methodID, ...) {
+        va_list args;
+       va_start(args,methodID);
+       functions->CallVoidMethodV(this,obj,methodID,args);
+       va_end(args);
+    }
+    void CallVoidMethodV(jobject obj, jmethodID methodID,
+                        va_list args) {
+        functions->CallVoidMethodV(this,obj,methodID,args);
+    }
+    void CallVoidMethodA(jobject obj, jmethodID methodID,
+                        const jvalue * args) {
+        functions->CallVoidMethodA(this,obj,methodID,args);
+    }
+
+    jobject CallNonvirtualObjectMethod(jobject obj, jclass clazz,
+                                      jmethodID methodID, ...) {
+        va_list args;
+       jobject result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualObjectMethodV(this,obj,clazz,
+                                                       methodID,args);
+       va_end(args);
+       return result;
+    }
+    jobject CallNonvirtualObjectMethodV(jobject obj, jclass clazz,
+                                       jmethodID methodID, va_list args) {
+        return functions->CallNonvirtualObjectMethodV(this,obj,clazz,
+                                                     methodID,args);
+    }
+    jobject CallNonvirtualObjectMethodA(jobject obj, jclass clazz,
+                                       jmethodID methodID, const jvalue * args) {
+        return functions->CallNonvirtualObjectMethodA(this,obj,clazz,
+                                                     methodID,args);
+    }
+
+    jboolean CallNonvirtualBooleanMethod(jobject obj, jclass clazz,
+                                        jmethodID methodID, ...) {
+        va_list args;
+       jboolean result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
+                                                        methodID,args);
+       va_end(args);
+       return result;
+    }
+    jboolean CallNonvirtualBooleanMethodV(jobject obj, jclass clazz,
+                                         jmethodID methodID, va_list args) {
+        return functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
+                                                      methodID,args);
+    }
+    jboolean CallNonvirtualBooleanMethodA(jobject obj, jclass clazz,
+                                         jmethodID methodID, const jvalue * args) {
+        return functions->CallNonvirtualBooleanMethodA(this,obj,clazz,
+                                                      methodID, args);
+    }
+
+    jbyte CallNonvirtualByteMethod(jobject obj, jclass clazz,
+                                  jmethodID methodID, ...) {
+        va_list args;
+       jbyte result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualByteMethodV(this,obj,clazz,
+                                                     methodID,args);
+       va_end(args);
+       return result;
+    }
+    jbyte CallNonvirtualByteMethodV(jobject obj, jclass clazz,
+                                   jmethodID methodID, va_list args) {
+        return functions->CallNonvirtualByteMethodV(this,obj,clazz,
+                                                   methodID,args);
+    }
+    jbyte CallNonvirtualByteMethodA(jobject obj, jclass clazz,
+                                   jmethodID methodID, const jvalue * args) {
+        return functions->CallNonvirtualByteMethodA(this,obj,clazz,
+                                                   methodID,args);
+    }
+
+    jchar CallNonvirtualCharMethod(jobject obj, jclass clazz,
+                                  jmethodID methodID, ...) {
+        va_list args;
+       jchar result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualCharMethodV(this,obj,clazz,
+                                                     methodID,args);
+       va_end(args);
+       return result;
+    }
+    jchar CallNonvirtualCharMethodV(jobject obj, jclass clazz,
+                                   jmethodID methodID, va_list args) {
+        return functions->CallNonvirtualCharMethodV(this,obj,clazz,
+                                                   methodID,args);
+    }
+    jchar CallNonvirtualCharMethodA(jobject obj, jclass clazz,
+                                   jmethodID methodID, const jvalue * args) {
+        return functions->CallNonvirtualCharMethodA(this,obj,clazz,
+                                                   methodID,args);
+    }
+
+    jshort CallNonvirtualShortMethod(jobject obj, jclass clazz,
+                                    jmethodID methodID, ...) {
+        va_list args;
+       jshort result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualShortMethodV(this,obj,clazz,
+                                                      methodID,args);
+       va_end(args);
+       return result;
+    }
+    jshort CallNonvirtualShortMethodV(jobject obj, jclass clazz,
+                                     jmethodID methodID, va_list args) {
+        return functions->CallNonvirtualShortMethodV(this,obj,clazz,
+                                                    methodID,args);
+    }
+    jshort CallNonvirtualShortMethodA(jobject obj, jclass clazz,
+                                     jmethodID methodID, const jvalue * args) {
+        return functions->CallNonvirtualShortMethodA(this,obj,clazz,
+                                                    methodID,args);
+    }
+
+    jint CallNonvirtualIntMethod(jobject obj, jclass clazz,
+                                jmethodID methodID, ...) {
+        va_list args;
+       jint result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualIntMethodV(this,obj,clazz,
+                                                    methodID,args);
+       va_end(args);
+       return result;
+    }
+    jint CallNonvirtualIntMethodV(jobject obj, jclass clazz,
+                                 jmethodID methodID, va_list args) {
+        return functions->CallNonvirtualIntMethodV(this,obj,clazz,
+                                                  methodID,args);
+    }
+    jint CallNonvirtualIntMethodA(jobject obj, jclass clazz,
+                                 jmethodID methodID, const jvalue * args) {
+        return functions->CallNonvirtualIntMethodA(this,obj,clazz,
+                                                  methodID,args);
+    }
+
+    jlong CallNonvirtualLongMethod(jobject obj, jclass clazz,
+                                  jmethodID methodID, ...) {
+        va_list args;
+       jlong result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualLongMethodV(this,obj,clazz,
+                                                     methodID,args);
+       va_end(args);
+       return result;
+    }
+    jlong CallNonvirtualLongMethodV(jobject obj, jclass clazz,
+                                   jmethodID methodID, va_list args) {
+        return functions->CallNonvirtualLongMethodV(this,obj,clazz,
+                                                   methodID,args);
+    }
+    jlong CallNonvirtualLongMethodA(jobject obj, jclass clazz,
+                                   jmethodID methodID, const jvalue * args) {
+        return functions->CallNonvirtualLongMethodA(this,obj,clazz,
+                                                   methodID,args);
+    }
+
+    jfloat CallNonvirtualFloatMethod(jobject obj, jclass clazz,
+                                    jmethodID methodID, ...) {
+        va_list args;
+       jfloat result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualFloatMethodV(this,obj,clazz,
+                                                      methodID,args);
+       va_end(args);
+       return result;
+    }
+    jfloat CallNonvirtualFloatMethodV(jobject obj, jclass clazz,
+                                     jmethodID methodID,
+                                     va_list args) {
+        return functions->CallNonvirtualFloatMethodV(this,obj,clazz,
+                                                    methodID,args);
+    }
+    jfloat CallNonvirtualFloatMethodA(jobject obj, jclass clazz,
+                                     jmethodID methodID,
+                                     const jvalue * args) {
+        return functions->CallNonvirtualFloatMethodA(this,obj,clazz,
+                                                    methodID,args);
+    }
+
+    jdouble CallNonvirtualDoubleMethod(jobject obj, jclass clazz,
+                                      jmethodID methodID, ...) {
+        va_list args;
+       jdouble result;
+       va_start(args,methodID);
+       result = functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
+                                                       methodID,args);
+       va_end(args);
+       return result;
+    }
+    jdouble CallNonvirtualDoubleMethodV(jobject obj, jclass clazz,
+                                       jmethodID methodID,
+                                       va_list args) {
+        return functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
+                                                     methodID,args);
+    }
+    jdouble CallNonvirtualDoubleMethodA(jobject obj, jclass clazz,
+                                       jmethodID methodID,
+                                       const jvalue * args) {
+        return functions->CallNonvirtualDoubleMethodA(this,obj,clazz,
+                                                     methodID,args);
+    }
+
+    void CallNonvirtualVoidMethod(jobject obj, jclass clazz,
+                                 jmethodID methodID, ...) {
+        va_list args;
+       va_start(args,methodID);
+       functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
+       va_end(args);
+    }
+    void CallNonvirtualVoidMethodV(jobject obj, jclass clazz,
+                                  jmethodID methodID,
+                                  va_list args) {
+        functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
+    }
+    void CallNonvirtualVoidMethodA(jobject obj, jclass clazz,
+                                  jmethodID methodID,
+                                  const jvalue * args) {
+        functions->CallNonvirtualVoidMethodA(this,obj,clazz,methodID,args);
+    }
+
+    jfieldID GetFieldID(jclass clazz, const char *name,
+                       const char *sig) {
+        return functions->GetFieldID(this,clazz,name,sig);
+    }
+
+    jobject GetObjectField(jobject obj, jfieldID fieldID) {
+        return functions->GetObjectField(this,obj,fieldID);
+    }
+    jboolean GetBooleanField(jobject obj, jfieldID fieldID) {
+        return functions->GetBooleanField(this,obj,fieldID);
+    }
+    jbyte GetByteField(jobject obj, jfieldID fieldID) {
+        return functions->GetByteField(this,obj,fieldID);
+    }
+    jchar GetCharField(jobject obj, jfieldID fieldID) {
+        return functions->GetCharField(this,obj,fieldID);
+    }
+    jshort GetShortField(jobject obj, jfieldID fieldID) {
+        return functions->GetShortField(this,obj,fieldID);
+    }
+    jint GetIntField(jobject obj, jfieldID fieldID) {
+        return functions->GetIntField(this,obj,fieldID);
+    }
+    jlong GetLongField(jobject obj, jfieldID fieldID) {
+        return functions->GetLongField(this,obj,fieldID);
+    }
+    jfloat GetFloatField(jobject obj, jfieldID fieldID) {
+        return functions->GetFloatField(this,obj,fieldID);
+    }
+    jdouble GetDoubleField(jobject obj, jfieldID fieldID) {
+        return functions->GetDoubleField(this,obj,fieldID);
+    }
+
+    void SetObjectField(jobject obj, jfieldID fieldID, jobject val) {
+        functions->SetObjectField(this,obj,fieldID,val);
+    }
+    void SetBooleanField(jobject obj, jfieldID fieldID,
+                        jboolean val) {
+        functions->SetBooleanField(this,obj,fieldID,val);
+    }
+    void SetByteField(jobject obj, jfieldID fieldID,
+                     jbyte val) {
+        functions->SetByteField(this,obj,fieldID,val);
+    }
+    void SetCharField(jobject obj, jfieldID fieldID,
+                     jchar val) {
+        functions->SetCharField(this,obj,fieldID,val);
+    }
+    void SetShortField(jobject obj, jfieldID fieldID,
+                      jshort val) {
+        functions->SetShortField(this,obj,fieldID,val);
+    }
+    void SetIntField(jobject obj, jfieldID fieldID,
+                    jint val) {
+        functions->SetIntField(this,obj,fieldID,val);
+    }
+    void SetLongField(jobject obj, jfieldID fieldID,
+                     jlong val) {
+        functions->SetLongField(this,obj,fieldID,val);
+    }
+    void SetFloatField(jobject obj, jfieldID fieldID,
+                      jfloat val) {
+        functions->SetFloatField(this,obj,fieldID,val);
+    }
+    void SetDoubleField(jobject obj, jfieldID fieldID,
+                       jdouble val) {
+        functions->SetDoubleField(this,obj,fieldID,val);
+    }
+
+    jmethodID GetStaticMethodID(jclass clazz, const char *name,
+                               const char *sig) {
+        return functions->GetStaticMethodID(this,clazz,name,sig);
+    }
+
+    jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID,
+                            ...) {
+        va_list args;
+       jobject result;
+       va_start(args,methodID);
+       result = functions->CallStaticObjectMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jobject CallStaticObjectMethodV(jclass clazz, jmethodID methodID,
+                             va_list args) {
+        return functions->CallStaticObjectMethodV(this,clazz,methodID,args);
+    }
+    jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID,
+                             const jvalue *args) {
+        return functions->CallStaticObjectMethodA(this,clazz,methodID,args);
+    }
+
+    jboolean CallStaticBooleanMethod(jclass clazz,
+                                    jmethodID methodID, ...) {
+        va_list args;
+       jboolean result;
+       va_start(args,methodID);
+       result = functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jboolean CallStaticBooleanMethodV(jclass clazz,
+                                     jmethodID methodID, va_list args) {
+        return functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
+    }
+    jboolean CallStaticBooleanMethodA(jclass clazz,
+                                     jmethodID methodID, const jvalue *args) {
+        return functions->CallStaticBooleanMethodA(this,clazz,methodID,args);
+    }
+
+    jbyte CallStaticByteMethod(jclass clazz,
+                              jmethodID methodID, ...) {
+        va_list args;
+       jbyte result;
+       va_start(args,methodID);
+       result = functions->CallStaticByteMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jbyte CallStaticByteMethodV(jclass clazz,
+                               jmethodID methodID, va_list args) {
+        return functions->CallStaticByteMethodV(this,clazz,methodID,args);
+    }
+    jbyte CallStaticByteMethodA(jclass clazz,
+                               jmethodID methodID, const jvalue *args) {
+        return functions->CallStaticByteMethodA(this,clazz,methodID,args);
+    }
+
+    jchar CallStaticCharMethod(jclass clazz,
+                              jmethodID methodID, ...) {
+        va_list args;
+       jchar result;
+       va_start(args,methodID);
+       result = functions->CallStaticCharMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jchar CallStaticCharMethodV(jclass clazz,
+                               jmethodID methodID, va_list args) {
+        return functions->CallStaticCharMethodV(this,clazz,methodID,args);
+    }
+    jchar CallStaticCharMethodA(jclass clazz,
+                               jmethodID methodID, const jvalue *args) {
+        return functions->CallStaticCharMethodA(this,clazz,methodID,args);
+    }
+
+    jshort CallStaticShortMethod(jclass clazz,
+                                jmethodID methodID, ...) {
+        va_list args;
+       jshort result;
+       va_start(args,methodID);
+       result = functions->CallStaticShortMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jshort CallStaticShortMethodV(jclass clazz,
+                                 jmethodID methodID, va_list args) {
+        return functions->CallStaticShortMethodV(this,clazz,methodID,args);
+    }
+    jshort CallStaticShortMethodA(jclass clazz,
+                                 jmethodID methodID, const jvalue *args) {
+        return functions->CallStaticShortMethodA(this,clazz,methodID,args);
+    }
+
+    jint CallStaticIntMethod(jclass clazz,
+                            jmethodID methodID, ...) {
+        va_list args;
+       jint result;
+       va_start(args,methodID);
+       result = functions->CallStaticIntMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jint CallStaticIntMethodV(jclass clazz,
+                             jmethodID methodID, va_list args) {
+        return functions->CallStaticIntMethodV(this,clazz,methodID,args);
+    }
+    jint CallStaticIntMethodA(jclass clazz,
+                             jmethodID methodID, const jvalue *args) {
+        return functions->CallStaticIntMethodA(this,clazz,methodID,args);
+    }
+
+    jlong CallStaticLongMethod(jclass clazz,
+                              jmethodID methodID, ...) {
+        va_list args;
+       jlong result;
+       va_start(args,methodID);
+       result = functions->CallStaticLongMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jlong CallStaticLongMethodV(jclass clazz,
+                               jmethodID methodID, va_list args) {
+        return functions->CallStaticLongMethodV(this,clazz,methodID,args);
+    }
+    jlong CallStaticLongMethodA(jclass clazz,
+                               jmethodID methodID, const jvalue *args) {
+        return functions->CallStaticLongMethodA(this,clazz,methodID,args);
+    }
+
+    jfloat CallStaticFloatMethod(jclass clazz,
+                                jmethodID methodID, ...) {
+        va_list args;
+       jfloat result;
+       va_start(args,methodID);
+       result = functions->CallStaticFloatMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jfloat CallStaticFloatMethodV(jclass clazz,
+                                 jmethodID methodID, va_list args) {
+        return functions->CallStaticFloatMethodV(this,clazz,methodID,args);
+    }
+    jfloat CallStaticFloatMethodA(jclass clazz,
+                                 jmethodID methodID, const jvalue *args) {
+        return functions->CallStaticFloatMethodA(this,clazz,methodID,args);
+    }
+
+    jdouble CallStaticDoubleMethod(jclass clazz,
+                                  jmethodID methodID, ...) {
+        va_list args;
+       jdouble result;
+       va_start(args,methodID);
+       result = functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
+       va_end(args);
+       return result;
+    }
+    jdouble CallStaticDoubleMethodV(jclass clazz,
+                                   jmethodID methodID, va_list args) {
+        return functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
+    }
+    jdouble CallStaticDoubleMethodA(jclass clazz,
+                                   jmethodID methodID, const jvalue *args) {
+        return functions->CallStaticDoubleMethodA(this,clazz,methodID,args);
+    }
+
+    void CallStaticVoidMethod(jclass cls, jmethodID methodID, ...) {
+        va_list args;
+       va_start(args,methodID);
+       functions->CallStaticVoidMethodV(this,cls,methodID,args);
+       va_end(args);
+    }
+    void CallStaticVoidMethodV(jclass cls, jmethodID methodID,
+                              va_list args) {
+        functions->CallStaticVoidMethodV(this,cls,methodID,args);
+    }
+    void CallStaticVoidMethodA(jclass cls, jmethodID methodID,
+                              const jvalue * args) {
+        functions->CallStaticVoidMethodA(this,cls,methodID,args);
+    }
+
+    jfieldID GetStaticFieldID(jclass clazz, const char *name,
+                             const char *sig) {
+        return functions->GetStaticFieldID(this,clazz,name,sig);
+    }
+    jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticObjectField(this,clazz,fieldID);
+    }
+    jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticBooleanField(this,clazz,fieldID);
+    }
+    jbyte GetStaticByteField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticByteField(this,clazz,fieldID);
+    }
+    jchar GetStaticCharField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticCharField(this,clazz,fieldID);
+    }
+    jshort GetStaticShortField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticShortField(this,clazz,fieldID);
+    }
+    jint GetStaticIntField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticIntField(this,clazz,fieldID);
+    }
+    jlong GetStaticLongField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticLongField(this,clazz,fieldID);
+    }
+    jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticFloatField(this,clazz,fieldID);
+    }
+    jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID) {
+        return functions->GetStaticDoubleField(this,clazz,fieldID);
+    }
+
+    void SetStaticObjectField(jclass clazz, jfieldID fieldID,
+                       jobject value) {
+      functions->SetStaticObjectField(this,clazz,fieldID,value);
+    }
+    void SetStaticBooleanField(jclass clazz, jfieldID fieldID,
+                       jboolean value) {
+      functions->SetStaticBooleanField(this,clazz,fieldID,value);
+    }
+    void SetStaticByteField(jclass clazz, jfieldID fieldID,
+                       jbyte value) {
+      functions->SetStaticByteField(this,clazz,fieldID,value);
+    }
+    void SetStaticCharField(jclass clazz, jfieldID fieldID,
+                       jchar value) {
+      functions->SetStaticCharField(this,clazz,fieldID,value);
+    }
+    void SetStaticShortField(jclass clazz, jfieldID fieldID,
+                       jshort value) {
+      functions->SetStaticShortField(this,clazz,fieldID,value);
+    }
+    void SetStaticIntField(jclass clazz, jfieldID fieldID,
+                       jint value) {
+      functions->SetStaticIntField(this,clazz,fieldID,value);
+    }
+    void SetStaticLongField(jclass clazz, jfieldID fieldID,
+                       jlong value) {
+      functions->SetStaticLongField(this,clazz,fieldID,value);
+    }
+    void SetStaticFloatField(jclass clazz, jfieldID fieldID,
+                       jfloat value) {
+      functions->SetStaticFloatField(this,clazz,fieldID,value);
+    }
+    void SetStaticDoubleField(jclass clazz, jfieldID fieldID,
+                       jdouble value) {
+      functions->SetStaticDoubleField(this,clazz,fieldID,value);
+    }
+
+    jstring NewString(const jchar *unicode, jsize len) {
+        return functions->NewString(this,unicode,len);
+    }
+    jsize GetStringLength(jstring str) {
+        return functions->GetStringLength(this,str);
+    }
+    const jchar *GetStringChars(jstring str, jboolean *isCopy) {
+        return functions->GetStringChars(this,str,isCopy);
+    }
+    void ReleaseStringChars(jstring str, const jchar *chars) {
+        functions->ReleaseStringChars(this,str,chars);
+    }
+
+    jstring NewStringUTF(const char *utf) {
+        return functions->NewStringUTF(this,utf);
+    }
+    jsize GetStringUTFLength(jstring str) {
+        return functions->GetStringUTFLength(this,str);
+    }
+    const char* GetStringUTFChars(jstring str, jboolean *isCopy) {
+        return functions->GetStringUTFChars(this,str,isCopy);
+    }
+    void ReleaseStringUTFChars(jstring str, const char* chars) {
+        functions->ReleaseStringUTFChars(this,str,chars);
+    }
+
+    jsize GetArrayLength(jarray array) {
+        return functions->GetArrayLength(this,array);
+    }
+
+    jobjectArray NewObjectArray(jsize len, jclass clazz,
+                               jobject init) {
+        return functions->NewObjectArray(this,len,clazz,init);
+    }
+    jobject GetObjectArrayElement(jobjectArray array, jsize index) {
+        return functions->GetObjectArrayElement(this,array,index);
+    }
+    void SetObjectArrayElement(jobjectArray array, jsize index,
+                              jobject val) {
+        functions->SetObjectArrayElement(this,array,index,val);
+    }
+
+    jbooleanArray NewBooleanArray(jsize len) {
+        return functions->NewBooleanArray(this,len);
+    }
+    jbyteArray NewByteArray(jsize len) {
+        return functions->NewByteArray(this,len);
+    }
+    jcharArray NewCharArray(jsize len) {
+        return functions->NewCharArray(this,len);
+    }
+    jshortArray NewShortArray(jsize len) {
+        return functions->NewShortArray(this,len);
+    }
+    jintArray NewIntArray(jsize len) {
+        return functions->NewIntArray(this,len);
+    }
+    jlongArray NewLongArray(jsize len) {
+        return functions->NewLongArray(this,len);
+    }
+    jfloatArray NewFloatArray(jsize len) {
+        return functions->NewFloatArray(this,len);
+    }
+    jdoubleArray NewDoubleArray(jsize len) {
+        return functions->NewDoubleArray(this,len);
+    }
+
+    jboolean * GetBooleanArrayElements(jbooleanArray array, jboolean *isCopy) {
+        return functions->GetBooleanArrayElements(this,array,isCopy);
+    }
+    jbyte * GetByteArrayElements(jbyteArray array, jboolean *isCopy) {
+        return functions->GetByteArrayElements(this,array,isCopy);
+    }
+    jchar * GetCharArrayElements(jcharArray array, jboolean *isCopy) {
+        return functions->GetCharArrayElements(this,array,isCopy);
+    }
+    jshort * GetShortArrayElements(jshortArray array, jboolean *isCopy) {
+        return functions->GetShortArrayElements(this,array,isCopy);
+    }
+    jint * GetIntArrayElements(jintArray array, jboolean *isCopy) {
+        return functions->GetIntArrayElements(this,array,isCopy);
+    }
+    jlong * GetLongArrayElements(jlongArray array, jboolean *isCopy) {
+        return functions->GetLongArrayElements(this,array,isCopy);
+    }
+    jfloat * GetFloatArrayElements(jfloatArray array, jboolean *isCopy) {
+        return functions->GetFloatArrayElements(this,array,isCopy);
+    }
+    jdouble * GetDoubleArrayElements(jdoubleArray array, jboolean *isCopy) {
+        return functions->GetDoubleArrayElements(this,array,isCopy);
+    }
+
+    void ReleaseBooleanArrayElements(jbooleanArray array,
+                                    jboolean *elems,
+                                    jint mode) {
+        functions->ReleaseBooleanArrayElements(this,array,elems,mode);
+    }
+    void ReleaseByteArrayElements(jbyteArray array,
+                                 jbyte *elems,
+                                 jint mode) {
+        functions->ReleaseByteArrayElements(this,array,elems,mode);
+    }
+    void ReleaseCharArrayElements(jcharArray array,
+                                 jchar *elems,
+                                 jint mode) {
+        functions->ReleaseCharArrayElements(this,array,elems,mode);
+    }
+    void ReleaseShortArrayElements(jshortArray array,
+                                  jshort *elems,
+                                  jint mode) {
+        functions->ReleaseShortArrayElements(this,array,elems,mode);
+    }
+    void ReleaseIntArrayElements(jintArray array,
+                                jint *elems,
+                                jint mode) {
+        functions->ReleaseIntArrayElements(this,array,elems,mode);
+    }
+    void ReleaseLongArrayElements(jlongArray array,
+                                 jlong *elems,
+                                 jint mode) {
+        functions->ReleaseLongArrayElements(this,array,elems,mode);
+    }
+    void ReleaseFloatArrayElements(jfloatArray array,
+                                  jfloat *elems,
+                                  jint mode) {
+        functions->ReleaseFloatArrayElements(this,array,elems,mode);
+    }
+    void ReleaseDoubleArrayElements(jdoubleArray array,
+                                   jdouble *elems,
+                                   jint mode) {
+        functions->ReleaseDoubleArrayElements(this,array,elems,mode);
+    }
+
+    void GetBooleanArrayRegion(jbooleanArray array,
+                              jsize start, jsize len, jboolean *buf) {
+        functions->GetBooleanArrayRegion(this,array,start,len,buf);
+    }
+    void GetByteArrayRegion(jbyteArray array,
+                           jsize start, jsize len, jbyte *buf) {
+        functions->GetByteArrayRegion(this,array,start,len,buf);
+    }
+    void GetCharArrayRegion(jcharArray array,
+                           jsize start, jsize len, jchar *buf) {
+        functions->GetCharArrayRegion(this,array,start,len,buf);
+    }
+    void GetShortArrayRegion(jshortArray array,
+                            jsize start, jsize len, jshort *buf) {
+        functions->GetShortArrayRegion(this,array,start,len,buf);
+    }
+    void GetIntArrayRegion(jintArray array,
+                          jsize start, jsize len, jint *buf) {
+        functions->GetIntArrayRegion(this,array,start,len,buf);
+    }
+    void GetLongArrayRegion(jlongArray array,
+                           jsize start, jsize len, jlong *buf) {
+        functions->GetLongArrayRegion(this,array,start,len,buf);
+    }
+    void GetFloatArrayRegion(jfloatArray array,
+                            jsize start, jsize len, jfloat *buf) {
+        functions->GetFloatArrayRegion(this,array,start,len,buf);
+    }
+    void GetDoubleArrayRegion(jdoubleArray array,
+                             jsize start, jsize len, jdouble *buf) {
+        functions->GetDoubleArrayRegion(this,array,start,len,buf);
+    }
+
+    void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len,
+                              const jboolean *buf) {
+        functions->SetBooleanArrayRegion(this,array,start,len,buf);
+    }
+    void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,
+                           const jbyte *buf) {
+        functions->SetByteArrayRegion(this,array,start,len,buf);
+    }
+    void SetCharArrayRegion(jcharArray array, jsize start, jsize len,
+                           const jchar *buf) {
+        functions->SetCharArrayRegion(this,array,start,len,buf);
+    }
+    void SetShortArrayRegion(jshortArray array, jsize start, jsize len,
+                            const jshort *buf) {
+        functions->SetShortArrayRegion(this,array,start,len,buf);
+    }
+    void SetIntArrayRegion(jintArray array, jsize start, jsize len,
+                          const jint *buf) {
+        functions->SetIntArrayRegion(this,array,start,len,buf);
+    }
+    void SetLongArrayRegion(jlongArray array, jsize start, jsize len,
+                           const jlong *buf) {
+        functions->SetLongArrayRegion(this,array,start,len,buf);
+    }
+    void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len,
+                            const jfloat *buf) {
+        functions->SetFloatArrayRegion(this,array,start,len,buf);
+    }
+    void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len,
+                             const jdouble *buf) {
+        functions->SetDoubleArrayRegion(this,array,start,len,buf);
+    }
+
+    jint RegisterNatives(jclass clazz, const JNINativeMethod *methods,
+                        jint nMethods) {
+        return functions->RegisterNatives(this,clazz,methods,nMethods);
+    }
+    jint UnregisterNatives(jclass clazz) {
+        return functions->UnregisterNatives(this,clazz);
+    }
+
+    jint MonitorEnter(jobject obj) {
+        return functions->MonitorEnter(this,obj);
+    }
+    jint MonitorExit(jobject obj) {
+        return functions->MonitorExit(this,obj);
+    }
+
+    jint GetJavaVM(JavaVM **vm) {
+        return functions->GetJavaVM(this,vm);
+    }
+
+    void GetStringRegion(jstring str, jsize start, jsize len, jchar *buf) {
+        functions->GetStringRegion(this,str,start,len,buf);
+    }
+    void GetStringUTFRegion(jstring str, jsize start, jsize len, char *buf) {
+        functions->GetStringUTFRegion(this,str,start,len,buf);
+    }
+
+    void * GetPrimitiveArrayCritical(jarray array, jboolean *isCopy) {
+        return functions->GetPrimitiveArrayCritical(this,array,isCopy);
+    }
+    void ReleasePrimitiveArrayCritical(jarray array, void *carray, jint mode) {
+        functions->ReleasePrimitiveArrayCritical(this,array,carray,mode);
+    }
+
+    const jchar * GetStringCritical(jstring string, jboolean *isCopy) {
+        return functions->GetStringCritical(this,string,isCopy);
+    }
+    void ReleaseStringCritical(jstring string, const jchar *cstring) {
+        functions->ReleaseStringCritical(this,string,cstring);
+    }
+
+    jweak NewWeakGlobalRef(jobject obj) {
+        return functions->NewWeakGlobalRef(this,obj);
+    }
+    void DeleteWeakGlobalRef(jweak ref) {
+        functions->DeleteWeakGlobalRef(this,ref);
+    }
+
+    jboolean ExceptionCheck() {
+       return functions->ExceptionCheck(this);
+    }
+
+    jobject NewDirectByteBuffer(void* address, jlong capacity) {
+        return functions->NewDirectByteBuffer(this, address, capacity);
+    }
+    void* GetDirectBufferAddress(jobject buf) {
+        return functions->GetDirectBufferAddress(this, buf);
+    }
+    jlong GetDirectBufferCapacity(jobject buf) {
+        return functions->GetDirectBufferCapacity(this, buf);
+    }
+    jobjectRefType GetObjectRefType(jobject obj) {
+        return functions->GetObjectRefType(this, obj);
+    }
+
+#endif /* __cplusplus */
+};
+
+typedef struct JavaVMOption {
+    char *optionString;
+    void *extraInfo;
+} JavaVMOption;
+
+typedef struct JavaVMInitArgs {
+    jint version;
+
+    jint nOptions;
+    JavaVMOption *options;
+    jboolean ignoreUnrecognized;
+} JavaVMInitArgs;
+
+typedef struct JavaVMAttachArgs {
+    jint version;
+
+    char *name;
+    jobject group;
+} JavaVMAttachArgs;
+
+/* These will be VM-specific. */
+
+#define JDK1_2
+#define JDK1_4
+
+/* End VM-specific. */
+
+struct JNIInvokeInterface_ {
+    void *reserved0;
+    void *reserved1;
+    void *reserved2;
+
+    jint (JNICALL *DestroyJavaVM)(JavaVM *vm);
+
+    jint (JNICALL *AttachCurrentThread)(JavaVM *vm, void **penv, void *args);
+
+    jint (JNICALL *DetachCurrentThread)(JavaVM *vm);
+
+    jint (JNICALL *GetEnv)(JavaVM *vm, void **penv, jint version);
+
+    jint (JNICALL *AttachCurrentThreadAsDaemon)(JavaVM *vm, void **penv, void *args);
+};
+
+struct JavaVM_ {
+    const struct JNIInvokeInterface_ *functions;
+#ifdef __cplusplus
+
+    jint DestroyJavaVM() {
+        return functions->DestroyJavaVM(this);
+    }
+    jint AttachCurrentThread(void **penv, void *args) {
+        return functions->AttachCurrentThread(this, penv, args);
+    }
+    jint DetachCurrentThread() {
+        return functions->DetachCurrentThread(this);
+    }
+
+    jint GetEnv(void **penv, jint version) {
+        return functions->GetEnv(this, penv, version);
+    }
+    jint AttachCurrentThreadAsDaemon(void **penv, void *args) {
+        return functions->AttachCurrentThreadAsDaemon(this, penv, args);
+    }
+#endif
+};
+
+#ifdef _JNI_IMPLEMENTATION_
+#define _JNI_IMPORT_OR_EXPORT_ JNIEXPORT
+#else
+#define _JNI_IMPORT_OR_EXPORT_ JNIIMPORT
+#endif
+_JNI_IMPORT_OR_EXPORT_ jint JNICALL
+JNI_GetDefaultJavaVMInitArgs(void *args);
+
+_JNI_IMPORT_OR_EXPORT_ jint JNICALL
+JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args);
+
+_JNI_IMPORT_OR_EXPORT_ jint JNICALL
+JNI_GetCreatedJavaVMs(JavaVM **, jsize, jsize *);
+
+/* Defined by native libraries. */
+JNIEXPORT jint JNICALL
+JNI_OnLoad(JavaVM *vm, void *reserved);
+
+JNIEXPORT void JNICALL
+JNI_OnUnload(JavaVM *vm, void *reserved);
+
+#define JNI_VERSION_1_1 0x00010001
+#define JNI_VERSION_1_2 0x00010002
+#define JNI_VERSION_1_4 0x00010004
+#define JNI_VERSION_1_6 0x00010006
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* !_JAVASOFT_JNI_H_ */
+
+
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/jni_md.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/jni_md.h
new file mode 100644 (file)
index 0000000..9ac4718
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * %W% %E%
+ *
+ * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ */
+
+#ifndef _JAVASOFT_JNI_MD_H_
+#define _JAVASOFT_JNI_MD_H_
+
+#define JNIEXPORT __declspec(dllexport)
+#define JNIIMPORT __declspec(dllimport)
+#define JNICALL __stdcall
+
+typedef long jint;
+typedef __int64 jlong;
+typedef signed char jbyte;
+
+#endif /* !_JAVASOFT_JNI_MD_H_ */
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/libexpatMT.lib b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/libexpatMT.lib
new file mode 100644 (file)
index 0000000..2436f61
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/libexpatMT.lib differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/org_simantics_fmu_FMUControlJNI.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/org_simantics_fmu_FMUControlJNI.h
new file mode 100644 (file)
index 0000000..2059987
--- /dev/null
@@ -0,0 +1,181 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */\r
+#include <jni.h>\r
+/* Header for class org_simantics_fmu_FMUControlJNI */\r
+\r
+#ifndef _Included_org_simantics_fmu_FMUControlJNI\r
+#define _Included_org_simantics_fmu_FMUControlJNI\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    loadFMUFile_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_loadFMUFile_1\r
+  (JNIEnv *, jobject, jstring, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setStepLength_\r
+ * Signature: (Ljava/lang/String;D)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setStepLength_1\r
+  (JNIEnv *, jobject, jstring, jdouble);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    instantiateSimulation_\r
+ * Signature: (Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_instantiateSimulation_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    initializeSimulation_\r
+ * Signature: (Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_initializeSimulation_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    subscribe_\r
+ * Signature: (Ljava/lang/String;[Ljava/lang/String;I)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_subscribe_1\r
+  (JNIEnv *, jobject, jstring, jobjectArray, jint);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setRealValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;D)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setRealValue_1\r
+  (JNIEnv *, jobject, jstring, jstring, jdouble);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setIntegerValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;I)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setIntegerValue_1\r
+  (JNIEnv *, jobject, jstring, jstring, jint);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setBooleanValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;Z)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setBooleanValue_1\r
+  (JNIEnv *, jobject, jstring, jstring, jboolean);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setTime_\r
+ * Signature: (Ljava/lang/String;D)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setTime_1\r
+  (JNIEnv *, jobject, jstring, jdouble);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    simulateStep_\r
+ * Signature: (Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_simulateStep_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getSubscribedResults_\r
+ * Signature: (Ljava/lang/String;[D)[D\r
+ */\r
+JNIEXPORT jdoubleArray JNICALL Java_org_simantics_fmu_FMUControlJNI_getSubscribedResults_1\r
+  (JNIEnv *, jobject, jstring, jdoubleArray);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    unloadFMU_\r
+ * Signature: (Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_unloadFMU_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    isInitialized_\r
+ * Signature: (Ljava/lang/String;)Z\r
+ */\r
+JNIEXPORT jboolean JNICALL Java_org_simantics_fmu_FMUControlJNI_isInitialized_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getTime_\r
+ * Signature: (Ljava/lang/String;)D\r
+ */\r
+JNIEXPORT jdouble JNICALL Java_org_simantics_fmu_FMUControlJNI_getTime_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getAllVariables_\r
+ * Signature: (Ljava/lang/String;)[Ljava/lang/String;\r
+ */\r
+JNIEXPORT jobjectArray JNICALL Java_org_simantics_fmu_FMUControlJNI_getAllVariables_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    filterVariables_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;\r
+ */\r
+JNIEXPORT jobjectArray JNICALL Java_org_simantics_fmu_FMUControlJNI_filterVariables_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getLastErrorMessage_\r
+ * Signature: (Ljava/lang/String;)Ljava/lang/String;\r
+ */\r
+JNIEXPORT jstring JNICALL Java_org_simantics_fmu_FMUControlJNI_getLastErrorMessage_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getRealValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)D\r
+ */\r
+JNIEXPORT jdouble JNICALL Java_org_simantics_fmu_FMUControlJNI_getRealValue_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getStringValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;\r
+ */\r
+JNIEXPORT jstring JNICALL Java_org_simantics_fmu_FMUControlJNI_getStringValue_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getIntegerValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_getIntegerValue_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getBooleanValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)Z\r
+ */\r
+JNIEXPORT jboolean JNICALL Java_org_simantics_fmu_FMUControlJNI_getBooleanValue_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/sim_support.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/sim_support.h
new file mode 100644 (file)
index 0000000..a2a5180
--- /dev/null
@@ -0,0 +1,31 @@
+/* ------------------------------------------------------------------------- \r
+ * sim_support.h\r
+ * Functions used by the FMU simulatios fmusim_me and fmusim_cs.\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+// Used 7z options, version 4.57:\r
+// -x   Extracts files from an archive with their full paths in the current dir, or in an output dir if specified\r
+// -aoa Overwrite All existing files without prompt\r
+// -o   Specifies a destination directory where files are to be extracted\r
+#define UNZIP_CMD "7z x -aoa -o"\r
+#define XML_FILE  "modelDescription.xml"\r
+#define DLL_DIR   "binaries\\win32\\"\r
+#define RESULT_FILE "result.csv"\r
+#define BUFSIZE 4096\r
+\r
+// return codes of the 7z command line tool\r
+#define SEVEN_ZIP_NO_ERROR 0 // success\r
+#define SEVEN_ZIP_WARNING 1  // e.g., one or more files were locked during zip\r
+#define SEVEN_ZIP_ERROR 2\r
+#define SEVEN_ZIP_COMMAND_LINE_ERROR 7\r
+#define SEVEN_ZIP_OUT_OF_MEMORY 8\r
+#define SEVEN_ZIP_STOPPED_BY_USER 255\r
+\r
+void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status, fmiString category, fmiString message, ...);\r
+int unzip(const char *zipPath, const char *outPath);\r
+void parseArguments(int argc, char *argv[], char** fmuFileName, double* tEnd, double* h, int* loggingOn, char* csv_separator);\r
+int loadFMU(FMU *fmu, const char* fmuFileName, const char* tmpPath);\r
+void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, boolean header);\r
+int error(const char* message);\r
+void printHelp(const char* fmusim);\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/stack.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/stack.h
new file mode 100644 (file)
index 0000000..a52977f
--- /dev/null
@@ -0,0 +1,28 @@
+/* ------------------------------------------------------------------------- \r
+ * stack.c\r
+ * A stack of pointers. \r
+ * Copyright 2010 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#ifndef STACK_H\r
+#define STACK_H\r
+\r
+typedef struct {\r
+    void** stack;\r
+    int stackSize;    // allocated size of stack\r
+    int stackPos;     // array index of top element, -1 if stack is empty.\r
+    int initialSize;  // how many element to allocate initially\r
+    int inc;          // how many elements to allocate when stack gets full\r
+} Stack;\r
+\r
+Stack* stackNew(int initialSize, int inc);\r
+int stackIsEmpty(Stack* s);\r
+int stackPush(Stack* s, void* e);\r
+void* stackPeek(Stack* s);\r
+void* stackPop(Stack* s);\r
+void** stackPopAllAsArray(Stack* s, int *size);\r
+void** stackLastPopedAsArray0(Stack* s, int n);\r
+void stackFree(Stack* s);\r
+\r
+#endif // STACK_H\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/trees.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/trees.h
new file mode 100644 (file)
index 0000000..d35639d
--- /dev/null
@@ -0,0 +1,128 @@
+/* header created automatically with -DGEN_TREES_H */
+
+local const ct_data static_ltree[L_CODES+2] = {
+{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},
+{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},
+{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},
+{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},
+{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},
+{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},
+{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},
+{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},
+{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},
+{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},
+{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},
+{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},
+{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},
+{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},
+{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},
+{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},
+{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},
+{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},
+{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},
+{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},
+{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},
+{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},
+{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},
+{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},
+{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},
+{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},
+{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},
+{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},
+{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},
+{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},
+{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},
+{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},
+{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},
+{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},
+{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},
+{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},
+{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},
+{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},
+{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},
+{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},
+{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},
+{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},
+{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},
+{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},
+{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},
+{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},
+{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},
+{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},
+{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},
+{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},
+{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},
+{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},
+{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},
+{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},
+{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},
+{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},
+{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},
+{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}
+};
+
+local const ct_data static_dtree[D_CODES] = {
+{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
+{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
+{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
+{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
+{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
+{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
+};
+
+const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
+ 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
+ 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
+10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
+13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
+18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
+23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
+};
+
+const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
+ 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
+13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
+17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
+19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
+22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
+23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
+};
+
+local const int base_length[LENGTH_CODES] = {
+0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
+64, 80, 96, 112, 128, 160, 192, 224, 0
+};
+
+local const int base_dist[D_CODES] = {
+    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
+   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
+ 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
+};
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/xml_parser.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/xml_parser.h
new file mode 100644 (file)
index 0000000..0730d56
--- /dev/null
@@ -0,0 +1,159 @@
+/* ------------------------------------------------------------------------- \r
+ * xml_parser.h\r
+ * A parser for file modelVariables.xml of an FMU.\r
+ * Supports "FMI for Model Exchange 1.0" and "FMI for Co-Simulation 1.0".\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/\r
+\r
+#ifndef xml_parser_h\r
+#define xml_parser_h\r
+\r
+// define XML_STATIC before including expat.h\r
+// to prevent error when linking with libexpatMT.lib\r
+#define XML_STATIC \r
+#include "expat.h"\r
+#include "stack.h"\r
+\r
+typedef unsigned int fmiValueReference;\r
+#define fmiUndefinedValueReference (fmiValueReference)(-1)\r
+\r
+#define SIZEOF_ELM 31\r
+extern const char *elmNames[SIZEOF_ELM];\r
+\r
+#define SIZEOF_ATT 47\r
+extern const char *attNames[SIZEOF_ATT];\r
+\r
+#define SIZEOF_ENU 13\r
+extern const char *enuNames[SIZEOF_ENU];\r
+\r
+// Elements\r
+typedef enum {\r
+    elm_fmiModelDescription,elm_UnitDefinitions,elm_BaseUnit,elm_DisplayUnitDefinition,elm_TypeDefinitions,\r
+    elm_Type,elm_RealType,elm_IntegerType,elm_BooleanType,elm_StringType,elm_EnumerationType,elm_Item,\r
+    elm_DefaultExperiment,elm_VendorAnnotations,elm_Tool,elm_Annotation,elm_ModelVariables,elm_ScalarVariable,\r
+    elm_DirectDependency,elm_Name,elm_Real,elm_Integer,elm_Boolean,elm_String,elm_Enumeration,\r
+    elm_Implementation,elm_CoSimulation_StandAlone,elm_CoSimulation_Tool,elm_Model,elm_File,elm_Capabilities\r
+} Elm;\r
+\r
+// Attributes\r
+typedef enum { \r
+  att_fmiVersion,att_displayUnit,att_gain,att_offset,att_unit,att_name,att_description,att_quantity,att_relativeQuantity,\r
+  att_min,att_max,att_nominal,att_declaredType,att_start,att_fixed,att_startTime,att_stopTime,att_tolerance,att_value,\r
+  att_valueReference,att_variability,att_causality,att_alias,att_modelName,att_modelIdentifier,att_guid,att_author,\r
+  att_version,att_generationTool,att_generationDateAndTime,att_variableNamingConvention,att_numberOfContinuousStates,\r
+  att_numberOfEventIndicators,att_input,\r
+  att_canHandleVariableCommunicationStepSize,att_canHandleEvents,att_canRejectSteps,att_canInterpolateInputs,\r
+  att_maxOutputDerivativeOrder,att_canRunAsynchronuously,att_canSignalEvents,att_canBeInstantiatedOnlyOncePerProcess,\r
+  att_canNotUseMemoryManagementFunctions,att_entryPoint,att_manualStart,att_type\r
+} Att;\r
+\r
+// Enumeration values\r
+typedef enum {\r
+    enu_flat,enu_structured,enu_constant,enu_parameter,enu_discrete,enu_continuous,\r
+    enu_input,enu_output,enu_internal,enu_none,enu_noAlias,enu_alias,enu_negatedAlias    \r
+} Enu;\r
+\r
+// AST node for element \r
+// DisplayUnitDefinition, RealType, IntegerType, BooleanType, StringType, DefaultExperiment, \r
+// Item, Annotation, Name, Real, Integer, Boolean, String, Enumeration, Capabilities, File\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+} Element;\r
+\r
+// AST node for element that has a list of elements \r
+// BaseUnit, EnumerationType, Tool, DirectDependency, Model\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    Element** list;    // null-terminated array of pointers to elements, not null\r
+} ListElement;\r
+\r
+// AST node for element Type\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, an even number\r
+    Element* typeSpec; // one of RealType, IntegerType etc. \r
+} Type;\r
+\r
+// AST node for element ScalarVariable\r
+typedef struct {\r
+    Elm type;          // element type \r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    Element* typeSpec; // one of Real, Integer, etc\r
+    Element** directDependencies; // null or null-terminated list of Name\r
+} ScalarVariable;\r
+\r
+// AST node for element CoSimulation_StandAlone and CoSimulation_Tool\r
+typedef struct {\r
+    Elm type; // one of elm_CoSimulation_StandAlone and elm_CoSimulation_Tool\r
+    const char** attributes; // null or n attribute value strings\r
+    int n;                   // size of attributes, even number\r
+    Element* capabilities;   // a set of capability attributes\r
+    ListElement* model;      // non-NULL to support tool coupling, NULL for standalone \r
+} CoSimulation;\r
+\r
+// AST node for element ModelDescription\r
+typedef struct {\r
+    Elm type;          // element type\r
+    const char** attributes; // null or n attribute value strings\r
+    int n;             // size of attributes, even number\r
+    ListElement** unitDefinitions;    // NULL or null-terminated list of BaseUnits\r
+    Type**        typeDefinitions;    // NULL or null-terminated list of Types \r
+    Element*      defaultExperiment;  // NULL or DefaultExperiment\r
+    ListElement** vendorAnnotations;  // NULL or null-terminated list of Tools\r
+    ScalarVariable** modelVariables;  // NULL or null-terminated list of ScalarVariable\r
+    CoSimulation* cosimulation;       // NULL if this ModelDescription is for model exchange only\r
+} ModelDescription;\r
+\r
+// types of AST nodes used to represent an element\r
+typedef enum { \r
+    astElement, \r
+    astListElement,\r
+    astType,\r
+    astScalarVariable,\r
+    astCoSimulation,\r
+    astModelDescription\r
+} AstNodeType;\r
+\r
+// Possible results when retrieving an attribute value from an element\r
+typedef enum { \r
+    valueMissing,\r
+    valueDefined,\r
+    valueIllegal\r
+} ValueStatus;\r
+\r
+// Public methods: Parsing and low-level AST access\r
+ModelDescription* parse(const char* xmlPath);\r
+const char* getString(void* element, Att a);\r
+double getDouble     (void* element, Att a, ValueStatus* vs);\r
+int getInt           (void* element, Att a, ValueStatus* vs);\r
+unsigned int getUInt (void* element, Att a, ValueStatus* vs);\r
+char getBoolean      (void* element, Att a, ValueStatus* vs);\r
+Enu getEnumValue     (void* element, Att a, ValueStatus* vs);\r
+void freeElement     (void* element);\r
+\r
+// Convenience methods for AST access. To be used afer successful validation only.\r
+const char* getModelIdentifier(ModelDescription* md);\r
+int getNumberOfStates(ModelDescription* md);\r
+int getNumberOfEventIndicators(ModelDescription* md);\r
+const char* getName(void* element);\r
+Enu getCausality(void* scalarVariable);\r
+Enu getVariability(void* scalarVariable);\r
+Enu getAlias(void* scalarVariable);\r
+fmiValueReference getValueReference(void* scalarVariable);\r
+ScalarVariable* getVariableByName(ModelDescription* md, const char* name);\r
+ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type);\r
+Type* getDeclaredType(ModelDescription* md, const char* declaredType);\r
+const char* getString2(ModelDescription* md, void* sv, Att a);\r
+const char * getDescription(ModelDescription* md, ScalarVariable* sv);\r
+const char * getVariableAttributeString(ModelDescription* md, fmiValueReference vr, Elm type, Att a);\r
+double getVariableAttributeDouble(ModelDescription* md, fmiValueReference vr, Elm type, Att a, ValueStatus* vs);\r
+double getNominal(ModelDescription* md, fmiValueReference vr);\r
+\r
+#endif // xml_parser_h\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/zutil.h b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/include/zutil.h
new file mode 100644 (file)
index 0000000..dff1112
--- /dev/null
@@ -0,0 +1,248 @@
+/* zutil.h -- internal interface and configuration of the compression library
+ * Copyright (C) 1995-2011 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZUTIL_H
+#define ZUTIL_H
+
+#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ)
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
+#include "zlib.h"
+
+#if defined(STDC) && !defined(Z_SOLO)
+#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
+#    include <stddef.h>
+#  endif
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+
+#ifdef Z_SOLO
+   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */
+#endif
+
+#ifndef local
+#  define local static
+#endif
+/* compile with -Dlocal if your debugger can't find static symbols */
+
+typedef unsigned char  uch;
+typedef uch FAR uchf;
+typedef unsigned short ush;
+typedef ush FAR ushf;
+typedef unsigned long  ulg;
+
+extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
+/* (size given to avoid silly warnings with Visual C++) */
+
+#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
+
+#define ERR_RETURN(strm,err) \
+  return (strm->msg = (char*)ERR_MSG(err), (err))
+/* To be used only when the state is known to be valid */
+
+        /* common constants */
+
+#ifndef DEF_WBITS
+#  define DEF_WBITS MAX_WBITS
+#endif
+/* default windowBits for decompression. MAX_WBITS is for compression only */
+
+#if MAX_MEM_LEVEL >= 8
+#  define DEF_MEM_LEVEL 8
+#else
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#endif
+/* default memLevel */
+
+#define STORED_BLOCK 0
+#define STATIC_TREES 1
+#define DYN_TREES    2
+/* The three kinds of block type */
+
+#define MIN_MATCH  3
+#define MAX_MATCH  258
+/* The minimum and maximum match lengths */
+
+#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
+
+        /* target dependencies */
+
+#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
+#  define OS_CODE  0x00
+#  ifndef Z_SOLO
+#    if defined(__TURBOC__) || defined(__BORLANDC__)
+#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
+         /* Allow compilation with ANSI keywords only enabled */
+         void _Cdecl farfree( void *block );
+         void *_Cdecl farmalloc( unsigned long nbytes );
+#      else
+#        include <alloc.h>
+#      endif
+#    else /* MSC or DJGPP */
+#      include <malloc.h>
+#    endif
+#  endif
+#endif
+
+#ifdef AMIGA
+#  define OS_CODE  0x01
+#endif
+
+#if defined(VAXC) || defined(VMS)
+#  define OS_CODE  0x02
+#  define F_OPEN(name, mode) \
+     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
+#endif
+
+#if defined(ATARI) || defined(atarist)
+#  define OS_CODE  0x05
+#endif
+
+#ifdef OS2
+#  define OS_CODE  0x06
+#  if defined(M_I86) && !defined(Z_SOLO)
+#    include <malloc.h>
+#  endif
+#endif
+
+#if defined(MACOS) || defined(TARGET_OS_MAC)
+#  define OS_CODE  0x07
+#  ifndef Z_SOLO
+#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
+#      include <unix.h> /* for fdopen */
+#    else
+#      ifndef fdopen
+#        define fdopen(fd,mode) NULL /* No fdopen() */
+#      endif
+#    endif
+#  endif
+#endif
+
+#ifdef TOPS20
+#  define OS_CODE  0x0a
+#endif
+
+#ifdef WIN32
+#  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */
+#    define OS_CODE  0x0b
+#  endif
+#endif
+
+#ifdef __50SERIES /* Prime/PRIMOS */
+#  define OS_CODE  0x0f
+#endif
+
+#if defined(_BEOS_) || defined(RISCOS)
+#  define fdopen(fd,mode) NULL /* No fdopen() */
+#endif
+
+#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
+#  if defined(_WIN32_WCE)
+#    define fdopen(fd,mode) NULL /* No fdopen() */
+#    ifndef _PTRDIFF_T_DEFINED
+       typedef int ptrdiff_t;
+#      define _PTRDIFF_T_DEFINED
+#    endif
+#  else
+#    define fdopen(fd,type)  _fdopen(fd,type)
+#  endif
+#endif
+
+#if defined(__BORLANDC__) && !defined(MSDOS)
+  #pragma warn -8004
+  #pragma warn -8008
+  #pragma warn -8066
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_WIN32) && (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
+    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#endif
+
+        /* common defaults */
+
+#ifndef OS_CODE
+#  define OS_CODE  0x03  /* assume Unix */
+#endif
+
+#ifndef F_OPEN
+#  define F_OPEN(name, mode) fopen((name), (mode))
+#endif
+
+         /* functions */
+
+#if defined(pyr) || defined(Z_SOLO)
+#  define NO_MEMCPY
+#endif
+#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
+ /* Use our own functions for small and medium model with MSC <= 5.0.
+  * You may have to use the same strategy for Borland C (untested).
+  * The __SC__ check is for Symantec.
+  */
+#  define NO_MEMCPY
+#endif
+#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
+#  define HAVE_MEMCPY
+#endif
+#ifdef HAVE_MEMCPY
+#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */
+#    define zmemcpy _fmemcpy
+#    define zmemcmp _fmemcmp
+#    define zmemzero(dest, len) _fmemset(dest, 0, len)
+#  else
+#    define zmemcpy memcpy
+#    define zmemcmp memcmp
+#    define zmemzero(dest, len) memset(dest, 0, len)
+#  endif
+#else
+   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
+   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
+   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
+#endif
+
+/* Diagnostic functions */
+#ifdef DEBUG
+#  include <stdio.h>
+   extern int ZLIB_INTERNAL z_verbose;
+   extern void ZLIB_INTERNAL z_error OF((char *m));
+#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
+#  define Trace(x) {if (z_verbose>=0) fprintf x ;}
+#  define Tracev(x) {if (z_verbose>0) fprintf x ;}
+#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}
+#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
+#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
+#else
+#  define Assert(cond,msg)
+#  define Trace(x)
+#  define Tracev(x)
+#  define Tracevv(x)
+#  define Tracec(c,x)
+#  define Tracecv(c,x)
+#endif
+
+#ifndef Z_SOLO
+   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
+                                    unsigned size));
+   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
+#endif
+
+#define ZALLOC(strm, items, size) \
+           (*((strm)->zalloc))((strm)->opaque, (items), (size))
+#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
+#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
+
+#endif /* ZUTIL_H */
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/fmu_control.cpp b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/fmu_control.cpp
new file mode 100644 (file)
index 0000000..a021729
--- /dev/null
@@ -0,0 +1,944 @@
+/* ------------------------------------------------------------------------- \r
+ * fmu_control.c\r
+ * Simulation controls for fmus\r
+ *\r
+ * Free libraries and tools used to implement this simulator:\r
+ *  - header files from the FMU specification\r
+ *  - eXpat 2.0.1 XML parser, see http://expat.sourceforge.net\r
+ *  - 7z.exe 4.57 zip and unzip tool, see http://www.7-zip.org <---------- Replace with zlib\r
+ * Author: Teemu Lempinen\r
+ * Copyright 2012 Semantum Oy\r
+ * -------------------------------------------------------------------------\r
+ */\r
+\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <map>\r
+#include <string>\r
+#include <vector>\r
+#include <iostream>\r
+#include <regex>\r
+\r
+#include <org_simantics_fmu_FMUControlJNI.h>\r
+\r
+extern "C" {\r
+       #include "fmi_me.h"\r
+       #include "sim_support.h"\r
+}\r
+\r
+#define PRINT(fmt,args) { FILE *fp = fopen("R:\\Simantics\\Sysdyn\\log.txt", "ab"); fprintf(fp, fmt, args); fclose(fp); }\r
+\r
+#include <direct.h>\r
+#define GetCurrentDir _getcwd\r
+\r
+using namespace std;\r
+\r
+\r
+struct FMUControlStruct {\r
+       double step;                                    // simulation step length\r
+       fmiReal currentTime;                    // current simulation time\r
+\r
+       fmiComponent c;                                 // instance of the fmu \r
+       ScalarVariable** vars;                  // model variables\r
+\r
+       fmiEventInfo eventInfo;         // updated by calls to initialize and eventUpdate\r
+       const char* guid;               // global unique id of the fmu\r
+       fmiCallbackFunctions callbacks; // called by the model during simulation\r
+       fmiStatus fmiFlag;              // return code of the fmu functions\r
+\r
+       map<string,int> indexes;                // indexes for variable names in vars-table\r
+       map<string,int>::iterator it;\r
+\r
+       int nx;                                                 // number of state variables\r
+       double *x;                                              // continuous states\r
+       double *xdot;                                   // the crresponding derivatives in same order\r
+       int nz;                         // number of state event indicators\r
+       double *z;                                              // state event indicators\r
+       double *prez;                                   // previous values of state event indicators\r
+       \r
+       bool initialized;                               // has the fmu been initialized\r
+\r
+       vector<fmiValueReference> subscription;         // result subscriptions\r
+       vector<string> allVariables;    // all variables in an initialized model\r
+       vector<fmiValueReference> fmiValueReferences;           // all value references\r
+\r
+       string lastErrorMessage;\r
+\r
+       FMU fmu;\r
+};\r
+\r
+map<string,FMUControlStruct> fmus;             // indexes for variable names in vars-table\r
+\r
+\r
+int throwException(JNIEnv *env, string message) {\r
+       jclass newExcCls;\r
+    newExcCls = env->FindClass("java/lang/Exception");\r
+    if (newExcCls == NULL) {\r
+        /* Unable to find the exception class, give up. */\r
+        return 0;\r
+    }\r
+       env->ThrowNew(newExcCls, message.c_str());\r
+       return 0;\r
+}\r
+\r
+bool exists(string id) {\r
+       map<string,FMUControlStruct>::iterator it = fmus.find(id);\r
+       if(it != fmus.end()) {\r
+               return true;\r
+       } else {\r
+               return false;\r
+       }\r
+}\r
+\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_loadFMUFile_1 \r
+       (JNIEnv *env, jobject obj, jstring id, jstring path, jstring tempDir) {\r
+       HMODULE module = NULL;\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+    const char *fmuPath = env->GetStringUTFChars(path, 0);\r
+       const char *fmuTempDir = env->GetStringUTFChars(tempDir, 0);\r
+\r
+       if(exists(fmuId)) {\r
+               // If a model has been loaded with this id, remove its contents. \r
+               // Old dll is released after loading the new from a different directory\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               module = (HMODULE)fmuStruct.fmu.dllHandle;\r
+               if (fmuStruct.c!=NULL) fmuStruct.fmu.freeModelInstance(fmuStruct.c);\r
+               if (fmuStruct.x!=NULL) free(fmuStruct.x);\r
+               if (fmuStruct.xdot!= NULL) free(fmuStruct.xdot);\r
+               if (fmuStruct.z!= NULL) free(fmuStruct.z);\r
+               if (fmuStruct.prez!= NULL) free(fmuStruct.prez);\r
+               FMU& fmu = fmuStruct.fmu;\r
+               ModelDescription *md = fmu.modelDescription;\r
+               freeElement(md);\r
+       } else {\r
+               // Create new control struct\r
+               fmus.insert( pair<string,FMUControlStruct>(string(fmuId), FMUControlStruct()) );\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               fmuStruct.currentTime = 0;      \r
+\r
+               fmuStruct.c = NULL;\r
+               fmuStruct.x = NULL;\r
+               fmuStruct.xdot = NULL; \r
+               fmuStruct.z = NULL;\r
+               fmuStruct.prez = NULL;   \r
+       }\r
+\r
+       FMUControlStruct& fmuStruct = fmus[fmuId];\r
+       // Extract fmu from fmuPath to fmuTempDir and load it to fmuStruct.fmu\r
+       int ret = loadFMU(&fmuStruct.fmu, fmuPath, fmuTempDir); \r
+       if(fmuStruct.fmu.modelDescription != NULL) {\r
+               fmuStruct.vars = fmuStruct.fmu.modelDescription->modelVariables;\r
+\r
+               fmuStruct.fmiValueReferences.clear();\r
+\r
+               int i;\r
+               for (i=0; fmuStruct.vars[i]; i++) {\r
+                       fmuStruct.fmiValueReferences.push_back(getValueReference(fmuStruct.vars[i]));\r
+               }\r
+\r
+       } else {\r
+               fmuStruct.vars = NULL;\r
+       }\r
+\r
+       if(module != NULL) {\r
+               /* \r
+               * If there was a previously loaded fmu for this id, unload its dll here.\r
+               * This is done only after loading the new model dll to ensure that \r
+               * related dlls are not unloaded\r
+               */ \r
+               FreeLibrary(module);\r
+       }\r
+\r
+       env->ReleaseStringUTFChars(id, fmuId);\r
+       env->ReleaseStringUTFChars(path, fmuPath);\r
+       env->ReleaseStringUTFChars(tempDir, fmuTempDir);\r
+       fflush(stdout);\r
+\r
+       /*\r
+        * Possible error messages from sim_support.c for loadFMU\r
+        * -1. FMU path not found\r
+        * -2. Unzip failed\r
+        * -3. Loading model description failed\r
+        * -4. FMU dll load failed\r
+        */\r
+       switch(ret) {\r
+               case -1:\r
+                       ret = throwException(env, "FMU path not found");\r
+                       break;\r
+               case -2:\r
+                       ret = throwException(env, "FMU Unzip failed");\r
+                       break;\r
+               case -3:\r
+                       ret = throwException(env, "Loading model description failed");\r
+                       break;\r
+               case -4:\r
+                       ret = throwException(env, "FMU dll load failed");\r
+                       break;\r
+       }\r
+\r
+       return ret;\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setStepLength_1 \r
+       (JNIEnv *env, jobject obj, jstring id, jdouble stepLength) {\r
+       int ret = 1;\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               fmuStruct.step = stepLength;\r
+       } else {\r
+               ret = 0;\r
+       }\r
+\r
+       env->ReleaseStringUTFChars(id, fmuId);\r
+       return ret;\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_subscribe_1\r
+  (JNIEnv *env, jobject obj, jstring id, jobjectArray names, jint size) {\r
+\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               size_t count = env->GetArrayLength(names);\r
+\r
+\r
+               // Reinitialize subscription\r
+               fmuStruct.subscription.clear();\r
+               if(fmuStruct.subscription.capacity() < count)\r
+                       fmuStruct.subscription.reserve(count);\r
+\r
+               // Add values in order\r
+               map<string,int>::iterator it;\r
+               for (size_t i=0; i<count; i++) {\r
+                       jstring string = (jstring) env->GetObjectArrayElement(names, i);\r
+                       const char *name = env->GetStringUTFChars(string, 0);\r
+                       it = fmuStruct.indexes.find(name);\r
+\r
+                       if(it != fmuStruct.indexes.end()) {\r
+                               // Found the subscribed element\r
+                               fmuStruct.subscription.push_back(fmuStruct.fmiValueReferences[fmuStruct.indexes[name]]);\r
+                       } else {\r
+                               // Element not found, use index -1\r
+                               fmuStruct.subscription.push_back(-1);\r
+                       }\r
+                       env->ReleaseStringUTFChars(string, name);\r
+               }\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return 1;\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "Subscribe: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+bool referenceExists(FMUControlStruct fmuStruct, string variable) {\r
+       map<string,int>::iterator it = fmuStruct.indexes.find(variable);\r
+       if(it != fmuStruct.indexes.end()) {\r
+               return true;\r
+       } else {\r
+               return false;\r
+       }\r
+}\r
+\r
+// Remember to check if reference exists\r
+fmiValueReference getReference(FMUControlStruct fmuStruct, string variable) {\r
+       return fmuStruct.fmiValueReferences[fmuStruct.indexes[variable]];\r
+}\r
+\r
+// Get string representation of a scalar variable type\r
+string getTypeString(ScalarVariable* sv) {\r
+       switch (sv->typeSpec->type){\r
+               case elm_Integer:\r
+                       return "Integer";\r
+               case elm_Enumeration:\r
+                       return "Enumeration";\r
+               case elm_Real:\r
+                       return "Real";\r
+               case elm_Boolean:\r
+                       return "Boolean";\r
+               default:\r
+                       return "No type";\r
+       }\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setRealValue_1\r
+  (JNIEnv *env, jobject obj, jstring id, jstring parameter, jdouble value) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               const char *name = env->GetStringUTFChars(parameter, 0);\r
+               string nameString = name;\r
+               string modelId = fmuId;\r
+               if(!referenceExists(fmuStruct, name)) {\r
+                       string errorMessage = "setRealValue: Model (id " + modelId + ") does not contain variable: " + nameString;\r
+                       env->ReleaseStringUTFChars(parameter, name);\r
+                       env->ReleaseStringUTFChars(id, fmuId);\r
+                       return throwException(env, errorMessage);\r
+               } else {\r
+                       // Check variable type\r
+                       ScalarVariable* sv = fmuStruct.vars[fmuStruct.indexes[name]];\r
+                       switch (sv->typeSpec->type){\r
+                               case elm_Real:\r
+                                       break; // ok\r
+                               default: {\r
+                                       string errorMessage = "setRealValue: " + nameString + " is not of type Real. (type: + " + getTypeString(sv) + ")";\r
+                                       env->ReleaseStringUTFChars(parameter, name);\r
+                                       env->ReleaseStringUTFChars(id, fmuId);\r
+                                       return throwException(env, errorMessage);\r
+                               }\r
+                       }\r
+\r
+                       // Change value\r
+                       fmiValueReference vr = getReference(fmuStruct, name);\r
+                       fmuStruct.fmu.setReal(fmuStruct.c, &vr, 1, &value);\r
+                       env->ReleaseStringUTFChars(parameter, name);\r
+                       env->ReleaseStringUTFChars(id, fmuId);\r
+                       return 1;\r
+               }\r
+       \r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "setRealValue: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setIntegerValue_1\r
+  (JNIEnv *env, jobject obj, jstring id, jstring parameter, jint value) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               const char *name = env->GetStringUTFChars(parameter, 0);\r
+               string nameString = name;\r
+               string modelId = fmuId;\r
+               if(!referenceExists(fmuStruct, name)) {\r
+                       string errorMessage = "setIntegerValue: Model (id " + modelId + ") does not contain variable: " + nameString;\r
+                       env->ReleaseStringUTFChars(parameter, name);\r
+                       env->ReleaseStringUTFChars(id, fmuId);\r
+                       return throwException(env, errorMessage);\r
+               } else {\r
+                       // Check variable type\r
+                       ScalarVariable* sv = fmuStruct.vars[fmuStruct.indexes[name]];\r
+                       switch (sv->typeSpec->type){\r
+                               case elm_Integer:\r
+                                       break; // ok\r
+                               default: {\r
+                                       string errorMessage = "setIntegerValue: " + nameString + " is not of type Integer. (type: + " + getTypeString(sv) + ")";\r
+                                       env->ReleaseStringUTFChars(parameter, name);\r
+                                       env->ReleaseStringUTFChars(id, fmuId);\r
+                                       return throwException(env, errorMessage);\r
+                               }\r
+                       }\r
+\r
+                       // Change value\r
+                       fmiValueReference vr = getReference(fmuStruct, name);\r
+                       const int intValue = (int) value;\r
+                       fmuStruct.fmu.setInteger(fmuStruct.c, &vr, 1, &intValue);\r
+                       env->ReleaseStringUTFChars(parameter, name);\r
+                       env->ReleaseStringUTFChars(id, fmuId);\r
+                       return 1;\r
+               }\r
+       }  else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "setIntegerValue: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setBooleanValue_1\r
+  (JNIEnv *env, jobject obj, jstring id, jstring parameter, jboolean value) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               const char *name = env->GetStringUTFChars(parameter, 0);\r
+               string nameString = name;\r
+               string modelId = fmuId;\r
+               if(!referenceExists(fmuStruct, name)) {\r
+                       string errorMessage = "setBooleanValue: Model (id " + modelId + ") does not contain variable: " + nameString;\r
+                       env->ReleaseStringUTFChars(parameter, name);\r
+                       env->ReleaseStringUTFChars(id, fmuId);\r
+                       return throwException(env, errorMessage);\r
+               } else {\r
+                       // Check variable type\r
+                       ScalarVariable* sv = fmuStruct.vars[fmuStruct.indexes[name]];\r
+                       switch (sv->typeSpec->type){\r
+                               case elm_Boolean:\r
+                                       break; // ok\r
+                               default: {\r
+                                       string errorMessage = "setBooleanValue: " + nameString + " is not of type Boolean. (type: + " + getTypeString(sv) + ")";\r
+                                       env->ReleaseStringUTFChars(parameter, name);\r
+                                       env->ReleaseStringUTFChars(id, fmuId);\r
+                                       return throwException(env, errorMessage);\r
+                               }\r
+                       }\r
+\r
+                       // Change value\r
+                       fmiValueReference vr = getReference(fmuStruct, name);\r
+                       fmiBoolean result = 1;\r
+                       if(value == 0)\r
+                               result = 0;\r
+                       fmuStruct.fmu.setBoolean(fmuStruct.c, &vr, 1, &result);\r
+                       env->ReleaseStringUTFChars(parameter, name);\r
+                       env->ReleaseStringUTFChars(id, fmuId);\r
+                       return 1;\r
+               }\r
+       }  else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "setBooleanValue: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+JNIEXPORT jboolean JNICALL Java_org_simantics_fmu_FMUControlJNI_isInitialized_1\r
+  (JNIEnv *env, jobject obj, jstring id) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return fmuStruct.initialized;\r
+       } else {\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return false;\r
+       }\r
+}\r
+\r
+\r
+JNIEXPORT jdouble JNICALL Java_org_simantics_fmu_FMUControlJNI_getTime_1\r
+  (JNIEnv *env, jobject obj, jstring id) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return fmuStruct.currentTime;\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               throwException(env, "getTime: Model id " + message + " not found");\r
+               return 0.0;\r
+       }\r
+}\r
+\r
+double getRealValue(FMUControlStruct fmuStruct, int index) {\r
+       ScalarVariable *sv = fmuStruct.vars[index];\r
+       fmiValueReference vr = fmuStruct.fmiValueReferences[index];\r
+       double real;\r
+       fmiInteger integer;\r
+       fmiBoolean fmibool;\r
+\r
+       switch (sv->typeSpec->type){\r
+        case elm_Real:\r
+                       fmuStruct.fmu.getReal(fmuStruct.c, &vr, 1, &real);\r
+            break;\r
+        case elm_Integer:\r
+        case elm_Enumeration:\r
+            fmuStruct.fmu.getInteger(fmuStruct.c, &vr, 1, &integer);\r
+                       real = (double)integer;\r
+            break;\r
+        case elm_Boolean:\r
+            fmuStruct.fmu.getBoolean(fmuStruct.c, &vr, 1, &fmibool);\r
+                       if(fmibool == fmiTrue)\r
+                               real = 1.0;\r
+                       else\r
+                               real = 0.0;\r
+            break;\r
+       }\r
+       return real;\r
+}\r
+\r
+JNIEXPORT jdoubleArray JNICALL Java_org_simantics_fmu_FMUControlJNI_getSubscribedResults_1\r
+  (JNIEnv *env, jobject obj, jstring id, jdoubleArray result) {\r
+\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+\r
+               jboolean isCopy;\r
+               jdouble* resultElements = env -> GetDoubleArrayElements(result, &isCopy);\r
+               jsize n = env -> GetArrayLength(result);\r
+\r
+               /*\r
+               int i;\r
+               for (i = 0; i < n; i++) {\r
+                       if(fmuStruct.subscription.empty() || fmuStruct.fmu.modelDescription == NULL) {\r
+                               // no subscription or model not initialized\r
+                               resultElements[i] = 0;\r
+                       } else if(fmuStruct.subscription[i] < 0) {\r
+                               // Variable does not exist\r
+                               resultElements[i] = 0;\r
+                       } else {\r
+                               // Get value \r
+                               resultElements[i] = getRealValue(fmuStruct, fmuStruct.subscription[i]);\r
+                       }\r
+               } \r
+               */\r
+\r
+               fmuStruct.fmu.getReal(fmuStruct.c, &fmuStruct.subscription[0], n, resultElements);\r
+\r
+               if (isCopy == JNI_TRUE) {\r
+                       env -> ReleaseDoubleArrayElements(result, resultElements, 0);\r
+               }\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               throwException(env, "getSubscribedResults: Model id " + message + " not found");\r
+       }\r
+       \r
+       return result;\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_instantiateSimulation_1\r
+  (JNIEnv *env, jobject obj, jstring id) {\r
+\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+\r
+               int k;\r
+               string s;\r
+\r
+\r
+               FMU& fmu = fmuStruct.fmu;\r
+\r
+               //ModelDescription* md = fmu.modelDescription;\r
+               if(fmu.modelDescription == NULL)\r
+                       return throwException(env, "No FMU loaded");\r
+\r
+               //fmuStruct.currentTime = 0; // start time\r
+\r
+               // instantiate the fmu\r
+               fmuStruct.guid = getString(fmu.modelDescription, att_guid);\r
+               fmuStruct.callbacks.logger = fmuLogger;\r
+               fmuStruct.callbacks.allocateMemory = calloc;\r
+               fmuStruct.callbacks.freeMemory = free;\r
+               fmuStruct.c = fmu.instantiateModel(getModelIdentifier(fmu.modelDescription), fmuStruct.guid, fmuStruct.callbacks, fmiFalse);\r
+               if (!fmuStruct.c) return throwException(env, "could not instantiate model");\r
+    \r
+               // allocate memory \r
+               fmuStruct.nx = getNumberOfStates(fmu.modelDescription);\r
+               fmuStruct.nz = getNumberOfEventIndicators(fmu.modelDescription); //\r
+    \r
+               fmuStruct.x    = (double *) calloc(fmuStruct.nx, sizeof(double));\r
+               fmuStruct.xdot = (double *) calloc(fmuStruct.nx, sizeof(double));\r
+\r
+               if (fmuStruct.nz>0) { //\r
+                       fmuStruct.z    =  (double *) calloc(fmuStruct.nz, sizeof(double)); //\r
+                       fmuStruct.prez =  (double *) calloc(fmuStruct.nz, sizeof(double)); //\r
+               }\r
+\r
+               //if (!x || !xdot) return error("out of memory");\r
+               if (!fmuStruct.x || !fmuStruct.xdot || fmuStruct.nz>0 && (!fmuStruct.z || !fmuStruct.prez)) return throwException(env, "out of memory");\r
+        \r
+               // set the start time\r
+               fmuStruct.fmiFlag = fmu.setTime(fmuStruct.c, fmuStruct.currentTime);\r
+               if (fmuStruct.fmiFlag > fmiWarning) return throwException(env, "could not set time");\r
+\r
+               // Clear all variables -vector\r
+               fmuStruct.allVariables.clear();\r
+\r
+               // Initialize variable index map and variable vector\r
+               fmuStruct.indexes.clear();\r
+               for (k=0; fmuStruct.vars[k]; k++) {\r
+                       ScalarVariable* sv = fmuStruct.vars[k];\r
+                       s = getName(sv);\r
+                       fmuStruct.indexes.insert ( pair<string,int>(s,k) );\r
+               }\r
+\r
+               // Set initialized flag to 0\r
+               fmuStruct.initialized = false;\r
+\r
+               fflush(stdout);\r
+               return 1;\r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "instantiateSimulation: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_initializeSimulation_1\r
+  (JNIEnv *env, jobject obj, jstring id) {\r
+\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+\r
+               FMU& fmu = fmuStruct.fmu;\r
+\r
+               if(fmu.modelDescription == NULL)\r
+                       return throwException(env, "No FMU loaded");\r
+\r
+               if(fmuStruct.initialized == true)\r
+                       return throwException(env, "FMU already initialized. Instantiate it first.");\r
+\r
+               fmiBoolean toleranceControlled = fmiFalse;\r
+\r
+               fmuStruct.fmiFlag =  fmu.initialize(fmuStruct.c, toleranceControlled, fmuStruct.currentTime, &(fmuStruct.eventInfo));\r
+               if (fmuStruct.fmiFlag > fmiWarning)  return throwException(env, "could not initialize model");\r
+\r
+               fmuStruct.initialized = true;\r
+\r
+               fflush(stdout);\r
+               return 1;\r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "initializeSimulation: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setTime_1\r
+  (JNIEnv *env, jobject obj, jstring id, jdouble time) {\r
+\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+\r
+               FMU& fmu = fmuStruct.fmu;\r
+               fmuStruct.currentTime = time;\r
+               fmu.setTime(fmuStruct.c, time);\r
+               return 1;\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "setTime: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+jobjectArray filterVariables(JNIEnv *env, jobject obj, jstring id, string regexp) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               jobjectArray ret;  \r
+               size_t i;  \r
+               string s;\r
+               // all variables -vector is empty - fill it. \r
+               // it is cleared when a new model is initialized.\r
+               if(fmuStruct.allVariables.size() < 1) {\r
+                       for (i=0; fmuStruct.vars[i]; i++) {\r
+                               ScalarVariable* sv = fmuStruct.vars[i];\r
+                               s = getName(sv);\r
+                               tr1::regex rx(regexp);\r
+                               if(regex_match(s.begin(), s.end(), rx))\r
+                                       fmuStruct.allVariables.push_back(s);\r
+                       }\r
+               }\r
+   \r
+               ret= (jobjectArray)env->NewObjectArray(fmuStruct.allVariables.size(),  \r
+                               env->FindClass("java/lang/String"),  \r
+                               env->NewStringUTF(""));  \r
+   \r
+               for(i=0;i<fmuStruct.allVariables.size();i++) {  \r
+                       env->SetObjectArrayElement(ret,i,env->NewStringUTF(fmuStruct.allVariables[i].c_str()));  \r
+               }  \r
+               return ret;  \r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               throwException(env, "getAllVariables: Model id " + message + " not found");\r
+               return (jobjectArray)env->NewObjectArray(0,  \r
+                               env->FindClass("java/lang/String"),  \r
+                               env->NewStringUTF(""));    \r
+       }\r
+}\r
+\r
+JNIEXPORT jobjectArray JNICALL Java_org_simantics_fmu_FMUControlJNI_getAllVariables_1\r
+  (JNIEnv *env, jobject obj, jstring id) {\r
+                return filterVariables(env, obj, id, "(.*)");\r
+}\r
+\r
+JNIEXPORT jobjectArray JNICALL Java_org_simantics_fmu_FMUControlJNI_filterVariables_1\r
+  (JNIEnv *env, jobject obj, jstring id, jstring regexp) {\r
+        const char *rx = env->GetStringUTFChars(regexp, 0);\r
+        jobjectArray result = filterVariables(env, obj, id, rx);\r
+        env->ReleaseStringUTFChars(regexp, rx);\r
+        return result;\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_simulateStep_1\r
+  (JNIEnv *env, jobject obj, jstring id) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+\r
+               if(&fmuStruct.fmu == NULL || fmuStruct.fmu.modelDescription == NULL || &fmuStruct.vars == NULL) {\r
+                       return throwException(env, "Simulate step failed - fmu not loaded");\r
+               }\r
+\r
+               if(fmuStruct.x == NULL) {\r
+                       return throwException(env, "Simulate step failed - fmu not instantiated");\r
+               }\r
+\r
+               if(fmuStruct.initialized == false) {\r
+                       fmiBoolean toleranceControlled = fmiFalse;\r
+                       fmuStruct.fmiFlag =  fmuStruct.fmu.initialize(fmuStruct.c, toleranceControlled, fmuStruct.currentTime, &(fmuStruct.eventInfo));\r
+                       if (fmuStruct.fmiFlag > fmiWarning)  return throwException(env, "could not initialize model");\r
+                       fmuStruct.initialized = true;\r
+               }\r
+\r
+               FMU& fmu = fmuStruct.fmu;\r
+               int debug = 0; // DEBUG ON = 1, OFF = 0\r
+\r
+               int i;\r
+               double dt, tPre, tEnd = fmuStruct.currentTime + fmuStruct.step;\r
+\r
+               fmiBoolean timeEvent, stateEvent, stepEvent;\r
+               fmiStatus fmiFlag;                      // return code of the fmu functions\r
+               fmiValueReference vr;\r
+\r
+\r
+\r
+               /* Simulate the duration of one step. The simulation may be done in \r
+                * multiple parts if events occur\r
+                */\r
+               while (fmuStruct.currentTime < tEnd) {\r
+                       // get current state and derivatives\r
+                       fmiFlag = fmu.getContinuousStates(fmuStruct.c, fmuStruct.x, fmuStruct.nx);\r
+                       if (fmiFlag > fmiWarning) \r
+                               return throwException(env, "could not retrieve states");\r
+\r
+                       fmiFlag = fmu.getDerivatives(fmuStruct.c, fmuStruct.xdot, fmuStruct.nx);\r
+                       if (fmiFlag > fmiWarning) \r
+                               return throwException(env, "could not retrieve derivatives");\r
+\r
+                        // advance time\r
+                       tPre = fmuStruct.currentTime;\r
+                       fmuStruct.currentTime = min(fmuStruct.currentTime+fmuStruct.step, tEnd);\r
+                       timeEvent = fmuStruct.eventInfo.upcomingTimeEvent && fmuStruct.eventInfo.nextEventTime < fmuStruct.currentTime;  \r
+               \r
+                       if (timeEvent) fmuStruct.currentTime = fmuStruct.eventInfo.nextEventTime;\r
+                       dt = fmuStruct.currentTime - tPre; \r
+                       fmiFlag = fmu.setTime(fmuStruct.c, fmuStruct.currentTime);\r
+                       if (fmiFlag > fmiWarning) throwException(env, "could not set time");\r
+\r
+                       if(referenceExists(fmuStruct, "time")) {\r
+                               vr = getReference(fmuStruct, "time");\r
+                               if(vr != NULL) {\r
+                                       fmu.setReal(fmuStruct.c, &vr, 1, &(fmuStruct.currentTime));\r
+                               }\r
+                       }\r
+\r
+                       if(debug)\r
+                               printf("Actual time: %lf\n", fmuStruct.currentTime);\r
+\r
+                       if (fmiFlag > fmiWarning) \r
+                               return throwException(env, "could not set time");\r
+\r
+                       // perform one step\r
+                       for (i=0; i<fmuStruct.nx; i++) \r
+                               fmuStruct.x[i] += dt*fmuStruct.xdot[i]; // forward Euler method\r
+\r
+                       fmiFlag = fmu.setContinuousStates(fmuStruct.c, fmuStruct.x, fmuStruct.nx);\r
+                       if (fmiFlag > fmiWarning) \r
+                               return throwException(env, "could not set states");\r
+\r
+                       // Check for step event, e.g. dynamic state selection\r
+                       fmiFlag = fmu.completedIntegratorStep(fmuStruct.c, &stepEvent);\r
+                       if (fmiFlag > fmiWarning) return throwException(env, "could not complete intgrator step");\r
+\r
+                       for (i=0; i<fmuStruct.nz; i++) fmuStruct.prez[i] = fmuStruct.z[i]; \r
+                       fmiFlag = fmu.getEventIndicators(fmuStruct.c, fmuStruct.z, fmuStruct.nz);\r
+                       if (fmiFlag > fmiWarning) return throwException(env, "could not retrieve event indicators");\r
+                       stateEvent = FALSE;\r
+                       for (i=0; i<fmuStruct.nz; i++) \r
+                               stateEvent = stateEvent || (fmuStruct.prez[i] * fmuStruct.z[i] < 0);  \r
+     \r
+\r
+                       stepEvent = fmiTrue;\r
+                       // handle events\r
+                       if (timeEvent || stateEvent || stepEvent) {\r
+        \r
+                               // event iteration in one step, ignoring intermediate results\r
+                               fmiFlag = fmu.eventUpdate(fmuStruct.c, fmiFalse, &(fmuStruct.eventInfo));\r
+                               if (fmiFlag > fmiWarning) return throwException(env, "could not perform event update");\r
+      \r
+                       } // if event\r
+       \r
+               }\r
+\r
+               fflush(stdout);\r
+               return 1;\r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "simulateStep: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_unloadFMU_1\r
+  (JNIEnv *env, jobject obj, jstring id) {\r
+       /* terminate crashes -Teemu\r
+       if(! eventInfo.terminateSimulation) ;\r
+               fmu.terminate(c);\r
+       */\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct& fmuStruct = fmus[fmuId];\r
+               fmus.erase(fmuId);\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               if(fmuStruct.fmu.modelDescription != NULL) {\r
+\r
+                       fmuStruct.fmu.freeModelInstance(fmuStruct.c);\r
+                       freeElement(fmuStruct.fmu.modelDescription);\r
+                       FreeLibrary((HMODULE)fmuStruct.fmu.dllHandle);\r
+                       if (fmuStruct.x!=NULL) free(fmuStruct.x);\r
+                       if (fmuStruct.xdot!= NULL) free(fmuStruct.xdot);\r
+                       if (fmuStruct.z!= NULL) free(fmuStruct.z);\r
+                       if (fmuStruct.prez!= NULL) free(fmuStruct.prez);\r
+                       return 1;\r
+\r
+               } else {\r
+\r
+                       if (fmuStruct.x!=NULL) free(fmuStruct.x);\r
+                       if (fmuStruct.xdot!= NULL) free(fmuStruct.xdot);\r
+                       if (fmuStruct.z!= NULL) free(fmuStruct.z);\r
+                       if (fmuStruct.prez!= NULL) free(fmuStruct.prez);\r
+                       return throwException(env, "FMU not loaded");\r
+               }\r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "unloadFMU: Model id " + message + " not found");\r
+       }\r
+}\r
+\r
+JNIEXPORT jstring JNICALL Java_org_simantics_fmu_FMUControlJNI_getLastErrorMessage_1\r
+  (JNIEnv *env, jobject obj, jstring id) {\r
+         return env->NewStringUTF("No errors");\r
+}\r
+\r
+JNIEXPORT jdouble JNICALL Java_org_simantics_fmu_FMUControlJNI_getRealValue_1\r
+  (JNIEnv *env, jobject obj, jstring id, jstring variable) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               const char *name = env->GetStringUTFChars(variable, 0);\r
+\r
+               if(referenceExists(fmuStruct, name)) {\r
+                       fmiValueReference vr = getReference(fmuStruct, name);\r
+\r
+                       double real;\r
+                       fmuStruct.fmu.getReal(fmuStruct.c, &vr, 1, &real);\r
+                       env->ReleaseStringUTFChars(variable, name);\r
+\r
+                       return real;\r
+\r
+               } else {\r
+                        string nameString = name;\r
+                        string message = "Variable " + nameString + " not found";\r
+                        env->ReleaseStringUTFChars(variable, name);\r
+                        return throwException(env, message);\r
+               }\r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "unloadFMU: Model id " + message + " not found");\r
+       }\r
+\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_getIntegerValue_1\r
+  (JNIEnv *env, jobject obj, jstring id, jstring variable) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               const char *name = env->GetStringUTFChars(variable, 0);\r
+\r
+               if(referenceExists(fmuStruct, name)) {\r
+                       fmiValueReference vr = getReference(fmuStruct, name);\r
+                       int result;\r
+                       fmuStruct.fmu.getInteger(fmuStruct.c, &vr, 1, &result);\r
+                       env->ReleaseStringUTFChars(variable, name);\r
+                       return result;\r
+\r
+               } else {\r
+                        string nameString = name;\r
+                        string message = "Variable " + nameString + " not found";\r
+                        env->ReleaseStringUTFChars(variable, name);\r
+                        return throwException(env, message);\r
+               }\r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "unloadFMU: Model id " + message + " not found");\r
+       }\r
+\r
+}\r
+\r
+JNIEXPORT jboolean JNICALL Java_org_simantics_fmu_FMUControlJNI_getBooleanValue_1\r
+  (JNIEnv *env, jobject obj, jstring id, jstring variable) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               const char *name = env->GetStringUTFChars(variable, 0);\r
+\r
+               if(referenceExists(fmuStruct, name)) {\r
+                       fmiValueReference vr = getReference(fmuStruct, name);\r
+                       fmiBoolean result;\r
+                       fmuStruct.fmu.getBoolean(fmuStruct.c, &vr, 1, &result);\r
+                       env->ReleaseStringUTFChars(variable, name);\r
+                       return result;\r
+\r
+               } else {\r
+                        string nameString = name;\r
+                        string message = "Variable " + nameString + " not found";\r
+                        env->ReleaseStringUTFChars(variable, name);\r
+                        return throwException(env, message);\r
+               }\r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return throwException(env, "unloadFMU: Model id " + message + " not found");\r
+       }\r
+\r
+}\r
+\r
+JNIEXPORT jstring JNICALL Java_org_simantics_fmu_FMUControlJNI_getStringValue_1\r
+  (JNIEnv *env, jobject obj, jstring id, jstring variable) {\r
+       const char *fmuId = env->GetStringUTFChars(id, 0);\r
+       if(exists(fmuId)) {\r
+               FMUControlStruct fmuStruct = fmus[fmuId];\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               const char *name = env->GetStringUTFChars(variable, 0);\r
+\r
+               if(referenceExists(fmuStruct, name)) {\r
+                       fmiValueReference vr = getReference(fmuStruct, name);\r
+                       fmiString result;\r
+                       fmuStruct.fmu.getString(fmuStruct.c, &vr, 1, &result);\r
+                       env->ReleaseStringUTFChars(variable, name);\r
+                       return env->NewStringUTF(result);\r
+\r
+               } else {\r
+                        string nameString = name;\r
+                        string message = "Variable " + nameString + " not found";\r
+                        env->ReleaseStringUTFChars(variable, name);\r
+                        return 0; //throwException(env, message);\r
+               }\r
+\r
+       } else {\r
+               string message = fmuId;\r
+               env->ReleaseStringUTFChars(id, fmuId);\r
+               return 0; //throwException(env, "unloadFMU: Model id " + message + " not found");\r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/sim_support.c b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/sim_support.c
new file mode 100644 (file)
index 0000000..b13dd78
--- /dev/null
@@ -0,0 +1,508 @@
+/* ------------------------------------------------------------------------- \r
+ * sim_support.c\r
+ * Functions used by both FMU simulators fmusim_me and fmusim_cs\r
+ * to parse command-line arguments, to unzip and load an fmu, \r
+ * to write CSV file, and more.\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+#include <time.h>\r
+\r
+#ifdef FMI_COSIMULATION\r
+#include "fmi_cs.h"\r
+#else\r
+#include "fmi_me.h"\r
+#endif\r
+\r
+#include "sim_support.h"\r
+#include "fmuExtract.h"\r
+\r
+int unzip(const char *zipPath, const char *outPath) {\r
+    //int code;\r
+    //char cwd[BUFSIZE];\r
+    //char binPath[BUFSIZE];\r
+    //int n = strlen(UNZIP_CMD) + strlen(outPath) + 1 +  strlen(zipPath) + 9;\r
+    //char* cmd = (char*)calloc(sizeof(char), n);\r
+\r
+    //// remember current directory\r
+    //if (!GetCurrentDirectory(BUFSIZE, cwd)) {\r
+    //    printf ("error: Could not get current directory\n");\r
+    //    return 0; // error\r
+    //}\r
+    //    \r
+    //// change to %FMUSDK_HOME%\bin to find 7z.dll and 7z.exe\r
+    //if (!GetEnvironmentVariable("FMUSDK_HOME", binPath, BUFSIZE)) {\r
+    //    if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {\r
+    //        printf ("error: Environment variable FMUSDK_HOME not defined\n");\r
+    //    }\r
+    //    else {\r
+    //        printf ("error: Could not get value of FMUSDK_HOME\n");\r
+    //    }\r
+    //    return 0; // error       \r
+    //}\r
+    //strcat(binPath, "\\bin");\r
+    //if (!SetCurrentDirectory(binPath)) {\r
+    //    printf ("error: could not change to directory '%s'\n", binPath); \r
+    //    return 0; // error        \r
+    //}\r
+   \r
+    //// run the unzip command\r
+    //// remove "> NUL" to see the unzip protocol\r
+    //sprintf(cmd, "%s%s \"%s\" > NUL", UNZIP_CMD, outPath, zipPath); \r
+    //// printf("cmd='%s'\n", cmd);\r
+    //code = system(cmd);\r
+    //free(cmd);\r
+    //if (code!=SEVEN_ZIP_NO_ERROR) {\r
+    //    switch (code) {\r
+    //        printf("7z: ");\r
+    //        case SEVEN_ZIP_WARNING:            printf("warning\n"); break;\r
+    //        case SEVEN_ZIP_ERROR:              printf("error\n"); break;\r
+    //        case SEVEN_ZIP_COMMAND_LINE_ERROR: printf("command line error\n"); break;\r
+    //        case SEVEN_ZIP_OUT_OF_MEMORY:      printf("out of memory\n"); break;\r
+    //        case SEVEN_ZIP_STOPPED_BY_USER:    printf("stopped by user\n"); break;\r
+    //        default: printf("unknown problem\n");\r
+    //    }\r
+    //}\r
+    //\r
+    //// restore current directory\r
+    //SetCurrentDirectory(cwd);\r
+    //\r
+    //return (code==SEVEN_ZIP_NO_ERROR || code==SEVEN_ZIP_WARNING) ? 1 : 0;  \r
+\r
+       // Get current directory\r
+       TCHAR s[260];\r
+       DWORD a = GetCurrentDirectory(260, s);\r
+\r
+       int ret =  unzipFMU(zipPath, outPath); // unzip changes the current directory\r
+\r
+       // Restore current direcory\r
+       SetCurrentDirectory(s);\r
+       return ret;\r
+}\r
+\r
+// fileName is an absolute path, e.g. C:\test\a.fmu\r
+// or relative to the current dir, e.g. ..\test\a.fmu\r
+// Does not check for existence of the file\r
+static char* getFmuPath(const char* fileName){\r
+    char pathName[MAX_PATH];\r
+    int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL);\r
+    return n ? strdup(pathName) : NULL;\r
+}\r
+\r
+int tmpPathRequests = 0;\r
+static char* getTmpPath() {\r
+    char tmpPath[BUFSIZE];\r
+    if(! GetTempPath(BUFSIZE, tmpPath)) {\r
+        printf ("error: Could not find temporary disk space\n");\r
+        return NULL;\r
+    }\r
+       if(tmpPathRequests % 2 == 0) {\r
+               strcat(tmpPath, "fmu\\");\r
+               tmpPathRequests++;\r
+       } else {\r
+               strcat(tmpPath, "fmu2\\");\r
+               tmpPathRequests = 0;\r
+       }\r
+\r
+       makedir(tmpPath);\r
+\r
+    return strdup(tmpPath);\r
+}\r
+\r
+static void* getAdr(int* s, FMU *fmu, const char* functionName){\r
+    char name[BUFSIZE];\r
+    void* fp;\r
+    sprintf(name, "%s_%s", getModelIdentifier(fmu->modelDescription), functionName);\r
+    fp = GetProcAddress(fmu->dllHandle, name);\r
+    if (!fp) {\r
+        printf ("warning: Function %s not found in dll\n", name);\r
+        *s = 0; // mark dll load as 'failed'        \r
+    }\r
+    return fp;\r
+}\r
+\r
+// Load the given dll and set function pointers in fmu\r
+// Return 0 to indicate failure\r
+static int loadDll(const char* dllPath, FMU *fmu) {\r
+    int x = 1, s = 1;\r
+    HANDLE h = LoadLibrary(dllPath);\r
+    if (!h) {\r
+        printf("error: Could not load %s\n", dllPath);\r
+        return 0; // failure\r
+    }\r
+    fmu->dllHandle = h;\r
+\r
+#ifdef FMI_COSIMULATION   \r
+    fmu->getTypesPlatform        = (fGetTypesPlatform)   getAdr(&s, fmu, "fmiGetTypesPlatform");\r
+    if (s==0) { \r
+        s = 1; // work around bug for FMUs exported using Dymola 2012 and SimulationX 3.x\r
+        fmu->getTypesPlatform    = (fGetTypesPlatform)   getAdr(&s, fmu, "fmiGetModelTypesPlatform");\r
+        if (s==1) printf("  using fmiGetModelTypesPlatform instead\n", dllPath);\r
+    }\r
+    fmu->instantiateSlave        = (fInstantiateSlave)   getAdr(&s, fmu, "fmiInstantiateSlave");\r
+    fmu->initializeSlave         = (fInitializeSlave)    getAdr(&s, fmu, "fmiInitializeSlave");    \r
+    fmu->terminateSlave          = (fTerminateSlave)     getAdr(&s, fmu, "fmiTerminateSlave");\r
+    fmu->resetSlave              = (fResetSlave)         getAdr(&s, fmu, "fmiResetSlave");\r
+    fmu->freeSlaveInstance       = (fFreeSlaveInstance)  getAdr(&s, fmu, "fmiFreeSlaveInstance");\r
+    fmu->setRealInputDerivatives = (fSetRealInputDerivatives) getAdr(&s, fmu, "fmiSetRealInputDerivatives");\r
+    fmu->getRealOutputDerivatives = (fGetRealOutputDerivatives) getAdr(&s, fmu, "fmiGetRealOutputDerivatives");\r
+    fmu->cancelStep              = (fCancelStep)         getAdr(&s, fmu, "fmiCancelStep");\r
+    fmu->doStep                  = (fDoStep)             getAdr(&s, fmu, "fmiDoStep");\r
+    // SimulationX 3.4 and 3.5 do not yet export getStatus and getXStatus: do not count this as failure here\r
+    fmu->getStatus               = (fGetStatus)          getAdr(&x, fmu, "fmiGetStatus");\r
+    fmu->getRealStatus           = (fGetRealStatus)      getAdr(&x, fmu, "fmiGetRealStatus");\r
+    fmu->getIntegerStatus        = (fGetIntegerStatus)   getAdr(&x, fmu, "fmiGetIntegerStatus");\r
+    fmu->getBooleanStatus        = (fGetBooleanStatus)   getAdr(&x, fmu, "fmiGetBooleanStatus");\r
+    fmu->getStringStatus         = (fGetStringStatus)    getAdr(&x, fmu, "fmiGetStringStatus");    \r
+\r
+#else // FMI for Model Exchange 1.0\r
+    fmu->getModelTypesPlatform   = (fGetModelTypesPlatform) getAdr(&s, fmu, "fmiGetModelTypesPlatform");\r
+    fmu->instantiateModel        = (fInstantiateModel)   getAdr(&s, fmu, "fmiInstantiateModel");\r
+    fmu->freeModelInstance       = (fFreeModelInstance)  getAdr(&s, fmu, "fmiFreeModelInstance");\r
+    fmu->setTime                 = (fSetTime)            getAdr(&s, fmu, "fmiSetTime");\r
+    fmu->setContinuousStates     = (fSetContinuousStates)getAdr(&s, fmu, "fmiSetContinuousStates");\r
+    fmu->completedIntegratorStep = (fCompletedIntegratorStep)getAdr(&s, fmu, "fmiCompletedIntegratorStep");\r
+    fmu->initialize              = (fInitialize)         getAdr(&s, fmu, "fmiInitialize");\r
+    fmu->getDerivatives          = (fGetDerivatives)     getAdr(&s, fmu, "fmiGetDerivatives");\r
+    fmu->getEventIndicators      = (fGetEventIndicators) getAdr(&s, fmu, "fmiGetEventIndicators");\r
+    fmu->eventUpdate             = (fEventUpdate)        getAdr(&s, fmu, "fmiEventUpdate");\r
+    fmu->getContinuousStates     = (fGetContinuousStates)getAdr(&s, fmu, "fmiGetContinuousStates");\r
+    fmu->getNominalContinuousStates = (fGetNominalContinuousStates)getAdr(&s, fmu, "fmiGetNominalContinuousStates");\r
+    fmu->getStateValueReferences = (fGetStateValueReferences)getAdr(&s, fmu, "fmiGetStateValueReferences");\r
+    fmu->terminate               = (fTerminate)          getAdr(&s, fmu, "fmiTerminate");\r
+#endif \r
+    fmu->getVersion              = (fGetVersion)         getAdr(&s, fmu, "fmiGetVersion");\r
+    fmu->setDebugLogging         = (fSetDebugLogging)    getAdr(&s, fmu, "fmiSetDebugLogging");\r
+    fmu->setReal                 = (fSetReal)            getAdr(&s, fmu, "fmiSetReal");\r
+    fmu->setInteger              = (fSetInteger)         getAdr(&s, fmu, "fmiSetInteger");\r
+    fmu->setBoolean              = (fSetBoolean)         getAdr(&s, fmu, "fmiSetBoolean");\r
+    fmu->setString               = (fSetString)          getAdr(&s, fmu, "fmiSetString");\r
+    fmu->getReal                 = (fGetReal)            getAdr(&s, fmu, "fmiGetReal");\r
+    fmu->getInteger              = (fGetInteger)         getAdr(&s, fmu, "fmiGetInteger");\r
+    fmu->getBoolean              = (fGetBoolean)         getAdr(&s, fmu, "fmiGetBoolean");\r
+    fmu->getString               = (fGetString)          getAdr(&s, fmu, "fmiGetString");\r
+    return s; \r
+}\r
+\r
+static void printModelDescription(ModelDescription* md){\r
+    Element* e = (Element*)md;  \r
+    int i;\r
+    printf("%s\n", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf("  %s=%s\n", e->attributes[i], e->attributes[i+1]);\r
+#ifdef FMI_COSIMULATION   \r
+    if (!md->cosimulation) {\r
+        printf("error: No Implementation element found in model description. This FMU is not for Co-Simulation.\n");\r
+        exit(EXIT_FAILURE);\r
+    }\r
+    e = md->cosimulation->capabilities;\r
+    printf("%s\n", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf("  %s=%s\n", e->attributes[i], e->attributes[i+1]);\r
+#endif // FMI_COSIMULATION  \r
+}\r
+\r
+/*\r
+ * return: 1 for successful laod or number for error.\r
+ * -1. FMU path not found\r
+ * -2. Unzip failed\r
+ * -3. Loading model description failed\r
+ * -4. FMU dll load failed\r
+ */\r
+int loadFMU(FMU *fmu, const char* fmuFileName, const char* tmpPath) {\r
+    char* fmuPath;\r
+    char* xmlPath;\r
+    char* dllPath;\r
+       unsigned old_clock = clock();\r
+       unsigned current_clock = 0;//will be assigned later\r
+    \r
+    // get absolute path to FMU, NULL if not found\r
+    fmuPath = getFmuPath(fmuFileName);\r
+    if (!fmuPath) return -1; // path not found\r
+\r
+    // unzip the FMU to the tmpPath directory\r
+    if (unzip(fmuPath, tmpPath)) return -2; // unzip failed\r
+\r
+    // parse tmpPath\modelDescription.xml\r
+    xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1);\r
+    sprintf(xmlPath, "%s%s", tmpPath, XML_FILE);\r
+    fmu->modelDescription = parse(xmlPath);\r
+    free(xmlPath);\r
+    if (!fmu->modelDescription) return -3; // loading model description failed\r
+\r
+       // printModelDescription(fmu.modelDescription);\r
+       // fflush(stdout);\r
+\r
+    // load the FMU dll\r
+    dllPath = calloc(sizeof(char), strlen(tmpPath) + strlen(DLL_DIR) \r
+            + strlen( getModelIdentifier(fmu->modelDescription)) +  strlen(".dll") + 1);\r
+    sprintf(dllPath,"%s%s%s.dll", tmpPath, DLL_DIR, getModelIdentifier(fmu->modelDescription));\r
+    if (!loadDll(dllPath, fmu)) return -4; // loading dll failed\r
+\r
+    free(dllPath);\r
+    free(fmuPath);\r
+\r
+       return 1;\r
+}\r
+\r
+static void doubleToCommaString(char* buffer, double r){\r
+    char* comma;\r
+    sprintf(buffer, "%.16g", r);\r
+    comma = strchr(buffer, '.');\r
+    if (comma) *comma = ',';\r
+}\r
+\r
+// output time and all non-alias variables in CSV format\r
+// if separator is ',', columns are separated by ',' and '.' is used for floating-point numbers.\r
+// otherwise, the given separator (e.g. ';' or '\t') is to separate columns, and ',' is used \r
+// as decimal dot in floating-point numbers.\r
+void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, boolean header) {\r
+    int k;\r
+    fmiReal r;\r
+    fmiInteger i;\r
+    fmiBoolean b;\r
+    fmiString s;\r
+    fmiValueReference vr;\r
+    ScalarVariable** vars = fmu->modelDescription->modelVariables;\r
+    char buffer[32];\r
+    \r
+    // print first column\r
+    if (header) \r
+        fprintf(file, "time"); \r
+    else {\r
+        if (separator==',') \r
+            fprintf(file, "%.16g", time);\r
+        else {\r
+            // separator is e.g. ';' or '\t'\r
+            doubleToCommaString(buffer, time);\r
+            fprintf(file, "%s", buffer);       \r
+        }\r
+    }\r
+    \r
+    // print all other columns\r
+    for (k=0; vars[k]; k++) {\r
+        ScalarVariable* sv = vars[k];\r
+        if (getAlias(sv)!=enu_noAlias) continue;\r
+        if (header) {\r
+            // output names only\r
+            if (separator==',') {\r
+                // treat array element, e.g. print a[1, 2] as a[1.2]\r
+                char* s = getName(sv);\r
+                fprintf(file, "%c", separator);\r
+                while (*s) {\r
+                   if (*s!=' ') fprintf(file, "%c", *s==',' ? '.' : *s);\r
+                   s++;\r
+                }\r
+             }\r
+            else\r
+                fprintf(file, "%c%s", separator, getName(sv));\r
+        }\r
+        else {\r
+            // output values\r
+            vr = getValueReference(sv);\r
+            switch (sv->typeSpec->type){\r
+                case elm_Real:\r
+                    fmu->getReal(c, &vr, 1, &r);\r
+                    if (separator==',') \r
+                        fprintf(file, ",%.16g", r);\r
+                    else {\r
+                        // separator is e.g. ';' or '\t'\r
+                        doubleToCommaString(buffer, r);\r
+                        fprintf(file, "%c%s", separator, buffer);       \r
+                    }\r
+                    break;\r
+                case elm_Integer:\r
+                case elm_Enumeration:\r
+                    fmu->getInteger(c, &vr, 1, &i);\r
+                    fprintf(file, "%c%d", separator, i);\r
+                    break;\r
+                case elm_Boolean:\r
+                    fmu->getBoolean(c, &vr, 1, &b);\r
+                    fprintf(file, "%c%d", separator, b);\r
+                    break;\r
+                case elm_String:\r
+                    fmu->getString(c, &vr, 1, &s);\r
+                    fprintf(file, "%c%s", separator, s);\r
+                    break;\r
+                default: \r
+                    fprintf(file, "%cNoValueForType=%d", separator,sv->typeSpec->type);\r
+            }\r
+        }\r
+    } // for\r
+    \r
+    // terminate this row\r
+    fprintf(file, "\n"); \r
+}\r
+\r
+static const char* fmiStatusToString(fmiStatus status){\r
+    switch (status){\r
+        case fmiOK:      return "ok";\r
+        case fmiWarning: return "warning";\r
+        case fmiDiscard: return "discard";\r
+        case fmiError:   return "error";\r
+        case fmiFatal:   return "fatal";\r
+#ifdef FMI_COSIMULATION\r
+        case fmiPending: return "fmiPending";\r
+#endif\r
+        default:         return "?";\r
+    }\r
+}\r
+\r
+// search a fmu for the given variable\r
+// return NULL if not found or vr = fmiUndefinedValueReference\r
+static ScalarVariable* getSV(FMU* fmu, char type, fmiValueReference vr) {\r
+    int i;\r
+    Elm tp;\r
+    ScalarVariable** vars = fmu->modelDescription->modelVariables;\r
+    if (vr==fmiUndefinedValueReference) return NULL;\r
+    switch (type) {\r
+        case 'r': tp = elm_Real;    break;\r
+        case 'i': tp = elm_Integer; break;\r
+        case 'b': tp = elm_Boolean; break;\r
+        case 's': tp = elm_String;  break;                \r
+    }\r
+    for (i=0; vars[i]; i++) {\r
+        ScalarVariable* sv = vars[i];\r
+        if (vr==getValueReference(sv) && tp==sv->typeSpec->type) \r
+            return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+// replace e.g. #r1365# by variable name and ## by # in message\r
+// copies the result to buffer\r
+static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU* fmu){\r
+    int i=0; // position in msg\r
+    int k=0; // position in buffer\r
+    int n;\r
+    char c = msg[i];\r
+    while (c!='\0' && k < nBuffer) {\r
+        if (c!='#') {\r
+            buffer[k++]=c;\r
+            i++;\r
+            c = msg[i];\r
+        }\r
+        else {\r
+            char* end = strchr(msg+i+1, '#');\r
+            if (!end) {\r
+                printf("unmatched '#' in '%s'\n", msg);\r
+                buffer[k++]='#';\r
+                break;\r
+            }\r
+            n = end - (msg+i);\r
+            if (n==1) {\r
+                // ## detected, output #\r
+                buffer[k++]='#';\r
+                i += 2;\r
+                c = msg[i];\r
+            }\r
+            else {\r
+                char type = msg[i+1]; // one of ribs\r
+                fmiValueReference vr;\r
+                int nvr = sscanf(msg+i+2, "%u", &vr);\r
+                if (nvr==1) {\r
+                    // vr of type detected, e.g. #r12#\r
+                    ScalarVariable* sv = getSV(fmu, type, vr);\r
+                    const char* name = sv ? getName(sv) : "?";\r
+                    sprintf(buffer+k, "%s", name);\r
+                    k += strlen(name);\r
+                    i += (n+1);\r
+                    c = msg[i]; \r
+                }\r
+                else {\r
+                    // could not parse the number\r
+                    printf("illegal value reference at position %d in '%s'\n", i+2, msg);\r
+                    buffer[k++]='#';\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+    } // while\r
+    buffer[k] = '\0';\r
+}\r
+\r
+#define MAX_MSG_SIZE 1000\r
+void fmuLogger(FMU *fmu, fmiComponent c, fmiString instanceName, fmiStatus status,\r
+               fmiString category, fmiString message, ...) {\r
+    char msg[MAX_MSG_SIZE];\r
+    char* copy;\r
+    va_list argp;\r
+\r
+    // replace C format strings\r
+         va_start(argp, message);\r
+    vsprintf(msg, message, argp);\r
+\r
+    // replace e.g. ## and #r12#  \r
+    copy = strdup(msg);\r
+    replaceRefsInMessage(copy, msg, MAX_MSG_SIZE, fmu);\r
+    free(copy);\r
+    \r
+    // print the final message\r
+    if (!instanceName) instanceName = "?";\r
+    if (!category) category = "?";\r
+    printf("%s %s (%s): %s\n", fmiStatusToString(status), instanceName, category, msg);\r
+}\r
+\r
+int error(const char* message){\r
+    printf("%s\n", message);\r
+    return 0;\r
+}\r
+\r
+void parseArguments(int argc, char *argv[], char** fmuFileName, double* tEnd, double* h, int* loggingOn, char* csv_separator) {\r
+    // parse command line arguments\r
+    if (argc>1) {\r
+        *fmuFileName = argv[1];\r
+    }\r
+    else {\r
+        printf("error: no fmu file\n");\r
+        printHelp(argv[0]);\r
+        exit(EXIT_FAILURE);\r
+    }\r
+    if (argc>2) {\r
+        if (sscanf(argv[2],"%lf", tEnd) != 1) {\r
+            printf("error: The given end time (%s) is not a number\n", argv[2]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>3) {\r
+        if (sscanf(argv[3],"%lf", h) != 1) {\r
+            printf("error: The given stepsize (%s) is not a number\n", argv[3]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>4) {\r
+        if (sscanf(argv[4],"%d", loggingOn) != 1 || *loggingOn<0 || *loggingOn>1) {\r
+            printf("error: The given logging flag (%s) is not boolean\n", argv[4]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+    }\r
+    if (argc>5) {\r
+        if (strlen(argv[5]) != 1) {\r
+            printf("error: The given CSV separator char (%s) is not valid\n", argv[5]);\r
+            exit(EXIT_FAILURE);\r
+        }\r
+        switch (argv[5][0]) {\r
+            case 'c': *csv_separator = ','; break; // comma\r
+            case 's': *csv_separator = ';'; break; // semicolon\r
+            default:  *csv_separator = argv[5][0]; break; // any other char\r
+        }\r
+    }\r
+    if (argc>6) {\r
+        printf("warning: Ignoring %d additional arguments: %s ...\n", argc-6, argv[6]);\r
+        printHelp(argv[0]);\r
+    }\r
+}\r
+\r
+void printHelp(const char* fmusim) {\r
+    printf("command syntax: %s <model.fmu> <tEnd> <h> <loggingOn> <csv separator>\n", fmusim);\r
+    printf("   <model.fmu> .... path to FMU, relative to current dir or absolute, required\n");\r
+    printf("   <tEnd> ......... end  time of simulation, optional, defaults to 1.0 sec\n");\r
+    printf("   <h> ............ step size of simulation, optional, defaults to 0.1 sec\n");\r
+    printf("   <loggingOn> .... 1 to activate logging,   optional, defaults to 0\n");\r
+    printf("   <csv separator>. separator in csv file,   optional, c for ';', s for';', defaults to c\n");\r
+}\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/stack.c b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/stack.c
new file mode 100644 (file)
index 0000000..042b796
--- /dev/null
@@ -0,0 +1,85 @@
+/* ------------------------------------------------------------------------- \r
+ * stack.c\r
+ * A stack of pointers. \r
+ * Copyright 2010 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <assert.h>\r
+#include "stack.h"\r
+\r
+Stack* stackNew(int initialSize, int inc){\r
+    Stack* s = (Stack*)malloc(sizeof(Stack));\r
+    s->stack = NULL;\r
+    s->stackSize = 0;\r
+    s->stackPos = -1;\r
+    s->initialSize = initialSize;\r
+    s->inc = inc;\r
+    return s;\r
+}\r
+\r
+int stackIsEmpty(Stack* s) {\r
+    return s->stackPos == -1;\r
+}\r
+\r
+// add an element to stack and grow stack if required\r
+// returns 1 to indicate success and 0 for error\r
+int stackPush(Stack* s, void* e) {\r
+    s->stackPos++;\r
+    if (s->stackPos==s->stackSize){\r
+               s->stackSize += (s->stack ? s->inc: s->initialSize);\r
+        s->stack = (void**) realloc(s->stack, s->stackSize * sizeof(void*));\r
+        if (!s->stack) return 0; // error;\r
+    }\r
+    s->stack[s->stackPos] = e;\r
+    return 1; // success\r
+}\r
+\r
+// return top element (possibly NULL), if stack not empty\r
+// runtime error if stack is empty\r
+void* stackPeek(Stack* s){\r
+    assert(!stackIsEmpty(s));\r
+    return s->stack[s->stackPos];\r
+}\r
+\r
+// remove top element (possibly NULL) from stack and return it\r
+// runtime error if stack is empty\r
+void* stackPop(Stack* s){\r
+    assert(!stackIsEmpty(s));\r
+    return s->stack[s->stackPos--];\r
+}\r
+\r
+// return the last n elements as null terminated array, \r
+// or NULL if memory allocation fails\r
+void** stackLastPopedAsArray0(Stack* s, int n){\r
+    int i;\r
+    void** array = (void**)malloc((n + 1)*sizeof(void*));\r
+    if (! array) return NULL; // failure\r
+    for (i=0; i<n; i++) {\r
+        array[i] = s->stack[i+ s->stackPos + 1];\r
+    }\r
+    array[n]=NULL; // terminating NULL\r
+    return array;\r
+}\r
+\r
+// return stack as possibly empty array, or NULL if memory allocation fails\r
+// On sucessful return, the stack is empty.\r
+void** stackPopAllAsArray(Stack* s, int *size) {\r
+    int i;\r
+    void** array = (void**)malloc((s->stackPos + 1)*sizeof(void*));\r
+    if (! array) return NULL; // failure\r
+    *size = s->stackPos + 1;\r
+    for (i=0; i<*size; i++) \r
+        array[i] = s->stack[i];\r
+    s->stackPos = -1;\r
+    return array; \r
+}\r
+\r
+// release the given stack\r
+void stackFree(Stack* s){\r
+    if (s->stack) free(s->stack);\r
+    free(s);\r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/xml_parser.c b/1.8/org.simantics.fmu/FMUSolution/FMUSimulator/src/xml_parser.c
new file mode 100644 (file)
index 0000000..93e6216
--- /dev/null
@@ -0,0 +1,860 @@
+/* ------------------------------------------------------------------------- \r
+ * xml_Parser.c\r
+ * A parser for file modelVariables.xml of an FMU.\r
+ * The parser creates an AST (abstract syntax tree) for a given XML file.\r
+ * The root node of the AST is of type ModelDescription.\r
+ * Validation already performed by this parser\r
+ * - check for match of open/close elements (performed by Expat)\r
+ * - ceck element, attribute and enum value names, all case sensitive\r
+ * - check for each element that is has the expected parent element\r
+ * - check for correct sequence of elements\r
+ * - check that all decalaredType values reference an existing Type\r
+ * Validation to be performed by this parser\r
+ * - check for each attribute value that it is of the expected type \r
+ * - check that required attributes are present  \r
+ * - check that dependencies are only declared for outputs and\r
+ *   refer only to inputs\r
+ * Author: Jakob Mauss\r
+ * Copyright 2011 QTronic GmbH. All rights reserved. \r
+ * -------------------------------------------------------------------------*/\r
+\r
+#include <stdio.h>\r
+#include <assert.h>\r
+#include <string.h>\r
+#include "xml_parser.h"\r
+\r
+const char *elmNames[SIZEOF_ELM] = { \r
+    "fmiModelDescription","UnitDefinitions","BaseUnit","DisplayUnitDefinition","TypeDefinitions",\r
+    "Type","RealType","IntegerType","BooleanType","StringType","EnumerationType","Item",\r
+     "DefaultExperiment","VendorAnnotations","Tool","Annotation", "ModelVariables","ScalarVariable",\r
+     "DirectDependency","Name","Real","Integer","Boolean","String","Enumeration",\r
+     "Implementation","CoSimulation_StandAlone","CoSimulation_Tool","Model","File","Capabilities"\r
+};\r
+\r
+const char *attNames[SIZEOF_ATT] = {\r
+    "fmiVersion","displayUnit","gain","offset","unit","name","description","quantity", "relativeQuantity",\r
+    "min","max","nominal","declaredType","start","fixed","startTime","stopTime","tolerance","value",\r
+    "valueReference","variability","causality","alias", "modelName","modelIdentifier","guid","author",\r
+    "version","generationTool","generationDateAndTime","variableNamingConvention","numberOfContinuousStates",\r
+    "numberOfEventIndicators","input",\r
+    "canHandleVariableCommunicationStepSize","canHandleEvents","canRejectSteps","canInterpolateInputs",\r
+    "maxOutputDerivativeOrder","canRunAsynchronuously","canSignalEvents","canBeInstantiatedOnlyOncePerProcess",\r
+    "canNotUseMemoryManagementFunctions","file","entryPoint","manualStart","type"\r
+};\r
+\r
+const char *enuNames[SIZEOF_ENU] = {\r
+    "flat","structured","constant","parameter","discrete","continuous",\r
+    "input","output", "internal","none","noAlias","alias","negatedAlias"\r
+};\r
+\r
+#define ANY_TYPE -1\r
+#define XMLBUFSIZE 1024\r
+char text[XMLBUFSIZE];       // XML file is parsed in chunks of length XMLBUFZIZE\r
+XML_Parser parser = NULL;    // non-NULL during parsing\r
+Stack* stack = NULL;         // the parser stack\r
+char* data = NULL;           // buffer that holds element content, see handleData\r
+int skipData=0;              // 1 to ignore element content, 0 when recordig content\r
+\r
+// ------------------------------------------------------------------------- \r
+// Low-level functions for inspecting the model description \r
+\r
+const char* getString(void* element, Att a){\r
+    Element* e = (Element*)element;\r
+    const char** attr = e->attributes;\r
+    int i;\r
+    for (i=0; i<e->n; i+=2)\r
+        if (attr[i]==attNames[a]) return attr[i+1];\r
+    return NULL;\r
+}\r
+\r
+double getDouble(void* element, Att a, ValueStatus* vs){\r
+    double d = 0;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return d; }\r
+    *vs = (1==sscanf(value, "%lf", &d)) ? valueDefined : valueIllegal;\r
+    return d;    \r
+}\r
+\r
+// getInt() is also used to retrieve Enumeration values from XML,\r
+// e.g. the start value for a variable of user-defined enumeration type.\r
+int getInt(void* element, Att a, ValueStatus* vs){\r
+    int n = 0;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return n; }\r
+    *vs = (1==sscanf(value, "%d", &n)) ? valueDefined : valueIllegal;\r
+    return n;    \r
+}\r
+\r
+unsigned int getUInt(void* element, Att a, ValueStatus* vs){\r
+    unsigned int u = -1;\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return u; }\r
+    *vs = (1==sscanf(value, "%u", &u)) ? valueDefined : valueIllegal;\r
+    return u;    \r
+}\r
+\r
+char getBoolean(void* element, Att a, ValueStatus* vs){\r
+    const char* value = getString(element, a);\r
+    if (!value) { *vs=valueMissing; return 0; };\r
+    *vs = valueDefined;\r
+    if (!strcmp(value, "true")) return 1;\r
+    if (!strcmp(value, "false")) return 0;\r
+    *vs = valueIllegal;    \r
+    return 0;\r
+}\r
+\r
+static int checkEnumValue(const char* enu);\r
+\r
+// Retrieve the value of the given built-in enum attribute.\r
+// If the value is missing, this is marked in the ValueStatus\r
+// and the corresponding default is returned.\r
+// Returns -1 or a globally unique id for the value such that\r
+// enuNames[id] is the string representation of the enum value. \r
+Enu getEnumValue(void* element, Att a, ValueStatus* vs) {\r
+    const char* value = getString(element, a);\r
+    Enu id = valueDefined;\r
+    if (!value) { \r
+        *vs = valueMissing;\r
+        switch (a) {\r
+            case att_variableNamingConvention: return enu_flat;\r
+            case att_variability: return enu_continuous;\r
+            case att_causality: return enu_internal;\r
+            case att_alias: return enu_noAlias;\r
+            default: return -1;\r
+        }\r
+    }\r
+    id = checkEnumValue(value);\r
+    if (id==-1) *vs = valueIllegal; \r
+    return id;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Convenience methods for accessing the model description. \r
+// Use is only safe after the ast has been successfuly validated.\r
+\r
+const char* getModelIdentifier(ModelDescription* md) {\r
+    const char* modelId = getString(md, att_modelIdentifier);\r
+    assert(modelId); // this is a required attribute\r
+    return modelId;\r
+}\r
+\r
+int getNumberOfStates(ModelDescription* md) {\r
+    ValueStatus vs;\r
+    int n = getUInt(md, att_numberOfContinuousStates, &vs);\r
+    assert(vs==valueDefined); // this is a required attribute\r
+    return n;\r
+}\r
+\r
+int getNumberOfEventIndicators(ModelDescription* md) {\r
+    ValueStatus vs;\r
+    int n = getInt(md, att_numberOfEventIndicators, &vs);\r
+    assert(vs==valueDefined); // this is a required attribute\r
+    return n;\r
+}\r
+\r
+// name is a required attribute of ScalarVariable, Type, Item, Annotation, and Tool\r
+const char* getName(void* element) { \r
+    const char* name = getString(element, att_name);\r
+    assert(name); // this is a required attribute\r
+    return name;\r
+}\r
+\r
+// returns one of: input, output, internal, none\r
+// if value is missing, the default internal is returned\r
+Enu getCausality(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_causality, &vs);\r
+}\r
+\r
+// returns one of constant, parameter, discrete, continuous\r
+// if value is missing, the default continuous is returned\r
+Enu getVariability(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_variability, &vs);\r
+}\r
+\r
+// returns one of noAlias, alias, negatedAlias\r
+// if value is missing, the default noAlias is returned \r
+Enu getAlias(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    return getEnumValue(scalarVariable, att_alias, &vs);\r
+}\r
+\r
+// the vr is unique only for one of the 4 base data types r,i,b,s and\r
+// may also be fmiUndefinedValueReference = 4294967295 = 0xFFFFFFFF\r
+// here, i means integer or enumeration\r
+fmiValueReference getValueReference(void* scalarVariable) {\r
+    ValueStatus vs;\r
+    fmiValueReference vr = getUInt(scalarVariable, att_valueReference, &vs);\r
+    assert(((Element*)scalarVariable)->type == elm_ScalarVariable);\r
+    assert(vs==valueDefined); // this is a reqired attribute\r
+    return vr;\r
+}\r
+\r
+// the name is unique within a fmu\r
+ScalarVariable* getVariableByName(ModelDescription* md, const char* name) {\r
+    int i;\r
+    if (md->modelVariables)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        if (!strcmp(getName(sv), name)) return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+// Enumeration and Integer have the same base type while \r
+// Real, String, Boolean define own base types.\r
+int sameBaseType(Elm t1, Elm t2){\r
+    return t1==t2 || \r
+           t1==elm_Enumeration && t2==elm_Integer || \r
+           t2==elm_Enumeration && t1==elm_Integer;\r
+}\r
+\r
+// returns NULL if variable not found or vr==fmiUndefinedValueReference\r
+ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type){\r
+    int i;\r
+    if (md->modelVariables && vr!=fmiUndefinedValueReference)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        if (sameBaseType(type, sv->typeSpec->type) && getValueReference(sv) == vr) \r
+            return sv;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+Type* getDeclaredType(ModelDescription* md, const char* declaredType){\r
+    int i;\r
+    if (declaredType && md->typeDefinitions)\r
+    for (i=0; md->typeDefinitions[i]; i++){\r
+        Type* tp = (Type*)md->typeDefinitions[i];\r
+        if (!strcmp(declaredType, getName(tp))) return tp;\r
+    }\r
+    return NULL;\r
+}\r
+\r
+const char* getString2(ModelDescription* md, void* tp, Att a) {\r
+    Type* type;\r
+    const char* value = getString(tp, a);\r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    type = getDeclaredType(md, getString(tp, att_declaredType));\r
+    return type ? getString(type->typeSpec, a) : NULL;\r
+}\r
+\r
+// Get description from variable or from declared type, or NULL.\r
+const char * getDescription(ModelDescription* md, ScalarVariable* sv) {\r
+    const char* value = getString(sv, att_description);\r
+    Type* type; \r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    type = getDeclaredType(md, getString(sv->typeSpec, att_declaredType));\r
+    return type ? getString(type, att_description) : NULL;\r
+}\r
+\r
+// Get attribute value from scalar variable given by vr and type, \r
+// incl. default value provided by declared type, if any.\r
+const char * getVariableAttributeString(ModelDescription* md, \r
+        fmiValueReference vr, Elm type, Att a){\r
+    const char* value;\r
+    const char* declaredType;\r
+    Type* tp; \r
+    ScalarVariable* sv = getVariable(md, vr, type);\r
+    if (!sv) return NULL;\r
+    value = getString(sv->typeSpec, a);\r
+    if (value) return value; // found\r
+    // search declared type, if any\r
+    tp = getDeclaredType(md, getString(sv->typeSpec, att_declaredType));\r
+    return tp ? getString(tp->typeSpec, a) : NULL;\r
+}\r
+\r
+// Get attribute value from scalar variable given by vr and type, \r
+// incl. default value provided by declared type, if any.\r
+double getVariableAttributeDouble(ModelDescription* md, \r
+        fmiValueReference vr, Elm type, Att a, ValueStatus* vs){\r
+    double d = 0;\r
+    const char* value = getVariableAttributeString(md, vr, type, a);\r
+    if (!value) { *vs = valueMissing; return d; }\r
+    *vs = (1==sscanf(value, "%lf", &d)) ? valueDefined : valueIllegal;\r
+    return d;    \r
+}\r
+\r
+// Get nominal value from real variable or its declared type.\r
+// Return 1, if no nominal value is defined.\r
+double getNominal(ModelDescription* md, fmiValueReference vr){\r
+    ValueStatus vs;\r
+    double nominal = getVariableAttributeDouble(md, vr, elm_Real, att_nominal, &vs);\r
+    return vs==valueDefined ? nominal : 1.0;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Various checks that log an error and stop the parser \r
+\r
+// Returns 0 to indicate error\r
+static int checkPointer(const void* ptr){\r
+    if (! ptr) {\r
+        printf("Out of memory\n");\r
+        if (parser) XML_StopParser(parser, XML_FALSE);\r
+        return 0; // error \r
+    }\r
+    return 1; // success\r
+}\r
+\r
+static int checkName(const char* name, const char* kind, const char* array[], int n){\r
+    int i;\r
+    for (i=0; i<n; i++) {\r
+        if (!strcmp(name, array[i])) return i;\r
+    }\r
+    printf("Illegal %s %s\n", kind, name);\r
+    XML_StopParser(parser, XML_FALSE);\r
+    return -1;\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkElement(const char* elm){\r
+    return checkName(elm, "element", elmNames, SIZEOF_ELM);\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkAttribute(const char* att){\r
+    return checkName(att, "attribute", attNames, SIZEOF_ATT);\r
+}\r
+\r
+// Returns -1 to indicate error\r
+static int checkEnumValue(const char* enu){\r
+    return checkName(enu, "enum value", enuNames, SIZEOF_ENU);\r
+}\r
+\r
+static void logFatalTypeError(const char* expected, Elm found) {\r
+    printf("Wrong element type, expected %s, found %s\n", \r
+            expected, elmNames[found]);\r
+    XML_StopParser(parser, XML_FALSE);\r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Verify that Element elm is of the given type\r
+static int checkElementType(void* element, Elm e) {\r
+    Element* elm = (Element* )element;\r
+    if (elm->type == e) return 1; // success\r
+    logFatalTypeError(elmNames[e], elm->type);\r
+    return 0; // error    \r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Verify that the next stack element exists and is of the given type\r
+// If e==ANY_TYPE, the type check is ommited \r
+static int checkPeek(Elm e) {\r
+    if (stackIsEmpty(stack)){\r
+        printf("Illegal document structure, expected %s\n", elmNames[e]);\r
+        XML_StopParser(parser, XML_FALSE);\r
+        return 0; // error\r
+    }\r
+    return e==ANY_TYPE ? 1 : checkElementType(stackPeek(stack), e);\r
+}\r
+\r
+// Returns NULL to indicate error\r
+// Get the next stack element, it is of the given type.\r
+// If e==ANY_TYPE, the type check is ommited \r
+static void* checkPop(Elm e){\r
+    return checkPeek(e) ? stackPop(stack) : NULL;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Helper \r
+\r
+AstNodeType getAstNodeType(Elm e){\r
+    switch (e) {\r
+    case elm_fmiModelDescription: \r
+        return astModelDescription;\r
+    case elm_Type:\r
+        return astType;\r
+    case elm_ScalarVariable:\r
+        return astScalarVariable;\r
+    case elm_CoSimulation_StandAlone:\r
+    case elm_CoSimulation_Tool:\r
+        return astCoSimulation;\r
+    case elm_BaseUnit:\r
+    case elm_EnumerationType:\r
+    case elm_Tool:\r
+    case elm_UnitDefinitions:\r
+    case elm_TypeDefinitions:\r
+    case elm_VendorAnnotations:\r
+    case elm_ModelVariables:\r
+    case elm_DirectDependency:\r
+    case elm_Model:\r
+        return astListElement;\r
+    default:\r
+        return astElement; \r
+    }\r
+}\r
+\r
+// Returns 0 to indicate error\r
+// Copies the attr array and all values.\r
+// Replaces all attribute names by constant literal strings.\r
+// Converts the null-terminated array into an array of known size n.\r
+int addAttributes(Element* el, const char** attr) {\r
+    int n, a;\r
+    const char** att = NULL;\r
+    for (n=0; attr[n]; n+=2);\r
+    if (n>0) {\r
+        att = calloc(n, sizeof(char*));\r
+        if (!checkPointer(att)) return 0;\r
+    } \r
+    for (n=0; attr[n]; n+=2) {\r
+        char* value = strdup(attr[n+1]);\r
+        if (!checkPointer(value)) return 0;\r
+        a = checkAttribute(attr[n]);\r
+        if (a == -1) return 0;  // illegal attribute error\r
+        att[n  ] = attNames[a]; // no heap memory\r
+        att[n+1] = value;       // heap memory\r
+    }\r
+    el->attributes = att; // NULL if n=0\r
+    el->n = n;\r
+    return 1; // success\r
+}\r
+\r
+// Returns NULL to indicate error\r
+Element* newElement(Elm type, int size, const char** attr) {\r
+    Element* e = (Element*)calloc(1, size);\r
+    if (!checkPointer(e)) return NULL; \r
+    e->type = type;\r
+    e->attributes = NULL;\r
+    e->n=0;\r
+    if (!addAttributes(e, attr)) return NULL;\r
+    return e;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// callback functions called by the XML parser \r
+\r
+// Create and push a new element node\r
+static void XMLCALL startElement(void *context, const char *elm, const char **attr) {\r
+    Elm el;\r
+    void* e;\r
+    int size;\r
+    el = checkElement(elm);\r
+    if (el==-1) return; // error\r
+    skipData = (el != elm_Name); // skip element content for all elements but Name\r
+    switch(getAstNodeType(el)){\r
+        case astElement:          size = sizeof(Element); break;\r
+        case astListElement:      size = sizeof(ListElement); break;\r
+        case astType:             size = sizeof(Type); break;\r
+        case astScalarVariable:   size = sizeof(ScalarVariable); break;\r
+        case astCoSimulation:     size = sizeof(CoSimulation); break;\r
+        case astModelDescription: size = sizeof(ModelDescription); break;\r
+               default: assert(0);\r
+    }\r
+    e = newElement(el, size, attr);\r
+    checkPointer(e); \r
+    stackPush(stack, e);\r
+}\r
+\r
+// Pop all elements of the given type from stack and \r
+// add it to the ListElement that follows.\r
+// The ListElement remains on the stack.\r
+static void popList(Elm e) {\r
+    int n = 0;\r
+    Element** array;\r
+    Element* elm = stackPop(stack);\r
+    while (elm->type == e) {\r
+        elm = stackPop(stack);\r
+        n++;\r
+    }\r
+    stackPush(stack, elm); // push ListElement back to stack\r
+    array = (Element**)stackLastPopedAsArray0(stack, n); // NULL terminated list\r
+    if (getAstNodeType(elm->type)!=astListElement) return; // failure\r
+    ((ListElement*)elm)->list = array;\r
+    return; // success only if list!=NULL    \r
+}\r
+\r
+// Pop the children from the stack and\r
+// check for correct type and sequence of children\r
+static void XMLCALL endElement(void *context, const char *elm) {\r
+    Elm el;\r
+    el = checkElement(elm);\r
+    switch(el) { \r
+        case elm_fmiModelDescription: \r
+            {\r
+                 ModelDescription* md;\r
+                 ListElement** ud = NULL;     // NULL or list of BaseUnits\r
+                 Type**        td = NULL;     // NULL or list of Types \r
+                 Element*      de = NULL;     // NULL or DefaultExperiment\r
+                 ListElement** va = NULL;     // NULL or list of Tools\r
+                 ScalarVariable** mv = NULL;  // NULL or list of ScalarVariable\r
+                 CoSimulation *cs = NULL;     // NULL or CoSimulation\r
+                 ListElement* child;\r
+\r
+                 child = checkPop(ANY_TYPE);\r
+                 if (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool) {\r
+                     cs = (CoSimulation*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_ModelVariables){\r
+                     mv = (ScalarVariable**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_VendorAnnotations){\r
+                     va = (ListElement**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_DefaultExperiment){\r
+                     de = (Element*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_TypeDefinitions){\r
+                     td = (Type**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (child->type == elm_UnitDefinitions){\r
+                     ud = (ListElement**)child->list;\r
+                     free(child);\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 // work around bug of SimulationX 3.4 and 3.5 which places Implementation at wrong location \r
+                 if (!cs && (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool)) {\r
+                     cs = (CoSimulation*)child;\r
+                     child = checkPop(ANY_TYPE);\r
+                     if (!child) return;\r
+                 }\r
+                 if (!checkElementType(child, elm_fmiModelDescription)) return;\r
+                 md = (ModelDescription*)child;\r
+                 md->modelVariables = mv;\r
+                 md->vendorAnnotations = va;\r
+                 md->defaultExperiment = de;\r
+                 md->typeDefinitions = td;\r
+                 md->unitDefinitions = ud;\r
+                 md->cosimulation = cs;\r
+                 stackPush(stack, md);\r
+                 break;\r
+            }\r
+        case elm_Implementation:\r
+            {\r
+                 // replace Implementation element\r
+                 void* cs = checkPop(ANY_TYPE);\r
+                 void* im = checkPop(elm_Implementation);\r
+                 stackPush(stack, cs);\r
+                 free(im);\r
+                 el = ((Element*)cs)->type;\r
+                 break;\r
+            }\r
+        case elm_CoSimulation_StandAlone:  \r
+            {\r
+                 Element* ca = checkPop(elm_Capabilities);\r
+                 CoSimulation* cs = checkPop(elm_CoSimulation_StandAlone);\r
+                 if (!ca || !cs) return;\r
+                 cs->capabilities = ca;\r
+                 stackPush(stack, cs);\r
+                 break;\r
+            }   \r
+        case elm_CoSimulation_Tool:\r
+            {\r
+                 ListElement* mo = checkPop(elm_Model);\r
+                 Element* ca = checkPop(elm_Capabilities);\r
+                 CoSimulation* cs = checkPop(elm_CoSimulation_Tool);\r
+                 if (!ca || !mo || !cs) return;\r
+                 cs->capabilities = ca;\r
+                 cs->model = mo;\r
+                 stackPush(stack, cs);\r
+                 break;\r
+            }   \r
+        case elm_Type:\r
+            {\r
+                Type* tp;\r
+                Element* ts = checkPop(ANY_TYPE);\r
+                if (!ts) return;\r
+                if (!checkPeek(elm_Type)) return;\r
+                tp = (Type*)stackPeek(stack);\r
+                switch (ts->type) {\r
+                    case elm_RealType:\r
+                    case elm_IntegerType:\r
+                    case elm_BooleanType:\r
+                    case elm_StringType:\r
+                    case elm_EnumerationType:\r
+                        break;\r
+                    default:\r
+                         logFatalTypeError("RealType or similar", ts->type);\r
+                         return;\r
+                }\r
+                tp->typeSpec = ts;\r
+                break;\r
+            }\r
+        case elm_ScalarVariable:\r
+            {\r
+                ScalarVariable* sv;\r
+                Element** list = NULL;\r
+                Element* child = checkPop(ANY_TYPE);\r
+                if (!child) return;\r
+                if (child->type==elm_DirectDependency){\r
+                    list = ((ListElement*)child)->list;\r
+                    free(child);\r
+                    child = checkPop(ANY_TYPE);\r
+                    if (!child) return;\r
+                }\r
+                if (!checkPeek(elm_ScalarVariable)) return;\r
+                sv = (ScalarVariable*)stackPeek(stack);\r
+                switch (child->type) {\r
+                    case elm_Real:\r
+                    case elm_Integer:\r
+                    case elm_Boolean:\r
+                    case elm_String:\r
+                    case elm_Enumeration:\r
+                        break;\r
+                    default:\r
+                         logFatalTypeError("Real or similar", child->type);\r
+                         return;\r
+                }\r
+                sv->directDependencies = list;\r
+                sv->typeSpec = child;\r
+                break;\r
+            }\r
+        case elm_ModelVariables:    popList(elm_ScalarVariable); break;\r
+        case elm_VendorAnnotations: popList(elm_Tool);break;\r
+        case elm_Tool:              popList(elm_Annotation); break;\r
+        case elm_TypeDefinitions:   popList(elm_Type); break;\r
+        case elm_EnumerationType:   popList(elm_Item); break;\r
+        case elm_UnitDefinitions:   popList(elm_BaseUnit); break;\r
+        case elm_BaseUnit:          popList(elm_DisplayUnitDefinition); break;\r
+        case elm_DirectDependency:  popList(elm_Name); break;\r
+        case elm_Model:             popList(elm_File); break;\r
+        case elm_Name:\r
+            {\r
+                 // Exception: the name value is represented as element content.\r
+                 // All other values of the XML file are represented using attributes.\r
+                 Element* name = checkPop(elm_Name);\r
+                 if (!name) return;\r
+                 name->n = 2;\r
+                 name->attributes = malloc(2*sizeof(char*));\r
+                 name->attributes[0] = attNames[att_input];\r
+                 name->attributes[1] = data;\r
+                 data = NULL;\r
+                 skipData = 1; // stop recording element content\r
+                 stackPush(stack, name);\r
+                 break;\r
+            }\r
+        case -1: return; // illegal element error\r
+        default: // must be a leaf Element\r
+                 assert(getAstNodeType(el)==astElement);\r
+                 break;\r
+    }\r
+    // All children of el removed from the stack.\r
+    // The top element must be of type el now.\r
+    checkPeek(el);\r
+}\r
+\r
+// Called to handle element data, e.g. "xy" in <Name>xy</Name>\r
+// Can be called many times, e.g. with "x" and then with "y" in the example above.\r
+// Feature in expat:\r
+// For some reason, if the element data is the empty string (Eg. <a></a>)\r
+// instead of an empty string with len == 0 we get "\n". The workaround is\r
+// to replace this with the empty string whenever we encounter "\n".\r
+void XMLCALL handleData(void *context, const XML_Char *s, int len) {\r
+    int n;\r
+    if (skipData) return;\r
+    if (!data) {\r
+        // start a new data string\r
+        if (len == 1 && s[0] == '\n') {\r
+            data = strdup("");\r
+        } else {\r
+            data = malloc(len + 1);\r
+            strncpy(data, s, len);\r
+            data[len] = '\0';\r
+        }\r
+    }\r
+    else {\r
+        // continue existing string\r
+        n = strlen(data) + len;\r
+        data = realloc(data, n+1);\r
+        strncat(data, s, len);\r
+        data[n] = '\0';\r
+    }\r
+    return;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// printing\r
\r
+static void printList(int indent, void** list);\r
+\r
+void printElement(int indent, void* element){\r
+    int i;\r
+    Element* e = (Element*)element;\r
+    if (!e) return;\r
+    // print attributes\r
+    for (i=0; i<indent; i++) printf(" ");\r
+    printf("%s", elmNames[e->type]);\r
+    for (i=0; i<e->n; i+=2) \r
+        printf(" %s=%s", e->attributes[i], e->attributes[i+1]);\r
+    printf("\n");\r
+    // print child nodes\r
+    indent += 2;\r
+    switch (getAstNodeType(e->type)) {\r
+        case astListElement:\r
+            printList(indent, ((ListElement*)e)->list);\r
+            break;\r
+        case astScalarVariable:\r
+            printElement(indent, ((Type*)e)->typeSpec);\r
+            printList(indent, ((ScalarVariable*)e)->directDependencies);\r
+            break;\r
+        case astType:\r
+            printElement(indent, ((Type*)e)->typeSpec);\r
+            break;\r
+        case astCoSimulation: {\r
+            CoSimulation* cs = (CoSimulation*)e;\r
+            printElement(indent, cs->capabilities);\r
+            printElement(indent, cs->model);\r
+            break;\r
+        }\r
+        case astModelDescription: {\r
+            ModelDescription *md = (ModelDescription*)e;\r
+            printList(indent, md->unitDefinitions);\r
+            printList(indent, md->typeDefinitions);\r
+            printElement(indent, md->defaultExperiment);\r
+            printList(indent, md->vendorAnnotations);\r
+            printList(indent, md->modelVariables);\r
+            printElement(indent, md->cosimulation);\r
+            break;\r
+        }\r
+    }\r
+}\r
+\r
+static void printList(int indent, void** list){\r
+    int i;\r
+    if (list) for (i=0; list[i]; i++) \r
+       printElement(indent, list[i]);\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// free memory of the AST\r
+\r
+static void freeList(void** list);\r
+\r
+void freeElement(void* element){\r
+    int i;\r
+    Element* e = (Element*)element;\r
+    if (!e) return;\r
+    // free attributes\r
+    for (i=0; i<e->n; i+=2) \r
+        free(e->attributes[i+1]);\r
+    if (e->attributes) free(e->attributes);\r
+    // free child nodes\r
+    switch (getAstNodeType(e->type)) {\r
+        case astListElement:\r
+            freeList(((ListElement*)e)->list);\r
+            break;\r
+        case astScalarVariable:\r
+            freeList(((ScalarVariable*)e)->directDependencies);\r
+        case astType:\r
+            freeElement(((Type*)e)->typeSpec);\r
+            break;\r
+        case astCoSimulation: {\r
+            CoSimulation* cs = (CoSimulation*)e;\r
+            freeElement(cs->capabilities);\r
+            freeElement(cs->model);\r
+            break;\r
+        }\r
+        case astModelDescription: {\r
+            ModelDescription* md = (ModelDescription*)e;\r
+            freeList(md->unitDefinitions);\r
+            freeList(md->typeDefinitions);\r
+            freeElement(md->defaultExperiment);\r
+            freeList(md->vendorAnnotations);\r
+            freeList(md->modelVariables);\r
+            freeElement(md->cosimulation);\r
+            break;\r
+       }\r
+    }\r
+    // free the struct\r
+    free(e);\r
+}\r
+\r
+static void freeList(void** list){\r
+    int i;\r
+    if (!list) return;\r
+    for (i=0; list[i]; i++) \r
+        freeElement(list[i]);\r
+    free(list);\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Validation - done after parsing to report all errors \r
+\r
+ModelDescription* validate(ModelDescription* md) {\r
+    int error = 0;\r
+    int i;\r
+    if (md->modelVariables)\r
+    for (i=0; md->modelVariables[i]; i++){\r
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];\r
+        char* declaredType = getString(sv->typeSpec, att_declaredType);\r
+        Type* decltype = getDeclaredType(md, declaredType);\r
+        if (declaredType && decltype==NULL) {\r
+            printf("Warning: Declared type %s of variable %s not found in modelDescription.xml\n", declaredType, getName(sv));\r
+            error++;\r
+        }\r
+    }\r
+    if (error) {\r
+        printf("Error: Found %d error in modelDescription.xml\n", error);\r
+        return NULL;\r
+    }\r
+    return md;\r
+}\r
+\r
+// ------------------------------------------------------------------------- \r
+// Entry function parse() of the XML parser \r
+\r
+static void cleanup(FILE *file) {\r
+    stackFree(stack);\r
+    stack = NULL;\r
+    XML_ParserFree(parser);\r
+    parser = NULL;\r
+    fclose(file);\r
+}\r
+\r
+// Returns NULL to indicate failure\r
+// Otherwise, return the root node md of the AST.\r
+// The receiver must call freeElement(md) to release AST memory.\r
+ModelDescription* parse(const char* xmlPath) {\r
+    ModelDescription* md = NULL;\r
+    FILE *file;\r
+    int done = 0;\r
+    stack = stackNew(100, 10);\r
+    if (!checkPointer(stack)) return NULL;  // failure\r
+    parser = XML_ParserCreate(NULL);\r
+    if (!checkPointer(parser)) return NULL;  // failure\r
+    XML_SetElementHandler(parser, startElement, endElement);\r
+    XML_SetCharacterDataHandler(parser, handleData);\r
+       file = fopen(xmlPath, "rb");\r
+       if (file == NULL) {\r
+        printf("Cannot open file '%s'\n", xmlPath);\r
+       XML_ParserFree(parser);\r
+        return NULL; // failure\r
+    }\r
+    while (!done) {\r
+        int n = fread(text, sizeof(char), XMLBUFSIZE, file);\r
+           if (n != XMLBUFSIZE) done = 1;\r
+        if (!XML_Parse(parser, text, n, done)){\r
+             printf("Parse error in file %s at line %d:\n%s\n", \r
+                     xmlPath,\r
+                        XML_GetCurrentLineNumber(parser),\r
+                        XML_ErrorString(XML_GetErrorCode(parser)));\r
+             while (! stackIsEmpty(stack)) md = stackPop(stack);\r
+             if (md) freeElement(md);\r
+             cleanup(file);\r
+             return NULL; // failure\r
+        }\r
+    }\r
+    md = stackPop(stack);\r
+    assert(stackIsEmpty(stack));\r
+    cleanup(file);\r
+    //printElement(1, md); // debug\r
+    return validate(md); // success if all refs are valid    \r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/FMUSolution.sln b/1.8/org.simantics.fmu/FMUSolution/FMUSolution.sln
new file mode 100644 (file)
index 0000000..2360dc1
--- /dev/null
@@ -0,0 +1,67 @@
+\r
+Microsoft Visual Studio Solution File, Format Version 11.00\r
+# Visual Studio 2010\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FMUSimulator", "FMUSimulator\FMUSimulator.vcxproj", "{9838038D-09A3-43A5-AB97-B5B5C763DF43}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A} = {C52F9E7B-498A-42BE-8DB4-85A15694382A}\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D} = {8FD826F8-3739-44E6-8CC8-997122E53B8D}\r
+       EndProjectSection\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "zlib-1.2.6\contrib\vstudio\vc10\miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D} = {8FD826F8-3739-44E6-8CC8-997122E53B8D}\r
+       EndProjectSection\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlib-1.2.6\contrib\vstudio\vc10\zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
+EndProject\r
+Global\r
+       GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
+               Debug|Win32 = Debug|Win32\r
+               Debug|x64 = Debug|x64\r
+               Release|Win32 = Release|Win32\r
+               Release|x64 = Release|x64\r
+               ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32\r
+               ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64\r
+       EndGlobalSection\r
+       GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.Debug|Win32.Build.0 = Debug|Win32\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.Debug|x64.ActiveCfg = Debug|x64\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.Debug|x64.Build.0 = Debug|x64\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.Release|Win32.ActiveCfg = Release|Win32\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.Release|Win32.Build.0 = Release|Win32\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.Release|x64.ActiveCfg = Release|x64\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.Release|x64.Build.0 = Release|x64\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.ReleaseWithoutAsm|Win32.Build.0 = Release|Win32\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {9838038D-09A3-43A5-AB97-B5B5C763DF43}.ReleaseWithoutAsm|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.Build.0 = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+       EndGlobalSection\r
+       GlobalSection(SolutionProperties) = preSolution\r
+               HideSolutionNode = FALSE\r
+       EndGlobalSection\r
+EndGlobal\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/x64/Release/libexpat-1.dll b/1.8/org.simantics.fmu/FMUSolution/x64/Release/libexpat-1.dll
new file mode 100644 (file)
index 0000000..0f8b01b
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/x64/Release/libexpat-1.dll differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/CMakeLists.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0a56ff6
--- /dev/null
@@ -0,0 +1,199 @@
+cmake_minimum_required(VERSION 2.4.4)
+set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS ON)
+
+project(zlib C)
+
+if(NOT DEFINED BUILD_SHARED_LIBS)
+    option(BUILD_SHARED_LIBS "Build a shared library form of zlib" ON)
+endif()
+
+include(CheckTypeSize)
+include(CheckFunctionExists)
+include(CheckIncludeFile)
+include(CheckCSourceCompiles)
+enable_testing()
+
+check_include_file(sys/types.h HAVE_SYS_TYPES_H)
+check_include_file(stdint.h    HAVE_STDINT_H)
+check_include_file(stddef.h    HAVE_STDDEF_H)
+
+#
+# Check to see if we have large file support
+#
+set(CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1)
+# We add these other definitions here because CheckTypeSize.cmake
+# in CMake 2.4.x does not automatically do so and we want
+# compatibility with CMake 2.4.x.
+if(HAVE_SYS_TYPES_H)
+    list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_SYS_TYPES_H)
+endif()
+if(HAVE_STDINT_H)
+    list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDINT_H)
+endif()
+if(HAVE_STDDEF_H)
+    list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDDEF_H)
+endif()
+check_type_size(off64_t OFF64_T)
+if(HAVE_OFF64_T)
+   add_definitions(-D_LARGEFILE64_SOURCE=1)
+endif()
+set(CMAKE_REQUIRED_DEFINITIONS) # clear variable
+
+#
+# Check for fseeko
+#
+check_function_exists(fseeko HAVE_FSEEKO)
+if(NOT HAVE_FSEEKO)
+    add_definitions(-DNO_FSEEKO)
+endif()
+
+#
+# Check for unistd.h
+#
+check_include_file(unistd.h Z_HAVE_UNISTD_H)
+
+if(MSVC)
+    set(CMAKE_DEBUG_POSTFIX "d")
+    add_definitions(-D_CRT_SECURE_NO_DEPRECATE)
+    add_definitions(-D_CRT_NONSTDC_NO_DEPRECATE)
+endif()
+
+if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)
+    # If we're doing an out of source build and the user has a zconf.h
+    # in their source tree...
+    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h)
+        message(FATAL_ERROR
+            "You must remove ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h "
+            "from the source tree.  This file is included with zlib "
+            "but CMake generates this file for you automatically "
+            "in the build directory.")
+  endif()
+endif()
+
+configure_file(${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.cmakein
+               ${CMAKE_CURRENT_BINARY_DIR}/zconf.h @ONLY)
+include_directories(${CMAKE_CURRENT_BINARY_DIR})
+
+
+#============================================================================
+# zlib
+#============================================================================
+
+set(ZLIB_PUBLIC_HDRS
+    ${CMAKE_CURRENT_BINARY_DIR}/zconf.h
+    zlib.h
+)
+set(ZLIB_PRIVATE_HDRS
+    crc32.h
+    deflate.h
+    gzguts.h
+    inffast.h
+    inffixed.h
+    inflate.h
+    inftrees.h
+    trees.h
+    zutil.h
+)
+set(ZLIB_SRCS
+    adler32.c
+    compress.c
+    crc32.c
+    deflate.c
+    gzclose.c
+    gzlib.c
+    gzread.c
+    gzwrite.c
+    inflate.c
+    infback.c
+    inftrees.c
+    inffast.c
+    trees.c
+    uncompr.c
+    zutil.c
+)
+
+if(NOT MINGW)
+    set(ZLIB_SRCS ${ZLIB_SRCS}
+        win32/zlib1.rc # If present will override custom build rule below.
+    )
+endif()
+
+# parse the full version number from zlib.h and include in ZLIB_FULL_VERSION
+file(READ ${CMAKE_CURRENT_SOURCE_DIR}/zlib.h _zlib_h_contents)
+string(REGEX REPLACE ".*#define[ \t]+ZLIB_VERSION[ \t]+\"([0-9A-Za-z.]+)\".*"
+    "\\1" ZLIB_FULL_VERSION ${_zlib_h_contents})
+
+if(MINGW)
+    # This gets us DLL resource information when compiling on MinGW.
+    if(NOT CMAKE_RC_COMPILER)
+        SET(CMAKE_RC_COMPILER windres.exe)
+    endif()
+
+    add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj
+                       COMMAND ${CMAKE_RC_COMPILER}
+                            -D GCC_WINDRES
+                            -I ${CMAKE_CURRENT_SOURCE_DIR}
+                            -I ${CMAKE_CURRENT_BINARY_DIR}
+                            -o ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj
+                            -i ${CMAKE_CURRENT_SOURCE_DIR}/win32/zlib1.rc)
+    set(ZLIB_SRCS ${ZLIB_SRCS} ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj)
+endif(MINGW)
+
+add_library(zlib ${ZLIB_SRCS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS})
+set_target_properties(zlib PROPERTIES DEFINE_SYMBOL ZLIB_DLL)
+
+set_target_properties(zlib PROPERTIES SOVERSION 1)
+
+if(NOT CYGWIN)
+    # This property causes shared libraries on Linux to have the full version
+    # encoded into their final filename.  We disable this on Cygwin because
+    # it causes cygz-${ZLIB_FULL_VERSION}.dll to be created when cygz.dll
+    # seems to be the default.
+    #
+    # This has no effect with MSVC, on that platform the version info for
+    # the DLL comes from the resource file win32/zlib1.rc
+    set_target_properties(zlib PROPERTIES VERSION ${ZLIB_FULL_VERSION})
+endif()
+
+if(UNIX)
+    # On unix-like platforms the library is almost always called libz
+   set_target_properties(zlib PROPERTIES OUTPUT_NAME z)
+elseif(BUILD_SHARED_LIBS AND WIN32)
+    # Creates zlib1.dll when building shared library version
+    set_target_properties(zlib PROPERTIES SUFFIX "1.dll")
+endif()
+
+if(NOT SKIP_INSTALL_LIBRARIES AND NOT SKIP_INSTALL_ALL )
+    install(TARGETS zlib
+        RUNTIME DESTINATION bin
+        ARCHIVE DESTINATION lib
+        LIBRARY DESTINATION lib )
+endif()
+if(NOT SKIP_INSTALL_HEADERS AND NOT SKIP_INSTALL_ALL )
+    install(FILES ${ZLIB_PUBLIC_HDRS} DESTINATION include)
+endif()
+if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL )
+    install(FILES zlib.3 DESTINATION share/man/man3)
+endif()
+
+#============================================================================
+# Example binaries
+#============================================================================
+
+add_executable(example test/example.c)
+target_link_libraries(example zlib)
+add_test(example example)
+
+add_executable(minigzip test/minigzip.c)
+target_link_libraries(minigzip zlib)
+
+if(HAVE_OFF64_T)
+    add_executable(example64 test/example.c)
+    target_link_libraries(example64 zlib)
+    set_target_properties(example64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64")
+    add_test(example64 example64)
+
+    add_executable(minigzip64 test/minigzip.c)
+    target_link_libraries(minigzip64 zlib)
+    set_target_properties(minigzip64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64")
+endif()
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/ChangeLog b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/ChangeLog
new file mode 100644 (file)
index 0000000..6fa5d44
--- /dev/null
@@ -0,0 +1,1347 @@
+
+                ChangeLog file for zlib
+
+Changes in 1.2.6 (29 Jan 2012)
+- Update the Pascal interface in contrib/pascal
+- Fix function numbers for gzgetc_ in zlibvc.def files
+- Fix configure.ac for contrib/minizip [Schiffer]
+- Fix large-entry detection in minizip on 64-bit systems [Schiffer]
+- Have ./configure use the compiler return code for error indication
+- Fix CMakeLists.txt for cross compilation [McClure]
+- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes]
+- Fix compilation of contrib/minizip on FreeBSD [Marquez]
+- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath]
+- Include io.h for Turbo C / Borland C on all platforms [Truta]
+- Make version explicit in contrib/minizip/configure.ac [Bosmans]
+- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant]
+- Minor cleanup up contrib/minizip/unzip.c [Vollant]
+- Fix bug when compiling minizip with C++ [Vollant]
+- Protect for long name and extra fields in contrib/minizip [Vollant]
+- Avoid some warnings in contrib/minizip [Vollant]
+- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip
+- Add missing libs to minizip linker command
+- Add support for VPATH builds in contrib/minizip
+- Add an --enable-demos option to contrib/minizip/configure
+- Add the generation of configure.log by ./configure
+- Exit when required parameters not provided to win32/Makefile.gcc
+- Have gzputc return the character written instead of the argument
+- Use the -m option on ldconfig for BSD systems [Tobias]
+- Correct in zlib.map when deflateResetKeep was added
+
+Changes in 1.2.5.3 (15 Jan 2012)
+- Restore gzgetc function for binary compatibility
+- Do not use _lseeki64 under Borland C++ [Truta]
+- Update win32/Makefile.msc to build test/*.c [Truta]
+- Remove old/visualc6 given CMakefile and other alternatives
+- Update AS400 build files and documentation [Monnerat]
+- Update win32/Makefile.gcc to build test/*.c [Truta]
+- Permit stronger flushes after Z_BLOCK flushes
+- Avoid extraneous empty blocks when doing empty flushes
+- Permit Z_NULL arguments to deflatePending
+- Allow deflatePrime() to insert bits in the middle of a stream
+- Remove second empty static block for Z_PARTIAL_FLUSH
+- Write out all of the available bits when using Z_BLOCK
+- Insert the first two strings in the hash table after a flush
+
+Changes in 1.2.5.2 (17 Dec 2011)
+- fix ld error: unable to find version dependency 'ZLIB_1.2.5'
+- use relative symlinks for shared libs
+- Avoid searching past window for Z_RLE strategy
+- Assure that high-water mark initialization is always applied in deflate
+- Add assertions to fill_window() in deflate.c to match comments
+- Update python link in README
+- Correct spelling error in gzread.c
+- Fix bug in gzgets() for a concatenated empty gzip stream
+- Correct error in comment for gz_make()
+- Change gzread() and related to ignore junk after gzip streams
+- Allow gzread() and related to continue after gzclearerr()
+- Allow gzrewind() and gzseek() after a premature end-of-file
+- Simplify gzseek() now that raw after gzip is ignored
+- Change gzgetc() to a macro for speed (~40% speedup in testing)
+- Fix gzclose() to return the actual error last encountered
+- Always add large file support for windows
+- Include zconf.h for windows large file support
+- Include zconf.h.cmakein for windows large file support
+- Update zconf.h.cmakein on make distclean
+- Merge vestigial vsnprintf determination from zutil.h to gzguts.h
+- Clarify how gzopen() appends in zlib.h comments
+- Correct documentation of gzdirect() since junk at end now ignored
+- Add a transparent write mode to gzopen() when 'T' is in the mode
+- Update python link in zlib man page
+- Get inffixed.h and MAKEFIXED result to match
+- Add a ./config --solo option to make zlib subset with no libary use
+- Add undocumented inflateResetKeep() function for CAB file decoding
+- Add --cover option to ./configure for gcc coverage testing
+- Add #define ZLIB_CONST option to use const in the z_stream interface
+- Add comment to gzdopen() in zlib.h to use dup() when using fileno()
+- Note behavior of uncompress() to provide as much data as it can
+- Add files in contrib/minizip to aid in building libminizip
+- Split off AR options in Makefile.in and configure
+- Change ON macro to Z_ARG to avoid application conflicts
+- Facilitate compilation with Borland C++ for pragmas and vsnprintf
+- Include io.h for Turbo C / Borland C++
+- Move example.c and minigzip.c to test/
+- Simplify incomplete code table filling in inflate_table()
+- Remove code from inflate.c and infback.c that is impossible to execute
+- Test the inflate code with full coverage
+- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw)
+- Add deflateResetKeep and fix inflateResetKeep to retain dictionary
+- Fix gzwrite.c to accommodate reduced memory zlib compilation
+- Have inflate() with Z_FINISH avoid the allocation of a window
+- Do not set strm->adler when doing raw inflate
+- Fix gzeof() to behave just like feof() when read is not past end of file
+- Fix bug in gzread.c when end-of-file is reached
+- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF
+- Document gzread() capability to read concurrently written files
+- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo]
+
+Changes in 1.2.5.1 (10 Sep 2011)
+- Update FAQ entry on shared builds (#13)
+- Avoid symbolic argument to chmod in Makefile.in
+- Fix bug and add consts in contrib/puff [Oberhumer]
+- Update contrib/puff/zeros.raw test file to have all block types
+- Add full coverage test for puff in contrib/puff/Makefile
+- Fix static-only-build install in Makefile.in
+- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno]
+- Add libz.a dependency to shared in Makefile.in for parallel builds
+- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out
+- Replace $(...) with `...` in configure for non-bash sh [Bowler]
+- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen]
+- Add solaris* to Linux* in configure to allow gcc use [Groffen]
+- Add *bsd* to Linux* case in configure [Bar-Lev]
+- Add inffast.obj to dependencies in win32/Makefile.msc
+- Correct spelling error in deflate.h [Kohler]
+- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc
+- Add test to configure for GNU C looking for gcc in output of $cc -v
+- Add zlib.pc generation to win32/Makefile.gcc [Weigelt]
+- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not
+- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense
+- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser)
+- Make stronger test in zconf.h to include unistd.h for LFS
+- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack]
+- Fix zlib.h LFS support when Z_PREFIX used
+- Add updated as400 support (removed from old) [Monnerat]
+- Avoid deflate sensitivity to volatile input data
+- Avoid division in adler32_combine for NO_DIVIDE
+- Clarify the use of Z_FINISH with deflateBound() amount of space
+- Set binary for output file in puff.c
+- Use u4 type for crc_table to avoid conversion warnings
+- Apply casts in zlib.h to avoid conversion warnings
+- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller]
+- Improve inflateSync() documentation to note indeterminancy
+- Add deflatePending() function to return the amount of pending output
+- Correct the spelling of "specification" in FAQ [Randers-Pehrson]
+- Add a check in configure for stdarg.h, use for gzprintf()
+- Check that pointers fit in ints when gzprint() compiled old style
+- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler]
+- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt]
+- Add debug records in assmebler code [Londer]
+- Update RFC references to use http://tools.ietf.org/html/... [Li]
+- Add --archs option, use of libtool to configure for Mac OS X [Borstel]
+
+Changes in 1.2.5 (19 Apr 2010)
+- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev]
+- Default to libdir as sharedlibdir in configure [Nieder]
+- Update copyright dates on modified source files
+- Update trees.c to be able to generate modified trees.h
+- Exit configure for MinGW, suggesting win32/Makefile.gcc
+- Check for NULL path in gz_open [Homurlu]
+
+Changes in 1.2.4.5 (18 Apr 2010)
+- Set sharedlibdir in configure [Torok]
+- Set LDFLAGS in Makefile.in [Bar-Lev]
+- Avoid mkdir objs race condition in Makefile.in [Bowler]
+- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays
+- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C
+- Don't use hidden attribute when it is a warning generator (e.g. Solaris)
+
+Changes in 1.2.4.4 (18 Apr 2010)
+- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok]
+- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty
+- Try to use bash or ksh regardless of functionality of /bin/sh
+- Fix configure incompatibility with NetBSD sh
+- Remove attempt to run under bash or ksh since have better NetBSD fix
+- Fix win32/Makefile.gcc for MinGW [Bar-Lev]
+- Add diagnostic messages when using CROSS_PREFIX in configure
+- Added --sharedlibdir option to configure [Weigelt]
+- Use hidden visibility attribute when available [Frysinger]
+
+Changes in 1.2.4.3 (10 Apr 2010)
+- Only use CROSS_PREFIX in configure for ar and ranlib if they exist
+- Use CROSS_PREFIX for nm [Bar-Lev]
+- Assume _LARGEFILE64_SOURCE defined is equivalent to true
+- Avoid use of undefined symbols in #if with && and ||
+- Make *64 prototypes in gzguts.h consistent with functions
+- Add -shared load option for MinGW in configure [Bowler]
+- Move z_off64_t to public interface, use instead of off64_t
+- Remove ! from shell test in configure (not portable to Solaris)
+- Change +0 macro tests to -0 for possibly increased portability
+
+Changes in 1.2.4.2 (9 Apr 2010)
+- Add consistent carriage returns to readme.txt's in masmx86 and masmx64
+- Really provide prototypes for *64 functions when building without LFS
+- Only define unlink() in minigzip.c if unistd.h not included
+- Update README to point to contrib/vstudio project files
+- Move projects/vc6 to old/ and remove projects/
+- Include stdlib.h in minigzip.c for setmode() definition under WinCE
+- Clean up assembler builds in win32/Makefile.msc [Rowe]
+- Include sys/types.h for Microsoft for off_t definition
+- Fix memory leak on error in gz_open()
+- Symbolize nm as $NM in configure [Weigelt]
+- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt]
+- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined
+- Fix bug in gzeof() to take into account unused input data
+- Avoid initialization of structures with variables in puff.c
+- Updated win32/README-WIN32.txt [Rowe]
+
+Changes in 1.2.4.1 (28 Mar 2010)
+- Remove the use of [a-z] constructs for sed in configure [gentoo 310225]
+- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech]
+- Restore "for debugging" comment on sprintf() in gzlib.c
+- Remove fdopen for MVS from gzguts.h
+- Put new README-WIN32.txt in win32 [Rowe]
+- Add check for shell to configure and invoke another shell if needed
+- Fix big fat stinking bug in gzseek() on uncompressed files
+- Remove vestigial F_OPEN64 define in zutil.h
+- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE
+- Avoid errors on non-LFS systems when applications define LFS macros
+- Set EXE to ".exe" in configure for MINGW [Kahle]
+- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill]
+- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev]
+- Add DLL install in win32/makefile.gcc [Bar-Lev]
+- Allow Linux* or linux* from uname in configure [Bar-Lev]
+- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev]
+- Add cross-compilation prefixes to configure [Bar-Lev]
+- Match type exactly in gz_load() invocation in gzread.c
+- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func
+- Provide prototypes for *64 functions when building zlib without LFS
+- Don't use -lc when linking shared library on MinGW
+- Remove errno.h check in configure and vestigial errno code in zutil.h
+
+Changes in 1.2.4 (14 Mar 2010)
+- Fix VER3 extraction in configure for no fourth subversion
+- Update zlib.3, add docs to Makefile.in to make .pdf out of it
+- Add zlib.3.pdf to distribution
+- Don't set error code in gzerror() if passed pointer is NULL
+- Apply destination directory fixes to CMakeLists.txt [Lowman]
+- Move #cmakedefine's to a new zconf.in.cmakein
+- Restore zconf.h for builds that don't use configure or cmake
+- Add distclean to dummy Makefile for convenience
+- Update and improve INDEX, README, and FAQ
+- Update CMakeLists.txt for the return of zconf.h [Lowman]
+- Update contrib/vstudio/vc9 and vc10 [Vollant]
+- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc
+- Apply license and readme changes to contrib/asm686 [Raiter]
+- Check file name lengths and add -c option in minigzip.c [Li]
+- Update contrib/amd64 and contrib/masmx86/ [Vollant]
+- Avoid use of "eof" parameter in trees.c to not shadow library variable
+- Update make_vms.com for removal of zlibdefs.h [Zinser]
+- Update assembler code and vstudio projects in contrib [Vollant]
+- Remove outdated assembler code contrib/masm686 and contrib/asm586
+- Remove old vc7 and vc8 from contrib/vstudio
+- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe]
+- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open()
+- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant]
+- Remove *64 functions from win32/zlib.def (they're not 64-bit yet)
+- Fix bug in void-returning vsprintf() case in gzwrite.c
+- Fix name change from inflate.h in contrib/inflate86/inffas86.c
+- Check if temporary file exists before removing in make_vms.com [Zinser]
+- Fix make install and uninstall for --static option
+- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta]
+- Update readme.txt in contrib/masmx64 and masmx86 to assemble
+
+Changes in 1.2.3.9 (21 Feb 2010)
+- Expunge gzio.c
+- Move as400 build information to old
+- Fix updates in contrib/minizip and contrib/vstudio
+- Add const to vsnprintf test in configure to avoid warnings [Weigelt]
+- Delete zconf.h (made by configure) [Weigelt]
+- Change zconf.in.h to zconf.h.in per convention [Weigelt]
+- Check for NULL buf in gzgets()
+- Return empty string for gzgets() with len == 1 (like fgets())
+- Fix description of gzgets() in zlib.h for end-of-file, NULL return
+- Update minizip to 1.1 [Vollant]
+- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c
+- Note in zlib.h that gzerror() should be used to distinguish from EOF
+- Remove use of snprintf() from gzlib.c
+- Fix bug in gzseek()
+- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant]
+- Fix zconf.h generation in CMakeLists.txt [Lowman]
+- Improve comments in zconf.h where modified by configure
+
+Changes in 1.2.3.8 (13 Feb 2010)
+- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer]
+- Use z_off64_t in gz_zero() and gz_skip() to match state->skip
+- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t)
+- Revert to Makefile.in from 1.2.3.6 (live with the clutter)
+- Fix missing error return in gzflush(), add zlib.h note
+- Add *64 functions to zlib.map [Levin]
+- Fix signed/unsigned comparison in gz_comp()
+- Use SFLAGS when testing shared linking in configure
+- Add --64 option to ./configure to use -m64 with gcc
+- Fix ./configure --help to correctly name options
+- Have make fail if a test fails [Levin]
+- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson]
+- Remove assembler object files from contrib
+
+Changes in 1.2.3.7 (24 Jan 2010)
+- Always gzopen() with O_LARGEFILE if available
+- Fix gzdirect() to work immediately after gzopen() or gzdopen()
+- Make gzdirect() more precise when the state changes while reading
+- Improve zlib.h documentation in many places
+- Catch memory allocation failure in gz_open()
+- Complete close operation if seek forward in gzclose_w() fails
+- Return Z_ERRNO from gzclose_r() if close() fails
+- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL
+- Return zero for gzwrite() errors to match zlib.h description
+- Return -1 on gzputs() error to match zlib.h description
+- Add zconf.in.h to allow recovery from configure modification [Weigelt]
+- Fix static library permissions in Makefile.in [Weigelt]
+- Avoid warnings in configure tests that hide functionality [Weigelt]
+- Add *BSD and DragonFly to Linux case in configure [gentoo 123571]
+- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212]
+- Avoid access of uninitialized data for first inflateReset2 call [Gomes]
+- Keep object files in subdirectories to reduce the clutter somewhat
+- Remove default Makefile and zlibdefs.h, add dummy Makefile
+- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_
+- Remove zlibdefs.h completely -- modify zconf.h instead
+
+Changes in 1.2.3.6 (17 Jan 2010)
+- Avoid void * arithmetic in gzread.c and gzwrite.c
+- Make compilers happier with const char * for gz_error message
+- Avoid unused parameter warning in inflate.c
+- Avoid signed-unsigned comparison warning in inflate.c
+- Indent #pragma's for traditional C
+- Fix usage of strwinerror() in glib.c, change to gz_strwinerror()
+- Correct email address in configure for system options
+- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser]
+- Update zlib.map [Brown]
+- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok]
+- Apply various fixes to CMakeLists.txt [Lowman]
+- Add checks on len in gzread() and gzwrite()
+- Add error message for no more room for gzungetc()
+- Remove zlib version check in gzwrite()
+- Defer compression of gzprintf() result until need to
+- Use snprintf() in gzdopen() if available
+- Remove USE_MMAP configuration determination (only used by minigzip)
+- Remove examples/pigz.c (available separately)
+- Update examples/gun.c to 1.6
+
+Changes in 1.2.3.5 (8 Jan 2010)
+- Add space after #if in zutil.h for some compilers
+- Fix relatively harmless bug in deflate_fast() [Exarevsky]
+- Fix same problem in deflate_slow()
+- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown]
+- Add deflate_rle() for faster Z_RLE strategy run-length encoding
+- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding
+- Change name of "write" variable in inffast.c to avoid library collisions
+- Fix premature EOF from gzread() in gzio.c [Brown]
+- Use zlib header window size if windowBits is 0 in inflateInit2()
+- Remove compressBound() call in deflate.c to avoid linking compress.o
+- Replace use of errno in gz* with functions, support WinCE [Alves]
+- Provide alternative to perror() in minigzip.c for WinCE [Alves]
+- Don't use _vsnprintf on later versions of MSVC [Lowman]
+- Add CMake build script and input file [Lowman]
+- Update contrib/minizip to 1.1 [Svensson, Vollant]
+- Moved nintendods directory from contrib to .
+- Replace gzio.c with a new set of routines with the same functionality
+- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above
+- Update contrib/minizip to 1.1b
+- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h
+
+Changes in 1.2.3.4 (21 Dec 2009)
+- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility
+- Update comments in configure and Makefile.in for default --shared
+- Fix test -z's in configure [Marquess]
+- Build examplesh and minigzipsh when not testing
+- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h
+- Import LDFLAGS from the environment in configure
+- Fix configure to populate SFLAGS with discovered CFLAGS options
+- Adapt make_vms.com to the new Makefile.in [Zinser]
+- Add zlib2ansi script for C++ compilation [Marquess]
+- Add _FILE_OFFSET_BITS=64 test to make test (when applicable)
+- Add AMD64 assembler code for longest match to contrib [Teterin]
+- Include options from $SFLAGS when doing $LDSHARED
+- Simplify 64-bit file support by introducing z_off64_t type
+- Make shared object files in objs directory to work around old Sun cc
+- Use only three-part version number for Darwin shared compiles
+- Add rc option to ar in Makefile.in for when ./configure not run
+- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4*
+- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile
+- Protect against _FILE_OFFSET_BITS being defined when compiling zlib
+- Rename Makefile.in targets allstatic to static and allshared to shared
+- Fix static and shared Makefile.in targets to be independent
+- Correct error return bug in gz_open() by setting state [Brown]
+- Put spaces before ;;'s in configure for better sh compatibility
+- Add pigz.c (parallel implementation of gzip) to examples/
+- Correct constant in crc32.c to UL [Leventhal]
+- Reject negative lengths in crc32_combine()
+- Add inflateReset2() function to work like inflateEnd()/inflateInit2()
+- Include sys/types.h for _LARGEFILE64_SOURCE [Brown]
+- Correct typo in doc/algorithm.txt [Janik]
+- Fix bug in adler32_combine() [Zhu]
+- Catch missing-end-of-block-code error in all inflates and in puff
+    Assures that random input to inflate eventually results in an error
+- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/
+- Update ENOUGH and its usage to reflect discovered bounds
+- Fix gzerror() error report on empty input file [Brown]
+- Add ush casts in trees.c to avoid pedantic runtime errors
+- Fix typo in zlib.h uncompress() description [Reiss]
+- Correct inflate() comments with regard to automatic header detection
+- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays)
+- Put new version of gzlog (2.0) in examples with interruption recovery
+- Add puff compile option to permit invalid distance-too-far streams
+- Add puff TEST command options, ability to read piped input
+- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but
+  _LARGEFILE64_SOURCE not defined
+- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart
+- Fix deflateSetDictionary() to use all 32K for output consistency
+- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h)
+- Clear bytes after deflate lookahead to avoid use of uninitialized data
+- Change a limit in inftrees.c to be more transparent to Coverity Prevent
+- Update win32/zlib.def with exported symbols from zlib.h
+- Correct spelling errors in zlib.h [Willem, Sobrado]
+- Allow Z_BLOCK for deflate() to force a new block
+- Allow negative bits in inflatePrime() to delete existing bit buffer
+- Add Z_TREES flush option to inflate() to return at end of trees
+- Add inflateMark() to return current state information for random access
+- Add Makefile for NintendoDS to contrib [Costa]
+- Add -w in configure compile tests to avoid spurious warnings [Beucler]
+- Fix typos in zlib.h comments for deflateSetDictionary()
+- Fix EOF detection in transparent gzread() [Maier]
+
+Changes in 1.2.3.3 (2 October 2006)
+- Make --shared the default for configure, add a --static option
+- Add compile option to permit invalid distance-too-far streams
+- Add inflateUndermine() function which is required to enable above
+- Remove use of "this" variable name for C++ compatibility [Marquess]
+- Add testing of shared library in make test, if shared library built
+- Use ftello() and fseeko() if available instead of ftell() and fseek()
+- Provide two versions of all functions that use the z_off_t type for
+  binary compatibility -- a normal version and a 64-bit offset version,
+  per the Large File Support Extension when _LARGEFILE64_SOURCE is
+  defined; use the 64-bit versions by default when _FILE_OFFSET_BITS
+  is defined to be 64
+- Add a --uname= option to configure to perhaps help with cross-compiling
+
+Changes in 1.2.3.2 (3 September 2006)
+- Turn off silly Borland warnings [Hay]
+- Use off64_t and define _LARGEFILE64_SOURCE when present
+- Fix missing dependency on inffixed.h in Makefile.in
+- Rig configure --shared to build both shared and static [Teredesai, Truta]
+- Remove zconf.in.h and instead create a new zlibdefs.h file
+- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant]
+- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt]
+
+Changes in 1.2.3.1 (16 August 2006)
+- Add watcom directory with OpenWatcom make files [Daniel]
+- Remove #undef of FAR in zconf.in.h for MVS [Fedtke]
+- Update make_vms.com [Zinser]
+- Use -fPIC for shared build in configure [Teredesai, Nicholson]
+- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen]
+- Use fdopen() (not _fdopen()) for Interix in zutil.h [B\8ack]
+- Add some FAQ entries about the contrib directory
+- Update the MVS question in the FAQ
+- Avoid extraneous reads after EOF in gzio.c [Brown]
+- Correct spelling of "successfully" in gzio.c [Randers-Pehrson]
+- Add comments to zlib.h about gzerror() usage [Brown]
+- Set extra flags in gzip header in gzopen() like deflate() does
+- Make configure options more compatible with double-dash conventions
+  [Weigelt]
+- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen]
+- Fix uninstall target in Makefile.in [Truta]
+- Add pkgconfig support [Weigelt]
+- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt]
+- Replace set_data_type() with a more accurate detect_data_type() in
+  trees.c, according to the txtvsbin.txt document [Truta]
+- Swap the order of #include <stdio.h> and #include "zlib.h" in
+  gzio.c, example.c and minigzip.c [Truta]
+- Shut up annoying VS2005 warnings about standard C deprecation [Rowe,
+  Truta] (where?)
+- Fix target "clean" from win32/Makefile.bor [Truta]
+- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe]
+- Update zlib www home address in win32/DLL_FAQ.txt [Truta]
+- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove]
+- Enable browse info in the "Debug" and "ASM Debug" configurations in
+  the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta]
+- Add pkgconfig support [Weigelt]
+- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h,
+  for use in win32/zlib1.rc [Polushin, Rowe, Truta]
+- Add a document that explains the new text detection scheme to
+  doc/txtvsbin.txt [Truta]
+- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta]
+- Move algorithm.txt into doc/ [Truta]
+- Synchronize FAQ with website
+- Fix compressBound(), was low for some pathological cases [Fearnley]
+- Take into account wrapper variations in deflateBound()
+- Set examples/zpipe.c input and output to binary mode for Windows
+- Update examples/zlib_how.html with new zpipe.c (also web site)
+- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems
+  that gcc became pickier in 4.0)
+- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain
+  un-versioned, the patch adds versioning only for symbols introduced in
+  zlib-1.2.0 or later.  It also declares as local those symbols which are
+  not designed to be exported." [Levin]
+- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure
+- Do not initialize global static by default in trees.c, add a response
+  NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess]
+- Don't use strerror() in gzio.c under WinCE [Yakimov]
+- Don't use errno.h in zutil.h under WinCE [Yakimov]
+- Move arguments for AR to its usage to allow replacing ar [Marot]
+- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson]
+- Improve inflateInit() and inflateInit2() documentation
+- Fix structure size comment in inflate.h
+- Change configure help option from --h* to --help [Santos]
+
+Changes in 1.2.3 (18 July 2005)
+- Apply security vulnerability fixes to contrib/infback9 as well
+- Clean up some text files (carriage returns, trailing space)
+- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
+
+Changes in 1.2.2.4 (11 July 2005)
+- Add inflatePrime() function for starting inflation at bit boundary
+- Avoid some Visual C warnings in deflate.c
+- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
+  compile
+- Fix some spelling errors in comments [Betts]
+- Correct inflateInit2() error return documentation in zlib.h
+- Add zran.c example of compressed data random access to examples
+  directory, shows use of inflatePrime()
+- Fix cast for assignments to strm->state in inflate.c and infback.c
+- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
+- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
+- Add cast in trees.c t avoid a warning [Oberhumer]
+- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
+- Update make_vms.com [Zinser]
+- Initialize state->write in inflateReset() since copied in inflate_fast()
+- Be more strict on incomplete code sets in inflate_table() and increase
+  ENOUGH and MAXD -- this repairs a possible security vulnerability for
+  invalid inflate input.  Thanks to Tavis Ormandy and Markus Oberhumer for
+  discovering the vulnerability and providing test cases.
+- Add ia64 support to configure for HP-UX [Smith]
+- Add error return to gzread() for format or i/o error [Levin]
+- Use malloc.h for OS/2 [Necasek]
+
+Changes in 1.2.2.3 (27 May 2005)
+- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
+- Typecast fread() return values in gzio.c [Vollant]
+- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
+- Fix crc check bug in gzread() after gzungetc() [Heiner]
+- Add the deflateTune() function to adjust internal compression parameters
+- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
+- Remove an incorrect assertion in examples/zpipe.c
+- Add C++ wrapper in infback9.h [Donais]
+- Fix bug in inflateCopy() when decoding fixed codes
+- Note in zlib.h how much deflateSetDictionary() actually uses
+- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
+- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
+- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
+- Add gzdirect() function to indicate transparent reads
+- Update contrib/minizip [Vollant]
+- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
+- Add casts in crc32.c to avoid warnings [Oberhumer]
+- Add contrib/masmx64 [Vollant]
+- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
+
+Changes in 1.2.2.2 (30 December 2004)
+- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
+  avoid implicit memcpy calls (portability for no-library compilation)
+- Increase sprintf() buffer size in gzdopen() to allow for large numbers
+- Add INFLATE_STRICT to check distances against zlib header
+- Improve WinCE errno handling and comments [Chang]
+- Remove comment about no gzip header processing in FAQ
+- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
+- Add updated make_vms.com [Coghlan], update README
+- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
+  fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html.
+- Add FAQ entry and comments in deflate.c on uninitialized memory access
+- Add Solaris 9 make options in configure [Gilbert]
+- Allow strerror() usage in gzio.c for STDC
+- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
+- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
+- Use z_off_t for adler32_combine() and crc32_combine() lengths
+- Make adler32() much faster for small len
+- Use OS_CODE in deflate() default gzip header
+
+Changes in 1.2.2.1 (31 October 2004)
+- Allow inflateSetDictionary() call for raw inflate
+- Fix inflate header crc check bug for file names and comments
+- Add deflateSetHeader() and gz_header structure for custom gzip headers
+- Add inflateGetheader() to retrieve gzip headers
+- Add crc32_combine() and adler32_combine() functions
+- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
+- Use zstreamp consistently in zlib.h (inflate_back functions)
+- Remove GUNZIP condition from definition of inflate_mode in inflate.h
+  and in contrib/inflate86/inffast.S [Truta, Anderson]
+- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
+- Update projects/README.projects and projects/visualc6 [Truta]
+- Update win32/DLL_FAQ.txt [Truta]
+- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
+- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
+- Use a new algorithm for setting strm->data_type in trees.c [Truta]
+- Do not define an exit() prototype in zutil.c unless DEBUG defined
+- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
+- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
+- Fix Darwin build version identification [Peterson]
+
+Changes in 1.2.2 (3 October 2004)
+- Update zlib.h comments on gzip in-memory processing
+- Set adler to 1 in inflateReset() to support Java test suite [Walles]
+- Add contrib/dotzlib [Ravn]
+- Update win32/DLL_FAQ.txt [Truta]
+- Update contrib/minizip [Vollant]
+- Move contrib/visual-basic.txt to old/ [Truta]
+- Fix assembler builds in projects/visualc6/ [Truta]
+
+Changes in 1.2.1.2 (9 September 2004)
+- Update INDEX file
+- Fix trees.c to update strm->data_type (no one ever noticed!)
+- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
+- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
+- Add limited multitasking protection to DYNAMIC_CRC_TABLE
+- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
+- Don't declare strerror() under VMS [Mozilla]
+- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
+- Update contrib/ada [Anisimkov]
+- Update contrib/minizip [Vollant]
+- Fix configure to not hardcode directories for Darwin [Peterson]
+- Fix gzio.c to not return error on empty files [Brown]
+- Fix indentation; update version in contrib/delphi/ZLib.pas and
+  contrib/pascal/zlibpas.pas [Truta]
+- Update mkasm.bat in contrib/masmx86 [Truta]
+- Update contrib/untgz [Truta]
+- Add projects/README.projects [Truta]
+- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
+- Update win32/DLL_FAQ.txt [Truta]
+- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
+- Remove an unnecessary assignment to curr in inftrees.c [Truta]
+- Add OS/2 to exe builds in configure [Poltorak]
+- Remove err dummy parameter in zlib.h [Kientzle]
+
+Changes in 1.2.1.1 (9 January 2004)
+- Update email address in README
+- Several FAQ updates
+- Fix a big fat bug in inftrees.c that prevented decoding valid
+  dynamic blocks with only literals and no distance codes --
+  Thanks to "Hot Emu" for the bug report and sample file
+- Add a note to puff.c on no distance codes case.
+
+Changes in 1.2.1 (17 November 2003)
+- Remove a tab in contrib/gzappend/gzappend.c
+- Update some interfaces in contrib for new zlib functions
+- Update zlib version number in some contrib entries
+- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta]
+- Support shared libraries on Hurd and KFreeBSD [Brown]
+- Fix error in NO_DIVIDE option of adler32.c
+
+Changes in 1.2.0.8 (4 November 2003)
+- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas
+- Add experimental NO_DIVIDE #define in adler32.c
+    - Possibly faster on some processors (let me know if it is)
+- Correct Z_BLOCK to not return on first inflate call if no wrap
+- Fix strm->data_type on inflate() return to correctly indicate EOB
+- Add deflatePrime() function for appending in the middle of a byte
+- Add contrib/gzappend for an example of appending to a stream
+- Update win32/DLL_FAQ.txt [Truta]
+- Delete Turbo C comment in README [Truta]
+- Improve some indentation in zconf.h [Truta]
+- Fix infinite loop on bad input in configure script [Church]
+- Fix gzeof() for concatenated gzip files [Johnson]
+- Add example to contrib/visual-basic.txt [Michael B.]
+- Add -p to mkdir's in Makefile.in [vda]
+- Fix configure to properly detect presence or lack of printf functions
+- Add AS400 support [Monnerat]
+- Add a little Cygwin support [Wilson]
+
+Changes in 1.2.0.7 (21 September 2003)
+- Correct some debug formats in contrib/infback9
+- Cast a type in a debug statement in trees.c
+- Change search and replace delimiter in configure from % to # [Beebe]
+- Update contrib/untgz to 0.2 with various fixes [Truta]
+- Add build support for Amiga [Nikl]
+- Remove some directories in old that have been updated to 1.2
+- Add dylib building for Mac OS X in configure and Makefile.in
+- Remove old distribution stuff from Makefile
+- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X
+- Update links in README
+
+Changes in 1.2.0.6 (13 September 2003)
+- Minor FAQ updates
+- Update contrib/minizip to 1.00 [Vollant]
+- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta]
+- Update POSTINC comment for 68060 [Nikl]
+- Add contrib/infback9 with deflate64 decoding (unsupported)
+- For MVS define NO_vsnprintf and undefine FAR [van Burik]
+- Add pragma for fdopen on MVS [van Burik]
+
+Changes in 1.2.0.5 (8 September 2003)
+- Add OF to inflateBackEnd() declaration in zlib.h
+- Remember start when using gzdopen in the middle of a file
+- Use internal off_t counters in gz* functions to properly handle seeks
+- Perform more rigorous check for distance-too-far in inffast.c
+- Add Z_BLOCK flush option to return from inflate at block boundary
+- Set strm->data_type on return from inflate
+    - Indicate bits unused, if at block boundary, and if in last block
+- Replace size_t with ptrdiff_t in crc32.c, and check for correct size
+- Add condition so old NO_DEFLATE define still works for compatibility
+- FAQ update regarding the Windows DLL [Truta]
+- INDEX update: add qnx entry, remove aix entry [Truta]
+- Install zlib.3 into mandir [Wilson]
+- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta]
+- Adapt the zlib interface to the new DLL convention guidelines [Truta]
+- Introduce ZLIB_WINAPI macro to allow the export of functions using
+  the WINAPI calling convention, for Visual Basic [Vollant, Truta]
+- Update msdos and win32 scripts and makefiles [Truta]
+- Export symbols by name, not by ordinal, in win32/zlib.def [Truta]
+- Add contrib/ada [Anisimkov]
+- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta]
+- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant]
+- Add contrib/masm686 [Truta]
+- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm
+  [Truta, Vollant]
+- Update contrib/delphi; rename to contrib/pascal; add example [Truta]
+- Remove contrib/delphi2; add a new contrib/delphi [Truta]
+- Avoid inclusion of the nonstandard <memory.h> in contrib/iostream,
+  and fix some method prototypes [Truta]
+- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip
+  [Truta]
+- Avoid the use of backslash (\) in contrib/minizip [Vollant]
+- Fix file time handling in contrib/untgz; update makefiles [Truta]
+- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines
+  [Vollant]
+- Remove contrib/vstudio/vc15_16 [Vollant]
+- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta]
+- Update README.contrib [Truta]
+- Invert the assignment order of match_head and s->prev[...] in
+  INSERT_STRING [Truta]
+- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings
+  [Truta]
+- Compare function pointers with 0, not with NULL or Z_NULL [Truta]
+- Fix prototype of syncsearch in inflate.c [Truta]
+- Introduce ASMINF macro to be enabled when using an ASM implementation
+  of inflate_fast [Truta]
+- Change NO_DEFLATE to NO_GZCOMPRESS [Truta]
+- Modify test_gzio in example.c to take a single file name as a
+  parameter [Truta]
+- Exit the example.c program if gzopen fails [Truta]
+- Add type casts around strlen in example.c [Truta]
+- Remove casting to sizeof in minigzip.c; give a proper type
+  to the variable compared with SUFFIX_LEN [Truta]
+- Update definitions of STDC and STDC99 in zconf.h [Truta]
+- Synchronize zconf.h with the new Windows DLL interface [Truta]
+- Use SYS16BIT instead of __32BIT__ to distinguish between
+  16- and 32-bit platforms [Truta]
+- Use far memory allocators in small 16-bit memory models for
+  Turbo C [Truta]
+- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in
+  zlibCompileFlags [Truta]
+- Cygwin has vsnprintf [Wilson]
+- In Windows16, OS_CODE is 0, as in MSDOS [Truta]
+- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson]
+
+Changes in 1.2.0.4 (10 August 2003)
+- Minor FAQ updates
+- Be more strict when checking inflateInit2's windowBits parameter
+- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well
+- Add gzip wrapper option to deflateInit2 using windowBits
+- Add updated QNX rule in configure and qnx directory [Bonnefoy]
+- Make inflate distance-too-far checks more rigorous
+- Clean up FAR usage in inflate
+- Add casting to sizeof() in gzio.c and minigzip.c
+
+Changes in 1.2.0.3 (19 July 2003)
+- Fix silly error in gzungetc() implementation [Vollant]
+- Update contrib/minizip and contrib/vstudio [Vollant]
+- Fix printf format in example.c
+- Correct cdecl support in zconf.in.h [Anisimkov]
+- Minor FAQ updates
+
+Changes in 1.2.0.2 (13 July 2003)
+- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons
+- Attempt to avoid warnings in crc32.c for pointer-int conversion
+- Add AIX to configure, remove aix directory [Bakker]
+- Add some casts to minigzip.c
+- Improve checking after insecure sprintf() or vsprintf() calls
+- Remove #elif's from crc32.c
+- Change leave label to inf_leave in inflate.c and infback.c to avoid
+  library conflicts
+- Remove inflate gzip decoding by default--only enable gzip decoding by
+  special request for stricter backward compatibility
+- Add zlibCompileFlags() function to return compilation information
+- More typecasting in deflate.c to avoid warnings
+- Remove leading underscore from _Capital #defines [Truta]
+- Fix configure to link shared library when testing
+- Add some Windows CE target adjustments [Mai]
+- Remove #define ZLIB_DLL in zconf.h [Vollant]
+- Add zlib.3 [Rodgers]
+- Update RFC URL in deflate.c and algorithm.txt [Mai]
+- Add zlib_dll_FAQ.txt to contrib [Truta]
+- Add UL to some constants [Truta]
+- Update minizip and vstudio [Vollant]
+- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h
+- Expand use of NO_DUMMY_DECL to avoid all dummy structures
+- Added iostream3 to contrib [Schwardt]
+- Replace rewind() with fseek() for WinCE [Truta]
+- Improve setting of zlib format compression level flags
+    - Report 0 for huffman and rle strategies and for level == 0 or 1
+    - Report 2 only for level == 6
+- Only deal with 64K limit when necessary at compile time [Truta]
+- Allow TOO_FAR check to be turned off at compile time [Truta]
+- Add gzclearerr() function [Souza]
+- Add gzungetc() function
+
+Changes in 1.2.0.1 (17 March 2003)
+- Add Z_RLE strategy for run-length encoding [Truta]
+    - When Z_RLE requested, restrict matches to distance one
+    - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE
+- Correct FASTEST compilation to allow level == 0
+- Clean up what gets compiled for FASTEST
+- Incorporate changes to zconf.in.h [Vollant]
+    - Refine detection of Turbo C need for dummy returns
+    - Refine ZLIB_DLL compilation
+    - Include additional header file on VMS for off_t typedef
+- Try to use _vsnprintf where it supplants vsprintf [Vollant]
+- Add some casts in inffast.c
+- Enchance comments in zlib.h on what happens if gzprintf() tries to
+  write more than 4095 bytes before compression
+- Remove unused state from inflateBackEnd()
+- Remove exit(0) from minigzip.c, example.c
+- Get rid of all those darn tabs
+- Add "check" target to Makefile.in that does the same thing as "test"
+- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in
+- Update contrib/inflate86 [Anderson]
+- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant]
+- Add msdos and win32 directories with makefiles [Truta]
+- More additions and improvements to the FAQ
+
+Changes in 1.2.0 (9 March 2003)
+- New and improved inflate code
+    - About 20% faster
+    - Does not allocate 32K window unless and until needed
+    - Automatically detects and decompresses gzip streams
+    - Raw inflate no longer needs an extra dummy byte at end
+    - Added inflateBack functions using a callback interface--even faster
+      than inflate, useful for file utilities (gzip, zip)
+    - Added inflateCopy() function to record state for random access on
+      externally generated deflate streams (e.g. in gzip files)
+    - More readable code (I hope)
+- New and improved crc32()
+    - About 50% faster, thanks to suggestions from Rodney Brown
+- Add deflateBound() and compressBound() functions
+- Fix memory leak in deflateInit2()
+- Permit setting dictionary for raw deflate (for parallel deflate)
+- Fix const declaration for gzwrite()
+- Check for some malloc() failures in gzio.c
+- Fix bug in gzopen() on single-byte file 0x1f
+- Fix bug in gzread() on concatenated file with 0x1f at end of buffer
+  and next buffer doesn't start with 0x8b
+- Fix uncompress() to return Z_DATA_ERROR on truncated input
+- Free memory at end of example.c
+- Remove MAX #define in trees.c (conflicted with some libraries)
+- Fix static const's in deflate.c, gzio.c, and zutil.[ch]
+- Declare malloc() and free() in gzio.c if STDC not defined
+- Use malloc() instead of calloc() in zutil.c if int big enough
+- Define STDC for AIX
+- Add aix/ with approach for compiling shared library on AIX
+- Add HP-UX support for shared libraries in configure
+- Add OpenUNIX support for shared libraries in configure
+- Use $cc instead of gcc to build shared library
+- Make prefix directory if needed when installing
+- Correct Macintosh avoidance of typedef Byte in zconf.h
+- Correct Turbo C memory allocation when under Linux
+- Use libz.a instead of -lz in Makefile (assure use of compiled library)
+- Update configure to check for snprintf or vsnprintf functions and their
+  return value, warn during make if using an insecure function
+- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that
+  is lost when library is used--resolution is to build new zconf.h
+- Documentation improvements (in zlib.h):
+    - Document raw deflate and inflate
+    - Update RFCs URL
+    - Point out that zlib and gzip formats are different
+    - Note that Z_BUF_ERROR is not fatal
+    - Document string limit for gzprintf() and possible buffer overflow
+    - Note requirement on avail_out when flushing
+    - Note permitted values of flush parameter of inflate()
+- Add some FAQs (and even answers) to the FAQ
+- Add contrib/inflate86/ for x86 faster inflate
+- Add contrib/blast/ for PKWare Data Compression Library decompression
+- Add contrib/puff/ simple inflate for deflate format description
+
+Changes in 1.1.4 (11 March 2002)
+- ZFREE was repeated on same allocation on some error conditions.
+  This creates a security problem described in
+  http://www.zlib.org/advisory-2002-03-11.txt
+- Returned incorrect error (Z_MEM_ERROR) on some invalid data
+- Avoid accesses before window for invalid distances with inflate window
+  less than 32K.
+- force windowBits > 8 to avoid a bug in the encoder for a window size
+  of 256 bytes. (A complete fix will be available in 1.1.5).
+
+Changes in 1.1.3 (9 July 1998)
+- fix "an inflate input buffer bug that shows up on rare but persistent
+  occasions" (Mark)
+- fix gzread and gztell for concatenated .gz files (Didier Le Botlan)
+- fix gzseek(..., SEEK_SET) in write mode
+- fix crc check after a gzeek (Frank Faubert)
+- fix miniunzip when the last entry in a zip file is itself a zip file
+  (J Lillge)
+- add contrib/asm586 and contrib/asm686 (Brian Raiter)
+  See http://www.muppetlabs.com/~breadbox/software/assembly.html
+- add support for Delphi 3 in contrib/delphi (Bob Dellaca)
+- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti)
+- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren)
+- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks)
+- added a FAQ file
+
+- Support gzdopen on Mac with Metrowerks (Jason Linhart)
+- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart)
+- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young)
+- avoid some warnings with Borland C (Tom Tanner)
+- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant)
+- emulate utime() for WIN32 in contrib/untgz  (Gilles Vollant)
+- allow several arguments to configure (Tim Mooney, Frodo Looijaard)
+- use libdir and includedir in Makefile.in (Tim Mooney)
+- support shared libraries on OSF1 V4 (Tim Mooney)
+- remove so_locations in "make clean"  (Tim Mooney)
+- fix maketree.c compilation error (Glenn, Mark)
+- Python interface to zlib now in Python 1.5 (Jeremy Hylton)
+- new Makefile.riscos (Rich Walker)
+- initialize static descriptors in trees.c for embedded targets (Nick Smith)
+- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith)
+- add the OS/2 files in Makefile.in too (Andrew Zabolotny)
+- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane)
+- fix maketree.c to allow clean compilation of inffixed.h (Mark)
+- fix parameter check in deflateCopy (Gunther Nikl)
+- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler)
+- Many portability patches by Christian Spieler:
+  . zutil.c, zutil.h: added "const" for zmem*
+  . Make_vms.com: fixed some typos
+  . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists
+  . msdos/Makefile.msc: remove "default rtl link library" info from obj files
+  . msdos/Makefile.*: use model-dependent name for the built zlib library
+  . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc:
+     new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT)
+- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane)
+- replace __far with _far for better portability (Christian Spieler, Tom Lane)
+- fix test for errno.h in configure (Tim Newsham)
+
+Changes in 1.1.2 (19 March 98)
+- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant)
+  See http://www.winimage.com/zLibDll/unzip.html
+- preinitialize the inflate tables for fixed codes, to make the code
+  completely thread safe (Mark)
+- some simplifications and slight speed-up to the inflate code (Mark)
+- fix gzeof on non-compressed files (Allan Schrum)
+- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs)
+- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn)
+- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny)
+- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori)
+- do not wrap extern "C" around system includes (Tom Lane)
+- mention zlib binding for TCL in README (Andreas Kupries)
+- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert)
+- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson)
+- allow "configure --prefix $HOME" (Tim Mooney)
+- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson)
+- move Makefile.sas to amiga/Makefile.sas
+
+Changes in 1.1.1 (27 Feb 98)
+- fix macros _tr_tally_* in deflate.h for debug mode  (Glenn Randers-Pehrson)
+- remove block truncation heuristic which had very marginal effect for zlib
+  (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the
+  compression ratio on some files. This also allows inlining _tr_tally for
+  matches in deflate_slow.
+- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier)
+
+Changes in 1.1.0 (24 Feb 98)
+- do not return STREAM_END prematurely in inflate (John Bowler)
+- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler)
+- compile with -DFASTEST to get compression code optimized for speed only
+- in minigzip, try mmap'ing the input file first (Miguel Albrecht)
+- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain
+  on Sun but significant on HP)
+
+- add a pointer to experimental unzip library in README (Gilles Vollant)
+- initialize variable gcc in configure (Chris Herborth)
+
+Changes in 1.0.9 (17 Feb 1998)
+- added gzputs and gzgets functions
+- do not clear eof flag in gzseek (Mark Diekhans)
+- fix gzseek for files in transparent mode (Mark Diekhans)
+- do not assume that vsprintf returns the number of bytes written (Jens Krinke)
+- replace EXPORT with ZEXPORT to avoid conflict with other programs
+- added compress2 in zconf.h, zlib.def, zlib.dnt
+- new asm code from Gilles Vollant in contrib/asm386
+- simplify the inflate code (Mark):
+ . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new()
+ . ZALLOC the length list in inflate_trees_fixed() instead of using stack
+ . ZALLOC the value area for huft_build() instead of using stack
+ . Simplify Z_FINISH check in inflate()
+
+- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8
+- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi)
+- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with
+  the declaration of FAR (Gilles VOllant)
+- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann)
+- read_buf buf parameter of type Bytef* instead of charf*
+- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout)
+- do not redeclare unlink in minigzip.c for WIN32 (John Bowler)
+- fix check for presence of directories in "make install" (Ian Willis)
+
+Changes in 1.0.8 (27 Jan 1998)
+- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant)
+- fix gzgetc and gzputc for big endian systems (Markus Oberhumer)
+- added compress2() to allow setting the compression level
+- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong)
+- use constant arrays for the static trees in trees.c instead of computing
+  them at run time (thanks to Ken Raeburn for this suggestion). To create
+  trees.h, compile with GEN_TREES_H and run "make test".
+- check return code of example in "make test" and display result
+- pass minigzip command line options to file_compress
+- simplifying code of inflateSync to avoid gcc 2.8 bug
+
+- support CC="gcc -Wall" in configure -s (QingLong)
+- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn)
+- fix test for shared library support to avoid compiler warnings
+- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant)
+- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit)
+- do not use fdopen for Metrowerks on Mac (Brad Pettit))
+- add checks for gzputc and gzputc in example.c
+- avoid warnings in gzio.c and deflate.c (Andreas Kleinert)
+- use const for the CRC table (Ken Raeburn)
+- fixed "make uninstall" for shared libraries
+- use Tracev instead of Trace in infblock.c
+- in example.c use correct compressed length for test_sync
+- suppress +vnocompatwarnings in configure for HPUX (not always supported)
+
+Changes in 1.0.7 (20 Jan 1998)
+- fix gzseek which was broken in write mode
+- return error for gzseek to negative absolute position
+- fix configure for Linux (Chun-Chung Chen)
+- increase stack space for MSC (Tim Wegner)
+- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant)
+- define EXPORTVA for gzprintf (Gilles Vollant)
+- added man page zlib.3 (Rick Rodgers)
+- for contrib/untgz, fix makedir() and improve Makefile
+
+- check gzseek in write mode in example.c
+- allocate extra buffer for seeks only if gzseek is actually called
+- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant)
+- add inflateSyncPoint in zconf.h
+- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def
+
+Changes in 1.0.6 (19 Jan 1998)
+- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
+  gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
+- Fix a deflate bug occurring only with compression level 0 (thanks to
+  Andy Buckler for finding this one).
+- In minigzip, pass transparently also the first byte for .Z files.
+- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
+- check Z_FINISH in inflate (thanks to Marc Schluper)
+- Implement deflateCopy (thanks to Adam Costello)
+- make static libraries by default in configure, add --shared option.
+- move MSDOS or Windows specific files to directory msdos
+- suppress the notion of partial flush to simplify the interface
+  (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4)
+- suppress history buffer provided by application to simplify the interface
+  (this feature was not implemented anyway in 1.0.4)
+- next_in and avail_in must be initialized before calling inflateInit or
+  inflateInit2
+- add EXPORT in all exported functions (for Windows DLL)
+- added Makefile.nt (thanks to Stephen Williams)
+- added the unsupported "contrib" directory:
+   contrib/asm386/ by Gilles Vollant <info@winimage.com>
+        386 asm code replacing longest_match().
+   contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
+        A C++ I/O streams interface to the zlib gz* functions
+   contrib/iostream2/  by Tyge Løvset <Tyge.Lovset@cmr.no>
+        Another C++ I/O streams interface
+   contrib/untgz/  by "Pedro A. Aranda Guti\irrez" <paag@tid.es>
+        A very simple tar.gz file extractor using zlib
+   contrib/visual-basic.txt by Carlos Rios <c_rios@sonda.cl>
+        How to use compress(), uncompress() and the gz* functions from VB.
+- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression
+  level) in minigzip (thanks to Tom Lane)
+
+- use const for rommable constants in deflate
+- added test for gzseek and gztell in example.c
+- add undocumented function inflateSyncPoint() (hack for Paul Mackerras)
+- add undocumented function zError to convert error code to string
+  (for Tim Smithers)
+- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code.
+- Use default memcpy for Symantec MSDOS compiler.
+- Add EXPORT keyword for check_func (needed for Windows DLL)
+- add current directory to LD_LIBRARY_PATH for "make test"
+- create also a link for libz.so.1
+- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura)
+- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX)
+- added -soname for Linux in configure (Chun-Chung Chen,
+- assign numbers to the exported functions in zlib.def (for Windows DLL)
+- add advice in zlib.h for best usage of deflateSetDictionary
+- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn)
+- allow compilation with ANSI keywords only enabled for TurboC in large model
+- avoid "versionString"[0] (Borland bug)
+- add NEED_DUMMY_RETURN for Borland
+- use variable z_verbose for tracing in debug mode (L. Peter Deutsch).
+- allow compilation with CC
+- defined STDC for OS/2 (David Charlap)
+- limit external names to 8 chars for MVS (Thomas Lund)
+- in minigzip.c, use static buffers only for 16-bit systems
+- fix suffix check for "minigzip -d foo.gz"
+- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee)
+- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau)
+- added makelcc.bat for lcc-win32 (Tom St Denis)
+- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe)
+- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion.
+- check for unistd.h in configure (for off_t)
+- remove useless check parameter in inflate_blocks_free
+- avoid useless assignment of s->check to itself in inflate_blocks_new
+- do not flush twice in gzclose (thanks to Ken Raeburn)
+- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h
+- use NO_ERRNO_H instead of enumeration of operating systems with errno.h
+- work around buggy fclose on pipes for HP/UX
+- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson)
+- fix configure if CC is already equal to gcc
+
+Changes in 1.0.5 (3 Jan 98)
+- Fix inflate to terminate gracefully when fed corrupted or invalid data
+- Use const for rommable constants in inflate
+- Eliminate memory leaks on error conditions in inflate
+- Removed some vestigial code in inflate
+- Update web address in README
+
+Changes in 1.0.4 (24 Jul 96)
+- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF
+  bit, so the decompressor could decompress all the correct data but went
+  on to attempt decompressing extra garbage data. This affected minigzip too.
+- zlibVersion and gzerror return const char* (needed for DLL)
+- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno)
+- use z_error only for DEBUG (avoid problem with DLLs)
+
+Changes in 1.0.3 (2 Jul 96)
+- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS
+  small and medium models; this makes the library incompatible with previous
+  versions for these models. (No effect in large model or on other systems.)
+- return OK instead of BUF_ERROR if previous deflate call returned with
+  avail_out as zero but there is nothing to do
+- added memcmp for non STDC compilers
+- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly)
+- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO)
+- better check for 16-bit mode MSC (avoids problem with Symantec)
+
+Changes in 1.0.2 (23 May 96)
+- added Windows DLL support
+- added a function zlibVersion (for the DLL support)
+- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model)
+- Bytef is define's instead of typedef'd only for Borland C
+- avoid reading uninitialized memory in example.c
+- mention in README that the zlib format is now RFC1950
+- updated Makefile.dj2
+- added algorithm.doc
+
+Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion]
+- fix array overlay in deflate.c which sometimes caused bad compressed data
+- fix inflate bug with empty stored block
+- fix MSDOS medium model which was broken in 0.99
+- fix deflateParams() which could generated bad compressed data.
+- Bytef is define'd instead of typedef'ed (work around Borland bug)
+- added an INDEX file
+- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32),
+  Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas)
+- speed up adler32 for modern machines without auto-increment
+- added -ansi for IRIX in configure
+- static_init_done in trees.c is an int
+- define unlink as delete for VMS
+- fix configure for QNX
+- add configure branch for SCO and HPUX
+- avoid many warnings (unused variables, dead assignments, etc...)
+- no fdopen for BeOS
+- fix the Watcom fix for 32 bit mode (define FAR as empty)
+- removed redefinition of Byte for MKWERKS
+- work around an MWKERKS bug (incorrect merge of all .h files)
+
+Changes in 0.99 (27 Jan 96)
+- allow preset dictionary shared between compressor and decompressor
+- allow compression level 0 (no compression)
+- add deflateParams in zlib.h: allow dynamic change of compression level
+  and compression strategy.
+- test large buffers and deflateParams in example.c
+- add optional "configure" to build zlib as a shared library
+- suppress Makefile.qnx, use configure instead
+- fixed deflate for 64-bit systems (detected on Cray)
+- fixed inflate_blocks for 64-bit systems (detected on Alpha)
+- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2)
+- always return Z_BUF_ERROR when deflate() has nothing to do
+- deflateInit and inflateInit are now macros to allow version checking
+- prefix all global functions and types with z_ with -DZ_PREFIX
+- make falloc completely reentrant (inftrees.c)
+- fixed very unlikely race condition in ct_static_init
+- free in reverse order of allocation to help memory manager
+- use zlib-1.0/* instead of zlib/* inside the tar.gz
+- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith
+  -Wconversion -Wstrict-prototypes -Wmissing-prototypes"
+- allow gzread on concatenated .gz files
+- deflateEnd now returns Z_DATA_ERROR if it was premature
+- deflate is finally (?) fully deterministic (no matches beyond end of input)
+- Document Z_SYNC_FLUSH
+- add uninstall in Makefile
+- Check for __cpluplus in zlib.h
+- Better test in ct_align for partial flush
+- avoid harmless warnings for Borland C++
+- initialize hash_head in deflate.c
+- avoid warning on fdopen (gzio.c) for HP cc -Aa
+- include stdlib.h for STDC compilers
+- include errno.h for Cray
+- ignore error if ranlib doesn't exist
+- call ranlib twice for NeXTSTEP
+- use exec_prefix instead of prefix for libz.a
+- renamed ct_* as _tr_* to avoid conflict with applications
+- clear z->msg in inflateInit2 before any error return
+- initialize opaque in example.c, gzio.c, deflate.c and inflate.c
+- fixed typo in zconf.h (_GNUC__ => __GNUC__)
+- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode)
+- fix typo in Make_vms.com (f$trnlnm -> f$getsyi)
+- in fcalloc, normalize pointer if size > 65520 bytes
+- don't use special fcalloc for 32 bit Borland C++
+- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc...
+- use Z_BINARY instead of BINARY
+- document that gzclose after gzdopen will close the file
+- allow "a" as mode in gzopen.
+- fix error checking in gzread
+- allow skipping .gz extra-field on pipes
+- added reference to Perl interface in README
+- put the crc table in FAR data (I dislike more and more the medium model :)
+- added get_crc_table
+- added a dimension to all arrays (Borland C can't count).
+- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast
+- guard against multiple inclusion of *.h (for precompiled header on Mac)
+- Watcom C pretends to be Microsoft C small model even in 32 bit mode.
+- don't use unsized arrays to avoid silly warnings by Visual C++:
+     warning C4746: 'inflate_mask' : unsized array treated as  '__far'
+     (what's wrong with far data in far model?).
+- define enum out of inflate_blocks_state to allow compilation with C++
+
+Changes in 0.95 (16 Aug 95)
+- fix MSDOS small and medium model (now easier to adapt to any compiler)
+- inlined send_bits
+- fix the final (:-) bug for deflate with flush (output was correct but
+  not completely flushed in rare occasions).
+- default window size is same for compression and decompression
+  (it's now sufficient to set MAX_WBITS in zconf.h).
+- voidp -> voidpf and voidnp -> voidp (for consistency with other
+  typedefs and because voidnp was not near in large model).
+
+Changes in 0.94 (13 Aug 95)
+- support MSDOS medium model
+- fix deflate with flush (could sometimes generate bad output)
+- fix deflateReset (zlib header was incorrectly suppressed)
+- added support for VMS
+- allow a compression level in gzopen()
+- gzflush now calls fflush
+- For deflate with flush, flush even if no more input is provided.
+- rename libgz.a as libz.a
+- avoid complex expression in infcodes.c triggering Turbo C bug
+- work around a problem with gcc on Alpha (in INSERT_STRING)
+- don't use inline functions (problem with some gcc versions)
+- allow renaming of Byte, uInt, etc... with #define.
+- avoid warning about (unused) pointer before start of array in deflate.c
+- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c
+- avoid reserved word 'new' in trees.c
+
+Changes in 0.93 (25 June 95)
+- temporarily disable inline functions
+- make deflate deterministic
+- give enough lookahead for PARTIAL_FLUSH
+- Set binary mode for stdin/stdout in minigzip.c for OS/2
+- don't even use signed char in inflate (not portable enough)
+- fix inflate memory leak for segmented architectures
+
+Changes in 0.92 (3 May 95)
+- don't assume that char is signed (problem on SGI)
+- Clear bit buffer when starting a stored block
+- no memcpy on Pyramid
+- suppressed inftest.c
+- optimized fill_window, put longest_match inline for gcc
+- optimized inflate on stored blocks.
+- untabify all sources to simplify patches
+
+Changes in 0.91 (2 May 95)
+- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h
+- Document the memory requirements in zconf.h
+- added "make install"
+- fix sync search logic in inflateSync
+- deflate(Z_FULL_FLUSH) now works even if output buffer too short
+- after inflateSync, don't scare people with just "lo world"
+- added support for DJGPP
+
+Changes in 0.9 (1 May 95)
+- don't assume that zalloc clears the allocated memory (the TurboC bug
+  was Mark's bug after all :)
+- let again gzread copy uncompressed data unchanged (was working in 0.71)
+- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented
+- added a test of inflateSync in example.c
+- moved MAX_WBITS to zconf.h because users might want to change that.
+- document explicitly that zalloc(64K) on MSDOS must return a normalized
+  pointer (zero offset)
+- added Makefiles for Microsoft C, Turbo C, Borland C++
+- faster crc32()
+
+Changes in 0.8 (29 April 95)
+- added fast inflate (inffast.c)
+- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this
+  is incompatible with previous versions of zlib which returned Z_OK.
+- work around a TurboC compiler bug (bad code for b << 0, see infutil.h)
+  (actually that was not a compiler bug, see 0.81 above)
+- gzread no longer reads one extra byte in certain cases
+- In gzio destroy(), don't reference a freed structure
+- avoid many warnings for MSDOS
+- avoid the ERROR symbol which is used by MS Windows
+
+Changes in 0.71 (14 April 95)
+- Fixed more MSDOS compilation problems :( There is still a bug with
+  TurboC large model.
+
+Changes in 0.7 (14 April 95)
+- Added full inflate support.
+- Simplified the crc32() interface. The pre- and post-conditioning
+  (one's complement) is now done inside crc32(). WARNING: this is
+  incompatible with previous versions; see zlib.h for the new usage.
+
+Changes in 0.61 (12 April 95)
+- workaround for a bug in TurboC. example and minigzip now work on MSDOS.
+
+Changes in 0.6 (11 April 95)
+- added minigzip.c
+- added gzdopen to reopen a file descriptor as gzFile
+- added transparent reading of non-gziped files in gzread.
+- fixed bug in gzread (don't read crc as data)
+- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose).
+- don't allocate big arrays in the stack (for MSDOS)
+- fix some MSDOS compilation problems
+
+Changes in 0.5:
+- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but
+  not yet Z_FULL_FLUSH.
+- support decompression but only in a single step (forced Z_FINISH)
+- added opaque object for zalloc and zfree.
+- added deflateReset and inflateReset
+- added a variable zlib_version for consistency checking.
+- renamed the 'filter' parameter of deflateInit2 as 'strategy'.
+  Added Z_FILTERED and Z_HUFFMAN_ONLY constants.
+
+Changes in 0.4:
+- avoid "zip" everywhere, use zlib instead of ziplib.
+- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush
+  if compression method == 8.
+- added adler32 and crc32
+- renamed deflateOptions as deflateInit2, call one or the other but not both
+- added the method parameter for deflateInit2.
+- added inflateInit2
+- simplied considerably deflateInit and inflateInit by not supporting
+  user-provided history buffer. This is supported only in deflateInit2
+  and inflateInit2.
+
+Changes in 0.3:
+- prefix all macro names with Z_
+- use Z_FINISH instead of deflateEnd to finish compression.
+- added Z_HUFFMAN_ONLY
+- added gzerror()
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/FAQ b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/FAQ
new file mode 100644 (file)
index 0000000..99b7cf9
--- /dev/null
@@ -0,0 +1,368 @@
+
+                Frequently Asked Questions about zlib
+
+
+If your question is not there, please check the zlib home page
+http://zlib.net/ which may have more recent information.
+The lastest zlib FAQ is at http://zlib.net/zlib_faq.html
+
+
+ 1. Is zlib Y2K-compliant?
+
+    Yes. zlib doesn't handle dates.
+
+ 2. Where can I get a Windows DLL version?
+
+    The zlib sources can be compiled without change to produce a DLL.  See the
+    file win32/DLL_FAQ.txt in the zlib distribution.  Pointers to the
+    precompiled DLL are found in the zlib web site at http://zlib.net/ .
+
+ 3. Where can I get a Visual Basic interface to zlib?
+
+    See
+        * http://marknelson.us/1997/01/01/zlib-engine/
+        * win32/DLL_FAQ.txt in the zlib distribution
+
+ 4. compress() returns Z_BUF_ERROR.
+
+    Make sure that before the call of compress(), the length of the compressed
+    buffer is equal to the available size of the compressed buffer and not
+    zero.  For Visual Basic, check that this parameter is passed by reference
+    ("as any"), not by value ("as long").
+
+ 5. deflate() or inflate() returns Z_BUF_ERROR.
+
+    Before making the call, make sure that avail_in and avail_out are not zero.
+    When setting the parameter flush equal to Z_FINISH, also make sure that
+    avail_out is big enough to allow processing all pending input.  Note that a
+    Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be
+    made with more input or output space.  A Z_BUF_ERROR may in fact be
+    unavoidable depending on how the functions are used, since it is not
+    possible to tell whether or not there is more output pending when
+    strm.avail_out returns with zero.  See http://zlib.net/zlib_how.html for a
+    heavily annotated example.
+
+ 6. Where's the zlib documentation (man pages, etc.)?
+
+    It's in zlib.h .  Examples of zlib usage are in the files test/example.c
+    and test/minigzip.c, with more in examples/ .
+
+ 7. Why don't you use GNU autoconf or libtool or ...?
+
+    Because we would like to keep zlib as a very small and simple package.
+    zlib is rather portable and doesn't need much configuration.
+
+ 8. I found a bug in zlib.
+
+    Most of the time, such problems are due to an incorrect usage of zlib.
+    Please try to reproduce the problem with a small program and send the
+    corresponding source to us at zlib@gzip.org .  Do not send multi-megabyte
+    data files without prior agreement.
+
+ 9. Why do I get "undefined reference to gzputc"?
+
+    If "make test" produces something like
+
+       example.o(.text+0x154): undefined reference to `gzputc'
+
+    check that you don't have old files libz.* in /usr/lib, /usr/local/lib or
+    /usr/X11R6/lib. Remove any old versions, then do "make install".
+
+10. I need a Delphi interface to zlib.
+
+    See the contrib/delphi directory in the zlib distribution.
+
+11. Can zlib handle .zip archives?
+
+    Not by itself, no.  See the directory contrib/minizip in the zlib
+    distribution.
+
+12. Can zlib handle .Z files?
+
+    No, sorry.  You have to spawn an uncompress or gunzip subprocess, or adapt
+    the code of uncompress on your own.
+
+13. How can I make a Unix shared library?
+
+    By default a shared (and a static) library is built for Unix.  So:
+
+    make distclean
+    ./configure
+    make
+
+14. How do I install a shared zlib library on Unix?
+
+    After the above, then:
+
+    make install
+
+    However, many flavors of Unix come with a shared zlib already installed.
+    Before going to the trouble of compiling a shared version of zlib and
+    trying to install it, you may want to check if it's already there!  If you
+    can #include <zlib.h>, it's there.  The -lz option will probably link to
+    it.  You can check the version at the top of zlib.h or with the
+    ZLIB_VERSION symbol defined in zlib.h .
+
+15. I have a question about OttoPDF.
+
+    We are not the authors of OttoPDF. The real author is on the OttoPDF web
+    site: Joel Hainley, jhainley@myndkryme.com.
+
+16. Can zlib decode Flate data in an Adobe PDF file?
+
+    Yes. See http://www.pdflib.com/ . To modify PDF forms, see
+    http://sourceforge.net/projects/acroformtool/ .
+
+17. Why am I getting this "register_frame_info not found" error on Solaris?
+
+    After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib
+    generates an error such as:
+
+        ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so:
+        symbol __register_frame_info: referenced symbol not found
+
+    The symbol __register_frame_info is not part of zlib, it is generated by
+    the C compiler (cc or gcc).  You must recompile applications using zlib
+    which have this problem.  This problem is specific to Solaris.  See
+    http://www.sunfreeware.com for Solaris versions of zlib and applications
+    using zlib.
+
+18. Why does gzip give an error on a file I make with compress/deflate?
+
+    The compress and deflate functions produce data in the zlib format, which
+    is different and incompatible with the gzip format.  The gz* functions in
+    zlib on the other hand use the gzip format.  Both the zlib and gzip formats
+    use the same compressed data format internally, but have different headers
+    and trailers around the compressed data.
+
+19. Ok, so why are there two different formats?
+
+    The gzip format was designed to retain the directory information about a
+    single file, such as the name and last modification date.  The zlib format
+    on the other hand was designed for in-memory and communication channel
+    applications, and has a much more compact header and trailer and uses a
+    faster integrity check than gzip.
+
+20. Well that's nice, but how do I make a gzip file in memory?
+
+    You can request that deflate write the gzip format instead of the zlib
+    format using deflateInit2().  You can also request that inflate decode the
+    gzip format using inflateInit2().  Read zlib.h for more details.
+
+21. Is zlib thread-safe?
+
+    Yes.  However any library routines that zlib uses and any application-
+    provided memory allocation routines must also be thread-safe.  zlib's gz*
+    functions use stdio library routines, and most of zlib's functions use the
+    library memory allocation routines by default.  zlib's *Init* functions
+    allow for the application to provide custom memory allocation routines.
+
+    Of course, you should only operate on any given zlib or gzip stream from a
+    single thread at a time.
+
+22. Can I use zlib in my commercial application?
+
+    Yes.  Please read the license in zlib.h.
+
+23. Is zlib under the GNU license?
+
+    No.  Please read the license in zlib.h.
+
+24. The license says that altered source versions must be "plainly marked". So
+    what exactly do I need to do to meet that requirement?
+
+    You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h.  In
+    particular, the final version number needs to be changed to "f", and an
+    identification string should be appended to ZLIB_VERSION.  Version numbers
+    x.x.x.f are reserved for modifications to zlib by others than the zlib
+    maintainers.  For example, if the version of the base zlib you are altering
+    is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and
+    ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3".  You can also
+    update the version strings in deflate.c and inftrees.c.
+
+    For altered source distributions, you should also note the origin and
+    nature of the changes in zlib.h, as well as in ChangeLog and README, along
+    with the dates of the alterations.  The origin should include at least your
+    name (or your company's name), and an email address to contact for help or
+    issues with the library.
+
+    Note that distributing a compiled zlib library along with zlib.h and
+    zconf.h is also a source distribution, and so you should change
+    ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes
+    in zlib.h as you would for a full source distribution.
+
+25. Will zlib work on a big-endian or little-endian architecture, and can I
+    exchange compressed data between them?
+
+    Yes and yes.
+
+26. Will zlib work on a 64-bit machine?
+
+    Yes.  It has been tested on 64-bit machines, and has no dependence on any
+    data types being limited to 32-bits in length.  If you have any
+    difficulties, please provide a complete problem report to zlib@gzip.org
+
+27. Will zlib decompress data from the PKWare Data Compression Library?
+
+    No.  The PKWare DCL uses a completely different compressed data format than
+    does PKZIP and zlib.  However, you can look in zlib's contrib/blast
+    directory for a possible solution to your problem.
+
+28. Can I access data randomly in a compressed stream?
+
+    No, not without some preparation.  If when compressing you periodically use
+    Z_FULL_FLUSH, carefully write all the pending data at those points, and
+    keep an index of those locations, then you can start decompression at those
+    points.  You have to be careful to not use Z_FULL_FLUSH too often, since it
+    can significantly degrade compression.  Alternatively, you can scan a
+    deflate stream once to generate an index, and then use that index for
+    random access.  See examples/zran.c .
+
+29. Does zlib work on MVS, OS/390, CICS, etc.?
+
+    It has in the past, but we have not heard of any recent evidence.  There
+    were working ports of zlib 1.1.4 to MVS, but those links no longer work.
+    If you know of recent, successful applications of zlib on these operating
+    systems, please let us know.  Thanks.
+
+30. Is there some simpler, easier to read version of inflate I can look at to
+    understand the deflate format?
+
+    First off, you should read RFC 1951.  Second, yes.  Look in zlib's
+    contrib/puff directory.
+
+31. Does zlib infringe on any patents?
+
+    As far as we know, no.  In fact, that was originally the whole point behind
+    zlib.  Look here for some more information:
+
+    http://www.gzip.org/#faq11
+
+32. Can zlib work with greater than 4 GB of data?
+
+    Yes.  inflate() and deflate() will process any amount of data correctly.
+    Each call of inflate() or deflate() is limited to input and output chunks
+    of the maximum value that can be stored in the compiler's "unsigned int"
+    type, but there is no limit to the number of chunks.  Note however that the
+    strm.total_in and strm_total_out counters may be limited to 4 GB.  These
+    counters are provided as a convenience and are not used internally by
+    inflate() or deflate().  The application can easily set up its own counters
+    updated after each call of inflate() or deflate() to count beyond 4 GB.
+    compress() and uncompress() may be limited to 4 GB, since they operate in a
+    single call.  gzseek() and gztell() may be limited to 4 GB depending on how
+    zlib is compiled.  See the zlibCompileFlags() function in zlib.h.
+
+    The word "may" appears several times above since there is a 4 GB limit only
+    if the compiler's "long" type is 32 bits.  If the compiler's "long" type is
+    64 bits, then the limit is 16 exabytes.
+
+33. Does zlib have any security vulnerabilities?
+
+    The only one that we are aware of is potentially in gzprintf().  If zlib is
+    compiled to use sprintf() or vsprintf(), then there is no protection
+    against a buffer overflow of an 8K string space (or other value as set by
+    gzbuffer()), other than the caller of gzprintf() assuring that the output
+    will not exceed 8K.  On the other hand, if zlib is compiled to use
+    snprintf() or vsnprintf(), which should normally be the case, then there is
+    no vulnerability.  The ./configure script will display warnings if an
+    insecure variation of sprintf() will be used by gzprintf().  Also the
+    zlibCompileFlags() function will return information on what variant of
+    sprintf() is used by gzprintf().
+
+    If you don't have snprintf() or vsnprintf() and would like one, you can
+    find a portable implementation here:
+
+        http://www.ijs.si/software/snprintf/
+
+    Note that you should be using the most recent version of zlib.  Versions
+    1.1.3 and before were subject to a double-free vulnerability, and versions
+    1.2.1 and 1.2.2 were subject to an access exception when decompressing
+    invalid compressed data.
+
+34. Is there a Java version of zlib?
+
+    Probably what you want is to use zlib in Java. zlib is already included
+    as part of the Java SDK in the java.util.zip package. If you really want
+    a version of zlib written in the Java language, look on the zlib home
+    page for links: http://zlib.net/ .
+
+35. I get this or that compiler or source-code scanner warning when I crank it
+    up to maximally-pedantic. Can't you guys write proper code?
+
+    Many years ago, we gave up attempting to avoid warnings on every compiler
+    in the universe.  It just got to be a waste of time, and some compilers
+    were downright silly as well as contradicted each other.  So now, we simply
+    make sure that the code always works.
+
+36. Valgrind (or some similar memory access checker) says that deflate is
+    performing a conditional jump that depends on an uninitialized value.
+    Isn't that a bug?
+
+    No.  That is intentional for performance reasons, and the output of deflate
+    is not affected.  This only started showing up recently since zlib 1.2.x
+    uses malloc() by default for allocations, whereas earlier versions used
+    calloc(), which zeros out the allocated memory.  Even though the code was
+    correct, versions 1.2.4 and later was changed to not stimulate these
+    checkers.
+
+37. Will zlib read the (insert any ancient or arcane format here) compressed
+    data format?
+
+    Probably not. Look in the comp.compression FAQ for pointers to various
+    formats and associated software.
+
+38. How can I encrypt/decrypt zip files with zlib?
+
+    zlib doesn't support encryption.  The original PKZIP encryption is very
+    weak and can be broken with freely available programs.  To get strong
+    encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib
+    compression.  For PKZIP compatible "encryption", look at
+    http://www.info-zip.org/
+
+39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
+
+    "gzip" is the gzip format, and "deflate" is the zlib format.  They should
+    probably have called the second one "zlib" instead to avoid confusion with
+    the raw deflate compressed data format.  While the HTTP 1.1 RFC 2616
+    correctly points to the zlib specification in RFC 1950 for the "deflate"
+    transfer encoding, there have been reports of servers and browsers that
+    incorrectly produce or expect raw deflate data per the deflate
+    specification in RFC 1951, most notably Microsoft.  So even though the
+    "deflate" transfer encoding using the zlib format would be the more
+    efficient approach (and in fact exactly what the zlib format was designed
+    for), using the "gzip" transfer encoding is probably more reliable due to
+    an unfortunate choice of name on the part of the HTTP 1.1 authors.
+
+    Bottom line: use the gzip format for HTTP 1.1 encoding.
+
+40. Does zlib support the new "Deflate64" format introduced by PKWare?
+
+    No.  PKWare has apparently decided to keep that format proprietary, since
+    they have not documented it as they have previous compression formats.  In
+    any case, the compression improvements are so modest compared to other more
+    modern approaches, that it's not worth the effort to implement.
+
+41. I'm having a problem with the zip functions in zlib, can you help?
+
+    There are no zip functions in zlib.  You are probably using minizip by
+    Giles Vollant, which is found in the contrib directory of zlib.  It is not
+    part of zlib.  In fact none of the stuff in contrib is part of zlib.  The
+    files in there are not supported by the zlib authors.  You need to contact
+    the authors of the respective contribution for help.
+
+42. The match.asm code in contrib is under the GNU General Public License.
+    Since it's part of zlib, doesn't that mean that all of zlib falls under the
+    GNU GPL?
+
+    No.  The files in contrib are not part of zlib.  They were contributed by
+    other authors and are provided as a convenience to the user within the zlib
+    distribution.  Each item in contrib has its own license.
+
+43. Is zlib subject to export controls?  What is its ECCN?
+
+    zlib is not subject to export controls, and so is classified as EAR99.
+
+44. Can you please sign these lengthy legal documents and fax them back to us
+    so that we can use your software in our product?
+
+    No. Go away. Shoo.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/INDEX b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/INDEX
new file mode 100644 (file)
index 0000000..246f5f4
--- /dev/null
@@ -0,0 +1,67 @@
+CMakeLists.txt  cmake build file
+ChangeLog       history of changes
+FAQ             Frequently Asked Questions about zlib
+INDEX           this file
+Makefile        dummy Makefile that tells you to ./configure
+Makefile.in     template for Unix Makefile
+README          guess what
+configure       configure script for Unix
+make_vms.com    makefile for VMS
+test/example.c  zlib usages examples for build testing
+test/minigzip.c minimal gzip-like functionality for build testing
+test/infcover.c inf*.c code coverage for build coverage testing
+treebuild.xml   XML description of source file dependencies
+zconf.h.cmakein zconf.h template for cmake
+zconf.h.in      zconf.h template for configure
+zlib.3          Man page for zlib
+zlib.3.pdf      Man page in PDF format
+zlib.map        Linux symbol information
+zlib.pc.in      Template for pkg-config descriptor
+zlib2ansi       perl script to convert source files for C++ compilation
+
+amiga/          makefiles for Amiga SAS C
+as400/          makefiles for AS/400
+doc/            documentation for formats and algorithms
+msdos/          makefiles for MSDOS
+nintendods/     makefile for Nintendo DS
+old/            makefiles for various architectures and zlib documentation
+                files that have not yet been updated for zlib 1.2.x
+qnx/            makefiles for QNX
+watcom/         makefiles for OpenWatcom
+win32/          makefiles for Windows
+
+                zlib public header files (required for library use):
+zconf.h
+zlib.h
+
+                private source files used to build the zlib library:
+adler32.c
+compress.c
+crc32.c
+crc32.h
+deflate.c
+deflate.h
+gzclose.c
+gzguts.h
+gzlib.c
+gzread.c
+gzwrite.c
+infback.c
+inffast.c
+inffast.h
+inffixed.h
+inflate.c
+inflate.h
+inftrees.c
+inftrees.h
+trees.c
+trees.h
+uncompr.c
+zutil.c
+zutil.h
+
+                source files for sample programs
+See examples/README.examples
+
+                unsupported contributions by third parties
+See contrib/README.contrib
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/Makefile b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/Makefile
new file mode 100644 (file)
index 0000000..6bba86c
--- /dev/null
@@ -0,0 +1,5 @@
+all:
+       -@echo "Please use ./configure first.  Thank you."
+
+distclean:
+       make -f Makefile.in distclean
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/Makefile.in b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/Makefile.in
new file mode 100644 (file)
index 0000000..ea430bf
--- /dev/null
@@ -0,0 +1,285 @@
+# Makefile for zlib
+# Copyright (C) 1995-2011 Jean-loup Gailly.
+# For conditions of distribution and use, see copyright notice in zlib.h
+
+# To compile and test, type:
+#    ./configure; make test
+# Normally configure builds both a static and a shared library.
+# If you want to build just a static library, use: ./configure --static
+
+# To use the asm code, type:
+#    cp contrib/asm?86/match.S ./match.S
+#    make LOC=-DASMV OBJA=match.o
+
+# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
+#    make install
+# To install in $HOME instead of /usr/local, use:
+#    make install prefix=$HOME
+
+CC=cc
+
+CFLAGS=-O
+#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
+#CFLAGS=-g -DDEBUG
+#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
+#           -Wstrict-prototypes -Wmissing-prototypes
+
+SFLAGS=-O
+LDFLAGS=
+TEST_LDFLAGS=-L. libz.a
+LDSHARED=$(CC)
+CPP=$(CC) -E
+
+STATICLIB=libz.a
+SHAREDLIB=libz.so
+SHAREDLIBV=libz.so.1.2.6
+SHAREDLIBM=libz.so.1
+LIBS=$(STATICLIB) $(SHAREDLIBV)
+
+AR=ar
+ARFLAGS=rc
+RANLIB=ranlib
+LDCONFIG=ldconfig
+LDSHAREDLIBC=-lc
+TAR=tar
+SHELL=/bin/sh
+EXE=
+
+prefix = /usr/local
+exec_prefix = ${prefix}
+libdir = ${exec_prefix}/lib
+sharedlibdir = ${libdir}
+includedir = ${prefix}/include
+mandir = ${prefix}/share/man
+man3dir = ${mandir}/man3
+pkgconfigdir = ${libdir}/pkgconfig
+tempfile := $(shell mktemp -u __XXXXXX)
+
+OBJZ = adler32.o crc32.o deflate.o infback.o inffast.o inflate.o inftrees.o trees.o zutil.o
+OBJG = compress.o uncompr.o gzclose.o gzlib.o gzread.o gzwrite.o
+OBJC = $(OBJZ) $(OBJG)
+
+PIC_OBJZ = adler32.lo crc32.lo deflate.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo zutil.lo
+PIC_OBJG = compress.lo uncompr.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo
+PIC_OBJC = $(PIC_OBJZ) $(PIC_OBJG)
+
+# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo
+OBJA =
+PIC_OBJA =
+
+OBJS = $(OBJC) $(OBJA)
+
+PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA)
+
+all: static shared
+
+static: example$(EXE) minigzip$(EXE)
+
+shared: examplesh$(EXE) minigzipsh$(EXE)
+
+all64: example64$(EXE) minigzip64$(EXE)
+
+check: test
+
+test: all teststatic testshared
+
+teststatic: static
+       @if echo hello world | ./minigzip | ./minigzip -d && ./example; then \
+         echo '                *** zlib test OK ***'; \
+       else \
+         echo '                *** zlib test FAILED ***'; false; \
+       fi
+       -@rm -f foo.gz
+
+testshared: shared
+       @LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
+       LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \
+       DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \
+       SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \
+       if echo hello world | ./minigzipsh | ./minigzipsh -d && ./examplesh; then \
+         echo '                *** zlib shared test OK ***'; \
+       else \
+         echo '                *** zlib shared test FAILED ***'; false; \
+       fi
+       -@rm -f foo.gz
+
+test64: all64
+       @if echo hello world | ./minigzip64 | ./minigzip64 -d && ./example64; then \
+         echo '                *** zlib 64-bit test OK ***'; \
+       else \
+         echo '                *** zlib 64-bit test FAILED ***'; false; \
+       fi
+       -@rm -f foo.gz
+
+infcover.o: test/infcover.c zlib.h zconf.h
+       $(CC) $(CFLAGS) -I. -c -o $@ test/infcover.c
+
+infcover: infcover.o libz.a
+       $(CC) $(CFLAGS) -o $@ infcover.o libz.a
+
+cover: infcover
+       rm -f *.gcda
+       ./infcover
+       gcov inf*.c
+
+libz.a: $(OBJS)
+       $(AR) $(ARFLAGS) $@ $(OBJS)
+       -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
+
+match.o: match.S
+       $(CPP) match.S > _match.s
+       $(CC) -c _match.s
+       mv _match.o match.o
+       rm -f _match.s
+
+match.lo: match.S
+       $(CPP) match.S > _match.s
+       $(CC) -c -fPIC _match.s
+       mv _match.o match.lo
+       rm -f _match.s
+
+example.o: test/example.c zlib.h zconf.h
+       $(CC) $(CFLAGS) -I. -c -o $@ test/example.c
+
+minigzip.o: test/minigzip.c zlib.h zconf.h
+       $(CC) $(CFLAGS) -I. -c -o $@ test/minigzip.c
+
+example64.o: test/example.c zlib.h zconf.h
+       $(CC) $(CFLAGS) -I. -D_FILE_OFFSET_BITS=64 -c -o $@ test/example.c
+
+minigzip64.o: test/minigzip.c zlib.h zconf.h
+       $(CC) $(CFLAGS) -I. -D_FILE_OFFSET_BITS=64 -c -o $@ test/minigzip.c
+
+.SUFFIXES: .lo
+
+.c.lo:
+       -@mkdir objs 2>/dev/null || test -d objs
+       $(CC) $(SFLAGS) -DPIC -c -o objs/$*.o $<
+       -@mv objs/$*.o $@
+
+placebo $(SHAREDLIBV): $(PIC_OBJS) libz.a
+       $(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) $(LDSHAREDLIBC) $(LDFLAGS)
+       rm -f $(SHAREDLIB) $(SHAREDLIBM)
+       ln -s $@ $(SHAREDLIB)
+       ln -s $@ $(SHAREDLIBM)
+       -@rmdir objs
+
+example$(EXE): example.o $(STATICLIB)
+       $(CC) $(CFLAGS) -o $@ example.o $(TEST_LDFLAGS)
+
+minigzip$(EXE): minigzip.o $(STATICLIB)
+       $(CC) $(CFLAGS) -o $@ minigzip.o $(TEST_LDFLAGS)
+
+examplesh$(EXE): example.o $(SHAREDLIBV)
+       $(CC) $(CFLAGS) -o $@ example.o -L. $(SHAREDLIBV)
+
+minigzipsh$(EXE): minigzip.o $(SHAREDLIBV)
+       $(CC) $(CFLAGS) -o $@ minigzip.o -L. $(SHAREDLIBV)
+
+example64$(EXE): example64.o $(STATICLIB)
+       $(CC) $(CFLAGS) -o $@ example64.o $(TEST_LDFLAGS)
+
+minigzip64$(EXE): minigzip64.o $(STATICLIB)
+       $(CC) $(CFLAGS) -o $@ minigzip64.o $(TEST_LDFLAGS)
+
+install-libs: $(LIBS)
+       -@if [ ! -d $(DESTDIR)$(exec_prefix)  ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi
+       -@if [ ! -d $(DESTDIR)$(libdir)       ]; then mkdir -p $(DESTDIR)$(libdir); fi
+       -@if [ ! -d $(DESTDIR)$(sharedlibdir) ]; then mkdir -p $(DESTDIR)$(sharedlibdir); fi
+       -@if [ ! -d $(DESTDIR)$(man3dir)      ]; then mkdir -p $(DESTDIR)$(man3dir); fi
+       -@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi
+       cp $(STATICLIB) $(DESTDIR)$(libdir)
+       chmod 644 $(DESTDIR)$(libdir)/$(STATICLIB)
+       -@($(RANLIB) $(DESTDIR)$(libdir)/libz.a || true) >/dev/null 2>&1
+       -@if test -n "$(SHAREDLIBV)"; then \
+         cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir); \
+         echo "cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)"; \
+         chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \
+         echo "chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV)"; \
+         rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \
+         ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB); \
+         ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \
+         ($(LDCONFIG) || true)  >/dev/null 2>&1; \
+       fi
+       cp zlib.3 $(DESTDIR)$(man3dir)
+       chmod 644 $(DESTDIR)$(man3dir)/zlib.3
+       cp zlib.pc $(DESTDIR)$(pkgconfigdir)
+       chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc
+# The ranlib in install is needed on NeXTSTEP which checks file times
+# ldconfig is for Linux
+
+install: install-libs
+       -@if [ ! -d $(DESTDIR)$(includedir)   ]; then mkdir -p $(DESTDIR)$(includedir); fi
+       cp zlib.h zconf.h $(DESTDIR)$(includedir)
+       chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
+
+uninstall:
+       cd $(DESTDIR)$(includedir); rm -f zlib.h zconf.h
+       cd $(DESTDIR)$(libdir); rm -f libz.a; \
+       if test -n "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \
+         rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
+       fi
+       cd $(DESTDIR)$(man3dir); rm -f zlib.3
+       cd $(DESTDIR)$(pkgconfigdir); rm -f zlib.pc
+
+docs: zlib.3.pdf
+
+zlib.3.pdf: zlib.3
+       groff -mandoc -f H -T ps zlib.3 | ps2pdf - zlib.3.pdf
+
+zconf.h.cmakein: zconf.h.in
+       -@echo "/#define ZCONF_H/ a\\\\\n#cmakedefine Z_PREFIX\\\\\n#cmakedefine Z_HAVE_UNISTD_H\n" > $(tempfile)
+       -@sed -f $(tempfile) zconf.h.in > zconf.h.cmakein
+       -@touch -r zconf.h.in zconf.h.cmakein
+       -@rm $(tempfile)
+
+zconf: zconf.h.in
+       cp -p zconf.h.in zconf.h
+
+mostlyclean: clean
+clean:
+       rm -f *.o *.lo *~ \
+          example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \
+          example64$(EXE) minigzip64$(EXE) \
+          infcover \
+          libz.* foo.gz so_locations \
+          _match.s maketree contrib/infback9/*.o
+       rm -rf objs
+       rm -f *.gcda *.gcno *.gcov
+       rm -f contrib/infback9/*.gcda contrib/infback9/*.gcno contrib/infback9/*.gcov
+
+maintainer-clean: distclean
+distclean: clean zconf zconf.h.cmakein docs
+       rm -f Makefile zlib.pc configure.log
+       -@rm -f .DS_Store
+       -@printf 'all:\n\t-@echo "Please use ./configure first.  Thank you."\n' > Makefile
+       -@printf '\ndistclean:\n\tmake -f Makefile.in distclean\n' >> Makefile
+       -@touch -r Makefile.in Makefile
+
+tags:
+       etags *.[ch]
+
+depend:
+       makedepend -- $(CFLAGS) -- *.[ch]
+
+# DO NOT DELETE THIS LINE -- make depend depends on it.
+
+adler32.o zutil.o: zutil.h zlib.h zconf.h
+gzclose.o gzlib.o gzread.o gzwrite.o: zlib.h zconf.h gzguts.h
+compress.o example.o minigzip.o uncompr.o: zlib.h zconf.h
+crc32.o: zutil.h zlib.h zconf.h crc32.h
+deflate.o: deflate.h zutil.h zlib.h zconf.h
+infback.o inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffixed.h
+inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inftrees.o: zutil.h zlib.h zconf.h inftrees.h
+trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
+
+adler32.lo zutil.lo: zutil.h zlib.h zconf.h
+gzclose.lo gzlib.lo gzread.lo gzwrite.lo: zlib.h zconf.h gzguts.h
+compress.lo example.lo minigzip.lo uncompr.lo: zlib.h zconf.h
+crc32.lo: zutil.h zlib.h zconf.h crc32.h
+deflate.lo: deflate.h zutil.h zlib.h zconf.h
+infback.lo inflate.lo: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffixed.h
+inffast.lo: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inftrees.lo: zutil.h zlib.h zconf.h inftrees.h
+trees.lo: deflate.h zutil.h zlib.h zconf.h trees.h
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/README b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/README
new file mode 100644 (file)
index 0000000..09070e2
--- /dev/null
@@ -0,0 +1,115 @@
+ZLIB DATA COMPRESSION LIBRARY
+
+zlib 1.2.6 is a general purpose data compression library.  All the code is
+thread safe.  The data format used by the zlib library is described by RFCs
+(Request for Comments) 1950 to 1952 in the files
+http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and
+rfc1952 (gzip format).
+
+All functions of the compression library are documented in the file zlib.h
+(volunteer to write man pages welcome, contact zlib@gzip.org).  A usage example
+of the library is given in the file test/example.c which also tests that
+the library is working correctly.  Another example is given in the file
+test/minigzip.c.  The compression library itself is composed of all source
+files in the root directory.
+
+To compile all files and run the test program, follow the instructions given at
+the top of Makefile.in.  In short "./configure; make test", and if that goes
+well, "make install" should work for most flavors of Unix.  For Windows, use
+one of the special makefiles in win32/ or contrib/vstudio/ .  For VMS, use
+make_vms.com.
+
+Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
+<info@winimage.com> for the Windows DLL version.  The zlib home page is
+http://zlib.net/ .  Before reporting a problem, please check this site to
+verify that you have the latest version of zlib; otherwise get the latest
+version and check whether the problem still exists or not.
+
+PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
+
+Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan.  1997
+issue of Dr.  Dobb's Journal; a copy of the article is available at
+http://marknelson.us/1997/01/01/zlib-engine/ .
+
+The changes made in version 1.2.6 are documented in the file ChangeLog.
+
+Unsupported third party contributions are provided in directory contrib/ .
+
+zlib is available in Java using the java.util.zip package, documented at
+http://java.sun.com/developer/technicalArticles/Programming/compression/ .
+
+A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is available
+at CPAN (Comprehensive Perl Archive Network) sites, including
+http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .
+
+A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
+available in Python 1.5 and later versions, see
+http://docs.python.org/library/zlib.html .
+
+zlib is built into tcl: http://wiki.tcl.tk/4610 .
+
+An experimental package to read and write files in .zip format, written on top
+of zlib by Gilles Vollant <info@winimage.com>, is available in the
+contrib/minizip directory of zlib.
+
+
+Notes for some targets:
+
+- For Windows DLL versions, please see win32/DLL_FAQ.txt
+
+- For 64-bit Irix, deflate.c must be compiled without any optimization. With
+  -O, one libpng test fails. The test works in 32 bit mode (with the -n32
+  compiler flag). The compiler bug has been reported to SGI.
+
+- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
+  when compiled with cc.
+
+- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
+  necessary to get gzprintf working correctly. This is done by configure.
+
+- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
+  other compilers. Use "make test" to check your compiler.
+
+- gzdopen is not supported on RISCOS or BEOS.
+
+- For PalmOs, see http://palmzlib.sourceforge.net/
+
+
+Acknowledgments:
+
+  The deflate format used by zlib was defined by Phil Katz.  The deflate and
+  zlib specifications were written by L.  Peter Deutsch.  Thanks to all the
+  people who reported problems and suggested various improvements in zlib; they
+  are too numerous to cite here.
+
+Copyright notice:
+
+ (C) 1995-2012 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+If you use the zlib library in a product, we would appreciate *not* receiving
+lengthy legal documents to sign.  The sources are provided for free but without
+warranty of any kind.  The library has been entirely written by Jean-loup
+Gailly and Mark Adler; it does not include third-party code.
+
+If you redistribute modified sources, we would appreciate that you include in
+the file ChangeLog history information documenting your changes.  Please read
+the FAQ for more information on the distribution of modified source versions.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/adler32.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/adler32.c
new file mode 100644 (file)
index 0000000..a868f07
--- /dev/null
@@ -0,0 +1,179 @@
+/* adler32.c -- compute the Adler-32 checksum of a data stream
+ * Copyright (C) 1995-2011 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#include "zutil.h"
+
+#define local static
+
+local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));
+
+#define BASE 65521      /* largest prime smaller than 65536 */
+#define NMAX 5552
+/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
+
+#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}
+#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
+#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
+#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
+#define DO16(buf)   DO8(buf,0); DO8(buf,8);
+
+/* use NO_DIVIDE if your processor does not do division in hardware --
+   try it both ways to see which is faster */
+#ifdef NO_DIVIDE
+/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
+   (thank you to John Reiser for pointing this out) */
+#  define CHOP(a) \
+    do { \
+        unsigned long tmp = a >> 16; \
+        a &= 0xffffUL; \
+        a += (tmp << 4) - tmp; \
+    } while (0)
+#  define MOD28(a) \
+    do { \
+        CHOP(a); \
+        if (a >= BASE) a -= BASE; \
+    } while (0)
+#  define MOD(a) \
+    do { \
+        CHOP(a); \
+        MOD28(a); \
+    } while (0)
+#  define MOD63(a) \
+    do { /* this assumes a is not negative */ \
+        z_off64_t tmp = a >> 32; \
+        a &= 0xffffffffL; \
+        a += (tmp << 8) - (tmp << 5) + tmp; \
+        tmp = a >> 16; \
+        a &= 0xffffL; \
+        a += (tmp << 4) - tmp; \
+        tmp = a >> 16; \
+        a &= 0xffffL; \
+        a += (tmp << 4) - tmp; \
+        if (a >= BASE) a -= BASE; \
+    } while (0)
+#else
+#  define MOD(a) a %= BASE
+#  define MOD28(a) a %= BASE
+#  define MOD63(a) a %= BASE
+#endif
+
+/* ========================================================================= */
+uLong ZEXPORT adler32(adler, buf, len)
+    uLong adler;
+    const Bytef *buf;
+    uInt len;
+{
+    unsigned long sum2;
+    unsigned n;
+
+    /* split Adler-32 into component sums */
+    sum2 = (adler >> 16) & 0xffff;
+    adler &= 0xffff;
+
+    /* in case user likes doing a byte at a time, keep it fast */
+    if (len == 1) {
+        adler += buf[0];
+        if (adler >= BASE)
+            adler -= BASE;
+        sum2 += adler;
+        if (sum2 >= BASE)
+            sum2 -= BASE;
+        return adler | (sum2 << 16);
+    }
+
+    /* initial Adler-32 value (deferred check for len == 1 speed) */
+    if (buf == Z_NULL)
+        return 1L;
+
+    /* in case short lengths are provided, keep it somewhat fast */
+    if (len < 16) {
+        while (len--) {
+            adler += *buf++;
+            sum2 += adler;
+        }
+        if (adler >= BASE)
+            adler -= BASE;
+        MOD28(sum2);            /* only added so many BASE's */
+        return adler | (sum2 << 16);
+    }
+
+    /* do length NMAX blocks -- requires just one modulo operation */
+    while (len >= NMAX) {
+        len -= NMAX;
+        n = NMAX / 16;          /* NMAX is divisible by 16 */
+        do {
+            DO16(buf);          /* 16 sums unrolled */
+            buf += 16;
+        } while (--n);
+        MOD(adler);
+        MOD(sum2);
+    }
+
+    /* do remaining bytes (less than NMAX, still just one modulo) */
+    if (len) {                  /* avoid modulos if none remaining */
+        while (len >= 16) {
+            len -= 16;
+            DO16(buf);
+            buf += 16;
+        }
+        while (len--) {
+            adler += *buf++;
+            sum2 += adler;
+        }
+        MOD(adler);
+        MOD(sum2);
+    }
+
+    /* return recombined sums */
+    return adler | (sum2 << 16);
+}
+
+/* ========================================================================= */
+local uLong adler32_combine_(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off64_t len2;
+{
+    unsigned long sum1;
+    unsigned long sum2;
+    unsigned rem;
+
+    /* for negative len, return invalid adler32 as a clue for debugging */
+    if (len2 < 0)
+        return 0xffffffffUL;
+
+    /* the derivation of this formula is left as an exercise for the reader */
+    MOD63(len2);                /* assumes len2 >= 0 */
+    rem = (unsigned)len2;
+    sum1 = adler1 & 0xffff;
+    sum2 = rem * sum1;
+    MOD(sum2);
+    sum1 += (adler2 & 0xffff) + BASE - 1;
+    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
+    if (sum1 >= BASE) sum1 -= BASE;
+    if (sum1 >= BASE) sum1 -= BASE;
+    if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
+    if (sum2 >= BASE) sum2 -= BASE;
+    return sum1 | (sum2 << 16);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_combine(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
+
+uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off64_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/amiga/Makefile.pup b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/amiga/Makefile.pup
new file mode 100644 (file)
index 0000000..8940c12
--- /dev/null
@@ -0,0 +1,69 @@
+# Amiga powerUP (TM) Makefile
+# makefile for libpng and SAS C V6.58/7.00 PPC compiler
+# Copyright (C) 1998 by Andreas R. Kleinert
+
+LIBNAME        = libzip.a
+
+CC     = scppc
+CFLAGS = NOSTKCHK NOSINT OPTIMIZE OPTGO OPTPEEP OPTINLOCAL OPTINL \
+         OPTLOOP OPTRDEP=8 OPTDEP=8 OPTCOMP=8 NOVER
+AR     = ppc-amigaos-ar cr
+RANLIB = ppc-amigaos-ranlib
+LD     = ppc-amigaos-ld -r
+LDFLAGS        = -o
+LDLIBS = LIB:scppc.a LIB:end.o
+RM     = delete quiet
+
+OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \
+       uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o
+
+TEST_OBJS = example.o minigzip.o
+
+all: example minigzip
+
+check: test
+test: all
+       example
+       echo hello world | minigzip | minigzip -d
+
+$(LIBNAME): $(OBJS)
+       $(AR) $@ $(OBJS)
+       -$(RANLIB) $@
+
+example: example.o $(LIBNAME)
+       $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS)
+
+minigzip: minigzip.o $(LIBNAME)
+       $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS)
+
+mostlyclean: clean
+clean:
+       $(RM) *.o example minigzip $(LIBNAME) foo.gz
+
+zip:
+       zip -ul9 zlib README ChangeLog Makefile Make????.??? Makefile.?? \
+         descrip.mms *.[ch]
+
+tgz:
+       cd ..; tar cfz zlib/zlib.tgz zlib/README zlib/ChangeLog zlib/Makefile \
+         zlib/Make????.??? zlib/Makefile.?? zlib/descrip.mms zlib/*.[ch]
+
+# DO NOT DELETE THIS LINE -- make depend depends on it.
+
+adler32.o: zlib.h zconf.h
+compress.o: zlib.h zconf.h
+crc32.o: crc32.h zlib.h zconf.h
+deflate.o: deflate.h zutil.h zlib.h zconf.h
+example.o: zlib.h zconf.h
+gzclose.o: zlib.h zconf.h gzguts.h
+gzlib.o: zlib.h zconf.h gzguts.h
+gzread.o: zlib.h zconf.h gzguts.h
+gzwrite.o: zlib.h zconf.h gzguts.h
+inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inftrees.o: zutil.h zlib.h zconf.h inftrees.h
+minigzip.o: zlib.h zconf.h
+trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
+uncompr.o: zlib.h zconf.h
+zutil.o: zutil.h zlib.h zconf.h
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/amiga/Makefile.sas b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/amiga/Makefile.sas
new file mode 100644 (file)
index 0000000..749e291
--- /dev/null
@@ -0,0 +1,68 @@
+# SMakefile for zlib
+# Modified from the standard UNIX Makefile Copyright Jean-loup Gailly
+# Osma Ahvenlampi <Osma.Ahvenlampi@hut.fi>
+# Amiga, SAS/C 6.56 & Smake
+
+CC=sc
+CFLAGS=OPT
+#CFLAGS=OPT CPU=68030
+#CFLAGS=DEBUG=LINE
+LDFLAGS=LIB z.lib
+
+SCOPTIONS=OPTSCHED OPTINLINE OPTALIAS OPTTIME OPTINLOCAL STRMERGE \
+       NOICONS PARMS=BOTH NOSTACKCHECK UTILLIB NOVERSION ERRORREXX \
+       DEF=POSTINC
+
+OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \
+       uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o
+
+TEST_OBJS = example.o minigzip.o
+
+all: SCOPTIONS example minigzip
+
+check: test
+test: all
+       example
+       echo hello world | minigzip | minigzip -d
+
+install: z.lib
+       copy clone zlib.h zconf.h INCLUDE:
+       copy clone z.lib LIB:
+
+z.lib: $(OBJS)
+       oml z.lib r $(OBJS)
+
+example: example.o z.lib
+       $(CC) $(CFLAGS) LINK TO $@ example.o $(LDFLAGS)
+
+minigzip: minigzip.o z.lib
+       $(CC) $(CFLAGS) LINK TO $@ minigzip.o $(LDFLAGS)
+
+mostlyclean: clean
+clean:
+       -delete force quiet example minigzip *.o z.lib foo.gz *.lnk SCOPTIONS
+
+SCOPTIONS: Makefile.sas
+       copy to $@ <from <
+$(SCOPTIONS)
+<
+
+# DO NOT DELETE THIS LINE -- make depend depends on it.
+
+adler32.o: zlib.h zconf.h
+compress.o: zlib.h zconf.h
+crc32.o: crc32.h zlib.h zconf.h
+deflate.o: deflate.h zutil.h zlib.h zconf.h
+example.o: zlib.h zconf.h
+gzclose.o: zlib.h zconf.h gzguts.h
+gzlib.o: zlib.h zconf.h gzguts.h
+gzread.o: zlib.h zconf.h gzguts.h
+gzwrite.o: zlib.h zconf.h gzguts.h
+inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inftrees.o: zutil.h zlib.h zconf.h inftrees.h
+minigzip.o: zlib.h zconf.h
+trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
+uncompr.o: zlib.h zconf.h
+zutil.o: zutil.h zlib.h zconf.h
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/bndsrc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/bndsrc
new file mode 100644 (file)
index 0000000..d048dbb
--- /dev/null
@@ -0,0 +1,206 @@
+STRPGMEXP PGMLVL(*CURRENT) SIGNATURE('ZLIB')
+
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+/*   Version 1.1.3 entry points.                                    */
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+
+/********************************************************************/
+/*   *MODULE      ADLER32      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("adler32")
+
+/********************************************************************/
+/*   *MODULE      COMPRESS     ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("compress")
+  EXPORT SYMBOL("compress2")
+
+/********************************************************************/
+/*   *MODULE      CRC32        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("crc32")
+  EXPORT SYMBOL("get_crc_table")
+
+/********************************************************************/
+/*   *MODULE      DEFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("deflate")
+  EXPORT SYMBOL("deflateEnd")
+  EXPORT SYMBOL("deflateSetDictionary")
+  EXPORT SYMBOL("deflateCopy")
+  EXPORT SYMBOL("deflateReset")
+  EXPORT SYMBOL("deflateParams")
+  EXPORT SYMBOL("deflatePrime")
+  EXPORT SYMBOL("deflateInit_")
+  EXPORT SYMBOL("deflateInit2_")
+
+/********************************************************************/
+/*   *MODULE      GZIO         ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzopen")
+  EXPORT SYMBOL("gzdopen")
+  EXPORT SYMBOL("gzsetparams")
+  EXPORT SYMBOL("gzread")
+  EXPORT SYMBOL("gzwrite")
+  EXPORT SYMBOL("gzprintf")
+  EXPORT SYMBOL("gzputs")
+  EXPORT SYMBOL("gzgets")
+  EXPORT SYMBOL("gzputc")
+  EXPORT SYMBOL("gzgetc")
+  EXPORT SYMBOL("gzflush")
+  EXPORT SYMBOL("gzseek")
+  EXPORT SYMBOL("gzrewind")
+  EXPORT SYMBOL("gztell")
+  EXPORT SYMBOL("gzeof")
+  EXPORT SYMBOL("gzclose")
+  EXPORT SYMBOL("gzerror")
+
+/********************************************************************/
+/*   *MODULE      INFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflate")
+  EXPORT SYMBOL("inflateEnd")
+  EXPORT SYMBOL("inflateSetDictionary")
+  EXPORT SYMBOL("inflateSync")
+  EXPORT SYMBOL("inflateReset")
+  EXPORT SYMBOL("inflateInit_")
+  EXPORT SYMBOL("inflateInit2_")
+  EXPORT SYMBOL("inflateSyncPoint")
+
+/********************************************************************/
+/*   *MODULE      UNCOMPR      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("uncompress")
+
+/********************************************************************/
+/*   *MODULE      ZUTIL        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("zlibVersion")
+  EXPORT SYMBOL("zError")
+
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+/*   Version 1.2.1 additional entry points.                         */
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+
+/********************************************************************/
+/*   *MODULE      COMPRESS     ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("compressBound")
+
+/********************************************************************/
+/*   *MODULE      DEFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("deflateBound")
+
+/********************************************************************/
+/*   *MODULE      GZIO         ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzungetc")
+  EXPORT SYMBOL("gzclearerr")
+
+/********************************************************************/
+/*   *MODULE      INFBACK      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflateBack")
+  EXPORT SYMBOL("inflateBackEnd")
+  EXPORT SYMBOL("inflateBackInit_")
+
+/********************************************************************/
+/*   *MODULE      INFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflateCopy")
+
+/********************************************************************/
+/*   *MODULE      ZUTIL        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("zlibCompileFlags")
+
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+/*   Version 1.2.5 additional entry points.                         */
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+
+/********************************************************************/
+/*   *MODULE      ADLER32      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("adler32_combine")
+  EXPORT SYMBOL("adler32_combine64")
+
+/********************************************************************/
+/*   *MODULE      CRC32        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("crc32_combine")
+  EXPORT SYMBOL("crc32_combine64")
+
+/********************************************************************/
+/*   *MODULE      GZLIB        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzbuffer")
+  EXPORT SYMBOL("gzoffset")
+  EXPORT SYMBOL("gzoffset64")
+  EXPORT SYMBOL("gzopen64")
+  EXPORT SYMBOL("gzseek64")
+  EXPORT SYMBOL("gztell64")
+
+/********************************************************************/
+/*   *MODULE      GZREAD       ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzclose_r")
+
+/********************************************************************/
+/*   *MODULE      GZWRITE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzclose_w")
+
+/********************************************************************/
+/*   *MODULE      INFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflateMark")
+  EXPORT SYMBOL("inflatePrime")
+  EXPORT SYMBOL("inflateReset2")
+  EXPORT SYMBOL("inflateUndermine")
+
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+/*   Version 1.2.6 additional entry points.                         */
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+
+/********************************************************************/
+/*   *MODULE      DEFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("deflateResetKeep")
+  EXPORT SYMBOL("deflatePending")
+
+/********************************************************************/
+/*   *MODULE      GZWRITE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzgetc_")
+  EXPORT SYMBOL("gzflags")
+
+/********************************************************************/
+/*   *MODULE      INFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflateResetKeep")
+
+ENDPGMEXP
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/compile.clp b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/compile.clp
new file mode 100644 (file)
index 0000000..ed96ad4
--- /dev/null
@@ -0,0 +1,110 @@
+/******************************************************************************/
+/*                                                                            */
+/*  ZLIB                                                                      */
+/*                                                                            */
+/*    Compile sources into modules and link them into a service program.      */
+/*                                                                            */
+/******************************************************************************/
+
+             PGM
+
+/*      Configuration adjustable parameters.                                  */
+
+             DCL        VAR(&SRCLIB) TYPE(*CHAR) LEN(10) +
+                          VALUE('ZLIB')                         /* Source library. */
+             DCL        VAR(&SRCFILE) TYPE(*CHAR) LEN(10) +
+                          VALUE('SOURCES')                      /* Source member file. */
+             DCL        VAR(&CTLFILE) TYPE(*CHAR) LEN(10) +
+                          VALUE('TOOLS')                        /* Control member file. */
+
+             DCL        VAR(&MODLIB) TYPE(*CHAR) LEN(10) +
+                          VALUE('ZLIB')                         /* Module library. */
+
+             DCL        VAR(&SRVLIB) TYPE(*CHAR) LEN(10) +
+                          VALUE('LGPL')                         /* Service program library. */
+
+             DCL        VAR(&CFLAGS) TYPE(*CHAR) +
+                          VALUE('OPTIMIZE(40)')                 /* Compile options. */
+
+             DCL        VAR(&TGTRLS) TYPE(*CHAR) +
+                          VALUE('V5R3M0')                       /* Target release. */
+
+
+/*      Working storage.                                                      */
+
+             DCL        VAR(&CMDLEN) TYPE(*DEC) LEN(15 5) VALUE(300)    /* Command length. */
+             DCL        VAR(&CMD) TYPE(*CHAR) LEN(512)
+             DCL        VAR(&FIXDCMD) TYPE(*CHAR) LEN(512)
+
+
+/*      Compile sources into modules.                                         */
+
+             CHGVAR     VAR(&FIXDCMD) VALUE('CRTCMOD' *BCAT &CFLAGS *BCAT      +
+                        'SYSIFCOPT(*IFS64IO)' *BCAT                            +
+                        'DEFINE(''_LARGEFILE64_SOURCE''' *BCAT                 +
+                        '''_LFS64_LARGEFILE=1'') TGTRLS(' *TCAT &TGTRLS *TCAT  +
+                        ') SRCFILE(' *TCAT &SRCLIB *TCAT '/' *TCAT             +
+                        &SRCFILE *TCAT ') MODULE(' *TCAT &MODLIB *TCAT '/')
+
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'ADLER32)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'COMPRESS)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'CRC32)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'DEFLATE)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'GZCLOSE)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'GZLIB)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'GZREAD)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'GZWRITE)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'INFBACK)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'INFFAST)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'INFLATE)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'INFTREES)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'TREES)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'UNCOMPR)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'ZUTIL)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+
+/*      Link modules into a service program.                                  */
+
+             CRTSRVPGM  SRVPGM(&SRVLIB/ZLIB) +
+                          MODULE(&MODLIB/ADLER32     &MODLIB/COMPRESS    +
+                                 &MODLIB/CRC32       &MODLIB/DEFLATE     +
+                                 &MODLIB/GZCLOSE     &MODLIB/GZLIB       +
+                                 &MODLIB/GZREAD      &MODLIB/GZWRITE     +
+                                 &MODLIB/INFBACK     &MODLIB/INFFAST     +
+                                 &MODLIB/INFLATE     &MODLIB/INFTREES    +
+                                 &MODLIB/TREES       &MODLIB/UNCOMPR     +
+                                 &MODLIB/ZUTIL)                          +
+                          SRCFILE(&SRCLIB/&CTLFILE) SRCMBR(BNDSRC)       +
+                          TEXT('ZLIB 1.2.6') TGTRLS(&TGTRLS)
+
+             ENDPGM
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/readme.txt
new file mode 100644 (file)
index 0000000..397fe99
--- /dev/null
@@ -0,0 +1,115 @@
+        ZLIB version 1.2.6 for AS400 installation instructions
+
+I) From an AS400 *SAVF file:
+
+1)      Unpacking archive to an AS400 save file
+
+On the AS400:
+
+_       Create the ZLIB AS400 library:
+
+        CRTLIB LIB(ZLIB) TYPE(*PROD) TEXT('ZLIB compression API library')
+
+_       Create a work save file, for example:
+
+                CRTSAVF FILE(ZLIB/ZLIBSAVF)
+
+On a PC connected to the target AS400:
+
+_       Unpack the save file image to a PC file "ZLIBSAVF"
+_       Upload this file into the save file on the AS400, for example
+                using ftp in BINARY mode.
+
+
+2)      Populating the ZLIB AS400 source library
+
+On the AS400:
+
+_       Extract the saved objects into the ZLIB AS400 library using:
+
+RSTOBJ OBJ(*ALL) SAVLIB(ZLIB) DEV(*SAVF) SAVF(ZLIB/ZLIBSAVF) RSTLIB(ZLIB)
+
+
+3)      Customize installation:
+
+_       Edit CL member ZLIB/TOOLS(COMPILE) and change parameters if needed,
+                according to the comments.
+
+_       Compile this member with:
+
+        CRTCLPGM PGM(ZLIB/COMPILE) SRCFILE(ZLIB/TOOLS) SRCMBR(COMPILE)
+
+
+4)      Compile and generate the service program:
+
+_       This can now be done by executing:
+
+        CALL PGM(ZLIB/COMPILE)
+
+
+
+II) From the original source distribution:
+
+1)      On the AS400, create the source library:
+
+        CRTLIB LIB(ZLIB) TYPE(*PROD) TEXT('ZLIB compression API library')
+
+2)      Create the source files:
+
+        CRTSRCPF FILE(ZLIB/SOURCES) RCDLEN(112) TEXT('ZLIB library modules')
+        CRTSRCPF FILE(ZLIB/H)       RCDLEN(112) TEXT('ZLIB library includes')
+        CRTSRCPF FILE(ZLIB/TOOLS)   RCDLEN(112) TEXT('ZLIB library control utilities')
+
+3)      From the machine hosting the distribution files, upload them (with
+                FTP in text mode, for example) according to the following table:
+
+    Original    AS400   AS400    AS400 AS400
+    file        file    member   type  description
+                SOURCES                Original ZLIB C subprogram sources
+    adler32.c           ADLER32  C     ZLIB - Compute the Adler-32 checksum of a dta strm
+    compress.c          COMPRESS C     ZLIB - Compress a memory buffer
+    crc32.c             CRC32    C     ZLIB - Compute the CRC-32 of a data stream
+    deflate.c           DEFLATE  C     ZLIB - Compress data using the deflation algorithm
+    gzclose.c           GZCLOSE  C     ZLIB - Close .gz files
+    gzlib.c             GZLIB    C     ZLIB - Miscellaneous .gz files IO support
+    gzread.c            GZREAD   C     ZLIB - Read .gz files
+    gzwrite.c           GZWRITE  C     ZLIB - Write .gz files
+    infback.c           INFBACK  C     ZLIB - Inflate using a callback interface
+    inffast.c           INFFAST  C     ZLIB - Fast proc. literals & length/distance pairs
+    inflate.c           INFLATE  C     ZLIB - Interface to inflate modules
+    inftrees.c          INFTREES C     ZLIB - Generate Huffman trees for efficient decode
+    trees.c             TREES    C     ZLIB - Output deflated data using Huffman coding
+    uncompr.c           UNCOMPR  C     ZLIB - Decompress a memory buffer
+    zutil.c             ZUTIL    C     ZLIB - Target dependent utility functions
+                H                      Original ZLIB C and ILE/RPG include files
+    crc32.h             CRC32    C     ZLIB - CRC32 tables
+    deflate.h           DEFLATE  C     ZLIB - Internal compression state
+    gzguts.h            GZGUTS   C     ZLIB - Definitions for the gzclose module
+    inffast.h           INFFAST  C     ZLIB - Header to use inffast.c
+    inffixed.h          INFFIXED C     ZLIB - Table for decoding fixed codes
+    inflate.h           INFLATE  C     ZLIB - Internal inflate state definitions
+    inftrees.h          INFTREES C     ZLIB - Header to use inftrees.c
+    trees.h             TREES    C     ZLIB - Created automatically with -DGEN_TREES_H
+    zconf.h             ZCONF    C     ZLIB - Compression library configuration
+    zlib.h              ZLIB     C     ZLIB - Compression library C user interface
+    as400/zlib.inc      ZLIB.INC RPGLE ZLIB - Compression library ILE RPG user interface
+    zutil.h             ZUTIL    C     ZLIB - Internal interface and configuration
+                TOOLS                  Building source software & AS/400 README
+    as400/bndsrc        BNDSRC         Entry point exportation list
+    as400/compile.clp   COMPILE  CLP   Compile sources & generate service program
+    as400/readme.txt    README   TXT   Installation instructions
+
+4)      Continue as in I)3).
+
+
+
+
+Notes:  For AS400 ILE RPG programmers, a /copy member defining the ZLIB
+                API prototypes for ILE RPG can be found in ZLIB/H(ZLIB.INC).
+                Please read comments in this member for more information.
+
+        Remember that most foreign textual data are ASCII coded: this
+                implementation does not handle conversion from/to ASCII, so
+                text data code conversions must be done explicitely.
+
+        Mainly for the reason above, always open zipped files in binary mode.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/zlib.inc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/as400/zlib.inc
new file mode 100644 (file)
index 0000000..5ce905f
--- /dev/null
@@ -0,0 +1,447 @@
+      *  ZLIB.INC - Interface to the general purpose compression library
+      *
+      *  ILE RPG400 version by Patrick Monnerat, DATASPHERE.
+      *  Version 1.2.6
+      *
+      *
+      *  WARNING:
+      *     Procedures inflateInit(), inflateInit2(), deflateInit(),
+      *         deflateInit2() and inflateBackInit() need to be called with
+      *         two additional arguments:
+      *         the package version string and the stream control structure.
+      *         size. This is needed because RPG lacks some macro feature.
+      *         Call these procedures as:
+      *             inflateInit(...: ZLIB_VERSION: %size(z_stream))
+      *
+      /if not defined(ZLIB_H_)
+      /define ZLIB_H_
+      *
+      **************************************************************************
+      *                               Constants
+      **************************************************************************
+      *
+      *  Versioning information.
+      *
+     D ZLIB_VERSION    C                   '1.2.6'
+     D ZLIB_VERNUM     C                   X'1260'
+     D ZLIB_VER_MAJOR  C                   1
+     D ZLIB_VER_MINOR  C                   2
+     D ZLIB_VER_REVISION...
+     D                 C                   6
+     D ZLIB_VER_SUBREVISION...
+     D                 C                   0
+      *
+      *  Other equates.
+      *
+     D Z_NO_FLUSH      C                   0
+     D Z_PARTIAL_FLUSH...
+     D                 C                   1
+     D Z_SYNC_FLUSH    C                   2
+     D Z_FULL_FLUSH    C                   3
+     D Z_FINISH        C                   4
+     D Z_BLOCK         C                   5
+     D Z_TREES         C                   6
+      *
+     D Z_OK            C                   0
+     D Z_STREAM_END    C                   1
+     D Z_NEED_DICT     C                   2
+     D Z_ERRNO         C                   -1
+     D Z_STREAM_ERROR  C                   -2
+     D Z_DATA_ERROR    C                   -3
+     D Z_MEM_ERROR     C                   -4
+     D Z_BUF_ERROR     C                   -5
+     DZ_VERSION_ERROR  C                   -6
+      *
+     D Z_NO_COMPRESSION...
+     D                 C                   0
+     D Z_BEST_SPEED    C                   1
+     D Z_BEST_COMPRESSION...
+     D                 C                   9
+     D Z_DEFAULT_COMPRESSION...
+     D                 C                   -1
+      *
+     D Z_FILTERED      C                   1
+     D Z_HUFFMAN_ONLY  C                   2
+     D Z_RLE           C                   3
+     D Z_DEFAULT_STRATEGY...
+     D                 C                   0
+      *
+     D Z_BINARY        C                   0
+     D Z_ASCII         C                   1
+     D Z_UNKNOWN       C                   2
+      *
+     D Z_DEFLATED      C                   8
+      *
+     D Z_NULL          C                   0
+      *
+      **************************************************************************
+      *                                 Types
+      **************************************************************************
+      *
+     D z_streamp       S               *                                        Stream struct ptr
+     D gzFile          S               *                                        File pointer
+     D z_off_t         S             10i 0                                      Stream offsets
+     D z_off64_t       S             20i 0                                      Stream offsets
+      *
+      **************************************************************************
+      *                               Structures
+      **************************************************************************
+      *
+      *  The GZIP encode/decode stream support structure.
+      *
+     D z_stream        DS                  align based(z_streamp)
+     D  zs_next_in                     *                                        Next input byte
+     D  zs_avail_in                  10U 0                                      Byte cnt at next_in
+     D  zs_total_in                  10U 0                                      Total bytes read
+     D  zs_next_out                    *                                        Output buffer ptr
+     D  zs_avail_out                 10U 0                                      Room left @ next_out
+     D  zs_total_out                 10U 0                                      Total bytes written
+     D  zs_msg                         *                                        Last errmsg or null
+     D  zs_state                       *                                        Internal state
+     D  zs_zalloc                      *   procptr                              Int. state allocator
+     D  zs_free                        *   procptr                              Int. state dealloc.
+     D  zs_opaque                      *                                        Private alloc. data
+     D  zs_data_type                 10i 0                                      ASC/BIN best guess
+     D  zs_adler                     10u 0                                      Uncompr. adler32 val
+     D                               10U 0                                      Reserved
+     D                               10U 0                                      Ptr. alignment
+      *
+      **************************************************************************
+      *                     Utility function prototypes
+      **************************************************************************
+      *
+     D compress        PR            10I 0 extproc('compress')
+     D  dest                      65535    options(*varsize)                    Destination buffer
+     D  destLen                      10U 0                                      Destination length
+     D  source                    65535    const options(*varsize)              Source buffer
+     D  sourceLen                    10u 0 value                                Source length
+      *
+     D compress2       PR            10I 0 extproc('compress2')
+     D  dest                      65535    options(*varsize)                    Destination buffer
+     D  destLen                      10U 0                                      Destination length
+     D  source                    65535    const options(*varsize)              Source buffer
+     D  sourceLen                    10U 0 value                                Source length
+     D  level                        10I 0 value                                Compression level
+      *
+     D compressBound   PR            10U 0 extproc('compressBound')
+     D  sourceLen                    10U 0 value
+      *
+     D uncompress      PR            10I 0 extproc('uncompress')
+     D  dest                      65535    options(*varsize)                    Destination buffer
+     D  destLen                      10U 0                                      Destination length
+     D  source                    65535    const options(*varsize)              Source buffer
+     D  sourceLen                    10U 0 value                                Source length
+      *
+      /if not defined(LARGE_FILES)
+     D gzopen          PR                  extproc('gzopen')
+     D                                     like(gzFile)
+     D  path                           *   value options(*string)               File pathname
+     D  mode                           *   value options(*string)               Open mode
+      /else
+     D gzopen          PR                  extproc('gzopen64')
+     D                                     like(gzFile)
+     D  path                           *   value options(*string)               File pathname
+     D  mode                           *   value options(*string)               Open mode
+      *
+     D gzopen64        PR                  extproc('gzopen64')
+     D                                     like(gzFile)
+     D  path                           *   value options(*string)               File pathname
+     D  mode                           *   value options(*string)               Open mode
+      /endif
+      *
+     D gzdopen         PR                  extproc('gzdopen')
+     D                                     like(gzFile)
+     D  fd                           10I 0 value                                File descriptor
+     D  mode                           *   value options(*string)               Open mode
+      *
+     D gzbuffer        PR            10I 0 extproc('gzbuffer')
+     D  file                               value like(gzFile)                   File pointer
+     D  size                         10U 0 value
+      *
+     D gzsetparams     PR            10I 0 extproc('gzsetparams')
+     D  file                               value like(gzFile)                   File pointer
+     D  level                        10I 0 value
+     D  strategy                     10I 0 value
+      *
+     D gzread          PR            10I 0 extproc('gzread')
+     D  file                               value like(gzFile)                   File pointer
+     D  buf                       65535    options(*varsize)                    Buffer
+     D  len                          10u 0 value                                Buffer length
+      *
+     D gzwrite         PR            10I 0 extproc('gzwrite')
+     D  file                               value like(gzFile)                   File pointer
+     D  buf                       65535    const options(*varsize)              Buffer
+     D  len                          10u 0 value                                Buffer length
+      *
+     D gzputs          PR            10I 0 extproc('gzputs')
+     D  file                               value like(gzFile)                   File pointer
+     D  s                              *   value options(*string)               String to output
+      *
+     D gzgets          PR              *   extproc('gzgets')
+     D  file                               value like(gzFile)                   File pointer
+     D  buf                       65535    options(*varsize)                    Read buffer
+     D  len                          10i 0 value                                Buffer length
+      *
+     D gzputc          PR            10i 0 extproc('gzputc')
+     D  file                               value like(gzFile)                   File pointer
+     D  c                            10I 0 value                                Character to write
+      *
+     D gzgetc          PR            10i 0 extproc('gzgetc')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzgetc_         PR            10i 0 extproc('gzgetc_')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzungetc        PR            10i 0 extproc('gzungetc')
+     D  c                            10I 0 value                                Character to push
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzflush         PR            10i 0 extproc('gzflush')
+     D  file                               value like(gzFile)                   File pointer
+     D  flush                        10I 0 value                                Type of flush
+      *
+      /if not defined(LARGE_FILES)
+     D gzseek          PR                  extproc('gzseek')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+     D  offset                             value like(z_off_t)                  Offset
+     D  whence                       10i 0 value                                Origin
+      /else
+     D gzseek          PR                  extproc('gzseek64')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+     D  offset                             value like(z_off_t)                  Offset
+     D  whence                       10i 0 value                                Origin
+      *
+     D gzseek64        PR                  extproc('gzseek64')
+     D                                     like(z_off64_t)
+     D  file                               value like(gzFile)                   File pointer
+     D  offset                             value like(z_off64_t)                Offset
+     D  whence                       10i 0 value                                Origin
+      /endif
+      *
+     D gzrewind        PR            10i 0 extproc('gzrewind')
+     D  file                               value like(gzFile)                   File pointer
+      *
+      /if not defined(LARGE_FILES)
+     D gztell          PR                  extproc('gztell')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+      /else
+     D gztell          PR                  extproc('gztell64')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gztell64        PR                  extproc('gztell64')
+     D                                     like(z_off64_t)
+     D  file                               value like(gzFile)                   File pointer
+      /endif
+      *
+      /if not defined(LARGE_FILES)
+     D gzoffset        PR                  extproc('gzoffset')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+      /else
+     D gzoffset        PR                  extproc('gzoffset64')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzoffset64      PR                  extproc('gzoffset64')
+     D                                     like(z_off64_t)
+     D  file                               value like(gzFile)                   File pointer
+      /endif
+      *
+     D gzeof           PR            10i 0 extproc('gzeof')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzclose_r       PR            10i 0 extproc('gzclose_r')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzclose_w       PR            10i 0 extproc('gzclose_w')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzclose         PR            10i 0 extproc('gzclose')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzerror         PR              *   extproc('gzerror')                   Error string
+     D  file                               value like(gzFile)                   File pointer
+     D  errnum                       10I 0                                      Error code
+      *
+     D gzclearerr      PR                  extproc('gzclearerr')
+     D  file                               value like(gzFile)                   File pointer
+      *
+      **************************************************************************
+      *                        Basic function prototypes
+      **************************************************************************
+      *
+     D zlibVersion     PR              *   extproc('zlibVersion')               Version string
+      *
+     D deflateInit     PR            10I 0 extproc('deflateInit_')              Init. compression
+     D  strm                               like(z_stream)                       Compression stream
+     D  level                        10I 0 value                                Compression level
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D deflate         PR            10I 0 extproc('deflate')                   Compress data
+     D  strm                               like(z_stream)                       Compression stream
+     D  flush                        10I 0 value                                Flush type required
+      *
+     D deflateEnd      PR            10I 0 extproc('deflateEnd')                Termin. compression
+     D  strm                               like(z_stream)                       Compression stream
+      *
+     D inflateInit     PR            10I 0 extproc('inflateInit_')              Init. expansion
+     D  strm                               like(z_stream)                       Expansion stream
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D inflate         PR            10I 0 extproc('inflate')                   Expand data
+     D  strm                               like(z_stream)                       Expansion stream
+     D  flush                        10I 0 value                                Flush type required
+      *
+     D inflateEnd      PR            10I 0 extproc('inflateEnd')                Termin. expansion
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+      **************************************************************************
+      *                        Advanced function prototypes
+      **************************************************************************
+      *
+     D deflateInit2    PR            10I 0 extproc('deflateInit2_')             Init. compression
+     D  strm                               like(z_stream)                       Compression stream
+     D  level                        10I 0 value                                Compression level
+     D  method                       10I 0 value                                Compression method
+     D  windowBits                   10I 0 value                                log2(window size)
+     D  memLevel                     10I 0 value                                Mem/cmpress tradeoff
+     D  strategy                     10I 0 value                                Compression stategy
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D deflateSetDictionary...
+     D                 PR            10I 0 extproc('deflateSetDictionary')      Init. dictionary
+     D  strm                               like(z_stream)                       Compression stream
+     D  dictionary                65535    const options(*varsize)              Dictionary bytes
+     D  dictLength                   10U 0 value                                Dictionary length
+      *
+     D deflateCopy     PR            10I 0 extproc('deflateCopy')               Compress strm 2 strm
+     D  dest                               like(z_stream)                       Destination stream
+     D  source                             like(z_stream)                       Source stream
+      *
+     D deflateReset    PR            10I 0 extproc('deflateReset')              End and init. stream
+     D  strm                               like(z_stream)                       Compression stream
+      *
+     D deflateParams   PR            10I 0 extproc('deflateParams')             Change level & strat
+     D  strm                               like(z_stream)                       Compression stream
+     D  level                        10I 0 value                                Compression level
+     D  strategy                     10I 0 value                                Compression stategy
+      *
+     D deflateBound    PR            10U 0 extproc('deflateBound')              Change level & strat
+     D  strm                               like(z_stream)                       Compression stream
+     D  sourcelen                    10U 0 value                                Compression level
+      *
+     D deflatePending  PR            10I 0 extproc('deflatePending')            Change level & strat
+     D  strm                               like(z_stream)                       Compression stream
+     D  pending                      10U 0                                      Pending bytes
+     D  bits                         10I 0                                      Pending bits
+      *
+     D deflatePrime    PR            10I 0 extproc('deflatePrime')              Change level & strat
+     D  strm                               like(z_stream)                       Compression stream
+     D  bits                         10I 0 value                                # of bits to insert
+     D  value                        10I 0 value                                Bits to insert
+      *
+     D inflateInit2    PR            10I 0 extproc('inflateInit2_')             Init. expansion
+     D  strm                               like(z_stream)                       Expansion stream
+     D  windowBits                   10I 0 value                                log2(window size)
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D inflateSetDictionary...
+     D                 PR            10I 0 extproc('inflateSetDictionary')      Init. dictionary
+     D  strm                               like(z_stream)                       Expansion stream
+     D  dictionary                65535    const options(*varsize)              Dictionary bytes
+     D  dictLength                   10U 0 value                                Dictionary length
+      *
+     D inflateSync     PR            10I 0 extproc('inflateSync')               Sync. expansion
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D inflateCopy     PR            10I 0 extproc('inflateCopy')
+     D  dest                               like(z_stream)                       Destination stream
+     D  source                             like(z_stream)                       Source stream
+      *
+     D inflateReset    PR            10I 0 extproc('inflateReset')              End and init. stream
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D inflateReset2   PR            10I 0 extproc('inflateReset2')             End and init. stream
+     D  strm                               like(z_stream)                       Expansion stream
+     D  windowBits                   10I 0 value                                Log2(buffer size)
+      *
+     D inflatePrime    PR            10I 0 extproc('inflatePrime')              Insert bits
+     D  strm                               like(z_stream)                       Expansion stream
+     D  bits                         10I 0 value                                Bit count
+     D  value                        10I 0 value                                Bits to insert
+      *
+     D inflateMark     PR            10I 0 extproc('inflateMark')               Get inflate info
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D inflateBackInit...
+     D                 PR            10I 0 extproc('inflateBackInit_')
+     D  strm                               like(z_stream)                       Expansion stream
+     D  windowBits                   10I 0 value                                Log2(buffer size)
+     D  window                    65535    options(*varsize)                    Buffer
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D inflateBack     PR            10I 0 extproc('inflateBack')
+     D  strm                               like(z_stream)                       Expansion stream
+     D  in                             *   value procptr                        Input function
+     D  in_desc                        *   value                                Input descriptor
+     D  out                            *   value procptr                        Output function
+     D  out_desc                       *   value                                Output descriptor
+      *
+     D inflateBackEnd  PR            10I 0 extproc('inflateBackEnd')
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D zlibCompileFlags...
+     D                 PR            10U 0 extproc('zlibCompileFlags')
+      *
+      **************************************************************************
+      *                        Checksum function prototypes
+      **************************************************************************
+      *
+     D adler32         PR            10U 0 extproc('adler32')                   New checksum
+     D  adler                        10U 0 value                                Old checksum
+     D  buf                       65535    const options(*varsize)              Bytes to accumulate
+     D  len                          10U 0 value                                Buffer length
+      *
+     D crc32           PR            10U 0 extproc('crc32')                     New checksum
+     D  crc                          10U 0 value                                Old checksum
+     D  buf                       65535    const options(*varsize)              Bytes to accumulate
+     D  len                          10U 0 value                                Buffer length
+      *
+      **************************************************************************
+      *                     Miscellaneous function prototypes
+      **************************************************************************
+      *
+     D zError          PR              *   extproc('zError')                    Error string
+     D  err                          10I 0 value                                Error code
+      *
+     D inflateSyncPoint...
+     D                 PR            10I 0 extproc('inflateSyncPoint')
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D get_crc_table   PR              *   extproc('get_crc_table')             Ptr to ulongs
+      *
+     D inflateUndermine...
+     D                 PR            10I 0 extproc('inflateUndermine')
+     D  strm                               like(z_stream)                       Expansion stream
+     D  arg                          10I 0 value                                Error code
+      *
+     D inflateResetKeep...
+     D                 PR            10I 0 extproc('inflateResetKeep')          End and init. stream
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D deflateResetKeep...
+     D                 PR            10I 0 extproc('deflateResetKeep')          End and init. stream
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D gzflags         PR            10U 0 extproc('gzflags')
+      *
+      /endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/compress.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/compress.c
new file mode 100644 (file)
index 0000000..ea4dfbe
--- /dev/null
@@ -0,0 +1,80 @@
+/* compress.c -- compress a memory buffer
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#define ZLIB_INTERNAL
+#include "zlib.h"
+
+/* ===========================================================================
+     Compresses the source buffer into the destination buffer. The level
+   parameter has the same meaning as in deflateInit.  sourceLen is the byte
+   length of the source buffer. Upon entry, destLen is the total size of the
+   destination buffer, which must be at least 0.1% larger than sourceLen plus
+   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
+
+     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+   Z_STREAM_ERROR if the level parameter is invalid.
+*/
+int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+    int level;
+{
+    z_stream stream;
+    int err;
+
+    stream.next_in = (Bytef*)source;
+    stream.avail_in = (uInt)sourceLen;
+#ifdef MAXSEG_64K
+    /* Check for source > 64K on 16-bit machine: */
+    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
+#endif
+    stream.next_out = dest;
+    stream.avail_out = (uInt)*destLen;
+    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
+
+    stream.zalloc = (alloc_func)0;
+    stream.zfree = (free_func)0;
+    stream.opaque = (voidpf)0;
+
+    err = deflateInit(&stream, level);
+    if (err != Z_OK) return err;
+
+    err = deflate(&stream, Z_FINISH);
+    if (err != Z_STREAM_END) {
+        deflateEnd(&stream);
+        return err == Z_OK ? Z_BUF_ERROR : err;
+    }
+    *destLen = stream.total_out;
+
+    err = deflateEnd(&stream);
+    return err;
+}
+
+/* ===========================================================================
+ */
+int ZEXPORT compress (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+{
+    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
+}
+
+/* ===========================================================================
+     If the default memLevel or windowBits for deflateInit() is changed, then
+   this function needs to be updated.
+ */
+uLong ZEXPORT compressBound (sourceLen)
+    uLong sourceLen;
+{
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+           (sourceLen >> 25) + 13;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/configure b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/configure
new file mode 100644 (file)
index 0000000..780317c
--- /dev/null
@@ -0,0 +1,720 @@
+#!/bin/sh
+# configure script for zlib.
+#
+# Normally configure builds both a static and a shared library.
+# If you want to build just a static library, use: ./configure --static
+#
+# To impose specific compiler or flags or install directory, use for example:
+#    prefix=$HOME CC=cc CFLAGS="-O4" ./configure
+# or for csh/tcsh users:
+#    (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure)
+
+# Incorrect settings of CC or CFLAGS may prevent creating a shared library.
+# If you have problems, try without defining CC and CFLAGS before reporting
+# an error.
+
+echo -------------------- >> configure.log
+echo $0 $* >> configure.log
+date >> configure.log
+
+if [ -n "${CHOST}" ]; then
+    uname="`echo "${CHOST}" | sed -e 's/^[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)-.*$/\1/'`"
+    CROSS_PREFIX="${CHOST}-"
+fi
+
+STATICLIB=libz.a
+VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`
+VER3=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\\.[0-9]*\).*/\1/p' < zlib.h`
+VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h`
+VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < zlib.h`
+if "${CROSS_PREFIX}ar" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+    AR=${AR-"${CROSS_PREFIX}ar"}
+    test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log
+else
+    AR=${AR-"ar"}
+    test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log
+fi
+ARFLAGS=${ARFLAGS-"rc"}
+if "${CROSS_PREFIX}ranlib" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+    RANLIB=${RANLIB-"${CROSS_PREFIX}ranlib"}
+    test -n "${CROSS_PREFIX}" && echo Using ${RANLIB} | tee -a configure.log
+else
+    RANLIB=${RANLIB-"ranlib"}
+fi
+if "${CROSS_PREFIX}nm" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+    NM=${NM-"${CROSS_PREFIX}nm"}
+    test -n "${CROSS_PREFIX}" && echo Using ${NM} | tee -a configure.log
+else
+    NM=${NM-"nm"}
+fi
+LDCONFIG=${LDCONFIG-"ldconfig"}
+LDSHAREDLIBC="${LDSHAREDLIBC--lc}"
+ARCHS=
+prefix=${prefix-/usr/local}
+exec_prefix=${exec_prefix-'${prefix}'}
+libdir=${libdir-'${exec_prefix}/lib'}
+sharedlibdir=${sharedlibdir-'${libdir}'}
+includedir=${includedir-'${prefix}/include'}
+mandir=${mandir-'${prefix}/share/man'}
+shared_ext='.so'
+shared=1
+solo=0
+cover=0
+zprefix=0
+build64=0
+gcc=0
+old_cc="$CC"
+old_cflags="$CFLAGS"
+OBJC='$(OBJZ) $(OBJG)'
+PIC_OBJC='$(PIC_OBJZ) $(PIC_OBJG)'
+
+while test $# -ge 1
+do
+case "$1" in
+    -h* | --help)
+      echo 'usage:' | tee -a configure.log
+      echo '  configure [--zprefix] [--prefix=PREFIX]  [--eprefix=EXPREFIX]' | tee -a configure.log
+      echo '    [--static] [--64] [--libdir=LIBDIR] [--sharedlibdir=LIBDIR]' | tee -a configure.log
+      echo '    [--includedir=INCLUDEDIR] [--archs="-arch i386 -arch x86_64"]' | tee -a configure.log
+        exit 0 ;;
+    -p*=* | --prefix=*) prefix=`echo $1 | sed 's/.*=//'`; shift ;;
+    -e*=* | --eprefix=*) exec_prefix=`echo $1 | sed 's/.*=//'`; shift ;;
+    -l*=* | --libdir=*) libdir=`echo $1 | sed 's/.*=//'`; shift ;;
+    --sharedlibdir=*) sharedlibdir=`echo $1 | sed 's/.*=//'`; shift ;;
+    -i*=* | --includedir=*) includedir=`echo $1 | sed 's/.*=//'`;shift ;;
+    -u*=* | --uname=*) uname=`echo $1 | sed 's/.*=//'`;shift ;;
+    -p* | --prefix) prefix="$2"; shift; shift ;;
+    -e* | --eprefix) exec_prefix="$2"; shift; shift ;;
+    -l* | --libdir) libdir="$2"; shift; shift ;;
+    -i* | --includedir) includedir="$2"; shift; shift ;;
+    -s* | --shared | --enable-shared) shared=1; shift ;;
+    -t | --static) shared=0; shift ;;
+    --solo) solo=1; shift ;;
+    --cover) cover=1; shift ;;
+    -z* | --zprefix) zprefix=1; shift ;;
+    -6* | --64) build64=1; shift ;;
+    -a*=* | --archs=*) ARCHS=`echo $1 | sed 's/.*=//'`; shift ;;
+    --sysconfdir=*) echo "ignored option: --sysconfdir" | tee -a configure.log; shift ;;
+    --localstatedir=*) echo "ignored option: --localstatedir" | tee -a configure.log; shift ;;
+    *) echo "unknown option: $1"; echo "$0 --help for help" | tee -a configure.log; exit 1 ;;
+    esac
+done
+
+test=ztest$$
+
+show()
+{
+  case "$*" in
+    *$test.c*)
+      echo === $test.c === >> configure.log
+      cat $test.c >> configure.log
+      echo === >> configure.log;;
+  esac
+  echo $* >> configure.log
+}
+
+cat > $test.c <<EOF
+#error error
+EOF
+if ($CC -c $CFLAGS $test.c) 2>/dev/null; then
+  try()
+  {
+    show $*
+    test "`( $* ) 2>&1 | tee -a configure.log`" = ""
+  }
+  echo - using any output from compiler to indicate an error >> configure.log
+else
+  try()
+  {
+    show $*
+    ( $* ) >> configure.log 2>&1
+    ret=$?
+    if test $ret -ne 0; then
+      echo "(exit code "$ret")" >> configure.log
+    fi
+    return $ret
+  }
+fi
+
+echo >> configure.log
+
+cat > $test.c <<EOF
+extern int getchar();
+int hello() {return getchar();}
+EOF
+
+test -z "$CC" && echo Checking for ${CROSS_PREFIX}gcc... | tee -a configure.log
+cc=${CC-${CROSS_PREFIX}gcc}
+cflags=${CFLAGS-"-O3"}
+# to force the asm version use: CFLAGS="-O3 -DASMV" ./configure
+case "$cc" in
+  *gcc*) gcc=1 ;;
+esac
+case `$cc -v 2>&1` in
+  *gcc*) gcc=1 ;;
+esac
+
+show $cc -c $cflags $test.c
+if test "$gcc" -eq 1 && ($cc -c $cflags $test.c) >> configure.log 2>&1; then
+  echo ... using gcc >> configure.log
+  CC="$cc"
+  CFLAGS="${CFLAGS--O3} ${ARCHS}"
+  SFLAGS="${CFLAGS--O3} -fPIC"
+  LDFLAGS="${LDFLAGS} ${ARCHS}"
+  if test $build64 -eq 1; then
+    CFLAGS="${CFLAGS} -m64"
+    SFLAGS="${SFLAGS} -m64"
+  fi
+  if test "${ZLIBGCCWARN}" = "YES"; then
+    CFLAGS="${CFLAGS} -Wall -Wextra -pedantic"
+  fi
+  if test -z "$uname"; then
+    uname=`(uname -s || echo unknown) 2>/dev/null`
+  fi
+  case "$uname" in
+  Linux* | linux* | GNU | GNU/* | solaris*)
+        LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,zlib.map"} ;;
+  *BSD | *bsd* | DragonFly)
+        LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,zlib.map"}
+        LDCONFIG="ldconfig -m" ;;
+  CYGWIN* | Cygwin* | cygwin* | OS/2*)
+        EXE='.exe' ;;
+  MINGW* | mingw*)
+# temporary bypass
+        rm -f $test.[co] $test $test$shared_ext
+        echo "Please use win32/Makefile.gcc instead." | tee -a configure.log
+        exit 1
+        LDSHARED=${LDSHARED-"$cc -shared"}
+        LDSHAREDLIBC=""
+        EXE='.exe' ;;
+  QNX*)  # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4
+         # (alain.bonnefoy@icbt.com)
+                 LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"} ;;
+  HP-UX*)
+         LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"}
+         case `(uname -m || echo unknown) 2>/dev/null` in
+         ia64)
+                 shared_ext='.so'
+                 SHAREDLIB='libz.so' ;;
+         *)
+                 shared_ext='.sl'
+                 SHAREDLIB='libz.sl' ;;
+         esac ;;
+  Darwin* | darwin*)
+             shared_ext='.dylib'
+             SHAREDLIB=libz$shared_ext
+             SHAREDLIBV=libz.$VER$shared_ext
+             SHAREDLIBM=libz.$VER1$shared_ext
+             LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER3"}
+             AR="libtool"
+             ARFLAGS="-o" ;;
+  *)             LDSHARED=${LDSHARED-"$cc -shared"} ;;
+  esac
+else
+  # find system name and corresponding cc options
+  CC=${CC-cc}
+  gcc=0
+  echo ... using $CC >> configure.log
+  if test -z "$uname"; then
+    uname=`(uname -sr || echo unknown) 2>/dev/null`
+  fi
+  case "$uname" in
+  HP-UX*)    SFLAGS=${CFLAGS-"-O +z"}
+             CFLAGS=${CFLAGS-"-O"}
+#            LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"}
+             LDSHARED=${LDSHARED-"ld -b"}
+         case `(uname -m || echo unknown) 2>/dev/null` in
+         ia64)
+             shared_ext='.so'
+             SHAREDLIB='libz.so' ;;
+         *)
+             shared_ext='.sl'
+             SHAREDLIB='libz.sl' ;;
+         esac ;;
+  IRIX*)     SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."}
+             CFLAGS=${CFLAGS-"-ansi -O2"}
+             LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;;
+  OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"}
+             CFLAGS=${CFLAGS-"-O -std1"}
+             LDFLAGS="${LDFLAGS} -Wl,-rpath,."
+             LDSHARED=${LDSHARED-"cc -shared  -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"} ;;
+  OSF1*)     SFLAGS=${CFLAGS-"-O -std1"}
+             CFLAGS=${CFLAGS-"-O -std1"}
+             LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;;
+  QNX*)      SFLAGS=${CFLAGS-"-4 -O"}
+             CFLAGS=${CFLAGS-"-4 -O"}
+             LDSHARED=${LDSHARED-"cc"}
+             RANLIB=${RANLIB-"true"}
+             AR="cc"
+             ARFLAGS="-A" ;;
+  SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "}
+             CFLAGS=${CFLAGS-"-O3"}
+             LDSHARED=${LDSHARED-"cc -dy -KPIC -G"} ;;
+  SunOS\ 5* | solaris*)
+         LDSHARED=${LDSHARED-"cc -G"}
+         case `(uname -m || echo unknown) 2>/dev/null` in
+         i86*)
+             SFLAGS=${CFLAGS-"-xpentium -fast -KPIC -R."}
+             CFLAGS=${CFLAGS-"-xpentium -fast"} ;;
+         *)
+             SFLAGS=${CFLAGS-"-fast -xcg92 -KPIC -R."}
+             CFLAGS=${CFLAGS-"-fast -xcg92"} ;;
+         esac ;;
+  SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"}
+             CFLAGS=${CFLAGS-"-O2"}
+             LDSHARED=${LDSHARED-"ld"} ;;
+  SunStudio\ 9*) SFLAGS=${CFLAGS-"-fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"}
+             CFLAGS=${CFLAGS-"-fast -xtarget=ultra3 -xarch=v9b"}
+             LDSHARED=${LDSHARED-"cc -xarch=v9b"} ;;
+  UNIX_System_V\ 4.2.0)
+             SFLAGS=${CFLAGS-"-KPIC -O"}
+             CFLAGS=${CFLAGS-"-O"}
+             LDSHARED=${LDSHARED-"cc -G"} ;;
+  UNIX_SV\ 4.2MP)
+             SFLAGS=${CFLAGS-"-Kconform_pic -O"}
+             CFLAGS=${CFLAGS-"-O"}
+             LDSHARED=${LDSHARED-"cc -G"} ;;
+  OpenUNIX\ 5)
+             SFLAGS=${CFLAGS-"-KPIC -O"}
+             CFLAGS=${CFLAGS-"-O"}
+             LDSHARED=${LDSHARED-"cc -G"} ;;
+  AIX*)  # Courtesy of dbakker@arrayasolutions.com
+             SFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
+             CFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
+             LDSHARED=${LDSHARED-"xlc -G"} ;;
+  # send working options for other systems to zlib@gzip.org
+  *)         SFLAGS=${CFLAGS-"-O"}
+             CFLAGS=${CFLAGS-"-O"}
+             LDSHARED=${LDSHARED-"cc -shared"} ;;
+  esac
+fi
+
+SHAREDLIB=${SHAREDLIB-"libz$shared_ext"}
+SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"}
+SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"}
+
+echo >> configure.log
+
+if test $shared -eq 1; then
+  echo Checking for shared library support... | tee -a configure.log
+  # we must test in two steps (cc then ld), required at least on SunOS 4.x
+  if try $CC -w -c $SFLAGS $test.c &&
+     try $LDSHARED $SFLAGS -o $test$shared_ext $test.o; then
+    echo Building shared library $SHAREDLIBV with $CC. | tee -a configure.log
+  elif test -z "$old_cc" -a -z "$old_cflags"; then
+    echo No shared library support. | tee -a configure.log
+    shared=0;
+  else
+    echo 'No shared library support; try without defining CC and CFLAGS' | tee -a configure.log
+    shared=0;
+  fi
+fi
+if test $shared -eq 0; then
+  LDSHARED="$CC"
+  ALL="static"
+  TEST="all teststatic"
+  SHAREDLIB=""
+  SHAREDLIBV=""
+  SHAREDLIBM=""
+  echo Building static library $STATICLIB version $VER with $CC. | tee -a configure.log
+else
+  ALL="static shared"
+  TEST="all teststatic testshared"
+fi
+
+CPP=${CPP-"$CC -E"}
+case $CFLAGS in
+  *ASMV*)
+    echo >> configure.log
+    show "$NM $test.o | grep _hello"
+    if test "`$NM $test.o | grep _hello | tee -a configure.log`" = ""; then
+      CPP="$CPP -DNO_UNDERLINE"
+      echo Checking for underline in external names... No. | tee -a configure.log
+    else
+      echo Checking for underline in external names... Yes. | tee -a configure.log
+    fi ;;
+esac
+
+echo >> configure.log
+
+cat > $test.c <<EOF
+#include <sys/types.h>
+off64_t dummy = 0;
+EOF
+if try $CC -c $CFLAGS -D_LARGEFILE64_SOURCE=1 $test.c; then
+  CFLAGS="${CFLAGS} -D_LARGEFILE64_SOURCE=1"
+  SFLAGS="${SFLAGS} -D_LARGEFILE64_SOURCE=1"
+  ALL="${ALL} all64"
+  TEST="${TEST} test64"
+  echo "Checking for off64_t... Yes." | tee -a configure.log
+  echo "Checking for fseeko... Yes." | tee -a configure.log
+else
+  echo "Checking for off64_t... No." | tee -a configure.log
+  echo >> configure.log
+  cat > $test.c <<EOF
+#include <stdio.h>
+int main(void) {
+  fseeko(NULL, 0, 0);
+  return 0;
+}
+EOF
+  if try $CC $CFLAGS -o $test $test.c; then
+    echo "Checking for fseeko... Yes." | tee -a configure.log
+  else
+    CFLAGS="${CFLAGS} -DNO_FSEEKO"
+    SFLAGS="${SFLAGS} -DNO_FSEEKO"
+    echo "Checking for fseeko... No." | tee -a configure.log
+  fi
+fi
+
+cp -p zconf.h.in zconf.h
+
+echo >> configure.log
+
+cat > $test.c <<EOF
+#include <unistd.h>
+int main() { return 0; }
+EOF
+if try $CC -c $CFLAGS $test.c; then
+  sed < zconf.h "/^#ifdef HAVE_UNISTD_H.* may be/s/def HAVE_UNISTD_H\(.*\) may be/ 1\1 was/" > zconf.temp.h
+  mv zconf.temp.h zconf.h
+  echo "Checking for unistd.h... Yes." | tee -a configure.log
+else
+  echo "Checking for unistd.h... No." | tee -a configure.log
+fi
+
+echo >> configure.log
+
+cat > $test.c <<EOF
+#include <stdarg.h>
+int main() { return 0; }
+EOF
+if try $CC -c $CFLAGS $test.c; then
+  sed < zconf.h "/^#ifdef HAVE_STDARG_H.* may be/s/def HAVE_STDARG_H\(.*\) may be/ 1\1 was/" > zconf.temp.h
+  mv zconf.temp.h zconf.h
+  echo "Checking for stdarg.h... Yes." | tee -a configure.log
+else
+  echo "Checking for stdarg.h... No." | tee -a configure.log
+fi
+
+if test $zprefix -eq 1; then
+  sed < zconf.h "/#ifdef Z_PREFIX.* may be/s/def Z_PREFIX\(.*\) may be/ 1\1 was/" > zconf.temp.h
+  mv zconf.temp.h zconf.h
+  echo >> configure.log
+  echo "Using z_ prefix on all symbols." | tee -a configure.log
+fi
+
+if test $solo -eq 1; then
+  sed '/#define ZCONF_H/a\
+#define Z_SOLO
+
+' < zconf.h > zconf.temp.h
+  mv zconf.temp.h zconf.h
+OBJC='$(OBJZ)'
+PIC_OBJC='$(PIC_OBJZ)'
+fi
+
+if test $cover -eq 1; then
+  CFLAGS="${CFLAGS} -fprofile-arcs -ftest-coverage"
+fi
+
+echo >> configure.log
+
+cat > $test.c <<EOF
+#include <stdio.h>
+#include <stdarg.h>
+#include "zconf.h"
+int main()
+{
+#ifndef STDC
+  choke me
+#endif
+  return 0;
+}
+EOF
+
+if try $CC -c $CFLAGS $test.c; then
+  echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()." | tee -a configure.log
+
+  echo >> configure.log
+  cat > $test.c <<EOF
+#include <stdio.h>
+#include <stdarg.h>
+int mytest(const char *fmt, ...)
+{
+  char buf[20];
+  va_list ap;
+  va_start(ap, fmt);
+  vsnprintf(buf, sizeof(buf), fmt, ap);
+  va_end(ap);
+  return 0;
+}
+int main()
+{
+  return (mytest("Hello%d\n", 1));
+}
+EOF
+  if try $CC $CFLAGS -o $test $test.c; then
+    echo "Checking for vsnprintf() in stdio.h... Yes." | tee -a configure.log
+
+    echo >> configure.log
+    cat >$test.c <<EOF
+#include <stdio.h>
+#include <stdarg.h>
+int mytest(const char *fmt, ...)
+{
+  int n;
+  char buf[20];
+  va_list ap;
+  va_start(ap, fmt);
+  n = vsnprintf(buf, sizeof(buf), fmt, ap);
+  va_end(ap);
+  return n;
+}
+int main()
+{
+  return (mytest("Hello%d\n", 1));
+}
+EOF
+
+    if try $CC -c $CFLAGS $test.c; then
+      echo "Checking for return value of vsnprintf()... Yes." | tee -a configure.log
+    else
+      CFLAGS="$CFLAGS -DHAS_vsnprintf_void"
+      SFLAGS="$SFLAGS -DHAS_vsnprintf_void"
+      echo "Checking for return value of vsnprintf()... No." | tee -a configure.log
+      echo "  WARNING: apparently vsnprintf() does not return a value. zlib" | tee -a configure.log
+      echo "  can build but will be open to possible string-format security" | tee -a configure.log
+      echo "  vulnerabilities." | tee -a configure.log
+    fi
+  else
+    CFLAGS="$CFLAGS -DNO_vsnprintf"
+    SFLAGS="$SFLAGS -DNO_vsnprintf"
+    echo "Checking for vsnprintf() in stdio.h... No." | tee -a configure.log
+    echo "  WARNING: vsnprintf() not found, falling back to vsprintf(). zlib" | tee -a configure.log
+    echo "  can build but will be open to possible buffer-overflow security" | tee -a configure.log
+    echo "  vulnerabilities." | tee -a configure.log
+
+    echo >> configure.log
+    cat >$test.c <<EOF
+#include <stdio.h>
+#include <stdarg.h>
+int mytest(const char *fmt, ...)
+{
+  int n;
+  char buf[20];
+  va_list ap;
+  va_start(ap, fmt);
+  n = vsprintf(buf, fmt, ap);
+  va_end(ap);
+  return n;
+}
+int main()
+{
+  return (mytest("Hello%d\n", 1));
+}
+EOF
+
+    if try $CC -c $CFLAGS $test.c; then
+      echo "Checking for return value of vsprintf()... Yes." | tee -a configure.log
+    else
+      CFLAGS="$CFLAGS -DHAS_vsprintf_void"
+      SFLAGS="$SFLAGS -DHAS_vsprintf_void"
+      echo "Checking for return value of vsprintf()... No." | tee -a configure.log
+      echo "  WARNING: apparently vsprintf() does not return a value. zlib" | tee -a configure.log
+      echo "  can build but will be open to possible string-format security" | tee -a configure.log
+      echo "  vulnerabilities." | tee -a configure.log
+    fi
+  fi
+else
+  echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()." | tee -a configure.log
+
+  echo >> configure.log
+  cat >$test.c <<EOF
+#include <stdio.h>
+int mytest()
+{
+  char buf[20];
+  snprintf(buf, sizeof(buf), "%s", "foo");
+  return 0;
+}
+int main()
+{
+  return (mytest());
+}
+EOF
+
+  if try $CC $CFLAGS -o $test $test.c; then
+    echo "Checking for snprintf() in stdio.h... Yes." | tee -a configure.log
+
+    echo >> configure.log
+    cat >$test.c <<EOF
+#include <stdio.h>
+int mytest()
+{
+  char buf[20];
+  return snprintf(buf, sizeof(buf), "%s", "foo");
+}
+int main()
+{
+  return (mytest());
+}
+EOF
+
+    if try $CC -c $CFLAGS $test.c; then
+      echo "Checking for return value of snprintf()... Yes." | tee -a configure.log
+    else
+      CFLAGS="$CFLAGS -DHAS_snprintf_void"
+      SFLAGS="$SFLAGS -DHAS_snprintf_void"
+      echo "Checking for return value of snprintf()... No." | tee -a configure.log
+      echo "  WARNING: apparently snprintf() does not return a value. zlib" | tee -a configure.log
+      echo "  can build but will be open to possible string-format security" | tee -a configure.log
+      echo "  vulnerabilities." | tee -a configure.log
+    fi
+  else
+    CFLAGS="$CFLAGS -DNO_snprintf"
+    SFLAGS="$SFLAGS -DNO_snprintf"
+    echo "Checking for snprintf() in stdio.h... No." | tee -a configure.log
+    echo "  WARNING: snprintf() not found, falling back to sprintf(). zlib" | tee -a configure.log
+    echo "  can build but will be open to possible buffer-overflow security" | tee -a configure.log
+    echo "  vulnerabilities." | tee -a configure.log
+
+    echo >> configure.log
+    cat >$test.c <<EOF
+#include <stdio.h>
+int mytest()
+{
+  char buf[20];
+  return sprintf(buf, "%s", "foo");
+}
+int main()
+{
+  return (mytest());
+}
+EOF
+
+    if try $CC -c $CFLAGS $test.c; then
+      echo "Checking for return value of sprintf()... Yes." | tee -a configure.log
+    else
+      CFLAGS="$CFLAGS -DHAS_sprintf_void"
+      SFLAGS="$SFLAGS -DHAS_sprintf_void"
+      echo "Checking for return value of sprintf()... No." | tee -a configure.log
+      echo "  WARNING: apparently sprintf() does not return a value. zlib" | tee -a configure.log
+      echo "  can build but will be open to possible string-format security" | tee -a configure.log
+      echo "  vulnerabilities." | tee -a configure.log
+    fi
+  fi
+fi
+
+if test "$gcc" -eq 1; then
+  echo >> configure.log
+  cat > $test.c <<EOF
+#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33)
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+int ZLIB_INTERNAL foo;
+int main()
+{
+  return 0;
+}
+EOF
+  if try $CC -c $CFLAGS $test.c; then
+    echo "Checking for attribute(visibility) support... Yes." | tee -a configure.log
+  else
+    CFLAGS="$CFLAGS -DNO_VIZ"
+    SFLAGS="$SFLAGS -DNO_VIZ"
+    echo "Checking for attribute(visibility) support... No." | tee -a configure.log
+  fi
+fi
+
+rm -f $test.[co] $test $test$shared_ext $test.gcno
+
+# show the results in the log
+echo >> configure.log
+echo ALL = $ALL >> configure.log
+echo AR = $AR >> configure.log
+echo ARFLAGS = $ARFLAGS >> configure.log
+echo CC = $CC >> configure.log
+echo CFLAGS = $CFLAGS >> configure.log
+echo CPP = $CPP >> configure.log
+echo EXE = $EXE >> configure.log
+echo LDCONFIG = $LDCONFIG >> configure.log
+echo LDFLAGS = $LDFLAGS >> configure.log
+echo LDSHARED = $LDSHARED >> configure.log
+echo LDSHAREDLIBC = $LDSHAREDLIBC >> configure.log
+echo OBJC = $OBJC >> configure.log
+echo PIC_OBJC = $PIC_OBJC >> configure.log
+echo RANLIB = $RANLIB >> configure.log
+echo SFLAGS = $SFLAGS >> configure.log
+echo SHAREDLIB = $SHAREDLIB >> configure.log
+echo SHAREDLIBM = $SHAREDLIBM >> configure.log
+echo SHAREDLIBV = $SHAREDLIBV >> configure.log
+echo STATICLIB = $STATICLIB >> configure.log
+echo TEST = $TEST >> configure.log
+echo VER = $VER >> configure.log
+echo exec_prefix = $exec_prefix >> configure.log
+echo includedir = $includedir >> configure.log
+echo libdir = $libdir >> configure.log
+echo mandir = $mandir >> configure.log
+echo prefix = $prefix >> configure.log
+echo sharedlibdir = $sharedlibdir >> configure.log
+echo uname = $uname >> configure.log
+echo -------------------- >> configure.log
+echo >> configure.log
+echo >> configure.log
+
+# udpate Makefile
+sed < Makefile.in "
+/^CC *=/s#=.*#=$CC#
+/^CFLAGS *=/s#=.*#=$CFLAGS#
+/^SFLAGS *=/s#=.*#=$SFLAGS#
+/^LDFLAGS *=/s#=.*#=$LDFLAGS#
+/^LDSHARED *=/s#=.*#=$LDSHARED#
+/^CPP *=/s#=.*#=$CPP#
+/^STATICLIB *=/s#=.*#=$STATICLIB#
+/^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
+/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
+/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
+/^AR *=/s#=.*#=$AR#
+/^ARFLAGS *=/s#=.*#=$ARFLAGS#
+/^RANLIB *=/s#=.*#=$RANLIB#
+/^LDCONFIG *=/s#=.*#=$LDCONFIG#
+/^LDSHAREDLIBC *=/s#=.*#=$LDSHAREDLIBC#
+/^EXE *=/s#=.*#=$EXE#
+/^prefix *=/s#=.*#=$prefix#
+/^exec_prefix *=/s#=.*#=$exec_prefix#
+/^libdir *=/s#=.*#=$libdir#
+/^sharedlibdir *=/s#=.*#=$sharedlibdir#
+/^includedir *=/s#=.*#=$includedir#
+/^mandir *=/s#=.*#=$mandir#
+/^OBJC *=/s#=.*#= $OBJC#
+/^PIC_OBJC *=/s#=.*#= $PIC_OBJC#
+/^all: */s#:.*#: $ALL#
+/^test: */s#:.*#: $TEST#
+" > Makefile
+
+sed < zlib.pc.in "
+/^CC *=/s#=.*#=$CC#
+/^CFLAGS *=/s#=.*#=$CFLAGS#
+/^CPP *=/s#=.*#=$CPP#
+/^LDSHARED *=/s#=.*#=$LDSHARED#
+/^STATICLIB *=/s#=.*#=$STATICLIB#
+/^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
+/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
+/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
+/^AR *=/s#=.*#=$AR#
+/^ARFLAGS *=/s#=.*#=$ARFLAGS#
+/^RANLIB *=/s#=.*#=$RANLIB#
+/^EXE *=/s#=.*#=$EXE#
+/^prefix *=/s#=.*#=$prefix#
+/^exec_prefix *=/s#=.*#=$exec_prefix#
+/^libdir *=/s#=.*#=$libdir#
+/^sharedlibdir *=/s#=.*#=$sharedlibdir#
+/^includedir *=/s#=.*#=$includedir#
+/^mandir *=/s#=.*#=$mandir#
+/^LDFLAGS *=/s#=.*#=$LDFLAGS#
+" | sed -e "
+s/\@VERSION\@/$VER/g;
+" > zlib.pc
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/README.contrib b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/README.contrib
new file mode 100644 (file)
index 0000000..dd2285d
--- /dev/null
@@ -0,0 +1,77 @@
+All files under this contrib directory are UNSUPPORTED. There were
+provided by users of zlib and were not tested by the authors of zlib.
+Use at your own risk. Please contact the authors of the contributions
+for help about these, not the zlib authors. Thanks.
+
+
+ada/        by Dmitriy Anisimkov <anisimkov@yahoo.com>
+        Support for Ada
+        See http://zlib-ada.sourceforge.net/
+
+amd64/      by Mikhail Teterin <mi@ALDAN.algebra.com>
+        asm code for AMD64
+        See patch at http://www.freebsd.org/cgi/query-pr.cgi?pr=bin/96393
+
+asm686/     by Brian Raiter <breadbox@muppetlabs.com>
+        asm code for Pentium and PPro/PII, using the AT&T (GNU as) syntax
+        See http://www.muppetlabs.com/~breadbox/software/assembly.html
+
+blast/      by Mark Adler <madler@alumni.caltech.edu>
+        Decompressor for output of PKWare Data Compression Library (DCL)
+
+delphi/     by Cosmin Truta <cosmint@cs.ubbcluj.ro>
+        Support for Delphi and C++ Builder
+
+dotzlib/    by Henrik Ravn <henrik@ravn.com>
+        Support for Microsoft .Net and Visual C++ .Net
+
+gcc_gvmat64/by Gilles Vollant <info@winimage.com>
+        GCC Version of x86 64-bit (AMD64 and Intel EM64t) code for x64
+        assembler to replace longest_match() and inflate_fast()
+
+infback9/   by Mark Adler <madler@alumni.caltech.edu>
+        Unsupported diffs to infback to decode the deflate64 format
+
+inflate86/  by Chris Anderson <christop@charm.net>
+        Tuned x86 gcc asm code to replace inflate_fast()
+
+iostream/   by Kevin Ruland <kevin@rodin.wustl.edu>
+        A C++ I/O streams interface to the zlib gz* functions
+
+iostream2/  by Tyge Løvset <Tyge.Lovset@cmr.no>
+        Another C++ I/O streams interface
+
+iostream3/  by Ludwig Schwardt <schwardt@sun.ac.za>
+            and Kevin Ruland <kevin@rodin.wustl.edu>
+        Yet another C++ I/O streams interface
+
+masmx64/    by Gilles Vollant <info@winimage.com>
+        x86 64-bit (AMD64 and Intel EM64t) code for x64 assembler to
+        replace longest_match() and inflate_fast(),  also masm x86
+        64-bits translation of Chris Anderson inflate_fast()
+
+masmx86/    by Gilles Vollant <info@winimage.com>
+        x86 asm code to replace longest_match() and inflate_fast(),
+        for Visual C++ and MASM (32 bits).
+        Based on Brian Raiter (asm686) and Chris Anderson (inflate86)
+
+minizip/    by Gilles Vollant <info@winimage.com>
+        Mini zip and unzip based on zlib
+        Includes Zip64 support by Mathias Svensson <mathias@result42.com>
+        See http://www.winimage.com/zLibDll/unzip.html
+
+pascal/     by Bob Dellaca <bobdl@xtra.co.nz> et al.
+        Support for Pascal
+
+puff/       by Mark Adler <madler@alumni.caltech.edu>
+        Small, low memory usage inflate.  Also serves to provide an
+        unambiguous description of the deflate format.
+
+testzlib/   by Gilles Vollant <info@winimage.com>
+        Example of the use of zlib
+
+untgz/      by Pedro A. Aranda Gutierrez <paag@tid.es>
+        A very simple tar.gz file extractor using zlib
+
+vstudio/    by Gilles Vollant <info@winimage.com>
+        Building a minizip-enhanced zlib with Microsoft Visual Studio
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/buffer_demo.adb b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/buffer_demo.adb
new file mode 100644 (file)
index 0000000..46b8638
--- /dev/null
@@ -0,0 +1,106 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2004 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+--
+--  $Id: buffer_demo.adb,v 1.3 2004/09/06 06:55:35 vagul Exp $
+
+--  This demo program provided by Dr Steve Sangwine <sjs@essex.ac.uk>
+--
+--  Demonstration of a problem with Zlib-Ada (already fixed) when a buffer
+--  of exactly the correct size is used for decompressed data, and the last
+--  few bytes passed in to Zlib are checksum bytes.
+
+--  This program compresses a string of text, and then decompresses the
+--  compressed text into a buffer of the same size as the original text.
+
+with Ada.Streams; use Ada.Streams;
+with Ada.Text_IO;
+
+with ZLib; use ZLib;
+
+procedure Buffer_Demo is
+   EOL  : Character renames ASCII.LF;
+   Text : constant String
+     := "Four score and seven years ago our fathers brought forth," & EOL &
+        "upon this continent, a new nation, conceived in liberty," & EOL &
+        "and dedicated to the proposition that `all men are created equal'.";
+
+   Source : Stream_Element_Array (1 .. Text'Length);
+   for Source'Address use Text'Address;
+
+begin
+   Ada.Text_IO.Put (Text);
+   Ada.Text_IO.New_Line;
+   Ada.Text_IO.Put_Line
+     ("Uncompressed size : " & Positive'Image (Text'Length) & " bytes");
+
+   declare
+      Compressed_Data : Stream_Element_Array (1 .. Text'Length);
+      L               : Stream_Element_Offset;
+   begin
+      Compress : declare
+         Compressor : Filter_Type;
+         I : Stream_Element_Offset;
+      begin
+         Deflate_Init (Compressor);
+
+         --  Compress the whole of T at once.
+
+         Translate (Compressor, Source, I, Compressed_Data, L, Finish);
+         pragma Assert (I = Source'Last);
+
+         Close (Compressor);
+
+         Ada.Text_IO.Put_Line
+           ("Compressed size :   "
+            & Stream_Element_Offset'Image (L) & " bytes");
+      end Compress;
+
+      --  Now we decompress the data, passing short blocks of data to Zlib
+      --  (because this demonstrates the problem - the last block passed will
+      --  contain checksum information and there will be no output, only a
+      --  check inside Zlib that the checksum is correct).
+
+      Decompress : declare
+         Decompressor : Filter_Type;
+
+         Uncompressed_Data : Stream_Element_Array (1 .. Text'Length);
+
+         Block_Size : constant := 4;
+         --  This makes sure that the last block contains
+         --  only Adler checksum data.
+
+         P : Stream_Element_Offset := Compressed_Data'First - 1;
+         O : Stream_Element_Offset;
+      begin
+         Inflate_Init (Decompressor);
+
+         loop
+            Translate
+              (Decompressor,
+               Compressed_Data
+                 (P + 1 .. Stream_Element_Offset'Min (P + Block_Size, L)),
+               P,
+               Uncompressed_Data
+                 (Total_Out (Decompressor) + 1 .. Uncompressed_Data'Last),
+               O,
+               No_Flush);
+
+               Ada.Text_IO.Put_Line
+                 ("Total in : " & Count'Image (Total_In (Decompressor)) &
+                  ", out : " & Count'Image (Total_Out (Decompressor)));
+
+               exit when P = L;
+         end loop;
+
+         Ada.Text_IO.New_Line;
+         Ada.Text_IO.Put_Line
+           ("Decompressed text matches original text : "
+             & Boolean'Image (Uncompressed_Data = Source));
+      end Decompress;
+   end;
+end Buffer_Demo;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/mtest.adb b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/mtest.adb
new file mode 100644 (file)
index 0000000..c4dfd08
--- /dev/null
@@ -0,0 +1,156 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2003 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+--  Continuous test for ZLib multithreading. If the test would fail
+--  we should provide thread safe allocation routines for the Z_Stream.
+--
+--  $Id: mtest.adb,v 1.4 2004/07/23 07:49:54 vagul Exp $
+
+with ZLib;
+with Ada.Streams;
+with Ada.Numerics.Discrete_Random;
+with Ada.Text_IO;
+with Ada.Exceptions;
+with Ada.Task_Identification;
+
+procedure MTest is
+   use Ada.Streams;
+   use ZLib;
+
+   Stop : Boolean := False;
+
+   pragma Atomic (Stop);
+
+   subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#;
+
+   package Random_Elements is
+      new Ada.Numerics.Discrete_Random (Visible_Symbols);
+
+   task type Test_Task;
+
+   task body Test_Task is
+      Buffer : Stream_Element_Array (1 .. 100_000);
+      Gen : Random_Elements.Generator;
+
+      Buffer_First  : Stream_Element_Offset;
+      Compare_First : Stream_Element_Offset;
+
+      Deflate : Filter_Type;
+      Inflate : Filter_Type;
+
+      procedure Further (Item : in Stream_Element_Array);
+
+      procedure Read_Buffer
+        (Item : out Ada.Streams.Stream_Element_Array;
+         Last : out Ada.Streams.Stream_Element_Offset);
+
+      -------------
+      -- Further --
+      -------------
+
+      procedure Further (Item : in Stream_Element_Array) is
+
+         procedure Compare (Item : in Stream_Element_Array);
+
+         -------------
+         -- Compare --
+         -------------
+
+         procedure Compare (Item : in Stream_Element_Array) is
+            Next_First : Stream_Element_Offset := Compare_First + Item'Length;
+         begin
+            if Buffer (Compare_First .. Next_First - 1) /= Item then
+               raise Program_Error;
+            end if;
+
+            Compare_First := Next_First;
+         end Compare;
+
+         procedure Compare_Write is new ZLib.Write (Write => Compare);
+      begin
+         Compare_Write (Inflate, Item, No_Flush);
+      end Further;
+
+      -----------------
+      -- Read_Buffer --
+      -----------------
+
+      procedure Read_Buffer
+        (Item : out Ada.Streams.Stream_Element_Array;
+         Last : out Ada.Streams.Stream_Element_Offset)
+      is
+         Buff_Diff   : Stream_Element_Offset := Buffer'Last - Buffer_First;
+         Next_First : Stream_Element_Offset;
+      begin
+         if Item'Length <= Buff_Diff then
+            Last := Item'Last;
+
+            Next_First := Buffer_First + Item'Length;
+
+            Item := Buffer (Buffer_First .. Next_First - 1);
+
+            Buffer_First := Next_First;
+         else
+            Last := Item'First + Buff_Diff;
+            Item (Item'First .. Last) := Buffer (Buffer_First .. Buffer'Last);
+            Buffer_First := Buffer'Last + 1;
+         end if;
+      end Read_Buffer;
+
+      procedure Translate is new Generic_Translate
+                                   (Data_In  => Read_Buffer,
+                                    Data_Out => Further);
+
+   begin
+      Random_Elements.Reset (Gen);
+
+      Buffer := (others => 20);
+
+      Main : loop
+         for J in Buffer'Range loop
+            Buffer (J) := Random_Elements.Random (Gen);
+
+            Deflate_Init (Deflate);
+            Inflate_Init (Inflate);
+
+            Buffer_First  := Buffer'First;
+            Compare_First := Buffer'First;
+
+            Translate (Deflate);
+
+            if Compare_First /= Buffer'Last + 1 then
+               raise Program_Error;
+            end if;
+
+            Ada.Text_IO.Put_Line
+              (Ada.Task_Identification.Image
+                 (Ada.Task_Identification.Current_Task)
+               & Stream_Element_Offset'Image (J)
+               & ZLib.Count'Image (Total_Out (Deflate)));
+
+            Close (Deflate);
+            Close (Inflate);
+
+            exit Main when Stop;
+         end loop;
+      end loop Main;
+   exception
+      when E : others =>
+         Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E));
+         Stop := True;
+   end Test_Task;
+
+   Test : array (1 .. 4) of Test_Task;
+
+   pragma Unreferenced (Test);
+
+   Dummy : Character;
+
+begin
+   Ada.Text_IO.Get_Immediate (Dummy);
+   Stop := True;
+end MTest;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/read.adb b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/read.adb
new file mode 100644 (file)
index 0000000..1f2efbf
--- /dev/null
@@ -0,0 +1,156 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2003 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+
+--  $Id: read.adb,v 1.8 2004/05/31 10:53:40 vagul Exp $
+
+--  Test/demo program for the generic read interface.
+
+with Ada.Numerics.Discrete_Random;
+with Ada.Streams;
+with Ada.Text_IO;
+
+with ZLib;
+
+procedure Read is
+
+   use Ada.Streams;
+
+   ------------------------------------
+   --  Test configuration parameters --
+   ------------------------------------
+
+   File_Size   : Stream_Element_Offset := 100_000;
+
+   Continuous  : constant Boolean          := False;
+   --  If this constant is True, the test would be repeated again and again,
+   --  with increment File_Size for every iteration.
+
+   Header      : constant ZLib.Header_Type := ZLib.Default;
+   --  Do not use Header other than Default in ZLib versions 1.1.4 and older.
+
+   Init_Random : constant := 8;
+   --  We are using the same random sequence, in case of we catch bug,
+   --  so we would be able to reproduce it.
+
+   -- End --
+
+   Pack_Size : Stream_Element_Offset;
+   Offset    : Stream_Element_Offset;
+
+   Filter     : ZLib.Filter_Type;
+
+   subtype Visible_Symbols
+      is Stream_Element range 16#20# .. 16#7E#;
+
+   package Random_Elements is new
+      Ada.Numerics.Discrete_Random (Visible_Symbols);
+
+   Gen : Random_Elements.Generator;
+   Period  : constant Stream_Element_Offset := 200;
+   --  Period constant variable for random generator not to be very random.
+   --  Bigger period, harder random.
+
+   Read_Buffer : Stream_Element_Array (1 .. 2048);
+   Read_First  : Stream_Element_Offset;
+   Read_Last   : Stream_Element_Offset;
+
+   procedure Reset;
+
+   procedure Read
+     (Item : out Stream_Element_Array;
+      Last : out Stream_Element_Offset);
+   --  this procedure is for generic instantiation of
+   --  ZLib.Read
+   --  reading data from the File_In.
+
+   procedure Read is new ZLib.Read
+                           (Read,
+                            Read_Buffer,
+                            Rest_First => Read_First,
+                            Rest_Last  => Read_Last);
+
+   ----------
+   -- Read --
+   ----------
+
+   procedure Read
+     (Item : out Stream_Element_Array;
+      Last : out Stream_Element_Offset) is
+   begin
+      Last := Stream_Element_Offset'Min
+               (Item'Last,
+                Item'First + File_Size - Offset);
+
+      for J in Item'First .. Last loop
+         if J < Item'First + Period then
+            Item (J) := Random_Elements.Random (Gen);
+         else
+            Item (J) := Item (J - Period);
+         end if;
+
+         Offset   := Offset + 1;
+      end loop;
+   end Read;
+
+   -----------
+   -- Reset --
+   -----------
+
+   procedure Reset is
+   begin
+      Random_Elements.Reset (Gen, Init_Random);
+      Pack_Size := 0;
+      Offset := 1;
+      Read_First := Read_Buffer'Last + 1;
+      Read_Last  := Read_Buffer'Last;
+   end Reset;
+
+begin
+   Ada.Text_IO.Put_Line ("ZLib " & ZLib.Version);
+
+   loop
+      for Level in ZLib.Compression_Level'Range loop
+
+         Ada.Text_IO.Put ("Level ="
+            & ZLib.Compression_Level'Image (Level));
+
+         --  Deflate using generic instantiation.
+
+         ZLib.Deflate_Init
+               (Filter,
+                Level,
+                Header => Header);
+
+         Reset;
+
+         Ada.Text_IO.Put
+           (Stream_Element_Offset'Image (File_Size) & " ->");
+
+         loop
+            declare
+               Buffer : Stream_Element_Array (1 .. 1024);
+               Last   : Stream_Element_Offset;
+            begin
+               Read (Filter, Buffer, Last);
+
+               Pack_Size := Pack_Size + Last - Buffer'First + 1;
+
+               exit when Last < Buffer'Last;
+            end;
+         end loop;
+
+         Ada.Text_IO.Put_Line (Stream_Element_Offset'Image (Pack_Size));
+
+         ZLib.Close (Filter);
+      end loop;
+
+      exit when not Continuous;
+
+      File_Size := File_Size + 1;
+   end loop;
+end Read;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/readme.txt
new file mode 100644 (file)
index 0000000..ce4d2ca
--- /dev/null
@@ -0,0 +1,65 @@
+                        ZLib for Ada thick binding (ZLib.Ada)
+                        Release 1.3
+
+ZLib.Ada is a thick binding interface to the popular ZLib data
+compression library, available at http://www.gzip.org/zlib/.
+It provides Ada-style access to the ZLib C library.
+
+
+        Here are the main changes since ZLib.Ada 1.2:
+
+- Attension: ZLib.Read generic routine have a initialization requirement
+  for Read_Last parameter now. It is a bit incompartible with previous version,
+  but extends functionality, we could use new parameters Allow_Read_Some and
+  Flush now.
+
+- Added Is_Open routines to ZLib and ZLib.Streams packages.
+
+- Add pragma Assert to check Stream_Element is 8 bit.
+
+- Fix extraction to buffer with exact known decompressed size. Error reported by
+  Steve Sangwine.
+
+- Fix definition of ULong (changed to unsigned_long), fix regression on 64 bits
+  computers. Patch provided by Pascal Obry.
+
+- Add Status_Error exception definition.
+
+- Add pragma Assertion that Ada.Streams.Stream_Element size is 8 bit.
+
+
+        How to build ZLib.Ada under GNAT
+
+You should have the ZLib library already build on your computer, before
+building ZLib.Ada. Make the directory of ZLib.Ada sources current and
+issue the command:
+
+  gnatmake test -largs -L<directory where libz.a is> -lz
+
+Or use the GNAT project file build for GNAT 3.15 or later:
+
+  gnatmake -Pzlib.gpr -L<directory where libz.a is>
+
+
+        How to build ZLib.Ada under Aonix ObjectAda for Win32 7.2.2
+
+1. Make a project with all *.ads and *.adb files from the distribution.
+2. Build the libz.a library from the ZLib C sources.
+3. Rename libz.a to z.lib.
+4. Add the library z.lib to the project.
+5. Add the libc.lib library from the ObjectAda distribution to the project.
+6. Build the executable using test.adb as a main procedure.
+
+
+        How to use ZLib.Ada
+
+The source files test.adb and read.adb are small demo programs that show
+the main functionality of ZLib.Ada.
+
+The routines from the package specifications are commented.
+
+
+Homepage: http://zlib-ada.sourceforge.net/
+Author: Dmitriy Anisimkov <anisimkov@yahoo.com>
+
+Contributors: Pascal Obry <pascal@obry.org>, Steve Sangwine <sjs@essex.ac.uk>
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/test.adb b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/test.adb
new file mode 100644 (file)
index 0000000..90773ac
--- /dev/null
@@ -0,0 +1,463 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2003 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+
+--  $Id: test.adb,v 1.17 2003/08/12 12:13:30 vagul Exp $
+
+--  The program has a few aims.
+--  1. Test ZLib.Ada95 thick binding functionality.
+--  2. Show the example of use main functionality of the ZLib.Ada95 binding.
+--  3. Build this program automatically compile all ZLib.Ada95 packages under
+--     GNAT Ada95 compiler.
+
+with ZLib.Streams;
+with Ada.Streams.Stream_IO;
+with Ada.Numerics.Discrete_Random;
+
+with Ada.Text_IO;
+
+with Ada.Calendar;
+
+procedure Test is
+
+   use Ada.Streams;
+   use Stream_IO;
+
+   ------------------------------------
+   --  Test configuration parameters --
+   ------------------------------------
+
+   File_Size   : Count   := 100_000;
+   Continuous  : constant Boolean := False;
+
+   Header      : constant ZLib.Header_Type := ZLib.Default;
+                                              --  ZLib.None;
+                                              --  ZLib.Auto;
+                                              --  ZLib.GZip;
+   --  Do not use Header other then Default in ZLib versions 1.1.4
+   --  and older.
+
+   Strategy    : constant ZLib.Strategy_Type := ZLib.Default_Strategy;
+   Init_Random : constant := 10;
+
+   -- End --
+
+   In_File_Name  : constant String := "testzlib.in";
+   --  Name of the input file
+
+   Z_File_Name   : constant String := "testzlib.zlb";
+   --  Name of the compressed file.
+
+   Out_File_Name : constant String := "testzlib.out";
+   --  Name of the decompressed file.
+
+   File_In   : File_Type;
+   File_Out  : File_Type;
+   File_Back : File_Type;
+   File_Z    : ZLib.Streams.Stream_Type;
+
+   Filter : ZLib.Filter_Type;
+
+   Time_Stamp : Ada.Calendar.Time;
+
+   procedure Generate_File;
+   --  Generate file of spetsified size with some random data.
+   --  The random data is repeatable, for the good compression.
+
+   procedure Compare_Streams
+     (Left, Right : in out Root_Stream_Type'Class);
+   --  The procedure compearing data in 2 streams.
+   --  It is for compare data before and after compression/decompression.
+
+   procedure Compare_Files (Left, Right : String);
+   --  Compare files. Based on the Compare_Streams.
+
+   procedure Copy_Streams
+     (Source, Target : in out Root_Stream_Type'Class;
+      Buffer_Size    : in     Stream_Element_Offset := 1024);
+   --  Copying data from one stream to another. It is for test stream
+   --  interface of the library.
+
+   procedure Data_In
+     (Item : out Stream_Element_Array;
+      Last : out Stream_Element_Offset);
+   --  this procedure is for generic instantiation of
+   --  ZLib.Generic_Translate.
+   --  reading data from the File_In.
+
+   procedure Data_Out (Item : in Stream_Element_Array);
+   --  this procedure is for generic instantiation of
+   --  ZLib.Generic_Translate.
+   --  writing data to the File_Out.
+
+   procedure Stamp;
+   --  Store the timestamp to the local variable.
+
+   procedure Print_Statistic (Msg : String; Data_Size : ZLib.Count);
+   --  Print the time statistic with the message.
+
+   procedure Translate is new ZLib.Generic_Translate
+                                (Data_In  => Data_In,
+                                 Data_Out => Data_Out);
+   --  This procedure is moving data from File_In to File_Out
+   --  with compression or decompression, depend on initialization of
+   --  Filter parameter.
+
+   -------------------
+   -- Compare_Files --
+   -------------------
+
+   procedure Compare_Files (Left, Right : String) is
+      Left_File, Right_File : File_Type;
+   begin
+      Open (Left_File, In_File, Left);
+      Open (Right_File, In_File, Right);
+      Compare_Streams (Stream (Left_File).all, Stream (Right_File).all);
+      Close (Left_File);
+      Close (Right_File);
+   end Compare_Files;
+
+   ---------------------
+   -- Compare_Streams --
+   ---------------------
+
+   procedure Compare_Streams
+     (Left, Right : in out Ada.Streams.Root_Stream_Type'Class)
+   is
+      Left_Buffer, Right_Buffer : Stream_Element_Array (0 .. 16#FFF#);
+      Left_Last, Right_Last : Stream_Element_Offset;
+   begin
+      loop
+         Read (Left, Left_Buffer, Left_Last);
+         Read (Right, Right_Buffer, Right_Last);
+
+         if Left_Last /= Right_Last then
+            Ada.Text_IO.Put_Line ("Compare error :"
+              & Stream_Element_Offset'Image (Left_Last)
+              & " /= "
+              & Stream_Element_Offset'Image (Right_Last));
+
+            raise Constraint_Error;
+
+         elsif Left_Buffer (0 .. Left_Last)
+               /= Right_Buffer (0 .. Right_Last)
+         then
+            Ada.Text_IO.Put_Line ("ERROR: IN and OUT files is not equal.");
+            raise Constraint_Error;
+
+         end if;
+
+         exit when Left_Last < Left_Buffer'Last;
+      end loop;
+   end Compare_Streams;
+
+   ------------------
+   -- Copy_Streams --
+   ------------------
+
+   procedure Copy_Streams
+     (Source, Target : in out Ada.Streams.Root_Stream_Type'Class;
+      Buffer_Size    : in     Stream_Element_Offset := 1024)
+   is
+      Buffer : Stream_Element_Array (1 .. Buffer_Size);
+      Last   : Stream_Element_Offset;
+   begin
+      loop
+         Read  (Source, Buffer, Last);
+         Write (Target, Buffer (1 .. Last));
+
+         exit when Last < Buffer'Last;
+      end loop;
+   end Copy_Streams;
+
+   -------------
+   -- Data_In --
+   -------------
+
+   procedure Data_In
+     (Item : out Stream_Element_Array;
+      Last : out Stream_Element_Offset) is
+   begin
+      Read (File_In, Item, Last);
+   end Data_In;
+
+   --------------
+   -- Data_Out --
+   --------------
+
+   procedure Data_Out (Item : in Stream_Element_Array) is
+   begin
+      Write (File_Out, Item);
+   end Data_Out;
+
+   -------------------
+   -- Generate_File --
+   -------------------
+
+   procedure Generate_File is
+      subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#;
+
+      package Random_Elements is
+         new Ada.Numerics.Discrete_Random (Visible_Symbols);
+
+      Gen    : Random_Elements.Generator;
+      Buffer : Stream_Element_Array := (1 .. 77 => 16#20#) & 10;
+
+      Buffer_Count : constant Count := File_Size / Buffer'Length;
+      --  Number of same buffers in the packet.
+
+      Density : constant Count := 30; --  from 0 to Buffer'Length - 2;
+
+      procedure Fill_Buffer (J, D : in Count);
+      --  Change the part of the buffer.
+
+      -----------------
+      -- Fill_Buffer --
+      -----------------
+
+      procedure Fill_Buffer (J, D : in Count) is
+      begin
+         for K in 0 .. D loop
+            Buffer
+              (Stream_Element_Offset ((J + K) mod (Buffer'Length - 1) + 1))
+             := Random_Elements.Random (Gen);
+
+         end loop;
+      end Fill_Buffer;
+
+   begin
+      Random_Elements.Reset (Gen, Init_Random);
+
+      Create (File_In, Out_File, In_File_Name);
+
+      Fill_Buffer (1, Buffer'Length - 2);
+
+      for J in 1 .. Buffer_Count loop
+         Write (File_In, Buffer);
+
+         Fill_Buffer (J, Density);
+      end loop;
+
+      --  fill remain size.
+
+      Write
+        (File_In,
+         Buffer
+           (1 .. Stream_Element_Offset
+                   (File_Size - Buffer'Length * Buffer_Count)));
+
+      Flush (File_In);
+      Close (File_In);
+   end Generate_File;
+
+   ---------------------
+   -- Print_Statistic --
+   ---------------------
+
+   procedure Print_Statistic (Msg : String; Data_Size : ZLib.Count) is
+      use Ada.Calendar;
+      use Ada.Text_IO;
+
+      package Count_IO is new Integer_IO (ZLib.Count);
+
+      Curr_Dur : Duration := Clock - Time_Stamp;
+   begin
+      Put (Msg);
+
+      Set_Col (20);
+      Ada.Text_IO.Put ("size =");
+
+      Count_IO.Put
+        (Data_Size,
+         Width => Stream_IO.Count'Image (File_Size)'Length);
+
+      Put_Line (" duration =" & Duration'Image (Curr_Dur));
+   end Print_Statistic;
+
+   -----------
+   -- Stamp --
+   -----------
+
+   procedure Stamp is
+   begin
+      Time_Stamp := Ada.Calendar.Clock;
+   end Stamp;
+
+begin
+   Ada.Text_IO.Put_Line ("ZLib " & ZLib.Version);
+
+   loop
+      Generate_File;
+
+      for Level in ZLib.Compression_Level'Range loop
+
+         Ada.Text_IO.Put_Line ("Level ="
+            & ZLib.Compression_Level'Image (Level));
+
+         --  Test generic interface.
+         Open   (File_In, In_File, In_File_Name);
+         Create (File_Out, Out_File, Z_File_Name);
+
+         Stamp;
+
+         --  Deflate using generic instantiation.
+
+         ZLib.Deflate_Init
+               (Filter   => Filter,
+                Level    => Level,
+                Strategy => Strategy,
+                Header   => Header);
+
+         Translate (Filter);
+         Print_Statistic ("Generic compress", ZLib.Total_Out (Filter));
+         ZLib.Close (Filter);
+
+         Close (File_In);
+         Close (File_Out);
+
+         Open   (File_In, In_File, Z_File_Name);
+         Create (File_Out, Out_File, Out_File_Name);
+
+         Stamp;
+
+         --  Inflate using generic instantiation.
+
+         ZLib.Inflate_Init (Filter, Header => Header);
+
+         Translate (Filter);
+         Print_Statistic ("Generic decompress", ZLib.Total_Out (Filter));
+
+         ZLib.Close (Filter);
+
+         Close (File_In);
+         Close (File_Out);
+
+         Compare_Files (In_File_Name, Out_File_Name);
+
+         --  Test stream interface.
+
+         --  Compress to the back stream.
+
+         Open   (File_In, In_File, In_File_Name);
+         Create (File_Back, Out_File, Z_File_Name);
+
+         Stamp;
+
+         ZLib.Streams.Create
+           (Stream          => File_Z,
+            Mode            => ZLib.Streams.Out_Stream,
+            Back            => ZLib.Streams.Stream_Access
+                                 (Stream (File_Back)),
+            Back_Compressed => True,
+            Level           => Level,
+            Strategy        => Strategy,
+            Header          => Header);
+
+         Copy_Streams
+           (Source => Stream (File_In).all,
+            Target => File_Z);
+
+         --  Flushing internal buffers to the back stream.
+
+         ZLib.Streams.Flush (File_Z, ZLib.Finish);
+
+         Print_Statistic ("Write compress",
+                          ZLib.Streams.Write_Total_Out (File_Z));
+
+         ZLib.Streams.Close (File_Z);
+
+         Close (File_In);
+         Close (File_Back);
+
+         --  Compare reading from original file and from
+         --  decompression stream.
+
+         Open (File_In,   In_File, In_File_Name);
+         Open (File_Back, In_File, Z_File_Name);
+
+         ZLib.Streams.Create
+           (Stream          => File_Z,
+            Mode            => ZLib.Streams.In_Stream,
+            Back            => ZLib.Streams.Stream_Access
+                                 (Stream (File_Back)),
+            Back_Compressed => True,
+            Header          => Header);
+
+         Stamp;
+         Compare_Streams (Stream (File_In).all, File_Z);
+
+         Print_Statistic ("Read decompress",
+                          ZLib.Streams.Read_Total_Out (File_Z));
+
+         ZLib.Streams.Close (File_Z);
+         Close (File_In);
+         Close (File_Back);
+
+         --  Compress by reading from compression stream.
+
+         Open (File_Back, In_File, In_File_Name);
+         Create (File_Out, Out_File, Z_File_Name);
+
+         ZLib.Streams.Create
+           (Stream          => File_Z,
+            Mode            => ZLib.Streams.In_Stream,
+            Back            => ZLib.Streams.Stream_Access
+                                 (Stream (File_Back)),
+            Back_Compressed => False,
+            Level           => Level,
+            Strategy        => Strategy,
+            Header          => Header);
+
+         Stamp;
+         Copy_Streams
+           (Source => File_Z,
+            Target => Stream (File_Out).all);
+
+         Print_Statistic ("Read compress",
+                          ZLib.Streams.Read_Total_Out (File_Z));
+
+         ZLib.Streams.Close (File_Z);
+
+         Close (File_Out);
+         Close (File_Back);
+
+         --  Decompress to decompression stream.
+
+         Open   (File_In,   In_File, Z_File_Name);
+         Create (File_Back, Out_File, Out_File_Name);
+
+         ZLib.Streams.Create
+           (Stream          => File_Z,
+            Mode            => ZLib.Streams.Out_Stream,
+            Back            => ZLib.Streams.Stream_Access
+                                 (Stream (File_Back)),
+            Back_Compressed => False,
+            Header          => Header);
+
+         Stamp;
+
+         Copy_Streams
+           (Source => Stream (File_In).all,
+            Target => File_Z);
+
+         Print_Statistic ("Write decompress",
+                          ZLib.Streams.Write_Total_Out (File_Z));
+
+         ZLib.Streams.Close (File_Z);
+         Close (File_In);
+         Close (File_Back);
+
+         Compare_Files (In_File_Name, Out_File_Name);
+      end loop;
+
+      Ada.Text_IO.Put_Line (Count'Image (File_Size) & " Ok.");
+
+      exit when not Continuous;
+
+      File_Size := File_Size + 1;
+   end loop;
+end Test;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-streams.adb b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-streams.adb
new file mode 100644 (file)
index 0000000..b6497ba
--- /dev/null
@@ -0,0 +1,225 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2003 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+
+--  $Id: zlib-streams.adb,v 1.10 2004/05/31 10:53:40 vagul Exp $
+
+with Ada.Unchecked_Deallocation;
+
+package body ZLib.Streams is
+
+   -----------
+   -- Close --
+   -----------
+
+   procedure Close (Stream : in out Stream_Type) is
+      procedure Free is new Ada.Unchecked_Deallocation
+         (Stream_Element_Array, Buffer_Access);
+   begin
+      if Stream.Mode = Out_Stream or Stream.Mode = Duplex then
+         --  We should flush the data written by the writer.
+
+         Flush (Stream, Finish);
+
+         Close (Stream.Writer);
+      end if;
+
+      if Stream.Mode = In_Stream or Stream.Mode = Duplex then
+         Close (Stream.Reader);
+         Free (Stream.Buffer);
+      end if;
+   end Close;
+
+   ------------
+   -- Create --
+   ------------
+
+   procedure Create
+     (Stream            :    out Stream_Type;
+      Mode              : in     Stream_Mode;
+      Back              : in     Stream_Access;
+      Back_Compressed   : in     Boolean;
+      Level             : in     Compression_Level := Default_Compression;
+      Strategy          : in     Strategy_Type     := Default_Strategy;
+      Header            : in     Header_Type       := Default;
+      Read_Buffer_Size  : in     Ada.Streams.Stream_Element_Offset
+                                    := Default_Buffer_Size;
+      Write_Buffer_Size : in     Ada.Streams.Stream_Element_Offset
+                                    := Default_Buffer_Size)
+   is
+
+      subtype Buffer_Subtype is Stream_Element_Array (1 .. Read_Buffer_Size);
+
+      procedure Init_Filter
+         (Filter   : in out Filter_Type;
+          Compress : in     Boolean);
+
+      -----------------
+      -- Init_Filter --
+      -----------------
+
+      procedure Init_Filter
+         (Filter   : in out Filter_Type;
+          Compress : in     Boolean) is
+      begin
+         if Compress then
+            Deflate_Init
+              (Filter, Level, Strategy, Header => Header);
+         else
+            Inflate_Init (Filter, Header => Header);
+         end if;
+      end Init_Filter;
+
+   begin
+      Stream.Back := Back;
+      Stream.Mode := Mode;
+
+      if Mode = Out_Stream or Mode = Duplex then
+         Init_Filter (Stream.Writer, Back_Compressed);
+         Stream.Buffer_Size := Write_Buffer_Size;
+      else
+         Stream.Buffer_Size := 0;
+      end if;
+
+      if Mode = In_Stream or Mode = Duplex then
+         Init_Filter (Stream.Reader, not Back_Compressed);
+
+         Stream.Buffer     := new Buffer_Subtype;
+         Stream.Rest_First := Stream.Buffer'Last + 1;
+         Stream.Rest_Last  := Stream.Buffer'Last;
+      end if;
+   end Create;
+
+   -----------
+   -- Flush --
+   -----------
+
+   procedure Flush
+     (Stream : in out Stream_Type;
+      Mode   : in     Flush_Mode := Sync_Flush)
+   is
+      Buffer : Stream_Element_Array (1 .. Stream.Buffer_Size);
+      Last   : Stream_Element_Offset;
+   begin
+      loop
+         Flush (Stream.Writer, Buffer, Last, Mode);
+
+         Ada.Streams.Write (Stream.Back.all, Buffer (1 .. Last));
+
+         exit when Last < Buffer'Last;
+      end loop;
+   end Flush;
+
+   -------------
+   -- Is_Open --
+   -------------
+
+   function Is_Open (Stream : Stream_Type) return Boolean is
+   begin
+      return Is_Open (Stream.Reader) or else Is_Open (Stream.Writer);
+   end Is_Open;
+
+   ----------
+   -- Read --
+   ----------
+
+   procedure Read
+     (Stream : in out Stream_Type;
+      Item   :    out Stream_Element_Array;
+      Last   :    out Stream_Element_Offset)
+   is
+
+      procedure Read
+        (Item : out Stream_Element_Array;
+         Last : out Stream_Element_Offset);
+
+      ----------
+      -- Read --
+      ----------
+
+      procedure Read
+        (Item : out Stream_Element_Array;
+         Last : out Stream_Element_Offset) is
+      begin
+         Ada.Streams.Read (Stream.Back.all, Item, Last);
+      end Read;
+
+      procedure Read is new ZLib.Read
+         (Read       => Read,
+          Buffer     => Stream.Buffer.all,
+          Rest_First => Stream.Rest_First,
+          Rest_Last  => Stream.Rest_Last);
+
+   begin
+      Read (Stream.Reader, Item, Last);
+   end Read;
+
+   -------------------
+   -- Read_Total_In --
+   -------------------
+
+   function Read_Total_In (Stream : in Stream_Type) return Count is
+   begin
+      return Total_In (Stream.Reader);
+   end Read_Total_In;
+
+   --------------------
+   -- Read_Total_Out --
+   --------------------
+
+   function Read_Total_Out (Stream : in Stream_Type) return Count is
+   begin
+      return Total_Out (Stream.Reader);
+   end Read_Total_Out;
+
+   -----------
+   -- Write --
+   -----------
+
+   procedure Write
+     (Stream : in out Stream_Type;
+      Item   : in     Stream_Element_Array)
+   is
+
+      procedure Write (Item : in Stream_Element_Array);
+
+      -----------
+      -- Write --
+      -----------
+
+      procedure Write (Item : in Stream_Element_Array) is
+      begin
+         Ada.Streams.Write (Stream.Back.all, Item);
+      end Write;
+
+      procedure Write is new ZLib.Write
+         (Write       => Write,
+          Buffer_Size => Stream.Buffer_Size);
+
+   begin
+      Write (Stream.Writer, Item, No_Flush);
+   end Write;
+
+   --------------------
+   -- Write_Total_In --
+   --------------------
+
+   function Write_Total_In (Stream : in Stream_Type) return Count is
+   begin
+      return Total_In (Stream.Writer);
+   end Write_Total_In;
+
+   ---------------------
+   -- Write_Total_Out --
+   ---------------------
+
+   function Write_Total_Out (Stream : in Stream_Type) return Count is
+   begin
+      return Total_Out (Stream.Writer);
+   end Write_Total_Out;
+
+end ZLib.Streams;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-streams.ads b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-streams.ads
new file mode 100644 (file)
index 0000000..f0193c6
--- /dev/null
@@ -0,0 +1,114 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2003 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+
+--  $Id: zlib-streams.ads,v 1.12 2004/05/31 10:53:40 vagul Exp $
+
+package ZLib.Streams is
+
+   type Stream_Mode is (In_Stream, Out_Stream, Duplex);
+
+   type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class;
+
+   type Stream_Type is
+      new Ada.Streams.Root_Stream_Type with private;
+
+   procedure Read
+     (Stream : in out Stream_Type;
+      Item   :    out Ada.Streams.Stream_Element_Array;
+      Last   :    out Ada.Streams.Stream_Element_Offset);
+
+   procedure Write
+     (Stream : in out Stream_Type;
+      Item   : in     Ada.Streams.Stream_Element_Array);
+
+   procedure Flush
+     (Stream : in out Stream_Type;
+      Mode   : in     Flush_Mode := Sync_Flush);
+   --  Flush the written data to the back stream,
+   --  all data placed to the compressor is flushing to the Back stream.
+   --  Should not be used untill necessary, becouse it is decreasing
+   --  compression.
+
+   function Read_Total_In (Stream : in Stream_Type) return Count;
+   pragma Inline (Read_Total_In);
+   --  Return total number of bytes read from back stream so far.
+
+   function Read_Total_Out (Stream : in Stream_Type) return Count;
+   pragma Inline (Read_Total_Out);
+   --  Return total number of bytes read so far.
+
+   function Write_Total_In (Stream : in Stream_Type) return Count;
+   pragma Inline (Write_Total_In);
+   --  Return total number of bytes written so far.
+
+   function Write_Total_Out (Stream : in Stream_Type) return Count;
+   pragma Inline (Write_Total_Out);
+   --  Return total number of bytes written to the back stream.
+
+   procedure Create
+     (Stream            :    out Stream_Type;
+      Mode              : in     Stream_Mode;
+      Back              : in     Stream_Access;
+      Back_Compressed   : in     Boolean;
+      Level             : in     Compression_Level := Default_Compression;
+      Strategy          : in     Strategy_Type     := Default_Strategy;
+      Header            : in     Header_Type       := Default;
+      Read_Buffer_Size  : in     Ada.Streams.Stream_Element_Offset
+                                    := Default_Buffer_Size;
+      Write_Buffer_Size : in     Ada.Streams.Stream_Element_Offset
+                                    := Default_Buffer_Size);
+   --  Create the Comression/Decompression stream.
+   --  If mode is In_Stream then Write operation is disabled.
+   --  If mode is Out_Stream then Read operation is disabled.
+
+   --  If Back_Compressed is true then
+   --  Data written to the Stream is compressing to the Back stream
+   --  and data read from the Stream is decompressed data from the Back stream.
+
+   --  If Back_Compressed is false then
+   --  Data written to the Stream is decompressing to the Back stream
+   --  and data read from the Stream is compressed data from the Back stream.
+
+   --  !!! When the Need_Header is False ZLib-Ada is using undocumented
+   --  ZLib 1.1.4 functionality to do not create/wait for ZLib headers.
+
+   function Is_Open (Stream : Stream_Type) return Boolean;
+
+   procedure Close (Stream : in out Stream_Type);
+
+private
+
+   use Ada.Streams;
+
+   type Buffer_Access is access all Stream_Element_Array;
+
+   type Stream_Type
+     is new Root_Stream_Type with
+   record
+      Mode       : Stream_Mode;
+
+      Buffer     : Buffer_Access;
+      Rest_First : Stream_Element_Offset;
+      Rest_Last  : Stream_Element_Offset;
+      --  Buffer for Read operation.
+      --  We need to have this buffer in the record
+      --  becouse not all read data from back stream
+      --  could be processed during the read operation.
+
+      Buffer_Size : Stream_Element_Offset;
+      --  Buffer size for write operation.
+      --  We do not need to have this buffer
+      --  in the record becouse all data could be
+      --  processed in the write operation.
+
+      Back       : Stream_Access;
+      Reader     : Filter_Type;
+      Writer     : Filter_Type;
+   end record;
+
+end ZLib.Streams;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-thin.adb b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-thin.adb
new file mode 100644 (file)
index 0000000..0ca4a71
--- /dev/null
@@ -0,0 +1,141 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2003 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+
+--  $Id: zlib-thin.adb,v 1.8 2003/12/14 18:27:31 vagul Exp $
+
+package body ZLib.Thin is
+
+   ZLIB_VERSION  : constant Chars_Ptr := zlibVersion;
+
+   Z_Stream_Size : constant Int := Z_Stream'Size / System.Storage_Unit;
+
+   --------------
+   -- Avail_In --
+   --------------
+
+   function Avail_In (Strm : in Z_Stream) return UInt is
+   begin
+      return Strm.Avail_In;
+   end Avail_In;
+
+   ---------------
+   -- Avail_Out --
+   ---------------
+
+   function Avail_Out (Strm : in Z_Stream) return UInt is
+   begin
+      return Strm.Avail_Out;
+   end Avail_Out;
+
+   ------------------
+   -- Deflate_Init --
+   ------------------
+
+   function Deflate_Init
+     (strm       : Z_Streamp;
+      level      : Int;
+      method     : Int;
+      windowBits : Int;
+      memLevel   : Int;
+      strategy   : Int)
+      return       Int is
+   begin
+      return deflateInit2
+               (strm,
+                level,
+                method,
+                windowBits,
+                memLevel,
+                strategy,
+                ZLIB_VERSION,
+                Z_Stream_Size);
+   end Deflate_Init;
+
+   ------------------
+   -- Inflate_Init --
+   ------------------
+
+   function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int is
+   begin
+      return inflateInit2 (strm, windowBits, ZLIB_VERSION, Z_Stream_Size);
+   end Inflate_Init;
+
+   ------------------------
+   -- Last_Error_Message --
+   ------------------------
+
+   function Last_Error_Message (Strm : in Z_Stream) return String is
+      use Interfaces.C.Strings;
+   begin
+      if Strm.msg = Null_Ptr then
+         return "";
+      else
+         return Value (Strm.msg);
+      end if;
+   end Last_Error_Message;
+
+   ------------
+   -- Set_In --
+   ------------
+
+   procedure Set_In
+     (Strm   : in out Z_Stream;
+      Buffer : in     Voidp;
+      Size   : in     UInt) is
+   begin
+      Strm.Next_In  := Buffer;
+      Strm.Avail_In := Size;
+   end Set_In;
+
+   ------------------
+   -- Set_Mem_Func --
+   ------------------
+
+   procedure Set_Mem_Func
+     (Strm   : in out Z_Stream;
+      Opaque : in     Voidp;
+      Alloc  : in     alloc_func;
+      Free   : in     free_func) is
+   begin
+      Strm.opaque := Opaque;
+      Strm.zalloc := Alloc;
+      Strm.zfree  := Free;
+   end Set_Mem_Func;
+
+   -------------
+   -- Set_Out --
+   -------------
+
+   procedure Set_Out
+     (Strm   : in out Z_Stream;
+      Buffer : in     Voidp;
+      Size   : in     UInt) is
+   begin
+      Strm.Next_Out  := Buffer;
+      Strm.Avail_Out := Size;
+   end Set_Out;
+
+   --------------
+   -- Total_In --
+   --------------
+
+   function Total_In (Strm : in Z_Stream) return ULong is
+   begin
+      return Strm.Total_In;
+   end Total_In;
+
+   ---------------
+   -- Total_Out --
+   ---------------
+
+   function Total_Out (Strm : in Z_Stream) return ULong is
+   begin
+      return Strm.Total_Out;
+   end Total_Out;
+
+end ZLib.Thin;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-thin.ads b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib-thin.ads
new file mode 100644 (file)
index 0000000..d4407eb
--- /dev/null
@@ -0,0 +1,450 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2003 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+
+--  $Id: zlib-thin.ads,v 1.11 2004/07/23 06:33:11 vagul Exp $
+
+with Interfaces.C.Strings;
+
+with System;
+
+private package ZLib.Thin is
+
+   --  From zconf.h
+
+   MAX_MEM_LEVEL : constant := 9;         --  zconf.h:105
+                                          --  zconf.h:105
+   MAX_WBITS : constant := 15;      --  zconf.h:115
+                                    --  32K LZ77 window
+                                    --  zconf.h:115
+   SEEK_SET : constant := 8#0000#;  --  zconf.h:244
+                                    --  Seek from beginning of file.
+                                    --  zconf.h:244
+   SEEK_CUR : constant := 1;        --  zconf.h:245
+                                    --  Seek from current position.
+                                    --  zconf.h:245
+   SEEK_END : constant := 2;        --  zconf.h:246
+                                    --  Set file pointer to EOF plus "offset"
+                                    --  zconf.h:246
+
+   type Byte is new Interfaces.C.unsigned_char; --  8 bits
+                                                --  zconf.h:214
+   type UInt is new Interfaces.C.unsigned;      --  16 bits or more
+                                                --  zconf.h:216
+   type Int is new Interfaces.C.int;
+
+   type ULong is new Interfaces.C.unsigned_long;     --  32 bits or more
+                                                     --  zconf.h:217
+   subtype Chars_Ptr is Interfaces.C.Strings.chars_ptr;
+
+   type ULong_Access is access ULong;
+   type Int_Access is access Int;
+
+   subtype Voidp is System.Address;            --  zconf.h:232
+
+   subtype Byte_Access is Voidp;
+
+   Nul : constant Voidp := System.Null_Address;
+   --  end from zconf
+
+   Z_NO_FLUSH : constant := 8#0000#;   --  zlib.h:125
+                                       --  zlib.h:125
+   Z_PARTIAL_FLUSH : constant := 1;       --  zlib.h:126
+                                          --  will be removed, use
+                                          --  Z_SYNC_FLUSH instead
+                                          --  zlib.h:126
+   Z_SYNC_FLUSH : constant := 2;       --  zlib.h:127
+                                       --  zlib.h:127
+   Z_FULL_FLUSH : constant := 3;       --  zlib.h:128
+                                       --  zlib.h:128
+   Z_FINISH : constant := 4;        --  zlib.h:129
+                                    --  zlib.h:129
+   Z_OK : constant := 8#0000#;   --  zlib.h:132
+                                 --  zlib.h:132
+   Z_STREAM_END : constant := 1;       --  zlib.h:133
+                                       --  zlib.h:133
+   Z_NEED_DICT : constant := 2;        --  zlib.h:134
+                                       --  zlib.h:134
+   Z_ERRNO : constant := -1;        --  zlib.h:135
+                                    --  zlib.h:135
+   Z_STREAM_ERROR : constant := -2;       --  zlib.h:136
+                                          --  zlib.h:136
+   Z_DATA_ERROR : constant := -3;      --  zlib.h:137
+                                       --  zlib.h:137
+   Z_MEM_ERROR : constant := -4;       --  zlib.h:138
+                                       --  zlib.h:138
+   Z_BUF_ERROR : constant := -5;       --  zlib.h:139
+                                       --  zlib.h:139
+   Z_VERSION_ERROR : constant := -6;      --  zlib.h:140
+                                          --  zlib.h:140
+   Z_NO_COMPRESSION : constant := 8#0000#;   --  zlib.h:145
+                                             --  zlib.h:145
+   Z_BEST_SPEED : constant := 1;       --  zlib.h:146
+                                       --  zlib.h:146
+   Z_BEST_COMPRESSION : constant := 9;       --  zlib.h:147
+                                             --  zlib.h:147
+   Z_DEFAULT_COMPRESSION : constant := -1;      --  zlib.h:148
+                                                --  zlib.h:148
+   Z_FILTERED : constant := 1;      --  zlib.h:151
+                                    --  zlib.h:151
+   Z_HUFFMAN_ONLY : constant := 2;        --  zlib.h:152
+                                          --  zlib.h:152
+   Z_DEFAULT_STRATEGY : constant := 8#0000#; --  zlib.h:153
+                                             --  zlib.h:153
+   Z_BINARY : constant := 8#0000#;  --  zlib.h:156
+                                    --  zlib.h:156
+   Z_ASCII : constant := 1;      --  zlib.h:157
+                                 --  zlib.h:157
+   Z_UNKNOWN : constant := 2;       --  zlib.h:158
+                                    --  zlib.h:158
+   Z_DEFLATED : constant := 8;      --  zlib.h:161
+                                    --  zlib.h:161
+   Z_NULL : constant := 8#0000#; --  zlib.h:164
+                                 --  for initializing zalloc, zfree, opaque
+                                 --  zlib.h:164
+   type gzFile is new Voidp;                  --  zlib.h:646
+
+   type Z_Stream is private;
+
+   type Z_Streamp is access all Z_Stream;     --  zlib.h:89
+
+   type alloc_func is access function
+     (Opaque : Voidp;
+      Items  : UInt;
+      Size   : UInt)
+      return Voidp; --  zlib.h:63
+
+   type free_func is access procedure (opaque : Voidp; address : Voidp);
+
+   function zlibVersion return Chars_Ptr;
+
+   function Deflate (strm : Z_Streamp; flush : Int) return Int;
+
+   function DeflateEnd (strm : Z_Streamp) return Int;
+
+   function Inflate (strm : Z_Streamp; flush : Int) return Int;
+
+   function InflateEnd (strm : Z_Streamp) return Int;
+
+   function deflateSetDictionary
+     (strm       : Z_Streamp;
+      dictionary : Byte_Access;
+      dictLength : UInt)
+      return       Int;
+
+   function deflateCopy (dest : Z_Streamp; source : Z_Streamp) return Int;
+   --  zlib.h:478
+
+   function deflateReset (strm : Z_Streamp) return Int; -- zlib.h:495
+
+   function deflateParams
+     (strm     : Z_Streamp;
+      level    : Int;
+      strategy : Int)
+      return     Int;       -- zlib.h:506
+
+   function inflateSetDictionary
+     (strm       : Z_Streamp;
+      dictionary : Byte_Access;
+      dictLength : UInt)
+      return       Int; --  zlib.h:548
+
+   function inflateSync (strm : Z_Streamp) return Int;  --  zlib.h:565
+
+   function inflateReset (strm : Z_Streamp) return Int; --  zlib.h:580
+
+   function compress
+     (dest      : Byte_Access;
+      destLen   : ULong_Access;
+      source    : Byte_Access;
+      sourceLen : ULong)
+      return      Int;           -- zlib.h:601
+
+   function compress2
+     (dest      : Byte_Access;
+      destLen   : ULong_Access;
+      source    : Byte_Access;
+      sourceLen : ULong;
+      level     : Int)
+      return      Int;          -- zlib.h:615
+
+   function uncompress
+     (dest      : Byte_Access;
+      destLen   : ULong_Access;
+      source    : Byte_Access;
+      sourceLen : ULong)
+      return      Int;
+
+   function gzopen (path : Chars_Ptr; mode : Chars_Ptr) return gzFile;
+
+   function gzdopen (fd : Int; mode : Chars_Ptr) return gzFile;
+
+   function gzsetparams
+     (file     : gzFile;
+      level    : Int;
+      strategy : Int)
+      return     Int;
+
+   function gzread
+     (file : gzFile;
+      buf  : Voidp;
+      len  : UInt)
+      return Int;
+
+   function gzwrite
+     (file : in gzFile;
+      buf  : in Voidp;
+      len  : in UInt)
+      return Int;
+
+   function gzprintf (file : in gzFile; format : in Chars_Ptr) return Int;
+
+   function gzputs (file : in gzFile; s : in Chars_Ptr) return Int;
+
+   function gzgets
+     (file : gzFile;
+      buf  : Chars_Ptr;
+      len  : Int)
+      return Chars_Ptr;
+
+   function gzputc (file : gzFile; char : Int) return Int;
+
+   function gzgetc (file : gzFile) return Int;
+
+   function gzflush (file : gzFile; flush : Int) return Int;
+
+   function gzseek
+     (file   : gzFile;
+      offset : Int;
+      whence : Int)
+      return   Int;
+
+   function gzrewind (file : gzFile) return Int;
+
+   function gztell (file : gzFile) return Int;
+
+   function gzeof (file : gzFile) return Int;
+
+   function gzclose (file : gzFile) return Int;
+
+   function gzerror (file : gzFile; errnum : Int_Access) return Chars_Ptr;
+
+   function adler32
+     (adler : ULong;
+      buf   : Byte_Access;
+      len   : UInt)
+      return  ULong;
+
+   function crc32
+     (crc  : ULong;
+      buf  : Byte_Access;
+      len  : UInt)
+      return ULong;
+
+   function deflateInit
+     (strm        : Z_Streamp;
+      level       : Int;
+      version     : Chars_Ptr;
+      stream_size : Int)
+      return        Int;
+
+   function deflateInit2
+     (strm        : Z_Streamp;
+      level       : Int;
+      method      : Int;
+      windowBits  : Int;
+      memLevel    : Int;
+      strategy    : Int;
+      version     : Chars_Ptr;
+      stream_size : Int)
+      return        Int;
+
+   function Deflate_Init
+     (strm       : Z_Streamp;
+      level      : Int;
+      method     : Int;
+      windowBits : Int;
+      memLevel   : Int;
+      strategy   : Int)
+      return       Int;
+   pragma Inline (Deflate_Init);
+
+   function inflateInit
+     (strm        : Z_Streamp;
+      version     : Chars_Ptr;
+      stream_size : Int)
+      return        Int;
+
+   function inflateInit2
+     (strm        : in Z_Streamp;
+      windowBits  : in Int;
+      version     : in Chars_Ptr;
+      stream_size : in Int)
+      return      Int;
+
+   function inflateBackInit
+     (strm        : in Z_Streamp;
+      windowBits  : in Int;
+      window      : in Byte_Access;
+      version     : in Chars_Ptr;
+      stream_size : in Int)
+      return      Int;
+   --  Size of window have to be 2**windowBits.
+
+   function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int;
+   pragma Inline (Inflate_Init);
+
+   function zError (err : Int) return Chars_Ptr;
+
+   function inflateSyncPoint (z : Z_Streamp) return Int;
+
+   function get_crc_table return ULong_Access;
+
+   --  Interface to the available fields of the z_stream structure.
+   --  The application must update next_in and avail_in when avail_in has
+   --  dropped to zero. It must update next_out and avail_out when avail_out
+   --  has dropped to zero. The application must initialize zalloc, zfree and
+   --  opaque before calling the init function.
+
+   procedure Set_In
+     (Strm   : in out Z_Stream;
+      Buffer : in Voidp;
+      Size   : in UInt);
+   pragma Inline (Set_In);
+
+   procedure Set_Out
+     (Strm   : in out Z_Stream;
+      Buffer : in Voidp;
+      Size   : in UInt);
+   pragma Inline (Set_Out);
+
+   procedure Set_Mem_Func
+     (Strm   : in out Z_Stream;
+      Opaque : in Voidp;
+      Alloc  : in alloc_func;
+      Free   : in free_func);
+   pragma Inline (Set_Mem_Func);
+
+   function Last_Error_Message (Strm : in Z_Stream) return String;
+   pragma Inline (Last_Error_Message);
+
+   function Avail_Out (Strm : in Z_Stream) return UInt;
+   pragma Inline (Avail_Out);
+
+   function Avail_In (Strm : in Z_Stream) return UInt;
+   pragma Inline (Avail_In);
+
+   function Total_In (Strm : in Z_Stream) return ULong;
+   pragma Inline (Total_In);
+
+   function Total_Out (Strm : in Z_Stream) return ULong;
+   pragma Inline (Total_Out);
+
+   function inflateCopy
+     (dest   : in Z_Streamp;
+      Source : in Z_Streamp)
+      return Int;
+
+   function compressBound (Source_Len : in ULong) return ULong;
+
+   function deflateBound
+     (Strm       : in Z_Streamp;
+      Source_Len : in ULong)
+      return     ULong;
+
+   function gzungetc (C : in Int; File : in  gzFile) return Int;
+
+   function zlibCompileFlags return ULong;
+
+private
+
+   type Z_Stream is record            -- zlib.h:68
+      Next_In   : Voidp      := Nul;  -- next input byte
+      Avail_In  : UInt       := 0;    -- number of bytes available at next_in
+      Total_In  : ULong      := 0;    -- total nb of input bytes read so far
+      Next_Out  : Voidp      := Nul;  -- next output byte should be put there
+      Avail_Out : UInt       := 0;    -- remaining free space at next_out
+      Total_Out : ULong      := 0;    -- total nb of bytes output so far
+      msg       : Chars_Ptr;          -- last error message, NULL if no error
+      state     : Voidp;              -- not visible by applications
+      zalloc    : alloc_func := null; -- used to allocate the internal state
+      zfree     : free_func  := null; -- used to free the internal state
+      opaque    : Voidp;              -- private data object passed to
+                                      --  zalloc and zfree
+      data_type : Int;                -- best guess about the data type:
+                                      --  ascii or binary
+      adler     : ULong;              -- adler32 value of the uncompressed
+                                      --  data
+      reserved  : ULong;              -- reserved for future use
+   end record;
+
+   pragma Convention (C, Z_Stream);
+
+   pragma Import (C, zlibVersion, "zlibVersion");
+   pragma Import (C, Deflate, "deflate");
+   pragma Import (C, DeflateEnd, "deflateEnd");
+   pragma Import (C, Inflate, "inflate");
+   pragma Import (C, InflateEnd, "inflateEnd");
+   pragma Import (C, deflateSetDictionary, "deflateSetDictionary");
+   pragma Import (C, deflateCopy, "deflateCopy");
+   pragma Import (C, deflateReset, "deflateReset");
+   pragma Import (C, deflateParams, "deflateParams");
+   pragma Import (C, inflateSetDictionary, "inflateSetDictionary");
+   pragma Import (C, inflateSync, "inflateSync");
+   pragma Import (C, inflateReset, "inflateReset");
+   pragma Import (C, compress, "compress");
+   pragma Import (C, compress2, "compress2");
+   pragma Import (C, uncompress, "uncompress");
+   pragma Import (C, gzopen, "gzopen");
+   pragma Import (C, gzdopen, "gzdopen");
+   pragma Import (C, gzsetparams, "gzsetparams");
+   pragma Import (C, gzread, "gzread");
+   pragma Import (C, gzwrite, "gzwrite");
+   pragma Import (C, gzprintf, "gzprintf");
+   pragma Import (C, gzputs, "gzputs");
+   pragma Import (C, gzgets, "gzgets");
+   pragma Import (C, gzputc, "gzputc");
+   pragma Import (C, gzgetc, "gzgetc");
+   pragma Import (C, gzflush, "gzflush");
+   pragma Import (C, gzseek, "gzseek");
+   pragma Import (C, gzrewind, "gzrewind");
+   pragma Import (C, gztell, "gztell");
+   pragma Import (C, gzeof, "gzeof");
+   pragma Import (C, gzclose, "gzclose");
+   pragma Import (C, gzerror, "gzerror");
+   pragma Import (C, adler32, "adler32");
+   pragma Import (C, crc32, "crc32");
+   pragma Import (C, deflateInit, "deflateInit_");
+   pragma Import (C, inflateInit, "inflateInit_");
+   pragma Import (C, deflateInit2, "deflateInit2_");
+   pragma Import (C, inflateInit2, "inflateInit2_");
+   pragma Import (C, zError, "zError");
+   pragma Import (C, inflateSyncPoint, "inflateSyncPoint");
+   pragma Import (C, get_crc_table, "get_crc_table");
+
+   --  since zlib 1.2.0:
+
+   pragma Import (C, inflateCopy, "inflateCopy");
+   pragma Import (C, compressBound, "compressBound");
+   pragma Import (C, deflateBound, "deflateBound");
+   pragma Import (C, gzungetc, "gzungetc");
+   pragma Import (C, zlibCompileFlags, "zlibCompileFlags");
+
+   pragma Import (C, inflateBackInit, "inflateBackInit_");
+
+   --  I stopped binding the inflateBack routines, becouse realize that
+   --  it does not support zlib and gzip headers for now, and have no
+   --  symmetric deflateBack routines.
+   --  ZLib-Ada is symmetric regarding deflate/inflate data transformation
+   --  and has a similar generic callback interface for the
+   --  deflate/inflate transformation based on the regular Deflate/Inflate
+   --  routines.
+
+   --  pragma Import (C, inflateBack, "inflateBack");
+   --  pragma Import (C, inflateBackEnd, "inflateBackEnd");
+
+end ZLib.Thin;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.adb b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.adb
new file mode 100644 (file)
index 0000000..8b6fd68
--- /dev/null
@@ -0,0 +1,701 @@
+----------------------------------------------------------------
+--  ZLib for Ada thick binding.                               --
+--                                                            --
+--  Copyright (C) 2002-2004 Dmitriy Anisimkov                 --
+--                                                            --
+--  Open source license information is in the zlib.ads file.  --
+----------------------------------------------------------------
+
+--  $Id: zlib.adb,v 1.31 2004/09/06 06:53:19 vagul Exp $
+
+with Ada.Exceptions;
+with Ada.Unchecked_Conversion;
+with Ada.Unchecked_Deallocation;
+
+with Interfaces.C.Strings;
+
+with ZLib.Thin;
+
+package body ZLib is
+
+   use type Thin.Int;
+
+   type Z_Stream is new Thin.Z_Stream;
+
+   type Return_Code_Enum is
+      (OK,
+       STREAM_END,
+       NEED_DICT,
+       ERRNO,
+       STREAM_ERROR,
+       DATA_ERROR,
+       MEM_ERROR,
+       BUF_ERROR,
+       VERSION_ERROR);
+
+   type Flate_Step_Function is access
+     function (Strm : in Thin.Z_Streamp; Flush : in Thin.Int) return Thin.Int;
+   pragma Convention (C, Flate_Step_Function);
+
+   type Flate_End_Function is access
+      function (Ctrm : in Thin.Z_Streamp) return Thin.Int;
+   pragma Convention (C, Flate_End_Function);
+
+   type Flate_Type is record
+      Step : Flate_Step_Function;
+      Done : Flate_End_Function;
+   end record;
+
+   subtype Footer_Array is Stream_Element_Array (1 .. 8);
+
+   Simple_GZip_Header : constant Stream_Element_Array (1 .. 10)
+     := (16#1f#, 16#8b#,                 --  Magic header
+         16#08#,                         --  Z_DEFLATED
+         16#00#,                         --  Flags
+         16#00#, 16#00#, 16#00#, 16#00#, --  Time
+         16#00#,                         --  XFlags
+         16#03#                          --  OS code
+        );
+   --  The simplest gzip header is not for informational, but just for
+   --  gzip format compatibility.
+   --  Note that some code below is using assumption
+   --  Simple_GZip_Header'Last > Footer_Array'Last, so do not make
+   --  Simple_GZip_Header'Last <= Footer_Array'Last.
+
+   Return_Code : constant array (Thin.Int range <>) of Return_Code_Enum
+     := (0 => OK,
+         1 => STREAM_END,
+         2 => NEED_DICT,
+        -1 => ERRNO,
+        -2 => STREAM_ERROR,
+        -3 => DATA_ERROR,
+        -4 => MEM_ERROR,
+        -5 => BUF_ERROR,
+        -6 => VERSION_ERROR);
+
+   Flate : constant array (Boolean) of Flate_Type
+     := (True  => (Step => Thin.Deflate'Access,
+                   Done => Thin.DeflateEnd'Access),
+         False => (Step => Thin.Inflate'Access,
+                   Done => Thin.InflateEnd'Access));
+
+   Flush_Finish : constant array (Boolean) of Flush_Mode
+     := (True => Finish, False => No_Flush);
+
+   procedure Raise_Error (Stream : in Z_Stream);
+   pragma Inline (Raise_Error);
+
+   procedure Raise_Error (Message : in String);
+   pragma Inline (Raise_Error);
+
+   procedure Check_Error (Stream : in Z_Stream; Code : in Thin.Int);
+
+   procedure Free is new Ada.Unchecked_Deallocation
+      (Z_Stream, Z_Stream_Access);
+
+   function To_Thin_Access is new Ada.Unchecked_Conversion
+     (Z_Stream_Access, Thin.Z_Streamp);
+
+   procedure Translate_GZip
+     (Filter    : in out Filter_Type;
+      In_Data   : in     Ada.Streams.Stream_Element_Array;
+      In_Last   :    out Ada.Streams.Stream_Element_Offset;
+      Out_Data  :    out Ada.Streams.Stream_Element_Array;
+      Out_Last  :    out Ada.Streams.Stream_Element_Offset;
+      Flush     : in     Flush_Mode);
+   --  Separate translate routine for make gzip header.
+
+   procedure Translate_Auto
+     (Filter    : in out Filter_Type;
+      In_Data   : in     Ada.Streams.Stream_Element_Array;
+      In_Last   :    out Ada.Streams.Stream_Element_Offset;
+      Out_Data  :    out Ada.Streams.Stream_Element_Array;
+      Out_Last  :    out Ada.Streams.Stream_Element_Offset;
+      Flush     : in     Flush_Mode);
+   --  translate routine without additional headers.
+
+   -----------------
+   -- Check_Error --
+   -----------------
+
+   procedure Check_Error (Stream : in Z_Stream; Code : in Thin.Int) is
+      use type Thin.Int;
+   begin
+      if Code /= Thin.Z_OK then
+         Raise_Error
+            (Return_Code_Enum'Image (Return_Code (Code))
+              & ": " & Last_Error_Message (Stream));
+      end if;
+   end Check_Error;
+
+   -----------
+   -- Close --
+   -----------
+
+   procedure Close
+     (Filter       : in out Filter_Type;
+      Ignore_Error : in     Boolean := False)
+   is
+      Code : Thin.Int;
+   begin
+      if not Ignore_Error and then not Is_Open (Filter) then
+         raise Status_Error;
+      end if;
+
+      Code := Flate (Filter.Compression).Done (To_Thin_Access (Filter.Strm));
+
+      if Ignore_Error or else Code = Thin.Z_OK then
+         Free (Filter.Strm);
+      else
+         declare
+            Error_Message : constant String
+              := Last_Error_Message (Filter.Strm.all);
+         begin
+            Free (Filter.Strm);
+            Ada.Exceptions.Raise_Exception
+               (ZLib_Error'Identity,
+                Return_Code_Enum'Image (Return_Code (Code))
+                  & ": " & Error_Message);
+         end;
+      end if;
+   end Close;
+
+   -----------
+   -- CRC32 --
+   -----------
+
+   function CRC32
+     (CRC  : in Unsigned_32;
+      Data : in Ada.Streams.Stream_Element_Array)
+      return Unsigned_32
+   is
+      use Thin;
+   begin
+      return Unsigned_32 (crc32 (ULong (CRC),
+                                 Data'Address,
+                                 Data'Length));
+   end CRC32;
+
+   procedure CRC32
+     (CRC  : in out Unsigned_32;
+      Data : in     Ada.Streams.Stream_Element_Array) is
+   begin
+      CRC := CRC32 (CRC, Data);
+   end CRC32;
+
+   ------------------
+   -- Deflate_Init --
+   ------------------
+
+   procedure Deflate_Init
+     (Filter       : in out Filter_Type;
+      Level        : in     Compression_Level  := Default_Compression;
+      Strategy     : in     Strategy_Type      := Default_Strategy;
+      Method       : in     Compression_Method := Deflated;
+      Window_Bits  : in     Window_Bits_Type   := Default_Window_Bits;
+      Memory_Level : in     Memory_Level_Type  := Default_Memory_Level;
+      Header       : in     Header_Type        := Default)
+   is
+      use type Thin.Int;
+      Win_Bits : Thin.Int := Thin.Int (Window_Bits);
+   begin
+      if Is_Open (Filter) then
+         raise Status_Error;
+      end if;
+
+      --  We allow ZLib to make header only in case of default header type.
+      --  Otherwise we would either do header by ourselfs, or do not do
+      --  header at all.
+
+      if Header = None or else Header = GZip then
+         Win_Bits := -Win_Bits;
+      end if;
+
+      --  For the GZip CRC calculation and make headers.
+
+      if Header = GZip then
+         Filter.CRC    := 0;
+         Filter.Offset := Simple_GZip_Header'First;
+      else
+         Filter.Offset := Simple_GZip_Header'Last + 1;
+      end if;
+
+      Filter.Strm        := new Z_Stream;
+      Filter.Compression := True;
+      Filter.Stream_End  := False;
+      Filter.Header      := Header;
+
+      if Thin.Deflate_Init
+           (To_Thin_Access (Filter.Strm),
+            Level      => Thin.Int (Level),
+            method     => Thin.Int (Method),
+            windowBits => Win_Bits,
+            memLevel   => Thin.Int (Memory_Level),
+            strategy   => Thin.Int (Strategy)) /= Thin.Z_OK
+      then
+         Raise_Error (Filter.Strm.all);
+      end if;
+   end Deflate_Init;
+
+   -----------
+   -- Flush --
+   -----------
+
+   procedure Flush
+     (Filter    : in out Filter_Type;
+      Out_Data  :    out Ada.Streams.Stream_Element_Array;
+      Out_Last  :    out Ada.Streams.Stream_Element_Offset;
+      Flush     : in     Flush_Mode)
+   is
+      No_Data : Stream_Element_Array := (1 .. 0 => 0);
+      Last    : Stream_Element_Offset;
+   begin
+      Translate (Filter, No_Data, Last, Out_Data, Out_Last, Flush);
+   end Flush;
+
+   -----------------------
+   -- Generic_Translate --
+   -----------------------
+
+   procedure Generic_Translate
+     (Filter          : in out ZLib.Filter_Type;
+      In_Buffer_Size  : in     Integer := Default_Buffer_Size;
+      Out_Buffer_Size : in     Integer := Default_Buffer_Size)
+   is
+      In_Buffer  : Stream_Element_Array
+                     (1 .. Stream_Element_Offset (In_Buffer_Size));
+      Out_Buffer : Stream_Element_Array
+                     (1 .. Stream_Element_Offset (Out_Buffer_Size));
+      Last       : Stream_Element_Offset;
+      In_Last    : Stream_Element_Offset;
+      In_First   : Stream_Element_Offset;
+      Out_Last   : Stream_Element_Offset;
+   begin
+      Main : loop
+         Data_In (In_Buffer, Last);
+
+         In_First := In_Buffer'First;
+
+         loop
+            Translate
+              (Filter   => Filter,
+               In_Data  => In_Buffer (In_First .. Last),
+               In_Last  => In_Last,
+               Out_Data => Out_Buffer,
+               Out_Last => Out_Last,
+               Flush    => Flush_Finish (Last < In_Buffer'First));
+
+            if Out_Buffer'First <= Out_Last then
+               Data_Out (Out_Buffer (Out_Buffer'First .. Out_Last));
+            end if;
+
+            exit Main when Stream_End (Filter);
+
+            --  The end of in buffer.
+
+            exit when In_Last = Last;
+
+            In_First := In_Last + 1;
+         end loop;
+      end loop Main;
+
+   end Generic_Translate;
+
+   ------------------
+   -- Inflate_Init --
+   ------------------
+
+   procedure Inflate_Init
+     (Filter      : in out Filter_Type;
+      Window_Bits : in     Window_Bits_Type := Default_Window_Bits;
+      Header      : in     Header_Type      := Default)
+   is
+      use type Thin.Int;
+      Win_Bits : Thin.Int := Thin.Int (Window_Bits);
+
+      procedure Check_Version;
+      --  Check the latest header types compatibility.
+
+      procedure Check_Version is
+      begin
+         if Version <= "1.1.4" then
+            Raise_Error
+              ("Inflate header type " & Header_Type'Image (Header)
+               & " incompatible with ZLib version " & Version);
+         end if;
+      end Check_Version;
+
+   begin
+      if Is_Open (Filter) then
+         raise Status_Error;
+      end if;
+
+      case Header is
+         when None =>
+            Check_Version;
+
+            --  Inflate data without headers determined
+            --  by negative Win_Bits.
+
+            Win_Bits := -Win_Bits;
+         when GZip =>
+            Check_Version;
+
+            --  Inflate gzip data defined by flag 16.
+
+            Win_Bits := Win_Bits + 16;
+         when Auto =>
+            Check_Version;
+
+            --  Inflate with automatic detection
+            --  of gzip or native header defined by flag 32.
+
+            Win_Bits := Win_Bits + 32;
+         when Default => null;
+      end case;
+
+      Filter.Strm        := new Z_Stream;
+      Filter.Compression := False;
+      Filter.Stream_End  := False;
+      Filter.Header      := Header;
+
+      if Thin.Inflate_Init
+         (To_Thin_Access (Filter.Strm), Win_Bits) /= Thin.Z_OK
+      then
+         Raise_Error (Filter.Strm.all);
+      end if;
+   end Inflate_Init;
+
+   -------------
+   -- Is_Open --
+   -------------
+
+   function Is_Open (Filter : in Filter_Type) return Boolean is
+   begin
+      return Filter.Strm /= null;
+   end Is_Open;
+
+   -----------------
+   -- Raise_Error --
+   -----------------
+
+   procedure Raise_Error (Message : in String) is
+   begin
+      Ada.Exceptions.Raise_Exception (ZLib_Error'Identity, Message);
+   end Raise_Error;
+
+   procedure Raise_Error (Stream : in Z_Stream) is
+   begin
+      Raise_Error (Last_Error_Message (Stream));
+   end Raise_Error;
+
+   ----------
+   -- Read --
+   ----------
+
+   procedure Read
+     (Filter : in out Filter_Type;
+      Item   :    out Ada.Streams.Stream_Element_Array;
+      Last   :    out Ada.Streams.Stream_Element_Offset;
+      Flush  : in     Flush_Mode := No_Flush)
+   is
+      In_Last    : Stream_Element_Offset;
+      Item_First : Ada.Streams.Stream_Element_Offset := Item'First;
+      V_Flush    : Flush_Mode := Flush;
+
+   begin
+      pragma Assert (Rest_First in Buffer'First .. Buffer'Last + 1);
+      pragma Assert (Rest_Last in Buffer'First - 1 .. Buffer'Last);
+
+      loop
+         if Rest_Last = Buffer'First - 1 then
+            V_Flush := Finish;
+
+         elsif Rest_First > Rest_Last then
+            Read (Buffer, Rest_Last);
+            Rest_First := Buffer'First;
+
+            if Rest_Last < Buffer'First then
+               V_Flush := Finish;
+            end if;
+         end if;
+
+         Translate
+           (Filter   => Filter,
+            In_Data  => Buffer (Rest_First .. Rest_Last),
+            In_Last  => In_Last,
+            Out_Data => Item (Item_First .. Item'Last),
+            Out_Last => Last,
+            Flush    => V_Flush);
+
+         Rest_First := In_Last + 1;
+
+         exit when Stream_End (Filter)
+           or else Last = Item'Last
+           or else (Last >= Item'First and then Allow_Read_Some);
+
+         Item_First := Last + 1;
+      end loop;
+   end Read;
+
+   ----------------
+   -- Stream_End --
+   ----------------
+
+   function Stream_End (Filter : in Filter_Type) return Boolean is
+   begin
+      if Filter.Header = GZip and Filter.Compression then
+         return Filter.Stream_End
+            and then Filter.Offset = Footer_Array'Last + 1;
+      else
+         return Filter.Stream_End;
+      end if;
+   end Stream_End;
+
+   --------------
+   -- Total_In --
+   --------------
+
+   function Total_In (Filter : in Filter_Type) return Count is
+   begin
+      return Count (Thin.Total_In (To_Thin_Access (Filter.Strm).all));
+   end Total_In;
+
+   ---------------
+   -- Total_Out --
+   ---------------
+
+   function Total_Out (Filter : in Filter_Type) return Count is
+   begin
+      return Count (Thin.Total_Out (To_Thin_Access (Filter.Strm).all));
+   end Total_Out;
+
+   ---------------
+   -- Translate --
+   ---------------
+
+   procedure Translate
+     (Filter    : in out Filter_Type;
+      In_Data   : in     Ada.Streams.Stream_Element_Array;
+      In_Last   :    out Ada.Streams.Stream_Element_Offset;
+      Out_Data  :    out Ada.Streams.Stream_Element_Array;
+      Out_Last  :    out Ada.Streams.Stream_Element_Offset;
+      Flush     : in     Flush_Mode) is
+   begin
+      if Filter.Header = GZip and then Filter.Compression then
+         Translate_GZip
+           (Filter   => Filter,
+            In_Data  => In_Data,
+            In_Last  => In_Last,
+            Out_Data => Out_Data,
+            Out_Last => Out_Last,
+            Flush    => Flush);
+      else
+         Translate_Auto
+           (Filter   => Filter,
+            In_Data  => In_Data,
+            In_Last  => In_Last,
+            Out_Data => Out_Data,
+            Out_Last => Out_Last,
+            Flush    => Flush);
+      end if;
+   end Translate;
+
+   --------------------
+   -- Translate_Auto --
+   --------------------
+
+   procedure Translate_Auto
+     (Filter    : in out Filter_Type;
+      In_Data   : in     Ada.Streams.Stream_Element_Array;
+      In_Last   :    out Ada.Streams.Stream_Element_Offset;
+      Out_Data  :    out Ada.Streams.Stream_Element_Array;
+      Out_Last  :    out Ada.Streams.Stream_Element_Offset;
+      Flush     : in     Flush_Mode)
+   is
+      use type Thin.Int;
+      Code : Thin.Int;
+
+   begin
+      if not Is_Open (Filter) then
+         raise Status_Error;
+      end if;
+
+      if Out_Data'Length = 0 and then In_Data'Length = 0 then
+         raise Constraint_Error;
+      end if;
+
+      Set_Out (Filter.Strm.all, Out_Data'Address, Out_Data'Length);
+      Set_In  (Filter.Strm.all, In_Data'Address, In_Data'Length);
+
+      Code := Flate (Filter.Compression).Step
+        (To_Thin_Access (Filter.Strm),
+         Thin.Int (Flush));
+
+      if Code = Thin.Z_STREAM_END then
+         Filter.Stream_End := True;
+      else
+         Check_Error (Filter.Strm.all, Code);
+      end if;
+
+      In_Last  := In_Data'Last
+         - Stream_Element_Offset (Avail_In (Filter.Strm.all));
+      Out_Last := Out_Data'Last
+         - Stream_Element_Offset (Avail_Out (Filter.Strm.all));
+   end Translate_Auto;
+
+   --------------------
+   -- Translate_GZip --
+   --------------------
+
+   procedure Translate_GZip
+     (Filter    : in out Filter_Type;
+      In_Data   : in     Ada.Streams.Stream_Element_Array;
+      In_Last   :    out Ada.Streams.Stream_Element_Offset;
+      Out_Data  :    out Ada.Streams.Stream_Element_Array;
+      Out_Last  :    out Ada.Streams.Stream_Element_Offset;
+      Flush     : in     Flush_Mode)
+   is
+      Out_First : Stream_Element_Offset;
+
+      procedure Add_Data (Data : in Stream_Element_Array);
+      --  Add data to stream from the Filter.Offset till necessary,
+      --  used for add gzip headr/footer.
+
+      procedure Put_32
+        (Item : in out Stream_Element_Array;
+         Data : in     Unsigned_32);
+      pragma Inline (Put_32);
+
+      --------------
+      -- Add_Data --
+      --------------
+
+      procedure Add_Data (Data : in Stream_Element_Array) is
+         Data_First : Stream_Element_Offset renames Filter.Offset;
+         Data_Last  : Stream_Element_Offset;
+         Data_Len   : Stream_Element_Offset; --  -1
+         Out_Len    : Stream_Element_Offset; --  -1
+      begin
+         Out_First := Out_Last + 1;
+
+         if Data_First > Data'Last then
+            return;
+         end if;
+
+         Data_Len  := Data'Last     - Data_First;
+         Out_Len   := Out_Data'Last - Out_First;
+
+         if Data_Len <= Out_Len then
+            Out_Last  := Out_First  + Data_Len;
+            Data_Last := Data'Last;
+         else
+            Out_Last  := Out_Data'Last;
+            Data_Last := Data_First + Out_Len;
+         end if;
+
+         Out_Data (Out_First .. Out_Last) := Data (Data_First .. Data_Last);
+
+         Data_First := Data_Last + 1;
+         Out_First  := Out_Last + 1;
+      end Add_Data;
+
+      ------------
+      -- Put_32 --
+      ------------
+
+      procedure Put_32
+        (Item : in out Stream_Element_Array;
+         Data : in     Unsigned_32)
+      is
+         D : Unsigned_32 := Data;
+      begin
+         for J in Item'First .. Item'First + 3 loop
+            Item (J) := Stream_Element (D and 16#FF#);
+            D := Shift_Right (D, 8);
+         end loop;
+      end Put_32;
+
+   begin
+      Out_Last := Out_Data'First - 1;
+
+      if not Filter.Stream_End then
+         Add_Data (Simple_GZip_Header);
+
+         Translate_Auto
+           (Filter   => Filter,
+            In_Data  => In_Data,
+            In_Last  => In_Last,
+            Out_Data => Out_Data (Out_First .. Out_Data'Last),
+            Out_Last => Out_Last,
+            Flush    => Flush);
+
+         CRC32 (Filter.CRC, In_Data (In_Data'First .. In_Last));
+      end if;
+
+      if Filter.Stream_End and then Out_Last <= Out_Data'Last then
+         --  This detection method would work only when
+         --  Simple_GZip_Header'Last > Footer_Array'Last
+
+         if Filter.Offset = Simple_GZip_Header'Last + 1 then
+            Filter.Offset := Footer_Array'First;
+         end if;
+
+         declare
+            Footer : Footer_Array;
+         begin
+            Put_32 (Footer, Filter.CRC);
+            Put_32 (Footer (Footer'First + 4 .. Footer'Last),
+                    Unsigned_32 (Total_In (Filter)));
+            Add_Data (Footer);
+         end;
+      end if;
+   end Translate_GZip;
+
+   -------------
+   -- Version --
+   -------------
+
+   function Version return String is
+   begin
+      return Interfaces.C.Strings.Value (Thin.zlibVersion);
+   end Version;
+
+   -----------
+   -- Write --
+   -----------
+
+   procedure Write
+     (Filter : in out Filter_Type;
+      Item   : in     Ada.Streams.Stream_Element_Array;
+      Flush  : in     Flush_Mode := No_Flush)
+   is
+      Buffer   : Stream_Element_Array (1 .. Buffer_Size);
+      In_Last  : Stream_Element_Offset;
+      Out_Last : Stream_Element_Offset;
+      In_First : Stream_Element_Offset := Item'First;
+   begin
+      if Item'Length = 0 and Flush = No_Flush then
+         return;
+      end if;
+
+      loop
+         Translate
+           (Filter   => Filter,
+            In_Data  => Item (In_First .. Item'Last),
+            In_Last  => In_Last,
+            Out_Data => Buffer,
+            Out_Last => Out_Last,
+            Flush    => Flush);
+
+         if Out_Last >= Buffer'First then
+            Write (Buffer (1 .. Out_Last));
+         end if;
+
+         exit when In_Last = Item'Last or Stream_End (Filter);
+
+         In_First := In_Last + 1;
+      end loop;
+   end Write;
+
+end ZLib;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.ads b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.ads
new file mode 100644 (file)
index 0000000..79ffc40
--- /dev/null
@@ -0,0 +1,328 @@
+------------------------------------------------------------------------------
+--                      ZLib for Ada thick binding.                         --
+--                                                                          --
+--              Copyright (C) 2002-2004 Dmitriy Anisimkov                   --
+--                                                                          --
+--  This library 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 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       --
+--  General Public License for more details.                                --
+--                                                                          --
+--  You should have received a copy of the GNU 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.          --
+--                                                                          --
+--  As a special exception, if other files instantiate generics from this   --
+--  unit, or you link this unit with other files to produce an executable,  --
+--  this  unit  does not  by itself cause  the resulting executable to be   --
+--  covered by the GNU General Public License. This exception does not      --
+--  however invalidate any other reasons why the executable file  might be  --
+--  covered by the  GNU Public License.                                     --
+------------------------------------------------------------------------------
+
+--  $Id: zlib.ads,v 1.26 2004/09/06 06:53:19 vagul Exp $
+
+with Ada.Streams;
+
+with Interfaces;
+
+package ZLib is
+
+   ZLib_Error   : exception;
+   Status_Error : exception;
+
+   type Compression_Level is new Integer range -1 .. 9;
+
+   type Flush_Mode is private;
+
+   type Compression_Method is private;
+
+   type Window_Bits_Type is new Integer range 8 .. 15;
+
+   type Memory_Level_Type is new Integer range 1 .. 9;
+
+   type Unsigned_32 is new Interfaces.Unsigned_32;
+
+   type Strategy_Type is private;
+
+   type Header_Type is (None, Auto, Default, GZip);
+   --  Header type usage have a some limitation for inflate.
+   --  See comment for Inflate_Init.
+
+   subtype Count is Ada.Streams.Stream_Element_Count;
+
+   Default_Memory_Level : constant Memory_Level_Type := 8;
+   Default_Window_Bits  : constant Window_Bits_Type  := 15;
+
+   ----------------------------------
+   -- Compression method constants --
+   ----------------------------------
+
+   Deflated : constant Compression_Method;
+   --  Only one method allowed in this ZLib version
+
+   ---------------------------------
+   -- Compression level constants --
+   ---------------------------------
+
+   No_Compression      : constant Compression_Level := 0;
+   Best_Speed          : constant Compression_Level := 1;
+   Best_Compression    : constant Compression_Level := 9;
+   Default_Compression : constant Compression_Level := -1;
+
+   --------------------------
+   -- Flush mode constants --
+   --------------------------
+
+   No_Flush      : constant Flush_Mode;
+   --  Regular way for compression, no flush
+
+   Partial_Flush : constant Flush_Mode;
+   --  Will be removed, use Z_SYNC_FLUSH instead
+
+   Sync_Flush    : constant Flush_Mode;
+   --  All pending output is flushed to the output buffer and the output
+   --  is aligned on a byte boundary, so that the decompressor can get all
+   --  input data available so far. (In particular avail_in is zero after the
+   --  call if enough output space has been provided  before the call.)
+   --  Flushing may degrade compression for some compression algorithms and so
+   --  it should be used only when necessary.
+
+   Block_Flush   : constant Flush_Mode;
+   --  Z_BLOCK requests that inflate() stop
+   --  if and when it get to the next deflate block boundary. When decoding the
+   --  zlib or gzip format, this will cause inflate() to return immediately
+   --  after the header and before the first block. When doing a raw inflate,
+   --  inflate() will go ahead and process the first block, and will return
+   --  when it gets to the end of that block, or when it runs out of data.
+
+   Full_Flush    : constant Flush_Mode;
+   --  All output is flushed as with SYNC_FLUSH, and the compression state
+   --  is reset so that decompression can restart from this point if previous
+   --  compressed data has been damaged or if random access is desired. Using
+   --  Full_Flush too often can seriously degrade the compression.
+
+   Finish        : constant Flush_Mode;
+   --  Just for tell the compressor that input data is complete.
+
+   ------------------------------------
+   -- Compression strategy constants --
+   ------------------------------------
+
+   --  RLE stategy could be used only in version 1.2.0 and later.
+
+   Filtered         : constant Strategy_Type;
+   Huffman_Only     : constant Strategy_Type;
+   RLE              : constant Strategy_Type;
+   Default_Strategy : constant Strategy_Type;
+
+   Default_Buffer_Size : constant := 4096;
+
+   type Filter_Type is tagged limited private;
+   --  The filter is for compression and for decompression.
+   --  The usage of the type is depend of its initialization.
+
+   function Version return String;
+   pragma Inline (Version);
+   --  Return string representation of the ZLib version.
+
+   procedure Deflate_Init
+     (Filter       : in out Filter_Type;
+      Level        : in     Compression_Level  := Default_Compression;
+      Strategy     : in     Strategy_Type      := Default_Strategy;
+      Method       : in     Compression_Method := Deflated;
+      Window_Bits  : in     Window_Bits_Type   := Default_Window_Bits;
+      Memory_Level : in     Memory_Level_Type  := Default_Memory_Level;
+      Header       : in     Header_Type        := Default);
+   --  Compressor initialization.
+   --  When Header parameter is Auto or Default, then default zlib header
+   --  would be provided for compressed data.
+   --  When Header is GZip, then gzip header would be set instead of
+   --  default header.
+   --  When Header is None, no header would be set for compressed data.
+
+   procedure Inflate_Init
+     (Filter      : in out Filter_Type;
+      Window_Bits : in     Window_Bits_Type := Default_Window_Bits;
+      Header      : in     Header_Type      := Default);
+   --  Decompressor initialization.
+   --  Default header type mean that ZLib default header is expecting in the
+   --  input compressed stream.
+   --  Header type None mean that no header is expecting in the input stream.
+   --  GZip header type mean that GZip header is expecting in the
+   --  input compressed stream.
+   --  Auto header type mean that header type (GZip or Native) would be
+   --  detected automatically in the input stream.
+   --  Note that header types parameter values None, GZip and Auto are
+   --  supported for inflate routine only in ZLib versions 1.2.0.2 and later.
+   --  Deflate_Init is supporting all header types.
+
+   function Is_Open (Filter : in Filter_Type) return Boolean;
+   pragma Inline (Is_Open);
+   --  Is the filter opened for compression or decompression.
+
+   procedure Close
+     (Filter       : in out Filter_Type;
+      Ignore_Error : in     Boolean := False);
+   --  Closing the compression or decompressor.
+   --  If stream is closing before the complete and Ignore_Error is False,
+   --  The exception would be raised.
+
+   generic
+      with procedure Data_In
+        (Item : out Ada.Streams.Stream_Element_Array;
+         Last : out Ada.Streams.Stream_Element_Offset);
+      with procedure Data_Out
+        (Item : in Ada.Streams.Stream_Element_Array);
+   procedure Generic_Translate
+     (Filter          : in out Filter_Type;
+      In_Buffer_Size  : in     Integer := Default_Buffer_Size;
+      Out_Buffer_Size : in     Integer := Default_Buffer_Size);
+   --  Compress/decompress data fetch from Data_In routine and pass the result
+   --  to the Data_Out routine. User should provide Data_In and Data_Out
+   --  for compression/decompression data flow.
+   --  Compression or decompression depend on Filter initialization.
+
+   function Total_In (Filter : in Filter_Type) return Count;
+   pragma Inline (Total_In);
+   --  Returns total number of input bytes read so far
+
+   function Total_Out (Filter : in Filter_Type) return Count;
+   pragma Inline (Total_Out);
+   --  Returns total number of bytes output so far
+
+   function CRC32
+     (CRC    : in Unsigned_32;
+      Data   : in Ada.Streams.Stream_Element_Array)
+      return Unsigned_32;
+   pragma Inline (CRC32);
+   --  Compute CRC32, it could be necessary for make gzip format
+
+   procedure CRC32
+     (CRC  : in out Unsigned_32;
+      Data : in     Ada.Streams.Stream_Element_Array);
+   pragma Inline (CRC32);
+   --  Compute CRC32, it could be necessary for make gzip format
+
+   -------------------------------------------------
+   --  Below is more complex low level routines.  --
+   -------------------------------------------------
+
+   procedure Translate
+     (Filter    : in out Filter_Type;
+      In_Data   : in     Ada.Streams.Stream_Element_Array;
+      In_Last   :    out Ada.Streams.Stream_Element_Offset;
+      Out_Data  :    out Ada.Streams.Stream_Element_Array;
+      Out_Last  :    out Ada.Streams.Stream_Element_Offset;
+      Flush     : in     Flush_Mode);
+   --  Compress/decompress the In_Data buffer and place the result into
+   --  Out_Data. In_Last is the index of last element from In_Data accepted by
+   --  the Filter. Out_Last is the last element of the received data from
+   --  Filter. To tell the filter that incoming data are complete put the
+   --  Flush parameter to Finish.
+
+   function Stream_End (Filter : in Filter_Type) return Boolean;
+   pragma Inline (Stream_End);
+   --  Return the true when the stream is complete.
+
+   procedure Flush
+     (Filter    : in out Filter_Type;
+      Out_Data  :    out Ada.Streams.Stream_Element_Array;
+      Out_Last  :    out Ada.Streams.Stream_Element_Offset;
+      Flush     : in     Flush_Mode);
+   pragma Inline (Flush);
+   --  Flushing the data from the compressor.
+
+   generic
+      with procedure Write
+        (Item : in Ada.Streams.Stream_Element_Array);
+      --  User should provide this routine for accept
+      --  compressed/decompressed data.
+
+      Buffer_Size : in Ada.Streams.Stream_Element_Offset
+         := Default_Buffer_Size;
+      --  Buffer size for Write user routine.
+
+   procedure Write
+     (Filter  : in out Filter_Type;
+      Item    : in     Ada.Streams.Stream_Element_Array;
+      Flush   : in     Flush_Mode := No_Flush);
+   --  Compress/Decompress data from Item to the generic parameter procedure
+   --  Write. Output buffer size could be set in Buffer_Size generic parameter.
+
+   generic
+      with procedure Read
+        (Item : out Ada.Streams.Stream_Element_Array;
+         Last : out Ada.Streams.Stream_Element_Offset);
+      --  User should provide data for compression/decompression
+      --  thru this routine.
+
+      Buffer : in out Ada.Streams.Stream_Element_Array;
+      --  Buffer for keep remaining data from the previous
+      --  back read.
+
+      Rest_First, Rest_Last : in out Ada.Streams.Stream_Element_Offset;
+      --  Rest_First have to be initialized to Buffer'Last + 1
+      --  Rest_Last have to be initialized to Buffer'Last
+      --  before usage.
+
+      Allow_Read_Some : in Boolean := False;
+      --  Is it allowed to return Last < Item'Last before end of data.
+
+   procedure Read
+     (Filter : in out Filter_Type;
+      Item   :    out Ada.Streams.Stream_Element_Array;
+      Last   :    out Ada.Streams.Stream_Element_Offset;
+      Flush  : in     Flush_Mode := No_Flush);
+   --  Compress/Decompress data from generic parameter procedure Read to the
+   --  Item. User should provide Buffer and initialized Rest_First, Rest_Last
+   --  indicators. If Allow_Read_Some is True, Read routines could return
+   --  Last < Item'Last only at end of stream.
+
+private
+
+   use Ada.Streams;
+
+   pragma Assert (Ada.Streams.Stream_Element'Size    =    8);
+   pragma Assert (Ada.Streams.Stream_Element'Modulus = 2**8);
+
+   type Flush_Mode is new Integer range 0 .. 5;
+
+   type Compression_Method is new Integer range 8 .. 8;
+
+   type Strategy_Type is new Integer range 0 .. 3;
+
+   No_Flush      : constant Flush_Mode := 0;
+   Partial_Flush : constant Flush_Mode := 1;
+   Sync_Flush    : constant Flush_Mode := 2;
+   Full_Flush    : constant Flush_Mode := 3;
+   Finish        : constant Flush_Mode := 4;
+   Block_Flush   : constant Flush_Mode := 5;
+
+   Filtered         : constant Strategy_Type := 1;
+   Huffman_Only     : constant Strategy_Type := 2;
+   RLE              : constant Strategy_Type := 3;
+   Default_Strategy : constant Strategy_Type := 0;
+
+   Deflated : constant Compression_Method := 8;
+
+   type Z_Stream;
+
+   type Z_Stream_Access is access all Z_Stream;
+
+   type Filter_Type is tagged limited record
+      Strm        : Z_Stream_Access;
+      Compression : Boolean;
+      Stream_End  : Boolean;
+      Header      : Header_Type;
+      CRC         : Unsigned_32;
+      Offset      : Stream_Element_Offset;
+      --  Offset for gzip header/footer output.
+   end record;
+
+end ZLib;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.gpr b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/ada/zlib.gpr
new file mode 100644 (file)
index 0000000..296b22a
--- /dev/null
@@ -0,0 +1,20 @@
+project Zlib is
+
+   for Languages use ("Ada");
+   for Source_Dirs use (".");
+   for Object_Dir use ".";
+   for Main use ("test.adb", "mtest.adb", "read.adb", "buffer_demo");
+
+   package Compiler is
+      for Default_Switches ("ada") use ("-gnatwcfilopru", "-gnatVcdfimorst", "-gnatyabcefhiklmnoprst");
+   end Compiler;
+
+   package Linker is
+      for Default_Switches ("ada") use ("-lz");
+   end Linker;
+
+   package Builder is
+      for Default_Switches ("ada") use ("-s", "-gnatQ");
+   end Builder;
+
+end Zlib;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/amd64/amd64-match.S b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/amd64/amd64-match.S
new file mode 100644 (file)
index 0000000..81d4a1c
--- /dev/null
@@ -0,0 +1,452 @@
+/*
+ * match.S -- optimized version of longest_match()
+ * based on the similar work by Gilles Vollant, and Brian Raiter, written 1998
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the BSD License. Use by owners of Che Guevarra
+ * parafernalia is prohibited, where possible, and highly discouraged
+ * elsewhere.
+ */
+
+#ifndef NO_UNDERLINE
+#      define  match_init      _match_init
+#      define  longest_match   _longest_match
+#endif
+
+#define        scanend         ebx
+#define        scanendw        bx
+#define        chainlenwmask   edx /* high word: current chain len low word: s->wmask */
+#define        curmatch        rsi
+#define        curmatchd       esi
+#define        windowbestlen   r8
+#define        scanalign       r9
+#define        scanalignd      r9d
+#define        window          r10
+#define        bestlen         r11
+#define        bestlend        r11d
+#define        scanstart       r12d
+#define        scanstartw      r12w
+#define scan           r13
+#define nicematch      r14d
+#define        limit           r15
+#define        limitd          r15d
+#define prev           rcx
+
+/*
+ * The 258 is a "magic number, not a parameter -- changing it
+ * breaks the hell loose
+ */
+#define        MAX_MATCH       (258)
+#define        MIN_MATCH       (3)
+#define        MIN_LOOKAHEAD   (MAX_MATCH + MIN_MATCH + 1)
+#define        MAX_MATCH_8     ((MAX_MATCH + 7) & ~7)
+
+/* stack frame offsets */
+#define        LocalVarsSize   (112)
+#define _chainlenwmask ( 8-LocalVarsSize)(%rsp)
+#define _windowbestlen (16-LocalVarsSize)(%rsp)
+#define save_r14        (24-LocalVarsSize)(%rsp)
+#define save_rsi        (32-LocalVarsSize)(%rsp)
+#define save_rbx        (40-LocalVarsSize)(%rsp)
+#define save_r12        (56-LocalVarsSize)(%rsp)
+#define save_r13        (64-LocalVarsSize)(%rsp)
+#define save_r15        (80-LocalVarsSize)(%rsp)
+
+
+.globl match_init, longest_match
+
+/*
+ * On AMD64 the first argument of a function (in our case -- the pointer to
+ * deflate_state structure) is passed in %rdi, hence our offsets below are
+ * all off of that.
+ */
+
+/* you can check the structure offset by running
+
+#include <stdlib.h>
+#include <stdio.h>
+#include "deflate.h"
+
+void print_depl()
+{
+deflate_state ds;
+deflate_state *s=&ds;
+printf("size pointer=%u\n",(int)sizeof(void*));
+
+printf("#define dsWSize         (%3u)(%%rdi)\n",(int)(((char*)&(s->w_size))-((char*)s)));
+printf("#define dsWMask         (%3u)(%%rdi)\n",(int)(((char*)&(s->w_mask))-((char*)s)));
+printf("#define dsWindow        (%3u)(%%rdi)\n",(int)(((char*)&(s->window))-((char*)s)));
+printf("#define dsPrev          (%3u)(%%rdi)\n",(int)(((char*)&(s->prev))-((char*)s)));
+printf("#define dsMatchLen      (%3u)(%%rdi)\n",(int)(((char*)&(s->match_length))-((char*)s)));
+printf("#define dsPrevMatch     (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_match))-((char*)s)));
+printf("#define dsStrStart      (%3u)(%%rdi)\n",(int)(((char*)&(s->strstart))-((char*)s)));
+printf("#define dsMatchStart    (%3u)(%%rdi)\n",(int)(((char*)&(s->match_start))-((char*)s)));
+printf("#define dsLookahead     (%3u)(%%rdi)\n",(int)(((char*)&(s->lookahead))-((char*)s)));
+printf("#define dsPrevLen       (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_length))-((char*)s)));
+printf("#define dsMaxChainLen   (%3u)(%%rdi)\n",(int)(((char*)&(s->max_chain_length))-((char*)s)));
+printf("#define dsGoodMatch     (%3u)(%%rdi)\n",(int)(((char*)&(s->good_match))-((char*)s)));
+printf("#define dsNiceMatch     (%3u)(%%rdi)\n",(int)(((char*)&(s->nice_match))-((char*)s)));
+}
+
+*/
+
+
+/*
+  to compile for XCode 3.2 on MacOSX x86_64
+  - run "gcc -g -c -DXCODE_MAC_X64_STRUCTURE amd64-match.S"
+ */
+
+
+#ifndef CURRENT_LINX_XCODE_MAC_X64_STRUCTURE
+#define dsWSize                ( 68)(%rdi)
+#define dsWMask                ( 76)(%rdi)
+#define dsWindow       ( 80)(%rdi)
+#define dsPrev         ( 96)(%rdi)
+#define dsMatchLen     (144)(%rdi)
+#define dsPrevMatch    (148)(%rdi)
+#define dsStrStart     (156)(%rdi)
+#define dsMatchStart   (160)(%rdi)
+#define dsLookahead    (164)(%rdi)
+#define dsPrevLen      (168)(%rdi)
+#define dsMaxChainLen  (172)(%rdi)
+#define dsGoodMatch    (188)(%rdi)
+#define dsNiceMatch    (192)(%rdi)
+
+#else 
+
+#ifndef STRUCT_OFFSET
+#      define STRUCT_OFFSET    (0)
+#endif
+
+
+#define dsWSize                ( 56 + STRUCT_OFFSET)(%rdi)
+#define dsWMask                ( 64 + STRUCT_OFFSET)(%rdi)
+#define dsWindow       ( 72 + STRUCT_OFFSET)(%rdi)
+#define dsPrev         ( 88 + STRUCT_OFFSET)(%rdi)
+#define dsMatchLen     (136 + STRUCT_OFFSET)(%rdi)
+#define dsPrevMatch    (140 + STRUCT_OFFSET)(%rdi)
+#define dsStrStart     (148 + STRUCT_OFFSET)(%rdi)
+#define dsMatchStart   (152 + STRUCT_OFFSET)(%rdi)
+#define dsLookahead    (156 + STRUCT_OFFSET)(%rdi)
+#define dsPrevLen      (160 + STRUCT_OFFSET)(%rdi)
+#define dsMaxChainLen  (164 + STRUCT_OFFSET)(%rdi)
+#define dsGoodMatch    (180 + STRUCT_OFFSET)(%rdi)
+#define dsNiceMatch    (184 + STRUCT_OFFSET)(%rdi)
+
+#endif
+
+
+
+
+.text
+
+/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */
+
+longest_match:
+/*
+ * Retrieve the function arguments. %curmatch will hold cur_match
+ * throughout the entire function (passed via rsi on amd64).
+ * rdi will hold the pointer to the deflate_state (first arg on amd64)
+ */
+               mov     %rsi, save_rsi
+               mov     %rbx, save_rbx
+               mov     %r12, save_r12
+               mov     %r13, save_r13
+               mov     %r14, save_r14
+               mov     %r15, save_r15
+
+/* uInt wmask = s->w_mask;                                             */
+/* unsigned chain_length = s->max_chain_length;                                */
+/* if (s->prev_length >= s->good_match) {                              */
+/*     chain_length >>= 2;                                             */
+/* }                                                                   */
+
+               movl    dsPrevLen, %eax
+               movl    dsGoodMatch, %ebx
+               cmpl    %ebx, %eax
+               movl    dsWMask, %eax
+               movl    dsMaxChainLen, %chainlenwmask
+               jl      LastMatchGood
+               shrl    $2, %chainlenwmask
+LastMatchGood:
+
+/* chainlen is decremented once beforehand so that the function can    */
+/* use the sign flag instead of the zero flag for the exit test.       */
+/* It is then shifted into the high word, to make room for the wmask   */
+/* value, which it will always accompany.                              */
+
+               decl    %chainlenwmask
+               shll    $16, %chainlenwmask
+               orl     %eax, %chainlenwmask
+
+/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;     */
+
+               movl    dsNiceMatch, %eax
+               movl    dsLookahead, %ebx
+               cmpl    %eax, %ebx
+               jl      LookaheadLess
+               movl    %eax, %ebx
+LookaheadLess: movl    %ebx, %nicematch
+
+/* register Bytef *scan = s->window + s->strstart;                     */
+
+               mov     dsWindow, %window
+               movl    dsStrStart, %limitd
+               lea     (%limit, %window), %scan
+
+/* Determine how many bytes the scan ptr is off from being             */
+/* dword-aligned.                                                      */
+
+               mov     %scan, %scanalign
+               negl    %scanalignd
+               andl    $3, %scanalignd
+
+/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ?                      */
+/*     s->strstart - (IPos)MAX_DIST(s) : NIL;                          */
+
+               movl    dsWSize, %eax
+               subl    $MIN_LOOKAHEAD, %eax
+               xorl    %ecx, %ecx
+               subl    %eax, %limitd
+               cmovng  %ecx, %limitd
+
+/* int best_len = s->prev_length;                                      */
+
+               movl    dsPrevLen, %bestlend
+
+/* Store the sum of s->window + best_len in %windowbestlen locally, and in memory.     */
+
+               lea     (%window, %bestlen), %windowbestlen
+               mov     %windowbestlen, _windowbestlen
+
+/* register ush scan_start = *(ushf*)scan;                             */
+/* register ush scan_end   = *(ushf*)(scan+best_len-1);                        */
+/* Posf *prev = s->prev;                                               */
+
+               movzwl  (%scan), %scanstart
+               movzwl  -1(%scan, %bestlen), %scanend
+               mov     dsPrev, %prev
+
+/* Jump into the main loop.                                            */
+
+               movl    %chainlenwmask, _chainlenwmask
+               jmp     LoopEntry
+
+.balign 16
+
+/* do {
+ *     match = s->window + cur_match;
+ *     if (*(ushf*)(match+best_len-1) != scan_end ||
+ *         *(ushf*)match != scan_start) continue;
+ *     [...]
+ * } while ((cur_match = prev[cur_match & wmask]) > limit
+ *          && --chain_length != 0);
+ *
+ * Here is the inner loop of the function. The function will spend the
+ * majority of its time in this loop, and majority of that time will
+ * be spent in the first ten instructions.
+ */
+LookupLoop:
+               andl    %chainlenwmask, %curmatchd
+               movzwl  (%prev, %curmatch, 2), %curmatchd
+               cmpl    %limitd, %curmatchd
+               jbe     LeaveNow
+               subl    $0x00010000, %chainlenwmask
+               js      LeaveNow
+LoopEntry:     cmpw    -1(%windowbestlen, %curmatch), %scanendw
+               jne     LookupLoop
+               cmpw    %scanstartw, (%window, %curmatch)
+               jne     LookupLoop
+
+/* Store the current value of chainlen.                                        */
+               movl    %chainlenwmask, _chainlenwmask
+
+/* %scan is the string under scrutiny, and %prev to the string we      */
+/* are hoping to match it up with. In actuality, %esi and %edi are     */
+/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is     */
+/* initialized to -(MAX_MATCH_8 - scanalign).                          */
+
+               mov     $(-MAX_MATCH_8), %rdx
+               lea     (%curmatch, %window), %windowbestlen
+               lea     MAX_MATCH_8(%windowbestlen, %scanalign), %windowbestlen
+               lea     MAX_MATCH_8(%scan, %scanalign), %prev
+
+/* the prefetching below makes very little difference... */
+               prefetcht1      (%windowbestlen, %rdx)
+               prefetcht1      (%prev, %rdx)
+
+/*
+ * Test the strings for equality, 8 bytes at a time. At the end,
+ * adjust %rdx so that it is offset to the exact byte that mismatched.
+ *
+ * It should be confessed that this loop usually does not represent
+ * much of the total running time. Replacing it with a more
+ * straightforward "rep cmpsb" would not drastically degrade
+ * performance -- unrolling it, for example, makes no difference.
+ */
+
+#undef USE_SSE /* works, but is 6-7% slower, than non-SSE... */
+
+LoopCmps:
+#ifdef USE_SSE
+               /* Preload the SSE registers */
+               movdqu    (%windowbestlen, %rdx), %xmm1
+               movdqu    (%prev, %rdx), %xmm2
+               pcmpeqb %xmm2, %xmm1
+               movdqu  16(%windowbestlen, %rdx), %xmm3
+               movdqu  16(%prev, %rdx), %xmm4
+               pcmpeqb %xmm4, %xmm3
+               movdqu  32(%windowbestlen, %rdx), %xmm5
+               movdqu  32(%prev, %rdx), %xmm6
+               pcmpeqb %xmm6, %xmm5
+               movdqu  48(%windowbestlen, %rdx), %xmm7
+               movdqu  48(%prev, %rdx), %xmm8
+               pcmpeqb %xmm8, %xmm7
+
+               /* Check the comparisions' results */
+               pmovmskb %xmm1, %rax
+               notw    %ax
+               bsfw    %ax, %ax
+               jnz     LeaveLoopCmps
+               
+               /* this is the only iteration of the loop with a possibility of having
+                  incremented rdx by 0x108 (each loop iteration add 16*4 = 0x40 
+                  and (0x40*4)+8=0x108 */
+               add     $8, %rdx
+               jz LenMaximum
+               add     $8, %rdx
+
+               
+               pmovmskb %xmm3, %rax
+               notw    %ax
+               bsfw    %ax, %ax
+               jnz     LeaveLoopCmps
+               
+               
+               add     $16, %rdx
+
+
+               pmovmskb %xmm5, %rax
+               notw    %ax
+               bsfw    %ax, %ax
+               jnz     LeaveLoopCmps
+               
+               add     $16, %rdx
+
+
+               pmovmskb %xmm7, %rax
+               notw    %ax
+               bsfw    %ax, %ax
+               jnz     LeaveLoopCmps
+               
+               add     $16, %rdx
+               
+               jmp     LoopCmps
+LeaveLoopCmps: add     %rax, %rdx
+#else
+               mov     (%windowbestlen, %rdx), %rax
+               xor     (%prev, %rdx), %rax
+               jnz     LeaveLoopCmps
+               
+               mov     8(%windowbestlen, %rdx), %rax
+               xor     8(%prev, %rdx), %rax
+               jnz     LeaveLoopCmps8
+
+               mov     16(%windowbestlen, %rdx), %rax
+               xor     16(%prev, %rdx), %rax
+               jnz     LeaveLoopCmps16
+                               
+               add     $24, %rdx
+               jnz     LoopCmps
+               jmp     LenMaximum
+#      if 0
+/*
+ * This three-liner is tantalizingly simple, but bsf is a slow instruction,
+ * and the complicated alternative down below is quite a bit faster. Sad...
+ */
+
+LeaveLoopCmps: bsf     %rax, %rax /* find the first non-zero bit */
+               shrl    $3, %eax /* divide by 8 to get the byte */
+               add     %rax, %rdx
+#      else
+LeaveLoopCmps16:
+               add     $8, %rdx
+LeaveLoopCmps8:
+               add     $8, %rdx
+LeaveLoopCmps: testl   $0xFFFFFFFF, %eax /* Check the first 4 bytes */
+               jnz     Check16
+               add     $4, %rdx
+               shr     $32, %rax
+Check16:        testw   $0xFFFF, %ax
+               jnz     LenLower
+               add     $2, %rdx
+               shrl    $16, %eax
+LenLower:      subb    $1, %al
+               adc     $0, %rdx
+#      endif
+#endif
+
+/* Calculate the length of the match. If it is longer than MAX_MATCH,  */
+/* then automatically accept it as the best possible match and leave.  */
+
+               lea     (%prev, %rdx), %rax
+               sub     %scan, %rax
+               cmpl    $MAX_MATCH, %eax
+               jge     LenMaximum
+
+/* If the length of the match is not longer than the best match we     */
+/* have so far, then forget it and return to the lookup loop.          */
+
+               cmpl    %bestlend, %eax
+               jg      LongerMatch
+               mov     _windowbestlen, %windowbestlen
+               mov     dsPrev, %prev
+               movl    _chainlenwmask, %edx
+               jmp     LookupLoop
+
+/*         s->match_start = cur_match;                                 */
+/*         best_len = len;                                             */
+/*         if (len >= nice_match) break;                               */
+/*         scan_end = *(ushf*)(scan+best_len-1);                       */
+
+LongerMatch:
+               movl    %eax, %bestlend
+               movl    %curmatchd, dsMatchStart
+               cmpl    %nicematch, %eax
+               jge     LeaveNow
+
+               lea     (%window, %bestlen), %windowbestlen
+               mov     %windowbestlen, _windowbestlen
+
+               movzwl  -1(%scan, %rax), %scanend
+               mov     dsPrev, %prev
+               movl    _chainlenwmask, %chainlenwmask
+               jmp     LookupLoop
+
+/* Accept the current string, with the maximum possible length.                */
+
+LenMaximum:
+               movl    $MAX_MATCH, %bestlend
+               movl    %curmatchd, dsMatchStart
+
+/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len;          */
+/* return s->lookahead;                                                        */
+
+LeaveNow:
+               movl    dsLookahead, %eax
+               cmpl    %eax, %bestlend
+               cmovngl %bestlend, %eax
+LookaheadRet:
+
+/* Restore the registers and return from whence we came.                       */
+
+       mov     save_rsi, %rsi
+       mov     save_rbx, %rbx
+       mov     save_r12, %r12
+       mov     save_r13, %r13
+       mov     save_r14, %r14
+       mov     save_r15, %r15
+
+       ret
+
+match_init:    ret
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/bndsrc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/bndsrc
new file mode 100644 (file)
index 0000000..d048dbb
--- /dev/null
@@ -0,0 +1,206 @@
+STRPGMEXP PGMLVL(*CURRENT) SIGNATURE('ZLIB')
+
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+/*   Version 1.1.3 entry points.                                    */
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+
+/********************************************************************/
+/*   *MODULE      ADLER32      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("adler32")
+
+/********************************************************************/
+/*   *MODULE      COMPRESS     ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("compress")
+  EXPORT SYMBOL("compress2")
+
+/********************************************************************/
+/*   *MODULE      CRC32        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("crc32")
+  EXPORT SYMBOL("get_crc_table")
+
+/********************************************************************/
+/*   *MODULE      DEFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("deflate")
+  EXPORT SYMBOL("deflateEnd")
+  EXPORT SYMBOL("deflateSetDictionary")
+  EXPORT SYMBOL("deflateCopy")
+  EXPORT SYMBOL("deflateReset")
+  EXPORT SYMBOL("deflateParams")
+  EXPORT SYMBOL("deflatePrime")
+  EXPORT SYMBOL("deflateInit_")
+  EXPORT SYMBOL("deflateInit2_")
+
+/********************************************************************/
+/*   *MODULE      GZIO         ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzopen")
+  EXPORT SYMBOL("gzdopen")
+  EXPORT SYMBOL("gzsetparams")
+  EXPORT SYMBOL("gzread")
+  EXPORT SYMBOL("gzwrite")
+  EXPORT SYMBOL("gzprintf")
+  EXPORT SYMBOL("gzputs")
+  EXPORT SYMBOL("gzgets")
+  EXPORT SYMBOL("gzputc")
+  EXPORT SYMBOL("gzgetc")
+  EXPORT SYMBOL("gzflush")
+  EXPORT SYMBOL("gzseek")
+  EXPORT SYMBOL("gzrewind")
+  EXPORT SYMBOL("gztell")
+  EXPORT SYMBOL("gzeof")
+  EXPORT SYMBOL("gzclose")
+  EXPORT SYMBOL("gzerror")
+
+/********************************************************************/
+/*   *MODULE      INFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflate")
+  EXPORT SYMBOL("inflateEnd")
+  EXPORT SYMBOL("inflateSetDictionary")
+  EXPORT SYMBOL("inflateSync")
+  EXPORT SYMBOL("inflateReset")
+  EXPORT SYMBOL("inflateInit_")
+  EXPORT SYMBOL("inflateInit2_")
+  EXPORT SYMBOL("inflateSyncPoint")
+
+/********************************************************************/
+/*   *MODULE      UNCOMPR      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("uncompress")
+
+/********************************************************************/
+/*   *MODULE      ZUTIL        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("zlibVersion")
+  EXPORT SYMBOL("zError")
+
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+/*   Version 1.2.1 additional entry points.                         */
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+
+/********************************************************************/
+/*   *MODULE      COMPRESS     ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("compressBound")
+
+/********************************************************************/
+/*   *MODULE      DEFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("deflateBound")
+
+/********************************************************************/
+/*   *MODULE      GZIO         ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzungetc")
+  EXPORT SYMBOL("gzclearerr")
+
+/********************************************************************/
+/*   *MODULE      INFBACK      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflateBack")
+  EXPORT SYMBOL("inflateBackEnd")
+  EXPORT SYMBOL("inflateBackInit_")
+
+/********************************************************************/
+/*   *MODULE      INFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflateCopy")
+
+/********************************************************************/
+/*   *MODULE      ZUTIL        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("zlibCompileFlags")
+
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+/*   Version 1.2.5 additional entry points.                         */
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+
+/********************************************************************/
+/*   *MODULE      ADLER32      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("adler32_combine")
+  EXPORT SYMBOL("adler32_combine64")
+
+/********************************************************************/
+/*   *MODULE      CRC32        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("crc32_combine")
+  EXPORT SYMBOL("crc32_combine64")
+
+/********************************************************************/
+/*   *MODULE      GZLIB        ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzbuffer")
+  EXPORT SYMBOL("gzoffset")
+  EXPORT SYMBOL("gzoffset64")
+  EXPORT SYMBOL("gzopen64")
+  EXPORT SYMBOL("gzseek64")
+  EXPORT SYMBOL("gztell64")
+
+/********************************************************************/
+/*   *MODULE      GZREAD       ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzclose_r")
+
+/********************************************************************/
+/*   *MODULE      GZWRITE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzclose_w")
+
+/********************************************************************/
+/*   *MODULE      INFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflateMark")
+  EXPORT SYMBOL("inflatePrime")
+  EXPORT SYMBOL("inflateReset2")
+  EXPORT SYMBOL("inflateUndermine")
+
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+/*   Version 1.2.6 additional entry points.                         */
+/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
+
+/********************************************************************/
+/*   *MODULE      DEFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("deflateResetKeep")
+  EXPORT SYMBOL("deflatePending")
+
+/********************************************************************/
+/*   *MODULE      GZWRITE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("gzgetc_")
+  EXPORT SYMBOL("gzflags")
+
+/********************************************************************/
+/*   *MODULE      INFLATE      ZLIB         01/02/01  00:15:09      */
+/********************************************************************/
+
+  EXPORT SYMBOL("inflateResetKeep")
+
+ENDPGMEXP
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/compile.clp b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/compile.clp
new file mode 100644 (file)
index 0000000..ed96ad4
--- /dev/null
@@ -0,0 +1,110 @@
+/******************************************************************************/
+/*                                                                            */
+/*  ZLIB                                                                      */
+/*                                                                            */
+/*    Compile sources into modules and link them into a service program.      */
+/*                                                                            */
+/******************************************************************************/
+
+             PGM
+
+/*      Configuration adjustable parameters.                                  */
+
+             DCL        VAR(&SRCLIB) TYPE(*CHAR) LEN(10) +
+                          VALUE('ZLIB')                         /* Source library. */
+             DCL        VAR(&SRCFILE) TYPE(*CHAR) LEN(10) +
+                          VALUE('SOURCES')                      /* Source member file. */
+             DCL        VAR(&CTLFILE) TYPE(*CHAR) LEN(10) +
+                          VALUE('TOOLS')                        /* Control member file. */
+
+             DCL        VAR(&MODLIB) TYPE(*CHAR) LEN(10) +
+                          VALUE('ZLIB')                         /* Module library. */
+
+             DCL        VAR(&SRVLIB) TYPE(*CHAR) LEN(10) +
+                          VALUE('LGPL')                         /* Service program library. */
+
+             DCL        VAR(&CFLAGS) TYPE(*CHAR) +
+                          VALUE('OPTIMIZE(40)')                 /* Compile options. */
+
+             DCL        VAR(&TGTRLS) TYPE(*CHAR) +
+                          VALUE('V5R3M0')                       /* Target release. */
+
+
+/*      Working storage.                                                      */
+
+             DCL        VAR(&CMDLEN) TYPE(*DEC) LEN(15 5) VALUE(300)    /* Command length. */
+             DCL        VAR(&CMD) TYPE(*CHAR) LEN(512)
+             DCL        VAR(&FIXDCMD) TYPE(*CHAR) LEN(512)
+
+
+/*      Compile sources into modules.                                         */
+
+             CHGVAR     VAR(&FIXDCMD) VALUE('CRTCMOD' *BCAT &CFLAGS *BCAT      +
+                        'SYSIFCOPT(*IFS64IO)' *BCAT                            +
+                        'DEFINE(''_LARGEFILE64_SOURCE''' *BCAT                 +
+                        '''_LFS64_LARGEFILE=1'') TGTRLS(' *TCAT &TGTRLS *TCAT  +
+                        ') SRCFILE(' *TCAT &SRCLIB *TCAT '/' *TCAT             +
+                        &SRCFILE *TCAT ') MODULE(' *TCAT &MODLIB *TCAT '/')
+
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'ADLER32)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'COMPRESS)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'CRC32)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'DEFLATE)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'GZCLOSE)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'GZLIB)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'GZREAD)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'GZWRITE)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'INFBACK)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'INFFAST)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'INFLATE)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'INFTREES)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'TREES)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'UNCOMPR)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+             CHGVAR     VAR(&CMD) VALUE(&FIXDCMD *TCAT 'ZUTIL)')
+             CALL       PGM(QCMDEXC) PARM(&CMD &CMDLEN)
+
+
+/*      Link modules into a service program.                                  */
+
+             CRTSRVPGM  SRVPGM(&SRVLIB/ZLIB) +
+                          MODULE(&MODLIB/ADLER32     &MODLIB/COMPRESS    +
+                                 &MODLIB/CRC32       &MODLIB/DEFLATE     +
+                                 &MODLIB/GZCLOSE     &MODLIB/GZLIB       +
+                                 &MODLIB/GZREAD      &MODLIB/GZWRITE     +
+                                 &MODLIB/INFBACK     &MODLIB/INFFAST     +
+                                 &MODLIB/INFLATE     &MODLIB/INFTREES    +
+                                 &MODLIB/TREES       &MODLIB/UNCOMPR     +
+                                 &MODLIB/ZUTIL)                          +
+                          SRCFILE(&SRCLIB/&CTLFILE) SRCMBR(BNDSRC)       +
+                          TEXT('ZLIB 1.2.6') TGTRLS(&TGTRLS)
+
+             ENDPGM
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/readme.txt
new file mode 100644 (file)
index 0000000..397fe99
--- /dev/null
@@ -0,0 +1,115 @@
+        ZLIB version 1.2.6 for AS400 installation instructions
+
+I) From an AS400 *SAVF file:
+
+1)      Unpacking archive to an AS400 save file
+
+On the AS400:
+
+_       Create the ZLIB AS400 library:
+
+        CRTLIB LIB(ZLIB) TYPE(*PROD) TEXT('ZLIB compression API library')
+
+_       Create a work save file, for example:
+
+                CRTSAVF FILE(ZLIB/ZLIBSAVF)
+
+On a PC connected to the target AS400:
+
+_       Unpack the save file image to a PC file "ZLIBSAVF"
+_       Upload this file into the save file on the AS400, for example
+                using ftp in BINARY mode.
+
+
+2)      Populating the ZLIB AS400 source library
+
+On the AS400:
+
+_       Extract the saved objects into the ZLIB AS400 library using:
+
+RSTOBJ OBJ(*ALL) SAVLIB(ZLIB) DEV(*SAVF) SAVF(ZLIB/ZLIBSAVF) RSTLIB(ZLIB)
+
+
+3)      Customize installation:
+
+_       Edit CL member ZLIB/TOOLS(COMPILE) and change parameters if needed,
+                according to the comments.
+
+_       Compile this member with:
+
+        CRTCLPGM PGM(ZLIB/COMPILE) SRCFILE(ZLIB/TOOLS) SRCMBR(COMPILE)
+
+
+4)      Compile and generate the service program:
+
+_       This can now be done by executing:
+
+        CALL PGM(ZLIB/COMPILE)
+
+
+
+II) From the original source distribution:
+
+1)      On the AS400, create the source library:
+
+        CRTLIB LIB(ZLIB) TYPE(*PROD) TEXT('ZLIB compression API library')
+
+2)      Create the source files:
+
+        CRTSRCPF FILE(ZLIB/SOURCES) RCDLEN(112) TEXT('ZLIB library modules')
+        CRTSRCPF FILE(ZLIB/H)       RCDLEN(112) TEXT('ZLIB library includes')
+        CRTSRCPF FILE(ZLIB/TOOLS)   RCDLEN(112) TEXT('ZLIB library control utilities')
+
+3)      From the machine hosting the distribution files, upload them (with
+                FTP in text mode, for example) according to the following table:
+
+    Original    AS400   AS400    AS400 AS400
+    file        file    member   type  description
+                SOURCES                Original ZLIB C subprogram sources
+    adler32.c           ADLER32  C     ZLIB - Compute the Adler-32 checksum of a dta strm
+    compress.c          COMPRESS C     ZLIB - Compress a memory buffer
+    crc32.c             CRC32    C     ZLIB - Compute the CRC-32 of a data stream
+    deflate.c           DEFLATE  C     ZLIB - Compress data using the deflation algorithm
+    gzclose.c           GZCLOSE  C     ZLIB - Close .gz files
+    gzlib.c             GZLIB    C     ZLIB - Miscellaneous .gz files IO support
+    gzread.c            GZREAD   C     ZLIB - Read .gz files
+    gzwrite.c           GZWRITE  C     ZLIB - Write .gz files
+    infback.c           INFBACK  C     ZLIB - Inflate using a callback interface
+    inffast.c           INFFAST  C     ZLIB - Fast proc. literals & length/distance pairs
+    inflate.c           INFLATE  C     ZLIB - Interface to inflate modules
+    inftrees.c          INFTREES C     ZLIB - Generate Huffman trees for efficient decode
+    trees.c             TREES    C     ZLIB - Output deflated data using Huffman coding
+    uncompr.c           UNCOMPR  C     ZLIB - Decompress a memory buffer
+    zutil.c             ZUTIL    C     ZLIB - Target dependent utility functions
+                H                      Original ZLIB C and ILE/RPG include files
+    crc32.h             CRC32    C     ZLIB - CRC32 tables
+    deflate.h           DEFLATE  C     ZLIB - Internal compression state
+    gzguts.h            GZGUTS   C     ZLIB - Definitions for the gzclose module
+    inffast.h           INFFAST  C     ZLIB - Header to use inffast.c
+    inffixed.h          INFFIXED C     ZLIB - Table for decoding fixed codes
+    inflate.h           INFLATE  C     ZLIB - Internal inflate state definitions
+    inftrees.h          INFTREES C     ZLIB - Header to use inftrees.c
+    trees.h             TREES    C     ZLIB - Created automatically with -DGEN_TREES_H
+    zconf.h             ZCONF    C     ZLIB - Compression library configuration
+    zlib.h              ZLIB     C     ZLIB - Compression library C user interface
+    as400/zlib.inc      ZLIB.INC RPGLE ZLIB - Compression library ILE RPG user interface
+    zutil.h             ZUTIL    C     ZLIB - Internal interface and configuration
+                TOOLS                  Building source software & AS/400 README
+    as400/bndsrc        BNDSRC         Entry point exportation list
+    as400/compile.clp   COMPILE  CLP   Compile sources & generate service program
+    as400/readme.txt    README   TXT   Installation instructions
+
+4)      Continue as in I)3).
+
+
+
+
+Notes:  For AS400 ILE RPG programmers, a /copy member defining the ZLIB
+                API prototypes for ILE RPG can be found in ZLIB/H(ZLIB.INC).
+                Please read comments in this member for more information.
+
+        Remember that most foreign textual data are ASCII coded: this
+                implementation does not handle conversion from/to ASCII, so
+                text data code conversions must be done explicitely.
+
+        Mainly for the reason above, always open zipped files in binary mode.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/zlib.inc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/as400/zlib.inc
new file mode 100644 (file)
index 0000000..5ce905f
--- /dev/null
@@ -0,0 +1,447 @@
+      *  ZLIB.INC - Interface to the general purpose compression library
+      *
+      *  ILE RPG400 version by Patrick Monnerat, DATASPHERE.
+      *  Version 1.2.6
+      *
+      *
+      *  WARNING:
+      *     Procedures inflateInit(), inflateInit2(), deflateInit(),
+      *         deflateInit2() and inflateBackInit() need to be called with
+      *         two additional arguments:
+      *         the package version string and the stream control structure.
+      *         size. This is needed because RPG lacks some macro feature.
+      *         Call these procedures as:
+      *             inflateInit(...: ZLIB_VERSION: %size(z_stream))
+      *
+      /if not defined(ZLIB_H_)
+      /define ZLIB_H_
+      *
+      **************************************************************************
+      *                               Constants
+      **************************************************************************
+      *
+      *  Versioning information.
+      *
+     D ZLIB_VERSION    C                   '1.2.6'
+     D ZLIB_VERNUM     C                   X'1260'
+     D ZLIB_VER_MAJOR  C                   1
+     D ZLIB_VER_MINOR  C                   2
+     D ZLIB_VER_REVISION...
+     D                 C                   6
+     D ZLIB_VER_SUBREVISION...
+     D                 C                   0
+      *
+      *  Other equates.
+      *
+     D Z_NO_FLUSH      C                   0
+     D Z_PARTIAL_FLUSH...
+     D                 C                   1
+     D Z_SYNC_FLUSH    C                   2
+     D Z_FULL_FLUSH    C                   3
+     D Z_FINISH        C                   4
+     D Z_BLOCK         C                   5
+     D Z_TREES         C                   6
+      *
+     D Z_OK            C                   0
+     D Z_STREAM_END    C                   1
+     D Z_NEED_DICT     C                   2
+     D Z_ERRNO         C                   -1
+     D Z_STREAM_ERROR  C                   -2
+     D Z_DATA_ERROR    C                   -3
+     D Z_MEM_ERROR     C                   -4
+     D Z_BUF_ERROR     C                   -5
+     DZ_VERSION_ERROR  C                   -6
+      *
+     D Z_NO_COMPRESSION...
+     D                 C                   0
+     D Z_BEST_SPEED    C                   1
+     D Z_BEST_COMPRESSION...
+     D                 C                   9
+     D Z_DEFAULT_COMPRESSION...
+     D                 C                   -1
+      *
+     D Z_FILTERED      C                   1
+     D Z_HUFFMAN_ONLY  C                   2
+     D Z_RLE           C                   3
+     D Z_DEFAULT_STRATEGY...
+     D                 C                   0
+      *
+     D Z_BINARY        C                   0
+     D Z_ASCII         C                   1
+     D Z_UNKNOWN       C                   2
+      *
+     D Z_DEFLATED      C                   8
+      *
+     D Z_NULL          C                   0
+      *
+      **************************************************************************
+      *                                 Types
+      **************************************************************************
+      *
+     D z_streamp       S               *                                        Stream struct ptr
+     D gzFile          S               *                                        File pointer
+     D z_off_t         S             10i 0                                      Stream offsets
+     D z_off64_t       S             20i 0                                      Stream offsets
+      *
+      **************************************************************************
+      *                               Structures
+      **************************************************************************
+      *
+      *  The GZIP encode/decode stream support structure.
+      *
+     D z_stream        DS                  align based(z_streamp)
+     D  zs_next_in                     *                                        Next input byte
+     D  zs_avail_in                  10U 0                                      Byte cnt at next_in
+     D  zs_total_in                  10U 0                                      Total bytes read
+     D  zs_next_out                    *                                        Output buffer ptr
+     D  zs_avail_out                 10U 0                                      Room left @ next_out
+     D  zs_total_out                 10U 0                                      Total bytes written
+     D  zs_msg                         *                                        Last errmsg or null
+     D  zs_state                       *                                        Internal state
+     D  zs_zalloc                      *   procptr                              Int. state allocator
+     D  zs_free                        *   procptr                              Int. state dealloc.
+     D  zs_opaque                      *                                        Private alloc. data
+     D  zs_data_type                 10i 0                                      ASC/BIN best guess
+     D  zs_adler                     10u 0                                      Uncompr. adler32 val
+     D                               10U 0                                      Reserved
+     D                               10U 0                                      Ptr. alignment
+      *
+      **************************************************************************
+      *                     Utility function prototypes
+      **************************************************************************
+      *
+     D compress        PR            10I 0 extproc('compress')
+     D  dest                      65535    options(*varsize)                    Destination buffer
+     D  destLen                      10U 0                                      Destination length
+     D  source                    65535    const options(*varsize)              Source buffer
+     D  sourceLen                    10u 0 value                                Source length
+      *
+     D compress2       PR            10I 0 extproc('compress2')
+     D  dest                      65535    options(*varsize)                    Destination buffer
+     D  destLen                      10U 0                                      Destination length
+     D  source                    65535    const options(*varsize)              Source buffer
+     D  sourceLen                    10U 0 value                                Source length
+     D  level                        10I 0 value                                Compression level
+      *
+     D compressBound   PR            10U 0 extproc('compressBound')
+     D  sourceLen                    10U 0 value
+      *
+     D uncompress      PR            10I 0 extproc('uncompress')
+     D  dest                      65535    options(*varsize)                    Destination buffer
+     D  destLen                      10U 0                                      Destination length
+     D  source                    65535    const options(*varsize)              Source buffer
+     D  sourceLen                    10U 0 value                                Source length
+      *
+      /if not defined(LARGE_FILES)
+     D gzopen          PR                  extproc('gzopen')
+     D                                     like(gzFile)
+     D  path                           *   value options(*string)               File pathname
+     D  mode                           *   value options(*string)               Open mode
+      /else
+     D gzopen          PR                  extproc('gzopen64')
+     D                                     like(gzFile)
+     D  path                           *   value options(*string)               File pathname
+     D  mode                           *   value options(*string)               Open mode
+      *
+     D gzopen64        PR                  extproc('gzopen64')
+     D                                     like(gzFile)
+     D  path                           *   value options(*string)               File pathname
+     D  mode                           *   value options(*string)               Open mode
+      /endif
+      *
+     D gzdopen         PR                  extproc('gzdopen')
+     D                                     like(gzFile)
+     D  fd                           10I 0 value                                File descriptor
+     D  mode                           *   value options(*string)               Open mode
+      *
+     D gzbuffer        PR            10I 0 extproc('gzbuffer')
+     D  file                               value like(gzFile)                   File pointer
+     D  size                         10U 0 value
+      *
+     D gzsetparams     PR            10I 0 extproc('gzsetparams')
+     D  file                               value like(gzFile)                   File pointer
+     D  level                        10I 0 value
+     D  strategy                     10I 0 value
+      *
+     D gzread          PR            10I 0 extproc('gzread')
+     D  file                               value like(gzFile)                   File pointer
+     D  buf                       65535    options(*varsize)                    Buffer
+     D  len                          10u 0 value                                Buffer length
+      *
+     D gzwrite         PR            10I 0 extproc('gzwrite')
+     D  file                               value like(gzFile)                   File pointer
+     D  buf                       65535    const options(*varsize)              Buffer
+     D  len                          10u 0 value                                Buffer length
+      *
+     D gzputs          PR            10I 0 extproc('gzputs')
+     D  file                               value like(gzFile)                   File pointer
+     D  s                              *   value options(*string)               String to output
+      *
+     D gzgets          PR              *   extproc('gzgets')
+     D  file                               value like(gzFile)                   File pointer
+     D  buf                       65535    options(*varsize)                    Read buffer
+     D  len                          10i 0 value                                Buffer length
+      *
+     D gzputc          PR            10i 0 extproc('gzputc')
+     D  file                               value like(gzFile)                   File pointer
+     D  c                            10I 0 value                                Character to write
+      *
+     D gzgetc          PR            10i 0 extproc('gzgetc')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzgetc_         PR            10i 0 extproc('gzgetc_')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzungetc        PR            10i 0 extproc('gzungetc')
+     D  c                            10I 0 value                                Character to push
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzflush         PR            10i 0 extproc('gzflush')
+     D  file                               value like(gzFile)                   File pointer
+     D  flush                        10I 0 value                                Type of flush
+      *
+      /if not defined(LARGE_FILES)
+     D gzseek          PR                  extproc('gzseek')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+     D  offset                             value like(z_off_t)                  Offset
+     D  whence                       10i 0 value                                Origin
+      /else
+     D gzseek          PR                  extproc('gzseek64')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+     D  offset                             value like(z_off_t)                  Offset
+     D  whence                       10i 0 value                                Origin
+      *
+     D gzseek64        PR                  extproc('gzseek64')
+     D                                     like(z_off64_t)
+     D  file                               value like(gzFile)                   File pointer
+     D  offset                             value like(z_off64_t)                Offset
+     D  whence                       10i 0 value                                Origin
+      /endif
+      *
+     D gzrewind        PR            10i 0 extproc('gzrewind')
+     D  file                               value like(gzFile)                   File pointer
+      *
+      /if not defined(LARGE_FILES)
+     D gztell          PR                  extproc('gztell')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+      /else
+     D gztell          PR                  extproc('gztell64')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gztell64        PR                  extproc('gztell64')
+     D                                     like(z_off64_t)
+     D  file                               value like(gzFile)                   File pointer
+      /endif
+      *
+      /if not defined(LARGE_FILES)
+     D gzoffset        PR                  extproc('gzoffset')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+      /else
+     D gzoffset        PR                  extproc('gzoffset64')
+     D                                     like(z_off_t)
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzoffset64      PR                  extproc('gzoffset64')
+     D                                     like(z_off64_t)
+     D  file                               value like(gzFile)                   File pointer
+      /endif
+      *
+     D gzeof           PR            10i 0 extproc('gzeof')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzclose_r       PR            10i 0 extproc('gzclose_r')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzclose_w       PR            10i 0 extproc('gzclose_w')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzclose         PR            10i 0 extproc('gzclose')
+     D  file                               value like(gzFile)                   File pointer
+      *
+     D gzerror         PR              *   extproc('gzerror')                   Error string
+     D  file                               value like(gzFile)                   File pointer
+     D  errnum                       10I 0                                      Error code
+      *
+     D gzclearerr      PR                  extproc('gzclearerr')
+     D  file                               value like(gzFile)                   File pointer
+      *
+      **************************************************************************
+      *                        Basic function prototypes
+      **************************************************************************
+      *
+     D zlibVersion     PR              *   extproc('zlibVersion')               Version string
+      *
+     D deflateInit     PR            10I 0 extproc('deflateInit_')              Init. compression
+     D  strm                               like(z_stream)                       Compression stream
+     D  level                        10I 0 value                                Compression level
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D deflate         PR            10I 0 extproc('deflate')                   Compress data
+     D  strm                               like(z_stream)                       Compression stream
+     D  flush                        10I 0 value                                Flush type required
+      *
+     D deflateEnd      PR            10I 0 extproc('deflateEnd')                Termin. compression
+     D  strm                               like(z_stream)                       Compression stream
+      *
+     D inflateInit     PR            10I 0 extproc('inflateInit_')              Init. expansion
+     D  strm                               like(z_stream)                       Expansion stream
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D inflate         PR            10I 0 extproc('inflate')                   Expand data
+     D  strm                               like(z_stream)                       Expansion stream
+     D  flush                        10I 0 value                                Flush type required
+      *
+     D inflateEnd      PR            10I 0 extproc('inflateEnd')                Termin. expansion
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+      **************************************************************************
+      *                        Advanced function prototypes
+      **************************************************************************
+      *
+     D deflateInit2    PR            10I 0 extproc('deflateInit2_')             Init. compression
+     D  strm                               like(z_stream)                       Compression stream
+     D  level                        10I 0 value                                Compression level
+     D  method                       10I 0 value                                Compression method
+     D  windowBits                   10I 0 value                                log2(window size)
+     D  memLevel                     10I 0 value                                Mem/cmpress tradeoff
+     D  strategy                     10I 0 value                                Compression stategy
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D deflateSetDictionary...
+     D                 PR            10I 0 extproc('deflateSetDictionary')      Init. dictionary
+     D  strm                               like(z_stream)                       Compression stream
+     D  dictionary                65535    const options(*varsize)              Dictionary bytes
+     D  dictLength                   10U 0 value                                Dictionary length
+      *
+     D deflateCopy     PR            10I 0 extproc('deflateCopy')               Compress strm 2 strm
+     D  dest                               like(z_stream)                       Destination stream
+     D  source                             like(z_stream)                       Source stream
+      *
+     D deflateReset    PR            10I 0 extproc('deflateReset')              End and init. stream
+     D  strm                               like(z_stream)                       Compression stream
+      *
+     D deflateParams   PR            10I 0 extproc('deflateParams')             Change level & strat
+     D  strm                               like(z_stream)                       Compression stream
+     D  level                        10I 0 value                                Compression level
+     D  strategy                     10I 0 value                                Compression stategy
+      *
+     D deflateBound    PR            10U 0 extproc('deflateBound')              Change level & strat
+     D  strm                               like(z_stream)                       Compression stream
+     D  sourcelen                    10U 0 value                                Compression level
+      *
+     D deflatePending  PR            10I 0 extproc('deflatePending')            Change level & strat
+     D  strm                               like(z_stream)                       Compression stream
+     D  pending                      10U 0                                      Pending bytes
+     D  bits                         10I 0                                      Pending bits
+      *
+     D deflatePrime    PR            10I 0 extproc('deflatePrime')              Change level & strat
+     D  strm                               like(z_stream)                       Compression stream
+     D  bits                         10I 0 value                                # of bits to insert
+     D  value                        10I 0 value                                Bits to insert
+      *
+     D inflateInit2    PR            10I 0 extproc('inflateInit2_')             Init. expansion
+     D  strm                               like(z_stream)                       Expansion stream
+     D  windowBits                   10I 0 value                                log2(window size)
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D inflateSetDictionary...
+     D                 PR            10I 0 extproc('inflateSetDictionary')      Init. dictionary
+     D  strm                               like(z_stream)                       Expansion stream
+     D  dictionary                65535    const options(*varsize)              Dictionary bytes
+     D  dictLength                   10U 0 value                                Dictionary length
+      *
+     D inflateSync     PR            10I 0 extproc('inflateSync')               Sync. expansion
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D inflateCopy     PR            10I 0 extproc('inflateCopy')
+     D  dest                               like(z_stream)                       Destination stream
+     D  source                             like(z_stream)                       Source stream
+      *
+     D inflateReset    PR            10I 0 extproc('inflateReset')              End and init. stream
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D inflateReset2   PR            10I 0 extproc('inflateReset2')             End and init. stream
+     D  strm                               like(z_stream)                       Expansion stream
+     D  windowBits                   10I 0 value                                Log2(buffer size)
+      *
+     D inflatePrime    PR            10I 0 extproc('inflatePrime')              Insert bits
+     D  strm                               like(z_stream)                       Expansion stream
+     D  bits                         10I 0 value                                Bit count
+     D  value                        10I 0 value                                Bits to insert
+      *
+     D inflateMark     PR            10I 0 extproc('inflateMark')               Get inflate info
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D inflateBackInit...
+     D                 PR            10I 0 extproc('inflateBackInit_')
+     D  strm                               like(z_stream)                       Expansion stream
+     D  windowBits                   10I 0 value                                Log2(buffer size)
+     D  window                    65535    options(*varsize)                    Buffer
+     D  version                        *   value options(*string)               Version string
+     D  stream_size                  10i 0 value                                Stream struct. size
+      *
+     D inflateBack     PR            10I 0 extproc('inflateBack')
+     D  strm                               like(z_stream)                       Expansion stream
+     D  in                             *   value procptr                        Input function
+     D  in_desc                        *   value                                Input descriptor
+     D  out                            *   value procptr                        Output function
+     D  out_desc                       *   value                                Output descriptor
+      *
+     D inflateBackEnd  PR            10I 0 extproc('inflateBackEnd')
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D zlibCompileFlags...
+     D                 PR            10U 0 extproc('zlibCompileFlags')
+      *
+      **************************************************************************
+      *                        Checksum function prototypes
+      **************************************************************************
+      *
+     D adler32         PR            10U 0 extproc('adler32')                   New checksum
+     D  adler                        10U 0 value                                Old checksum
+     D  buf                       65535    const options(*varsize)              Bytes to accumulate
+     D  len                          10U 0 value                                Buffer length
+      *
+     D crc32           PR            10U 0 extproc('crc32')                     New checksum
+     D  crc                          10U 0 value                                Old checksum
+     D  buf                       65535    const options(*varsize)              Bytes to accumulate
+     D  len                          10U 0 value                                Buffer length
+      *
+      **************************************************************************
+      *                     Miscellaneous function prototypes
+      **************************************************************************
+      *
+     D zError          PR              *   extproc('zError')                    Error string
+     D  err                          10I 0 value                                Error code
+      *
+     D inflateSyncPoint...
+     D                 PR            10I 0 extproc('inflateSyncPoint')
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D get_crc_table   PR              *   extproc('get_crc_table')             Ptr to ulongs
+      *
+     D inflateUndermine...
+     D                 PR            10I 0 extproc('inflateUndermine')
+     D  strm                               like(z_stream)                       Expansion stream
+     D  arg                          10I 0 value                                Error code
+      *
+     D inflateResetKeep...
+     D                 PR            10I 0 extproc('inflateResetKeep')          End and init. stream
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D deflateResetKeep...
+     D                 PR            10I 0 extproc('deflateResetKeep')          End and init. stream
+     D  strm                               like(z_stream)                       Expansion stream
+      *
+     D gzflags         PR            10U 0 extproc('gzflags')
+      *
+      /endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/asm686/README.686 b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/asm686/README.686
new file mode 100644 (file)
index 0000000..a0bf3be
--- /dev/null
@@ -0,0 +1,51 @@
+This is a patched version of zlib, modified to use
+Pentium-Pro-optimized assembly code in the deflation algorithm. The
+files changed/added by this patch are:
+
+README.686
+match.S
+
+The speedup that this patch provides varies, depending on whether the
+compiler used to build the original version of zlib falls afoul of the
+PPro's speed traps. My own tests show a speedup of around 10-20% at
+the default compression level, and 20-30% using -9, against a version
+compiled using gcc 2.7.2.3. Your mileage may vary.
+
+Note that this code has been tailored for the PPro/PII in particular,
+and will not perform particuarly well on a Pentium.
+
+If you are using an assembler other than GNU as, you will have to
+translate match.S to use your assembler's syntax. (Have fun.)
+
+Brian Raiter
+breadbox@muppetlabs.com
+April, 1998
+
+
+Added for zlib 1.1.3:
+
+The patches come from
+http://www.muppetlabs.com/~breadbox/software/assembly.html
+
+To compile zlib with this asm file, copy match.S to the zlib directory
+then do:
+
+CFLAGS="-O3 -DASMV" ./configure
+make OBJA=match.o
+
+
+Update:
+
+I've been ignoring these assembly routines for years, believing that
+gcc's generated code had caught up with it sometime around gcc 2.95
+and the major rearchitecting of the Pentium 4. However, I recently
+learned that, despite what I believed, this code still has some life
+in it. On the Pentium 4 and AMD64 chips, it continues to run about 8%
+faster than the code produced by gcc 4.1.
+
+In acknowledgement of its continuing usefulness, I've altered the
+license to match that of the rest of zlib. Share and Enjoy!
+
+Brian Raiter
+breadbox@muppetlabs.com
+April, 2007
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/asm686/match.S b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/asm686/match.S
new file mode 100644 (file)
index 0000000..fa42109
--- /dev/null
@@ -0,0 +1,357 @@
+/* match.S -- x86 assembly version of the zlib longest_match() function.
+ * Optimized for the Intel 686 chips (PPro and later).
+ *
+ * Copyright (C) 1998, 2007 Brian Raiter <breadbox@muppetlabs.com>
+ *
+ * This software is provided 'as-is', without any express or implied
+ * warranty.  In no event will the author be held liable for any damages
+ * arising from the use of this software.
+ *
+ * Permission is granted to anyone to use this software for any purpose,
+ * including commercial applications, and to alter it and redistribute it
+ * freely, subject to the following restrictions:
+ *
+ * 1. The origin of this software must not be misrepresented; you must not
+ *    claim that you wrote the original software. If you use this software
+ *    in a product, an acknowledgment in the product documentation would be
+ *    appreciated but is not required.
+ * 2. Altered source versions must be plainly marked as such, and must not be
+ *    misrepresented as being the original software.
+ * 3. This notice may not be removed or altered from any source distribution.
+ */
+
+#ifndef NO_UNDERLINE
+#define        match_init      _match_init
+#define        longest_match   _longest_match
+#endif
+
+#define        MAX_MATCH       (258)
+#define        MIN_MATCH       (3)
+#define        MIN_LOOKAHEAD   (MAX_MATCH + MIN_MATCH + 1)
+#define        MAX_MATCH_8     ((MAX_MATCH + 7) & ~7)
+
+/* stack frame offsets */
+
+#define        chainlenwmask           0       /* high word: current chain len */
+                                       /* low word: s->wmask           */
+#define        window                  4       /* local copy of s->window      */
+#define        windowbestlen           8       /* s->window + bestlen          */
+#define        scanstart               16      /* first two bytes of string    */
+#define        scanend                 12      /* last two bytes of string     */
+#define        scanalign               20      /* dword-misalignment of string */
+#define        nicematch               24      /* a good enough match size     */
+#define        bestlen                 28      /* size of best match so far    */
+#define        scan                    32      /* ptr to string wanting match  */
+
+#define        LocalVarsSize           (36)
+/*     saved ebx               36 */
+/*     saved edi               40 */
+/*     saved esi               44 */
+/*     saved ebp               48 */
+/*     return address          52 */
+#define        deflatestate            56      /* the function arguments       */
+#define        curmatch                60
+
+/* All the +zlib1222add offsets are due to the addition of fields
+ *  in zlib in the deflate_state structure since the asm code was first written
+ * (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").
+ * (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").
+ * if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").
+ */
+
+#define zlib1222add            (8)
+
+#define        dsWSize                 (36+zlib1222add)
+#define        dsWMask                 (44+zlib1222add)
+#define        dsWindow                (48+zlib1222add)
+#define        dsPrev                  (56+zlib1222add)
+#define        dsMatchLen              (88+zlib1222add)
+#define        dsPrevMatch             (92+zlib1222add)
+#define        dsStrStart              (100+zlib1222add)
+#define        dsMatchStart            (104+zlib1222add)
+#define        dsLookahead             (108+zlib1222add)
+#define        dsPrevLen               (112+zlib1222add)
+#define        dsMaxChainLen           (116+zlib1222add)
+#define        dsGoodMatch             (132+zlib1222add)
+#define        dsNiceMatch             (136+zlib1222add)
+
+
+.file "match.S"
+
+.globl match_init, longest_match
+
+.text
+
+/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */
+.cfi_sections  .debug_frame
+
+longest_match:
+
+.cfi_startproc
+/* Save registers that the compiler may be using, and adjust %esp to   */
+/* make room for our stack frame.                                      */
+
+               pushl   %ebp
+               .cfi_def_cfa_offset 8
+               .cfi_offset ebp, -8
+               pushl   %edi
+               .cfi_def_cfa_offset 12
+               pushl   %esi
+               .cfi_def_cfa_offset 16
+               pushl   %ebx
+               .cfi_def_cfa_offset 20
+               subl    $LocalVarsSize, %esp
+               .cfi_def_cfa_offset LocalVarsSize+20
+
+/* Retrieve the function arguments. %ecx will hold cur_match           */
+/* throughout the entire function. %edx will hold the pointer to the   */
+/* deflate_state structure during the function's setup (before         */
+/* entering the main loop).                                            */
+
+               movl    deflatestate(%esp), %edx
+               movl    curmatch(%esp), %ecx
+
+/* uInt wmask = s->w_mask;                                             */
+/* unsigned chain_length = s->max_chain_length;                                */
+/* if (s->prev_length >= s->good_match) {                              */
+/*     chain_length >>= 2;                                             */
+/* }                                                                   */
+               movl    dsPrevLen(%edx), %eax
+               movl    dsGoodMatch(%edx), %ebx
+               cmpl    %ebx, %eax
+               movl    dsWMask(%edx), %eax
+               movl    dsMaxChainLen(%edx), %ebx
+               jl      LastMatchGood
+               shrl    $2, %ebx
+LastMatchGood:
+
+/* chainlen is decremented once beforehand so that the function can    */
+/* use the sign flag instead of the zero flag for the exit test.       */
+/* It is then shifted into the high word, to make room for the wmask   */
+/* value, which it will always accompany.                              */
+
+               decl    %ebx
+               shll    $16, %ebx
+               orl     %eax, %ebx
+               movl    %ebx, chainlenwmask(%esp)
+
+/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;     */
+
+               movl    dsNiceMatch(%edx), %eax
+               movl    dsLookahead(%edx), %ebx
+               cmpl    %eax, %ebx
+               jl      LookaheadLess
+               movl    %eax, %ebx
+LookaheadLess: movl    %ebx, nicematch(%esp)
+
+/* register Bytef *scan = s->window + s->strstart;                     */
+
+               movl    dsWindow(%edx), %esi
+               movl    %esi, window(%esp)
+               movl    dsStrStart(%edx), %ebp
+               lea     (%esi,%ebp), %edi
+               movl    %edi, scan(%esp)
+
+/* Determine how many bytes the scan ptr is off from being             */
+/* dword-aligned.                                                      */
+
+               movl    %edi, %eax
+               negl    %eax
+               andl    $3, %eax
+               movl    %eax, scanalign(%esp)
+
+/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ?                      */
+/*     s->strstart - (IPos)MAX_DIST(s) : NIL;                          */
+
+               movl    dsWSize(%edx), %eax
+               subl    $MIN_LOOKAHEAD, %eax
+               subl    %eax, %ebp
+               jg      LimitPositive
+               xorl    %ebp, %ebp
+LimitPositive:
+
+/* int best_len = s->prev_length;                                      */
+
+               movl    dsPrevLen(%edx), %eax
+               movl    %eax, bestlen(%esp)
+
+/* Store the sum of s->window + best_len in %esi locally, and in %esi. */
+
+               addl    %eax, %esi
+               movl    %esi, windowbestlen(%esp)
+
+/* register ush scan_start = *(ushf*)scan;                             */
+/* register ush scan_end   = *(ushf*)(scan+best_len-1);                        */
+/* Posf *prev = s->prev;                                               */
+
+               movzwl  (%edi), %ebx
+               movl    %ebx, scanstart(%esp)
+               movzwl  -1(%edi,%eax), %ebx
+               movl    %ebx, scanend(%esp)
+               movl    dsPrev(%edx), %edi
+
+/* Jump into the main loop.                                            */
+
+               movl    chainlenwmask(%esp), %edx
+               jmp     LoopEntry
+
+.balign 16
+
+/* do {
+ *     match = s->window + cur_match;
+ *     if (*(ushf*)(match+best_len-1) != scan_end ||
+ *         *(ushf*)match != scan_start) continue;
+ *     [...]
+ * } while ((cur_match = prev[cur_match & wmask]) > limit
+ *          && --chain_length != 0);
+ *
+ * Here is the inner loop of the function. The function will spend the
+ * majority of its time in this loop, and majority of that time will
+ * be spent in the first ten instructions.
+ *
+ * Within this loop:
+ * %ebx = scanend
+ * %ecx = curmatch
+ * %edx = chainlenwmask - i.e., ((chainlen << 16) | wmask)
+ * %esi = windowbestlen - i.e., (window + bestlen)
+ * %edi = prev
+ * %ebp = limit
+ */
+LookupLoop:
+               andl    %edx, %ecx
+               movzwl  (%edi,%ecx,2), %ecx
+               cmpl    %ebp, %ecx
+               jbe     LeaveNow
+               subl    $0x00010000, %edx
+               js      LeaveNow
+LoopEntry:     movzwl  -1(%esi,%ecx), %eax
+               cmpl    %ebx, %eax
+               jnz     LookupLoop
+               movl    window(%esp), %eax
+               movzwl  (%eax,%ecx), %eax
+               cmpl    scanstart(%esp), %eax
+               jnz     LookupLoop
+
+/* Store the current value of chainlen.                                        */
+
+               movl    %edx, chainlenwmask(%esp)
+
+/* Point %edi to the string under scrutiny, and %esi to the string we  */
+/* are hoping to match it up with. In actuality, %esi and %edi are     */
+/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is     */
+/* initialized to -(MAX_MATCH_8 - scanalign).                          */
+
+               movl    window(%esp), %esi
+               movl    scan(%esp), %edi
+               addl    %ecx, %esi
+               movl    scanalign(%esp), %eax
+               movl    $(-MAX_MATCH_8), %edx
+               lea     MAX_MATCH_8(%edi,%eax), %edi
+               lea     MAX_MATCH_8(%esi,%eax), %esi
+
+/* Test the strings for equality, 8 bytes at a time. At the end,
+ * adjust %edx so that it is offset to the exact byte that mismatched.
+ *
+ * We already know at this point that the first three bytes of the
+ * strings match each other, and they can be safely passed over before
+ * starting the compare loop. So what this code does is skip over 0-3
+ * bytes, as much as necessary in order to dword-align the %edi
+ * pointer. (%esi will still be misaligned three times out of four.)
+ *
+ * It should be confessed that this loop usually does not represent
+ * much of the total running time. Replacing it with a more
+ * straightforward "rep cmpsb" would not drastically degrade
+ * performance.
+ */
+LoopCmps:
+               movl    (%esi,%edx), %eax
+               xorl    (%edi,%edx), %eax
+               jnz     LeaveLoopCmps
+               movl    4(%esi,%edx), %eax
+               xorl    4(%edi,%edx), %eax
+               jnz     LeaveLoopCmps4
+               addl    $8, %edx
+               jnz     LoopCmps
+               jmp     LenMaximum
+LeaveLoopCmps4:        addl    $4, %edx
+LeaveLoopCmps: testl   $0x0000FFFF, %eax
+               jnz     LenLower
+               addl    $2, %edx
+               shrl    $16, %eax
+LenLower:      subb    $1, %al
+               adcl    $0, %edx
+
+/* Calculate the length of the match. If it is longer than MAX_MATCH,  */
+/* then automatically accept it as the best possible match and leave.  */
+
+               lea     (%edi,%edx), %eax
+               movl    scan(%esp), %edi
+               subl    %edi, %eax
+               cmpl    $MAX_MATCH, %eax
+               jge     LenMaximum
+
+/* If the length of the match is not longer than the best match we     */
+/* have so far, then forget it and return to the lookup loop.          */
+
+               movl    deflatestate(%esp), %edx
+               movl    bestlen(%esp), %ebx
+               cmpl    %ebx, %eax
+               jg      LongerMatch
+               movl    windowbestlen(%esp), %esi
+               movl    dsPrev(%edx), %edi
+               movl    scanend(%esp), %ebx
+               movl    chainlenwmask(%esp), %edx
+               jmp     LookupLoop
+
+/*         s->match_start = cur_match;                                 */
+/*         best_len = len;                                             */
+/*         if (len >= nice_match) break;                               */
+/*         scan_end = *(ushf*)(scan+best_len-1);                       */
+
+LongerMatch:   movl    nicematch(%esp), %ebx
+               movl    %eax, bestlen(%esp)
+               movl    %ecx, dsMatchStart(%edx)
+               cmpl    %ebx, %eax
+               jge     LeaveNow
+               movl    window(%esp), %esi
+               addl    %eax, %esi
+               movl    %esi, windowbestlen(%esp)
+               movzwl  -1(%edi,%eax), %ebx
+               movl    dsPrev(%edx), %edi
+               movl    %ebx, scanend(%esp)
+               movl    chainlenwmask(%esp), %edx
+               jmp     LookupLoop
+
+/* Accept the current string, with the maximum possible length.                */
+
+LenMaximum:    movl    deflatestate(%esp), %edx
+               movl    $MAX_MATCH, bestlen(%esp)
+               movl    %ecx, dsMatchStart(%edx)
+
+/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len;          */
+/* return s->lookahead;                                                        */
+
+LeaveNow:
+               movl    deflatestate(%esp), %edx
+               movl    bestlen(%esp), %ebx
+               movl    dsLookahead(%edx), %eax
+               cmpl    %eax, %ebx
+               jg      LookaheadRet
+               movl    %ebx, %eax
+LookaheadRet:
+
+/* Restore the stack and return from whence we came.                   */
+
+               addl    $LocalVarsSize, %esp
+               .cfi_def_cfa_offset 20
+               popl    %ebx
+               .cfi_def_cfa_offset 16
+               popl    %esi
+               .cfi_def_cfa_offset 12
+               popl    %edi
+               .cfi_def_cfa_offset 8
+               popl    %ebp
+               .cfi_def_cfa_offset 4
+.cfi_endproc
+match_init:    ret
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/Makefile b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/Makefile
new file mode 100644 (file)
index 0000000..9be80ba
--- /dev/null
@@ -0,0 +1,8 @@
+blast: blast.c blast.h
+       cc -DTEST -o blast blast.c
+
+test: blast
+       blast < test.pk | cmp - test.txt
+
+clean:
+       rm -f blast blast.o
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/README b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/README
new file mode 100644 (file)
index 0000000..e3a60b3
--- /dev/null
@@ -0,0 +1,4 @@
+Read blast.h for purpose and usage.
+
+Mark Adler
+madler@alumni.caltech.edu
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/blast.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/blast.c
new file mode 100644 (file)
index 0000000..4ce697a
--- /dev/null
@@ -0,0 +1,444 @@
+/* blast.c
+ * Copyright (C) 2003 Mark Adler
+ * For conditions of distribution and use, see copyright notice in blast.h
+ * version 1.1, 16 Feb 2003
+ *
+ * blast.c decompresses data compressed by the PKWare Compression Library.
+ * This function provides functionality similar to the explode() function of
+ * the PKWare library, hence the name "blast".
+ *
+ * This decompressor is based on the excellent format description provided by
+ * Ben Rudiak-Gould in comp.compression on August 13, 2001.  Interestingly, the
+ * example Ben provided in the post is incorrect.  The distance 110001 should
+ * instead be 111000.  When corrected, the example byte stream becomes:
+ *
+ *    00 04 82 24 25 8f 80 7f
+ *
+ * which decompresses to "AIAIAIAIAIAIA" (without the quotes).
+ */
+
+/*
+ * Change history:
+ *
+ * 1.0  12 Feb 2003     - First version
+ * 1.1  16 Feb 2003     - Fixed distance check for > 4 GB uncompressed data
+ */
+
+#include <setjmp.h>             /* for setjmp(), longjmp(), and jmp_buf */
+#include "blast.h"              /* prototype for blast() */
+
+#define local static            /* for local function definitions */
+#define MAXBITS 13              /* maximum code length */
+#define MAXWIN 4096             /* maximum window size */
+
+/* input and output state */
+struct state {
+    /* input state */
+    blast_in infun;             /* input function provided by user */
+    void *inhow;                /* opaque information passed to infun() */
+    unsigned char *in;          /* next input location */
+    unsigned left;              /* available input at in */
+    int bitbuf;                 /* bit buffer */
+    int bitcnt;                 /* number of bits in bit buffer */
+
+    /* input limit error return state for bits() and decode() */
+    jmp_buf env;
+
+    /* output state */
+    blast_out outfun;           /* output function provided by user */
+    void *outhow;               /* opaque information passed to outfun() */
+    unsigned next;              /* index of next write location in out[] */
+    int first;                  /* true to check distances (for first 4K) */
+    unsigned char out[MAXWIN];  /* output buffer and sliding window */
+};
+
+/*
+ * Return need bits from the input stream.  This always leaves less than
+ * eight bits in the buffer.  bits() works properly for need == 0.
+ *
+ * Format notes:
+ *
+ * - Bits are stored in bytes from the least significant bit to the most
+ *   significant bit.  Therefore bits are dropped from the bottom of the bit
+ *   buffer, using shift right, and new bytes are appended to the top of the
+ *   bit buffer, using shift left.
+ */
+local int bits(struct state *s, int need)
+{
+    int val;            /* bit accumulator */
+
+    /* load at least need bits into val */
+    val = s->bitbuf;
+    while (s->bitcnt < need) {
+        if (s->left == 0) {
+            s->left = s->infun(s->inhow, &(s->in));
+            if (s->left == 0) longjmp(s->env, 1);       /* out of input */
+        }
+        val |= (int)(*(s->in)++) << s->bitcnt;          /* load eight bits */
+        s->left--;
+        s->bitcnt += 8;
+    }
+
+    /* drop need bits and update buffer, always zero to seven bits left */
+    s->bitbuf = val >> need;
+    s->bitcnt -= need;
+
+    /* return need bits, zeroing the bits above that */
+    return val & ((1 << need) - 1);
+}
+
+/*
+ * Huffman code decoding tables.  count[1..MAXBITS] is the number of symbols of
+ * each length, which for a canonical code are stepped through in order.
+ * symbol[] are the symbol values in canonical order, where the number of
+ * entries is the sum of the counts in count[].  The decoding process can be
+ * seen in the function decode() below.
+ */
+struct huffman {
+    short *count;       /* number of symbols of each length */
+    short *symbol;      /* canonically ordered symbols */
+};
+
+/*
+ * Decode a code from the stream s using huffman table h.  Return the symbol or
+ * a negative value if there is an error.  If all of the lengths are zero, i.e.
+ * an empty code, or if the code is incomplete and an invalid code is received,
+ * then -9 is returned after reading MAXBITS bits.
+ *
+ * Format notes:
+ *
+ * - The codes as stored in the compressed data are bit-reversed relative to
+ *   a simple integer ordering of codes of the same lengths.  Hence below the
+ *   bits are pulled from the compressed data one at a time and used to
+ *   build the code value reversed from what is in the stream in order to
+ *   permit simple integer comparisons for decoding.
+ *
+ * - The first code for the shortest length is all ones.  Subsequent codes of
+ *   the same length are simply integer decrements of the previous code.  When
+ *   moving up a length, a one bit is appended to the code.  For a complete
+ *   code, the last code of the longest length will be all zeros.  To support
+ *   this ordering, the bits pulled during decoding are inverted to apply the
+ *   more "natural" ordering starting with all zeros and incrementing.
+ */
+local int decode(struct state *s, struct huffman *h)
+{
+    int len;            /* current number of bits in code */
+    int code;           /* len bits being decoded */
+    int first;          /* first code of length len */
+    int count;          /* number of codes of length len */
+    int index;          /* index of first code of length len in symbol table */
+    int bitbuf;         /* bits from stream */
+    int left;           /* bits left in next or left to process */
+    short *next;        /* next number of codes */
+
+    bitbuf = s->bitbuf;
+    left = s->bitcnt;
+    code = first = index = 0;
+    len = 1;
+    next = h->count + 1;
+    while (1) {
+        while (left--) {
+            code |= (bitbuf & 1) ^ 1;   /* invert code */
+            bitbuf >>= 1;
+            count = *next++;
+            if (code < first + count) { /* if length len, return symbol */
+                s->bitbuf = bitbuf;
+                s->bitcnt = (s->bitcnt - len) & 7;
+                return h->symbol[index + (code - first)];
+            }
+            index += count;             /* else update for next length */
+            first += count;
+            first <<= 1;
+            code <<= 1;
+            len++;
+        }
+        left = (MAXBITS+1) - len;
+        if (left == 0) break;
+        if (s->left == 0) {
+            s->left = s->infun(s->inhow, &(s->in));
+            if (s->left == 0) longjmp(s->env, 1);       /* out of input */
+        }
+        bitbuf = *(s->in)++;
+        s->left--;
+        if (left > 8) left = 8;
+    }
+    return -9;                          /* ran out of codes */
+}
+
+/*
+ * Given a list of repeated code lengths rep[0..n-1], where each byte is a
+ * count (high four bits + 1) and a code length (low four bits), generate the
+ * list of code lengths.  This compaction reduces the size of the object code.
+ * Then given the list of code lengths length[0..n-1] representing a canonical
+ * Huffman code for n symbols, construct the tables required to decode those
+ * codes.  Those tables are the number of codes of each length, and the symbols
+ * sorted by length, retaining their original order within each length.  The
+ * return value is zero for a complete code set, negative for an over-
+ * subscribed code set, and positive for an incomplete code set.  The tables
+ * can be used if the return value is zero or positive, but they cannot be used
+ * if the return value is negative.  If the return value is zero, it is not
+ * possible for decode() using that table to return an error--any stream of
+ * enough bits will resolve to a symbol.  If the return value is positive, then
+ * it is possible for decode() using that table to return an error for received
+ * codes past the end of the incomplete lengths.
+ */
+local int construct(struct huffman *h, const unsigned char *rep, int n)
+{
+    int symbol;         /* current symbol when stepping through length[] */
+    int len;            /* current length when stepping through h->count[] */
+    int left;           /* number of possible codes left of current length */
+    short offs[MAXBITS+1];      /* offsets in symbol table for each length */
+    short length[256];  /* code lengths */
+
+    /* convert compact repeat counts into symbol bit length list */
+    symbol = 0;
+    do {
+        len = *rep++;
+        left = (len >> 4) + 1;
+        len &= 15;
+        do {
+            length[symbol++] = len;
+        } while (--left);
+    } while (--n);
+    n = symbol;
+
+    /* count number of codes of each length */
+    for (len = 0; len <= MAXBITS; len++)
+        h->count[len] = 0;
+    for (symbol = 0; symbol < n; symbol++)
+        (h->count[length[symbol]])++;   /* assumes lengths are within bounds */
+    if (h->count[0] == n)               /* no codes! */
+        return 0;                       /* complete, but decode() will fail */
+
+    /* check for an over-subscribed or incomplete set of lengths */
+    left = 1;                           /* one possible code of zero length */
+    for (len = 1; len <= MAXBITS; len++) {
+        left <<= 1;                     /* one more bit, double codes left */
+        left -= h->count[len];          /* deduct count from possible codes */
+        if (left < 0) return left;      /* over-subscribed--return negative */
+    }                                   /* left > 0 means incomplete */
+
+    /* generate offsets into symbol table for each length for sorting */
+    offs[1] = 0;
+    for (len = 1; len < MAXBITS; len++)
+        offs[len + 1] = offs[len] + h->count[len];
+
+    /*
+     * put symbols in table sorted by length, by symbol order within each
+     * length
+     */
+    for (symbol = 0; symbol < n; symbol++)
+        if (length[symbol] != 0)
+            h->symbol[offs[length[symbol]]++] = symbol;
+
+    /* return zero for complete set, positive for incomplete set */
+    return left;
+}
+
+/*
+ * Decode PKWare Compression Library stream.
+ *
+ * Format notes:
+ *
+ * - First byte is 0 if literals are uncoded or 1 if they are coded.  Second
+ *   byte is 4, 5, or 6 for the number of extra bits in the distance code.
+ *   This is the base-2 logarithm of the dictionary size minus six.
+ *
+ * - Compressed data is a combination of literals and length/distance pairs
+ *   terminated by an end code.  Literals are either Huffman coded or
+ *   uncoded bytes.  A length/distance pair is a coded length followed by a
+ *   coded distance to represent a string that occurs earlier in the
+ *   uncompressed data that occurs again at the current location.
+ *
+ * - A bit preceding a literal or length/distance pair indicates which comes
+ *   next, 0 for literals, 1 for length/distance.
+ *
+ * - If literals are uncoded, then the next eight bits are the literal, in the
+ *   normal bit order in th stream, i.e. no bit-reversal is needed. Similarly,
+ *   no bit reversal is needed for either the length extra bits or the distance
+ *   extra bits.
+ *
+ * - Literal bytes are simply written to the output.  A length/distance pair is
+ *   an instruction to copy previously uncompressed bytes to the output.  The
+ *   copy is from distance bytes back in the output stream, copying for length
+ *   bytes.
+ *
+ * - Distances pointing before the beginning of the output data are not
+ *   permitted.
+ *
+ * - Overlapped copies, where the length is greater than the distance, are
+ *   allowed and common.  For example, a distance of one and a length of 518
+ *   simply copies the last byte 518 times.  A distance of four and a length of
+ *   twelve copies the last four bytes three times.  A simple forward copy
+ *   ignoring whether the length is greater than the distance or not implements
+ *   this correctly.
+ */
+local int decomp(struct state *s)
+{
+    int lit;            /* true if literals are coded */
+    int dict;           /* log2(dictionary size) - 6 */
+    int symbol;         /* decoded symbol, extra bits for distance */
+    int len;            /* length for copy */
+    int dist;           /* distance for copy */
+    int copy;           /* copy counter */
+    unsigned char *from, *to;   /* copy pointers */
+    static int virgin = 1;                              /* build tables once */
+    static short litcnt[MAXBITS+1], litsym[256];        /* litcode memory */
+    static short lencnt[MAXBITS+1], lensym[16];         /* lencode memory */
+    static short distcnt[MAXBITS+1], distsym[64];       /* distcode memory */
+    static struct huffman litcode = {litcnt, litsym};   /* length code */
+    static struct huffman lencode = {lencnt, lensym};   /* length code */
+    static struct huffman distcode = {distcnt, distsym};/* distance code */
+        /* bit lengths of literal codes */
+    static const unsigned char litlen[] = {
+        11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8,
+        9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5,
+        7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12,
+        8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27,
+        44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45,
+        44, 173};
+        /* bit lengths of length codes 0..15 */
+    static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23};
+        /* bit lengths of distance codes 0..63 */
+    static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248};
+    static const short base[16] = {     /* base for length codes */
+        3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264};
+    static const char extra[16] = {     /* extra bits for length codes */
+        0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8};
+
+    /* set up decoding tables (once--might not be thread-safe) */
+    if (virgin) {
+        construct(&litcode, litlen, sizeof(litlen));
+        construct(&lencode, lenlen, sizeof(lenlen));
+        construct(&distcode, distlen, sizeof(distlen));
+        virgin = 0;
+    }
+
+    /* read header */
+    lit = bits(s, 8);
+    if (lit > 1) return -1;
+    dict = bits(s, 8);
+    if (dict < 4 || dict > 6) return -2;
+
+    /* decode literals and length/distance pairs */
+    do {
+        if (bits(s, 1)) {
+            /* get length */
+            symbol = decode(s, &lencode);
+            len = base[symbol] + bits(s, extra[symbol]);
+            if (len == 519) break;              /* end code */
+
+            /* get distance */
+            symbol = len == 2 ? 2 : dict;
+            dist = decode(s, &distcode) << symbol;
+            dist += bits(s, symbol);
+            dist++;
+            if (s->first && dist > s->next)
+                return -3;              /* distance too far back */
+
+            /* copy length bytes from distance bytes back */
+            do {
+                to = s->out + s->next;
+                from = to - dist;
+                copy = MAXWIN;
+                if (s->next < dist) {
+                    from += copy;
+                    copy = dist;
+                }
+                copy -= s->next;
+                if (copy > len) copy = len;
+                len -= copy;
+                s->next += copy;
+                do {
+                    *to++ = *from++;
+                } while (--copy);
+                if (s->next == MAXWIN) {
+                    if (s->outfun(s->outhow, s->out, s->next)) return 1;
+                    s->next = 0;
+                    s->first = 0;
+                }
+            } while (len != 0);
+        }
+        else {
+            /* get literal and write it */
+            symbol = lit ? decode(s, &litcode) : bits(s, 8);
+            s->out[s->next++] = symbol;
+            if (s->next == MAXWIN) {
+                if (s->outfun(s->outhow, s->out, s->next)) return 1;
+                s->next = 0;
+                s->first = 0;
+            }
+        }
+    } while (1);
+    return 0;
+}
+
+/* See comments in blast.h */
+int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow)
+{
+    struct state s;             /* input/output state */
+    int err;                    /* return value */
+
+    /* initialize input state */
+    s.infun = infun;
+    s.inhow = inhow;
+    s.left = 0;
+    s.bitbuf = 0;
+    s.bitcnt = 0;
+
+    /* initialize output state */
+    s.outfun = outfun;
+    s.outhow = outhow;
+    s.next = 0;
+    s.first = 1;
+
+    /* return if bits() or decode() tries to read past available input */
+    if (setjmp(s.env) != 0)             /* if came back here via longjmp(), */
+        err = 2;                        /*  then skip decomp(), return error */
+    else
+        err = decomp(&s);               /* decompress */
+
+    /* write any leftover output and update the error code if needed */
+    if (err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0)
+        err = 1;
+    return err;
+}
+
+#ifdef TEST
+/* Example of how to use blast() */
+#include <stdio.h>
+#include <stdlib.h>
+
+#define CHUNK 16384
+
+local unsigned inf(void *how, unsigned char **buf)
+{
+    static unsigned char hold[CHUNK];
+
+    *buf = hold;
+    return fread(hold, 1, CHUNK, (FILE *)how);
+}
+
+local int outf(void *how, unsigned char *buf, unsigned len)
+{
+    return fwrite(buf, 1, len, (FILE *)how) != len;
+}
+
+/* Decompress a PKWare Compression Library stream from stdin to stdout */
+int main(void)
+{
+    int ret, n;
+
+    /* decompress to stdout */
+    ret = blast(inf, stdin, outf, stdout);
+    if (ret != 0) fprintf(stderr, "blast error: %d\n", ret);
+
+    /* see if there are any leftover bytes */
+    n = 0;
+    while (getchar() != EOF) n++;
+    if (n) fprintf(stderr, "blast warning: %d unused bytes of input\n", n);
+
+    /* return blast() error code */
+    return ret;
+}
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/blast.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/blast.h
new file mode 100644 (file)
index 0000000..ce9e541
--- /dev/null
@@ -0,0 +1,71 @@
+/* blast.h -- interface for blast.c
+  Copyright (C) 2003 Mark Adler
+  version 1.1, 16 Feb 2003
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the author be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Mark Adler    madler@alumni.caltech.edu
+ */
+
+
+/*
+ * blast() decompresses the PKWare Data Compression Library (DCL) compressed
+ * format.  It provides the same functionality as the explode() function in
+ * that library.  (Note: PKWare overused the "implode" verb, and the format
+ * used by their library implode() function is completely different and
+ * incompatible with the implode compression method supported by PKZIP.)
+ */
+
+
+typedef unsigned (*blast_in)(void *how, unsigned char **buf);
+typedef int (*blast_out)(void *how, unsigned char *buf, unsigned len);
+/* Definitions for input/output functions passed to blast().  See below for
+ * what the provided functions need to do.
+ */
+
+
+int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow);
+/* Decompress input to output using the provided infun() and outfun() calls.
+ * On success, the return value of blast() is zero.  If there is an error in
+ * the source data, i.e. it is not in the proper format, then a negative value
+ * is returned.  If there is not enough input available or there is not enough
+ * output space, then a positive error is returned.
+ *
+ * The input function is invoked: len = infun(how, &buf), where buf is set by
+ * infun() to point to the input buffer, and infun() returns the number of
+ * available bytes there.  If infun() returns zero, then blast() returns with
+ * an input error.  (blast() only asks for input if it needs it.)  inhow is for
+ * use by the application to pass an input descriptor to infun(), if desired.
+ *
+ * The output function is invoked: err = outfun(how, buf, len), where the bytes
+ * to be written are buf[0..len-1].  If err is not zero, then blast() returns
+ * with an output error.  outfun() is always called with len <= 4096.  outhow
+ * is for use by the application to pass an output descriptor to outfun(), if
+ * desired.
+ *
+ * The return codes are:
+ *
+ *   2:  ran out of input before completing decompression
+ *   1:  output error before completing decompression
+ *   0:  successful decompression
+ *  -1:  literal flag not zero or one
+ *  -2:  dictionary size not in 4..6
+ *  -3:  distance is too far back
+ *
+ * At the bottom of blast.c is an example program that uses blast() that can be
+ * compiled to produce a command-line decompression filter by defining TEST.
+ */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/test.pk b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/test.pk
new file mode 100644 (file)
index 0000000..be10b2b
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/test.pk differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/test.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/blast/test.txt
new file mode 100644 (file)
index 0000000..bfdf1c5
--- /dev/null
@@ -0,0 +1 @@
+AIAIAIAIAIAIA
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/ZLib.pas b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/ZLib.pas
new file mode 100644 (file)
index 0000000..6daf8bb
--- /dev/null
@@ -0,0 +1,557 @@
+{*******************************************************}
+{                                                       }
+{       Borland Delphi Supplemental Components          }
+{       ZLIB Data Compression Interface Unit            }
+{                                                       }
+{       Copyright (c) 1997,99 Borland Corporation       }
+{                                                       }
+{*******************************************************}
+
+{ Updated for zlib 1.2.x by Cosmin Truta <cosmint@cs.ubbcluj.ro> }
+
+unit ZLib;
+
+interface
+
+uses SysUtils, Classes;
+
+type
+  TAlloc = function (AppData: Pointer; Items, Size: Integer): Pointer; cdecl;
+  TFree = procedure (AppData, Block: Pointer); cdecl;
+
+  // Internal structure.  Ignore.
+  TZStreamRec = packed record
+    next_in: PChar;       // next input byte
+    avail_in: Integer;    // number of bytes available at next_in
+    total_in: Longint;    // total nb of input bytes read so far
+
+    next_out: PChar;      // next output byte should be put here
+    avail_out: Integer;   // remaining free space at next_out
+    total_out: Longint;   // total nb of bytes output so far
+
+    msg: PChar;           // last error message, NULL if no error
+    internal: Pointer;    // not visible by applications
+
+    zalloc: TAlloc;       // used to allocate the internal state
+    zfree: TFree;         // used to free the internal state
+    AppData: Pointer;     // private data object passed to zalloc and zfree
+
+    data_type: Integer;   // best guess about the data type: ascii or binary
+    adler: Longint;       // adler32 value of the uncompressed data
+    reserved: Longint;    // reserved for future use
+  end;
+
+  // Abstract ancestor class
+  TCustomZlibStream = class(TStream)
+  private
+    FStrm: TStream;
+    FStrmPos: Integer;
+    FOnProgress: TNotifyEvent;
+    FZRec: TZStreamRec;
+    FBuffer: array [Word] of Char;
+  protected
+    procedure Progress(Sender: TObject); dynamic;
+    property OnProgress: TNotifyEvent read FOnProgress write FOnProgress;
+    constructor Create(Strm: TStream);
+  end;
+
+{ TCompressionStream compresses data on the fly as data is written to it, and
+  stores the compressed data to another stream.
+
+  TCompressionStream is write-only and strictly sequential. Reading from the
+  stream will raise an exception. Using Seek to move the stream pointer
+  will raise an exception.
+
+  Output data is cached internally, written to the output stream only when
+  the internal output buffer is full.  All pending output data is flushed
+  when the stream is destroyed.
+
+  The Position property returns the number of uncompressed bytes of
+  data that have been written to the stream so far.
+
+  CompressionRate returns the on-the-fly percentage by which the original
+  data has been compressed:  (1 - (CompressedBytes / UncompressedBytes)) * 100
+  If raw data size = 100 and compressed data size = 25, the CompressionRate
+  is 75%
+
+  The OnProgress event is called each time the output buffer is filled and
+  written to the output stream.  This is useful for updating a progress
+  indicator when you are writing a large chunk of data to the compression
+  stream in a single call.}
+
+
+  TCompressionLevel = (clNone, clFastest, clDefault, clMax);
+
+  TCompressionStream = class(TCustomZlibStream)
+  private
+    function GetCompressionRate: Single;
+  public
+    constructor Create(CompressionLevel: TCompressionLevel; Dest: TStream);
+    destructor Destroy; override;
+    function Read(var Buffer; Count: Longint): Longint; override;
+    function Write(const Buffer; Count: Longint): Longint; override;
+    function Seek(Offset: Longint; Origin: Word): Longint; override;
+    property CompressionRate: Single read GetCompressionRate;
+    property OnProgress;
+  end;
+
+{ TDecompressionStream decompresses data on the fly as data is read from it.
+
+  Compressed data comes from a separate source stream.  TDecompressionStream
+  is read-only and unidirectional; you can seek forward in the stream, but not
+  backwards.  The special case of setting the stream position to zero is
+  allowed.  Seeking forward decompresses data until the requested position in
+  the uncompressed data has been reached.  Seeking backwards, seeking relative
+  to the end of the stream, requesting the size of the stream, and writing to
+  the stream will raise an exception.
+
+  The Position property returns the number of bytes of uncompressed data that
+  have been read from the stream so far.
+
+  The OnProgress event is called each time the internal input buffer of
+  compressed data is exhausted and the next block is read from the input stream.
+  This is useful for updating a progress indicator when you are reading a
+  large chunk of data from the decompression stream in a single call.}
+
+  TDecompressionStream = class(TCustomZlibStream)
+  public
+    constructor Create(Source: TStream);
+    destructor Destroy; override;
+    function Read(var Buffer; Count: Longint): Longint; override;
+    function Write(const Buffer; Count: Longint): Longint; override;
+    function Seek(Offset: Longint; Origin: Word): Longint; override;
+    property OnProgress;
+  end;
+
+
+
+{ CompressBuf compresses data, buffer to buffer, in one call.
+   In: InBuf = ptr to compressed data
+       InBytes = number of bytes in InBuf
+  Out: OutBuf = ptr to newly allocated buffer containing decompressed data
+       OutBytes = number of bytes in OutBuf   }
+procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
+                      out OutBuf: Pointer; out OutBytes: Integer);
+
+
+{ DecompressBuf decompresses data, buffer to buffer, in one call.
+   In: InBuf = ptr to compressed data
+       InBytes = number of bytes in InBuf
+       OutEstimate = zero, or est. size of the decompressed data
+  Out: OutBuf = ptr to newly allocated buffer containing decompressed data
+       OutBytes = number of bytes in OutBuf   }
+procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
+ OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
+
+{ DecompressToUserBuf decompresses data, buffer to buffer, in one call.
+   In: InBuf = ptr to compressed data
+       InBytes = number of bytes in InBuf
+  Out: OutBuf = ptr to user-allocated buffer to contain decompressed data
+       BufSize = number of bytes in OutBuf   }
+procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer;
+  const OutBuf: Pointer; BufSize: Integer);
+
+const
+  zlib_version = '1.2.6';
+
+type
+  EZlibError = class(Exception);
+  ECompressionError = class(EZlibError);
+  EDecompressionError = class(EZlibError);
+
+implementation
+
+uses ZLibConst;
+
+const
+  Z_NO_FLUSH      = 0;
+  Z_PARTIAL_FLUSH = 1;
+  Z_SYNC_FLUSH    = 2;
+  Z_FULL_FLUSH    = 3;
+  Z_FINISH        = 4;
+
+  Z_OK            = 0;
+  Z_STREAM_END    = 1;
+  Z_NEED_DICT     = 2;
+  Z_ERRNO         = (-1);
+  Z_STREAM_ERROR  = (-2);
+  Z_DATA_ERROR    = (-3);
+  Z_MEM_ERROR     = (-4);
+  Z_BUF_ERROR     = (-5);
+  Z_VERSION_ERROR = (-6);
+
+  Z_NO_COMPRESSION       =   0;
+  Z_BEST_SPEED           =   1;
+  Z_BEST_COMPRESSION     =   9;
+  Z_DEFAULT_COMPRESSION  = (-1);
+
+  Z_FILTERED            = 1;
+  Z_HUFFMAN_ONLY        = 2;
+  Z_RLE                 = 3;
+  Z_DEFAULT_STRATEGY    = 0;
+
+  Z_BINARY   = 0;
+  Z_ASCII    = 1;
+  Z_UNKNOWN  = 2;
+
+  Z_DEFLATED = 8;
+
+
+{$L adler32.obj}
+{$L compress.obj}
+{$L crc32.obj}
+{$L deflate.obj}
+{$L infback.obj}
+{$L inffast.obj}
+{$L inflate.obj}
+{$L inftrees.obj}
+{$L trees.obj}
+{$L uncompr.obj}
+{$L zutil.obj}
+
+procedure adler32; external;
+procedure compressBound; external;
+procedure crc32; external;
+procedure deflateInit2_; external;
+procedure deflateParams; external;
+
+function _malloc(Size: Integer): Pointer; cdecl;
+begin
+  Result := AllocMem(Size);
+end;
+
+procedure _free(Block: Pointer); cdecl;
+begin
+  FreeMem(Block);
+end;
+
+procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl;
+begin
+  FillChar(P^, count, B);
+end;
+
+procedure _memcpy(dest, source: Pointer; count: Integer); cdecl;
+begin
+  Move(source^, dest^, count);
+end;
+
+
+
+// deflate compresses data
+function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar;
+  recsize: Integer): Integer; external;
+function deflate(var strm: TZStreamRec; flush: Integer): Integer; external;
+function deflateEnd(var strm: TZStreamRec): Integer; external;
+
+// inflate decompresses data
+function inflateInit_(var strm: TZStreamRec; version: PChar;
+  recsize: Integer): Integer; external;
+function inflate(var strm: TZStreamRec; flush: Integer): Integer; external;
+function inflateEnd(var strm: TZStreamRec): Integer; external;
+function inflateReset(var strm: TZStreamRec): Integer; external;
+
+
+function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer; cdecl;
+begin
+//  GetMem(Result, Items*Size);
+  Result := AllocMem(Items * Size);
+end;
+
+procedure zlibFreeMem(AppData, Block: Pointer); cdecl;
+begin
+  FreeMem(Block);
+end;
+
+{function zlibCheck(code: Integer): Integer;
+begin
+  Result := code;
+  if code < 0 then
+    raise EZlibError.Create('error');    //!!
+end;}
+
+function CCheck(code: Integer): Integer;
+begin
+  Result := code;
+  if code < 0 then
+    raise ECompressionError.Create('error'); //!!
+end;
+
+function DCheck(code: Integer): Integer;
+begin
+  Result := code;
+  if code < 0 then
+    raise EDecompressionError.Create('error');  //!!
+end;
+
+procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
+                      out OutBuf: Pointer; out OutBytes: Integer);
+var
+  strm: TZStreamRec;
+  P: Pointer;
+begin
+  FillChar(strm, sizeof(strm), 0);
+  strm.zalloc := zlibAllocMem;
+  strm.zfree := zlibFreeMem;
+  OutBytes := ((InBytes + (InBytes div 10) + 12) + 255) and not 255;
+  GetMem(OutBuf, OutBytes);
+  try
+    strm.next_in := InBuf;
+    strm.avail_in := InBytes;
+    strm.next_out := OutBuf;
+    strm.avail_out := OutBytes;
+    CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm)));
+    try
+      while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do
+      begin
+        P := OutBuf;
+        Inc(OutBytes, 256);
+        ReallocMem(OutBuf, OutBytes);
+        strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
+        strm.avail_out := 256;
+      end;
+    finally
+      CCheck(deflateEnd(strm));
+    end;
+    ReallocMem(OutBuf, strm.total_out);
+    OutBytes := strm.total_out;
+  except
+    FreeMem(OutBuf);
+    raise
+  end;
+end;
+
+
+procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
+  OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
+var
+  strm: TZStreamRec;
+  P: Pointer;
+  BufInc: Integer;
+begin
+  FillChar(strm, sizeof(strm), 0);
+  strm.zalloc := zlibAllocMem;
+  strm.zfree := zlibFreeMem;
+  BufInc := (InBytes + 255) and not 255;
+  if OutEstimate = 0 then
+    OutBytes := BufInc
+  else
+    OutBytes := OutEstimate;
+  GetMem(OutBuf, OutBytes);
+  try
+    strm.next_in := InBuf;
+    strm.avail_in := InBytes;
+    strm.next_out := OutBuf;
+    strm.avail_out := OutBytes;
+    DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
+    try
+      while DCheck(inflate(strm, Z_NO_FLUSH)) <> Z_STREAM_END do
+      begin
+        P := OutBuf;
+        Inc(OutBytes, BufInc);
+        ReallocMem(OutBuf, OutBytes);
+        strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
+        strm.avail_out := BufInc;
+      end;
+    finally
+      DCheck(inflateEnd(strm));
+    end;
+    ReallocMem(OutBuf, strm.total_out);
+    OutBytes := strm.total_out;
+  except
+    FreeMem(OutBuf);
+    raise
+  end;
+end;
+
+procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer;
+  const OutBuf: Pointer; BufSize: Integer);
+var
+  strm: TZStreamRec;
+begin
+  FillChar(strm, sizeof(strm), 0);
+  strm.zalloc := zlibAllocMem;
+  strm.zfree := zlibFreeMem;
+  strm.next_in := InBuf;
+  strm.avail_in := InBytes;
+  strm.next_out := OutBuf;
+  strm.avail_out := BufSize;
+  DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
+  try
+    if DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END then
+      raise EZlibError.CreateRes(@sTargetBufferTooSmall);
+  finally
+    DCheck(inflateEnd(strm));
+  end;
+end;
+
+// TCustomZlibStream
+
+constructor TCustomZLibStream.Create(Strm: TStream);
+begin
+  inherited Create;
+  FStrm := Strm;
+  FStrmPos := Strm.Position;
+  FZRec.zalloc := zlibAllocMem;
+  FZRec.zfree := zlibFreeMem;
+end;
+
+procedure TCustomZLibStream.Progress(Sender: TObject);
+begin
+  if Assigned(FOnProgress) then FOnProgress(Sender);
+end;
+
+
+// TCompressionStream
+
+constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel;
+  Dest: TStream);
+const
+  Levels: array [TCompressionLevel] of ShortInt =
+    (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION);
+begin
+  inherited Create(Dest);
+  FZRec.next_out := FBuffer;
+  FZRec.avail_out := sizeof(FBuffer);
+  CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec)));
+end;
+
+destructor TCompressionStream.Destroy;
+begin
+  FZRec.next_in := nil;
+  FZRec.avail_in := 0;
+  try
+    if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
+    while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END)
+      and (FZRec.avail_out = 0) do
+    begin
+      FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
+      FZRec.next_out := FBuffer;
+      FZRec.avail_out := sizeof(FBuffer);
+    end;
+    if FZRec.avail_out < sizeof(FBuffer) then
+      FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out);
+  finally
+    deflateEnd(FZRec);
+  end;
+  inherited Destroy;
+end;
+
+function TCompressionStream.Read(var Buffer; Count: Longint): Longint;
+begin
+  raise ECompressionError.CreateRes(@sInvalidStreamOp);
+end;
+
+function TCompressionStream.Write(const Buffer; Count: Longint): Longint;
+begin
+  FZRec.next_in := @Buffer;
+  FZRec.avail_in := Count;
+  if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
+  while (FZRec.avail_in > 0) do
+  begin
+    CCheck(deflate(FZRec, 0));
+    if FZRec.avail_out = 0 then
+    begin
+      FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
+      FZRec.next_out := FBuffer;
+      FZRec.avail_out := sizeof(FBuffer);
+      FStrmPos := FStrm.Position;
+      Progress(Self);
+    end;
+  end;
+  Result := Count;
+end;
+
+function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
+begin
+  if (Offset = 0) and (Origin = soFromCurrent) then
+    Result := FZRec.total_in
+  else
+    raise ECompressionError.CreateRes(@sInvalidStreamOp);
+end;
+
+function TCompressionStream.GetCompressionRate: Single;
+begin
+  if FZRec.total_in = 0 then
+    Result := 0
+  else
+    Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0;
+end;
+
+
+// TDecompressionStream
+
+constructor TDecompressionStream.Create(Source: TStream);
+begin
+  inherited Create(Source);
+  FZRec.next_in := FBuffer;
+  FZRec.avail_in := 0;
+  DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec)));
+end;
+
+destructor TDecompressionStream.Destroy;
+begin
+  FStrm.Seek(-FZRec.avail_in, 1);
+  inflateEnd(FZRec);
+  inherited Destroy;
+end;
+
+function TDecompressionStream.Read(var Buffer; Count: Longint): Longint;
+begin
+  FZRec.next_out := @Buffer;
+  FZRec.avail_out := Count;
+  if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
+  while (FZRec.avail_out > 0) do
+  begin
+    if FZRec.avail_in = 0 then
+    begin
+      FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer));
+      if FZRec.avail_in = 0 then
+      begin
+        Result := Count - FZRec.avail_out;
+        Exit;
+      end;
+      FZRec.next_in := FBuffer;
+      FStrmPos := FStrm.Position;
+      Progress(Self);
+    end;
+    CCheck(inflate(FZRec, 0));
+  end;
+  Result := Count;
+end;
+
+function TDecompressionStream.Write(const Buffer; Count: Longint): Longint;
+begin
+  raise EDecompressionError.CreateRes(@sInvalidStreamOp);
+end;
+
+function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
+var
+  I: Integer;
+  Buf: array [0..4095] of Char;
+begin
+  if (Offset = 0) and (Origin = soFromBeginning) then
+  begin
+    DCheck(inflateReset(FZRec));
+    FZRec.next_in := FBuffer;
+    FZRec.avail_in := 0;
+    FStrm.Position := 0;
+    FStrmPos := 0;
+  end
+  else if ( (Offset >= 0) and (Origin = soFromCurrent)) or
+          ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then
+  begin
+    if Origin = soFromBeginning then Dec(Offset, FZRec.total_out);
+    if Offset > 0 then
+    begin
+      for I := 1 to Offset div sizeof(Buf) do
+        ReadBuffer(Buf, sizeof(Buf));
+      ReadBuffer(Buf, Offset mod sizeof(Buf));
+    end;
+  end
+  else
+    raise EDecompressionError.CreateRes(@sInvalidStreamOp);
+  Result := FZRec.total_out;
+end;
+
+
+end.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/ZLibConst.pas b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/ZLibConst.pas
new file mode 100644 (file)
index 0000000..cdfe136
--- /dev/null
@@ -0,0 +1,11 @@
+unit ZLibConst;
+
+interface
+
+resourcestring
+  sTargetBufferTooSmall = 'ZLib error: target buffer may be too small';
+  sInvalidStreamOp = 'Invalid stream operation';
+
+implementation
+
+end.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/readme.txt
new file mode 100644 (file)
index 0000000..2dc9a8b
--- /dev/null
@@ -0,0 +1,76 @@
+
+Overview
+========
+
+This directory contains an update to the ZLib interface unit,
+distributed by Borland as a Delphi supplemental component.
+
+The original ZLib unit is Copyright (c) 1997,99 Borland Corp.,
+and is based on zlib version 1.0.4.  There are a series of bugs
+and security problems associated with that old zlib version, and
+we recommend the users to update their ZLib unit.
+
+
+Summary of modifications
+========================
+
+- Improved makefile, adapted to zlib version 1.2.1.
+
+- Some field types from TZStreamRec are changed from Integer to
+  Longint, for consistency with the zlib.h header, and for 64-bit
+  readiness.
+
+- The zlib_version constant is updated.
+
+- The new Z_RLE strategy has its corresponding symbolic constant.
+
+- The allocation and deallocation functions and function types
+  (TAlloc, TFree, zlibAllocMem and zlibFreeMem) are now cdecl,
+  and _malloc and _free are added as C RTL stubs.  As a result,
+  the original C sources of zlib can be compiled out of the box,
+  and linked to the ZLib unit.
+
+
+Suggestions for improvements
+============================
+
+Currently, the ZLib unit provides only a limited wrapper around
+the zlib library, and much of the original zlib functionality is
+missing.  Handling compressed file formats like ZIP/GZIP or PNG
+cannot be implemented without having this functionality.
+Applications that handle these formats are either using their own,
+duplicated code, or not using the ZLib unit at all.
+
+Here are a few suggestions:
+
+- Checksum class wrappers around adler32() and crc32(), similar
+  to the Java classes that implement the java.util.zip.Checksum
+  interface.
+
+- The ability to read and write raw deflate streams, without the
+  zlib stream header and trailer.  Raw deflate streams are used
+  in the ZIP file format.
+
+- The ability to read and write gzip streams, used in the GZIP
+  file format, and normally produced by the gzip program.
+
+- The ability to select a different compression strategy, useful
+  to PNG and MNG image compression, and to multimedia compression
+  in general.  Besides the compression level
+
+    TCompressionLevel = (clNone, clFastest, clDefault, clMax);
+
+  which, in fact, could have used the 'z' prefix and avoided
+  TColor-like symbols
+
+    TCompressionLevel = (zcNone, zcFastest, zcDefault, zcMax);
+
+  there could be a compression strategy
+
+    TCompressionStrategy = (zsDefault, zsFiltered, zsHuffmanOnly, zsRle);
+
+- ZIP and GZIP stream handling via TStreams.
+
+
+--
+Cosmin Truta <cosmint@cs.ubbcluj.ro>
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/zlibd32.mak b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/delphi/zlibd32.mak
new file mode 100644 (file)
index 0000000..9bb00b7
--- /dev/null
@@ -0,0 +1,99 @@
+# Makefile for zlib
+# For use with Delphi and C++ Builder under Win32
+# Updated for zlib 1.2.x by Cosmin Truta
+
+# ------------ Borland C++ ------------
+
+# This project uses the Delphi (fastcall/register) calling convention:
+LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl
+
+CC = bcc32
+LD = bcc32
+AR = tlib
+# do not use "-pr" in CFLAGS
+CFLAGS = -a -d -k- -O2 $(LOC)
+LDFLAGS =
+
+
+# variables
+ZLIB_LIB = zlib.lib
+
+OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj
+OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
+OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj
+OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
+
+
+# targets
+all: $(ZLIB_LIB) example.exe minigzip.exe
+
+.c.obj:
+       $(CC) -c $(CFLAGS) $*.c
+
+adler32.obj: adler32.c zlib.h zconf.h
+
+compress.obj: compress.c zlib.h zconf.h
+
+crc32.obj: crc32.c zlib.h zconf.h crc32.h
+
+deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
+
+gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
+
+gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
+
+gzread.obj: gzread.c zlib.h zconf.h gzguts.h
+
+gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
+
+infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h
+
+inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h
+
+trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h
+
+uncompr.obj: uncompr.c zlib.h zconf.h
+
+zutil.obj: zutil.c zutil.h zlib.h zconf.h
+
+example.obj: test/example.c zlib.h zconf.h
+
+minigzip.obj: test/minigzip.c zlib.h zconf.h
+
+
+# For the sake of the old Borland make,
+# the command line is cut to fit in the MS-DOS 128 byte limit:
+$(ZLIB_LIB): $(OBJ1) $(OBJ2)
+       -del $(ZLIB_LIB)
+       $(AR) $(ZLIB_LIB) $(OBJP1)
+       $(AR) $(ZLIB_LIB) $(OBJP2)
+
+
+# testing
+test: example.exe minigzip.exe
+       example
+       echo hello world | minigzip | minigzip -d
+
+example.exe: example.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB)
+
+minigzip.exe: minigzip.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB)
+
+
+# cleanup
+clean:
+       -del *.obj
+       -del *.exe
+       -del *.lib
+       -del *.tds
+       -del zlib.bak
+       -del foo.gz
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.build b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.build
new file mode 100644 (file)
index 0000000..7f90d6b
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8" ?>\r
+<project name="DotZLib" default="build" basedir="./DotZLib">\r
+       <description>A .Net wrapper library around ZLib1.dll</description>\r
+\r
+       <property name="nunit.location" value="c:/program files/NUnit V2.1/bin" />\r
+       <property name="build.root" value="bin" />\r
+\r
+       <property name="debug" value="true" />\r
+       <property name="nunit" value="true" />\r
+\r
+       <property name="build.folder" value="${build.root}/debug/" if="${debug}" />\r
+       <property name="build.folder" value="${build.root}/release/" unless="${debug}" />\r
+\r
+       <target name="clean" description="Remove all generated files">\r
+               <delete dir="${build.root}" failonerror="false" />\r
+       </target>\r
+\r
+       <target name="build" description="compiles the source code">\r
+\r
+               <mkdir dir="${build.folder}" />\r
+               <csc target="library" output="${build.folder}DotZLib.dll" debug="${debug}">\r
+                       <references basedir="${nunit.location}">\r
+                               <includes if="${nunit}" name="nunit.framework.dll" />\r
+                       </references>\r
+                       <sources>\r
+                               <includes name="*.cs" />\r
+                               <excludes name="UnitTests.cs" unless="${nunit}" />\r
+                       </sources>\r
+                       <arg value="/d:nunit" if="${nunit}" />\r
+               </csc>\r
+       </target>\r
+\r
+</project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.chm b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.chm
new file mode 100644 (file)
index 0000000..f214a44
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.chm differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.sln b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib.sln
new file mode 100644 (file)
index 0000000..ac45ca0
--- /dev/null
@@ -0,0 +1,21 @@
+Microsoft Visual Studio Solution File, Format Version 8.00\r
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotZLib", "DotZLib\DotZLib.csproj", "{BB1EE0B1-1808-46CB-B786-949D91117FC5}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+       EndProjectSection\r
+EndProject\r
+Global\r
+       GlobalSection(SolutionConfiguration) = preSolution\r
+               Debug = Debug\r
+               Release = Release\r
+       EndGlobalSection\r
+       GlobalSection(ProjectConfiguration) = postSolution\r
+               {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Debug.ActiveCfg = Debug|.NET\r
+               {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Debug.Build.0 = Debug|.NET\r
+               {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Release.ActiveCfg = Release|.NET\r
+               {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Release.Build.0 = Release|.NET\r
+       EndGlobalSection\r
+       GlobalSection(ExtensibilityGlobals) = postSolution\r
+       EndGlobalSection\r
+       GlobalSection(ExtensibilityAddIns) = postSolution\r
+       EndGlobalSection\r
+EndGlobal\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/AssemblyInfo.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..0491bfc
--- /dev/null
@@ -0,0 +1,58 @@
+using System.Reflection;\r
+using System.Runtime.CompilerServices;\r
+\r
+//\r
+// General Information about an assembly is controlled through the following\r
+// set of attributes. Change these attribute values to modify the information\r
+// associated with an assembly.\r
+//\r
+[assembly: AssemblyTitle("DotZLib")]\r
+[assembly: AssemblyDescription(".Net bindings for ZLib compression dll 1.2.x")]\r
+[assembly: AssemblyConfiguration("")]\r
+[assembly: AssemblyCompany("Henrik Ravn")]\r
+[assembly: AssemblyProduct("")]\r
+[assembly: AssemblyCopyright("(c) 2004 by Henrik Ravn")]\r
+[assembly: AssemblyTrademark("")]\r
+[assembly: AssemblyCulture("")]\r
+\r
+//\r
+// Version information for an assembly consists of the following four values:\r
+//\r
+//      Major Version\r
+//      Minor Version\r
+//      Build Number\r
+//      Revision\r
+//\r
+// You can specify all the values or you can default the Revision and Build Numbers\r
+// by using the '*' as shown below:\r
+\r
+[assembly: AssemblyVersion("1.0.*")]\r
+\r
+//\r
+// In order to sign your assembly you must specify a key to use. Refer to the\r
+// Microsoft .NET Framework documentation for more information on assembly signing.\r
+//\r
+// Use the attributes below to control which key is used for signing.\r
+//\r
+// Notes:\r
+//   (*) If no key is specified, the assembly is not signed.\r
+//   (*) KeyName refers to a key that has been installed in the Crypto Service\r
+//       Provider (CSP) on your machine. KeyFile refers to a file which contains\r
+//       a key.\r
+//   (*) If the KeyFile and the KeyName values are both specified, the\r
+//       following processing occurs:\r
+//       (1) If the KeyName can be found in the CSP, that key is used.\r
+//       (2) If the KeyName does not exist and the KeyFile does exist, the key\r
+//           in the KeyFile is installed into the CSP and used.\r
+//   (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.\r
+//       When specifying the KeyFile, the location of the KeyFile should be\r
+//       relative to the project output directory which is\r
+//       %Project Directory%\obj\<configuration>. For example, if your KeyFile is\r
+//       located in the project directory, you would specify the AssemblyKeyFile\r
+//       attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]\r
+//   (*) Delay Signing is an advanced option - see the Microsoft .NET Framework\r
+//       documentation for more information on this.\r
+//\r
+[assembly: AssemblyDelaySign(false)]\r
+[assembly: AssemblyKeyFile("")]\r
+[assembly: AssemblyKeyName("")]\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/ChecksumImpl.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/ChecksumImpl.cs
new file mode 100644 (file)
index 0000000..788b2fc
--- /dev/null
@@ -0,0 +1,202 @@
+//\r
+// Â© Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.Runtime.InteropServices;\r
+using System.Text;\r
+\r
+\r
+namespace DotZLib\r
+{\r
+    #region ChecksumGeneratorBase\r
+    /// <summary>\r
+    /// Implements the common functionality needed for all <see cref="ChecksumGenerator"/>s\r
+    /// </summary>\r
+    /// <example></example>\r
+    public abstract class ChecksumGeneratorBase : ChecksumGenerator\r
+    {\r
+        /// <summary>\r
+        /// The value of the current checksum\r
+        /// </summary>\r
+        protected uint _current;\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the checksum generator base - the current checksum is\r
+        /// set to zero\r
+        /// </summary>\r
+        public ChecksumGeneratorBase()\r
+        {\r
+            _current = 0;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the checksum generator basewith a specified value\r
+        /// </summary>\r
+        /// <param name="initialValue">The value to set the current checksum to</param>\r
+        public ChecksumGeneratorBase(uint initialValue)\r
+        {\r
+            _current = initialValue;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Resets the current checksum to zero\r
+        /// </summary>\r
+        public void Reset() { _current = 0; }\r
+\r
+        /// <summary>\r
+        /// Gets the current checksum value\r
+        /// </summary>\r
+        public uint Value { get { return _current; } }\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with part of an array of bytes\r
+        /// </summary>\r
+        /// <param name="data">The data to update the checksum with</param>\r
+        /// <param name="offset">Where in <c>data</c> to start updating</param>\r
+        /// <param name="count">The number of bytes from <c>data</c> to use</param>\r
+        /// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>\r
+        /// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>\r
+        /// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>\r
+        /// <remarks>All the other <c>Update</c> methods are implmeneted in terms of this one.\r
+        /// This is therefore the only method a derived class has to implement</remarks>\r
+        public abstract void Update(byte[] data, int offset, int count);\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with an array of bytes.\r
+        /// </summary>\r
+        /// <param name="data">The data to update the checksum with</param>\r
+        public void Update(byte[] data)\r
+        {\r
+            Update(data, 0, data.Length);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with the data from a string\r
+        /// </summary>\r
+        /// <param name="data">The string to update the checksum with</param>\r
+        /// <remarks>The characters in the string are converted by the UTF-8 encoding</remarks>\r
+        public void Update(string data)\r
+        {\r
+                       Update(Encoding.UTF8.GetBytes(data));\r
+        }\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with the data from a string, using a specific encoding\r
+        /// </summary>\r
+        /// <param name="data">The string to update the checksum with</param>\r
+        /// <param name="encoding">The encoding to use</param>\r
+        public void Update(string data, Encoding encoding)\r
+        {\r
+            Update(encoding.GetBytes(data));\r
+        }\r
+\r
+    }\r
+    #endregion\r
+\r
+    #region CRC32\r
+    /// <summary>\r
+    /// Implements a CRC32 checksum generator\r
+    /// </summary>\r
+    public sealed class CRC32Checksum : ChecksumGeneratorBase\r
+    {\r
+        #region DLL imports\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern uint crc32(uint crc, int data, uint length);\r
+\r
+        #endregion\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the CRC32 checksum generator\r
+        /// </summary>\r
+        public CRC32Checksum() : base() {}\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the CRC32 checksum generator with a specified value\r
+        /// </summary>\r
+        /// <param name="initialValue">The value to set the current checksum to</param>\r
+        public CRC32Checksum(uint initialValue) : base(initialValue) {}\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with part of an array of bytes\r
+        /// </summary>\r
+        /// <param name="data">The data to update the checksum with</param>\r
+        /// <param name="offset">Where in <c>data</c> to start updating</param>\r
+        /// <param name="count">The number of bytes from <c>data</c> to use</param>\r
+        /// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>\r
+        /// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>\r
+        /// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>\r
+        public override void Update(byte[] data, int offset, int count)\r
+        {\r
+            if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();\r
+            if ((offset+count) > data.Length) throw new ArgumentException();\r
+            GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);\r
+            try\r
+            {\r
+                _current = crc32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count);\r
+            }\r
+            finally\r
+            {\r
+                hData.Free();\r
+            }\r
+        }\r
+\r
+    }\r
+    #endregion\r
+\r
+    #region Adler\r
+    /// <summary>\r
+    /// Implements a checksum generator that computes the Adler checksum on data\r
+    /// </summary>\r
+    public sealed class AdlerChecksum : ChecksumGeneratorBase\r
+    {\r
+        #region DLL imports\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern uint adler32(uint adler, int data, uint length);\r
+\r
+        #endregion\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the Adler checksum generator\r
+        /// </summary>\r
+        public AdlerChecksum() : base() {}\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the Adler checksum generator with a specified value\r
+        /// </summary>\r
+        /// <param name="initialValue">The value to set the current checksum to</param>\r
+        public AdlerChecksum(uint initialValue) : base(initialValue) {}\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with part of an array of bytes\r
+        /// </summary>\r
+        /// <param name="data">The data to update the checksum with</param>\r
+        /// <param name="offset">Where in <c>data</c> to start updating</param>\r
+        /// <param name="count">The number of bytes from <c>data</c> to use</param>\r
+        /// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>\r
+        /// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>\r
+        /// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>\r
+        public override void Update(byte[] data, int offset, int count)\r
+        {\r
+            if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();\r
+            if ((offset+count) > data.Length) throw new ArgumentException();\r
+            GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);\r
+            try\r
+            {\r
+                _current = adler32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count);\r
+            }\r
+            finally\r
+            {\r
+                hData.Free();\r
+            }\r
+        }\r
+\r
+    }\r
+    #endregion\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/CircularBuffer.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/CircularBuffer.cs
new file mode 100644 (file)
index 0000000..c1cab3a
--- /dev/null
@@ -0,0 +1,83 @@
+//\r
+// Â© Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.Diagnostics;\r
+\r
+namespace DotZLib\r
+{\r
+\r
+       /// <summary>\r
+       /// This class implements a circular buffer\r
+       /// </summary>\r
+       internal class CircularBuffer\r
+       {\r
+        #region Private data\r
+        private int _capacity;\r
+        private int _head;\r
+        private int _tail;\r
+        private int _size;\r
+        private byte[] _buffer;\r
+        #endregion\r
+\r
+        public CircularBuffer(int capacity)\r
+        {\r
+            Debug.Assert( capacity > 0 );\r
+            _buffer = new byte[capacity];\r
+            _capacity = capacity;\r
+            _head = 0;\r
+            _tail = 0;\r
+            _size = 0;\r
+        }\r
+\r
+        public int Size { get { return _size; } }\r
+\r
+        public int Put(byte[] source, int offset, int count)\r
+        {\r
+            Debug.Assert( count > 0 );\r
+            int trueCount = Math.Min(count, _capacity - Size);\r
+            for (int i = 0; i < trueCount; ++i)\r
+                _buffer[(_tail+i) % _capacity] = source[offset+i];\r
+            _tail += trueCount;\r
+            _tail %= _capacity;\r
+            _size += trueCount;\r
+            return trueCount;\r
+        }\r
+\r
+        public bool Put(byte b)\r
+        {\r
+            if (Size == _capacity) // no room\r
+                return false;\r
+            _buffer[_tail++] = b;\r
+            _tail %= _capacity;\r
+            ++_size;\r
+            return true;\r
+        }\r
+\r
+        public int Get(byte[] destination, int offset, int count)\r
+        {\r
+            int trueCount = Math.Min(count,Size);\r
+            for (int i = 0; i < trueCount; ++i)\r
+                destination[offset + i] = _buffer[(_head+i) % _capacity];\r
+            _head += trueCount;\r
+            _head %= _capacity;\r
+            _size -= trueCount;\r
+            return trueCount;\r
+        }\r
+\r
+        public int Get()\r
+        {\r
+            if (Size == 0)\r
+                return -1;\r
+\r
+            int result = (int)_buffer[_head++ % _capacity];\r
+            --_size;\r
+            return result;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/CodecBase.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/CodecBase.cs
new file mode 100644 (file)
index 0000000..42e6da3
--- /dev/null
@@ -0,0 +1,198 @@
+//\r
+// Â© Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.Runtime.InteropServices;\r
+\r
+namespace DotZLib\r
+{\r
+       /// <summary>\r
+       /// Implements the common functionality needed for all <see cref="Codec"/>s\r
+       /// </summary>\r
+       public abstract class CodecBase : Codec, IDisposable\r
+       {\r
+\r
+        #region Data members\r
+\r
+        /// <summary>\r
+        /// Instance of the internal zlib buffer structure that is\r
+        /// passed to all functions in the zlib dll\r
+        /// </summary>\r
+        internal ZStream _ztream = new ZStream();\r
+\r
+        /// <summary>\r
+        /// True if the object instance has been disposed, false otherwise\r
+        /// </summary>\r
+        protected bool _isDisposed = false;\r
+\r
+        /// <summary>\r
+        /// The size of the internal buffers\r
+        /// </summary>\r
+        protected const int kBufferSize = 16384;\r
+\r
+        private byte[] _outBuffer = new byte[kBufferSize];\r
+        private byte[] _inBuffer = new byte[kBufferSize];\r
+\r
+        private GCHandle _hInput;\r
+        private GCHandle _hOutput;\r
+\r
+        private uint _checksum = 0;\r
+\r
+        #endregion\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the <c>CodeBase</c> class.\r
+        /// </summary>\r
+               public CodecBase()\r
+               {\r
+            try\r
+            {\r
+                _hInput = GCHandle.Alloc(_inBuffer, GCHandleType.Pinned);\r
+                _hOutput = GCHandle.Alloc(_outBuffer, GCHandleType.Pinned);\r
+            }\r
+            catch (Exception)\r
+            {\r
+                CleanUp(false);\r
+                throw;\r
+            }\r
+        }\r
+\r
+\r
+        #region Codec Members\r
+\r
+        /// <summary>\r
+        /// Occurs when more processed data are available.\r
+        /// </summary>\r
+        public event DataAvailableHandler DataAvailable;\r
+\r
+        /// <summary>\r
+        /// Fires the <see cref="DataAvailable"/> event\r
+        /// </summary>\r
+        protected void OnDataAvailable()\r
+        {\r
+            if (_ztream.total_out > 0)\r
+            {\r
+                if (DataAvailable != null)\r
+                    DataAvailable( _outBuffer, 0, (int)_ztream.total_out);\r
+                resetOutput();\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Adds more data to the codec to be processed.\r
+        /// </summary>\r
+        /// <param name="data">Byte array containing the data to be added to the codec</param>\r
+        /// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>\r
+        public void Add(byte[] data)\r
+        {\r
+            Add(data,0,data.Length);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Adds more data to the codec to be processed.\r
+        /// </summary>\r
+        /// <param name="data">Byte array containing the data to be added to the codec</param>\r
+        /// <param name="offset">The index of the first byte to add from <c>data</c></param>\r
+        /// <param name="count">The number of bytes to add</param>\r
+        /// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>\r
+        /// <remarks>This must be implemented by a derived class</remarks>\r
+        public abstract void Add(byte[] data, int offset, int count);\r
+\r
+        /// <summary>\r
+        /// Finishes up any pending data that needs to be processed and handled.\r
+        /// </summary>\r
+        /// <remarks>This must be implemented by a derived class</remarks>\r
+        public abstract void Finish();\r
+\r
+        /// <summary>\r
+        /// Gets the checksum of the data that has been added so far\r
+        /// </summary>\r
+        public uint Checksum { get { return _checksum; } }\r
+\r
+        #endregion\r
+\r
+        #region Destructor & IDisposable stuff\r
+\r
+        /// <summary>\r
+        /// Destroys this instance\r
+        /// </summary>\r
+        ~CodecBase()\r
+        {\r
+            CleanUp(false);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Releases any unmanaged resources and calls the <see cref="CleanUp()"/> method of the derived class\r
+        /// </summary>\r
+        public void Dispose()\r
+        {\r
+            CleanUp(true);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Performs any codec specific cleanup\r
+        /// </summary>\r
+        /// <remarks>This must be implemented by a derived class</remarks>\r
+        protected abstract void CleanUp();\r
+\r
+        // performs the release of the handles and calls the dereived CleanUp()\r
+        private void CleanUp(bool isDisposing)\r
+        {\r
+            if (!_isDisposed)\r
+            {\r
+                CleanUp();\r
+                if (_hInput.IsAllocated)\r
+                    _hInput.Free();\r
+                if (_hOutput.IsAllocated)\r
+                    _hOutput.Free();\r
+\r
+                _isDisposed = true;\r
+            }\r
+        }\r
+\r
+\r
+        #endregion\r
+\r
+        #region Helper methods\r
+\r
+        /// <summary>\r
+        /// Copies a number of bytes to the internal codec buffer - ready for proccesing\r
+        /// </summary>\r
+        /// <param name="data">The byte array that contains the data to copy</param>\r
+        /// <param name="startIndex">The index of the first byte to copy</param>\r
+        /// <param name="count">The number of bytes to copy from <c>data</c></param>\r
+        protected void copyInput(byte[] data, int startIndex, int count)\r
+        {\r
+            Array.Copy(data, startIndex, _inBuffer,0, count);\r
+            _ztream.next_in = _hInput.AddrOfPinnedObject();\r
+            _ztream.total_in = 0;\r
+            _ztream.avail_in = (uint)count;\r
+\r
+        }\r
+\r
+        /// <summary>\r
+        /// Resets the internal output buffers to a known state - ready for processing\r
+        /// </summary>\r
+        protected void resetOutput()\r
+        {\r
+            _ztream.total_out = 0;\r
+            _ztream.avail_out = kBufferSize;\r
+            _ztream.next_out = _hOutput.AddrOfPinnedObject();\r
+        }\r
+\r
+        /// <summary>\r
+        /// Updates the running checksum property\r
+        /// </summary>\r
+        /// <param name="newSum">The new checksum value</param>\r
+        protected void setChecksum(uint newSum)\r
+        {\r
+            _checksum = newSum;\r
+        }\r
+        #endregion\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/Deflater.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/Deflater.cs
new file mode 100644 (file)
index 0000000..c247792
--- /dev/null
@@ -0,0 +1,106 @@
+//\r
+// Â© Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.Diagnostics;\r
+using System.Runtime.InteropServices;\r
+\r
+namespace DotZLib\r
+{\r
+\r
+    /// <summary>\r
+    /// Implements a data compressor, using the deflate algorithm in the ZLib dll\r
+    /// </summary>\r
+       public sealed class Deflater : CodecBase\r
+       {\r
+        #region Dll imports\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]\r
+        private static extern int deflateInit_(ref ZStream sz, int level, string vs, int size);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int deflate(ref ZStream sz, int flush);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int deflateReset(ref ZStream sz);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int deflateEnd(ref ZStream sz);\r
+        #endregion\r
+\r
+        /// <summary>\r
+        /// Constructs an new instance of the <c>Deflater</c>\r
+        /// </summary>\r
+        /// <param name="level">The compression level to use for this <c>Deflater</c></param>\r
+               public Deflater(CompressLevel level) : base()\r
+               {\r
+            int retval = deflateInit_(ref _ztream, (int)level, Info.Version, Marshal.SizeOf(_ztream));\r
+            if (retval != 0)\r
+                throw new ZLibException(retval, "Could not initialize deflater");\r
+\r
+            resetOutput();\r
+               }\r
+\r
+        /// <summary>\r
+        /// Adds more data to the codec to be processed.\r
+        /// </summary>\r
+        /// <param name="data">Byte array containing the data to be added to the codec</param>\r
+        /// <param name="offset">The index of the first byte to add from <c>data</c></param>\r
+        /// <param name="count">The number of bytes to add</param>\r
+        /// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>\r
+        public override void Add(byte[] data, int offset, int count)\r
+        {\r
+            if (data == null) throw new ArgumentNullException();\r
+            if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();\r
+            if ((offset+count) > data.Length) throw new ArgumentException();\r
+\r
+            int total = count;\r
+            int inputIndex = offset;\r
+            int err = 0;\r
+\r
+            while (err >= 0 && inputIndex < total)\r
+            {\r
+                copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize));\r
+                while (err >= 0 && _ztream.avail_in > 0)\r
+                {\r
+                    err = deflate(ref _ztream, (int)FlushTypes.None);\r
+                    if (err == 0)\r
+                        while (_ztream.avail_out == 0)\r
+                        {\r
+                            OnDataAvailable();\r
+                            err = deflate(ref _ztream, (int)FlushTypes.None);\r
+                        }\r
+                    inputIndex += (int)_ztream.total_in;\r
+                }\r
+            }\r
+            setChecksum( _ztream.adler );\r
+        }\r
+\r
+\r
+        /// <summary>\r
+        /// Finishes up any pending data that needs to be processed and handled.\r
+        /// </summary>\r
+        public override void Finish()\r
+        {\r
+            int err;\r
+            do\r
+            {\r
+                err = deflate(ref _ztream, (int)FlushTypes.Finish);\r
+                OnDataAvailable();\r
+            }\r
+            while (err == 0);\r
+            setChecksum( _ztream.adler );\r
+            deflateReset(ref _ztream);\r
+            resetOutput();\r
+        }\r
+\r
+        /// <summary>\r
+        /// Closes the internal zlib deflate stream\r
+        /// </summary>\r
+        protected override void CleanUp() { deflateEnd(ref _ztream); }\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/DotZLib.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/DotZLib.cs
new file mode 100644 (file)
index 0000000..be184b4
--- /dev/null
@@ -0,0 +1,288 @@
+//\r
+// Â© Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.IO;\r
+using System.Runtime.InteropServices;\r
+using System.Text;\r
+\r
+\r
+namespace DotZLib\r
+{\r
+\r
+    #region Internal types\r
+\r
+    /// <summary>\r
+    /// Defines constants for the various flush types used with zlib\r
+    /// </summary>\r
+    internal enum FlushTypes\r
+    {\r
+        None,  Partial,  Sync,  Full,  Finish,  Block\r
+    }\r
+\r
+    #region ZStream structure\r
+    // internal mapping of the zlib zstream structure for marshalling\r
+    [StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Ansi)]\r
+    internal struct ZStream\r
+    {\r
+        public IntPtr next_in;\r
+        public uint avail_in;\r
+        public uint total_in;\r
+\r
+        public IntPtr next_out;\r
+        public uint avail_out;\r
+        public uint total_out;\r
+\r
+        [MarshalAs(UnmanagedType.LPStr)]\r
+        string msg;\r
+        uint state;\r
+\r
+        uint zalloc;\r
+        uint zfree;\r
+        uint opaque;\r
+\r
+        int data_type;\r
+        public uint adler;\r
+        uint reserved;\r
+    }\r
+\r
+    #endregion\r
+\r
+    #endregion\r
+\r
+    #region Public enums\r
+    /// <summary>\r
+    /// Defines constants for the available compression levels in zlib\r
+    /// </summary>\r
+    public enum CompressLevel : int\r
+    {\r
+        /// <summary>\r
+        /// The default compression level with a reasonable compromise between compression and speed\r
+        /// </summary>\r
+        Default = -1,\r
+        /// <summary>\r
+        /// No compression at all. The data are passed straight through.\r
+        /// </summary>\r
+        None = 0,\r
+        /// <summary>\r
+        /// The maximum compression rate available.\r
+        /// </summary>\r
+        Best = 9,\r
+        /// <summary>\r
+        /// The fastest available compression level.\r
+        /// </summary>\r
+        Fastest = 1\r
+    }\r
+    #endregion\r
+\r
+    #region Exception classes\r
+    /// <summary>\r
+    /// The exception that is thrown when an error occurs on the zlib dll\r
+    /// </summary>\r
+    public class ZLibException : ApplicationException\r
+    {\r
+        /// <summary>\r
+        /// Initializes a new instance of the <see cref="ZLibException"/> class with a specified\r
+        /// error message and error code\r
+        /// </summary>\r
+        /// <param name="errorCode">The zlib error code that caused the exception</param>\r
+        /// <param name="msg">A message that (hopefully) describes the error</param>\r
+        public ZLibException(int errorCode, string msg) : base(String.Format("ZLib error {0} {1}", errorCode, msg))\r
+        {\r
+        }\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the <see cref="ZLibException"/> class with a specified\r
+        /// error code\r
+        /// </summary>\r
+        /// <param name="errorCode">The zlib error code that caused the exception</param>\r
+        public ZLibException(int errorCode) : base(String.Format("ZLib error {0}", errorCode))\r
+        {\r
+        }\r
+    }\r
+    #endregion\r
+\r
+    #region Interfaces\r
+\r
+    /// <summary>\r
+    /// Declares methods and properties that enables a running checksum to be calculated\r
+    /// </summary>\r
+    public interface ChecksumGenerator\r
+    {\r
+        /// <summary>\r
+        /// Gets the current value of the checksum\r
+        /// </summary>\r
+        uint Value { get; }\r
+\r
+        /// <summary>\r
+        /// Clears the current checksum to 0\r
+        /// </summary>\r
+        void Reset();\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with an array of bytes\r
+        /// </summary>\r
+        /// <param name="data">The data to update the checksum with</param>\r
+        void Update(byte[] data);\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with part of an array of bytes\r
+        /// </summary>\r
+        /// <param name="data">The data to update the checksum with</param>\r
+        /// <param name="offset">Where in <c>data</c> to start updating</param>\r
+        /// <param name="count">The number of bytes from <c>data</c> to use</param>\r
+        /// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>\r
+        /// <exception cref="ArgumentNullException"><c>data</c> is a null reference</exception>\r
+        /// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>\r
+        void Update(byte[] data, int offset, int count);\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with the data from a string\r
+        /// </summary>\r
+        /// <param name="data">The string to update the checksum with</param>\r
+        /// <remarks>The characters in the string are converted by the UTF-8 encoding</remarks>\r
+        void Update(string data);\r
+\r
+        /// <summary>\r
+        /// Updates the current checksum with the data from a string, using a specific encoding\r
+        /// </summary>\r
+        /// <param name="data">The string to update the checksum with</param>\r
+        /// <param name="encoding">The encoding to use</param>\r
+        void Update(string data, Encoding encoding);\r
+    }\r
+\r
+\r
+    /// <summary>\r
+    /// Represents the method that will be called from a codec when new data\r
+    /// are available.\r
+    /// </summary>\r
+    /// <paramref name="data">The byte array containing the processed data</paramref>\r
+    /// <paramref name="startIndex">The index of the first processed byte in <c>data</c></paramref>\r
+    /// <paramref name="count">The number of processed bytes available</paramref>\r
+    /// <remarks>On return from this method, the data may be overwritten, so grab it while you can.\r
+    /// You cannot assume that startIndex will be zero.\r
+    /// </remarks>\r
+    public delegate void DataAvailableHandler(byte[] data, int startIndex, int count);\r
+\r
+    /// <summary>\r
+    /// Declares methods and events for implementing compressors/decompressors\r
+    /// </summary>\r
+    public interface Codec\r
+    {\r
+        /// <summary>\r
+        /// Occurs when more processed data are available.\r
+        /// </summary>\r
+        event DataAvailableHandler DataAvailable;\r
+\r
+        /// <summary>\r
+        /// Adds more data to the codec to be processed.\r
+        /// </summary>\r
+        /// <param name="data">Byte array containing the data to be added to the codec</param>\r
+        /// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>\r
+        void Add(byte[] data);\r
+\r
+        /// <summary>\r
+        /// Adds more data to the codec to be processed.\r
+        /// </summary>\r
+        /// <param name="data">Byte array containing the data to be added to the codec</param>\r
+        /// <param name="offset">The index of the first byte to add from <c>data</c></param>\r
+        /// <param name="count">The number of bytes to add</param>\r
+        /// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>\r
+        void Add(byte[] data, int offset, int count);\r
+\r
+        /// <summary>\r
+        /// Finishes up any pending data that needs to be processed and handled.\r
+        /// </summary>\r
+        void Finish();\r
+\r
+        /// <summary>\r
+        /// Gets the checksum of the data that has been added so far\r
+        /// </summary>\r
+        uint Checksum { get; }\r
+\r
+\r
+    }\r
+\r
+    #endregion\r
+\r
+    #region Classes\r
+    /// <summary>\r
+    /// Encapsulates general information about the ZLib library\r
+    /// </summary>\r
+    public class Info\r
+    {\r
+        #region DLL imports\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern uint zlibCompileFlags();\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern string zlibVersion();\r
+        #endregion\r
+\r
+        #region Private stuff\r
+        private uint _flags;\r
+\r
+        // helper function that unpacks a bitsize mask\r
+        private static int bitSize(uint bits)\r
+        {\r
+            switch (bits)\r
+            {\r
+                case 0: return 16;\r
+                case 1: return 32;\r
+                case 2: return 64;\r
+            }\r
+            return -1;\r
+        }\r
+        #endregion\r
+\r
+        /// <summary>\r
+        /// Constructs an instance of the <c>Info</c> class.\r
+        /// </summary>\r
+        public Info()\r
+        {\r
+            _flags = zlibCompileFlags();\r
+        }\r
+\r
+        /// <summary>\r
+        /// True if the library is compiled with debug info\r
+        /// </summary>\r
+        public bool HasDebugInfo { get { return 0 != (_flags & 0x100); } }\r
+\r
+        /// <summary>\r
+        /// True if the library is compiled with assembly optimizations\r
+        /// </summary>\r
+        public bool UsesAssemblyCode { get { return 0 != (_flags & 0x200); } }\r
+\r
+        /// <summary>\r
+        /// Gets the size of the unsigned int that was compiled into Zlib\r
+        /// </summary>\r
+        public int SizeOfUInt { get { return bitSize(_flags & 3); } }\r
+\r
+        /// <summary>\r
+        /// Gets the size of the unsigned long that was compiled into Zlib\r
+        /// </summary>\r
+        public int SizeOfULong { get { return bitSize((_flags >> 2) & 3); } }\r
+\r
+        /// <summary>\r
+        /// Gets the size of the pointers that were compiled into Zlib\r
+        /// </summary>\r
+        public int SizeOfPointer { get { return bitSize((_flags >> 4) & 3); } }\r
+\r
+        /// <summary>\r
+        /// Gets the size of the z_off_t type that was compiled into Zlib\r
+        /// </summary>\r
+        public int SizeOfOffset { get { return bitSize((_flags >> 6) & 3); } }\r
+\r
+        /// <summary>\r
+        /// Gets the version of ZLib as a string, e.g. "1.2.1"\r
+        /// </summary>\r
+        public static string Version { get { return zlibVersion(); } }\r
+    }\r
+\r
+    #endregion\r
+\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/DotZLib.csproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/DotZLib.csproj
new file mode 100644 (file)
index 0000000..71eeb85
--- /dev/null
@@ -0,0 +1,141 @@
+<VisualStudioProject>\r
+    <CSHARP\r
+        ProjectType = "Local"\r
+        ProductVersion = "7.10.3077"\r
+        SchemaVersion = "2.0"\r
+        ProjectGuid = "{BB1EE0B1-1808-46CB-B786-949D91117FC5}"\r
+    >\r
+        <Build>\r
+            <Settings\r
+                ApplicationIcon = ""\r
+                AssemblyKeyContainerName = ""\r
+                AssemblyName = "DotZLib"\r
+                AssemblyOriginatorKeyFile = ""\r
+                DefaultClientScript = "JScript"\r
+                DefaultHTMLPageLayout = "Grid"\r
+                DefaultTargetSchema = "IE50"\r
+                DelaySign = "false"\r
+                OutputType = "Library"\r
+                PreBuildEvent = ""\r
+                PostBuildEvent = ""\r
+                RootNamespace = "DotZLib"\r
+                RunPostBuildEvent = "OnBuildSuccess"\r
+                StartupObject = ""\r
+            >\r
+                <Config\r
+                    Name = "Debug"\r
+                    AllowUnsafeBlocks = "false"\r
+                    BaseAddress = "285212672"\r
+                    CheckForOverflowUnderflow = "false"\r
+                    ConfigurationOverrideFile = ""\r
+                    DefineConstants = "DEBUG;TRACE"\r
+                    DocumentationFile = "docs\DotZLib.xml"\r
+                    DebugSymbols = "true"\r
+                    FileAlignment = "4096"\r
+                    IncrementalBuild = "false"\r
+                    NoStdLib = "false"\r
+                    NoWarn = "1591"\r
+                    Optimize = "false"\r
+                    OutputPath = "bin\Debug\"\r
+                    RegisterForComInterop = "false"\r
+                    RemoveIntegerChecks = "false"\r
+                    TreatWarningsAsErrors = "false"\r
+                    WarningLevel = "4"\r
+                />\r
+                <Config\r
+                    Name = "Release"\r
+                    AllowUnsafeBlocks = "false"\r
+                    BaseAddress = "285212672"\r
+                    CheckForOverflowUnderflow = "false"\r
+                    ConfigurationOverrideFile = ""\r
+                    DefineConstants = "TRACE"\r
+                    DocumentationFile = "docs\DotZLib.xml"\r
+                    DebugSymbols = "false"\r
+                    FileAlignment = "4096"\r
+                    IncrementalBuild = "false"\r
+                    NoStdLib = "false"\r
+                    NoWarn = ""\r
+                    Optimize = "true"\r
+                    OutputPath = "bin\Release\"\r
+                    RegisterForComInterop = "false"\r
+                    RemoveIntegerChecks = "false"\r
+                    TreatWarningsAsErrors = "false"\r
+                    WarningLevel = "4"\r
+                />\r
+            </Settings>\r
+            <References>\r
+                <Reference\r
+                    Name = "System"\r
+                    AssemblyName = "System"\r
+                    HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.dll"\r
+                />\r
+                <Reference\r
+                    Name = "System.Data"\r
+                    AssemblyName = "System.Data"\r
+                    HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.Data.dll"\r
+                />\r
+                <Reference\r
+                    Name = "System.XML"\r
+                    AssemblyName = "System.Xml"\r
+                    HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.XML.dll"\r
+                />\r
+                <Reference\r
+                    Name = "nunit.framework"\r
+                    AssemblyName = "nunit.framework"\r
+                    HintPath = "E:\apps\NUnit V2.1\\bin\nunit.framework.dll"\r
+                    AssemblyFolderKey = "hklm\dn\nunit.framework"\r
+                />\r
+            </References>\r
+        </Build>\r
+        <Files>\r
+            <Include>\r
+                <File\r
+                    RelPath = "AssemblyInfo.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+                <File\r
+                    RelPath = "ChecksumImpl.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+                <File\r
+                    RelPath = "CircularBuffer.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+                <File\r
+                    RelPath = "CodecBase.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+                <File\r
+                    RelPath = "Deflater.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+                <File\r
+                    RelPath = "DotZLib.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+                <File\r
+                    RelPath = "GZipStream.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+                <File\r
+                    RelPath = "Inflater.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+                <File\r
+                    RelPath = "UnitTests.cs"\r
+                    SubType = "Code"\r
+                    BuildAction = "Compile"\r
+                />\r
+            </Include>\r
+        </Files>\r
+    </CSHARP>\r
+</VisualStudioProject>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/GZipStream.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/GZipStream.cs
new file mode 100644 (file)
index 0000000..b161300
--- /dev/null
@@ -0,0 +1,301 @@
+//\r
+// Â© Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.IO;\r
+using System.Runtime.InteropServices;\r
+\r
+namespace DotZLib\r
+{\r
+       /// <summary>\r
+       /// Implements a compressed <see cref="Stream"/>, in GZip (.gz) format.\r
+       /// </summary>\r
+       public class GZipStream : Stream, IDisposable\r
+       {\r
+        #region Dll Imports\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]\r
+        private static extern IntPtr gzopen(string name, string mode);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int gzclose(IntPtr gzFile);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int gzwrite(IntPtr gzFile, int data, int length);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int gzread(IntPtr gzFile, int data, int length);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int gzgetc(IntPtr gzFile);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int gzputc(IntPtr gzFile, int c);\r
+\r
+        #endregion\r
+\r
+        #region Private data\r
+        private IntPtr _gzFile;\r
+        private bool _isDisposed = false;\r
+        private bool _isWriting;\r
+        #endregion\r
+\r
+        #region Constructors\r
+        /// <summary>\r
+        /// Creates a new file as a writeable GZipStream\r
+        /// </summary>\r
+        /// <param name="fileName">The name of the compressed file to create</param>\r
+        /// <param name="level">The compression level to use when adding data</param>\r
+        /// <exception cref="ZLibException">If an error occurred in the internal zlib function</exception>\r
+               public GZipStream(string fileName, CompressLevel level)\r
+               {\r
+            _isWriting = true;\r
+            _gzFile = gzopen(fileName, String.Format("wb{0}", (int)level));\r
+            if (_gzFile == IntPtr.Zero)\r
+                throw new ZLibException(-1, "Could not open " + fileName);\r
+               }\r
+\r
+        /// <summary>\r
+        /// Opens an existing file as a readable GZipStream\r
+        /// </summary>\r
+        /// <param name="fileName">The name of the file to open</param>\r
+        /// <exception cref="ZLibException">If an error occurred in the internal zlib function</exception>\r
+        public GZipStream(string fileName)\r
+        {\r
+            _isWriting = false;\r
+            _gzFile = gzopen(fileName, "rb");\r
+            if (_gzFile == IntPtr.Zero)\r
+                throw new ZLibException(-1, "Could not open " + fileName);\r
+\r
+        }\r
+        #endregion\r
+\r
+        #region Access properties\r
+        /// <summary>\r
+        /// Returns true of this stream can be read from, false otherwise\r
+        /// </summary>\r
+        public override bool CanRead\r
+        {\r
+            get\r
+            {\r
+                return !_isWriting;\r
+            }\r
+        }\r
+\r
+\r
+        /// <summary>\r
+        /// Returns false.\r
+        /// </summary>\r
+        public override bool CanSeek\r
+        {\r
+            get\r
+            {\r
+                return false;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns true if this tsream is writeable, false otherwise\r
+        /// </summary>\r
+        public override bool CanWrite\r
+        {\r
+            get\r
+            {\r
+                return _isWriting;\r
+            }\r
+        }\r
+        #endregion\r
+\r
+        #region Destructor & IDispose stuff\r
+\r
+        /// <summary>\r
+        /// Destroys this instance\r
+        /// </summary>\r
+        ~GZipStream()\r
+        {\r
+            cleanUp(false);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Closes the external file handle\r
+        /// </summary>\r
+        public void Dispose()\r
+        {\r
+            cleanUp(true);\r
+        }\r
+\r
+        // Does the actual closing of the file handle.\r
+        private void cleanUp(bool isDisposing)\r
+        {\r
+            if (!_isDisposed)\r
+            {\r
+                gzclose(_gzFile);\r
+                _isDisposed = true;\r
+            }\r
+        }\r
+        #endregion\r
+\r
+        #region Basic reading and writing\r
+        /// <summary>\r
+        /// Attempts to read a number of bytes from the stream.\r
+        /// </summary>\r
+        /// <param name="buffer">The destination data buffer</param>\r
+        /// <param name="offset">The index of the first destination byte in <c>buffer</c></param>\r
+        /// <param name="count">The number of bytes requested</param>\r
+        /// <returns>The number of bytes read</returns>\r
+        /// <exception cref="ArgumentNullException">If <c>buffer</c> is null</exception>\r
+        /// <exception cref="ArgumentOutOfRangeException">If <c>count</c> or <c>offset</c> are negative</exception>\r
+        /// <exception cref="ArgumentException">If <c>offset</c>  + <c>count</c> is &gt; buffer.Length</exception>\r
+        /// <exception cref="NotSupportedException">If this stream is not readable.</exception>\r
+        /// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception>\r
+        public override int Read(byte[] buffer, int offset, int count)\r
+        {\r
+            if (!CanRead) throw new NotSupportedException();\r
+            if (buffer == null) throw new ArgumentNullException();\r
+            if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();\r
+            if ((offset+count) > buffer.Length) throw new ArgumentException();\r
+            if (_isDisposed) throw new ObjectDisposedException("GZipStream");\r
+\r
+            GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned);\r
+            int result;\r
+            try\r
+            {\r
+                result = gzread(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count);\r
+                if (result < 0)\r
+                    throw new IOException();\r
+            }\r
+            finally\r
+            {\r
+                h.Free();\r
+            }\r
+            return result;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Attempts to read a single byte from the stream.\r
+        /// </summary>\r
+        /// <returns>The byte that was read, or -1 in case of error or End-Of-File</returns>\r
+        public override int ReadByte()\r
+        {\r
+            if (!CanRead) throw new NotSupportedException();\r
+            if (_isDisposed) throw new ObjectDisposedException("GZipStream");\r
+            return gzgetc(_gzFile);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Writes a number of bytes to the stream\r
+        /// </summary>\r
+        /// <param name="buffer"></param>\r
+        /// <param name="offset"></param>\r
+        /// <param name="count"></param>\r
+        /// <exception cref="ArgumentNullException">If <c>buffer</c> is null</exception>\r
+        /// <exception cref="ArgumentOutOfRangeException">If <c>count</c> or <c>offset</c> are negative</exception>\r
+        /// <exception cref="ArgumentException">If <c>offset</c>  + <c>count</c> is &gt; buffer.Length</exception>\r
+        /// <exception cref="NotSupportedException">If this stream is not writeable.</exception>\r
+        /// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception>\r
+        public override void Write(byte[] buffer, int offset, int count)\r
+        {\r
+            if (!CanWrite) throw new NotSupportedException();\r
+            if (buffer == null) throw new ArgumentNullException();\r
+            if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();\r
+            if ((offset+count) > buffer.Length) throw new ArgumentException();\r
+            if (_isDisposed) throw new ObjectDisposedException("GZipStream");\r
+\r
+            GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned);\r
+            try\r
+            {\r
+                int result = gzwrite(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count);\r
+                if (result < 0)\r
+                    throw new IOException();\r
+            }\r
+            finally\r
+            {\r
+                h.Free();\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Writes a single byte to the stream\r
+        /// </summary>\r
+        /// <param name="value">The byte to add to the stream.</param>\r
+        /// <exception cref="NotSupportedException">If this stream is not writeable.</exception>\r
+        /// <exception cref="ObjectDisposedException">If this stream has been disposed.</exception>\r
+        public override void WriteByte(byte value)\r
+        {\r
+            if (!CanWrite) throw new NotSupportedException();\r
+            if (_isDisposed) throw new ObjectDisposedException("GZipStream");\r
+\r
+            int result = gzputc(_gzFile, (int)value);\r
+            if (result < 0)\r
+                throw new IOException();\r
+        }\r
+        #endregion\r
+\r
+        #region Position & length stuff\r
+        /// <summary>\r
+        /// Not supported.\r
+        /// </summary>\r
+        /// <param name="value"></param>\r
+        /// <exception cref="NotSupportedException">Always thrown</exception>\r
+        public override void SetLength(long value)\r
+        {\r
+            throw new NotSupportedException();\r
+        }\r
+\r
+        /// <summary>\r
+        ///  Not suppported.\r
+        /// </summary>\r
+        /// <param name="offset"></param>\r
+        /// <param name="origin"></param>\r
+        /// <returns></returns>\r
+        /// <exception cref="NotSupportedException">Always thrown</exception>\r
+        public override long Seek(long offset, SeekOrigin origin)\r
+        {\r
+            throw new NotSupportedException();\r
+        }\r
+\r
+        /// <summary>\r
+        /// Flushes the <c>GZipStream</c>.\r
+        /// </summary>\r
+        /// <remarks>In this implementation, this method does nothing. This is because excessive\r
+        /// flushing may degrade the achievable compression rates.</remarks>\r
+        public override void Flush()\r
+        {\r
+            // left empty on purpose\r
+        }\r
+\r
+        /// <summary>\r
+        /// Gets/sets the current position in the <c>GZipStream</c>. Not suppported.\r
+        /// </summary>\r
+        /// <remarks>In this implementation this property is not supported</remarks>\r
+        /// <exception cref="NotSupportedException">Always thrown</exception>\r
+        public override long Position\r
+        {\r
+            get\r
+            {\r
+                throw new NotSupportedException();\r
+            }\r
+            set\r
+            {\r
+                throw new NotSupportedException();\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Gets the size of the stream. Not suppported.\r
+        /// </summary>\r
+        /// <remarks>In this implementation this property is not supported</remarks>\r
+        /// <exception cref="NotSupportedException">Always thrown</exception>\r
+        public override long Length\r
+        {\r
+            get\r
+            {\r
+                throw new NotSupportedException();\r
+            }\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/Inflater.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/Inflater.cs
new file mode 100644 (file)
index 0000000..8ed5451
--- /dev/null
@@ -0,0 +1,105 @@
+//\r
+// Â© Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.Diagnostics;\r
+using System.Runtime.InteropServices;\r
+\r
+namespace DotZLib\r
+{\r
+\r
+    /// <summary>\r
+    /// Implements a data decompressor, using the inflate algorithm in the ZLib dll\r
+    /// </summary>\r
+    public class Inflater : CodecBase\r
+       {\r
+        #region Dll imports\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]\r
+        private static extern int inflateInit_(ref ZStream sz, string vs, int size);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int inflate(ref ZStream sz, int flush);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int inflateReset(ref ZStream sz);\r
+\r
+        [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]\r
+        private static extern int inflateEnd(ref ZStream sz);\r
+        #endregion\r
+\r
+        /// <summary>\r
+        /// Constructs an new instance of the <c>Inflater</c>\r
+        /// </summary>\r
+        public Inflater() : base()\r
+               {\r
+            int retval = inflateInit_(ref _ztream, Info.Version, Marshal.SizeOf(_ztream));\r
+            if (retval != 0)\r
+                throw new ZLibException(retval, "Could not initialize inflater");\r
+\r
+            resetOutput();\r
+        }\r
+\r
+\r
+        /// <summary>\r
+        /// Adds more data to the codec to be processed.\r
+        /// </summary>\r
+        /// <param name="data">Byte array containing the data to be added to the codec</param>\r
+        /// <param name="offset">The index of the first byte to add from <c>data</c></param>\r
+        /// <param name="count">The number of bytes to add</param>\r
+        /// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>\r
+        public override void Add(byte[] data, int offset, int count)\r
+        {\r
+            if (data == null) throw new ArgumentNullException();\r
+            if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();\r
+            if ((offset+count) > data.Length) throw new ArgumentException();\r
+\r
+            int total = count;\r
+            int inputIndex = offset;\r
+            int err = 0;\r
+\r
+            while (err >= 0 && inputIndex < total)\r
+            {\r
+                copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize));\r
+                err = inflate(ref _ztream, (int)FlushTypes.None);\r
+                if (err == 0)\r
+                    while (_ztream.avail_out == 0)\r
+                    {\r
+                        OnDataAvailable();\r
+                        err = inflate(ref _ztream, (int)FlushTypes.None);\r
+                    }\r
+\r
+                inputIndex += (int)_ztream.total_in;\r
+            }\r
+            setChecksum( _ztream.adler );\r
+        }\r
+\r
+\r
+        /// <summary>\r
+        /// Finishes up any pending data that needs to be processed and handled.\r
+        /// </summary>\r
+        public override void Finish()\r
+        {\r
+            int err;\r
+            do\r
+            {\r
+                err = inflate(ref _ztream, (int)FlushTypes.Finish);\r
+                OnDataAvailable();\r
+            }\r
+            while (err == 0);\r
+            setChecksum( _ztream.adler );\r
+            inflateReset(ref _ztream);\r
+            resetOutput();\r
+        }\r
+\r
+        /// <summary>\r
+        /// Closes the internal zlib inflate stream\r
+        /// </summary>\r
+        protected override void CleanUp() { inflateEnd(ref _ztream); }\r
+\r
+\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/UnitTests.cs b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/DotZLib/UnitTests.cs
new file mode 100644 (file)
index 0000000..b33d9d9
--- /dev/null
@@ -0,0 +1,274 @@
+//\r
+// Â© Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.Collections;\r
+using System.IO;\r
+\r
+// uncomment the define below to include unit tests\r
+//#define nunit\r
+#if nunit\r
+using NUnit.Framework;\r
+\r
+// Unit tests for the DotZLib class library\r
+// ----------------------------------------\r
+//\r
+// Use this with NUnit 2 from http://www.nunit.org\r
+//\r
+\r
+namespace DotZLibTests\r
+{\r
+    using DotZLib;\r
+\r
+    // helper methods\r
+    internal class Utils\r
+    {\r
+        public static bool byteArrEqual( byte[] lhs, byte[] rhs )\r
+        {\r
+            if (lhs.Length != rhs.Length)\r
+                return false;\r
+            for (int i = lhs.Length-1; i >= 0; --i)\r
+                if (lhs[i] != rhs[i])\r
+                    return false;\r
+            return true;\r
+        }\r
+\r
+    }\r
+\r
+\r
+    [TestFixture]\r
+    public class CircBufferTests\r
+    {\r
+        #region Circular buffer tests\r
+        [Test]\r
+        public void SinglePutGet()\r
+        {\r
+            CircularBuffer buf = new CircularBuffer(10);\r
+            Assert.AreEqual( 0, buf.Size );\r
+            Assert.AreEqual( -1, buf.Get() );\r
+\r
+            Assert.IsTrue(buf.Put( 1 ));\r
+            Assert.AreEqual( 1, buf.Size );\r
+            Assert.AreEqual( 1, buf.Get() );\r
+            Assert.AreEqual( 0, buf.Size );\r
+            Assert.AreEqual( -1, buf.Get() );\r
+        }\r
+\r
+        [Test]\r
+        public void BlockPutGet()\r
+        {\r
+            CircularBuffer buf = new CircularBuffer(10);\r
+            byte[] arr = {1,2,3,4,5,6,7,8,9,10};\r
+            Assert.AreEqual( 10, buf.Put(arr,0,10) );\r
+            Assert.AreEqual( 10, buf.Size );\r
+            Assert.IsFalse( buf.Put(11) );\r
+            Assert.AreEqual( 1, buf.Get() );\r
+            Assert.IsTrue( buf.Put(11) );\r
+\r
+            byte[] arr2 = (byte[])arr.Clone();\r
+            Assert.AreEqual( 9, buf.Get(arr2,1,9) );\r
+            Assert.IsTrue( Utils.byteArrEqual(arr,arr2) );\r
+        }\r
+\r
+        #endregion\r
+    }\r
+\r
+    [TestFixture]\r
+    public class ChecksumTests\r
+    {\r
+        #region CRC32 Tests\r
+        [Test]\r
+        public void CRC32_Null()\r
+        {\r
+            CRC32Checksum crc32 = new CRC32Checksum();\r
+            Assert.AreEqual( 0, crc32.Value );\r
+\r
+            crc32 = new CRC32Checksum(1);\r
+            Assert.AreEqual( 1, crc32.Value );\r
+\r
+            crc32 = new CRC32Checksum(556);\r
+            Assert.AreEqual( 556, crc32.Value );\r
+        }\r
+\r
+        [Test]\r
+        public void CRC32_Data()\r
+        {\r
+            CRC32Checksum crc32 = new CRC32Checksum();\r
+            byte[] data = { 1,2,3,4,5,6,7 };\r
+            crc32.Update(data);\r
+            Assert.AreEqual( 0x70e46888, crc32.Value  );\r
+\r
+            crc32 = new CRC32Checksum();\r
+            crc32.Update("penguin");\r
+            Assert.AreEqual( 0x0e5c1a120, crc32.Value );\r
+\r
+            crc32 = new CRC32Checksum(1);\r
+            crc32.Update("penguin");\r
+            Assert.AreEqual(0x43b6aa94, crc32.Value);\r
+\r
+        }\r
+        #endregion\r
+\r
+        #region Adler tests\r
+\r
+        [Test]\r
+        public void Adler_Null()\r
+        {\r
+            AdlerChecksum adler = new AdlerChecksum();\r
+            Assert.AreEqual(0, adler.Value);\r
+\r
+            adler = new AdlerChecksum(1);\r
+            Assert.AreEqual( 1, adler.Value );\r
+\r
+            adler = new AdlerChecksum(556);\r
+            Assert.AreEqual( 556, adler.Value );\r
+        }\r
+\r
+        [Test]\r
+        public void Adler_Data()\r
+        {\r
+            AdlerChecksum adler = new AdlerChecksum(1);\r
+            byte[] data = { 1,2,3,4,5,6,7 };\r
+            adler.Update(data);\r
+            Assert.AreEqual( 0x5b001d, adler.Value  );\r
+\r
+            adler = new AdlerChecksum();\r
+            adler.Update("penguin");\r
+            Assert.AreEqual(0x0bcf02f6, adler.Value );\r
+\r
+            adler = new AdlerChecksum(1);\r
+            adler.Update("penguin");\r
+            Assert.AreEqual(0x0bd602f7, adler.Value);\r
+\r
+        }\r
+        #endregion\r
+    }\r
+\r
+    [TestFixture]\r
+    public class InfoTests\r
+    {\r
+        #region Info tests\r
+        [Test]\r
+        public void Info_Version()\r
+        {\r
+            Info info = new Info();\r
+            Assert.AreEqual("1.2.6", Info.Version);\r
+            Assert.AreEqual(32, info.SizeOfUInt);\r
+            Assert.AreEqual(32, info.SizeOfULong);\r
+            Assert.AreEqual(32, info.SizeOfPointer);\r
+            Assert.AreEqual(32, info.SizeOfOffset);\r
+        }\r
+        #endregion\r
+    }\r
+\r
+    [TestFixture]\r
+    public class DeflateInflateTests\r
+    {\r
+        #region Deflate tests\r
+        [Test]\r
+        public void Deflate_Init()\r
+        {\r
+            using (Deflater def = new Deflater(CompressLevel.Default))\r
+            {\r
+            }\r
+        }\r
+\r
+        private ArrayList compressedData = new ArrayList();\r
+        private uint adler1;\r
+\r
+        private ArrayList uncompressedData = new ArrayList();\r
+        private uint adler2;\r
+\r
+        public void CDataAvail(byte[] data, int startIndex, int count)\r
+        {\r
+            for (int i = 0; i < count; ++i)\r
+                compressedData.Add(data[i+startIndex]);\r
+        }\r
+\r
+        [Test]\r
+        public void Deflate_Compress()\r
+        {\r
+            compressedData.Clear();\r
+\r
+            byte[] testData = new byte[35000];\r
+            for (int i = 0; i < testData.Length; ++i)\r
+                testData[i] = 5;\r
+\r
+            using (Deflater def = new Deflater((CompressLevel)5))\r
+            {\r
+                def.DataAvailable += new DataAvailableHandler(CDataAvail);\r
+                def.Add(testData);\r
+                def.Finish();\r
+                adler1 = def.Checksum;\r
+            }\r
+        }\r
+        #endregion\r
+\r
+        #region Inflate tests\r
+        [Test]\r
+        public void Inflate_Init()\r
+        {\r
+            using (Inflater inf = new Inflater())\r
+            {\r
+            }\r
+        }\r
+\r
+        private void DDataAvail(byte[] data, int startIndex, int count)\r
+        {\r
+            for (int i = 0; i < count; ++i)\r
+                uncompressedData.Add(data[i+startIndex]);\r
+        }\r
+\r
+        [Test]\r
+        public void Inflate_Expand()\r
+        {\r
+            uncompressedData.Clear();\r
+\r
+            using (Inflater inf = new Inflater())\r
+            {\r
+                inf.DataAvailable += new DataAvailableHandler(DDataAvail);\r
+                inf.Add((byte[])compressedData.ToArray(typeof(byte)));\r
+                inf.Finish();\r
+                adler2 = inf.Checksum;\r
+            }\r
+            Assert.AreEqual( adler1, adler2 );\r
+        }\r
+        #endregion\r
+    }\r
+\r
+    [TestFixture]\r
+    public class GZipStreamTests\r
+    {\r
+        #region GZipStream test\r
+        [Test]\r
+        public void GZipStream_WriteRead()\r
+        {\r
+            using (GZipStream gzOut = new GZipStream("gzstream.gz", CompressLevel.Best))\r
+            {\r
+                BinaryWriter writer = new BinaryWriter(gzOut);\r
+                writer.Write("hi there");\r
+                writer.Write(Math.PI);\r
+                writer.Write(42);\r
+            }\r
+\r
+            using (GZipStream gzIn = new GZipStream("gzstream.gz"))\r
+            {\r
+                BinaryReader reader = new BinaryReader(gzIn);\r
+                string s = reader.ReadString();\r
+                Assert.AreEqual("hi there",s);\r
+                double d = reader.ReadDouble();\r
+                Assert.AreEqual(Math.PI, d);\r
+                int i = reader.ReadInt32();\r
+                Assert.AreEqual(42,i);\r
+            }\r
+\r
+        }\r
+        #endregion\r
+       }\r
+}\r
+\r
+#endif\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/LICENSE_1_0.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/LICENSE_1_0.txt
new file mode 100644 (file)
index 0000000..30aac2c
--- /dev/null
@@ -0,0 +1,23 @@
+Boost Software License - Version 1.0 - August 17th, 2003\r
+\r
+Permission is hereby granted, free of charge, to any person or organization\r
+obtaining a copy of the software and accompanying documentation covered by\r
+this license (the "Software") to use, reproduce, display, distribute,\r
+execute, and transmit the Software, and to prepare derivative works of the\r
+Software, and to permit third-parties to whom the Software is furnished to\r
+do so, all subject to the following:\r
+\r
+The copyright notices in the Software and this entire statement, including\r
+the above license grant, this restriction and the following disclaimer,\r
+must be included in all copies of the Software, in whole or in part, and\r
+all derivative works of the Software, unless such copies or derivative\r
+works are solely in the form of machine-executable object code generated by\r
+a source language processor.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\r
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\r
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\r
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r
+DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/dotzlib/readme.txt
new file mode 100644 (file)
index 0000000..b239572
--- /dev/null
@@ -0,0 +1,58 @@
+This directory contains a .Net wrapper class library for the ZLib1.dll\r
+\r
+The wrapper includes support for inflating/deflating memory buffers,\r
+.Net streaming wrappers for the gz streams part of zlib, and wrappers\r
+for the checksum parts of zlib. See DotZLib/UnitTests.cs for examples.\r
+\r
+Directory structure:\r
+--------------------\r
+\r
+LICENSE_1_0.txt       - License file.\r
+readme.txt            - This file.\r
+DotZLib.chm           - Class library documentation\r
+DotZLib.build         - NAnt build file\r
+DotZLib.sln           - Microsoft Visual Studio 2003 solution file\r
+\r
+DotZLib\*.cs          - Source files for the class library\r
+\r
+Unit tests:\r
+-----------\r
+The file DotZLib/UnitTests.cs contains unit tests for use with NUnit 2.1 or higher.\r
+To include unit tests in the build, define nunit before building.\r
+\r
+\r
+Build instructions:\r
+-------------------\r
+\r
+1. Using Visual Studio.Net 2003:\r
+   Open DotZLib.sln in VS.Net and build from there. Output file (DotZLib.dll)\r
+   will be found ./DotZLib/bin/release or ./DotZLib/bin/debug, depending on\r
+   you are building the release or debug version of the library. Check\r
+   DotZLib/UnitTests.cs for instructions on how to include unit tests in the\r
+   build.\r
+\r
+2. Using NAnt:\r
+   Open a command prompt with access to the build environment and run nant\r
+   in the same directory as the DotZLib.build file.\r
+   You can define 2 properties on the nant command-line to control the build:\r
+   debug={true|false} to toggle between release/debug builds (default=true).\r
+   nunit={true|false} to include or esclude unit tests (default=true).\r
+   Also the target clean will remove binaries.\r
+   Output file (DotZLib.dll) will be found in either ./DotZLib/bin/release\r
+   or ./DotZLib/bin/debug, depending on whether you are building the release\r
+   or debug version of the library.\r
+\r
+   Examples:\r
+     nant -D:debug=false -D:nunit=false\r
+       will build a release mode version of the library without unit tests.\r
+     nant\r
+       will build a debug version of the library with unit tests\r
+     nant clean\r
+       will remove all previously built files.\r
+\r
+\r
+---------------------------------\r
+Copyright (c) Henrik Ravn 2004\r
+\r
+Use, modification and distribution are subject to the Boost Software License, Version 1.0.\r
+(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/gcc_gvmat64/gvmat64.S b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/gcc_gvmat64/gvmat64.S
new file mode 100644 (file)
index 0000000..dd858dd
--- /dev/null
@@ -0,0 +1,574 @@
+/*\r
+;uInt longest_match_x64(\r
+;    deflate_state *s,\r
+;    IPos cur_match);                             // current match \r
+\r
+; gvmat64.S -- Asm portion of the optimized longest_match for 32 bits x86_64\r
+;  (AMD64 on Athlon 64, Opteron, Phenom\r
+;     and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7)\r
+; this file is translation from gvmat64.asm to GCC 4.x (for Linux, Mac XCode)\r
+; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant.\r
+;\r
+; File written by Gilles Vollant, by converting to assembly the longest_match\r
+;  from Jean-loup Gailly in deflate.c of zLib and infoZip zip.\r
+;  and by taking inspiration on asm686 with masm, optimised assembly code\r
+;        from Brian Raiter, written 1998\r
+;\r
+;  This software is provided 'as-is', without any express or implied\r
+;  warranty.  In no event will the authors be held liable for any damages\r
+;  arising from the use of this software.\r
+;\r
+;  Permission is granted to anyone to use this software for any purpose,\r
+;  including commercial applications, and to alter it and redistribute it\r
+;  freely, subject to the following restrictions:\r
+;\r
+;  1. The origin of this software must not be misrepresented; you must not\r
+;     claim that you wrote the original software. If you use this software\r
+;     in a product, an acknowledgment in the product documentation would be\r
+;     appreciated but is not required.\r
+;  2. Altered source versions must be plainly marked as such, and must not be\r
+;     misrepresented as being the original software\r
+;  3. This notice may not be removed or altered from any source distribution.\r
+;\r
+;         http://www.zlib.net\r
+;         http://www.winimage.com/zLibDll\r
+;         http://www.muppetlabs.com/~breadbox/software/assembly.html\r
+;\r
+; to compile this file for zLib, I use option:\r
+;   gcc -c -arch x86_64 gvmat64.S\r
+\r
+\r
+;uInt longest_match(s, cur_match)\r
+;    deflate_state *s;\r
+;    IPos cur_match;                             // current match /\r
+;\r
+; with XCode for Mac, I had strange error with some jump on intel syntax\r
+; this is why BEFORE_JMP and AFTER_JMP are used\r
+ */\r
+\r
+\r
+#define BEFORE_JMP .att_syntax\r
+#define AFTER_JMP .intel_syntax noprefix\r
+\r
+#ifndef NO_UNDERLINE\r
+#      define  match_init      _match_init\r
+#      define  longest_match   _longest_match\r
+#endif\r
+\r
+.intel_syntax noprefix\r
+\r
+.globl match_init, longest_match\r
+.text\r
+longest_match:\r
+\r
+\r
+\r
+#define LocalVarsSize 96\r
+/*\r
+; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12\r
+; free register :  r14,r15\r
+; register can be saved : rsp\r
+*/\r
+\r
+#define chainlenwmask     (rsp + 8 - LocalVarsSize)\r
+#define nicematch         (rsp + 16 - LocalVarsSize)\r
+\r
+#define save_rdi        (rsp + 24 - LocalVarsSize)\r
+#define save_rsi        (rsp + 32 - LocalVarsSize)\r
+#define save_rbx        (rsp + 40 - LocalVarsSize)\r
+#define save_rbp        (rsp + 48 - LocalVarsSize)\r
+#define save_r12        (rsp + 56 - LocalVarsSize)\r
+#define save_r13        (rsp + 64 - LocalVarsSize)\r
+#define save_r14        (rsp + 72 - LocalVarsSize)\r
+#define save_r15        (rsp + 80 - LocalVarsSize)\r
+\r
+\r
+/*\r
+;  all the +4 offsets are due to the addition of pending_buf_size (in zlib\r
+;  in the deflate_state structure since the asm code was first written\r
+;  (if you compile with zlib 1.0.4 or older, remove the +4).\r
+;  Note : these value are good with a 8 bytes boundary pack structure\r
+*/\r
+\r
+#define    MAX_MATCH              258\r
+#define    MIN_MATCH              3\r
+#define    MIN_LOOKAHEAD          (MAX_MATCH+MIN_MATCH+1)\r
+\r
+/*\r
+;;; Offsets for fields in the deflate_state structure. These numbers\r
+;;; are calculated from the definition of deflate_state, with the\r
+;;; assumption that the compiler will dword-align the fields. (Thus,\r
+;;; changing the definition of deflate_state could easily cause this\r
+;;; program to crash horribly, without so much as a warning at\r
+;;; compile time. Sigh.)\r
+\r
+;  all the +zlib1222add offsets are due to the addition of fields\r
+;  in zlib in the deflate_state structure since the asm code was first written\r
+;  (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").\r
+;  (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").\r
+;  if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").\r
+*/\r
+\r
+\r
+\r
+/* you can check the structure offset by running\r
+\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include "deflate.h"\r
+\r
+void print_depl()\r
+{\r
+deflate_state ds;\r
+deflate_state *s=&ds;\r
+printf("size pointer=%u\n",(int)sizeof(void*));\r
+\r
+printf("#define dsWSize         %u\n",(int)(((char*)&(s->w_size))-((char*)s)));\r
+printf("#define dsWMask         %u\n",(int)(((char*)&(s->w_mask))-((char*)s)));\r
+printf("#define dsWindow        %u\n",(int)(((char*)&(s->window))-((char*)s)));\r
+printf("#define dsPrev          %u\n",(int)(((char*)&(s->prev))-((char*)s)));\r
+printf("#define dsMatchLen      %u\n",(int)(((char*)&(s->match_length))-((char*)s)));\r
+printf("#define dsPrevMatch     %u\n",(int)(((char*)&(s->prev_match))-((char*)s)));\r
+printf("#define dsStrStart      %u\n",(int)(((char*)&(s->strstart))-((char*)s)));\r
+printf("#define dsMatchStart    %u\n",(int)(((char*)&(s->match_start))-((char*)s)));\r
+printf("#define dsLookahead     %u\n",(int)(((char*)&(s->lookahead))-((char*)s)));\r
+printf("#define dsPrevLen       %u\n",(int)(((char*)&(s->prev_length))-((char*)s)));\r
+printf("#define dsMaxChainLen   %u\n",(int)(((char*)&(s->max_chain_length))-((char*)s)));\r
+printf("#define dsGoodMatch     %u\n",(int)(((char*)&(s->good_match))-((char*)s)));\r
+printf("#define dsNiceMatch     %u\n",(int)(((char*)&(s->nice_match))-((char*)s)));\r
+}\r
+*/\r
+\r
+#define dsWSize          68\r
+#define dsWMask          76\r
+#define dsWindow         80\r
+#define dsPrev           96\r
+#define dsMatchLen       144\r
+#define dsPrevMatch      148\r
+#define dsStrStart       156\r
+#define dsMatchStart     160\r
+#define dsLookahead      164\r
+#define dsPrevLen        168\r
+#define dsMaxChainLen    172\r
+#define dsGoodMatch      188\r
+#define dsNiceMatch      192\r
+\r
+#define window_size      [ rcx + dsWSize]\r
+#define WMask            [ rcx + dsWMask]\r
+#define window_ad        [ rcx + dsWindow]\r
+#define prev_ad          [ rcx + dsPrev]\r
+#define strstart         [ rcx + dsStrStart]\r
+#define match_start      [ rcx + dsMatchStart]\r
+#define Lookahead        [ rcx + dsLookahead] //; 0ffffffffh on infozip\r
+#define prev_length      [ rcx + dsPrevLen]\r
+#define max_chain_length [ rcx + dsMaxChainLen]\r
+#define good_match       [ rcx + dsGoodMatch]\r
+#define nice_match       [ rcx + dsNiceMatch]\r
+\r
+/*\r
+; windows:\r
+; parameter 1 in rcx(deflate state s), param 2 in rdx (cur match)\r
+\r
+; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and\r
+; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp\r
+;\r
+; All registers must be preserved across the call, except for\r
+;   rax, rcx, rdx, r8, r9, r10, and r11, which are scratch.\r
+\r
+;\r
+; gcc on macosx-linux:\r
+; see http://www.x86-64.org/documentation/abi-0.99.pdf\r
+; param 1 in rdi, param 2 in rsi\r
+; rbx, rsp, rbp, r12 to r15 must be preserved\r
+\r
+;;; Save registers that the compiler may be using, and adjust esp to\r
+;;; make room for our stack frame.\r
+\r
+\r
+;;; Retrieve the function arguments. r8d will hold cur_match\r
+;;; throughout the entire function. edx will hold the pointer to the\r
+;;; deflate_state structure during the function's setup (before\r
+;;; entering the main loop.\r
+\r
+; ms: parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match)\r
+; mac: param 1 in rdi, param 2 rsi\r
+; this clear high 32 bits of r8, which can be garbage in both r8 and rdx\r
+*/\r
+        mov [save_rbx],rbx\r
+        mov [save_rbp],rbp\r
+\r
+\r
+        mov rcx,rdi\r
+\r
+        mov r8d,esi\r
+\r
+\r
+        mov [save_r12],r12\r
+        mov [save_r13],r13\r
+        mov [save_r14],r14\r
+        mov [save_r15],r15\r
+\r
+\r
+//;;; uInt wmask = s->w_mask;\r
+//;;; unsigned chain_length = s->max_chain_length;\r
+//;;; if (s->prev_length >= s->good_match) {\r
+//;;;     chain_length >>= 2;\r
+//;;; }\r
+\r
+\r
+        mov edi, prev_length\r
+        mov esi, good_match\r
+        mov eax, WMask\r
+        mov ebx, max_chain_length\r
+        cmp edi, esi\r
+        jl  LastMatchGood\r
+        shr ebx, 2\r
+LastMatchGood:\r
+\r
+//;;; chainlen is decremented once beforehand so that the function can\r
+//;;; use the sign flag instead of the zero flag for the exit test.\r
+//;;; It is then shifted into the high word, to make room for the wmask\r
+//;;; value, which it will always accompany.\r
+\r
+        dec ebx\r
+        shl ebx, 16\r
+        or  ebx, eax\r
+\r
+//;;; on zlib only\r
+//;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;\r
+\r
+\r
+\r
+        mov eax, nice_match\r
+        mov [chainlenwmask], ebx\r
+        mov r10d, Lookahead\r
+        cmp r10d, eax\r
+        cmovnl r10d, eax\r
+        mov [nicematch],r10d\r
+\r
+\r
+\r
+//;;; register Bytef *scan = s->window + s->strstart;\r
+        mov r10, window_ad\r
+        mov ebp, strstart\r
+        lea r13, [r10 + rbp]\r
+\r
+//;;; Determine how many bytes the scan ptr is off from being\r
+//;;; dword-aligned.\r
+\r
+         mov r9,r13\r
+         neg r13\r
+         and r13,3\r
+\r
+//;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ?\r
+//;;;     s->strstart - (IPos)MAX_DIST(s) : NIL;\r
+\r
+\r
+        mov eax, window_size\r
+        sub eax, MIN_LOOKAHEAD\r
+\r
+\r
+        xor edi,edi\r
+        sub ebp, eax\r
+\r
+        mov r11d, prev_length\r
+\r
+        cmovng ebp,edi\r
+\r
+//;;; int best_len = s->prev_length;\r
+\r
+\r
+//;;; Store the sum of s->window + best_len in esi locally, and in esi.\r
+\r
+       lea  rsi,[r10+r11]\r
+\r
+//;;; register ush scan_start = *(ushf*)scan;\r
+//;;; register ush scan_end   = *(ushf*)(scan+best_len-1);\r
+//;;; Posf *prev = s->prev;\r
+\r
+        movzx r12d,word ptr [r9]\r
+        movzx ebx, word ptr [r9 + r11 - 1]\r
+\r
+        mov rdi, prev_ad\r
+\r
+//;;; Jump into the main loop.\r
+\r
+        mov edx, [chainlenwmask]\r
+\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+        jz  LookupLoopIsZero\r
+                               \r
+                                               \r
+                                               \r
+LookupLoop1:\r
+        and r8d, edx\r
+\r
+        movzx   r8d, word ptr [rdi + r8*2]\r
+        cmp r8d, ebp\r
+        jbe LeaveNow\r
+               \r
+               \r
+               \r
+        sub edx, 0x00010000\r
+               BEFORE_JMP\r
+        js  LeaveNow\r
+               AFTER_JMP\r
+\r
+LoopEntry1:\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+               BEFORE_JMP\r
+        jz  LookupLoopIsZero\r
+               AFTER_JMP\r
+\r
+LookupLoop2:\r
+        and r8d, edx\r
+\r
+        movzx   r8d, word ptr [rdi + r8*2]\r
+        cmp r8d, ebp\r
+               BEFORE_JMP\r
+        jbe LeaveNow\r
+               AFTER_JMP\r
+        sub edx, 0x00010000\r
+               BEFORE_JMP\r
+        js  LeaveNow\r
+               AFTER_JMP\r
+\r
+LoopEntry2:\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+               BEFORE_JMP\r
+        jz  LookupLoopIsZero\r
+               AFTER_JMP\r
+\r
+LookupLoop4:\r
+        and r8d, edx\r
+\r
+        movzx   r8d, word ptr [rdi + r8*2]\r
+        cmp r8d, ebp\r
+               BEFORE_JMP\r
+        jbe LeaveNow\r
+               AFTER_JMP\r
+        sub edx, 0x00010000\r
+               BEFORE_JMP\r
+        js  LeaveNow\r
+               AFTER_JMP\r
+\r
+LoopEntry4:\r
+\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+               BEFORE_JMP\r
+        jnz LookupLoop1\r
+        jmp LookupLoopIsZero\r
+               AFTER_JMP\r
+/*\r
+;;; do {\r
+;;;     match = s->window + cur_match;\r
+;;;     if (*(ushf*)(match+best_len-1) != scan_end ||\r
+;;;         *(ushf*)match != scan_start) continue;\r
+;;;     [...]\r
+;;; } while ((cur_match = prev[cur_match & wmask]) > limit\r
+;;;          && --chain_length != 0);\r
+;;;\r
+;;; Here is the inner loop of the function. The function will spend the\r
+;;; majority of its time in this loop, and majority of that time will\r
+;;; be spent in the first ten instructions.\r
+;;;\r
+;;; Within this loop:\r
+;;; ebx = scanend\r
+;;; r8d = curmatch\r
+;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask)\r
+;;; esi = windowbestlen - i.e., (window + bestlen)\r
+;;; edi = prev\r
+;;; ebp = limit\r
+*/\r
+.balign 16\r
+LookupLoop:\r
+        and r8d, edx\r
+\r
+        movzx   r8d, word ptr [rdi + r8*2]\r
+        cmp r8d, ebp\r
+               BEFORE_JMP\r
+        jbe LeaveNow\r
+               AFTER_JMP\r
+        sub edx, 0x00010000\r
+               BEFORE_JMP\r
+        js  LeaveNow\r
+               AFTER_JMP\r
+\r
+LoopEntry:\r
+\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+               BEFORE_JMP\r
+        jnz LookupLoop1\r
+               AFTER_JMP\r
+LookupLoopIsZero:\r
+        cmp     r12w, word ptr [r10 + r8]\r
+               BEFORE_JMP\r
+        jnz LookupLoop1\r
+               AFTER_JMP\r
+\r
+\r
+//;;; Store the current value of chainlen.\r
+        mov [chainlenwmask], edx\r
+/*\r
+;;; Point edi to the string under scrutiny, and esi to the string we\r
+;;; are hoping to match it up with. In actuality, esi and edi are\r
+;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is\r
+;;; initialized to -(MAX_MATCH_8 - scanalign).\r
+*/\r
+        lea rsi,[r8+r10]\r
+        mov rdx, 0xfffffffffffffef8 //; -(MAX_MATCH_8)\r
+        lea rsi, [rsi + r13 + 0x0108] //;MAX_MATCH_8]\r
+        lea rdi, [r9 + r13 + 0x0108] //;MAX_MATCH_8]\r
+\r
+        prefetcht1 [rsi+rdx]\r
+        prefetcht1 [rdi+rdx]\r
+\r
+/*\r
+;;; Test the strings for equality, 8 bytes at a time. At the end,\r
+;;; adjust rdx so that it is offset to the exact byte that mismatched.\r
+;;;\r
+;;; We already know at this point that the first three bytes of the\r
+;;; strings match each other, and they can be safely passed over before\r
+;;; starting the compare loop. So what this code does is skip over 0-3\r
+;;; bytes, as much as necessary in order to dword-align the edi\r
+;;; pointer. (rsi will still be misaligned three times out of four.)\r
+;;;\r
+;;; It should be confessed that this loop usually does not represent\r
+;;; much of the total running time. Replacing it with a more\r
+;;; straightforward "rep cmpsb" would not drastically degrade\r
+;;; performance.\r
+*/\r
+\r
+LoopCmps:\r
+        mov rax, [rsi + rdx]\r
+        xor rax, [rdi + rdx]\r
+        jnz LeaveLoopCmps\r
+\r
+        mov rax, [rsi + rdx + 8]\r
+        xor rax, [rdi + rdx + 8]\r
+        jnz LeaveLoopCmps8\r
+\r
+\r
+        mov rax, [rsi + rdx + 8+8]\r
+        xor rax, [rdi + rdx + 8+8]\r
+        jnz LeaveLoopCmps16\r
+\r
+        add rdx,8+8+8\r
+\r
+               BEFORE_JMP\r
+        jnz  LoopCmps\r
+        jmp  LenMaximum\r
+               AFTER_JMP\r
+               \r
+LeaveLoopCmps16: add rdx,8\r
+LeaveLoopCmps8: add rdx,8\r
+LeaveLoopCmps:\r
+\r
+        test    eax, 0x0000FFFF\r
+        jnz LenLower\r
+\r
+        test eax,0xffffffff\r
+\r
+        jnz LenLower32\r
+\r
+        add rdx,4\r
+        shr rax,32\r
+        or ax,ax\r
+               BEFORE_JMP\r
+        jnz LenLower\r
+               AFTER_JMP\r
+\r
+LenLower32:\r
+        shr eax,16\r
+        add rdx,2\r
+               \r
+LenLower:              \r
+        sub al, 1\r
+        adc rdx, 0\r
+//;;; Calculate the length of the match. If it is longer than MAX_MATCH,\r
+//;;; then automatically accept it as the best possible match and leave.\r
+\r
+        lea rax, [rdi + rdx]\r
+        sub rax, r9\r
+        cmp eax, MAX_MATCH\r
+               BEFORE_JMP\r
+        jge LenMaximum\r
+               AFTER_JMP\r
+/*\r
+;;; If the length of the match is not longer than the best match we\r
+;;; have so far, then forget it and return to the lookup loop.\r
+;///////////////////////////////////\r
+*/\r
+        cmp eax, r11d\r
+        jg  LongerMatch\r
+\r
+        lea rsi,[r10+r11]\r
+\r
+        mov rdi, prev_ad\r
+        mov edx, [chainlenwmask]\r
+               BEFORE_JMP\r
+        jmp LookupLoop\r
+               AFTER_JMP\r
+/*\r
+;;;         s->match_start = cur_match;\r
+;;;         best_len = len;\r
+;;;         if (len >= nice_match) break;\r
+;;;         scan_end = *(ushf*)(scan+best_len-1);\r
+*/\r
+LongerMatch:\r
+        mov r11d, eax\r
+        mov match_start, r8d\r
+        cmp eax, [nicematch]\r
+               BEFORE_JMP\r
+        jge LeaveNow\r
+               AFTER_JMP\r
+\r
+        lea rsi,[r10+rax]\r
+\r
+        movzx   ebx, word ptr [r9 + rax - 1]\r
+        mov rdi, prev_ad\r
+        mov edx, [chainlenwmask]\r
+               BEFORE_JMP\r
+        jmp LookupLoop\r
+               AFTER_JMP\r
+\r
+//;;; Accept the current string, with the maximum possible length.\r
+\r
+LenMaximum:\r
+        mov r11d,MAX_MATCH\r
+        mov match_start, r8d\r
+\r
+//;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len;\r
+//;;; return s->lookahead;\r
+\r
+LeaveNow:\r
+        mov eax, Lookahead\r
+        cmp r11d, eax\r
+        cmovng eax, r11d\r
+\r
+\r
+\r
+//;;; Restore the stack and return from whence we came.\r
+\r
+\r
+//        mov rsi,[save_rsi]\r
+//        mov rdi,[save_rdi]\r
+        mov rbx,[save_rbx]\r
+        mov rbp,[save_rbp]\r
+        mov r12,[save_r12]\r
+        mov r13,[save_r13]\r
+        mov r14,[save_r14]\r
+        mov r15,[save_r15]\r
+\r
+\r
+        ret 0\r
+//; please don't remove this string !\r
+//; Your can freely use gvmat64 in any free or commercial app\r
+//; but it is far better don't remove the string in the binary!\r
+ //   db     0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0\r
+\r
+\r
+match_init:\r
+  ret 0\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/README b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/README
new file mode 100644 (file)
index 0000000..e75ed13
--- /dev/null
@@ -0,0 +1 @@
+See infback9.h for what this is and how to use it.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/infback9.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/infback9.c
new file mode 100644 (file)
index 0000000..7bbe90c
--- /dev/null
@@ -0,0 +1,617 @@
+/* infback9.c -- inflate deflate64 data using a call-back interface
+ * Copyright (C) 1995-2008 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "infback9.h"
+#include "inftree9.h"
+#include "inflate9.h"
+
+#define WSIZE 65536UL
+
+/*
+   strm provides memory allocation functions in zalloc and zfree, or
+   Z_NULL to use the library memory allocation functions.
+
+   window is a user-supplied window and output buffer that is 64K bytes.
+ */
+int ZEXPORT inflateBack9Init_(strm, window, version, stream_size)
+z_stream FAR *strm;
+unsigned char FAR *window;
+const char *version;
+int stream_size;
+{
+    struct inflate_state FAR *state;
+
+    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+        stream_size != (int)(sizeof(z_stream)))
+        return Z_VERSION_ERROR;
+    if (strm == Z_NULL || window == Z_NULL)
+        return Z_STREAM_ERROR;
+    strm->msg = Z_NULL;                 /* in case we return an error */
+    if (strm->zalloc == (alloc_func)0) {
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+    }
+    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
+    state = (struct inflate_state FAR *)ZALLOC(strm, 1,
+                                               sizeof(struct inflate_state));
+    if (state == Z_NULL) return Z_MEM_ERROR;
+    Tracev((stderr, "inflate: allocated\n"));
+    strm->state = (voidpf)state;
+    state->window = window;
+    return Z_OK;
+}
+
+/*
+   Build and output length and distance decoding tables for fixed code
+   decoding.
+ */
+#ifdef MAKEFIXED
+#include <stdio.h>
+
+void makefixed9(void)
+{
+    unsigned sym, bits, low, size;
+    code *next, *lenfix, *distfix;
+    struct inflate_state state;
+    code fixed[544];
+
+    /* literal/length table */
+    sym = 0;
+    while (sym < 144) state.lens[sym++] = 8;
+    while (sym < 256) state.lens[sym++] = 9;
+    while (sym < 280) state.lens[sym++] = 7;
+    while (sym < 288) state.lens[sym++] = 8;
+    next = fixed;
+    lenfix = next;
+    bits = 9;
+    inflate_table9(LENS, state.lens, 288, &(next), &(bits), state.work);
+
+    /* distance table */
+    sym = 0;
+    while (sym < 32) state.lens[sym++] = 5;
+    distfix = next;
+    bits = 5;
+    inflate_table9(DISTS, state.lens, 32, &(next), &(bits), state.work);
+
+    /* write tables */
+    puts("    /* inffix9.h -- table for decoding deflate64 fixed codes");
+    puts("     * Generated automatically by makefixed9().");
+    puts("     */");
+    puts("");
+    puts("    /* WARNING: this file should *not* be used by applications.");
+    puts("       It is part of the implementation of this library and is");
+    puts("       subject to change. Applications should only use zlib.h.");
+    puts("     */");
+    puts("");
+    size = 1U << 9;
+    printf("    static const code lenfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 6) == 0) printf("\n        ");
+        printf("{%u,%u,%d}", lenfix[low].op, lenfix[low].bits,
+               lenfix[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n    };");
+    size = 1U << 5;
+    printf("\n    static const code distfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 5) == 0) printf("\n        ");
+        printf("{%u,%u,%d}", distfix[low].op, distfix[low].bits,
+               distfix[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n    };");
+}
+#endif /* MAKEFIXED */
+
+/* Macros for inflateBack(): */
+
+/* Clear the input bit accumulator */
+#define INITBITS() \
+    do { \
+        hold = 0; \
+        bits = 0; \
+    } while (0)
+
+/* Assure that some input is available.  If input is requested, but denied,
+   then return a Z_BUF_ERROR from inflateBack(). */
+#define PULL() \
+    do { \
+        if (have == 0) { \
+            have = in(in_desc, &next); \
+            if (have == 0) { \
+                next = Z_NULL; \
+                ret = Z_BUF_ERROR; \
+                goto inf_leave; \
+            } \
+        } \
+    } while (0)
+
+/* Get a byte of input into the bit accumulator, or return from inflateBack()
+   with an error if there is no input available. */
+#define PULLBYTE() \
+    do { \
+        PULL(); \
+        have--; \
+        hold += (unsigned long)(*next++) << bits; \
+        bits += 8; \
+    } while (0)
+
+/* Assure that there are at least n bits in the bit accumulator.  If there is
+   not enough available input to do that, then return from inflateBack() with
+   an error. */
+#define NEEDBITS(n) \
+    do { \
+        while (bits < (unsigned)(n)) \
+            PULLBYTE(); \
+    } while (0)
+
+/* Return the low n bits of the bit accumulator (n <= 16) */
+#define BITS(n) \
+    ((unsigned)hold & ((1U << (n)) - 1))
+
+/* Remove n bits from the bit accumulator */
+#define DROPBITS(n) \
+    do { \
+        hold >>= (n); \
+        bits -= (unsigned)(n); \
+    } while (0)
+
+/* Remove zero to seven bits as needed to go to a byte boundary */
+#define BYTEBITS() \
+    do { \
+        hold >>= bits & 7; \
+        bits -= bits & 7; \
+    } while (0)
+
+/* Assure that some output space is available, by writing out the window
+   if it's full.  If the write fails, return from inflateBack() with a
+   Z_BUF_ERROR. */
+#define ROOM() \
+    do { \
+        if (left == 0) { \
+            put = window; \
+            left = WSIZE; \
+            wrap = 1; \
+            if (out(out_desc, put, (unsigned)left)) { \
+                ret = Z_BUF_ERROR; \
+                goto inf_leave; \
+            } \
+        } \
+    } while (0)
+
+/*
+   strm provides the memory allocation functions and window buffer on input,
+   and provides information on the unused input on return.  For Z_DATA_ERROR
+   returns, strm will also provide an error message.
+
+   in() and out() are the call-back input and output functions.  When
+   inflateBack() needs more input, it calls in().  When inflateBack() has
+   filled the window with output, or when it completes with data in the
+   window, it calls out() to write out the data.  The application must not
+   change the provided input until in() is called again or inflateBack()
+   returns.  The application must not change the window/output buffer until
+   inflateBack() returns.
+
+   in() and out() are called with a descriptor parameter provided in the
+   inflateBack() call.  This parameter can be a structure that provides the
+   information required to do the read or write, as well as accumulated
+   information on the input and output such as totals and check values.
+
+   in() should return zero on failure.  out() should return non-zero on
+   failure.  If either in() or out() fails, than inflateBack() returns a
+   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
+   was in() or out() that caused in the error.  Otherwise,  inflateBack()
+   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
+   error, or Z_MEM_ERROR if it could not allocate memory for the state.
+   inflateBack() can also return Z_STREAM_ERROR if the input parameters
+   are not correct, i.e. strm is Z_NULL or the state was not initialized.
+ */
+int ZEXPORT inflateBack9(strm, in, in_desc, out, out_desc)
+z_stream FAR *strm;
+in_func in;
+void FAR *in_desc;
+out_func out;
+void FAR *out_desc;
+{
+    struct inflate_state FAR *state;
+    unsigned char FAR *next;    /* next input */
+    unsigned char FAR *put;     /* next output */
+    unsigned have;              /* available input */
+    unsigned long left;         /* available output */
+    inflate_mode mode;          /* current inflate mode */
+    int lastblock;              /* true if processing last block */
+    int wrap;                   /* true if the window has wrapped */
+    unsigned long write;        /* window write index */
+    unsigned char FAR *window;  /* allocated sliding window, if needed */
+    unsigned long hold;         /* bit buffer */
+    unsigned bits;              /* bits in bit buffer */
+    unsigned extra;             /* extra bits needed */
+    unsigned long length;       /* literal or length of data to copy */
+    unsigned long offset;       /* distance back to copy string from */
+    unsigned long copy;         /* number of stored or match bytes to copy */
+    unsigned char FAR *from;    /* where to copy match bytes from */
+    code const FAR *lencode;    /* starting table for length/literal codes */
+    code const FAR *distcode;   /* starting table for distance codes */
+    unsigned lenbits;           /* index bits for lencode */
+    unsigned distbits;          /* index bits for distcode */
+    code here;                  /* current decoding table entry */
+    code last;                  /* parent table entry */
+    unsigned len;               /* length to copy for repeats, bits to drop */
+    int ret;                    /* return code */
+    static const unsigned short order[19] = /* permutation of code lengths */
+        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+#include "inffix9.h"
+
+    /* Check that the strm exists and that the state was initialized */
+    if (strm == Z_NULL || strm->state == Z_NULL)
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* Reset the state */
+    strm->msg = Z_NULL;
+    mode = TYPE;
+    lastblock = 0;
+    write = 0;
+    wrap = 0;
+    window = state->window;
+    next = strm->next_in;
+    have = next != Z_NULL ? strm->avail_in : 0;
+    hold = 0;
+    bits = 0;
+    put = window;
+    left = WSIZE;
+    lencode = Z_NULL;
+    distcode = Z_NULL;
+
+    /* Inflate until end of block marked as last */
+    for (;;)
+        switch (mode) {
+        case TYPE:
+            /* determine and dispatch block type */
+            if (lastblock) {
+                BYTEBITS();
+                mode = DONE;
+                break;
+            }
+            NEEDBITS(3);
+            lastblock = BITS(1);
+            DROPBITS(1);
+            switch (BITS(2)) {
+            case 0:                             /* stored block */
+                Tracev((stderr, "inflate:     stored block%s\n",
+                        lastblock ? " (last)" : ""));
+                mode = STORED;
+                break;
+            case 1:                             /* fixed block */
+                lencode = lenfix;
+                lenbits = 9;
+                distcode = distfix;
+                distbits = 5;
+                Tracev((stderr, "inflate:     fixed codes block%s\n",
+                        lastblock ? " (last)" : ""));
+                mode = LEN;                     /* decode codes */
+                break;
+            case 2:                             /* dynamic block */
+                Tracev((stderr, "inflate:     dynamic codes block%s\n",
+                        lastblock ? " (last)" : ""));
+                mode = TABLE;
+                break;
+            case 3:
+                strm->msg = (char *)"invalid block type";
+                mode = BAD;
+            }
+            DROPBITS(2);
+            break;
+
+        case STORED:
+            /* get and verify stored block length */
+            BYTEBITS();                         /* go to byte boundary */
+            NEEDBITS(32);
+            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
+                strm->msg = (char *)"invalid stored block lengths";
+                mode = BAD;
+                break;
+            }
+            length = (unsigned)hold & 0xffff;
+            Tracev((stderr, "inflate:       stored length %lu\n",
+                    length));
+            INITBITS();
+
+            /* copy stored block from input to output */
+            while (length != 0) {
+                copy = length;
+                PULL();
+                ROOM();
+                if (copy > have) copy = have;
+                if (copy > left) copy = left;
+                zmemcpy(put, next, copy);
+                have -= copy;
+                next += copy;
+                left -= copy;
+                put += copy;
+                length -= copy;
+            }
+            Tracev((stderr, "inflate:       stored end\n"));
+            mode = TYPE;
+            break;
+
+        case TABLE:
+            /* get dynamic table entries descriptor */
+            NEEDBITS(14);
+            state->nlen = BITS(5) + 257;
+            DROPBITS(5);
+            state->ndist = BITS(5) + 1;
+            DROPBITS(5);
+            state->ncode = BITS(4) + 4;
+            DROPBITS(4);
+            if (state->nlen > 286) {
+                strm->msg = (char *)"too many length symbols";
+                mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       table sizes ok\n"));
+
+            /* get code length code lengths (not a typo) */
+            state->have = 0;
+            while (state->have < state->ncode) {
+                NEEDBITS(3);
+                state->lens[order[state->have++]] = (unsigned short)BITS(3);
+                DROPBITS(3);
+            }
+            while (state->have < 19)
+                state->lens[order[state->have++]] = 0;
+            state->next = state->codes;
+            lencode = (code const FAR *)(state->next);
+            lenbits = 7;
+            ret = inflate_table9(CODES, state->lens, 19, &(state->next),
+                                &(lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid code lengths set";
+                mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       code lengths ok\n"));
+
+            /* get length and distance code code lengths */
+            state->have = 0;
+            while (state->have < state->nlen + state->ndist) {
+                for (;;) {
+                    here = lencode[BITS(lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                if (here.val < 16) {
+                    NEEDBITS(here.bits);
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
+                }
+                else {
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
+                        if (state->have == 0) {
+                            strm->msg = (char *)"invalid bit length repeat";
+                            mode = BAD;
+                            break;
+                        }
+                        len = (unsigned)(state->lens[state->have - 1]);
+                        copy = 3 + BITS(2);
+                        DROPBITS(2);
+                    }
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 3 + BITS(3);
+                        DROPBITS(3);
+                    }
+                    else {
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 11 + BITS(7);
+                        DROPBITS(7);
+                    }
+                    if (state->have + copy > state->nlen + state->ndist) {
+                        strm->msg = (char *)"invalid bit length repeat";
+                        mode = BAD;
+                        break;
+                    }
+                    while (copy--)
+                        state->lens[state->have++] = (unsigned short)len;
+                }
+            }
+
+            /* handle error breaks in while */
+            if (mode == BAD) break;
+
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftree9.h
+               concerning the ENOUGH constants, which depend on those values */
+            state->next = state->codes;
+            lencode = (code const FAR *)(state->next);
+            lenbits = 9;
+            ret = inflate_table9(LENS, state->lens, state->nlen,
+                            &(state->next), &(lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid literal/lengths set";
+                mode = BAD;
+                break;
+            }
+            distcode = (code const FAR *)(state->next);
+            distbits = 6;
+            ret = inflate_table9(DISTS, state->lens + state->nlen,
+                            state->ndist, &(state->next), &(distbits),
+                            state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid distances set";
+                mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       codes ok\n"));
+            mode = LEN;
+
+        case LEN:
+            /* get a literal, length, or end-of-block code */
+            for (;;) {
+                here = lencode[BITS(lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = lencode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(here.bits);
+            length = (unsigned)here.val;
+
+            /* process literal */
+            if (here.op == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                        "inflate:         literal '%c'\n" :
+                        "inflate:         literal 0x%02x\n", here.val));
+                ROOM();
+                *put++ = (unsigned char)(length);
+                left--;
+                mode = LEN;
+                break;
+            }
+
+            /* process end of block */
+            if (here.op & 32) {
+                Tracevv((stderr, "inflate:         end of block\n"));
+                mode = TYPE;
+                break;
+            }
+
+            /* invalid code */
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid literal/length code";
+                mode = BAD;
+                break;
+            }
+
+            /* length code -- get extra bits, if any */
+            extra = (unsigned)(here.op) & 31;
+            if (extra != 0) {
+                NEEDBITS(extra);
+                length += BITS(extra);
+                DROPBITS(extra);
+            }
+            Tracevv((stderr, "inflate:         length %lu\n", length));
+
+            /* get distance code */
+            for (;;) {
+                here = distcode[BITS(distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if ((here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = distcode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(here.bits);
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid distance code";
+                mode = BAD;
+                break;
+            }
+            offset = (unsigned)here.val;
+
+            /* get distance extra bits, if any */
+            extra = (unsigned)(here.op) & 15;
+            if (extra != 0) {
+                NEEDBITS(extra);
+                offset += BITS(extra);
+                DROPBITS(extra);
+            }
+            if (offset > WSIZE - (wrap ? 0: left)) {
+                strm->msg = (char *)"invalid distance too far back";
+                mode = BAD;
+                break;
+            }
+            Tracevv((stderr, "inflate:         distance %lu\n", offset));
+
+            /* copy match from window to output */
+            do {
+                ROOM();
+                copy = WSIZE - offset;
+                if (copy < left) {
+                    from = put + copy;
+                    copy = left - copy;
+                }
+                else {
+                    from = put - offset;
+                    copy = left;
+                }
+                if (copy > length) copy = length;
+                length -= copy;
+                left -= copy;
+                do {
+                    *put++ = *from++;
+                } while (--copy);
+            } while (length != 0);
+            break;
+
+        case DONE:
+            /* inflate stream terminated properly -- write leftover output */
+            ret = Z_STREAM_END;
+            if (left < WSIZE) {
+                if (out(out_desc, window, (unsigned)(WSIZE - left)))
+                    ret = Z_BUF_ERROR;
+            }
+            goto inf_leave;
+
+        case BAD:
+            ret = Z_DATA_ERROR;
+            goto inf_leave;
+
+        default:                /* can't happen, but makes compilers happy */
+            ret = Z_STREAM_ERROR;
+            goto inf_leave;
+        }
+
+    /* Return unused input */
+  inf_leave:
+    strm->next_in = next;
+    strm->avail_in = have;
+    return ret;
+}
+
+int ZEXPORT inflateBack9End(strm)
+z_stream FAR *strm;
+{
+    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
+        return Z_STREAM_ERROR;
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+    Tracev((stderr, "inflate: end\n"));
+    return Z_OK;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/infback9.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/infback9.h
new file mode 100644 (file)
index 0000000..1073c0a
--- /dev/null
@@ -0,0 +1,37 @@
+/* infback9.h -- header for using inflateBack9 functions
+ * Copyright (C) 2003 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ * This header file and associated patches provide a decoder for PKWare's
+ * undocumented deflate64 compression method (method 9).  Use with infback9.c,
+ * inftree9.h, inftree9.c, and inffix9.h.  These patches are not supported.
+ * This should be compiled with zlib, since it uses zutil.h and zutil.o.
+ * This code has not yet been tested on 16-bit architectures.  See the
+ * comments in zlib.h for inflateBack() usage.  These functions are used
+ * identically, except that there is no windowBits parameter, and a 64K
+ * window must be provided.  Also if int's are 16 bits, then a zero for
+ * the third parameter of the "out" function actually means 65536UL.
+ * zlib.h must be included before this header file.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ZEXTERN int ZEXPORT inflateBack9 OF((z_stream FAR *strm,
+                                    in_func in, void FAR *in_desc,
+                                    out_func out, void FAR *out_desc));
+ZEXTERN int ZEXPORT inflateBack9End OF((z_stream FAR *strm));
+ZEXTERN int ZEXPORT inflateBack9Init_ OF((z_stream FAR *strm,
+                                         unsigned char FAR *window,
+                                         const char *version,
+                                         int stream_size));
+#define inflateBack9Init(strm, window) \
+        inflateBack9Init_((strm), (window), \
+        ZLIB_VERSION, sizeof(z_stream))
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inffix9.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inffix9.h
new file mode 100644 (file)
index 0000000..ee5671d
--- /dev/null
@@ -0,0 +1,107 @@
+    /* inffix9.h -- table for decoding deflate64 fixed codes
+     * Generated automatically by makefixed9().
+     */
+
+    /* WARNING: this file should *not* be used by applications.
+       It is part of the implementation of this library and is
+       subject to change. Applications should only use zlib.h.
+     */
+
+    static const code lenfix[512] = {
+        {96,7,0},{0,8,80},{0,8,16},{132,8,115},{130,7,31},{0,8,112},
+        {0,8,48},{0,9,192},{128,7,10},{0,8,96},{0,8,32},{0,9,160},
+        {0,8,0},{0,8,128},{0,8,64},{0,9,224},{128,7,6},{0,8,88},
+        {0,8,24},{0,9,144},{131,7,59},{0,8,120},{0,8,56},{0,9,208},
+        {129,7,17},{0,8,104},{0,8,40},{0,9,176},{0,8,8},{0,8,136},
+        {0,8,72},{0,9,240},{128,7,4},{0,8,84},{0,8,20},{133,8,227},
+        {131,7,43},{0,8,116},{0,8,52},{0,9,200},{129,7,13},{0,8,100},
+        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},
+        {128,7,8},{0,8,92},{0,8,28},{0,9,152},{132,7,83},{0,8,124},
+        {0,8,60},{0,9,216},{130,7,23},{0,8,108},{0,8,44},{0,9,184},
+        {0,8,12},{0,8,140},{0,8,76},{0,9,248},{128,7,3},{0,8,82},
+        {0,8,18},{133,8,163},{131,7,35},{0,8,114},{0,8,50},{0,9,196},
+        {129,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},{0,8,130},
+        {0,8,66},{0,9,228},{128,7,7},{0,8,90},{0,8,26},{0,9,148},
+        {132,7,67},{0,8,122},{0,8,58},{0,9,212},{130,7,19},{0,8,106},
+        {0,8,42},{0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},
+        {128,7,5},{0,8,86},{0,8,22},{65,8,0},{131,7,51},{0,8,118},
+        {0,8,54},{0,9,204},{129,7,15},{0,8,102},{0,8,38},{0,9,172},
+        {0,8,6},{0,8,134},{0,8,70},{0,9,236},{128,7,9},{0,8,94},
+        {0,8,30},{0,9,156},{132,7,99},{0,8,126},{0,8,62},{0,9,220},
+        {130,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
+        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{133,8,131},
+        {130,7,31},{0,8,113},{0,8,49},{0,9,194},{128,7,10},{0,8,97},
+        {0,8,33},{0,9,162},{0,8,1},{0,8,129},{0,8,65},{0,9,226},
+        {128,7,6},{0,8,89},{0,8,25},{0,9,146},{131,7,59},{0,8,121},
+        {0,8,57},{0,9,210},{129,7,17},{0,8,105},{0,8,41},{0,9,178},
+        {0,8,9},{0,8,137},{0,8,73},{0,9,242},{128,7,4},{0,8,85},
+        {0,8,21},{144,8,3},{131,7,43},{0,8,117},{0,8,53},{0,9,202},
+        {129,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},
+        {0,8,69},{0,9,234},{128,7,8},{0,8,93},{0,8,29},{0,9,154},
+        {132,7,83},{0,8,125},{0,8,61},{0,9,218},{130,7,23},{0,8,109},
+        {0,8,45},{0,9,186},{0,8,13},{0,8,141},{0,8,77},{0,9,250},
+        {128,7,3},{0,8,83},{0,8,19},{133,8,195},{131,7,35},{0,8,115},
+        {0,8,51},{0,9,198},{129,7,11},{0,8,99},{0,8,35},{0,9,166},
+        {0,8,3},{0,8,131},{0,8,67},{0,9,230},{128,7,7},{0,8,91},
+        {0,8,27},{0,9,150},{132,7,67},{0,8,123},{0,8,59},{0,9,214},
+        {130,7,19},{0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},
+        {0,8,75},{0,9,246},{128,7,5},{0,8,87},{0,8,23},{77,8,0},
+        {131,7,51},{0,8,119},{0,8,55},{0,9,206},{129,7,15},{0,8,103},
+        {0,8,39},{0,9,174},{0,8,7},{0,8,135},{0,8,71},{0,9,238},
+        {128,7,9},{0,8,95},{0,8,31},{0,9,158},{132,7,99},{0,8,127},
+        {0,8,63},{0,9,222},{130,7,27},{0,8,111},{0,8,47},{0,9,190},
+        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},
+        {0,8,16},{132,8,115},{130,7,31},{0,8,112},{0,8,48},{0,9,193},
+        {128,7,10},{0,8,96},{0,8,32},{0,9,161},{0,8,0},{0,8,128},
+        {0,8,64},{0,9,225},{128,7,6},{0,8,88},{0,8,24},{0,9,145},
+        {131,7,59},{0,8,120},{0,8,56},{0,9,209},{129,7,17},{0,8,104},
+        {0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},{0,9,241},
+        {128,7,4},{0,8,84},{0,8,20},{133,8,227},{131,7,43},{0,8,116},
+        {0,8,52},{0,9,201},{129,7,13},{0,8,100},{0,8,36},{0,9,169},
+        {0,8,4},{0,8,132},{0,8,68},{0,9,233},{128,7,8},{0,8,92},
+        {0,8,28},{0,9,153},{132,7,83},{0,8,124},{0,8,60},{0,9,217},
+        {130,7,23},{0,8,108},{0,8,44},{0,9,185},{0,8,12},{0,8,140},
+        {0,8,76},{0,9,249},{128,7,3},{0,8,82},{0,8,18},{133,8,163},
+        {131,7,35},{0,8,114},{0,8,50},{0,9,197},{129,7,11},{0,8,98},
+        {0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
+        {128,7,7},{0,8,90},{0,8,26},{0,9,149},{132,7,67},{0,8,122},
+        {0,8,58},{0,9,213},{130,7,19},{0,8,106},{0,8,42},{0,9,181},
+        {0,8,10},{0,8,138},{0,8,74},{0,9,245},{128,7,5},{0,8,86},
+        {0,8,22},{65,8,0},{131,7,51},{0,8,118},{0,8,54},{0,9,205},
+        {129,7,15},{0,8,102},{0,8,38},{0,9,173},{0,8,6},{0,8,134},
+        {0,8,70},{0,9,237},{128,7,9},{0,8,94},{0,8,30},{0,9,157},
+        {132,7,99},{0,8,126},{0,8,62},{0,9,221},{130,7,27},{0,8,110},
+        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},
+        {96,7,0},{0,8,81},{0,8,17},{133,8,131},{130,7,31},{0,8,113},
+        {0,8,49},{0,9,195},{128,7,10},{0,8,97},{0,8,33},{0,9,163},
+        {0,8,1},{0,8,129},{0,8,65},{0,9,227},{128,7,6},{0,8,89},
+        {0,8,25},{0,9,147},{131,7,59},{0,8,121},{0,8,57},{0,9,211},
+        {129,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},{0,8,137},
+        {0,8,73},{0,9,243},{128,7,4},{0,8,85},{0,8,21},{144,8,3},
+        {131,7,43},{0,8,117},{0,8,53},{0,9,203},{129,7,13},{0,8,101},
+        {0,8,37},{0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},
+        {128,7,8},{0,8,93},{0,8,29},{0,9,155},{132,7,83},{0,8,125},
+        {0,8,61},{0,9,219},{130,7,23},{0,8,109},{0,8,45},{0,9,187},
+        {0,8,13},{0,8,141},{0,8,77},{0,9,251},{128,7,3},{0,8,83},
+        {0,8,19},{133,8,195},{131,7,35},{0,8,115},{0,8,51},{0,9,199},
+        {129,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
+        {0,8,67},{0,9,231},{128,7,7},{0,8,91},{0,8,27},{0,9,151},
+        {132,7,67},{0,8,123},{0,8,59},{0,9,215},{130,7,19},{0,8,107},
+        {0,8,43},{0,9,183},{0,8,11},{0,8,139},{0,8,75},{0,9,247},
+        {128,7,5},{0,8,87},{0,8,23},{77,8,0},{131,7,51},{0,8,119},
+        {0,8,55},{0,9,207},{129,7,15},{0,8,103},{0,8,39},{0,9,175},
+        {0,8,7},{0,8,135},{0,8,71},{0,9,239},{128,7,9},{0,8,95},
+        {0,8,31},{0,9,159},{132,7,99},{0,8,127},{0,8,63},{0,9,223},
+        {130,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},
+        {0,8,79},{0,9,255}
+    };
+
+    static const code distfix[32] = {
+        {128,5,1},{135,5,257},{131,5,17},{139,5,4097},{129,5,5},
+        {137,5,1025},{133,5,65},{141,5,16385},{128,5,3},{136,5,513},
+        {132,5,33},{140,5,8193},{130,5,9},{138,5,2049},{134,5,129},
+        {142,5,32769},{128,5,2},{135,5,385},{131,5,25},{139,5,6145},
+        {129,5,7},{137,5,1537},{133,5,97},{141,5,24577},{128,5,4},
+        {136,5,769},{132,5,49},{140,5,12289},{130,5,13},{138,5,3073},
+        {134,5,193},{142,5,49153}
+    };
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inflate9.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inflate9.h
new file mode 100644 (file)
index 0000000..ee9a793
--- /dev/null
@@ -0,0 +1,47 @@
+/* inflate9.h -- internal inflate state definition
+ * Copyright (C) 1995-2003 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* Possible inflate modes between inflate() calls */
+typedef enum {
+        TYPE,       /* i: waiting for type bits, including last-flag bit */
+        STORED,     /* i: waiting for stored size (length and complement) */
+        TABLE,      /* i: waiting for dynamic block table lengths */
+            LEN,        /* i: waiting for length/lit code */
+    DONE,       /* finished check, done -- remain here until reset */
+    BAD         /* got a data error -- remain here until reset */
+} inflate_mode;
+
+/*
+    State transitions between above modes -
+
+    (most modes can go to the BAD mode -- not shown for clarity)
+
+    Read deflate blocks:
+            TYPE -> STORED or TABLE or LEN or DONE
+            STORED -> TYPE
+            TABLE -> LENLENS -> CODELENS -> LEN
+    Read deflate codes:
+                LEN -> LEN or TYPE
+ */
+
+/* state maintained between inflate() calls.  Approximately 7K bytes. */
+struct inflate_state {
+        /* sliding window */
+    unsigned char FAR *window;  /* allocated sliding window, if needed */
+        /* dynamic table building */
+    unsigned ncode;             /* number of code length code lengths */
+    unsigned nlen;              /* number of length code lengths */
+    unsigned ndist;             /* number of distance code lengths */
+    unsigned have;              /* number of code lengths in lens[] */
+    code FAR *next;             /* next available space in codes[] */
+    unsigned short lens[320];   /* temporary storage for code lengths */
+    unsigned short work[288];   /* work area for code table building */
+    code codes[ENOUGH];         /* space for code tables */
+};
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inftree9.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inftree9.c
new file mode 100644 (file)
index 0000000..4ce2a1f
--- /dev/null
@@ -0,0 +1,324 @@
+/* inftree9.c -- generate Huffman trees for efficient decoding
+ * Copyright (C) 1995-2012 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "inftree9.h"
+
+#define MAXBITS 15
+
+const char inflate9_copyright[] =
+   " inflate9 1.2.6 Copyright 1995-2012 Mark Adler ";
+/*
+  If you use the zlib library in a product, an acknowledgment is welcome
+  in the documentation of your product. If for some reason you cannot
+  include such an acknowledgment, I would appreciate that you keep this
+  copyright string in the executable of your product.
+ */
+
+/*
+   Build a set of tables to decode the provided canonical Huffman code.
+   The code lengths are lens[0..codes-1].  The result starts at *table,
+   whose indices are 0..2^bits-1.  work is a writable array of at least
+   lens shorts, which is used as a work area.  type is the type of code
+   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
+   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
+   on return points to the next available entry's address.  bits is the
+   requested root table index bits, and on return it is the actual root
+   table index bits.  It will differ if the request is greater than the
+   longest code or if it is less than the shortest code.
+ */
+int inflate_table9(type, lens, codes, table, bits, work)
+codetype type;
+unsigned short FAR *lens;
+unsigned codes;
+code FAR * FAR *table;
+unsigned FAR *bits;
+unsigned short FAR *work;
+{
+    unsigned len;               /* a code's length in bits */
+    unsigned sym;               /* index of code symbols */
+    unsigned min, max;          /* minimum and maximum code lengths */
+    unsigned root;              /* number of index bits for root table */
+    unsigned curr;              /* number of index bits for current table */
+    unsigned drop;              /* code bits to drop for sub-table */
+    int left;                   /* number of prefix codes available */
+    unsigned used;              /* code entries in table used */
+    unsigned huff;              /* Huffman code */
+    unsigned incr;              /* for incrementing code, index */
+    unsigned fill;              /* index for replicating entries */
+    unsigned low;               /* low bits for current root entry */
+    unsigned mask;              /* mask for low root bits */
+    code this;                  /* table entry for duplication */
+    code FAR *next;             /* next available space in table */
+    const unsigned short FAR *base;     /* base value table to use */
+    const unsigned short FAR *extra;    /* extra bits table to use */
+    int end;                    /* use base and extra for symbol > end */
+    unsigned short count[MAXBITS+1];    /* number of codes of each length */
+    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
+    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
+        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17,
+        19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,
+        131, 163, 195, 227, 3, 0, 0};
+    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
+        128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129,
+        130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132,
+        133, 133, 133, 133, 144, 203, 69};
+    static const unsigned short dbase[32] = { /* Distance codes 0..31 base */
+        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49,
+        65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073,
+        4097, 6145, 8193, 12289, 16385, 24577, 32769, 49153};
+    static const unsigned short dext[32] = { /* Distance codes 0..31 extra */
+        128, 128, 128, 128, 129, 129, 130, 130, 131, 131, 132, 132,
+        133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138,
+        139, 139, 140, 140, 141, 141, 142, 142};
+
+    /*
+       Process a set of code lengths to create a canonical Huffman code.  The
+       code lengths are lens[0..codes-1].  Each length corresponds to the
+       symbols 0..codes-1.  The Huffman code is generated by first sorting the
+       symbols by length from short to long, and retaining the symbol order
+       for codes with equal lengths.  Then the code starts with all zero bits
+       for the first code of the shortest length, and the codes are integer
+       increments for the same length, and zeros are appended as the length
+       increases.  For the deflate format, these bits are stored backwards
+       from their more natural integer increment ordering, and so when the
+       decoding tables are built in the large loop below, the integer codes
+       are incremented backwards.
+
+       This routine assumes, but does not check, that all of the entries in
+       lens[] are in the range 0..MAXBITS.  The caller must assure this.
+       1..MAXBITS is interpreted as that code length.  zero means that that
+       symbol does not occur in this code.
+
+       The codes are sorted by computing a count of codes for each length,
+       creating from that a table of starting indices for each length in the
+       sorted table, and then entering the symbols in order in the sorted
+       table.  The sorted table is work[], with that space being provided by
+       the caller.
+
+       The length counts are used for other purposes as well, i.e. finding
+       the minimum and maximum length codes, determining if there are any
+       codes at all, checking for a valid set of lengths, and looking ahead
+       at length counts to determine sub-table sizes when building the
+       decoding tables.
+     */
+
+    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
+    for (len = 0; len <= MAXBITS; len++)
+        count[len] = 0;
+    for (sym = 0; sym < codes; sym++)
+        count[lens[sym]]++;
+
+    /* bound code lengths, force root to be within code lengths */
+    root = *bits;
+    for (max = MAXBITS; max >= 1; max--)
+        if (count[max] != 0) break;
+    if (root > max) root = max;
+    if (max == 0) return -1;            /* no codes! */
+    for (min = 1; min <= MAXBITS; min++)
+        if (count[min] != 0) break;
+    if (root < min) root = min;
+
+    /* check for an over-subscribed or incomplete set of lengths */
+    left = 1;
+    for (len = 1; len <= MAXBITS; len++) {
+        left <<= 1;
+        left -= count[len];
+        if (left < 0) return -1;        /* over-subscribed */
+    }
+    if (left > 0 && (type == CODES || max != 1))
+        return -1;                      /* incomplete set */
+
+    /* generate offsets into symbol table for each length for sorting */
+    offs[1] = 0;
+    for (len = 1; len < MAXBITS; len++)
+        offs[len + 1] = offs[len] + count[len];
+
+    /* sort symbols by length, by symbol order within each length */
+    for (sym = 0; sym < codes; sym++)
+        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
+
+    /*
+       Create and fill in decoding tables.  In this loop, the table being
+       filled is at next and has curr index bits.  The code being used is huff
+       with length len.  That code is converted to an index by dropping drop
+       bits off of the bottom.  For codes where len is less than drop + curr,
+       those top drop + curr - len bits are incremented through all values to
+       fill the table with replicated entries.
+
+       root is the number of index bits for the root table.  When len exceeds
+       root, sub-tables are created pointed to by the root entry with an index
+       of the low root bits of huff.  This is saved in low to check for when a
+       new sub-table should be started.  drop is zero when the root table is
+       being filled, and drop is root when sub-tables are being filled.
+
+       When a new sub-table is needed, it is necessary to look ahead in the
+       code lengths to determine what size sub-table is needed.  The length
+       counts are used for this, and so count[] is decremented as codes are
+       entered in the tables.
+
+       used keeps track of how many table entries have been allocated from the
+       provided *table space.  It is checked for LENS and DIST tables against
+       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
+       the initial root table size constants.  See the comments in inftree9.h
+       for more information.
+
+       sym increments through all symbols, and the loop terminates when
+       all codes of length max, i.e. all codes, have been processed.  This
+       routine permits incomplete codes, so another loop after this one fills
+       in the rest of the decoding tables with invalid code markers.
+     */
+
+    /* set up for code type */
+    switch (type) {
+    case CODES:
+        base = extra = work;    /* dummy value--not used */
+        end = 19;
+        break;
+    case LENS:
+        base = lbase;
+        base -= 257;
+        extra = lext;
+        extra -= 257;
+        end = 256;
+        break;
+    default:            /* DISTS */
+        base = dbase;
+        extra = dext;
+        end = -1;
+    }
+
+    /* initialize state for loop */
+    huff = 0;                   /* starting code */
+    sym = 0;                    /* starting code symbol */
+    len = min;                  /* starting code length */
+    next = *table;              /* current table to fill in */
+    curr = root;                /* current table index bits */
+    drop = 0;                   /* current bits to drop from code for index */
+    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
+    used = 1U << root;          /* use root table entries */
+    mask = used - 1;            /* mask for comparing low */
+
+    /* check available table space */
+    if ((type == LENS && used >= ENOUGH_LENS) ||
+        (type == DISTS && used >= ENOUGH_DISTS))
+        return 1;
+
+    /* process all codes and make table entries */
+    for (;;) {
+        /* create table entry */
+        this.bits = (unsigned char)(len - drop);
+        if ((int)(work[sym]) < end) {
+            this.op = (unsigned char)0;
+            this.val = work[sym];
+        }
+        else if ((int)(work[sym]) > end) {
+            this.op = (unsigned char)(extra[work[sym]]);
+            this.val = base[work[sym]];
+        }
+        else {
+            this.op = (unsigned char)(32 + 64);         /* end of block */
+            this.val = 0;
+        }
+
+        /* replicate for those indices with low len bits equal to huff */
+        incr = 1U << (len - drop);
+        fill = 1U << curr;
+        do {
+            fill -= incr;
+            next[(huff >> drop) + fill] = this;
+        } while (fill != 0);
+
+        /* backwards increment the len-bit code huff */
+        incr = 1U << (len - 1);
+        while (huff & incr)
+            incr >>= 1;
+        if (incr != 0) {
+            huff &= incr - 1;
+            huff += incr;
+        }
+        else
+            huff = 0;
+
+        /* go to next symbol, update count, len */
+        sym++;
+        if (--(count[len]) == 0) {
+            if (len == max) break;
+            len = lens[work[sym]];
+        }
+
+        /* create new sub-table if needed */
+        if (len > root && (huff & mask) != low) {
+            /* if first time, transition to sub-tables */
+            if (drop == 0)
+                drop = root;
+
+            /* increment past last table */
+            next += 1U << curr;
+
+            /* determine length of next table */
+            curr = len - drop;
+            left = (int)(1 << curr);
+            while (curr + drop < max) {
+                left -= count[curr + drop];
+                if (left <= 0) break;
+                curr++;
+                left <<= 1;
+            }
+
+            /* check for enough space */
+            used += 1U << curr;
+            if ((type == LENS && used >= ENOUGH_LENS) ||
+                (type == DISTS && used >= ENOUGH_DISTS))
+                return 1;
+
+            /* point entry in root table to sub-table */
+            low = huff & mask;
+            (*table)[low].op = (unsigned char)curr;
+            (*table)[low].bits = (unsigned char)root;
+            (*table)[low].val = (unsigned short)(next - *table);
+        }
+    }
+
+    /*
+       Fill in rest of table for incomplete codes.  This loop is similar to the
+       loop above in incrementing huff for table indices.  It is assumed that
+       len is equal to curr + drop, so there is no loop needed to increment
+       through high index bits.  When the current sub-table is filled, the loop
+       drops back to the root table to fill in any remaining entries there.
+     */
+    this.op = (unsigned char)64;                /* invalid code marker */
+    this.bits = (unsigned char)(len - drop);
+    this.val = (unsigned short)0;
+    while (huff != 0) {
+        /* when done with sub-table, drop back to root table */
+        if (drop != 0 && (huff & mask) != low) {
+            drop = 0;
+            len = root;
+            next = *table;
+            curr = root;
+            this.bits = (unsigned char)len;
+        }
+
+        /* put invalid code marker in table */
+        next[huff >> drop] = this;
+
+        /* backwards increment the len-bit code huff */
+        incr = 1U << (len - 1);
+        while (huff & incr)
+            incr >>= 1;
+        if (incr != 0) {
+            huff &= incr - 1;
+            huff += incr;
+        }
+        else
+            huff = 0;
+    }
+
+    /* set return parameters */
+    *table += used;
+    *bits = root;
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inftree9.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/infback9/inftree9.h
new file mode 100644 (file)
index 0000000..5ab21f0
--- /dev/null
@@ -0,0 +1,61 @@
+/* inftree9.h -- header to use inftree9.c
+ * Copyright (C) 1995-2008 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* Structure for decoding tables.  Each entry provides either the
+   information needed to do the operation requested by the code that
+   indexed that table entry, or it provides a pointer to another
+   table that indexes more bits of the code.  op indicates whether
+   the entry is a pointer to another table, a literal, a length or
+   distance, an end-of-block, or an invalid code.  For a table
+   pointer, the low four bits of op is the number of index bits of
+   that table.  For a length or distance, the low four bits of op
+   is the number of extra bits to get after the code.  bits is
+   the number of bits in this code or part of the code to drop off
+   of the bit buffer.  val is the actual byte to output in the case
+   of a literal, the base length or distance, or the offset from
+   the current table to the next table.  Each entry is four bytes. */
+typedef struct {
+    unsigned char op;           /* operation, extra bits, table bits */
+    unsigned char bits;         /* bits in this part of the code */
+    unsigned short val;         /* offset in table or code value */
+} code;
+
+/* op values as set by inflate_table():
+    00000000 - literal
+    0000tttt - table link, tttt != 0 is the number of table index bits
+    100eeeee - length or distance, eeee is the number of extra bits
+    01100000 - end of block
+    01000000 - invalid code
+ */
+
+/* Maximum size of the dynamic table.  The maximum number of code structures is
+   1446, which is the sum of 852 for literal/length codes and 594 for distance
+   codes.  These values were found by exhaustive searches using the program
+   examples/enough.c found in the zlib distribtution.  The arguments to that
+   program are the number of symbols, the initial root table size, and the
+   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
+   returns returns 852, and "enough 32 6 15" for distance codes returns 594.
+   The initial root table size (9 or 6) is found in the fifth argument of the
+   inflate_table() calls in infback9.c.  If the root table size is changed,
+   then these maximum sizes would be need to be recalculated and updated. */
+#define ENOUGH_LENS 852
+#define ENOUGH_DISTS 594
+#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
+
+/* Type of code to build for inflate_table9() */
+typedef enum {
+    CODES,
+    LENS,
+    DISTS
+} codetype;
+
+extern int inflate_table9 OF((codetype type, unsigned short FAR *lens,
+                             unsigned codes, code FAR * FAR *table,
+                             unsigned FAR *bits, unsigned short FAR *work));
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/inflate86/inffas86.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/inflate86/inffas86.c
new file mode 100644 (file)
index 0000000..7292f67
--- /dev/null
@@ -0,0 +1,1157 @@
+/* inffas86.c is a hand tuned assembler version of
+ *
+ * inffast.c -- fast decoding
+ * Copyright (C) 1995-2003 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ *
+ * Copyright (C) 2003 Chris Anderson <christop@charm.net>
+ * Please use the copyright conditions above.
+ *
+ * Dec-29-2003 -- I added AMD64 inflate asm support.  This version is also
+ * slightly quicker on x86 systems because, instead of using rep movsb to copy
+ * data, it uses rep movsw, which moves data in 2-byte chunks instead of single
+ * bytes.  I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates
+ * from http://fedora.linux.duke.edu/fc1_x86_64
+ * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with
+ * 1GB ram.  The 64-bit version is about 4% faster than the 32-bit version,
+ * when decompressing mozilla-source-1.3.tar.gz.
+ *
+ * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from
+ * the gcc -S output of zlib-1.2.0/inffast.c.  Zlib-1.2.0 is in beta release at
+ * the moment.  I have successfully compiled and tested this code with gcc2.96,
+ * gcc3.2, icc5.0, msvc6.0.  It is very close to the speed of inffast.S
+ * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX
+ * enabled.  I will attempt to merge the MMX code into this version.  Newer
+ * versions of this and inffast.S can be found at
+ * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+/* Mark Adler's comments from inffast.c: */
+
+/*
+   Decode literal, length, and distance codes and write out the resulting
+   literal and match bytes until either not enough input or output is
+   available, an end-of-block is encountered, or a data error is encountered.
+   When large enough input and output buffers are supplied to inflate(), for
+   example, a 16K input buffer and a 64K output buffer, more than 95% of the
+   inflate execution time is spent in this routine.
+
+   Entry assumptions:
+
+        state->mode == LEN
+        strm->avail_in >= 6
+        strm->avail_out >= 258
+        start >= strm->avail_out
+        state->bits < 8
+
+   On return, state->mode is one of:
+
+        LEN -- ran out of enough output space or enough available input
+        TYPE -- reached end of block code, inflate() to interpret next block
+        BAD -- error in block data
+
+   Notes:
+
+    - The maximum input bits used by a length/distance pair is 15 bits for the
+      length code, 5 bits for the length extra, 15 bits for the distance code,
+      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
+      Therefore if strm->avail_in >= 6, then there is enough input to avoid
+      checking for available input while decoding.
+
+    - The maximum bytes that a single length/distance pair can output is 258
+      bytes, which is the maximum length that can be coded.  inflate_fast()
+      requires strm->avail_out >= 258 for each loop to avoid checking for
+      output space.
+ */
+void inflate_fast(strm, start)
+z_streamp strm;
+unsigned start;         /* inflate()'s starting value for strm->avail_out */
+{
+    struct inflate_state FAR *state;
+    struct inffast_ar {
+/* 64   32                               x86  x86_64 */
+/* ar offset                              register */
+/*  0    0 */ void *esp;                /* esp save */
+/*  8    4 */ void *ebp;                /* ebp save */
+/* 16    8 */ unsigned char FAR *in;    /* esi rsi  local strm->next_in */
+/* 24   12 */ unsigned char FAR *last;  /*     r9   while in < last */
+/* 32   16 */ unsigned char FAR *out;   /* edi rdi  local strm->next_out */
+/* 40   20 */ unsigned char FAR *beg;   /*          inflate()'s init next_out */
+/* 48   24 */ unsigned char FAR *end;   /*     r10  while out < end */
+/* 56   28 */ unsigned char FAR *window;/*          size of window, wsize!=0 */
+/* 64   32 */ code const FAR *lcode;    /* ebp rbp  local strm->lencode */
+/* 72   36 */ code const FAR *dcode;    /*     r11  local strm->distcode */
+/* 80   40 */ unsigned long hold;       /* edx rdx  local strm->hold */
+/* 88   44 */ unsigned bits;            /* ebx rbx  local strm->bits */
+/* 92   48 */ unsigned wsize;           /*          window size */
+/* 96   52 */ unsigned write;           /*          window write index */
+/*100   56 */ unsigned lmask;           /*     r12  mask for lcode */
+/*104   60 */ unsigned dmask;           /*     r13  mask for dcode */
+/*108   64 */ unsigned len;             /*     r14  match length */
+/*112   68 */ unsigned dist;            /*     r15  match distance */
+/*116   72 */ unsigned status;          /*          set when state chng*/
+    } ar;
+
+#if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )
+#define PAD_AVAIL_IN 6
+#define PAD_AVAIL_OUT 258
+#else
+#define PAD_AVAIL_IN 5
+#define PAD_AVAIL_OUT 257
+#endif
+
+    /* copy state to local variables */
+    state = (struct inflate_state FAR *)strm->state;
+    ar.in = strm->next_in;
+    ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN);
+    ar.out = strm->next_out;
+    ar.beg = ar.out - (start - strm->avail_out);
+    ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT);
+    ar.wsize = state->wsize;
+    ar.write = state->wnext;
+    ar.window = state->window;
+    ar.hold = state->hold;
+    ar.bits = state->bits;
+    ar.lcode = state->lencode;
+    ar.dcode = state->distcode;
+    ar.lmask = (1U << state->lenbits) - 1;
+    ar.dmask = (1U << state->distbits) - 1;
+
+    /* decode literals and length/distances until end-of-block or not enough
+       input data or output space */
+
+    /* align in on 1/2 hold size boundary */
+    while (((unsigned long)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) {
+        ar.hold += (unsigned long)*ar.in++ << ar.bits;
+        ar.bits += 8;
+    }
+
+#if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )
+    __asm__ __volatile__ (
+"        leaq    %0, %%rax\n"
+"        movq    %%rbp, 8(%%rax)\n"       /* save regs rbp and rsp */
+"        movq    %%rsp, (%%rax)\n"
+"        movq    %%rax, %%rsp\n"          /* make rsp point to &ar */
+"        movq    16(%%rsp), %%rsi\n"      /* rsi  = in */
+"        movq    32(%%rsp), %%rdi\n"      /* rdi  = out */
+"        movq    24(%%rsp), %%r9\n"       /* r9   = last */
+"        movq    48(%%rsp), %%r10\n"      /* r10  = end */
+"        movq    64(%%rsp), %%rbp\n"      /* rbp  = lcode */
+"        movq    72(%%rsp), %%r11\n"      /* r11  = dcode */
+"        movq    80(%%rsp), %%rdx\n"      /* rdx  = hold */
+"        movl    88(%%rsp), %%ebx\n"      /* ebx  = bits */
+"        movl    100(%%rsp), %%r12d\n"    /* r12d = lmask */
+"        movl    104(%%rsp), %%r13d\n"    /* r13d = dmask */
+                                          /* r14d = len */
+                                          /* r15d = dist */
+"        cld\n"
+"        cmpq    %%rdi, %%r10\n"
+"        je      .L_one_time\n"           /* if only one decode left */
+"        cmpq    %%rsi, %%r9\n"
+"        je      .L_one_time\n"
+"        jmp     .L_do_loop\n"
+
+".L_one_time:\n"
+"        movq    %%r12, %%r8\n"           /* r8 = lmask */
+"        cmpb    $32, %%bl\n"
+"        ja      .L_get_length_code_one_time\n"
+
+"        lodsl\n"                         /* eax = *(uint *)in++ */
+"        movb    %%bl, %%cl\n"            /* cl = bits, needs it for shifting */
+"        addb    $32, %%bl\n"             /* bits += 32 */
+"        shlq    %%cl, %%rax\n"
+"        orq     %%rax, %%rdx\n"          /* hold |= *((uint *)in)++ << bits */
+"        jmp     .L_get_length_code_one_time\n"
+
+".align 32,0x90\n"
+".L_while_test:\n"
+"        cmpq    %%rdi, %%r10\n"
+"        jbe     .L_break_loop\n"
+"        cmpq    %%rsi, %%r9\n"
+"        jbe     .L_break_loop\n"
+
+".L_do_loop:\n"
+"        movq    %%r12, %%r8\n"           /* r8 = lmask */
+"        cmpb    $32, %%bl\n"
+"        ja      .L_get_length_code\n"    /* if (32 < bits) */
+
+"        lodsl\n"                         /* eax = *(uint *)in++ */
+"        movb    %%bl, %%cl\n"            /* cl = bits, needs it for shifting */
+"        addb    $32, %%bl\n"             /* bits += 32 */
+"        shlq    %%cl, %%rax\n"
+"        orq     %%rax, %%rdx\n"          /* hold |= *((uint *)in)++ << bits */
+
+".L_get_length_code:\n"
+"        andq    %%rdx, %%r8\n"            /* r8 &= hold */
+"        movl    (%%rbp,%%r8,4), %%eax\n"  /* eax = lcode[hold & lmask] */
+
+"        movb    %%ah, %%cl\n"            /* cl = this.bits */
+"        subb    %%ah, %%bl\n"            /* bits -= this.bits */
+"        shrq    %%cl, %%rdx\n"           /* hold >>= this.bits */
+
+"        testb   %%al, %%al\n"
+"        jnz     .L_test_for_length_base\n" /* if (op != 0) 45.7% */
+
+"        movq    %%r12, %%r8\n"            /* r8 = lmask */
+"        shrl    $16, %%eax\n"            /* output this.val char */
+"        stosb\n"
+
+".L_get_length_code_one_time:\n"
+"        andq    %%rdx, %%r8\n"            /* r8 &= hold */
+"        movl    (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */
+
+".L_dolen:\n"
+"        movb    %%ah, %%cl\n"            /* cl = this.bits */
+"        subb    %%ah, %%bl\n"            /* bits -= this.bits */
+"        shrq    %%cl, %%rdx\n"           /* hold >>= this.bits */
+
+"        testb   %%al, %%al\n"
+"        jnz     .L_test_for_length_base\n" /* if (op != 0) 45.7% */
+
+"        shrl    $16, %%eax\n"            /* output this.val char */
+"        stosb\n"
+"        jmp     .L_while_test\n"
+
+".align 32,0x90\n"
+".L_test_for_length_base:\n"
+"        movl    %%eax, %%r14d\n"         /* len = this */
+"        shrl    $16, %%r14d\n"           /* len = this.val */
+"        movb    %%al, %%cl\n"
+
+"        testb   $16, %%al\n"
+"        jz      .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */
+"        andb    $15, %%cl\n"             /* op &= 15 */
+"        jz      .L_decode_distance\n"    /* if (!op) */
+
+".L_add_bits_to_len:\n"
+"        subb    %%cl, %%bl\n"
+"        xorl    %%eax, %%eax\n"
+"        incl    %%eax\n"
+"        shll    %%cl, %%eax\n"
+"        decl    %%eax\n"
+"        andl    %%edx, %%eax\n"          /* eax &= hold */
+"        shrq    %%cl, %%rdx\n"
+"        addl    %%eax, %%r14d\n"         /* len += hold & mask[op] */
+
+".L_decode_distance:\n"
+"        movq    %%r13, %%r8\n"           /* r8 = dmask */
+"        cmpb    $32, %%bl\n"
+"        ja      .L_get_distance_code\n"  /* if (32 < bits) */
+
+"        lodsl\n"                         /* eax = *(uint *)in++ */
+"        movb    %%bl, %%cl\n"            /* cl = bits, needs it for shifting */
+"        addb    $32, %%bl\n"             /* bits += 32 */
+"        shlq    %%cl, %%rax\n"
+"        orq     %%rax, %%rdx\n"          /* hold |= *((uint *)in)++ << bits */
+
+".L_get_distance_code:\n"
+"        andq    %%rdx, %%r8\n"           /* r8 &= hold */
+"        movl    (%%r11,%%r8,4), %%eax\n" /* eax = dcode[hold & dmask] */
+
+".L_dodist:\n"
+"        movl    %%eax, %%r15d\n"         /* dist = this */
+"        shrl    $16, %%r15d\n"           /* dist = this.val */
+"        movb    %%ah, %%cl\n"
+"        subb    %%ah, %%bl\n"            /* bits -= this.bits */
+"        shrq    %%cl, %%rdx\n"           /* hold >>= this.bits */
+"        movb    %%al, %%cl\n"            /* cl = this.op */
+
+"        testb   $16, %%al\n"             /* if ((op & 16) == 0) */
+"        jz      .L_test_for_second_level_dist\n"
+"        andb    $15, %%cl\n"             /* op &= 15 */
+"        jz      .L_check_dist_one\n"
+
+".L_add_bits_to_dist:\n"
+"        subb    %%cl, %%bl\n"
+"        xorl    %%eax, %%eax\n"
+"        incl    %%eax\n"
+"        shll    %%cl, %%eax\n"
+"        decl    %%eax\n"                 /* (1 << op) - 1 */
+"        andl    %%edx, %%eax\n"          /* eax &= hold */
+"        shrq    %%cl, %%rdx\n"
+"        addl    %%eax, %%r15d\n"         /* dist += hold & ((1 << op) - 1) */
+
+".L_check_window:\n"
+"        movq    %%rsi, %%r8\n"           /* save in so from can use it's reg */
+"        movq    %%rdi, %%rax\n"
+"        subq    40(%%rsp), %%rax\n"      /* nbytes = out - beg */
+
+"        cmpl    %%r15d, %%eax\n"
+"        jb      .L_clip_window\n"        /* if (dist > nbytes) 4.2% */
+
+"        movl    %%r14d, %%ecx\n"         /* ecx = len */
+"        movq    %%rdi, %%rsi\n"
+"        subq    %%r15, %%rsi\n"          /* from = out - dist */
+
+"        sarl    %%ecx\n"
+"        jnc     .L_copy_two\n"           /* if len % 2 == 0 */
+
+"        rep     movsw\n"
+"        movb    (%%rsi), %%al\n"
+"        movb    %%al, (%%rdi)\n"
+"        incq    %%rdi\n"
+
+"        movq    %%r8, %%rsi\n"           /* move in back to %rsi, toss from */
+"        jmp     .L_while_test\n"
+
+".L_copy_two:\n"
+"        rep     movsw\n"
+"        movq    %%r8, %%rsi\n"           /* move in back to %rsi, toss from */
+"        jmp     .L_while_test\n"
+
+".align 32,0x90\n"
+".L_check_dist_one:\n"
+"        cmpl    $1, %%r15d\n"            /* if dist 1, is a memset */
+"        jne     .L_check_window\n"
+"        cmpq    %%rdi, 40(%%rsp)\n"      /* if out == beg, outside window */
+"        je      .L_check_window\n"
+
+"        movl    %%r14d, %%ecx\n"         /* ecx = len */
+"        movb    -1(%%rdi), %%al\n"
+"        movb    %%al, %%ah\n"
+
+"        sarl    %%ecx\n"
+"        jnc     .L_set_two\n"
+"        movb    %%al, (%%rdi)\n"
+"        incq    %%rdi\n"
+
+".L_set_two:\n"
+"        rep     stosw\n"
+"        jmp     .L_while_test\n"
+
+".align 32,0x90\n"
+".L_test_for_second_level_length:\n"
+"        testb   $64, %%al\n"
+"        jnz     .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */
+
+"        xorl    %%eax, %%eax\n"
+"        incl    %%eax\n"
+"        shll    %%cl, %%eax\n"
+"        decl    %%eax\n"
+"        andl    %%edx, %%eax\n"         /* eax &= hold */
+"        addl    %%r14d, %%eax\n"        /* eax += len */
+"        movl    (%%rbp,%%rax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/
+"        jmp     .L_dolen\n"
+
+".align 32,0x90\n"
+".L_test_for_second_level_dist:\n"
+"        testb   $64, %%al\n"
+"        jnz     .L_invalid_distance_code\n" /* if ((op & 64) != 0) */
+
+"        xorl    %%eax, %%eax\n"
+"        incl    %%eax\n"
+"        shll    %%cl, %%eax\n"
+"        decl    %%eax\n"
+"        andl    %%edx, %%eax\n"         /* eax &= hold */
+"        addl    %%r15d, %%eax\n"        /* eax += dist */
+"        movl    (%%r11,%%rax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/
+"        jmp     .L_dodist\n"
+
+".align 32,0x90\n"
+".L_clip_window:\n"
+"        movl    %%eax, %%ecx\n"         /* ecx = nbytes */
+"        movl    92(%%rsp), %%eax\n"     /* eax = wsize, prepare for dist cmp */
+"        negl    %%ecx\n"                /* nbytes = -nbytes */
+
+"        cmpl    %%r15d, %%eax\n"
+"        jb      .L_invalid_distance_too_far\n" /* if (dist > wsize) */
+
+"        addl    %%r15d, %%ecx\n"         /* nbytes = dist - nbytes */
+"        cmpl    $0, 96(%%rsp)\n"
+"        jne     .L_wrap_around_window\n" /* if (write != 0) */
+
+"        movq    56(%%rsp), %%rsi\n"     /* from  = window */
+"        subl    %%ecx, %%eax\n"         /* eax  -= nbytes */
+"        addq    %%rax, %%rsi\n"         /* from += wsize - nbytes */
+
+"        movl    %%r14d, %%eax\n"        /* eax = len */
+"        cmpl    %%ecx, %%r14d\n"
+"        jbe     .L_do_copy\n"           /* if (nbytes >= len) */
+
+"        subl    %%ecx, %%eax\n"         /* eax -= nbytes */
+"        rep     movsb\n"
+"        movq    %%rdi, %%rsi\n"
+"        subq    %%r15, %%rsi\n"         /* from = &out[ -dist ] */
+"        jmp     .L_do_copy\n"
+
+".align 32,0x90\n"
+".L_wrap_around_window:\n"
+"        movl    96(%%rsp), %%eax\n"     /* eax = write */
+"        cmpl    %%eax, %%ecx\n"
+"        jbe     .L_contiguous_in_window\n" /* if (write >= nbytes) */
+
+"        movl    92(%%rsp), %%esi\n"     /* from  = wsize */
+"        addq    56(%%rsp), %%rsi\n"     /* from += window */
+"        addq    %%rax, %%rsi\n"         /* from += write */
+"        subq    %%rcx, %%rsi\n"         /* from -= nbytes */
+"        subl    %%eax, %%ecx\n"         /* nbytes -= write */
+
+"        movl    %%r14d, %%eax\n"        /* eax = len */
+"        cmpl    %%ecx, %%eax\n"
+"        jbe     .L_do_copy\n"           /* if (nbytes >= len) */
+
+"        subl    %%ecx, %%eax\n"         /* len -= nbytes */
+"        rep     movsb\n"
+"        movq    56(%%rsp), %%rsi\n"     /* from = window */
+"        movl    96(%%rsp), %%ecx\n"     /* nbytes = write */
+"        cmpl    %%ecx, %%eax\n"
+"        jbe     .L_do_copy\n"           /* if (nbytes >= len) */
+
+"        subl    %%ecx, %%eax\n"         /* len -= nbytes */
+"        rep     movsb\n"
+"        movq    %%rdi, %%rsi\n"
+"        subq    %%r15, %%rsi\n"         /* from = out - dist */
+"        jmp     .L_do_copy\n"
+
+".align 32,0x90\n"
+".L_contiguous_in_window:\n"
+"        movq    56(%%rsp), %%rsi\n"     /* rsi = window */
+"        addq    %%rax, %%rsi\n"
+"        subq    %%rcx, %%rsi\n"         /* from += write - nbytes */
+
+"        movl    %%r14d, %%eax\n"        /* eax = len */
+"        cmpl    %%ecx, %%eax\n"
+"        jbe     .L_do_copy\n"           /* if (nbytes >= len) */
+
+"        subl    %%ecx, %%eax\n"         /* len -= nbytes */
+"        rep     movsb\n"
+"        movq    %%rdi, %%rsi\n"
+"        subq    %%r15, %%rsi\n"         /* from = out - dist */
+"        jmp     .L_do_copy\n"           /* if (nbytes >= len) */
+
+".align 32,0x90\n"
+".L_do_copy:\n"
+"        movl    %%eax, %%ecx\n"         /* ecx = len */
+"        rep     movsb\n"
+
+"        movq    %%r8, %%rsi\n"          /* move in back to %esi, toss from */
+"        jmp     .L_while_test\n"
+
+".L_test_for_end_of_block:\n"
+"        testb   $32, %%al\n"
+"        jz      .L_invalid_literal_length_code\n"
+"        movl    $1, 116(%%rsp)\n"
+"        jmp     .L_break_loop_with_status\n"
+
+".L_invalid_literal_length_code:\n"
+"        movl    $2, 116(%%rsp)\n"
+"        jmp     .L_break_loop_with_status\n"
+
+".L_invalid_distance_code:\n"
+"        movl    $3, 116(%%rsp)\n"
+"        jmp     .L_break_loop_with_status\n"
+
+".L_invalid_distance_too_far:\n"
+"        movl    $4, 116(%%rsp)\n"
+"        jmp     .L_break_loop_with_status\n"
+
+".L_break_loop:\n"
+"        movl    $0, 116(%%rsp)\n"
+
+".L_break_loop_with_status:\n"
+/* put in, out, bits, and hold back into ar and pop esp */
+"        movq    %%rsi, 16(%%rsp)\n"     /* in */
+"        movq    %%rdi, 32(%%rsp)\n"     /* out */
+"        movl    %%ebx, 88(%%rsp)\n"     /* bits */
+"        movq    %%rdx, 80(%%rsp)\n"     /* hold */
+"        movq    (%%rsp), %%rax\n"       /* restore rbp and rsp */
+"        movq    8(%%rsp), %%rbp\n"
+"        movq    %%rax, %%rsp\n"
+          :
+          : "m" (ar)
+          : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi",
+            "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15"
+    );
+#elif ( defined( __GNUC__ ) || defined( __ICC ) ) && defined( __i386 )
+    __asm__ __volatile__ (
+"        leal    %0, %%eax\n"
+"        movl    %%esp, (%%eax)\n"        /* save esp, ebp */
+"        movl    %%ebp, 4(%%eax)\n"
+"        movl    %%eax, %%esp\n"
+"        movl    8(%%esp), %%esi\n"       /* esi = in */
+"        movl    16(%%esp), %%edi\n"      /* edi = out */
+"        movl    40(%%esp), %%edx\n"      /* edx = hold */
+"        movl    44(%%esp), %%ebx\n"      /* ebx = bits */
+"        movl    32(%%esp), %%ebp\n"      /* ebp = lcode */
+
+"        cld\n"
+"        jmp     .L_do_loop\n"
+
+".align 32,0x90\n"
+".L_while_test:\n"
+"        cmpl    %%edi, 24(%%esp)\n"      /* out < end */
+"        jbe     .L_break_loop\n"
+"        cmpl    %%esi, 12(%%esp)\n"      /* in < last */
+"        jbe     .L_break_loop\n"
+
+".L_do_loop:\n"
+"        cmpb    $15, %%bl\n"
+"        ja      .L_get_length_code\n"    /* if (15 < bits) */
+
+"        xorl    %%eax, %%eax\n"
+"        lodsw\n"                         /* al = *(ushort *)in++ */
+"        movb    %%bl, %%cl\n"            /* cl = bits, needs it for shifting */
+"        addb    $16, %%bl\n"             /* bits += 16 */
+"        shll    %%cl, %%eax\n"
+"        orl     %%eax, %%edx\n"        /* hold |= *((ushort *)in)++ << bits */
+
+".L_get_length_code:\n"
+"        movl    56(%%esp), %%eax\n"      /* eax = lmask */
+"        andl    %%edx, %%eax\n"          /* eax &= hold */
+"        movl    (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[hold & lmask] */
+
+".L_dolen:\n"
+"        movb    %%ah, %%cl\n"            /* cl = this.bits */
+"        subb    %%ah, %%bl\n"            /* bits -= this.bits */
+"        shrl    %%cl, %%edx\n"           /* hold >>= this.bits */
+
+"        testb   %%al, %%al\n"
+"        jnz     .L_test_for_length_base\n" /* if (op != 0) 45.7% */
+
+"        shrl    $16, %%eax\n"            /* output this.val char */
+"        stosb\n"
+"        jmp     .L_while_test\n"
+
+".align 32,0x90\n"
+".L_test_for_length_base:\n"
+"        movl    %%eax, %%ecx\n"          /* len = this */
+"        shrl    $16, %%ecx\n"            /* len = this.val */
+"        movl    %%ecx, 64(%%esp)\n"      /* save len */
+"        movb    %%al, %%cl\n"
+
+"        testb   $16, %%al\n"
+"        jz      .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */
+"        andb    $15, %%cl\n"             /* op &= 15 */
+"        jz      .L_decode_distance\n"    /* if (!op) */
+"        cmpb    %%cl, %%bl\n"
+"        jae     .L_add_bits_to_len\n"    /* if (op <= bits) */
+
+"        movb    %%cl, %%ch\n"            /* stash op in ch, freeing cl */
+"        xorl    %%eax, %%eax\n"
+"        lodsw\n"                         /* al = *(ushort *)in++ */
+"        movb    %%bl, %%cl\n"            /* cl = bits, needs it for shifting */
+"        addb    $16, %%bl\n"             /* bits += 16 */
+"        shll    %%cl, %%eax\n"
+"        orl     %%eax, %%edx\n"         /* hold |= *((ushort *)in)++ << bits */
+"        movb    %%ch, %%cl\n"            /* move op back to ecx */
+
+".L_add_bits_to_len:\n"
+"        subb    %%cl, %%bl\n"
+"        xorl    %%eax, %%eax\n"
+"        incl    %%eax\n"
+"        shll    %%cl, %%eax\n"
+"        decl    %%eax\n"
+"        andl    %%edx, %%eax\n"          /* eax &= hold */
+"        shrl    %%cl, %%edx\n"
+"        addl    %%eax, 64(%%esp)\n"      /* len += hold & mask[op] */
+
+".L_decode_distance:\n"
+"        cmpb    $15, %%bl\n"
+"        ja      .L_get_distance_code\n"  /* if (15 < bits) */
+
+"        xorl    %%eax, %%eax\n"
+"        lodsw\n"                         /* al = *(ushort *)in++ */
+"        movb    %%bl, %%cl\n"            /* cl = bits, needs it for shifting */
+"        addb    $16, %%bl\n"             /* bits += 16 */
+"        shll    %%cl, %%eax\n"
+"        orl     %%eax, %%edx\n"         /* hold |= *((ushort *)in)++ << bits */
+
+".L_get_distance_code:\n"
+"        movl    60(%%esp), %%eax\n"      /* eax = dmask */
+"        movl    36(%%esp), %%ecx\n"      /* ecx = dcode */
+"        andl    %%edx, %%eax\n"          /* eax &= hold */
+"        movl    (%%ecx,%%eax,4), %%eax\n"/* eax = dcode[hold & dmask] */
+
+".L_dodist:\n"
+"        movl    %%eax, %%ebp\n"          /* dist = this */
+"        shrl    $16, %%ebp\n"            /* dist = this.val */
+"        movb    %%ah, %%cl\n"
+"        subb    %%ah, %%bl\n"            /* bits -= this.bits */
+"        shrl    %%cl, %%edx\n"           /* hold >>= this.bits */
+"        movb    %%al, %%cl\n"            /* cl = this.op */
+
+"        testb   $16, %%al\n"             /* if ((op & 16) == 0) */
+"        jz      .L_test_for_second_level_dist\n"
+"        andb    $15, %%cl\n"             /* op &= 15 */
+"        jz      .L_check_dist_one\n"
+"        cmpb    %%cl, %%bl\n"
+"        jae     .L_add_bits_to_dist\n"   /* if (op <= bits) 97.6% */
+
+"        movb    %%cl, %%ch\n"            /* stash op in ch, freeing cl */
+"        xorl    %%eax, %%eax\n"
+"        lodsw\n"                         /* al = *(ushort *)in++ */
+"        movb    %%bl, %%cl\n"            /* cl = bits, needs it for shifting */
+"        addb    $16, %%bl\n"             /* bits += 16 */
+"        shll    %%cl, %%eax\n"
+"        orl     %%eax, %%edx\n"        /* hold |= *((ushort *)in)++ << bits */
+"        movb    %%ch, %%cl\n"            /* move op back to ecx */
+
+".L_add_bits_to_dist:\n"
+"        subb    %%cl, %%bl\n"
+"        xorl    %%eax, %%eax\n"
+"        incl    %%eax\n"
+"        shll    %%cl, %%eax\n"
+"        decl    %%eax\n"                 /* (1 << op) - 1 */
+"        andl    %%edx, %%eax\n"          /* eax &= hold */
+"        shrl    %%cl, %%edx\n"
+"        addl    %%eax, %%ebp\n"          /* dist += hold & ((1 << op) - 1) */
+
+".L_check_window:\n"
+"        movl    %%esi, 8(%%esp)\n"       /* save in so from can use it's reg */
+"        movl    %%edi, %%eax\n"
+"        subl    20(%%esp), %%eax\n"      /* nbytes = out - beg */
+
+"        cmpl    %%ebp, %%eax\n"
+"        jb      .L_clip_window\n"        /* if (dist > nbytes) 4.2% */
+
+"        movl    64(%%esp), %%ecx\n"      /* ecx = len */
+"        movl    %%edi, %%esi\n"
+"        subl    %%ebp, %%esi\n"          /* from = out - dist */
+
+"        sarl    %%ecx\n"
+"        jnc     .L_copy_two\n"           /* if len % 2 == 0 */
+
+"        rep     movsw\n"
+"        movb    (%%esi), %%al\n"
+"        movb    %%al, (%%edi)\n"
+"        incl    %%edi\n"
+
+"        movl    8(%%esp), %%esi\n"       /* move in back to %esi, toss from */
+"        movl    32(%%esp), %%ebp\n"      /* ebp = lcode */
+"        jmp     .L_while_test\n"
+
+".L_copy_two:\n"
+"        rep     movsw\n"
+"        movl    8(%%esp), %%esi\n"       /* move in back to %esi, toss from */
+"        movl    32(%%esp), %%ebp\n"      /* ebp = lcode */
+"        jmp     .L_while_test\n"
+
+".align 32,0x90\n"
+".L_check_dist_one:\n"
+"        cmpl    $1, %%ebp\n"            /* if dist 1, is a memset */
+"        jne     .L_check_window\n"
+"        cmpl    %%edi, 20(%%esp)\n"
+"        je      .L_check_window\n"      /* out == beg, if outside window */
+
+"        movl    64(%%esp), %%ecx\n"      /* ecx = len */
+"        movb    -1(%%edi), %%al\n"
+"        movb    %%al, %%ah\n"
+
+"        sarl    %%ecx\n"
+"        jnc     .L_set_two\n"
+"        movb    %%al, (%%edi)\n"
+"        incl    %%edi\n"
+
+".L_set_two:\n"
+"        rep     stosw\n"
+"        movl    32(%%esp), %%ebp\n"      /* ebp = lcode */
+"        jmp     .L_while_test\n"
+
+".align 32,0x90\n"
+".L_test_for_second_level_length:\n"
+"        testb   $64, %%al\n"
+"        jnz     .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */
+
+"        xorl    %%eax, %%eax\n"
+"        incl    %%eax\n"
+"        shll    %%cl, %%eax\n"
+"        decl    %%eax\n"
+"        andl    %%edx, %%eax\n"         /* eax &= hold */
+"        addl    64(%%esp), %%eax\n"     /* eax += len */
+"        movl    (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/
+"        jmp     .L_dolen\n"
+
+".align 32,0x90\n"
+".L_test_for_second_level_dist:\n"
+"        testb   $64, %%al\n"
+"        jnz     .L_invalid_distance_code\n" /* if ((op & 64) != 0) */
+
+"        xorl    %%eax, %%eax\n"
+"        incl    %%eax\n"
+"        shll    %%cl, %%eax\n"
+"        decl    %%eax\n"
+"        andl    %%edx, %%eax\n"         /* eax &= hold */
+"        addl    %%ebp, %%eax\n"         /* eax += dist */
+"        movl    36(%%esp), %%ecx\n"     /* ecx = dcode */
+"        movl    (%%ecx,%%eax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/
+"        jmp     .L_dodist\n"
+
+".align 32,0x90\n"
+".L_clip_window:\n"
+"        movl    %%eax, %%ecx\n"
+"        movl    48(%%esp), %%eax\n"     /* eax = wsize */
+"        negl    %%ecx\n"                /* nbytes = -nbytes */
+"        movl    28(%%esp), %%esi\n"     /* from = window */
+
+"        cmpl    %%ebp, %%eax\n"
+"        jb      .L_invalid_distance_too_far\n" /* if (dist > wsize) */
+
+"        addl    %%ebp, %%ecx\n"         /* nbytes = dist - nbytes */
+"        cmpl    $0, 52(%%esp)\n"
+"        jne     .L_wrap_around_window\n" /* if (write != 0) */
+
+"        subl    %%ecx, %%eax\n"
+"        addl    %%eax, %%esi\n"         /* from += wsize - nbytes */
+
+"        movl    64(%%esp), %%eax\n"     /* eax = len */
+"        cmpl    %%ecx, %%eax\n"
+"        jbe     .L_do_copy\n"           /* if (nbytes >= len) */
+
+"        subl    %%ecx, %%eax\n"         /* len -= nbytes */
+"        rep     movsb\n"
+"        movl    %%edi, %%esi\n"
+"        subl    %%ebp, %%esi\n"         /* from = out - dist */
+"        jmp     .L_do_copy\n"
+
+".align 32,0x90\n"
+".L_wrap_around_window:\n"
+"        movl    52(%%esp), %%eax\n"     /* eax = write */
+"        cmpl    %%eax, %%ecx\n"
+"        jbe     .L_contiguous_in_window\n" /* if (write >= nbytes) */
+
+"        addl    48(%%esp), %%esi\n"     /* from += wsize */
+"        addl    %%eax, %%esi\n"         /* from += write */
+"        subl    %%ecx, %%esi\n"         /* from -= nbytes */
+"        subl    %%eax, %%ecx\n"         /* nbytes -= write */
+
+"        movl    64(%%esp), %%eax\n"     /* eax = len */
+"        cmpl    %%ecx, %%eax\n"
+"        jbe     .L_do_copy\n"           /* if (nbytes >= len) */
+
+"        subl    %%ecx, %%eax\n"         /* len -= nbytes */
+"        rep     movsb\n"
+"        movl    28(%%esp), %%esi\n"     /* from = window */
+"        movl    52(%%esp), %%ecx\n"     /* nbytes = write */
+"        cmpl    %%ecx, %%eax\n"
+"        jbe     .L_do_copy\n"           /* if (nbytes >= len) */
+
+"        subl    %%ecx, %%eax\n"         /* len -= nbytes */
+"        rep     movsb\n"
+"        movl    %%edi, %%esi\n"
+"        subl    %%ebp, %%esi\n"         /* from = out - dist */
+"        jmp     .L_do_copy\n"
+
+".align 32,0x90\n"
+".L_contiguous_in_window:\n"
+"        addl    %%eax, %%esi\n"
+"        subl    %%ecx, %%esi\n"         /* from += write - nbytes */
+
+"        movl    64(%%esp), %%eax\n"     /* eax = len */
+"        cmpl    %%ecx, %%eax\n"
+"        jbe     .L_do_copy\n"           /* if (nbytes >= len) */
+
+"        subl    %%ecx, %%eax\n"         /* len -= nbytes */
+"        rep     movsb\n"
+"        movl    %%edi, %%esi\n"
+"        subl    %%ebp, %%esi\n"         /* from = out - dist */
+"        jmp     .L_do_copy\n"           /* if (nbytes >= len) */
+
+".align 32,0x90\n"
+".L_do_copy:\n"
+"        movl    %%eax, %%ecx\n"
+"        rep     movsb\n"
+
+"        movl    8(%%esp), %%esi\n"      /* move in back to %esi, toss from */
+"        movl    32(%%esp), %%ebp\n"     /* ebp = lcode */
+"        jmp     .L_while_test\n"
+
+".L_test_for_end_of_block:\n"
+"        testb   $32, %%al\n"
+"        jz      .L_invalid_literal_length_code\n"
+"        movl    $1, 72(%%esp)\n"
+"        jmp     .L_break_loop_with_status\n"
+
+".L_invalid_literal_length_code:\n"
+"        movl    $2, 72(%%esp)\n"
+"        jmp     .L_break_loop_with_status\n"
+
+".L_invalid_distance_code:\n"
+"        movl    $3, 72(%%esp)\n"
+"        jmp     .L_break_loop_with_status\n"
+
+".L_invalid_distance_too_far:\n"
+"        movl    8(%%esp), %%esi\n"
+"        movl    $4, 72(%%esp)\n"
+"        jmp     .L_break_loop_with_status\n"
+
+".L_break_loop:\n"
+"        movl    $0, 72(%%esp)\n"
+
+".L_break_loop_with_status:\n"
+/* put in, out, bits, and hold back into ar and pop esp */
+"        movl    %%esi, 8(%%esp)\n"      /* save in */
+"        movl    %%edi, 16(%%esp)\n"     /* save out */
+"        movl    %%ebx, 44(%%esp)\n"     /* save bits */
+"        movl    %%edx, 40(%%esp)\n"     /* save hold */
+"        movl    4(%%esp), %%ebp\n"      /* restore esp, ebp */
+"        movl    (%%esp), %%esp\n"
+          :
+          : "m" (ar)
+          : "memory", "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi"
+    );
+#elif defined( _MSC_VER ) && ! defined( _M_AMD64 )
+    __asm {
+       lea     eax, ar
+       mov     [eax], esp         /* save esp, ebp */
+       mov     [eax+4], ebp
+       mov     esp, eax
+       mov     esi, [esp+8]       /* esi = in */
+       mov     edi, [esp+16]      /* edi = out */
+       mov     edx, [esp+40]      /* edx = hold */
+       mov     ebx, [esp+44]      /* ebx = bits */
+       mov     ebp, [esp+32]      /* ebp = lcode */
+
+       cld
+       jmp     L_do_loop
+
+ALIGN 4
+L_while_test:
+       cmp     [esp+24], edi
+       jbe     L_break_loop
+       cmp     [esp+12], esi
+       jbe     L_break_loop
+
+L_do_loop:
+       cmp     bl, 15
+       ja      L_get_length_code    /* if (15 < bits) */
+
+       xor     eax, eax
+       lodsw                         /* al = *(ushort *)in++ */
+       mov     cl, bl            /* cl = bits, needs it for shifting */
+       add     bl, 16             /* bits += 16 */
+       shl     eax, cl
+       or      edx, eax        /* hold |= *((ushort *)in)++ << bits */
+
+L_get_length_code:
+       mov     eax, [esp+56]      /* eax = lmask */
+       and     eax, edx          /* eax &= hold */
+       mov     eax, [ebp+eax*4] /* eax = lcode[hold & lmask] */
+
+L_dolen:
+       mov     cl, ah            /* cl = this.bits */
+       sub     bl, ah            /* bits -= this.bits */
+       shr     edx, cl           /* hold >>= this.bits */
+
+       test    al, al
+       jnz     L_test_for_length_base /* if (op != 0) 45.7% */
+
+       shr     eax, 16            /* output this.val char */
+       stosb
+       jmp     L_while_test
+
+ALIGN 4
+L_test_for_length_base:
+       mov     ecx, eax          /* len = this */
+       shr     ecx, 16            /* len = this.val */
+       mov     [esp+64], ecx      /* save len */
+       mov     cl, al
+
+       test    al, 16
+       jz      L_test_for_second_level_length /* if ((op & 16) == 0) 8% */
+       and     cl, 15             /* op &= 15 */
+       jz      L_decode_distance    /* if (!op) */
+       cmp     bl, cl
+       jae     L_add_bits_to_len    /* if (op <= bits) */
+
+       mov     ch, cl            /* stash op in ch, freeing cl */
+       xor     eax, eax
+       lodsw                         /* al = *(ushort *)in++ */
+       mov     cl, bl            /* cl = bits, needs it for shifting */
+       add     bl, 16             /* bits += 16 */
+       shl     eax, cl
+       or      edx, eax         /* hold |= *((ushort *)in)++ << bits */
+       mov     cl, ch            /* move op back to ecx */
+
+L_add_bits_to_len:
+       sub     bl, cl
+       xor     eax, eax
+       inc     eax
+       shl     eax, cl
+       dec     eax
+       and     eax, edx          /* eax &= hold */
+       shr     edx, cl
+       add     [esp+64], eax      /* len += hold & mask[op] */
+
+L_decode_distance:
+       cmp     bl, 15
+       ja      L_get_distance_code  /* if (15 < bits) */
+
+       xor     eax, eax
+       lodsw                         /* al = *(ushort *)in++ */
+       mov     cl, bl            /* cl = bits, needs it for shifting */
+       add     bl, 16             /* bits += 16 */
+       shl     eax, cl
+       or      edx, eax         /* hold |= *((ushort *)in)++ << bits */
+
+L_get_distance_code:
+       mov     eax, [esp+60]      /* eax = dmask */
+       mov     ecx, [esp+36]      /* ecx = dcode */
+       and     eax, edx          /* eax &= hold */
+       mov     eax, [ecx+eax*4]/* eax = dcode[hold & dmask] */
+
+L_dodist:
+       mov     ebp, eax          /* dist = this */
+       shr     ebp, 16            /* dist = this.val */
+       mov     cl, ah
+       sub     bl, ah            /* bits -= this.bits */
+       shr     edx, cl           /* hold >>= this.bits */
+       mov     cl, al            /* cl = this.op */
+
+       test    al, 16             /* if ((op & 16) == 0) */
+       jz      L_test_for_second_level_dist
+       and     cl, 15             /* op &= 15 */
+       jz      L_check_dist_one
+       cmp     bl, cl
+       jae     L_add_bits_to_dist   /* if (op <= bits) 97.6% */
+
+       mov     ch, cl            /* stash op in ch, freeing cl */
+       xor     eax, eax
+       lodsw                         /* al = *(ushort *)in++ */
+       mov     cl, bl            /* cl = bits, needs it for shifting */
+       add     bl, 16             /* bits += 16 */
+       shl     eax, cl
+       or      edx, eax        /* hold |= *((ushort *)in)++ << bits */
+       mov     cl, ch            /* move op back to ecx */
+
+L_add_bits_to_dist:
+       sub     bl, cl
+       xor     eax, eax
+       inc     eax
+       shl     eax, cl
+       dec     eax                 /* (1 << op) - 1 */
+       and     eax, edx          /* eax &= hold */
+       shr     edx, cl
+       add     ebp, eax          /* dist += hold & ((1 << op) - 1) */
+
+L_check_window:
+       mov     [esp+8], esi       /* save in so from can use it's reg */
+       mov     eax, edi
+       sub     eax, [esp+20]      /* nbytes = out - beg */
+
+       cmp     eax, ebp
+       jb      L_clip_window        /* if (dist > nbytes) 4.2% */
+
+       mov     ecx, [esp+64]      /* ecx = len */
+       mov     esi, edi
+       sub     esi, ebp          /* from = out - dist */
+
+       sar     ecx, 1
+       jnc     L_copy_two
+
+       rep     movsw
+       mov     al, [esi]
+       mov     [edi], al
+       inc     edi
+
+       mov     esi, [esp+8]      /* move in back to %esi, toss from */
+       mov     ebp, [esp+32]     /* ebp = lcode */
+       jmp     L_while_test
+
+L_copy_two:
+       rep     movsw
+       mov     esi, [esp+8]      /* move in back to %esi, toss from */
+       mov     ebp, [esp+32]     /* ebp = lcode */
+       jmp     L_while_test
+
+ALIGN 4
+L_check_dist_one:
+       cmp     ebp, 1            /* if dist 1, is a memset */
+       jne     L_check_window
+       cmp     [esp+20], edi
+       je      L_check_window    /* out == beg, if outside window */
+
+       mov     ecx, [esp+64]     /* ecx = len */
+       mov     al, [edi-1]
+       mov     ah, al
+
+       sar     ecx, 1
+       jnc     L_set_two
+       mov     [edi], al         /* memset out with from[-1] */
+       inc     edi
+
+L_set_two:
+       rep     stosw
+       mov     ebp, [esp+32]     /* ebp = lcode */
+       jmp     L_while_test
+
+ALIGN 4
+L_test_for_second_level_length:
+       test    al, 64
+       jnz     L_test_for_end_of_block /* if ((op & 64) != 0) */
+
+       xor     eax, eax
+       inc     eax
+       shl     eax, cl
+       dec     eax
+       and     eax, edx         /* eax &= hold */
+       add     eax, [esp+64]     /* eax += len */
+       mov     eax, [ebp+eax*4] /* eax = lcode[val+(hold&mask[op])]*/
+       jmp     L_dolen
+
+ALIGN 4
+L_test_for_second_level_dist:
+       test    al, 64
+       jnz     L_invalid_distance_code /* if ((op & 64) != 0) */
+
+       xor     eax, eax
+       inc     eax
+       shl     eax, cl
+       dec     eax
+       and     eax, edx         /* eax &= hold */
+       add     eax, ebp         /* eax += dist */
+       mov     ecx, [esp+36]     /* ecx = dcode */
+       mov     eax, [ecx+eax*4] /* eax = dcode[val+(hold&mask[op])]*/
+       jmp     L_dodist
+
+ALIGN 4
+L_clip_window:
+       mov     ecx, eax
+       mov     eax, [esp+48]     /* eax = wsize */
+       neg     ecx                /* nbytes = -nbytes */
+       mov     esi, [esp+28]     /* from = window */
+
+       cmp     eax, ebp
+       jb      L_invalid_distance_too_far /* if (dist > wsize) */
+
+       add     ecx, ebp         /* nbytes = dist - nbytes */
+       cmp     dword ptr [esp+52], 0
+       jne     L_wrap_around_window /* if (write != 0) */
+
+       sub     eax, ecx
+       add     esi, eax         /* from += wsize - nbytes */
+
+       mov     eax, [esp+64]    /* eax = len */
+       cmp     eax, ecx
+       jbe     L_do_copy          /* if (nbytes >= len) */
+
+       sub     eax, ecx         /* len -= nbytes */
+       rep     movsb
+       mov     esi, edi
+       sub     esi, ebp         /* from = out - dist */
+       jmp     L_do_copy
+
+ALIGN 4
+L_wrap_around_window:
+       mov     eax, [esp+52]    /* eax = write */
+       cmp     ecx, eax
+       jbe     L_contiguous_in_window /* if (write >= nbytes) */
+
+       add     esi, [esp+48]    /* from += wsize */
+       add     esi, eax         /* from += write */
+       sub     esi, ecx         /* from -= nbytes */
+       sub     ecx, eax         /* nbytes -= write */
+
+       mov     eax, [esp+64]    /* eax = len */
+       cmp     eax, ecx
+       jbe     L_do_copy          /* if (nbytes >= len) */
+
+       sub     eax, ecx         /* len -= nbytes */
+       rep     movsb
+       mov     esi, [esp+28]     /* from = window */
+       mov     ecx, [esp+52]     /* nbytes = write */
+       cmp     eax, ecx
+       jbe     L_do_copy          /* if (nbytes >= len) */
+
+       sub     eax, ecx         /* len -= nbytes */
+       rep     movsb
+       mov     esi, edi
+       sub     esi, ebp         /* from = out - dist */
+       jmp     L_do_copy
+
+ALIGN 4
+L_contiguous_in_window:
+       add     esi, eax
+       sub     esi, ecx         /* from += write - nbytes */
+
+       mov     eax, [esp+64]    /* eax = len */
+       cmp     eax, ecx
+       jbe     L_do_copy          /* if (nbytes >= len) */
+
+       sub     eax, ecx         /* len -= nbytes */
+       rep     movsb
+       mov     esi, edi
+       sub     esi, ebp         /* from = out - dist */
+       jmp     L_do_copy
+
+ALIGN 4
+L_do_copy:
+       mov     ecx, eax
+       rep     movsb
+
+       mov     esi, [esp+8]      /* move in back to %esi, toss from */
+       mov     ebp, [esp+32]     /* ebp = lcode */
+       jmp     L_while_test
+
+L_test_for_end_of_block:
+       test    al, 32
+       jz      L_invalid_literal_length_code
+       mov     dword ptr [esp+72], 1
+       jmp     L_break_loop_with_status
+
+L_invalid_literal_length_code:
+       mov     dword ptr [esp+72], 2
+       jmp     L_break_loop_with_status
+
+L_invalid_distance_code:
+       mov     dword ptr [esp+72], 3
+       jmp     L_break_loop_with_status
+
+L_invalid_distance_too_far:
+       mov     esi, [esp+4]
+       mov     dword ptr [esp+72], 4
+       jmp     L_break_loop_with_status
+
+L_break_loop:
+       mov     dword ptr [esp+72], 0
+
+L_break_loop_with_status:
+/* put in, out, bits, and hold back into ar and pop esp */
+       mov     [esp+8], esi     /* save in */
+       mov     [esp+16], edi    /* save out */
+       mov     [esp+44], ebx    /* save bits */
+       mov     [esp+40], edx    /* save hold */
+       mov     ebp, [esp+4]     /* restore esp, ebp */
+       mov     esp, [esp]
+    }
+#else
+#error "x86 architecture not defined"
+#endif
+
+    if (ar.status > 1) {
+        if (ar.status == 2)
+            strm->msg = "invalid literal/length code";
+        else if (ar.status == 3)
+            strm->msg = "invalid distance code";
+        else
+            strm->msg = "invalid distance too far back";
+        state->mode = BAD;
+    }
+    else if ( ar.status == 1 ) {
+        state->mode = TYPE;
+    }
+
+    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
+    ar.len = ar.bits >> 3;
+    ar.in -= ar.len;
+    ar.bits -= ar.len << 3;
+    ar.hold &= (1U << ar.bits) - 1;
+
+    /* update state and return */
+    strm->next_in = ar.in;
+    strm->next_out = ar.out;
+    strm->avail_in = (unsigned)(ar.in < ar.last ?
+                                PAD_AVAIL_IN + (ar.last - ar.in) :
+                                PAD_AVAIL_IN - (ar.in - ar.last));
+    strm->avail_out = (unsigned)(ar.out < ar.end ?
+                                 PAD_AVAIL_OUT + (ar.end - ar.out) :
+                                 PAD_AVAIL_OUT - (ar.out - ar.end));
+    state->hold = ar.hold;
+    state->bits = ar.bits;
+    return;
+}
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/inflate86/inffast.S b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/inflate86/inffast.S
new file mode 100644 (file)
index 0000000..2245a29
--- /dev/null
@@ -0,0 +1,1368 @@
+/*
+ * inffast.S is a hand tuned assembler version of:
+ *
+ * inffast.c -- fast decoding
+ * Copyright (C) 1995-2003 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ *
+ * Copyright (C) 2003 Chris Anderson <christop@charm.net>
+ * Please use the copyright conditions above.
+ *
+ * This version (Jan-23-2003) of inflate_fast was coded and tested under
+ * GNU/Linux on a pentium 3, using the gcc-3.2 compiler distribution.  On that
+ * machine, I found that gzip style archives decompressed about 20% faster than
+ * the gcc-3.2 -O3 -fomit-frame-pointer compiled version.  Your results will
+ * depend on how large of a buffer is used for z_stream.next_in & next_out
+ * (8K-32K worked best for my 256K cpu cache) and how much overhead there is in
+ * stream processing I/O and crc32/addler32.  In my case, this routine used
+ * 70% of the cpu time and crc32 used 20%.
+ *
+ * I am confident that this version will work in the general case, but I have
+ * not tested a wide variety of datasets or a wide variety of platforms.
+ *
+ * Jan-24-2003 -- Added -DUSE_MMX define for slightly faster inflating.
+ * It should be a runtime flag instead of compile time flag...
+ *
+ * Jan-26-2003 -- Added runtime check for MMX support with cpuid instruction.
+ * With -DUSE_MMX, only MMX code is compiled.  With -DNO_MMX, only non-MMX code
+ * is compiled.  Without either option, runtime detection is enabled.  Runtime
+ * detection should work on all modern cpus and the recomended algorithm (flip
+ * ID bit on eflags and then use the cpuid instruction) is used in many
+ * multimedia applications.  Tested under win2k with gcc-2.95 and gas-2.12
+ * distributed with cygwin3.  Compiling with gcc-2.95 -c inffast.S -o
+ * inffast.obj generates a COFF object which can then be linked with MSVC++
+ * compiled code.  Tested under FreeBSD 4.7 with gcc-2.95.
+ *
+ * Jan-28-2003 -- Tested Athlon XP... MMX mode is slower than no MMX (and
+ * slower than compiler generated code).  Adjusted cpuid check to use the MMX
+ * code only for Pentiums < P4 until I have more data on the P4.  Speed
+ * improvment is only about 15% on the Athlon when compared with code generated
+ * with MSVC++.  Not sure yet, but I think the P4 will also be slower using the
+ * MMX mode because many of it's x86 ALU instructions execute in .5 cycles and
+ * have less latency than MMX ops.  Added code to buffer the last 11 bytes of
+ * the input stream since the MMX code grabs bits in chunks of 32, which
+ * differs from the inffast.c algorithm.  I don't think there would have been
+ * read overruns where a page boundary was crossed (a segfault), but there
+ * could have been overruns when next_in ends on unaligned memory (unintialized
+ * memory read).
+ *
+ * Mar-13-2003 -- P4 MMX is slightly slower than P4 NO_MMX.  I created a C
+ * version of the non-MMX code so that it doesn't depend on zstrm and zstate
+ * structure offsets which are hard coded in this file.  This was last tested
+ * with zlib-1.2.0 which is currently in beta testing, newer versions of this
+ * and inffas86.c can be found at http://www.eetbeetee.com/zlib/ and
+ * http://www.charm.net/~christop/zlib/
+ */
+
+
+/*
+ * if you have underscore linking problems (_inflate_fast undefined), try
+ * using -DGAS_COFF
+ */
+#if ! defined( GAS_COFF ) && ! defined( GAS_ELF )
+
+#if defined( WIN32 ) || defined( __CYGWIN__ )
+#define GAS_COFF /* windows object format */
+#else
+#define GAS_ELF
+#endif
+
+#endif /* ! GAS_COFF && ! GAS_ELF */
+
+
+#if defined( GAS_COFF )
+
+/* coff externals have underscores */
+#define inflate_fast _inflate_fast
+#define inflate_fast_use_mmx _inflate_fast_use_mmx
+
+#endif /* GAS_COFF */
+
+
+.file "inffast.S"
+
+.globl inflate_fast
+
+.text
+.align 4,0
+.L_invalid_literal_length_code_msg:
+.string "invalid literal/length code"
+
+.align 4,0
+.L_invalid_distance_code_msg:
+.string "invalid distance code"
+
+.align 4,0
+.L_invalid_distance_too_far_msg:
+.string "invalid distance too far back"
+
+#if ! defined( NO_MMX )
+.align 4,0
+.L_mask: /* mask[N] = ( 1 << N ) - 1 */
+.long 0
+.long 1
+.long 3
+.long 7
+.long 15
+.long 31
+.long 63
+.long 127
+.long 255
+.long 511
+.long 1023
+.long 2047
+.long 4095
+.long 8191
+.long 16383
+.long 32767
+.long 65535
+.long 131071
+.long 262143
+.long 524287
+.long 1048575
+.long 2097151
+.long 4194303
+.long 8388607
+.long 16777215
+.long 33554431
+.long 67108863
+.long 134217727
+.long 268435455
+.long 536870911
+.long 1073741823
+.long 2147483647
+.long 4294967295
+#endif /* NO_MMX */
+
+.text
+
+/*
+ * struct z_stream offsets, in zlib.h
+ */
+#define next_in_strm   0   /* strm->next_in */
+#define avail_in_strm  4   /* strm->avail_in */
+#define next_out_strm  12  /* strm->next_out */
+#define avail_out_strm 16  /* strm->avail_out */
+#define msg_strm       24  /* strm->msg */
+#define state_strm     28  /* strm->state */
+
+/*
+ * struct inflate_state offsets, in inflate.h
+ */
+#define mode_state     0   /* state->mode */
+#define wsize_state    32  /* state->wsize */
+#define write_state    40  /* state->write */
+#define window_state   44  /* state->window */
+#define hold_state     48  /* state->hold */
+#define bits_state     52  /* state->bits */
+#define lencode_state  68  /* state->lencode */
+#define distcode_state 72  /* state->distcode */
+#define lenbits_state  76  /* state->lenbits */
+#define distbits_state 80  /* state->distbits */
+
+/*
+ * inflate_fast's activation record
+ */
+#define local_var_size 64 /* how much local space for vars */
+#define strm_sp        88 /* first arg: z_stream * (local_var_size + 24) */
+#define start_sp       92 /* second arg: unsigned int (local_var_size + 28) */
+
+/*
+ * offsets for local vars on stack
+ */
+#define out            60  /* unsigned char* */
+#define window         56  /* unsigned char* */
+#define wsize          52  /* unsigned int */
+#define write          48  /* unsigned int */
+#define in             44  /* unsigned char* */
+#define beg            40  /* unsigned char* */
+#define buf            28  /* char[ 12 ] */
+#define len            24  /* unsigned int */
+#define last           20  /* unsigned char* */
+#define end            16  /* unsigned char* */
+#define dcode          12  /* code* */
+#define lcode           8  /* code* */
+#define dmask           4  /* unsigned int */
+#define lmask           0  /* unsigned int */
+
+/*
+ * typedef enum inflate_mode consts, in inflate.h
+ */
+#define INFLATE_MODE_TYPE 11  /* state->mode flags enum-ed in inflate.h */
+#define INFLATE_MODE_BAD  26
+
+
+#if ! defined( USE_MMX ) && ! defined( NO_MMX )
+
+#define RUN_TIME_MMX
+
+#define CHECK_MMX    1
+#define DO_USE_MMX   2
+#define DONT_USE_MMX 3
+
+.globl inflate_fast_use_mmx
+
+.data
+
+.align 4,0
+inflate_fast_use_mmx: /* integer flag for run time control 1=check,2=mmx,3=no */
+.long CHECK_MMX
+
+#if defined( GAS_ELF )
+/* elf info */
+.type   inflate_fast_use_mmx,@object
+.size   inflate_fast_use_mmx,4
+#endif
+
+#endif /* RUN_TIME_MMX */
+
+#if defined( GAS_COFF )
+/* coff info: scl 2 = extern, type 32 = function */
+.def inflate_fast; .scl 2; .type 32; .endef
+#endif
+
+.text
+
+.align 32,0x90
+inflate_fast:
+        pushl   %edi
+        pushl   %esi
+        pushl   %ebp
+        pushl   %ebx
+        pushf   /* save eflags (strm_sp, state_sp assumes this is 32 bits) */
+        subl    $local_var_size, %esp
+        cld
+
+#define strm_r  %esi
+#define state_r %edi
+
+        movl    strm_sp(%esp), strm_r
+        movl    state_strm(strm_r), state_r
+
+        /* in = strm->next_in;
+         * out = strm->next_out;
+         * last = in + strm->avail_in - 11;
+         * beg = out - (start - strm->avail_out);
+         * end = out + (strm->avail_out - 257);
+         */
+        movl    avail_in_strm(strm_r), %edx
+        movl    next_in_strm(strm_r), %eax
+
+        addl    %eax, %edx      /* avail_in += next_in */
+        subl    $11, %edx       /* avail_in -= 11 */
+
+        movl    %eax, in(%esp)
+        movl    %edx, last(%esp)
+
+        movl    start_sp(%esp), %ebp
+        movl    avail_out_strm(strm_r), %ecx
+        movl    next_out_strm(strm_r), %ebx
+
+        subl    %ecx, %ebp      /* start -= avail_out */
+        negl    %ebp            /* start = -start */
+        addl    %ebx, %ebp      /* start += next_out */
+
+        subl    $257, %ecx      /* avail_out -= 257 */
+        addl    %ebx, %ecx      /* avail_out += out */
+
+        movl    %ebx, out(%esp)
+        movl    %ebp, beg(%esp)
+        movl    %ecx, end(%esp)
+
+        /* wsize = state->wsize;
+         * write = state->write;
+         * window = state->window;
+         * hold = state->hold;
+         * bits = state->bits;
+         * lcode = state->lencode;
+         * dcode = state->distcode;
+         * lmask = ( 1 << state->lenbits ) - 1;
+         * dmask = ( 1 << state->distbits ) - 1;
+         */
+
+        movl    lencode_state(state_r), %eax
+        movl    distcode_state(state_r), %ecx
+
+        movl    %eax, lcode(%esp)
+        movl    %ecx, dcode(%esp)
+
+        movl    $1, %eax
+        movl    lenbits_state(state_r), %ecx
+        shll    %cl, %eax
+        decl    %eax
+        movl    %eax, lmask(%esp)
+
+        movl    $1, %eax
+        movl    distbits_state(state_r), %ecx
+        shll    %cl, %eax
+        decl    %eax
+        movl    %eax, dmask(%esp)
+
+        movl    wsize_state(state_r), %eax
+        movl    write_state(state_r), %ecx
+        movl    window_state(state_r), %edx
+
+        movl    %eax, wsize(%esp)
+        movl    %ecx, write(%esp)
+        movl    %edx, window(%esp)
+
+        movl    hold_state(state_r), %ebp
+        movl    bits_state(state_r), %ebx
+
+#undef strm_r
+#undef state_r
+
+#define in_r       %esi
+#define from_r     %esi
+#define out_r      %edi
+
+        movl    in(%esp), in_r
+        movl    last(%esp), %ecx
+        cmpl    in_r, %ecx
+        ja      .L_align_long           /* if in < last */
+
+        addl    $11, %ecx               /* ecx = &in[ avail_in ] */
+        subl    in_r, %ecx              /* ecx = avail_in */
+        movl    $12, %eax
+        subl    %ecx, %eax              /* eax = 12 - avail_in */
+        leal    buf(%esp), %edi
+        rep     movsb                   /* memcpy( buf, in, avail_in ) */
+        movl    %eax, %ecx
+        xorl    %eax, %eax
+        rep     stosb         /* memset( &buf[ avail_in ], 0, 12 - avail_in ) */
+        leal    buf(%esp), in_r         /* in = buf */
+        movl    in_r, last(%esp)        /* last = in, do just one iteration */
+        jmp     .L_is_aligned
+
+        /* align in_r on long boundary */
+.L_align_long:
+        testl   $3, in_r
+        jz      .L_is_aligned
+        xorl    %eax, %eax
+        movb    (in_r), %al
+        incl    in_r
+        movl    %ebx, %ecx
+        addl    $8, %ebx
+        shll    %cl, %eax
+        orl     %eax, %ebp
+        jmp     .L_align_long
+
+.L_is_aligned:
+        movl    out(%esp), out_r
+
+#if defined( NO_MMX )
+        jmp     .L_do_loop
+#endif
+
+#if defined( USE_MMX )
+        jmp     .L_init_mmx
+#endif
+
+/*** Runtime MMX check ***/
+
+#if defined( RUN_TIME_MMX )
+.L_check_mmx:
+        cmpl    $DO_USE_MMX, inflate_fast_use_mmx
+        je      .L_init_mmx
+        ja      .L_do_loop /* > 2 */
+
+        pushl   %eax
+        pushl   %ebx
+        pushl   %ecx
+        pushl   %edx
+        pushf
+        movl    (%esp), %eax      /* copy eflags to eax */
+        xorl    $0x200000, (%esp) /* try toggling ID bit of eflags (bit 21)
+                                   * to see if cpu supports cpuid...
+                                   * ID bit method not supported by NexGen but
+                                   * bios may load a cpuid instruction and
+                                   * cpuid may be disabled on Cyrix 5-6x86 */
+        popf
+        pushf
+        popl    %edx              /* copy new eflags to edx */
+        xorl    %eax, %edx        /* test if ID bit is flipped */
+        jz      .L_dont_use_mmx   /* not flipped if zero */
+        xorl    %eax, %eax
+        cpuid
+        cmpl    $0x756e6547, %ebx /* check for GenuineIntel in ebx,ecx,edx */
+        jne     .L_dont_use_mmx
+        cmpl    $0x6c65746e, %ecx
+        jne     .L_dont_use_mmx
+        cmpl    $0x49656e69, %edx
+        jne     .L_dont_use_mmx
+        movl    $1, %eax
+        cpuid                     /* get cpu features */
+        shrl    $8, %eax
+        andl    $15, %eax
+        cmpl    $6, %eax          /* check for Pentium family, is 0xf for P4 */
+        jne     .L_dont_use_mmx
+        testl   $0x800000, %edx   /* test if MMX feature is set (bit 23) */
+        jnz     .L_use_mmx
+        jmp     .L_dont_use_mmx
+.L_use_mmx:
+        movl    $DO_USE_MMX, inflate_fast_use_mmx
+        jmp     .L_check_mmx_pop
+.L_dont_use_mmx:
+        movl    $DONT_USE_MMX, inflate_fast_use_mmx
+.L_check_mmx_pop:
+        popl    %edx
+        popl    %ecx
+        popl    %ebx
+        popl    %eax
+        jmp     .L_check_mmx
+#endif
+
+
+/*** Non-MMX code ***/
+
+#if defined ( NO_MMX ) || defined( RUN_TIME_MMX )
+
+#define hold_r     %ebp
+#define bits_r     %bl
+#define bitslong_r %ebx
+
+.align 32,0x90
+.L_while_test:
+        /* while (in < last && out < end)
+         */
+        cmpl    out_r, end(%esp)
+        jbe     .L_break_loop           /* if (out >= end) */
+
+        cmpl    in_r, last(%esp)
+        jbe     .L_break_loop
+
+.L_do_loop:
+        /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out
+         *
+         * do {
+         *   if (bits < 15) {
+         *     hold |= *((unsigned short *)in)++ << bits;
+         *     bits += 16
+         *   }
+         *   this = lcode[hold & lmask]
+         */
+        cmpb    $15, bits_r
+        ja      .L_get_length_code      /* if (15 < bits) */
+
+        xorl    %eax, %eax
+        lodsw                           /* al = *(ushort *)in++ */
+        movb    bits_r, %cl             /* cl = bits, needs it for shifting */
+        addb    $16, bits_r             /* bits += 16 */
+        shll    %cl, %eax
+        orl     %eax, hold_r            /* hold |= *((ushort *)in)++ << bits */
+
+.L_get_length_code:
+        movl    lmask(%esp), %edx       /* edx = lmask */
+        movl    lcode(%esp), %ecx       /* ecx = lcode */
+        andl    hold_r, %edx            /* edx &= hold */
+        movl    (%ecx,%edx,4), %eax     /* eax = lcode[hold & lmask] */
+
+.L_dolen:
+        /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out
+         *
+         * dolen:
+         *    bits -= this.bits;
+         *    hold >>= this.bits
+         */
+        movb    %ah, %cl                /* cl = this.bits */
+        subb    %ah, bits_r             /* bits -= this.bits */
+        shrl    %cl, hold_r             /* hold >>= this.bits */
+
+        /* check if op is a literal
+         * if (op == 0) {
+         *    PUP(out) = this.val;
+         *  }
+         */
+        testb   %al, %al
+        jnz     .L_test_for_length_base /* if (op != 0) 45.7% */
+
+        shrl    $16, %eax               /* output this.val char */
+        stosb
+        jmp     .L_while_test
+
+.L_test_for_length_base:
+        /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = len
+         *
+         * else if (op & 16) {
+         *   len = this.val
+         *   op &= 15
+         *   if (op) {
+         *     if (op > bits) {
+         *       hold |= *((unsigned short *)in)++ << bits;
+         *       bits += 16
+         *     }
+         *     len += hold & mask[op];
+         *     bits -= op;
+         *     hold >>= op;
+         *   }
+         */
+#define len_r %edx
+        movl    %eax, len_r             /* len = this */
+        shrl    $16, len_r              /* len = this.val */
+        movb    %al, %cl
+
+        testb   $16, %al
+        jz      .L_test_for_second_level_length /* if ((op & 16) == 0) 8% */
+        andb    $15, %cl                /* op &= 15 */
+        jz      .L_save_len             /* if (!op) */
+        cmpb    %cl, bits_r
+        jae     .L_add_bits_to_len      /* if (op <= bits) */
+
+        movb    %cl, %ch                /* stash op in ch, freeing cl */
+        xorl    %eax, %eax
+        lodsw                           /* al = *(ushort *)in++ */
+        movb    bits_r, %cl             /* cl = bits, needs it for shifting */
+        addb    $16, bits_r             /* bits += 16 */
+        shll    %cl, %eax
+        orl     %eax, hold_r            /* hold |= *((ushort *)in)++ << bits */
+        movb    %ch, %cl                /* move op back to ecx */
+
+.L_add_bits_to_len:
+        movl    $1, %eax
+        shll    %cl, %eax
+        decl    %eax
+        subb    %cl, bits_r
+        andl    hold_r, %eax            /* eax &= hold */
+        shrl    %cl, hold_r
+        addl    %eax, len_r             /* len += hold & mask[op] */
+
+.L_save_len:
+        movl    len_r, len(%esp)        /* save len */
+#undef  len_r
+
+.L_decode_distance:
+        /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = dist
+         *
+         *   if (bits < 15) {
+         *     hold |= *((unsigned short *)in)++ << bits;
+         *     bits += 16
+         *   }
+         *   this = dcode[hold & dmask];
+         * dodist:
+         *   bits -= this.bits;
+         *   hold >>= this.bits;
+         *   op = this.op;
+         */
+
+        cmpb    $15, bits_r
+        ja      .L_get_distance_code    /* if (15 < bits) */
+
+        xorl    %eax, %eax
+        lodsw                           /* al = *(ushort *)in++ */
+        movb    bits_r, %cl             /* cl = bits, needs it for shifting */
+        addb    $16, bits_r             /* bits += 16 */
+        shll    %cl, %eax
+        orl     %eax, hold_r            /* hold |= *((ushort *)in)++ << bits */
+
+.L_get_distance_code:
+        movl    dmask(%esp), %edx       /* edx = dmask */
+        movl    dcode(%esp), %ecx       /* ecx = dcode */
+        andl    hold_r, %edx            /* edx &= hold */
+        movl    (%ecx,%edx,4), %eax     /* eax = dcode[hold & dmask] */
+
+#define dist_r %edx
+.L_dodist:
+        movl    %eax, dist_r            /* dist = this */
+        shrl    $16, dist_r             /* dist = this.val */
+        movb    %ah, %cl
+        subb    %ah, bits_r             /* bits -= this.bits */
+        shrl    %cl, hold_r             /* hold >>= this.bits */
+
+        /* if (op & 16) {
+         *   dist = this.val
+         *   op &= 15
+         *   if (op > bits) {
+         *     hold |= *((unsigned short *)in)++ << bits;
+         *     bits += 16
+         *   }
+         *   dist += hold & mask[op];
+         *   bits -= op;
+         *   hold >>= op;
+         */
+        movb    %al, %cl                /* cl = this.op */
+
+        testb   $16, %al                /* if ((op & 16) == 0) */
+        jz      .L_test_for_second_level_dist
+        andb    $15, %cl                /* op &= 15 */
+        jz      .L_check_dist_one
+        cmpb    %cl, bits_r
+        jae     .L_add_bits_to_dist     /* if (op <= bits) 97.6% */
+
+        movb    %cl, %ch                /* stash op in ch, freeing cl */
+        xorl    %eax, %eax
+        lodsw                           /* al = *(ushort *)in++ */
+        movb    bits_r, %cl             /* cl = bits, needs it for shifting */
+        addb    $16, bits_r             /* bits += 16 */
+        shll    %cl, %eax
+        orl     %eax, hold_r            /* hold |= *((ushort *)in)++ << bits */
+        movb    %ch, %cl                /* move op back to ecx */
+
+.L_add_bits_to_dist:
+        movl    $1, %eax
+        shll    %cl, %eax
+        decl    %eax                    /* (1 << op) - 1 */
+        subb    %cl, bits_r
+        andl    hold_r, %eax            /* eax &= hold */
+        shrl    %cl, hold_r
+        addl    %eax, dist_r            /* dist += hold & ((1 << op) - 1) */
+        jmp     .L_check_window
+
+.L_check_window:
+        /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist
+         *       %ecx = nbytes
+         *
+         * nbytes = out - beg;
+         * if (dist <= nbytes) {
+         *   from = out - dist;
+         *   do {
+         *     PUP(out) = PUP(from);
+         *   } while (--len > 0) {
+         * }
+         */
+
+        movl    in_r, in(%esp)          /* save in so from can use it's reg */
+        movl    out_r, %eax
+        subl    beg(%esp), %eax         /* nbytes = out - beg */
+
+        cmpl    dist_r, %eax
+        jb      .L_clip_window          /* if (dist > nbytes) 4.2% */
+
+        movl    len(%esp), %ecx
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+
+        subl    $3, %ecx
+        movb    (from_r), %al
+        movb    %al, (out_r)
+        movb    1(from_r), %al
+        movb    2(from_r), %dl
+        addl    $3, from_r
+        movb    %al, 1(out_r)
+        movb    %dl, 2(out_r)
+        addl    $3, out_r
+        rep     movsb
+
+        movl    in(%esp), in_r          /* move in back to %esi, toss from */
+        jmp     .L_while_test
+
+.align 16,0x90
+.L_check_dist_one:
+        cmpl    $1, dist_r
+        jne     .L_check_window
+        cmpl    out_r, beg(%esp)
+        je      .L_check_window
+
+        decl    out_r
+        movl    len(%esp), %ecx
+        movb    (out_r), %al
+        subl    $3, %ecx
+
+        movb    %al, 1(out_r)
+        movb    %al, 2(out_r)
+        movb    %al, 3(out_r)
+        addl    $4, out_r
+        rep     stosb
+
+        jmp     .L_while_test
+
+.align 16,0x90
+.L_test_for_second_level_length:
+        /* else if ((op & 64) == 0) {
+         *   this = lcode[this.val + (hold & mask[op])];
+         * }
+         */
+        testb   $64, %al
+        jnz     .L_test_for_end_of_block  /* if ((op & 64) != 0) */
+
+        movl    $1, %eax
+        shll    %cl, %eax
+        decl    %eax
+        andl    hold_r, %eax            /* eax &= hold */
+        addl    %edx, %eax              /* eax += this.val */
+        movl    lcode(%esp), %edx       /* edx = lcode */
+        movl    (%edx,%eax,4), %eax     /* eax = lcode[val + (hold&mask[op])] */
+        jmp     .L_dolen
+
+.align 16,0x90
+.L_test_for_second_level_dist:
+        /* else if ((op & 64) == 0) {
+         *   this = dcode[this.val + (hold & mask[op])];
+         * }
+         */
+        testb   $64, %al
+        jnz     .L_invalid_distance_code  /* if ((op & 64) != 0) */
+
+        movl    $1, %eax
+        shll    %cl, %eax
+        decl    %eax
+        andl    hold_r, %eax            /* eax &= hold */
+        addl    %edx, %eax              /* eax += this.val */
+        movl    dcode(%esp), %edx       /* edx = dcode */
+        movl    (%edx,%eax,4), %eax     /* eax = dcode[val + (hold&mask[op])] */
+        jmp     .L_dodist
+
+.align 16,0x90
+.L_clip_window:
+        /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist
+         *       %ecx = nbytes
+         *
+         * else {
+         *   if (dist > wsize) {
+         *     invalid distance
+         *   }
+         *   from = window;
+         *   nbytes = dist - nbytes;
+         *   if (write == 0) {
+         *     from += wsize - nbytes;
+         */
+#define nbytes_r %ecx
+        movl    %eax, nbytes_r
+        movl    wsize(%esp), %eax       /* prepare for dist compare */
+        negl    nbytes_r                /* nbytes = -nbytes */
+        movl    window(%esp), from_r    /* from = window */
+
+        cmpl    dist_r, %eax
+        jb      .L_invalid_distance_too_far /* if (dist > wsize) */
+
+        addl    dist_r, nbytes_r        /* nbytes = dist - nbytes */
+        cmpl    $0, write(%esp)
+        jne     .L_wrap_around_window   /* if (write != 0) */
+
+        subl    nbytes_r, %eax
+        addl    %eax, from_r            /* from += wsize - nbytes */
+
+        /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist
+         *       %ecx = nbytes, %eax = len
+         *
+         *     if (nbytes < len) {
+         *       len -= nbytes;
+         *       do {
+         *         PUP(out) = PUP(from);
+         *       } while (--nbytes);
+         *       from = out - dist;
+         *     }
+         *   }
+         */
+#define len_r %eax
+        movl    len(%esp), len_r
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1             /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+        jmp     .L_do_copy1
+
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1             /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+        jmp     .L_do_copy1
+
+.L_wrap_around_window:
+        /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist
+         *       %ecx = nbytes, %eax = write, %eax = len
+         *
+         *   else if (write < nbytes) {
+         *     from += wsize + write - nbytes;
+         *     nbytes -= write;
+         *     if (nbytes < len) {
+         *       len -= nbytes;
+         *       do {
+         *         PUP(out) = PUP(from);
+         *       } while (--nbytes);
+         *       from = window;
+         *       nbytes = write;
+         *       if (nbytes < len) {
+         *         len -= nbytes;
+         *         do {
+         *           PUP(out) = PUP(from);
+         *         } while(--nbytes);
+         *         from = out - dist;
+         *       }
+         *     }
+         *   }
+         */
+#define write_r %eax
+        movl    write(%esp), write_r
+        cmpl    write_r, nbytes_r
+        jbe     .L_contiguous_in_window /* if (write >= nbytes) */
+
+        addl    wsize(%esp), from_r
+        addl    write_r, from_r
+        subl    nbytes_r, from_r        /* from += wsize + write - nbytes */
+        subl    write_r, nbytes_r       /* nbytes -= write */
+#undef write_r
+
+        movl    len(%esp), len_r
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1             /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    window(%esp), from_r    /* from = window */
+        movl    write(%esp), nbytes_r   /* nbytes = write */
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1             /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+        jmp     .L_do_copy1
+
+.L_contiguous_in_window:
+        /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist
+         *       %ecx = nbytes, %eax = write, %eax = len
+         *
+         *   else {
+         *     from += write - nbytes;
+         *     if (nbytes < len) {
+         *       len -= nbytes;
+         *       do {
+         *         PUP(out) = PUP(from);
+         *       } while (--nbytes);
+         *       from = out - dist;
+         *     }
+         *   }
+         */
+#define write_r %eax
+        addl    write_r, from_r
+        subl    nbytes_r, from_r        /* from += write - nbytes */
+#undef write_r
+
+        movl    len(%esp), len_r
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1             /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+
+.L_do_copy1:
+        /* regs: %esi = from, %esi = in, %ebp = hold, %bl = bits, %edi = out
+         *       %eax = len
+         *
+         *     while (len > 0) {
+         *       PUP(out) = PUP(from);
+         *       len--;
+         *     }
+         *   }
+         * } while (in < last && out < end);
+         */
+#undef nbytes_r
+#define in_r %esi
+        movl    len_r, %ecx
+        rep     movsb
+
+        movl    in(%esp), in_r          /* move in back to %esi, toss from */
+        jmp     .L_while_test
+
+#undef len_r
+#undef dist_r
+
+#endif /* NO_MMX || RUN_TIME_MMX */
+
+
+/*** MMX code ***/
+
+#if defined( USE_MMX ) || defined( RUN_TIME_MMX )
+
+.align 32,0x90
+.L_init_mmx:
+        emms
+
+#undef  bits_r
+#undef  bitslong_r
+#define bitslong_r %ebp
+#define hold_mm    %mm0
+        movd    %ebp, hold_mm
+        movl    %ebx, bitslong_r
+
+#define used_mm   %mm1
+#define dmask2_mm %mm2
+#define lmask2_mm %mm3
+#define lmask_mm  %mm4
+#define dmask_mm  %mm5
+#define tmp_mm    %mm6
+
+        movd    lmask(%esp), lmask_mm
+        movq    lmask_mm, lmask2_mm
+        movd    dmask(%esp), dmask_mm
+        movq    dmask_mm, dmask2_mm
+        pxor    used_mm, used_mm
+        movl    lcode(%esp), %ebx       /* ebx = lcode */
+        jmp     .L_do_loop_mmx
+
+.align 32,0x90
+.L_while_test_mmx:
+        /* while (in < last && out < end)
+         */
+        cmpl    out_r, end(%esp)
+        jbe     .L_break_loop           /* if (out >= end) */
+
+        cmpl    in_r, last(%esp)
+        jbe     .L_break_loop
+
+.L_do_loop_mmx:
+        psrlq   used_mm, hold_mm        /* hold_mm >>= last bit length */
+
+        cmpl    $32, bitslong_r
+        ja      .L_get_length_code_mmx  /* if (32 < bits) */
+
+        movd    bitslong_r, tmp_mm
+        movd    (in_r), %mm7
+        addl    $4, in_r
+        psllq   tmp_mm, %mm7
+        addl    $32, bitslong_r
+        por     %mm7, hold_mm           /* hold_mm |= *((uint *)in)++ << bits */
+
+.L_get_length_code_mmx:
+        pand    hold_mm, lmask_mm
+        movd    lmask_mm, %eax
+        movq    lmask2_mm, lmask_mm
+        movl    (%ebx,%eax,4), %eax     /* eax = lcode[hold & lmask] */
+
+.L_dolen_mmx:
+        movzbl  %ah, %ecx               /* ecx = this.bits */
+        movd    %ecx, used_mm
+        subl    %ecx, bitslong_r        /* bits -= this.bits */
+
+        testb   %al, %al
+        jnz     .L_test_for_length_base_mmx /* if (op != 0) 45.7% */
+
+        shrl    $16, %eax               /* output this.val char */
+        stosb
+        jmp     .L_while_test_mmx
+
+.L_test_for_length_base_mmx:
+#define len_r  %edx
+        movl    %eax, len_r             /* len = this */
+        shrl    $16, len_r              /* len = this.val */
+
+        testb   $16, %al
+        jz      .L_test_for_second_level_length_mmx /* if ((op & 16) == 0) 8% */
+        andl    $15, %eax               /* op &= 15 */
+        jz      .L_decode_distance_mmx  /* if (!op) */
+
+        psrlq   used_mm, hold_mm        /* hold_mm >>= last bit length */
+        movd    %eax, used_mm
+        movd    hold_mm, %ecx
+        subl    %eax, bitslong_r
+        andl    .L_mask(,%eax,4), %ecx
+        addl    %ecx, len_r             /* len += hold & mask[op] */
+
+.L_decode_distance_mmx:
+        psrlq   used_mm, hold_mm        /* hold_mm >>= last bit length */
+
+        cmpl    $32, bitslong_r
+        ja      .L_get_dist_code_mmx    /* if (32 < bits) */
+
+        movd    bitslong_r, tmp_mm
+        movd    (in_r), %mm7
+        addl    $4, in_r
+        psllq   tmp_mm, %mm7
+        addl    $32, bitslong_r
+        por     %mm7, hold_mm           /* hold_mm |= *((uint *)in)++ << bits */
+
+.L_get_dist_code_mmx:
+        movl    dcode(%esp), %ebx       /* ebx = dcode */
+        pand    hold_mm, dmask_mm
+        movd    dmask_mm, %eax
+        movq    dmask2_mm, dmask_mm
+        movl    (%ebx,%eax,4), %eax     /* eax = dcode[hold & lmask] */
+
+.L_dodist_mmx:
+#define dist_r %ebx
+        movzbl  %ah, %ecx               /* ecx = this.bits */
+        movl    %eax, dist_r
+        shrl    $16, dist_r             /* dist  = this.val */
+        subl    %ecx, bitslong_r        /* bits -= this.bits */
+        movd    %ecx, used_mm
+
+        testb   $16, %al                /* if ((op & 16) == 0) */
+        jz      .L_test_for_second_level_dist_mmx
+        andl    $15, %eax               /* op &= 15 */
+        jz      .L_check_dist_one_mmx
+
+.L_add_bits_to_dist_mmx:
+        psrlq   used_mm, hold_mm        /* hold_mm >>= last bit length */
+        movd    %eax, used_mm           /* save bit length of current op */
+        movd    hold_mm, %ecx           /* get the next bits on input stream */
+        subl    %eax, bitslong_r        /* bits -= op bits */
+        andl    .L_mask(,%eax,4), %ecx  /* ecx   = hold & mask[op] */
+        addl    %ecx, dist_r            /* dist += hold & mask[op] */
+
+.L_check_window_mmx:
+        movl    in_r, in(%esp)          /* save in so from can use it's reg */
+        movl    out_r, %eax
+        subl    beg(%esp), %eax         /* nbytes = out - beg */
+
+        cmpl    dist_r, %eax
+        jb      .L_clip_window_mmx      /* if (dist > nbytes) 4.2% */
+
+        movl    len_r, %ecx
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+
+        subl    $3, %ecx
+        movb    (from_r), %al
+        movb    %al, (out_r)
+        movb    1(from_r), %al
+        movb    2(from_r), %dl
+        addl    $3, from_r
+        movb    %al, 1(out_r)
+        movb    %dl, 2(out_r)
+        addl    $3, out_r
+        rep     movsb
+
+        movl    in(%esp), in_r          /* move in back to %esi, toss from */
+        movl    lcode(%esp), %ebx       /* move lcode back to %ebx, toss dist */
+        jmp     .L_while_test_mmx
+
+.align 16,0x90
+.L_check_dist_one_mmx:
+        cmpl    $1, dist_r
+        jne     .L_check_window_mmx
+        cmpl    out_r, beg(%esp)
+        je      .L_check_window_mmx
+
+        decl    out_r
+        movl    len_r, %ecx
+        movb    (out_r), %al
+        subl    $3, %ecx
+
+        movb    %al, 1(out_r)
+        movb    %al, 2(out_r)
+        movb    %al, 3(out_r)
+        addl    $4, out_r
+        rep     stosb
+
+        movl    lcode(%esp), %ebx       /* move lcode back to %ebx, toss dist */
+        jmp     .L_while_test_mmx
+
+.align 16,0x90
+.L_test_for_second_level_length_mmx:
+        testb   $64, %al
+        jnz     .L_test_for_end_of_block  /* if ((op & 64) != 0) */
+
+        andl    $15, %eax
+        psrlq   used_mm, hold_mm        /* hold_mm >>= last bit length */
+        movd    hold_mm, %ecx
+        andl    .L_mask(,%eax,4), %ecx
+        addl    len_r, %ecx
+        movl    (%ebx,%ecx,4), %eax     /* eax = lcode[hold & lmask] */
+        jmp     .L_dolen_mmx
+
+.align 16,0x90
+.L_test_for_second_level_dist_mmx:
+        testb   $64, %al
+        jnz     .L_invalid_distance_code  /* if ((op & 64) != 0) */
+
+        andl    $15, %eax
+        psrlq   used_mm, hold_mm        /* hold_mm >>= last bit length */
+        movd    hold_mm, %ecx
+        andl    .L_mask(,%eax,4), %ecx
+        movl    dcode(%esp), %eax       /* ecx = dcode */
+        addl    dist_r, %ecx
+        movl    (%eax,%ecx,4), %eax     /* eax = lcode[hold & lmask] */
+        jmp     .L_dodist_mmx
+
+.align 16,0x90
+.L_clip_window_mmx:
+#define nbytes_r %ecx
+        movl    %eax, nbytes_r
+        movl    wsize(%esp), %eax       /* prepare for dist compare */
+        negl    nbytes_r                /* nbytes = -nbytes */
+        movl    window(%esp), from_r    /* from = window */
+
+        cmpl    dist_r, %eax
+        jb      .L_invalid_distance_too_far /* if (dist > wsize) */
+
+        addl    dist_r, nbytes_r        /* nbytes = dist - nbytes */
+        cmpl    $0, write(%esp)
+        jne     .L_wrap_around_window_mmx /* if (write != 0) */
+
+        subl    nbytes_r, %eax
+        addl    %eax, from_r            /* from += wsize - nbytes */
+
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1_mmx         /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+        jmp     .L_do_copy1_mmx
+
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1_mmx         /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+        jmp     .L_do_copy1_mmx
+
+.L_wrap_around_window_mmx:
+#define write_r %eax
+        movl    write(%esp), write_r
+        cmpl    write_r, nbytes_r
+        jbe     .L_contiguous_in_window_mmx /* if (write >= nbytes) */
+
+        addl    wsize(%esp), from_r
+        addl    write_r, from_r
+        subl    nbytes_r, from_r        /* from += wsize + write - nbytes */
+        subl    write_r, nbytes_r       /* nbytes -= write */
+#undef write_r
+
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1_mmx         /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    window(%esp), from_r    /* from = window */
+        movl    write(%esp), nbytes_r   /* nbytes = write */
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1_mmx         /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+        jmp     .L_do_copy1_mmx
+
+.L_contiguous_in_window_mmx:
+#define write_r %eax
+        addl    write_r, from_r
+        subl    nbytes_r, from_r        /* from += write - nbytes */
+#undef write_r
+
+        cmpl    nbytes_r, len_r
+        jbe     .L_do_copy1_mmx         /* if (nbytes >= len) */
+
+        subl    nbytes_r, len_r         /* len -= nbytes */
+        rep     movsb
+        movl    out_r, from_r
+        subl    dist_r, from_r          /* from = out - dist */
+
+.L_do_copy1_mmx:
+#undef nbytes_r
+#define in_r %esi
+        movl    len_r, %ecx
+        rep     movsb
+
+        movl    in(%esp), in_r          /* move in back to %esi, toss from */
+        movl    lcode(%esp), %ebx       /* move lcode back to %ebx, toss dist */
+        jmp     .L_while_test_mmx
+
+#undef hold_r
+#undef bitslong_r
+
+#endif /* USE_MMX || RUN_TIME_MMX */
+
+
+/*** USE_MMX, NO_MMX, and RUNTIME_MMX from here on ***/
+
+.L_invalid_distance_code:
+        /* else {
+         *   strm->msg = "invalid distance code";
+         *   state->mode = BAD;
+         * }
+         */
+        movl    $.L_invalid_distance_code_msg, %ecx
+        movl    $INFLATE_MODE_BAD, %edx
+        jmp     .L_update_stream_state
+
+.L_test_for_end_of_block:
+        /* else if (op & 32) {
+         *   state->mode = TYPE;
+         *   break;
+         * }
+         */
+        testb   $32, %al
+        jz      .L_invalid_literal_length_code  /* if ((op & 32) == 0) */
+
+        movl    $0, %ecx
+        movl    $INFLATE_MODE_TYPE, %edx
+        jmp     .L_update_stream_state
+
+.L_invalid_literal_length_code:
+        /* else {
+         *   strm->msg = "invalid literal/length code";
+         *   state->mode = BAD;
+         * }
+         */
+        movl    $.L_invalid_literal_length_code_msg, %ecx
+        movl    $INFLATE_MODE_BAD, %edx
+        jmp     .L_update_stream_state
+
+.L_invalid_distance_too_far:
+        /* strm->msg = "invalid distance too far back";
+         * state->mode = BAD;
+         */
+        movl    in(%esp), in_r          /* from_r has in's reg, put in back */
+        movl    $.L_invalid_distance_too_far_msg, %ecx
+        movl    $INFLATE_MODE_BAD, %edx
+        jmp     .L_update_stream_state
+
+.L_update_stream_state:
+        /* set strm->msg = %ecx, strm->state->mode = %edx */
+        movl    strm_sp(%esp), %eax
+        testl   %ecx, %ecx              /* if (msg != NULL) */
+        jz      .L_skip_msg
+        movl    %ecx, msg_strm(%eax)    /* strm->msg = msg */
+.L_skip_msg:
+        movl    state_strm(%eax), %eax  /* state = strm->state */
+        movl    %edx, mode_state(%eax)  /* state->mode = edx (BAD | TYPE) */
+        jmp     .L_break_loop
+
+.align 32,0x90
+.L_break_loop:
+
+/*
+ * Regs:
+ *
+ * bits = %ebp when mmx, and in %ebx when non-mmx
+ * hold = %hold_mm when mmx, and in %ebp when non-mmx
+ * in   = %esi
+ * out  = %edi
+ */
+
+#if defined( USE_MMX ) || defined( RUN_TIME_MMX )
+
+#if defined( RUN_TIME_MMX )
+
+        cmpl    $DO_USE_MMX, inflate_fast_use_mmx
+        jne     .L_update_next_in
+
+#endif /* RUN_TIME_MMX */
+
+        movl    %ebp, %ebx
+
+.L_update_next_in:
+
+#endif
+
+#define strm_r  %eax
+#define state_r %edx
+
+        /* len = bits >> 3;
+         * in -= len;
+         * bits -= len << 3;
+         * hold &= (1U << bits) - 1;
+         * state->hold = hold;
+         * state->bits = bits;
+         * strm->next_in = in;
+         * strm->next_out = out;
+         */
+        movl    strm_sp(%esp), strm_r
+        movl    %ebx, %ecx
+        movl    state_strm(strm_r), state_r
+        shrl    $3, %ecx
+        subl    %ecx, in_r
+        shll    $3, %ecx
+        subl    %ecx, %ebx
+        movl    out_r, next_out_strm(strm_r)
+        movl    %ebx, bits_state(state_r)
+        movl    %ebx, %ecx
+
+        leal    buf(%esp), %ebx
+        cmpl    %ebx, last(%esp)
+        jne     .L_buf_not_used         /* if buf != last */
+
+        subl    %ebx, in_r              /* in -= buf */
+        movl    next_in_strm(strm_r), %ebx
+        movl    %ebx, last(%esp)        /* last = strm->next_in */
+        addl    %ebx, in_r              /* in += strm->next_in */
+        movl    avail_in_strm(strm_r), %ebx
+        subl    $11, %ebx
+        addl    %ebx, last(%esp)    /* last = &strm->next_in[ avail_in - 11 ] */
+
+.L_buf_not_used:
+        movl    in_r, next_in_strm(strm_r)
+
+        movl    $1, %ebx
+        shll    %cl, %ebx
+        decl    %ebx
+
+#if defined( USE_MMX ) || defined( RUN_TIME_MMX )
+
+#if defined( RUN_TIME_MMX )
+
+        cmpl    $DO_USE_MMX, inflate_fast_use_mmx
+        jne     .L_update_hold
+
+#endif /* RUN_TIME_MMX */
+
+        psrlq   used_mm, hold_mm        /* hold_mm >>= last bit length */
+        movd    hold_mm, %ebp
+
+        emms
+
+.L_update_hold:
+
+#endif /* USE_MMX || RUN_TIME_MMX */
+
+        andl    %ebx, %ebp
+        movl    %ebp, hold_state(state_r)
+
+#define last_r %ebx
+
+        /* strm->avail_in = in < last ? 11 + (last - in) : 11 - (in - last) */
+        movl    last(%esp), last_r
+        cmpl    in_r, last_r
+        jbe     .L_last_is_smaller     /* if (in >= last) */
+
+        subl    in_r, last_r           /* last -= in */
+        addl    $11, last_r            /* last += 11 */
+        movl    last_r, avail_in_strm(strm_r)
+        jmp     .L_fixup_out
+.L_last_is_smaller:
+        subl    last_r, in_r           /* in -= last */
+        negl    in_r                   /* in = -in */
+        addl    $11, in_r              /* in += 11 */
+        movl    in_r, avail_in_strm(strm_r)
+
+#undef last_r
+#define end_r %ebx
+
+.L_fixup_out:
+        /* strm->avail_out = out < end ? 257 + (end - out) : 257 - (out - end)*/
+        movl    end(%esp), end_r
+        cmpl    out_r, end_r
+        jbe     .L_end_is_smaller      /* if (out >= end) */
+
+        subl    out_r, end_r           /* end -= out */
+        addl    $257, end_r            /* end += 257 */
+        movl    end_r, avail_out_strm(strm_r)
+        jmp     .L_done
+.L_end_is_smaller:
+        subl    end_r, out_r           /* out -= end */
+        negl    out_r                  /* out = -out */
+        addl    $257, out_r            /* out += 257 */
+        movl    out_r, avail_out_strm(strm_r)
+
+#undef end_r
+#undef strm_r
+#undef state_r
+
+.L_done:
+        addl    $local_var_size, %esp
+        popf
+        popl    %ebx
+        popl    %ebp
+        popl    %esi
+        popl    %edi
+        ret
+
+#if defined( GAS_ELF )
+/* elf info */
+.type inflate_fast,@function
+.size inflate_fast,.-inflate_fast
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/test.cpp b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/test.cpp
new file mode 100644 (file)
index 0000000..7d265b3
--- /dev/null
@@ -0,0 +1,24 @@
+
+#include "zfstream.h"
+
+int main() {
+
+  // Construct a stream object with this filebuffer.  Anything sent
+  // to this stream will go to standard out.
+  gzofstream os( 1, ios::out );
+
+  // This text is getting compressed and sent to stdout.
+  // To prove this, run 'test | zcat'.
+  os << "Hello, Mommy" << endl;
+
+  os << setcompressionlevel( Z_NO_COMPRESSION );
+  os << "hello, hello, hi, ho!" << endl;
+
+  setcompressionlevel( os, Z_DEFAULT_COMPRESSION )
+    << "I'm compressing again" << endl;
+
+  os.close();
+
+  return 0;
+
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/zfstream.cpp b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/zfstream.cpp
new file mode 100644 (file)
index 0000000..d0cd85f
--- /dev/null
@@ -0,0 +1,329 @@
+
+#include "zfstream.h"
+
+gzfilebuf::gzfilebuf() :
+  file(NULL),
+  mode(0),
+  own_file_descriptor(0)
+{ }
+
+gzfilebuf::~gzfilebuf() {
+
+  sync();
+  if ( own_file_descriptor )
+    close();
+
+}
+
+gzfilebuf *gzfilebuf::open( const char *name,
+                            int io_mode ) {
+
+  if ( is_open() )
+    return NULL;
+
+  char char_mode[10];
+  char *p = char_mode;
+
+  if ( io_mode & ios::in ) {
+    mode = ios::in;
+    *p++ = 'r';
+  } else if ( io_mode & ios::app ) {
+    mode = ios::app;
+    *p++ = 'a';
+  } else {
+    mode = ios::out;
+    *p++ = 'w';
+  }
+
+  if ( io_mode & ios::binary ) {
+    mode |= ios::binary;
+    *p++ = 'b';
+  }
+
+  // Hard code the compression level
+  if ( io_mode & (ios::out|ios::app )) {
+    *p++ = '9';
+  }
+
+  // Put the end-of-string indicator
+  *p = '\0';
+
+  if ( (file = gzopen(name, char_mode)) == NULL )
+    return NULL;
+
+  own_file_descriptor = 1;
+
+  return this;
+
+}
+
+gzfilebuf *gzfilebuf::attach( int file_descriptor,
+                              int io_mode ) {
+
+  if ( is_open() )
+    return NULL;
+
+  char char_mode[10];
+  char *p = char_mode;
+
+  if ( io_mode & ios::in ) {
+    mode = ios::in;
+    *p++ = 'r';
+  } else if ( io_mode & ios::app ) {
+    mode = ios::app;
+    *p++ = 'a';
+  } else {
+    mode = ios::out;
+    *p++ = 'w';
+  }
+
+  if ( io_mode & ios::binary ) {
+    mode |= ios::binary;
+    *p++ = 'b';
+  }
+
+  // Hard code the compression level
+  if ( io_mode & (ios::out|ios::app )) {
+    *p++ = '9';
+  }
+
+  // Put the end-of-string indicator
+  *p = '\0';
+
+  if ( (file = gzdopen(file_descriptor, char_mode)) == NULL )
+    return NULL;
+
+  own_file_descriptor = 0;
+
+  return this;
+
+}
+
+gzfilebuf *gzfilebuf::close() {
+
+  if ( is_open() ) {
+
+    sync();
+    gzclose( file );
+    file = NULL;
+
+  }
+
+  return this;
+
+}
+
+int gzfilebuf::setcompressionlevel( int comp_level ) {
+
+  return gzsetparams(file, comp_level, -2);
+
+}
+
+int gzfilebuf::setcompressionstrategy( int comp_strategy ) {
+
+  return gzsetparams(file, -2, comp_strategy);
+
+}
+
+
+streampos gzfilebuf::seekoff( streamoff off, ios::seek_dir dir, int which ) {
+
+  return streampos(EOF);
+
+}
+
+int gzfilebuf::underflow() {
+
+  // If the file hasn't been opened for reading, error.
+  if ( !is_open() || !(mode & ios::in) )
+    return EOF;
+
+  // if a buffer doesn't exists, allocate one.
+  if ( !base() ) {
+
+    if ( (allocate()) == EOF )
+      return EOF;
+    setp(0,0);
+
+  } else {
+
+    if ( in_avail() )
+      return (unsigned char) *gptr();
+
+    if ( out_waiting() ) {
+      if ( flushbuf() == EOF )
+        return EOF;
+    }
+
+  }
+
+  // Attempt to fill the buffer.
+
+  int result = fillbuf();
+  if ( result == EOF ) {
+    // disable get area
+    setg(0,0,0);
+    return EOF;
+  }
+
+  return (unsigned char) *gptr();
+
+}
+
+int gzfilebuf::overflow( int c ) {
+
+  if ( !is_open() || !(mode & ios::out) )
+    return EOF;
+
+  if ( !base() ) {
+    if ( allocate() == EOF )
+      return EOF;
+    setg(0,0,0);
+  } else {
+    if (in_avail()) {
+        return EOF;
+    }
+    if (out_waiting()) {
+      if (flushbuf() == EOF)
+        return EOF;
+    }
+  }
+
+  int bl = blen();
+  setp( base(), base() + bl);
+
+  if ( c != EOF ) {
+
+    *pptr() = c;
+    pbump(1);
+
+  }
+
+  return 0;
+
+}
+
+int gzfilebuf::sync() {
+
+  if ( !is_open() )
+    return EOF;
+
+  if ( out_waiting() )
+    return flushbuf();
+
+  return 0;
+
+}
+
+int gzfilebuf::flushbuf() {
+
+  int n;
+  char *q;
+
+  q = pbase();
+  n = pptr() - q;
+
+  if ( gzwrite( file, q, n) < n )
+    return EOF;
+
+  setp(0,0);
+
+  return 0;
+
+}
+
+int gzfilebuf::fillbuf() {
+
+  int required;
+  char *p;
+
+  p = base();
+
+  required = blen();
+
+  int t = gzread( file, p, required );
+
+  if ( t <= 0) return EOF;
+
+  setg( base(), base(), base()+t);
+
+  return t;
+
+}
+
+gzfilestream_common::gzfilestream_common() :
+  ios( gzfilestream_common::rdbuf() )
+{ }
+
+gzfilestream_common::~gzfilestream_common()
+{ }
+
+void gzfilestream_common::attach( int fd, int io_mode ) {
+
+  if ( !buffer.attach( fd, io_mode) )
+    clear( ios::failbit | ios::badbit );
+  else
+    clear();
+
+}
+
+void gzfilestream_common::open( const char *name, int io_mode ) {
+
+  if ( !buffer.open( name, io_mode ) )
+    clear( ios::failbit | ios::badbit );
+  else
+    clear();
+
+}
+
+void gzfilestream_common::close() {
+
+  if ( !buffer.close() )
+    clear( ios::failbit | ios::badbit );
+
+}
+
+gzfilebuf *gzfilestream_common::rdbuf()
+{
+  return &buffer;
+}
+
+gzifstream::gzifstream() :
+  ios( gzfilestream_common::rdbuf() )
+{
+  clear( ios::badbit );
+}
+
+gzifstream::gzifstream( const char *name, int io_mode ) :
+  ios( gzfilestream_common::rdbuf() )
+{
+  gzfilestream_common::open( name, io_mode );
+}
+
+gzifstream::gzifstream( int fd, int io_mode ) :
+  ios( gzfilestream_common::rdbuf() )
+{
+  gzfilestream_common::attach( fd, io_mode );
+}
+
+gzifstream::~gzifstream() { }
+
+gzofstream::gzofstream() :
+  ios( gzfilestream_common::rdbuf() )
+{
+  clear( ios::badbit );
+}
+
+gzofstream::gzofstream( const char *name, int io_mode ) :
+  ios( gzfilestream_common::rdbuf() )
+{
+  gzfilestream_common::open( name, io_mode );
+}
+
+gzofstream::gzofstream( int fd, int io_mode ) :
+  ios( gzfilestream_common::rdbuf() )
+{
+  gzfilestream_common::attach( fd, io_mode );
+}
+
+gzofstream::~gzofstream() { }
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/zfstream.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream/zfstream.h
new file mode 100644 (file)
index 0000000..ed79098
--- /dev/null
@@ -0,0 +1,128 @@
+
+#ifndef zfstream_h
+#define zfstream_h
+
+#include <fstream.h>
+#include "zlib.h"
+
+class gzfilebuf : public streambuf {
+
+public:
+
+  gzfilebuf( );
+  virtual ~gzfilebuf();
+
+  gzfilebuf *open( const char *name, int io_mode );
+  gzfilebuf *attach( int file_descriptor, int io_mode );
+  gzfilebuf *close();
+
+  int setcompressionlevel( int comp_level );
+  int setcompressionstrategy( int comp_strategy );
+
+  inline int is_open() const { return (file !=NULL); }
+
+  virtual streampos seekoff( streamoff, ios::seek_dir, int );
+
+  virtual int sync();
+
+protected:
+
+  virtual int underflow();
+  virtual int overflow( int = EOF );
+
+private:
+
+  gzFile file;
+  short mode;
+  short own_file_descriptor;
+
+  int flushbuf();
+  int fillbuf();
+
+};
+
+class gzfilestream_common : virtual public ios {
+
+  friend class gzifstream;
+  friend class gzofstream;
+  friend gzofstream &setcompressionlevel( gzofstream &, int );
+  friend gzofstream &setcompressionstrategy( gzofstream &, int );
+
+public:
+  virtual ~gzfilestream_common();
+
+  void attach( int fd, int io_mode );
+  void open( const char *name, int io_mode );
+  void close();
+
+protected:
+  gzfilestream_common();
+
+private:
+  gzfilebuf *rdbuf();
+
+  gzfilebuf buffer;
+
+};
+
+class gzifstream : public gzfilestream_common, public istream {
+
+public:
+
+  gzifstream();
+  gzifstream( const char *name, int io_mode = ios::in );
+  gzifstream( int fd, int io_mode = ios::in );
+
+  virtual ~gzifstream();
+
+};
+
+class gzofstream : public gzfilestream_common, public ostream {
+
+public:
+
+  gzofstream();
+  gzofstream( const char *name, int io_mode = ios::out );
+  gzofstream( int fd, int io_mode = ios::out );
+
+  virtual ~gzofstream();
+
+};
+
+template<class T> class gzomanip {
+  friend gzofstream &operator<<(gzofstream &, const gzomanip<T> &);
+public:
+  gzomanip(gzofstream &(*f)(gzofstream &, T), T v) : func(f), val(v) { }
+private:
+  gzofstream &(*func)(gzofstream &, T);
+  T val;
+};
+
+template<class T> gzofstream &operator<<(gzofstream &s, const gzomanip<T> &m)
+{
+  return (*m.func)(s, m.val);
+}
+
+inline gzofstream &setcompressionlevel( gzofstream &s, int l )
+{
+  (s.rdbuf())->setcompressionlevel(l);
+  return s;
+}
+
+inline gzofstream &setcompressionstrategy( gzofstream &s, int l )
+{
+  (s.rdbuf())->setcompressionstrategy(l);
+  return s;
+}
+
+inline gzomanip<int> setcompressionlevel(int l)
+{
+  return gzomanip<int>(&setcompressionlevel,l);
+}
+
+inline gzomanip<int> setcompressionstrategy(int l)
+{
+  return gzomanip<int>(&setcompressionstrategy,l);
+}
+
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream2/zstream.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream2/zstream.h
new file mode 100644 (file)
index 0000000..43d2332
--- /dev/null
@@ -0,0 +1,307 @@
+/*
+ *
+ * Copyright (c) 1997
+ * Christian Michelsen Research AS
+ * Advanced Computing
+ * Fantoftvegen 38, 5036 BERGEN, Norway
+ * http://www.cmr.no
+ *
+ * Permission to use, copy, modify, distribute and sell this software
+ * and its documentation for any purpose is hereby granted without fee,
+ * provided that the above copyright notice appear in all copies and
+ * that both that copyright notice and this permission notice appear
+ * in supporting documentation.  Christian Michelsen Research AS makes no
+ * representations about the suitability of this software for any
+ * purpose.  It is provided "as is" without express or implied warranty.
+ *
+ */
+
+#ifndef ZSTREAM__H
+#define ZSTREAM__H
+
+/*
+ * zstream.h - C++ interface to the 'zlib' general purpose compression library
+ * $Id: zstream.h 1.1 1997-06-25 12:00:56+02 tyge Exp tyge $
+ */
+
+#include <strstream.h>
+#include <string.h>
+#include <stdio.h>
+#include "zlib.h"
+
+#if defined(_WIN32)
+#   include <fcntl.h>
+#   include <io.h>
+#   define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+#else
+#   define SET_BINARY_MODE(file)
+#endif
+
+class zstringlen {
+public:
+    zstringlen(class izstream&);
+    zstringlen(class ozstream&, const char*);
+    size_t value() const { return val.word; }
+private:
+    struct Val { unsigned char byte; size_t word; } val;
+};
+
+//  ----------------------------- izstream -----------------------------
+
+class izstream
+{
+    public:
+        izstream() : m_fp(0) {}
+        izstream(FILE* fp) : m_fp(0) { open(fp); }
+        izstream(const char* name) : m_fp(0) { open(name); }
+        ~izstream() { close(); }
+
+        /* Opens a gzip (.gz) file for reading.
+         * open() can be used to read a file which is not in gzip format;
+         * in this case read() will directly read from the file without
+         * decompression. errno can be checked to distinguish two error
+         * cases (if errno is zero, the zlib error is Z_MEM_ERROR).
+         */
+        void open(const char* name) {
+            if (m_fp) close();
+            m_fp = ::gzopen(name, "rb");
+        }
+
+        void open(FILE* fp) {
+            SET_BINARY_MODE(fp);
+            if (m_fp) close();
+            m_fp = ::gzdopen(fileno(fp), "rb");
+        }
+
+        /* Flushes all pending input if necessary, closes the compressed file
+         * and deallocates all the (de)compression state. The return value is
+         * the zlib error number (see function error() below).
+         */
+        int close() {
+            int r = ::gzclose(m_fp);
+            m_fp = 0; return r;
+        }
+
+        /* Binary read the given number of bytes from the compressed file.
+         */
+        int read(void* buf, size_t len) {
+            return ::gzread(m_fp, buf, len);
+        }
+
+        /* Returns the error message for the last error which occurred on the
+         * given compressed file. errnum is set to zlib error number. If an
+         * error occurred in the file system and not in the compression library,
+         * errnum is set to Z_ERRNO and the application may consult errno
+         * to get the exact error code.
+         */
+        const char* error(int* errnum) {
+            return ::gzerror(m_fp, errnum);
+        }
+
+        gzFile fp() { return m_fp; }
+
+    private:
+        gzFile m_fp;
+};
+
+/*
+ * Binary read the given (array of) object(s) from the compressed file.
+ * If the input file was not in gzip format, read() copies the objects number
+ * of bytes into the buffer.
+ * returns the number of uncompressed bytes actually read
+ * (0 for end of file, -1 for error).
+ */
+template <class T, class Items>
+inline int read(izstream& zs, T* x, Items items) {
+    return ::gzread(zs.fp(), x, items*sizeof(T));
+}
+
+/*
+ * Binary input with the '>' operator.
+ */
+template <class T>
+inline izstream& operator>(izstream& zs, T& x) {
+    ::gzread(zs.fp(), &x, sizeof(T));
+    return zs;
+}
+
+
+inline zstringlen::zstringlen(izstream& zs) {
+    zs > val.byte;
+    if (val.byte == 255) zs > val.word;
+    else val.word = val.byte;
+}
+
+/*
+ * Read length of string + the string with the '>' operator.
+ */
+inline izstream& operator>(izstream& zs, char* x) {
+    zstringlen len(zs);
+    ::gzread(zs.fp(), x, len.value());
+    x[len.value()] = '\0';
+    return zs;
+}
+
+inline char* read_string(izstream& zs) {
+    zstringlen len(zs);
+    char* x = new char[len.value()+1];
+    ::gzread(zs.fp(), x, len.value());
+    x[len.value()] = '\0';
+    return x;
+}
+
+// ----------------------------- ozstream -----------------------------
+
+class ozstream
+{
+    public:
+        ozstream() : m_fp(0), m_os(0) {
+        }
+        ozstream(FILE* fp, int level = Z_DEFAULT_COMPRESSION)
+            : m_fp(0), m_os(0) {
+            open(fp, level);
+        }
+        ozstream(const char* name, int level = Z_DEFAULT_COMPRESSION)
+            : m_fp(0), m_os(0) {
+            open(name, level);
+        }
+        ~ozstream() {
+            close();
+        }
+
+        /* Opens a gzip (.gz) file for writing.
+         * The compression level parameter should be in 0..9
+         * errno can be checked to distinguish two error cases
+         * (if errno is zero, the zlib error is Z_MEM_ERROR).
+         */
+        void open(const char* name, int level = Z_DEFAULT_COMPRESSION) {
+            char mode[4] = "wb\0";
+            if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level;
+            if (m_fp) close();
+            m_fp = ::gzopen(name, mode);
+        }
+
+        /* open from a FILE pointer.
+         */
+        void open(FILE* fp, int level = Z_DEFAULT_COMPRESSION) {
+            SET_BINARY_MODE(fp);
+            char mode[4] = "wb\0";
+            if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level;
+            if (m_fp) close();
+            m_fp = ::gzdopen(fileno(fp), mode);
+        }
+
+        /* Flushes all pending output if necessary, closes the compressed file
+         * and deallocates all the (de)compression state. The return value is
+         * the zlib error number (see function error() below).
+         */
+        int close() {
+            if (m_os) {
+                ::gzwrite(m_fp, m_os->str(), m_os->pcount());
+                delete[] m_os->str(); delete m_os; m_os = 0;
+            }
+            int r = ::gzclose(m_fp); m_fp = 0; return r;
+        }
+
+        /* Binary write the given number of bytes into the compressed file.
+         */
+        int write(const void* buf, size_t len) {
+            return ::gzwrite(m_fp, (voidp) buf, len);
+        }
+
+        /* Flushes all pending output into the compressed file. The parameter
+         * _flush is as in the deflate() function. The return value is the zlib
+         * error number (see function gzerror below). flush() returns Z_OK if
+         * the flush_ parameter is Z_FINISH and all output could be flushed.
+         * flush() should be called only when strictly necessary because it can
+         * degrade compression.
+         */
+        int flush(int _flush) {
+            os_flush();
+            return ::gzflush(m_fp, _flush);
+        }
+
+        /* Returns the error message for the last error which occurred on the
+         * given compressed file. errnum is set to zlib error number. If an
+         * error occurred in the file system and not in the compression library,
+         * errnum is set to Z_ERRNO and the application may consult errno
+         * to get the exact error code.
+         */
+        const char* error(int* errnum) {
+            return ::gzerror(m_fp, errnum);
+        }
+
+        gzFile fp() { return m_fp; }
+
+        ostream& os() {
+            if (m_os == 0) m_os = new ostrstream;
+            return *m_os;
+        }
+
+        void os_flush() {
+            if (m_os && m_os->pcount()>0) {
+                ostrstream* oss = new ostrstream;
+                oss->fill(m_os->fill());
+                oss->flags(m_os->flags());
+                oss->precision(m_os->precision());
+                oss->width(m_os->width());
+                ::gzwrite(m_fp, m_os->str(), m_os->pcount());
+                delete[] m_os->str(); delete m_os; m_os = oss;
+            }
+        }
+
+    private:
+        gzFile m_fp;
+        ostrstream* m_os;
+};
+
+/*
+ * Binary write the given (array of) object(s) into the compressed file.
+ * returns the number of uncompressed bytes actually written
+ * (0 in case of error).
+ */
+template <class T, class Items>
+inline int write(ozstream& zs, const T* x, Items items) {
+    return ::gzwrite(zs.fp(), (voidp) x, items*sizeof(T));
+}
+
+/*
+ * Binary output with the '<' operator.
+ */
+template <class T>
+inline ozstream& operator<(ozstream& zs, const T& x) {
+    ::gzwrite(zs.fp(), (voidp) &x, sizeof(T));
+    return zs;
+}
+
+inline zstringlen::zstringlen(ozstream& zs, const char* x) {
+    val.byte = 255;  val.word = ::strlen(x);
+    if (val.word < 255) zs < (val.byte = val.word);
+    else zs < val;
+}
+
+/*
+ * Write length of string + the string with the '<' operator.
+ */
+inline ozstream& operator<(ozstream& zs, const char* x) {
+    zstringlen len(zs, x);
+    ::gzwrite(zs.fp(), (voidp) x, len.value());
+    return zs;
+}
+
+#ifdef _MSC_VER
+inline ozstream& operator<(ozstream& zs, char* const& x) {
+    return zs < (const char*) x;
+}
+#endif
+
+/*
+ * Ascii write with the << operator;
+ */
+template <class T>
+inline ostream& operator<<(ozstream& zs, const T& x) {
+    zs.os_flush();
+    return zs.os() << x;
+}
+
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream2/zstream_test.cpp b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream2/zstream_test.cpp
new file mode 100644 (file)
index 0000000..6273f62
--- /dev/null
@@ -0,0 +1,25 @@
+#include "zstream.h"
+#include <math.h>
+#include <stdlib.h>
+#include <iomanip.h>
+
+void main() {
+    char h[256] = "Hello";
+    char* g = "Goodbye";
+    ozstream out("temp.gz");
+    out < "This works well" < h < g;
+    out.close();
+
+    izstream in("temp.gz"); // read it back
+    char *x = read_string(in), *y = new char[256], z[256];
+    in > y > z;
+    in.close();
+    cout << x << endl << y << endl << z << endl;
+
+    out.open("temp.gz"); // try ascii output; zcat temp.gz to see the results
+    out << setw(50) << setfill('#') << setprecision(20) << x << endl << y << endl << z << endl;
+    out << z << endl << y << endl << x << endl;
+    out << 1.1234567890123456789 << endl;
+
+    delete[] x; delete[] y;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/README b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/README
new file mode 100644 (file)
index 0000000..f7b319a
--- /dev/null
@@ -0,0 +1,35 @@
+These classes provide a C++ stream interface to the zlib library. It allows you
+to do things like:
+
+  gzofstream outf("blah.gz");
+  outf << "These go into the gzip file " << 123 << endl;
+
+It does this by deriving a specialized stream buffer for gzipped files, which is
+the way Stroustrup would have done it. :->
+
+The gzifstream and gzofstream classes were originally written by Kevin Ruland
+and made available in the zlib contrib/iostream directory. The older version still
+compiles under gcc 2.xx, but not under gcc 3.xx, which sparked the development of
+this version.
+
+The new classes are as standard-compliant as possible, closely following the
+approach of the standard library's fstream classes. It compiles under gcc versions
+3.2 and 3.3, but not under gcc 2.xx. This is mainly due to changes in the standard
+library naming scheme. The new version of gzifstream/gzofstream/gzfilebuf differs
+from the previous one in the following respects:
+- added showmanyc
+- added setbuf, with support for unbuffered output via setbuf(0,0)
+- a few bug fixes of stream behavior
+- gzipped output file opened with default compression level instead of maximum level
+- setcompressionlevel()/strategy() members replaced by single setcompression()
+
+The code is provided "as is", with the permission to use, copy, modify, distribute
+and sell it for any purpose without fee.
+
+Ludwig Schwardt
+<schwardt@sun.ac.za>
+
+DSP Lab
+Electrical & Electronic Engineering Department
+University of Stellenbosch
+South Africa
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/TODO b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/TODO
new file mode 100644 (file)
index 0000000..7032f97
--- /dev/null
@@ -0,0 +1,17 @@
+Possible upgrades to gzfilebuf:
+
+- The ability to do putback (e.g. putbackfail)
+
+- The ability to seek (zlib supports this, but could be slow/tricky)
+
+- Simultaneous read/write access (does it make sense?)
+
+- Support for ios_base::ate open mode
+
+- Locale support?
+
+- Check public interface to see which calls give problems
+  (due to dependence on library internals)
+
+- Override operator<<(ostream&, gzfilebuf*) to allow direct copying
+  of stream buffer to stream ( i.e. os << is.rdbuf(); )
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/test.cc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/test.cc
new file mode 100644 (file)
index 0000000..9423533
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Test program for gzifstream and gzofstream
+ *
+ * by Ludwig Schwardt <schwardt@sun.ac.za>
+ * original version by Kevin Ruland <kevin@rodin.wustl.edu>
+ */
+
+#include "zfstream.h"
+#include <iostream>      // for cout
+
+int main() {
+
+  gzofstream outf;
+  gzifstream inf;
+  char buf[80];
+
+  outf.open("test1.txt.gz");
+  outf << "The quick brown fox sidestepped the lazy canine\n"
+       << 1.3 << "\nPlan " << 9 << std::endl;
+  outf.close();
+  std::cout << "Wrote the following message to 'test1.txt.gz' (check with zcat or zless):\n"
+            << "The quick brown fox sidestepped the lazy canine\n"
+            << 1.3 << "\nPlan " << 9 << std::endl;
+
+  std::cout << "\nReading 'test1.txt.gz' (buffered) produces:\n";
+  inf.open("test1.txt.gz");
+  while (inf.getline(buf,80,'\n')) {
+    std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n";
+  }
+  inf.close();
+
+  outf.rdbuf()->pubsetbuf(0,0);
+  outf.open("test2.txt.gz");
+  outf << setcompression(Z_NO_COMPRESSION)
+       << "The quick brown fox sidestepped the lazy canine\n"
+       << 1.3 << "\nPlan " << 9 << std::endl;
+  outf.close();
+  std::cout << "\nWrote the same message to 'test2.txt.gz' in uncompressed form";
+
+  std::cout << "\nReading 'test2.txt.gz' (unbuffered) produces:\n";
+  inf.rdbuf()->pubsetbuf(0,0);
+  inf.open("test2.txt.gz");
+  while (inf.getline(buf,80,'\n')) {
+    std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n";
+  }
+  inf.close();
+
+  return 0;
+
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/zfstream.cc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/zfstream.cc
new file mode 100644 (file)
index 0000000..94eb933
--- /dev/null
@@ -0,0 +1,479 @@
+/*
+ * A C++ I/O streams interface to the zlib gz* functions
+ *
+ * by Ludwig Schwardt <schwardt@sun.ac.za>
+ * original version by Kevin Ruland <kevin@rodin.wustl.edu>
+ *
+ * This version is standard-compliant and compatible with gcc 3.x.
+ */
+
+#include "zfstream.h"
+#include <cstring>          // for strcpy, strcat, strlen (mode strings)
+#include <cstdio>           // for BUFSIZ
+
+// Internal buffer sizes (default and "unbuffered" versions)
+#define BIGBUFSIZE BUFSIZ
+#define SMALLBUFSIZE 1
+
+/*****************************************************************************/
+
+// Default constructor
+gzfilebuf::gzfilebuf()
+: file(NULL), io_mode(std::ios_base::openmode(0)), own_fd(false),
+  buffer(NULL), buffer_size(BIGBUFSIZE), own_buffer(true)
+{
+  // No buffers to start with
+  this->disable_buffer();
+}
+
+// Destructor
+gzfilebuf::~gzfilebuf()
+{
+  // Sync output buffer and close only if responsible for file
+  // (i.e. attached streams should be left open at this stage)
+  this->sync();
+  if (own_fd)
+    this->close();
+  // Make sure internal buffer is deallocated
+  this->disable_buffer();
+}
+
+// Set compression level and strategy
+int
+gzfilebuf::setcompression(int comp_level,
+                          int comp_strategy)
+{
+  return gzsetparams(file, comp_level, comp_strategy);
+}
+
+// Open gzipped file
+gzfilebuf*
+gzfilebuf::open(const char *name,
+                std::ios_base::openmode mode)
+{
+  // Fail if file already open
+  if (this->is_open())
+    return NULL;
+  // Don't support simultaneous read/write access (yet)
+  if ((mode & std::ios_base::in) && (mode & std::ios_base::out))
+    return NULL;
+
+  // Build mode string for gzopen and check it [27.8.1.3.2]
+  char char_mode[6] = "\0\0\0\0\0";
+  if (!this->open_mode(mode, char_mode))
+    return NULL;
+
+  // Attempt to open file
+  if ((file = gzopen(name, char_mode)) == NULL)
+    return NULL;
+
+  // On success, allocate internal buffer and set flags
+  this->enable_buffer();
+  io_mode = mode;
+  own_fd = true;
+  return this;
+}
+
+// Attach to gzipped file
+gzfilebuf*
+gzfilebuf::attach(int fd,
+                  std::ios_base::openmode mode)
+{
+  // Fail if file already open
+  if (this->is_open())
+    return NULL;
+  // Don't support simultaneous read/write access (yet)
+  if ((mode & std::ios_base::in) && (mode & std::ios_base::out))
+    return NULL;
+
+  // Build mode string for gzdopen and check it [27.8.1.3.2]
+  char char_mode[6] = "\0\0\0\0\0";
+  if (!this->open_mode(mode, char_mode))
+    return NULL;
+
+  // Attempt to attach to file
+  if ((file = gzdopen(fd, char_mode)) == NULL)
+    return NULL;
+
+  // On success, allocate internal buffer and set flags
+  this->enable_buffer();
+  io_mode = mode;
+  own_fd = false;
+  return this;
+}
+
+// Close gzipped file
+gzfilebuf*
+gzfilebuf::close()
+{
+  // Fail immediately if no file is open
+  if (!this->is_open())
+    return NULL;
+  // Assume success
+  gzfilebuf* retval = this;
+  // Attempt to sync and close gzipped file
+  if (this->sync() == -1)
+    retval = NULL;
+  if (gzclose(file) < 0)
+    retval = NULL;
+  // File is now gone anyway (postcondition [27.8.1.3.8])
+  file = NULL;
+  own_fd = false;
+  // Destroy internal buffer if it exists
+  this->disable_buffer();
+  return retval;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+// Convert int open mode to mode string
+bool
+gzfilebuf::open_mode(std::ios_base::openmode mode,
+                     char* c_mode) const
+{
+  bool testb = mode & std::ios_base::binary;
+  bool testi = mode & std::ios_base::in;
+  bool testo = mode & std::ios_base::out;
+  bool testt = mode & std::ios_base::trunc;
+  bool testa = mode & std::ios_base::app;
+
+  // Check for valid flag combinations - see [27.8.1.3.2] (Table 92)
+  // Original zfstream hardcoded the compression level to maximum here...
+  // Double the time for less than 1% size improvement seems
+  // excessive though - keeping it at the default level
+  // To change back, just append "9" to the next three mode strings
+  if (!testi && testo && !testt && !testa)
+    strcpy(c_mode, "w");
+  if (!testi && testo && !testt && testa)
+    strcpy(c_mode, "a");
+  if (!testi && testo && testt && !testa)
+    strcpy(c_mode, "w");
+  if (testi && !testo && !testt && !testa)
+    strcpy(c_mode, "r");
+  // No read/write mode yet
+//  if (testi && testo && !testt && !testa)
+//    strcpy(c_mode, "r+");
+//  if (testi && testo && testt && !testa)
+//    strcpy(c_mode, "w+");
+
+  // Mode string should be empty for invalid combination of flags
+  if (strlen(c_mode) == 0)
+    return false;
+  if (testb)
+    strcat(c_mode, "b");
+  return true;
+}
+
+// Determine number of characters in internal get buffer
+std::streamsize
+gzfilebuf::showmanyc()
+{
+  // Calls to underflow will fail if file not opened for reading
+  if (!this->is_open() || !(io_mode & std::ios_base::in))
+    return -1;
+  // Make sure get area is in use
+  if (this->gptr() && (this->gptr() < this->egptr()))
+    return std::streamsize(this->egptr() - this->gptr());
+  else
+    return 0;
+}
+
+// Fill get area from gzipped file
+gzfilebuf::int_type
+gzfilebuf::underflow()
+{
+  // If something is left in the get area by chance, return it
+  // (this shouldn't normally happen, as underflow is only supposed
+  // to be called when gptr >= egptr, but it serves as error check)
+  if (this->gptr() && (this->gptr() < this->egptr()))
+    return traits_type::to_int_type(*(this->gptr()));
+
+  // If the file hasn't been opened for reading, produce error
+  if (!this->is_open() || !(io_mode & std::ios_base::in))
+    return traits_type::eof();
+
+  // Attempt to fill internal buffer from gzipped file
+  // (buffer must be guaranteed to exist...)
+  int bytes_read = gzread(file, buffer, buffer_size);
+  // Indicates error or EOF
+  if (bytes_read <= 0)
+  {
+    // Reset get area
+    this->setg(buffer, buffer, buffer);
+    return traits_type::eof();
+  }
+  // Make all bytes read from file available as get area
+  this->setg(buffer, buffer, buffer + bytes_read);
+
+  // Return next character in get area
+  return traits_type::to_int_type(*(this->gptr()));
+}
+
+// Write put area to gzipped file
+gzfilebuf::int_type
+gzfilebuf::overflow(int_type c)
+{
+  // Determine whether put area is in use
+  if (this->pbase())
+  {
+    // Double-check pointer range
+    if (this->pptr() > this->epptr() || this->pptr() < this->pbase())
+      return traits_type::eof();
+    // Add extra character to buffer if not EOF
+    if (!traits_type::eq_int_type(c, traits_type::eof()))
+    {
+      *(this->pptr()) = traits_type::to_char_type(c);
+      this->pbump(1);
+    }
+    // Number of characters to write to file
+    int bytes_to_write = this->pptr() - this->pbase();
+    // Overflow doesn't fail if nothing is to be written
+    if (bytes_to_write > 0)
+    {
+      // If the file hasn't been opened for writing, produce error
+      if (!this->is_open() || !(io_mode & std::ios_base::out))
+        return traits_type::eof();
+      // If gzipped file won't accept all bytes written to it, fail
+      if (gzwrite(file, this->pbase(), bytes_to_write) != bytes_to_write)
+        return traits_type::eof();
+      // Reset next pointer to point to pbase on success
+      this->pbump(-bytes_to_write);
+    }
+  }
+  // Write extra character to file if not EOF
+  else if (!traits_type::eq_int_type(c, traits_type::eof()))
+  {
+    // If the file hasn't been opened for writing, produce error
+    if (!this->is_open() || !(io_mode & std::ios_base::out))
+      return traits_type::eof();
+    // Impromptu char buffer (allows "unbuffered" output)
+    char_type last_char = traits_type::to_char_type(c);
+    // If gzipped file won't accept this character, fail
+    if (gzwrite(file, &last_char, 1) != 1)
+      return traits_type::eof();
+  }
+
+  // If you got here, you have succeeded (even if c was EOF)
+  // The return value should therefore be non-EOF
+  if (traits_type::eq_int_type(c, traits_type::eof()))
+    return traits_type::not_eof(c);
+  else
+    return c;
+}
+
+// Assign new buffer
+std::streambuf*
+gzfilebuf::setbuf(char_type* p,
+                  std::streamsize n)
+{
+  // First make sure stuff is sync'ed, for safety
+  if (this->sync() == -1)
+    return NULL;
+  // If buffering is turned off on purpose via setbuf(0,0), still allocate one...
+  // "Unbuffered" only really refers to put [27.8.1.4.10], while get needs at
+  // least a buffer of size 1 (very inefficient though, therefore make it bigger?)
+  // This follows from [27.5.2.4.3]/12 (gptr needs to point at something, it seems)
+  if (!p || !n)
+  {
+    // Replace existing buffer (if any) with small internal buffer
+    this->disable_buffer();
+    buffer = NULL;
+    buffer_size = 0;
+    own_buffer = true;
+    this->enable_buffer();
+  }
+  else
+  {
+    // Replace existing buffer (if any) with external buffer
+    this->disable_buffer();
+    buffer = p;
+    buffer_size = n;
+    own_buffer = false;
+    this->enable_buffer();
+  }
+  return this;
+}
+
+// Write put area to gzipped file (i.e. ensures that put area is empty)
+int
+gzfilebuf::sync()
+{
+  return traits_type::eq_int_type(this->overflow(), traits_type::eof()) ? -1 : 0;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+// Allocate internal buffer
+void
+gzfilebuf::enable_buffer()
+{
+  // If internal buffer required, allocate one
+  if (own_buffer && !buffer)
+  {
+    // Check for buffered vs. "unbuffered"
+    if (buffer_size > 0)
+    {
+      // Allocate internal buffer
+      buffer = new char_type[buffer_size];
+      // Get area starts empty and will be expanded by underflow as need arises
+      this->setg(buffer, buffer, buffer);
+      // Setup entire internal buffer as put area.
+      // The one-past-end pointer actually points to the last element of the buffer,
+      // so that overflow(c) can safely add the extra character c to the sequence.
+      // These pointers remain in place for the duration of the buffer
+      this->setp(buffer, buffer + buffer_size - 1);
+    }
+    else
+    {
+      // Even in "unbuffered" case, (small?) get buffer is still required
+      buffer_size = SMALLBUFSIZE;
+      buffer = new char_type[buffer_size];
+      this->setg(buffer, buffer, buffer);
+      // "Unbuffered" means no put buffer
+      this->setp(0, 0);
+    }
+  }
+  else
+  {
+    // If buffer already allocated, reset buffer pointers just to make sure no
+    // stale chars are lying around
+    this->setg(buffer, buffer, buffer);
+    this->setp(buffer, buffer + buffer_size - 1);
+  }
+}
+
+// Destroy internal buffer
+void
+gzfilebuf::disable_buffer()
+{
+  // If internal buffer exists, deallocate it
+  if (own_buffer && buffer)
+  {
+    // Preserve unbuffered status by zeroing size
+    if (!this->pbase())
+      buffer_size = 0;
+    delete[] buffer;
+    buffer = NULL;
+    this->setg(0, 0, 0);
+    this->setp(0, 0);
+  }
+  else
+  {
+    // Reset buffer pointers to initial state if external buffer exists
+    this->setg(buffer, buffer, buffer);
+    if (buffer)
+      this->setp(buffer, buffer + buffer_size - 1);
+    else
+      this->setp(0, 0);
+  }
+}
+
+/*****************************************************************************/
+
+// Default constructor initializes stream buffer
+gzifstream::gzifstream()
+: std::istream(NULL), sb()
+{ this->init(&sb); }
+
+// Initialize stream buffer and open file
+gzifstream::gzifstream(const char* name,
+                       std::ios_base::openmode mode)
+: std::istream(NULL), sb()
+{
+  this->init(&sb);
+  this->open(name, mode);
+}
+
+// Initialize stream buffer and attach to file
+gzifstream::gzifstream(int fd,
+                       std::ios_base::openmode mode)
+: std::istream(NULL), sb()
+{
+  this->init(&sb);
+  this->attach(fd, mode);
+}
+
+// Open file and go into fail() state if unsuccessful
+void
+gzifstream::open(const char* name,
+                 std::ios_base::openmode mode)
+{
+  if (!sb.open(name, mode | std::ios_base::in))
+    this->setstate(std::ios_base::failbit);
+  else
+    this->clear();
+}
+
+// Attach to file and go into fail() state if unsuccessful
+void
+gzifstream::attach(int fd,
+                   std::ios_base::openmode mode)
+{
+  if (!sb.attach(fd, mode | std::ios_base::in))
+    this->setstate(std::ios_base::failbit);
+  else
+    this->clear();
+}
+
+// Close file
+void
+gzifstream::close()
+{
+  if (!sb.close())
+    this->setstate(std::ios_base::failbit);
+}
+
+/*****************************************************************************/
+
+// Default constructor initializes stream buffer
+gzofstream::gzofstream()
+: std::ostream(NULL), sb()
+{ this->init(&sb); }
+
+// Initialize stream buffer and open file
+gzofstream::gzofstream(const char* name,
+                       std::ios_base::openmode mode)
+: std::ostream(NULL), sb()
+{
+  this->init(&sb);
+  this->open(name, mode);
+}
+
+// Initialize stream buffer and attach to file
+gzofstream::gzofstream(int fd,
+                       std::ios_base::openmode mode)
+: std::ostream(NULL), sb()
+{
+  this->init(&sb);
+  this->attach(fd, mode);
+}
+
+// Open file and go into fail() state if unsuccessful
+void
+gzofstream::open(const char* name,
+                 std::ios_base::openmode mode)
+{
+  if (!sb.open(name, mode | std::ios_base::out))
+    this->setstate(std::ios_base::failbit);
+  else
+    this->clear();
+}
+
+// Attach to file and go into fail() state if unsuccessful
+void
+gzofstream::attach(int fd,
+                   std::ios_base::openmode mode)
+{
+  if (!sb.attach(fd, mode | std::ios_base::out))
+    this->setstate(std::ios_base::failbit);
+  else
+    this->clear();
+}
+
+// Close file
+void
+gzofstream::close()
+{
+  if (!sb.close())
+    this->setstate(std::ios_base::failbit);
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/zfstream.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/iostream3/zfstream.h
new file mode 100644 (file)
index 0000000..8574479
--- /dev/null
@@ -0,0 +1,466 @@
+/*
+ * A C++ I/O streams interface to the zlib gz* functions
+ *
+ * by Ludwig Schwardt <schwardt@sun.ac.za>
+ * original version by Kevin Ruland <kevin@rodin.wustl.edu>
+ *
+ * This version is standard-compliant and compatible with gcc 3.x.
+ */
+
+#ifndef ZFSTREAM_H
+#define ZFSTREAM_H
+
+#include <istream>  // not iostream, since we don't need cin/cout
+#include <ostream>
+#include "zlib.h"
+
+/*****************************************************************************/
+
+/**
+ *  @brief  Gzipped file stream buffer class.
+ *
+ *  This class implements basic_filebuf for gzipped files. It doesn't yet support
+ *  seeking (allowed by zlib but slow/limited), putback and read/write access
+ *  (tricky). Otherwise, it attempts to be a drop-in replacement for the standard
+ *  file streambuf.
+*/
+class gzfilebuf : public std::streambuf
+{
+public:
+  //  Default constructor.
+  gzfilebuf();
+
+  //  Destructor.
+  virtual
+  ~gzfilebuf();
+
+  /**
+   *  @brief  Set compression level and strategy on the fly.
+   *  @param  comp_level  Compression level (see zlib.h for allowed values)
+   *  @param  comp_strategy  Compression strategy (see zlib.h for allowed values)
+   *  @return  Z_OK on success, Z_STREAM_ERROR otherwise.
+   *
+   *  Unfortunately, these parameters cannot be modified separately, as the
+   *  previous zfstream version assumed. Since the strategy is seldom changed,
+   *  it can default and setcompression(level) then becomes like the old
+   *  setcompressionlevel(level).
+  */
+  int
+  setcompression(int comp_level,
+                 int comp_strategy = Z_DEFAULT_STRATEGY);
+
+  /**
+   *  @brief  Check if file is open.
+   *  @return  True if file is open.
+  */
+  bool
+  is_open() const { return (file != NULL); }
+
+  /**
+   *  @brief  Open gzipped file.
+   *  @param  name  File name.
+   *  @param  mode  Open mode flags.
+   *  @return  @c this on success, NULL on failure.
+  */
+  gzfilebuf*
+  open(const char* name,
+       std::ios_base::openmode mode);
+
+  /**
+   *  @brief  Attach to already open gzipped file.
+   *  @param  fd  File descriptor.
+   *  @param  mode  Open mode flags.
+   *  @return  @c this on success, NULL on failure.
+  */
+  gzfilebuf*
+  attach(int fd,
+         std::ios_base::openmode mode);
+
+  /**
+   *  @brief  Close gzipped file.
+   *  @return  @c this on success, NULL on failure.
+  */
+  gzfilebuf*
+  close();
+
+protected:
+  /**
+   *  @brief  Convert ios open mode int to mode string used by zlib.
+   *  @return  True if valid mode flag combination.
+  */
+  bool
+  open_mode(std::ios_base::openmode mode,
+            char* c_mode) const;
+
+  /**
+   *  @brief  Number of characters available in stream buffer.
+   *  @return  Number of characters.
+   *
+   *  This indicates number of characters in get area of stream buffer.
+   *  These characters can be read without accessing the gzipped file.
+  */
+  virtual std::streamsize
+  showmanyc();
+
+  /**
+   *  @brief  Fill get area from gzipped file.
+   *  @return  First character in get area on success, EOF on error.
+   *
+   *  This actually reads characters from gzipped file to stream
+   *  buffer. Always buffered.
+  */
+  virtual int_type
+  underflow();
+
+  /**
+   *  @brief  Write put area to gzipped file.
+   *  @param  c  Extra character to add to buffer contents.
+   *  @return  Non-EOF on success, EOF on error.
+   *
+   *  This actually writes characters in stream buffer to
+   *  gzipped file. With unbuffered output this is done one
+   *  character at a time.
+  */
+  virtual int_type
+  overflow(int_type c = traits_type::eof());
+
+  /**
+   *  @brief  Installs external stream buffer.
+   *  @param  p  Pointer to char buffer.
+   *  @param  n  Size of external buffer.
+   *  @return  @c this on success, NULL on failure.
+   *
+   *  Call setbuf(0,0) to enable unbuffered output.
+  */
+  virtual std::streambuf*
+  setbuf(char_type* p,
+         std::streamsize n);
+
+  /**
+   *  @brief  Flush stream buffer to file.
+   *  @return  0 on success, -1 on error.
+   *
+   *  This calls underflow(EOF) to do the job.
+  */
+  virtual int
+  sync();
+
+//
+// Some future enhancements
+//
+//  virtual int_type uflow();
+//  virtual int_type pbackfail(int_type c = traits_type::eof());
+//  virtual pos_type
+//  seekoff(off_type off,
+//          std::ios_base::seekdir way,
+//          std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out);
+//  virtual pos_type
+//  seekpos(pos_type sp,
+//          std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out);
+
+private:
+  /**
+   *  @brief  Allocate internal buffer.
+   *
+   *  This function is safe to call multiple times. It will ensure
+   *  that a proper internal buffer exists if it is required. If the
+   *  buffer already exists or is external, the buffer pointers will be
+   *  reset to their original state.
+  */
+  void
+  enable_buffer();
+
+  /**
+   *  @brief  Destroy internal buffer.
+   *
+   *  This function is safe to call multiple times. It will ensure
+   *  that the internal buffer is deallocated if it exists. In any
+   *  case, it will also reset the buffer pointers.
+  */
+  void
+  disable_buffer();
+
+  /**
+   *  Underlying file pointer.
+  */
+  gzFile file;
+
+  /**
+   *  Mode in which file was opened.
+  */
+  std::ios_base::openmode io_mode;
+
+  /**
+   *  @brief  True if this object owns file descriptor.
+   *
+   *  This makes the class responsible for closing the file
+   *  upon destruction.
+  */
+  bool own_fd;
+
+  /**
+   *  @brief  Stream buffer.
+   *
+   *  For simplicity this remains allocated on the free store for the
+   *  entire life span of the gzfilebuf object, unless replaced by setbuf.
+  */
+  char_type* buffer;
+
+  /**
+   *  @brief  Stream buffer size.
+   *
+   *  Defaults to system default buffer size (typically 8192 bytes).
+   *  Modified by setbuf.
+  */
+  std::streamsize buffer_size;
+
+  /**
+   *  @brief  True if this object owns stream buffer.
+   *
+   *  This makes the class responsible for deleting the buffer
+   *  upon destruction.
+  */
+  bool own_buffer;
+};
+
+/*****************************************************************************/
+
+/**
+ *  @brief  Gzipped file input stream class.
+ *
+ *  This class implements ifstream for gzipped files. Seeking and putback
+ *  is not supported yet.
+*/
+class gzifstream : public std::istream
+{
+public:
+  //  Default constructor
+  gzifstream();
+
+  /**
+   *  @brief  Construct stream on gzipped file to be opened.
+   *  @param  name  File name.
+   *  @param  mode  Open mode flags (forced to contain ios::in).
+  */
+  explicit
+  gzifstream(const char* name,
+             std::ios_base::openmode mode = std::ios_base::in);
+
+  /**
+   *  @brief  Construct stream on already open gzipped file.
+   *  @param  fd    File descriptor.
+   *  @param  mode  Open mode flags (forced to contain ios::in).
+  */
+  explicit
+  gzifstream(int fd,
+             std::ios_base::openmode mode = std::ios_base::in);
+
+  /**
+   *  Obtain underlying stream buffer.
+  */
+  gzfilebuf*
+  rdbuf() const
+  { return const_cast<gzfilebuf*>(&sb); }
+
+  /**
+   *  @brief  Check if file is open.
+   *  @return  True if file is open.
+  */
+  bool
+  is_open() { return sb.is_open(); }
+
+  /**
+   *  @brief  Open gzipped file.
+   *  @param  name  File name.
+   *  @param  mode  Open mode flags (forced to contain ios::in).
+   *
+   *  Stream will be in state good() if file opens successfully;
+   *  otherwise in state fail(). This differs from the behavior of
+   *  ifstream, which never sets the state to good() and therefore
+   *  won't allow you to reuse the stream for a second file unless
+   *  you manually clear() the state. The choice is a matter of
+   *  convenience.
+  */
+  void
+  open(const char* name,
+       std::ios_base::openmode mode = std::ios_base::in);
+
+  /**
+   *  @brief  Attach to already open gzipped file.
+   *  @param  fd  File descriptor.
+   *  @param  mode  Open mode flags (forced to contain ios::in).
+   *
+   *  Stream will be in state good() if attach succeeded; otherwise
+   *  in state fail().
+  */
+  void
+  attach(int fd,
+         std::ios_base::openmode mode = std::ios_base::in);
+
+  /**
+   *  @brief  Close gzipped file.
+   *
+   *  Stream will be in state fail() if close failed.
+  */
+  void
+  close();
+
+private:
+  /**
+   *  Underlying stream buffer.
+  */
+  gzfilebuf sb;
+};
+
+/*****************************************************************************/
+
+/**
+ *  @brief  Gzipped file output stream class.
+ *
+ *  This class implements ofstream for gzipped files. Seeking and putback
+ *  is not supported yet.
+*/
+class gzofstream : public std::ostream
+{
+public:
+  //  Default constructor
+  gzofstream();
+
+  /**
+   *  @brief  Construct stream on gzipped file to be opened.
+   *  @param  name  File name.
+   *  @param  mode  Open mode flags (forced to contain ios::out).
+  */
+  explicit
+  gzofstream(const char* name,
+             std::ios_base::openmode mode = std::ios_base::out);
+
+  /**
+   *  @brief  Construct stream on already open gzipped file.
+   *  @param  fd    File descriptor.
+   *  @param  mode  Open mode flags (forced to contain ios::out).
+  */
+  explicit
+  gzofstream(int fd,
+             std::ios_base::openmode mode = std::ios_base::out);
+
+  /**
+   *  Obtain underlying stream buffer.
+  */
+  gzfilebuf*
+  rdbuf() const
+  { return const_cast<gzfilebuf*>(&sb); }
+
+  /**
+   *  @brief  Check if file is open.
+   *  @return  True if file is open.
+  */
+  bool
+  is_open() { return sb.is_open(); }
+
+  /**
+   *  @brief  Open gzipped file.
+   *  @param  name  File name.
+   *  @param  mode  Open mode flags (forced to contain ios::out).
+   *
+   *  Stream will be in state good() if file opens successfully;
+   *  otherwise in state fail(). This differs from the behavior of
+   *  ofstream, which never sets the state to good() and therefore
+   *  won't allow you to reuse the stream for a second file unless
+   *  you manually clear() the state. The choice is a matter of
+   *  convenience.
+  */
+  void
+  open(const char* name,
+       std::ios_base::openmode mode = std::ios_base::out);
+
+  /**
+   *  @brief  Attach to already open gzipped file.
+   *  @param  fd  File descriptor.
+   *  @param  mode  Open mode flags (forced to contain ios::out).
+   *
+   *  Stream will be in state good() if attach succeeded; otherwise
+   *  in state fail().
+  */
+  void
+  attach(int fd,
+         std::ios_base::openmode mode = std::ios_base::out);
+
+  /**
+   *  @brief  Close gzipped file.
+   *
+   *  Stream will be in state fail() if close failed.
+  */
+  void
+  close();
+
+private:
+  /**
+   *  Underlying stream buffer.
+  */
+  gzfilebuf sb;
+};
+
+/*****************************************************************************/
+
+/**
+ *  @brief  Gzipped file output stream manipulator class.
+ *
+ *  This class defines a two-argument manipulator for gzofstream. It is used
+ *  as base for the setcompression(int,int) manipulator.
+*/
+template<typename T1, typename T2>
+  class gzomanip2
+  {
+  public:
+    // Allows insertor to peek at internals
+    template <typename Ta, typename Tb>
+      friend gzofstream&
+      operator<<(gzofstream&,
+                 const gzomanip2<Ta,Tb>&);
+
+    // Constructor
+    gzomanip2(gzofstream& (*f)(gzofstream&, T1, T2),
+              T1 v1,
+              T2 v2);
+  private:
+    // Underlying manipulator function
+    gzofstream&
+    (*func)(gzofstream&, T1, T2);
+
+    // Arguments for manipulator function
+    T1 val1;
+    T2 val2;
+  };
+
+/*****************************************************************************/
+
+// Manipulator function thunks through to stream buffer
+inline gzofstream&
+setcompression(gzofstream &gzs, int l, int s = Z_DEFAULT_STRATEGY)
+{
+  (gzs.rdbuf())->setcompression(l, s);
+  return gzs;
+}
+
+// Manipulator constructor stores arguments
+template<typename T1, typename T2>
+  inline
+  gzomanip2<T1,T2>::gzomanip2(gzofstream &(*f)(gzofstream &, T1, T2),
+                              T1 v1,
+                              T2 v2)
+  : func(f), val1(v1), val2(v2)
+  { }
+
+// Insertor applies underlying manipulator function to stream
+template<typename T1, typename T2>
+  inline gzofstream&
+  operator<<(gzofstream& s, const gzomanip2<T1,T2>& m)
+  { return (*m.func)(s, m.val1, m.val2); }
+
+// Insert this onto stream to simplify setting of compression level
+inline gzomanip2<int,int>
+setcompression(int l, int s = Z_DEFAULT_STRATEGY)
+{ return gzomanip2<int,int>(&setcompression, l, s); }
+
+#endif // ZFSTREAM_H
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/bld_ml64.bat b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/bld_ml64.bat
new file mode 100644 (file)
index 0000000..8f9343d
--- /dev/null
@@ -0,0 +1,2 @@
+ml64.exe /Flinffasx64 /c /Zi inffasx64.asm\r
+ml64.exe /Flgvmat64   /c /Zi gvmat64.asm\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.asm b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.asm
new file mode 100644 (file)
index 0000000..9879c28
--- /dev/null
@@ -0,0 +1,553 @@
+;uInt longest_match_x64(\r
+;    deflate_state *s,\r
+;    IPos cur_match);                             /* current match */\r
+\r
+; gvmat64.asm -- Asm portion of the optimized longest_match for 32 bits x86_64\r
+;  (AMD64 on Athlon 64, Opteron, Phenom\r
+;     and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7)\r
+; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant.\r
+;\r
+; File written by Gilles Vollant, by converting to assembly the longest_match\r
+;  from Jean-loup Gailly in deflate.c of zLib and infoZip zip.\r
+;\r
+;  and by taking inspiration on asm686 with masm, optimised assembly code\r
+;        from Brian Raiter, written 1998\r
+;\r
+;  This software is provided 'as-is', without any express or implied\r
+;  warranty.  In no event will the authors be held liable for any damages\r
+;  arising from the use of this software.\r
+;\r
+;  Permission is granted to anyone to use this software for any purpose,\r
+;  including commercial applications, and to alter it and redistribute it\r
+;  freely, subject to the following restrictions:\r
+;\r
+;  1. The origin of this software must not be misrepresented; you must not\r
+;     claim that you wrote the original software. If you use this software\r
+;     in a product, an acknowledgment in the product documentation would be\r
+;     appreciated but is not required.\r
+;  2. Altered source versions must be plainly marked as such, and must not be\r
+;     misrepresented as being the original software\r
+;  3. This notice may not be removed or altered from any source distribution.\r
+;\r
+;\r
+;\r
+;         http://www.zlib.net\r
+;         http://www.winimage.com/zLibDll\r
+;         http://www.muppetlabs.com/~breadbox/software/assembly.html\r
+;\r
+; to compile this file for infozip Zip, I use option:\r
+;   ml64.exe /Flgvmat64 /c /Zi /DINFOZIP gvmat64.asm\r
+;\r
+; to compile this file for zLib, I use option:\r
+;   ml64.exe /Flgvmat64 /c /Zi gvmat64.asm\r
+; Be carrefull to adapt zlib1222add below to your version of zLib\r
+;   (if you use a version of zLib before 1.0.4 or after 1.2.2.2, change\r
+;    value of zlib1222add later)\r
+;\r
+; This file compile with Microsoft Macro Assembler (x64) for AMD64\r
+;\r
+;   ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK\r
+;\r
+;   (you can get Windows WDK with ml64 for AMD64 from\r
+;      http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price)\r
+;\r
+\r
+\r
+;uInt longest_match(s, cur_match)\r
+;    deflate_state *s;\r
+;    IPos cur_match;                             /* current match */\r
+.code\r
+longest_match PROC\r
+\r
+\r
+;LocalVarsSize   equ 88\r
+ LocalVarsSize   equ 72\r
+\r
+; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12\r
+; free register :  r14,r15\r
+; register can be saved : rsp\r
+\r
+ chainlenwmask   equ  rsp + 8 - LocalVarsSize    ; high word: current chain len\r
+                                                 ; low word: s->wmask\r
+;window          equ  rsp + xx - LocalVarsSize   ; local copy of s->window ; stored in r10\r
+;windowbestlen   equ  rsp + xx - LocalVarsSize   ; s->window + bestlen , use r10+r11\r
+;scanstart       equ  rsp + xx - LocalVarsSize   ; first two bytes of string ; stored in r12w\r
+;scanend         equ  rsp + xx - LocalVarsSize   ; last two bytes of string use ebx\r
+;scanalign       equ  rsp + xx - LocalVarsSize   ; dword-misalignment of string r13\r
+;bestlen         equ  rsp + xx - LocalVarsSize   ; size of best match so far -> r11d\r
+;scan            equ  rsp + xx - LocalVarsSize   ; ptr to string wanting match -> r9\r
+IFDEF INFOZIP\r
+ELSE\r
+ nicematch       equ  (rsp + 16 - LocalVarsSize) ; a good enough match size\r
+ENDIF\r
+\r
+save_rdi        equ  rsp + 24 - LocalVarsSize\r
+save_rsi        equ  rsp + 32 - LocalVarsSize\r
+save_rbx        equ  rsp + 40 - LocalVarsSize\r
+save_rbp        equ  rsp + 48 - LocalVarsSize\r
+save_r12        equ  rsp + 56 - LocalVarsSize\r
+save_r13        equ  rsp + 64 - LocalVarsSize\r
+;save_r14        equ  rsp + 72 - LocalVarsSize\r
+;save_r15        equ  rsp + 80 - LocalVarsSize\r
+\r
+\r
+; summary of register usage\r
+; scanend     ebx\r
+; scanendw    bx\r
+; chainlenwmask   edx\r
+; curmatch    rsi\r
+; curmatchd   esi\r
+; windowbestlen   r8\r
+; scanalign   r9\r
+; scanalignd  r9d\r
+; window      r10\r
+; bestlen     r11\r
+; bestlend    r11d\r
+; scanstart   r12d\r
+; scanstartw  r12w\r
+; scan        r13\r
+; nicematch   r14d\r
+; limit       r15\r
+; limitd      r15d\r
+; prev        rcx\r
+\r
+;  all the +4 offsets are due to the addition of pending_buf_size (in zlib\r
+;  in the deflate_state structure since the asm code was first written\r
+;  (if you compile with zlib 1.0.4 or older, remove the +4).\r
+;  Note : these value are good with a 8 bytes boundary pack structure\r
+\r
+\r
+    MAX_MATCH           equ     258\r
+    MIN_MATCH           equ     3\r
+    MIN_LOOKAHEAD       equ     (MAX_MATCH+MIN_MATCH+1)\r
+\r
+\r
+;;; Offsets for fields in the deflate_state structure. These numbers\r
+;;; are calculated from the definition of deflate_state, with the\r
+;;; assumption that the compiler will dword-align the fields. (Thus,\r
+;;; changing the definition of deflate_state could easily cause this\r
+;;; program to crash horribly, without so much as a warning at\r
+;;; compile time. Sigh.)\r
+\r
+;  all the +zlib1222add offsets are due to the addition of fields\r
+;  in zlib in the deflate_state structure since the asm code was first written\r
+;  (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").\r
+;  (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").\r
+;  if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").\r
+\r
+\r
+IFDEF INFOZIP\r
+\r
+_DATA   SEGMENT\r
+COMM    window_size:DWORD\r
+; WMask ; 7fff\r
+COMM    window:BYTE:010040H\r
+COMM    prev:WORD:08000H\r
+; MatchLen : unused\r
+; PrevMatch : unused\r
+COMM    strstart:DWORD\r
+COMM    match_start:DWORD\r
+; Lookahead : ignore\r
+COMM    prev_length:DWORD ; PrevLen\r
+COMM    max_chain_length:DWORD\r
+COMM    good_match:DWORD\r
+COMM    nice_match:DWORD\r
+prev_ad equ OFFSET prev\r
+window_ad equ OFFSET window\r
+nicematch equ nice_match\r
+_DATA ENDS\r
+WMask equ 07fffh\r
+\r
+ELSE\r
+\r
+  IFNDEF zlib1222add\r
+    zlib1222add equ 8\r
+  ENDIF\r
+dsWSize         equ 56+zlib1222add+(zlib1222add/2)\r
+dsWMask         equ 64+zlib1222add+(zlib1222add/2)\r
+dsWindow        equ 72+zlib1222add\r
+dsPrev          equ 88+zlib1222add\r
+dsMatchLen      equ 128+zlib1222add\r
+dsPrevMatch     equ 132+zlib1222add\r
+dsStrStart      equ 140+zlib1222add\r
+dsMatchStart    equ 144+zlib1222add\r
+dsLookahead     equ 148+zlib1222add\r
+dsPrevLen       equ 152+zlib1222add\r
+dsMaxChainLen   equ 156+zlib1222add\r
+dsGoodMatch     equ 172+zlib1222add\r
+dsNiceMatch     equ 176+zlib1222add\r
+\r
+window_size     equ [ rcx + dsWSize]\r
+WMask           equ [ rcx + dsWMask]\r
+window_ad       equ [ rcx + dsWindow]\r
+prev_ad         equ [ rcx + dsPrev]\r
+strstart        equ [ rcx + dsStrStart]\r
+match_start     equ [ rcx + dsMatchStart]\r
+Lookahead       equ [ rcx + dsLookahead] ; 0ffffffffh on infozip\r
+prev_length     equ [ rcx + dsPrevLen]\r
+max_chain_length equ [ rcx + dsMaxChainLen]\r
+good_match      equ [ rcx + dsGoodMatch]\r
+nice_match      equ [ rcx + dsNiceMatch]\r
+ENDIF\r
+\r
+; parameter 1 in r8(deflate state s), param 2 in rdx (cur match)\r
+\r
+; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and\r
+; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp\r
+;\r
+; All registers must be preserved across the call, except for\r
+;   rax, rcx, rdx, r8, r9, r10, and r11, which are scratch.\r
+\r
+\r
+\r
+;;; Save registers that the compiler may be using, and adjust esp to\r
+;;; make room for our stack frame.\r
+\r
+\r
+;;; Retrieve the function arguments. r8d will hold cur_match\r
+;;; throughout the entire function. edx will hold the pointer to the\r
+;;; deflate_state structure during the function's setup (before\r
+;;; entering the main loop.\r
+\r
+; parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match)\r
+\r
+; this clear high 32 bits of r8, which can be garbage in both r8 and rdx\r
+\r
+        mov [save_rdi],rdi\r
+        mov [save_rsi],rsi\r
+        mov [save_rbx],rbx\r
+        mov [save_rbp],rbp\r
+IFDEF INFOZIP\r
+        mov r8d,ecx\r
+ELSE\r
+        mov r8d,edx\r
+ENDIF\r
+        mov [save_r12],r12\r
+        mov [save_r13],r13\r
+;        mov [save_r14],r14\r
+;        mov [save_r15],r15\r
+\r
+\r
+;;; uInt wmask = s->w_mask;\r
+;;; unsigned chain_length = s->max_chain_length;\r
+;;; if (s->prev_length >= s->good_match) {\r
+;;;     chain_length >>= 2;\r
+;;; }\r
+\r
+        mov edi, prev_length\r
+        mov esi, good_match\r
+        mov eax, WMask\r
+        mov ebx, max_chain_length\r
+        cmp edi, esi\r
+        jl  LastMatchGood\r
+        shr ebx, 2\r
+LastMatchGood:\r
+\r
+;;; chainlen is decremented once beforehand so that the function can\r
+;;; use the sign flag instead of the zero flag for the exit test.\r
+;;; It is then shifted into the high word, to make room for the wmask\r
+;;; value, which it will always accompany.\r
+\r
+        dec ebx\r
+        shl ebx, 16\r
+        or  ebx, eax\r
+\r
+;;; on zlib only\r
+;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;\r
+\r
+IFDEF INFOZIP\r
+        mov [chainlenwmask], ebx\r
+; on infozip nice_match = [nice_match]\r
+ELSE\r
+        mov eax, nice_match\r
+        mov [chainlenwmask], ebx\r
+        mov r10d, Lookahead\r
+        cmp r10d, eax\r
+        cmovnl r10d, eax\r
+        mov [nicematch],r10d\r
+ENDIF\r
+\r
+;;; register Bytef *scan = s->window + s->strstart;\r
+        mov r10, window_ad\r
+        mov ebp, strstart\r
+        lea r13, [r10 + rbp]\r
+\r
+;;; Determine how many bytes the scan ptr is off from being\r
+;;; dword-aligned.\r
+\r
+         mov r9,r13\r
+         neg r13\r
+         and r13,3\r
+\r
+;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ?\r
+;;;     s->strstart - (IPos)MAX_DIST(s) : NIL;\r
+IFDEF INFOZIP\r
+        mov eax,07efah ; MAX_DIST = (WSIZE-MIN_LOOKAHEAD) (0x8000-(3+8+1))\r
+ELSE\r
+        mov eax, window_size\r
+        sub eax, MIN_LOOKAHEAD\r
+ENDIF\r
+        xor edi,edi\r
+        sub ebp, eax\r
+\r
+        mov r11d, prev_length\r
+\r
+        cmovng ebp,edi\r
+\r
+;;; int best_len = s->prev_length;\r
+\r
+\r
+;;; Store the sum of s->window + best_len in esi locally, and in esi.\r
+\r
+       lea  rsi,[r10+r11]\r
+\r
+;;; register ush scan_start = *(ushf*)scan;\r
+;;; register ush scan_end   = *(ushf*)(scan+best_len-1);\r
+;;; Posf *prev = s->prev;\r
+\r
+        movzx r12d,word ptr [r9]\r
+        movzx ebx, word ptr [r9 + r11 - 1]\r
+\r
+        mov rdi, prev_ad\r
+\r
+;;; Jump into the main loop.\r
+\r
+        mov edx, [chainlenwmask]\r
+\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+        jz  LookupLoopIsZero\r
+\r
+LookupLoop1:\r
+        and r8d, edx\r
+\r
+        movzx   r8d, word ptr [rdi + r8*2]\r
+        cmp r8d, ebp\r
+        jbe LeaveNow\r
+        sub edx, 00010000h\r
+        js  LeaveNow\r
+\r
+LoopEntry1:\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+        jz  LookupLoopIsZero\r
+\r
+LookupLoop2:\r
+        and r8d, edx\r
+\r
+        movzx   r8d, word ptr [rdi + r8*2]\r
+        cmp r8d, ebp\r
+        jbe LeaveNow\r
+        sub edx, 00010000h\r
+        js  LeaveNow\r
+\r
+LoopEntry2:\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+        jz  LookupLoopIsZero\r
+\r
+LookupLoop4:\r
+        and r8d, edx\r
+\r
+        movzx   r8d, word ptr [rdi + r8*2]\r
+        cmp r8d, ebp\r
+        jbe LeaveNow\r
+        sub edx, 00010000h\r
+        js  LeaveNow\r
+\r
+LoopEntry4:\r
+\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+        jnz LookupLoop1\r
+        jmp LookupLoopIsZero\r
+\r
+\r
+;;; do {\r
+;;;     match = s->window + cur_match;\r
+;;;     if (*(ushf*)(match+best_len-1) != scan_end ||\r
+;;;         *(ushf*)match != scan_start) continue;\r
+;;;     [...]\r
+;;; } while ((cur_match = prev[cur_match & wmask]) > limit\r
+;;;          && --chain_length != 0);\r
+;;;\r
+;;; Here is the inner loop of the function. The function will spend the\r
+;;; majority of its time in this loop, and majority of that time will\r
+;;; be spent in the first ten instructions.\r
+;;;\r
+;;; Within this loop:\r
+;;; ebx = scanend\r
+;;; r8d = curmatch\r
+;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask)\r
+;;; esi = windowbestlen - i.e., (window + bestlen)\r
+;;; edi = prev\r
+;;; ebp = limit\r
+\r
+LookupLoop:\r
+        and r8d, edx\r
+\r
+        movzx   r8d, word ptr [rdi + r8*2]\r
+        cmp r8d, ebp\r
+        jbe LeaveNow\r
+        sub edx, 00010000h\r
+        js  LeaveNow\r
+\r
+LoopEntry:\r
+\r
+        cmp bx,word ptr [rsi + r8 - 1]\r
+        jnz LookupLoop1\r
+LookupLoopIsZero:\r
+        cmp     r12w, word ptr [r10 + r8]\r
+        jnz LookupLoop1\r
+\r
+\r
+;;; Store the current value of chainlen.\r
+        mov [chainlenwmask], edx\r
+\r
+;;; Point edi to the string under scrutiny, and esi to the string we\r
+;;; are hoping to match it up with. In actuality, esi and edi are\r
+;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is\r
+;;; initialized to -(MAX_MATCH_8 - scanalign).\r
+\r
+        lea rsi,[r8+r10]\r
+        mov rdx, 0fffffffffffffef8h; -(MAX_MATCH_8)\r
+        lea rsi, [rsi + r13 + 0108h] ;MAX_MATCH_8]\r
+        lea rdi, [r9 + r13 + 0108h] ;MAX_MATCH_8]\r
+\r
+        prefetcht1 [rsi+rdx]\r
+        prefetcht1 [rdi+rdx]\r
+\r
+\r
+;;; Test the strings for equality, 8 bytes at a time. At the end,\r
+;;; adjust rdx so that it is offset to the exact byte that mismatched.\r
+;;;\r
+;;; We already know at this point that the first three bytes of the\r
+;;; strings match each other, and they can be safely passed over before\r
+;;; starting the compare loop. So what this code does is skip over 0-3\r
+;;; bytes, as much as necessary in order to dword-align the edi\r
+;;; pointer. (rsi will still be misaligned three times out of four.)\r
+;;;\r
+;;; It should be confessed that this loop usually does not represent\r
+;;; much of the total running time. Replacing it with a more\r
+;;; straightforward "rep cmpsb" would not drastically degrade\r
+;;; performance.\r
+\r
+\r
+LoopCmps:\r
+        mov rax, [rsi + rdx]\r
+        xor rax, [rdi + rdx]\r
+        jnz LeaveLoopCmps\r
+\r
+        mov rax, [rsi + rdx + 8]\r
+        xor rax, [rdi + rdx + 8]\r
+        jnz LeaveLoopCmps8\r
+\r
+\r
+        mov rax, [rsi + rdx + 8+8]\r
+        xor rax, [rdi + rdx + 8+8]\r
+        jnz LeaveLoopCmps16\r
+\r
+        add rdx,8+8+8\r
+\r
+        jnz short LoopCmps\r
+        jmp short LenMaximum\r
+LeaveLoopCmps16: add rdx,8\r
+LeaveLoopCmps8: add rdx,8\r
+LeaveLoopCmps:\r
+\r
+        test    eax, 0000FFFFh\r
+        jnz LenLower\r
+\r
+        test eax,0ffffffffh\r
+\r
+        jnz LenLower32\r
+\r
+        add rdx,4\r
+        shr rax,32\r
+        or ax,ax\r
+        jnz LenLower\r
+\r
+LenLower32:\r
+        shr eax,16\r
+        add rdx,2\r
+LenLower:   sub al, 1\r
+        adc rdx, 0\r
+;;; Calculate the length of the match. If it is longer than MAX_MATCH,\r
+;;; then automatically accept it as the best possible match and leave.\r
+\r
+        lea rax, [rdi + rdx]\r
+        sub rax, r9\r
+        cmp eax, MAX_MATCH\r
+        jge LenMaximum\r
+\r
+;;; If the length of the match is not longer than the best match we\r
+;;; have so far, then forget it and return to the lookup loop.\r
+;///////////////////////////////////\r
+\r
+        cmp eax, r11d\r
+        jg  LongerMatch\r
+\r
+        lea rsi,[r10+r11]\r
+\r
+        mov rdi, prev_ad\r
+        mov edx, [chainlenwmask]\r
+        jmp LookupLoop\r
+\r
+;;;         s->match_start = cur_match;\r
+;;;         best_len = len;\r
+;;;         if (len >= nice_match) break;\r
+;;;         scan_end = *(ushf*)(scan+best_len-1);\r
+\r
+LongerMatch:\r
+        mov r11d, eax\r
+        mov match_start, r8d\r
+        cmp eax, [nicematch]\r
+        jge LeaveNow\r
+\r
+        lea rsi,[r10+rax]\r
+\r
+        movzx   ebx, word ptr [r9 + rax - 1]\r
+        mov rdi, prev_ad\r
+        mov edx, [chainlenwmask]\r
+        jmp LookupLoop\r
+\r
+;;; Accept the current string, with the maximum possible length.\r
+\r
+LenMaximum:\r
+        mov r11d,MAX_MATCH\r
+        mov match_start, r8d\r
+\r
+;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len;\r
+;;; return s->lookahead;\r
+\r
+LeaveNow:\r
+IFDEF INFOZIP\r
+        mov eax,r11d\r
+ELSE\r
+        mov eax, Lookahead\r
+        cmp r11d, eax\r
+        cmovng eax, r11d\r
+ENDIF\r
+\r
+;;; Restore the stack and return from whence we came.\r
+\r
+\r
+        mov rsi,[save_rsi]\r
+        mov rdi,[save_rdi]\r
+        mov rbx,[save_rbx]\r
+        mov rbp,[save_rbp]\r
+        mov r12,[save_r12]\r
+        mov r13,[save_r13]\r
+;        mov r14,[save_r14]\r
+;        mov r15,[save_r15]\r
+\r
+\r
+        ret 0\r
+; please don't remove this string !\r
+; Your can freely use gvmat64 in any free or commercial app\r
+; but it is far better don't remove the string in the binary!\r
+    db     0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0\r
+longest_match   ENDP\r
+\r
+match_init PROC\r
+  ret 0\r
+match_init ENDP\r
+\r
+\r
+END\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.lst b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.lst
new file mode 100644 (file)
index 0000000..aa5e476
--- /dev/null
@@ -0,0 +1,666 @@
+Microsoft (R) Macro Assembler (x64) Version 10.00.40219.01  05/20/14 09:52:26\r
+gvmat64.asm                                                 Page 1 - 1\r
+\r
+\r
+                               ;uInt longest_match_x64(\r
+                               ;    deflate_state *s,\r
+                               ;    IPos cur_match);                             /* current match */\r
+\r
+                               ; gvmat64.asm -- Asm portion of the optimized longest_match for 32 bits x86_64\r
+                               ;  (AMD64 on Athlon 64, Opteron, Phenom\r
+                               ;     and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7)\r
+                               ; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant.\r
+                               ;\r
+                               ; File written by Gilles Vollant, by converting to assembly the longest_match\r
+                               ;  from Jean-loup Gailly in deflate.c of zLib and infoZip zip.\r
+                               ;\r
+                               ;  and by taking inspiration on asm686 with masm, optimised assembly code\r
+                               ;        from Brian Raiter, written 1998\r
+                               ;\r
+                               ;  This software is provided 'as-is', without any express or implied\r
+                               ;  warranty.  In no event will the authors be held liable for any damages\r
+                               ;  arising from the use of this software.\r
+                               ;\r
+                               ;  Permission is granted to anyone to use this software for any purpose,\r
+                               ;  including commercial applications, and to alter it and redistribute it\r
+                               ;  freely, subject to the following restrictions:\r
+                               ;\r
+                               ;  1. The origin of this software must not be misrepresented; you must not\r
+                               ;     claim that you wrote the original software. If you use this software\r
+                               ;     in a product, an acknowledgment in the product documentation would be\r
+                               ;     appreciated but is not required.\r
+                               ;  2. Altered source versions must be plainly marked as such, and must not be\r
+                               ;     misrepresented as being the original software\r
+                               ;  3. This notice may not be removed or altered from any source distribution.\r
+                               ;\r
+                               ;\r
+                               ;\r
+                               ;         http://www.zlib.net\r
+                               ;         http://www.winimage.com/zLibDll\r
+                               ;         http://www.muppetlabs.com/~breadbox/software/assembly.html\r
+                               ;\r
+                               ; to compile this file for infozip Zip, I use option:\r
+                               ;   ml64.exe /Flgvmat64 /c /Zi /DINFOZIP gvmat64.asm\r
+                               ;\r
+                               ; to compile this file for zLib, I use option:\r
+                               ;   ml64.exe /Flgvmat64 /c /Zi gvmat64.asm\r
+                               ; Be carrefull to adapt zlib1222add below to your version of zLib\r
+                               ;   (if you use a version of zLib before 1.0.4 or after 1.2.2.2, change\r
+                               ;    value of zlib1222add later)\r
+                               ;\r
+                               ; This file compile with Microsoft Macro Assembler (x64) for AMD64\r
+                               ;\r
+                               ;   ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK\r
+                               ;\r
+                               ;   (you can get Windows WDK with ml64 for AMD64 from\r
+                               ;      http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price)\r
+                               ;\r
+\r
+\r
+                               ;uInt longest_match(s, cur_match)\r
+                               ;    deflate_state *s;\r
+                               ;    IPos cur_match;                             /* current match */\r
+ 00000000                      .code\r
+ 00000000                      longest_match PROC\r
+\r
+\r
+                               ;LocalVarsSize   equ 88\r
+ = 00000048                     LocalVarsSize   equ 72\r
+\r
+                               ; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12\r
+                               ; free register :  r14,r15\r
+                               ; register can be saved : rsp\r
+\r
+ = rsp + 8 - LocalVarsSize      chainlenwmask   equ  rsp + 8 - LocalVarsSize    ; high word: current chain len\r
+                                                                                ; low word: s->wmask\r
+                               ;window          equ  rsp + xx - LocalVarsSize   ; local copy of s->window ; stored in r10\r
+                               ;windowbestlen   equ  rsp + xx - LocalVarsSize   ; s->window + bestlen , use r10+r11\r
+                               ;scanstart       equ  rsp + xx - LocalVarsSize   ; first two bytes of string ; stored in r12w\r
+                               ;scanend         equ  rsp + xx - LocalVarsSize   ; last two bytes of string use ebx\r
+                               ;scanalign       equ  rsp + xx - LocalVarsSize   ; dword-misalignment of string r13\r
+                               ;bestlen         equ  rsp + xx - LocalVarsSize   ; size of best match so far -> r11d\r
+                               ;scan            equ  rsp + xx - LocalVarsSize   ; ptr to string wanting match -> r9\r
+                               IFDEF INFOZIP\r
+                               ELSE\r
+ = (rsp + 16 - LocalVarsSiz     nicematch       equ  (rsp + 16 - LocalVarsSize) ; a good enough match size\r
+   e)\r
+                               ENDIF\r
+\r
+ = rsp + 24 - LocalVarsSize    save_rdi        equ  rsp + 24 - LocalVarsSize\r
+ = rsp + 32 - LocalVarsSize    save_rsi        equ  rsp + 32 - LocalVarsSize\r
+ = rsp + 40 - LocalVarsSize    save_rbx        equ  rsp + 40 - LocalVarsSize\r
+ = rsp + 48 - LocalVarsSize    save_rbp        equ  rsp + 48 - LocalVarsSize\r
+ = rsp + 56 - LocalVarsSize    save_r12        equ  rsp + 56 - LocalVarsSize\r
+ = rsp + 64 - LocalVarsSize    save_r13        equ  rsp + 64 - LocalVarsSize\r
+                               ;save_r14        equ  rsp + 72 - LocalVarsSize\r
+                               ;save_r15        equ  rsp + 80 - LocalVarsSize\r
+\r
+\r
+                               ; summary of register usage\r
+                               ; scanend     ebx\r
+                               ; scanendw    bx\r
+                               ; chainlenwmask   edx\r
+                               ; curmatch    rsi\r
+                               ; curmatchd   esi\r
+                               ; windowbestlen   r8\r
+                               ; scanalign   r9\r
+                               ; scanalignd  r9d\r
+                               ; window      r10\r
+                               ; bestlen     r11\r
+                               ; bestlend    r11d\r
+                               ; scanstart   r12d\r
+                               ; scanstartw  r12w\r
+                               ; scan        r13\r
+                               ; nicematch   r14d\r
+                               ; limit       r15\r
+                               ; limitd      r15d\r
+                               ; prev        rcx\r
+\r
+                               ;  all the +4 offsets are due to the addition of pending_buf_size (in zlib\r
+                               ;  in the deflate_state structure since the asm code was first written\r
+                               ;  (if you compile with zlib 1.0.4 or older, remove the +4).\r
+                               ;  Note : these value are good with a 8 bytes boundary pack structure\r
+\r
+\r
+ = 00000102                        MAX_MATCH           equ     258\r
+ = 00000003                        MIN_MATCH           equ     3\r
+ = 00000106                        MIN_LOOKAHEAD       equ     (MAX_MATCH+MIN_MATCH+1)\r
+\r
+\r
+                               ;;; Offsets for fields in the deflate_state structure. These numbers\r
+                               ;;; are calculated from the definition of deflate_state, with the\r
+                               ;;; assumption that the compiler will dword-align the fields. (Thus,\r
+                               ;;; changing the definition of deflate_state could easily cause this\r
+                               ;;; program to crash horribly, without so much as a warning at\r
+                               ;;; compile time. Sigh.)\r
+\r
+                               ;  all the +zlib1222add offsets are due to the addition of fields\r
+                               ;  in zlib in the deflate_state structure since the asm code was first written\r
+                               ;  (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").\r
+                               ;  (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").\r
+                               ;  if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").\r
+\r
+\r
+                               IFDEF INFOZIP\r
+                               ELSE\r
+\r
+                                 IFNDEF zlib1222add\r
+ = 00000008                        zlib1222add equ 8\r
+                                 ENDIF\r
+ = 00000044                    dsWSize         equ 56+zlib1222add+(zlib1222add/2)\r
+ = 0000004C                    dsWMask         equ 64+zlib1222add+(zlib1222add/2)\r
+ = 00000050                    dsWindow        equ 72+zlib1222add\r
+ = 00000060                    dsPrev          equ 88+zlib1222add\r
+ = 00000088                    dsMatchLen      equ 128+zlib1222add\r
+ = 0000008C                    dsPrevMatch     equ 132+zlib1222add\r
+ = 00000094                    dsStrStart      equ 140+zlib1222add\r
+ = 00000098                    dsMatchStart    equ 144+zlib1222add\r
+ = 0000009C                    dsLookahead     equ 148+zlib1222add\r
+ = 000000A0                    dsPrevLen       equ 152+zlib1222add\r
+ = 000000A4                    dsMaxChainLen   equ 156+zlib1222add\r
+ = 000000B4                    dsGoodMatch     equ 172+zlib1222add\r
+ = 000000B8                    dsNiceMatch     equ 176+zlib1222add\r
+\r
+ = [ rcx + dsWSize]            window_size     equ [ rcx + dsWSize]\r
+ = [ rcx + dsWMask]            WMask           equ [ rcx + dsWMask]\r
+ = [ rcx + dsWindow]           window_ad       equ [ rcx + dsWindow]\r
+ = [ rcx + dsPrev]             prev_ad         equ [ rcx + dsPrev]\r
+ = [ rcx + dsStrStart]         strstart        equ [ rcx + dsStrStart]\r
+ = [ rcx + dsMatchStart]       match_start     equ [ rcx + dsMatchStart]\r
+ = [ rcx + dsLookahead]                Lookahead       equ [ rcx + dsLookahead] ; 0ffffffffh on infozip\r
+ = [ rcx + dsPrevLen]          prev_length     equ [ rcx + dsPrevLen]\r
+ = [ rcx + dsMaxChainLen]      max_chain_length equ [ rcx + dsMaxChainLen]\r
+ = [ rcx + dsGoodMatch]                good_match      equ [ rcx + dsGoodMatch]\r
+ = [ rcx + dsNiceMatch]                nice_match      equ [ rcx + dsNiceMatch]\r
+                               ENDIF\r
+\r
+                               ; parameter 1 in r8(deflate state s), param 2 in rdx (cur match)\r
+\r
+                               ; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and\r
+                               ; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp\r
+                               ;\r
+                               ; All registers must be preserved across the call, except for\r
+                               ;   rax, rcx, rdx, r8, r9, r10, and r11, which are scratch.\r
+\r
+\r
+\r
+                               ;;; Save registers that the compiler may be using, and adjust esp to\r
+                               ;;; make room for our stack frame.\r
+\r
+\r
+                               ;;; Retrieve the function arguments. r8d will hold cur_match\r
+                               ;;; throughout the entire function. edx will hold the pointer to the\r
+                               ;;; deflate_state structure during the function's setup (before\r
+                               ;;; entering the main loop.\r
+\r
+                               ; parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match)\r
+\r
+                               ; this clear high 32 bits of r8, which can be garbage in both r8 and rdx\r
+\r
+ 00000000  48/ 89 7C 24                        mov [save_rdi],rdi\r
+          D0\r
+ 00000005  48/ 89 74 24                        mov [save_rsi],rsi\r
+          D8\r
+ 0000000A  48/ 89 5C 24                        mov [save_rbx],rbx\r
+          E0\r
+ 0000000F  48/ 89 6C 24                        mov [save_rbp],rbp\r
+          E8\r
+                               IFDEF INFOZIP\r
+                               ELSE\r
+ 00000014  44/ 8B C2                   mov r8d,edx\r
+                               ENDIF\r
+ 00000017  4C/ 89 64 24                        mov [save_r12],r12\r
+          F0\r
+ 0000001C  4C/ 89 6C 24                        mov [save_r13],r13\r
+          F8\r
+                               ;        mov [save_r14],r14\r
+                               ;        mov [save_r15],r15\r
+\r
+\r
+                               ;;; uInt wmask = s->w_mask;\r
+                               ;;; unsigned chain_length = s->max_chain_length;\r
+                               ;;; if (s->prev_length >= s->good_match) {\r
+                               ;;;     chain_length >>= 2;\r
+                               ;;; }\r
+\r
+ 00000021  8B B9 000000A0              mov edi, prev_length\r
+ 00000027  8B B1 000000B4              mov esi, good_match\r
+ 0000002D  8B 41 4C                    mov eax, WMask\r
+ 00000030  8B 99 000000A4              mov ebx, max_chain_length\r
+ 00000036  3B FE                       cmp edi, esi\r
+ 00000038  7C 03                       jl  LastMatchGood\r
+ 0000003A  C1 EB 02                    shr ebx, 2\r
+ 0000003D                      LastMatchGood:\r
+\r
+                               ;;; chainlen is decremented once beforehand so that the function can\r
+                               ;;; use the sign flag instead of the zero flag for the exit test.\r
+                               ;;; It is then shifted into the high word, to make room for the wmask\r
+                               ;;; value, which it will always accompany.\r
+\r
+ 0000003D  FF CB                       dec ebx\r
+ 0000003F  C1 E3 10                    shl ebx, 16\r
+ 00000042  0B D8                       or  ebx, eax\r
+\r
+                               ;;; on zlib only\r
+                               ;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;\r
+\r
+                               IFDEF INFOZIP\r
+                               ELSE\r
+ 00000044  8B 81 000000B8              mov eax, nice_match\r
+ 0000004A  89 5C 24 C0                 mov [chainlenwmask], ebx\r
+ 0000004E  44/ 8B 91                   mov r10d, Lookahead\r
+          0000009C\r
+ 00000055  44/ 3B D0                   cmp r10d, eax\r
+ 00000058  44/ 0F 4D D0                        cmovnl r10d, eax\r
+ 0000005C  44/ 89 54 24                        mov [nicematch],r10d\r
+          C8\r
+                               ENDIF\r
+\r
+                               ;;; register Bytef *scan = s->window + s->strstart;\r
+ 00000061  4C/ 8B 51 50                        mov r10, window_ad\r
+ 00000065  8B A9 00000094              mov ebp, strstart\r
+ 0000006B  4E/ 8D 6C 15                        lea r13, [r10 + rbp]\r
+          00\r
+\r
+                               ;;; Determine how many bytes the scan ptr is off from being\r
+                               ;;; dword-aligned.\r
+\r
+ 00000070  4D/ 8B CD                    mov r9,r13\r
+ 00000073  49/ F7 DD                    neg r13\r
+ 00000076  49/ 83 E5 03                         and r13,3\r
+\r
+                               ;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ?\r
+                               ;;;     s->strstart - (IPos)MAX_DIST(s) : NIL;\r
+                               IFDEF INFOZIP\r
+                               ELSE\r
+ 0000007A  8B 41 44                    mov eax, window_size\r
+ 0000007D  2D 00000106                 sub eax, MIN_LOOKAHEAD\r
+                               ENDIF\r
+ 00000082  33 FF                       xor edi,edi\r
+ 00000084  2B E8                       sub ebp, eax\r
+\r
+ 00000086  44/ 8B 99                   mov r11d, prev_length\r
+          000000A0\r
+\r
+ 0000008D  0F 4E EF                    cmovng ebp,edi\r
+\r
+                               ;;; int best_len = s->prev_length;\r
+\r
+\r
+                               ;;; Store the sum of s->window + best_len in esi locally, and in esi.\r
+\r
+ 00000090  4B/ 8D 34 13                       lea  rsi,[r10+r11]\r
+\r
+                               ;;; register ush scan_start = *(ushf*)scan;\r
+                               ;;; register ush scan_end   = *(ushf*)(scan+best_len-1);\r
+                               ;;; Posf *prev = s->prev;\r
+\r
+ 00000094  45/ 0F B7 21                        movzx r12d,word ptr [r9]\r
+ 00000098  43/ 0F B7 5C 0B             movzx ebx, word ptr [r9 + r11 - 1]\r
+          FF\r
+\r
+ 0000009E  48/ 8B 79 60                        mov rdi, prev_ad\r
+\r
+                               ;;; Jump into the main loop.\r
+\r
+ 000000A2  8B 54 24 C0                 mov edx, [chainlenwmask]\r
+\r
+ 000000A6  66| 41/ 3B 5C 30            cmp bx,word ptr [rsi + r8 - 1]\r
+          FF\r
+ 000000AC  0F 84 0000009A              jz  LookupLoopIsZero\r
+\r
+ 000000B2                      LookupLoop1:\r
+ 000000B2  44/ 23 C2                   and r8d, edx\r
+\r
+ 000000B5  46/ 0F B7 04 47             movzx   r8d, word ptr [rdi + r8*2]\r
+ 000000BA  44/ 3B C5                   cmp r8d, ebp\r
+ 000000BD  0F 86 00000170              jbe LeaveNow\r
+ 000000C3  81 EA 00010000              sub edx, 00010000h\r
+ 000000C9  0F 88 00000164              js  LeaveNow\r
+\r
+ 000000CF                      LoopEntry1:\r
+ 000000CF  66| 41/ 3B 5C 30            cmp bx,word ptr [rsi + r8 - 1]\r
+          FF\r
+ 000000D5  74 75                       jz  LookupLoopIsZero\r
+\r
+ 000000D7                      LookupLoop2:\r
+ 000000D7  44/ 23 C2                   and r8d, edx\r
+\r
+ 000000DA  46/ 0F B7 04 47             movzx   r8d, word ptr [rdi + r8*2]\r
+ 000000DF  44/ 3B C5                   cmp r8d, ebp\r
+ 000000E2  0F 86 0000014B              jbe LeaveNow\r
+ 000000E8  81 EA 00010000              sub edx, 00010000h\r
+ 000000EE  0F 88 0000013F              js  LeaveNow\r
+\r
+ 000000F4                      LoopEntry2:\r
+ 000000F4  66| 41/ 3B 5C 30            cmp bx,word ptr [rsi + r8 - 1]\r
+          FF\r
+ 000000FA  74 50                       jz  LookupLoopIsZero\r
+\r
+ 000000FC                      LookupLoop4:\r
+ 000000FC  44/ 23 C2                   and r8d, edx\r
+\r
+ 000000FF  46/ 0F B7 04 47             movzx   r8d, word ptr [rdi + r8*2]\r
+ 00000104  44/ 3B C5                   cmp r8d, ebp\r
+ 00000107  0F 86 00000126              jbe LeaveNow\r
+ 0000010D  81 EA 00010000              sub edx, 00010000h\r
+ 00000113  0F 88 0000011A              js  LeaveNow\r
+\r
+ 00000119                      LoopEntry4:\r
+\r
+ 00000119  66| 41/ 3B 5C 30            cmp bx,word ptr [rsi + r8 - 1]\r
+          FF\r
+ 0000011F  75 91                       jnz LookupLoop1\r
+ 00000121  EB 29                       jmp LookupLoopIsZero\r
+\r
+\r
+                               ;;; do {\r
+                               ;;;     match = s->window + cur_match;\r
+                               ;;;     if (*(ushf*)(match+best_len-1) != scan_end ||\r
+                               ;;;         *(ushf*)match != scan_start) continue;\r
+                               ;;;     [...]\r
+                               ;;; } while ((cur_match = prev[cur_match & wmask]) > limit\r
+                               ;;;          && --chain_length != 0);\r
+                               ;;;\r
+                               ;;; Here is the inner loop of the function. The function will spend the\r
+                               ;;; majority of its time in this loop, and majority of that time will\r
+                               ;;; be spent in the first ten instructions.\r
+                               ;;;\r
+                               ;;; Within this loop:\r
+                               ;;; ebx = scanend\r
+                               ;;; r8d = curmatch\r
+                               ;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask)\r
+                               ;;; esi = windowbestlen - i.e., (window + bestlen)\r
+                               ;;; edi = prev\r
+                               ;;; ebp = limit\r
+\r
+ 00000123                      LookupLoop:\r
+ 00000123  44/ 23 C2                   and r8d, edx\r
+\r
+ 00000126  46/ 0F B7 04 47             movzx   r8d, word ptr [rdi + r8*2]\r
+ 0000012B  44/ 3B C5                   cmp r8d, ebp\r
+ 0000012E  0F 86 000000FF              jbe LeaveNow\r
+ 00000134  81 EA 00010000              sub edx, 00010000h\r
+ 0000013A  0F 88 000000F3              js  LeaveNow\r
+\r
+ 00000140                      LoopEntry:\r
+\r
+ 00000140  66| 41/ 3B 5C 30            cmp bx,word ptr [rsi + r8 - 1]\r
+          FF\r
+ 00000146  0F 85 FFFFFF66              jnz LookupLoop1\r
+ 0000014C                      LookupLoopIsZero:\r
+ 0000014C  66| 47/ 3B 24 10            cmp     r12w, word ptr [r10 + r8]\r
+ 00000151  0F 85 FFFFFF5B              jnz LookupLoop1\r
+\r
+\r
+                               ;;; Store the current value of chainlen.\r
+ 00000157  89 54 24 C0                 mov [chainlenwmask], edx\r
+\r
+                               ;;; Point edi to the string under scrutiny, and esi to the string we\r
+                               ;;; are hoping to match it up with. In actuality, esi and edi are\r
+                               ;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is\r
+                               ;;; initialized to -(MAX_MATCH_8 - scanalign).\r
+\r
+ 0000015B  4B/ 8D 34 02                        lea rsi,[r8+r10]\r
+ 0000015F  48/ BA                      mov rdx, 0fffffffffffffef8h; -(MAX_MATCH_8)\r
+          FFFFFFFFFFFFFEF8\r
+ 00000169  49/ 8D B4 35                        lea rsi, [rsi + r13 + 0108h] ;MAX_MATCH_8]\r
+          00000108\r
+ 00000171  4B/ 8D BC 0D                        lea rdi, [r9 + r13 + 0108h] ;MAX_MATCH_8]\r
+          00000108\r
+\r
+ 00000179  0F 18 14 32                 prefetcht1 [rsi+rdx]\r
+ 0000017D  0F 18 14 3A                 prefetcht1 [rdi+rdx]\r
+\r
+\r
+                               ;;; Test the strings for equality, 8 bytes at a time. At the end,\r
+                               ;;; adjust rdx so that it is offset to the exact byte that mismatched.\r
+                               ;;;\r
+                               ;;; We already know at this point that the first three bytes of the\r
+                               ;;; strings match each other, and they can be safely passed over before\r
+                               ;;; starting the compare loop. So what this code does is skip over 0-3\r
+                               ;;; bytes, as much as necessary in order to dword-align the edi\r
+                               ;;; pointer. (rsi will still be misaligned three times out of four.)\r
+                               ;;;\r
+                               ;;; It should be confessed that this loop usually does not represent\r
+                               ;;; much of the total running time. Replacing it with a more\r
+                               ;;; straightforward "rep cmpsb" would not drastically degrade\r
+                               ;;; performance.\r
+\r
+\r
+ 00000181                      LoopCmps:\r
+ 00000181  48/ 8B 04 32                        mov rax, [rsi + rdx]\r
+ 00000185  48/ 33 04 3A                        xor rax, [rdi + rdx]\r
+ 00000189  75 28                       jnz LeaveLoopCmps\r
+\r
+ 0000018B  48/ 8B 44 32                        mov rax, [rsi + rdx + 8]\r
+          08\r
+ 00000190  48/ 33 44 3A                        xor rax, [rdi + rdx + 8]\r
+          08\r
+ 00000195  75 18                       jnz LeaveLoopCmps8\r
+\r
+\r
+ 00000197  48/ 8B 44 32                        mov rax, [rsi + rdx + 8+8]\r
+          10\r
+ 0000019C  48/ 33 44 3A                        xor rax, [rdi + rdx + 8+8]\r
+          10\r
+ 000001A1  75 08                       jnz LeaveLoopCmps16\r
+\r
+ 000001A3  48/ 83 C2 18                        add rdx,8+8+8\r
+\r
+ 000001A7  75 D8                       jnz short LoopCmps\r
+ 000001A9  EB 7B                       jmp short LenMaximum\r
+ 000001AB  48/ 83 C2 08                LeaveLoopCmps16: add rdx,8\r
+ 000001AF  48/ 83 C2 08                LeaveLoopCmps8: add rdx,8\r
+ 000001B3                      LeaveLoopCmps:\r
+\r
+ 000001B3  A9 0000FFFF                 test    eax, 0000FFFFh\r
+ 000001B8  75 1B                       jnz LenLower\r
+\r
+ 000001BA  A9 FFFFFFFF                 test eax,0ffffffffh\r
+\r
+ 000001BF  75 0D                       jnz LenLower32\r
+\r
+ 000001C1  48/ 83 C2 04                        add rdx,4\r
+ 000001C5  48/ C1 E8 20                        shr rax,32\r
+ 000001C9  66| 0B C0                   or ax,ax\r
+ 000001CC  75 07                       jnz LenLower\r
+\r
+ 000001CE                      LenLower32:\r
+ 000001CE  C1 E8 10                    shr eax,16\r
+ 000001D1  48/ 83 C2 02                        add rdx,2\r
+ 000001D5  2C 01               LenLower:   sub al, 1\r
+ 000001D7  48/ 83 D2 00                        adc rdx, 0\r
+                               ;;; Calculate the length of the match. If it is longer than MAX_MATCH,\r
+                               ;;; then automatically accept it as the best possible match and leave.\r
+\r
+ 000001DB  48/ 8D 04 3A                        lea rax, [rdi + rdx]\r
+ 000001DF  49/ 2B C1                   sub rax, r9\r
+ 000001E2  3D 00000102                 cmp eax, MAX_MATCH\r
+ 000001E7  7D 3D                       jge LenMaximum\r
+\r
+                               ;;; If the length of the match is not longer than the best match we\r
+                               ;;; have so far, then forget it and return to the lookup loop.\r
+                               ;///////////////////////////////////\r
+\r
+ 000001E9  41/ 3B C3                   cmp eax, r11d\r
+ 000001EC  7F 11                       jg  LongerMatch\r
+\r
+ 000001EE  4B/ 8D 34 13                        lea rsi,[r10+r11]\r
+\r
+ 000001F2  48/ 8B 79 60                        mov rdi, prev_ad\r
+ 000001F6  8B 54 24 C0                 mov edx, [chainlenwmask]\r
+ 000001FA  E9 FFFFFF24                 jmp LookupLoop\r
+\r
+                               ;;;         s->match_start = cur_match;\r
+                               ;;;         best_len = len;\r
+                               ;;;         if (len >= nice_match) break;\r
+                               ;;;         scan_end = *(ushf*)(scan+best_len-1);\r
+\r
+ 000001FF                      LongerMatch:\r
+ 000001FF  44/ 8B D8                   mov r11d, eax\r
+ 00000202  44/ 89 81                   mov match_start, r8d\r
+          00000098\r
+ 00000209  3B 44 24 C8                 cmp eax, [nicematch]\r
+ 0000020D  7D 24                       jge LeaveNow\r
+\r
+ 0000020F  4A/ 8D 34 10                        lea rsi,[r10+rax]\r
+\r
+ 00000213  42/ 0F B7 5C 08             movzx   ebx, word ptr [r9 + rax - 1]\r
+          FF\r
+ 00000219  48/ 8B 79 60                        mov rdi, prev_ad\r
+ 0000021D  8B 54 24 C0                 mov edx, [chainlenwmask]\r
+ 00000221  E9 FFFFFEFD                 jmp LookupLoop\r
+\r
+                               ;;; Accept the current string, with the maximum possible length.\r
+\r
+ 00000226                      LenMaximum:\r
+ 00000226  41/ BB                      mov r11d,MAX_MATCH\r
+          00000102\r
+ 0000022C  44/ 89 81                   mov match_start, r8d\r
+          00000098\r
+\r
+                               ;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len;\r
+                               ;;; return s->lookahead;\r
+\r
+ 00000233                      LeaveNow:\r
+                               IFDEF INFOZIP\r
+                               ELSE\r
+ 00000233  8B 81 0000009C              mov eax, Lookahead\r
+ 00000239  44/ 3B D8                   cmp r11d, eax\r
+ 0000023C  41/ 0F 4E C3                        cmovng eax, r11d\r
+                               ENDIF\r
+\r
+                               ;;; Restore the stack and return from whence we came.\r
+\r
+\r
+ 00000240  48/ 8B 74 24                        mov rsi,[save_rsi]\r
+          D8\r
+ 00000245  48/ 8B 7C 24                        mov rdi,[save_rdi]\r
+          D0\r
+ 0000024A  48/ 8B 5C 24                        mov rbx,[save_rbx]\r
+          E0\r
+ 0000024F  48/ 8B 6C 24                        mov rbp,[save_rbp]\r
+          E8\r
+ 00000254  4C/ 8B 64 24                        mov r12,[save_r12]\r
+          F0\r
+ 00000259  4C/ 8B 6C 24                        mov r13,[save_r13]\r
+          F8\r
+                               ;        mov r14,[save_r14]\r
+                               ;        mov r15,[save_r15]\r
+\r
+\r
+ 0000025E  C3                          ret 0\r
+                               ; please don't remove this string !\r
+                               ; Your can freely use gvmat64 in any free or commercial app\r
+                               ; but it is far better don't remove the string in the binary!\r
+ 0000025F  0D 0A 61 73 6D          db     0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0\r
+          36 38 36 20 77\r
+          69 74 68 20 6D\r
+          61 73 6D 2C 20\r
+          6F 70 74 69 6D\r
+          69 73 65 64 20\r
+          61 73 73 65 6D\r
+          62 6C 79 20 63\r
+          6F 64 65 20 66\r
+          72 6F 6D 20 42\r
+          72 69 61 6E 20\r
+          52 61 69 74 65\r
+          72 2C 20 77 72\r
+          69 74 74 65 6E\r
+          20 31 39 39 38\r
+          2C 20 63 6F 6E\r
+          76 65 72 74 65\r
+          64 20 74 6F 20\r
+          61 6D 64 20 36\r
+          34 20 62 79 20\r
+          47 69 6C 6C 65\r
+          73 20 56 6F 6C\r
+          6C 61 6E 74 20\r
+          32 30 30 35 0D\r
+          0A 00\r
+ 000002D9                      longest_match   ENDP\r
+\r
+ 000002D9                      match_init PROC\r
+ 000002D9  C3                    ret 0\r
+ 000002DA                      match_init ENDP\r
+\r
+\r
+                               END\r
+\fMicrosoft (R) Macro Assembler (x64) Version 10.00.40219.01  05/20/14 09:52:26\r
+gvmat64.asm                                                 Symbols 2 - 1\r
+\r
+\r
+\r
+\r
+Procedures, parameters, and locals:\r
+\r
+                N a m e                 Type     Value    Attr\r
+\r
+longest_match  . . . . . . . . .       P        00000000 _TEXT Length= 000002D9 Public\r
+  LastMatchGood  . . . . . . . .       L        0000003D _TEXT \r
+  LookupLoop1  . . . . . . . . .       L        000000B2 _TEXT \r
+  LoopEntry1 . . . . . . . . . .       L        000000CF _TEXT \r
+  LookupLoop2  . . . . . . . . .       L        000000D7 _TEXT \r
+  LoopEntry2 . . . . . . . . . .       L        000000F4 _TEXT \r
+  LookupLoop4  . . . . . . . . .       L        000000FC _TEXT \r
+  LoopEntry4 . . . . . . . . . .       L        00000119 _TEXT \r
+  LookupLoop . . . . . . . . . .       L        00000123 _TEXT \r
+  LoopEntry  . . . . . . . . . .       L        00000140 _TEXT \r
+  LookupLoopIsZero . . . . . . .       L        0000014C _TEXT \r
+  LoopCmps . . . . . . . . . . .       L        00000181 _TEXT \r
+  LeaveLoopCmps16  . . . . . . .       L        000001AB _TEXT \r
+  LeaveLoopCmps8 . . . . . . . .       L        000001AF _TEXT \r
+  LeaveLoopCmps  . . . . . . . .       L        000001B3 _TEXT \r
+  LenLower32 . . . . . . . . . .       L        000001CE _TEXT \r
+  LenLower . . . . . . . . . . .       L        000001D5 _TEXT \r
+  LongerMatch  . . . . . . . . .       L        000001FF _TEXT \r
+  LenMaximum . . . . . . . . . .       L        00000226 _TEXT \r
+  LeaveNow . . . . . . . . . . .       L        00000233 _TEXT \r
+match_init . . . . . . . . . . .       P        000002D9 _TEXT Length= 00000001 Public\r
+\r
+\r
+Symbols:\r
+\r
+                N a m e                 Type     Value    Attr\r
+\r
+LocalVarsSize  . . . . . . . . .       Number   00000048h   \r
+Lookahead  . . . . . . . . . . .       Text     [ rcx + dsLookahead]\r
+MAX_MATCH  . . . . . . . . . . .       Number   00000102h   \r
+MIN_LOOKAHEAD  . . . . . . . . .       Number   00000106h   \r
+MIN_MATCH  . . . . . . . . . . .       Number   00000003h   \r
+WMask  . . . . . . . . . . . . .       Text     [ rcx + dsWMask]\r
+chainlenwmask  . . . . . . . . .       Text     rsp + 8 - LocalVarsSize\r
+dsGoodMatch  . . . . . . . . . .       Number   000000B4h   \r
+dsLookahead  . . . . . . . . . .       Number   0000009Ch   \r
+dsMatchLen . . . . . . . . . . .       Number   00000088h   \r
+dsMatchStart . . . . . . . . . .       Number   00000098h   \r
+dsMaxChainLen  . . . . . . . . .       Number   000000A4h   \r
+dsNiceMatch  . . . . . . . . . .       Number   000000B8h   \r
+dsPrevLen  . . . . . . . . . . .       Number   000000A0h   \r
+dsPrevMatch  . . . . . . . . . .       Number   0000008Ch   \r
+dsPrev . . . . . . . . . . . . .       Number   00000060h   \r
+dsStrStart . . . . . . . . . . .       Number   00000094h   \r
+dsWMask  . . . . . . . . . . . .       Number   0000004Ch   \r
+dsWSize  . . . . . . . . . . . .       Number   00000044h   \r
+dsWindow . . . . . . . . . . . .       Number   00000050h   \r
+good_match . . . . . . . . . . .       Text     [ rcx + dsGoodMatch]\r
+match_start  . . . . . . . . . .       Text     [ rcx + dsMatchStart]\r
+max_chain_length . . . . . . . .       Text     [ rcx + dsMaxChainLen]\r
+nice_match . . . . . . . . . . .       Text     [ rcx + dsNiceMatch]\r
+nicematch  . . . . . . . . . . .       Text     (rsp + 16 - LocalVarsSize)\r
+prev_ad  . . . . . . . . . . . .       Text     [ rcx + dsPrev]\r
+prev_length  . . . . . . . . . .       Text     [ rcx + dsPrevLen]\r
+save_r12 . . . . . . . . . . . .       Text     rsp + 56 - LocalVarsSize\r
+save_r13 . . . . . . . . . . . .       Text     rsp + 64 - LocalVarsSize\r
+save_rbp . . . . . . . . . . . .       Text     rsp + 48 - LocalVarsSize\r
+save_rbx . . . . . . . . . . . .       Text     rsp + 40 - LocalVarsSize\r
+save_rdi . . . . . . . . . . . .       Text     rsp + 24 - LocalVarsSize\r
+save_rsi . . . . . . . . . . . .       Text     rsp + 32 - LocalVarsSize\r
+strstart . . . . . . . . . . . .       Text     [ rcx + dsStrStart]\r
+window_ad  . . . . . . . . . . .       Text     [ rcx + dsWindow]\r
+window_size  . . . . . . . . . .       Text     [ rcx + dsWSize]\r
+zlib1222add  . . . . . . . . . .       Number   00000008h   \r
+\r
+          0 Warnings\r
+          0 Errors\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.obj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.obj
new file mode 100644 (file)
index 0000000..dc25f15
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/gvmat64.obj differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffas8664.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffas8664.c
new file mode 100644 (file)
index 0000000..e8af06f
--- /dev/null
@@ -0,0 +1,186 @@
+/* inffas8664.c is a hand tuned assembler version of inffast.c - fast decoding\r
+ * version for AMD64 on Windows using Microsoft C compiler\r
+ *\r
+ * Copyright (C) 1995-2003 Mark Adler\r
+ * For conditions of distribution and use, see copyright notice in zlib.h\r
+ *\r
+ * Copyright (C) 2003 Chris Anderson <christop@charm.net>\r
+ * Please use the copyright conditions above.\r
+ *\r
+ * 2005 - Adaptation to Microsoft C Compiler for AMD64 by Gilles Vollant\r
+ *\r
+ * inffas8664.c call function inffas8664fnc in inffasx64.asm\r
+ *  inffasx64.asm is automatically convert from AMD64 portion of inffas86.c\r
+ *\r
+ * Dec-29-2003 -- I added AMD64 inflate asm support.  This version is also\r
+ * slightly quicker on x86 systems because, instead of using rep movsb to copy\r
+ * data, it uses rep movsw, which moves data in 2-byte chunks instead of single\r
+ * bytes.  I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates\r
+ * from http://fedora.linux.duke.edu/fc1_x86_64\r
+ * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with\r
+ * 1GB ram.  The 64-bit version is about 4% faster than the 32-bit version,\r
+ * when decompressing mozilla-source-1.3.tar.gz.\r
+ *\r
+ * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from\r
+ * the gcc -S output of zlib-1.2.0/inffast.c.  Zlib-1.2.0 is in beta release at\r
+ * the moment.  I have successfully compiled and tested this code with gcc2.96,\r
+ * gcc3.2, icc5.0, msvc6.0.  It is very close to the speed of inffast.S\r
+ * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX\r
+ * enabled.  I will attempt to merge the MMX code into this version.  Newer\r
+ * versions of this and inffast.S can be found at\r
+ * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/\r
+ *\r
+ */\r
+\r
+#include <stdio.h>\r
+#include "zutil.h"\r
+#include "inftrees.h"\r
+#include "inflate.h"\r
+#include "inffast.h"\r
+\r
+/* Mark Adler's comments from inffast.c: */\r
+\r
+/*\r
+   Decode literal, length, and distance codes and write out the resulting\r
+   literal and match bytes until either not enough input or output is\r
+   available, an end-of-block is encountered, or a data error is encountered.\r
+   When large enough input and output buffers are supplied to inflate(), for\r
+   example, a 16K input buffer and a 64K output buffer, more than 95% of the\r
+   inflate execution time is spent in this routine.\r
+\r
+   Entry assumptions:\r
+\r
+        state->mode == LEN\r
+        strm->avail_in >= 6\r
+        strm->avail_out >= 258\r
+        start >= strm->avail_out\r
+        state->bits < 8\r
+\r
+   On return, state->mode is one of:\r
+\r
+        LEN -- ran out of enough output space or enough available input\r
+        TYPE -- reached end of block code, inflate() to interpret next block\r
+        BAD -- error in block data\r
+\r
+   Notes:\r
+\r
+    - The maximum input bits used by a length/distance pair is 15 bits for the\r
+      length code, 5 bits for the length extra, 15 bits for the distance code,\r
+      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.\r
+      Therefore if strm->avail_in >= 6, then there is enough input to avoid\r
+      checking for available input while decoding.\r
+\r
+    - The maximum bytes that a single length/distance pair can output is 258\r
+      bytes, which is the maximum length that can be coded.  inflate_fast()\r
+      requires strm->avail_out >= 258 for each loop to avoid checking for\r
+      output space.\r
+ */\r
+\r
+\r
+\r
+    typedef struct inffast_ar {\r
+/* 64   32                               x86  x86_64 */\r
+/* ar offset                              register */\r
+/*  0    0 */ void *esp;                /* esp save */\r
+/*  8    4 */ void *ebp;                /* ebp save */\r
+/* 16    8 */ unsigned char FAR *in;    /* esi rsi  local strm->next_in */\r
+/* 24   12 */ unsigned char FAR *last;  /*     r9   while in < last */\r
+/* 32   16 */ unsigned char FAR *out;   /* edi rdi  local strm->next_out */\r
+/* 40   20 */ unsigned char FAR *beg;   /*          inflate()'s init next_out */\r
+/* 48   24 */ unsigned char FAR *end;   /*     r10  while out < end */\r
+/* 56   28 */ unsigned char FAR *window;/*          size of window, wsize!=0 */\r
+/* 64   32 */ code const FAR *lcode;    /* ebp rbp  local strm->lencode */\r
+/* 72   36 */ code const FAR *dcode;    /*     r11  local strm->distcode */\r
+/* 80   40 */ size_t /*unsigned long */hold;       /* edx rdx  local strm->hold */\r
+/* 88   44 */ unsigned bits;            /* ebx rbx  local strm->bits */\r
+/* 92   48 */ unsigned wsize;           /*          window size */\r
+/* 96   52 */ unsigned write;           /*          window write index */\r
+/*100   56 */ unsigned lmask;           /*     r12  mask for lcode */\r
+/*104   60 */ unsigned dmask;           /*     r13  mask for dcode */\r
+/*108   64 */ unsigned len;             /*     r14  match length */\r
+/*112   68 */ unsigned dist;            /*     r15  match distance */\r
+/*116   72 */ unsigned status;          /*          set when state chng*/\r
+    } type_ar;\r
+#ifdef ASMINF\r
+\r
+void inflate_fast(strm, start)\r
+z_streamp strm;\r
+unsigned start;         /* inflate()'s starting value for strm->avail_out */\r
+{\r
+    struct inflate_state FAR *state;\r
+    type_ar ar;\r
+    void inffas8664fnc(struct inffast_ar * par);\r
+\r
+\r
+\r
+#if (defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )) || (defined(_MSC_VER) && defined(_M_AMD64))\r
+#define PAD_AVAIL_IN 6\r
+#define PAD_AVAIL_OUT 258\r
+#else\r
+#define PAD_AVAIL_IN 5\r
+#define PAD_AVAIL_OUT 257\r
+#endif\r
+\r
+    /* copy state to local variables */\r
+    state = (struct inflate_state FAR *)strm->state;\r
+\r
+    ar.in = strm->next_in;\r
+    ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN);\r
+    ar.out = strm->next_out;\r
+    ar.beg = ar.out - (start - strm->avail_out);\r
+    ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT);\r
+    ar.wsize = state->wsize;\r
+    ar.write = state->wnext;\r
+    ar.window = state->window;\r
+    ar.hold = state->hold;\r
+    ar.bits = state->bits;\r
+    ar.lcode = state->lencode;\r
+    ar.dcode = state->distcode;\r
+    ar.lmask = (1U << state->lenbits) - 1;\r
+    ar.dmask = (1U << state->distbits) - 1;\r
+\r
+    /* decode literals and length/distances until end-of-block or not enough\r
+       input data or output space */\r
+\r
+    /* align in on 1/2 hold size boundary */\r
+    while (((size_t)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) {\r
+        ar.hold += (unsigned long)*ar.in++ << ar.bits;\r
+        ar.bits += 8;\r
+    }\r
+\r
+    inffas8664fnc(&ar);\r
+\r
+    if (ar.status > 1) {\r
+        if (ar.status == 2)\r
+            strm->msg = "invalid literal/length code";\r
+        else if (ar.status == 3)\r
+            strm->msg = "invalid distance code";\r
+        else\r
+            strm->msg = "invalid distance too far back";\r
+        state->mode = BAD;\r
+    }\r
+    else if ( ar.status == 1 ) {\r
+        state->mode = TYPE;\r
+    }\r
+\r
+    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\r
+    ar.len = ar.bits >> 3;\r
+    ar.in -= ar.len;\r
+    ar.bits -= ar.len << 3;\r
+    ar.hold &= (1U << ar.bits) - 1;\r
+\r
+    /* update state and return */\r
+    strm->next_in = ar.in;\r
+    strm->next_out = ar.out;\r
+    strm->avail_in = (unsigned)(ar.in < ar.last ?\r
+                                PAD_AVAIL_IN + (ar.last - ar.in) :\r
+                                PAD_AVAIL_IN - (ar.in - ar.last));\r
+    strm->avail_out = (unsigned)(ar.out < ar.end ?\r
+                                 PAD_AVAIL_OUT + (ar.end - ar.out) :\r
+                                 PAD_AVAIL_OUT - (ar.out - ar.end));\r
+    state->hold = (unsigned long)ar.hold;\r
+    state->bits = ar.bits;\r
+    return;\r
+}\r
+\r
+#endif\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.asm b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.asm
new file mode 100644 (file)
index 0000000..60a8d89
--- /dev/null
@@ -0,0 +1,396 @@
+; inffasx64.asm is a hand tuned assembler version of inffast.c - fast decoding\r
+; version for AMD64 on Windows using Microsoft C compiler\r
+;\r
+; inffasx64.asm is automatically convert from AMD64 portion of inffas86.c\r
+; inffasx64.asm is called by inffas8664.c, which contain more info.\r
+\r
+\r
+; to compile this file, I use option\r
+;   ml64.exe /Flinffasx64 /c /Zi inffasx64.asm\r
+;   with Microsoft Macro Assembler (x64) for AMD64\r
+;\r
+\r
+; This file compile with Microsoft Macro Assembler (x64) for AMD64\r
+;\r
+;   ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK\r
+;\r
+;   (you can get Windows WDK with ml64 for AMD64 from\r
+;      http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price)\r
+;\r
+\r
+\r
+.code\r
+inffas8664fnc PROC\r
+\r
+; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and\r
+; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp\r
+;\r
+; All registers must be preserved across the call, except for\r
+;   rax, rcx, rdx, r8, r-9, r10, and r11, which are scratch.\r
+\r
+\r
+       mov [rsp-8],rsi\r
+       mov [rsp-16],rdi\r
+       mov [rsp-24],r12\r
+       mov [rsp-32],r13\r
+       mov [rsp-40],r14\r
+       mov [rsp-48],r15\r
+       mov [rsp-56],rbx\r
+\r
+       mov rax,rcx\r
+\r
+       mov     [rax+8], rbp       ; /* save regs rbp and rsp */\r
+       mov     [rax], rsp\r
+\r
+       mov     rsp, rax          ; /* make rsp point to &ar */\r
+\r
+       mov     rsi, [rsp+16]      ; /* rsi  = in */\r
+       mov     rdi, [rsp+32]      ; /* rdi  = out */\r
+       mov     r9, [rsp+24]       ; /* r9   = last */\r
+       mov     r10, [rsp+48]      ; /* r10  = end */\r
+       mov     rbp, [rsp+64]      ; /* rbp  = lcode */\r
+       mov     r11, [rsp+72]      ; /* r11  = dcode */\r
+       mov     rdx, [rsp+80]      ; /* rdx  = hold */\r
+       mov     ebx, [rsp+88]      ; /* ebx  = bits */\r
+       mov     r12d, [rsp+100]    ; /* r12d = lmask */\r
+       mov     r13d, [rsp+104]    ; /* r13d = dmask */\r
+                                          ; /* r14d = len */\r
+                                          ; /* r15d = dist */\r
+\r
+\r
+       cld\r
+       cmp     r10, rdi\r
+       je      L_one_time           ; /* if only one decode left */\r
+       cmp     r9, rsi\r
+\r
+    jne L_do_loop\r
+\r
+\r
+L_one_time:\r
+       mov     r8, r12           ; /* r8 = lmask */\r
+       cmp     bl, 32\r
+       ja      L_get_length_code_one_time\r
+\r
+       lodsd                         ; /* eax = *(uint *)in++ */\r
+       mov     cl, bl            ; /* cl = bits, needs it for shifting */\r
+       add     bl, 32             ; /* bits += 32 */\r
+       shl     rax, cl\r
+       or      rdx, rax          ; /* hold |= *((uint *)in)++ << bits */\r
+       jmp     L_get_length_code_one_time\r
+\r
+ALIGN 4\r
+L_while_test:\r
+       cmp     r10, rdi\r
+       jbe     L_break_loop\r
+       cmp     r9, rsi\r
+       jbe     L_break_loop\r
+\r
+L_do_loop:\r
+       mov     r8, r12           ; /* r8 = lmask */\r
+       cmp     bl, 32\r
+       ja      L_get_length_code    ; /* if (32 < bits) */\r
+\r
+       lodsd                         ; /* eax = *(uint *)in++ */\r
+       mov     cl, bl            ; /* cl = bits, needs it for shifting */\r
+       add     bl, 32             ; /* bits += 32 */\r
+       shl     rax, cl\r
+       or      rdx, rax          ; /* hold |= *((uint *)in)++ << bits */\r
+\r
+L_get_length_code:\r
+       and     r8, rdx            ; /* r8 &= hold */\r
+       mov     eax, [rbp+r8*4]  ; /* eax = lcode[hold & lmask] */\r
+\r
+       mov     cl, ah            ; /* cl = this.bits */\r
+       sub     bl, ah            ; /* bits -= this.bits */\r
+       shr     rdx, cl           ; /* hold >>= this.bits */\r
+\r
+       test    al, al\r
+       jnz     L_test_for_length_base ; /* if (op != 0) 45.7% */\r
+\r
+       mov     r8, r12            ; /* r8 = lmask */\r
+       shr     eax, 16            ; /* output this.val char */\r
+       stosb\r
+\r
+L_get_length_code_one_time:\r
+       and     r8, rdx            ; /* r8 &= hold */\r
+       mov     eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */\r
+\r
+L_dolen:\r
+       mov     cl, ah            ; /* cl = this.bits */\r
+       sub     bl, ah            ; /* bits -= this.bits */\r
+       shr     rdx, cl           ; /* hold >>= this.bits */\r
+\r
+       test    al, al\r
+       jnz     L_test_for_length_base ; /* if (op != 0) 45.7% */\r
+\r
+       shr     eax, 16            ; /* output this.val char */\r
+       stosb\r
+       jmp     L_while_test\r
+\r
+ALIGN 4\r
+L_test_for_length_base:\r
+       mov     r14d, eax         ; /* len = this */\r
+       shr     r14d, 16           ; /* len = this.val */\r
+       mov     cl, al\r
+\r
+       test    al, 16\r
+       jz      L_test_for_second_level_length ; /* if ((op & 16) == 0) 8% */\r
+       and     cl, 15             ; /* op &= 15 */\r
+       jz      L_decode_distance    ; /* if (!op) */\r
+\r
+L_add_bits_to_len:\r
+       sub     bl, cl\r
+       xor     eax, eax\r
+       inc     eax\r
+       shl     eax, cl\r
+       dec     eax\r
+       and     eax, edx          ; /* eax &= hold */\r
+       shr     rdx, cl\r
+       add     r14d, eax         ; /* len += hold & mask[op] */\r
+\r
+L_decode_distance:\r
+       mov     r8, r13           ; /* r8 = dmask */\r
+       cmp     bl, 32\r
+       ja      L_get_distance_code  ; /* if (32 < bits) */\r
+\r
+       lodsd                         ; /* eax = *(uint *)in++ */\r
+       mov     cl, bl            ; /* cl = bits, needs it for shifting */\r
+       add     bl, 32             ; /* bits += 32 */\r
+       shl     rax, cl\r
+       or      rdx, rax          ; /* hold |= *((uint *)in)++ << bits */\r
+\r
+L_get_distance_code:\r
+       and     r8, rdx           ; /* r8 &= hold */\r
+       mov     eax, [r11+r8*4] ; /* eax = dcode[hold & dmask] */\r
+\r
+L_dodist:\r
+       mov     r15d, eax         ; /* dist = this */\r
+       shr     r15d, 16           ; /* dist = this.val */\r
+       mov     cl, ah\r
+       sub     bl, ah            ; /* bits -= this.bits */\r
+       shr     rdx, cl           ; /* hold >>= this.bits */\r
+       mov     cl, al            ; /* cl = this.op */\r
+\r
+       test    al, 16             ; /* if ((op & 16) == 0) */\r
+       jz      L_test_for_second_level_dist\r
+       and     cl, 15             ; /* op &= 15 */\r
+       jz      L_check_dist_one\r
+\r
+L_add_bits_to_dist:\r
+       sub     bl, cl\r
+       xor     eax, eax\r
+       inc     eax\r
+       shl     eax, cl\r
+       dec     eax                 ; /* (1 << op) - 1 */\r
+       and     eax, edx          ; /* eax &= hold */\r
+       shr     rdx, cl\r
+       add     r15d, eax         ; /* dist += hold & ((1 << op) - 1) */\r
+\r
+L_check_window:\r
+       mov     r8, rsi           ; /* save in so from can use it's reg */\r
+       mov     rax, rdi\r
+       sub     rax, [rsp+40]      ; /* nbytes = out - beg */\r
+\r
+       cmp     eax, r15d\r
+       jb      L_clip_window        ; /* if (dist > nbytes) 4.2% */\r
+\r
+       mov     ecx, r14d         ; /* ecx = len */\r
+       mov     rsi, rdi\r
+       sub     rsi, r15          ; /* from = out - dist */\r
+\r
+       sar     ecx, 1\r
+       jnc     L_copy_two           ; /* if len % 2 == 0 */\r
+\r
+       rep     movsw\r
+       mov     al, [rsi]\r
+       mov     [rdi], al\r
+       inc     rdi\r
+\r
+       mov     rsi, r8           ; /* move in back to %rsi, toss from */\r
+       jmp     L_while_test\r
+\r
+L_copy_two:\r
+       rep     movsw\r
+       mov     rsi, r8           ; /* move in back to %rsi, toss from */\r
+       jmp     L_while_test\r
+\r
+ALIGN 4\r
+L_check_dist_one:\r
+       cmp     r15d, 1            ; /* if dist 1, is a memset */\r
+       jne     L_check_window\r
+       cmp     [rsp+40], rdi      ; /* if out == beg, outside window */\r
+       je      L_check_window\r
+\r
+       mov     ecx, r14d         ; /* ecx = len */\r
+       mov     al, [rdi-1]\r
+       mov     ah, al\r
+\r
+       sar     ecx, 1\r
+       jnc     L_set_two\r
+       mov     [rdi], al\r
+       inc     rdi\r
+\r
+L_set_two:\r
+       rep     stosw\r
+       jmp     L_while_test\r
+\r
+ALIGN 4\r
+L_test_for_second_level_length:\r
+       test    al, 64\r
+       jnz     L_test_for_end_of_block ; /* if ((op & 64) != 0) */\r
+\r
+       xor     eax, eax\r
+       inc     eax\r
+       shl     eax, cl\r
+       dec     eax\r
+       and     eax, edx         ; /* eax &= hold */\r
+       add     eax, r14d        ; /* eax += len */\r
+       mov     eax, [rbp+rax*4] ; /* eax = lcode[val+(hold&mask[op])]*/\r
+       jmp     L_dolen\r
+\r
+ALIGN 4\r
+L_test_for_second_level_dist:\r
+       test    al, 64\r
+       jnz     L_invalid_distance_code ; /* if ((op & 64) != 0) */\r
+\r
+       xor     eax, eax\r
+       inc     eax\r
+       shl     eax, cl\r
+       dec     eax\r
+       and     eax, edx         ; /* eax &= hold */\r
+       add     eax, r15d        ; /* eax += dist */\r
+       mov     eax, [r11+rax*4] ; /* eax = dcode[val+(hold&mask[op])]*/\r
+       jmp     L_dodist\r
+\r
+ALIGN 4\r
+L_clip_window:\r
+       mov     ecx, eax         ; /* ecx = nbytes */\r
+       mov     eax, [rsp+92]     ; /* eax = wsize, prepare for dist cmp */\r
+       neg     ecx                ; /* nbytes = -nbytes */\r
+\r
+       cmp     eax, r15d\r
+       jb      L_invalid_distance_too_far ; /* if (dist > wsize) */\r
+\r
+       add     ecx, r15d         ; /* nbytes = dist - nbytes */\r
+       cmp     dword ptr [rsp+96], 0\r
+       jne     L_wrap_around_window ; /* if (write != 0) */\r
+\r
+       mov     rsi, [rsp+56]     ; /* from  = window */\r
+       sub     eax, ecx         ; /* eax  -= nbytes */\r
+       add     rsi, rax         ; /* from += wsize - nbytes */\r
+\r
+       mov     eax, r14d        ; /* eax = len */\r
+       cmp     r14d, ecx\r
+       jbe     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+       sub     eax, ecx         ; /* eax -= nbytes */\r
+       rep     movsb\r
+       mov     rsi, rdi\r
+       sub     rsi, r15         ; /* from = &out[ -dist ] */\r
+       jmp     L_do_copy\r
+\r
+ALIGN 4\r
+L_wrap_around_window:\r
+       mov     eax, [rsp+96]     ; /* eax = write */\r
+       cmp     ecx, eax\r
+       jbe     L_contiguous_in_window ; /* if (write >= nbytes) */\r
+\r
+       mov     esi, [rsp+92]     ; /* from  = wsize */\r
+       add     rsi, [rsp+56]     ; /* from += window */\r
+       add     rsi, rax         ; /* from += write */\r
+       sub     rsi, rcx         ; /* from -= nbytes */\r
+       sub     ecx, eax         ; /* nbytes -= write */\r
+\r
+       mov     eax, r14d        ; /* eax = len */\r
+       cmp     eax, ecx\r
+       jbe     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+       sub     eax, ecx         ; /* len -= nbytes */\r
+       rep     movsb\r
+       mov     rsi, [rsp+56]     ; /* from = window */\r
+       mov     ecx, [rsp+96]     ; /* nbytes = write */\r
+       cmp     eax, ecx\r
+       jbe     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+       sub     eax, ecx         ; /* len -= nbytes */\r
+       rep     movsb\r
+       mov     rsi, rdi\r
+       sub     rsi, r15         ; /* from = out - dist */\r
+       jmp     L_do_copy\r
+\r
+ALIGN 4\r
+L_contiguous_in_window:\r
+       mov     rsi, [rsp+56]     ; /* rsi = window */\r
+       add     rsi, rax\r
+       sub     rsi, rcx         ; /* from += write - nbytes */\r
+\r
+       mov     eax, r14d        ; /* eax = len */\r
+       cmp     eax, ecx\r
+       jbe     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+       sub     eax, ecx         ; /* len -= nbytes */\r
+       rep     movsb\r
+       mov     rsi, rdi\r
+       sub     rsi, r15         ; /* from = out - dist */\r
+       jmp     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+ALIGN 4\r
+L_do_copy:\r
+       mov     ecx, eax         ; /* ecx = len */\r
+       rep     movsb\r
+\r
+       mov     rsi, r8          ; /* move in back to %esi, toss from */\r
+       jmp     L_while_test\r
+\r
+L_test_for_end_of_block:\r
+       test    al, 32\r
+       jz      L_invalid_literal_length_code\r
+       mov     dword ptr [rsp+116], 1\r
+       jmp     L_break_loop_with_status\r
+\r
+L_invalid_literal_length_code:\r
+       mov     dword ptr [rsp+116], 2\r
+       jmp     L_break_loop_with_status\r
+\r
+L_invalid_distance_code:\r
+       mov     dword ptr [rsp+116], 3\r
+       jmp     L_break_loop_with_status\r
+\r
+L_invalid_distance_too_far:\r
+       mov     dword ptr [rsp+116], 4\r
+       jmp     L_break_loop_with_status\r
+\r
+L_break_loop:\r
+       mov     dword ptr [rsp+116], 0\r
+\r
+L_break_loop_with_status:\r
+; /* put in, out, bits, and hold back into ar and pop esp */\r
+       mov     [rsp+16], rsi     ; /* in */\r
+       mov     [rsp+32], rdi     ; /* out */\r
+       mov     [rsp+88], ebx     ; /* bits */\r
+       mov     [rsp+80], rdx     ; /* hold */\r
+\r
+       mov     rax, [rsp]       ; /* restore rbp and rsp */\r
+       mov     rbp, [rsp+8]\r
+       mov     rsp, rax\r
+\r
+\r
+\r
+       mov rsi,[rsp-8]\r
+       mov rdi,[rsp-16]\r
+       mov r12,[rsp-24]\r
+       mov r13,[rsp-32]\r
+       mov r14,[rsp-40]\r
+       mov r15,[rsp-48]\r
+       mov rbx,[rsp-56]\r
+\r
+    ret 0\r
+;          :\r
+;          : "m" (ar)\r
+;          : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi",\r
+;            "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15"\r
+;    );\r
+\r
+inffas8664fnc  ENDP\r
+;_TEXT ENDS\r
+END\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.lst b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.lst
new file mode 100644 (file)
index 0000000..53b89a6
--- /dev/null
@@ -0,0 +1,488 @@
+Microsoft (R) Macro Assembler (x64) Version 10.00.40219.01  05/20/14 09:52:26\r
+inffasx64.asm                                               Page 1 - 1\r
+\r
+\r
+                               ; inffasx64.asm is a hand tuned assembler version of inffast.c - fast decoding\r
+                               ; version for AMD64 on Windows using Microsoft C compiler\r
+                               ;\r
+                               ; inffasx64.asm is automatically convert from AMD64 portion of inffas86.c\r
+                               ; inffasx64.asm is called by inffas8664.c, which contain more info.\r
+\r
+\r
+                               ; to compile this file, I use option\r
+                               ;   ml64.exe /Flinffasx64 /c /Zi inffasx64.asm\r
+                               ;   with Microsoft Macro Assembler (x64) for AMD64\r
+                               ;\r
+\r
+                               ; This file compile with Microsoft Macro Assembler (x64) for AMD64\r
+                               ;\r
+                               ;   ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK\r
+                               ;\r
+                               ;   (you can get Windows WDK with ml64 for AMD64 from\r
+                               ;      http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price)\r
+                               ;\r
+\r
+\r
+ 00000000                      .code\r
+ 00000000                      inffas8664fnc PROC\r
+\r
+                               ; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and\r
+                               ; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp\r
+                               ;\r
+                               ; All registers must be preserved across the call, except for\r
+                               ;   rax, rcx, rdx, r8, r-9, r10, and r11, which are scratch.\r
+\r
+\r
+ 00000000  48/ 89 74 24                        mov [rsp-8],rsi\r
+          F8\r
+ 00000005  48/ 89 7C 24                        mov [rsp-16],rdi\r
+          F0\r
+ 0000000A  4C/ 89 64 24                        mov [rsp-24],r12\r
+          E8\r
+ 0000000F  4C/ 89 6C 24                        mov [rsp-32],r13\r
+          E0\r
+ 00000014  4C/ 89 74 24                        mov [rsp-40],r14\r
+          D8\r
+ 00000019  4C/ 89 7C 24                        mov [rsp-48],r15\r
+          D0\r
+ 0000001E  48/ 89 5C 24                        mov [rsp-56],rbx\r
+          C8\r
+\r
+ 00000023  48/ 8B C1                   mov rax,rcx\r
+\r
+ 00000026  48/ 89 68 08                        mov     [rax+8], rbp       ; /* save regs rbp and rsp */\r
+ 0000002A  48/ 89 20                   mov     [rax], rsp\r
+\r
+ 0000002D  48/ 8B E0                   mov     rsp, rax          ; /* make rsp point to &ar */\r
+\r
+ 00000030  48/ 8B 74 24                        mov     rsi, [rsp+16]      ; /* rsi  = in */\r
+          10\r
+ 00000035  48/ 8B 7C 24                        mov     rdi, [rsp+32]      ; /* rdi  = out */\r
+          20\r
+ 0000003A  4C/ 8B 4C 24                        mov     r9, [rsp+24]       ; /* r9   = last */\r
+          18\r
+ 0000003F  4C/ 8B 54 24                        mov     r10, [rsp+48]      ; /* r10  = end */\r
+          30\r
+ 00000044  48/ 8B 6C 24                        mov     rbp, [rsp+64]      ; /* rbp  = lcode */\r
+          40\r
+ 00000049  4C/ 8B 5C 24                        mov     r11, [rsp+72]      ; /* r11  = dcode */\r
+          48\r
+ 0000004E  48/ 8B 54 24                        mov     rdx, [rsp+80]      ; /* rdx  = hold */\r
+          50\r
+ 00000053  8B 5C 24 58                 mov     ebx, [rsp+88]      ; /* ebx  = bits */\r
+ 00000057  44/ 8B 64 24                        mov     r12d, [rsp+100]    ; /* r12d = lmask */\r
+          64\r
+ 0000005C  44/ 8B 6C 24                        mov     r13d, [rsp+104]    ; /* r13d = dmask */\r
+          68\r
+                                                                         ; /* r14d = len */\r
+                                                                         ; /* r15d = dist */\r
+\r
+\r
+ 00000061  FC                          cld\r
+ 00000062  4C/ 3B D7                   cmp     r10, rdi\r
+ 00000065  74 05                       je      L_one_time           ; /* if only one decode left */\r
+ 00000067  4C/ 3B CE                   cmp     r9, rsi\r
+\r
+ 0000006A  75 2A                   jne L_do_loop\r
+\r
+\r
+ 0000006C                      L_one_time:\r
+ 0000006C  4D/ 8B C4                   mov     r8, r12           ; /* r8 = lmask */\r
+ 0000006F  80 FB 20                    cmp     bl, 32\r
+ 00000072  77 50                       ja      L_get_length_code_one_time\r
+\r
+ 00000074  AD                          lodsd                         ; /* eax = *(uint *)in++ */\r
+ 00000075  8A CB                       mov     cl, bl            ; /* cl = bits, needs it for shifting */\r
+ 00000077  80 C3 20                    add     bl, 32             ; /* bits += 32 */\r
+ 0000007A  48/ D3 E0                   shl     rax, cl\r
+ 0000007D  48/ 0B D0                   or      rdx, rax          ; /* hold |= *((uint *)in)++ << bits */\r
+ 00000080  EB 42                       jmp     L_get_length_code_one_time\r
+\r
+                               ALIGN 4\r
+ 00000084                      L_while_test:\r
+ 00000084  4C/ 3B D7                   cmp     r10, rdi\r
+ 00000087  0F 86 0000023F              jbe     L_break_loop\r
+ 0000008D  4C/ 3B CE                   cmp     r9, rsi\r
+ 00000090  0F 86 00000236              jbe     L_break_loop\r
+\r
+ 00000096                      L_do_loop:\r
+ 00000096  4D/ 8B C4                   mov     r8, r12           ; /* r8 = lmask */\r
+ 00000099  80 FB 20                    cmp     bl, 32\r
+ 0000009C  77 0C                       ja      L_get_length_code    ; /* if (32 < bits) */\r
+\r
+ 0000009E  AD                          lodsd                         ; /* eax = *(uint *)in++ */\r
+ 0000009F  8A CB                       mov     cl, bl            ; /* cl = bits, needs it for shifting */\r
+ 000000A1  80 C3 20                    add     bl, 32             ; /* bits += 32 */\r
+ 000000A4  48/ D3 E0                   shl     rax, cl\r
+ 000000A7  48/ 0B D0                   or      rdx, rax          ; /* hold |= *((uint *)in)++ << bits */\r
+\r
+ 000000AA                      L_get_length_code:\r
+ 000000AA  4C/ 23 C2                   and     r8, rdx            ; /* r8 &= hold */\r
+ 000000AD  42/ 8B 44 85                        mov     eax, [rbp+r8*4]  ; /* eax = lcode[hold & lmask] */\r
+          00\r
+\r
+ 000000B2  8A CC                       mov     cl, ah            ; /* cl = this.bits */\r
+ 000000B4  2A DC                       sub     bl, ah            ; /* bits -= this.bits */\r
+ 000000B6  48/ D3 EA                   shr     rdx, cl           ; /* hold >>= this.bits */\r
+\r
+ 000000B9  84 C0                       test    al, al\r
+ 000000BB  75 23                       jnz     L_test_for_length_base ; /* if (op != 0) 45.7% */\r
+\r
+ 000000BD  4D/ 8B C4                   mov     r8, r12            ; /* r8 = lmask */\r
+ 000000C0  C1 E8 10                    shr     eax, 16            ; /* output this.val char */\r
+ 000000C3  AA                          stosb\r
+\r
+ 000000C4                      L_get_length_code_one_time:\r
+ 000000C4  4C/ 23 C2                   and     r8, rdx            ; /* r8 &= hold */\r
+ 000000C7  42/ 8B 44 85                        mov     eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */\r
+          00\r
+\r
+ 000000CC                      L_dolen:\r
+ 000000CC  8A CC                       mov     cl, ah            ; /* cl = this.bits */\r
+ 000000CE  2A DC                       sub     bl, ah            ; /* bits -= this.bits */\r
+ 000000D0  48/ D3 EA                   shr     rdx, cl           ; /* hold >>= this.bits */\r
+\r
+ 000000D3  84 C0                       test    al, al\r
+ 000000D5  75 09                       jnz     L_test_for_length_base ; /* if (op != 0) 45.7% */\r
+\r
+ 000000D7  C1 E8 10                    shr     eax, 16            ; /* output this.val char */\r
+ 000000DA  AA                          stosb\r
+ 000000DB  EB A7                       jmp     L_while_test\r
+\r
+                               ALIGN 4\r
+ 000000E0                      L_test_for_length_base:\r
+ 000000E0  44/ 8B F0                   mov     r14d, eax         ; /* len = this */\r
+ 000000E3  41/ C1 EE 10                        shr     r14d, 16           ; /* len = this.val */\r
+ 000000E7  8A C8                       mov     cl, al\r
+\r
+ 000000E9  A8 10                       test    al, 16\r
+ 000000EB  0F 84 000000C7              jz      L_test_for_second_level_length ; /* if ((op & 16) == 0) 8% */\r
+ 000000F1  80 E1 0F                    and     cl, 15             ; /* op &= 15 */\r
+ 000000F4  74 12                       jz      L_decode_distance    ; /* if (!op) */\r
+\r
+ 000000F6                      L_add_bits_to_len:\r
+ 000000F6  2A D9                       sub     bl, cl\r
+ 000000F8  33 C0                       xor     eax, eax\r
+ 000000FA  FF C0                       inc     eax\r
+ 000000FC  D3 E0                       shl     eax, cl\r
+ 000000FE  FF C8                       dec     eax\r
+ 00000100  23 C2                       and     eax, edx          ; /* eax &= hold */\r
+ 00000102  48/ D3 EA                   shr     rdx, cl\r
+ 00000105  44/ 03 F0                   add     r14d, eax         ; /* len += hold & mask[op] */\r
+\r
+ 00000108                      L_decode_distance:\r
+ 00000108  4D/ 8B C5                   mov     r8, r13           ; /* r8 = dmask */\r
+ 0000010B  80 FB 20                    cmp     bl, 32\r
+ 0000010E  77 0C                       ja      L_get_distance_code  ; /* if (32 < bits) */\r
+\r
+ 00000110  AD                          lodsd                         ; /* eax = *(uint *)in++ */\r
+ 00000111  8A CB                       mov     cl, bl            ; /* cl = bits, needs it for shifting */\r
+ 00000113  80 C3 20                    add     bl, 32             ; /* bits += 32 */\r
+ 00000116  48/ D3 E0                   shl     rax, cl\r
+ 00000119  48/ 0B D0                   or      rdx, rax          ; /* hold |= *((uint *)in)++ << bits */\r
+\r
+ 0000011C                      L_get_distance_code:\r
+ 0000011C  4C/ 23 C2                   and     r8, rdx           ; /* r8 &= hold */\r
+ 0000011F  43/ 8B 04 83                        mov     eax, [r11+r8*4] ; /* eax = dcode[hold & dmask] */\r
+\r
+ 00000123                      L_dodist:\r
+ 00000123  44/ 8B F8                   mov     r15d, eax         ; /* dist = this */\r
+ 00000126  41/ C1 EF 10                        shr     r15d, 16           ; /* dist = this.val */\r
+ 0000012A  8A CC                       mov     cl, ah\r
+ 0000012C  2A DC                       sub     bl, ah            ; /* bits -= this.bits */\r
+ 0000012E  48/ D3 EA                   shr     rdx, cl           ; /* hold >>= this.bits */\r
+ 00000131  8A C8                       mov     cl, al            ; /* cl = this.op */\r
+\r
+ 00000133  A8 10                       test    al, 16             ; /* if ((op & 16) == 0) */\r
+ 00000135  0F 84 0000009D              jz      L_test_for_second_level_dist\r
+ 0000013B  80 E1 0F                    and     cl, 15             ; /* op &= 15 */\r
+ 0000013E  74 50                       jz      L_check_dist_one\r
+\r
+ 00000140                      L_add_bits_to_dist:\r
+ 00000140  2A D9                       sub     bl, cl\r
+ 00000142  33 C0                       xor     eax, eax\r
+ 00000144  FF C0                       inc     eax\r
+ 00000146  D3 E0                       shl     eax, cl\r
+ 00000148  FF C8                       dec     eax                 ; /* (1 << op) - 1 */\r
+ 0000014A  23 C2                       and     eax, edx          ; /* eax &= hold */\r
+ 0000014C  48/ D3 EA                   shr     rdx, cl\r
+ 0000014F  44/ 03 F8                   add     r15d, eax         ; /* dist += hold & ((1 << op) - 1) */\r
+\r
+ 00000152                      L_check_window:\r
+ 00000152  4C/ 8B C6                   mov     r8, rsi           ; /* save in so from can use it's reg */\r
+ 00000155  48/ 8B C7                   mov     rax, rdi\r
+ 00000158  48/ 2B 44 24                        sub     rax, [rsp+40]      ; /* nbytes = out - beg */\r
+          28\r
+\r
+ 0000015D  41/ 3B C7                   cmp     eax, r15d\r
+ 00000160  0F 82 00000092              jb      L_clip_window        ; /* if (dist > nbytes) 4.2% */\r
+\r
+ 00000166  41/ 8B CE                   mov     ecx, r14d         ; /* ecx = len */\r
+ 00000169  48/ 8B F7                   mov     rsi, rdi\r
+ 0000016C  49/ 2B F7                   sub     rsi, r15          ; /* from = out - dist */\r
+\r
+ 0000016F  D1 F9                       sar     ecx, 1\r
+ 00000171  73 12                       jnc     L_copy_two           ; /* if len % 2 == 0 */\r
+\r
+ 00000173  F3/ 66| A5                  rep     movsw\r
+ 00000176  8A 06                       mov     al, [rsi]\r
+ 00000178  88 07                       mov     [rdi], al\r
+ 0000017A  48/ FF C7                   inc     rdi\r
+\r
+ 0000017D  49/ 8B F0                   mov     rsi, r8           ; /* move in back to %rsi, toss from */\r
+ 00000180  E9 FFFFFEFF                 jmp     L_while_test\r
+\r
+ 00000185                      L_copy_two:\r
+ 00000185  F3/ 66| A5                  rep     movsw\r
+ 00000188  49/ 8B F0                   mov     rsi, r8           ; /* move in back to %rsi, toss from */\r
+ 0000018B  E9 FFFFFEF4                 jmp     L_while_test\r
+\r
+                               ALIGN 4\r
+ 00000190                      L_check_dist_one:\r
+ 00000190  41/ 83 FF 01                        cmp     r15d, 1            ; /* if dist 1, is a memset */\r
+ 00000194  75 BC                       jne     L_check_window\r
+ 00000196  48/ 39 7C 24                        cmp     [rsp+40], rdi      ; /* if out == beg, outside window */\r
+          28\r
+ 0000019B  74 B5                       je      L_check_window\r
+\r
+ 0000019D  41/ 8B CE                   mov     ecx, r14d         ; /* ecx = len */\r
+ 000001A0  8A 47 FF                    mov     al, [rdi-1]\r
+ 000001A3  8A E0                       mov     ah, al\r
+\r
+ 000001A5  D1 F9                       sar     ecx, 1\r
+ 000001A7  73 05                       jnc     L_set_two\r
+ 000001A9  88 07                       mov     [rdi], al\r
+ 000001AB  48/ FF C7                   inc     rdi\r
+\r
+ 000001AE                      L_set_two:\r
+ 000001AE  F3/ 66| AB                  rep     stosw\r
+ 000001B1  E9 FFFFFECE                 jmp     L_while_test\r
+\r
+                               ALIGN 4\r
+ 000001B8                      L_test_for_second_level_length:\r
+ 000001B8  A8 40                       test    al, 64\r
+ 000001BA  0F 85 000000E0              jnz     L_test_for_end_of_block ; /* if ((op & 64) != 0) */\r
+\r
+ 000001C0  33 C0                       xor     eax, eax\r
+ 000001C2  FF C0                       inc     eax\r
+ 000001C4  D3 E0                       shl     eax, cl\r
+ 000001C6  FF C8                       dec     eax\r
+ 000001C8  23 C2                       and     eax, edx         ; /* eax &= hold */\r
+ 000001CA  41/ 03 C6                   add     eax, r14d        ; /* eax += len */\r
+ 000001CD  8B 44 85 00                 mov     eax, [rbp+rax*4] ; /* eax = lcode[val+(hold&mask[op])]*/\r
+ 000001D1  E9 FFFFFEF6                 jmp     L_dolen\r
+\r
+                               ALIGN 4\r
+ 000001D8                      L_test_for_second_level_dist:\r
+ 000001D8  A8 40                       test    al, 64\r
+ 000001DA  0F 85 000000D8              jnz     L_invalid_distance_code ; /* if ((op & 64) != 0) */\r
+\r
+ 000001E0  33 C0                       xor     eax, eax\r
+ 000001E2  FF C0                       inc     eax\r
+ 000001E4  D3 E0                       shl     eax, cl\r
+ 000001E6  FF C8                       dec     eax\r
+ 000001E8  23 C2                       and     eax, edx         ; /* eax &= hold */\r
+ 000001EA  41/ 03 C7                   add     eax, r15d        ; /* eax += dist */\r
+ 000001ED  41/ 8B 04 83                        mov     eax, [r11+rax*4] ; /* eax = dcode[val+(hold&mask[op])]*/\r
+ 000001F1  E9 FFFFFF2D                 jmp     L_dodist\r
+\r
+                               ALIGN 4\r
+ 000001F8                      L_clip_window:\r
+ 000001F8  8B C8                       mov     ecx, eax         ; /* ecx = nbytes */\r
+ 000001FA  8B 44 24 5C                 mov     eax, [rsp+92]     ; /* eax = wsize, prepare for dist cmp */\r
+ 000001FE  F7 D9                       neg     ecx                ; /* nbytes = -nbytes */\r
+\r
+ 00000200  41/ 3B C7                   cmp     eax, r15d\r
+ 00000203  0F 82 000000B9              jb      L_invalid_distance_too_far ; /* if (dist > wsize) */\r
+\r
+ 00000209  41/ 03 CF                   add     ecx, r15d         ; /* nbytes = dist - nbytes */\r
+ 0000020C  83 7C 24 60 00              cmp     dword ptr [rsp+96], 0\r
+ 00000211  75 21                       jne     L_wrap_around_window ; /* if (write != 0) */\r
+\r
+ 00000213  48/ 8B 74 24                        mov     rsi, [rsp+56]     ; /* from  = window */\r
+          38\r
+ 00000218  2B C1                       sub     eax, ecx         ; /* eax  -= nbytes */\r
+ 0000021A  48/ 03 F0                   add     rsi, rax         ; /* from += wsize - nbytes */\r
+\r
+ 0000021D  41/ 8B C6                   mov     eax, r14d        ; /* eax = len */\r
+ 00000220  44/ 3B F1                   cmp     r14d, ecx\r
+ 00000223  76 6F                       jbe     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+ 00000225  2B C1                       sub     eax, ecx         ; /* eax -= nbytes */\r
+ 00000227  F3/ A4                      rep     movsb\r
+ 00000229  48/ 8B F7                   mov     rsi, rdi\r
+ 0000022C  49/ 2B F7                   sub     rsi, r15         ; /* from = &out[ -dist ] */\r
+ 0000022F  EB 63                       jmp     L_do_copy\r
+\r
+                               ALIGN 4\r
+ 00000234                      L_wrap_around_window:\r
+ 00000234  8B 44 24 60                 mov     eax, [rsp+96]     ; /* eax = write */\r
+ 00000238  3B C8                       cmp     ecx, eax\r
+ 0000023A  76 38                       jbe     L_contiguous_in_window ; /* if (write >= nbytes) */\r
+\r
+ 0000023C  8B 74 24 5C                 mov     esi, [rsp+92]     ; /* from  = wsize */\r
+ 00000240  48/ 03 74 24                        add     rsi, [rsp+56]     ; /* from += window */\r
+          38\r
+ 00000245  48/ 03 F0                   add     rsi, rax         ; /* from += write */\r
+ 00000248  48/ 2B F1                   sub     rsi, rcx         ; /* from -= nbytes */\r
+ 0000024B  2B C8                       sub     ecx, eax         ; /* nbytes -= write */\r
+\r
+ 0000024D  41/ 8B C6                   mov     eax, r14d        ; /* eax = len */\r
+ 00000250  3B C1                       cmp     eax, ecx\r
+ 00000252  76 40                       jbe     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+ 00000254  2B C1                       sub     eax, ecx         ; /* len -= nbytes */\r
+ 00000256  F3/ A4                      rep     movsb\r
+ 00000258  48/ 8B 74 24                        mov     rsi, [rsp+56]     ; /* from = window */\r
+          38\r
+ 0000025D  8B 4C 24 60                 mov     ecx, [rsp+96]     ; /* nbytes = write */\r
+ 00000261  3B C1                       cmp     eax, ecx\r
+ 00000263  76 2F                       jbe     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+ 00000265  2B C1                       sub     eax, ecx         ; /* len -= nbytes */\r
+ 00000267  F3/ A4                      rep     movsb\r
+ 00000269  48/ 8B F7                   mov     rsi, rdi\r
+ 0000026C  49/ 2B F7                   sub     rsi, r15         ; /* from = out - dist */\r
+ 0000026F  EB 23                       jmp     L_do_copy\r
+\r
+                               ALIGN 4\r
+ 00000274                      L_contiguous_in_window:\r
+ 00000274  48/ 8B 74 24                        mov     rsi, [rsp+56]     ; /* rsi = window */\r
+          38\r
+ 00000279  48/ 03 F0                   add     rsi, rax\r
+ 0000027C  48/ 2B F1                   sub     rsi, rcx         ; /* from += write - nbytes */\r
+\r
+ 0000027F  41/ 8B C6                   mov     eax, r14d        ; /* eax = len */\r
+ 00000282  3B C1                       cmp     eax, ecx\r
+ 00000284  76 0E                       jbe     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+ 00000286  2B C1                       sub     eax, ecx         ; /* len -= nbytes */\r
+ 00000288  F3/ A4                      rep     movsb\r
+ 0000028A  48/ 8B F7                   mov     rsi, rdi\r
+ 0000028D  49/ 2B F7                   sub     rsi, r15         ; /* from = out - dist */\r
+ 00000290  EB 02                       jmp     L_do_copy           ; /* if (nbytes >= len) */\r
+\r
+                               ALIGN 4\r
+ 00000294                      L_do_copy:\r
+ 00000294  8B C8                       mov     ecx, eax         ; /* ecx = len */\r
+ 00000296  F3/ A4                      rep     movsb\r
+\r
+ 00000298  49/ 8B F0                   mov     rsi, r8          ; /* move in back to %esi, toss from */\r
+ 0000029B  E9 FFFFFDE4                 jmp     L_while_test\r
+\r
+ 000002A0                      L_test_for_end_of_block:\r
+ 000002A0  A8 20                       test    al, 32\r
+ 000002A2  74 0A                       jz      L_invalid_literal_length_code\r
+ 000002A4  C7 44 24 74                 mov     dword ptr [rsp+116], 1\r
+          00000001\r
+ 000002AC  EB 26                       jmp     L_break_loop_with_status\r
+\r
+ 000002AE                      L_invalid_literal_length_code:\r
+ 000002AE  C7 44 24 74                 mov     dword ptr [rsp+116], 2\r
+          00000002\r
+ 000002B6  EB 1C                       jmp     L_break_loop_with_status\r
+\r
+ 000002B8                      L_invalid_distance_code:\r
+ 000002B8  C7 44 24 74                 mov     dword ptr [rsp+116], 3\r
+          00000003\r
+ 000002C0  EB 12                       jmp     L_break_loop_with_status\r
+\r
+ 000002C2                      L_invalid_distance_too_far:\r
+ 000002C2  C7 44 24 74                 mov     dword ptr [rsp+116], 4\r
+          00000004\r
+ 000002CA  EB 08                       jmp     L_break_loop_with_status\r
+\r
+ 000002CC                      L_break_loop:\r
+ 000002CC  C7 44 24 74                 mov     dword ptr [rsp+116], 0\r
+          00000000\r
+\r
+ 000002D4                      L_break_loop_with_status:\r
+                               ; /* put in, out, bits, and hold back into ar and pop esp */\r
+ 000002D4  48/ 89 74 24                        mov     [rsp+16], rsi     ; /* in */\r
+          10\r
+ 000002D9  48/ 89 7C 24                        mov     [rsp+32], rdi     ; /* out */\r
+          20\r
+ 000002DE  89 5C 24 58                 mov     [rsp+88], ebx     ; /* bits */\r
+ 000002E2  48/ 89 54 24                        mov     [rsp+80], rdx     ; /* hold */\r
+          50\r
+\r
+ 000002E7  48/ 8B 04 24                        mov     rax, [rsp]       ; /* restore rbp and rsp */\r
+ 000002EB  48/ 8B 6C 24                        mov     rbp, [rsp+8]\r
+          08\r
+ 000002F0  48/ 8B E0                   mov     rsp, rax\r
+\r
+\r
+\r
+ 000002F3  48/ 8B 74 24                        mov rsi,[rsp-8]\r
+          F8\r
+ 000002F8  48/ 8B 7C 24                        mov rdi,[rsp-16]\r
+          F0\r
+ 000002FD  4C/ 8B 64 24                        mov r12,[rsp-24]\r
+          E8\r
+ 00000302  4C/ 8B 6C 24                        mov r13,[rsp-32]\r
+          E0\r
+ 00000307  4C/ 8B 74 24                        mov r14,[rsp-40]\r
+          D8\r
+ 0000030C  4C/ 8B 7C 24                        mov r15,[rsp-48]\r
+          D0\r
+ 00000311  48/ 8B 5C 24                        mov rbx,[rsp-56]\r
+          C8\r
+\r
+ 00000316  C3                      ret 0\r
+                               ;          :\r
+                               ;          : "m" (ar)\r
+                               ;          : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi",\r
+                               ;            "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15"\r
+                               ;    );\r
+\r
+ 00000317                      inffas8664fnc   ENDP\r
+                               ;_TEXT  ENDS\r
+                               END\r
+\fMicrosoft (R) Macro Assembler (x64) Version 10.00.40219.01  05/20/14 09:52:26\r
+inffasx64.asm                                               Symbols 2 - 1\r
+\r
+\r
+\r
+\r
+Procedures, parameters, and locals:\r
+\r
+                N a m e                 Type     Value    Attr\r
+\r
+inffas8664fnc  . . . . . . . . .       P        00000000 _TEXT Length= 00000317 Public\r
+  L_one_time . . . . . . . . . .       L        0000006C _TEXT \r
+  L_while_test . . . . . . . . .       L        00000084 _TEXT \r
+  L_do_loop  . . . . . . . . . .       L        00000096 _TEXT \r
+  L_get_length_code  . . . . . .       L        000000AA _TEXT \r
+  L_get_length_code_one_time . .       L        000000C4 _TEXT \r
+  L_dolen  . . . . . . . . . . .       L        000000CC _TEXT \r
+  L_test_for_length_base . . . .       L        000000E0 _TEXT \r
+  L_add_bits_to_len  . . . . . .       L        000000F6 _TEXT \r
+  L_decode_distance  . . . . . .       L        00000108 _TEXT \r
+  L_get_distance_code  . . . . .       L        0000011C _TEXT \r
+  L_dodist . . . . . . . . . . .       L        00000123 _TEXT \r
+  L_add_bits_to_dist . . . . . .       L        00000140 _TEXT \r
+  L_check_window . . . . . . . .       L        00000152 _TEXT \r
+  L_copy_two . . . . . . . . . .       L        00000185 _TEXT \r
+  L_check_dist_one . . . . . . .       L        00000190 _TEXT \r
+  L_set_two  . . . . . . . . . .       L        000001AE _TEXT \r
+  L_test_for_second_level_length .     L        000001B8 _TEXT \r
+  L_test_for_second_level_dist .       L        000001D8 _TEXT \r
+  L_clip_window  . . . . . . . .       L        000001F8 _TEXT \r
+  L_wrap_around_window . . . . .       L        00000234 _TEXT \r
+  L_contiguous_in_window . . . .       L        00000274 _TEXT \r
+  L_do_copy  . . . . . . . . . .       L        00000294 _TEXT \r
+  L_test_for_end_of_block  . . .       L        000002A0 _TEXT \r
+  L_invalid_literal_length_code        L        000002AE _TEXT \r
+  L_invalid_distance_code  . . .       L        000002B8 _TEXT \r
+  L_invalid_distance_too_far . .       L        000002C2 _TEXT \r
+  L_break_loop . . . . . . . . .       L        000002CC _TEXT \r
+  L_break_loop_with_status . . .       L        000002D4 _TEXT \r
+\r
+\r
+Symbols:\r
+\r
+                N a m e                 Type     Value    Attr\r
+\r
+\r
+          0 Warnings\r
+          0 Errors\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.obj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.obj
new file mode 100644 (file)
index 0000000..7136ecc
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/inffasx64.obj differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx64/readme.txt
new file mode 100644 (file)
index 0000000..2da6733
--- /dev/null
@@ -0,0 +1,31 @@
+Summary\r
+-------\r
+This directory contains ASM implementations of the functions\r
+longest_match() and inflate_fast(), for 64 bits x86 (both AMD64 and Intel EM64t),\r
+for use with Microsoft Macro Assembler (x64) for AMD64 and Microsoft C++ 64 bits.\r
+\r
+gvmat64.asm is written by Gilles Vollant (2005), by using Brian Raiter 686/32 bits\r
+   assembly optimized version from Jean-loup Gailly original longest_match function\r
+\r
+inffasx64.asm and inffas8664.c were written by Chris Anderson, by optimizing\r
+   original function from Mark Adler\r
+\r
+Use instructions\r
+----------------\r
+Assemble the .asm files using MASM and put the object files into the zlib source\r
+directory.  You can also get object files here:\r
+\r
+     http://www.winimage.com/zLibDll/zlib124_masm_obj.zip\r
+\r
+define ASMV and ASMINF in your project. Include inffas8664.c in your source tree,\r
+and inffasx64.obj and gvmat64.obj as object to link.\r
+\r
+\r
+Build instructions\r
+------------------\r
+run bld_64.bat with Microsoft Macro Assembler (x64) for AMD64 (ml64.exe)\r
+\r
+ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK\r
+\r
+You can get Windows 2003 server DDK with ml64 and cl for AMD64 from\r
+  http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price)\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/bld_ml32.bat b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/bld_ml32.bat
new file mode 100644 (file)
index 0000000..e1b86bf
--- /dev/null
@@ -0,0 +1,2 @@
+ml /coff /Zi /c /Flmatch686.lst match686.asm\r
+ml /coff /Zi /c /Flinffas32.lst inffas32.asm\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/inffas32.asm b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/inffas32.asm
new file mode 100644 (file)
index 0000000..03d20f8
--- /dev/null
@@ -0,0 +1,1080 @@
+;/* inffas32.asm is a hand tuned assembler version of inffast.c -- fast decoding\r
+; *\r
+; * inffas32.asm is derivated from inffas86.c, with translation of assembly code\r
+; *\r
+; * Copyright (C) 1995-2003 Mark Adler\r
+; * For conditions of distribution and use, see copyright notice in zlib.h\r
+; *\r
+; * Copyright (C) 2003 Chris Anderson <christop@charm.net>\r
+; * Please use the copyright conditions above.\r
+; *\r
+; * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from\r
+; * the gcc -S output of zlib-1.2.0/inffast.c.  Zlib-1.2.0 is in beta release at\r
+; * the moment.  I have successfully compiled and tested this code with gcc2.96,\r
+; * gcc3.2, icc5.0, msvc6.0.  It is very close to the speed of inffast.S\r
+; * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX\r
+; * enabled.  I will attempt to merge the MMX code into this version.  Newer\r
+; * versions of this and inffast.S can be found at\r
+; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/\r
+; *\r
+; * 2005 : modification by Gilles Vollant\r
+; */\r
+; For Visual C++ 4.x and higher and ML 6.x and higher\r
+;   ml.exe is in directory \MASM611C of Win95 DDK\r
+;   ml.exe is also distributed in http://www.masm32.com/masmdl.htm\r
+;    and in VC++2003 toolkit at http://msdn.microsoft.com/visualc/vctoolkit2003/\r
+;\r
+;\r
+;   compile with command line option\r
+;   ml  /coff /Zi /c /Flinffas32.lst inffas32.asm\r
+\r
+;   if you define NO_GZIP (see inflate.h), compile with\r
+;   ml  /coff /Zi /c /Flinffas32.lst /DNO_GUNZIP inffas32.asm\r
+\r
+\r
+; zlib122sup is 0 fort zlib 1.2.2.1 and lower\r
+; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head\r
+;        in inflate_state in inflate.h)\r
+zlib1222sup      equ    8\r
+\r
+\r
+IFDEF GUNZIP\r
+  INFLATE_MODE_TYPE    equ 11\r
+  INFLATE_MODE_BAD     equ 26\r
+ELSE\r
+  IFNDEF NO_GUNZIP\r
+    INFLATE_MODE_TYPE    equ 11\r
+    INFLATE_MODE_BAD     equ 26\r
+  ELSE\r
+    INFLATE_MODE_TYPE    equ 3\r
+    INFLATE_MODE_BAD     equ 17\r
+  ENDIF\r
+ENDIF\r
+\r
+\r
+; 75 "inffast.S"\r
+;FILE "inffast.S"\r
+\r
+;;;GLOBAL _inflate_fast\r
+\r
+;;;SECTION .text\r
+\r
+\r
+\r
+       .586p\r
+       .mmx\r
+\r
+       name    inflate_fast_x86\r
+       .MODEL  FLAT\r
+\r
+_DATA                  segment\r
+inflate_fast_use_mmx:\r
+       dd      1\r
+\r
+\r
+_TEXT                  segment\r
+\r
+\r
+\r
+ALIGN 4\r
+       db      'Fast decoding Code from Chris Anderson'\r
+       db      0\r
+\r
+ALIGN 4\r
+invalid_literal_length_code_msg:\r
+       db      'invalid literal/length code'\r
+       db      0\r
+\r
+ALIGN 4\r
+invalid_distance_code_msg:\r
+       db      'invalid distance code'\r
+       db      0\r
+\r
+ALIGN 4\r
+invalid_distance_too_far_msg:\r
+       db      'invalid distance too far back'\r
+       db      0\r
+\r
+\r
+ALIGN 4\r
+inflate_fast_mask:\r
+dd     0\r
+dd     1\r
+dd     3\r
+dd     7\r
+dd     15\r
+dd     31\r
+dd     63\r
+dd     127\r
+dd     255\r
+dd     511\r
+dd     1023\r
+dd     2047\r
+dd     4095\r
+dd     8191\r
+dd     16383\r
+dd     32767\r
+dd     65535\r
+dd     131071\r
+dd     262143\r
+dd     524287\r
+dd     1048575\r
+dd     2097151\r
+dd     4194303\r
+dd     8388607\r
+dd     16777215\r
+dd     33554431\r
+dd     67108863\r
+dd     134217727\r
+dd     268435455\r
+dd     536870911\r
+dd     1073741823\r
+dd     2147483647\r
+dd     4294967295\r
+\r
+\r
+mode_state      equ    0       ;/* state->mode */\r
+wsize_state     equ    (32+zlib1222sup)        ;/* state->wsize */\r
+write_state     equ    (36+4+zlib1222sup)      ;/* state->write */\r
+window_state    equ    (40+4+zlib1222sup)      ;/* state->window */\r
+hold_state      equ    (44+4+zlib1222sup)      ;/* state->hold */\r
+bits_state      equ    (48+4+zlib1222sup)      ;/* state->bits */\r
+lencode_state   equ    (64+4+zlib1222sup)      ;/* state->lencode */\r
+distcode_state  equ    (68+4+zlib1222sup)      ;/* state->distcode */\r
+lenbits_state   equ    (72+4+zlib1222sup)      ;/* state->lenbits */\r
+distbits_state  equ    (76+4+zlib1222sup)      ;/* state->distbits */\r
+\r
+\r
+;;SECTION .text\r
+; 205 "inffast.S"\r
+;GLOBAL        inflate_fast_use_mmx\r
+\r
+;SECTION .data\r
+\r
+\r
+; GLOBAL inflate_fast_use_mmx:object\r
+;.size inflate_fast_use_mmx, 4\r
+; 226 "inffast.S"\r
+;SECTION .text\r
+\r
+ALIGN 4\r
+_inflate_fast proc near\r
+.FPO (16, 4, 0, 0, 1, 0)\r
+       push  edi\r
+       push  esi\r
+       push  ebp\r
+       push  ebx\r
+       pushfd\r
+       sub  esp,64\r
+       cld\r
+\r
+\r
+\r
+\r
+       mov  esi, [esp+88]\r
+       mov  edi, [esi+28]\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+       mov  edx, [esi+4]\r
+       mov  eax, [esi+0]\r
+\r
+       add  edx,eax\r
+       sub  edx,11\r
+\r
+       mov  [esp+44],eax\r
+       mov  [esp+20],edx\r
+\r
+       mov  ebp, [esp+92]\r
+       mov  ecx, [esi+16]\r
+       mov  ebx, [esi+12]\r
+\r
+       sub  ebp,ecx\r
+       neg  ebp\r
+       add  ebp,ebx\r
+\r
+       sub  ecx,257\r
+       add  ecx,ebx\r
+\r
+       mov  [esp+60],ebx\r
+       mov  [esp+40],ebp\r
+       mov  [esp+16],ecx\r
+; 285 "inffast.S"\r
+       mov  eax, [edi+lencode_state]\r
+       mov  ecx, [edi+distcode_state]\r
+\r
+       mov  [esp+8],eax\r
+       mov  [esp+12],ecx\r
+\r
+       mov  eax,1\r
+       mov  ecx, [edi+lenbits_state]\r
+       shl  eax,cl\r
+       dec  eax\r
+       mov  [esp+0],eax\r
+\r
+       mov  eax,1\r
+       mov  ecx, [edi+distbits_state]\r
+       shl  eax,cl\r
+       dec  eax\r
+       mov  [esp+4],eax\r
+\r
+       mov  eax, [edi+wsize_state]\r
+       mov  ecx, [edi+write_state]\r
+       mov  edx, [edi+window_state]\r
+\r
+       mov  [esp+52],eax\r
+       mov  [esp+48],ecx\r
+       mov  [esp+56],edx\r
+\r
+       mov  ebp, [edi+hold_state]\r
+       mov  ebx, [edi+bits_state]\r
+; 321 "inffast.S"\r
+       mov  esi, [esp+44]\r
+       mov  ecx, [esp+20]\r
+       cmp  ecx,esi\r
+       ja   L_align_long\r
+\r
+       add  ecx,11\r
+       sub  ecx,esi\r
+       mov  eax,12\r
+       sub  eax,ecx\r
+       lea  edi, [esp+28]\r
+       rep movsb\r
+       mov  ecx,eax\r
+       xor  eax,eax\r
+       rep stosb\r
+       lea  esi, [esp+28]\r
+       mov  [esp+20],esi\r
+       jmp  L_is_aligned\r
+\r
+\r
+L_align_long:\r
+       test  esi,3\r
+       jz   L_is_aligned\r
+       xor  eax,eax\r
+       mov  al, [esi]\r
+       inc  esi\r
+       mov  ecx,ebx\r
+       add  ebx,8\r
+       shl  eax,cl\r
+       or  ebp,eax\r
+       jmp L_align_long\r
+\r
+L_is_aligned:\r
+       mov  edi, [esp+60]\r
+; 366 "inffast.S"\r
+L_check_mmx:\r
+       cmp  dword ptr [inflate_fast_use_mmx],2\r
+       je   L_init_mmx\r
+       ja   L_do_loop\r
+\r
+       push  eax\r
+       push  ebx\r
+       push  ecx\r
+       push  edx\r
+       pushfd\r
+       mov  eax, [esp]\r
+       xor  dword ptr [esp],0200000h\r
+\r
+\r
+\r
+\r
+       popfd\r
+       pushfd\r
+       pop  edx\r
+       xor  edx,eax\r
+       jz   L_dont_use_mmx\r
+       xor  eax,eax\r
+       cpuid\r
+       cmp  ebx,0756e6547h\r
+       jne  L_dont_use_mmx\r
+       cmp  ecx,06c65746eh\r
+       jne  L_dont_use_mmx\r
+       cmp  edx,049656e69h\r
+       jne  L_dont_use_mmx\r
+       mov  eax,1\r
+       cpuid\r
+       shr  eax,8\r
+       and  eax,15\r
+       cmp  eax,6\r
+       jne  L_dont_use_mmx\r
+       test  edx,0800000h\r
+       jnz  L_use_mmx\r
+       jmp  L_dont_use_mmx\r
+L_use_mmx:\r
+       mov  dword ptr [inflate_fast_use_mmx],2\r
+       jmp  L_check_mmx_pop\r
+L_dont_use_mmx:\r
+       mov  dword ptr [inflate_fast_use_mmx],3\r
+L_check_mmx_pop:\r
+       pop  edx\r
+       pop  ecx\r
+       pop  ebx\r
+       pop  eax\r
+       jmp  L_check_mmx\r
+; 426 "inffast.S"\r
+ALIGN 4\r
+L_do_loop:\r
+; 437 "inffast.S"\r
+       cmp  bl,15\r
+       ja   L_get_length_code\r
+\r
+       xor  eax,eax\r
+       lodsw\r
+       mov  cl,bl\r
+       add  bl,16\r
+       shl  eax,cl\r
+       or  ebp,eax\r
+\r
+L_get_length_code:\r
+       mov  edx, [esp+0]\r
+       mov  ecx, [esp+8]\r
+       and  edx,ebp\r
+       mov  eax, [ecx+edx*4]\r
+\r
+L_dolen:\r
+\r
+\r
+\r
+\r
+\r
+\r
+       mov  cl,ah\r
+       sub  bl,ah\r
+       shr  ebp,cl\r
+\r
+\r
+\r
+\r
+\r
+\r
+       test  al,al\r
+       jnz   L_test_for_length_base\r
+\r
+       shr  eax,16\r
+       stosb\r
+\r
+L_while_test:\r
+\r
+\r
+       cmp  [esp+16],edi\r
+       jbe  L_break_loop\r
+\r
+       cmp  [esp+20],esi\r
+       ja   L_do_loop\r
+       jmp  L_break_loop\r
+\r
+L_test_for_length_base:\r
+; 502 "inffast.S"\r
+       mov  edx,eax\r
+       shr  edx,16\r
+       mov  cl,al\r
+\r
+       test  al,16\r
+       jz   L_test_for_second_level_length\r
+       and  cl,15\r
+       jz   L_save_len\r
+       cmp  bl,cl\r
+       jae  L_add_bits_to_len\r
+\r
+       mov  ch,cl\r
+       xor  eax,eax\r
+       lodsw\r
+       mov  cl,bl\r
+       add  bl,16\r
+       shl  eax,cl\r
+       or  ebp,eax\r
+       mov  cl,ch\r
+\r
+L_add_bits_to_len:\r
+       mov  eax,1\r
+       shl  eax,cl\r
+       dec  eax\r
+       sub  bl,cl\r
+       and  eax,ebp\r
+       shr  ebp,cl\r
+       add  edx,eax\r
+\r
+L_save_len:\r
+       mov  [esp+24],edx\r
+\r
+\r
+L_decode_distance:\r
+; 549 "inffast.S"\r
+       cmp  bl,15\r
+       ja   L_get_distance_code\r
+\r
+       xor  eax,eax\r
+       lodsw\r
+       mov  cl,bl\r
+       add  bl,16\r
+       shl  eax,cl\r
+       or  ebp,eax\r
+\r
+L_get_distance_code:\r
+       mov  edx, [esp+4]\r
+       mov  ecx, [esp+12]\r
+       and  edx,ebp\r
+       mov  eax, [ecx+edx*4]\r
+\r
+\r
+L_dodist:\r
+       mov  edx,eax\r
+       shr  edx,16\r
+       mov  cl,ah\r
+       sub  bl,ah\r
+       shr  ebp,cl\r
+; 584 "inffast.S"\r
+       mov  cl,al\r
+\r
+       test  al,16\r
+       jz  L_test_for_second_level_dist\r
+       and  cl,15\r
+       jz  L_check_dist_one\r
+       cmp  bl,cl\r
+       jae  L_add_bits_to_dist\r
+\r
+       mov  ch,cl\r
+       xor  eax,eax\r
+       lodsw\r
+       mov  cl,bl\r
+       add  bl,16\r
+       shl  eax,cl\r
+       or  ebp,eax\r
+       mov  cl,ch\r
+\r
+L_add_bits_to_dist:\r
+       mov  eax,1\r
+       shl  eax,cl\r
+       dec  eax\r
+       sub  bl,cl\r
+       and  eax,ebp\r
+       shr  ebp,cl\r
+       add  edx,eax\r
+       jmp  L_check_window\r
+\r
+L_check_window:\r
+; 625 "inffast.S"\r
+       mov  [esp+44],esi\r
+       mov  eax,edi\r
+       sub  eax, [esp+40]\r
+\r
+       cmp  eax,edx\r
+       jb   L_clip_window\r
+\r
+       mov  ecx, [esp+24]\r
+       mov  esi,edi\r
+       sub  esi,edx\r
+\r
+       sub  ecx,3\r
+       mov  al, [esi]\r
+       mov  [edi],al\r
+       mov  al, [esi+1]\r
+       mov  dl, [esi+2]\r
+       add  esi,3\r
+       mov  [edi+1],al\r
+       mov  [edi+2],dl\r
+       add  edi,3\r
+       rep movsb\r
+\r
+       mov  esi, [esp+44]\r
+       jmp  L_while_test\r
+\r
+ALIGN 4\r
+L_check_dist_one:\r
+       cmp  edx,1\r
+       jne  L_check_window\r
+       cmp  [esp+40],edi\r
+       je  L_check_window\r
+\r
+       dec  edi\r
+       mov  ecx, [esp+24]\r
+       mov  al, [edi]\r
+       sub  ecx,3\r
+\r
+       mov  [edi+1],al\r
+       mov  [edi+2],al\r
+       mov  [edi+3],al\r
+       add  edi,4\r
+       rep stosb\r
+\r
+       jmp  L_while_test\r
+\r
+ALIGN 4\r
+L_test_for_second_level_length:\r
+\r
+\r
+\r
+\r
+       test  al,64\r
+       jnz   L_test_for_end_of_block\r
+\r
+       mov  eax,1\r
+       shl  eax,cl\r
+       dec  eax\r
+       and  eax,ebp\r
+       add  eax,edx\r
+       mov  edx, [esp+8]\r
+       mov  eax, [edx+eax*4]\r
+       jmp  L_dolen\r
+\r
+ALIGN 4\r
+L_test_for_second_level_dist:\r
+\r
+\r
+\r
+\r
+       test  al,64\r
+       jnz   L_invalid_distance_code\r
+\r
+       mov  eax,1\r
+       shl  eax,cl\r
+       dec  eax\r
+       and  eax,ebp\r
+       add  eax,edx\r
+       mov  edx, [esp+12]\r
+       mov  eax, [edx+eax*4]\r
+       jmp  L_dodist\r
+\r
+ALIGN 4\r
+L_clip_window:\r
+; 721 "inffast.S"\r
+       mov  ecx,eax\r
+       mov  eax, [esp+52]\r
+       neg  ecx\r
+       mov  esi, [esp+56]\r
+\r
+       cmp  eax,edx\r
+       jb   L_invalid_distance_too_far\r
+\r
+       add  ecx,edx\r
+       cmp  dword ptr [esp+48],0\r
+       jne  L_wrap_around_window\r
+\r
+       sub  eax,ecx\r
+       add  esi,eax\r
+; 749 "inffast.S"\r
+       mov  eax, [esp+24]\r
+       cmp  eax,ecx\r
+       jbe  L_do_copy1\r
+\r
+       sub  eax,ecx\r
+       rep movsb\r
+       mov  esi,edi\r
+       sub  esi,edx\r
+       jmp  L_do_copy1\r
+\r
+       cmp  eax,ecx\r
+       jbe  L_do_copy1\r
+\r
+       sub  eax,ecx\r
+       rep movsb\r
+       mov  esi,edi\r
+       sub  esi,edx\r
+       jmp  L_do_copy1\r
+\r
+L_wrap_around_window:\r
+; 793 "inffast.S"\r
+       mov  eax, [esp+48]\r
+       cmp  ecx,eax\r
+       jbe  L_contiguous_in_window\r
+\r
+       add  esi, [esp+52]\r
+       add  esi,eax\r
+       sub  esi,ecx\r
+       sub  ecx,eax\r
+\r
+\r
+       mov  eax, [esp+24]\r
+       cmp  eax,ecx\r
+       jbe  L_do_copy1\r
+\r
+       sub  eax,ecx\r
+       rep movsb\r
+       mov  esi, [esp+56]\r
+       mov  ecx, [esp+48]\r
+       cmp  eax,ecx\r
+       jbe  L_do_copy1\r
+\r
+       sub  eax,ecx\r
+       rep movsb\r
+       mov  esi,edi\r
+       sub  esi,edx\r
+       jmp  L_do_copy1\r
+\r
+L_contiguous_in_window:\r
+; 836 "inffast.S"\r
+       add  esi,eax\r
+       sub  esi,ecx\r
+\r
+\r
+       mov  eax, [esp+24]\r
+       cmp  eax,ecx\r
+       jbe  L_do_copy1\r
+\r
+       sub  eax,ecx\r
+       rep movsb\r
+       mov  esi,edi\r
+       sub  esi,edx\r
+\r
+L_do_copy1:\r
+; 862 "inffast.S"\r
+       mov  ecx,eax\r
+       rep movsb\r
+\r
+       mov  esi, [esp+44]\r
+       jmp  L_while_test\r
+; 878 "inffast.S"\r
+ALIGN 4\r
+L_init_mmx:\r
+       emms\r
+\r
+\r
+\r
+\r
+\r
+       movd mm0,ebp\r
+       mov  ebp,ebx\r
+; 896 "inffast.S"\r
+       movd mm4,dword ptr [esp+0]\r
+       movq mm3,mm4\r
+       movd mm5,dword ptr [esp+4]\r
+       movq mm2,mm5\r
+       pxor mm1,mm1\r
+       mov  ebx, [esp+8]\r
+       jmp  L_do_loop_mmx\r
+\r
+ALIGN 4\r
+L_do_loop_mmx:\r
+       psrlq mm0,mm1\r
+\r
+       cmp  ebp,32\r
+       ja  L_get_length_code_mmx\r
+\r
+       movd mm6,ebp\r
+       movd mm7,dword ptr [esi]\r
+       add  esi,4\r
+       psllq mm7,mm6\r
+       add  ebp,32\r
+       por mm0,mm7\r
+\r
+L_get_length_code_mmx:\r
+       pand mm4,mm0\r
+       movd eax,mm4\r
+       movq mm4,mm3\r
+       mov  eax, [ebx+eax*4]\r
+\r
+L_dolen_mmx:\r
+       movzx  ecx,ah\r
+       movd mm1,ecx\r
+       sub  ebp,ecx\r
+\r
+       test  al,al\r
+       jnz L_test_for_length_base_mmx\r
+\r
+       shr  eax,16\r
+       stosb\r
+\r
+L_while_test_mmx:\r
+\r
+\r
+       cmp  [esp+16],edi\r
+       jbe L_break_loop\r
+\r
+       cmp  [esp+20],esi\r
+       ja L_do_loop_mmx\r
+       jmp L_break_loop\r
+\r
+L_test_for_length_base_mmx:\r
+\r
+       mov  edx,eax\r
+       shr  edx,16\r
+\r
+       test  al,16\r
+       jz  L_test_for_second_level_length_mmx\r
+       and  eax,15\r
+       jz L_decode_distance_mmx\r
+\r
+       psrlq mm0,mm1\r
+       movd mm1,eax\r
+       movd ecx,mm0\r
+       sub  ebp,eax\r
+       and  ecx, [inflate_fast_mask+eax*4]\r
+       add  edx,ecx\r
+\r
+L_decode_distance_mmx:\r
+       psrlq mm0,mm1\r
+\r
+       cmp  ebp,32\r
+       ja L_get_dist_code_mmx\r
+\r
+       movd mm6,ebp\r
+       movd mm7,dword ptr [esi]\r
+       add  esi,4\r
+       psllq mm7,mm6\r
+       add  ebp,32\r
+       por mm0,mm7\r
+\r
+L_get_dist_code_mmx:\r
+       mov  ebx, [esp+12]\r
+       pand mm5,mm0\r
+       movd eax,mm5\r
+       movq mm5,mm2\r
+       mov  eax, [ebx+eax*4]\r
+\r
+L_dodist_mmx:\r
+\r
+       movzx  ecx,ah\r
+       mov  ebx,eax\r
+       shr  ebx,16\r
+       sub  ebp,ecx\r
+       movd mm1,ecx\r
+\r
+       test  al,16\r
+       jz L_test_for_second_level_dist_mmx\r
+       and  eax,15\r
+       jz L_check_dist_one_mmx\r
+\r
+L_add_bits_to_dist_mmx:\r
+       psrlq mm0,mm1\r
+       movd mm1,eax\r
+       movd ecx,mm0\r
+       sub  ebp,eax\r
+       and  ecx, [inflate_fast_mask+eax*4]\r
+       add  ebx,ecx\r
+\r
+L_check_window_mmx:\r
+       mov  [esp+44],esi\r
+       mov  eax,edi\r
+       sub  eax, [esp+40]\r
+\r
+       cmp  eax,ebx\r
+       jb L_clip_window_mmx\r
+\r
+       mov  ecx,edx\r
+       mov  esi,edi\r
+       sub  esi,ebx\r
+\r
+       sub  ecx,3\r
+       mov  al, [esi]\r
+       mov  [edi],al\r
+       mov  al, [esi+1]\r
+       mov  dl, [esi+2]\r
+       add  esi,3\r
+       mov  [edi+1],al\r
+       mov  [edi+2],dl\r
+       add  edi,3\r
+       rep movsb\r
+\r
+       mov  esi, [esp+44]\r
+       mov  ebx, [esp+8]\r
+       jmp  L_while_test_mmx\r
+\r
+ALIGN 4\r
+L_check_dist_one_mmx:\r
+       cmp  ebx,1\r
+       jne  L_check_window_mmx\r
+       cmp  [esp+40],edi\r
+       je   L_check_window_mmx\r
+\r
+       dec  edi\r
+       mov  ecx,edx\r
+       mov  al, [edi]\r
+       sub  ecx,3\r
+\r
+       mov  [edi+1],al\r
+       mov  [edi+2],al\r
+       mov  [edi+3],al\r
+       add  edi,4\r
+       rep stosb\r
+\r
+       mov  ebx, [esp+8]\r
+       jmp  L_while_test_mmx\r
+\r
+ALIGN 4\r
+L_test_for_second_level_length_mmx:\r
+       test  al,64\r
+       jnz L_test_for_end_of_block\r
+\r
+       and  eax,15\r
+       psrlq mm0,mm1\r
+       movd ecx,mm0\r
+       and  ecx, [inflate_fast_mask+eax*4]\r
+       add  ecx,edx\r
+       mov  eax, [ebx+ecx*4]\r
+       jmp L_dolen_mmx\r
+\r
+ALIGN 4\r
+L_test_for_second_level_dist_mmx:\r
+       test  al,64\r
+       jnz L_invalid_distance_code\r
+\r
+       and  eax,15\r
+       psrlq mm0,mm1\r
+       movd ecx,mm0\r
+       and  ecx, [inflate_fast_mask+eax*4]\r
+       mov  eax, [esp+12]\r
+       add  ecx,ebx\r
+       mov  eax, [eax+ecx*4]\r
+       jmp  L_dodist_mmx\r
+\r
+ALIGN 4\r
+L_clip_window_mmx:\r
+\r
+       mov  ecx,eax\r
+       mov  eax, [esp+52]\r
+       neg  ecx\r
+       mov  esi, [esp+56]\r
+\r
+       cmp  eax,ebx\r
+       jb  L_invalid_distance_too_far\r
+\r
+       add  ecx,ebx\r
+       cmp  dword ptr [esp+48],0\r
+       jne  L_wrap_around_window_mmx\r
+\r
+       sub  eax,ecx\r
+       add  esi,eax\r
+\r
+       cmp  edx,ecx\r
+       jbe  L_do_copy1_mmx\r
+\r
+       sub  edx,ecx\r
+       rep movsb\r
+       mov  esi,edi\r
+       sub  esi,ebx\r
+       jmp  L_do_copy1_mmx\r
+\r
+       cmp  edx,ecx\r
+       jbe  L_do_copy1_mmx\r
+\r
+       sub  edx,ecx\r
+       rep movsb\r
+       mov  esi,edi\r
+       sub  esi,ebx\r
+       jmp  L_do_copy1_mmx\r
+\r
+L_wrap_around_window_mmx:\r
+\r
+       mov  eax, [esp+48]\r
+       cmp  ecx,eax\r
+       jbe  L_contiguous_in_window_mmx\r
+\r
+       add  esi, [esp+52]\r
+       add  esi,eax\r
+       sub  esi,ecx\r
+       sub  ecx,eax\r
+\r
+\r
+       cmp  edx,ecx\r
+       jbe  L_do_copy1_mmx\r
+\r
+       sub  edx,ecx\r
+       rep movsb\r
+       mov  esi, [esp+56]\r
+       mov  ecx, [esp+48]\r
+       cmp  edx,ecx\r
+       jbe  L_do_copy1_mmx\r
+\r
+       sub  edx,ecx\r
+       rep movsb\r
+       mov  esi,edi\r
+       sub  esi,ebx\r
+       jmp  L_do_copy1_mmx\r
+\r
+L_contiguous_in_window_mmx:\r
+\r
+       add  esi,eax\r
+       sub  esi,ecx\r
+\r
+\r
+       cmp  edx,ecx\r
+       jbe  L_do_copy1_mmx\r
+\r
+       sub  edx,ecx\r
+       rep movsb\r
+       mov  esi,edi\r
+       sub  esi,ebx\r
+\r
+L_do_copy1_mmx:\r
+\r
+\r
+       mov  ecx,edx\r
+       rep movsb\r
+\r
+       mov  esi, [esp+44]\r
+       mov  ebx, [esp+8]\r
+       jmp  L_while_test_mmx\r
+; 1174 "inffast.S"\r
+L_invalid_distance_code:\r
+\r
+\r
+\r
+\r
+\r
+       mov  ecx, invalid_distance_code_msg\r
+       mov  edx,INFLATE_MODE_BAD\r
+       jmp  L_update_stream_state\r
+\r
+L_test_for_end_of_block:\r
+\r
+\r
+\r
+\r
+\r
+       test  al,32\r
+       jz  L_invalid_literal_length_code\r
+\r
+       mov  ecx,0\r
+       mov  edx,INFLATE_MODE_TYPE\r
+       jmp  L_update_stream_state\r
+\r
+L_invalid_literal_length_code:\r
+\r
+\r
+\r
+\r
+\r
+       mov  ecx, invalid_literal_length_code_msg\r
+       mov  edx,INFLATE_MODE_BAD\r
+       jmp  L_update_stream_state\r
+\r
+L_invalid_distance_too_far:\r
+\r
+\r
+\r
+       mov  esi, [esp+44]\r
+       mov  ecx, invalid_distance_too_far_msg\r
+       mov  edx,INFLATE_MODE_BAD\r
+       jmp  L_update_stream_state\r
+\r
+L_update_stream_state:\r
+\r
+       mov  eax, [esp+88]\r
+       test  ecx,ecx\r
+       jz  L_skip_msg\r
+       mov  [eax+24],ecx\r
+L_skip_msg:\r
+       mov  eax, [eax+28]\r
+       mov  [eax+mode_state],edx\r
+       jmp  L_break_loop\r
+\r
+ALIGN 4\r
+L_break_loop:\r
+; 1243 "inffast.S"\r
+       cmp  dword ptr [inflate_fast_use_mmx],2\r
+       jne  L_update_next_in\r
+\r
+\r
+\r
+       mov  ebx,ebp\r
+\r
+L_update_next_in:\r
+; 1266 "inffast.S"\r
+       mov  eax, [esp+88]\r
+       mov  ecx,ebx\r
+       mov  edx, [eax+28]\r
+       shr  ecx,3\r
+       sub  esi,ecx\r
+       shl  ecx,3\r
+       sub  ebx,ecx\r
+       mov  [eax+12],edi\r
+       mov  [edx+bits_state],ebx\r
+       mov  ecx,ebx\r
+\r
+       lea  ebx, [esp+28]\r
+       cmp  [esp+20],ebx\r
+       jne  L_buf_not_used\r
+\r
+       sub  esi,ebx\r
+       mov  ebx, [eax+0]\r
+       mov  [esp+20],ebx\r
+       add  esi,ebx\r
+       mov  ebx, [eax+4]\r
+       sub  ebx,11\r
+       add  [esp+20],ebx\r
+\r
+L_buf_not_used:\r
+       mov  [eax+0],esi\r
+\r
+       mov  ebx,1\r
+       shl  ebx,cl\r
+       dec  ebx\r
+\r
+\r
+\r
+\r
+\r
+       cmp  dword ptr [inflate_fast_use_mmx],2\r
+       jne  L_update_hold\r
+\r
+\r
+\r
+       psrlq mm0,mm1\r
+       movd ebp,mm0\r
+\r
+       emms\r
+\r
+L_update_hold:\r
+\r
+\r
+\r
+       and  ebp,ebx\r
+       mov  [edx+hold_state],ebp\r
+\r
+\r
+\r
+\r
+       mov  ebx, [esp+20]\r
+       cmp  ebx,esi\r
+       jbe  L_last_is_smaller\r
+\r
+       sub  ebx,esi\r
+       add  ebx,11\r
+       mov  [eax+4],ebx\r
+       jmp  L_fixup_out\r
+L_last_is_smaller:\r
+       sub  esi,ebx\r
+       neg  esi\r
+       add  esi,11\r
+       mov  [eax+4],esi\r
+\r
+\r
+\r
+\r
+L_fixup_out:\r
+\r
+       mov  ebx, [esp+16]\r
+       cmp  ebx,edi\r
+       jbe  L_end_is_smaller\r
+\r
+       sub  ebx,edi\r
+       add  ebx,257\r
+       mov  [eax+16],ebx\r
+       jmp  L_done\r
+L_end_is_smaller:\r
+       sub  edi,ebx\r
+       neg  edi\r
+       add  edi,257\r
+       mov  [eax+16],edi\r
+\r
+\r
+\r
+\r
+\r
+L_done:\r
+       add  esp,64\r
+       popfd\r
+       pop  ebx\r
+       pop  ebp\r
+       pop  esi\r
+       pop  edi\r
+       ret\r
+_inflate_fast endp\r
+\r
+_TEXT  ends\r
+end\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/inffas32.lst b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/inffas32.lst
new file mode 100644 (file)
index 0000000..d38b3a6
--- /dev/null
@@ -0,0 +1,1224 @@
+Microsoft (R) Macro Assembler Version 10.00.30319.01       04/13/12 13:33:41\r
+inffas32.asm                                                Page 1 - 1\r
+\r
+\r
+                               ;/* inffas32.asm is a hand tuned assembler version of inffast.c -- fast decoding\r
+                               ; *\r
+                               ; * inffas32.asm is derivated from inffas86.c, with translation of assembly code\r
+                               ; *\r
+                               ; * Copyright (C) 1995-2003 Mark Adler\r
+                               ; * For conditions of distribution and use, see copyright notice in zlib.h\r
+                               ; *\r
+                               ; * Copyright (C) 2003 Chris Anderson <christop@charm.net>\r
+                               ; * Please use the copyright conditions above.\r
+                               ; *\r
+                               ; * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from\r
+                               ; * the gcc -S output of zlib-1.2.0/inffast.c.  Zlib-1.2.0 is in beta release at\r
+                               ; * the moment.  I have successfully compiled and tested this code with gcc2.96,\r
+                               ; * gcc3.2, icc5.0, msvc6.0.  It is very close to the speed of inffast.S\r
+                               ; * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX\r
+                               ; * enabled.  I will attempt to merge the MMX code into this version.  Newer\r
+                               ; * versions of this and inffast.S can be found at\r
+                               ; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/\r
+                               ; *\r
+                               ; * 2005 : modification by Gilles Vollant\r
+                               ; */\r
+                               ; For Visual C++ 4.x and higher and ML 6.x and higher\r
+                               ;   ml.exe is in directory \MASM611C of Win95 DDK\r
+                               ;   ml.exe is also distributed in http://www.masm32.com/masmdl.htm\r
+                               ;    and in VC++2003 toolkit at http://msdn.microsoft.com/visualc/vctoolkit2003/\r
+                               ;\r
+                               ;\r
+                               ;   compile with command line option\r
+                               ;   ml  /coff /Zi /c /Flinffas32.lst inffas32.asm\r
+\r
+                               ;   if you define NO_GZIP (see inflate.h), compile with\r
+                               ;   ml  /coff /Zi /c /Flinffas32.lst /DNO_GUNZIP inffas32.asm\r
+\r
+\r
+                               ; zlib122sup is 0 fort zlib 1.2.2.1 and lower\r
+                               ; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head\r
+                               ;        in inflate_state in inflate.h)\r
+ = 00000008                    zlib1222sup      equ    8\r
+\r
+\r
+                               IFDEF GUNZIP\r
+                               ELSE\r
+                                 IFNDEF NO_GUNZIP\r
+ = 0000000B                        INFLATE_MODE_TYPE    equ 11\r
+ = 0000001A                        INFLATE_MODE_BAD     equ 26\r
+                                 ELSE\r
+                                 ENDIF\r
+                               ENDIF\r
+\r
+\r
+                               ; 75 "inffast.S"\r
+                               ;FILE "inffast.S"\r
+\r
+                               ;;;GLOBAL _inflate_fast\r
+\r
+                               ;;;SECTION .text\r
+\r
+\r
+\r
+                                       .586p\r
+                                       .mmx\r
+\r
+                                       name    inflate_fast_x86\r
+                                       .MODEL  FLAT\r
+\r
+ 00000000                      _DATA                   segment\r
+ 00000000                      inflate_fast_use_mmx:\r
+ 00000000  00000001                    dd      1\r
+\r
+\r
+ 00000000                      _TEXT                   segment\r
+\r
+\r
+\r
+                               ALIGN 4\r
+ 00000000  46 61 73 74 20              db      'Fast decoding Code from Chris Anderson'\r
+          64 65 63 6F 64\r
+          69 6E 67 20 43\r
+          6F 64 65 20 66\r
+          72 6F 6D 20 43\r
+          68 72 69 73 20\r
+          41 6E 64 65 72\r
+          73 6F 6E\r
+ 00000026  00                          db      0\r
+\r
+                               ALIGN 4\r
+ 00000028                      invalid_literal_length_code_msg:\r
+ 00000028  69 6E 76 61 6C              db      'invalid literal/length code'\r
+          69 64 20 6C 69\r
+          74 65 72 61 6C\r
+          2F 6C 65 6E 67\r
+          74 68 20 63 6F\r
+          64 65\r
+ 00000043  00                          db      0\r
+\r
+                               ALIGN 4\r
+ 00000044                      invalid_distance_code_msg:\r
+ 00000044  69 6E 76 61 6C              db      'invalid distance code'\r
+          69 64 20 64 69\r
+          73 74 61 6E 63\r
+          65 20 63 6F 64\r
+          65\r
+ 00000059  00                          db      0\r
+\r
+                               ALIGN 4\r
+ 0000005C                      invalid_distance_too_far_msg:\r
+ 0000005C  69 6E 76 61 6C              db      'invalid distance too far back'\r
+          69 64 20 64 69\r
+          73 74 61 6E 63\r
+          65 20 74 6F 6F\r
+          20 66 61 72 20\r
+          62 61 63 6B\r
+ 00000079  00                          db      0\r
+\r
+\r
+                               ALIGN 4\r
+ 0000007C                      inflate_fast_mask:\r
+ 0000007C  00000000            dd      0\r
+ 00000080  00000001            dd      1\r
+ 00000084  00000003            dd      3\r
+ 00000088  00000007            dd      7\r
+ 0000008C  0000000F            dd      15\r
+ 00000090  0000001F            dd      31\r
+ 00000094  0000003F            dd      63\r
+ 00000098  0000007F            dd      127\r
+ 0000009C  000000FF            dd      255\r
+ 000000A0  000001FF            dd      511\r
+ 000000A4  000003FF            dd      1023\r
+ 000000A8  000007FF            dd      2047\r
+ 000000AC  00000FFF            dd      4095\r
+ 000000B0  00001FFF            dd      8191\r
+ 000000B4  00003FFF            dd      16383\r
+ 000000B8  00007FFF            dd      32767\r
+ 000000BC  0000FFFF            dd      65535\r
+ 000000C0  0001FFFF            dd      131071\r
+ 000000C4  0003FFFF            dd      262143\r
+ 000000C8  0007FFFF            dd      524287\r
+ 000000CC  000FFFFF            dd      1048575\r
+ 000000D0  001FFFFF            dd      2097151\r
+ 000000D4  003FFFFF            dd      4194303\r
+ 000000D8  007FFFFF            dd      8388607\r
+ 000000DC  00FFFFFF            dd      16777215\r
+ 000000E0  01FFFFFF            dd      33554431\r
+ 000000E4  03FFFFFF            dd      67108863\r
+ 000000E8  07FFFFFF            dd      134217727\r
+ 000000EC  0FFFFFFF            dd      268435455\r
+ 000000F0  1FFFFFFF            dd      536870911\r
+ 000000F4  3FFFFFFF            dd      1073741823\r
+ 000000F8  7FFFFFFF            dd      2147483647\r
+ 000000FC  FFFFFFFF            dd      4294967295\r
+\r
+\r
+ = 00000000                    mode_state       equ    0       ;/* state->mode */\r
+ = 00000028                    wsize_state      equ    (32+zlib1222sup)        ;/* state->wsize */\r
+ = 00000030                    write_state      equ    (36+4+zlib1222sup)      ;/* state->write */\r
+ = 00000034                    window_state     equ    (40+4+zlib1222sup)      ;/* state->window */\r
+ = 00000038                    hold_state       equ    (44+4+zlib1222sup)      ;/* state->hold */\r
+ = 0000003C                    bits_state       equ    (48+4+zlib1222sup)      ;/* state->bits */\r
+ = 0000004C                    lencode_state    equ    (64+4+zlib1222sup)      ;/* state->lencode */\r
+ = 00000050                    distcode_state   equ    (68+4+zlib1222sup)      ;/* state->distcode */\r
+ = 00000054                    lenbits_state    equ    (72+4+zlib1222sup)      ;/* state->lenbits */\r
+ = 00000058                    distbits_state   equ    (76+4+zlib1222sup)      ;/* state->distbits */\r
+\r
+\r
+                               ;;SECTION .text\r
+                               ; 205 "inffast.S"\r
+                               ;GLOBAL inflate_fast_use_mmx\r
+\r
+                               ;SECTION .data\r
+\r
+\r
+                               ; GLOBAL inflate_fast_use_mmx:object\r
+                               ;.size inflate_fast_use_mmx, 4\r
+                               ; 226 "inffast.S"\r
+                               ;SECTION .text\r
+\r
+                               ALIGN 4\r
+ 00000100                      _inflate_fast proc near\r
+ 00000100                      .FPO (16, 4, 0, 0, 1, 0)\r
+ 00000100  57                          push  edi\r
+ 00000101  56                          push  esi\r
+ 00000102  55                          push  ebp\r
+ 00000103  53                          push  ebx\r
+ 00000104  9C                          pushfd\r
+ 00000105  83 EC 40                    sub  esp,64\r
+ 00000108  FC                          cld\r
+\r
+\r
+\r
+\r
+ 00000109  8B 74 24 58                 mov  esi, [esp+88]\r
+ 0000010D  8B 7E 1C                    mov  edi, [esi+28]\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+ 00000110  8B 56 04                    mov  edx, [esi+4]\r
+ 00000113  8B 06                       mov  eax, [esi+0]\r
+\r
+ 00000115  03 D0                       add  edx,eax\r
+ 00000117  83 EA 0B                    sub  edx,11\r
+\r
+ 0000011A  89 44 24 2C                 mov  [esp+44],eax\r
+ 0000011E  89 54 24 14                 mov  [esp+20],edx\r
+\r
+ 00000122  8B 6C 24 5C                 mov  ebp, [esp+92]\r
+ 00000126  8B 4E 10                    mov  ecx, [esi+16]\r
+ 00000129  8B 5E 0C                    mov  ebx, [esi+12]\r
+\r
+ 0000012C  2B E9                       sub  ebp,ecx\r
+ 0000012E  F7 DD                       neg  ebp\r
+ 00000130  03 EB                       add  ebp,ebx\r
+\r
+ 00000132  81 E9 00000101              sub  ecx,257\r
+ 00000138  03 CB                       add  ecx,ebx\r
+\r
+ 0000013A  89 5C 24 3C                 mov  [esp+60],ebx\r
+ 0000013E  89 6C 24 28                 mov  [esp+40],ebp\r
+ 00000142  89 4C 24 10                 mov  [esp+16],ecx\r
+                               ; 285 "inffast.S"\r
+ 00000146  8B 47 4C                    mov  eax, [edi+lencode_state]\r
+ 00000149  8B 4F 50                    mov  ecx, [edi+distcode_state]\r
+\r
+ 0000014C  89 44 24 08                 mov  [esp+8],eax\r
+ 00000150  89 4C 24 0C                 mov  [esp+12],ecx\r
+\r
+ 00000154  B8 00000001                 mov  eax,1\r
+ 00000159  8B 4F 54                    mov  ecx, [edi+lenbits_state]\r
+ 0000015C  D3 E0                       shl  eax,cl\r
+ 0000015E  48                          dec  eax\r
+ 0000015F  89 04 24                    mov  [esp+0],eax\r
+\r
+ 00000162  B8 00000001                 mov  eax,1\r
+ 00000167  8B 4F 58                    mov  ecx, [edi+distbits_state]\r
+ 0000016A  D3 E0                       shl  eax,cl\r
+ 0000016C  48                          dec  eax\r
+ 0000016D  89 44 24 04                 mov  [esp+4],eax\r
+\r
+ 00000171  8B 47 28                    mov  eax, [edi+wsize_state]\r
+ 00000174  8B 4F 30                    mov  ecx, [edi+write_state]\r
+ 00000177  8B 57 34                    mov  edx, [edi+window_state]\r
+\r
+ 0000017A  89 44 24 34                 mov  [esp+52],eax\r
+ 0000017E  89 4C 24 30                 mov  [esp+48],ecx\r
+ 00000182  89 54 24 38                 mov  [esp+56],edx\r
+\r
+ 00000186  8B 6F 38                    mov  ebp, [edi+hold_state]\r
+ 00000189  8B 5F 3C                    mov  ebx, [edi+bits_state]\r
+                               ; 321 "inffast.S"\r
+ 0000018C  8B 74 24 2C                 mov  esi, [esp+44]\r
+ 00000190  8B 4C 24 14                 mov  ecx, [esp+20]\r
+ 00000194  3B CE                       cmp  ecx,esi\r
+ 00000196  77 22                       ja   L_align_long\r
+\r
+ 00000198  83 C1 0B                    add  ecx,11\r
+ 0000019B  2B CE                       sub  ecx,esi\r
+ 0000019D  B8 0000000C                 mov  eax,12\r
+ 000001A2  2B C1                       sub  eax,ecx\r
+ 000001A4  8D 7C 24 1C                 lea  edi, [esp+28]\r
+ 000001A8  F3/ A4                      rep movsb\r
+ 000001AA  8B C8                       mov  ecx,eax\r
+ 000001AC  33 C0                       xor  eax,eax\r
+ 000001AE  F3/ AA                      rep stosb\r
+ 000001B0  8D 74 24 1C                 lea  esi, [esp+28]\r
+ 000001B4  89 74 24 14                 mov  [esp+20],esi\r
+ 000001B8  EB 18                       jmp  L_is_aligned\r
+\r
+\r
+ 000001BA                      L_align_long:\r
+ 000001BA  F7 C6 00000003              test  esi,3\r
+ 000001C0  74 10                       jz   L_is_aligned\r
+ 000001C2  33 C0                       xor  eax,eax\r
+ 000001C4  8A 06                       mov  al, [esi]\r
+ 000001C6  46                          inc  esi\r
+ 000001C7  8B CB                       mov  ecx,ebx\r
+ 000001C9  83 C3 08                    add  ebx,8\r
+ 000001CC  D3 E0                       shl  eax,cl\r
+ 000001CE  0B E8                       or  ebp,eax\r
+ 000001D0  EB E8                       jmp L_align_long\r
+\r
+ 000001D2                      L_is_aligned:\r
+ 000001D2  8B 7C 24 3C                 mov  edi, [esp+60]\r
+                               ; 366 "inffast.S"\r
+ 000001D6                      L_check_mmx:\r
+ 000001D6  83 3D 00000000 R            cmp  dword ptr [inflate_fast_use_mmx],2\r
+          02\r
+ 000001DD  0F 84 00000289              je   L_init_mmx\r
+ 000001E3  77 6B                       ja   L_do_loop\r
+\r
+ 000001E5  50                          push  eax\r
+ 000001E6  53                          push  ebx\r
+ 000001E7  51                          push  ecx\r
+ 000001E8  52                          push  edx\r
+ 000001E9  9C                          pushfd\r
+ 000001EA  8B 04 24                    mov  eax, [esp]\r
+ 000001ED  81 34 24                    xor  dword ptr [esp],0200000h\r
+          00200000\r
+\r
+\r
+\r
+\r
+ 000001F4  9D                          popfd\r
+ 000001F5  9C                          pushfd\r
+ 000001F6  5A                          pop  edx\r
+ 000001F7  33 D0                       xor  edx,eax\r
+ 000001F9  74 44                       jz   L_dont_use_mmx\r
+ 000001FB  33 C0                       xor  eax,eax\r
+ 000001FD  0F A2                       cpuid\r
+ 000001FF  81 FB 756E6547              cmp  ebx,0756e6547h\r
+ 00000205  75 38                       jne  L_dont_use_mmx\r
+ 00000207  81 F9 6C65746E              cmp  ecx,06c65746eh\r
+ 0000020D  75 30                       jne  L_dont_use_mmx\r
+ 0000020F  81 FA 49656E69              cmp  edx,049656e69h\r
+ 00000215  75 28                       jne  L_dont_use_mmx\r
+ 00000217  B8 00000001                 mov  eax,1\r
+ 0000021C  0F A2                       cpuid\r
+ 0000021E  C1 E8 08                    shr  eax,8\r
+ 00000221  83 E0 0F                    and  eax,15\r
+ 00000224  83 F8 06                    cmp  eax,6\r
+ 00000227  75 16                       jne  L_dont_use_mmx\r
+ 00000229  F7 C2 00800000              test  edx,0800000h\r
+ 0000022F  75 02                       jnz  L_use_mmx\r
+ 00000231  EB 0C                       jmp  L_dont_use_mmx\r
+ 00000233                      L_use_mmx:\r
+ 00000233  C7 05 00000000 R            mov  dword ptr [inflate_fast_use_mmx],2\r
+          00000002\r
+ 0000023D  EB 0A                       jmp  L_check_mmx_pop\r
+ 0000023F                      L_dont_use_mmx:\r
+ 0000023F  C7 05 00000000 R            mov  dword ptr [inflate_fast_use_mmx],3\r
+          00000003\r
+ 00000249                      L_check_mmx_pop:\r
+ 00000249  5A                          pop  edx\r
+ 0000024A  59                          pop  ecx\r
+ 0000024B  5B                          pop  ebx\r
+ 0000024C  58                          pop  eax\r
+ 0000024D  EB 87                       jmp  L_check_mmx\r
+                               ; 426 "inffast.S"\r
+                               ALIGN 4\r
+ 00000250                      L_do_loop:\r
+                               ; 437 "inffast.S"\r
+ 00000250  80 FB 0F                    cmp  bl,15\r
+ 00000253  77 0D                       ja   L_get_length_code\r
+\r
+ 00000255  33 C0                       xor  eax,eax\r
+ 00000257  66| AD                      lodsw\r
+ 00000259  8A CB                       mov  cl,bl\r
+ 0000025B  80 C3 10                    add  bl,16\r
+ 0000025E  D3 E0                       shl  eax,cl\r
+ 00000260  0B E8                       or  ebp,eax\r
+\r
+ 00000262                      L_get_length_code:\r
+ 00000262  8B 14 24                    mov  edx, [esp+0]\r
+ 00000265  8B 4C 24 08                 mov  ecx, [esp+8]\r
+ 00000269  23 D5                       and  edx,ebp\r
+ 0000026B  8B 04 91                    mov  eax, [ecx+edx*4]\r
+\r
+ 0000026E                      L_dolen:\r
+\r
+\r
+\r
+\r
+\r
+\r
+ 0000026E  8A CC                       mov  cl,ah\r
+ 00000270  2A DC                       sub  bl,ah\r
+ 00000272  D3 ED                       shr  ebp,cl\r
+\r
+\r
+\r
+\r
+\r
+\r
+ 00000274  84 C0                       test  al,al\r
+ 00000276  75 19                       jnz   L_test_for_length_base\r
+\r
+ 00000278  C1 E8 10                    shr  eax,16\r
+ 0000027B  AA                          stosb\r
+\r
+ 0000027C                      L_while_test:\r
+\r
+\r
+ 0000027C  39 7C 24 10                 cmp  [esp+16],edi\r
+ 00000280  0F 86 00000462              jbe  L_break_loop\r
+\r
+ 00000286  39 74 24 14                 cmp  [esp+20],esi\r
+ 0000028A  77 C4                       ja   L_do_loop\r
+ 0000028C  E9 00000457                 jmp  L_break_loop\r
+\r
+ 00000291                      L_test_for_length_base:\r
+                               ; 502 "inffast.S"\r
+ 00000291  8B D0                       mov  edx,eax\r
+ 00000293  C1 EA 10                    shr  edx,16\r
+ 00000296  8A C8                       mov  cl,al\r
+\r
+ 00000298  A8 10                       test  al,16\r
+ 0000029A  0F 84 000000F4              jz   L_test_for_second_level_length\r
+ 000002A0  80 E1 0F                    and  cl,15\r
+ 000002A3  74 25                       jz   L_save_len\r
+ 000002A5  3A D9                       cmp  bl,cl\r
+ 000002A7  73 11                       jae  L_add_bits_to_len\r
+\r
+ 000002A9  8A E9                       mov  ch,cl\r
+ 000002AB  33 C0                       xor  eax,eax\r
+ 000002AD  66| AD                      lodsw\r
+ 000002AF  8A CB                       mov  cl,bl\r
+ 000002B1  80 C3 10                    add  bl,16\r
+ 000002B4  D3 E0                       shl  eax,cl\r
+ 000002B6  0B E8                       or  ebp,eax\r
+ 000002B8  8A CD                       mov  cl,ch\r
+\r
+ 000002BA                      L_add_bits_to_len:\r
+ 000002BA  B8 00000001                 mov  eax,1\r
+ 000002BF  D3 E0                       shl  eax,cl\r
+ 000002C1  48                          dec  eax\r
+ 000002C2  2A D9                       sub  bl,cl\r
+ 000002C4  23 C5                       and  eax,ebp\r
+ 000002C6  D3 ED                       shr  ebp,cl\r
+ 000002C8  03 D0                       add  edx,eax\r
+\r
+ 000002CA                      L_save_len:\r
+ 000002CA  89 54 24 18                 mov  [esp+24],edx\r
+\r
+\r
+ 000002CE                      L_decode_distance:\r
+                               ; 549 "inffast.S"\r
+ 000002CE  80 FB 0F                    cmp  bl,15\r
+ 000002D1  77 0D                       ja   L_get_distance_code\r
+\r
+ 000002D3  33 C0                       xor  eax,eax\r
+ 000002D5  66| AD                      lodsw\r
+ 000002D7  8A CB                       mov  cl,bl\r
+ 000002D9  80 C3 10                    add  bl,16\r
+ 000002DC  D3 E0                       shl  eax,cl\r
+ 000002DE  0B E8                       or  ebp,eax\r
+\r
+ 000002E0                      L_get_distance_code:\r
+ 000002E0  8B 54 24 04                 mov  edx, [esp+4]\r
+ 000002E4  8B 4C 24 0C                 mov  ecx, [esp+12]\r
+ 000002E8  23 D5                       and  edx,ebp\r
+ 000002EA  8B 04 91                    mov  eax, [ecx+edx*4]\r
+\r
+\r
+ 000002ED                      L_dodist:\r
+ 000002ED  8B D0                       mov  edx,eax\r
+ 000002EF  C1 EA 10                    shr  edx,16\r
+ 000002F2  8A CC                       mov  cl,ah\r
+ 000002F4  2A DC                       sub  bl,ah\r
+ 000002F6  D3 ED                       shr  ebp,cl\r
+                               ; 584 "inffast.S"\r
+ 000002F8  8A C8                       mov  cl,al\r
+\r
+ 000002FA  A8 10                       test  al,16\r
+ 000002FC  0F 84 000000B2              jz  L_test_for_second_level_dist\r
+ 00000302  80 E1 0F                    and  cl,15\r
+ 00000305  74 65                       jz  L_check_dist_one\r
+ 00000307  3A D9                       cmp  bl,cl\r
+ 00000309  73 11                       jae  L_add_bits_to_dist\r
+\r
+ 0000030B  8A E9                       mov  ch,cl\r
+ 0000030D  33 C0                       xor  eax,eax\r
+ 0000030F  66| AD                      lodsw\r
+ 00000311  8A CB                       mov  cl,bl\r
+ 00000313  80 C3 10                    add  bl,16\r
+ 00000316  D3 E0                       shl  eax,cl\r
+ 00000318  0B E8                       or  ebp,eax\r
+ 0000031A  8A CD                       mov  cl,ch\r
+\r
+ 0000031C                      L_add_bits_to_dist:\r
+ 0000031C  B8 00000001                 mov  eax,1\r
+ 00000321  D3 E0                       shl  eax,cl\r
+ 00000323  48                          dec  eax\r
+ 00000324  2A D9                       sub  bl,cl\r
+ 00000326  23 C5                       and  eax,ebp\r
+ 00000328  D3 ED                       shr  ebp,cl\r
+ 0000032A  03 D0                       add  edx,eax\r
+ 0000032C  EB 00                       jmp  L_check_window\r
+\r
+ 0000032E                      L_check_window:\r
+                               ; 625 "inffast.S"\r
+ 0000032E  89 74 24 2C                 mov  [esp+44],esi\r
+ 00000332  8B C7                       mov  eax,edi\r
+ 00000334  2B 44 24 28                 sub  eax, [esp+40]\r
+\r
+ 00000338  3B C2                       cmp  eax,edx\r
+ 0000033A  0F 82 00000094              jb   L_clip_window\r
+\r
+ 00000340  8B 4C 24 18                 mov  ecx, [esp+24]\r
+ 00000344  8B F7                       mov  esi,edi\r
+ 00000346  2B F2                       sub  esi,edx\r
+\r
+ 00000348  83 E9 03                    sub  ecx,3\r
+ 0000034B  8A 06                       mov  al, [esi]\r
+ 0000034D  88 07                       mov  [edi],al\r
+ 0000034F  8A 46 01                    mov  al, [esi+1]\r
+ 00000352  8A 56 02                    mov  dl, [esi+2]\r
+ 00000355  83 C6 03                    add  esi,3\r
+ 00000358  88 47 01                    mov  [edi+1],al\r
+ 0000035B  88 57 02                    mov  [edi+2],dl\r
+ 0000035E  83 C7 03                    add  edi,3\r
+ 00000361  F3/ A4                      rep movsb\r
+\r
+ 00000363  8B 74 24 2C                 mov  esi, [esp+44]\r
+ 00000367  E9 FFFFFF10                 jmp  L_while_test\r
+\r
+                               ALIGN 4\r
+ 0000036C                      L_check_dist_one:\r
+ 0000036C  83 FA 01                    cmp  edx,1\r
+ 0000036F  75 BD                       jne  L_check_window\r
+ 00000371  39 7C 24 28                 cmp  [esp+40],edi\r
+ 00000375  74 B7                       je  L_check_window\r
+\r
+ 00000377  4F                          dec  edi\r
+ 00000378  8B 4C 24 18                 mov  ecx, [esp+24]\r
+ 0000037C  8A 07                       mov  al, [edi]\r
+ 0000037E  83 E9 03                    sub  ecx,3\r
+\r
+ 00000381  88 47 01                    mov  [edi+1],al\r
+ 00000384  88 47 02                    mov  [edi+2],al\r
+ 00000387  88 47 03                    mov  [edi+3],al\r
+ 0000038A  83 C7 04                    add  edi,4\r
+ 0000038D  F3/ AA                      rep stosb\r
+\r
+ 0000038F  E9 FFFFFEE8                 jmp  L_while_test\r
+\r
+                               ALIGN 4\r
+ 00000394                      L_test_for_second_level_length:\r
+\r
+\r
+\r
+\r
+ 00000394  A8 40                       test  al,64\r
+ 00000396  0F 85 0000030E              jnz   L_test_for_end_of_block\r
+\r
+ 0000039C  B8 00000001                 mov  eax,1\r
+ 000003A1  D3 E0                       shl  eax,cl\r
+ 000003A3  48                          dec  eax\r
+ 000003A4  23 C5                       and  eax,ebp\r
+ 000003A6  03 C2                       add  eax,edx\r
+ 000003A8  8B 54 24 08                 mov  edx, [esp+8]\r
+ 000003AC  8B 04 82                    mov  eax, [edx+eax*4]\r
+ 000003AF  E9 FFFFFEBA                 jmp  L_dolen\r
+\r
+                               ALIGN 4\r
+ 000003B4                      L_test_for_second_level_dist:\r
+\r
+\r
+\r
+\r
+ 000003B4  A8 40                       test  al,64\r
+ 000003B6  0F 85 000002E2              jnz   L_invalid_distance_code\r
+\r
+ 000003BC  B8 00000001                 mov  eax,1\r
+ 000003C1  D3 E0                       shl  eax,cl\r
+ 000003C3  48                          dec  eax\r
+ 000003C4  23 C5                       and  eax,ebp\r
+ 000003C6  03 C2                       add  eax,edx\r
+ 000003C8  8B 54 24 0C                 mov  edx, [esp+12]\r
+ 000003CC  8B 04 82                    mov  eax, [edx+eax*4]\r
+ 000003CF  E9 FFFFFF19                 jmp  L_dodist\r
+\r
+                               ALIGN 4\r
+ 000003D4                      L_clip_window:\r
+                               ; 721 "inffast.S"\r
+ 000003D4  8B C8                       mov  ecx,eax\r
+ 000003D6  8B 44 24 34                 mov  eax, [esp+52]\r
+ 000003DA  F7 D9                       neg  ecx\r
+ 000003DC  8B 74 24 38                 mov  esi, [esp+56]\r
+\r
+ 000003E0  3B C2                       cmp  eax,edx\r
+ 000003E2  0F 82 000002DE              jb   L_invalid_distance_too_far\r
+\r
+ 000003E8  03 CA                       add  ecx,edx\r
+ 000003EA  83 7C 24 30 00              cmp  dword ptr [esp+48],0\r
+ 000003EF  75 24                       jne  L_wrap_around_window\r
+\r
+ 000003F1  2B C1                       sub  eax,ecx\r
+ 000003F3  03 F0                       add  esi,eax\r
+                               ; 749 "inffast.S"\r
+ 000003F5  8B 44 24 18                 mov  eax, [esp+24]\r
+ 000003F9  3B C1                       cmp  eax,ecx\r
+ 000003FB  76 60                       jbe  L_do_copy1\r
+\r
+ 000003FD  2B C1                       sub  eax,ecx\r
+ 000003FF  F3/ A4                      rep movsb\r
+ 00000401  8B F7                       mov  esi,edi\r
+ 00000403  2B F2                       sub  esi,edx\r
+ 00000405  EB 56                       jmp  L_do_copy1\r
+\r
+ 00000407  3B C1                       cmp  eax,ecx\r
+ 00000409  76 52                       jbe  L_do_copy1\r
+\r
+ 0000040B  2B C1                       sub  eax,ecx\r
+ 0000040D  F3/ A4                      rep movsb\r
+ 0000040F  8B F7                       mov  esi,edi\r
+ 00000411  2B F2                       sub  esi,edx\r
+ 00000413  EB 48                       jmp  L_do_copy1\r
+\r
+ 00000415                      L_wrap_around_window:\r
+                               ; 793 "inffast.S"\r
+ 00000415  8B 44 24 30                 mov  eax, [esp+48]\r
+ 00000419  3B C8                       cmp  ecx,eax\r
+ 0000041B  76 2C                       jbe  L_contiguous_in_window\r
+\r
+ 0000041D  03 74 24 34                 add  esi, [esp+52]\r
+ 00000421  03 F0                       add  esi,eax\r
+ 00000423  2B F1                       sub  esi,ecx\r
+ 00000425  2B C8                       sub  ecx,eax\r
+\r
+\r
+ 00000427  8B 44 24 18                 mov  eax, [esp+24]\r
+ 0000042B  3B C1                       cmp  eax,ecx\r
+ 0000042D  76 2E                       jbe  L_do_copy1\r
+\r
+ 0000042F  2B C1                       sub  eax,ecx\r
+ 00000431  F3/ A4                      rep movsb\r
+ 00000433  8B 74 24 38                 mov  esi, [esp+56]\r
+ 00000437  8B 4C 24 30                 mov  ecx, [esp+48]\r
+ 0000043B  3B C1                       cmp  eax,ecx\r
+ 0000043D  76 1E                       jbe  L_do_copy1\r
+\r
+ 0000043F  2B C1                       sub  eax,ecx\r
+ 00000441  F3/ A4                      rep movsb\r
+ 00000443  8B F7                       mov  esi,edi\r
+ 00000445  2B F2                       sub  esi,edx\r
+ 00000447  EB 14                       jmp  L_do_copy1\r
+\r
+ 00000449                      L_contiguous_in_window:\r
+                               ; 836 "inffast.S"\r
+ 00000449  03 F0                       add  esi,eax\r
+ 0000044B  2B F1                       sub  esi,ecx\r
+\r
+\r
+ 0000044D  8B 44 24 18                 mov  eax, [esp+24]\r
+ 00000451  3B C1                       cmp  eax,ecx\r
+ 00000453  76 08                       jbe  L_do_copy1\r
+\r
+ 00000455  2B C1                       sub  eax,ecx\r
+ 00000457  F3/ A4                      rep movsb\r
+ 00000459  8B F7                       mov  esi,edi\r
+ 0000045B  2B F2                       sub  esi,edx\r
+\r
+ 0000045D                      L_do_copy1:\r
+                               ; 862 "inffast.S"\r
+ 0000045D  8B C8                       mov  ecx,eax\r
+ 0000045F  F3/ A4                      rep movsb\r
+\r
+ 00000461  8B 74 24 2C                 mov  esi, [esp+44]\r
+ 00000465  E9 FFFFFE12                 jmp  L_while_test\r
+                               ; 878 "inffast.S"\r
+                               ALIGN 4\r
+ 0000046C                      L_init_mmx:\r
+ 0000046C  0F 77                       emms\r
+\r
+\r
+\r
+\r
+\r
+ 0000046E  0F 6E C5                    movd mm0,ebp\r
+ 00000471  8B EB                       mov  ebp,ebx\r
+                               ; 896 "inffast.S"\r
+ 00000473  0F 6E 24 24                 movd mm4,dword ptr [esp+0]\r
+ 00000477  0F 7F E3                    movq mm3,mm4\r
+ 0000047A  0F 6E 6C 24 04              movd mm5,dword ptr [esp+4]\r
+ 0000047F  0F 7F EA                    movq mm2,mm5\r
+ 00000482  0F EF C9                    pxor mm1,mm1\r
+ 00000485  8B 5C 24 08                 mov  ebx, [esp+8]\r
+ 00000489  EB 01                       jmp  L_do_loop_mmx\r
+\r
+                               ALIGN 4\r
+ 0000048C                      L_do_loop_mmx:\r
+ 0000048C  0F D3 C1                    psrlq mm0,mm1\r
+\r
+ 0000048F  83 FD 20                    cmp  ebp,32\r
+ 00000492  77 12                       ja  L_get_length_code_mmx\r
+\r
+ 00000494  0F 6E F5                    movd mm6,ebp\r
+ 00000497  0F 6E 3E                    movd mm7,dword ptr [esi]\r
+ 0000049A  83 C6 04                    add  esi,4\r
+ 0000049D  0F F3 FE                    psllq mm7,mm6\r
+ 000004A0  83 C5 20                    add  ebp,32\r
+ 000004A3  0F EB C7                    por mm0,mm7\r
+\r
+ 000004A6                      L_get_length_code_mmx:\r
+ 000004A6  0F DB E0                    pand mm4,mm0\r
+ 000004A9  0F 7E E0                    movd eax,mm4\r
+ 000004AC  0F 7F DC                    movq mm4,mm3\r
+ 000004AF  8B 04 83                    mov  eax, [ebx+eax*4]\r
+\r
+ 000004B2                      L_dolen_mmx:\r
+ 000004B2  0F B6 CC                    movzx  ecx,ah\r
+ 000004B5  0F 6E C9                    movd mm1,ecx\r
+ 000004B8  2B E9                       sub  ebp,ecx\r
+\r
+ 000004BA  84 C0                       test  al,al\r
+ 000004BC  75 19                       jnz L_test_for_length_base_mmx\r
+\r
+ 000004BE  C1 E8 10                    shr  eax,16\r
+ 000004C1  AA                          stosb\r
+\r
+ 000004C2                      L_while_test_mmx:\r
+\r
+\r
+ 000004C2  39 7C 24 10                 cmp  [esp+16],edi\r
+ 000004C6  0F 86 0000021C              jbe L_break_loop\r
+\r
+ 000004CC  39 74 24 14                 cmp  [esp+20],esi\r
+ 000004D0  77 BA                       ja L_do_loop_mmx\r
+ 000004D2  E9 00000211                 jmp L_break_loop\r
+\r
+ 000004D7                      L_test_for_length_base_mmx:\r
+\r
+ 000004D7  8B D0                       mov  edx,eax\r
+ 000004D9  C1 EA 10                    shr  edx,16\r
+\r
+ 000004DC  A8 10                       test  al,16\r
+ 000004DE  0F 84 000000E0              jz  L_test_for_second_level_length_mmx\r
+ 000004E4  83 E0 0F                    and  eax,15\r
+ 000004E7  74 14                       jz L_decode_distance_mmx\r
+\r
+ 000004E9  0F D3 C1                    psrlq mm0,mm1\r
+ 000004EC  0F 6E C8                    movd mm1,eax\r
+ 000004EF  0F 7E C1                    movd ecx,mm0\r
+ 000004F2  2B E8                       sub  ebp,eax\r
+ 000004F4  23 0C 85                    and  ecx, [inflate_fast_mask+eax*4]\r
+          0000007C R\r
+ 000004FB  03 D1                       add  edx,ecx\r
+\r
+ 000004FD                      L_decode_distance_mmx:\r
+ 000004FD  0F D3 C1                    psrlq mm0,mm1\r
+\r
+ 00000500  83 FD 20                    cmp  ebp,32\r
+ 00000503  77 12                       ja L_get_dist_code_mmx\r
+\r
+ 00000505  0F 6E F5                    movd mm6,ebp\r
+ 00000508  0F 6E 3E                    movd mm7,dword ptr [esi]\r
+ 0000050B  83 C6 04                    add  esi,4\r
+ 0000050E  0F F3 FE                    psllq mm7,mm6\r
+ 00000511  83 C5 20                    add  ebp,32\r
+ 00000514  0F EB C7                    por mm0,mm7\r
+\r
+ 00000517                      L_get_dist_code_mmx:\r
+ 00000517  8B 5C 24 0C                 mov  ebx, [esp+12]\r
+ 0000051B  0F DB E8                    pand mm5,mm0\r
+ 0000051E  0F 7E E8                    movd eax,mm5\r
+ 00000521  0F 7F D5                    movq mm5,mm2\r
+ 00000524  8B 04 83                    mov  eax, [ebx+eax*4]\r
+\r
+ 00000527                      L_dodist_mmx:\r
+\r
+ 00000527  0F B6 CC                    movzx  ecx,ah\r
+ 0000052A  8B D8                       mov  ebx,eax\r
+ 0000052C  C1 EB 10                    shr  ebx,16\r
+ 0000052F  2B E9                       sub  ebp,ecx\r
+ 00000531  0F 6E C9                    movd mm1,ecx\r
+\r
+ 00000534  A8 10                       test  al,16\r
+ 00000536  0F 84 000000AC              jz L_test_for_second_level_dist_mmx\r
+ 0000053C  83 E0 0F                    and  eax,15\r
+ 0000053F  74 57                       jz L_check_dist_one_mmx\r
+\r
+ 00000541                      L_add_bits_to_dist_mmx:\r
+ 00000541  0F D3 C1                    psrlq mm0,mm1\r
+ 00000544  0F 6E C8                    movd mm1,eax\r
+ 00000547  0F 7E C1                    movd ecx,mm0\r
+ 0000054A  2B E8                       sub  ebp,eax\r
+ 0000054C  23 0C 85                    and  ecx, [inflate_fast_mask+eax*4]\r
+          0000007C R\r
+ 00000553  03 D9                       add  ebx,ecx\r
+\r
+ 00000555                      L_check_window_mmx:\r
+ 00000555  89 74 24 2C                 mov  [esp+44],esi\r
+ 00000559  8B C7                       mov  eax,edi\r
+ 0000055B  2B 44 24 28                 sub  eax, [esp+40]\r
+\r
+ 0000055F  3B C3                       cmp  eax,ebx\r
+ 00000561  0F 82 000000A9              jb L_clip_window_mmx\r
+\r
+ 00000567  8B CA                       mov  ecx,edx\r
+ 00000569  8B F7                       mov  esi,edi\r
+ 0000056B  2B F3                       sub  esi,ebx\r
+\r
+ 0000056D  83 E9 03                    sub  ecx,3\r
+ 00000570  8A 06                       mov  al, [esi]\r
+ 00000572  88 07                       mov  [edi],al\r
+ 00000574  8A 46 01                    mov  al, [esi+1]\r
+ 00000577  8A 56 02                    mov  dl, [esi+2]\r
+ 0000057A  83 C6 03                    add  esi,3\r
+ 0000057D  88 47 01                    mov  [edi+1],al\r
+ 00000580  88 57 02                    mov  [edi+2],dl\r
+ 00000583  83 C7 03                    add  edi,3\r
+ 00000586  F3/ A4                      rep movsb\r
+\r
+ 00000588  8B 74 24 2C                 mov  esi, [esp+44]\r
+ 0000058C  8B 5C 24 08                 mov  ebx, [esp+8]\r
+ 00000590  E9 FFFFFF2D                 jmp  L_while_test_mmx\r
+\r
+                               ALIGN 4\r
+ 00000598                      L_check_dist_one_mmx:\r
+ 00000598  83 FB 01                    cmp  ebx,1\r
+ 0000059B  75 B8                       jne  L_check_window_mmx\r
+ 0000059D  39 7C 24 28                 cmp  [esp+40],edi\r
+ 000005A1  74 B2                       je   L_check_window_mmx\r
+\r
+ 000005A3  4F                          dec  edi\r
+ 000005A4  8B CA                       mov  ecx,edx\r
+ 000005A6  8A 07                       mov  al, [edi]\r
+ 000005A8  83 E9 03                    sub  ecx,3\r
+\r
+ 000005AB  88 47 01                    mov  [edi+1],al\r
+ 000005AE  88 47 02                    mov  [edi+2],al\r
+ 000005B1  88 47 03                    mov  [edi+3],al\r
+ 000005B4  83 C7 04                    add  edi,4\r
+ 000005B7  F3/ AA                      rep stosb\r
+\r
+ 000005B9  8B 5C 24 08                 mov  ebx, [esp+8]\r
+ 000005BD  E9 FFFFFF00                 jmp  L_while_test_mmx\r
+\r
+                               ALIGN 4\r
+ 000005C4                      L_test_for_second_level_length_mmx:\r
+ 000005C4  A8 40                       test  al,64\r
+ 000005C6  0F 85 000000DE              jnz L_test_for_end_of_block\r
+\r
+ 000005CC  83 E0 0F                    and  eax,15\r
+ 000005CF  0F D3 C1                    psrlq mm0,mm1\r
+ 000005D2  0F 7E C1                    movd ecx,mm0\r
+ 000005D5  23 0C 85                    and  ecx, [inflate_fast_mask+eax*4]\r
+          0000007C R\r
+ 000005DC  03 CA                       add  ecx,edx\r
+ 000005DE  8B 04 8B                    mov  eax, [ebx+ecx*4]\r
+ 000005E1  E9 FFFFFECC                 jmp L_dolen_mmx\r
+\r
+                               ALIGN 4\r
+ 000005E8                      L_test_for_second_level_dist_mmx:\r
+ 000005E8  A8 40                       test  al,64\r
+ 000005EA  0F 85 000000AE              jnz L_invalid_distance_code\r
+\r
+ 000005F0  83 E0 0F                    and  eax,15\r
+ 000005F3  0F D3 C1                    psrlq mm0,mm1\r
+ 000005F6  0F 7E C1                    movd ecx,mm0\r
+ 000005F9  23 0C 85                    and  ecx, [inflate_fast_mask+eax*4]\r
+          0000007C R\r
+ 00000600  8B 44 24 0C                 mov  eax, [esp+12]\r
+ 00000604  03 CB                       add  ecx,ebx\r
+ 00000606  8B 04 88                    mov  eax, [eax+ecx*4]\r
+ 00000609  E9 FFFFFF19                 jmp  L_dodist_mmx\r
+\r
+                               ALIGN 4\r
+ 00000610                      L_clip_window_mmx:\r
+\r
+ 00000610  8B C8                       mov  ecx,eax\r
+ 00000612  8B 44 24 34                 mov  eax, [esp+52]\r
+ 00000616  F7 D9                       neg  ecx\r
+ 00000618  8B 74 24 38                 mov  esi, [esp+56]\r
+\r
+ 0000061C  3B C3                       cmp  eax,ebx\r
+ 0000061E  0F 82 000000A2              jb  L_invalid_distance_too_far\r
+\r
+ 00000624  03 CB                       add  ecx,ebx\r
+ 00000626  83 7C 24 30 00              cmp  dword ptr [esp+48],0\r
+ 0000062B  75 20                       jne  L_wrap_around_window_mmx\r
+\r
+ 0000062D  2B C1                       sub  eax,ecx\r
+ 0000062F  03 F0                       add  esi,eax\r
+\r
+ 00000631  3B D1                       cmp  edx,ecx\r
+ 00000633  76 58                       jbe  L_do_copy1_mmx\r
+\r
+ 00000635  2B D1                       sub  edx,ecx\r
+ 00000637  F3/ A4                      rep movsb\r
+ 00000639  8B F7                       mov  esi,edi\r
+ 0000063B  2B F3                       sub  esi,ebx\r
+ 0000063D  EB 4E                       jmp  L_do_copy1_mmx\r
+\r
+ 0000063F  3B D1                       cmp  edx,ecx\r
+ 00000641  76 4A                       jbe  L_do_copy1_mmx\r
+\r
+ 00000643  2B D1                       sub  edx,ecx\r
+ 00000645  F3/ A4                      rep movsb\r
+ 00000647  8B F7                       mov  esi,edi\r
+ 00000649  2B F3                       sub  esi,ebx\r
+ 0000064B  EB 40                       jmp  L_do_copy1_mmx\r
+\r
+ 0000064D                      L_wrap_around_window_mmx:\r
+\r
+ 0000064D  8B 44 24 30                 mov  eax, [esp+48]\r
+ 00000651  3B C8                       cmp  ecx,eax\r
+ 00000653  76 28                       jbe  L_contiguous_in_window_mmx\r
+\r
+ 00000655  03 74 24 34                 add  esi, [esp+52]\r
+ 00000659  03 F0                       add  esi,eax\r
+ 0000065B  2B F1                       sub  esi,ecx\r
+ 0000065D  2B C8                       sub  ecx,eax\r
+\r
+\r
+ 0000065F  3B D1                       cmp  edx,ecx\r
+ 00000661  76 2A                       jbe  L_do_copy1_mmx\r
+\r
+ 00000663  2B D1                       sub  edx,ecx\r
+ 00000665  F3/ A4                      rep movsb\r
+ 00000667  8B 74 24 38                 mov  esi, [esp+56]\r
+ 0000066B  8B 4C 24 30                 mov  ecx, [esp+48]\r
+ 0000066F  3B D1                       cmp  edx,ecx\r
+ 00000671  76 1A                       jbe  L_do_copy1_mmx\r
+\r
+ 00000673  2B D1                       sub  edx,ecx\r
+ 00000675  F3/ A4                      rep movsb\r
+ 00000677  8B F7                       mov  esi,edi\r
+ 00000679  2B F3                       sub  esi,ebx\r
+ 0000067B  EB 10                       jmp  L_do_copy1_mmx\r
+\r
+ 0000067D                      L_contiguous_in_window_mmx:\r
+\r
+ 0000067D  03 F0                       add  esi,eax\r
+ 0000067F  2B F1                       sub  esi,ecx\r
+\r
+\r
+ 00000681  3B D1                       cmp  edx,ecx\r
+ 00000683  76 08                       jbe  L_do_copy1_mmx\r
+\r
+ 00000685  2B D1                       sub  edx,ecx\r
+ 00000687  F3/ A4                      rep movsb\r
+ 00000689  8B F7                       mov  esi,edi\r
+ 0000068B  2B F3                       sub  esi,ebx\r
+\r
+ 0000068D                      L_do_copy1_mmx:\r
+\r
+\r
+ 0000068D  8B CA                       mov  ecx,edx\r
+ 0000068F  F3/ A4                      rep movsb\r
+\r
+ 00000691  8B 74 24 2C                 mov  esi, [esp+44]\r
+ 00000695  8B 5C 24 08                 mov  ebx, [esp+8]\r
+ 00000699  E9 FFFFFE24                 jmp  L_while_test_mmx\r
+                               ; 1174 "inffast.S"\r
+ 0000069E                      L_invalid_distance_code:\r
+\r
+\r
+\r
+\r
+\r
+ 0000069E  B9 00000044 R               mov  ecx, invalid_distance_code_msg\r
+ 000006A3  BA 0000001A                 mov  edx,INFLATE_MODE_BAD\r
+ 000006A8  EB 2C                       jmp  L_update_stream_state\r
+\r
+ 000006AA                      L_test_for_end_of_block:\r
+\r
+\r
+\r
+\r
+\r
+ 000006AA  A8 20                       test  al,32\r
+ 000006AC  74 0C                       jz  L_invalid_literal_length_code\r
+\r
+ 000006AE  B9 00000000                 mov  ecx,0\r
+ 000006B3  BA 0000000B                 mov  edx,INFLATE_MODE_TYPE\r
+ 000006B8  EB 1C                       jmp  L_update_stream_state\r
+\r
+ 000006BA                      L_invalid_literal_length_code:\r
+\r
+\r
+\r
+\r
+\r
+ 000006BA  B9 00000028 R               mov  ecx, invalid_literal_length_code_msg\r
+ 000006BF  BA 0000001A                 mov  edx,INFLATE_MODE_BAD\r
+ 000006C4  EB 10                       jmp  L_update_stream_state\r
+\r
+ 000006C6                      L_invalid_distance_too_far:\r
+\r
+\r
+\r
+ 000006C6  8B 74 24 2C                 mov  esi, [esp+44]\r
+ 000006CA  B9 0000005C R               mov  ecx, invalid_distance_too_far_msg\r
+ 000006CF  BA 0000001A                 mov  edx,INFLATE_MODE_BAD\r
+ 000006D4  EB 00                       jmp  L_update_stream_state\r
+\r
+ 000006D6                      L_update_stream_state:\r
+\r
+ 000006D6  8B 44 24 58                 mov  eax, [esp+88]\r
+ 000006DA  85 C9                       test  ecx,ecx\r
+ 000006DC  74 03                       jz  L_skip_msg\r
+ 000006DE  89 48 18                    mov  [eax+24],ecx\r
+ 000006E1                      L_skip_msg:\r
+ 000006E1  8B 40 1C                    mov  eax, [eax+28]\r
+ 000006E4  89 10                       mov  [eax+mode_state],edx\r
+ 000006E6  EB 00                       jmp  L_break_loop\r
+\r
+                               ALIGN 4\r
+ 000006E8                      L_break_loop:\r
+                               ; 1243 "inffast.S"\r
+ 000006E8  83 3D 00000000 R            cmp  dword ptr [inflate_fast_use_mmx],2\r
+          02\r
+ 000006EF  75 02                       jne  L_update_next_in\r
+\r
+\r
+\r
+ 000006F1  8B DD                       mov  ebx,ebp\r
+\r
+ 000006F3                      L_update_next_in:\r
+                               ; 1266 "inffast.S"\r
+ 000006F3  8B 44 24 58                 mov  eax, [esp+88]\r
+ 000006F7  8B CB                       mov  ecx,ebx\r
+ 000006F9  8B 50 1C                    mov  edx, [eax+28]\r
+ 000006FC  C1 E9 03                    shr  ecx,3\r
+ 000006FF  2B F1                       sub  esi,ecx\r
+ 00000701  C1 E1 03                    shl  ecx,3\r
+ 00000704  2B D9                       sub  ebx,ecx\r
+ 00000706  89 78 0C                    mov  [eax+12],edi\r
+ 00000709  89 5A 3C                    mov  [edx+bits_state],ebx\r
+ 0000070C  8B CB                       mov  ecx,ebx\r
+\r
+ 0000070E  8D 5C 24 1C                 lea  ebx, [esp+28]\r
+ 00000712  39 5C 24 14                 cmp  [esp+20],ebx\r
+ 00000716  75 14                       jne  L_buf_not_used\r
+\r
+ 00000718  2B F3                       sub  esi,ebx\r
+ 0000071A  8B 18                       mov  ebx, [eax+0]\r
+ 0000071C  89 5C 24 14                 mov  [esp+20],ebx\r
+ 00000720  03 F3                       add  esi,ebx\r
+ 00000722  8B 58 04                    mov  ebx, [eax+4]\r
+ 00000725  83 EB 0B                    sub  ebx,11\r
+ 00000728  01 5C 24 14                 add  [esp+20],ebx\r
+\r
+ 0000072C                      L_buf_not_used:\r
+ 0000072C  89 30                       mov  [eax+0],esi\r
+\r
+ 0000072E  BB 00000001                 mov  ebx,1\r
+ 00000733  D3 E3                       shl  ebx,cl\r
+ 00000735  4B                          dec  ebx\r
+\r
+\r
+\r
+\r
+\r
+ 00000736  83 3D 00000000 R            cmp  dword ptr [inflate_fast_use_mmx],2\r
+          02\r
+ 0000073D  75 08                       jne  L_update_hold\r
+\r
+\r
+\r
+ 0000073F  0F D3 C1                    psrlq mm0,mm1\r
+ 00000742  0F 7E C5                    movd ebp,mm0\r
+\r
+ 00000745  0F 77                       emms\r
+\r
+ 00000747                      L_update_hold:\r
+\r
+\r
+\r
+ 00000747  23 EB                       and  ebp,ebx\r
+ 00000749  89 6A 38                    mov  [edx+hold_state],ebp\r
+\r
+\r
+\r
+\r
+ 0000074C  8B 5C 24 14                 mov  ebx, [esp+20]\r
+ 00000750  3B DE                       cmp  ebx,esi\r
+ 00000752  76 0A                       jbe  L_last_is_smaller\r
+\r
+ 00000754  2B DE                       sub  ebx,esi\r
+ 00000756  83 C3 0B                    add  ebx,11\r
+ 00000759  89 58 04                    mov  [eax+4],ebx\r
+ 0000075C  EB 0A                       jmp  L_fixup_out\r
+ 0000075E                      L_last_is_smaller:\r
+ 0000075E  2B F3                       sub  esi,ebx\r
+ 00000760  F7 DE                       neg  esi\r
+ 00000762  83 C6 0B                    add  esi,11\r
+ 00000765  89 70 04                    mov  [eax+4],esi\r
+\r
+\r
+\r
+\r
+ 00000768                      L_fixup_out:\r
+\r
+ 00000768  8B 5C 24 10                 mov  ebx, [esp+16]\r
+ 0000076C  3B DF                       cmp  ebx,edi\r
+ 0000076E  76 0D                       jbe  L_end_is_smaller\r
+\r
+ 00000770  2B DF                       sub  ebx,edi\r
+ 00000772  81 C3 00000101              add  ebx,257\r
+ 00000778  89 58 10                    mov  [eax+16],ebx\r
+ 0000077B  EB 0D                       jmp  L_done\r
+ 0000077D                      L_end_is_smaller:\r
+ 0000077D  2B FB                       sub  edi,ebx\r
+ 0000077F  F7 DF                       neg  edi\r
+ 00000781  81 C7 00000101              add  edi,257\r
+ 00000787  89 78 10                    mov  [eax+16],edi\r
+\r
+\r
+\r
+\r
+\r
+ 0000078A                      L_done:\r
+ 0000078A  83 C4 40                    add  esp,64\r
+ 0000078D  9D                          popfd\r
+ 0000078E  5B                          pop  ebx\r
+ 0000078F  5D                          pop  ebp\r
+ 00000790  5E                          pop  esi\r
+ 00000791  5F                          pop  edi\r
+ 00000792  C3                          ret\r
+ 00000793                      _inflate_fast endp\r
+\r
+ 00000004                      _TEXT   ends\r
+                               end\r
+\fMicrosoft (R) Macro Assembler Version 10.00.30319.01      04/13/12 13:33:41\r
+inffas32.asm                                                Symbols 2 - 1\r
+\r
+\r
+\r
+\r
+Segments and Groups:\r
+\r
+                N a m e                 Size     Length   Align   Combine Class\r
+\r
+FLAT . . . . . . . . . . . . . .       GROUP\r
+_DATA  . . . . . . . . . . . . .       32 Bit   00000004 Para    Public  'DATA'        \r
+_TEXT  . . . . . . . . . . . . .       32 Bit   00000793 Para    Public  'CODE'        \r
+\r
+\r
+Procedures, parameters, and locals:\r
+\r
+                N a m e                 Type     Value    Attr\r
+\r
+_inflate_fast  . . . . . . . . .       P Near   00000100 _TEXT Length= 00000693 Public\r
+  L_align_long . . . . . . . . .       L Near   000001BA _TEXT \r
+  L_is_aligned . . . . . . . . .       L Near   000001D2 _TEXT \r
+  L_check_mmx  . . . . . . . . .       L Near   000001D6 _TEXT \r
+  L_use_mmx  . . . . . . . . . .       L Near   00000233 _TEXT \r
+  L_dont_use_mmx . . . . . . . .       L Near   0000023F _TEXT \r
+  L_check_mmx_pop  . . . . . . .       L Near   00000249 _TEXT \r
+  L_do_loop  . . . . . . . . . .       L Near   00000250 _TEXT \r
+  L_get_length_code  . . . . . .       L Near   00000262 _TEXT \r
+  L_dolen  . . . . . . . . . . .       L Near   0000026E _TEXT \r
+  L_while_test . . . . . . . . .       L Near   0000027C _TEXT \r
+  L_test_for_length_base . . . .       L Near   00000291 _TEXT \r
+  L_add_bits_to_len  . . . . . .       L Near   000002BA _TEXT \r
+  L_save_len . . . . . . . . . .       L Near   000002CA _TEXT \r
+  L_decode_distance  . . . . . .       L Near   000002CE _TEXT \r
+  L_get_distance_code  . . . . .       L Near   000002E0 _TEXT \r
+  L_dodist . . . . . . . . . . .       L Near   000002ED _TEXT \r
+  L_add_bits_to_dist . . . . . .       L Near   0000031C _TEXT \r
+  L_check_window . . . . . . . .       L Near   0000032E _TEXT \r
+  L_check_dist_one . . . . . . .       L Near   0000036C _TEXT \r
+  L_test_for_second_level_length .     L Near   00000394 _TEXT \r
+  L_test_for_second_level_dist .       L Near   000003B4 _TEXT \r
+  L_clip_window  . . . . . . . .       L Near   000003D4 _TEXT \r
+  L_wrap_around_window . . . . .       L Near   00000415 _TEXT \r
+  L_contiguous_in_window . . . .       L Near   00000449 _TEXT \r
+  L_do_copy1 . . . . . . . . . .       L Near   0000045D _TEXT \r
+  L_init_mmx . . . . . . . . . .       L Near   0000046C _TEXT \r
+  L_do_loop_mmx  . . . . . . . .       L Near   0000048C _TEXT \r
+  L_get_length_code_mmx  . . . .       L Near   000004A6 _TEXT \r
+  L_dolen_mmx  . . . . . . . . .       L Near   000004B2 _TEXT \r
+  L_while_test_mmx . . . . . . .       L Near   000004C2 _TEXT \r
+  L_test_for_length_base_mmx . .       L Near   000004D7 _TEXT \r
+  L_decode_distance_mmx  . . . .       L Near   000004FD _TEXT \r
+  L_get_dist_code_mmx  . . . . .       L Near   00000517 _TEXT \r
+  L_dodist_mmx . . . . . . . . .       L Near   00000527 _TEXT \r
+  L_add_bits_to_dist_mmx . . . .       L Near   00000541 _TEXT \r
+  L_check_window_mmx . . . . . .       L Near   00000555 _TEXT \r
+  L_check_dist_one_mmx . . . . .       L Near   00000598 _TEXT \r
+  L_test_for_second_level_length_mmx . L Near   000005C4 _TEXT \r
+  L_test_for_second_level_dist_mmx .   L Near   000005E8 _TEXT \r
+  L_clip_window_mmx  . . . . . .       L Near   00000610 _TEXT \r
+  L_wrap_around_window_mmx . . .       L Near   0000064D _TEXT \r
+  L_contiguous_in_window_mmx . .       L Near   0000067D _TEXT \r
+  L_do_copy1_mmx . . . . . . . .       L Near   0000068D _TEXT \r
+  L_invalid_distance_code  . . .       L Near   0000069E _TEXT \r
+  L_test_for_end_of_block  . . .       L Near   000006AA _TEXT \r
+  L_invalid_literal_length_code        L Near   000006BA _TEXT \r
+  L_invalid_distance_too_far . .       L Near   000006C6 _TEXT \r
+  L_update_stream_state  . . . .       L Near   000006D6 _TEXT \r
+  L_skip_msg . . . . . . . . . .       L Near   000006E1 _TEXT \r
+  L_break_loop . . . . . . . . .       L Near   000006E8 _TEXT \r
+  L_update_next_in . . . . . . .       L Near   000006F3 _TEXT \r
+  L_buf_not_used . . . . . . . .       L Near   0000072C _TEXT \r
+  L_update_hold  . . . . . . . .       L Near   00000747 _TEXT \r
+  L_last_is_smaller  . . . . . .       L Near   0000075E _TEXT \r
+  L_fixup_out  . . . . . . . . .       L Near   00000768 _TEXT \r
+  L_end_is_smaller . . . . . . .       L Near   0000077D _TEXT \r
+  L_done . . . . . . . . . . . .       L Near   0000078A _TEXT \r
+\r
+\r
+Symbols:\r
+\r
+                N a m e                 Type     Value    Attr\r
+\r
+@CodeSize  . . . . . . . . . . .       Number   00000000h   \r
+@DataSize  . . . . . . . . . . .       Number   00000000h   \r
+@Interface . . . . . . . . . . .       Number   00000000h   \r
+@Model . . . . . . . . . . . . .       Number   00000007h   \r
+@code  . . . . . . . . . . . . .       Text     _TEXT\r
+@data  . . . . . . . . . . . . .       Text     FLAT\r
+@fardata?  . . . . . . . . . . .       Text     FLAT\r
+@fardata . . . . . . . . . . . .       Text     FLAT\r
+@stack . . . . . . . . . . . . .       Text     FLAT\r
+INFLATE_MODE_BAD . . . . . . . .       Number   0000001Ah   \r
+INFLATE_MODE_TYPE  . . . . . . .       Number   0000000Bh   \r
+bits_state . . . . . . . . . . .       Number   0000003Ch   \r
+distbits_state . . . . . . . . .       Number   00000058h   \r
+distcode_state . . . . . . . . .       Number   00000050h   \r
+hold_state . . . . . . . . . . .       Number   00000038h   \r
+inflate_fast_mask  . . . . . . .       L Near   0000007C _TEXT \r
+inflate_fast_use_mmx . . . . . .       L Near   00000000 _DATA \r
+invalid_distance_code_msg  . . .       L Near   00000044 _TEXT \r
+invalid_distance_too_far_msg . .       L Near   0000005C _TEXT \r
+invalid_literal_length_code_msg        L Near   00000028 _TEXT \r
+lenbits_state  . . . . . . . . .       Number   00000054h   \r
+lencode_state  . . . . . . . . .       Number   0000004Ch   \r
+mode_state . . . . . . . . . . .       Number   00000000h   \r
+window_state . . . . . . . . . .       Number   00000034h   \r
+write_state  . . . . . . . . . .       Number   00000030h   \r
+wsize_state  . . . . . . . . . .       Number   00000028h   \r
+zlib1222sup  . . . . . . . . . .       Number   00000008h   \r
+\r
+          0 Warnings\r
+          0 Errors\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/match686.asm b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/match686.asm
new file mode 100644 (file)
index 0000000..3b09212
--- /dev/null
@@ -0,0 +1,479 @@
+; match686.asm -- Asm portion of the optimized longest_match for 32 bits x86\r
+; Copyright (C) 1995-1996 Jean-loup Gailly, Brian Raiter and Gilles Vollant.\r
+; File written by Gilles Vollant, by converting match686.S from Brian Raiter\r
+; for MASM. This is as assembly version of longest_match\r
+;  from Jean-loup Gailly in deflate.c\r
+;\r
+;         http://www.zlib.net\r
+;         http://www.winimage.com/zLibDll\r
+;         http://www.muppetlabs.com/~breadbox/software/assembly.html\r
+;\r
+; For Visual C++ 4.x and higher and ML 6.x and higher\r
+;   ml.exe is distributed in\r
+;  http://www.microsoft.com/downloads/details.aspx?FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64\r
+;\r
+; this file contain two implementation of longest_match\r
+;\r
+;  this longest_match was written by Brian raiter (1998), optimized for Pentium Pro\r
+;   (and the faster known version of match_init on modern Core 2 Duo and AMD Phenom)\r
+;\r
+;  for using an assembly version of longest_match, you need define ASMV in project\r
+;\r
+;    compile the asm file running\r
+;           ml /coff /Zi /c /Flmatch686.lst match686.asm\r
+;    and do not include match686.obj in your project\r
+;\r
+; note: contrib of zLib 1.2.3 and earlier contained both a deprecated version for\r
+;  Pentium (prior Pentium Pro) and this version for Pentium Pro and modern processor\r
+;  with autoselect (with cpu detection code)\r
+;  if you want support the old pentium optimization, you can still use these version\r
+;\r
+; this file is not optimized for old pentium, but it compatible with all x86 32 bits\r
+; processor (starting 80386)\r
+;\r
+;\r
+; see below : zlib1222add must be adjuster if you use a zlib version < 1.2.2.2\r
+\r
+;uInt longest_match(s, cur_match)\r
+;    deflate_state *s;\r
+;    IPos cur_match;                             /* current match */\r
+\r
+    NbStack         equ     76\r
+    cur_match       equ     dword ptr[esp+NbStack-0]\r
+    str_s           equ     dword ptr[esp+NbStack-4]\r
+; 5 dword on top (ret,ebp,esi,edi,ebx)\r
+    adrret          equ     dword ptr[esp+NbStack-8]\r
+    pushebp         equ     dword ptr[esp+NbStack-12]\r
+    pushedi         equ     dword ptr[esp+NbStack-16]\r
+    pushesi         equ     dword ptr[esp+NbStack-20]\r
+    pushebx         equ     dword ptr[esp+NbStack-24]\r
+\r
+    chain_length    equ     dword ptr [esp+NbStack-28]\r
+    limit           equ     dword ptr [esp+NbStack-32]\r
+    best_len        equ     dword ptr [esp+NbStack-36]\r
+    window          equ     dword ptr [esp+NbStack-40]\r
+    prev            equ     dword ptr [esp+NbStack-44]\r
+    scan_start      equ      word ptr [esp+NbStack-48]\r
+    wmask           equ     dword ptr [esp+NbStack-52]\r
+    match_start_ptr equ     dword ptr [esp+NbStack-56]\r
+    nice_match      equ     dword ptr [esp+NbStack-60]\r
+    scan            equ     dword ptr [esp+NbStack-64]\r
+\r
+    windowlen       equ     dword ptr [esp+NbStack-68]\r
+    match_start     equ     dword ptr [esp+NbStack-72]\r
+    strend          equ     dword ptr [esp+NbStack-76]\r
+    NbStackAdd      equ     (NbStack-24)\r
+\r
+    .386p\r
+\r
+    name    gvmatch\r
+    .MODEL  FLAT\r
+\r
+\r
+\r
+;  all the +zlib1222add offsets are due to the addition of fields\r
+;  in zlib in the deflate_state structure since the asm code was first written\r
+;  (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").\r
+;  (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").\r
+;  if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").\r
+\r
+    zlib1222add         equ     8\r
+\r
+;  Note : these value are good with a 8 bytes boundary pack structure\r
+    dep_chain_length    equ     74h+zlib1222add\r
+    dep_window          equ     30h+zlib1222add\r
+    dep_strstart        equ     64h+zlib1222add\r
+    dep_prev_length     equ     70h+zlib1222add\r
+    dep_nice_match      equ     88h+zlib1222add\r
+    dep_w_size          equ     24h+zlib1222add\r
+    dep_prev            equ     38h+zlib1222add\r
+    dep_w_mask          equ     2ch+zlib1222add\r
+    dep_good_match      equ     84h+zlib1222add\r
+    dep_match_start     equ     68h+zlib1222add\r
+    dep_lookahead       equ     6ch+zlib1222add\r
+\r
+\r
+_TEXT                   segment\r
+\r
+IFDEF NOUNDERLINE\r
+            public  longest_match\r
+            public  match_init\r
+ELSE\r
+            public  _longest_match\r
+            public  _match_init\r
+ENDIF\r
+\r
+    MAX_MATCH           equ     258\r
+    MIN_MATCH           equ     3\r
+    MIN_LOOKAHEAD       equ     (MAX_MATCH+MIN_MATCH+1)\r
+\r
+\r
+\r
+MAX_MATCH       equ     258\r
+MIN_MATCH       equ     3\r
+MIN_LOOKAHEAD   equ     (MAX_MATCH + MIN_MATCH + 1)\r
+MAX_MATCH_8_     equ     ((MAX_MATCH + 7) AND 0FFF0h)\r
+\r
+\r
+;;; stack frame offsets\r
+\r
+chainlenwmask   equ  esp + 0    ; high word: current chain len\r
+                    ; low word: s->wmask\r
+window      equ  esp + 4    ; local copy of s->window\r
+windowbestlen   equ  esp + 8    ; s->window + bestlen\r
+scanstart   equ  esp + 16   ; first two bytes of string\r
+scanend     equ  esp + 12   ; last two bytes of string\r
+scanalign   equ  esp + 20   ; dword-misalignment of string\r
+nicematch   equ  esp + 24   ; a good enough match size\r
+bestlen     equ  esp + 28   ; size of best match so far\r
+scan        equ  esp + 32   ; ptr to string wanting match\r
+\r
+LocalVarsSize   equ 36\r
+;   saved ebx   byte esp + 36\r
+;   saved edi   byte esp + 40\r
+;   saved esi   byte esp + 44\r
+;   saved ebp   byte esp + 48\r
+;   return address  byte esp + 52\r
+deflatestate    equ  esp + 56   ; the function arguments\r
+curmatch    equ  esp + 60\r
+\r
+;;; Offsets for fields in the deflate_state structure. These numbers\r
+;;; are calculated from the definition of deflate_state, with the\r
+;;; assumption that the compiler will dword-align the fields. (Thus,\r
+;;; changing the definition of deflate_state could easily cause this\r
+;;; program to crash horribly, without so much as a warning at\r
+;;; compile time. Sigh.)\r
+\r
+dsWSize     equ 36+zlib1222add\r
+dsWMask     equ 44+zlib1222add\r
+dsWindow    equ 48+zlib1222add\r
+dsPrev      equ 56+zlib1222add\r
+dsMatchLen  equ 88+zlib1222add\r
+dsPrevMatch equ 92+zlib1222add\r
+dsStrStart  equ 100+zlib1222add\r
+dsMatchStart    equ 104+zlib1222add\r
+dsLookahead equ 108+zlib1222add\r
+dsPrevLen   equ 112+zlib1222add\r
+dsMaxChainLen   equ 116+zlib1222add\r
+dsGoodMatch equ 132+zlib1222add\r
+dsNiceMatch equ 136+zlib1222add\r
+\r
+\r
+;;; match686.asm -- Pentium-Pro-optimized version of longest_match()\r
+;;; Written for zlib 1.1.2\r
+;;; Copyright (C) 1998 Brian Raiter <breadbox@muppetlabs.com>\r
+;;; You can look at http://www.muppetlabs.com/~breadbox/software/assembly.html\r
+;;;\r
+;;\r
+;;  This software is provided 'as-is', without any express or implied\r
+;;  warranty.  In no event will the authors be held liable for any damages\r
+;;  arising from the use of this software.\r
+;;\r
+;;  Permission is granted to anyone to use this software for any purpose,\r
+;;  including commercial applications, and to alter it and redistribute it\r
+;;  freely, subject to the following restrictions:\r
+;;\r
+;;  1. The origin of this software must not be misrepresented; you must not\r
+;;     claim that you wrote the original software. If you use this software\r
+;;     in a product, an acknowledgment in the product documentation would be\r
+;;     appreciated but is not required.\r
+;;  2. Altered source versions must be plainly marked as such, and must not be\r
+;;     misrepresented as being the original software\r
+;;  3. This notice may not be removed or altered from any source distribution.\r
+;;\r
+\r
+;GLOBAL _longest_match, _match_init\r
+\r
+\r
+;SECTION    .text\r
+\r
+;;; uInt longest_match(deflate_state *deflatestate, IPos curmatch)\r
+\r
+;_longest_match:\r
+    IFDEF NOUNDERLINE\r
+    longest_match       proc near\r
+    ELSE\r
+    _longest_match      proc near\r
+    ENDIF\r
+.FPO (9, 4, 0, 0, 1, 0)\r
+\r
+;;; Save registers that the compiler may be using, and adjust esp to\r
+;;; make room for our stack frame.\r
+\r
+        push    ebp\r
+        push    edi\r
+        push    esi\r
+        push    ebx\r
+        sub esp, LocalVarsSize\r
+\r
+;;; Retrieve the function arguments. ecx will hold cur_match\r
+;;; throughout the entire function. edx will hold the pointer to the\r
+;;; deflate_state structure during the function's setup (before\r
+;;; entering the main loop.\r
+\r
+        mov edx, [deflatestate]\r
+        mov ecx, [curmatch]\r
+\r
+;;; uInt wmask = s->w_mask;\r
+;;; unsigned chain_length = s->max_chain_length;\r
+;;; if (s->prev_length >= s->good_match) {\r
+;;;     chain_length >>= 2;\r
+;;; }\r
+\r
+        mov eax, [edx + dsPrevLen]\r
+        mov ebx, [edx + dsGoodMatch]\r
+        cmp eax, ebx\r
+        mov eax, [edx + dsWMask]\r
+        mov ebx, [edx + dsMaxChainLen]\r
+        jl  LastMatchGood\r
+        shr ebx, 2\r
+LastMatchGood:\r
+\r
+;;; chainlen is decremented once beforehand so that the function can\r
+;;; use the sign flag instead of the zero flag for the exit test.\r
+;;; It is then shifted into the high word, to make room for the wmask\r
+;;; value, which it will always accompany.\r
+\r
+        dec ebx\r
+        shl ebx, 16\r
+        or  ebx, eax\r
+        mov [chainlenwmask], ebx\r
+\r
+;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;\r
+\r
+        mov eax, [edx + dsNiceMatch]\r
+        mov ebx, [edx + dsLookahead]\r
+        cmp ebx, eax\r
+        jl  LookaheadLess\r
+        mov ebx, eax\r
+LookaheadLess:  mov [nicematch], ebx\r
+\r
+;;; register Bytef *scan = s->window + s->strstart;\r
+\r
+        mov esi, [edx + dsWindow]\r
+        mov [window], esi\r
+        mov ebp, [edx + dsStrStart]\r
+        lea edi, [esi + ebp]\r
+        mov [scan], edi\r
+\r
+;;; Determine how many bytes the scan ptr is off from being\r
+;;; dword-aligned.\r
+\r
+        mov eax, edi\r
+        neg eax\r
+        and eax, 3\r
+        mov [scanalign], eax\r
+\r
+;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ?\r
+;;;     s->strstart - (IPos)MAX_DIST(s) : NIL;\r
+\r
+        mov eax, [edx + dsWSize]\r
+        sub eax, MIN_LOOKAHEAD\r
+        sub ebp, eax\r
+        jg  LimitPositive\r
+        xor ebp, ebp\r
+LimitPositive:\r
+\r
+;;; int best_len = s->prev_length;\r
+\r
+        mov eax, [edx + dsPrevLen]\r
+        mov [bestlen], eax\r
+\r
+;;; Store the sum of s->window + best_len in esi locally, and in esi.\r
+\r
+        add esi, eax\r
+        mov [windowbestlen], esi\r
+\r
+;;; register ush scan_start = *(ushf*)scan;\r
+;;; register ush scan_end   = *(ushf*)(scan+best_len-1);\r
+;;; Posf *prev = s->prev;\r
+\r
+        movzx   ebx, word ptr [edi]\r
+        mov [scanstart], ebx\r
+        movzx   ebx, word ptr [edi + eax - 1]\r
+        mov [scanend], ebx\r
+        mov edi, [edx + dsPrev]\r
+\r
+;;; Jump into the main loop.\r
+\r
+        mov edx, [chainlenwmask]\r
+        jmp short LoopEntry\r
+\r
+align 4\r
+\r
+;;; do {\r
+;;;     match = s->window + cur_match;\r
+;;;     if (*(ushf*)(match+best_len-1) != scan_end ||\r
+;;;         *(ushf*)match != scan_start) continue;\r
+;;;     [...]\r
+;;; } while ((cur_match = prev[cur_match & wmask]) > limit\r
+;;;          && --chain_length != 0);\r
+;;;\r
+;;; Here is the inner loop of the function. The function will spend the\r
+;;; majority of its time in this loop, and majority of that time will\r
+;;; be spent in the first ten instructions.\r
+;;;\r
+;;; Within this loop:\r
+;;; ebx = scanend\r
+;;; ecx = curmatch\r
+;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask)\r
+;;; esi = windowbestlen - i.e., (window + bestlen)\r
+;;; edi = prev\r
+;;; ebp = limit\r
+\r
+LookupLoop:\r
+        and ecx, edx\r
+        movzx   ecx, word ptr [edi + ecx*2]\r
+        cmp ecx, ebp\r
+        jbe LeaveNow\r
+        sub edx, 00010000h\r
+        js  LeaveNow\r
+LoopEntry:  movzx   eax, word ptr [esi + ecx - 1]\r
+        cmp eax, ebx\r
+        jnz LookupLoop\r
+        mov eax, [window]\r
+        movzx   eax, word ptr [eax + ecx]\r
+        cmp eax, [scanstart]\r
+        jnz LookupLoop\r
+\r
+;;; Store the current value of chainlen.\r
+\r
+        mov [chainlenwmask], edx\r
+\r
+;;; Point edi to the string under scrutiny, and esi to the string we\r
+;;; are hoping to match it up with. In actuality, esi and edi are\r
+;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is\r
+;;; initialized to -(MAX_MATCH_8 - scanalign).\r
+\r
+        mov esi, [window]\r
+        mov edi, [scan]\r
+        add esi, ecx\r
+        mov eax, [scanalign]\r
+        mov edx, 0fffffef8h; -(MAX_MATCH_8)\r
+        lea edi, [edi + eax + 0108h] ;MAX_MATCH_8]\r
+        lea esi, [esi + eax + 0108h] ;MAX_MATCH_8]\r
+\r
+;;; Test the strings for equality, 8 bytes at a time. At the end,\r
+;;; adjust edx so that it is offset to the exact byte that mismatched.\r
+;;;\r
+;;; We already know at this point that the first three bytes of the\r
+;;; strings match each other, and they can be safely passed over before\r
+;;; starting the compare loop. So what this code does is skip over 0-3\r
+;;; bytes, as much as necessary in order to dword-align the edi\r
+;;; pointer. (esi will still be misaligned three times out of four.)\r
+;;;\r
+;;; It should be confessed that this loop usually does not represent\r
+;;; much of the total running time. Replacing it with a more\r
+;;; straightforward "rep cmpsb" would not drastically degrade\r
+;;; performance.\r
+\r
+LoopCmps:\r
+        mov eax, [esi + edx]\r
+        xor eax, [edi + edx]\r
+        jnz LeaveLoopCmps\r
+        mov eax, [esi + edx + 4]\r
+        xor eax, [edi + edx + 4]\r
+        jnz LeaveLoopCmps4\r
+        add edx, 8\r
+        jnz LoopCmps\r
+        jmp short LenMaximum\r
+LeaveLoopCmps4: add edx, 4\r
+LeaveLoopCmps:  test    eax, 0000FFFFh\r
+        jnz LenLower\r
+        add edx,  2\r
+        shr eax, 16\r
+LenLower:   sub al, 1\r
+        adc edx, 0\r
+\r
+;;; Calculate the length of the match. If it is longer than MAX_MATCH,\r
+;;; then automatically accept it as the best possible match and leave.\r
+\r
+        lea eax, [edi + edx]\r
+        mov edi, [scan]\r
+        sub eax, edi\r
+        cmp eax, MAX_MATCH\r
+        jge LenMaximum\r
+\r
+;;; If the length of the match is not longer than the best match we\r
+;;; have so far, then forget it and return to the lookup loop.\r
+\r
+        mov edx, [deflatestate]\r
+        mov ebx, [bestlen]\r
+        cmp eax, ebx\r
+        jg  LongerMatch\r
+        mov esi, [windowbestlen]\r
+        mov edi, [edx + dsPrev]\r
+        mov ebx, [scanend]\r
+        mov edx, [chainlenwmask]\r
+        jmp LookupLoop\r
+\r
+;;;         s->match_start = cur_match;\r
+;;;         best_len = len;\r
+;;;         if (len >= nice_match) break;\r
+;;;         scan_end = *(ushf*)(scan+best_len-1);\r
+\r
+LongerMatch:    mov ebx, [nicematch]\r
+        mov [bestlen], eax\r
+        mov [edx + dsMatchStart], ecx\r
+        cmp eax, ebx\r
+        jge LeaveNow\r
+        mov esi, [window]\r
+        add esi, eax\r
+        mov [windowbestlen], esi\r
+        movzx   ebx, word ptr [edi + eax - 1]\r
+        mov edi, [edx + dsPrev]\r
+        mov [scanend], ebx\r
+        mov edx, [chainlenwmask]\r
+        jmp LookupLoop\r
+\r
+;;; Accept the current string, with the maximum possible length.\r
+\r
+LenMaximum: mov edx, [deflatestate]\r
+        mov dword ptr [bestlen], MAX_MATCH\r
+        mov [edx + dsMatchStart], ecx\r
+\r
+;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len;\r
+;;; return s->lookahead;\r
+\r
+LeaveNow:\r
+        mov edx, [deflatestate]\r
+        mov ebx, [bestlen]\r
+        mov eax, [edx + dsLookahead]\r
+        cmp ebx, eax\r
+        jg  LookaheadRet\r
+        mov eax, ebx\r
+LookaheadRet:\r
+\r
+;;; Restore the stack and return from whence we came.\r
+\r
+        add esp, LocalVarsSize\r
+        pop ebx\r
+        pop esi\r
+        pop edi\r
+        pop ebp\r
+\r
+        ret\r
+; please don't remove this string !\r
+; Your can freely use match686 in any free or commercial app if you don't remove the string in the binary!\r
+    db     0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998",0dh,0ah\r
+\r
+\r
+    IFDEF NOUNDERLINE\r
+    longest_match       endp\r
+    ELSE\r
+    _longest_match      endp\r
+    ENDIF\r
+\r
+    IFDEF NOUNDERLINE\r
+    match_init      proc near\r
+                    ret\r
+    match_init      endp\r
+    ELSE\r
+    _match_init     proc near\r
+                    ret\r
+    _match_init     endp\r
+    ENDIF\r
+\r
+\r
+_TEXT   ends\r
+end\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/match686.lst b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/match686.lst
new file mode 100644 (file)
index 0000000..efa90e1
--- /dev/null
@@ -0,0 +1,624 @@
+Microsoft (R) Macro Assembler Version 10.00.30319.01       04/13/12 13:33:40\r
+match686.asm                                                Page 1 - 1\r
+\r
+\r
+                               ; match686.asm -- Asm portion of the optimized longest_match for 32 bits x86\r
+                               ; Copyright (C) 1995-1996 Jean-loup Gailly, Brian Raiter and Gilles Vollant.\r
+                               ; File written by Gilles Vollant, by converting match686.S from Brian Raiter\r
+                               ; for MASM. This is as assembly version of longest_match\r
+                               ;  from Jean-loup Gailly in deflate.c\r
+                               ;\r
+                               ;         http://www.zlib.net\r
+                               ;         http://www.winimage.com/zLibDll\r
+                               ;         http://www.muppetlabs.com/~breadbox/software/assembly.html\r
+                               ;\r
+                               ; For Visual C++ 4.x and higher and ML 6.x and higher\r
+                               ;   ml.exe is distributed in\r
+                               ;  http://www.microsoft.com/downloads/details.aspx?FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64\r
+                               ;\r
+                               ; this file contain two implementation of longest_match\r
+                               ;\r
+                               ;  this longest_match was written by Brian raiter (1998), optimized for Pentium Pro\r
+                               ;   (and the faster known version of match_init on modern Core 2 Duo and AMD Phenom)\r
+                               ;\r
+                               ;  for using an assembly version of longest_match, you need define ASMV in project\r
+                               ;\r
+                               ;    compile the asm file running\r
+                               ;           ml /coff /Zi /c /Flmatch686.lst match686.asm\r
+                               ;    and do not include match686.obj in your project\r
+                               ;\r
+                               ; note: contrib of zLib 1.2.3 and earlier contained both a deprecated version for\r
+                               ;  Pentium (prior Pentium Pro) and this version for Pentium Pro and modern processor\r
+                               ;  with autoselect (with cpu detection code)\r
+                               ;  if you want support the old pentium optimization, you can still use these version\r
+                               ;\r
+                               ; this file is not optimized for old pentium, but it compatible with all x86 32 bits\r
+                               ; processor (starting 80386)\r
+                               ;\r
+                               ;\r
+                               ; see below : zlib1222add must be adjuster if you use a zlib version < 1.2.2.2\r
+\r
+                               ;uInt longest_match(s, cur_match)\r
+                               ;    deflate_state *s;\r
+                               ;    IPos cur_match;                             /* current match */\r
+\r
+ = 0000004C                        NbStack         equ     76\r
+ = dword ptr[esp+NbStack-0]        cur_match       equ     dword ptr[esp+NbStack-0]\r
+ = dword ptr[esp+NbStack-4]        str_s           equ     dword ptr[esp+NbStack-4]\r
+                               ; 5 dword on top (ret,ebp,esi,edi,ebx)\r
+ = dword ptr[esp+NbStack-8]        adrret          equ     dword ptr[esp+NbStack-8]\r
+ = dword ptr[esp+NbStack-12        pushebp         equ     dword ptr[esp+NbStack-12]\r
+   ]\r
+ = dword ptr[esp+NbStack-16        pushedi         equ     dword ptr[esp+NbStack-16]\r
+   ]\r
+ = dword ptr[esp+NbStack-20        pushesi         equ     dword ptr[esp+NbStack-20]\r
+   ]\r
+ = dword ptr[esp+NbStack-24        pushebx         equ     dword ptr[esp+NbStack-24]\r
+   ]\r
+\r
+ = dword ptr [esp+NbStack-2        chain_length    equ     dword ptr [esp+NbStack-28]\r
+   8]\r
+ = dword ptr [esp+NbStack-3        limit           equ     dword ptr [esp+NbStack-32]\r
+   2]\r
+ = dword ptr [esp+NbStack-3        best_len        equ     dword ptr [esp+NbStack-36]\r
+   6]\r
+ = dword ptr [esp+NbStack-4        window          equ     dword ptr [esp+NbStack-40]\r
+   0]\r
+ = dword ptr [esp+NbStack-4        prev            equ     dword ptr [esp+NbStack-44]\r
+   4]\r
+ = word ptr [esp+NbStack-48        scan_start      equ      word ptr [esp+NbStack-48]\r
+   ]\r
+ = dword ptr [esp+NbStack-5        wmask           equ     dword ptr [esp+NbStack-52]\r
+   2]\r
+ = dword ptr [esp+NbStack-5        match_start_ptr equ     dword ptr [esp+NbStack-56]\r
+   6]\r
+ = dword ptr [esp+NbStack-6        nice_match      equ     dword ptr [esp+NbStack-60]\r
+   0]\r
+ = dword ptr [esp+NbStack-6        scan            equ     dword ptr [esp+NbStack-64]\r
+   4]\r
+\r
+ = dword ptr [esp+NbStack-6        windowlen       equ     dword ptr [esp+NbStack-68]\r
+   8]\r
+ = dword ptr [esp+NbStack-7        match_start     equ     dword ptr [esp+NbStack-72]\r
+   2]\r
+ = dword ptr [esp+NbStack-7        strend          equ     dword ptr [esp+NbStack-76]\r
+   6]\r
+ = 00000034                        NbStackAdd      equ     (NbStack-24)\r
+\r
+                                   .386p\r
+\r
+                                   name    gvmatch\r
+                                   .MODEL  FLAT\r
+\r
+\r
+\r
+                               ;  all the +zlib1222add offsets are due to the addition of fields\r
+                               ;  in zlib in the deflate_state structure since the asm code was first written\r
+                               ;  (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").\r
+                               ;  (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").\r
+                               ;  if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").\r
+\r
+ = 00000008                        zlib1222add         equ     8\r
+\r
+                               ;  Note : these value are good with a 8 bytes boundary pack structure\r
+ = 0000007C                        dep_chain_length    equ     74h+zlib1222add\r
+ = 00000038                        dep_window          equ     30h+zlib1222add\r
+ = 0000006C                        dep_strstart        equ     64h+zlib1222add\r
+ = 00000078                        dep_prev_length     equ     70h+zlib1222add\r
+ = 00000090                        dep_nice_match      equ     88h+zlib1222add\r
+ = 0000002C                        dep_w_size          equ     24h+zlib1222add\r
+ = 00000040                        dep_prev            equ     38h+zlib1222add\r
+ = 00000034                        dep_w_mask          equ     2ch+zlib1222add\r
+ = 0000008C                        dep_good_match      equ     84h+zlib1222add\r
+ = 00000070                        dep_match_start     equ     68h+zlib1222add\r
+ = 00000074                        dep_lookahead       equ     6ch+zlib1222add\r
+\r
+\r
+ 00000000                      _TEXT                   segment\r
+\r
+                               IFDEF NOUNDERLINE\r
+                               ELSE\r
+                                           public  _longest_match\r
+                                           public  _match_init\r
+                               ENDIF\r
+\r
+ = 00000102                        MAX_MATCH           equ     258\r
+ = 00000003                        MIN_MATCH           equ     3\r
+ = 00000106                        MIN_LOOKAHEAD       equ     (MAX_MATCH+MIN_MATCH+1)\r
+\r
+\r
+\r
+ = 00000102                    MAX_MATCH       equ     258\r
+ = 00000003                    MIN_MATCH       equ     3\r
+ = 00000106                    MIN_LOOKAHEAD   equ     (MAX_MATCH + MIN_MATCH + 1)\r
+ = 00000100                    MAX_MATCH_8_     equ     ((MAX_MATCH + 7) AND 0FFF0h)\r
+\r
+\r
+                               ;;; stack frame offsets\r
+\r
+ = esp + 0                     chainlenwmask   equ  esp + 0    ; high word: current chain len\r
+                                                   ; low word: s->wmask\r
+ = esp + 4                     window      equ  esp + 4    ; local copy of s->window\r
+ = esp + 8                     windowbestlen   equ  esp + 8    ; s->window + bestlen\r
+ = esp + 16                    scanstart   equ  esp + 16   ; first two bytes of string\r
+ = esp + 12                    scanend     equ  esp + 12   ; last two bytes of string\r
+ = esp + 20                    scanalign   equ  esp + 20   ; dword-misalignment of string\r
+ = esp + 24                    nicematch   equ  esp + 24   ; a good enough match size\r
+ = esp + 28                    bestlen     equ  esp + 28   ; size of best match so far\r
+ = esp + 32                    scan        equ  esp + 32   ; ptr to string wanting match\r
+\r
+ = 00000024                    LocalVarsSize   equ 36\r
+                               ;   saved ebx   byte esp + 36\r
+                               ;   saved edi   byte esp + 40\r
+                               ;   saved esi   byte esp + 44\r
+                               ;   saved ebp   byte esp + 48\r
+                               ;   return address  byte esp + 52\r
+ = esp + 56                    deflatestate    equ  esp + 56   ; the function arguments\r
+ = esp + 60                    curmatch    equ  esp + 60\r
+\r
+                               ;;; Offsets for fields in the deflate_state structure. These numbers\r
+                               ;;; are calculated from the definition of deflate_state, with the\r
+                               ;;; assumption that the compiler will dword-align the fields. (Thus,\r
+                               ;;; changing the definition of deflate_state could easily cause this\r
+                               ;;; program to crash horribly, without so much as a warning at\r
+                               ;;; compile time. Sigh.)\r
+\r
+ = 0000002C                    dsWSize     equ 36+zlib1222add\r
+ = 00000034                    dsWMask     equ 44+zlib1222add\r
+ = 00000038                    dsWindow    equ 48+zlib1222add\r
+ = 00000040                    dsPrev      equ 56+zlib1222add\r
+ = 00000060                    dsMatchLen  equ 88+zlib1222add\r
+ = 00000064                    dsPrevMatch equ 92+zlib1222add\r
+ = 0000006C                    dsStrStart  equ 100+zlib1222add\r
+ = 00000070                    dsMatchStart    equ 104+zlib1222add\r
+ = 00000074                    dsLookahead equ 108+zlib1222add\r
+ = 00000078                    dsPrevLen   equ 112+zlib1222add\r
+ = 0000007C                    dsMaxChainLen   equ 116+zlib1222add\r
+ = 0000008C                    dsGoodMatch equ 132+zlib1222add\r
+ = 00000090                    dsNiceMatch equ 136+zlib1222add\r
+\r
+\r
+                               ;;; match686.asm -- Pentium-Pro-optimized version of longest_match()\r
+                               ;;; Written for zlib 1.1.2\r
+                               ;;; Copyright (C) 1998 Brian Raiter <breadbox@muppetlabs.com>\r
+                               ;;; You can look at http://www.muppetlabs.com/~breadbox/software/assembly.html\r
+                               ;;;\r
+                               ;;\r
+                               ;;  This software is provided 'as-is', without any express or implied\r
+                               ;;  warranty.  In no event will the authors be held liable for any damages\r
+                               ;;  arising from the use of this software.\r
+                               ;;\r
+                               ;;  Permission is granted to anyone to use this software for any purpose,\r
+                               ;;  including commercial applications, and to alter it and redistribute it\r
+                               ;;  freely, subject to the following restrictions:\r
+                               ;;\r
+                               ;;  1. The origin of this software must not be misrepresented; you must not\r
+                               ;;     claim that you wrote the original software. If you use this software\r
+                               ;;     in a product, an acknowledgment in the product documentation would be\r
+                               ;;     appreciated but is not required.\r
+                               ;;  2. Altered source versions must be plainly marked as such, and must not be\r
+                               ;;     misrepresented as being the original software\r
+                               ;;  3. This notice may not be removed or altered from any source distribution.\r
+                               ;;\r
+\r
+                               ;GLOBAL _longest_match, _match_init\r
+\r
+\r
+                               ;SECTION    .text\r
+\r
+                               ;;; uInt longest_match(deflate_state *deflatestate, IPos curmatch)\r
+\r
+                               ;_longest_match:\r
+                                   IFDEF NOUNDERLINE\r
+                                   ELSE\r
+ 00000000                          _longest_match      proc near\r
+                                   ENDIF\r
+ 00000000                      .FPO (9, 4, 0, 0, 1, 0)\r
+\r
+                               ;;; Save registers that the compiler may be using, and adjust esp to\r
+                               ;;; make room for our stack frame.\r
+\r
+ 00000000  55                          push    ebp\r
+ 00000001  57                          push    edi\r
+ 00000002  56                          push    esi\r
+ 00000003  53                          push    ebx\r
+ 00000004  83 EC 24                    sub esp, LocalVarsSize\r
+\r
+                               ;;; Retrieve the function arguments. ecx will hold cur_match\r
+                               ;;; throughout the entire function. edx will hold the pointer to the\r
+                               ;;; deflate_state structure during the function's setup (before\r
+                               ;;; entering the main loop.\r
+\r
+ 00000007  8B 54 24 38                 mov edx, [deflatestate]\r
+ 0000000B  8B 4C 24 3C                 mov ecx, [curmatch]\r
+\r
+                               ;;; uInt wmask = s->w_mask;\r
+                               ;;; unsigned chain_length = s->max_chain_length;\r
+                               ;;; if (s->prev_length >= s->good_match) {\r
+                               ;;;     chain_length >>= 2;\r
+                               ;;; }\r
+\r
+ 0000000F  8B 42 78                    mov eax, [edx + dsPrevLen]\r
+ 00000012  8B 9A 0000008C              mov ebx, [edx + dsGoodMatch]\r
+ 00000018  3B C3                       cmp eax, ebx\r
+ 0000001A  8B 42 34                    mov eax, [edx + dsWMask]\r
+ 0000001D  8B 5A 7C                    mov ebx, [edx + dsMaxChainLen]\r
+ 00000020  7C 03                       jl  LastMatchGood\r
+ 00000022  C1 EB 02                    shr ebx, 2\r
+ 00000025                      LastMatchGood:\r
+\r
+                               ;;; chainlen is decremented once beforehand so that the function can\r
+                               ;;; use the sign flag instead of the zero flag for the exit test.\r
+                               ;;; It is then shifted into the high word, to make room for the wmask\r
+                               ;;; value, which it will always accompany.\r
+\r
+ 00000025  4B                          dec ebx\r
+ 00000026  C1 E3 10                    shl ebx, 16\r
+ 00000029  0B D8                       or  ebx, eax\r
+ 0000002B  89 1C 24                    mov [chainlenwmask], ebx\r
+\r
+                               ;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;\r
+\r
+ 0000002E  8B 82 00000090              mov eax, [edx + dsNiceMatch]\r
+ 00000034  8B 5A 74                    mov ebx, [edx + dsLookahead]\r
+ 00000037  3B D8                       cmp ebx, eax\r
+ 00000039  7C 02                       jl  LookaheadLess\r
+ 0000003B  8B D8                       mov ebx, eax\r
+ 0000003D  89 5C 24 18         LookaheadLess:  mov [nicematch], ebx\r
+\r
+                               ;;; register Bytef *scan = s->window + s->strstart;\r
+\r
+ 00000041  8B 72 38                    mov esi, [edx + dsWindow]\r
+ 00000044  89 74 24 04                 mov [window], esi\r
+ 00000048  8B 6A 6C                    mov ebp, [edx + dsStrStart]\r
+ 0000004B  8D 7C 35 00                 lea edi, [esi + ebp]\r
+ 0000004F  89 7C 24 20                 mov [scan], edi\r
+\r
+                               ;;; Determine how many bytes the scan ptr is off from being\r
+                               ;;; dword-aligned.\r
+\r
+ 00000053  8B C7                       mov eax, edi\r
+ 00000055  F7 D8                       neg eax\r
+ 00000057  83 E0 03                    and eax, 3\r
+ 0000005A  89 44 24 14                 mov [scanalign], eax\r
+\r
+                               ;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ?\r
+                               ;;;     s->strstart - (IPos)MAX_DIST(s) : NIL;\r
+\r
+ 0000005E  8B 42 2C                    mov eax, [edx + dsWSize]\r
+ 00000061  2D 00000106                 sub eax, MIN_LOOKAHEAD\r
+ 00000066  2B E8                       sub ebp, eax\r
+ 00000068  7F 02                       jg  LimitPositive\r
+ 0000006A  33 ED                       xor ebp, ebp\r
+ 0000006C                      LimitPositive:\r
+\r
+                               ;;; int best_len = s->prev_length;\r
+\r
+ 0000006C  8B 42 78                    mov eax, [edx + dsPrevLen]\r
+ 0000006F  89 44 24 1C                 mov [bestlen], eax\r
+\r
+                               ;;; Store the sum of s->window + best_len in esi locally, and in esi.\r
+\r
+ 00000073  03 F0                       add esi, eax\r
+ 00000075  89 74 24 08                 mov [windowbestlen], esi\r
+\r
+                               ;;; register ush scan_start = *(ushf*)scan;\r
+                               ;;; register ush scan_end   = *(ushf*)(scan+best_len-1);\r
+                               ;;; Posf *prev = s->prev;\r
+\r
+ 00000079  0F B7 1F                    movzx   ebx, word ptr [edi]\r
+ 0000007C  89 5C 24 10                 mov [scanstart], ebx\r
+ 00000080  0F B7 5C 38 FF              movzx   ebx, word ptr [edi + eax - 1]\r
+ 00000085  89 5C 24 0C                 mov [scanend], ebx\r
+ 00000089  8B 7A 40                    mov edi, [edx + dsPrev]\r
+\r
+                               ;;; Jump into the main loop.\r
+\r
+ 0000008C  8B 14 24                    mov edx, [chainlenwmask]\r
+ 0000008F  EB 1D                       jmp short LoopEntry\r
+\r
+                               align 4\r
+\r
+                               ;;; do {\r
+                               ;;;     match = s->window + cur_match;\r
+                               ;;;     if (*(ushf*)(match+best_len-1) != scan_end ||\r
+                               ;;;         *(ushf*)match != scan_start) continue;\r
+                               ;;;     [...]\r
+                               ;;; } while ((cur_match = prev[cur_match & wmask]) > limit\r
+                               ;;;          && --chain_length != 0);\r
+                               ;;;\r
+                               ;;; Here is the inner loop of the function. The function will spend the\r
+                               ;;; majority of its time in this loop, and majority of that time will\r
+                               ;;; be spent in the first ten instructions.\r
+                               ;;;\r
+                               ;;; Within this loop:\r
+                               ;;; ebx = scanend\r
+                               ;;; ecx = curmatch\r
+                               ;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask)\r
+                               ;;; esi = windowbestlen - i.e., (window + bestlen)\r
+                               ;;; edi = prev\r
+                               ;;; ebp = limit\r
+\r
+ 00000094                      LookupLoop:\r
+ 00000094  23 CA                       and ecx, edx\r
+ 00000096  0F B7 0C 4F                 movzx   ecx, word ptr [edi + ecx*2]\r
+ 0000009A  3B CD                       cmp ecx, ebp\r
+ 0000009C  0F 86 000000E0              jbe LeaveNow\r
+ 000000A2  81 EA 00010000              sub edx, 00010000h\r
+ 000000A8  0F 88 000000D4              js  LeaveNow\r
+ 000000AE  0F B7 44 31 FF      LoopEntry:  movzx   eax, word ptr [esi + ecx - 1]\r
+ 000000B3  3B C3                       cmp eax, ebx\r
+ 000000B5  75 DD                       jnz LookupLoop\r
+ 000000B7  8B 44 24 04                 mov eax, [window]\r
+ 000000BB  0F B7 04 01                 movzx   eax, word ptr [eax + ecx]\r
+ 000000BF  3B 44 24 10                 cmp eax, [scanstart]\r
+ 000000C3  75 CF                       jnz LookupLoop\r
+\r
+                               ;;; Store the current value of chainlen.\r
+\r
+ 000000C5  89 14 24                    mov [chainlenwmask], edx\r
+\r
+                               ;;; Point edi to the string under scrutiny, and esi to the string we\r
+                               ;;; are hoping to match it up with. In actuality, esi and edi are\r
+                               ;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is\r
+                               ;;; initialized to -(MAX_MATCH_8 - scanalign).\r
+\r
+ 000000C8  8B 74 24 04                 mov esi, [window]\r
+ 000000CC  8B 7C 24 20                 mov edi, [scan]\r
+ 000000D0  03 F1                       add esi, ecx\r
+ 000000D2  8B 44 24 14                 mov eax, [scanalign]\r
+ 000000D6  BA FFFFFEF8                 mov edx, 0fffffef8h; -(MAX_MATCH_8)\r
+ 000000DB  8D BC 38                    lea edi, [edi + eax + 0108h] ;MAX_MATCH_8]\r
+          00000108\r
+ 000000E2  8D B4 30                    lea esi, [esi + eax + 0108h] ;MAX_MATCH_8]\r
+          00000108\r
+\r
+                               ;;; Test the strings for equality, 8 bytes at a time. At the end,\r
+                               ;;; adjust edx so that it is offset to the exact byte that mismatched.\r
+                               ;;;\r
+                               ;;; We already know at this point that the first three bytes of the\r
+                               ;;; strings match each other, and they can be safely passed over before\r
+                               ;;; starting the compare loop. So what this code does is skip over 0-3\r
+                               ;;; bytes, as much as necessary in order to dword-align the edi\r
+                               ;;; pointer. (esi will still be misaligned three times out of four.)\r
+                               ;;;\r
+                               ;;; It should be confessed that this loop usually does not represent\r
+                               ;;; much of the total running time. Replacing it with a more\r
+                               ;;; straightforward "rep cmpsb" would not drastically degrade\r
+                               ;;; performance.\r
+\r
+ 000000E9                      LoopCmps:\r
+ 000000E9  8B 04 32                    mov eax, [esi + edx]\r
+ 000000EC  33 04 3A                    xor eax, [edi + edx]\r
+ 000000EF  75 14                       jnz LeaveLoopCmps\r
+ 000000F1  8B 44 32 04                 mov eax, [esi + edx + 4]\r
+ 000000F5  33 44 3A 04                 xor eax, [edi + edx + 4]\r
+ 000000F9  75 07                       jnz LeaveLoopCmps4\r
+ 000000FB  83 C2 08                    add edx, 8\r
+ 000000FE  75 E9                       jnz LoopCmps\r
+ 00000100  EB 71                       jmp short LenMaximum\r
+ 00000102  83 C2 04            LeaveLoopCmps4: add edx, 4\r
+ 00000105  A9 0000FFFF         LeaveLoopCmps:  test    eax, 0000FFFFh\r
+ 0000010A  75 06                       jnz LenLower\r
+ 0000010C  83 C2 02                    add edx,  2\r
+ 0000010F  C1 E8 10                    shr eax, 16\r
+ 00000112  2C 01               LenLower:   sub al, 1\r
+ 00000114  83 D2 00                    adc edx, 0\r
+\r
+                               ;;; Calculate the length of the match. If it is longer than MAX_MATCH,\r
+                               ;;; then automatically accept it as the best possible match and leave.\r
+\r
+ 00000117  8D 04 3A                    lea eax, [edi + edx]\r
+ 0000011A  8B 7C 24 20                 mov edi, [scan]\r
+ 0000011E  2B C7                       sub eax, edi\r
+ 00000120  3D 00000102                 cmp eax, MAX_MATCH\r
+ 00000125  7D 4C                       jge LenMaximum\r
+\r
+                               ;;; If the length of the match is not longer than the best match we\r
+                               ;;; have so far, then forget it and return to the lookup loop.\r
+\r
+ 00000127  8B 54 24 38                 mov edx, [deflatestate]\r
+ 0000012B  8B 5C 24 1C                 mov ebx, [bestlen]\r
+ 0000012F  3B C3                       cmp eax, ebx\r
+ 00000131  7F 13                       jg  LongerMatch\r
+ 00000133  8B 74 24 08                 mov esi, [windowbestlen]\r
+ 00000137  8B 7A 40                    mov edi, [edx + dsPrev]\r
+ 0000013A  8B 5C 24 0C                 mov ebx, [scanend]\r
+ 0000013E  8B 14 24                    mov edx, [chainlenwmask]\r
+ 00000141  E9 FFFFFF4E                 jmp LookupLoop\r
+\r
+                               ;;;         s->match_start = cur_match;\r
+                               ;;;         best_len = len;\r
+                               ;;;         if (len >= nice_match) break;\r
+                               ;;;         scan_end = *(ushf*)(scan+best_len-1);\r
+\r
+ 00000146  8B 5C 24 18         LongerMatch:    mov ebx, [nicematch]\r
+ 0000014A  89 44 24 1C                 mov [bestlen], eax\r
+ 0000014E  89 4A 70                    mov [edx + dsMatchStart], ecx\r
+ 00000151  3B C3                       cmp eax, ebx\r
+ 00000153  7D 2D                       jge LeaveNow\r
+ 00000155  8B 74 24 04                 mov esi, [window]\r
+ 00000159  03 F0                       add esi, eax\r
+ 0000015B  89 74 24 08                 mov [windowbestlen], esi\r
+ 0000015F  0F B7 5C 38 FF              movzx   ebx, word ptr [edi + eax - 1]\r
+ 00000164  8B 7A 40                    mov edi, [edx + dsPrev]\r
+ 00000167  89 5C 24 0C                 mov [scanend], ebx\r
+ 0000016B  8B 14 24                    mov edx, [chainlenwmask]\r
+ 0000016E  E9 FFFFFF21                 jmp LookupLoop\r
+\r
+                               ;;; Accept the current string, with the maximum possible length.\r
+\r
+ 00000173  8B 54 24 38         LenMaximum: mov edx, [deflatestate]\r
+ 00000177  C7 44 24 1C                 mov dword ptr [bestlen], MAX_MATCH\r
+          00000102\r
+ 0000017F  89 4A 70                    mov [edx + dsMatchStart], ecx\r
+\r
+                               ;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len;\r
+                               ;;; return s->lookahead;\r
+\r
+ 00000182                      LeaveNow:\r
+ 00000182  8B 54 24 38                 mov edx, [deflatestate]\r
+ 00000186  8B 5C 24 1C                 mov ebx, [bestlen]\r
+ 0000018A  8B 42 74                    mov eax, [edx + dsLookahead]\r
+ 0000018D  3B D8                       cmp ebx, eax\r
+ 0000018F  7F 02                       jg  LookaheadRet\r
+ 00000191  8B C3                       mov eax, ebx\r
+ 00000193                      LookaheadRet:\r
+\r
+                               ;;; Restore the stack and return from whence we came.\r
+\r
+ 00000193  83 C4 24                    add esp, LocalVarsSize\r
+ 00000196  5B                          pop ebx\r
+ 00000197  5E                          pop esi\r
+ 00000198  5F                          pop edi\r
+ 00000199  5D                          pop ebp\r
+\r
+ 0000019A  C3                          ret\r
+                               ; please don't remove this string !\r
+                               ; Your can freely use match686 in any free or commercial app if you don't remove the string in the binary!\r
+ 0000019B  0D 0A 61 73 6D          db     0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998",0dh,0ah\r
+          36 38 36 20 77\r
+          69 74 68 20 6D\r
+          61 73 6D 2C 20\r
+          6F 70 74 69 6D\r
+          69 73 65 64 20\r
+          61 73 73 65 6D\r
+          62 6C 79 20 63\r
+          6F 64 65 20 66\r
+          72 6F 6D 20 42\r
+          72 69 61 6E 20\r
+          52 61 69 74 65\r
+          72 2C 20 77 72\r
+          69 74 74 65 6E\r
+          20 31 39 39 38\r
+          0D 0A\r
+\r
+\r
+                                   IFDEF NOUNDERLINE\r
+                                   ELSE\r
+ 000001E8                          _longest_match      endp\r
+                                   ENDIF\r
+\r
+                                   IFDEF NOUNDERLINE\r
+                                   ELSE\r
+ 000001E8                          _match_init     proc near\r
+ 000001E8  C3                                      ret\r
+ 000001E9                          _match_init     endp\r
+                                   ENDIF\r
+\r
+\r
+ 000001E9                      _TEXT   ends\r
+                               end\r
+\fMicrosoft (R) Macro Assembler Version 10.00.30319.01      04/13/12 13:33:40\r
+match686.asm                                                Symbols 2 - 1\r
+\r
+\r
+\r
+\r
+Segments and Groups:\r
+\r
+                N a m e                 Size     Length   Align   Combine Class\r
+\r
+FLAT . . . . . . . . . . . . . .       GROUP\r
+_DATA  . . . . . . . . . . . . .       32 Bit   00000000 Para    Public  'DATA'        \r
+_TEXT  . . . . . . . . . . . . .       32 Bit   000001E9 Para    Public  'CODE'        \r
+\r
+\r
+Procedures, parameters, and locals:\r
+\r
+                N a m e                 Type     Value    Attr\r
+\r
+_longest_match . . . . . . . . .       P Near   00000000 _TEXT Length= 000001E8 Public\r
+  LastMatchGood  . . . . . . . .       L Near   00000025 _TEXT \r
+  LookaheadLess  . . . . . . . .       L Near   0000003D _TEXT \r
+  LimitPositive  . . . . . . . .       L Near   0000006C _TEXT \r
+  LookupLoop . . . . . . . . . .       L Near   00000094 _TEXT \r
+  LoopEntry  . . . . . . . . . .       L Near   000000AE _TEXT \r
+  LoopCmps . . . . . . . . . . .       L Near   000000E9 _TEXT \r
+  LeaveLoopCmps4 . . . . . . . .       L Near   00000102 _TEXT \r
+  LeaveLoopCmps  . . . . . . . .       L Near   00000105 _TEXT \r
+  LenLower . . . . . . . . . . .       L Near   00000112 _TEXT \r
+  LongerMatch  . . . . . . . . .       L Near   00000146 _TEXT \r
+  LenMaximum . . . . . . . . . .       L Near   00000173 _TEXT \r
+  LeaveNow . . . . . . . . . . .       L Near   00000182 _TEXT \r
+  LookaheadRet . . . . . . . . .       L Near   00000193 _TEXT \r
+_match_init  . . . . . . . . . .       P Near   000001E8 _TEXT Length= 00000001 Public\r
+\r
+\r
+Symbols:\r
+\r
+                N a m e                 Type     Value    Attr\r
+\r
+@CodeSize  . . . . . . . . . . .       Number   00000000h   \r
+@DataSize  . . . . . . . . . . .       Number   00000000h   \r
+@Interface . . . . . . . . . . .       Number   00000000h   \r
+@Model . . . . . . . . . . . . .       Number   00000007h   \r
+@code  . . . . . . . . . . . . .       Text     _TEXT\r
+@data  . . . . . . . . . . . . .       Text     FLAT\r
+@fardata?  . . . . . . . . . . .       Text     FLAT\r
+@fardata . . . . . . . . . . . .       Text     FLAT\r
+@stack . . . . . . . . . . . . .       Text     FLAT\r
+LocalVarsSize  . . . . . . . . .       Number   00000024h   \r
+MAX_MATCH_8_ . . . . . . . . . .       Number   00000100h   \r
+MAX_MATCH  . . . . . . . . . . .       Number   00000102h   \r
+MIN_LOOKAHEAD  . . . . . . . . .       Number   00000106h   \r
+MIN_MATCH  . . . . . . . . . . .       Number   00000003h   \r
+NbStackAdd . . . . . . . . . . .       Number   00000034h   \r
+NbStack  . . . . . . . . . . . .       Number   0000004Ch   \r
+adrret . . . . . . . . . . . . .       Text     dword ptr[esp+NbStack-8]\r
+best_len . . . . . . . . . . . .       Text     dword ptr [esp+NbStack-36]\r
+bestlen  . . . . . . . . . . . .       Text     esp + 28\r
+chain_length . . . . . . . . . .       Text     dword ptr [esp+NbStack-28]\r
+chainlenwmask  . . . . . . . . .       Text     esp + 0\r
+cur_match  . . . . . . . . . . .       Text     dword ptr[esp+NbStack-0]\r
+curmatch . . . . . . . . . . . .       Text     esp + 60\r
+deflatestate . . . . . . . . . .       Text     esp + 56\r
+dep_chain_length . . . . . . . .       Number   0000007Ch   \r
+dep_good_match . . . . . . . . .       Number   0000008Ch   \r
+dep_lookahead  . . . . . . . . .       Number   00000074h   \r
+dep_match_start  . . . . . . . .       Number   00000070h   \r
+dep_nice_match . . . . . . . . .       Number   00000090h   \r
+dep_prev_length  . . . . . . . .       Number   00000078h   \r
+dep_prev . . . . . . . . . . . .       Number   00000040h   \r
+dep_strstart . . . . . . . . . .       Number   0000006Ch   \r
+dep_w_mask . . . . . . . . . . .       Number   00000034h   \r
+dep_w_size . . . . . . . . . . .       Number   0000002Ch   \r
+dep_window . . . . . . . . . . .       Number   00000038h   \r
+dsGoodMatch  . . . . . . . . . .       Number   0000008Ch   \r
+dsLookahead  . . . . . . . . . .       Number   00000074h   \r
+dsMatchLen . . . . . . . . . . .       Number   00000060h   \r
+dsMatchStart . . . . . . . . . .       Number   00000070h   \r
+dsMaxChainLen  . . . . . . . . .       Number   0000007Ch   \r
+dsNiceMatch  . . . . . . . . . .       Number   00000090h   \r
+dsPrevLen  . . . . . . . . . . .       Number   00000078h   \r
+dsPrevMatch  . . . . . . . . . .       Number   00000064h   \r
+dsPrev . . . . . . . . . . . . .       Number   00000040h   \r
+dsStrStart . . . . . . . . . . .       Number   0000006Ch   \r
+dsWMask  . . . . . . . . . . . .       Number   00000034h   \r
+dsWSize  . . . . . . . . . . . .       Number   0000002Ch   \r
+dsWindow . . . . . . . . . . . .       Number   00000038h   \r
+limit  . . . . . . . . . . . . .       Text     dword ptr [esp+NbStack-32]\r
+match_start_ptr  . . . . . . . .       Text     dword ptr [esp+NbStack-56]\r
+match_start  . . . . . . . . . .       Text     dword ptr [esp+NbStack-72]\r
+nice_match . . . . . . . . . . .       Text     dword ptr [esp+NbStack-60]\r
+nicematch  . . . . . . . . . . .       Text     esp + 24\r
+prev . . . . . . . . . . . . . .       Text     dword ptr [esp+NbStack-44]\r
+pushebp  . . . . . . . . . . . .       Text     dword ptr[esp+NbStack-12]\r
+pushebx  . . . . . . . . . . . .       Text     dword ptr[esp+NbStack-24]\r
+pushedi  . . . . . . . . . . . .       Text     dword ptr[esp+NbStack-16]\r
+pushesi  . . . . . . . . . . . .       Text     dword ptr[esp+NbStack-20]\r
+scan_start . . . . . . . . . . .       Text     word ptr [esp+NbStack-48]\r
+scanalign  . . . . . . . . . . .       Text     esp + 20\r
+scanend  . . . . . . . . . . . .       Text     esp + 12\r
+scanstart  . . . . . . . . . . .       Text     esp + 16\r
+scan . . . . . . . . . . . . . .       Text     esp + 32\r
+str_s  . . . . . . . . . . . . .       Text     dword ptr[esp+NbStack-4]\r
+strend . . . . . . . . . . . . .       Text     dword ptr [esp+NbStack-76]\r
+windowbestlen  . . . . . . . . .       Text     esp + 8\r
+windowlen  . . . . . . . . . . .       Text     dword ptr [esp+NbStack-68]\r
+window . . . . . . . . . . . . .       Text     esp + 4\r
+wmask  . . . . . . . . . . . . .       Text     dword ptr [esp+NbStack-52]\r
+zlib1222add  . . . . . . . . . .       Number   00000008h   \r
+\r
+          0 Warnings\r
+          0 Errors\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/masmx86/readme.txt
new file mode 100644 (file)
index 0000000..3271f72
--- /dev/null
@@ -0,0 +1,27 @@
+\r
+Summary\r
+-------\r
+This directory contains ASM implementations of the functions\r
+longest_match() and inflate_fast().\r
+\r
+\r
+Use instructions\r
+----------------\r
+Assemble using MASM, and copy the object files into the zlib source\r
+directory, then run the appropriate makefile, as suggested below.  You can\r
+donwload MASM from here:\r
+\r
+    http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64\r
+\r
+You can also get objects files here:\r
+\r
+    http://www.winimage.com/zLibDll/zlib124_masm_obj.zip\r
+\r
+Build instructions\r
+------------------\r
+* With Microsoft C and MASM:\r
+nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj"\r
+\r
+* With Borland C and TASM:\r
+make -f win32/Makefile.bor LOCAL_ZLIB="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" OBJPA="+match686c.obj+match686.obj+inffas32.obj"\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/Makefile b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/Makefile
new file mode 100644 (file)
index 0000000..84eaad2
--- /dev/null
@@ -0,0 +1,25 @@
+CC=cc
+CFLAGS=-O -I../..
+
+UNZ_OBJS = miniunz.o unzip.o ioapi.o ../../libz.a
+ZIP_OBJS = minizip.o zip.o   ioapi.o ../../libz.a
+
+.c.o:
+       $(CC) -c $(CFLAGS) $*.c
+
+all: miniunz minizip
+
+miniunz:  $(UNZ_OBJS)
+       $(CC) $(CFLAGS) -o $@ $(UNZ_OBJS)
+
+minizip:  $(ZIP_OBJS)
+       $(CC) $(CFLAGS) -o $@ $(ZIP_OBJS)
+
+test:  miniunz minizip
+       ./minizip test readme.txt
+       ./miniunz -l test.zip
+       mv readme.txt readme.old
+       ./miniunz test.zip
+
+clean:
+       /bin/rm -f *.o *~ minizip miniunz
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/Makefile.am b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/Makefile.am
new file mode 100644 (file)
index 0000000..2ced913
--- /dev/null
@@ -0,0 +1,38 @@
+lib_LTLIBRARIES = libminizip.la
+
+if COND_DEMOS
+bin_PROGRAMS = miniunzip minizip
+endif
+
+zlib_top_srcdir = $(top_srcdir)/../..
+zlib_top_builddir = $(top_builddir)/../..
+
+AM_CPPFLAGS = -I$(zlib_top_srcdir)
+AM_LDFLAGS = -L$(zlib_top_builddir)
+
+libminizip_la_SOURCES = \
+       ioapi.c \
+       mztools.c \
+       unzip.c \
+       zip.c
+
+libminizip_la_LDFLAGS = $(AM_LDFLAGS) -version-info 1:0:0 -lz
+
+minizip_includedir = $(includedir)/minizip
+minizip_include_HEADERS = \
+       crypt.h \
+       ioapi.h \
+       mztools.h \
+       unzip.h \
+       zip.h
+
+pkgconfigdir = $(libdir)/pkgconfig
+pkgconfig_DATA = minizip.pc
+
+EXTRA_PROGRAMS = miniunzip minizip
+
+miniunzip_SOURCES = miniunz.c
+miniunzip_LDADD = libminizip.la
+
+minizip_SOURCES = minizip.c
+minizip_LDADD = libminizip.la -lz
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/MiniZip64_Changes.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/MiniZip64_Changes.txt
new file mode 100644 (file)
index 0000000..13a1bd9
--- /dev/null
@@ -0,0 +1,6 @@
+
+MiniZip 1.1 was derrived from MiniZip at version 1.01f
+
+Change in 1.0 (Okt 2009)
+ - **TODO - Add history**
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/MiniZip64_info.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/MiniZip64_info.txt
new file mode 100644 (file)
index 0000000..57d7152
--- /dev/null
@@ -0,0 +1,74 @@
+MiniZip - Copyright (c) 1998-2010 - by Gilles Vollant - version 1.1 64 bits from Mathias Svensson
+
+Introduction
+---------------------
+MiniZip 1.1 is built from MiniZip 1.0 by Gilles Vollant ( http://www.winimage.com/zLibDll/minizip.html )
+
+When adding ZIP64 support into minizip it would result into risk of breaking compatibility with minizip 1.0.
+All possible work was done for compatibility.
+
+
+Background
+---------------------
+When adding ZIP64 support Mathias Svensson found that Even Rouault have added ZIP64 
+support for unzip.c into minizip for a open source project called gdal ( http://www.gdal.org/ )
+
+That was used as a starting point. And after that ZIP64 support was added to zip.c
+some refactoring and code cleanup was also done.
+
+
+Changed from MiniZip 1.0 to MiniZip 1.1
+---------------------------------------
+* Added ZIP64 support for unzip ( by Even Rouault )
+* Added ZIP64 support for zip ( by Mathias Svensson )
+* Reverted some changed that Even Rouault did.
+* Bunch of patches received from Gulles Vollant that he received for MiniZip from various users.
+* Added unzip patch for BZIP Compression method (patch create by Daniel Borca)
+* Added BZIP Compress method for zip
+* Did some refactoring and code cleanup
+
+
+Credits
+
+ Gilles Vollant    - Original MiniZip author
+ Even Rouault      - ZIP64 unzip Support
+ Daniel Borca      - BZip Compression method support in unzip
+ Mathias Svensson  - ZIP64 zip support
+ Mathias Svensson  - BZip Compression method support in zip
+
+ Resources
+
+ ZipLayout   http://result42.com/projects/ZipFileLayout
+             Command line tool for Windows that shows the layout and information of the headers in a zip archive.
+             Used when debugging and validating the creation of zip files using MiniZip64
+
+
+ ZIP App Note  http://www.pkware.com/documents/casestudies/APPNOTE.TXT
+               Zip File specification
+
+
+Notes.
+ * To be able to use BZip compression method in zip64.c or unzip64.c the BZIP2 lib is needed and HAVE_BZIP2 need to be defined.
+
+License
+----------------------------------------------------------
+   Condition of use and distribution are the same than zlib :
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+----------------------------------------------------------
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/configure.ac b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/configure.ac
new file mode 100644 (file)
index 0000000..53adbb8
--- /dev/null
@@ -0,0 +1,22 @@
+#                                               -*- Autoconf -*-
+# Process this file with autoconf to produce a configure script.
+
+AC_INIT([minizip], [1.2.6], [bugzilla.redhat.com])
+AC_CONFIG_SRCDIR([minizip.c])
+AM_INIT_AUTOMAKE([foreign])
+LT_INIT
+
+AC_MSG_CHECKING([whether to build example programs])
+AC_ARG_ENABLE([demos], AC_HELP_STRING([--enable-demos], [build example programs]))
+AM_CONDITIONAL([COND_DEMOS], [test "$enable_demos" = yes])
+if test "$enable_demos" = yes
+then
+       AC_MSG_RESULT([yes])
+else
+       AC_MSG_RESULT([no])
+fi
+
+AC_SUBST([HAVE_UNISTD_H], [0])
+AC_CHECK_HEADER([unistd.h], [HAVE_UNISTD_H=1], [])
+AC_CONFIG_FILES([Makefile minizip.pc])
+AC_OUTPUT
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/crypt.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/crypt.h
new file mode 100644 (file)
index 0000000..a01d08d
--- /dev/null
@@ -0,0 +1,131 @@
+/* crypt.h -- base code for crypt/uncrypt ZIPfile
+
+
+   Version 1.01e, February 12th, 2005
+
+   Copyright (C) 1998-2005 Gilles Vollant
+
+   This code is a modified version of crypting code in Infozip distribution
+
+   The encryption/decryption parts of this source code (as opposed to the
+   non-echoing password parts) were originally written in Europe.  The
+   whole source package can be freely distributed, including from the USA.
+   (Prior to January 2000, re-export from the US was a violation of US law.)
+
+   This encryption code is a direct transcription of the algorithm from
+   Roger Schlafly, described by Phil Katz in the file appnote.txt.  This
+   file (appnote.txt) is distributed with the PKZIP program (even in the
+   version without encryption capabilities).
+
+   If you don't need crypting in your application, just define symbols
+   NOCRYPT and NOUNCRYPT.
+
+   This code support the "Traditional PKWARE Encryption".
+
+   The new AES encryption added on Zip format by Winzip (see the page
+   http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
+   Encryption is not supported.
+*/
+
+#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
+
+/***********************************************************************
+ * Return the next byte in the pseudo-random sequence
+ */
+static int decrypt_byte(unsigned long* pkeys, const unsigned long* pcrc_32_tab)
+{
+    unsigned temp;  /* POTENTIAL BUG:  temp*(temp^1) may overflow in an
+                     * unpredictable manner on 16-bit systems; not a problem
+                     * with any known compiler so far, though */
+
+    temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
+    return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
+}
+
+/***********************************************************************
+ * Update the encryption keys with the next byte of plain text
+ */
+static int update_keys(unsigned long* pkeys,const unsigned long* pcrc_32_tab,int c)
+{
+    (*(pkeys+0)) = CRC32((*(pkeys+0)), c);
+    (*(pkeys+1)) += (*(pkeys+0)) & 0xff;
+    (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
+    {
+      register int keyshift = (int)((*(pkeys+1)) >> 24);
+      (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift);
+    }
+    return c;
+}
+
+
+/***********************************************************************
+ * Initialize the encryption keys and the random header according to
+ * the given password.
+ */
+static void init_keys(const char* passwd,unsigned long* pkeys,const unsigned long* pcrc_32_tab)
+{
+    *(pkeys+0) = 305419896L;
+    *(pkeys+1) = 591751049L;
+    *(pkeys+2) = 878082192L;
+    while (*passwd != '\0') {
+        update_keys(pkeys,pcrc_32_tab,(int)*passwd);
+        passwd++;
+    }
+}
+
+#define zdecode(pkeys,pcrc_32_tab,c) \
+    (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab)))
+
+#define zencode(pkeys,pcrc_32_tab,c,t) \
+    (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c))
+
+#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED
+
+#define RAND_HEAD_LEN  12
+   /* "last resort" source for second part of crypt seed pattern */
+#  ifndef ZCR_SEED2
+#    define ZCR_SEED2 3141592654UL     /* use PI as default pattern */
+#  endif
+
+static int crypthead(const char* passwd,      /* password string */
+                     unsigned char* buf,      /* where to write header */
+                     int bufSize,
+                     unsigned long* pkeys,
+                     const unsigned long* pcrc_32_tab,
+                     unsigned long crcForCrypting)
+{
+    int n;                       /* index in random header */
+    int t;                       /* temporary */
+    int c;                       /* random byte */
+    unsigned char header[RAND_HEAD_LEN-2]; /* random header */
+    static unsigned calls = 0;   /* ensure different random header each time */
+
+    if (bufSize<RAND_HEAD_LEN)
+      return 0;
+
+    /* First generate RAND_HEAD_LEN-2 random bytes. We encrypt the
+     * output of rand() to get less predictability, since rand() is
+     * often poorly implemented.
+     */
+    if (++calls == 1)
+    {
+        srand((unsigned)(time(NULL) ^ ZCR_SEED2));
+    }
+    init_keys(passwd, pkeys, pcrc_32_tab);
+    for (n = 0; n < RAND_HEAD_LEN-2; n++)
+    {
+        c = (rand() >> 7) & 0xff;
+        header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t);
+    }
+    /* Encrypt random header (last two bytes is high word of crc) */
+    init_keys(passwd, pkeys, pcrc_32_tab);
+    for (n = 0; n < RAND_HEAD_LEN-2; n++)
+    {
+        buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
+    }
+    buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t);
+    buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t);
+    return n;
+}
+
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/fmuExtract.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/fmuExtract.h
new file mode 100644 (file)
index 0000000..9a6fac9
--- /dev/null
@@ -0,0 +1,28 @@
+/* ------------------------------------------------------------------------- \r
+ * Function for extracting FMU files\r
+ * Author: Teemu Lempinen\r
+ * Copyright 2012 Semantum Oy\r
+ * -------------------------------------------------------------------------*/ \r
+\r
+#ifndef fmuExtract_h\r
+#define fmuExtract_h\r
+\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#ifdef EXTRACT_DLL \r
+   #define EXTRACT_API __declspec(dllexport) \r
+#else \r
+   #define EXTRACT_API  __declspec(dllimport) \r
+#endif \r
+\r
+EXTRACT_API int unzipFMU(const char *zipFileName, const char*outPath);\r
+EXTRACT_API int makedir(char *newdir);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif // fmuExtract_h\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/ioapi.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/ioapi.c
new file mode 100644 (file)
index 0000000..7f5c191
--- /dev/null
@@ -0,0 +1,247 @@
+/* ioapi.h -- IO base function header for compress/uncompress .zip
+   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications for Zip64 support
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+         For more info read MiniZip_info.txt
+
+*/
+
+#if defined(_WIN32) && (!(defined(_CRT_SECURE_NO_WARNINGS)))
+        #define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#if defined(__APPLE__) || defined(IOAPI_NO_64)
+// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
+#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
+#define FTELLO_FUNC(stream) ftello(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
+#else
+#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
+#define FTELLO_FUNC(stream) ftello64(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
+#endif
+
+
+#include "ioapi.h"
+
+voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)
+{
+    if (pfilefunc->zfile_func64.zopen64_file != NULL)
+        return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode);
+    else
+    {
+        return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode);
+    }
+}
+
+long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)
+{
+    if (pfilefunc->zfile_func64.zseek64_file != NULL)
+        return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin);
+    else
+    {
+        uLong offsetTruncated = (uLong)offset;
+        if (offsetTruncated != offset)
+            return -1;
+        else
+            return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin);
+    }
+}
+
+ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)
+{
+    if (pfilefunc->zfile_func64.zseek64_file != NULL)
+        return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream);
+    else
+    {
+        uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream);
+        if ((tell_uLong) == MAXU32)
+            return (ZPOS64_T)-1;
+        else
+            return tell_uLong;
+    }
+}
+
+void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32)
+{
+    p_filefunc64_32->zfile_func64.zopen64_file = NULL;
+    p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file;
+    p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
+    p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file;
+    p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file;
+    p_filefunc64_32->zfile_func64.ztell64_file = NULL;
+    p_filefunc64_32->zfile_func64.zseek64_file = NULL;
+    p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file;
+    p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
+    p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque;
+    p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file;
+    p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file;
+}
+
+
+
+static voidpf  ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode));
+static uLong   ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
+static uLong   ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size));
+static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream));
+static long    ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
+static int     ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream));
+static int     ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream));
+
+static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
+{
+    FILE* file = NULL;
+    const char* mode_fopen = NULL;
+    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
+        mode_fopen = "rb";
+    else
+    if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
+        mode_fopen = "r+b";
+    else
+    if (mode & ZLIB_FILEFUNC_MODE_CREATE)
+        mode_fopen = "wb";
+
+    if ((filename!=NULL) && (mode_fopen != NULL))
+        file = fopen(filename, mode_fopen);
+    return file;
+}
+
+static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode)
+{
+    FILE* file = NULL;
+    const char* mode_fopen = NULL;
+    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
+        mode_fopen = "rb";
+    else
+    if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
+        mode_fopen = "r+b";
+    else
+    if (mode & ZLIB_FILEFUNC_MODE_CREATE)
+        mode_fopen = "wb";
+
+    if ((filename!=NULL) && (mode_fopen != NULL))
+        file = FOPEN_FUNC((const char*)filename, mode_fopen);
+    return file;
+}
+
+
+static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size)
+{
+    uLong ret;
+    ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
+    return ret;
+}
+
+static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size)
+{
+    uLong ret;
+    ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
+    return ret;
+}
+
+static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
+{
+    long ret;
+    ret = ftell((FILE *)stream);
+    return ret;
+}
+
+
+static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream)
+{
+    ZPOS64_T ret;
+    ret = FTELLO_FUNC((FILE *)stream);
+    return ret;
+}
+
+static long ZCALLBACK fseek_file_func (voidpf  opaque, voidpf stream, uLong offset, int origin)
+{
+    int fseek_origin=0;
+    long ret;
+    switch (origin)
+    {
+    case ZLIB_FILEFUNC_SEEK_CUR :
+        fseek_origin = SEEK_CUR;
+        break;
+    case ZLIB_FILEFUNC_SEEK_END :
+        fseek_origin = SEEK_END;
+        break;
+    case ZLIB_FILEFUNC_SEEK_SET :
+        fseek_origin = SEEK_SET;
+        break;
+    default: return -1;
+    }
+    ret = 0;
+    if (fseek((FILE *)stream, offset, fseek_origin) != 0)
+        ret = -1;
+    return ret;
+}
+
+static long ZCALLBACK fseek64_file_func (voidpf  opaque, voidpf stream, ZPOS64_T offset, int origin)
+{
+    int fseek_origin=0;
+    long ret;
+    switch (origin)
+    {
+    case ZLIB_FILEFUNC_SEEK_CUR :
+        fseek_origin = SEEK_CUR;
+        break;
+    case ZLIB_FILEFUNC_SEEK_END :
+        fseek_origin = SEEK_END;
+        break;
+    case ZLIB_FILEFUNC_SEEK_SET :
+        fseek_origin = SEEK_SET;
+        break;
+    default: return -1;
+    }
+    ret = 0;
+
+    if(FSEEKO_FUNC((FILE *)stream, offset, fseek_origin) != 0)
+                        ret = -1;
+
+    return ret;
+}
+
+
+static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
+{
+    int ret;
+    ret = fclose((FILE *)stream);
+    return ret;
+}
+
+static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream)
+{
+    int ret;
+    ret = ferror((FILE *)stream);
+    return ret;
+}
+
+void fill_fopen_filefunc (pzlib_filefunc_def)
+  zlib_filefunc_def* pzlib_filefunc_def;
+{
+    pzlib_filefunc_def->zopen_file = fopen_file_func;
+    pzlib_filefunc_def->zread_file = fread_file_func;
+    pzlib_filefunc_def->zwrite_file = fwrite_file_func;
+    pzlib_filefunc_def->ztell_file = ftell_file_func;
+    pzlib_filefunc_def->zseek_file = fseek_file_func;
+    pzlib_filefunc_def->zclose_file = fclose_file_func;
+    pzlib_filefunc_def->zerror_file = ferror_file_func;
+    pzlib_filefunc_def->opaque = NULL;
+}
+
+void fill_fopen64_filefunc (zlib_filefunc64_def*  pzlib_filefunc_def)
+{
+    pzlib_filefunc_def->zopen64_file = fopen64_file_func;
+    pzlib_filefunc_def->zread_file = fread_file_func;
+    pzlib_filefunc_def->zwrite_file = fwrite_file_func;
+    pzlib_filefunc_def->ztell64_file = ftell64_file_func;
+    pzlib_filefunc_def->zseek64_file = fseek64_file_func;
+    pzlib_filefunc_def->zclose_file = fclose_file_func;
+    pzlib_filefunc_def->zerror_file = ferror_file_func;
+    pzlib_filefunc_def->opaque = NULL;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/ioapi.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/ioapi.h
new file mode 100644 (file)
index 0000000..8dcbdb0
--- /dev/null
@@ -0,0 +1,208 @@
+/* ioapi.h -- IO base function header for compress/uncompress .zip
+   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications for Zip64 support
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+         For more info read MiniZip_info.txt
+
+         Changes
+
+    Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this)
+    Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
+               More if/def section may be needed to support other platforms
+    Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
+                          (but you should use iowin32.c for windows instead)
+
+*/
+
+#ifndef _ZLIBIOAPI64_H
+#define _ZLIBIOAPI64_H
+
+#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
+
+  // Linux needs this to support file operation on files larger then 4+GB
+  // But might need better if/def to select just the platforms that needs them.
+
+        #ifndef __USE_FILE_OFFSET64
+                #define __USE_FILE_OFFSET64
+        #endif
+        #ifndef __USE_LARGEFILE64
+                #define __USE_LARGEFILE64
+        #endif
+        #ifndef _LARGEFILE64_SOURCE
+                #define _LARGEFILE64_SOURCE
+        #endif
+        #ifndef _FILE_OFFSET_BIT
+                #define _FILE_OFFSET_BIT 64
+        #endif
+
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "zlib.h"
+
+#if defined(USE_FILE32API)
+#define fopen64 fopen
+#define ftello64 ftell
+#define fseeko64 fseek
+#else
+#ifdef __FreeBSD__
+#define fopen64 fopen
+#define ftello64 ftello
+#define fseeko64 fseeko
+#endif
+#ifdef _MSC_VER
+ #define fopen64 fopen
+ #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
+  #define ftello64 _ftelli64
+  #define fseeko64 _fseeki64
+ #else // old MSC
+  #define ftello64 ftell
+  #define fseeko64 fseek
+ #endif
+#endif
+#endif
+
+/*
+#ifndef ZPOS64_T
+  #ifdef _WIN32
+                #define ZPOS64_T fpos_t
+  #else
+    #include <stdint.h>
+    #define ZPOS64_T uint64_t
+  #endif
+#endif
+*/
+
+#ifdef HAVE_MINIZIP64_CONF_H
+#include "mz64conf.h"
+#endif
+
+/* a type choosen by DEFINE */
+#ifdef HAVE_64BIT_INT_CUSTOM
+typedef  64BIT_INT_CUSTOM_TYPE ZPOS64_T;
+#else
+#ifdef HAS_STDINT_H
+#include "stdint.h"
+typedef uint64_t ZPOS64_T;
+#else
+
+/* Maximum unsigned 32-bit value used as placeholder for zip64 */
+#define MAXU32 0xffffffff
+
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+typedef unsigned __int64 ZPOS64_T;
+#else
+typedef unsigned long long int ZPOS64_T;
+#endif
+#endif
+#endif
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#define ZLIB_FILEFUNC_SEEK_CUR (1)
+#define ZLIB_FILEFUNC_SEEK_END (2)
+#define ZLIB_FILEFUNC_SEEK_SET (0)
+
+#define ZLIB_FILEFUNC_MODE_READ      (1)
+#define ZLIB_FILEFUNC_MODE_WRITE     (2)
+#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
+
+#define ZLIB_FILEFUNC_MODE_EXISTING (4)
+#define ZLIB_FILEFUNC_MODE_CREATE   (8)
+
+
+#ifndef ZCALLBACK
+ #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
+   #define ZCALLBACK CALLBACK
+ #else
+   #define ZCALLBACK
+ #endif
+#endif
+
+
+
+
+typedef voidpf   (ZCALLBACK *open_file_func)      OF((voidpf opaque, const char* filename, int mode));
+typedef uLong    (ZCALLBACK *read_file_func)      OF((voidpf opaque, voidpf stream, void* buf, uLong size));
+typedef uLong    (ZCALLBACK *write_file_func)     OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
+typedef int      (ZCALLBACK *close_file_func)     OF((voidpf opaque, voidpf stream));
+typedef int      (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
+
+typedef long     (ZCALLBACK *tell_file_func)      OF((voidpf opaque, voidpf stream));
+typedef long     (ZCALLBACK *seek_file_func)      OF((voidpf opaque, voidpf stream, uLong offset, int origin));
+
+
+/* here is the "old" 32 bits structure structure */
+typedef struct zlib_filefunc_def_s
+{
+    open_file_func      zopen_file;
+    read_file_func      zread_file;
+    write_file_func     zwrite_file;
+    tell_file_func      ztell_file;
+    seek_file_func      zseek_file;
+    close_file_func     zclose_file;
+    testerror_file_func zerror_file;
+    voidpf              opaque;
+} zlib_filefunc_def;
+
+typedef ZPOS64_T (ZCALLBACK *tell64_file_func)    OF((voidpf opaque, voidpf stream));
+typedef long     (ZCALLBACK *seek64_file_func)    OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
+typedef voidpf   (ZCALLBACK *open64_file_func)    OF((voidpf opaque, const void* filename, int mode));
+
+typedef struct zlib_filefunc64_def_s
+{
+    open64_file_func    zopen64_file;
+    read_file_func      zread_file;
+    write_file_func     zwrite_file;
+    tell64_file_func    ztell64_file;
+    seek64_file_func    zseek64_file;
+    close_file_func     zclose_file;
+    testerror_file_func zerror_file;
+    voidpf              opaque;
+} zlib_filefunc64_def;
+
+void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
+void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
+
+/* now internal definition, only for zip.c and unzip.h */
+typedef struct zlib_filefunc64_32_def_s
+{
+    zlib_filefunc64_def zfile_func64;
+    open_file_func      zopen32_file;
+    tell_file_func      ztell32_file;
+    seek_file_func      zseek32_file;
+} zlib_filefunc64_32_def;
+
+
+#define ZREAD64(filefunc,filestream,buf,size)     ((*((filefunc).zfile_func64.zread_file))   ((filefunc).zfile_func64.opaque,filestream,buf,size))
+#define ZWRITE64(filefunc,filestream,buf,size)    ((*((filefunc).zfile_func64.zwrite_file))  ((filefunc).zfile_func64.opaque,filestream,buf,size))
+//#define ZTELL64(filefunc,filestream)            ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))
+//#define ZSEEK64(filefunc,filestream,pos,mode)   ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))
+#define ZCLOSE64(filefunc,filestream)             ((*((filefunc).zfile_func64.zclose_file))  ((filefunc).zfile_func64.opaque,filestream))
+#define ZERROR64(filefunc,filestream)             ((*((filefunc).zfile_func64.zerror_file))  ((filefunc).zfile_func64.opaque,filestream))
+
+voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
+long    call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
+ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
+
+void    fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32);
+
+#define ZOPEN64(filefunc,filename,mode)         (call_zopen64((&(filefunc)),(filename),(mode)))
+#define ZTELL64(filefunc,filestream)            (call_ztell64((&(filefunc)),(filestream)))
+#define ZSEEK64(filefunc,filestream,pos,mode)   (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/iowin32.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/iowin32.c
new file mode 100644 (file)
index 0000000..6a2a883
--- /dev/null
@@ -0,0 +1,389 @@
+/* iowin32.c -- IO base function header for compress/uncompress .zip
+     Version 1.1, February 14h, 2010
+     part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications for Zip64 support
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+     For more info read MiniZip_info.txt
+
+*/
+
+#include <stdlib.h>
+
+#include "zlib.h"
+#include "ioapi.h"
+#include "iowin32.h"
+
+#ifndef INVALID_HANDLE_VALUE
+#define INVALID_HANDLE_VALUE (0xFFFFFFFF)
+#endif
+
+#ifndef INVALID_SET_FILE_POINTER
+#define INVALID_SET_FILE_POINTER ((DWORD)-1)
+#endif
+
+voidpf  ZCALLBACK win32_open_file_func  OF((voidpf opaque, const char* filename, int mode));
+uLong   ZCALLBACK win32_read_file_func  OF((voidpf opaque, voidpf stream, void* buf, uLong size));
+uLong   ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
+ZPOS64_T ZCALLBACK win32_tell64_file_func  OF((voidpf opaque, voidpf stream));
+long    ZCALLBACK win32_seek64_file_func  OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
+int     ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream));
+int     ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream));
+
+typedef struct
+{
+    HANDLE hf;
+    int error;
+} WIN32FILE_IOWIN;
+
+
+static void win32_translate_open_mode(int mode,
+                                      DWORD* lpdwDesiredAccess,
+                                      DWORD* lpdwCreationDisposition,
+                                      DWORD* lpdwShareMode,
+                                      DWORD* lpdwFlagsAndAttributes)
+{
+    *lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0;
+
+    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
+    {
+        *lpdwDesiredAccess = GENERIC_READ;
+        *lpdwCreationDisposition = OPEN_EXISTING;
+        *lpdwShareMode = FILE_SHARE_READ;
+    }
+    else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
+    {
+        *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
+        *lpdwCreationDisposition = OPEN_EXISTING;
+    }
+    else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
+    {
+        *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
+        *lpdwCreationDisposition = CREATE_ALWAYS;
+    }
+}
+
+static voidpf win32_build_iowin(HANDLE hFile)
+{
+    voidpf ret=NULL;
+
+    if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
+    {
+        WIN32FILE_IOWIN w32fiow;
+        w32fiow.hf = hFile;
+        w32fiow.error = 0;
+        ret = malloc(sizeof(WIN32FILE_IOWIN));
+
+        if (ret==NULL)
+            CloseHandle(hFile);
+        else
+            *((WIN32FILE_IOWIN*)ret) = w32fiow;
+    }
+    return ret;
+}
+
+voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode)
+{
+    const char* mode_fopen = NULL;
+    DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
+    HANDLE hFile = NULL;
+
+    win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
+
+    if ((filename!=NULL) && (dwDesiredAccess != 0))
+        hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
+
+    return win32_build_iowin(hFile);
+}
+
+
+voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode)
+{
+    const char* mode_fopen = NULL;
+    DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
+    HANDLE hFile = NULL;
+
+    win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
+
+    if ((filename!=NULL) && (dwDesiredAccess != 0))
+        hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
+
+    return win32_build_iowin(hFile);
+}
+
+
+voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode)
+{
+    const char* mode_fopen = NULL;
+    DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
+    HANDLE hFile = NULL;
+
+    win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
+
+    if ((filename!=NULL) && (dwDesiredAccess != 0))
+        hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
+
+    return win32_build_iowin(hFile);
+}
+
+
+voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode)
+{
+    const char* mode_fopen = NULL;
+    DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
+    HANDLE hFile = NULL;
+
+    win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
+
+    if ((filename!=NULL) && (dwDesiredAccess != 0))
+        hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
+
+    return win32_build_iowin(hFile);
+}
+
+
+uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size)
+{
+    uLong ret=0;
+    HANDLE hFile = NULL;
+    if (stream!=NULL)
+        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+
+    if (hFile != NULL)
+    {
+        if (!ReadFile(hFile, buf, size, &ret, NULL))
+        {
+            DWORD dwErr = GetLastError();
+            if (dwErr == ERROR_HANDLE_EOF)
+                dwErr = 0;
+            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+        }
+    }
+
+    return ret;
+}
+
+
+uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size)
+{
+    uLong ret=0;
+    HANDLE hFile = NULL;
+    if (stream!=NULL)
+        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+
+    if (hFile != NULL)
+    {
+        if (!WriteFile(hFile, buf, size, &ret, NULL))
+        {
+            DWORD dwErr = GetLastError();
+            if (dwErr == ERROR_HANDLE_EOF)
+                dwErr = 0;
+            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+        }
+    }
+
+    return ret;
+}
+
+long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream)
+{
+    long ret=-1;
+    HANDLE hFile = NULL;
+    if (stream!=NULL)
+        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+    if (hFile != NULL)
+    {
+        DWORD dwSet = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
+        if (dwSet == INVALID_SET_FILE_POINTER)
+        {
+            DWORD dwErr = GetLastError();
+            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+            ret = -1;
+        }
+        else
+            ret=(long)dwSet;
+    }
+    return ret;
+}
+
+ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream)
+{
+    ZPOS64_T ret= (ZPOS64_T)-1;
+    HANDLE hFile = NULL;
+    if (stream!=NULL)
+        hFile = ((WIN32FILE_IOWIN*)stream)->hf;
+
+    if (hFile)
+    {
+        LARGE_INTEGER li;
+        li.QuadPart = 0;
+        li.u.LowPart = SetFilePointer(hFile, li.u.LowPart, &li.u.HighPart, FILE_CURRENT);
+        if ( (li.LowPart == 0xFFFFFFFF) && (GetLastError() != NO_ERROR))
+        {
+            DWORD dwErr = GetLastError();
+            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+            ret = (ZPOS64_T)-1;
+        }
+        else
+            ret=li.QuadPart;
+    }
+    return ret;
+}
+
+
+long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin)
+{
+    DWORD dwMoveMethod=0xFFFFFFFF;
+    HANDLE hFile = NULL;
+
+    long ret=-1;
+    if (stream!=NULL)
+        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+    switch (origin)
+    {
+    case ZLIB_FILEFUNC_SEEK_CUR :
+        dwMoveMethod = FILE_CURRENT;
+        break;
+    case ZLIB_FILEFUNC_SEEK_END :
+        dwMoveMethod = FILE_END;
+        break;
+    case ZLIB_FILEFUNC_SEEK_SET :
+        dwMoveMethod = FILE_BEGIN;
+        break;
+    default: return -1;
+    }
+
+    if (hFile != NULL)
+    {
+        DWORD dwSet = SetFilePointer(hFile, offset, NULL, dwMoveMethod);
+        if (dwSet == INVALID_SET_FILE_POINTER)
+        {
+            DWORD dwErr = GetLastError();
+            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+            ret = -1;
+        }
+        else
+            ret=0;
+    }
+    return ret;
+}
+
+long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin)
+{
+    DWORD dwMoveMethod=0xFFFFFFFF;
+    HANDLE hFile = NULL;
+    long ret=-1;
+
+    if (stream!=NULL)
+        hFile = ((WIN32FILE_IOWIN*)stream)->hf;
+
+    switch (origin)
+    {
+        case ZLIB_FILEFUNC_SEEK_CUR :
+            dwMoveMethod = FILE_CURRENT;
+            break;
+        case ZLIB_FILEFUNC_SEEK_END :
+            dwMoveMethod = FILE_END;
+            break;
+        case ZLIB_FILEFUNC_SEEK_SET :
+            dwMoveMethod = FILE_BEGIN;
+            break;
+        default: return -1;
+    }
+
+    if (hFile)
+    {
+        LARGE_INTEGER* li = (LARGE_INTEGER*)&offset;
+        DWORD dwSet = SetFilePointer(hFile, li->u.LowPart, &li->u.HighPart, dwMoveMethod);
+        if (dwSet == INVALID_SET_FILE_POINTER)
+        {
+            DWORD dwErr = GetLastError();
+            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+            ret = -1;
+        }
+        else
+            ret=0;
+    }
+    return ret;
+}
+
+int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream)
+{
+    int ret=-1;
+
+    if (stream!=NULL)
+    {
+        HANDLE hFile;
+        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+        if (hFile != NULL)
+        {
+            CloseHandle(hFile);
+            ret=0;
+        }
+        free(stream);
+    }
+    return ret;
+}
+
+int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream)
+{
+    int ret=-1;
+    if (stream!=NULL)
+    {
+        ret = ((WIN32FILE_IOWIN*)stream) -> error;
+    }
+    return ret;
+}
+
+void fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def)
+{
+    pzlib_filefunc_def->zopen_file = win32_open_file_func;
+    pzlib_filefunc_def->zread_file = win32_read_file_func;
+    pzlib_filefunc_def->zwrite_file = win32_write_file_func;
+    pzlib_filefunc_def->ztell_file = win32_tell_file_func;
+    pzlib_filefunc_def->zseek_file = win32_seek_file_func;
+    pzlib_filefunc_def->zclose_file = win32_close_file_func;
+    pzlib_filefunc_def->zerror_file = win32_error_file_func;
+    pzlib_filefunc_def->opaque = NULL;
+}
+
+void fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def)
+{
+    pzlib_filefunc_def->zopen64_file = win32_open64_file_func;
+    pzlib_filefunc_def->zread_file = win32_read_file_func;
+    pzlib_filefunc_def->zwrite_file = win32_write_file_func;
+    pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
+    pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
+    pzlib_filefunc_def->zclose_file = win32_close_file_func;
+    pzlib_filefunc_def->zerror_file = win32_error_file_func;
+    pzlib_filefunc_def->opaque = NULL;
+}
+
+
+void fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def)
+{
+    pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA;
+    pzlib_filefunc_def->zread_file = win32_read_file_func;
+    pzlib_filefunc_def->zwrite_file = win32_write_file_func;
+    pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
+    pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
+    pzlib_filefunc_def->zclose_file = win32_close_file_func;
+    pzlib_filefunc_def->zerror_file = win32_error_file_func;
+    pzlib_filefunc_def->opaque = NULL;
+}
+
+
+void fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def)
+{
+    pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW;
+    pzlib_filefunc_def->zread_file = win32_read_file_func;
+    pzlib_filefunc_def->zwrite_file = win32_write_file_func;
+    pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
+    pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
+    pzlib_filefunc_def->zclose_file = win32_close_file_func;
+    pzlib_filefunc_def->zerror_file = win32_error_file_func;
+    pzlib_filefunc_def->opaque = NULL;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/iowin32.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/iowin32.h
new file mode 100644 (file)
index 0000000..0ca0969
--- /dev/null
@@ -0,0 +1,28 @@
+/* iowin32.h -- IO base function header for compress/uncompress .zip
+     Version 1.1, February 14h, 2010
+     part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications for Zip64 support
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+         For more info read MiniZip_info.txt
+
+*/
+
+#include <windows.h>
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
+void fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def));
+void fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def));
+void fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def));
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/make_vms.com b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/make_vms.com
new file mode 100644 (file)
index 0000000..9ac13a9
--- /dev/null
@@ -0,0 +1,25 @@
+$ if f$search("ioapi.h_orig") .eqs. "" then copy ioapi.h ioapi.h_orig
+$ open/write zdef vmsdefs.h
+$ copy sys$input: zdef
+$ deck
+#define unix
+#define fill_zlib_filefunc64_32_def_from_filefunc32 fillzffunc64from
+#define Write_Zip64EndOfCentralDirectoryLocator Write_Zip64EoDLocator
+#define Write_Zip64EndOfCentralDirectoryRecord Write_Zip64EoDRecord
+#define Write_EndOfCentralDirectoryRecord Write_EoDRecord
+$ eod
+$ close zdef
+$ copy vmsdefs.h,ioapi.h_orig ioapi.h
+$ cc/include=[--]/prefix=all ioapi.c
+$ cc/include=[--]/prefix=all miniunz.c
+$ cc/include=[--]/prefix=all unzip.c
+$ cc/include=[--]/prefix=all minizip.c
+$ cc/include=[--]/prefix=all zip.c
+$ link miniunz,unzip,ioapi,[--]libz.olb/lib
+$ link minizip,zip,ioapi,[--]libz.olb/lib
+$ mcr []minizip test minizip_info.txt
+$ mcr []miniunz -l test.zip
+$ rename minizip_info.txt; minizip_info.txt_old
+$ mcr []miniunz test.zip
+$ delete test.zip;*
+$exit
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/miniunz.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/miniunz.c
new file mode 100644 (file)
index 0000000..9fefd18
--- /dev/null
@@ -0,0 +1,737 @@
+/*
+   miniunz.c
+   Version 1.1, February 14h, 2010
+   sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications of Unzip for Zip64
+         Copyright (C) 2007-2008 Even Rouault
+
+         Modifications for Zip64 support on both zip and unzip
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+*/
+
+#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
+        #ifndef __USE_FILE_OFFSET64
+                #define __USE_FILE_OFFSET64
+        #endif
+        #ifndef __USE_LARGEFILE64
+                #define __USE_LARGEFILE64
+        #endif
+        #ifndef _LARGEFILE64_SOURCE
+                #define _LARGEFILE64_SOURCE
+        #endif
+        #ifndef _FILE_OFFSET_BIT
+                #define _FILE_OFFSET_BIT 64
+        #endif
+#endif
+
+#ifdef __APPLE__
+// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
+#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
+#define FTELLO_FUNC(stream) ftello(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
+#else
+#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
+#define FTELLO_FUNC(stream) ftello64(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
+#endif
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fmuExtract.h>
+
+#ifdef _WIN32
+# include <direct.h>
+# include <io.h>
+#else
+# include <unistd.h>
+# include <utime.h>
+#endif
+
+
+#include "unzip.h"
+
+#define CASESENSITIVITY (0)
+#define WRITEBUFFERSIZE (8192)
+#define MAXFILENAME (256)
+
+#ifdef _WIN32
+#define USEWIN32IOAPI
+#include "iowin32.h"
+#endif
+/*
+  mini unzip, demo of unzip package
+
+  usage :
+  Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir]
+
+  list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT
+    if it exists
+*/
+
+
+/* change_file_date : change the date/time of a file
+    filename : the filename of the file where date/time must be modified
+    dosdate : the new date at the MSDos format (4 bytes)
+    tmu_date : the SAME new date at the tm_unz format */
+void change_file_date(filename,dosdate,tmu_date)
+    const char *filename;
+    uLong dosdate;
+    tm_unz tmu_date;
+{
+#ifdef _WIN32
+  HANDLE hFile;
+  FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite;
+
+  hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE,
+                      0,NULL,OPEN_EXISTING,0,NULL);
+  GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite);
+  DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal);
+  LocalFileTimeToFileTime(&ftLocal,&ftm);
+  SetFileTime(hFile,&ftm,&ftLastAcc,&ftm);
+  CloseHandle(hFile);
+#else
+#ifdef unix || __APPLE__
+  struct utimbuf ut;
+  struct tm newdate;
+  newdate.tm_sec = tmu_date.tm_sec;
+  newdate.tm_min=tmu_date.tm_min;
+  newdate.tm_hour=tmu_date.tm_hour;
+  newdate.tm_mday=tmu_date.tm_mday;
+  newdate.tm_mon=tmu_date.tm_mon;
+  if (tmu_date.tm_year > 1900)
+      newdate.tm_year=tmu_date.tm_year - 1900;
+  else
+      newdate.tm_year=tmu_date.tm_year ;
+  newdate.tm_isdst=-1;
+
+  ut.actime=ut.modtime=mktime(&newdate);
+  utime(filename,&ut);
+#endif
+#endif
+}
+
+
+/* mymkdir and change_file_date are not 100 % portable
+   As I don't know well Unix, I wait feedback for the unix portion */
+
+int mymkdir(dirname)
+    const char* dirname;
+{
+    int ret=0;
+#ifdef _WIN32
+    ret = _mkdir(dirname);
+#elif unix
+    ret = mkdir (dirname,0775);
+#elif __APPLE__
+    ret = mkdir (dirname,0775);
+#endif
+    return ret;
+}
+
+int makedir (newdir)
+    char *newdir;
+{
+  char *buffer ;
+  char *p;
+  int  len = (int)strlen(newdir);
+
+  if (len <= 0)
+    return 0;
+
+  buffer = (char*)malloc(len+1);
+        if (buffer==NULL)
+        {
+                printf("Error allocating memory\n");
+                return UNZ_INTERNALERROR;
+        }
+  strcpy(buffer,newdir);
+
+  if (buffer[len-1] == '/') {
+    buffer[len-1] = '\0';
+  }
+  if (mymkdir(buffer) == 0)
+    {
+      free(buffer);
+      return 1;
+    }
+
+  p = buffer+1;
+  while (1)
+    {
+      char hold;
+
+      while(*p && *p != '\\' && *p != '/')
+        p++;
+      hold = *p;
+      *p = 0;
+      if ((mymkdir(buffer) == -1) && (errno == ENOENT))
+        {
+          printf("couldn't create directory %s\n",buffer);
+          free(buffer);
+          return 0;
+        }
+      if (hold == 0)
+        break;
+      *p++ = hold;
+    }
+  free(buffer);
+  return 1;
+}
+
+void do_banner()
+{
+    printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n");
+    printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
+}
+
+void do_help()
+{
+    printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \
+           "  -e  Extract without pathname (junk paths)\n" \
+           "  -x  Extract with pathname\n" \
+           "  -v  list files\n" \
+           "  -l  list files\n" \
+           "  -d  directory to extract into\n" \
+           "  -o  overwrite files without prompting\n" \
+           "  -p  extract crypted file using password\n\n");
+}
+
+void Display64BitsSize(ZPOS64_T n, int size_char)
+{
+  /* to avoid compatibility problem , we do here the conversion */
+  char number[21];
+  int offset=19;
+  int pos_string = 19;
+  number[20]=0;
+  for (;;) {
+      number[offset]=(char)((n%10)+'0');
+      if (number[offset] != '0')
+          pos_string=offset;
+      n/=10;
+      if (offset==0)
+          break;
+      offset--;
+  }
+  {
+      int size_display_string = 19-pos_string;
+      while (size_char > size_display_string)
+      {
+          size_char--;
+          printf(" ");
+      }
+  }
+
+  printf("%s",&number[pos_string]);
+}
+
+int do_list(uf)
+    unzFile uf;
+{
+    uLong i;
+    unz_global_info64 gi;
+    int err;
+
+    err = unzGetGlobalInfo64(uf,&gi);
+    if (err!=UNZ_OK)
+        printf("error %d with zipfile in unzGetGlobalInfo \n",err);
+    printf("  Length  Method     Size Ratio   Date    Time   CRC-32     Name\n");
+    printf("  ------  ------     ---- -----   ----    ----   ------     ----\n");
+    for (i=0;i<gi.number_entry;i++)
+    {
+        char filename_inzip[256];
+        unz_file_info64 file_info;
+        uLong ratio=0;
+        const char *string_method;
+        char charCrypt=' ';
+        err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
+        if (err!=UNZ_OK)
+        {
+            printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
+            break;
+        }
+        if (file_info.uncompressed_size>0)
+            ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size);
+
+        /* display a '*' if the file is crypted */
+        if ((file_info.flag & 1) != 0)
+            charCrypt='*';
+
+        if (file_info.compression_method==0)
+            string_method="Stored";
+        else
+        if (file_info.compression_method==Z_DEFLATED)
+        {
+            uInt iLevel=(uInt)((file_info.flag & 0x6)/2);
+            if (iLevel==0)
+              string_method="Defl:N";
+            else if (iLevel==1)
+              string_method="Defl:X";
+            else if ((iLevel==2) || (iLevel==3))
+              string_method="Defl:F"; /* 2:fast , 3 : extra fast*/
+        }
+        else
+        if (file_info.compression_method==Z_BZIP2ED)
+        {
+              string_method="BZip2 ";
+        }
+        else
+            string_method="Unkn. ";
+
+        Display64BitsSize(file_info.uncompressed_size,7);
+        printf("  %6s%c",string_method,charCrypt);
+        Display64BitsSize(file_info.compressed_size,7);
+        printf(" %3lu%%  %2.2lu-%2.2lu-%2.2lu  %2.2lu:%2.2lu  %8.8lx   %s\n",
+                ratio,
+                (uLong)file_info.tmu_date.tm_mon + 1,
+                (uLong)file_info.tmu_date.tm_mday,
+                (uLong)file_info.tmu_date.tm_year % 100,
+                (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min,
+                (uLong)file_info.crc,filename_inzip);
+        if ((i+1)<gi.number_entry)
+        {
+            err = unzGoToNextFile(uf);
+            if (err!=UNZ_OK)
+            {
+                printf("error %d with zipfile in unzGoToNextFile\n",err);
+                break;
+            }
+        }
+    }
+
+    return 0;
+}
+
+
+int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
+    unzFile uf;
+    const int* popt_extract_without_path;
+    int* popt_overwrite;
+    const char* password;
+{
+    char filename_inzip[256];
+    char* filename_withoutpath;
+    char* p;
+    int err=UNZ_OK;
+    FILE *fout=NULL;
+    void* buf;
+    uInt size_buf;
+
+    unz_file_info64 file_info;
+    uLong ratio=0;
+    err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
+
+    if (err!=UNZ_OK)
+    {
+        printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
+        return err;
+    }
+
+    size_buf = WRITEBUFFERSIZE;
+    buf = (void*)malloc(size_buf);
+    if (buf==NULL)
+    {
+        printf("Error allocating memory\n");
+        return UNZ_INTERNALERROR;
+    }
+
+    p = filename_withoutpath = filename_inzip;
+    while ((*p) != '\0')
+    {
+        if (((*p)=='/') || ((*p)=='\\'))
+            filename_withoutpath = p+1;
+        p++;
+    }
+
+    if ((*filename_withoutpath)=='\0')
+    {
+        if ((*popt_extract_without_path)==0)
+        {
+            printf("creating directory: %s\n",filename_inzip);
+            mymkdir(filename_inzip);
+        }
+    }
+    else
+    {
+        const char* write_filename;
+        int skip=0;
+
+        if ((*popt_extract_without_path)==0)
+            write_filename = filename_inzip;
+        else
+            write_filename = filename_withoutpath;
+
+        err = unzOpenCurrentFilePassword(uf,password);
+        if (err!=UNZ_OK)
+        {
+            printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err);
+        }
+
+        if (((*popt_overwrite)==0) && (err==UNZ_OK))
+        {
+            char rep=0;
+            FILE* ftestexist;
+            ftestexist = FOPEN_FUNC(write_filename,"rb");
+            if (ftestexist!=NULL)
+            {
+                fclose(ftestexist);
+                do
+                {
+                    char answer[128];
+                    int ret;
+
+                    printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
+                    ret = scanf("%1s",answer);
+                    if (ret != 1)
+                    {
+                       exit(EXIT_FAILURE);
+                    }
+                    rep = answer[0] ;
+                    if ((rep>='a') && (rep<='z'))
+                        rep -= 0x20;
+                }
+                while ((rep!='Y') && (rep!='N') && (rep!='A'));
+            }
+
+            if (rep == 'N')
+                skip = 1;
+
+            if (rep == 'A')
+                *popt_overwrite=1;
+        }
+
+        if ((skip==0) && (err==UNZ_OK))
+        {
+            fout=FOPEN_FUNC(write_filename,"wb");
+            /* some zipfile don't contain directory alone before file */
+            if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
+                                (filename_withoutpath!=(char*)filename_inzip))
+            {
+                char c=*(filename_withoutpath-1);
+                *(filename_withoutpath-1)='\0';
+                makedir(write_filename);
+                *(filename_withoutpath-1)=c;
+                fout=FOPEN_FUNC(write_filename,"wb");
+            }
+
+            if (fout==NULL)
+            {
+                printf("error opening %s\n",write_filename);
+            }
+        }
+
+        if (fout!=NULL)
+        {
+            printf(" extracting: %s\n",write_filename);
+
+            do
+            {
+                err = unzReadCurrentFile(uf,buf,size_buf);
+                if (err<0)
+                {
+                    printf("error %d with zipfile in unzReadCurrentFile\n",err);
+                    break;
+                }
+                if (err>0)
+                    if (fwrite(buf,err,1,fout)!=1)
+                    {
+                        printf("error in writing extracted file\n");
+                        err=UNZ_ERRNO;
+                        break;
+                    }
+            }
+            while (err>0);
+            if (fout)
+                    fclose(fout);
+
+            if (err==0)
+                change_file_date(write_filename,file_info.dosDate,
+                                 file_info.tmu_date);
+        }
+
+        if (err==UNZ_OK)
+        {
+            err = unzCloseCurrentFile (uf);
+            if (err!=UNZ_OK)
+            {
+                printf("error %d with zipfile in unzCloseCurrentFile\n",err);
+            }
+        }
+        else
+            unzCloseCurrentFile(uf); /* don't lose the error */
+    }
+
+    free(buf);
+    return err;
+}
+
+
+int do_extract(uf,opt_extract_without_path,opt_overwrite,password)
+    unzFile uf;
+    int opt_extract_without_path;
+    int opt_overwrite;
+    const char* password;
+{
+    uLong i;
+    unz_global_info64 gi;
+    int err;
+    FILE* fout=NULL;
+
+    err = unzGetGlobalInfo64(uf,&gi);
+    if (err!=UNZ_OK)
+        printf("error %d with zipfile in unzGetGlobalInfo \n",err);
+
+    for (i=0;i<gi.number_entry;i++)
+    {
+        if (do_extract_currentfile(uf,&opt_extract_without_path,
+                                      &opt_overwrite,
+                                      password) != UNZ_OK)
+            break;
+
+        if ((i+1)<gi.number_entry)
+        {
+            err = unzGoToNextFile(uf);
+            if (err!=UNZ_OK)
+            {
+                printf("error %d with zipfile in unzGoToNextFile\n",err);
+                break;
+            }
+        }
+    }
+
+    return 0;
+}
+
+int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password)
+    unzFile uf;
+    const char* filename;
+    int opt_extract_without_path;
+    int opt_overwrite;
+    const char* password;
+{
+    int err = UNZ_OK;
+    if (unzLocateFile(uf,filename,CASESENSITIVITY)!=UNZ_OK)
+    {
+        printf("file %s not found in the zipfile\n",filename);
+        return 2;
+    }
+
+    if (do_extract_currentfile(uf,&opt_extract_without_path,
+                                      &opt_overwrite,
+                                      password) == UNZ_OK)
+        return 0;
+    else
+        return 1;
+}
+
+/*
+ * Modified from the original main function
+ */
+int unzipFMU(const char *zipFileName, const char *outPath) {
+    const char *filename_to_extract=NULL;
+    const char *password=NULL;
+    char filename_try[MAXFILENAME+16] = "";
+    int ret_value=0;
+    int opt_do_list=0;
+    int opt_do_extract=1;
+    int opt_do_extract_withoutpath=0;
+    int opt_overwrite=1;
+    int opt_extractdir=1;
+    const char *dirname=outPath;
+    unzFile uf=NULL;    
+
+    if (zipFileName!=NULL)
+    {
+
+#        ifdef USEWIN32IOAPI
+        zlib_filefunc64_def ffunc;
+#        endif
+
+        strncpy(filename_try, zipFileName,MAXFILENAME-1);
+        /* strncpy doesnt append the trailing NULL, of the string is too long. */
+        filename_try[ MAXFILENAME ] = '\0';
+
+#        ifdef USEWIN32IOAPI
+        fill_win32_filefunc64A(&ffunc);
+        uf = unzOpen2_64(zipFileName,&ffunc);
+#        else
+        uf = unzOpen64(zipFileName);
+#        endif
+        if (uf==NULL)
+        {
+            strcat(filename_try,".zip");
+#            ifdef USEWIN32IOAPI
+            uf = unzOpen2_64(filename_try,&ffunc);
+#            else
+            uf = unzOpen64(filename_try);
+#            endif
+        }
+    }
+
+    if (uf==NULL)
+    {
+        printf("Cannot open %s or %s.zip\n",zipFileName,zipFileName);
+        return 1;
+    }
+    printf("%s opened\n",filename_try);
+
+    if (opt_do_list==1)
+        ret_value = do_list(uf);
+    else if (opt_do_extract==1)
+    {
+#ifdef _WIN32
+        if (opt_extractdir && _chdir(dirname))
+#else
+        if (opt_extractdir && chdir(dirname))
+#endif
+        {
+          printf("Error changing into %s, aborting\n", dirname);
+          exit(-1);
+        }
+
+        if (filename_to_extract == NULL)
+            ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, password);
+        else
+            ret_value = do_extract_onefile(uf, filename_to_extract, opt_do_extract_withoutpath, opt_overwrite, password);
+    }
+
+    unzClose(uf);
+
+    return ret_value;
+}
+
+// Original
+//int main(argc,argv)
+//    int argc;
+//    char *argv[];
+//{
+//    const char *zipfilename=NULL;
+//    const char *filename_to_extract=NULL;
+//    const char *password=NULL;
+//    char filename_try[MAXFILENAME+16] = "";
+//    int i;
+//    int ret_value=0;
+//    int opt_do_list=0;
+//    int opt_do_extract=1;
+//    int opt_do_extract_withoutpath=0;
+//    int opt_overwrite=0;
+//    int opt_extractdir=0;
+//    const char *dirname=NULL;
+//    unzFile uf=NULL;
+//
+//    do_banner();
+//    if (argc==1)
+//    {
+//        do_help();
+//        return 0;
+//    }
+//    else
+//    {
+//        for (i=1;i<argc;i++)
+//        {
+//            if ((*argv[i])=='-')
+//            {
+//                const char *p=argv[i]+1;
+//
+//                while ((*p)!='\0')
+//                {
+//                    char c=*(p++);;
+//                    if ((c=='l') || (c=='L'))
+//                        opt_do_list = 1;
+//                    if ((c=='v') || (c=='V'))
+//                        opt_do_list = 1;
+//                    if ((c=='x') || (c=='X'))
+//                        opt_do_extract = 1;
+//                    if ((c=='e') || (c=='E'))
+//                        opt_do_extract = opt_do_extract_withoutpath = 1;
+//                    if ((c=='o') || (c=='O'))
+//                        opt_overwrite=1;
+//                    if ((c=='d') || (c=='D'))
+//                    {
+//                        opt_extractdir=1;
+//                        dirname=argv[i+1];
+//                    }
+//
+//                    if (((c=='p') || (c=='P')) && (i+1<argc))
+//                    {
+//                        password=argv[i+1];
+//                        i++;
+//                    }
+//                }
+//            }
+//            else
+//            {
+//                if (zipfilename == NULL)
+//                    zipfilename = argv[i];
+//                else if ((filename_to_extract==NULL) && (!opt_extractdir))
+//                        filename_to_extract = argv[i] ;
+//            }
+//        }
+//    }
+//
+//    if (zipfilename!=NULL)
+//    {
+//
+//#        ifdef USEWIN32IOAPI
+//        zlib_filefunc64_def ffunc;
+//#        endif
+//
+//        strncpy(filename_try, zipfilename,MAXFILENAME-1);
+//        /* strncpy doesnt append the trailing NULL, of the string is too long. */
+//        filename_try[ MAXFILENAME ] = '\0';
+//
+//#        ifdef USEWIN32IOAPI
+//        fill_win32_filefunc64A(&ffunc);
+//        uf = unzOpen2_64(zipfilename,&ffunc);
+//#        else
+//        uf = unzOpen64(zipfilename);
+//#        endif
+//        if (uf==NULL)
+//        {
+//            strcat(filename_try,".zip");
+//#            ifdef USEWIN32IOAPI
+//            uf = unzOpen2_64(filename_try,&ffunc);
+//#            else
+//            uf = unzOpen64(filename_try);
+//#            endif
+//        }
+//    }
+//
+//    if (uf==NULL)
+//    {
+//        printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
+//        return 1;
+//    }
+//    printf("%s opened\n",filename_try);
+//
+//    if (opt_do_list==1)
+//        ret_value = do_list(uf);
+//    else if (opt_do_extract==1)
+//    {
+//#ifdef _WIN32
+//        if (opt_extractdir && _chdir(dirname))
+//#else
+//        if (opt_extractdir && chdir(dirname))
+//#endif
+//        {
+//          printf("Error changing into %s, aborting\n", dirname);
+//          exit(-1);
+//        }
+//
+//        if (filename_to_extract == NULL)
+//            ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, password);
+//        else
+//            ret_value = do_extract_onefile(uf, filename_to_extract, opt_do_extract_withoutpath, opt_overwrite, password);
+//    }
+//
+//    unzClose(uf);
+//
+//    return ret_value;
+//}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.c
new file mode 100644 (file)
index 0000000..4288962
--- /dev/null
@@ -0,0 +1,520 @@
+/*
+   minizip.c
+   Version 1.1, February 14h, 2010
+   sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications of Unzip for Zip64
+         Copyright (C) 2007-2008 Even Rouault
+
+         Modifications for Zip64 support on both zip and unzip
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+*/
+
+
+#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
+        #ifndef __USE_FILE_OFFSET64
+                #define __USE_FILE_OFFSET64
+        #endif
+        #ifndef __USE_LARGEFILE64
+                #define __USE_LARGEFILE64
+        #endif
+        #ifndef _LARGEFILE64_SOURCE
+                #define _LARGEFILE64_SOURCE
+        #endif
+        #ifndef _FILE_OFFSET_BIT
+                #define _FILE_OFFSET_BIT 64
+        #endif
+#endif
+
+#ifdef __APPLE__
+// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
+#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
+#define FTELLO_FUNC(stream) ftello(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
+#else
+#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
+#define FTELLO_FUNC(stream) ftello64(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
+#endif
+
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <errno.h>
+#include <fcntl.h>
+
+#ifdef _WIN32
+# include <direct.h>
+# include <io.h>
+#else
+# include <unistd.h>
+# include <utime.h>
+# include <sys/types.h>
+# include <sys/stat.h>
+#endif
+
+#include "zip.h"
+
+#ifdef _WIN32
+        #define USEWIN32IOAPI
+        #include "iowin32.h"
+#endif
+
+
+
+#define WRITEBUFFERSIZE (16384)
+#define MAXFILENAME (256)
+
+#ifdef _WIN32
+uLong filetime(f, tmzip, dt)
+    char *f;                /* name of file to get info on */
+    tm_zip *tmzip;             /* return value: access, modific. and creation times */
+    uLong *dt;             /* dostime */
+{
+  int ret = 0;
+  {
+      FILETIME ftLocal;
+      HANDLE hFind;
+      WIN32_FIND_DATAA ff32;
+
+      hFind = FindFirstFileA(f,&ff32);
+      if (hFind != INVALID_HANDLE_VALUE)
+      {
+        FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
+        FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0);
+        FindClose(hFind);
+        ret = 1;
+      }
+  }
+  return ret;
+}
+#else
+#ifdef unix || __APPLE__
+uLong filetime(f, tmzip, dt)
+    char *f;               /* name of file to get info on */
+    tm_zip *tmzip;         /* return value: access, modific. and creation times */
+    uLong *dt;             /* dostime */
+{
+  int ret=0;
+  struct stat s;        /* results of stat() */
+  struct tm* filedate;
+  time_t tm_t=0;
+
+  if (strcmp(f,"-")!=0)
+  {
+    char name[MAXFILENAME+1];
+    int len = strlen(f);
+    if (len > MAXFILENAME)
+      len = MAXFILENAME;
+
+    strncpy(name, f,MAXFILENAME-1);
+    /* strncpy doesnt append the trailing NULL, of the string is too long. */
+    name[ MAXFILENAME ] = '\0';
+
+    if (name[len - 1] == '/')
+      name[len - 1] = '\0';
+    /* not all systems allow stat'ing a file with / appended */
+    if (stat(name,&s)==0)
+    {
+      tm_t = s.st_mtime;
+      ret = 1;
+    }
+  }
+  filedate = localtime(&tm_t);
+
+  tmzip->tm_sec  = filedate->tm_sec;
+  tmzip->tm_min  = filedate->tm_min;
+  tmzip->tm_hour = filedate->tm_hour;
+  tmzip->tm_mday = filedate->tm_mday;
+  tmzip->tm_mon  = filedate->tm_mon ;
+  tmzip->tm_year = filedate->tm_year;
+
+  return ret;
+}
+#else
+uLong filetime(f, tmzip, dt)
+    char *f;                /* name of file to get info on */
+    tm_zip *tmzip;             /* return value: access, modific. and creation times */
+    uLong *dt;             /* dostime */
+{
+    return 0;
+}
+#endif
+#endif
+
+
+
+
+int check_exist_file(filename)
+    const char* filename;
+{
+    FILE* ftestexist;
+    int ret = 1;
+    ftestexist = FOPEN_FUNC(filename,"rb");
+    if (ftestexist==NULL)
+        ret = 0;
+    else
+        fclose(ftestexist);
+    return ret;
+}
+
+void do_banner()
+{
+    printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n");
+    printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n");
+}
+
+void do_help()
+{
+    printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \
+           "  -o  Overwrite existing file.zip\n" \
+           "  -a  Append to existing file.zip\n" \
+           "  -0  Store only\n" \
+           "  -1  Compress faster\n" \
+           "  -9  Compress better\n\n" \
+           "  -j  exclude path. store only the file name.\n\n");
+}
+
+/* calculate the CRC32 of a file,
+   because to encrypt a file, we need known the CRC32 of the file before */
+int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc)
+{
+   unsigned long calculate_crc=0;
+   int err=ZIP_OK;
+   FILE * fin = FOPEN_FUNC(filenameinzip,"rb");
+
+   unsigned long size_read = 0;
+   unsigned long total_read = 0;
+   if (fin==NULL)
+   {
+       err = ZIP_ERRNO;
+   }
+
+    if (err == ZIP_OK)
+        do
+        {
+            err = ZIP_OK;
+            size_read = (int)fread(buf,1,size_buf,fin);
+            if (size_read < size_buf)
+                if (feof(fin)==0)
+            {
+                printf("error in reading %s\n",filenameinzip);
+                err = ZIP_ERRNO;
+            }
+
+            if (size_read>0)
+                calculate_crc = crc32(calculate_crc,buf,size_read);
+            total_read += size_read;
+
+        } while ((err == ZIP_OK) && (size_read>0));
+
+    if (fin)
+        fclose(fin);
+
+    *result_crc=calculate_crc;
+    printf("file %s crc %lx\n", filenameinzip, calculate_crc);
+    return err;
+}
+
+int isLargeFile(const char* filename)
+{
+  int largeFile = 0;
+  ZPOS64_T pos = 0;
+  FILE* pFile = FOPEN_FUNC(filename, "rb");
+
+  if(pFile != NULL)
+  {
+    int n = FSEEKO_FUNC(pFile, 0, SEEK_END);
+    pos = FTELLO_FUNC(pFile);
+
+                printf("File : %s is %lld bytes\n", filename, pos);
+
+    if(pos >= 0xffffffff)
+     largeFile = 1;
+
+                fclose(pFile);
+  }
+
+ return largeFile;
+}
+
+int main(argc,argv)
+    int argc;
+    char *argv[];
+{
+    int i;
+    int opt_overwrite=0;
+    int opt_compress_level=Z_DEFAULT_COMPRESSION;
+    int opt_exclude_path=0;
+    int zipfilenamearg = 0;
+    char filename_try[MAXFILENAME+16];
+    int zipok;
+    int err=0;
+    int size_buf=0;
+    void* buf=NULL;
+    const char* password=NULL;
+
+
+    do_banner();
+    if (argc==1)
+    {
+        do_help();
+        return 0;
+    }
+    else
+    {
+        for (i=1;i<argc;i++)
+        {
+            if ((*argv[i])=='-')
+            {
+                const char *p=argv[i]+1;
+
+                while ((*p)!='\0')
+                {
+                    char c=*(p++);;
+                    if ((c=='o') || (c=='O'))
+                        opt_overwrite = 1;
+                    if ((c=='a') || (c=='A'))
+                        opt_overwrite = 2;
+                    if ((c>='0') && (c<='9'))
+                        opt_compress_level = c-'0';
+                    if ((c=='j') || (c=='J'))
+                        opt_exclude_path = 1;
+
+                    if (((c=='p') || (c=='P')) && (i+1<argc))
+                    {
+                        password=argv[i+1];
+                        i++;
+                    }
+                }
+            }
+            else
+            {
+                if (zipfilenamearg == 0)
+                {
+                    zipfilenamearg = i ;
+                }
+            }
+        }
+    }
+
+    size_buf = WRITEBUFFERSIZE;
+    buf = (void*)malloc(size_buf);
+    if (buf==NULL)
+    {
+        printf("Error allocating memory\n");
+        return ZIP_INTERNALERROR;
+    }
+
+    if (zipfilenamearg==0)
+    {
+        zipok=0;
+    }
+    else
+    {
+        int i,len;
+        int dot_found=0;
+
+        zipok = 1 ;
+        strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1);
+        /* strncpy doesnt append the trailing NULL, of the string is too long. */
+        filename_try[ MAXFILENAME ] = '\0';
+
+        len=(int)strlen(filename_try);
+        for (i=0;i<len;i++)
+            if (filename_try[i]=='.')
+                dot_found=1;
+
+        if (dot_found==0)
+            strcat(filename_try,".zip");
+
+        if (opt_overwrite==2)
+        {
+            /* if the file don't exist, we not append file */
+            if (check_exist_file(filename_try)==0)
+                opt_overwrite=1;
+        }
+        else
+        if (opt_overwrite==0)
+            if (check_exist_file(filename_try)!=0)
+            {
+                char rep=0;
+                do
+                {
+                    char answer[128];
+                    int ret;
+                    printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
+                    ret = scanf("%1s",answer);
+                    if (ret != 1)
+                    {
+                       exit(EXIT_FAILURE);
+                    }
+                    rep = answer[0] ;
+                    if ((rep>='a') && (rep<='z'))
+                        rep -= 0x20;
+                }
+                while ((rep!='Y') && (rep!='N') && (rep!='A'));
+                if (rep=='N')
+                    zipok = 0;
+                if (rep=='A')
+                    opt_overwrite = 2;
+            }
+    }
+
+    if (zipok==1)
+    {
+        zipFile zf;
+        int errclose;
+#        ifdef USEWIN32IOAPI
+        zlib_filefunc64_def ffunc;
+        fill_win32_filefunc64A(&ffunc);
+        zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
+#        else
+        zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0);
+#        endif
+
+        if (zf == NULL)
+        {
+            printf("error opening %s\n",filename_try);
+            err= ZIP_ERRNO;
+        }
+        else
+            printf("creating %s\n",filename_try);
+
+        for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
+        {
+            if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
+                  ((argv[i][1]=='o') || (argv[i][1]=='O') ||
+                   (argv[i][1]=='a') || (argv[i][1]=='A') ||
+                   (argv[i][1]=='p') || (argv[i][1]=='P') ||
+                   ((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
+                  (strlen(argv[i]) == 2)))
+            {
+                FILE * fin;
+                int size_read;
+                const char* filenameinzip = argv[i];
+                const char *savefilenameinzip;
+                zip_fileinfo zi;
+                unsigned long crcFile=0;
+                int zip64 = 0;
+
+                zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
+                zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
+                zi.dosDate = 0;
+                zi.internal_fa = 0;
+                zi.external_fa = 0;
+                filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);
+
+/*
+                err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
+                                 NULL,0,NULL,0,NULL / * comment * /,
+                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
+                                 opt_compress_level);
+*/
+                if ((password != NULL) && (err==ZIP_OK))
+                    err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);
+
+                zip64 = isLargeFile(filenameinzip);
+
+                                                         /* The path name saved, should not include a leading slash. */
+               /*if it did, windows/xp and dynazip couldn't read the zip file. */
+                 savefilenameinzip = filenameinzip;
+                 while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' )
+                 {
+                     savefilenameinzip++;
+                 }
+
+                 /*should the zip file contain any path at all?*/
+                 if( opt_exclude_path )
+                 {
+                     const char *tmpptr;
+                     const char *lastslash = 0;
+                     for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
+                     {
+                         if( *tmpptr == '\\' || *tmpptr == '/')
+                         {
+                             lastslash = tmpptr;
+                         }
+                     }
+                     if( lastslash != NULL )
+                     {
+                         savefilenameinzip = lastslash+1; // base filename follows last slash.
+                     }
+                 }
+
+                 /**/
+                err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi,
+                                 NULL,0,NULL,0,NULL /* comment*/,
+                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
+                                 opt_compress_level,0,
+                                 /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
+                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+                                 password,crcFile, zip64);
+
+                if (err != ZIP_OK)
+                    printf("error in opening %s in zipfile\n",filenameinzip);
+                else
+                {
+                    fin = FOPEN_FUNC(filenameinzip,"rb");
+                    if (fin==NULL)
+                    {
+                        err=ZIP_ERRNO;
+                        printf("error in opening %s for reading\n",filenameinzip);
+                    }
+                }
+
+                if (err == ZIP_OK)
+                    do
+                    {
+                        err = ZIP_OK;
+                        size_read = (int)fread(buf,1,size_buf,fin);
+                        if (size_read < size_buf)
+                            if (feof(fin)==0)
+                        {
+                            printf("error in reading %s\n",filenameinzip);
+                            err = ZIP_ERRNO;
+                        }
+
+                        if (size_read>0)
+                        {
+                            err = zipWriteInFileInZip (zf,buf,size_read);
+                            if (err<0)
+                            {
+                                printf("error in writing %s in the zipfile\n",
+                                                 filenameinzip);
+                            }
+
+                        }
+                    } while ((err == ZIP_OK) && (size_read>0));
+
+                if (fin)
+                    fclose(fin);
+
+                if (err<0)
+                    err=ZIP_ERRNO;
+                else
+                {
+                    err = zipCloseFileInZip(zf);
+                    if (err!=ZIP_OK)
+                        printf("error in closing %s in the zipfile\n",
+                                    filenameinzip);
+                }
+            }
+        }
+        errclose = zipClose(zf,NULL);
+        if (errclose != ZIP_OK)
+            printf("error in closing %s\n",filename_try);
+    }
+    else
+    {
+       do_help();
+    }
+
+    free(buf);
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.h
new file mode 100644 (file)
index 0000000..725bbba
--- /dev/null
@@ -0,0 +1,6 @@
+#ifndef ABC_DLL // abc.dll source code will define this macro before including this header\r
+#define ABC_API __declspec( dllimport )\r
+#else\r
+#define ABC_API __declspec( dllexport )\r
+#endif\r
+class ABC_API CAbc {\85};
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.pc.in b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/minizip.pc.in
new file mode 100644 (file)
index 0000000..69b5b7f
--- /dev/null
@@ -0,0 +1,12 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@/minizip
+
+Name: minizip
+Description: Minizip zip file manipulation library
+Requires:
+Version: @PACKAGE_VERSION@
+Libs: -L${libdir} -lminizip
+Libs.private: -lz
+Cflags: -I${includedir}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/mztools.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/mztools.c
new file mode 100644 (file)
index 0000000..96891c2
--- /dev/null
@@ -0,0 +1,291 @@
+/*
+  Additional tools for Minizip
+  Code: Xavier Roche '2004
+  License: Same as ZLIB (www.gzip.org)
+*/
+
+/* Code */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "zlib.h"
+#include "unzip.h"
+
+#define READ_8(adr)  ((unsigned char)*(adr))
+#define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) )
+#define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) )
+
+#define WRITE_8(buff, n) do { \
+  *((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \
+} while(0)
+#define WRITE_16(buff, n) do { \
+  WRITE_8((unsigned char*)(buff), n); \
+  WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \
+} while(0)
+#define WRITE_32(buff, n) do { \
+  WRITE_16((unsigned char*)(buff), (n) & 0xffff); \
+  WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \
+} while(0)
+
+extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered)
+const char* file;
+const char* fileOut;
+const char* fileOutTmp;
+uLong* nRecovered;
+uLong* bytesRecovered;
+{
+  int err = Z_OK;
+  FILE* fpZip = fopen(file, "rb");
+  FILE* fpOut = fopen(fileOut, "wb");
+  FILE* fpOutCD = fopen(fileOutTmp, "wb");
+  if (fpZip != NULL &&  fpOut != NULL) {
+    int entries = 0;
+    uLong totalBytes = 0;
+    char header[30];
+    char filename[1024];
+    char extra[1024];
+    int offset = 0;
+    int offsetCD = 0;
+    while ( fread(header, 1, 30, fpZip) == 30 ) {
+      int currentOffset = offset;
+
+      /* File entry */
+      if (READ_32(header) == 0x04034b50) {
+        unsigned int version = READ_16(header + 4);
+        unsigned int gpflag = READ_16(header + 6);
+        unsigned int method = READ_16(header + 8);
+        unsigned int filetime = READ_16(header + 10);
+        unsigned int filedate = READ_16(header + 12);
+        unsigned int crc = READ_32(header + 14); /* crc */
+        unsigned int cpsize = READ_32(header + 18); /* compressed size */
+        unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */
+        unsigned int fnsize = READ_16(header + 26); /* file name length */
+        unsigned int extsize = READ_16(header + 28); /* extra field length */
+        filename[0] = extra[0] = '\0';
+
+        /* Header */
+        if (fwrite(header, 1, 30, fpOut) == 30) {
+          offset += 30;
+        } else {
+          err = Z_ERRNO;
+          break;
+        }
+
+        /* Filename */
+        if (fnsize > 0) {
+          if (fnsize < sizeof(filename)) {
+            if (fread(filename, 1, fnsize, fpZip) == fnsize) {
+                if (fwrite(filename, 1, fnsize, fpOut) == fnsize) {
+                offset += fnsize;
+              } else {
+                err = Z_ERRNO;
+                break;
+              }
+            } else {
+              err = Z_ERRNO;
+              break;
+            }
+          } else {
+            err = Z_ERRNO;
+            break;
+          }
+        } else {
+          err = Z_STREAM_ERROR;
+          break;
+        }
+
+        /* Extra field */
+        if (extsize > 0) {
+          if (extsize < sizeof(extra)) {
+            if (fread(extra, 1, extsize, fpZip) == extsize) {
+              if (fwrite(extra, 1, extsize, fpOut) == extsize) {
+                offset += extsize;
+                } else {
+                err = Z_ERRNO;
+                break;
+              }
+            } else {
+              err = Z_ERRNO;
+              break;
+            }
+          } else {
+            err = Z_ERRNO;
+            break;
+          }
+        }
+
+        /* Data */
+        {
+          int dataSize = cpsize;
+          if (dataSize == 0) {
+            dataSize = uncpsize;
+          }
+          if (dataSize > 0) {
+            char* data = malloc(dataSize);
+            if (data != NULL) {
+              if ((int)fread(data, 1, dataSize, fpZip) == dataSize) {
+                if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) {
+                  offset += dataSize;
+                  totalBytes += dataSize;
+                } else {
+                  err = Z_ERRNO;
+                }
+              } else {
+                err = Z_ERRNO;
+              }
+              free(data);
+              if (err != Z_OK) {
+                break;
+              }
+            } else {
+              err = Z_MEM_ERROR;
+              break;
+            }
+          }
+        }
+
+        /* Central directory entry */
+        {
+          char header[46];
+          char* comment = "";
+          int comsize = (int) strlen(comment);
+          WRITE_32(header, 0x02014b50);
+          WRITE_16(header + 4, version);
+          WRITE_16(header + 6, version);
+          WRITE_16(header + 8, gpflag);
+          WRITE_16(header + 10, method);
+          WRITE_16(header + 12, filetime);
+          WRITE_16(header + 14, filedate);
+          WRITE_32(header + 16, crc);
+          WRITE_32(header + 20, cpsize);
+          WRITE_32(header + 24, uncpsize);
+          WRITE_16(header + 28, fnsize);
+          WRITE_16(header + 30, extsize);
+          WRITE_16(header + 32, comsize);
+          WRITE_16(header + 34, 0);     /* disk # */
+          WRITE_16(header + 36, 0);     /* int attrb */
+          WRITE_32(header + 38, 0);     /* ext attrb */
+          WRITE_32(header + 42, currentOffset);
+          /* Header */
+          if (fwrite(header, 1, 46, fpOutCD) == 46) {
+            offsetCD += 46;
+
+            /* Filename */
+            if (fnsize > 0) {
+              if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) {
+                offsetCD += fnsize;
+              } else {
+                err = Z_ERRNO;
+                break;
+              }
+            } else {
+              err = Z_STREAM_ERROR;
+              break;
+            }
+
+            /* Extra field */
+            if (extsize > 0) {
+              if (fwrite(extra, 1, extsize, fpOutCD) == extsize) {
+                offsetCD += extsize;
+              } else {
+                err = Z_ERRNO;
+                break;
+              }
+            }
+
+            /* Comment field */
+            if (comsize > 0) {
+              if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) {
+                offsetCD += comsize;
+              } else {
+                err = Z_ERRNO;
+                break;
+              }
+            }
+
+
+          } else {
+            err = Z_ERRNO;
+            break;
+          }
+        }
+
+        /* Success */
+        entries++;
+
+      } else {
+        break;
+      }
+    }
+
+    /* Final central directory  */
+    {
+      int entriesZip = entries;
+      char header[22];
+      char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools";
+      int comsize = (int) strlen(comment);
+      if (entriesZip > 0xffff) {
+        entriesZip = 0xffff;
+      }
+      WRITE_32(header, 0x06054b50);
+      WRITE_16(header + 4, 0);    /* disk # */
+      WRITE_16(header + 6, 0);    /* disk # */
+      WRITE_16(header + 8, entriesZip);   /* hack */
+      WRITE_16(header + 10, entriesZip);  /* hack */
+      WRITE_32(header + 12, offsetCD);    /* size of CD */
+      WRITE_32(header + 16, offset);      /* offset to CD */
+      WRITE_16(header + 20, comsize);     /* comment */
+
+      /* Header */
+      if (fwrite(header, 1, 22, fpOutCD) == 22) {
+
+        /* Comment field */
+        if (comsize > 0) {
+          if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) {
+            err = Z_ERRNO;
+          }
+        }
+
+      } else {
+        err = Z_ERRNO;
+      }
+    }
+
+    /* Final merge (file + central directory) */
+    fclose(fpOutCD);
+    if (err == Z_OK) {
+      fpOutCD = fopen(fileOutTmp, "rb");
+      if (fpOutCD != NULL) {
+        int nRead;
+        char buffer[8192];
+        while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) {
+          if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) {
+            err = Z_ERRNO;
+            break;
+          }
+        }
+        fclose(fpOutCD);
+      }
+    }
+
+    /* Close */
+    fclose(fpZip);
+    fclose(fpOut);
+
+    /* Wipe temporary file */
+    (void)remove(fileOutTmp);
+
+    /* Number of recovered entries */
+    if (err == Z_OK) {
+      if (nRecovered != NULL) {
+        *nRecovered = entries;
+      }
+      if (bytesRecovered != NULL) {
+        *bytesRecovered = totalBytes;
+      }
+    }
+  } else {
+    err = Z_STREAM_ERROR;
+  }
+  return err;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/mztools.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/mztools.h
new file mode 100644 (file)
index 0000000..a49a426
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+  Additional tools for Minizip
+  Code: Xavier Roche '2004
+  License: Same as ZLIB (www.gzip.org)
+*/
+
+#ifndef _zip_tools_H
+#define _zip_tools_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef _ZLIB_H
+#include "zlib.h"
+#endif
+
+#include "unzip.h"
+
+/* Repair a ZIP file (missing central directory)
+   file: file to recover
+   fileOut: output file after recovery
+   fileOutTmp: temporary file name used for recovery
+*/
+extern int ZEXPORT unzRepair(const char* file,
+                             const char* fileOut,
+                             const char* fileOutTmp,
+                             uLong* nRecovered,
+                             uLong* bytesRecovered);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/unzip.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/unzip.c
new file mode 100644 (file)
index 0000000..affad4b
--- /dev/null
@@ -0,0 +1,2125 @@
+/* unzip.c -- IO for uncompress .zip files using zlib
+   Version 1.1, February 14h, 2010
+   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications of Unzip for Zip64
+         Copyright (C) 2007-2008 Even Rouault
+
+         Modifications for Zip64 support on both zip and unzip
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+         For more info read MiniZip_info.txt
+
+
+  ------------------------------------------------------------------------------------
+  Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of
+  compatibility with older software. The following is from the original crypt.c.
+  Code woven in by Terry Thorsen 1/2003.
+
+  Copyright (c) 1990-2000 Info-ZIP.  All rights reserved.
+
+  See the accompanying file LICENSE, version 2000-Apr-09 or later
+  (the contents of which are also included in zip.h) for terms of use.
+  If, for some reason, all these files are missing, the Info-ZIP license
+  also may be found at:  ftp://ftp.info-zip.org/pub/infozip/license.html
+
+        crypt.c (full version) by Info-ZIP.      Last revised:  [see crypt.h]
+
+  The encryption/decryption parts of this source code (as opposed to the
+  non-echoing password parts) were originally written in Europe.  The
+  whole source package can be freely distributed, including from the USA.
+  (Prior to January 2000, re-export from the US was a violation of US law.)
+
+        This encryption code is a direct transcription of the algorithm from
+  Roger Schlafly, described by Phil Katz in the file appnote.txt.  This
+  file (appnote.txt) is distributed with the PKZIP program (even in the
+  version without encryption capabilities).
+
+        ------------------------------------------------------------------------------------
+
+        Changes in unzip.c
+
+        2007-2008 - Even Rouault - Addition of cpl_unzGetCurrentFileZStreamPos
+  2007-2008 - Even Rouault - Decoration of symbol names unz* -> cpl_unz*
+  2007-2008 - Even Rouault - Remove old C style function prototypes
+  2007-2008 - Even Rouault - Add unzip support for ZIP64
+
+        Copyright (C) 2007-2008 Even Rouault
+
+
+        Oct-2009 - Mathias Svensson - Removed cpl_* from symbol names (Even Rouault added them but since this is now moved to a new project (minizip64) I renamed them again).
+  Oct-2009 - Mathias Svensson - Fixed problem if uncompressed size was > 4G and compressed size was <4G
+                                should only read the compressed/uncompressed size from the Zip64 format if
+                                the size from normal header was 0xFFFFFFFF
+  Oct-2009 - Mathias Svensson - Applied some bug fixes from paches recived from Gilles Vollant
+        Oct-2009 - Mathias Svensson - Applied support to unzip files with compression mathod BZIP2 (bzip2 lib is required)
+                                Patch created by Daniel Borca
+
+  Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer
+
+  Copyright (C) 1998 - 2010 Gilles Vollant, Even Rouault, Mathias Svensson
+
+*/
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifndef NOUNCRYPT
+        #define NOUNCRYPT
+#endif
+
+#include "zlib.h"
+#include "unzip.h"
+
+#ifdef STDC
+#  include <stddef.h>
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+#ifdef NO_ERRNO_H
+    extern int errno;
+#else
+#   include <errno.h>
+#endif
+
+
+#ifndef local
+#  define local static
+#endif
+/* compile with -Dlocal if your debugger can't find static symbols */
+
+
+#ifndef CASESENSITIVITYDEFAULT_NO
+#  if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES)
+#    define CASESENSITIVITYDEFAULT_NO
+#  endif
+#endif
+
+
+#ifndef UNZ_BUFSIZE
+#define UNZ_BUFSIZE (16384)
+#endif
+
+#ifndef UNZ_MAXFILENAMEINZIP
+#define UNZ_MAXFILENAMEINZIP (256)
+#endif
+
+#ifndef ALLOC
+# define ALLOC(size) (malloc(size))
+#endif
+#ifndef TRYFREE
+# define TRYFREE(p) {if (p) free(p);}
+#endif
+
+#define SIZECENTRALDIRITEM (0x2e)
+#define SIZEZIPLOCALHEADER (0x1e)
+
+
+const char unz_copyright[] =
+   " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
+
+/* unz_file_info_interntal contain internal info about a file in zipfile*/
+typedef struct unz_file_info64_internal_s
+{
+    ZPOS64_T offset_curfile;/* relative offset of local header 8 bytes */
+} unz_file_info64_internal;
+
+
+/* file_in_zip_read_info_s contain internal information about a file in zipfile,
+    when reading and decompress it */
+typedef struct
+{
+    char  *read_buffer;         /* internal buffer for compressed data */
+    z_stream stream;            /* zLib stream structure for inflate */
+
+#ifdef HAVE_BZIP2
+    bz_stream bstream;          /* bzLib stream structure for bziped */
+#endif
+
+    ZPOS64_T pos_in_zipfile;       /* position in byte on the zipfile, for fseek*/
+    uLong stream_initialised;   /* flag set if stream structure is initialised*/
+
+    ZPOS64_T offset_local_extrafield;/* offset of the local extra field */
+    uInt  size_local_extrafield;/* size of the local extra field */
+    ZPOS64_T pos_local_extrafield;   /* position in the local extra field in read*/
+    ZPOS64_T total_out_64;
+
+    uLong crc32;                /* crc32 of all data uncompressed */
+    uLong crc32_wait;           /* crc32 we must obtain after decompress all */
+    ZPOS64_T rest_read_compressed; /* number of byte to be decompressed */
+    ZPOS64_T rest_read_uncompressed;/*number of byte to be obtained after decomp*/
+    zlib_filefunc64_32_def z_filefunc;
+    voidpf filestream;        /* io structore of the zipfile */
+    uLong compression_method;   /* compression method (0==store) */
+    ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
+    int   raw;
+} file_in_zip64_read_info_s;
+
+
+/* unz64_s contain internal information about the zipfile
+*/
+typedef struct
+{
+    zlib_filefunc64_32_def z_filefunc;
+    int is64bitOpenFunction;
+    voidpf filestream;        /* io structore of the zipfile */
+    unz_global_info64 gi;       /* public global information */
+    ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
+    ZPOS64_T num_file;             /* number of the current file in the zipfile*/
+    ZPOS64_T pos_in_central_dir;   /* pos of the current file in the central dir*/
+    ZPOS64_T current_file_ok;      /* flag about the usability of the current file*/
+    ZPOS64_T central_pos;          /* position of the beginning of the central dir*/
+
+    ZPOS64_T size_central_dir;     /* size of the central directory  */
+    ZPOS64_T offset_central_dir;   /* offset of start of central directory with
+                                   respect to the starting disk number */
+
+    unz_file_info64 cur_file_info; /* public info about the current file in zip*/
+    unz_file_info64_internal cur_file_info_internal; /* private info about it*/
+    file_in_zip64_read_info_s* pfile_in_zip_read; /* structure about the current
+                                        file if we are decompressing it */
+    int encrypted;
+
+    int isZip64;
+
+#    ifndef NOUNCRYPT
+    unsigned long keys[3];     /* keys defining the pseudo-random sequence */
+    const unsigned long* pcrc_32_tab;
+#    endif
+} unz64_s;
+
+
+#ifndef NOUNCRYPT
+#include "crypt.h"
+#endif
+
+/* ===========================================================================
+     Read a byte from a gz_stream; update next_in and avail_in. Return EOF
+   for end of file.
+   IN assertion: the stream s has been sucessfully opened for reading.
+*/
+
+
+local int unz64local_getByte OF((
+    const zlib_filefunc64_32_def* pzlib_filefunc_def,
+    voidpf filestream,
+    int *pi));
+
+local int unz64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi)
+{
+    unsigned char c;
+    int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1);
+    if (err==1)
+    {
+        *pi = (int)c;
+        return UNZ_OK;
+    }
+    else
+    {
+        if (ZERROR64(*pzlib_filefunc_def,filestream))
+            return UNZ_ERRNO;
+        else
+            return UNZ_EOF;
+    }
+}
+
+
+/* ===========================================================================
+   Reads a long in LSB order from the given gz_stream. Sets
+*/
+local int unz64local_getShort OF((
+    const zlib_filefunc64_32_def* pzlib_filefunc_def,
+    voidpf filestream,
+    uLong *pX));
+
+local int unz64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def,
+                             voidpf filestream,
+                             uLong *pX)
+{
+    uLong x ;
+    int i = 0;
+    int err;
+
+    err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x = (uLong)i;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((uLong)i)<<8;
+
+    if (err==UNZ_OK)
+        *pX = x;
+    else
+        *pX = 0;
+    return err;
+}
+
+local int unz64local_getLong OF((
+    const zlib_filefunc64_32_def* pzlib_filefunc_def,
+    voidpf filestream,
+    uLong *pX));
+
+local int unz64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def,
+                            voidpf filestream,
+                            uLong *pX)
+{
+    uLong x ;
+    int i = 0;
+    int err;
+
+    err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x = (uLong)i;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((uLong)i)<<8;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((uLong)i)<<16;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x += ((uLong)i)<<24;
+
+    if (err==UNZ_OK)
+        *pX = x;
+    else
+        *pX = 0;
+    return err;
+}
+
+local int unz64local_getLong64 OF((
+    const zlib_filefunc64_32_def* pzlib_filefunc_def,
+    voidpf filestream,
+    ZPOS64_T *pX));
+
+
+local int unz64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def,
+                            voidpf filestream,
+                            ZPOS64_T *pX)
+{
+    ZPOS64_T x ;
+    int i = 0;
+    int err;
+
+    err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x = (ZPOS64_T)i;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((ZPOS64_T)i)<<8;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((ZPOS64_T)i)<<16;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((ZPOS64_T)i)<<24;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((ZPOS64_T)i)<<32;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((ZPOS64_T)i)<<40;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((ZPOS64_T)i)<<48;
+
+    if (err==UNZ_OK)
+        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x |= ((ZPOS64_T)i)<<56;
+
+    if (err==UNZ_OK)
+        *pX = x;
+    else
+        *pX = 0;
+    return err;
+}
+
+/* My own strcmpi / strcasecmp */
+local int strcmpcasenosensitive_internal (const char* fileName1, const char* fileName2)
+{
+    for (;;)
+    {
+        char c1=*(fileName1++);
+        char c2=*(fileName2++);
+        if ((c1>='a') && (c1<='z'))
+            c1 -= 0x20;
+        if ((c2>='a') && (c2<='z'))
+            c2 -= 0x20;
+        if (c1=='\0')
+            return ((c2=='\0') ? 0 : -1);
+        if (c2=='\0')
+            return 1;
+        if (c1<c2)
+            return -1;
+        if (c1>c2)
+            return 1;
+    }
+}
+
+
+#ifdef  CASESENSITIVITYDEFAULT_NO
+#define CASESENSITIVITYDEFAULTVALUE 2
+#else
+#define CASESENSITIVITYDEFAULTVALUE 1
+#endif
+
+#ifndef STRCMPCASENOSENTIVEFUNCTION
+#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal
+#endif
+
+/*
+   Compare two filename (fileName1,fileName2).
+   If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
+   If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
+                                                                or strcasecmp)
+   If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
+        (like 1 on Unix, 2 on Windows)
+
+*/
+extern int ZEXPORT unzStringFileNameCompare (const char*  fileName1,
+                                                 const char*  fileName2,
+                                                 int iCaseSensitivity)
+
+{
+    if (iCaseSensitivity==0)
+        iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE;
+
+    if (iCaseSensitivity==1)
+        return strcmp(fileName1,fileName2);
+
+    return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2);
+}
+
+#ifndef BUFREADCOMMENT
+#define BUFREADCOMMENT (0x400)
+#endif
+
+/*
+  Locate the Central directory of a zipfile (at the end, just before
+    the global comment)
+*/
+local ZPOS64_T unz64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
+local ZPOS64_T unz64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
+{
+    unsigned char* buf;
+    ZPOS64_T uSizeFile;
+    ZPOS64_T uBackRead;
+    ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
+    ZPOS64_T uPosFound=0;
+
+    if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
+        return 0;
+
+
+    uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
+
+    if (uMaxBack>uSizeFile)
+        uMaxBack = uSizeFile;
+
+    buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
+    if (buf==NULL)
+        return 0;
+
+    uBackRead = 4;
+    while (uBackRead<uMaxBack)
+    {
+        uLong uReadSize;
+        ZPOS64_T uReadPos ;
+        int i;
+        if (uBackRead+BUFREADCOMMENT>uMaxBack)
+            uBackRead = uMaxBack;
+        else
+            uBackRead+=BUFREADCOMMENT;
+        uReadPos = uSizeFile-uBackRead ;
+
+        uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
+                     (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
+        if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+            break;
+
+        if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
+            break;
+
+        for (i=(int)uReadSize-3; (i--)>0;)
+            if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
+                ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
+            {
+                uPosFound = uReadPos+i;
+                break;
+            }
+
+        if (uPosFound!=0)
+            break;
+    }
+    TRYFREE(buf);
+    return uPosFound;
+}
+
+
+/*
+  Locate the Central directory 64 of a zipfile (at the end, just before
+    the global comment)
+*/
+local ZPOS64_T unz64local_SearchCentralDir64 OF((
+    const zlib_filefunc64_32_def* pzlib_filefunc_def,
+    voidpf filestream));
+
+local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def,
+                                      voidpf filestream)
+{
+    unsigned char* buf;
+    ZPOS64_T uSizeFile;
+    ZPOS64_T uBackRead;
+    ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
+    ZPOS64_T uPosFound=0;
+    uLong uL;
+                ZPOS64_T relativeOffset;
+
+    if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
+        return 0;
+
+
+    uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
+
+    if (uMaxBack>uSizeFile)
+        uMaxBack = uSizeFile;
+
+    buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
+    if (buf==NULL)
+        return 0;
+
+    uBackRead = 4;
+    while (uBackRead<uMaxBack)
+    {
+        uLong uReadSize;
+        ZPOS64_T uReadPos;
+        int i;
+        if (uBackRead+BUFREADCOMMENT>uMaxBack)
+            uBackRead = uMaxBack;
+        else
+            uBackRead+=BUFREADCOMMENT;
+        uReadPos = uSizeFile-uBackRead ;
+
+        uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
+                     (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
+        if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+            break;
+
+        if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
+            break;
+
+        for (i=(int)uReadSize-3; (i--)>0;)
+            if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
+                ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07))
+            {
+                uPosFound = uReadPos+i;
+                break;
+            }
+
+        if (uPosFound!=0)
+            break;
+    }
+    TRYFREE(buf);
+    if (uPosFound == 0)
+        return 0;
+
+    /* Zip64 end of central directory locator */
+    if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0)
+        return 0;
+
+    /* the signature, already checked */
+    if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
+        return 0;
+
+    /* number of the disk with the start of the zip64 end of  central directory */
+    if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
+        return 0;
+    if (uL != 0)
+        return 0;
+
+    /* relative offset of the zip64 end of central directory record */
+    if (unz64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=UNZ_OK)
+        return 0;
+
+    /* total number of disks */
+    if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
+        return 0;
+    if (uL != 1)
+        return 0;
+
+    /* Goto end of central directory record */
+    if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0)
+        return 0;
+
+     /* the signature */
+    if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
+        return 0;
+
+    if (uL != 0x06064b50)
+        return 0;
+
+    return relativeOffset;
+}
+
+/*
+  Open a Zip file. path contain the full pathname (by example,
+     on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer
+     "zlib/zlib114.zip".
+     If the zipfile cannot be opened (file doesn't exist or in not valid), the
+       return value is NULL.
+     Else, the return value is a unzFile Handle, usable with other function
+       of this unzip package.
+*/
+local unzFile unzOpenInternal (const void *path,
+                               zlib_filefunc64_32_def* pzlib_filefunc64_32_def,
+                               int is64bitOpenFunction)
+{
+    unz64_s us;
+    unz64_s *s;
+    ZPOS64_T central_pos;
+    uLong   uL;
+
+    uLong number_disk;          /* number of the current dist, used for
+                                   spaning ZIP, unsupported, always 0*/
+    uLong number_disk_with_CD;  /* number the the disk with central dir, used
+                                   for spaning ZIP, unsupported, always 0*/
+    ZPOS64_T number_entry_CD;      /* total number of entries in
+                                   the central dir
+                                   (same than number_entry on nospan) */
+
+    int err=UNZ_OK;
+
+    if (unz_copyright[0]!=' ')
+        return NULL;
+
+    us.z_filefunc.zseek32_file = NULL;
+    us.z_filefunc.ztell32_file = NULL;
+    if (pzlib_filefunc64_32_def==NULL)
+        fill_fopen64_filefunc(&us.z_filefunc.zfile_func64);
+    else
+        us.z_filefunc = *pzlib_filefunc64_32_def;
+    us.is64bitOpenFunction = is64bitOpenFunction;
+
+
+
+    us.filestream = ZOPEN64(us.z_filefunc,
+                                                 path,
+                                                 ZLIB_FILEFUNC_MODE_READ |
+                                                 ZLIB_FILEFUNC_MODE_EXISTING);
+    if (us.filestream==NULL)
+        return NULL;
+
+    central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream);
+    if (central_pos)
+    {
+        uLong uS;
+        ZPOS64_T uL64;
+
+        us.isZip64 = 1;
+
+        if (ZSEEK64(us.z_filefunc, us.filestream,
+                                      central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+        err=UNZ_ERRNO;
+
+        /* the signature, already checked */
+        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* size of zip64 end of central directory record */
+        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* version made by */
+        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* version needed to extract */
+        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* number of this disk */
+        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* number of the disk with the start of the central directory */
+        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* total number of entries in the central directory on this disk */
+        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* total number of entries in the central directory */
+        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        if ((number_entry_CD!=us.gi.number_entry) ||
+            (number_disk_with_CD!=0) ||
+            (number_disk!=0))
+            err=UNZ_BADZIPFILE;
+
+        /* size of the central directory */
+        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* offset of start of central directory with respect to the
+          starting disk number */
+        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        us.gi.size_comment = 0;
+    }
+    else
+    {
+        central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream);
+        if (central_pos==0)
+            err=UNZ_ERRNO;
+
+        us.isZip64 = 0;
+
+        if (ZSEEK64(us.z_filefunc, us.filestream,
+                                        central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+            err=UNZ_ERRNO;
+
+        /* the signature, already checked */
+        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* number of this disk */
+        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* number of the disk with the start of the central directory */
+        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
+            err=UNZ_ERRNO;
+
+        /* total number of entries in the central dir on this disk */
+        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
+            err=UNZ_ERRNO;
+        us.gi.number_entry = uL;
+
+        /* total number of entries in the central dir */
+        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
+            err=UNZ_ERRNO;
+        number_entry_CD = uL;
+
+        if ((number_entry_CD!=us.gi.number_entry) ||
+            (number_disk_with_CD!=0) ||
+            (number_disk!=0))
+            err=UNZ_BADZIPFILE;
+
+        /* size of the central directory */
+        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
+            err=UNZ_ERRNO;
+        us.size_central_dir = uL;
+
+        /* offset of start of central directory with respect to the
+            starting disk number */
+        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
+            err=UNZ_ERRNO;
+        us.offset_central_dir = uL;
+
+        /* zipfile comment length */
+        if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK)
+            err=UNZ_ERRNO;
+    }
+
+    if ((central_pos<us.offset_central_dir+us.size_central_dir) &&
+        (err==UNZ_OK))
+        err=UNZ_BADZIPFILE;
+
+    if (err!=UNZ_OK)
+    {
+        ZCLOSE64(us.z_filefunc, us.filestream);
+        return NULL;
+    }
+
+    us.byte_before_the_zipfile = central_pos -
+                            (us.offset_central_dir+us.size_central_dir);
+    us.central_pos = central_pos;
+    us.pfile_in_zip_read = NULL;
+    us.encrypted = 0;
+
+
+    s=(unz64_s*)ALLOC(sizeof(unz64_s));
+    if( s != NULL)
+    {
+        *s=us;
+        unzGoToFirstFile((unzFile)s);
+    }
+    return (unzFile)s;
+}
+
+
+extern unzFile ZEXPORT unzOpen2 (const char *path,
+                                        zlib_filefunc_def* pzlib_filefunc32_def)
+{
+    if (pzlib_filefunc32_def != NULL)
+    {
+        zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
+        fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def);
+        return unzOpenInternal(path, &zlib_filefunc64_32_def_fill, 0);
+    }
+    else
+        return unzOpenInternal(path, NULL, 0);
+}
+
+extern unzFile ZEXPORT unzOpen2_64 (const void *path,
+                                     zlib_filefunc64_def* pzlib_filefunc_def)
+{
+    if (pzlib_filefunc_def != NULL)
+    {
+        zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
+        zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def;
+        zlib_filefunc64_32_def_fill.ztell32_file = NULL;
+        zlib_filefunc64_32_def_fill.zseek32_file = NULL;
+        return unzOpenInternal(path, &zlib_filefunc64_32_def_fill, 1);
+    }
+    else
+        return unzOpenInternal(path, NULL, 1);
+}
+
+extern unzFile ZEXPORT unzOpen (const char *path)
+{
+    return unzOpenInternal(path, NULL, 0);
+}
+
+extern unzFile ZEXPORT unzOpen64 (const void *path)
+{
+    return unzOpenInternal(path, NULL, 1);
+}
+
+/*
+  Close a ZipFile opened with unzipOpen.
+  If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
+    these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
+  return UNZ_OK if there is no problem. */
+extern int ZEXPORT unzClose (unzFile file)
+{
+    unz64_s* s;
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+
+    if (s->pfile_in_zip_read!=NULL)
+        unzCloseCurrentFile(file);
+
+    ZCLOSE64(s->z_filefunc, s->filestream);
+    TRYFREE(s);
+    return UNZ_OK;
+}
+
+
+/*
+  Write info about the ZipFile in the *pglobal_info structure.
+  No preparation of the structure is needed
+  return UNZ_OK if there is no problem. */
+extern int ZEXPORT unzGetGlobalInfo64 (unzFile file, unz_global_info64* pglobal_info)
+{
+    unz64_s* s;
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    *pglobal_info=s->gi;
+    return UNZ_OK;
+}
+
+extern int ZEXPORT unzGetGlobalInfo (unzFile file, unz_global_info* pglobal_info32)
+{
+    unz64_s* s;
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    /* to do : check if number_entry is not truncated */
+    pglobal_info32->number_entry = (uLong)s->gi.number_entry;
+    pglobal_info32->size_comment = s->gi.size_comment;
+    return UNZ_OK;
+}
+/*
+   Translate date/time from Dos format to tm_unz (readable more easilty)
+*/
+local void unz64local_DosDateToTmuDate (ZPOS64_T ulDosDate, tm_unz* ptm)
+{
+    ZPOS64_T uDate;
+    uDate = (ZPOS64_T)(ulDosDate>>16);
+    ptm->tm_mday = (uInt)(uDate&0x1f) ;
+    ptm->tm_mon =  (uInt)((((uDate)&0x1E0)/0x20)-1) ;
+    ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
+
+    ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
+    ptm->tm_min =  (uInt) ((ulDosDate&0x7E0)/0x20) ;
+    ptm->tm_sec =  (uInt) (2*(ulDosDate&0x1f)) ;
+}
+
+/*
+  Get Info about the current file in the zipfile, with internal only info
+*/
+local int unz64local_GetCurrentFileInfoInternal OF((unzFile file,
+                                                  unz_file_info64 *pfile_info,
+                                                  unz_file_info64_internal
+                                                  *pfile_info_internal,
+                                                  char *szFileName,
+                                                  uLong fileNameBufferSize,
+                                                  void *extraField,
+                                                  uLong extraFieldBufferSize,
+                                                  char *szComment,
+                                                  uLong commentBufferSize));
+
+local int unz64local_GetCurrentFileInfoInternal (unzFile file,
+                                                  unz_file_info64 *pfile_info,
+                                                  unz_file_info64_internal
+                                                  *pfile_info_internal,
+                                                  char *szFileName,
+                                                  uLong fileNameBufferSize,
+                                                  void *extraField,
+                                                  uLong extraFieldBufferSize,
+                                                  char *szComment,
+                                                  uLong commentBufferSize)
+{
+    unz64_s* s;
+    unz_file_info64 file_info;
+    unz_file_info64_internal file_info_internal;
+    int err=UNZ_OK;
+    uLong uMagic;
+    long lSeek=0;
+    uLong uL;
+
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    if (ZSEEK64(s->z_filefunc, s->filestream,
+              s->pos_in_central_dir+s->byte_before_the_zipfile,
+              ZLIB_FILEFUNC_SEEK_SET)!=0)
+        err=UNZ_ERRNO;
+
+
+    /* we check the magic */
+    if (err==UNZ_OK)
+    {
+        if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK)
+            err=UNZ_ERRNO;
+        else if (uMagic!=0x02014b50)
+            err=UNZ_BADZIPFILE;
+    }
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    unz64local_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK)
+        err=UNZ_ERRNO;
+    file_info.compressed_size = uL;
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK)
+        err=UNZ_ERRNO;
+    file_info.uncompressed_size = uL;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+                // relative offset of local header
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK)
+        err=UNZ_ERRNO;
+    file_info_internal.offset_curfile = uL;
+
+    lSeek+=file_info.size_filename;
+    if ((err==UNZ_OK) && (szFileName!=NULL))
+    {
+        uLong uSizeRead ;
+        if (file_info.size_filename<fileNameBufferSize)
+        {
+            *(szFileName+file_info.size_filename)='\0';
+            uSizeRead = file_info.size_filename;
+        }
+        else
+            uSizeRead = fileNameBufferSize;
+
+        if ((file_info.size_filename>0) && (fileNameBufferSize>0))
+            if (ZREAD64(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead)
+                err=UNZ_ERRNO;
+        lSeek -= uSizeRead;
+    }
+
+    // Read extrafield
+    if ((err==UNZ_OK) && (extraField!=NULL))
+    {
+        ZPOS64_T uSizeRead ;
+        if (file_info.size_file_extra<extraFieldBufferSize)
+            uSizeRead = file_info.size_file_extra;
+        else
+            uSizeRead = extraFieldBufferSize;
+
+        if (lSeek!=0)
+        {
+            if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0)
+                lSeek=0;
+            else
+                err=UNZ_ERRNO;
+        }
+
+        if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0))
+            if (ZREAD64(s->z_filefunc, s->filestream,extraField,(uLong)uSizeRead)!=uSizeRead)
+                err=UNZ_ERRNO;
+
+        lSeek += file_info.size_file_extra - (uLong)uSizeRead;
+    }
+    else
+        lSeek += file_info.size_file_extra;
+
+
+    if ((err==UNZ_OK) && (file_info.size_file_extra != 0))
+    {
+                                uLong acc = 0;
+
+        // since lSeek now points to after the extra field we need to move back
+        lSeek -= file_info.size_file_extra;
+
+        if (lSeek!=0)
+        {
+            if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0)
+                lSeek=0;
+            else
+                err=UNZ_ERRNO;
+        }
+
+        while(acc < file_info.size_file_extra)
+        {
+            uLong headerId;
+                                                uLong dataSize;
+
+            if (unz64local_getShort(&s->z_filefunc, s->filestream,&headerId) != UNZ_OK)
+                err=UNZ_ERRNO;
+
+            if (unz64local_getShort(&s->z_filefunc, s->filestream,&dataSize) != UNZ_OK)
+                err=UNZ_ERRNO;
+
+            /* ZIP64 extra fields */
+            if (headerId == 0x0001)
+            {
+                                                        uLong uL;
+
+                                                                if(file_info.uncompressed_size == MAXU32)
+                                                                {
+                                                                        if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK)
+                                                                                        err=UNZ_ERRNO;
+                                                                }
+
+                                                                if(file_info.compressed_size == MAXU32)
+                                                                {
+                                                                        if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK)
+                                                                                  err=UNZ_ERRNO;
+                                                                }
+
+                                                                if(file_info_internal.offset_curfile == MAXU32)
+                                                                {
+                                                                        /* Relative Header offset */
+                                                                        if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK)
+                                                                                err=UNZ_ERRNO;
+                                                                }
+
+                                                                if(file_info.disk_num_start == MAXU32)
+                                                                {
+                                                                        /* Disk Start Number */
+                                                                        if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK)
+                                                                                err=UNZ_ERRNO;
+                                                                }
+
+            }
+            else
+            {
+                if (ZSEEK64(s->z_filefunc, s->filestream,dataSize,ZLIB_FILEFUNC_SEEK_CUR)!=0)
+                    err=UNZ_ERRNO;
+            }
+
+            acc += 2 + 2 + dataSize;
+        }
+    }
+
+    if ((err==UNZ_OK) && (szComment!=NULL))
+    {
+        uLong uSizeRead ;
+        if (file_info.size_file_comment<commentBufferSize)
+        {
+            *(szComment+file_info.size_file_comment)='\0';
+            uSizeRead = file_info.size_file_comment;
+        }
+        else
+            uSizeRead = commentBufferSize;
+
+        if (lSeek!=0)
+        {
+            if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0)
+                lSeek=0;
+            else
+                err=UNZ_ERRNO;
+        }
+
+        if ((file_info.size_file_comment>0) && (commentBufferSize>0))
+            if (ZREAD64(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead)
+                err=UNZ_ERRNO;
+        lSeek+=file_info.size_file_comment - uSizeRead;
+    }
+    else
+        lSeek+=file_info.size_file_comment;
+
+
+    if ((err==UNZ_OK) && (pfile_info!=NULL))
+        *pfile_info=file_info;
+
+    if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
+        *pfile_info_internal=file_info_internal;
+
+    return err;
+}
+
+
+
+/*
+  Write info about the ZipFile in the *pglobal_info structure.
+  No preparation of the structure is needed
+  return UNZ_OK if there is no problem.
+*/
+extern int ZEXPORT unzGetCurrentFileInfo64 (unzFile file,
+                                          unz_file_info64 * pfile_info,
+                                          char * szFileName, uLong fileNameBufferSize,
+                                          void *extraField, uLong extraFieldBufferSize,
+                                          char* szComment,  uLong commentBufferSize)
+{
+    return unz64local_GetCurrentFileInfoInternal(file,pfile_info,NULL,
+                                                szFileName,fileNameBufferSize,
+                                                extraField,extraFieldBufferSize,
+                                                szComment,commentBufferSize);
+}
+
+extern int ZEXPORT unzGetCurrentFileInfo (unzFile file,
+                                          unz_file_info * pfile_info,
+                                          char * szFileName, uLong fileNameBufferSize,
+                                          void *extraField, uLong extraFieldBufferSize,
+                                          char* szComment,  uLong commentBufferSize)
+{
+    int err;
+    unz_file_info64 file_info64;
+    err = unz64local_GetCurrentFileInfoInternal(file,&file_info64,NULL,
+                                                szFileName,fileNameBufferSize,
+                                                extraField,extraFieldBufferSize,
+                                                szComment,commentBufferSize);
+    if ((err==UNZ_OK) && (pfile_info != NULL))
+    {
+        pfile_info->version = file_info64.version;
+        pfile_info->version_needed = file_info64.version_needed;
+        pfile_info->flag = file_info64.flag;
+        pfile_info->compression_method = file_info64.compression_method;
+        pfile_info->dosDate = file_info64.dosDate;
+        pfile_info->crc = file_info64.crc;
+
+        pfile_info->size_filename = file_info64.size_filename;
+        pfile_info->size_file_extra = file_info64.size_file_extra;
+        pfile_info->size_file_comment = file_info64.size_file_comment;
+
+        pfile_info->disk_num_start = file_info64.disk_num_start;
+        pfile_info->internal_fa = file_info64.internal_fa;
+        pfile_info->external_fa = file_info64.external_fa;
+
+        pfile_info->tmu_date = file_info64.tmu_date,
+
+
+        pfile_info->compressed_size = (uLong)file_info64.compressed_size;
+        pfile_info->uncompressed_size = (uLong)file_info64.uncompressed_size;
+
+    }
+    return err;
+}
+/*
+  Set the current file of the zipfile to the first file.
+  return UNZ_OK if there is no problem
+*/
+extern int ZEXPORT unzGoToFirstFile (unzFile file)
+{
+    int err=UNZ_OK;
+    unz64_s* s;
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    s->pos_in_central_dir=s->offset_central_dir;
+    s->num_file=0;
+    err=unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+                                             &s->cur_file_info_internal,
+                                             NULL,0,NULL,0,NULL,0);
+    s->current_file_ok = (err == UNZ_OK);
+    return err;
+}
+
+/*
+  Set the current file of the zipfile to the next file.
+  return UNZ_OK if there is no problem
+  return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
+*/
+extern int ZEXPORT unzGoToNextFile (unzFile  file)
+{
+    unz64_s* s;
+    int err;
+
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    if (!s->current_file_ok)
+        return UNZ_END_OF_LIST_OF_FILE;
+    if (s->gi.number_entry != 0xffff)    /* 2^16 files overflow hack */
+      if (s->num_file+1==s->gi.number_entry)
+        return UNZ_END_OF_LIST_OF_FILE;
+
+    s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
+            s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
+    s->num_file++;
+    err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+                                               &s->cur_file_info_internal,
+                                               NULL,0,NULL,0,NULL,0);
+    s->current_file_ok = (err == UNZ_OK);
+    return err;
+}
+
+
+/*
+  Try locate the file szFileName in the zipfile.
+  For the iCaseSensitivity signification, see unzipStringFileNameCompare
+
+  return value :
+  UNZ_OK if the file is found. It becomes the current file.
+  UNZ_END_OF_LIST_OF_FILE if the file is not found
+*/
+extern int ZEXPORT unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity)
+{
+    unz64_s* s;
+    int err;
+
+    /* We remember the 'current' position in the file so that we can jump
+     * back there if we fail.
+     */
+    unz_file_info64 cur_file_infoSaved;
+    unz_file_info64_internal cur_file_info_internalSaved;
+    ZPOS64_T num_fileSaved;
+    ZPOS64_T pos_in_central_dirSaved;
+
+
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+
+    if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
+        return UNZ_PARAMERROR;
+
+    s=(unz64_s*)file;
+    if (!s->current_file_ok)
+        return UNZ_END_OF_LIST_OF_FILE;
+
+    /* Save the current state */
+    num_fileSaved = s->num_file;
+    pos_in_central_dirSaved = s->pos_in_central_dir;
+    cur_file_infoSaved = s->cur_file_info;
+    cur_file_info_internalSaved = s->cur_file_info_internal;
+
+    err = unzGoToFirstFile(file);
+
+    while (err == UNZ_OK)
+    {
+        char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
+        err = unzGetCurrentFileInfo64(file,NULL,
+                                    szCurrentFileName,sizeof(szCurrentFileName)-1,
+                                    NULL,0,NULL,0);
+        if (err == UNZ_OK)
+        {
+            if (unzStringFileNameCompare(szCurrentFileName,
+                                            szFileName,iCaseSensitivity)==0)
+                return UNZ_OK;
+            err = unzGoToNextFile(file);
+        }
+    }
+
+    /* We failed, so restore the state of the 'current file' to where we
+     * were.
+     */
+    s->num_file = num_fileSaved ;
+    s->pos_in_central_dir = pos_in_central_dirSaved ;
+    s->cur_file_info = cur_file_infoSaved;
+    s->cur_file_info_internal = cur_file_info_internalSaved;
+    return err;
+}
+
+
+/*
+///////////////////////////////////////////
+// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net)
+// I need random access
+//
+// Further optimization could be realized by adding an ability
+// to cache the directory in memory. The goal being a single
+// comprehensive file read to put the file I need in a memory.
+*/
+
+/*
+typedef struct unz_file_pos_s
+{
+    ZPOS64_T pos_in_zip_directory;   // offset in file
+    ZPOS64_T num_of_file;            // # of file
+} unz_file_pos;
+*/
+
+extern int ZEXPORT unzGetFilePos64(unzFile file, unz64_file_pos*  file_pos)
+{
+    unz64_s* s;
+
+    if (file==NULL || file_pos==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    if (!s->current_file_ok)
+        return UNZ_END_OF_LIST_OF_FILE;
+
+    file_pos->pos_in_zip_directory  = s->pos_in_central_dir;
+    file_pos->num_of_file           = s->num_file;
+
+    return UNZ_OK;
+}
+
+extern int ZEXPORT unzGetFilePos(
+    unzFile file,
+    unz_file_pos* file_pos)
+{
+    unz64_file_pos file_pos64;
+    int err = unzGetFilePos64(file,&file_pos64);
+    if (err==UNZ_OK)
+    {
+        file_pos->pos_in_zip_directory = (uLong)file_pos64.pos_in_zip_directory;
+        file_pos->num_of_file = (uLong)file_pos64.num_of_file;
+    }
+    return err;
+}
+
+extern int ZEXPORT unzGoToFilePos64(unzFile file, const unz64_file_pos* file_pos)
+{
+    unz64_s* s;
+    int err;
+
+    if (file==NULL || file_pos==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+
+    /* jump to the right spot */
+    s->pos_in_central_dir = file_pos->pos_in_zip_directory;
+    s->num_file           = file_pos->num_of_file;
+
+    /* set the current file */
+    err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+                                               &s->cur_file_info_internal,
+                                               NULL,0,NULL,0,NULL,0);
+    /* return results */
+    s->current_file_ok = (err == UNZ_OK);
+    return err;
+}
+
+extern int ZEXPORT unzGoToFilePos(
+    unzFile file,
+    unz_file_pos* file_pos)
+{
+    unz64_file_pos file_pos64;
+    if (file_pos == NULL)
+        return UNZ_PARAMERROR;
+
+    file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory;
+    file_pos64.num_of_file = file_pos->num_of_file;
+    return unzGoToFilePos64(file,&file_pos64);
+}
+
+/*
+// Unzip Helper Functions - should be here?
+///////////////////////////////////////////
+*/
+
+/*
+  Read the local header of the current zipfile
+  Check the coherency of the local header and info in the end of central
+        directory about this file
+  store in *piSizeVar the size of extra info in local header
+        (filename and size of extra field data)
+*/
+local int unz64local_CheckCurrentFileCoherencyHeader (unz64_s* s, uInt* piSizeVar,
+                                                    ZPOS64_T * poffset_local_extrafield,
+                                                    uInt  * psize_local_extrafield)
+{
+    uLong uMagic,uData,uFlags;
+    uLong size_filename;
+    uLong size_extra_field;
+    int err=UNZ_OK;
+
+    *piSizeVar = 0;
+    *poffset_local_extrafield = 0;
+    *psize_local_extrafield = 0;
+
+    if (ZSEEK64(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile +
+                                s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0)
+        return UNZ_ERRNO;
+
+
+    if (err==UNZ_OK)
+    {
+        if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK)
+            err=UNZ_ERRNO;
+        else if (uMagic!=0x04034b50)
+            err=UNZ_BADZIPFILE;
+    }
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK)
+        err=UNZ_ERRNO;
+/*
+    else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
+        err=UNZ_BADZIPFILE;
+*/
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK)
+        err=UNZ_ERRNO;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK)
+        err=UNZ_ERRNO;
+    else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
+        err=UNZ_BADZIPFILE;
+
+    if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
+/* #ifdef HAVE_BZIP2 */
+                         (s->cur_file_info.compression_method!=Z_BZIP2ED) &&
+/* #endif */
+                         (s->cur_file_info.compression_method!=Z_DEFLATED))
+        err=UNZ_BADZIPFILE;
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */
+        err=UNZ_ERRNO;
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */
+        err=UNZ_ERRNO;
+    else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0))
+        err=UNZ_BADZIPFILE;
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */
+        err=UNZ_ERRNO;
+    else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0))
+        err=UNZ_BADZIPFILE;
+
+    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */
+        err=UNZ_ERRNO;
+    else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0))
+        err=UNZ_BADZIPFILE;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK)
+        err=UNZ_ERRNO;
+    else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
+        err=UNZ_BADZIPFILE;
+
+    *piSizeVar += (uInt)size_filename;
+
+    if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK)
+        err=UNZ_ERRNO;
+    *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
+                                    SIZEZIPLOCALHEADER + size_filename;
+    *psize_local_extrafield = (uInt)size_extra_field;
+
+    *piSizeVar += (uInt)size_extra_field;
+
+    return err;
+}
+
+/*
+  Open for reading data the current file in the zipfile.
+  If there is no error and the file is opened, the return value is UNZ_OK.
+*/
+extern int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method,
+                                            int* level, int raw, const char* password)
+{
+    int err=UNZ_OK;
+    uInt iSizeVar;
+    unz64_s* s;
+    file_in_zip64_read_info_s* pfile_in_zip_read_info;
+    ZPOS64_T offset_local_extrafield;  /* offset of the local extra field */
+    uInt  size_local_extrafield;    /* size of the local extra field */
+#    ifndef NOUNCRYPT
+    char source[12];
+#    else
+    if (password != NULL)
+        return UNZ_PARAMERROR;
+#    endif
+
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    if (!s->current_file_ok)
+        return UNZ_PARAMERROR;
+
+    if (s->pfile_in_zip_read != NULL)
+        unzCloseCurrentFile(file);
+
+    if (unz64local_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
+        return UNZ_BADZIPFILE;
+
+    pfile_in_zip_read_info = (file_in_zip64_read_info_s*)ALLOC(sizeof(file_in_zip64_read_info_s));
+    if (pfile_in_zip_read_info==NULL)
+        return UNZ_INTERNALERROR;
+
+    pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE);
+    pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
+    pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
+    pfile_in_zip_read_info->pos_local_extrafield=0;
+    pfile_in_zip_read_info->raw=raw;
+
+    if (pfile_in_zip_read_info->read_buffer==NULL)
+    {
+        TRYFREE(pfile_in_zip_read_info);
+        return UNZ_INTERNALERROR;
+    }
+
+    pfile_in_zip_read_info->stream_initialised=0;
+
+    if (method!=NULL)
+        *method = (int)s->cur_file_info.compression_method;
+
+    if (level!=NULL)
+    {
+        *level = 6;
+        switch (s->cur_file_info.flag & 0x06)
+        {
+          case 6 : *level = 1; break;
+          case 4 : *level = 2; break;
+          case 2 : *level = 9; break;
+        }
+    }
+
+    if ((s->cur_file_info.compression_method!=0) &&
+/* #ifdef HAVE_BZIP2 */
+        (s->cur_file_info.compression_method!=Z_BZIP2ED) &&
+/* #endif */
+        (s->cur_file_info.compression_method!=Z_DEFLATED))
+
+        err=UNZ_BADZIPFILE;
+
+    pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
+    pfile_in_zip_read_info->crc32=0;
+    pfile_in_zip_read_info->total_out_64=0;
+    pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method;
+    pfile_in_zip_read_info->filestream=s->filestream;
+    pfile_in_zip_read_info->z_filefunc=s->z_filefunc;
+    pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
+
+    pfile_in_zip_read_info->stream.total_out = 0;
+
+    if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw))
+    {
+#ifdef HAVE_BZIP2
+      pfile_in_zip_read_info->bstream.bzalloc = (void *(*) (void *, int, int))0;
+      pfile_in_zip_read_info->bstream.bzfree = (free_func)0;
+      pfile_in_zip_read_info->bstream.opaque = (voidpf)0;
+      pfile_in_zip_read_info->bstream.state = (voidpf)0;
+
+      pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
+      pfile_in_zip_read_info->stream.zfree = (free_func)0;
+      pfile_in_zip_read_info->stream.opaque = (voidpf)0;
+      pfile_in_zip_read_info->stream.next_in = (voidpf)0;
+      pfile_in_zip_read_info->stream.avail_in = 0;
+
+      err=BZ2_bzDecompressInit(&pfile_in_zip_read_info->bstream, 0, 0);
+      if (err == Z_OK)
+        pfile_in_zip_read_info->stream_initialised=Z_BZIP2ED;
+      else
+      {
+        TRYFREE(pfile_in_zip_read_info);
+        return err;
+      }
+#else
+      pfile_in_zip_read_info->raw=1;
+#endif
+    }
+    else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw))
+    {
+      pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
+      pfile_in_zip_read_info->stream.zfree = (free_func)0;
+      pfile_in_zip_read_info->stream.opaque = (voidpf)0;
+      pfile_in_zip_read_info->stream.next_in = 0;
+      pfile_in_zip_read_info->stream.avail_in = 0;
+
+      err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
+      if (err == Z_OK)
+        pfile_in_zip_read_info->stream_initialised=Z_DEFLATED;
+      else
+      {
+        TRYFREE(pfile_in_zip_read_info);
+        return err;
+      }
+        /* windowBits is passed < 0 to tell that there is no zlib header.
+         * Note that in this case inflate *requires* an extra "dummy" byte
+         * after the compressed stream in order to complete decompression and
+         * return Z_STREAM_END.
+         * In unzip, i don't wait absolutely Z_STREAM_END because I known the
+         * size of both compressed and uncompressed data
+         */
+    }
+    pfile_in_zip_read_info->rest_read_compressed =
+            s->cur_file_info.compressed_size ;
+    pfile_in_zip_read_info->rest_read_uncompressed =
+            s->cur_file_info.uncompressed_size ;
+
+
+    pfile_in_zip_read_info->pos_in_zipfile =
+            s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER +
+              iSizeVar;
+
+    pfile_in_zip_read_info->stream.avail_in = (uInt)0;
+
+    s->pfile_in_zip_read = pfile_in_zip_read_info;
+                s->encrypted = 0;
+
+#    ifndef NOUNCRYPT
+    if (password != NULL)
+    {
+        int i;
+        s->pcrc_32_tab = get_crc_table();
+        init_keys(password,s->keys,s->pcrc_32_tab);
+        if (ZSEEK64(s->z_filefunc, s->filestream,
+                  s->pfile_in_zip_read->pos_in_zipfile +
+                     s->pfile_in_zip_read->byte_before_the_zipfile,
+                  SEEK_SET)!=0)
+            return UNZ_INTERNALERROR;
+        if(ZREAD64(s->z_filefunc, s->filestream,source, 12)<12)
+            return UNZ_INTERNALERROR;
+
+        for (i = 0; i<12; i++)
+            zdecode(s->keys,s->pcrc_32_tab,source[i]);
+
+        s->pfile_in_zip_read->pos_in_zipfile+=12;
+        s->encrypted=1;
+    }
+#    endif
+
+
+    return UNZ_OK;
+}
+
+extern int ZEXPORT unzOpenCurrentFile (unzFile file)
+{
+    return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL);
+}
+
+extern int ZEXPORT unzOpenCurrentFilePassword (unzFile file, const char*  password)
+{
+    return unzOpenCurrentFile3(file, NULL, NULL, 0, password);
+}
+
+extern int ZEXPORT unzOpenCurrentFile2 (unzFile file, int* method, int* level, int raw)
+{
+    return unzOpenCurrentFile3(file, method, level, raw, NULL);
+}
+
+/** Addition for GDAL : START */
+
+extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64( unzFile file)
+{
+    unz64_s* s;
+    file_in_zip64_read_info_s* pfile_in_zip_read_info;
+    s=(unz64_s*)file;
+    if (file==NULL)
+        return 0; //UNZ_PARAMERROR;
+    pfile_in_zip_read_info=s->pfile_in_zip_read;
+    if (pfile_in_zip_read_info==NULL)
+        return 0; //UNZ_PARAMERROR;
+    return pfile_in_zip_read_info->pos_in_zipfile +
+                         pfile_in_zip_read_info->byte_before_the_zipfile;
+}
+
+/** Addition for GDAL : END */
+
+/*
+  Read bytes from the current file.
+  buf contain buffer where data must be copied
+  len the size of buf.
+
+  return the number of byte copied if somes bytes are copied
+  return 0 if the end of file was reached
+  return <0 with error code if there is an error
+    (UNZ_ERRNO for IO error, or zLib error for uncompress error)
+*/
+extern int ZEXPORT unzReadCurrentFile  (unzFile file, voidp buf, unsigned len)
+{
+    int err=UNZ_OK;
+    uInt iRead = 0;
+    unz64_s* s;
+    file_in_zip64_read_info_s* pfile_in_zip_read_info;
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+    if (pfile_in_zip_read_info==NULL)
+        return UNZ_PARAMERROR;
+
+
+    if (pfile_in_zip_read_info->read_buffer == NULL)
+        return UNZ_END_OF_LIST_OF_FILE;
+    if (len==0)
+        return 0;
+
+    pfile_in_zip_read_info->stream.next_out = (Bytef*)buf;
+
+    pfile_in_zip_read_info->stream.avail_out = (uInt)len;
+
+    if ((len>pfile_in_zip_read_info->rest_read_uncompressed) &&
+        (!(pfile_in_zip_read_info->raw)))
+        pfile_in_zip_read_info->stream.avail_out =
+            (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
+
+    if ((len>pfile_in_zip_read_info->rest_read_compressed+
+           pfile_in_zip_read_info->stream.avail_in) &&
+         (pfile_in_zip_read_info->raw))
+        pfile_in_zip_read_info->stream.avail_out =
+            (uInt)pfile_in_zip_read_info->rest_read_compressed+
+            pfile_in_zip_read_info->stream.avail_in;
+
+    while (pfile_in_zip_read_info->stream.avail_out>0)
+    {
+        if ((pfile_in_zip_read_info->stream.avail_in==0) &&
+            (pfile_in_zip_read_info->rest_read_compressed>0))
+        {
+            uInt uReadThis = UNZ_BUFSIZE;
+            if (pfile_in_zip_read_info->rest_read_compressed<uReadThis)
+                uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
+            if (uReadThis == 0)
+                return UNZ_EOF;
+            if (ZSEEK64(pfile_in_zip_read_info->z_filefunc,
+                      pfile_in_zip_read_info->filestream,
+                      pfile_in_zip_read_info->pos_in_zipfile +
+                         pfile_in_zip_read_info->byte_before_the_zipfile,
+                         ZLIB_FILEFUNC_SEEK_SET)!=0)
+                return UNZ_ERRNO;
+            if (ZREAD64(pfile_in_zip_read_info->z_filefunc,
+                      pfile_in_zip_read_info->filestream,
+                      pfile_in_zip_read_info->read_buffer,
+                      uReadThis)!=uReadThis)
+                return UNZ_ERRNO;
+
+
+#            ifndef NOUNCRYPT
+            if(s->encrypted)
+            {
+                uInt i;
+                for(i=0;i<uReadThis;i++)
+                  pfile_in_zip_read_info->read_buffer[i] =
+                      zdecode(s->keys,s->pcrc_32_tab,
+                              pfile_in_zip_read_info->read_buffer[i]);
+            }
+#            endif
+
+
+            pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
+
+            pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
+
+            pfile_in_zip_read_info->stream.next_in =
+                (Bytef*)pfile_in_zip_read_info->read_buffer;
+            pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
+        }
+
+        if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw))
+        {
+            uInt uDoCopy,i ;
+
+            if ((pfile_in_zip_read_info->stream.avail_in == 0) &&
+                (pfile_in_zip_read_info->rest_read_compressed == 0))
+                return (iRead==0) ? UNZ_EOF : iRead;
+
+            if (pfile_in_zip_read_info->stream.avail_out <
+                            pfile_in_zip_read_info->stream.avail_in)
+                uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
+            else
+                uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
+
+            for (i=0;i<uDoCopy;i++)
+                *(pfile_in_zip_read_info->stream.next_out+i) =
+                        *(pfile_in_zip_read_info->stream.next_in+i);
+
+            pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uDoCopy;
+
+            pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,
+                                pfile_in_zip_read_info->stream.next_out,
+                                uDoCopy);
+            pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
+            pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
+            pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
+            pfile_in_zip_read_info->stream.next_out += uDoCopy;
+            pfile_in_zip_read_info->stream.next_in += uDoCopy;
+            pfile_in_zip_read_info->stream.total_out += uDoCopy;
+            iRead += uDoCopy;
+        }
+        else if (pfile_in_zip_read_info->compression_method==Z_BZIP2ED)
+        {
+#ifdef HAVE_BZIP2
+            uLong uTotalOutBefore,uTotalOutAfter;
+            const Bytef *bufBefore;
+            uLong uOutThis;
+
+            pfile_in_zip_read_info->bstream.next_in        = (char*)pfile_in_zip_read_info->stream.next_in;
+            pfile_in_zip_read_info->bstream.avail_in       = pfile_in_zip_read_info->stream.avail_in;
+            pfile_in_zip_read_info->bstream.total_in_lo32  = pfile_in_zip_read_info->stream.total_in;
+            pfile_in_zip_read_info->bstream.total_in_hi32  = 0;
+            pfile_in_zip_read_info->bstream.next_out       = (char*)pfile_in_zip_read_info->stream.next_out;
+            pfile_in_zip_read_info->bstream.avail_out      = pfile_in_zip_read_info->stream.avail_out;
+            pfile_in_zip_read_info->bstream.total_out_lo32 = pfile_in_zip_read_info->stream.total_out;
+            pfile_in_zip_read_info->bstream.total_out_hi32 = 0;
+
+            uTotalOutBefore = pfile_in_zip_read_info->bstream.total_out_lo32;
+            bufBefore = (const Bytef *)pfile_in_zip_read_info->bstream.next_out;
+
+            err=BZ2_bzDecompress(&pfile_in_zip_read_info->bstream);
+
+            uTotalOutAfter = pfile_in_zip_read_info->bstream.total_out_lo32;
+            uOutThis = uTotalOutAfter-uTotalOutBefore;
+
+            pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis;
+
+            pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis));
+            pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis;
+            iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
+
+            pfile_in_zip_read_info->stream.next_in   = (Bytef*)pfile_in_zip_read_info->bstream.next_in;
+            pfile_in_zip_read_info->stream.avail_in  = pfile_in_zip_read_info->bstream.avail_in;
+            pfile_in_zip_read_info->stream.total_in  = pfile_in_zip_read_info->bstream.total_in_lo32;
+            pfile_in_zip_read_info->stream.next_out  = (Bytef*)pfile_in_zip_read_info->bstream.next_out;
+            pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->bstream.avail_out;
+            pfile_in_zip_read_info->stream.total_out = pfile_in_zip_read_info->bstream.total_out_lo32;
+
+            if (err==BZ_STREAM_END)
+              return (iRead==0) ? UNZ_EOF : iRead;
+            if (err!=BZ_OK)
+              break;
+#endif
+        } // end Z_BZIP2ED
+        else
+        {
+            ZPOS64_T uTotalOutBefore,uTotalOutAfter;
+            const Bytef *bufBefore;
+            ZPOS64_T uOutThis;
+            int flush=Z_SYNC_FLUSH;
+
+            uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
+            bufBefore = pfile_in_zip_read_info->stream.next_out;
+
+            /*
+            if ((pfile_in_zip_read_info->rest_read_uncompressed ==
+                     pfile_in_zip_read_info->stream.avail_out) &&
+                (pfile_in_zip_read_info->rest_read_compressed == 0))
+                flush = Z_FINISH;
+            */
+            err=inflate(&pfile_in_zip_read_info->stream,flush);
+
+            if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL))
+              err = Z_DATA_ERROR;
+
+            uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
+            uOutThis = uTotalOutAfter-uTotalOutBefore;
+
+            pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis;
+
+            pfile_in_zip_read_info->crc32 =
+                crc32(pfile_in_zip_read_info->crc32,bufBefore,
+                        (uInt)(uOutThis));
+
+            pfile_in_zip_read_info->rest_read_uncompressed -=
+                uOutThis;
+
+            iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
+
+            if (err==Z_STREAM_END)
+                return (iRead==0) ? UNZ_EOF : iRead;
+            if (err!=Z_OK)
+                break;
+        }
+    }
+
+    if (err==Z_OK)
+        return iRead;
+    return err;
+}
+
+
+/*
+  Give the current position in uncompressed data
+*/
+extern z_off_t ZEXPORT unztell (unzFile file)
+{
+    unz64_s* s;
+    file_in_zip64_read_info_s* pfile_in_zip_read_info;
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+    if (pfile_in_zip_read_info==NULL)
+        return UNZ_PARAMERROR;
+
+    return (z_off_t)pfile_in_zip_read_info->stream.total_out;
+}
+
+extern ZPOS64_T ZEXPORT unztell64 (unzFile file)
+{
+
+    unz64_s* s;
+    file_in_zip64_read_info_s* pfile_in_zip_read_info;
+    if (file==NULL)
+        return (ZPOS64_T)-1;
+    s=(unz64_s*)file;
+    pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+    if (pfile_in_zip_read_info==NULL)
+        return (ZPOS64_T)-1;
+
+    return pfile_in_zip_read_info->total_out_64;
+}
+
+
+/*
+  return 1 if the end of file was reached, 0 elsewhere
+*/
+extern int ZEXPORT unzeof (unzFile file)
+{
+    unz64_s* s;
+    file_in_zip64_read_info_s* pfile_in_zip_read_info;
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+    if (pfile_in_zip_read_info==NULL)
+        return UNZ_PARAMERROR;
+
+    if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
+        return 1;
+    else
+        return 0;
+}
+
+
+
+/*
+Read extra field from the current file (opened by unzOpenCurrentFile)
+This is the local-header version of the extra field (sometimes, there is
+more info in the local-header version than in the central-header)
+
+  if buf==NULL, it return the size of the local extra field that can be read
+
+  if buf!=NULL, len is the size of the buffer, the extra header is copied in
+    buf.
+  the return value is the number of bytes copied in buf, or (if <0)
+    the error code
+*/
+extern int ZEXPORT unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len)
+{
+    unz64_s* s;
+    file_in_zip64_read_info_s* pfile_in_zip_read_info;
+    uInt read_now;
+    ZPOS64_T size_to_read;
+
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+    if (pfile_in_zip_read_info==NULL)
+        return UNZ_PARAMERROR;
+
+    size_to_read = (pfile_in_zip_read_info->size_local_extrafield -
+                pfile_in_zip_read_info->pos_local_extrafield);
+
+    if (buf==NULL)
+        return (int)size_to_read;
+
+    if (len>size_to_read)
+        read_now = (uInt)size_to_read;
+    else
+        read_now = (uInt)len ;
+
+    if (read_now==0)
+        return 0;
+
+    if (ZSEEK64(pfile_in_zip_read_info->z_filefunc,
+              pfile_in_zip_read_info->filestream,
+              pfile_in_zip_read_info->offset_local_extrafield +
+              pfile_in_zip_read_info->pos_local_extrafield,
+              ZLIB_FILEFUNC_SEEK_SET)!=0)
+        return UNZ_ERRNO;
+
+    if (ZREAD64(pfile_in_zip_read_info->z_filefunc,
+              pfile_in_zip_read_info->filestream,
+              buf,read_now)!=read_now)
+        return UNZ_ERRNO;
+
+    return (int)read_now;
+}
+
+/*
+  Close the file in zip opened with unzipOpenCurrentFile
+  Return UNZ_CRCERROR if all the file was read but the CRC is not good
+*/
+extern int ZEXPORT unzCloseCurrentFile (unzFile file)
+{
+    int err=UNZ_OK;
+
+    unz64_s* s;
+    file_in_zip64_read_info_s* pfile_in_zip_read_info;
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+    if (pfile_in_zip_read_info==NULL)
+        return UNZ_PARAMERROR;
+
+
+    if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) &&
+        (!pfile_in_zip_read_info->raw))
+    {
+        if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
+            err=UNZ_CRCERROR;
+    }
+
+
+    TRYFREE(pfile_in_zip_read_info->read_buffer);
+    pfile_in_zip_read_info->read_buffer = NULL;
+    if (pfile_in_zip_read_info->stream_initialised == Z_DEFLATED)
+        inflateEnd(&pfile_in_zip_read_info->stream);
+#ifdef HAVE_BZIP2
+    else if (pfile_in_zip_read_info->stream_initialised == Z_BZIP2ED)
+        BZ2_bzDecompressEnd(&pfile_in_zip_read_info->bstream);
+#endif
+
+
+    pfile_in_zip_read_info->stream_initialised = 0;
+    TRYFREE(pfile_in_zip_read_info);
+
+    s->pfile_in_zip_read=NULL;
+
+    return err;
+}
+
+
+/*
+  Get the global comment string of the ZipFile, in the szComment buffer.
+  uSizeBuf is the size of the szComment buffer.
+  return the number of byte copied or an error code <0
+*/
+extern int ZEXPORT unzGetGlobalComment (unzFile file, char * szComment, uLong uSizeBuf)
+{
+    unz64_s* s;
+    uLong uReadThis ;
+    if (file==NULL)
+        return (int)UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+
+    uReadThis = uSizeBuf;
+    if (uReadThis>s->gi.size_comment)
+        uReadThis = s->gi.size_comment;
+
+    if (ZSEEK64(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0)
+        return UNZ_ERRNO;
+
+    if (uReadThis>0)
+    {
+      *szComment='\0';
+      if (ZREAD64(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis)
+        return UNZ_ERRNO;
+    }
+
+    if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment))
+        *(szComment+s->gi.size_comment)='\0';
+    return (int)uReadThis;
+}
+
+/* Additions by RX '2004 */
+extern ZPOS64_T ZEXPORT unzGetOffset64(unzFile file)
+{
+    unz64_s* s;
+
+    if (file==NULL)
+          return 0; //UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+    if (!s->current_file_ok)
+      return 0;
+    if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff)
+      if (s->num_file==s->gi.number_entry)
+         return 0;
+    return s->pos_in_central_dir;
+}
+
+extern uLong ZEXPORT unzGetOffset (unzFile file)
+{
+    ZPOS64_T offset64;
+
+    if (file==NULL)
+          return 0; //UNZ_PARAMERROR;
+    offset64 = unzGetOffset64(file);
+    return (uLong)offset64;
+}
+
+extern int ZEXPORT unzSetOffset64(unzFile file, ZPOS64_T pos)
+{
+    unz64_s* s;
+    int err;
+
+    if (file==NULL)
+        return UNZ_PARAMERROR;
+    s=(unz64_s*)file;
+
+    s->pos_in_central_dir = pos;
+    s->num_file = s->gi.number_entry;      /* hack */
+    err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+                                              &s->cur_file_info_internal,
+                                              NULL,0,NULL,0,NULL,0);
+    s->current_file_ok = (err == UNZ_OK);
+    return err;
+}
+
+extern int ZEXPORT unzSetOffset (unzFile file, uLong pos)
+{
+    return unzSetOffset64(file,pos);
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/unzip.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/unzip.h
new file mode 100644 (file)
index 0000000..3183968
--- /dev/null
@@ -0,0 +1,437 @@
+/* unzip.h -- IO for uncompress .zip files using zlib
+   Version 1.1, February 14h, 2010
+   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications of Unzip for Zip64
+         Copyright (C) 2007-2008 Even Rouault
+
+         Modifications for Zip64 support on both zip and unzip
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+         For more info read MiniZip_info.txt
+
+         ---------------------------------------------------------------------------------
+
+        Condition of use and distribution are the same than zlib :
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  ---------------------------------------------------------------------------------
+
+        Changes
+
+        See header of unzip64.c
+
+*/
+
+#ifndef _unz64_H
+#define _unz64_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef _ZLIB_H
+#include "zlib.h"
+#endif
+
+#ifndef  _ZLIBIOAPI_H
+#include "ioapi.h"
+#endif
+
+#ifdef HAVE_BZIP2
+#include "bzlib.h"
+#endif
+
+#define Z_BZIP2ED 12
+
+#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
+/* like the STRICT of WIN32, we define a pointer that cannot be converted
+    from (void*) without cast */
+typedef struct TagunzFile__ { int unused; } unzFile__;
+typedef unzFile__ *unzFile;
+#else
+typedef voidp unzFile;
+#endif
+
+
+#define UNZ_OK                          (0)
+#define UNZ_END_OF_LIST_OF_FILE         (-100)
+#define UNZ_ERRNO                       (Z_ERRNO)
+#define UNZ_EOF                         (0)
+#define UNZ_PARAMERROR                  (-102)
+#define UNZ_BADZIPFILE                  (-103)
+#define UNZ_INTERNALERROR               (-104)
+#define UNZ_CRCERROR                    (-105)
+
+/* tm_unz contain date/time info */
+typedef struct tm_unz_s
+{
+    uInt tm_sec;            /* seconds after the minute - [0,59] */
+    uInt tm_min;            /* minutes after the hour - [0,59] */
+    uInt tm_hour;           /* hours since midnight - [0,23] */
+    uInt tm_mday;           /* day of the month - [1,31] */
+    uInt tm_mon;            /* months since January - [0,11] */
+    uInt tm_year;           /* years - [1980..2044] */
+} tm_unz;
+
+/* unz_global_info structure contain global data about the ZIPfile
+   These data comes from the end of central dir */
+typedef struct unz_global_info64_s
+{
+    ZPOS64_T number_entry;         /* total number of entries in
+                                     the central dir on this disk */
+    uLong size_comment;         /* size of the global comment of the zipfile */
+} unz_global_info64;
+
+typedef struct unz_global_info_s
+{
+    uLong number_entry;         /* total number of entries in
+                                     the central dir on this disk */
+    uLong size_comment;         /* size of the global comment of the zipfile */
+} unz_global_info;
+
+/* unz_file_info contain information about a file in the zipfile */
+typedef struct unz_file_info64_s
+{
+    uLong version;              /* version made by                 2 bytes */
+    uLong version_needed;       /* version needed to extract       2 bytes */
+    uLong flag;                 /* general purpose bit flag        2 bytes */
+    uLong compression_method;   /* compression method              2 bytes */
+    uLong dosDate;              /* last mod file date in Dos fmt   4 bytes */
+    uLong crc;                  /* crc-32                          4 bytes */
+    ZPOS64_T compressed_size;   /* compressed size                 8 bytes */
+    ZPOS64_T uncompressed_size; /* uncompressed size               8 bytes */
+    uLong size_filename;        /* filename length                 2 bytes */
+    uLong size_file_extra;      /* extra field length              2 bytes */
+    uLong size_file_comment;    /* file comment length             2 bytes */
+
+    uLong disk_num_start;       /* disk number start               2 bytes */
+    uLong internal_fa;          /* internal file attributes        2 bytes */
+    uLong external_fa;          /* external file attributes        4 bytes */
+
+    tm_unz tmu_date;
+} unz_file_info64;
+
+typedef struct unz_file_info_s
+{
+    uLong version;              /* version made by                 2 bytes */
+    uLong version_needed;       /* version needed to extract       2 bytes */
+    uLong flag;                 /* general purpose bit flag        2 bytes */
+    uLong compression_method;   /* compression method              2 bytes */
+    uLong dosDate;              /* last mod file date in Dos fmt   4 bytes */
+    uLong crc;                  /* crc-32                          4 bytes */
+    uLong compressed_size;      /* compressed size                 4 bytes */
+    uLong uncompressed_size;    /* uncompressed size               4 bytes */
+    uLong size_filename;        /* filename length                 2 bytes */
+    uLong size_file_extra;      /* extra field length              2 bytes */
+    uLong size_file_comment;    /* file comment length             2 bytes */
+
+    uLong disk_num_start;       /* disk number start               2 bytes */
+    uLong internal_fa;          /* internal file attributes        2 bytes */
+    uLong external_fa;          /* external file attributes        4 bytes */
+
+    tm_unz tmu_date;
+} unz_file_info;
+
+extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1,
+                                                 const char* fileName2,
+                                                 int iCaseSensitivity));
+/*
+   Compare two filename (fileName1,fileName2).
+   If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
+   If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
+                                or strcasecmp)
+   If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
+    (like 1 on Unix, 2 on Windows)
+*/
+
+
+extern unzFile ZEXPORT unzOpen OF((const char *path));
+extern unzFile ZEXPORT unzOpen64 OF((const void *path));
+/*
+  Open a Zip file. path contain the full pathname (by example,
+     on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer
+     "zlib/zlib113.zip".
+     If the zipfile cannot be opened (file don't exist or in not valid), the
+       return value is NULL.
+     Else, the return value is a unzFile Handle, usable with other function
+       of this unzip package.
+     the "64" function take a const void* pointer, because the path is just the
+       value passed to the open64_file_func callback.
+     Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path
+       is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char*
+       does not describe the reality
+*/
+
+
+extern unzFile ZEXPORT unzOpen2 OF((const char *path,
+                                    zlib_filefunc_def* pzlib_filefunc_def));
+/*
+   Open a Zip file, like unzOpen, but provide a set of file low level API
+      for read/write the zip file (see ioapi.h)
+*/
+
+extern unzFile ZEXPORT unzOpen2_64 OF((const void *path,
+                                    zlib_filefunc64_def* pzlib_filefunc_def));
+/*
+   Open a Zip file, like unz64Open, but provide a set of file low level API
+      for read/write the zip file (see ioapi.h)
+*/
+
+extern int ZEXPORT unzClose OF((unzFile file));
+/*
+  Close a ZipFile opened with unzipOpen.
+  If there is files inside the .Zip opened with unzOpenCurrentFile (see later),
+    these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
+  return UNZ_OK if there is no problem. */
+
+extern int ZEXPORT unzGetGlobalInfo OF((unzFile file,
+                                        unz_global_info *pglobal_info));
+
+extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file,
+                                        unz_global_info64 *pglobal_info));
+/*
+  Write info about the ZipFile in the *pglobal_info structure.
+  No preparation of the structure is needed
+  return UNZ_OK if there is no problem. */
+
+
+extern int ZEXPORT unzGetGlobalComment OF((unzFile file,
+                                           char *szComment,
+                                           uLong uSizeBuf));
+/*
+  Get the global comment string of the ZipFile, in the szComment buffer.
+  uSizeBuf is the size of the szComment buffer.
+  return the number of byte copied or an error code <0
+*/
+
+
+/***************************************************************************/
+/* Unzip package allow you browse the directory of the zipfile */
+
+extern int ZEXPORT unzGoToFirstFile OF((unzFile file));
+/*
+  Set the current file of the zipfile to the first file.
+  return UNZ_OK if there is no problem
+*/
+
+extern int ZEXPORT unzGoToNextFile OF((unzFile file));
+/*
+  Set the current file of the zipfile to the next file.
+  return UNZ_OK if there is no problem
+  return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
+*/
+
+extern int ZEXPORT unzLocateFile OF((unzFile file,
+                     const char *szFileName,
+                     int iCaseSensitivity));
+/*
+  Try locate the file szFileName in the zipfile.
+  For the iCaseSensitivity signification, see unzStringFileNameCompare
+
+  return value :
+  UNZ_OK if the file is found. It becomes the current file.
+  UNZ_END_OF_LIST_OF_FILE if the file is not found
+*/
+
+
+/* ****************************************** */
+/* Ryan supplied functions */
+/* unz_file_info contain information about a file in the zipfile */
+typedef struct unz_file_pos_s
+{
+    uLong pos_in_zip_directory;   /* offset in zip file directory */
+    uLong num_of_file;            /* # of file */
+} unz_file_pos;
+
+extern int ZEXPORT unzGetFilePos(
+    unzFile file,
+    unz_file_pos* file_pos);
+
+extern int ZEXPORT unzGoToFilePos(
+    unzFile file,
+    unz_file_pos* file_pos);
+
+typedef struct unz64_file_pos_s
+{
+    ZPOS64_T pos_in_zip_directory;   /* offset in zip file directory */
+    ZPOS64_T num_of_file;            /* # of file */
+} unz64_file_pos;
+
+extern int ZEXPORT unzGetFilePos64(
+    unzFile file,
+    unz64_file_pos* file_pos);
+
+extern int ZEXPORT unzGoToFilePos64(
+    unzFile file,
+    const unz64_file_pos* file_pos);
+
+/* ****************************************** */
+
+extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file,
+                         unz_file_info64 *pfile_info,
+                         char *szFileName,
+                         uLong fileNameBufferSize,
+                         void *extraField,
+                         uLong extraFieldBufferSize,
+                         char *szComment,
+                         uLong commentBufferSize));
+
+extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file,
+                         unz_file_info *pfile_info,
+                         char *szFileName,
+                         uLong fileNameBufferSize,
+                         void *extraField,
+                         uLong extraFieldBufferSize,
+                         char *szComment,
+                         uLong commentBufferSize));
+/*
+  Get Info about the current file
+  if pfile_info!=NULL, the *pfile_info structure will contain somes info about
+        the current file
+  if szFileName!=NULL, the filemane string will be copied in szFileName
+            (fileNameBufferSize is the size of the buffer)
+  if extraField!=NULL, the extra field information will be copied in extraField
+            (extraFieldBufferSize is the size of the buffer).
+            This is the Central-header version of the extra field
+  if szComment!=NULL, the comment string of the file will be copied in szComment
+            (commentBufferSize is the size of the buffer)
+*/
+
+
+/** Addition for GDAL : START */
+
+extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file));
+
+/** Addition for GDAL : END */
+
+
+/***************************************************************************/
+/* for reading the content of the current zipfile, you can open it, read data
+   from it, and close it (you can close it before reading all the file)
+   */
+
+extern int ZEXPORT unzOpenCurrentFile OF((unzFile file));
+/*
+  Open for reading data the current file in the zipfile.
+  If there is no error, the return value is UNZ_OK.
+*/
+
+extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file,
+                                                  const char* password));
+/*
+  Open for reading data the current file in the zipfile.
+  password is a crypting password
+  If there is no error, the return value is UNZ_OK.
+*/
+
+extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file,
+                                           int* method,
+                                           int* level,
+                                           int raw));
+/*
+  Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
+    if raw==1
+  *method will receive method of compression, *level will receive level of
+     compression
+  note : you can set level parameter as NULL (if you did not want known level,
+         but you CANNOT set method parameter as NULL
+*/
+
+extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file,
+                                           int* method,
+                                           int* level,
+                                           int raw,
+                                           const char* password));
+/*
+  Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
+    if raw==1
+  *method will receive method of compression, *level will receive level of
+     compression
+  note : you can set level parameter as NULL (if you did not want known level,
+         but you CANNOT set method parameter as NULL
+*/
+
+
+extern int ZEXPORT unzCloseCurrentFile OF((unzFile file));
+/*
+  Close the file in zip opened with unzOpenCurrentFile
+  Return UNZ_CRCERROR if all the file was read but the CRC is not good
+*/
+
+extern int ZEXPORT unzReadCurrentFile OF((unzFile file,
+                      voidp buf,
+                      unsigned len));
+/*
+  Read bytes from the current file (opened by unzOpenCurrentFile)
+  buf contain buffer where data must be copied
+  len the size of buf.
+
+  return the number of byte copied if somes bytes are copied
+  return 0 if the end of file was reached
+  return <0 with error code if there is an error
+    (UNZ_ERRNO for IO error, or zLib error for uncompress error)
+*/
+
+extern z_off_t ZEXPORT unztell OF((unzFile file));
+
+extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file));
+/*
+  Give the current position in uncompressed data
+*/
+
+extern int ZEXPORT unzeof OF((unzFile file));
+/*
+  return 1 if the end of file was reached, 0 elsewhere
+*/
+
+extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
+                                             voidp buf,
+                                             unsigned len));
+/*
+  Read extra field from the current file (opened by unzOpenCurrentFile)
+  This is the local-header version of the extra field (sometimes, there is
+    more info in the local-header version than in the central-header)
+
+  if buf==NULL, it return the size of the local extra field
+
+  if buf!=NULL, len is the size of the buffer, the extra header is copied in
+    buf.
+  the return value is the number of bytes copied in buf, or (if <0)
+    the error code
+*/
+
+/***************************************************************************/
+
+/* Get the current file offset */
+extern ZPOS64_T ZEXPORT unzGetOffset64 (unzFile file);
+extern uLong ZEXPORT unzGetOffset (unzFile file);
+
+/* Set the current file offset */
+extern int ZEXPORT unzSetOffset64 (unzFile file, ZPOS64_T pos);
+extern int ZEXPORT unzSetOffset (unzFile file, uLong pos);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _unz64_H */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/zip.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/zip.c
new file mode 100644 (file)
index 0000000..1b99580
--- /dev/null
@@ -0,0 +1,2007 @@
+/* zip.c -- IO on .zip files using zlib
+   Version 1.1, February 14h, 2010
+   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications for Zip64 support
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+         For more info read MiniZip_info.txt
+
+         Changes
+   Oct-2009 - Mathias Svensson - Remove old C style function prototypes
+   Oct-2009 - Mathias Svensson - Added Zip64 Support when creating new file archives
+   Oct-2009 - Mathias Svensson - Did some code cleanup and refactoring to get better overview of some functions.
+   Oct-2009 - Mathias Svensson - Added zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data
+                                 It is used when recreting zip archive with RAW when deleting items from a zip.
+                                 ZIP64 data is automaticly added to items that needs it, and existing ZIP64 data need to be removed.
+   Oct-2009 - Mathias Svensson - Added support for BZIP2 as compression mode (bzip2 lib is required)
+   Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer
+
+*/
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "zlib.h"
+#include "zip.h"
+
+#ifdef STDC
+#  include <stddef.h>
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+#ifdef NO_ERRNO_H
+    extern int errno;
+#else
+#   include <errno.h>
+#endif
+
+
+#ifndef local
+#  define local static
+#endif
+/* compile with -Dlocal if your debugger can't find static symbols */
+
+#ifndef VERSIONMADEBY
+# define VERSIONMADEBY   (0x0) /* platform depedent */
+#endif
+
+#ifndef Z_BUFSIZE
+#define Z_BUFSIZE (64*1024) //(16384)
+#endif
+
+#ifndef Z_MAXFILENAMEINZIP
+#define Z_MAXFILENAMEINZIP (256)
+#endif
+
+#ifndef ALLOC
+# define ALLOC(size) (malloc(size))
+#endif
+#ifndef TRYFREE
+# define TRYFREE(p) {if (p) free(p);}
+#endif
+
+/*
+#define SIZECENTRALDIRITEM (0x2e)
+#define SIZEZIPLOCALHEADER (0x1e)
+*/
+
+/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */
+
+
+// NOT sure that this work on ALL platform
+#define MAKEULONG64(a, b) ((ZPOS64_T)(((unsigned long)(a)) | ((ZPOS64_T)((unsigned long)(b))) << 32))
+
+#ifndef SEEK_CUR
+#define SEEK_CUR    1
+#endif
+
+#ifndef SEEK_END
+#define SEEK_END    2
+#endif
+
+#ifndef SEEK_SET
+#define SEEK_SET    0
+#endif
+
+#ifndef DEF_MEM_LEVEL
+#if MAX_MEM_LEVEL >= 8
+#  define DEF_MEM_LEVEL 8
+#else
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#endif
+#endif
+const char zip_copyright[] =" zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
+
+
+#define SIZEDATA_INDATABLOCK (4096-(4*4))
+
+#define LOCALHEADERMAGIC    (0x04034b50)
+#define CENTRALHEADERMAGIC  (0x02014b50)
+#define ENDHEADERMAGIC      (0x06054b50)
+#define ZIP64ENDHEADERMAGIC      (0x6064b50)
+#define ZIP64ENDLOCHEADERMAGIC   (0x7064b50)
+
+#define FLAG_LOCALHEADER_OFFSET (0x06)
+#define CRC_LOCALHEADER_OFFSET  (0x0e)
+
+#define SIZECENTRALHEADER (0x2e) /* 46 */
+
+typedef struct linkedlist_datablock_internal_s
+{
+  struct linkedlist_datablock_internal_s* next_datablock;
+  uLong  avail_in_this_block;
+  uLong  filled_in_this_block;
+  uLong  unused; /* for future use and alignement */
+  unsigned char data[SIZEDATA_INDATABLOCK];
+} linkedlist_datablock_internal;
+
+typedef struct linkedlist_data_s
+{
+    linkedlist_datablock_internal* first_block;
+    linkedlist_datablock_internal* last_block;
+} linkedlist_data;
+
+
+typedef struct
+{
+    z_stream stream;            /* zLib stream structure for inflate */
+#ifdef HAVE_BZIP2
+    bz_stream bstream;          /* bzLib stream structure for bziped */
+#endif
+
+    int  stream_initialised;    /* 1 is stream is initialised */
+    uInt pos_in_buffered_data;  /* last written byte in buffered_data */
+
+    ZPOS64_T pos_local_header;     /* offset of the local header of the file
+                                     currenty writing */
+    char* central_header;       /* central header data for the current file */
+    uLong size_centralExtra;
+    uLong size_centralheader;   /* size of the central header for cur file */
+    uLong size_centralExtraFree; /* Extra bytes allocated to the centralheader but that are not used */
+    uLong flag;                 /* flag of the file currently writing */
+
+    int  method;                /* compression method of file currenty wr.*/
+    int  raw;                   /* 1 for directly writing raw data */
+    Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/
+    uLong dosDate;
+    uLong crc32;
+    int  encrypt;
+    int  zip64;               /* Add ZIP64 extened information in the extra field */
+    ZPOS64_T pos_zip64extrainfo;
+    ZPOS64_T totalCompressedData;
+    ZPOS64_T totalUncompressedData;
+#ifndef NOCRYPT
+    unsigned long keys[3];     /* keys defining the pseudo-random sequence */
+    const unsigned long* pcrc_32_tab;
+    int crypt_header_size;
+#endif
+} curfile64_info;
+
+typedef struct
+{
+    zlib_filefunc64_32_def z_filefunc;
+    voidpf filestream;        /* io structore of the zipfile */
+    linkedlist_data central_dir;/* datablock with central dir in construction*/
+    int  in_opened_file_inzip;  /* 1 if a file in the zip is currently writ.*/
+    curfile64_info ci;            /* info on the file curretly writing */
+
+    ZPOS64_T begin_pos;            /* position of the beginning of the zipfile */
+    ZPOS64_T add_position_when_writting_offset;
+    ZPOS64_T number_entry;
+
+#ifndef NO_ADDFILEINEXISTINGZIP
+    char *globalcomment;
+#endif
+
+} zip64_internal;
+
+
+#ifndef NOCRYPT
+#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED
+#include "crypt.h"
+#endif
+
+local linkedlist_datablock_internal* allocate_new_datablock()
+{
+    linkedlist_datablock_internal* ldi;
+    ldi = (linkedlist_datablock_internal*)
+                 ALLOC(sizeof(linkedlist_datablock_internal));
+    if (ldi!=NULL)
+    {
+        ldi->next_datablock = NULL ;
+        ldi->filled_in_this_block = 0 ;
+        ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ;
+    }
+    return ldi;
+}
+
+local void free_datablock(linkedlist_datablock_internal* ldi)
+{
+    while (ldi!=NULL)
+    {
+        linkedlist_datablock_internal* ldinext = ldi->next_datablock;
+        TRYFREE(ldi);
+        ldi = ldinext;
+    }
+}
+
+local void init_linkedlist(linkedlist_data* ll)
+{
+    ll->first_block = ll->last_block = NULL;
+}
+
+local void free_linkedlist(linkedlist_data* ll)
+{
+    free_datablock(ll->first_block);
+    ll->first_block = ll->last_block = NULL;
+}
+
+
+local int add_data_in_datablock(linkedlist_data* ll, const void* buf, uLong len)
+{
+    linkedlist_datablock_internal* ldi;
+    const unsigned char* from_copy;
+
+    if (ll==NULL)
+        return ZIP_INTERNALERROR;
+
+    if (ll->last_block == NULL)
+    {
+        ll->first_block = ll->last_block = allocate_new_datablock();
+        if (ll->first_block == NULL)
+            return ZIP_INTERNALERROR;
+    }
+
+    ldi = ll->last_block;
+    from_copy = (unsigned char*)buf;
+
+    while (len>0)
+    {
+        uInt copy_this;
+        uInt i;
+        unsigned char* to_copy;
+
+        if (ldi->avail_in_this_block==0)
+        {
+            ldi->next_datablock = allocate_new_datablock();
+            if (ldi->next_datablock == NULL)
+                return ZIP_INTERNALERROR;
+            ldi = ldi->next_datablock ;
+            ll->last_block = ldi;
+        }
+
+        if (ldi->avail_in_this_block < len)
+            copy_this = (uInt)ldi->avail_in_this_block;
+        else
+            copy_this = (uInt)len;
+
+        to_copy = &(ldi->data[ldi->filled_in_this_block]);
+
+        for (i=0;i<copy_this;i++)
+            *(to_copy+i)=*(from_copy+i);
+
+        ldi->filled_in_this_block += copy_this;
+        ldi->avail_in_this_block -= copy_this;
+        from_copy += copy_this ;
+        len -= copy_this;
+    }
+    return ZIP_OK;
+}
+
+
+
+/****************************************************************************/
+
+#ifndef NO_ADDFILEINEXISTINGZIP
+/* ===========================================================================
+   Inputs a long in LSB order to the given file
+   nbByte == 1, 2 ,4 or 8 (byte, short or long, ZPOS64_T)
+*/
+
+local int zip64local_putValue OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte));
+local int zip64local_putValue (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte)
+{
+    unsigned char buf[8];
+    int n;
+    for (n = 0; n < nbByte; n++)
+    {
+        buf[n] = (unsigned char)(x & 0xff);
+        x >>= 8;
+    }
+    if (x != 0)
+      {     /* data overflow - hack for ZIP64 (X Roche) */
+      for (n = 0; n < nbByte; n++)
+        {
+          buf[n] = 0xff;
+        }
+      }
+
+    if (ZWRITE64(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte)
+        return ZIP_ERRNO;
+    else
+        return ZIP_OK;
+}
+
+local void zip64local_putValue_inmemory OF((void* dest, ZPOS64_T x, int nbByte));
+local void zip64local_putValue_inmemory (void* dest, ZPOS64_T x, int nbByte)
+{
+    unsigned char* buf=(unsigned char*)dest;
+    int n;
+    for (n = 0; n < nbByte; n++) {
+        buf[n] = (unsigned char)(x & 0xff);
+        x >>= 8;
+    }
+
+    if (x != 0)
+    {     /* data overflow - hack for ZIP64 */
+       for (n = 0; n < nbByte; n++)
+       {
+          buf[n] = 0xff;
+       }
+    }
+}
+
+/****************************************************************************/
+
+
+local uLong zip64local_TmzDateToDosDate(const tm_zip* ptm)
+{
+    uLong year = (uLong)ptm->tm_year;
+    if (year>=1980)
+        year-=1980;
+    else if (year>=80)
+        year-=80;
+    return
+      (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) |
+        ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour));
+}
+
+
+/****************************************************************************/
+
+local int zip64local_getByte OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi));
+
+local int zip64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def,voidpf filestream,int* pi)
+{
+    unsigned char c;
+    int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1);
+    if (err==1)
+    {
+        *pi = (int)c;
+        return ZIP_OK;
+    }
+    else
+    {
+        if (ZERROR64(*pzlib_filefunc_def,filestream))
+            return ZIP_ERRNO;
+        else
+            return ZIP_EOF;
+    }
+}
+
+
+/* ===========================================================================
+   Reads a long in LSB order from the given gz_stream. Sets
+*/
+local int zip64local_getShort OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX));
+
+local int zip64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX)
+{
+    uLong x ;
+    int i = 0;
+    int err;
+
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x = (uLong)i;
+
+    if (err==ZIP_OK)
+        err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x += ((uLong)i)<<8;
+
+    if (err==ZIP_OK)
+        *pX = x;
+    else
+        *pX = 0;
+    return err;
+}
+
+local int zip64local_getLong OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX));
+
+local int zip64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX)
+{
+    uLong x ;
+    int i = 0;
+    int err;
+
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x = (uLong)i;
+
+    if (err==ZIP_OK)
+        err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x += ((uLong)i)<<8;
+
+    if (err==ZIP_OK)
+        err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x += ((uLong)i)<<16;
+
+    if (err==ZIP_OK)
+        err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+    x += ((uLong)i)<<24;
+
+    if (err==ZIP_OK)
+        *pX = x;
+    else
+        *pX = 0;
+    return err;
+}
+
+local int zip64local_getLong64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX));
+
+
+local int zip64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX)
+{
+  ZPOS64_T x;
+  int i = 0;
+  int err;
+
+  err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+  x = (ZPOS64_T)i;
+
+  if (err==ZIP_OK)
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+  x += ((ZPOS64_T)i)<<8;
+
+  if (err==ZIP_OK)
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+  x += ((ZPOS64_T)i)<<16;
+
+  if (err==ZIP_OK)
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+  x += ((ZPOS64_T)i)<<24;
+
+  if (err==ZIP_OK)
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+  x += ((ZPOS64_T)i)<<32;
+
+  if (err==ZIP_OK)
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+  x += ((ZPOS64_T)i)<<40;
+
+  if (err==ZIP_OK)
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+  x += ((ZPOS64_T)i)<<48;
+
+  if (err==ZIP_OK)
+    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+  x += ((ZPOS64_T)i)<<56;
+
+  if (err==ZIP_OK)
+    *pX = x;
+  else
+    *pX = 0;
+
+  return err;
+}
+
+#ifndef BUFREADCOMMENT
+#define BUFREADCOMMENT (0x400)
+#endif
+/*
+  Locate the Central directory of a zipfile (at the end, just before
+    the global comment)
+*/
+local ZPOS64_T zip64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
+
+local ZPOS64_T zip64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
+{
+  unsigned char* buf;
+  ZPOS64_T uSizeFile;
+  ZPOS64_T uBackRead;
+  ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
+  ZPOS64_T uPosFound=0;
+
+  if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
+    return 0;
+
+
+  uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
+
+  if (uMaxBack>uSizeFile)
+    uMaxBack = uSizeFile;
+
+  buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
+  if (buf==NULL)
+    return 0;
+
+  uBackRead = 4;
+  while (uBackRead<uMaxBack)
+  {
+    uLong uReadSize;
+    ZPOS64_T uReadPos ;
+    int i;
+    if (uBackRead+BUFREADCOMMENT>uMaxBack)
+      uBackRead = uMaxBack;
+    else
+      uBackRead+=BUFREADCOMMENT;
+    uReadPos = uSizeFile-uBackRead ;
+
+    uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
+      (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
+    if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+      break;
+
+    if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
+      break;
+
+    for (i=(int)uReadSize-3; (i--)>0;)
+      if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
+        ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
+      {
+        uPosFound = uReadPos+i;
+        break;
+      }
+
+      if (uPosFound!=0)
+        break;
+  }
+  TRYFREE(buf);
+  return uPosFound;
+}
+
+/*
+Locate the End of Zip64 Central directory locator and from there find the CD of a zipfile (at the end, just before
+the global comment)
+*/
+local ZPOS64_T zip64local_SearchCentralDir64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
+
+local ZPOS64_T zip64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
+{
+  unsigned char* buf;
+  ZPOS64_T uSizeFile;
+  ZPOS64_T uBackRead;
+  ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
+  ZPOS64_T uPosFound=0;
+  uLong uL;
+  ZPOS64_T relativeOffset;
+
+  if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
+    return 0;
+
+  uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
+
+  if (uMaxBack>uSizeFile)
+    uMaxBack = uSizeFile;
+
+  buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
+  if (buf==NULL)
+    return 0;
+
+  uBackRead = 4;
+  while (uBackRead<uMaxBack)
+  {
+    uLong uReadSize;
+    ZPOS64_T uReadPos;
+    int i;
+    if (uBackRead+BUFREADCOMMENT>uMaxBack)
+      uBackRead = uMaxBack;
+    else
+      uBackRead+=BUFREADCOMMENT;
+    uReadPos = uSizeFile-uBackRead ;
+
+    uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
+      (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
+    if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+      break;
+
+    if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
+      break;
+
+    for (i=(int)uReadSize-3; (i--)>0;)
+    {
+      // Signature "0x07064b50" Zip64 end of central directory locater
+      if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07))
+      {
+        uPosFound = uReadPos+i;
+        break;
+      }
+    }
+
+      if (uPosFound!=0)
+        break;
+  }
+
+  TRYFREE(buf);
+  if (uPosFound == 0)
+    return 0;
+
+  /* Zip64 end of central directory locator */
+  if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0)
+    return 0;
+
+  /* the signature, already checked */
+  if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
+    return 0;
+
+  /* number of the disk with the start of the zip64 end of  central directory */
+  if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
+    return 0;
+  if (uL != 0)
+    return 0;
+
+  /* relative offset of the zip64 end of central directory record */
+  if (zip64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=ZIP_OK)
+    return 0;
+
+  /* total number of disks */
+  if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
+    return 0;
+  if (uL != 1)
+    return 0;
+
+  /* Goto Zip64 end of central directory record */
+  if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0)
+    return 0;
+
+  /* the signature */
+  if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
+    return 0;
+
+  if (uL != 0x06064b50) // signature of 'Zip64 end of central directory'
+    return 0;
+
+  return relativeOffset;
+}
+
+int LoadCentralDirectoryRecord(zip64_internal* pziinit)
+{
+  int err=ZIP_OK;
+  ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
+
+  ZPOS64_T size_central_dir;     /* size of the central directory  */
+  ZPOS64_T offset_central_dir;   /* offset of start of central directory */
+  ZPOS64_T central_pos;
+  uLong uL;
+
+  uLong number_disk;          /* number of the current dist, used for
+                              spaning ZIP, unsupported, always 0*/
+  uLong number_disk_with_CD;  /* number the the disk with central dir, used
+                              for spaning ZIP, unsupported, always 0*/
+  ZPOS64_T number_entry;
+  ZPOS64_T number_entry_CD;      /* total number of entries in
+                                the central dir
+                                (same than number_entry on nospan) */
+  uLong VersionMadeBy;
+  uLong VersionNeeded;
+  uLong size_comment;
+
+  int hasZIP64Record = 0;
+
+  // check first if we find a ZIP64 record
+  central_pos = zip64local_SearchCentralDir64(&pziinit->z_filefunc,pziinit->filestream);
+  if(central_pos > 0)
+  {
+    hasZIP64Record = 1;
+  }
+  else if(central_pos == 0)
+  {
+    central_pos = zip64local_SearchCentralDir(&pziinit->z_filefunc,pziinit->filestream);
+  }
+
+/* disable to allow appending to empty ZIP archive
+        if (central_pos==0)
+            err=ZIP_ERRNO;
+*/
+
+  if(hasZIP64Record)
+  {
+    ZPOS64_T sizeEndOfCentralDirectory;
+    if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos, ZLIB_FILEFUNC_SEEK_SET) != 0)
+      err=ZIP_ERRNO;
+
+    /* the signature, already checked */
+    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* size of zip64 end of central directory record */
+    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &sizeEndOfCentralDirectory)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* version made by */
+    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionMadeBy)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* version needed to extract */
+    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionNeeded)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* number of this disk */
+    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* number of the disk with the start of the central directory */
+    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* total number of entries in the central directory on this disk */
+    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &number_entry)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* total number of entries in the central directory */
+    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&number_entry_CD)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0))
+      err=ZIP_BADZIPFILE;
+
+    /* size of the central directory */
+    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&size_central_dir)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* offset of start of central directory with respect to the
+    starting disk number */
+    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&offset_central_dir)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    // TODO..
+    // read the comment from the standard central header.
+    size_comment = 0;
+  }
+  else
+  {
+    // Read End of central Directory info
+    if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+      err=ZIP_ERRNO;
+
+    /* the signature, already checked */
+    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* number of this disk */
+    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* number of the disk with the start of the central directory */
+    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK)
+      err=ZIP_ERRNO;
+
+    /* total number of entries in the central dir on this disk */
+    number_entry = 0;
+    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
+      err=ZIP_ERRNO;
+    else
+      number_entry = uL;
+
+    /* total number of entries in the central dir */
+    number_entry_CD = 0;
+    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
+      err=ZIP_ERRNO;
+    else
+      number_entry_CD = uL;
+
+    if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0))
+      err=ZIP_BADZIPFILE;
+
+    /* size of the central directory */
+    size_central_dir = 0;
+    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
+      err=ZIP_ERRNO;
+    else
+      size_central_dir = uL;
+
+    /* offset of start of central directory with respect to the starting disk number */
+    offset_central_dir = 0;
+    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
+      err=ZIP_ERRNO;
+    else
+      offset_central_dir = uL;
+
+
+    /* zipfile global comment length */
+    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &size_comment)!=ZIP_OK)
+      err=ZIP_ERRNO;
+  }
+
+  if ((central_pos<offset_central_dir+size_central_dir) &&
+    (err==ZIP_OK))
+    err=ZIP_BADZIPFILE;
+
+  if (err!=ZIP_OK)
+  {
+    ZCLOSE64(pziinit->z_filefunc, pziinit->filestream);
+    return ZIP_ERRNO;
+  }
+
+  if (size_comment>0)
+  {
+    pziinit->globalcomment = (char*)ALLOC(size_comment+1);
+    if (pziinit->globalcomment)
+    {
+      size_comment = ZREAD64(pziinit->z_filefunc, pziinit->filestream, pziinit->globalcomment,size_comment);
+      pziinit->globalcomment[size_comment]=0;
+    }
+  }
+
+  byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir);
+  pziinit->add_position_when_writting_offset = byte_before_the_zipfile;
+
+  {
+    ZPOS64_T size_central_dir_to_read = size_central_dir;
+    size_t buf_size = SIZEDATA_INDATABLOCK;
+    void* buf_read = (void*)ALLOC(buf_size);
+    if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0)
+      err=ZIP_ERRNO;
+
+    while ((size_central_dir_to_read>0) && (err==ZIP_OK))
+    {
+      ZPOS64_T read_this = SIZEDATA_INDATABLOCK;
+      if (read_this > size_central_dir_to_read)
+        read_this = size_central_dir_to_read;
+
+      if (ZREAD64(pziinit->z_filefunc, pziinit->filestream,buf_read,(uLong)read_this) != read_this)
+        err=ZIP_ERRNO;
+
+      if (err==ZIP_OK)
+        err = add_data_in_datablock(&pziinit->central_dir,buf_read, (uLong)read_this);
+
+      size_central_dir_to_read-=read_this;
+    }
+    TRYFREE(buf_read);
+  }
+  pziinit->begin_pos = byte_before_the_zipfile;
+  pziinit->number_entry = number_entry_CD;
+
+  if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET) != 0)
+    err=ZIP_ERRNO;
+
+  return err;
+}
+
+
+#endif /* !NO_ADDFILEINEXISTINGZIP*/
+
+
+/************************************************************/
+extern zipFile ZEXPORT zipOpen3 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_32_def* pzlib_filefunc64_32_def)
+{
+    zip64_internal ziinit;
+    zip64_internal* zi;
+    int err=ZIP_OK;
+
+    ziinit.z_filefunc.zseek32_file = NULL;
+    ziinit.z_filefunc.ztell32_file = NULL;
+    if (pzlib_filefunc64_32_def==NULL)
+        fill_fopen64_filefunc(&ziinit.z_filefunc.zfile_func64);
+    else
+        ziinit.z_filefunc = *pzlib_filefunc64_32_def;
+
+    ziinit.filestream = ZOPEN64(ziinit.z_filefunc,
+                  pathname,
+                  (append == APPEND_STATUS_CREATE) ?
+                  (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) :
+                    (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING));
+
+    if (ziinit.filestream == NULL)
+        return NULL;
+
+    if (append == APPEND_STATUS_CREATEAFTER)
+        ZSEEK64(ziinit.z_filefunc,ziinit.filestream,0,SEEK_END);
+
+    ziinit.begin_pos = ZTELL64(ziinit.z_filefunc,ziinit.filestream);
+    ziinit.in_opened_file_inzip = 0;
+    ziinit.ci.stream_initialised = 0;
+    ziinit.number_entry = 0;
+    ziinit.add_position_when_writting_offset = 0;
+    init_linkedlist(&(ziinit.central_dir));
+
+
+
+    zi = (zip64_internal*)ALLOC(sizeof(zip64_internal));
+    if (zi==NULL)
+    {
+        ZCLOSE64(ziinit.z_filefunc,ziinit.filestream);
+        return NULL;
+    }
+
+    /* now we add file in a zipfile */
+#    ifndef NO_ADDFILEINEXISTINGZIP
+    ziinit.globalcomment = NULL;
+    if (append == APPEND_STATUS_ADDINZIP)
+    {
+      // Read and Cache Central Directory Records
+      err = LoadCentralDirectoryRecord(&ziinit);
+    }
+
+    if (globalcomment)
+    {
+      *globalcomment = ziinit.globalcomment;
+    }
+#    endif /* !NO_ADDFILEINEXISTINGZIP*/
+
+    if (err != ZIP_OK)
+    {
+#    ifndef NO_ADDFILEINEXISTINGZIP
+        TRYFREE(ziinit.globalcomment);
+#    endif /* !NO_ADDFILEINEXISTINGZIP*/
+        TRYFREE(zi);
+        return NULL;
+    }
+    else
+    {
+        *zi = ziinit;
+        return (zipFile)zi;
+    }
+}
+
+extern zipFile ZEXPORT zipOpen2 (const char *pathname, int append, zipcharpc* globalcomment, zlib_filefunc_def* pzlib_filefunc32_def)
+{
+    if (pzlib_filefunc32_def != NULL)
+    {
+        zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
+        fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def);
+        return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill);
+    }
+    else
+        return zipOpen3(pathname, append, globalcomment, NULL);
+}
+
+extern zipFile ZEXPORT zipOpen2_64 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def)
+{
+    if (pzlib_filefunc_def != NULL)
+    {
+        zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
+        zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def;
+        zlib_filefunc64_32_def_fill.ztell32_file = NULL;
+        zlib_filefunc64_32_def_fill.zseek32_file = NULL;
+        return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill);
+    }
+    else
+        return zipOpen3(pathname, append, globalcomment, NULL);
+}
+
+
+
+extern zipFile ZEXPORT zipOpen (const char* pathname, int append)
+{
+    return zipOpen3((const void*)pathname,append,NULL,NULL);
+}
+
+extern zipFile ZEXPORT zipOpen64 (const void* pathname, int append)
+{
+    return zipOpen3(pathname,append,NULL,NULL);
+}
+
+int Write_LocalFileHeader(zip64_internal* zi, const char* filename, uInt size_extrafield_local, const void* extrafield_local)
+{
+  /* write the local header */
+  int err;
+  uInt size_filename = (uInt)strlen(filename);
+  uInt size_extrafield = size_extrafield_local;
+
+  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC, 4);
+
+  if (err==ZIP_OK)
+  {
+    if(zi->ci.zip64)
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);/* version needed to extract */
+    else
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */
+  }
+
+  if (err==ZIP_OK)
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2);
+
+  if (err==ZIP_OK)
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2);
+
+  if (err==ZIP_OK)
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4);
+
+  // CRC / Compressed size / Uncompressed size will be filled in later and rewritten later
+  if (err==ZIP_OK)
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */
+  if (err==ZIP_OK)
+  {
+    if(zi->ci.zip64)
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* compressed size, unknown */
+    else
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */
+  }
+  if (err==ZIP_OK)
+  {
+    if(zi->ci.zip64)
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* uncompressed size, unknown */
+    else
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */
+  }
+
+  if (err==ZIP_OK)
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2);
+
+  if(zi->ci.zip64)
+  {
+    size_extrafield += 20;
+  }
+
+  if (err==ZIP_OK)
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield,2);
+
+  if ((err==ZIP_OK) && (size_filename > 0))
+  {
+    if (ZWRITE64(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename)
+      err = ZIP_ERRNO;
+  }
+
+  if ((err==ZIP_OK) && (size_extrafield_local > 0))
+  {
+    if (ZWRITE64(zi->z_filefunc, zi->filestream, extrafield_local, size_extrafield_local) != size_extrafield_local)
+      err = ZIP_ERRNO;
+  }
+
+
+  if ((err==ZIP_OK) && (zi->ci.zip64))
+  {
+      // write the Zip64 extended info
+      short HeaderID = 1;
+      short DataSize = 16;
+      ZPOS64_T CompressedSize = 0;
+      ZPOS64_T UncompressedSize = 0;
+
+      // Remember position of Zip64 extended info for the local file header. (needed when we update size after done with file)
+      zi->ci.pos_zip64extrainfo = ZTELL64(zi->z_filefunc,zi->filestream);
+
+      err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)HeaderID,2);
+      err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)DataSize,2);
+
+      err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)UncompressedSize,8);
+      err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)CompressedSize,8);
+  }
+
+  return err;
+}
+
+/*
+ NOTE.
+ When writing RAW the ZIP64 extended information in extrafield_local and extrafield_global needs to be stripped
+ before calling this function it can be done with zipRemoveExtraInfoBlock
+
+ It is not done here because then we need to realloc a new buffer since parameters are 'const' and I want to minimize
+ unnecessary allocations.
+ */
+extern int ZEXPORT zipOpenNewFileInZip4_64 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+                                         const void* extrafield_local, uInt size_extrafield_local,
+                                         const void* extrafield_global, uInt size_extrafield_global,
+                                         const char* comment, int method, int level, int raw,
+                                         int windowBits,int memLevel, int strategy,
+                                         const char* password, uLong crcForCrypting,
+                                         uLong versionMadeBy, uLong flagBase, int zip64)
+{
+    zip64_internal* zi;
+    uInt size_filename;
+    uInt size_comment;
+    uInt i;
+    int err = ZIP_OK;
+
+#    ifdef NOCRYPT
+    (crcForCrypting);
+    if (password != NULL)
+        return ZIP_PARAMERROR;
+#    endif
+
+    if (file == NULL)
+        return ZIP_PARAMERROR;
+
+#ifdef HAVE_BZIP2
+    if ((method!=0) && (method!=Z_DEFLATED) && (method!=Z_BZIP2ED))
+      return ZIP_PARAMERROR;
+#else
+    if ((method!=0) && (method!=Z_DEFLATED))
+      return ZIP_PARAMERROR;
+#endif
+
+    zi = (zip64_internal*)file;
+
+    if (zi->in_opened_file_inzip == 1)
+    {
+        err = zipCloseFileInZip (file);
+        if (err != ZIP_OK)
+            return err;
+    }
+
+    if (filename==NULL)
+        filename="-";
+
+    if (comment==NULL)
+        size_comment = 0;
+    else
+        size_comment = (uInt)strlen(comment);
+
+    size_filename = (uInt)strlen(filename);
+
+    if (zipfi == NULL)
+        zi->ci.dosDate = 0;
+    else
+    {
+        if (zipfi->dosDate != 0)
+            zi->ci.dosDate = zipfi->dosDate;
+        else
+          zi->ci.dosDate = zip64local_TmzDateToDosDate(&zipfi->tmz_date);
+    }
+
+    zi->ci.flag = flagBase;
+    if ((level==8) || (level==9))
+      zi->ci.flag |= 2;
+    if ((level==2))
+      zi->ci.flag |= 4;
+    if ((level==1))
+      zi->ci.flag |= 6;
+    if (password != NULL)
+      zi->ci.flag |= 1;
+
+    zi->ci.crc32 = 0;
+    zi->ci.method = method;
+    zi->ci.encrypt = 0;
+    zi->ci.stream_initialised = 0;
+    zi->ci.pos_in_buffered_data = 0;
+    zi->ci.raw = raw;
+    zi->ci.pos_local_header = ZTELL64(zi->z_filefunc,zi->filestream);
+
+    zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment;
+    zi->ci.size_centralExtraFree = 32; // Extra space we have reserved in case we need to add ZIP64 extra info data
+
+    zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader + zi->ci.size_centralExtraFree);
+
+    zi->ci.size_centralExtra = size_extrafield_global;
+    zip64local_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4);
+    /* version info */
+    zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)versionMadeBy,2);
+    zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2);
+    zip64local_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2);
+    zip64local_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2);
+    zip64local_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4);
+    zip64local_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/
+    zip64local_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/
+    zip64local_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/
+    zip64local_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2);
+    zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2);
+    zip64local_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2);
+    zip64local_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/
+
+    if (zipfi==NULL)
+        zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2);
+    else
+        zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2);
+
+    if (zipfi==NULL)
+        zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4);
+    else
+        zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4);
+
+    if(zi->ci.pos_local_header >= 0xffffffff)
+      zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)0xffffffff,4);
+    else
+      zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header - zi->add_position_when_writting_offset,4);
+
+    for (i=0;i<size_filename;i++)
+        *(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i);
+
+    for (i=0;i<size_extrafield_global;i++)
+        *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) =
+              *(((const char*)extrafield_global)+i);
+
+    for (i=0;i<size_comment;i++)
+        *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+
+              size_extrafield_global+i) = *(comment+i);
+    if (zi->ci.central_header == NULL)
+        return ZIP_INTERNALERROR;
+
+    zi->ci.zip64 = zip64;
+    zi->ci.totalCompressedData = 0;
+    zi->ci.totalUncompressedData = 0;
+    zi->ci.pos_zip64extrainfo = 0;
+
+    err = Write_LocalFileHeader(zi, filename, size_extrafield_local, extrafield_local);
+
+#ifdef HAVE_BZIP2
+    zi->ci.bstream.avail_in = (uInt)0;
+    zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
+    zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
+    zi->ci.bstream.total_in_hi32 = 0;
+    zi->ci.bstream.total_in_lo32 = 0;
+    zi->ci.bstream.total_out_hi32 = 0;
+    zi->ci.bstream.total_out_lo32 = 0;
+#endif
+
+    zi->ci.stream.avail_in = (uInt)0;
+    zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
+    zi->ci.stream.next_out = zi->ci.buffered_data;
+    zi->ci.stream.total_in = 0;
+    zi->ci.stream.total_out = 0;
+    zi->ci.stream.data_type = Z_BINARY;
+
+#ifdef HAVE_BZIP2
+    if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED || zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
+#else
+    if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
+#endif
+    {
+        if(zi->ci.method == Z_DEFLATED)
+        {
+          zi->ci.stream.zalloc = (alloc_func)0;
+          zi->ci.stream.zfree = (free_func)0;
+          zi->ci.stream.opaque = (voidpf)0;
+
+          if (windowBits>0)
+              windowBits = -windowBits;
+
+          err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy);
+
+          if (err==Z_OK)
+              zi->ci.stream_initialised = Z_DEFLATED;
+        }
+        else if(zi->ci.method == Z_BZIP2ED)
+        {
+#ifdef HAVE_BZIP2
+            // Init BZip stuff here
+          zi->ci.bstream.bzalloc = 0;
+          zi->ci.bstream.bzfree = 0;
+          zi->ci.bstream.opaque = (voidpf)0;
+
+          err = BZ2_bzCompressInit(&zi->ci.bstream, level, 0,35);
+          if(err == BZ_OK)
+            zi->ci.stream_initialised = Z_BZIP2ED;
+#endif
+        }
+
+    }
+
+#    ifndef NOCRYPT
+    zi->ci.crypt_header_size = 0;
+    if ((err==Z_OK) && (password != NULL))
+    {
+        unsigned char bufHead[RAND_HEAD_LEN];
+        unsigned int sizeHead;
+        zi->ci.encrypt = 1;
+        zi->ci.pcrc_32_tab = get_crc_table();
+        /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/
+
+        sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting);
+        zi->ci.crypt_header_size = sizeHead;
+
+        if (ZWRITE64(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead)
+                err = ZIP_ERRNO;
+    }
+#    endif
+
+    if (err==Z_OK)
+        zi->in_opened_file_inzip = 1;
+    return err;
+}
+
+extern int ZEXPORT zipOpenNewFileInZip4 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+                                         const void* extrafield_local, uInt size_extrafield_local,
+                                         const void* extrafield_global, uInt size_extrafield_global,
+                                         const char* comment, int method, int level, int raw,
+                                         int windowBits,int memLevel, int strategy,
+                                         const char* password, uLong crcForCrypting,
+                                         uLong versionMadeBy, uLong flagBase)
+{
+    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+                                 extrafield_local, size_extrafield_local,
+                                 extrafield_global, size_extrafield_global,
+                                 comment, method, level, raw,
+                                 windowBits, memLevel, strategy,
+                                 password, crcForCrypting, versionMadeBy, flagBase, 0);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip3 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+                                         const void* extrafield_local, uInt size_extrafield_local,
+                                         const void* extrafield_global, uInt size_extrafield_global,
+                                         const char* comment, int method, int level, int raw,
+                                         int windowBits,int memLevel, int strategy,
+                                         const char* password, uLong crcForCrypting)
+{
+    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+                                 extrafield_local, size_extrafield_local,
+                                 extrafield_global, size_extrafield_global,
+                                 comment, method, level, raw,
+                                 windowBits, memLevel, strategy,
+                                 password, crcForCrypting, VERSIONMADEBY, 0, 0);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip3_64(zipFile file, const char* filename, const zip_fileinfo* zipfi,
+                                         const void* extrafield_local, uInt size_extrafield_local,
+                                         const void* extrafield_global, uInt size_extrafield_global,
+                                         const char* comment, int method, int level, int raw,
+                                         int windowBits,int memLevel, int strategy,
+                                         const char* password, uLong crcForCrypting, int zip64)
+{
+    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+                                 extrafield_local, size_extrafield_local,
+                                 extrafield_global, size_extrafield_global,
+                                 comment, method, level, raw,
+                                 windowBits, memLevel, strategy,
+                                 password, crcForCrypting, VERSIONMADEBY, 0, zip64);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip2(zipFile file, const char* filename, const zip_fileinfo* zipfi,
+                                        const void* extrafield_local, uInt size_extrafield_local,
+                                        const void* extrafield_global, uInt size_extrafield_global,
+                                        const char* comment, int method, int level, int raw)
+{
+    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+                                 extrafield_local, size_extrafield_local,
+                                 extrafield_global, size_extrafield_global,
+                                 comment, method, level, raw,
+                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+                                 NULL, 0, VERSIONMADEBY, 0, 0);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip2_64(zipFile file, const char* filename, const zip_fileinfo* zipfi,
+                                        const void* extrafield_local, uInt size_extrafield_local,
+                                        const void* extrafield_global, uInt size_extrafield_global,
+                                        const char* comment, int method, int level, int raw, int zip64)
+{
+    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+                                 extrafield_local, size_extrafield_local,
+                                 extrafield_global, size_extrafield_global,
+                                 comment, method, level, raw,
+                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+                                 NULL, 0, VERSIONMADEBY, 0, zip64);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip64 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+                                        const void* extrafield_local, uInt size_extrafield_local,
+                                        const void*extrafield_global, uInt size_extrafield_global,
+                                        const char* comment, int method, int level, int zip64)
+{
+    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+                                 extrafield_local, size_extrafield_local,
+                                 extrafield_global, size_extrafield_global,
+                                 comment, method, level, 0,
+                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+                                 NULL, 0, VERSIONMADEBY, 0, zip64);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+                                        const void* extrafield_local, uInt size_extrafield_local,
+                                        const void*extrafield_global, uInt size_extrafield_global,
+                                        const char* comment, int method, int level)
+{
+    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+                                 extrafield_local, size_extrafield_local,
+                                 extrafield_global, size_extrafield_global,
+                                 comment, method, level, 0,
+                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+                                 NULL, 0, VERSIONMADEBY, 0, 0);
+}
+
+local int zip64FlushWriteBuffer(zip64_internal* zi)
+{
+    int err=ZIP_OK;
+
+    if (zi->ci.encrypt != 0)
+    {
+#ifndef NOCRYPT
+        uInt i;
+        int t;
+        for (i=0;i<zi->ci.pos_in_buffered_data;i++)
+            zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t);
+#endif
+    }
+
+    if (ZWRITE64(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) != zi->ci.pos_in_buffered_data)
+      err = ZIP_ERRNO;
+
+    zi->ci.totalCompressedData += zi->ci.pos_in_buffered_data;
+
+#ifdef HAVE_BZIP2
+    if(zi->ci.method == Z_BZIP2ED)
+    {
+      zi->ci.totalUncompressedData += zi->ci.bstream.total_in_lo32;
+      zi->ci.bstream.total_in_lo32 = 0;
+      zi->ci.bstream.total_in_hi32 = 0;
+    }
+    else
+#endif
+    {
+      zi->ci.totalUncompressedData += zi->ci.stream.total_in;
+      zi->ci.stream.total_in = 0;
+    }
+
+
+    zi->ci.pos_in_buffered_data = 0;
+
+    return err;
+}
+
+extern int ZEXPORT zipWriteInFileInZip (zipFile file,const void* buf,unsigned int len)
+{
+    zip64_internal* zi;
+    int err=ZIP_OK;
+
+    if (file == NULL)
+        return ZIP_PARAMERROR;
+    zi = (zip64_internal*)file;
+
+    if (zi->in_opened_file_inzip == 0)
+        return ZIP_PARAMERROR;
+
+    zi->ci.crc32 = crc32(zi->ci.crc32,buf,(uInt)len);
+
+#ifdef HAVE_BZIP2
+    if(zi->ci.method == Z_BZIP2ED && (!zi->ci.raw))
+    {
+      zi->ci.bstream.next_in = (void*)buf;
+      zi->ci.bstream.avail_in = len;
+      err = BZ_RUN_OK;
+
+      while ((err==BZ_RUN_OK) && (zi->ci.bstream.avail_in>0))
+      {
+        if (zi->ci.bstream.avail_out == 0)
+        {
+          if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
+            err = ZIP_ERRNO;
+          zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
+          zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
+        }
+
+
+        if(err != BZ_RUN_OK)
+          break;
+
+        if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
+        {
+          uLong uTotalOutBefore_lo = zi->ci.bstream.total_out_lo32;
+//          uLong uTotalOutBefore_hi = zi->ci.bstream.total_out_hi32;
+          err=BZ2_bzCompress(&zi->ci.bstream,  BZ_RUN);
+
+          zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore_lo) ;
+        }
+      }
+
+      if(err == BZ_RUN_OK)
+        err = ZIP_OK;
+    }
+    else
+#endif
+    {
+      zi->ci.stream.next_in = (Bytef*)buf;
+      zi->ci.stream.avail_in = len;
+
+      while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0))
+      {
+          if (zi->ci.stream.avail_out == 0)
+          {
+              if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
+                  err = ZIP_ERRNO;
+              zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
+              zi->ci.stream.next_out = zi->ci.buffered_data;
+          }
+
+
+          if(err != ZIP_OK)
+              break;
+
+          if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
+          {
+              uLong uTotalOutBefore = zi->ci.stream.total_out;
+              err=deflate(&zi->ci.stream,  Z_NO_FLUSH);
+              if(uTotalOutBefore > zi->ci.stream.total_out)
+              {
+                int bBreak = 0;
+                bBreak++;
+              }
+
+              zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ;
+          }
+          else
+          {
+              uInt copy_this,i;
+              if (zi->ci.stream.avail_in < zi->ci.stream.avail_out)
+                  copy_this = zi->ci.stream.avail_in;
+              else
+                  copy_this = zi->ci.stream.avail_out;
+
+              for (i = 0; i < copy_this; i++)
+                  *(((char*)zi->ci.stream.next_out)+i) =
+                      *(((const char*)zi->ci.stream.next_in)+i);
+              {
+                  zi->ci.stream.avail_in -= copy_this;
+                  zi->ci.stream.avail_out-= copy_this;
+                  zi->ci.stream.next_in+= copy_this;
+                  zi->ci.stream.next_out+= copy_this;
+                  zi->ci.stream.total_in+= copy_this;
+                  zi->ci.stream.total_out+= copy_this;
+                  zi->ci.pos_in_buffered_data += copy_this;
+              }
+          }
+      }// while(...)
+    }
+
+    return err;
+}
+
+extern int ZEXPORT zipCloseFileInZipRaw (zipFile file, uLong uncompressed_size, uLong crc32)
+{
+    return zipCloseFileInZipRaw64 (file, uncompressed_size, crc32);
+}
+
+extern int ZEXPORT zipCloseFileInZipRaw64 (zipFile file, ZPOS64_T uncompressed_size, uLong crc32)
+{
+    zip64_internal* zi;
+    ZPOS64_T compressed_size;
+    uLong invalidValue = 0xffffffff;
+    short datasize = 0;
+    int err=ZIP_OK;
+
+    if (file == NULL)
+        return ZIP_PARAMERROR;
+    zi = (zip64_internal*)file;
+
+    if (zi->in_opened_file_inzip == 0)
+        return ZIP_PARAMERROR;
+    zi->ci.stream.avail_in = 0;
+
+    if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
+                {
+                        while (err==ZIP_OK)
+                        {
+                                uLong uTotalOutBefore;
+                                if (zi->ci.stream.avail_out == 0)
+                                {
+                                        if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
+                                                err = ZIP_ERRNO;
+                                        zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
+                                        zi->ci.stream.next_out = zi->ci.buffered_data;
+                                }
+                                uTotalOutBefore = zi->ci.stream.total_out;
+                                err=deflate(&zi->ci.stream,  Z_FINISH);
+                                zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ;
+                        }
+                }
+    else if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
+    {
+#ifdef HAVE_BZIP2
+      err = BZ_FINISH_OK;
+      while (err==BZ_FINISH_OK)
+      {
+        uLong uTotalOutBefore;
+        if (zi->ci.bstream.avail_out == 0)
+        {
+          if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
+            err = ZIP_ERRNO;
+          zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
+          zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
+        }
+        uTotalOutBefore = zi->ci.bstream.total_out_lo32;
+        err=BZ2_bzCompress(&zi->ci.bstream,  BZ_FINISH);
+        if(err == BZ_STREAM_END)
+          err = Z_STREAM_END;
+
+        zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore);
+      }
+
+      if(err == BZ_FINISH_OK)
+        err = ZIP_OK;
+#endif
+    }
+
+    if (err==Z_STREAM_END)
+        err=ZIP_OK; /* this is normal */
+
+    if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK))
+                {
+        if (zip64FlushWriteBuffer(zi)==ZIP_ERRNO)
+            err = ZIP_ERRNO;
+                }
+
+    if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
+    {
+        int tmp_err = deflateEnd(&zi->ci.stream);
+        if (err == ZIP_OK)
+            err = tmp_err;
+        zi->ci.stream_initialised = 0;
+    }
+#ifdef HAVE_BZIP2
+    else if((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
+    {
+      int tmperr = BZ2_bzCompressEnd(&zi->ci.bstream);
+                        if (err==ZIP_OK)
+                                err = tmperr;
+                        zi->ci.stream_initialised = 0;
+    }
+#endif
+
+    if (!zi->ci.raw)
+    {
+        crc32 = (uLong)zi->ci.crc32;
+        uncompressed_size = zi->ci.totalUncompressedData;
+    }
+    compressed_size = zi->ci.totalCompressedData;
+
+#    ifndef NOCRYPT
+    compressed_size += zi->ci.crypt_header_size;
+#    endif
+
+    // update Current Item crc and sizes,
+    if(compressed_size >= 0xffffffff || uncompressed_size >= 0xffffffff || zi->ci.pos_local_header >= 0xffffffff)
+    {
+      /*version Made by*/
+      zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)45,2);
+      /*version needed*/
+      zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)45,2);
+
+    }
+
+    zip64local_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/
+
+
+    if(compressed_size >= 0xffffffff)
+      zip64local_putValue_inmemory(zi->ci.central_header+20, invalidValue,4); /*compr size*/
+    else
+      zip64local_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/
+
+    /// set internal file attributes field
+    if (zi->ci.stream.data_type == Z_ASCII)
+        zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2);
+
+    if(uncompressed_size >= 0xffffffff)
+      zip64local_putValue_inmemory(zi->ci.central_header+24, invalidValue,4); /*uncompr size*/
+    else
+      zip64local_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/
+
+    // Add ZIP64 extra info field for uncompressed size
+    if(uncompressed_size >= 0xffffffff)
+      datasize += 8;
+
+    // Add ZIP64 extra info field for compressed size
+    if(compressed_size >= 0xffffffff)
+      datasize += 8;
+
+    // Add ZIP64 extra info field for relative offset to local file header of current file
+    if(zi->ci.pos_local_header >= 0xffffffff)
+      datasize += 8;
+
+    if(datasize > 0)
+    {
+      char* p = NULL;
+
+      if((uLong)(datasize + 4) > zi->ci.size_centralExtraFree)
+      {
+        // we can not write more data to the buffer that we have room for.
+        return ZIP_BADZIPFILE;
+      }
+
+      p = zi->ci.central_header + zi->ci.size_centralheader;
+
+      // Add Extra Information Header for 'ZIP64 information'
+      zip64local_putValue_inmemory(p, 0x0001, 2); // HeaderID
+      p += 2;
+      zip64local_putValue_inmemory(p, datasize, 2); // DataSize
+      p += 2;
+
+      if(uncompressed_size >= 0xffffffff)
+      {
+        zip64local_putValue_inmemory(p, uncompressed_size, 8);
+        p += 8;
+      }
+
+      if(compressed_size >= 0xffffffff)
+      {
+        zip64local_putValue_inmemory(p, compressed_size, 8);
+        p += 8;
+      }
+
+      if(zi->ci.pos_local_header >= 0xffffffff)
+      {
+        zip64local_putValue_inmemory(p, zi->ci.pos_local_header, 8);
+        p += 8;
+      }
+
+      // Update how much extra free space we got in the memory buffer
+      // and increase the centralheader size so the new ZIP64 fields are included
+      // ( 4 below is the size of HeaderID and DataSize field )
+      zi->ci.size_centralExtraFree -= datasize + 4;
+      zi->ci.size_centralheader += datasize + 4;
+
+      // Update the extra info size field
+      zi->ci.size_centralExtra += datasize + 4;
+      zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)zi->ci.size_centralExtra,2);
+    }
+
+    if (err==ZIP_OK)
+        err = add_data_in_datablock(&zi->central_dir, zi->ci.central_header, (uLong)zi->ci.size_centralheader);
+
+    free(zi->ci.central_header);
+
+    if (err==ZIP_OK)
+    {
+        // Update the LocalFileHeader with the new values.
+
+        ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream);
+
+        if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0)
+            err = ZIP_ERRNO;
+
+        if (err==ZIP_OK)
+            err = zip64local_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */
+
+        if(uncompressed_size >= 0xffffffff || compressed_size >= 0xffffffff )
+        {
+          if(zi->ci.pos_zip64extrainfo > 0)
+          {
+            // Update the size in the ZIP64 extended field.
+            if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_zip64extrainfo + 4,ZLIB_FILEFUNC_SEEK_SET)!=0)
+              err = ZIP_ERRNO;
+
+            if (err==ZIP_OK) /* compressed size, unknown */
+              err = zip64local_putValue(&zi->z_filefunc, zi->filestream, uncompressed_size, 8);
+
+            if (err==ZIP_OK) /* uncompressed size, unknown */
+              err = zip64local_putValue(&zi->z_filefunc, zi->filestream, compressed_size, 8);
+          }
+          else
+              err = ZIP_BADZIPFILE; // Caller passed zip64 = 0, so no room for zip64 info -> fatal
+        }
+        else
+        {
+          if (err==ZIP_OK) /* compressed size, unknown */
+              err = zip64local_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4);
+
+          if (err==ZIP_OK) /* uncompressed size, unknown */
+              err = zip64local_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4);
+        }
+
+        if (ZSEEK64(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0)
+            err = ZIP_ERRNO;
+    }
+
+    zi->number_entry ++;
+    zi->in_opened_file_inzip = 0;
+
+    return err;
+}
+
+extern int ZEXPORT zipCloseFileInZip (zipFile file)
+{
+    return zipCloseFileInZipRaw (file,0,0);
+}
+
+int Write_Zip64EndOfCentralDirectoryLocator(zip64_internal* zi, ZPOS64_T zip64eocd_pos_inzip)
+{
+  int err = ZIP_OK;
+  ZPOS64_T pos = zip64eocd_pos_inzip - zi->add_position_when_writting_offset;
+
+  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDLOCHEADERMAGIC,4);
+
+  /*num disks*/
+    if (err==ZIP_OK) /* number of the disk with the start of the central directory */
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
+
+  /*relative offset*/
+    if (err==ZIP_OK) /* Relative offset to the Zip64EndOfCentralDirectory */
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream, pos,8);
+
+  /*total disks*/ /* Do not support spawning of disk so always say 1 here*/
+    if (err==ZIP_OK) /* number of the disk with the start of the central directory */
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)1,4);
+
+    return err;
+}
+
+int Write_Zip64EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip)
+{
+  int err = ZIP_OK;
+
+  uLong Zip64DataSize = 44;
+
+  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDHEADERMAGIC,4);
+
+  if (err==ZIP_OK) /* size of this 'zip64 end of central directory' */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)Zip64DataSize,8); // why ZPOS64_T of this ?
+
+  if (err==ZIP_OK) /* version made by */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);
+
+  if (err==ZIP_OK) /* version needed */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);
+
+  if (err==ZIP_OK) /* number of this disk */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
+
+  if (err==ZIP_OK) /* number of the disk with the start of the central directory */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
+
+  if (err==ZIP_OK) /* total number of entries in the central dir on this disk */
+    err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8);
+
+  if (err==ZIP_OK) /* total number of entries in the central dir */
+    err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8);
+
+  if (err==ZIP_OK) /* size of the central directory */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)size_centraldir,8);
+
+  if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */
+  {
+    ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (ZPOS64_T)pos,8);
+  }
+  return err;
+}
+int Write_EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip)
+{
+  int err = ZIP_OK;
+
+  /*signature*/
+  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4);
+
+  if (err==ZIP_OK) /* number of this disk */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2);
+
+  if (err==ZIP_OK) /* number of the disk with the start of the central directory */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2);
+
+  if (err==ZIP_OK) /* total number of entries in the central dir on this disk */
+  {
+    {
+      if(zi->number_entry >= 0xFFFF)
+        err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record
+      else
+        err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2);
+    }
+  }
+
+  if (err==ZIP_OK) /* total number of entries in the central dir */
+  {
+    if(zi->number_entry >= 0xFFFF)
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record
+    else
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2);
+  }
+
+  if (err==ZIP_OK) /* size of the central directory */
+    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4);
+
+  if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */
+  {
+    ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
+    if(pos >= 0xffffffff)
+    {
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)0xffffffff,4);
+    }
+    else
+      err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writting_offset),4);
+  }
+
+   return err;
+}
+
+int Write_GlobalComment(zip64_internal* zi, const char* global_comment)
+{
+  int err = ZIP_OK;
+  uInt size_global_comment = 0;
+
+  if(global_comment != NULL)
+    size_global_comment = (uInt)strlen(global_comment);
+
+  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2);
+
+  if (err == ZIP_OK && size_global_comment > 0)
+  {
+    if (ZWRITE64(zi->z_filefunc,zi->filestream, global_comment, size_global_comment) != size_global_comment)
+      err = ZIP_ERRNO;
+  }
+  return err;
+}
+
+extern int ZEXPORT zipClose (zipFile file, const char* global_comment)
+{
+    zip64_internal* zi;
+    int err = 0;
+    uLong size_centraldir = 0;
+    ZPOS64_T centraldir_pos_inzip;
+    ZPOS64_T pos;
+
+    if (file == NULL)
+        return ZIP_PARAMERROR;
+
+    zi = (zip64_internal*)file;
+
+    if (zi->in_opened_file_inzip == 1)
+    {
+        err = zipCloseFileInZip (file);
+    }
+
+#ifndef NO_ADDFILEINEXISTINGZIP
+    if (global_comment==NULL)
+        global_comment = zi->globalcomment;
+#endif
+
+    centraldir_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream);
+
+    if (err==ZIP_OK)
+    {
+        linkedlist_datablock_internal* ldi = zi->central_dir.first_block;
+        while (ldi!=NULL)
+        {
+            if ((err==ZIP_OK) && (ldi->filled_in_this_block>0))
+            {
+                if (ZWRITE64(zi->z_filefunc,zi->filestream, ldi->data, ldi->filled_in_this_block) != ldi->filled_in_this_block)
+                    err = ZIP_ERRNO;
+            }
+
+            size_centraldir += ldi->filled_in_this_block;
+            ldi = ldi->next_datablock;
+        }
+    }
+    free_linkedlist(&(zi->central_dir));
+
+    pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
+    if(pos >= 0xffffffff || zi->number_entry > 0xFFFF)
+    {
+      ZPOS64_T Zip64EOCDpos = ZTELL64(zi->z_filefunc,zi->filestream);
+      Write_Zip64EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip);
+
+      Write_Zip64EndOfCentralDirectoryLocator(zi, Zip64EOCDpos);
+    }
+
+    if (err==ZIP_OK)
+      err = Write_EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip);
+
+    if(err == ZIP_OK)
+      err = Write_GlobalComment(zi, global_comment);
+
+    if (ZCLOSE64(zi->z_filefunc,zi->filestream) != 0)
+        if (err == ZIP_OK)
+            err = ZIP_ERRNO;
+
+#ifndef NO_ADDFILEINEXISTINGZIP
+    TRYFREE(zi->globalcomment);
+#endif
+    TRYFREE(zi);
+
+    return err;
+}
+
+extern int ZEXPORT zipRemoveExtraInfoBlock (char* pData, int* dataLen, short sHeader)
+{
+  char* p = pData;
+  int size = 0;
+  char* pNewHeader;
+  char* pTmp;
+  short header;
+  short dataSize;
+
+  int retVal = ZIP_OK;
+
+  if(pData == NULL || *dataLen < 4)
+    return ZIP_PARAMERROR;
+
+  pNewHeader = (char*)ALLOC(*dataLen);
+  pTmp = pNewHeader;
+
+  while(p < (pData + *dataLen))
+  {
+    header = *(short*)p;
+    dataSize = *(((short*)p)+1);
+
+    if( header == sHeader ) // Header found.
+    {
+      p += dataSize + 4; // skip it. do not copy to temp buffer
+    }
+    else
+    {
+      // Extra Info block should not be removed, So copy it to the temp buffer.
+      memcpy(pTmp, p, dataSize + 4);
+      p += dataSize + 4;
+      size += dataSize + 4;
+    }
+
+  }
+
+  if(size < *dataLen)
+  {
+    // clean old extra info block.
+    memset(pData,0, *dataLen);
+
+    // copy the new extra info block over the old
+    if(size > 0)
+      memcpy(pData, pNewHeader, size);
+
+    // set the new extra info size
+    *dataLen = size;
+
+    retVal = ZIP_OK;
+  }
+  else
+    retVal = ZIP_ERRNO;
+
+  TRYFREE(pNewHeader);
+
+  return retVal;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/zip.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/minizip/zip.h
new file mode 100644 (file)
index 0000000..8aaebb6
--- /dev/null
@@ -0,0 +1,362 @@
+/* zip.h -- IO on .zip files using zlib
+   Version 1.1, February 14h, 2010
+   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+         Modifications for Zip64 support
+         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+         For more info read MiniZip_info.txt
+
+         ---------------------------------------------------------------------------
+
+   Condition of use and distribution are the same than zlib :
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+        ---------------------------------------------------------------------------
+
+        Changes
+
+        See header of zip.h
+
+*/
+
+#ifndef _zip12_H
+#define _zip12_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//#define HAVE_BZIP2
+
+#ifndef _ZLIB_H
+#include "zlib.h"
+#endif
+
+#ifndef _ZLIBIOAPI_H
+#include "ioapi.h"
+#endif
+
+#ifdef HAVE_BZIP2
+#include "bzlib.h"
+#endif
+
+#define Z_BZIP2ED 12
+
+#if defined(STRICTZIP) || defined(STRICTZIPUNZIP)
+/* like the STRICT of WIN32, we define a pointer that cannot be converted
+    from (void*) without cast */
+typedef struct TagzipFile__ { int unused; } zipFile__;
+typedef zipFile__ *zipFile;
+#else
+typedef voidp zipFile;
+#endif
+
+#define ZIP_OK                          (0)
+#define ZIP_EOF                         (0)
+#define ZIP_ERRNO                       (Z_ERRNO)
+#define ZIP_PARAMERROR                  (-102)
+#define ZIP_BADZIPFILE                  (-103)
+#define ZIP_INTERNALERROR               (-104)
+
+#ifndef DEF_MEM_LEVEL
+#  if MAX_MEM_LEVEL >= 8
+#    define DEF_MEM_LEVEL 8
+#  else
+#    define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#  endif
+#endif
+/* default memLevel */
+
+/* tm_zip contain date/time info */
+typedef struct tm_zip_s
+{
+    uInt tm_sec;            /* seconds after the minute - [0,59] */
+    uInt tm_min;            /* minutes after the hour - [0,59] */
+    uInt tm_hour;           /* hours since midnight - [0,23] */
+    uInt tm_mday;           /* day of the month - [1,31] */
+    uInt tm_mon;            /* months since January - [0,11] */
+    uInt tm_year;           /* years - [1980..2044] */
+} tm_zip;
+
+typedef struct
+{
+    tm_zip      tmz_date;       /* date in understandable format           */
+    uLong       dosDate;       /* if dos_date == 0, tmu_date is used      */
+/*    uLong       flag;        */   /* general purpose bit flag        2 bytes */
+
+    uLong       internal_fa;    /* internal file attributes        2 bytes */
+    uLong       external_fa;    /* external file attributes        4 bytes */
+} zip_fileinfo;
+
+typedef const char* zipcharpc;
+
+
+#define APPEND_STATUS_CREATE        (0)
+#define APPEND_STATUS_CREATEAFTER   (1)
+#define APPEND_STATUS_ADDINZIP      (2)
+
+extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append));
+extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append));
+/*
+  Create a zipfile.
+     pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on
+       an Unix computer "zlib/zlib113.zip".
+     if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip
+       will be created at the end of the file.
+         (useful if the file contain a self extractor code)
+     if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will
+       add files in existing zip (be sure you don't add file that doesn't exist)
+     If the zipfile cannot be opened, the return value is NULL.
+     Else, the return value is a zipFile Handle, usable with other function
+       of this zip package.
+*/
+
+/* Note : there is no delete function into a zipfile.
+   If you want delete file into a zipfile, you must open a zipfile, and create another
+   Of couse, you can use RAW reading and writing to copy the file you did not want delte
+*/
+
+extern zipFile ZEXPORT zipOpen2 OF((const char *pathname,
+                                   int append,
+                                   zipcharpc* globalcomment,
+                                   zlib_filefunc_def* pzlib_filefunc_def));
+
+extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname,
+                                   int append,
+                                   zipcharpc* globalcomment,
+                                   zlib_filefunc64_def* pzlib_filefunc_def));
+
+extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
+                       const char* filename,
+                       const zip_fileinfo* zipfi,
+                       const void* extrafield_local,
+                       uInt size_extrafield_local,
+                       const void* extrafield_global,
+                       uInt size_extrafield_global,
+                       const char* comment,
+                       int method,
+                       int level));
+
+extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file,
+                       const char* filename,
+                       const zip_fileinfo* zipfi,
+                       const void* extrafield_local,
+                       uInt size_extrafield_local,
+                       const void* extrafield_global,
+                       uInt size_extrafield_global,
+                       const char* comment,
+                       int method,
+                       int level,
+                       int zip64));
+
+/*
+  Open a file in the ZIP for writing.
+  filename : the filename in zip (if NULL, '-' without quote will be used
+  *zipfi contain supplemental information
+  if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local
+    contains the extrafield data the the local header
+  if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global
+    contains the extrafield data the the local header
+  if comment != NULL, comment contain the comment string
+  method contain the compression method (0 for store, Z_DEFLATED for deflate)
+  level contain the level of compression (can be Z_DEFAULT_COMPRESSION)
+  zip64 is set to 1 if a zip64 extended information block should be added to the local file header.
+                    this MUST be '1' if the uncompressed size is >= 0xffffffff.
+
+*/
+
+
+extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file,
+                                            const char* filename,
+                                            const zip_fileinfo* zipfi,
+                                            const void* extrafield_local,
+                                            uInt size_extrafield_local,
+                                            const void* extrafield_global,
+                                            uInt size_extrafield_global,
+                                            const char* comment,
+                                            int method,
+                                            int level,
+                                            int raw));
+
+
+extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file,
+                                            const char* filename,
+                                            const zip_fileinfo* zipfi,
+                                            const void* extrafield_local,
+                                            uInt size_extrafield_local,
+                                            const void* extrafield_global,
+                                            uInt size_extrafield_global,
+                                            const char* comment,
+                                            int method,
+                                            int level,
+                                            int raw,
+                                            int zip64));
+/*
+  Same than zipOpenNewFileInZip, except if raw=1, we write raw file
+ */
+
+extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file,
+                                            const char* filename,
+                                            const zip_fileinfo* zipfi,
+                                            const void* extrafield_local,
+                                            uInt size_extrafield_local,
+                                            const void* extrafield_global,
+                                            uInt size_extrafield_global,
+                                            const char* comment,
+                                            int method,
+                                            int level,
+                                            int raw,
+                                            int windowBits,
+                                            int memLevel,
+                                            int strategy,
+                                            const char* password,
+                                            uLong crcForCrypting));
+
+extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file,
+                                            const char* filename,
+                                            const zip_fileinfo* zipfi,
+                                            const void* extrafield_local,
+                                            uInt size_extrafield_local,
+                                            const void* extrafield_global,
+                                            uInt size_extrafield_global,
+                                            const char* comment,
+                                            int method,
+                                            int level,
+                                            int raw,
+                                            int windowBits,
+                                            int memLevel,
+                                            int strategy,
+                                            const char* password,
+                                            uLong crcForCrypting,
+                                            int zip64
+                                            ));
+
+/*
+  Same than zipOpenNewFileInZip2, except
+    windowBits,memLevel,,strategy : see parameter strategy in deflateInit2
+    password : crypting password (NULL for no crypting)
+    crcForCrypting : crc of file to compress (needed for crypting)
+ */
+
+extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file,
+                                            const char* filename,
+                                            const zip_fileinfo* zipfi,
+                                            const void* extrafield_local,
+                                            uInt size_extrafield_local,
+                                            const void* extrafield_global,
+                                            uInt size_extrafield_global,
+                                            const char* comment,
+                                            int method,
+                                            int level,
+                                            int raw,
+                                            int windowBits,
+                                            int memLevel,
+                                            int strategy,
+                                            const char* password,
+                                            uLong crcForCrypting,
+                                            uLong versionMadeBy,
+                                            uLong flagBase
+                                            ));
+
+
+extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file,
+                                            const char* filename,
+                                            const zip_fileinfo* zipfi,
+                                            const void* extrafield_local,
+                                            uInt size_extrafield_local,
+                                            const void* extrafield_global,
+                                            uInt size_extrafield_global,
+                                            const char* comment,
+                                            int method,
+                                            int level,
+                                            int raw,
+                                            int windowBits,
+                                            int memLevel,
+                                            int strategy,
+                                            const char* password,
+                                            uLong crcForCrypting,
+                                            uLong versionMadeBy,
+                                            uLong flagBase,
+                                            int zip64
+                                            ));
+/*
+  Same than zipOpenNewFileInZip4, except
+    versionMadeBy : value for Version made by field
+    flag : value for flag field (compression level info will be added)
+ */
+
+
+extern int ZEXPORT zipWriteInFileInZip OF((zipFile file,
+                       const void* buf,
+                       unsigned len));
+/*
+  Write data in the zipfile
+*/
+
+extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
+/*
+  Close the current file in the zipfile
+*/
+
+extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file,
+                                            uLong uncompressed_size,
+                                            uLong crc32));
+
+extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file,
+                                            ZPOS64_T uncompressed_size,
+                                            uLong crc32));
+
+/*
+  Close the current file in the zipfile, for file opened with
+    parameter raw=1 in zipOpenNewFileInZip2
+  uncompressed_size and crc32 are value for the uncompressed size
+*/
+
+extern int ZEXPORT zipClose OF((zipFile file,
+                const char* global_comment));
+/*
+  Close the zipfile
+*/
+
+
+extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader));
+/*
+  zipRemoveExtraInfoBlock -  Added by Mathias Svensson
+
+  Remove extra information block from a extra information data for the local file header or central directory header
+
+  It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode.
+
+  0x0001 is the signature header for the ZIP64 extra information blocks
+
+  usage.
+                        Remove ZIP64 Extra information from a central director extra field data
+              zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001);
+
+                        Remove ZIP64 Extra information from a Local File Header extra field data
+        zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001);
+*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _zip64_H */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/example.pas b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/example.pas
new file mode 100644 (file)
index 0000000..5518b36
--- /dev/null
@@ -0,0 +1,599 @@
+(* example.c -- usage example of the zlib compression library
+ * Copyright (C) 1995-2003 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ *
+ * Pascal translation
+ * Copyright (C) 1998 by Jacques Nomssi Nzali.
+ * For conditions of distribution and use, see copyright notice in readme.txt
+ *
+ * Adaptation to the zlibpas interface
+ * Copyright (C) 2003 by Cosmin Truta.
+ * For conditions of distribution and use, see copyright notice in readme.txt
+ *)
+
+program example;
+
+{$DEFINE TEST_COMPRESS}
+{DO NOT $DEFINE TEST_GZIO}
+{$DEFINE TEST_DEFLATE}
+{$DEFINE TEST_INFLATE}
+{$DEFINE TEST_FLUSH}
+{$DEFINE TEST_SYNC}
+{$DEFINE TEST_DICT}
+
+uses SysUtils, zlibpas;
+
+const TESTFILE = 'foo.gz';
+
+(* "hello world" would be more standard, but the repeated "hello"
+ * stresses the compression code better, sorry...
+ *)
+const hello: PChar = 'hello, hello!';
+
+const dictionary: PChar = 'hello';
+
+var dictId: LongInt; (* Adler32 value of the dictionary *)
+
+procedure CHECK_ERR(err: Integer; msg: String);
+begin
+  if err <> Z_OK then
+  begin
+    WriteLn(msg, ' error: ', err);
+    Halt(1);
+  end;
+end;
+
+procedure EXIT_ERR(const msg: String);
+begin
+  WriteLn('Error: ', msg);
+  Halt(1);
+end;
+
+(* ===========================================================================
+ * Test compress and uncompress
+ *)
+{$IFDEF TEST_COMPRESS}
+procedure test_compress(compr: Pointer; comprLen: LongInt;
+                        uncompr: Pointer; uncomprLen: LongInt);
+var err: Integer;
+    len: LongInt;
+begin
+  len := StrLen(hello)+1;
+
+  err := compress(compr, comprLen, hello, len);
+  CHECK_ERR(err, 'compress');
+
+  StrCopy(PChar(uncompr), 'garbage');
+
+  err := uncompress(uncompr, uncomprLen, compr, comprLen);
+  CHECK_ERR(err, 'uncompress');
+
+  if StrComp(PChar(uncompr), hello) <> 0 then
+    EXIT_ERR('bad uncompress')
+  else
+    WriteLn('uncompress(): ', PChar(uncompr));
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test read/write of .gz files
+ *)
+{$IFDEF TEST_GZIO}
+procedure test_gzio(const fname: PChar; (* compressed file name *)
+                    uncompr: Pointer;
+                    uncomprLen: LongInt);
+var err: Integer;
+    len: Integer;
+    zfile: gzFile;
+    pos: LongInt;
+begin
+  len := StrLen(hello)+1;
+
+  zfile := gzopen(fname, 'wb');
+  if zfile = NIL then
+  begin
+    WriteLn('gzopen error');
+    Halt(1);
+  end;
+  gzputc(zfile, 'h');
+  if gzputs(zfile, 'ello') <> 4 then
+  begin
+    WriteLn('gzputs err: ', gzerror(zfile, err));
+    Halt(1);
+  end;
+  {$IFDEF GZ_FORMAT_STRING}
+  if gzprintf(zfile, ', %s!', 'hello') <> 8 then
+  begin
+    WriteLn('gzprintf err: ', gzerror(zfile, err));
+    Halt(1);
+  end;
+  {$ELSE}
+  if gzputs(zfile, ', hello!') <> 8 then
+  begin
+    WriteLn('gzputs err: ', gzerror(zfile, err));
+    Halt(1);
+  end;
+  {$ENDIF}
+  gzseek(zfile, 1, SEEK_CUR); (* add one zero byte *)
+  gzclose(zfile);
+
+  zfile := gzopen(fname, 'rb');
+  if zfile = NIL then
+  begin
+    WriteLn('gzopen error');
+    Halt(1);
+  end;
+
+  StrCopy(PChar(uncompr), 'garbage');
+
+  if gzread(zfile, uncompr, uncomprLen) <> len then
+  begin
+    WriteLn('gzread err: ', gzerror(zfile, err));
+    Halt(1);
+  end;
+  if StrComp(PChar(uncompr), hello) <> 0 then
+  begin
+    WriteLn('bad gzread: ', PChar(uncompr));
+    Halt(1);
+  end
+  else
+    WriteLn('gzread(): ', PChar(uncompr));
+
+  pos := gzseek(zfile, -8, SEEK_CUR);
+  if (pos <> 6) or (gztell(zfile) <> pos) then
+  begin
+    WriteLn('gzseek error, pos=', pos, ', gztell=', gztell(zfile));
+    Halt(1);
+  end;
+
+  if gzgetc(zfile) <> ' ' then
+  begin
+    WriteLn('gzgetc error');
+    Halt(1);
+  end;
+
+  if gzungetc(' ', zfile) <> ' ' then
+  begin
+    WriteLn('gzungetc error');
+    Halt(1);
+  end;
+
+  gzgets(zfile, PChar(uncompr), uncomprLen);
+  uncomprLen := StrLen(PChar(uncompr));
+  if uncomprLen <> 7 then (* " hello!" *)
+  begin
+    WriteLn('gzgets err after gzseek: ', gzerror(zfile, err));
+    Halt(1);
+  end;
+  if StrComp(PChar(uncompr), hello + 6) <> 0 then
+  begin
+    WriteLn('bad gzgets after gzseek');
+    Halt(1);
+  end
+  else
+    WriteLn('gzgets() after gzseek: ', PChar(uncompr));
+
+  gzclose(zfile);
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test deflate with small buffers
+ *)
+{$IFDEF TEST_DEFLATE}
+procedure test_deflate(compr: Pointer; comprLen: LongInt);
+var c_stream: z_stream; (* compression stream *)
+    err: Integer;
+    len: LongInt;
+begin
+  len := StrLen(hello)+1;
+
+  c_stream.zalloc := NIL;
+  c_stream.zfree := NIL;
+  c_stream.opaque := NIL;
+
+  err := deflateInit(c_stream, Z_DEFAULT_COMPRESSION);
+  CHECK_ERR(err, 'deflateInit');
+
+  c_stream.next_in := hello;
+  c_stream.next_out := compr;
+
+  while (c_stream.total_in <> len) and
+        (c_stream.total_out < comprLen) do
+  begin
+    c_stream.avail_out := 1; { force small buffers }
+    c_stream.avail_in := 1;
+    err := deflate(c_stream, Z_NO_FLUSH);
+    CHECK_ERR(err, 'deflate');
+  end;
+
+  (* Finish the stream, still forcing small buffers: *)
+  while TRUE do
+  begin
+    c_stream.avail_out := 1;
+    err := deflate(c_stream, Z_FINISH);
+    if err = Z_STREAM_END then
+      break;
+    CHECK_ERR(err, 'deflate');
+  end;
+
+  err := deflateEnd(c_stream);
+  CHECK_ERR(err, 'deflateEnd');
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test inflate with small buffers
+ *)
+{$IFDEF TEST_INFLATE}
+procedure test_inflate(compr: Pointer; comprLen : LongInt;
+                       uncompr: Pointer; uncomprLen : LongInt);
+var err: Integer;
+    d_stream: z_stream; (* decompression stream *)
+begin
+  StrCopy(PChar(uncompr), 'garbage');
+
+  d_stream.zalloc := NIL;
+  d_stream.zfree := NIL;
+  d_stream.opaque := NIL;
+
+  d_stream.next_in := compr;
+  d_stream.avail_in := 0;
+  d_stream.next_out := uncompr;
+
+  err := inflateInit(d_stream);
+  CHECK_ERR(err, 'inflateInit');
+
+  while (d_stream.total_out < uncomprLen) and
+        (d_stream.total_in < comprLen) do
+  begin
+    d_stream.avail_out := 1; (* force small buffers *)
+    d_stream.avail_in := 1;
+    err := inflate(d_stream, Z_NO_FLUSH);
+    if err = Z_STREAM_END then
+      break;
+    CHECK_ERR(err, 'inflate');
+  end;
+
+  err := inflateEnd(d_stream);
+  CHECK_ERR(err, 'inflateEnd');
+
+  if StrComp(PChar(uncompr), hello) <> 0 then
+    EXIT_ERR('bad inflate')
+  else
+    WriteLn('inflate(): ', PChar(uncompr));
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test deflate with large buffers and dynamic change of compression level
+ *)
+{$IFDEF TEST_DEFLATE}
+procedure test_large_deflate(compr: Pointer; comprLen: LongInt;
+                             uncompr: Pointer; uncomprLen: LongInt);
+var c_stream: z_stream; (* compression stream *)
+    err: Integer;
+begin
+  c_stream.zalloc := NIL;
+  c_stream.zfree := NIL;
+  c_stream.opaque := NIL;
+
+  err := deflateInit(c_stream, Z_BEST_SPEED);
+  CHECK_ERR(err, 'deflateInit');
+
+  c_stream.next_out := compr;
+  c_stream.avail_out := Integer(comprLen);
+
+  (* At this point, uncompr is still mostly zeroes, so it should compress
+   * very well:
+   *)
+  c_stream.next_in := uncompr;
+  c_stream.avail_in := Integer(uncomprLen);
+  err := deflate(c_stream, Z_NO_FLUSH);
+  CHECK_ERR(err, 'deflate');
+  if c_stream.avail_in <> 0 then
+    EXIT_ERR('deflate not greedy');
+
+  (* Feed in already compressed data and switch to no compression: *)
+  deflateParams(c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY);
+  c_stream.next_in := compr;
+  c_stream.avail_in := Integer(comprLen div 2);
+  err := deflate(c_stream, Z_NO_FLUSH);
+  CHECK_ERR(err, 'deflate');
+
+  (* Switch back to compressing mode: *)
+  deflateParams(c_stream, Z_BEST_COMPRESSION, Z_FILTERED);
+  c_stream.next_in := uncompr;
+  c_stream.avail_in := Integer(uncomprLen);
+  err := deflate(c_stream, Z_NO_FLUSH);
+  CHECK_ERR(err, 'deflate');
+
+  err := deflate(c_stream, Z_FINISH);
+  if err <> Z_STREAM_END then
+    EXIT_ERR('deflate should report Z_STREAM_END');
+
+  err := deflateEnd(c_stream);
+  CHECK_ERR(err, 'deflateEnd');
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test inflate with large buffers
+ *)
+{$IFDEF TEST_INFLATE}
+procedure test_large_inflate(compr: Pointer; comprLen: LongInt;
+                             uncompr: Pointer; uncomprLen: LongInt);
+var err: Integer;
+    d_stream: z_stream; (* decompression stream *)
+begin
+  StrCopy(PChar(uncompr), 'garbage');
+
+  d_stream.zalloc := NIL;
+  d_stream.zfree := NIL;
+  d_stream.opaque := NIL;
+
+  d_stream.next_in := compr;
+  d_stream.avail_in := Integer(comprLen);
+
+  err := inflateInit(d_stream);
+  CHECK_ERR(err, 'inflateInit');
+
+  while TRUE do
+  begin
+    d_stream.next_out := uncompr;            (* discard the output *)
+    d_stream.avail_out := Integer(uncomprLen);
+    err := inflate(d_stream, Z_NO_FLUSH);
+    if err = Z_STREAM_END then
+      break;
+    CHECK_ERR(err, 'large inflate');
+  end;
+
+  err := inflateEnd(d_stream);
+  CHECK_ERR(err, 'inflateEnd');
+
+  if d_stream.total_out <> 2 * uncomprLen + comprLen div 2 then
+  begin
+    WriteLn('bad large inflate: ', d_stream.total_out);
+    Halt(1);
+  end
+  else
+    WriteLn('large_inflate(): OK');
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test deflate with full flush
+ *)
+{$IFDEF TEST_FLUSH}
+procedure test_flush(compr: Pointer; var comprLen : LongInt);
+var c_stream: z_stream; (* compression stream *)
+    err: Integer;
+    len: Integer;
+begin
+  len := StrLen(hello)+1;
+
+  c_stream.zalloc := NIL;
+  c_stream.zfree := NIL;
+  c_stream.opaque := NIL;
+
+  err := deflateInit(c_stream, Z_DEFAULT_COMPRESSION);
+  CHECK_ERR(err, 'deflateInit');
+
+  c_stream.next_in := hello;
+  c_stream.next_out := compr;
+  c_stream.avail_in := 3;
+  c_stream.avail_out := Integer(comprLen);
+  err := deflate(c_stream, Z_FULL_FLUSH);
+  CHECK_ERR(err, 'deflate');
+
+  Inc(PByteArray(compr)^[3]); (* force an error in first compressed block *)
+  c_stream.avail_in := len - 3;
+
+  err := deflate(c_stream, Z_FINISH);
+  if err <> Z_STREAM_END then
+    CHECK_ERR(err, 'deflate');
+
+  err := deflateEnd(c_stream);
+  CHECK_ERR(err, 'deflateEnd');
+
+  comprLen := c_stream.total_out;
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test inflateSync()
+ *)
+{$IFDEF TEST_SYNC}
+procedure test_sync(compr: Pointer; comprLen: LongInt;
+                    uncompr: Pointer; uncomprLen : LongInt);
+var err: Integer;
+    d_stream: z_stream; (* decompression stream *)
+begin
+  StrCopy(PChar(uncompr), 'garbage');
+
+  d_stream.zalloc := NIL;
+  d_stream.zfree := NIL;
+  d_stream.opaque := NIL;
+
+  d_stream.next_in := compr;
+  d_stream.avail_in := 2; (* just read the zlib header *)
+
+  err := inflateInit(d_stream);
+  CHECK_ERR(err, 'inflateInit');
+
+  d_stream.next_out := uncompr;
+  d_stream.avail_out := Integer(uncomprLen);
+
+  inflate(d_stream, Z_NO_FLUSH);
+  CHECK_ERR(err, 'inflate');
+
+  d_stream.avail_in := Integer(comprLen-2);   (* read all compressed data *)
+  err := inflateSync(d_stream);               (* but skip the damaged part *)
+  CHECK_ERR(err, 'inflateSync');
+
+  err := inflate(d_stream, Z_FINISH);
+  if err <> Z_DATA_ERROR then
+    EXIT_ERR('inflate should report DATA_ERROR');
+    (* Because of incorrect adler32 *)
+
+  err := inflateEnd(d_stream);
+  CHECK_ERR(err, 'inflateEnd');
+
+  WriteLn('after inflateSync(): hel', PChar(uncompr));
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test deflate with preset dictionary
+ *)
+{$IFDEF TEST_DICT}
+procedure test_dict_deflate(compr: Pointer; comprLen: LongInt);
+var c_stream: z_stream; (* compression stream *)
+    err: Integer;
+begin
+  c_stream.zalloc := NIL;
+  c_stream.zfree := NIL;
+  c_stream.opaque := NIL;
+
+  err := deflateInit(c_stream, Z_BEST_COMPRESSION);
+  CHECK_ERR(err, 'deflateInit');
+
+  err := deflateSetDictionary(c_stream, dictionary, StrLen(dictionary));
+  CHECK_ERR(err, 'deflateSetDictionary');
+
+  dictId := c_stream.adler;
+  c_stream.next_out := compr;
+  c_stream.avail_out := Integer(comprLen);
+
+  c_stream.next_in := hello;
+  c_stream.avail_in := StrLen(hello)+1;
+
+  err := deflate(c_stream, Z_FINISH);
+  if err <> Z_STREAM_END then
+    EXIT_ERR('deflate should report Z_STREAM_END');
+
+  err := deflateEnd(c_stream);
+  CHECK_ERR(err, 'deflateEnd');
+end;
+{$ENDIF}
+
+(* ===========================================================================
+ * Test inflate with a preset dictionary
+ *)
+{$IFDEF TEST_DICT}
+procedure test_dict_inflate(compr: Pointer; comprLen: LongInt;
+                            uncompr: Pointer; uncomprLen: LongInt);
+var err: Integer;
+    d_stream: z_stream; (* decompression stream *)
+begin
+  StrCopy(PChar(uncompr), 'garbage');
+
+  d_stream.zalloc := NIL;
+  d_stream.zfree := NIL;
+  d_stream.opaque := NIL;
+
+  d_stream.next_in := compr;
+  d_stream.avail_in := Integer(comprLen);
+
+  err := inflateInit(d_stream);
+  CHECK_ERR(err, 'inflateInit');
+
+  d_stream.next_out := uncompr;
+  d_stream.avail_out := Integer(uncomprLen);
+
+  while TRUE do
+  begin
+    err := inflate(d_stream, Z_NO_FLUSH);
+    if err = Z_STREAM_END then
+      break;
+    if err = Z_NEED_DICT then
+    begin
+      if d_stream.adler <> dictId then
+        EXIT_ERR('unexpected dictionary');
+      err := inflateSetDictionary(d_stream, dictionary, StrLen(dictionary));
+    end;
+    CHECK_ERR(err, 'inflate with dict');
+  end;
+
+  err := inflateEnd(d_stream);
+  CHECK_ERR(err, 'inflateEnd');
+
+  if StrComp(PChar(uncompr), hello) <> 0 then
+    EXIT_ERR('bad inflate with dict')
+  else
+    WriteLn('inflate with dictionary: ', PChar(uncompr));
+end;
+{$ENDIF}
+
+var compr, uncompr: Pointer;
+    comprLen, uncomprLen: LongInt;
+
+begin
+  if zlibVersion^ <> ZLIB_VERSION[1] then
+    EXIT_ERR('Incompatible zlib version');
+
+  WriteLn('zlib version: ', zlibVersion);
+  WriteLn('zlib compile flags: ', Format('0x%x', [zlibCompileFlags]));
+
+  comprLen := 10000 * SizeOf(Integer); (* don't overflow on MSDOS *)
+  uncomprLen := comprLen;
+  GetMem(compr, comprLen);
+  GetMem(uncompr, uncomprLen);
+  if (compr = NIL) or (uncompr = NIL) then
+    EXIT_ERR('Out of memory');
+  (* compr and uncompr are cleared to avoid reading uninitialized
+   * data and to ensure that uncompr compresses well.
+   *)
+  FillChar(compr^, comprLen, 0);
+  FillChar(uncompr^, uncomprLen, 0);
+
+  {$IFDEF TEST_COMPRESS}
+  WriteLn('** Testing compress');
+  test_compress(compr, comprLen, uncompr, uncomprLen);
+  {$ENDIF}
+
+  {$IFDEF TEST_GZIO}
+  WriteLn('** Testing gzio');
+  if ParamCount >= 1 then
+    test_gzio(ParamStr(1), uncompr, uncomprLen)
+  else
+    test_gzio(TESTFILE, uncompr, uncomprLen);
+  {$ENDIF}
+
+  {$IFDEF TEST_DEFLATE}
+  WriteLn('** Testing deflate with small buffers');
+  test_deflate(compr, comprLen);
+  {$ENDIF}
+  {$IFDEF TEST_INFLATE}
+  WriteLn('** Testing inflate with small buffers');
+  test_inflate(compr, comprLen, uncompr, uncomprLen);
+  {$ENDIF}
+
+  {$IFDEF TEST_DEFLATE}
+  WriteLn('** Testing deflate with large buffers');
+  test_large_deflate(compr, comprLen, uncompr, uncomprLen);
+  {$ENDIF}
+  {$IFDEF TEST_INFLATE}
+  WriteLn('** Testing inflate with large buffers');
+  test_large_inflate(compr, comprLen, uncompr, uncomprLen);
+  {$ENDIF}
+
+  {$IFDEF TEST_FLUSH}
+  WriteLn('** Testing deflate with full flush');
+  test_flush(compr, comprLen);
+  {$ENDIF}
+  {$IFDEF TEST_SYNC}
+  WriteLn('** Testing inflateSync');
+  test_sync(compr, comprLen, uncompr, uncomprLen);
+  {$ENDIF}
+  comprLen := uncomprLen;
+
+  {$IFDEF TEST_DICT}
+  WriteLn('** Testing deflate and inflate with preset dictionary');
+  test_dict_deflate(compr, comprLen);
+  test_dict_inflate(compr, comprLen, uncompr, uncomprLen);
+  {$ENDIF}
+
+  FreeMem(compr, comprLen);
+  FreeMem(uncompr, uncomprLen);
+end.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/readme.txt
new file mode 100644 (file)
index 0000000..60e87c8
--- /dev/null
@@ -0,0 +1,76 @@
+
+This directory contains a Pascal (Delphi, Kylix) interface to the
+zlib data compression library.
+
+
+Directory listing
+=================
+
+zlibd32.mak     makefile for Borland C++
+example.pas     usage example of zlib
+zlibpas.pas     the Pascal interface to zlib
+readme.txt      this file
+
+
+Compatibility notes
+===================
+
+- Although the name "zlib" would have been more normal for the
+  zlibpas unit, this name is already taken by Borland's ZLib unit.
+  This is somehow unfortunate, because that unit is not a genuine
+  interface to the full-fledged zlib functionality, but a suite of
+  class wrappers around zlib streams.  Other essential features,
+  such as checksums, are missing.
+  It would have been more appropriate for that unit to have a name
+  like "ZStreams", or something similar.
+
+- The C and zlib-supplied types int, uInt, long, uLong, etc. are
+  translated directly into Pascal types of similar sizes (Integer,
+  LongInt, etc.), to avoid namespace pollution.  In particular,
+  there is no conversion of unsigned int into a Pascal unsigned
+  integer.  The Word type is non-portable and has the same size
+  (16 bits) both in a 16-bit and in a 32-bit environment, unlike
+  Integer.  Even if there is a 32-bit Cardinal type, there is no
+  real need for unsigned int in zlib under a 32-bit environment.
+
+- Except for the callbacks, the zlib function interfaces are
+  assuming the calling convention normally used in Pascal
+  (__pascal for DOS and Windows16, __fastcall for Windows32).
+  Since the cdecl keyword is used, the old Turbo Pascal does
+  not work with this interface.
+
+- The gz* function interfaces are not translated, to avoid
+  interfacing problems with the C runtime library.  Besides,
+    gzprintf(gzFile file, const char *format, ...)
+  cannot be translated into Pascal.
+
+
+Legal issues
+============
+
+The zlibpas interface is:
+  Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler.
+  Copyright (C) 1998 by Bob Dellaca.
+  Copyright (C) 2003 by Cosmin Truta.
+
+The example program is:
+  Copyright (C) 1995-2003 by Jean-loup Gailly.
+  Copyright (C) 1998,1999,2000 by Jacques Nomssi Nzali.
+  Copyright (C) 2003 by Cosmin Truta.
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the author be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/zlibd32.mak b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/zlibd32.mak
new file mode 100644 (file)
index 0000000..9bb00b7
--- /dev/null
@@ -0,0 +1,99 @@
+# Makefile for zlib
+# For use with Delphi and C++ Builder under Win32
+# Updated for zlib 1.2.x by Cosmin Truta
+
+# ------------ Borland C++ ------------
+
+# This project uses the Delphi (fastcall/register) calling convention:
+LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl
+
+CC = bcc32
+LD = bcc32
+AR = tlib
+# do not use "-pr" in CFLAGS
+CFLAGS = -a -d -k- -O2 $(LOC)
+LDFLAGS =
+
+
+# variables
+ZLIB_LIB = zlib.lib
+
+OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj
+OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
+OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj
+OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
+
+
+# targets
+all: $(ZLIB_LIB) example.exe minigzip.exe
+
+.c.obj:
+       $(CC) -c $(CFLAGS) $*.c
+
+adler32.obj: adler32.c zlib.h zconf.h
+
+compress.obj: compress.c zlib.h zconf.h
+
+crc32.obj: crc32.c zlib.h zconf.h crc32.h
+
+deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
+
+gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
+
+gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
+
+gzread.obj: gzread.c zlib.h zconf.h gzguts.h
+
+gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
+
+infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h
+
+inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h
+
+trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h
+
+uncompr.obj: uncompr.c zlib.h zconf.h
+
+zutil.obj: zutil.c zutil.h zlib.h zconf.h
+
+example.obj: test/example.c zlib.h zconf.h
+
+minigzip.obj: test/minigzip.c zlib.h zconf.h
+
+
+# For the sake of the old Borland make,
+# the command line is cut to fit in the MS-DOS 128 byte limit:
+$(ZLIB_LIB): $(OBJ1) $(OBJ2)
+       -del $(ZLIB_LIB)
+       $(AR) $(ZLIB_LIB) $(OBJP1)
+       $(AR) $(ZLIB_LIB) $(OBJP2)
+
+
+# testing
+test: example.exe minigzip.exe
+       example
+       echo hello world | minigzip | minigzip -d
+
+example.exe: example.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB)
+
+minigzip.exe: minigzip.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB)
+
+
+# cleanup
+clean:
+       -del *.obj
+       -del *.exe
+       -del *.lib
+       -del *.tds
+       -del zlib.bak
+       -del foo.gz
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/zlibpas.pas b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/pascal/zlibpas.pas
new file mode 100644 (file)
index 0000000..5c9875c
--- /dev/null
@@ -0,0 +1,276 @@
+(* zlibpas -- Pascal interface to the zlib data compression library
+ *
+ * Copyright (C) 2003 Cosmin Truta.
+ * Derived from original sources by Bob Dellaca.
+ * For conditions of distribution and use, see copyright notice in readme.txt
+ *)
+
+unit zlibpas;
+
+interface
+
+const
+  ZLIB_VERSION = '1.2.6';
+  ZLIB_VERNUM  = $1260;
+
+type
+  alloc_func = function(opaque: Pointer; items, size: Integer): Pointer;
+                 cdecl;
+  free_func  = procedure(opaque, address: Pointer);
+                 cdecl;
+
+  in_func    = function(opaque: Pointer; var buf: PByte): Integer;
+                 cdecl;
+  out_func   = function(opaque: Pointer; buf: PByte; size: Integer): Integer;
+                 cdecl;
+
+  z_streamp = ^z_stream;
+  z_stream = packed record
+    next_in: PChar;       (* next input byte *)
+    avail_in: Integer;    (* number of bytes available at next_in *)
+    total_in: LongInt;    (* total nb of input bytes read so far *)
+
+    next_out: PChar;      (* next output byte should be put there *)
+    avail_out: Integer;   (* remaining free space at next_out *)
+    total_out: LongInt;   (* total nb of bytes output so far *)
+
+    msg: PChar;           (* last error message, NULL if no error *)
+    state: Pointer;       (* not visible by applications *)
+
+    zalloc: alloc_func;   (* used to allocate the internal state *)
+    zfree: free_func;     (* used to free the internal state *)
+    opaque: Pointer;      (* private data object passed to zalloc and zfree *)
+
+    data_type: Integer;   (* best guess about the data type: ascii or binary *)
+    adler: LongInt;       (* adler32 value of the uncompressed data *)
+    reserved: LongInt;    (* reserved for future use *)
+  end;
+
+  gz_headerp = ^gz_header;
+  gz_header = packed record
+    text: Integer;        (* true if compressed data believed to be text *)
+    time: LongInt;        (* modification time *)
+    xflags: Integer;      (* extra flags (not used when writing a gzip file) *)
+    os: Integer;          (* operating system *)
+    extra: PChar;         (* pointer to extra field or Z_NULL if none *)
+    extra_len: Integer;   (* extra field length (valid if extra != Z_NULL) *)
+    extra_max: Integer;   (* space at extra (only when reading header) *)
+    name: PChar;          (* pointer to zero-terminated file name or Z_NULL *)
+    name_max: Integer;    (* space at name (only when reading header) *)
+    comment: PChar;       (* pointer to zero-terminated comment or Z_NULL *)
+    comm_max: Integer;    (* space at comment (only when reading header) *)
+    hcrc: Integer;        (* true if there was or will be a header crc *)
+    done: Integer;        (* true when done reading gzip header *)
+  end;
+
+(* constants *)
+const
+  Z_NO_FLUSH      = 0;
+  Z_PARTIAL_FLUSH = 1;
+  Z_SYNC_FLUSH    = 2;
+  Z_FULL_FLUSH    = 3;
+  Z_FINISH        = 4;
+  Z_BLOCK         = 5;
+  Z_TREES         = 6;
+
+  Z_OK            =  0;
+  Z_STREAM_END    =  1;
+  Z_NEED_DICT     =  2;
+  Z_ERRNO         = -1;
+  Z_STREAM_ERROR  = -2;
+  Z_DATA_ERROR    = -3;
+  Z_MEM_ERROR     = -4;
+  Z_BUF_ERROR     = -5;
+  Z_VERSION_ERROR = -6;
+
+  Z_NO_COMPRESSION       =  0;
+  Z_BEST_SPEED           =  1;
+  Z_BEST_COMPRESSION     =  9;
+  Z_DEFAULT_COMPRESSION  = -1;
+
+  Z_FILTERED            = 1;
+  Z_HUFFMAN_ONLY        = 2;
+  Z_RLE                 = 3;
+  Z_FIXED               = 4;
+  Z_DEFAULT_STRATEGY    = 0;
+
+  Z_BINARY   = 0;
+  Z_TEXT     = 1;
+  Z_ASCII    = 1;
+  Z_UNKNOWN  = 2;
+
+  Z_DEFLATED = 8;
+
+(* basic functions *)
+function zlibVersion: PChar;
+function deflateInit(var strm: z_stream; level: Integer): Integer;
+function deflate(var strm: z_stream; flush: Integer): Integer;
+function deflateEnd(var strm: z_stream): Integer;
+function inflateInit(var strm: z_stream): Integer;
+function inflate(var strm: z_stream; flush: Integer): Integer;
+function inflateEnd(var strm: z_stream): Integer;
+
+(* advanced functions *)
+function deflateInit2(var strm: z_stream; level, method, windowBits,
+                      memLevel, strategy: Integer): Integer;
+function deflateSetDictionary(var strm: z_stream; const dictionary: PChar;
+                              dictLength: Integer): Integer;
+function deflateCopy(var dest, source: z_stream): Integer;
+function deflateReset(var strm: z_stream): Integer;
+function deflateParams(var strm: z_stream; level, strategy: Integer): Integer;
+function deflateTune(var strm: z_stream; good_length, max_lazy, nice_length, max_chain: Integer): Integer;
+function deflateBound(var strm: z_stream; sourceLen: LongInt): LongInt;
+function deflatePending(var strm: z_stream; var pending: Integer; var bits: Integer): Integer;
+function deflatePrime(var strm: z_stream; bits, value: Integer): Integer;
+function deflateSetHeader(var strm: z_stream; head: gz_header): Integer;
+function inflateInit2(var strm: z_stream; windowBits: Integer): Integer;
+function inflateSetDictionary(var strm: z_stream; const dictionary: PChar;
+                              dictLength: Integer): Integer;
+function inflateSync(var strm: z_stream): Integer;
+function inflateCopy(var dest, source: z_stream): Integer;
+function inflateReset(var strm: z_stream): Integer;
+function inflateReset2(var strm: z_stream; windowBits: Integer): Integer;
+function inflatePrime(var strm: z_stream; bits, value: Integer): Integer;
+function inflateMark(var strm: z_stream): LongInt;
+function inflateGetHeader(var strm: z_stream; var head: gz_header): Integer;
+function inflateBackInit(var strm: z_stream;
+                         windowBits: Integer; window: PChar): Integer;
+function inflateBack(var strm: z_stream; in_fn: in_func; in_desc: Pointer;
+                     out_fn: out_func; out_desc: Pointer): Integer;
+function inflateBackEnd(var strm: z_stream): Integer;
+function zlibCompileFlags: LongInt;
+
+(* utility functions *)
+function compress(dest: PChar; var destLen: LongInt;
+                  const source: PChar; sourceLen: LongInt): Integer;
+function compress2(dest: PChar; var destLen: LongInt;
+                  const source: PChar; sourceLen: LongInt;
+                  level: Integer): Integer;
+function compressBound(sourceLen: LongInt): LongInt;
+function uncompress(dest: PChar; var destLen: LongInt;
+                    const source: PChar; sourceLen: LongInt): Integer;
+
+(* checksum functions *)
+function adler32(adler: LongInt; const buf: PChar; len: Integer): LongInt;
+function adler32_combine(adler1, adler2, len2: LongInt): LongInt;
+function crc32(crc: LongInt; const buf: PChar; len: Integer): LongInt;
+function crc32_combine(crc1, crc2, len2: LongInt): LongInt;
+
+(* various hacks, don't look :) *)
+function deflateInit_(var strm: z_stream; level: Integer;
+                      const version: PChar; stream_size: Integer): Integer;
+function inflateInit_(var strm: z_stream; const version: PChar;
+                      stream_size: Integer): Integer;
+function deflateInit2_(var strm: z_stream;
+                       level, method, windowBits, memLevel, strategy: Integer;
+                       const version: PChar; stream_size: Integer): Integer;
+function inflateInit2_(var strm: z_stream; windowBits: Integer;
+                       const version: PChar; stream_size: Integer): Integer;
+function inflateBackInit_(var strm: z_stream;
+                          windowBits: Integer; window: PChar;
+                          const version: PChar; stream_size: Integer): Integer;
+
+
+implementation
+
+{$L adler32.obj}
+{$L compress.obj}
+{$L crc32.obj}
+{$L deflate.obj}
+{$L infback.obj}
+{$L inffast.obj}
+{$L inflate.obj}
+{$L inftrees.obj}
+{$L trees.obj}
+{$L uncompr.obj}
+{$L zutil.obj}
+
+function adler32; external;
+function adler32_combine; external;
+function compress; external;
+function compress2; external;
+function compressBound; external;
+function crc32; external;
+function crc32_combine; external;
+function deflate; external;
+function deflateBound; external;
+function deflateCopy; external;
+function deflateEnd; external;
+function deflateInit_; external;
+function deflateInit2_; external;
+function deflateParams; external;
+function deflatePending; external;
+function deflatePrime; external;
+function deflateReset; external;
+function deflateSetDictionary; external;
+function deflateSetHeader; external;
+function deflateTune; external;
+function inflate; external;
+function inflateBack; external;
+function inflateBackEnd; external;
+function inflateBackInit_; external;
+function inflateCopy; external;
+function inflateEnd; external;
+function inflateGetHeader; external;
+function inflateInit_; external;
+function inflateInit2_; external;
+function inflateMark; external;
+function inflatePrime; external;
+function inflateReset; external;
+function inflateReset2; external;
+function inflateSetDictionary; external;
+function inflateSync; external;
+function uncompress; external;
+function zlibCompileFlags; external;
+function zlibVersion; external;
+
+function deflateInit(var strm: z_stream; level: Integer): Integer;
+begin
+  Result := deflateInit_(strm, level, ZLIB_VERSION, sizeof(z_stream));
+end;
+
+function deflateInit2(var strm: z_stream; level, method, windowBits, memLevel,
+                      strategy: Integer): Integer;
+begin
+  Result := deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
+                          ZLIB_VERSION, sizeof(z_stream));
+end;
+
+function inflateInit(var strm: z_stream): Integer;
+begin
+  Result := inflateInit_(strm, ZLIB_VERSION, sizeof(z_stream));
+end;
+
+function inflateInit2(var strm: z_stream; windowBits: Integer): Integer;
+begin
+  Result := inflateInit2_(strm, windowBits, ZLIB_VERSION, sizeof(z_stream));
+end;
+
+function inflateBackInit(var strm: z_stream;
+                         windowBits: Integer; window: PChar): Integer;
+begin
+  Result := inflateBackInit_(strm, windowBits, window,
+                             ZLIB_VERSION, sizeof(z_stream));
+end;
+
+function _malloc(Size: Integer): Pointer; cdecl;
+begin
+  GetMem(Result, Size);
+end;
+
+procedure _free(Block: Pointer); cdecl;
+begin
+  FreeMem(Block);
+end;
+
+procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl;
+begin
+  FillChar(P^, count, B);
+end;
+
+procedure _memcpy(dest, source: Pointer; count: Integer); cdecl;
+begin
+  Move(source^, dest^, count);
+end;
+
+end.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/Makefile b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/Makefile
new file mode 100644 (file)
index 0000000..0e2594c
--- /dev/null
@@ -0,0 +1,42 @@
+CFLAGS=-O
+
+puff: puff.o pufftest.o
+
+puff.o: puff.h
+
+pufftest.o: puff.h
+
+test: puff
+       puff zeros.raw
+
+puft: puff.c puff.h pufftest.o
+       cc -fprofile-arcs -ftest-coverage -o puft puff.c pufftest.o
+
+# puff full coverage test (should say 100%)
+cov: puft
+       @rm -f *.gcov *.gcda
+       @puft -w zeros.raw 2>&1 | cat > /dev/null
+       @echo '04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2
+       @echo '00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2
+       @echo '00 00 00 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 254
+       @echo '00 01 00 fe ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2
+       @echo '01 01 00 fe ff 0a' | xxd -r -p | puft -f 2>&1 | cat > /dev/null
+       @echo '02 7e ff ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246
+       @echo '02' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2
+       @echo '04 80 49 92 24 49 92 24 0f b4 ff ff c3 04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2
+       @echo '04 80 49 92 24 49 92 24 71 ff ff 93 11 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 249
+       @echo '04 c0 81 08 00 00 00 00 20 7f eb 0b 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246
+       @echo '0b 00 00' | xxd -r -p | puft -f 2>&1 | cat > /dev/null
+       @echo '1a 07' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246
+       @echo '0c c0 81 00 00 00 00 00 90 ff 6b 04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 245
+       @puft -f zeros.raw 2>&1 | cat > /dev/null
+       @echo 'fc 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 253
+       @echo '04 00 fe ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 252
+       @echo '04 00 24 49' | xxd -r -p | puft 2> /dev/null || test $$? -eq 251
+       @echo '04 80 49 92 24 49 92 24 0f b4 ff ff c3 84' | xxd -r -p | puft 2> /dev/null || test $$? -eq 248
+       @echo '04 00 24 e9 ff ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 250
+       @echo '04 00 24 e9 ff 6d' | xxd -r -p | puft 2> /dev/null || test $$? -eq 247
+       @gcov -n puff.c
+
+clean:
+       rm -f puff puft *.o *.gc*
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/README b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/README
new file mode 100644 (file)
index 0000000..bbc4cb5
--- /dev/null
@@ -0,0 +1,63 @@
+Puff -- A Simple Inflate
+3 Mar 2003
+Mark Adler
+madler@alumni.caltech.edu
+
+What this is --
+
+puff.c provides the routine puff() to decompress the deflate data format.  It
+does so more slowly than zlib, but the code is about one-fifth the size of the
+inflate code in zlib, and written to be very easy to read.
+
+Why I wrote this --
+
+puff.c was written to document the deflate format unambiguously, by virtue of
+being working C code.  It is meant to supplement RFC 1951, which formally
+describes the deflate format.  I have received many questions on details of the
+deflate format, and I hope that reading this code will answer those questions.
+puff.c is heavily commented with details of the deflate format, especially
+those little nooks and cranies of the format that might not be obvious from a
+specification.
+
+puff.c may also be useful in applications where code size or memory usage is a
+very limited resource, and speed is not as important.
+
+How to use it --
+
+Well, most likely you should just be reading puff.c and using zlib for actual
+applications, but if you must ...
+
+Include puff.h in your code, which provides this prototype:
+
+int puff(unsigned char *dest,           /* pointer to destination pointer */
+         unsigned long *destlen,        /* amount of output space */
+         unsigned char *source,         /* pointer to source data pointer */
+         unsigned long *sourcelen);     /* amount of input available */
+
+Then you can call puff() to decompress a deflate stream that is in memory in
+its entirety at source, to a sufficiently sized block of memory for the
+decompressed data at dest.  puff() is the only external symbol in puff.c  The
+only C library functions that puff.c needs are setjmp() and longjmp(), which
+are used to simplify error checking in the code to improve readabilty.  puff.c
+does no memory allocation, and uses less than 2K bytes off of the stack.
+
+If destlen is not enough space for the uncompressed data, then inflate will
+return an error without writing more than destlen bytes.  Note that this means
+that in order to decompress the deflate data successfully, you need to know
+the size of the uncompressed data ahead of time.
+
+If needed, puff() can determine the size of the uncompressed data with no
+output space.  This is done by passing dest equal to (unsigned char *)0.  Then
+the initial value of *destlen is ignored and *destlen is set to the length of
+the uncompressed data.  So if the size of the uncompressed data is not known,
+then two passes of puff() can be used--first to determine the size, and second
+to do the actual inflation after allocating the appropriate memory.  Not
+pretty, but it works.  (This is one of the reasons you should be using zlib.)
+
+The deflate format is self-terminating.  If the deflate stream does not end
+in *sourcelen bytes, puff() will return an error without reading at or past
+endsource.
+
+On return, *sourcelen is updated to the amount of input data consumed, and
+*destlen is updated to the size of the uncompressed data.  See the comments
+in puff.c for the possible return codes for puff().
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/puff.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/puff.c
new file mode 100644 (file)
index 0000000..df8470c
--- /dev/null
@@ -0,0 +1,837 @@
+/*
+ * puff.c
+ * Copyright (C) 2002-2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in puff.h
+ * version 2.2, 25 Apr 2010
+ *
+ * puff.c is a simple inflate written to be an unambiguous way to specify the
+ * deflate format.  It is not written for speed but rather simplicity.  As a
+ * side benefit, this code might actually be useful when small code is more
+ * important than speed, such as bootstrap applications.  For typical deflate
+ * data, zlib's inflate() is about four times as fast as puff().  zlib's
+ * inflate compiles to around 20K on my machine, whereas puff.c compiles to
+ * around 4K on my machine (a PowerPC using GNU cc).  If the faster decode()
+ * function here is used, then puff() is only twice as slow as zlib's
+ * inflate().
+ *
+ * All dynamically allocated memory comes from the stack.  The stack required
+ * is less than 2K bytes.  This code is compatible with 16-bit int's and
+ * assumes that long's are at least 32 bits.  puff.c uses the short data type,
+ * assumed to be 16 bits, for arrays in order to to conserve memory.  The code
+ * works whether integers are stored big endian or little endian.
+ *
+ * In the comments below are "Format notes" that describe the inflate process
+ * and document some of the less obvious aspects of the format.  This source
+ * code is meant to supplement RFC 1951, which formally describes the deflate
+ * format:
+ *
+ *    http://www.zlib.org/rfc-deflate.html
+ */
+
+/*
+ * Change history:
+ *
+ * 1.0  10 Feb 2002     - First version
+ * 1.1  17 Feb 2002     - Clarifications of some comments and notes
+ *                      - Update puff() dest and source pointers on negative
+ *                        errors to facilitate debugging deflators
+ *                      - Remove longest from struct huffman -- not needed
+ *                      - Simplify offs[] index in construct()
+ *                      - Add input size and checking, using longjmp() to
+ *                        maintain easy readability
+ *                      - Use short data type for large arrays
+ *                      - Use pointers instead of long to specify source and
+ *                        destination sizes to avoid arbitrary 4 GB limits
+ * 1.2  17 Mar 2002     - Add faster version of decode(), doubles speed (!),
+ *                        but leave simple version for readabilty
+ *                      - Make sure invalid distances detected if pointers
+ *                        are 16 bits
+ *                      - Fix fixed codes table error
+ *                      - Provide a scanning mode for determining size of
+ *                        uncompressed data
+ * 1.3  20 Mar 2002     - Go back to lengths for puff() parameters [Gailly]
+ *                      - Add a puff.h file for the interface
+ *                      - Add braces in puff() for else do [Gailly]
+ *                      - Use indexes instead of pointers for readability
+ * 1.4  31 Mar 2002     - Simplify construct() code set check
+ *                      - Fix some comments
+ *                      - Add FIXLCODES #define
+ * 1.5   6 Apr 2002     - Minor comment fixes
+ * 1.6   7 Aug 2002     - Minor format changes
+ * 1.7   3 Mar 2003     - Added test code for distribution
+ *                      - Added zlib-like license
+ * 1.8   9 Jan 2004     - Added some comments on no distance codes case
+ * 1.9  21 Feb 2008     - Fix bug on 16-bit integer architectures [Pohland]
+ *                      - Catch missing end-of-block symbol error
+ * 2.0  25 Jul 2008     - Add #define to permit distance too far back
+ *                      - Add option in TEST code for puff to write the data
+ *                      - Add option in TEST code to skip input bytes
+ *                      - Allow TEST code to read from piped stdin
+ * 2.1   4 Apr 2010     - Avoid variable initialization for happier compilers
+ *                      - Avoid unsigned comparisons for even happier compilers
+ * 2.2  25 Apr 2010     - Fix bug in variable initializations [Oberhumer]
+ *                      - Add const where appropriate [Oberhumer]
+ *                      - Split if's and ?'s for coverage testing
+ *                      - Break out test code to separate file
+ *                      - Move NIL to puff.h
+ *                      - Allow incomplete code only if single code length is 1
+ *                      - Add full code coverage test to Makefile
+ */
+
+#include <setjmp.h>             /* for setjmp(), longjmp(), and jmp_buf */
+#include "puff.h"               /* prototype for puff() */
+
+#define local static            /* for local function definitions */
+
+/*
+ * Maximums for allocations and loops.  It is not useful to change these --
+ * they are fixed by the deflate format.
+ */
+#define MAXBITS 15              /* maximum bits in a code */
+#define MAXLCODES 286           /* maximum number of literal/length codes */
+#define MAXDCODES 30            /* maximum number of distance codes */
+#define MAXCODES (MAXLCODES+MAXDCODES)  /* maximum codes lengths to read */
+#define FIXLCODES 288           /* number of fixed literal/length codes */
+
+/* input and output state */
+struct state {
+    /* output state */
+    unsigned char *out;         /* output buffer */
+    unsigned long outlen;       /* available space at out */
+    unsigned long outcnt;       /* bytes written to out so far */
+
+    /* input state */
+    const unsigned char *in;    /* input buffer */
+    unsigned long inlen;        /* available input at in */
+    unsigned long incnt;        /* bytes read so far */
+    int bitbuf;                 /* bit buffer */
+    int bitcnt;                 /* number of bits in bit buffer */
+
+    /* input limit error return state for bits() and decode() */
+    jmp_buf env;
+};
+
+/*
+ * Return need bits from the input stream.  This always leaves less than
+ * eight bits in the buffer.  bits() works properly for need == 0.
+ *
+ * Format notes:
+ *
+ * - Bits are stored in bytes from the least significant bit to the most
+ *   significant bit.  Therefore bits are dropped from the bottom of the bit
+ *   buffer, using shift right, and new bytes are appended to the top of the
+ *   bit buffer, using shift left.
+ */
+local int bits(struct state *s, int need)
+{
+    long val;           /* bit accumulator (can use up to 20 bits) */
+
+    /* load at least need bits into val */
+    val = s->bitbuf;
+    while (s->bitcnt < need) {
+        if (s->incnt == s->inlen)
+            longjmp(s->env, 1);         /* out of input */
+        val |= (long)(s->in[s->incnt++]) << s->bitcnt;  /* load eight bits */
+        s->bitcnt += 8;
+    }
+
+    /* drop need bits and update buffer, always zero to seven bits left */
+    s->bitbuf = (int)(val >> need);
+    s->bitcnt -= need;
+
+    /* return need bits, zeroing the bits above that */
+    return (int)(val & ((1L << need) - 1));
+}
+
+/*
+ * Process a stored block.
+ *
+ * Format notes:
+ *
+ * - After the two-bit stored block type (00), the stored block length and
+ *   stored bytes are byte-aligned for fast copying.  Therefore any leftover
+ *   bits in the byte that has the last bit of the type, as many as seven, are
+ *   discarded.  The value of the discarded bits are not defined and should not
+ *   be checked against any expectation.
+ *
+ * - The second inverted copy of the stored block length does not have to be
+ *   checked, but it's probably a good idea to do so anyway.
+ *
+ * - A stored block can have zero length.  This is sometimes used to byte-align
+ *   subsets of the compressed data for random access or partial recovery.
+ */
+local int stored(struct state *s)
+{
+    unsigned len;       /* length of stored block */
+
+    /* discard leftover bits from current byte (assumes s->bitcnt < 8) */
+    s->bitbuf = 0;
+    s->bitcnt = 0;
+
+    /* get length and check against its one's complement */
+    if (s->incnt + 4 > s->inlen)
+        return 2;                               /* not enough input */
+    len = s->in[s->incnt++];
+    len |= s->in[s->incnt++] << 8;
+    if (s->in[s->incnt++] != (~len & 0xff) ||
+        s->in[s->incnt++] != ((~len >> 8) & 0xff))
+        return -2;                              /* didn't match complement! */
+
+    /* copy len bytes from in to out */
+    if (s->incnt + len > s->inlen)
+        return 2;                               /* not enough input */
+    if (s->out != NIL) {
+        if (s->outcnt + len > s->outlen)
+            return 1;                           /* not enough output space */
+        while (len--)
+            s->out[s->outcnt++] = s->in[s->incnt++];
+    }
+    else {                                      /* just scanning */
+        s->outcnt += len;
+        s->incnt += len;
+    }
+
+    /* done with a valid stored block */
+    return 0;
+}
+
+/*
+ * Huffman code decoding tables.  count[1..MAXBITS] is the number of symbols of
+ * each length, which for a canonical code are stepped through in order.
+ * symbol[] are the symbol values in canonical order, where the number of
+ * entries is the sum of the counts in count[].  The decoding process can be
+ * seen in the function decode() below.
+ */
+struct huffman {
+    short *count;       /* number of symbols of each length */
+    short *symbol;      /* canonically ordered symbols */
+};
+
+/*
+ * Decode a code from the stream s using huffman table h.  Return the symbol or
+ * a negative value if there is an error.  If all of the lengths are zero, i.e.
+ * an empty code, or if the code is incomplete and an invalid code is received,
+ * then -10 is returned after reading MAXBITS bits.
+ *
+ * Format notes:
+ *
+ * - The codes as stored in the compressed data are bit-reversed relative to
+ *   a simple integer ordering of codes of the same lengths.  Hence below the
+ *   bits are pulled from the compressed data one at a time and used to
+ *   build the code value reversed from what is in the stream in order to
+ *   permit simple integer comparisons for decoding.  A table-based decoding
+ *   scheme (as used in zlib) does not need to do this reversal.
+ *
+ * - The first code for the shortest length is all zeros.  Subsequent codes of
+ *   the same length are simply integer increments of the previous code.  When
+ *   moving up a length, a zero bit is appended to the code.  For a complete
+ *   code, the last code of the longest length will be all ones.
+ *
+ * - Incomplete codes are handled by this decoder, since they are permitted
+ *   in the deflate format.  See the format notes for fixed() and dynamic().
+ */
+#ifdef SLOW
+local int decode(struct state *s, const struct huffman *h)
+{
+    int len;            /* current number of bits in code */
+    int code;           /* len bits being decoded */
+    int first;          /* first code of length len */
+    int count;          /* number of codes of length len */
+    int index;          /* index of first code of length len in symbol table */
+
+    code = first = index = 0;
+    for (len = 1; len <= MAXBITS; len++) {
+        code |= bits(s, 1);             /* get next bit */
+        count = h->count[len];
+        if (code - count < first)       /* if length len, return symbol */
+            return h->symbol[index + (code - first)];
+        index += count;                 /* else update for next length */
+        first += count;
+        first <<= 1;
+        code <<= 1;
+    }
+    return -10;                         /* ran out of codes */
+}
+
+/*
+ * A faster version of decode() for real applications of this code.   It's not
+ * as readable, but it makes puff() twice as fast.  And it only makes the code
+ * a few percent larger.
+ */
+#else /* !SLOW */
+local int decode(struct state *s, const struct huffman *h)
+{
+    int len;            /* current number of bits in code */
+    int code;           /* len bits being decoded */
+    int first;          /* first code of length len */
+    int count;          /* number of codes of length len */
+    int index;          /* index of first code of length len in symbol table */
+    int bitbuf;         /* bits from stream */
+    int left;           /* bits left in next or left to process */
+    short *next;        /* next number of codes */
+
+    bitbuf = s->bitbuf;
+    left = s->bitcnt;
+    code = first = index = 0;
+    len = 1;
+    next = h->count + 1;
+    while (1) {
+        while (left--) {
+            code |= bitbuf & 1;
+            bitbuf >>= 1;
+            count = *next++;
+            if (code - count < first) { /* if length len, return symbol */
+                s->bitbuf = bitbuf;
+                s->bitcnt = (s->bitcnt - len) & 7;
+                return h->symbol[index + (code - first)];
+            }
+            index += count;             /* else update for next length */
+            first += count;
+            first <<= 1;
+            code <<= 1;
+            len++;
+        }
+        left = (MAXBITS+1) - len;
+        if (left == 0)
+            break;
+        if (s->incnt == s->inlen)
+            longjmp(s->env, 1);         /* out of input */
+        bitbuf = s->in[s->incnt++];
+        if (left > 8)
+            left = 8;
+    }
+    return -10;                         /* ran out of codes */
+}
+#endif /* SLOW */
+
+/*
+ * Given the list of code lengths length[0..n-1] representing a canonical
+ * Huffman code for n symbols, construct the tables required to decode those
+ * codes.  Those tables are the number of codes of each length, and the symbols
+ * sorted by length, retaining their original order within each length.  The
+ * return value is zero for a complete code set, negative for an over-
+ * subscribed code set, and positive for an incomplete code set.  The tables
+ * can be used if the return value is zero or positive, but they cannot be used
+ * if the return value is negative.  If the return value is zero, it is not
+ * possible for decode() using that table to return an error--any stream of
+ * enough bits will resolve to a symbol.  If the return value is positive, then
+ * it is possible for decode() using that table to return an error for received
+ * codes past the end of the incomplete lengths.
+ *
+ * Not used by decode(), but used for error checking, h->count[0] is the number
+ * of the n symbols not in the code.  So n - h->count[0] is the number of
+ * codes.  This is useful for checking for incomplete codes that have more than
+ * one symbol, which is an error in a dynamic block.
+ *
+ * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS
+ * This is assured by the construction of the length arrays in dynamic() and
+ * fixed() and is not verified by construct().
+ *
+ * Format notes:
+ *
+ * - Permitted and expected examples of incomplete codes are one of the fixed
+ *   codes and any code with a single symbol which in deflate is coded as one
+ *   bit instead of zero bits.  See the format notes for fixed() and dynamic().
+ *
+ * - Within a given code length, the symbols are kept in ascending order for
+ *   the code bits definition.
+ */
+local int construct(struct huffman *h, const short *length, int n)
+{
+    int symbol;         /* current symbol when stepping through length[] */
+    int len;            /* current length when stepping through h->count[] */
+    int left;           /* number of possible codes left of current length */
+    short offs[MAXBITS+1];      /* offsets in symbol table for each length */
+
+    /* count number of codes of each length */
+    for (len = 0; len <= MAXBITS; len++)
+        h->count[len] = 0;
+    for (symbol = 0; symbol < n; symbol++)
+        (h->count[length[symbol]])++;   /* assumes lengths are within bounds */
+    if (h->count[0] == n)               /* no codes! */
+        return 0;                       /* complete, but decode() will fail */
+
+    /* check for an over-subscribed or incomplete set of lengths */
+    left = 1;                           /* one possible code of zero length */
+    for (len = 1; len <= MAXBITS; len++) {
+        left <<= 1;                     /* one more bit, double codes left */
+        left -= h->count[len];          /* deduct count from possible codes */
+        if (left < 0)
+            return left;                /* over-subscribed--return negative */
+    }                                   /* left > 0 means incomplete */
+
+    /* generate offsets into symbol table for each length for sorting */
+    offs[1] = 0;
+    for (len = 1; len < MAXBITS; len++)
+        offs[len + 1] = offs[len] + h->count[len];
+
+    /*
+     * put symbols in table sorted by length, by symbol order within each
+     * length
+     */
+    for (symbol = 0; symbol < n; symbol++)
+        if (length[symbol] != 0)
+            h->symbol[offs[length[symbol]]++] = symbol;
+
+    /* return zero for complete set, positive for incomplete set */
+    return left;
+}
+
+/*
+ * Decode literal/length and distance codes until an end-of-block code.
+ *
+ * Format notes:
+ *
+ * - Compressed data that is after the block type if fixed or after the code
+ *   description if dynamic is a combination of literals and length/distance
+ *   pairs terminated by and end-of-block code.  Literals are simply Huffman
+ *   coded bytes.  A length/distance pair is a coded length followed by a
+ *   coded distance to represent a string that occurs earlier in the
+ *   uncompressed data that occurs again at the current location.
+ *
+ * - Literals, lengths, and the end-of-block code are combined into a single
+ *   code of up to 286 symbols.  They are 256 literals (0..255), 29 length
+ *   symbols (257..285), and the end-of-block symbol (256).
+ *
+ * - There are 256 possible lengths (3..258), and so 29 symbols are not enough
+ *   to represent all of those.  Lengths 3..10 and 258 are in fact represented
+ *   by just a length symbol.  Lengths 11..257 are represented as a symbol and
+ *   some number of extra bits that are added as an integer to the base length
+ *   of the length symbol.  The number of extra bits is determined by the base
+ *   length symbol.  These are in the static arrays below, lens[] for the base
+ *   lengths and lext[] for the corresponding number of extra bits.
+ *
+ * - The reason that 258 gets its own symbol is that the longest length is used
+ *   often in highly redundant files.  Note that 258 can also be coded as the
+ *   base value 227 plus the maximum extra value of 31.  While a good deflate
+ *   should never do this, it is not an error, and should be decoded properly.
+ *
+ * - If a length is decoded, including its extra bits if any, then it is
+ *   followed a distance code.  There are up to 30 distance symbols.  Again
+ *   there are many more possible distances (1..32768), so extra bits are added
+ *   to a base value represented by the symbol.  The distances 1..4 get their
+ *   own symbol, but the rest require extra bits.  The base distances and
+ *   corresponding number of extra bits are below in the static arrays dist[]
+ *   and dext[].
+ *
+ * - Literal bytes are simply written to the output.  A length/distance pair is
+ *   an instruction to copy previously uncompressed bytes to the output.  The
+ *   copy is from distance bytes back in the output stream, copying for length
+ *   bytes.
+ *
+ * - Distances pointing before the beginning of the output data are not
+ *   permitted.
+ *
+ * - Overlapped copies, where the length is greater than the distance, are
+ *   allowed and common.  For example, a distance of one and a length of 258
+ *   simply copies the last byte 258 times.  A distance of four and a length of
+ *   twelve copies the last four bytes three times.  A simple forward copy
+ *   ignoring whether the length is greater than the distance or not implements
+ *   this correctly.  You should not use memcpy() since its behavior is not
+ *   defined for overlapped arrays.  You should not use memmove() or bcopy()
+ *   since though their behavior -is- defined for overlapping arrays, it is
+ *   defined to do the wrong thing in this case.
+ */
+local int codes(struct state *s,
+                const struct huffman *lencode,
+                const struct huffman *distcode)
+{
+    int symbol;         /* decoded symbol */
+    int len;            /* length for copy */
+    unsigned dist;      /* distance for copy */
+    static const short lens[29] = { /* Size base for length codes 257..285 */
+        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
+    static const short lext[29] = { /* Extra bits for length codes 257..285 */
+        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+        3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
+    static const short dists[30] = { /* Offset base for distance codes 0..29 */
+        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+        8193, 12289, 16385, 24577};
+    static const short dext[30] = { /* Extra bits for distance codes 0..29 */
+        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+        7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
+        12, 12, 13, 13};
+
+    /* decode literals and length/distance pairs */
+    do {
+        symbol = decode(s, lencode);
+        if (symbol < 0)
+            return symbol;              /* invalid symbol */
+        if (symbol < 256) {             /* literal: symbol is the byte */
+            /* write out the literal */
+            if (s->out != NIL) {
+                if (s->outcnt == s->outlen)
+                    return 1;
+                s->out[s->outcnt] = symbol;
+            }
+            s->outcnt++;
+        }
+        else if (symbol > 256) {        /* length */
+            /* get and compute length */
+            symbol -= 257;
+            if (symbol >= 29)
+                return -10;             /* invalid fixed code */
+            len = lens[symbol] + bits(s, lext[symbol]);
+
+            /* get and check distance */
+            symbol = decode(s, distcode);
+            if (symbol < 0)
+                return symbol;          /* invalid symbol */
+            dist = dists[symbol] + bits(s, dext[symbol]);
+#ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+            if (dist > s->outcnt)
+                return -11;     /* distance too far back */
+#endif
+
+            /* copy length bytes from distance bytes back */
+            if (s->out != NIL) {
+                if (s->outcnt + len > s->outlen)
+                    return 1;
+                while (len--) {
+                    s->out[s->outcnt] =
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                        dist > s->outcnt ?
+                            0 :
+#endif
+                            s->out[s->outcnt - dist];
+                    s->outcnt++;
+                }
+            }
+            else
+                s->outcnt += len;
+        }
+    } while (symbol != 256);            /* end of block symbol */
+
+    /* done with a valid fixed or dynamic block */
+    return 0;
+}
+
+/*
+ * Process a fixed codes block.
+ *
+ * Format notes:
+ *
+ * - This block type can be useful for compressing small amounts of data for
+ *   which the size of the code descriptions in a dynamic block exceeds the
+ *   benefit of custom codes for that block.  For fixed codes, no bits are
+ *   spent on code descriptions.  Instead the code lengths for literal/length
+ *   codes and distance codes are fixed.  The specific lengths for each symbol
+ *   can be seen in the "for" loops below.
+ *
+ * - The literal/length code is complete, but has two symbols that are invalid
+ *   and should result in an error if received.  This cannot be implemented
+ *   simply as an incomplete code since those two symbols are in the "middle"
+ *   of the code.  They are eight bits long and the longest literal/length\
+ *   code is nine bits.  Therefore the code must be constructed with those
+ *   symbols, and the invalid symbols must be detected after decoding.
+ *
+ * - The fixed distance codes also have two invalid symbols that should result
+ *   in an error if received.  Since all of the distance codes are the same
+ *   length, this can be implemented as an incomplete code.  Then the invalid
+ *   codes are detected while decoding.
+ */
+local int fixed(struct state *s)
+{
+    static int virgin = 1;
+    static short lencnt[MAXBITS+1], lensym[FIXLCODES];
+    static short distcnt[MAXBITS+1], distsym[MAXDCODES];
+    static struct huffman lencode, distcode;
+
+    /* build fixed huffman tables if first call (may not be thread safe) */
+    if (virgin) {
+        int symbol;
+        short lengths[FIXLCODES];
+
+        /* construct lencode and distcode */
+        lencode.count = lencnt;
+        lencode.symbol = lensym;
+        distcode.count = distcnt;
+        distcode.symbol = distsym;
+
+        /* literal/length table */
+        for (symbol = 0; symbol < 144; symbol++)
+            lengths[symbol] = 8;
+        for (; symbol < 256; symbol++)
+            lengths[symbol] = 9;
+        for (; symbol < 280; symbol++)
+            lengths[symbol] = 7;
+        for (; symbol < FIXLCODES; symbol++)
+            lengths[symbol] = 8;
+        construct(&lencode, lengths, FIXLCODES);
+
+        /* distance table */
+        for (symbol = 0; symbol < MAXDCODES; symbol++)
+            lengths[symbol] = 5;
+        construct(&distcode, lengths, MAXDCODES);
+
+        /* do this just once */
+        virgin = 0;
+    }
+
+    /* decode data until end-of-block code */
+    return codes(s, &lencode, &distcode);
+}
+
+/*
+ * Process a dynamic codes block.
+ *
+ * Format notes:
+ *
+ * - A dynamic block starts with a description of the literal/length and
+ *   distance codes for that block.  New dynamic blocks allow the compressor to
+ *   rapidly adapt to changing data with new codes optimized for that data.
+ *
+ * - The codes used by the deflate format are "canonical", which means that
+ *   the actual bits of the codes are generated in an unambiguous way simply
+ *   from the number of bits in each code.  Therefore the code descriptions
+ *   are simply a list of code lengths for each symbol.
+ *
+ * - The code lengths are stored in order for the symbols, so lengths are
+ *   provided for each of the literal/length symbols, and for each of the
+ *   distance symbols.
+ *
+ * - If a symbol is not used in the block, this is represented by a zero as
+ *   as the code length.  This does not mean a zero-length code, but rather
+ *   that no code should be created for this symbol.  There is no way in the
+ *   deflate format to represent a zero-length code.
+ *
+ * - The maximum number of bits in a code is 15, so the possible lengths for
+ *   any code are 1..15.
+ *
+ * - The fact that a length of zero is not permitted for a code has an
+ *   interesting consequence.  Normally if only one symbol is used for a given
+ *   code, then in fact that code could be represented with zero bits.  However
+ *   in deflate, that code has to be at least one bit.  So for example, if
+ *   only a single distance base symbol appears in a block, then it will be
+ *   represented by a single code of length one, in particular one 0 bit.  This
+ *   is an incomplete code, since if a 1 bit is received, it has no meaning,
+ *   and should result in an error.  So incomplete distance codes of one symbol
+ *   should be permitted, and the receipt of invalid codes should be handled.
+ *
+ * - It is also possible to have a single literal/length code, but that code
+ *   must be the end-of-block code, since every dynamic block has one.  This
+ *   is not the most efficient way to create an empty block (an empty fixed
+ *   block is fewer bits), but it is allowed by the format.  So incomplete
+ *   literal/length codes of one symbol should also be permitted.
+ *
+ * - If there are only literal codes and no lengths, then there are no distance
+ *   codes.  This is represented by one distance code with zero bits.
+ *
+ * - The list of up to 286 length/literal lengths and up to 30 distance lengths
+ *   are themselves compressed using Huffman codes and run-length encoding.  In
+ *   the list of code lengths, a 0 symbol means no code, a 1..15 symbol means
+ *   that length, and the symbols 16, 17, and 18 are run-length instructions.
+ *   Each of 16, 17, and 18 are follwed by extra bits to define the length of
+ *   the run.  16 copies the last length 3 to 6 times.  17 represents 3 to 10
+ *   zero lengths, and 18 represents 11 to 138 zero lengths.  Unused symbols
+ *   are common, hence the special coding for zero lengths.
+ *
+ * - The symbols for 0..18 are Huffman coded, and so that code must be
+ *   described first.  This is simply a sequence of up to 19 three-bit values
+ *   representing no code (0) or the code length for that symbol (1..7).
+ *
+ * - A dynamic block starts with three fixed-size counts from which is computed
+ *   the number of literal/length code lengths, the number of distance code
+ *   lengths, and the number of code length code lengths (ok, you come up with
+ *   a better name!) in the code descriptions.  For the literal/length and
+ *   distance codes, lengths after those provided are considered zero, i.e. no
+ *   code.  The code length code lengths are received in a permuted order (see
+ *   the order[] array below) to make a short code length code length list more
+ *   likely.  As it turns out, very short and very long codes are less likely
+ *   to be seen in a dynamic code description, hence what may appear initially
+ *   to be a peculiar ordering.
+ *
+ * - Given the number of literal/length code lengths (nlen) and distance code
+ *   lengths (ndist), then they are treated as one long list of nlen + ndist
+ *   code lengths.  Therefore run-length coding can and often does cross the
+ *   boundary between the two sets of lengths.
+ *
+ * - So to summarize, the code description at the start of a dynamic block is
+ *   three counts for the number of code lengths for the literal/length codes,
+ *   the distance codes, and the code length codes.  This is followed by the
+ *   code length code lengths, three bits each.  This is used to construct the
+ *   code length code which is used to read the remainder of the lengths.  Then
+ *   the literal/length code lengths and distance lengths are read as a single
+ *   set of lengths using the code length codes.  Codes are constructed from
+ *   the resulting two sets of lengths, and then finally you can start
+ *   decoding actual compressed data in the block.
+ *
+ * - For reference, a "typical" size for the code description in a dynamic
+ *   block is around 80 bytes.
+ */
+local int dynamic(struct state *s)
+{
+    int nlen, ndist, ncode;             /* number of lengths in descriptor */
+    int index;                          /* index of lengths[] */
+    int err;                            /* construct() return value */
+    short lengths[MAXCODES];            /* descriptor code lengths */
+    short lencnt[MAXBITS+1], lensym[MAXLCODES];         /* lencode memory */
+    short distcnt[MAXBITS+1], distsym[MAXDCODES];       /* distcode memory */
+    struct huffman lencode, distcode;   /* length and distance codes */
+    static const short order[19] =      /* permutation of code length codes */
+        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+    /* construct lencode and distcode */
+    lencode.count = lencnt;
+    lencode.symbol = lensym;
+    distcode.count = distcnt;
+    distcode.symbol = distsym;
+
+    /* get number of lengths in each table, check lengths */
+    nlen = bits(s, 5) + 257;
+    ndist = bits(s, 5) + 1;
+    ncode = bits(s, 4) + 4;
+    if (nlen > MAXLCODES || ndist > MAXDCODES)
+        return -3;                      /* bad counts */
+
+    /* read code length code lengths (really), missing lengths are zero */
+    for (index = 0; index < ncode; index++)
+        lengths[order[index]] = bits(s, 3);
+    for (; index < 19; index++)
+        lengths[order[index]] = 0;
+
+    /* build huffman table for code lengths codes (use lencode temporarily) */
+    err = construct(&lencode, lengths, 19);
+    if (err != 0)               /* require complete code set here */
+        return -4;
+
+    /* read length/literal and distance code length tables */
+    index = 0;
+    while (index < nlen + ndist) {
+        int symbol;             /* decoded value */
+        int len;                /* last length to repeat */
+
+        symbol = decode(s, &lencode);
+        if (symbol < 16)                /* length in 0..15 */
+            lengths[index++] = symbol;
+        else {                          /* repeat instruction */
+            len = 0;                    /* assume repeating zeros */
+            if (symbol == 16) {         /* repeat last length 3..6 times */
+                if (index == 0)
+                    return -5;          /* no last length! */
+                len = lengths[index - 1];       /* last length */
+                symbol = 3 + bits(s, 2);
+            }
+            else if (symbol == 17)      /* repeat zero 3..10 times */
+                symbol = 3 + bits(s, 3);
+            else                        /* == 18, repeat zero 11..138 times */
+                symbol = 11 + bits(s, 7);
+            if (index + symbol > nlen + ndist)
+                return -6;              /* too many lengths! */
+            while (symbol--)            /* repeat last or zero symbol times */
+                lengths[index++] = len;
+        }
+    }
+
+    /* check for end-of-block code -- there better be one! */
+    if (lengths[256] == 0)
+        return -9;
+
+    /* build huffman table for literal/length codes */
+    err = construct(&lencode, lengths, nlen);
+    if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1]))
+        return -7;      /* incomplete code ok only for single length 1 code */
+
+    /* build huffman table for distance codes */
+    err = construct(&distcode, lengths + nlen, ndist);
+    if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1]))
+        return -8;      /* incomplete code ok only for single length 1 code */
+
+    /* decode data until end-of-block code */
+    return codes(s, &lencode, &distcode);
+}
+
+/*
+ * Inflate source to dest.  On return, destlen and sourcelen are updated to the
+ * size of the uncompressed data and the size of the deflate data respectively.
+ * On success, the return value of puff() is zero.  If there is an error in the
+ * source data, i.e. it is not in the deflate format, then a negative value is
+ * returned.  If there is not enough input available or there is not enough
+ * output space, then a positive error is returned.  In that case, destlen and
+ * sourcelen are not updated to facilitate retrying from the beginning with the
+ * provision of more input data or more output space.  In the case of invalid
+ * inflate data (a negative error), the dest and source pointers are updated to
+ * facilitate the debugging of deflators.
+ *
+ * puff() also has a mode to determine the size of the uncompressed output with
+ * no output written.  For this dest must be (unsigned char *)0.  In this case,
+ * the input value of *destlen is ignored, and on return *destlen is set to the
+ * size of the uncompressed output.
+ *
+ * The return codes are:
+ *
+ *   2:  available inflate data did not terminate
+ *   1:  output space exhausted before completing inflate
+ *   0:  successful inflate
+ *  -1:  invalid block type (type == 3)
+ *  -2:  stored block length did not match one's complement
+ *  -3:  dynamic block code description: too many length or distance codes
+ *  -4:  dynamic block code description: code lengths codes incomplete
+ *  -5:  dynamic block code description: repeat lengths with no first length
+ *  -6:  dynamic block code description: repeat more than specified lengths
+ *  -7:  dynamic block code description: invalid literal/length code lengths
+ *  -8:  dynamic block code description: invalid distance code lengths
+ *  -9:  dynamic block code description: missing end-of-block code
+ * -10:  invalid literal/length or distance code in fixed or dynamic block
+ * -11:  distance is too far back in fixed or dynamic block
+ *
+ * Format notes:
+ *
+ * - Three bits are read for each block to determine the kind of block and
+ *   whether or not it is the last block.  Then the block is decoded and the
+ *   process repeated if it was not the last block.
+ *
+ * - The leftover bits in the last byte of the deflate data after the last
+ *   block (if it was a fixed or dynamic block) are undefined and have no
+ *   expected values to check.
+ */
+int puff(unsigned char *dest,           /* pointer to destination pointer */
+         unsigned long *destlen,        /* amount of output space */
+         const unsigned char *source,   /* pointer to source data pointer */
+         unsigned long *sourcelen)      /* amount of input available */
+{
+    struct state s;             /* input/output state */
+    int last, type;             /* block information */
+    int err;                    /* return value */
+
+    /* initialize output state */
+    s.out = dest;
+    s.outlen = *destlen;                /* ignored if dest is NIL */
+    s.outcnt = 0;
+
+    /* initialize input state */
+    s.in = source;
+    s.inlen = *sourcelen;
+    s.incnt = 0;
+    s.bitbuf = 0;
+    s.bitcnt = 0;
+
+    /* return if bits() or decode() tries to read past available input */
+    if (setjmp(s.env) != 0)             /* if came back here via longjmp() */
+        err = 2;                        /* then skip do-loop, return error */
+    else {
+        /* process blocks until last block or error */
+        do {
+            last = bits(&s, 1);         /* one if last block */
+            type = bits(&s, 2);         /* block type 0..3 */
+            err = type == 0 ?
+                    stored(&s) :
+                    (type == 1 ?
+                        fixed(&s) :
+                        (type == 2 ?
+                            dynamic(&s) :
+                            -1));       /* type == 3, invalid */
+            if (err != 0)
+                break;                  /* return with error */
+        } while (!last);
+    }
+
+    /* update the lengths and return */
+    if (err <= 0) {
+        *destlen = s.outcnt;
+        *sourcelen = s.incnt;
+    }
+    return err;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/puff.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/puff.h
new file mode 100644 (file)
index 0000000..6a0080a
--- /dev/null
@@ -0,0 +1,35 @@
+/* puff.h
+  Copyright (C) 2002-2010 Mark Adler, all rights reserved
+  version 2.2, 25 Apr 2010
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the author be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Mark Adler    madler@alumni.caltech.edu
+ */
+
+
+/*
+ * See puff.c for purpose and usage.
+ */
+#ifndef NIL
+#  define NIL ((unsigned char *)0)      /* for no output option */
+#endif
+
+int puff(unsigned char *dest,           /* pointer to destination pointer */
+         unsigned long *destlen,        /* amount of output space */
+         const unsigned char *source,   /* pointer to source data pointer */
+         unsigned long *sourcelen);     /* amount of input available */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/pufftest.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/pufftest.c
new file mode 100644 (file)
index 0000000..76e35f6
--- /dev/null
@@ -0,0 +1,165 @@
+/*
+ * pufftest.c
+ * Copyright (C) 2002-2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in puff.h
+ * version 2.2, 25 Apr 2010
+ */
+
+/* Example of how to use puff().
+
+   Usage: puff [-w] [-f] [-nnn] file
+          ... | puff [-w] [-f] [-nnn]
+
+   where file is the input file with deflate data, nnn is the number of bytes
+   of input to skip before inflating (e.g. to skip a zlib or gzip header), and
+   -w is used to write the decompressed data to stdout.  -f is for coverage
+   testing, and causes pufftest to fail with not enough output space (-f does
+   a write like -w, so -w is not required). */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "puff.h"
+
+#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
+#  include <fcntl.h>
+#  include <io.h>
+#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+#else
+#  define SET_BINARY_MODE(file)
+#endif
+
+#define local static
+
+/* Return size times approximately the cube root of 2, keeping the result as 1,
+   3, or 5 times a power of 2 -- the result is always > size, until the result
+   is the maximum value of an unsigned long, where it remains.  This is useful
+   to keep reallocations less than ~33% over the actual data. */
+local size_t bythirds(size_t size)
+{
+    int n;
+    size_t m;
+
+    m = size;
+    for (n = 0; m; n++)
+        m >>= 1;
+    if (n < 3)
+        return size + 1;
+    n -= 3;
+    m = size >> n;
+    m += m == 6 ? 2 : 1;
+    m <<= n;
+    return m > size ? m : (size_t)(-1);
+}
+
+/* Read the input file *name, or stdin if name is NULL, into allocated memory.
+   Reallocate to larger buffers until the entire file is read in.  Return a
+   pointer to the allocated data, or NULL if there was a memory allocation
+   failure.  *len is the number of bytes of data read from the input file (even
+   if load() returns NULL).  If the input file was empty or could not be opened
+   or read, *len is zero. */
+local void *load(const char *name, size_t *len)
+{
+    size_t size;
+    void *buf, *swap;
+    FILE *in;
+
+    *len = 0;
+    buf = malloc(size = 4096);
+    if (buf == NULL)
+        return NULL;
+    in = name == NULL ? stdin : fopen(name, "rb");
+    if (in != NULL) {
+        for (;;) {
+            *len += fread((char *)buf + *len, 1, size - *len, in);
+            if (*len < size) break;
+            size = bythirds(size);
+            if (size == *len || (swap = realloc(buf, size)) == NULL) {
+                free(buf);
+                buf = NULL;
+                break;
+            }
+            buf = swap;
+        }
+        fclose(in);
+    }
+    return buf;
+}
+
+int main(int argc, char **argv)
+{
+    int ret, put = 0, fail = 0;
+    unsigned skip = 0;
+    char *arg, *name = NULL;
+    unsigned char *source = NULL, *dest;
+    size_t len = 0;
+    unsigned long sourcelen, destlen;
+
+    /* process arguments */
+    while (arg = *++argv, --argc)
+        if (arg[0] == '-') {
+            if (arg[1] == 'w' && arg[2] == 0)
+                put = 1;
+            else if (arg[1] == 'f' && arg[2] == 0)
+                fail = 1, put = 1;
+            else if (arg[1] >= '0' && arg[1] <= '9')
+                skip = (unsigned)atoi(arg + 1);
+            else {
+                fprintf(stderr, "invalid option %s\n", arg);
+                return 3;
+            }
+        }
+        else if (name != NULL) {
+            fprintf(stderr, "only one file name allowed\n");
+            return 3;
+        }
+        else
+            name = arg;
+    source = load(name, &len);
+    if (source == NULL) {
+        fprintf(stderr, "memory allocation failure\n");
+        return 4;
+    }
+    if (len == 0) {
+        fprintf(stderr, "could not read %s, or it was empty\n",
+                name == NULL ? "<stdin>" : name);
+        free(source);
+        return 3;
+    }
+    if (skip >= len) {
+        fprintf(stderr, "skip request of %d leaves no input\n", skip);
+        free(source);
+        return 3;
+    }
+
+    /* test inflate data with offset skip */
+    len -= skip;
+    sourcelen = (unsigned long)len;
+    ret = puff(NIL, &destlen, source + skip, &sourcelen);
+    if (ret)
+        fprintf(stderr, "puff() failed with return code %d\n", ret);
+    else {
+        fprintf(stderr, "puff() succeeded uncompressing %lu bytes\n", destlen);
+        if (sourcelen < len) fprintf(stderr, "%lu compressed bytes unused\n",
+                                     len - sourcelen);
+    }
+
+    /* if requested, inflate again and write decompressd data to stdout */
+    if (put && ret == 0) {
+        if (fail)
+            destlen >>= 1;
+        dest = malloc(destlen);
+        if (dest == NULL) {
+            fprintf(stderr, "memory allocation failure\n");
+            free(source);
+            return 4;
+        }
+        puff(dest, &destlen, source + skip, &sourcelen);
+        SET_BINARY_MODE(stdout);
+        fwrite(dest, 1, destlen, stdout);
+        free(dest);
+    }
+
+    /* clean up */
+    free(source);
+    return ret;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/zeros.raw b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/zeros.raw
new file mode 100644 (file)
index 0000000..0a90e76
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/puff/zeros.raw differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/testzlib/testzlib.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/testzlib/testzlib.c
new file mode 100644 (file)
index 0000000..135888e
--- /dev/null
@@ -0,0 +1,275 @@
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <windows.h>\r
+\r
+#include "zlib.h"\r
+\r
+\r
+void MyDoMinus64(LARGE_INTEGER *R,LARGE_INTEGER A,LARGE_INTEGER B)\r
+{\r
+    R->HighPart = A.HighPart - B.HighPart;\r
+    if (A.LowPart >= B.LowPart)\r
+        R->LowPart = A.LowPart - B.LowPart;\r
+    else\r
+    {\r
+        R->LowPart = A.LowPart - B.LowPart;\r
+        R->HighPart --;\r
+    }\r
+}\r
+\r
+#ifdef _M_X64\r
+// see http://msdn2.microsoft.com/library/twchhe95(en-us,vs.80).aspx for __rdtsc\r
+unsigned __int64 __rdtsc(void);\r
+void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64)\r
+{\r
+ //   printf("rdtsc = %I64x\n",__rdtsc());\r
+   pbeginTime64->QuadPart=__rdtsc();\r
+}\r
+\r
+LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf)\r
+{\r
+    LARGE_INTEGER LIres;\r
+    unsigned _int64 res=__rdtsc()-((unsigned _int64)(beginTime64.QuadPart));\r
+    LIres.QuadPart=res;\r
+   // printf("rdtsc = %I64x\n",__rdtsc());\r
+    return LIres;\r
+}\r
+#else\r
+#ifdef _M_IX86\r
+void myGetRDTSC32(LARGE_INTEGER * pbeginTime64)\r
+{\r
+    DWORD dwEdx,dwEax;\r
+    _asm\r
+    {\r
+        rdtsc\r
+        mov dwEax,eax\r
+        mov dwEdx,edx\r
+    }\r
+    pbeginTime64->LowPart=dwEax;\r
+    pbeginTime64->HighPart=dwEdx;\r
+}\r
+\r
+void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64)\r
+{\r
+    myGetRDTSC32(pbeginTime64);\r
+}\r
+\r
+LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf)\r
+{\r
+    LARGE_INTEGER LIres,endTime64;\r
+    myGetRDTSC32(&endTime64);\r
+\r
+    LIres.LowPart=LIres.HighPart=0;\r
+    MyDoMinus64(&LIres,endTime64,beginTime64);\r
+    return LIres;\r
+}\r
+#else\r
+void myGetRDTSC32(LARGE_INTEGER * pbeginTime64)\r
+{\r
+}\r
+\r
+void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64)\r
+{\r
+}\r
+\r
+LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf)\r
+{\r
+    LARGE_INTEGER lr;\r
+    lr.QuadPart=0;\r
+    return lr;\r
+}\r
+#endif\r
+#endif\r
+\r
+void BeginCountPerfCounter(LARGE_INTEGER * pbeginTime64,BOOL fComputeTimeQueryPerf)\r
+{\r
+    if ((!fComputeTimeQueryPerf) || (!QueryPerformanceCounter(pbeginTime64)))\r
+    {\r
+        pbeginTime64->LowPart = GetTickCount();\r
+        pbeginTime64->HighPart = 0;\r
+    }\r
+}\r
+\r
+DWORD GetMsecSincePerfCounter(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf)\r
+{\r
+    LARGE_INTEGER endTime64,ticksPerSecond,ticks;\r
+    DWORDLONG ticksShifted,tickSecShifted;\r
+    DWORD dwLog=16+0;\r
+    DWORD dwRet;\r
+    if ((!fComputeTimeQueryPerf) || (!QueryPerformanceCounter(&endTime64)))\r
+        dwRet = (GetTickCount() - beginTime64.LowPart)*1;\r
+    else\r
+    {\r
+        MyDoMinus64(&ticks,endTime64,beginTime64);\r
+        QueryPerformanceFrequency(&ticksPerSecond);\r
+\r
+\r
+        {\r
+            ticksShifted = Int64ShrlMod32(*(DWORDLONG*)&ticks,dwLog);\r
+            tickSecShifted = Int64ShrlMod32(*(DWORDLONG*)&ticksPerSecond,dwLog);\r
+\r
+        }\r
+\r
+        dwRet = (DWORD)((((DWORD)ticksShifted)*1000)/(DWORD)(tickSecShifted));\r
+        dwRet *=1;\r
+    }\r
+    return dwRet;\r
+}\r
+\r
+int ReadFileMemory(const char* filename,long* plFileSize,void** pFilePtr)\r
+{\r
+    FILE* stream;\r
+    void* ptr;\r
+    int retVal=1;\r
+    stream=fopen(filename, "rb");\r
+    if (stream==NULL)\r
+        return 0;\r
+\r
+    fseek(stream,0,SEEK_END);\r
+\r
+    *plFileSize=ftell(stream);\r
+    fseek(stream,0,SEEK_SET);\r
+    ptr=malloc((*plFileSize)+1);\r
+    if (ptr==NULL)\r
+        retVal=0;\r
+    else\r
+    {\r
+        if (fread(ptr, 1, *plFileSize,stream) != (*plFileSize))\r
+            retVal=0;\r
+    }\r
+    fclose(stream);\r
+    *pFilePtr=ptr;\r
+    return retVal;\r
+}\r
+\r
+int main(int argc, char *argv[])\r
+{\r
+    int BlockSizeCompress=0x8000;\r
+    int BlockSizeUncompress=0x8000;\r
+    int cprLevel=Z_DEFAULT_COMPRESSION ;\r
+    long lFileSize;\r
+    unsigned char* FilePtr;\r
+    long lBufferSizeCpr;\r
+    long lBufferSizeUncpr;\r
+    long lCompressedSize=0;\r
+    unsigned char* CprPtr;\r
+    unsigned char* UncprPtr;\r
+    long lSizeCpr,lSizeUncpr;\r
+    DWORD dwGetTick,dwMsecQP;\r
+    LARGE_INTEGER li_qp,li_rdtsc,dwResRdtsc;\r
+\r
+    if (argc<=1)\r
+    {\r
+        printf("run TestZlib <File> [BlockSizeCompress] [BlockSizeUncompress] [compres. level]\n");\r
+        return 0;\r
+    }\r
+\r
+    if (ReadFileMemory(argv[1],&lFileSize,&FilePtr)==0)\r
+    {\r
+        printf("error reading %s\n",argv[1]);\r
+        return 1;\r
+    }\r
+    else printf("file %s read, %u bytes\n",argv[1],lFileSize);\r
+\r
+    if (argc>=3)\r
+        BlockSizeCompress=atol(argv[2]);\r
+\r
+    if (argc>=4)\r
+        BlockSizeUncompress=atol(argv[3]);\r
+\r
+    if (argc>=5)\r
+        cprLevel=(int)atol(argv[4]);\r
+\r
+    lBufferSizeCpr = lFileSize + (lFileSize/0x10) + 0x200;\r
+    lBufferSizeUncpr = lBufferSizeCpr;\r
+\r
+    CprPtr=(unsigned char*)malloc(lBufferSizeCpr + BlockSizeCompress);\r
+\r
+    BeginCountPerfCounter(&li_qp,TRUE);\r
+    dwGetTick=GetTickCount();\r
+    BeginCountRdtsc(&li_rdtsc);\r
+    {\r
+        z_stream zcpr;\r
+        int ret=Z_OK;\r
+        long lOrigToDo = lFileSize;\r
+        long lOrigDone = 0;\r
+        int step=0;\r
+        memset(&zcpr,0,sizeof(z_stream));\r
+        deflateInit(&zcpr,cprLevel);\r
+\r
+        zcpr.next_in = FilePtr;\r
+        zcpr.next_out = CprPtr;\r
+\r
+\r
+        do\r
+        {\r
+            long all_read_before = zcpr.total_in;\r
+            zcpr.avail_in = min(lOrigToDo,BlockSizeCompress);\r
+            zcpr.avail_out = BlockSizeCompress;\r
+            ret=deflate(&zcpr,(zcpr.avail_in==lOrigToDo) ? Z_FINISH : Z_SYNC_FLUSH);\r
+            lOrigDone += (zcpr.total_in-all_read_before);\r
+            lOrigToDo -= (zcpr.total_in-all_read_before);\r
+            step++;\r
+        } while (ret==Z_OK);\r
+\r
+        lSizeCpr=zcpr.total_out;\r
+        deflateEnd(&zcpr);\r
+        dwGetTick=GetTickCount()-dwGetTick;\r
+        dwMsecQP=GetMsecSincePerfCounter(li_qp,TRUE);\r
+        dwResRdtsc=GetResRdtsc(li_rdtsc,TRUE);\r
+        printf("total compress size = %u, in %u step\n",lSizeCpr,step);\r
+        printf("time = %u msec = %f sec\n",dwGetTick,dwGetTick/(double)1000.);\r
+        printf("defcpr time QP = %u msec = %f sec\n",dwMsecQP,dwMsecQP/(double)1000.);\r
+        printf("defcpr result rdtsc = %I64x\n\n",dwResRdtsc.QuadPart);\r
+    }\r
+\r
+    CprPtr=(unsigned char*)realloc(CprPtr,lSizeCpr);\r
+    UncprPtr=(unsigned char*)malloc(lBufferSizeUncpr + BlockSizeUncompress);\r
+\r
+    BeginCountPerfCounter(&li_qp,TRUE);\r
+    dwGetTick=GetTickCount();\r
+    BeginCountRdtsc(&li_rdtsc);\r
+    {\r
+        z_stream zcpr;\r
+        int ret=Z_OK;\r
+        long lOrigToDo = lSizeCpr;\r
+        long lOrigDone = 0;\r
+        int step=0;\r
+        memset(&zcpr,0,sizeof(z_stream));\r
+        inflateInit(&zcpr);\r
+\r
+        zcpr.next_in = CprPtr;\r
+        zcpr.next_out = UncprPtr;\r
+\r
+\r
+        do\r
+        {\r
+            long all_read_before = zcpr.total_in;\r
+            zcpr.avail_in = min(lOrigToDo,BlockSizeUncompress);\r
+            zcpr.avail_out = BlockSizeUncompress;\r
+            ret=inflate(&zcpr,Z_SYNC_FLUSH);\r
+            lOrigDone += (zcpr.total_in-all_read_before);\r
+            lOrigToDo -= (zcpr.total_in-all_read_before);\r
+            step++;\r
+        } while (ret==Z_OK);\r
+\r
+        lSizeUncpr=zcpr.total_out;\r
+        inflateEnd(&zcpr);\r
+        dwGetTick=GetTickCount()-dwGetTick;\r
+        dwMsecQP=GetMsecSincePerfCounter(li_qp,TRUE);\r
+        dwResRdtsc=GetResRdtsc(li_rdtsc,TRUE);\r
+        printf("total uncompress size = %u, in %u step\n",lSizeUncpr,step);\r
+        printf("time = %u msec = %f sec\n",dwGetTick,dwGetTick/(double)1000.);\r
+        printf("uncpr  time QP = %u msec = %f sec\n",dwMsecQP,dwMsecQP/(double)1000.);\r
+        printf("uncpr  result rdtsc = %I64x\n\n",dwResRdtsc.QuadPart);\r
+    }\r
+\r
+    if (lSizeUncpr==lFileSize)\r
+    {\r
+        if (memcmp(FilePtr,UncprPtr,lFileSize)==0)\r
+            printf("compare ok\n");\r
+\r
+    }\r
+\r
+    return 0;\r
+}\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/testzlib/testzlib.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/testzlib/testzlib.txt
new file mode 100644 (file)
index 0000000..62258f1
--- /dev/null
@@ -0,0 +1,10 @@
+To build testzLib with Visual Studio 2005:\r
+\r
+copy to a directory file from :\r
+- root of zLib tree\r
+- contrib/testzlib\r
+- contrib/masmx86\r
+- contrib/masmx64\r
+- contrib/vstudio/vc7\r
+\r
+and open testzlib8.sln
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/Makefile b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/Makefile
new file mode 100644 (file)
index 0000000..b54266f
--- /dev/null
@@ -0,0 +1,14 @@
+CC=cc
+CFLAGS=-g
+
+untgz: untgz.o ../../libz.a
+       $(CC) $(CFLAGS) -o untgz untgz.o -L../.. -lz
+
+untgz.o: untgz.c ../../zlib.h
+       $(CC) $(CFLAGS) -c -I../.. untgz.c
+
+../../libz.a:
+       cd ../..; ./configure; make
+
+clean:
+       rm -f untgz untgz.o *~
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/Makefile.msc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/Makefile.msc
new file mode 100644 (file)
index 0000000..77b8602
--- /dev/null
@@ -0,0 +1,17 @@
+CC=cl
+CFLAGS=-MD
+
+untgz.exe: untgz.obj ..\..\zlib.lib
+       $(CC) $(CFLAGS) untgz.obj ..\..\zlib.lib
+
+untgz.obj: untgz.c ..\..\zlib.h
+       $(CC) $(CFLAGS) -c -I..\.. untgz.c
+
+..\..\zlib.lib:
+       cd ..\..
+       $(MAKE) -f win32\makefile.msc
+       cd contrib\untgz
+
+clean:
+       -del untgz.obj
+       -del untgz.exe
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/untgz.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/untgz/untgz.c
new file mode 100644 (file)
index 0000000..2c391e5
--- /dev/null
@@ -0,0 +1,674 @@
+/*
+ * untgz.c -- Display contents and extract files from a gzip'd TAR file
+ *
+ * written by Pedro A. Aranda Gutierrez <paag@tid.es>
+ * adaptation to Unix by Jean-loup Gailly <jloup@gzip.org>
+ * various fixes by Cosmin Truta <cosmint@cs.ubbcluj.ro>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <errno.h>
+
+#include "zlib.h"
+
+#ifdef unix
+#  include <unistd.h>
+#else
+#  include <direct.h>
+#  include <io.h>
+#endif
+
+#ifdef WIN32
+#include <windows.h>
+#  ifndef F_OK
+#    define F_OK  0
+#  endif
+#  define mkdir(dirname,mode)   _mkdir(dirname)
+#  ifdef _MSC_VER
+#    define access(path,mode)   _access(path,mode)
+#    define chmod(path,mode)    _chmod(path,mode)
+#    define strdup(str)         _strdup(str)
+#  endif
+#else
+#  include <utime.h>
+#endif
+
+
+/* values used in typeflag field */
+
+#define REGTYPE  '0'            /* regular file */
+#define AREGTYPE '\0'           /* regular file */
+#define LNKTYPE  '1'            /* link */
+#define SYMTYPE  '2'            /* reserved */
+#define CHRTYPE  '3'            /* character special */
+#define BLKTYPE  '4'            /* block special */
+#define DIRTYPE  '5'            /* directory */
+#define FIFOTYPE '6'            /* FIFO special */
+#define CONTTYPE '7'            /* reserved */
+
+/* GNU tar extensions */
+
+#define GNUTYPE_DUMPDIR  'D'    /* file names from dumped directory */
+#define GNUTYPE_LONGLINK 'K'    /* long link name */
+#define GNUTYPE_LONGNAME 'L'    /* long file name */
+#define GNUTYPE_MULTIVOL 'M'    /* continuation of file from another volume */
+#define GNUTYPE_NAMES    'N'    /* file name that does not fit into main hdr */
+#define GNUTYPE_SPARSE   'S'    /* sparse file */
+#define GNUTYPE_VOLHDR   'V'    /* tape/volume header */
+
+
+/* tar header */
+
+#define BLOCKSIZE     512
+#define SHORTNAMESIZE 100
+
+struct tar_header
+{                               /* byte offset */
+  char name[100];               /*   0 */
+  char mode[8];                 /* 100 */
+  char uid[8];                  /* 108 */
+  char gid[8];                  /* 116 */
+  char size[12];                /* 124 */
+  char mtime[12];               /* 136 */
+  char chksum[8];               /* 148 */
+  char typeflag;                /* 156 */
+  char linkname[100];           /* 157 */
+  char magic[6];                /* 257 */
+  char version[2];              /* 263 */
+  char uname[32];               /* 265 */
+  char gname[32];               /* 297 */
+  char devmajor[8];             /* 329 */
+  char devminor[8];             /* 337 */
+  char prefix[155];             /* 345 */
+                                /* 500 */
+};
+
+union tar_buffer
+{
+  char               buffer[BLOCKSIZE];
+  struct tar_header  header;
+};
+
+struct attr_item
+{
+  struct attr_item  *next;
+  char              *fname;
+  int                mode;
+  time_t             time;
+};
+
+enum { TGZ_EXTRACT, TGZ_LIST, TGZ_INVALID };
+
+char *TGZfname          OF((const char *));
+void TGZnotfound        OF((const char *));
+
+int getoct              OF((char *, int));
+char *strtime           OF((time_t *));
+int setfiletime         OF((char *, time_t));
+void push_attr          OF((struct attr_item **, char *, int, time_t));
+void restore_attr       OF((struct attr_item **));
+
+int ExprMatch           OF((char *, char *));
+
+int makedir             OF((char *));
+int matchname           OF((int, int, char **, char *));
+
+void error              OF((const char *));
+int tar                 OF((gzFile, int, int, int, char **));
+
+void help               OF((int));
+int main                OF((int, char **));
+
+char *prog;
+
+const char *TGZsuffix[] = { "\0", ".tar", ".tar.gz", ".taz", ".tgz", NULL };
+
+/* return the file name of the TGZ archive */
+/* or NULL if it does not exist */
+
+char *TGZfname (const char *arcname)
+{
+  static char buffer[1024];
+  int origlen,i;
+
+  strcpy(buffer,arcname);
+  origlen = strlen(buffer);
+
+  for (i=0; TGZsuffix[i]; i++)
+    {
+       strcpy(buffer+origlen,TGZsuffix[i]);
+       if (access(buffer,F_OK) == 0)
+         return buffer;
+    }
+  return NULL;
+}
+
+
+/* error message for the filename */
+
+void TGZnotfound (const char *arcname)
+{
+  int i;
+
+  fprintf(stderr,"%s: Couldn't find ",prog);
+  for (i=0;TGZsuffix[i];i++)
+    fprintf(stderr,(TGZsuffix[i+1]) ? "%s%s, " : "or %s%s\n",
+            arcname,
+            TGZsuffix[i]);
+  exit(1);
+}
+
+
+/* convert octal digits to int */
+/* on error return -1 */
+
+int getoct (char *p,int width)
+{
+  int result = 0;
+  char c;
+
+  while (width--)
+    {
+      c = *p++;
+      if (c == 0)
+        break;
+      if (c == ' ')
+        continue;
+      if (c < '0' || c > '7')
+        return -1;
+      result = result * 8 + (c - '0');
+    }
+  return result;
+}
+
+
+/* convert time_t to string */
+/* use the "YYYY/MM/DD hh:mm:ss" format */
+
+char *strtime (time_t *t)
+{
+  struct tm   *local;
+  static char result[32];
+
+  local = localtime(t);
+  sprintf(result,"%4d/%02d/%02d %02d:%02d:%02d",
+          local->tm_year+1900, local->tm_mon+1, local->tm_mday,
+          local->tm_hour, local->tm_min, local->tm_sec);
+  return result;
+}
+
+
+/* set file time */
+
+int setfiletime (char *fname,time_t ftime)
+{
+#ifdef WIN32
+  static int isWinNT = -1;
+  SYSTEMTIME st;
+  FILETIME locft, modft;
+  struct tm *loctm;
+  HANDLE hFile;
+  int result;
+
+  loctm = localtime(&ftime);
+  if (loctm == NULL)
+    return -1;
+
+  st.wYear         = (WORD)loctm->tm_year + 1900;
+  st.wMonth        = (WORD)loctm->tm_mon + 1;
+  st.wDayOfWeek    = (WORD)loctm->tm_wday;
+  st.wDay          = (WORD)loctm->tm_mday;
+  st.wHour         = (WORD)loctm->tm_hour;
+  st.wMinute       = (WORD)loctm->tm_min;
+  st.wSecond       = (WORD)loctm->tm_sec;
+  st.wMilliseconds = 0;
+  if (!SystemTimeToFileTime(&st, &locft) ||
+      !LocalFileTimeToFileTime(&locft, &modft))
+    return -1;
+
+  if (isWinNT < 0)
+    isWinNT = (GetVersion() < 0x80000000) ? 1 : 0;
+  hFile = CreateFile(fname, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
+                     (isWinNT ? FILE_FLAG_BACKUP_SEMANTICS : 0),
+                     NULL);
+  if (hFile == INVALID_HANDLE_VALUE)
+    return -1;
+  result = SetFileTime(hFile, NULL, NULL, &modft) ? 0 : -1;
+  CloseHandle(hFile);
+  return result;
+#else
+  struct utimbuf settime;
+
+  settime.actime = settime.modtime = ftime;
+  return utime(fname,&settime);
+#endif
+}
+
+
+/* push file attributes */
+
+void push_attr(struct attr_item **list,char *fname,int mode,time_t time)
+{
+  struct attr_item *item;
+
+  item = (struct attr_item *)malloc(sizeof(struct attr_item));
+  if (item == NULL)
+    error("Out of memory");
+  item->fname = strdup(fname);
+  item->mode  = mode;
+  item->time  = time;
+  item->next  = *list;
+  *list       = item;
+}
+
+
+/* restore file attributes */
+
+void restore_attr(struct attr_item **list)
+{
+  struct attr_item *item, *prev;
+
+  for (item = *list; item != NULL; )
+    {
+      setfiletime(item->fname,item->time);
+      chmod(item->fname,item->mode);
+      prev = item;
+      item = item->next;
+      free(prev);
+    }
+  *list = NULL;
+}
+
+
+/* match regular expression */
+
+#define ISSPECIAL(c) (((c) == '*') || ((c) == '/'))
+
+int ExprMatch (char *string,char *expr)
+{
+  while (1)
+    {
+      if (ISSPECIAL(*expr))
+        {
+          if (*expr == '/')
+            {
+              if (*string != '\\' && *string != '/')
+                return 0;
+              string ++; expr++;
+            }
+          else if (*expr == '*')
+            {
+              if (*expr ++ == 0)
+                return 1;
+              while (*++string != *expr)
+                if (*string == 0)
+                  return 0;
+            }
+        }
+      else
+        {
+          if (*string != *expr)
+            return 0;
+          if (*expr++ == 0)
+            return 1;
+          string++;
+        }
+    }
+}
+
+
+/* recursive mkdir */
+/* abort on ENOENT; ignore other errors like "directory already exists" */
+/* return 1 if OK */
+/*        0 on error */
+
+int makedir (char *newdir)
+{
+  char *buffer = strdup(newdir);
+  char *p;
+  int  len = strlen(buffer);
+
+  if (len <= 0) {
+    free(buffer);
+    return 0;
+  }
+  if (buffer[len-1] == '/') {
+    buffer[len-1] = '\0';
+  }
+  if (mkdir(buffer, 0755) == 0)
+    {
+      free(buffer);
+      return 1;
+    }
+
+  p = buffer+1;
+  while (1)
+    {
+      char hold;
+
+      while(*p && *p != '\\' && *p != '/')
+        p++;
+      hold = *p;
+      *p = 0;
+      if ((mkdir(buffer, 0755) == -1) && (errno == ENOENT))
+        {
+          fprintf(stderr,"%s: Couldn't create directory %s\n",prog,buffer);
+          free(buffer);
+          return 0;
+        }
+      if (hold == 0)
+        break;
+      *p++ = hold;
+    }
+  free(buffer);
+  return 1;
+}
+
+
+int matchname (int arg,int argc,char **argv,char *fname)
+{
+  if (arg == argc)      /* no arguments given (untgz tgzarchive) */
+    return 1;
+
+  while (arg < argc)
+    if (ExprMatch(fname,argv[arg++]))
+      return 1;
+
+  return 0; /* ignore this for the moment being */
+}
+
+
+/* tar file list or extract */
+
+int tar (gzFile in,int action,int arg,int argc,char **argv)
+{
+  union  tar_buffer buffer;
+  int    len;
+  int    err;
+  int    getheader = 1;
+  int    remaining = 0;
+  FILE   *outfile = NULL;
+  char   fname[BLOCKSIZE];
+  int    tarmode;
+  time_t tartime;
+  struct attr_item *attributes = NULL;
+
+  if (action == TGZ_LIST)
+    printf("    date      time     size                       file\n"
+           " ---------- -------- --------- -------------------------------------\n");
+  while (1)
+    {
+      len = gzread(in, &buffer, BLOCKSIZE);
+      if (len < 0)
+        error(gzerror(in, &err));
+      /*
+       * Always expect complete blocks to process
+       * the tar information.
+       */
+      if (len != BLOCKSIZE)
+        {
+          action = TGZ_INVALID; /* force error exit */
+          remaining = 0;        /* force I/O cleanup */
+        }
+
+      /*
+       * If we have to get a tar header
+       */
+      if (getheader >= 1)
+        {
+          /*
+           * if we met the end of the tar
+           * or the end-of-tar block,
+           * we are done
+           */
+          if (len == 0 || buffer.header.name[0] == 0)
+            break;
+
+          tarmode = getoct(buffer.header.mode,8);
+          tartime = (time_t)getoct(buffer.header.mtime,12);
+          if (tarmode == -1 || tartime == (time_t)-1)
+            {
+              buffer.header.name[0] = 0;
+              action = TGZ_INVALID;
+            }
+
+          if (getheader == 1)
+            {
+              strncpy(fname,buffer.header.name,SHORTNAMESIZE);
+              if (fname[SHORTNAMESIZE-1] != 0)
+                  fname[SHORTNAMESIZE] = 0;
+            }
+          else
+            {
+              /*
+               * The file name is longer than SHORTNAMESIZE
+               */
+              if (strncmp(fname,buffer.header.name,SHORTNAMESIZE-1) != 0)
+                  error("bad long name");
+              getheader = 1;
+            }
+
+          /*
+           * Act according to the type flag
+           */
+          switch (buffer.header.typeflag)
+            {
+            case DIRTYPE:
+              if (action == TGZ_LIST)
+                printf(" %s     <dir> %s\n",strtime(&tartime),fname);
+              if (action == TGZ_EXTRACT)
+                {
+                  makedir(fname);
+                  push_attr(&attributes,fname,tarmode,tartime);
+                }
+              break;
+            case REGTYPE:
+            case AREGTYPE:
+              remaining = getoct(buffer.header.size,12);
+              if (remaining == -1)
+                {
+                  action = TGZ_INVALID;
+                  break;
+                }
+              if (action == TGZ_LIST)
+                printf(" %s %9d %s\n",strtime(&tartime),remaining,fname);
+              else if (action == TGZ_EXTRACT)
+                {
+                  if (matchname(arg,argc,argv,fname))
+                    {
+                      outfile = fopen(fname,"wb");
+                      if (outfile == NULL) {
+                        /* try creating directory */
+                        char *p = strrchr(fname, '/');
+                        if (p != NULL) {
+                          *p = '\0';
+                          makedir(fname);
+                          *p = '/';
+                          outfile = fopen(fname,"wb");
+                        }
+                      }
+                      if (outfile != NULL)
+                        printf("Extracting %s\n",fname);
+                      else
+                        fprintf(stderr, "%s: Couldn't create %s",prog,fname);
+                    }
+                  else
+                    outfile = NULL;
+                }
+              getheader = 0;
+              break;
+            case GNUTYPE_LONGLINK:
+            case GNUTYPE_LONGNAME:
+              remaining = getoct(buffer.header.size,12);
+              if (remaining < 0 || remaining >= BLOCKSIZE)
+                {
+                  action = TGZ_INVALID;
+                  break;
+                }
+              len = gzread(in, fname, BLOCKSIZE);
+              if (len < 0)
+                error(gzerror(in, &err));
+              if (fname[BLOCKSIZE-1] != 0 || (int)strlen(fname) > remaining)
+                {
+                  action = TGZ_INVALID;
+                  break;
+                }
+              getheader = 2;
+              break;
+            default:
+              if (action == TGZ_LIST)
+                printf(" %s     <---> %s\n",strtime(&tartime),fname);
+              break;
+            }
+        }
+      else
+        {
+          unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining;
+
+          if (outfile != NULL)
+            {
+              if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes)
+                {
+                  fprintf(stderr,
+                    "%s: Error writing %s -- skipping\n",prog,fname);
+                  fclose(outfile);
+                  outfile = NULL;
+                  remove(fname);
+                }
+            }
+          remaining -= bytes;
+        }
+
+      if (remaining == 0)
+        {
+          getheader = 1;
+          if (outfile != NULL)
+            {
+              fclose(outfile);
+              outfile = NULL;
+              if (action != TGZ_INVALID)
+                push_attr(&attributes,fname,tarmode,tartime);
+            }
+        }
+
+      /*
+       * Abandon if errors are found
+       */
+      if (action == TGZ_INVALID)
+        {
+          error("broken archive");
+          break;
+        }
+    }
+
+  /*
+   * Restore file modes and time stamps
+   */
+  restore_attr(&attributes);
+
+  if (gzclose(in) != Z_OK)
+    error("failed gzclose");
+
+  return 0;
+}
+
+
+/* ============================================================ */
+
+void help(int exitval)
+{
+  printf("untgz version 0.2.1\n"
+         "  using zlib version %s\n\n",
+         zlibVersion());
+  printf("Usage: untgz file.tgz            extract all files\n"
+         "       untgz file.tgz fname ...  extract selected files\n"
+         "       untgz -l file.tgz         list archive contents\n"
+         "       untgz -h                  display this help\n");
+  exit(exitval);
+}
+
+void error(const char *msg)
+{
+  fprintf(stderr, "%s: %s\n", prog, msg);
+  exit(1);
+}
+
+
+/* ============================================================ */
+
+#if defined(WIN32) && defined(__GNUC__)
+int _CRT_glob = 0;      /* disable argument globbing in MinGW */
+#endif
+
+int main(int argc,char **argv)
+{
+    int         action = TGZ_EXTRACT;
+    int         arg = 1;
+    char        *TGZfile;
+    gzFile      *f;
+
+    prog = strrchr(argv[0],'\\');
+    if (prog == NULL)
+      {
+        prog = strrchr(argv[0],'/');
+        if (prog == NULL)
+          {
+            prog = strrchr(argv[0],':');
+            if (prog == NULL)
+              prog = argv[0];
+            else
+              prog++;
+          }
+        else
+          prog++;
+      }
+    else
+      prog++;
+
+    if (argc == 1)
+      help(0);
+
+    if (strcmp(argv[arg],"-l") == 0)
+      {
+        action = TGZ_LIST;
+        if (argc == ++arg)
+          help(0);
+      }
+    else if (strcmp(argv[arg],"-h") == 0)
+      {
+        help(0);
+      }
+
+    if ((TGZfile = TGZfname(argv[arg])) == NULL)
+      TGZnotfound(argv[arg]);
+
+    ++arg;
+    if ((action == TGZ_LIST) && (arg != argc))
+      help(1);
+
+/*
+ *  Process the TGZ file
+ */
+    switch(action)
+      {
+      case TGZ_LIST:
+      case TGZ_EXTRACT:
+        f = gzopen(TGZfile,"rb");
+        if (f == NULL)
+          {
+            fprintf(stderr,"%s: Couldn't gzopen %s\n",prog,TGZfile);
+            return 1;
+          }
+        exit(tar(f, action, arg, argc, argv));
+      break;
+
+      default:
+        error("Unknown option");
+        exit(1);
+      }
+
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/readme.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/readme.txt
new file mode 100644 (file)
index 0000000..904888b
--- /dev/null
@@ -0,0 +1,60 @@
+Building instructions for the DLL versions of Zlib 1.2.4\r
+========================================================\r
+\r
+This directory contains projects that build zlib and minizip using\r
+Microsoft Visual C++ 9.0/10.0, and Visual C++ .\r
+\r
+You don't need to build these projects yourself. You can download the\r
+binaries from:\r
+  http://www.winimage.com/zLibDll\r
+\r
+More information can be found at this site.\r
+\r
+first compile assembly code by running\r
+bld_ml64.bat in contrib\masmx64\r
+bld_ml32.bat in contrib\masmx86\r
+\r
+\r
+\r
+\r
+Build instructions for Visual Studio 2008 (32 bits or 64 bits)\r
+--------------------------------------------------------------\r
+- Uncompress current zlib, including all contrib/* files\r
+- Open contrib\vstudio\vc9\zlibvc.sln with Microsoft Visual C++ 2008.0\r
+- Or run: vcbuild /rebuild contrib\vstudio\vc9\zlibvc.sln "Release|Win32"\r
+\r
+Build instructions for Visual Studio 2010 (32 bits or 64 bits)\r
+--------------------------------------------------------------\r
+- Uncompress current zlib, including all contrib/* files\r
+- Open contrib\vstudio\vc10\zlibvc.sln with Microsoft Visual C++ 2010.0\r
+\r
+\r
+Important\r
+---------\r
+- To use zlibwapi.dll in your application, you must define the\r
+  macro ZLIB_WINAPI when compiling your application's source files.\r
+\r
+\r
+Additional notes\r
+----------------\r
+- This DLL, named zlibwapi.dll, is compatible to the old zlib.dll built\r
+  by Gilles Vollant from the zlib 1.1.x sources, and distributed at\r
+    http://www.winimage.com/zLibDll\r
+  It uses the WINAPI calling convention for the exported functions, and\r
+  includes the minizip functionality. If your application needs that\r
+  particular build of zlib.dll, you can rename zlibwapi.dll to zlib.dll.\r
+\r
+- The new DLL was renamed because there exist several incompatible\r
+  versions of zlib.dll on the Internet.\r
+\r
+- There is also an official DLL build of zlib, named zlib1.dll. This one\r
+  is exporting the functions using the CDECL convention. See the file\r
+  win32\DLL_FAQ.txt found in this zlib distribution.\r
+\r
+- There used to be a ZLIB_DLL macro in zlib 1.1.x, but now this symbol\r
+  has a slightly different effect. To avoid compatibility problems, do\r
+  not define it here.\r
+\r
+\r
+Gilles Vollant\r
+info@winimage.com\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/FMITest.dll b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/FMITest.dll
new file mode 100644 (file)
index 0000000..34c4c13
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/FMITest.dll differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/FMITest.lib b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/FMITest.lib
new file mode 100644 (file)
index 0000000..cc21c8a
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/FMITest.lib differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/libexpat-1.dll b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/libexpat-1.dll
new file mode 100644 (file)
index 0000000..ead838f
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/binaries/win32/libexpat-1.dll differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/miniunz.vcxproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/miniunz.vcxproj
new file mode 100644 (file)
index 0000000..7973206
--- /dev/null
@@ -0,0 +1,317 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup Label="ProjectConfigurations">\r
+    <ProjectConfiguration Include="Debug|Itanium">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|Win32">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|x64">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Itanium">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Win32">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|x64">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+  </ItemGroup>\r
+  <PropertyGroup Label="Globals">\r
+    <ProjectGuid>{C52F9E7B-498A-42BE-8DB4-85A15694382A}</ProjectGuid>\r
+    <Keyword>Win32Proj</Keyword>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\r
+  <ImportGroup Label="ExtensionSettings">\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <PropertyGroup Label="UserMacros" />\r
+  <PropertyGroup>\r
+    <_ProjectFileVersion>10.0.30128.1</_ProjectFileVersion>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\MiniUnzip$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\MiniUnzip$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\MiniUnzip$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\MiniUnzip$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\MiniUnzip$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\MiniUnzip$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\MiniUnzip$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\MiniUnzip$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\MiniUnzip$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</GenerateManifest>\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(ProjectDir)..\..\minizip;$(ProjectDir);$(IncludePath)</IncludePath>\r
+    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ProjectDir);$(LibraryPath)</LibraryPath>\r
+    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ProjectDir);$(IncludePath)</IncludePath>\r
+  </PropertyGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>EXTRACT_DLL;WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>false</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>$(OutDir)zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)miniunz.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+      <ImportLibrary>$(OutDir)miniunz.lib</ImportLibrary>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)miniunz.map</MapFileName>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>EXTRACT_DLL;WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>$(OutDir)zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)miniunz.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)miniunz.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)miniunz.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)miniunz.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;EXTRACT_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)miniunz.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\minizip\miniunz.c" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClInclude Include="..\..\minizip\fmuExctract.h" />\r
+  </ItemGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\r
+  <ImportGroup Label="ExtensionTargets">\r
+  </ImportGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/miniunz.vcxproj.filters b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/miniunz.vcxproj.filters
new file mode 100644 (file)
index 0000000..f65bad9
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup>\r
+    <Filter Include="Source Files">\r
+      <UniqueIdentifier>{048af943-022b-4db6-beeb-a54c34774ee2}</UniqueIdentifier>\r
+      <Extensions>cpp;c;cxx;def;odl;idl;hpj;bat;asm</Extensions>\r
+    </Filter>\r
+    <Filter Include="Header Files">\r
+      <UniqueIdentifier>{c1d600d2-888f-4aea-b73e-8b0dd9befa0c}</UniqueIdentifier>\r
+      <Extensions>h;hpp;hxx;hm;inl;inc</Extensions>\r
+    </Filter>\r
+    <Filter Include="Resource Files">\r
+      <UniqueIdentifier>{0844199a-966b-4f19-81db-1e0125e141b9}</UniqueIdentifier>\r
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>\r
+    </Filter>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\minizip\miniunz.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClInclude Include="..\..\minizip\fmuExctract.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+  </ItemGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/minizip.vcxproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/minizip.vcxproj
new file mode 100644 (file)
index 0000000..917e156
--- /dev/null
@@ -0,0 +1,307 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup Label="ProjectConfigurations">\r
+    <ProjectConfiguration Include="Debug|Itanium">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|Win32">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|x64">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Itanium">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Win32">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|x64">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+  </ItemGroup>\r
+  <PropertyGroup Label="Globals">\r
+    <ProjectGuid>{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}</ProjectGuid>\r
+    <Keyword>Win32Proj</Keyword>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\r
+  <ImportGroup Label="ExtensionSettings">\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <PropertyGroup Label="UserMacros" />\r
+  <PropertyGroup>\r
+    <_ProjectFileVersion>10.0.30128.1</_ProjectFileVersion>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\MiniZip$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\MiniZip$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\MiniZip$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\MiniZip$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\$(Configuration)\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\$(Configuration)\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\$(Configuration)\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\$(Configuration)\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</LinkIncremental>\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+  </PropertyGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)minizip.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)minizip.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)minizip.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)minizip.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)minizip.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)minizip.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)minizip.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)minizip.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)minizip.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\minizip\minizip.c" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ProjectReference Include="zlibvc.vcxproj">\r
+      <Project>{8fd826f8-3739-44e6-8cc8-997122e53b8d}</Project>\r
+    </ProjectReference>\r
+  </ItemGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\r
+  <ImportGroup Label="ExtensionTargets">\r
+  </ImportGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/minizip.vcxproj.filters b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/minizip.vcxproj.filters
new file mode 100644 (file)
index 0000000..dd73cd3
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup>\r
+    <Filter Include="Source Files">\r
+      <UniqueIdentifier>{c0419b40-bf50-40da-b153-ff74215b79de}</UniqueIdentifier>\r
+      <Extensions>cpp;c;cxx;def;odl;idl;hpj;bat;asm</Extensions>\r
+    </Filter>\r
+    <Filter Include="Header Files">\r
+      <UniqueIdentifier>{bb87b070-735b-478e-92ce-7383abb2f36c}</UniqueIdentifier>\r
+      <Extensions>h;hpp;hxx;hm;inl;inc</Extensions>\r
+    </Filter>\r
+    <Filter Include="Resource Files">\r
+      <UniqueIdentifier>{f46ab6a6-548f-43cb-ae96-681abb5bd5db}</UniqueIdentifier>\r
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>\r
+    </Filter>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\minizip\minizip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+  </ItemGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/modelDescription.xml b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/modelDescription.xml
new file mode 100644 (file)
index 0000000..4f29967
--- /dev/null
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="FMITest"\r
+  modelIdentifier="FMITest"\r
+  guid="{2aa0bc83-3303-405c-9eaa-75319018664c}"\r
+  generationTool="OpenModelica Compiler 1.8.1+ (r11690)"\r
+  generationDateAndTime="2012-04-12T15:11:43Z"\r
+  variableNamingConvention="structured"\r
+  numberOfContinuousStates="1"\r
+  numberOfEventIndicators="1">\r
+  <ModelVariables>\r
+  <ScalarVariable\r
+    name="stock"\r
+    valueReference="0"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stock)"\r
+    valueReference="1"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valve"\r
+    valueReference="2"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="par"\r
+    valueReference="3"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="4.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valve2"\r
+    valueReference="4"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="alias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  </ModelVariables>\r
+</fmiModelDescription>\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest.c
new file mode 100644 (file)
index 0000000..7f8b8c0
--- /dev/null
@@ -0,0 +1,361 @@
+/* Simulation code for FMITest generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "simulation_runtime.h"\r
+#include "omc_error.h"\r
+\r
+#include <assert.h>\r
+#include <string.h>\r
+\r
+#include "FMITest_functions.h"\r
+\r
+#include "_FMITest.h"\r
+#include "FMITest_functions.c"\r
+/* dummy VARINFO and FILEINFO */\r
+const FILE_INFO dummyFILE_INFO = {"",-1,-1,-1,-1,1};\r
+const VAR_INFO dummyVAR_INFO = {-1,"","",(FILE_INFO){"",-1,-1,-1,-1,1}};\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef _OMC_MEASURE_TIME\r
+int measure_time_flag = 1;\r
+#else\r
+int measure_time_flag = 0;\r
+#endif\r
+\r
+void setupDataStruc(DATA *data)\r
+{\r
+  ASSERT(data,"Error while initialize Data");\r
+  data->modelData.modelName = "FMITest";\r
+  data->modelData.modelFilePrefix = "FMITest";\r
+  data->modelData.modelDir = "";\r
+  data->modelData.modelGUID = "{2aa0bc83-3303-405c-9eaa-75319018664c}";\r
+  \r
+  data->modelData.nStates = 1;\r
+  data->modelData.nVariablesReal = 2*1+1;\r
+  data->modelData.nVariablesInteger = 0;\r
+  data->modelData.nVariablesBoolean = 0;\r
+  data->modelData.nVariablesString = 0;\r
+  data->modelData.nParametersReal = 1;\r
+  data->modelData.nParametersInteger = 0;\r
+  data->modelData.nParametersBoolean = 0;\r
+  data->modelData.nParametersString = 0;\r
+  data->modelData.nInputVars = 0;\r
+  data->modelData.nOutputVars = 0;\r
+  data->modelData.nJacobians = 4;\r
+  data->modelData.nHelpVars = 0;\r
+  \r
+  data->modelData.nAliasReal = 1;\r
+  data->modelData.nAliasInteger = 0;\r
+  data->modelData.nAliasBoolean = 0;\r
+  data->modelData.nAliasString = 0;\r
+  \r
+  data->modelData.nZeroCrossings = 1;\r
+  data->modelData.nSamples = 0;\r
+  data->modelData.nInitEquations = 0;\r
+  data->modelData.nResiduals = 1;\r
+  data->modelData.nExtObjs = 0;\r
+  data->modelData.nFunctions = 0;\r
+  data->modelData.nEquations = 4;\r
+  \r
+  data->modelData.nDelayExpressions = 0;\r
+  \r
+}\r
+\r
+void setupDataStruc2(DATA *data)\r
+{\r
+  const struct FUNCTION_INFO funcInfo[1] = {{-1,"",omc_dummyFileInfo}};\r
+  memcpy(data->modelData.functionNames, &funcInfo, data->modelData.nFunctions*sizeof(FUNCTION_INFO));\r
+  \r
+  const VAR_INFO** equationInfo_cref1 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref1[0] = &$Pvalve__varInfo;\r
+  const VAR_INFO** equationInfo_cref3 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref3[0] = &$P$DER$Pstock__varInfo;\r
+  const struct EQUATION_INFO equationInfo[4] = {\r
+    {1003,"SES_ALGORITHM 0", 0, NULL},\r
+    {1004,"SES_SIMPLE_ASSIGN 1",1,equationInfo_cref1},\r
+    {1005,"SES_ALGORITHM 2", 0, NULL},\r
+    {1006,"SES_SIMPLE_ASSIGN 3",1,equationInfo_cref3}\r
+  };\r
+  const int n_omc_equationInfo_reverse_prof_index = 0;\r
+  const int omc_equationInfo_reverse_prof_index[] = {\r
+    \r
+  };\r
+  memcpy(data->modelData.equationInfo, &equationInfo, data->modelData.nEquations*sizeof(EQUATION_INFO));\r
+  \r
+  data->modelData.nProfileBlocks = n_omc_equationInfo_reverse_prof_index;\r
+  data->modelData.equationInfo_reverse_prof_index = (int*) malloc(data->modelData.nProfileBlocks*sizeof(int));\r
+  memcpy(data->modelData.equationInfo_reverse_prof_index, omc_equationInfo_reverse_prof_index, data->modelData.nProfileBlocks*sizeof(int));\r
+}\r
+\r
+/* Has to be performed after _init.xml file has been read */\r
+void callExternalObjectConstructors(DATA *data)\r
+{\r
+  state mem_state;\r
+  mem_state = get_memory_state();\r
+  /* data->simulationInfo.extObjs = NULL; */\r
+}\r
+\r
+void callExternalObjectDestructors(DATA *data)\r
+{\r
+  if (data->simulationInfo.extObjs) {\r
+    free(data->simulationInfo.extObjs);\r
+    data->simulationInfo.extObjs = 0;\r
+  }\r
+}\r
+\r
+\r
+int input_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+int output_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* Initializes the raw time events of the simulation using the now\r
+   calcualted parameters. */\r
+void function_sampleInit(DATA *data)\r
+{\r
+}\r
+\r
+int function_updateSample(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_storeDelayed(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundStartValues(DATA *data)\r
+{\r
+\r
+  \r
+  DEBUG_INFO(LOG_INIT, "updating start-values:");\r
+  \r
+  return 0;\r
+}\r
+\r
+int initial_residual(DATA *data, double $P$_lambda, double* initialResiduals)\r
+{\r
+  int i = 0;\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  DEBUG_INFO(LOG_RES_INIT, "updating initial_residuals:");\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($Pstock - $P$START$Pstock));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stock - $_start(stock)) = %f", i, initialResiduals[i-1]);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundParameters(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_0(DATA *data) {\r
+  modelica_boolean tmp0;\r
+  modelica_boolean tmp1;\r
+  /*#modelicaLine [FMITest.mo:7:2-7:56]*/\r
+  RELATIONTOZC(tmp0, $Pstock, 4.9999, 0,GreaterEq,>=);\r
+  RELATIONTOZC(tmp1, $Ppar, 0.0, -1,Greater,>);\r
+  $Pvalve = ((tmp0 && tmp1)?0.0:$Ppar); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_1(DATA *data) {\r
+  /*#modelicaLine [FMITest.mo:9:2-9:20]*/\r
+  $P$DER$Pstock = $Pvalve; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+static void functionODE_system0(DATA *data,int omc_thread_number)\r
+{\r
+  eqFunction_0(data);\r
+  eqFunction_1(data);\r
+}\r
+static void (*functionODE_systems[1])(DATA *, int) = {\r
+  functionODE_system0\r
+};\r
+\r
+void function_initMemoryState()\r
+{\r
+  push_memory_states(1);\r
+}\r
+\r
+int functionODE(DATA *data)\r
+{\r
+  int id,th_id;\r
+  state mem_state; /* We need to have separate memory pools for separate systems... */\r
+  mem_state = get_memory_state();\r
+  for (id=0; id<1; id++) {\r
+    th_id = omp_get_thread_num();\r
+    functionODE_systems[id](data,th_id);\r
+  }\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+#include <simulation_inline_solver.h>\r
+const char *_omc_force_solver=_OMC_FORCE_SOLVER;\r
+const int inline_work_states_ndims=_OMC_SOLVER_WORK_STATES_NDIMS;\r
+int functionODE_inline(DATA* data, double stepSize)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* for continuous time variables */\r
+int functionAlgebraics(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_2(DATA *data) {\r
+  modelica_boolean tmp2;\r
+  modelica_boolean tmp3;\r
+  /*#modelicaLine [FMITest.mo:7:2-7:56]*/\r
+  SAVEZEROCROSS(tmp2, $Pstock, 4.9999, 0,GreaterEq,>=);\r
+  SAVEZEROCROSS(tmp3, $Ppar, 0.0, -1,Greater,>);\r
+  $Pvalve = ((tmp2 && tmp3)?0.0:$Ppar); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_3(DATA *data) {\r
+  /*#modelicaLine [FMITest.mo:9:2-9:20]*/\r
+  $P$DER$Pstock = $Pvalve; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+int functionDAE(DATA *data, int *needToIterate)\r
+{\r
+  state mem_state;\r
+  *needToIterate = 0;\r
+  \r
+  mem_state = get_memory_state();\r
+  eqFunction_2(data);\r
+  eqFunction_3(data);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_onlyZeroCrossings(DATA *data, double *gout,double *t)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  ZEROCROSSING(0, GreaterEq($Pstock, 4.9999));\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int checkForDiscreteChanges(DATA *data)\r
+{\r
+  int needToIterate = 0;\r
+\r
+  \r
+  return needToIterate;\r
+}\r
+\r
+/* function to check assert after a step is done */\r
+int checkForAsserts(DATA *data)\r
+{\r
+\r
+  \r
+  return 0;\r
+}\r
+\r
+ int initialAnalyticJacobianA(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianB(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianC(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianD(DATA* data){\r
+    return 1;\r
+ }\r
+ int functionJacA(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacB(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacC(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacD(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+const char *linear_model_frame =\r
+  "model linear_FMITest\n  parameter Integer n = 1; // states \n  parameter Integer k = 0; // top-level inputs \n  parameter Integer l = 0; // top-level outputs \n"\r
+  "  parameter Real x0[1] = {%s};\n"\r
+  "  parameter Real u0[0] = {%s};\n"\r
+  "  parameter Real A[1,1] = [%s];\n"\r
+  "  parameter Real B[1,0] = zeros(1,0);%s\n"\r
+  "  parameter Real C[0,1] = zeros(0,1);%s\n"\r
+  "  parameter Real D[0,0] = zeros(0,0);%s\n"\r
+  "  Real x[1](start=x0);\n"\r
+  "  input Real u[0];\n"\r
+  "  output Real y[0];\n"\r
+  "\n  Real x_Pstock = x[1];\n      \n"\r
+  "equation\n  der(x) = A * x + B * u;\n  y = C * x + D * u;\nend linear_FMITest;\n"\r
+;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+/* forward the main in the simulation runtime */\r
+extern int _main_SimulationRuntime(int argc, char**argv, DATA *data);\r
+\r
+/* call the simulation runtime main from our main! */\r
+int main(int argc, char**argv)\r
+{\r
+  DATA data;\r
+  setupDataStruc(&data);\r
+  return _main_SimulationRuntime(argc, argv, &data);\r
+}\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_FMU.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_FMU.c
new file mode 100644 (file)
index 0000000..7f6ceab
--- /dev/null
@@ -0,0 +1,152 @@
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER FMITest\r
+#define MODEL_GUID "{2aa0bc83-3303-405c-9eaa-75319018664c}"\r
+\r
+// include fmu header files, typedefs and macros\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "omc_error.h"\r
+#include "fmiModelTypes.h"\r
+#include "fmiModelFunctions.h"\r
+#include "FMITest_functions.h"\r
+#include "initialization.h"\r
+#include "events.h"\r
+#include "fmu_model_interface.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+void setStartValues(ModelInstance *comp);\r
+void setDefaultStartValues(ModelInstance *comp);\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo);\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value);\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value);\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value);\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value);\r
+\r
+// define model size\r
+#define NUMBER_OF_STATES 1\r
+#define NUMBER_OF_EVENT_INDICATORS 1\r
+#define NUMBER_OF_REALS 5\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_EXTERNALFUNCTIONS 0\r
+\r
+// define variable data for model\r
+#define $Pstock_ 0 \r
+#define $P$DER$Pstock_ 1 \r
+#define $Pvalve_ 2 \r
+#define $Ppar_ 3 \r
+#define $Pvalve2_ 4 \r
+\r
+\r
+// define initial state vector as vector of value references\r
+#define STATES { $Pstock_ }\r
+#define STATESDERIVATIVES { $P$DER$Pstock_ }\r
+\r
+\r
+// implementation of the Model Exchange functions\r
+#include "fmu_model_interface.c"\r
+\r
+// Set values for all variables that define a start value\r
+void setDefaultStartValues(ModelInstance *comp) {\r
+\r
+comp->fmuData->modelData.realVarsData[0].attribute.start = 0.0;\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = 4.0;\r
+}\r
+// Set values for all variables that define a start value\r
+void setStartValues(ModelInstance *comp) {\r
+\r
+  comp->fmuData->modelData.realVarsData[0].attribute.start =  comp->fmuData->localData[0]->realVars[0];\r
+  comp->fmuData->modelData.realVarsData[1].attribute.start =  comp->fmuData->localData[0]->realVars[1];\r
+  comp->fmuData->modelData.realVarsData[2].attribute.start =  comp->fmuData->localData[0]->realVars[2];\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = comp->fmuData->simulationInfo.realParameter[0];\r
+}\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $Pstock_ : return comp->fmuData->localData[0]->realVars[0]; break;\r
+      case $P$DER$Pstock_ : return comp->fmuData->localData[0]->realVars[1]; break;\r
+      case $Pvalve_ : return comp->fmuData->localData[0]->realVars[2]; break;\r
+      case $Ppar_ : return comp->fmuData->simulationInfo.realParameter[0]; break;\r
+      case $Pvalve2_ : return getReal(comp, $Pvalve_); break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+}\r
+\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value) {\r
+  switch (vr) {\r
+      case $Pstock_ : comp->fmuData->localData[0]->realVars[0]=value; break;\r
+      case $P$DER$Pstock_ : comp->fmuData->localData[0]->realVars[1]=value; break;\r
+      case $Pvalve_ : comp->fmuData->localData[0]->realVars[2]=value; break;\r
+      case $Ppar_ : comp->fmuData->simulationInfo.realParameter[0]=value; break;\r
+      case $Pvalve2_ : return setReal(comp, $Pvalve_, value); break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value) {\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value) {\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value){\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_functions.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_functions.c
new file mode 100644 (file)
index 0000000..2d7eacf
--- /dev/null
@@ -0,0 +1,16 @@
+#include "FMITest_functions.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#define _OMC_LIT0_data "'p"\r
+static const size_t _OMC_LIT0_strlen = 2;\r
+static const char _OMC_LIT0[3] = _OMC_LIT0_data;\r
+#define _OMC_LIT1_data "'p/s"\r
+static const size_t _OMC_LIT1_strlen = 4;\r
+static const char _OMC_LIT1[5] = _OMC_LIT1_data;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_functions.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_functions.h
new file mode 100644 (file)
index 0000000..66c8a41
--- /dev/null
@@ -0,0 +1,17 @@
+#ifndef FMITest__H\r
+#define FMITest__H\r
+#define omp_get_thread_num() 0\r
+#include "modelica.h"\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <errno.h>\r
+#include "simulation_runtime.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
+\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_records.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/FMITest_records.c
new file mode 100644 (file)
index 0000000..8b85f1d
--- /dev/null
@@ -0,0 +1,3 @@
+/* Additional record code for FMITest generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#include "meta_modelica.h"\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/_FMITest.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/sources/_FMITest.h
new file mode 100644 (file)
index 0000000..67c6b94
--- /dev/null
@@ -0,0 +1,34 @@
+/* Simulation code for FMITest generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#define time data->localData[0]->timeValue\r
+\r
+/* States */\r
+#define _$Pstock(i) data->localData[i]->realVars[0]\r
+#define $Pstock _$Pstock(0)\r
+#define $P$PRE$Pstock data->simulationInfo.realVarsPre[0]\r
+#define $P$START$Pstock data->modelData.realVarsData[0].attribute.start\r
+#define $Pstock__varInfo data->modelData.realVarsData[0].info\r
+/* StatesDerivatives */\r
+#define _$P$DER$Pstock(i) data->localData[i]->realVars[1]\r
+#define $P$DER$Pstock _$P$DER$Pstock(0)\r
+#define $P$PRE$P$DER$Pstock data->simulationInfo.realVarsPre[1]\r
+#define $P$START$P$DER$Pstock data->modelData.realVarsData[1].attribute.start\r
+#define $P$DER$Pstock__varInfo data->modelData.realVarsData[1].info\r
+/* Algebraic Vars */\r
+#define _$Pvalve(i) data->localData[i]->realVars[2]\r
+#define $Pvalve _$Pvalve(0)\r
+#define $P$PRE$Pvalve data->simulationInfo.realVarsPre[2]\r
+#define $P$START$Pvalve data->modelData.realVarsData[2].attribute.start\r
+#define $Pvalve__varInfo data->modelData.realVarsData[2].info\r
+/* Algebraic Parameter */\r
+#define $Ppar data->simulationInfo.realParameter[0]\r
+#define $P$START$Ppar data->modelData.realParameterData[0].attribute.start\r
+#define $Ppar__varInfo data->modelData.realParameterData[0].info\r
+/* External Objects */\r
+/* Algebraic Integer Vars */\r
+/* Algebraic Integer Parameter */\r
+/* Algebraic Boolean Vars */\r
+/* Algebraic Boolean Parameters */\r
+/* Algebraic String Variables */\r
+/* Algebraic String Parameter */\r
+/* Jacobian Variables */\r
+\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlib.vcxproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlib.vcxproj
new file mode 100644 (file)
index 0000000..9088d17
--- /dev/null
@@ -0,0 +1,420 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup Label="ProjectConfigurations">\r
+    <ProjectConfiguration Include="Debug|Itanium">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|Win32">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|x64">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|Itanium">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|Win32">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|x64">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Itanium">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Win32">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|x64">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+  </ItemGroup>\r
+  <PropertyGroup Label="Globals">\r
+    <ProjectGuid>{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}</ProjectGuid>\r
+    <RootNamespace>testzlib</RootNamespace>\r
+    <Keyword>Win32Proj</Keyword>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\r
+  <ImportGroup Label="ExtensionSettings">\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <PropertyGroup Label="UserMacros" />\r
+  <PropertyGroup>\r
+    <_ProjectFileVersion>10.0.30128.1</_ProjectFileVersion>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">x86\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">x86\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">x64\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">x64\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">ia64\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">ia64\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\TestZlib$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\TestZlib$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</GenerateManifest>\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+  </PropertyGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerOutput>AssemblyAndSourceCode</AssemblerOutput>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)testzlib.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\r
+    <ClCompile>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerOutput>AssemblyAndSourceCode</AssemblerOutput>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)testzlib.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">\r
+    <ClCompile>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\r
+    <ClCompile>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\..\adler32.c" />\r
+    <ClCompile Include="..\..\..\compress.c" />\r
+    <ClCompile Include="..\..\..\crc32.c" />\r
+    <ClCompile Include="..\..\..\deflate.c" />\r
+    <ClCompile Include="..\..\..\infback.c" />\r
+    <ClCompile Include="..\..\masmx64\inffas8664.c">\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inffast.c" />\r
+    <ClCompile Include="..\..\..\inflate.c" />\r
+    <ClCompile Include="..\..\..\inftrees.c" />\r
+    <ClCompile Include="..\..\testzlib\testzlib.c" />\r
+    <ClCompile Include="..\..\..\trees.c" />\r
+    <ClCompile Include="..\..\..\uncompr.c" />\r
+    <ClCompile Include="..\..\..\zutil.c" />\r
+  </ItemGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\r
+  <ImportGroup Label="ExtensionTargets">\r
+  </ImportGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlib.vcxproj.filters b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlib.vcxproj.filters
new file mode 100644 (file)
index 0000000..249daa8
--- /dev/null
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup>\r
+    <Filter Include="Source Files">\r
+      <UniqueIdentifier>{c1f6a2e3-5da5-4955-8653-310d3efe05a9}</UniqueIdentifier>\r
+      <Extensions>cpp;c;cxx;def;odl;idl;hpj;bat;asm</Extensions>\r
+    </Filter>\r
+    <Filter Include="Header Files">\r
+      <UniqueIdentifier>{c2aaffdc-2c95-4d6f-8466-4bec5890af2c}</UniqueIdentifier>\r
+      <Extensions>h;hpp;hxx;hm;inl;inc</Extensions>\r
+    </Filter>\r
+    <Filter Include="Resource Files">\r
+      <UniqueIdentifier>{c274fe07-05f2-461c-964b-f6341e4e7eb5}</UniqueIdentifier>\r
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>\r
+    </Filter>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\..\adler32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\compress.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\crc32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\deflate.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\infback.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\masmx64\inffas8664.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inffast.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inflate.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inftrees.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\testzlib\testzlib.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\trees.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\uncompr.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\zutil.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+  </ItemGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlibdll.vcxproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlibdll.vcxproj
new file mode 100644 (file)
index 0000000..2d62815
--- /dev/null
@@ -0,0 +1,310 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup Label="ProjectConfigurations">\r
+    <ProjectConfiguration Include="Debug|Itanium">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|Win32">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|x64">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Itanium">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Win32">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|x64">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+  </ItemGroup>\r
+  <PropertyGroup Label="Globals">\r
+    <ProjectGuid>{C52F9E7B-498A-42BE-8DB4-85A15694366A}</ProjectGuid>\r
+    <Keyword>Win32Proj</Keyword>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">\r
+    <ConfigurationType>Application</ConfigurationType>\r
+    <CharacterSet>MultiByte</CharacterSet>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\r
+  <ImportGroup Label="ExtensionSettings">\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <PropertyGroup Label="UserMacros" />\r
+  <PropertyGroup>\r
+    <_ProjectFileVersion>10.0.30128.1</_ProjectFileVersion>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\TestZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\TestZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\TestZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\TestZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\TestZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\TestZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\TestZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\TestZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\TestZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\TestZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\TestZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\TestZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</GenerateManifest>\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+  </PropertyGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)testzlib.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <TargetMachine>MachineX86</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)testzlib.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MinimalRebuild>true</MinimalRebuild>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)testzlib.pdb</ProgramDatabaseFile>\r
+      <SubSystem>Console</SubSystem>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>MaxSpeed</Optimization>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <OmitFramePointers>true</OmitFramePointers>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\minizip;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeader>\r
+      </PrecompiledHeader>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <Link>\r
+      <AdditionalDependencies>ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)testzlib.exe</OutputFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <SubSystem>Console</SubSystem>\r
+      <OptimizeReferences>true</OptimizeReferences>\r
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\testzlib\testzlib.c" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ProjectReference Include="zlibvc.vcxproj">\r
+      <Project>{8fd826f8-3739-44e6-8cc8-997122e53b8d}</Project>\r
+    </ProjectReference>\r
+  </ItemGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\r
+  <ImportGroup Label="ExtensionTargets">\r
+  </ImportGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlibdll.vcxproj.filters b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/testzlibdll.vcxproj.filters
new file mode 100644 (file)
index 0000000..53a8693
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup>\r
+    <Filter Include="Source Files">\r
+      <UniqueIdentifier>{fa61a89f-93fc-4c89-b29e-36224b7592f4}</UniqueIdentifier>\r
+      <Extensions>cpp;c;cxx;def;odl;idl;hpj;bat;asm</Extensions>\r
+    </Filter>\r
+    <Filter Include="Header Files">\r
+      <UniqueIdentifier>{d4b85da0-2ba2-4934-b57f-e2584e3848ee}</UniqueIdentifier>\r
+      <Extensions>h;hpp;hxx;hm;inl;inc</Extensions>\r
+    </Filter>\r
+    <Filter Include="Resource Files">\r
+      <UniqueIdentifier>{e573e075-00bd-4a7d-bd67-a8cc9bfc5aca}</UniqueIdentifier>\r
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>\r
+    </Filter>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\testzlib\testzlib.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+  </ItemGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlib.rc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlib.rc
new file mode 100644 (file)
index 0000000..8f22fab
--- /dev/null
@@ -0,0 +1,32 @@
+#include <windows.h>\r
+\r
+#define IDR_VERSION1  1\r
+IDR_VERSION1   VERSIONINFO     MOVEABLE IMPURE LOADONCALL DISCARDABLE\r
+  FILEVERSION   1.2.6,1\r
+  PRODUCTVERSION 1.2.6,1\r
+  FILEFLAGSMASK        VS_FFI_FILEFLAGSMASK\r
+  FILEFLAGS    0\r
+  FILEOS       VOS_DOS_WINDOWS32\r
+  FILETYPE     VFT_DLL\r
+  FILESUBTYPE  0       // not used\r
+BEGIN\r
+  BLOCK "StringFileInfo"\r
+  BEGIN\r
+    BLOCK "040904E4"\r
+    //language ID = U.S. English, char set = Windows, Multilingual\r
+\r
+    BEGIN\r
+      VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0"\r
+      VALUE "FileVersion",     "1.2.6\0"\r
+      VALUE "InternalName",    "zlib\0"\r
+      VALUE "OriginalFilename",        "zlib.dll\0"\r
+      VALUE "ProductName",     "ZLib.DLL\0"\r
+      VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0"\r
+      VALUE "LegalCopyright", "(C) 1995-2012 Jean-loup Gailly & Mark Adler\0"\r
+    END\r
+  END\r
+  BLOCK "VarFileInfo"\r
+  BEGIN\r
+    VALUE "Translation", 0x0409, 1252\r
+  END\r
+END\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibstat.vcxproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibstat.vcxproj
new file mode 100644 (file)
index 0000000..2682fca
--- /dev/null
@@ -0,0 +1,457 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup Label="ProjectConfigurations">\r
+    <ProjectConfiguration Include="Debug|Itanium">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|Win32">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|x64">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|Itanium">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|Win32">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|x64">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Itanium">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Win32">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|x64">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+  </ItemGroup>\r
+  <PropertyGroup Label="Globals">\r
+    <ProjectGuid>{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}</ProjectGuid>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">\r
+    <ConfigurationType>StaticLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\r
+  <ImportGroup Label="ExtensionSettings">\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <PropertyGroup Label="UserMacros" />\r
+  <PropertyGroup>\r
+    <_ProjectFileVersion>10.0.30128.1</_ProjectFileVersion>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">x86\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">x86\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">x64\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">x64\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">ia64\ZlibStat$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">ia64\ZlibStat$(Configuration)\Tmp\</IntDir>\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+  </PropertyGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <DebugInformationFormat>OldStyle</DebugInformationFormat>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <AdditionalDependencies>..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <DebugInformationFormat>OldStyle</DebugInformationFormat>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <DebugInformationFormat>OldStyle</DebugInformationFormat>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <AdditionalDependencies>..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">\r
+    <Midl>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">\r
+    <Midl>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibstat.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Lib>\r
+      <AdditionalOptions>/MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions)</AdditionalOptions>\r
+      <OutputFile>$(OutDir)zlibstat.lib</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </Lib>\r
+  </ItemDefinitionGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\..\adler32.c" />\r
+    <ClCompile Include="..\..\..\compress.c" />\r
+    <ClCompile Include="..\..\..\crc32.c" />\r
+    <ClCompile Include="..\..\..\deflate.c" />\r
+    <ClCompile Include="..\..\..\gzclose.c" />\r
+    <ClCompile Include="..\..\..\gzlib.c" />\r
+    <ClCompile Include="..\..\..\gzread.c" />\r
+    <ClCompile Include="..\..\..\gzwrite.c" />\r
+    <ClCompile Include="..\..\..\infback.c" />\r
+    <ClCompile Include="..\..\masmx64\inffas8664.c">\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inffast.c" />\r
+    <ClCompile Include="..\..\..\inflate.c" />\r
+    <ClCompile Include="..\..\..\inftrees.c" />\r
+    <ClCompile Include="..\..\minizip\ioapi.c" />\r
+    <ClCompile Include="..\..\..\trees.c" />\r
+    <ClCompile Include="..\..\..\uncompr.c" />\r
+    <ClCompile Include="..\..\minizip\unzip.c" />\r
+    <ClCompile Include="..\..\minizip\zip.c" />\r
+    <ClCompile Include="..\..\..\zutil.c" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ResourceCompile Include="zlib.rc" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <None Include="zlibvc.def" />\r
+  </ItemGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\r
+  <ImportGroup Label="ExtensionTargets">\r
+  </ImportGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibstat.vcxproj.filters b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibstat.vcxproj.filters
new file mode 100644 (file)
index 0000000..c8c7f7e
--- /dev/null
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup>\r
+    <Filter Include="Source Files">\r
+      <UniqueIdentifier>{174213f6-7f66-4ae8-a3a8-a1e0a1e6ffdd}</UniqueIdentifier>\r
+    </Filter>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\..\adler32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\compress.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\crc32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\deflate.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\gzclose.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\gzlib.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\gzread.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\gzwrite.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\infback.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\masmx64\inffas8664.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inffast.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inflate.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inftrees.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\minizip\ioapi.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\trees.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\uncompr.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\minizip\unzip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\minizip\zip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\zutil.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ResourceCompile Include="zlib.rc">\r
+      <Filter>Source Files</Filter>\r
+    </ResourceCompile>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <None Include="zlibvc.def">\r
+      <Filter>Source Files</Filter>\r
+    </None>\r
+  </ItemGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.def b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.def
new file mode 100644 (file)
index 0000000..571b0a6
--- /dev/null
@@ -0,0 +1,137 @@
+LIBRARY\r
+; zlib data compression and ZIP file I/O library\r
+\r
+VERSION                1.24\r
+\r
+EXPORTS\r
+        adler32                                  @1\r
+        compress                                 @2\r
+        crc32                                    @3\r
+        deflate                                  @4\r
+        deflateCopy                              @5\r
+        deflateEnd                               @6\r
+        deflateInit2_                            @7\r
+        deflateInit_                             @8\r
+        deflateParams                            @9\r
+        deflateReset                             @10\r
+        deflateSetDictionary                     @11\r
+        gzclose                                  @12\r
+        gzdopen                                  @13\r
+        gzerror                                  @14\r
+        gzflush                                  @15\r
+        gzopen                                   @16\r
+        gzread                                   @17\r
+        gzwrite                                  @18\r
+        inflate                                  @19\r
+        inflateEnd                               @20\r
+        inflateInit2_                            @21\r
+        inflateInit_                             @22\r
+        inflateReset                             @23\r
+        inflateSetDictionary                     @24\r
+        inflateSync                              @25\r
+        uncompress                               @26\r
+        zlibVersion                              @27\r
+        gzprintf                                 @28\r
+        gzputc                                   @29\r
+        gzgetc                                   @30\r
+        gzseek                                   @31\r
+        gzrewind                                 @32\r
+        gztell                                   @33\r
+        gzeof                                    @34\r
+        gzsetparams                              @35\r
+        zError                                   @36\r
+        inflateSyncPoint                         @37\r
+        get_crc_table                            @38\r
+        compress2                                @39\r
+        gzputs                                   @40\r
+        gzgets                                   @41\r
+        inflateCopy                              @42\r
+        inflateBackInit_                         @43\r
+        inflateBack                              @44\r
+        inflateBackEnd                           @45\r
+        compressBound                            @46\r
+        deflateBound                             @47\r
+        gzclearerr                               @48\r
+        gzungetc                                 @49\r
+        zlibCompileFlags                         @50\r
+        deflatePrime                             @51\r
+        deflatePending                           @52\r
+\r
+        unzOpen                                  @61\r
+        unzClose                                 @62\r
+        unzGetGlobalInfo                         @63\r
+        unzGetCurrentFileInfo                    @64\r
+        unzGoToFirstFile                         @65\r
+        unzGoToNextFile                          @66\r
+        unzOpenCurrentFile                       @67\r
+        unzReadCurrentFile                       @68\r
+        unzOpenCurrentFile3                      @69\r
+        unztell                                  @70\r
+        unzeof                                   @71\r
+        unzCloseCurrentFile                      @72\r
+        unzGetGlobalComment                      @73\r
+        unzStringFileNameCompare                 @74\r
+        unzLocateFile                            @75\r
+        unzGetLocalExtrafield                    @76\r
+        unzOpen2                                 @77\r
+        unzOpenCurrentFile2                      @78\r
+        unzOpenCurrentFilePassword               @79\r
+\r
+        zipOpen                                  @80\r
+        zipOpenNewFileInZip                      @81\r
+        zipWriteInFileInZip                      @82\r
+        zipCloseFileInZip                        @83\r
+        zipClose                                 @84\r
+        zipOpenNewFileInZip2                     @86\r
+        zipCloseFileInZipRaw                     @87\r
+        zipOpen2                                 @88\r
+        zipOpenNewFileInZip3                     @89\r
+\r
+        unzGetFilePos                            @100\r
+        unzGoToFilePos                           @101\r
+\r
+        fill_win32_filefunc                      @110\r
+\r
+; zlibwapi v1.2.4 added:\r
+        fill_win32_filefunc64                   @111\r
+        fill_win32_filefunc64A                  @112\r
+        fill_win32_filefunc64W                  @113\r
+\r
+        unzOpen64                               @120\r
+        unzOpen2_64                             @121\r
+        unzGetGlobalInfo64                      @122\r
+        unzGetCurrentFileInfo64                 @124\r
+        unzGetCurrentFileZStreamPos64           @125\r
+        unztell64                               @126\r
+        unzGetFilePos64                         @127\r
+        unzGoToFilePos64                        @128\r
+\r
+        zipOpen64                               @130\r
+        zipOpen2_64                             @131\r
+        zipOpenNewFileInZip64                   @132\r
+        zipOpenNewFileInZip2_64                 @133\r
+        zipOpenNewFileInZip3_64                 @134\r
+        zipOpenNewFileInZip4_64                 @135\r
+        zipCloseFileInZipRaw64                  @136\r
+\r
+; zlib1 v1.2.4 added:\r
+        adler32_combine                         @140\r
+        crc32_combine                           @142\r
+        deflateSetHeader                        @144\r
+        deflateTune                             @145\r
+        gzbuffer                                @146\r
+        gzclose_r                               @147\r
+        gzclose_w                               @148\r
+        gzdirect                                @149\r
+        gzoffset                                @150\r
+        inflateGetHeader                        @156\r
+        inflateMark                             @157\r
+        inflatePrime                            @158\r
+        inflateReset2                           @159\r
+        inflateUndermine                        @160\r
+\r
+; zlib1 v1.2.6 added:\r
+        gzgetc_                                 @161\r
+        gzflags                                 @162\r
+        inflateResetKeep                        @163\r
+       deflateResetKeep                        @164
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.sln b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.sln
new file mode 100644 (file)
index 0000000..6f6ffd5
--- /dev/null
@@ -0,0 +1,135 @@
+\r
+Microsoft Visual Studio Solution File, Format Version 11.00\r
+# Visual Studio 2010\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}"\r
+EndProject\r
+Global\r
+       GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
+               Debug|Itanium = Debug|Itanium\r
+               Debug|Win32 = Debug|Win32\r
+               Debug|x64 = Debug|x64\r
+               Release|Itanium = Release|Itanium\r
+               Release|Win32 = Release|Win32\r
+               Release|x64 = Release|x64\r
+               ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium\r
+               ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32\r
+               ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64\r
+       EndGlobalSection\r
+       GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.Build.0 = Release|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.Build.0 = Release|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.Build.0 = Release|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.Build.0 = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.Build.0 = Release|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.Build.0 = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+       EndGlobalSection\r
+       GlobalSection(SolutionProperties) = preSolution\r
+               HideSolutionNode = FALSE\r
+       EndGlobalSection\r
+EndGlobal\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.vcxproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.vcxproj
new file mode 100644 (file)
index 0000000..fd0f53f
--- /dev/null
@@ -0,0 +1,659 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup Label="ProjectConfigurations">\r
+    <ProjectConfiguration Include="Debug|Itanium">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|Win32">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Debug|x64">\r
+      <Configuration>Debug</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|Itanium">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|Win32">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="ReleaseWithoutAsm|x64">\r
+      <Configuration>ReleaseWithoutAsm</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Itanium">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Itanium</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|Win32">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>Win32</Platform>\r
+    </ProjectConfiguration>\r
+    <ProjectConfiguration Include="Release|x64">\r
+      <Configuration>Release</Configuration>\r
+      <Platform>x64</Platform>\r
+    </ProjectConfiguration>\r
+  </ItemGroup>\r
+  <PropertyGroup Label="Globals">\r
+    <ProjectGuid>{8FD826F8-3739-44E6-8CC8-997122E53B8D}</ProjectGuid>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+    <WholeProgramOptimization>true</WholeProgramOptimization>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">\r
+    <ConfigurationType>DynamicLibrary</ConfigurationType>\r
+    <UseOfMfc>false</UseOfMfc>\r
+  </PropertyGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\r
+  <ImportGroup Label="ExtensionSettings">\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">\r
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />\r
+  </ImportGroup>\r
+  <PropertyGroup Label="UserMacros" />\r
+  <PropertyGroup>\r
+    <_ProjectFileVersion>10.0.30128.1</_ProjectFileVersion>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">x86\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">$(SolutionDir)Release\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">x86\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">x86\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\ZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">x64\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\ZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">ia64\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">true</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">x64\ZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">x64\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">ia64\ZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">ia64\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\ZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">x64\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</GenerateManifest>\r
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\ZlibDll$(Configuration)\</OutDir>\r
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ia64\ZlibDll$(Configuration)\Tmp\</IntDir>\r
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</LinkIncremental>\r
+    <GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">false</GenerateManifest>\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />\r
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>\r
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />\r
+  </PropertyGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>Win32</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>\r
+      <AdditionalDependencies>..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>Win32</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerOutput>All</AssemblerOutput>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>\r
+      <OutputFile>$(OutDir)zlibwapi.dll</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>Win32</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerOutput>All</AssemblerOutput>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>\r
+      <AdditionalDependencies>..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)zlibwapi.dll</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r
+      <DataExecutionPrevention>\r
+      </DataExecutionPrevention>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <AdditionalDependencies>..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)zlibwapi.dll</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <Optimization>Disabled</Optimization>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <OutputFile>$(OutDir)zlibwapi.dll</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <GenerateDebugInformation>true</GenerateDebugInformation>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|x64'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerOutput>All</AssemblerOutput>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <OutputFile>$(OutDir)zlibwapi.dll</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerOutput>All</AssemblerOutput>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <OutputFile>$(OutDir)zlibwapi.dll</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>X64</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerOutput>All</AssemblerOutput>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <AdditionalDependencies>..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies)</AdditionalDependencies>\r
+      <OutputFile>$(OutDir)zlibwapi.dll</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+      <TargetMachine>MachineX64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">\r
+    <Midl>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <MkTypLibCompatible>true</MkTypLibCompatible>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <TargetEnvironment>Itanium</TargetEnvironment>\r
+      <TypeLibraryName>$(OutDir)zlibvc.tlb</TypeLibraryName>\r
+    </Midl>\r
+    <ClCompile>\r
+      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\r
+      <AdditionalIncludeDirectories>..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions>_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <StringPooling>true</StringPooling>\r
+      <ExceptionHandling>\r
+      </ExceptionHandling>\r
+      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\r
+      <BufferSecurityCheck>false</BufferSecurityCheck>\r
+      <FunctionLevelLinking>true</FunctionLevelLinking>\r
+      <PrecompiledHeaderOutputFile>$(IntDir)zlibvc.pch</PrecompiledHeaderOutputFile>\r
+      <AssemblerOutput>All</AssemblerOutput>\r
+      <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>\r
+      <ObjectFileName>$(IntDir)</ObjectFileName>\r
+      <ProgramDataBaseFileName>$(OutDir)</ProgramDataBaseFileName>\r
+      <BrowseInformation>\r
+      </BrowseInformation>\r
+      <WarningLevel>Level3</WarningLevel>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+    </ClCompile>\r
+    <ResourceCompile>\r
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <Culture>0x040c</Culture>\r
+    </ResourceCompile>\r
+    <Link>\r
+      <OutputFile>$(OutDir)zlibwapi.dll</OutputFile>\r
+      <SuppressStartupBanner>true</SuppressStartupBanner>\r
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>\r
+      <ModuleDefinitionFile>.\zlibvc.def</ModuleDefinitionFile>\r
+      <ProgramDatabaseFile>$(OutDir)zlibwapi.pdb</ProgramDatabaseFile>\r
+      <GenerateMapFile>true</GenerateMapFile>\r
+      <MapFileName>$(OutDir)zlibwapi.map</MapFileName>\r
+      <SubSystem>Windows</SubSystem>\r
+      <ImportLibrary>$(OutDir)zlibwapi.lib</ImportLibrary>\r
+      <TargetMachine>MachineIA64</TargetMachine>\r
+    </Link>\r
+  </ItemDefinitionGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\..\adler32.c" />\r
+    <ClCompile Include="..\..\..\compress.c" />\r
+    <ClCompile Include="..\..\..\crc32.c" />\r
+    <ClCompile Include="..\..\..\deflate.c" />\r
+    <ClCompile Include="..\..\..\gzclose.c" />\r
+    <ClCompile Include="..\..\..\gzlib.c" />\r
+    <ClCompile Include="..\..\..\gzread.c" />\r
+    <ClCompile Include="..\..\..\gzwrite.c" />\r
+    <ClCompile Include="..\..\..\infback.c" />\r
+    <ClCompile Include="..\..\masmx64\inffas8664.c">\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseWithoutAsm|Win32'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">true</ExcludedFromBuild>\r
+      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inffast.c" />\r
+    <ClCompile Include="..\..\..\inflate.c" />\r
+    <ClCompile Include="..\..\..\inftrees.c" />\r
+    <ClCompile Include="..\..\minizip\ioapi.c" />\r
+    <ClCompile Include="..\..\minizip\iowin32.c" />\r
+    <ClCompile Include="..\..\..\trees.c" />\r
+    <ClCompile Include="..\..\..\uncompr.c" />\r
+    <ClCompile Include="..\..\minizip\unzip.c">\r
+      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ZLIB_INTERNAL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">ZLIB_INTERNAL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">ZLIB_INTERNAL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\minizip\zip.c">\r
+      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Itanium'">ZLIB_INTERNAL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">ZLIB_INTERNAL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
+      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">ZLIB_INTERNAL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\zutil.c" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ResourceCompile Include="zlib.rc" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <None Include="zlibvc.def" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClInclude Include="..\..\..\deflate.h" />\r
+    <ClInclude Include="..\..\..\infblock.h" />\r
+    <ClInclude Include="..\..\..\infcodes.h" />\r
+    <ClInclude Include="..\..\..\inffast.h" />\r
+    <ClInclude Include="..\..\..\inftrees.h" />\r
+    <ClInclude Include="..\..\..\infutil.h" />\r
+    <ClInclude Include="..\..\..\zconf.h" />\r
+    <ClInclude Include="..\..\..\zlib.h" />\r
+    <ClInclude Include="..\..\..\zutil.h" />\r
+  </ItemGroup>\r
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\r
+  <ImportGroup Label="ExtensionTargets">\r
+  </ImportGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.vcxproj.filters b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc10/zlibvc.vcxproj.filters
new file mode 100644 (file)
index 0000000..180b71c
--- /dev/null
@@ -0,0 +1,118 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <ItemGroup>\r
+    <Filter Include="Source Files">\r
+      <UniqueIdentifier>{07934a85-8b61-443d-a0ee-b2eedb74f3cd}</UniqueIdentifier>\r
+      <Extensions>cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90</Extensions>\r
+    </Filter>\r
+    <Filter Include="Header Files">\r
+      <UniqueIdentifier>{1d99675b-433d-4a21-9e50-ed4ab8b19762}</UniqueIdentifier>\r
+      <Extensions>h;hpp;hxx;hm;inl;fi;fd</Extensions>\r
+    </Filter>\r
+    <Filter Include="Resource Files">\r
+      <UniqueIdentifier>{431c0958-fa71-44d0-9084-2d19d100c0cc}</UniqueIdentifier>\r
+      <Extensions>ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe</Extensions>\r
+    </Filter>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClCompile Include="..\..\..\adler32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\compress.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\crc32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\deflate.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\gzclose.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\gzlib.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\gzread.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\gzwrite.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\infback.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\masmx64\inffas8664.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inffast.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inflate.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\inftrees.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\minizip\ioapi.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\minizip\iowin32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\trees.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\uncompr.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\minizip\unzip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\minizip\zip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\..\..\zutil.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ResourceCompile Include="zlib.rc">\r
+      <Filter>Source Files</Filter>\r
+    </ResourceCompile>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <None Include="zlibvc.def">\r
+      <Filter>Source Files</Filter>\r
+    </None>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <ClInclude Include="..\..\..\deflate.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\..\..\infblock.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\..\..\infcodes.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\..\..\inffast.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\..\..\inftrees.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\..\..\infutil.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\..\..\zconf.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\..\..\zlib.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\..\..\zutil.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+  </ItemGroup>\r
+</Project>
\ No newline at end of file
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/miniunz.vcproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/miniunz.vcproj
new file mode 100644 (file)
index 0000000..7da32b9
--- /dev/null
@@ -0,0 +1,565 @@
+<?xml version="1.0" encoding="Windows-1252"?>\r
+<VisualStudioProject\r
+       ProjectType="Visual C++"\r
+       Version="9.00"\r
+       Name="miniunz"\r
+       ProjectGUID="{C52F9E7B-498A-42BE-8DB4-85A15694382A}"\r
+       Keyword="Win32Proj"\r
+       TargetFrameworkVersion="131072"\r
+       >\r
+       <Platforms>\r
+               <Platform\r
+                       Name="Win32"\r
+               />\r
+               <Platform\r
+                       Name="x64"\r
+               />\r
+               <Platform\r
+                       Name="Itanium"\r
+               />\r
+       </Platforms>\r
+       <ToolFiles>\r
+       </ToolFiles>\r
+       <Configurations>\r
+               <Configuration\r
+                       Name="Debug|Win32"\r
+                       OutputDirectory="x86\MiniUnzip$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\MiniUnzip$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="1"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="4"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x86\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/miniunz.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/miniunz.pdb"\r
+                               SubSystem="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Win32"\r
+                       OutputDirectory="x86\MiniUnzip$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\MiniUnzip$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x86\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/miniunz.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|x64"\r
+                       OutputDirectory="x64\MiniUnzip$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\MiniUnzip$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x64\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/miniunz.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/miniunz.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|Itanium"\r
+                       OutputDirectory="ia64\MiniUnzip$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\MiniUnzip$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="ia64\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/miniunz.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/miniunz.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|x64"\r
+                       OutputDirectory="x64\MiniUnzip$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\MiniUnzip$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x64\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/miniunz.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Itanium"\r
+                       OutputDirectory="ia64\MiniUnzip$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\MiniUnzip$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="ia64\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/miniunz.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+       </Configurations>\r
+       <References>\r
+       </References>\r
+       <Files>\r
+               <Filter\r
+                       Name="Source Files"\r
+                       Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm"\r
+                       >\r
+                       <File\r
+                               RelativePath="..\..\minizip\miniunz.c"\r
+                               >\r
+                       </File>\r
+               </Filter>\r
+               <Filter\r
+                       Name="Header Files"\r
+                       Filter="h;hpp;hxx;hm;inl;inc"\r
+                       >\r
+               </Filter>\r
+               <Filter\r
+                       Name="Resource Files"\r
+                       Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+                       >\r
+               </Filter>\r
+       </Files>\r
+       <Globals>\r
+       </Globals>\r
+</VisualStudioProject>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/minizip.vcproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/minizip.vcproj
new file mode 100644 (file)
index 0000000..e57e07d
--- /dev/null
@@ -0,0 +1,562 @@
+<?xml version="1.0" encoding="Windows-1252"?>\r
+<VisualStudioProject\r
+       ProjectType="Visual C++"\r
+       Version="9.00"\r
+       Name="minizip"\r
+       ProjectGUID="{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}"\r
+       Keyword="Win32Proj"\r
+       TargetFrameworkVersion="131072"\r
+       >\r
+       <Platforms>\r
+               <Platform\r
+                       Name="Win32"\r
+               />\r
+               <Platform\r
+                       Name="x64"\r
+               />\r
+               <Platform\r
+                       Name="Itanium"\r
+               />\r
+       </Platforms>\r
+       <ToolFiles>\r
+       </ToolFiles>\r
+       <Configurations>\r
+               <Configuration\r
+                       Name="Debug|Win32"\r
+                       OutputDirectory="x86\MiniZip$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\MiniZip$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="1"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="4"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x86\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/minizip.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/minizip.pdb"\r
+                               SubSystem="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Win32"\r
+                       OutputDirectory="x86\MiniZip$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\MiniZip$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x86\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/minizip.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|x64"\r
+                       OutputDirectory="x64\$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\$(ConfigurationName)"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x64\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/minizip.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/minizip.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|Itanium"\r
+                       OutputDirectory="ia64\$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\$(ConfigurationName)"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="ia64\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/minizip.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/minizip.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|x64"\r
+                       OutputDirectory="x64\$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\$(ConfigurationName)"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x64\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/minizip.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Itanium"\r
+                       OutputDirectory="ia64\$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\$(ConfigurationName)"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="ia64\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/minizip.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+       </Configurations>\r
+       <References>\r
+       </References>\r
+       <Files>\r
+               <Filter\r
+                       Name="Source Files"\r
+                       Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm"\r
+                       >\r
+                       <File\r
+                               RelativePath="..\..\minizip\minizip.c"\r
+                               >\r
+                       </File>\r
+               </Filter>\r
+               <Filter\r
+                       Name="Header Files"\r
+                       Filter="h;hpp;hxx;hm;inl;inc"\r
+                       >\r
+               </Filter>\r
+               <Filter\r
+                       Name="Resource Files"\r
+                       Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+                       >\r
+               </Filter>\r
+       </Files>\r
+       <Globals>\r
+       </Globals>\r
+</VisualStudioProject>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/testzlib.vcproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/testzlib.vcproj
new file mode 100644 (file)
index 0000000..9cb0bf8
--- /dev/null
@@ -0,0 +1,852 @@
+<?xml version="1.0" encoding="Windows-1252"?>\r
+<VisualStudioProject\r
+       ProjectType="Visual C++"\r
+       Version="9,00"\r
+       Name="testzlib"\r
+       ProjectGUID="{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"\r
+       RootNamespace="testzlib"\r
+       Keyword="Win32Proj"\r
+       TargetFrameworkVersion="131072"\r
+       >\r
+       <Platforms>\r
+               <Platform\r
+                       Name="Win32"\r
+               />\r
+               <Platform\r
+                       Name="x64"\r
+               />\r
+               <Platform\r
+                       Name="Itanium"\r
+               />\r
+       </Platforms>\r
+       <ToolFiles>\r
+       </ToolFiles>\r
+       <Configurations>\r
+               <Configuration\r
+                       Name="Debug|Win32"\r
+                       OutputDirectory="x86\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="1"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerOutput="4"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="4"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="..\..\masmx86\match686.obj ..\..\masmx86\inffas32.obj"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/testzlib.pdb"\r
+                               SubSystem="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|x64"\r
+                       OutputDirectory="x64\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="..\..\masmx64\gvmat64.obj ..\..\masmx64\inffasx64.obj"\r
+                               GenerateManifest="false"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|Itanium"\r
+                       OutputDirectory="ia64\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerOutput="4"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/testzlib.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|Win32"\r
+                       OutputDirectory="x86\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       CharacterSet="2"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|x64"\r
+                       OutputDirectory="x64\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies=""\r
+                               GenerateManifest="false"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|Itanium"\r
+                       OutputDirectory="ia64\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       CharacterSet="2"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Win32"\r
+                       OutputDirectory="x86\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       CharacterSet="2"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="..\..\masmx86\match686.obj ..\..\masmx86\inffas32.obj"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|x64"\r
+                       OutputDirectory="x64\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="..\..\masmx64\gvmat64.obj ..\..\masmx64\inffasx64.obj"\r
+                               GenerateManifest="false"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Itanium"\r
+                       OutputDirectory="ia64\TestZlib$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\TestZlib$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       CharacterSet="2"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\.."\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+       </Configurations>\r
+       <References>\r
+       </References>\r
+       <Files>\r
+               <Filter\r
+                       Name="Source Files"\r
+                       Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm"\r
+                       >\r
+                       <File\r
+                               RelativePath="..\..\..\adler32.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\compress.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\crc32.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\deflate.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\infback.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\masmx64\inffas8664.c"\r
+                               >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Debug|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="ReleaseWithoutAsm|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="ReleaseWithoutAsm|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inffast.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inflate.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inftrees.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\testzlib\testzlib.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\trees.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\uncompr.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\zutil.c"\r
+                               >\r
+                       </File>\r
+               </Filter>\r
+               <Filter\r
+                       Name="Header Files"\r
+                       Filter="h;hpp;hxx;hm;inl;inc"\r
+                       >\r
+               </Filter>\r
+               <Filter\r
+                       Name="Resource Files"\r
+                       Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+                       >\r
+               </Filter>\r
+       </Files>\r
+       <Globals>\r
+       </Globals>\r
+</VisualStudioProject>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/testzlibdll.vcproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/testzlibdll.vcproj
new file mode 100644 (file)
index 0000000..b1ddde0
--- /dev/null
@@ -0,0 +1,565 @@
+<?xml version="1.0" encoding="Windows-1252"?>\r
+<VisualStudioProject\r
+       ProjectType="Visual C++"\r
+       Version="9.00"\r
+       Name="TestZlibDll"\r
+       ProjectGUID="{C52F9E7B-498A-42BE-8DB4-85A15694366A}"\r
+       Keyword="Win32Proj"\r
+       TargetFrameworkVersion="131072"\r
+       >\r
+       <Platforms>\r
+               <Platform\r
+                       Name="Win32"\r
+               />\r
+               <Platform\r
+                       Name="x64"\r
+               />\r
+               <Platform\r
+                       Name="Itanium"\r
+               />\r
+       </Platforms>\r
+       <ToolFiles>\r
+       </ToolFiles>\r
+       <Configurations>\r
+               <Configuration\r
+                       Name="Debug|Win32"\r
+                       OutputDirectory="x86\TestZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\TestZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="1"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="4"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x86\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/testzlib.pdb"\r
+                               SubSystem="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Win32"\r
+                       OutputDirectory="x86\TestZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\TestZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x86\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|x64"\r
+                       OutputDirectory="x64\TestZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\TestZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x64\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/testzlib.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|Itanium"\r
+                       OutputDirectory="ia64\TestZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\TestZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="ia64\ZlibDllDebug\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="2"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/testzlib.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|x64"\r
+                       OutputDirectory="x64\TestZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\TestZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="x64\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Itanium"\r
+                       OutputDirectory="ia64\TestZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\TestZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               OmitFramePointers="true"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\minizip"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64"\r
+                               StringPooling="true"\r
+                               BasicRuntimeChecks="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               UsePrecompiledHeader="0"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               WarningLevel="3"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="ia64\ZlibDllRelease\zlibwapi.lib"\r
+                               OutputFile="$(OutDir)/testzlib.exe"\r
+                               LinkIncremental="1"\r
+                               GenerateManifest="false"\r
+                               GenerateDebugInformation="true"\r
+                               SubSystem="1"\r
+                               OptimizeReferences="2"\r
+                               EnableCOMDATFolding="2"\r
+                               OptimizeForWindows98="1"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+       </Configurations>\r
+       <References>\r
+       </References>\r
+       <Files>\r
+               <Filter\r
+                       Name="Source Files"\r
+                       Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm"\r
+                       >\r
+                       <File\r
+                               RelativePath="..\..\testzlib\testzlib.c"\r
+                               >\r
+                       </File>\r
+               </Filter>\r
+               <Filter\r
+                       Name="Header Files"\r
+                       Filter="h;hpp;hxx;hm;inl;inc"\r
+                       >\r
+               </Filter>\r
+               <Filter\r
+                       Name="Resource Files"\r
+                       Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+                       >\r
+               </Filter>\r
+       </Files>\r
+       <Globals>\r
+       </Globals>\r
+</VisualStudioProject>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlib.rc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlib.rc
new file mode 100644 (file)
index 0000000..8f22fab
--- /dev/null
@@ -0,0 +1,32 @@
+#include <windows.h>\r
+\r
+#define IDR_VERSION1  1\r
+IDR_VERSION1   VERSIONINFO     MOVEABLE IMPURE LOADONCALL DISCARDABLE\r
+  FILEVERSION   1.2.6,1\r
+  PRODUCTVERSION 1.2.6,1\r
+  FILEFLAGSMASK        VS_FFI_FILEFLAGSMASK\r
+  FILEFLAGS    0\r
+  FILEOS       VOS_DOS_WINDOWS32\r
+  FILETYPE     VFT_DLL\r
+  FILESUBTYPE  0       // not used\r
+BEGIN\r
+  BLOCK "StringFileInfo"\r
+  BEGIN\r
+    BLOCK "040904E4"\r
+    //language ID = U.S. English, char set = Windows, Multilingual\r
+\r
+    BEGIN\r
+      VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0"\r
+      VALUE "FileVersion",     "1.2.6\0"\r
+      VALUE "InternalName",    "zlib\0"\r
+      VALUE "OriginalFilename",        "zlib.dll\0"\r
+      VALUE "ProductName",     "ZLib.DLL\0"\r
+      VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0"\r
+      VALUE "LegalCopyright", "(C) 1995-2012 Jean-loup Gailly & Mark Adler\0"\r
+    END\r
+  END\r
+  BLOCK "VarFileInfo"\r
+  BEGIN\r
+    VALUE "Translation", 0x0409, 1252\r
+  END\r
+END\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibstat.vcproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibstat.vcproj
new file mode 100644 (file)
index 0000000..61c76c7
--- /dev/null
@@ -0,0 +1,835 @@
+<?xml version="1.0" encoding="Windows-1252"?>\r
+<VisualStudioProject\r
+       ProjectType="Visual C++"\r
+       Version="9,00"\r
+       Name="zlibstat"\r
+       ProjectGUID="{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}"\r
+       TargetFrameworkVersion="131072"\r
+       >\r
+       <Platforms>\r
+               <Platform\r
+                       Name="Win32"\r
+               />\r
+               <Platform\r
+                       Name="x64"\r
+               />\r
+               <Platform\r
+                       Name="Itanium"\r
+               />\r
+       </Platforms>\r
+       <ToolFiles>\r
+       </ToolFiles>\r
+       <Configurations>\r
+               <Configuration\r
+                       Name="Debug|Win32"\r
+                       OutputDirectory="x86\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="1"\r
+                               BufferSecurityCheck="false"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:X86 /NODEFAULTLIB"\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|x64"\r
+                       OutputDirectory="x64\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:AMD64 /NODEFAULTLIB"\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|Itanium"\r
+                       OutputDirectory="ia64\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                               Detect64BitPortabilityProblems="true"\r
+                               DebugInformationFormat="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:IA64 /NODEFAULTLIB"\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Win32"\r
+                       OutputDirectory="x86\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:X86 /NODEFAULTLIB"\r
+                               AdditionalDependencies="..\..\masmx86\match686.obj ..\..\masmx86\inffas32.obj "\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|x64"\r
+                       OutputDirectory="x64\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;WIN64"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:AMD64 /NODEFAULTLIB"\r
+                               AdditionalDependencies="..\..\masmx64\gvmat64.obj ..\..\masmx64\inffasx64.obj "\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Itanium"\r
+                       OutputDirectory="ia64\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:IA64 /NODEFAULTLIB"\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|Win32"\r
+                       OutputDirectory="x86\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:X86 /NODEFAULTLIB"\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|x64"\r
+                       OutputDirectory="x64\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:AMD64 /NODEFAULTLIB"\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|Itanium"\r
+                       OutputDirectory="ia64\ZlibStat$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\ZlibStat$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="4"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TargetEnvironment="2"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLibrarianTool"\r
+                               AdditionalOptions="/MACHINE:IA64 /NODEFAULTLIB"\r
+                               OutputFile="$(OutDir)\zlibstat.lib"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+       </Configurations>\r
+       <References>\r
+       </References>\r
+       <Files>\r
+               <Filter\r
+                       Name="Source Files"\r
+                       >\r
+                       <File\r
+                               RelativePath="..\..\..\adler32.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\compress.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\crc32.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\deflate.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzclose.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzguts.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzlib.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzread.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzwrite.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\infback.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\masmx64\inffas8664.c"\r
+                               >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Debug|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="ReleaseWithoutAsm|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="ReleaseWithoutAsm|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inffast.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inflate.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inftrees.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\minizip\ioapi.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\trees.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\uncompr.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\minizip\unzip.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\minizip\zip.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath=".\zlib.rc"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath=".\zlibvc.def"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\zutil.c"\r
+                               >\r
+                       </File>\r
+               </Filter>\r
+       </Files>\r
+       <Globals>\r
+       </Globals>\r
+</VisualStudioProject>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.def b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.def
new file mode 100644 (file)
index 0000000..571b0a6
--- /dev/null
@@ -0,0 +1,137 @@
+LIBRARY\r
+; zlib data compression and ZIP file I/O library\r
+\r
+VERSION                1.24\r
+\r
+EXPORTS\r
+        adler32                                  @1\r
+        compress                                 @2\r
+        crc32                                    @3\r
+        deflate                                  @4\r
+        deflateCopy                              @5\r
+        deflateEnd                               @6\r
+        deflateInit2_                            @7\r
+        deflateInit_                             @8\r
+        deflateParams                            @9\r
+        deflateReset                             @10\r
+        deflateSetDictionary                     @11\r
+        gzclose                                  @12\r
+        gzdopen                                  @13\r
+        gzerror                                  @14\r
+        gzflush                                  @15\r
+        gzopen                                   @16\r
+        gzread                                   @17\r
+        gzwrite                                  @18\r
+        inflate                                  @19\r
+        inflateEnd                               @20\r
+        inflateInit2_                            @21\r
+        inflateInit_                             @22\r
+        inflateReset                             @23\r
+        inflateSetDictionary                     @24\r
+        inflateSync                              @25\r
+        uncompress                               @26\r
+        zlibVersion                              @27\r
+        gzprintf                                 @28\r
+        gzputc                                   @29\r
+        gzgetc                                   @30\r
+        gzseek                                   @31\r
+        gzrewind                                 @32\r
+        gztell                                   @33\r
+        gzeof                                    @34\r
+        gzsetparams                              @35\r
+        zError                                   @36\r
+        inflateSyncPoint                         @37\r
+        get_crc_table                            @38\r
+        compress2                                @39\r
+        gzputs                                   @40\r
+        gzgets                                   @41\r
+        inflateCopy                              @42\r
+        inflateBackInit_                         @43\r
+        inflateBack                              @44\r
+        inflateBackEnd                           @45\r
+        compressBound                            @46\r
+        deflateBound                             @47\r
+        gzclearerr                               @48\r
+        gzungetc                                 @49\r
+        zlibCompileFlags                         @50\r
+        deflatePrime                             @51\r
+        deflatePending                           @52\r
+\r
+        unzOpen                                  @61\r
+        unzClose                                 @62\r
+        unzGetGlobalInfo                         @63\r
+        unzGetCurrentFileInfo                    @64\r
+        unzGoToFirstFile                         @65\r
+        unzGoToNextFile                          @66\r
+        unzOpenCurrentFile                       @67\r
+        unzReadCurrentFile                       @68\r
+        unzOpenCurrentFile3                      @69\r
+        unztell                                  @70\r
+        unzeof                                   @71\r
+        unzCloseCurrentFile                      @72\r
+        unzGetGlobalComment                      @73\r
+        unzStringFileNameCompare                 @74\r
+        unzLocateFile                            @75\r
+        unzGetLocalExtrafield                    @76\r
+        unzOpen2                                 @77\r
+        unzOpenCurrentFile2                      @78\r
+        unzOpenCurrentFilePassword               @79\r
+\r
+        zipOpen                                  @80\r
+        zipOpenNewFileInZip                      @81\r
+        zipWriteInFileInZip                      @82\r
+        zipCloseFileInZip                        @83\r
+        zipClose                                 @84\r
+        zipOpenNewFileInZip2                     @86\r
+        zipCloseFileInZipRaw                     @87\r
+        zipOpen2                                 @88\r
+        zipOpenNewFileInZip3                     @89\r
+\r
+        unzGetFilePos                            @100\r
+        unzGoToFilePos                           @101\r
+\r
+        fill_win32_filefunc                      @110\r
+\r
+; zlibwapi v1.2.4 added:\r
+        fill_win32_filefunc64                   @111\r
+        fill_win32_filefunc64A                  @112\r
+        fill_win32_filefunc64W                  @113\r
+\r
+        unzOpen64                               @120\r
+        unzOpen2_64                             @121\r
+        unzGetGlobalInfo64                      @122\r
+        unzGetCurrentFileInfo64                 @124\r
+        unzGetCurrentFileZStreamPos64           @125\r
+        unztell64                               @126\r
+        unzGetFilePos64                         @127\r
+        unzGoToFilePos64                        @128\r
+\r
+        zipOpen64                               @130\r
+        zipOpen2_64                             @131\r
+        zipOpenNewFileInZip64                   @132\r
+        zipOpenNewFileInZip2_64                 @133\r
+        zipOpenNewFileInZip3_64                 @134\r
+        zipOpenNewFileInZip4_64                 @135\r
+        zipCloseFileInZipRaw64                  @136\r
+\r
+; zlib1 v1.2.4 added:\r
+        adler32_combine                         @140\r
+        crc32_combine                           @142\r
+        deflateSetHeader                        @144\r
+        deflateTune                             @145\r
+        gzbuffer                                @146\r
+        gzclose_r                               @147\r
+        gzclose_w                               @148\r
+        gzdirect                                @149\r
+        gzoffset                                @150\r
+        inflateGetHeader                        @156\r
+        inflateMark                             @157\r
+        inflatePrime                            @158\r
+        inflateReset2                           @159\r
+        inflateUndermine                        @160\r
+\r
+; zlib1 v1.2.6 added:\r
+        gzgetc_                                 @161\r
+        gzflags                                 @162\r
+        inflateResetKeep                        @163\r
+       deflateResetKeep                        @164
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.sln b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.sln
new file mode 100644 (file)
index 0000000..b482967
--- /dev/null
@@ -0,0 +1,144 @@
+\r
+Microsoft Visual Studio Solution File, Format Version 10.00\r
+# Visual Studio 2008\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestZlibDll", "testzlibdll.vcproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D} = {8FD826F8-3739-44E6-8CC8-997122E53B8D}\r
+       EndProjectSection\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D} = {8FD826F8-3739-44E6-8CC8-997122E53B8D}\r
+       EndProjectSection\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D} = {8FD826F8-3739-44E6-8CC8-997122E53B8D}\r
+       EndProjectSection\r
+EndProject\r
+Global\r
+       GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
+               Debug|Itanium = Debug|Itanium\r
+               Debug|Win32 = Debug|Win32\r
+               Debug|x64 = Debug|x64\r
+               Release|Itanium = Release|Itanium\r
+               Release|Win32 = Release|Win32\r
+               Release|x64 = Release|x64\r
+               ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium\r
+               ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32\r
+               ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64\r
+       EndGlobalSection\r
+       GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.Build.0 = Release|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.Build.0 = Release|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.Build.0 = Release|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.Build.0 = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.Build.0 = Release|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.Build.0 = Debug|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.Build.0 = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+       EndGlobalSection\r
+       GlobalSection(SolutionProperties) = preSolution\r
+               HideSolutionNode = FALSE\r
+       EndGlobalSection\r
+EndGlobal\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.vcproj b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/contrib/vstudio/vc9/zlibvc.vcproj
new file mode 100644 (file)
index 0000000..c9a8947
--- /dev/null
@@ -0,0 +1,1156 @@
+<?xml version="1.0" encoding="Windows-1252"?>\r
+<VisualStudioProject\r
+       ProjectType="Visual C++"\r
+       Version="9,00"\r
+       Name="zlibvc"\r
+       ProjectGUID="{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
+       RootNamespace="zlibvc"\r
+       TargetFrameworkVersion="131072"\r
+       >\r
+       <Platforms>\r
+               <Platform\r
+                       Name="Win32"\r
+               />\r
+               <Platform\r
+                       Name="x64"\r
+               />\r
+               <Platform\r
+                       Name="Itanium"\r
+               />\r
+       </Platforms>\r
+       <ToolFiles>\r
+       </ToolFiles>\r
+       <Configurations>\r
+               <Configuration\r
+                       Name="Debug|Win32"\r
+                       OutputDirectory="x86\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="_DEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="1"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="1"\r
+                               BufferSecurityCheck="false"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                               DebugInformationFormat="4"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="_DEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalOptions="/MACHINE:I386"\r
+                               AdditionalDependencies="..\..\masmx86\match686.obj ..\..\masmx86\inffas32.obj"\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="2"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|x64"\r
+                       OutputDirectory="x64\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="_DEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="3"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="_DEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="..\..\masmx64\gvmat64.obj ..\..\masmx64\inffasx64.obj "\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="2"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Debug|Itanium"\r
+                       OutputDirectory="ia64\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="_DEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="2"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="3"\r
+                               BufferSecurityCheck="false"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                               DebugInformationFormat="3"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="_DEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="2"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|Win32"\r
+                       OutputDirectory="x86\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="1"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerOutput="2"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalOptions="/MACHINE:I386"\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="1"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               IgnoreAllDefaultLibraries="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               OptimizeForWindows98="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|x64"\r
+                       OutputDirectory="x64\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="3"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerOutput="2"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="1"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               IgnoreAllDefaultLibraries="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               OptimizeForWindows98="1"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="ReleaseWithoutAsm|Itanium"\r
+                       OutputDirectory="ia64\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="2"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerOutput="2"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="1"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               IgnoreAllDefaultLibraries="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               OptimizeForWindows98="1"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Win32"\r
+                       OutputDirectory="x86\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x86\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="1"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="0"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerOutput="2"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalOptions="/MACHINE:I386"\r
+                               AdditionalDependencies="..\..\masmx86\match686.obj ..\..\masmx86\inffas32.obj "\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="1"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               IgnoreAllDefaultLibraries="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               OptimizeForWindows98="1"\r
+                               RandomizedBaseAddress="1"\r
+                               DataExecutionPrevention="0"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|x64"\r
+                       OutputDirectory="x64\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="x64\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="3"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerOutput="2"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               AdditionalDependencies="..\..\masmx64\gvmat64.obj ..\..\masmx64\inffasx64.obj "\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="1"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               IgnoreAllDefaultLibraries="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               OptimizeForWindows98="1"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                               TargetMachine="17"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Itanium"\r
+                       OutputDirectory="ia64\ZlibDll$(ConfigurationName)"\r
+                       IntermediateDirectory="ia64\ZlibDll$(ConfigurationName)\Tmp"\r
+                       ConfigurationType="2"\r
+                       InheritedPropertySheets="UpgradeFromVC70.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       WholeProgramOptimization="1"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               MkTypLibCompatible="true"\r
+                               SuppressStartupBanner="true"\r
+                               TargetEnvironment="2"\r
+                               TypeLibraryName="$(OutDir)/zlibvc.tlb"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="..\..\..;..\..\masmx86"\r
+                               PreprocessorDefinitions="_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64"\r
+                               StringPooling="true"\r
+                               ExceptionHandling="0"\r
+                               RuntimeLibrary="2"\r
+                               BufferSecurityCheck="false"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile="$(IntDir)/zlibvc.pch"\r
+                               AssemblerOutput="2"\r
+                               AssemblerListingLocation="$(IntDir)\"\r
+                               ObjectFile="$(IntDir)\"\r
+                               ProgramDataBaseFileName="$(OutDir)\"\r
+                               BrowseInformation="0"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               Culture="1036"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile="$(OutDir)\zlibwapi.dll"\r
+                               LinkIncremental="1"\r
+                               SuppressStartupBanner="true"\r
+                               GenerateManifest="false"\r
+                               IgnoreAllDefaultLibraries="false"\r
+                               ModuleDefinitionFile=".\zlibvc.def"\r
+                               ProgramDatabaseFile="$(OutDir)/zlibwapi.pdb"\r
+                               GenerateMapFile="true"\r
+                               MapFileName="$(OutDir)/zlibwapi.map"\r
+                               SubSystem="2"\r
+                               OptimizeForWindows98="1"\r
+                               ImportLibrary="$(OutDir)/zlibwapi.lib"\r
+                               TargetMachine="5"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+       </Configurations>\r
+       <References>\r
+       </References>\r
+       <Files>\r
+               <Filter\r
+                       Name="Source Files"\r
+                       Filter="cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90"\r
+                       >\r
+                       <File\r
+                               RelativePath="..\..\..\adler32.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\compress.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\crc32.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\deflate.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzclose.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzguts.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzlib.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzread.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\gzwrite.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\infback.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\masmx64\inffas8664.c"\r
+                               >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Debug|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="ReleaseWithoutAsm|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="ReleaseWithoutAsm|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Itanium"\r
+                                       ExcludedFromBuild="true"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                       />\r
+                               </FileConfiguration>\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inffast.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inflate.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inftrees.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\minizip\ioapi.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\minizip\iowin32.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\trees.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\uncompr.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\minizip\unzip.c"\r
+                               >\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               AdditionalIncludeDirectories=""\r
+                                               PreprocessorDefinitions="ZLIB_INTERNAL"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|x64"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               AdditionalIncludeDirectories=""\r
+                                               PreprocessorDefinitions="ZLIB_INTERNAL"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Itanium"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               AdditionalIncludeDirectories=""\r
+                                               PreprocessorDefinitions="ZLIB_INTERNAL"\r
+                                       />\r
+                               </FileConfiguration>\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\minizip\zip.c"\r
+                               >\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               AdditionalIncludeDirectories=""\r
+                                               PreprocessorDefinitions="ZLIB_INTERNAL"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|x64"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               AdditionalIncludeDirectories=""\r
+                                               PreprocessorDefinitions="ZLIB_INTERNAL"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Itanium"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               AdditionalIncludeDirectories=""\r
+                                               PreprocessorDefinitions="ZLIB_INTERNAL"\r
+                                       />\r
+                               </FileConfiguration>\r
+                       </File>\r
+                       <File\r
+                               RelativePath=".\zlib.rc"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath=".\zlibvc.def"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\zutil.c"\r
+                               >\r
+                       </File>\r
+               </Filter>\r
+               <Filter\r
+                       Name="Header Files"\r
+                       Filter="h;hpp;hxx;hm;inl;fi;fd"\r
+                       >\r
+                       <File\r
+                               RelativePath="..\..\..\deflate.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\infblock.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\infcodes.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inffast.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\inftrees.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\infutil.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\zconf.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\zlib.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
+                               RelativePath="..\..\..\zutil.h"\r
+                               >\r
+                       </File>\r
+               </Filter>\r
+               <Filter\r
+                       Name="Resource Files"\r
+                       Filter="ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"\r
+                       >\r
+               </Filter>\r
+       </Files>\r
+       <Globals>\r
+       </Globals>\r
+</VisualStudioProject>\r
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/crc32.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/crc32.c
new file mode 100644 (file)
index 0000000..c12471e
--- /dev/null
@@ -0,0 +1,447 @@
+/* crc32.c -- compute the CRC-32 of a data stream
+ * Copyright (C) 1995-2006, 2010, 2011 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ *
+ * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
+ * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
+ * tables for updating the shift register in one step with three exclusive-ors
+ * instead of four steps with four exclusive-ors.  This results in about a
+ * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
+ */
+
+/* @(#) $Id$ */
+
+/*
+  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
+  protection on the static variables used to control the first-use generation
+  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
+  first call get_crc_table() to initialize the tables before allowing more than
+  one thread to use crc32().
+
+  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.
+ */
+
+#ifdef MAKECRCH
+#  include <stdio.h>
+#  ifndef DYNAMIC_CRC_TABLE
+#    define DYNAMIC_CRC_TABLE
+#  endif /* !DYNAMIC_CRC_TABLE */
+#endif /* MAKECRCH */
+
+#include "zutil.h"      /* for STDC and FAR definitions */
+
+#define local static
+
+/* Find a four-byte integer type for crc32_little() and crc32_big(). */
+#ifndef NOBYFOUR
+#  ifdef STDC           /* need ANSI C limits.h to determine sizes */
+#    include <limits.h>
+#    define BYFOUR
+#    if (UINT_MAX == 0xffffffffUL)
+       typedef unsigned int u4;
+#    else
+#      if (ULONG_MAX == 0xffffffffUL)
+         typedef unsigned long u4;
+#      else
+#        if (USHRT_MAX == 0xffffffffUL)
+           typedef unsigned short u4;
+#        else
+#          undef BYFOUR     /* can't find a four-byte integer type! */
+#        endif
+#      endif
+#    endif
+#  endif /* STDC */
+#endif /* !NOBYFOUR */
+
+/* Definitions for doing the crc four data bytes at a time. */
+#ifdef BYFOUR
+   typedef u4 crc_table_t;
+#  define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \
+                (((w)&0xff00)<<8)+(((w)&0xff)<<24))
+   local unsigned long crc32_little OF((unsigned long,
+                        const unsigned char FAR *, unsigned));
+   local unsigned long crc32_big OF((unsigned long,
+                        const unsigned char FAR *, unsigned));
+#  define TBLS 8
+#else
+   typedef unsigned long crc_table_t;
+#  define TBLS 1
+#endif /* BYFOUR */
+
+/* Local functions for crc concatenation */
+local unsigned long gf2_matrix_times OF((unsigned long *mat,
+                                         unsigned long vec));
+local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
+local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));
+
+
+#ifdef DYNAMIC_CRC_TABLE
+
+local volatile int crc_table_empty = 1;
+local crc_table_t FAR crc_table[TBLS][256];
+local void make_crc_table OF((void));
+#ifdef MAKECRCH
+   local void write_table OF((FILE *, const crc_table_t FAR *));
+#endif /* MAKECRCH */
+/*
+  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
+  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
+
+  Polynomials over GF(2) are represented in binary, one bit per coefficient,
+  with the lowest powers in the most significant bit.  Then adding polynomials
+  is just exclusive-or, and multiplying a polynomial by x is a right shift by
+  one.  If we call the above polynomial p, and represent a byte as the
+  polynomial q, also with the lowest power in the most significant bit (so the
+  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
+  where a mod b means the remainder after dividing a by b.
+
+  This calculation is done using the shift-register method of multiplying and
+  taking the remainder.  The register is initialized to zero, and for each
+  incoming bit, x^32 is added mod p to the register if the bit is a one (where
+  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
+  x (which is shifting right by one and adding x^32 mod p if the bit shifted
+  out is a one).  We start with the highest power (least significant bit) of
+  q and repeat for all eight bits of q.
+
+  The first table is simply the CRC of all possible eight bit values.  This is
+  all the information needed to generate CRCs on data a byte at a time for all
+  combinations of CRC register values and incoming bytes.  The remaining tables
+  allow for word-at-a-time CRC calculation for both big-endian and little-
+  endian machines, where a word is four bytes.
+*/
+local void make_crc_table()
+{
+    crc_table_t c;
+    int n, k;
+    crc_table_t poly;                   /* polynomial exclusive-or pattern */
+    /* terms of polynomial defining this crc (except x^32): */
+    static volatile int first = 1;      /* flag to limit concurrent making */
+    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
+
+    /* See if another task is already doing this (not thread-safe, but better
+       than nothing -- significantly reduces duration of vulnerability in
+       case the advice about DYNAMIC_CRC_TABLE is ignored) */
+    if (first) {
+        first = 0;
+
+        /* make exclusive-or pattern from polynomial (0xedb88320UL) */
+        poly = 0;
+        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)
+            poly |= (crc_table_t)1 << (31 - p[n]);
+
+        /* generate a crc for every 8-bit value */
+        for (n = 0; n < 256; n++) {
+            c = (crc_table_t)n;
+            for (k = 0; k < 8; k++)
+                c = c & 1 ? poly ^ (c >> 1) : c >> 1;
+            crc_table[0][n] = c;
+        }
+
+#ifdef BYFOUR
+        /* generate crc for each value followed by one, two, and three zeros,
+           and then the byte reversal of those as well as the first table */
+        for (n = 0; n < 256; n++) {
+            c = crc_table[0][n];
+            crc_table[4][n] = REV(c);
+            for (k = 1; k < 4; k++) {
+                c = crc_table[0][c & 0xff] ^ (c >> 8);
+                crc_table[k][n] = c;
+                crc_table[k + 4][n] = REV(c);
+            }
+        }
+#endif /* BYFOUR */
+
+        crc_table_empty = 0;
+    }
+    else {      /* not first */
+        /* wait for the other guy to finish (not efficient, but rare) */
+        while (crc_table_empty)
+            ;
+    }
+
+#ifdef MAKECRCH
+    /* write out CRC tables to crc32.h */
+    {
+        FILE *out;
+
+        out = fopen("crc32.h", "w");
+        if (out == NULL) return;
+        fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
+        fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
+        fprintf(out, "local const crc_table_t FAR ");
+        fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
+        write_table(out, crc_table[0]);
+#  ifdef BYFOUR
+        fprintf(out, "#ifdef BYFOUR\n");
+        for (k = 1; k < 8; k++) {
+            fprintf(out, "  },\n  {\n");
+            write_table(out, crc_table[k]);
+        }
+        fprintf(out, "#endif\n");
+#  endif /* BYFOUR */
+        fprintf(out, "  }\n};\n");
+        fclose(out);
+    }
+#endif /* MAKECRCH */
+}
+
+#ifdef MAKECRCH
+local void write_table(out, table)
+    FILE *out;
+    const crc_table_t FAR *table;
+{
+    int n;
+
+    for (n = 0; n < 256; n++)
+        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ",
+                (unsigned long)(table[n]),
+                n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
+}
+#endif /* MAKECRCH */
+
+#else /* !DYNAMIC_CRC_TABLE */
+/* ========================================================================
+ * Tables of CRC-32s of all single-byte values, made by make_crc_table().
+ */
+#include "crc32.h"
+#endif /* DYNAMIC_CRC_TABLE */
+
+/* =========================================================================
+ * This function can be used by asm versions of crc32()
+ */
+const unsigned long FAR * ZEXPORT get_crc_table()
+{
+#ifdef DYNAMIC_CRC_TABLE
+    if (crc_table_empty)
+        make_crc_table();
+#endif /* DYNAMIC_CRC_TABLE */
+    return (const unsigned long FAR *)crc_table;
+}
+
+/* ========================================================================= */
+#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
+#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
+
+/* ========================================================================= */
+unsigned long ZEXPORT crc32(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    uInt len;
+{
+    if (buf == Z_NULL) return 0UL;
+
+#ifdef DYNAMIC_CRC_TABLE
+    if (crc_table_empty)
+        make_crc_table();
+#endif /* DYNAMIC_CRC_TABLE */
+
+#ifdef BYFOUR
+    if (sizeof(void *) == sizeof(ptrdiff_t)) {
+        u4 endian;
+
+        endian = 1;
+        if (*((unsigned char *)(&endian)))
+            return crc32_little(crc, buf, len);
+        else
+            return crc32_big(crc, buf, len);
+    }
+#endif /* BYFOUR */
+    crc = crc ^ 0xffffffffUL;
+    while (len >= 8) {
+        DO8;
+        len -= 8;
+    }
+    if (len) do {
+        DO1;
+    } while (--len);
+    return crc ^ 0xffffffffUL;
+}
+
+#ifdef BYFOUR
+
+/* ========================================================================= */
+#define DOLIT4 c ^= *buf4++; \
+        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
+            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
+#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
+
+/* ========================================================================= */
+local unsigned long crc32_little(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    unsigned len;
+{
+    register u4 c;
+    register const u4 FAR *buf4;
+
+    c = (u4)crc;
+    c = ~c;
+    while (len && ((ptrdiff_t)buf & 3)) {
+        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
+        len--;
+    }
+
+    buf4 = (const u4 FAR *)(const void FAR *)buf;
+    while (len >= 32) {
+        DOLIT32;
+        len -= 32;
+    }
+    while (len >= 4) {
+        DOLIT4;
+        len -= 4;
+    }
+    buf = (const unsigned char FAR *)buf4;
+
+    if (len) do {
+        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
+    } while (--len);
+    c = ~c;
+    return (unsigned long)c;
+}
+
+/* ========================================================================= */
+#define DOBIG4 c ^= *++buf4; \
+        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
+            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
+#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
+
+/* ========================================================================= */
+local unsigned long crc32_big(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    unsigned len;
+{
+    register u4 c;
+    register const u4 FAR *buf4;
+
+    c = REV((u4)crc);
+    c = ~c;
+    while (len && ((ptrdiff_t)buf & 3)) {
+        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
+        len--;
+    }
+
+    buf4 = (const u4 FAR *)(const void FAR *)buf;
+    buf4--;
+    while (len >= 32) {
+        DOBIG32;
+        len -= 32;
+    }
+    while (len >= 4) {
+        DOBIG4;
+        len -= 4;
+    }
+    buf4++;
+    buf = (const unsigned char FAR *)buf4;
+
+    if (len) do {
+        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
+    } while (--len);
+    c = ~c;
+    return (unsigned long)(REV(c));
+}
+
+#endif /* BYFOUR */
+
+#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */
+
+/* ========================================================================= */
+local unsigned long gf2_matrix_times(mat, vec)
+    unsigned long *mat;
+    unsigned long vec;
+{
+    unsigned long sum;
+
+    sum = 0;
+    while (vec) {
+        if (vec & 1)
+            sum ^= *mat;
+        vec >>= 1;
+        mat++;
+    }
+    return sum;
+}
+
+/* ========================================================================= */
+local void gf2_matrix_square(square, mat)
+    unsigned long *square;
+    unsigned long *mat;
+{
+    int n;
+
+    for (n = 0; n < GF2_DIM; n++)
+        square[n] = gf2_matrix_times(mat, mat[n]);
+}
+
+/* ========================================================================= */
+local uLong crc32_combine_(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off64_t len2;
+{
+    int n;
+    unsigned long row;
+    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
+    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
+
+    /* degenerate case (also disallow negative lengths) */
+    if (len2 <= 0)
+        return crc1;
+
+    /* put operator for one zero bit in odd */
+    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
+    row = 1;
+    for (n = 1; n < GF2_DIM; n++) {
+        odd[n] = row;
+        row <<= 1;
+    }
+
+    /* put operator for two zero bits in even */
+    gf2_matrix_square(even, odd);
+
+    /* put operator for four zero bits in odd */
+    gf2_matrix_square(odd, even);
+
+    /* apply len2 zeros to crc1 (first square will put the operator for one
+       zero byte, eight zero bits, in even) */
+    do {
+        /* apply zeros operator for this bit of len2 */
+        gf2_matrix_square(even, odd);
+        if (len2 & 1)
+            crc1 = gf2_matrix_times(even, crc1);
+        len2 >>= 1;
+
+        /* if no more bits set, then done */
+        if (len2 == 0)
+            break;
+
+        /* another iteration of the loop with odd and even swapped */
+        gf2_matrix_square(odd, even);
+        if (len2 & 1)
+            crc1 = gf2_matrix_times(odd, crc1);
+        len2 >>= 1;
+
+        /* if no more bits set, then done */
+    } while (len2 != 0);
+
+    /* return combined crc */
+    crc1 ^= crc2;
+    return crc1;
+}
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_combine(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
+
+uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off64_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/crc32.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/crc32.h
new file mode 100644 (file)
index 0000000..c3e7171
--- /dev/null
@@ -0,0 +1,441 @@
+/* crc32.h -- tables for rapid CRC calculation
+ * Generated automatically by crc32.c
+ */
+
+local const crc_table_t FAR crc_table[TBLS][256] =
+{
+  {
+    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
+    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
+    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
+    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
+    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
+    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
+    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
+    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
+    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
+    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
+    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
+    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
+    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
+    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
+    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
+    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
+    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
+    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
+    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
+    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
+    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
+    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
+    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
+    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
+    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
+    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
+    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
+    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
+    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
+    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
+    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
+    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
+    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
+    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
+    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
+    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
+    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
+    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
+    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
+    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
+    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
+    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
+    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
+    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
+    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
+    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
+    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
+    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
+    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
+    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
+    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
+    0x2d02ef8dUL
+#ifdef BYFOUR
+  },
+  {
+    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
+    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
+    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
+    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
+    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
+    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
+    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
+    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
+    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
+    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
+    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
+    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
+    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
+    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
+    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
+    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
+    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
+    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
+    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
+    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
+    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
+    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
+    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
+    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
+    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
+    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
+    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
+    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
+    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
+    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
+    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
+    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
+    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
+    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
+    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
+    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
+    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
+    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
+    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
+    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
+    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
+    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
+    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
+    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
+    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
+    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
+    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
+    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
+    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
+    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
+    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
+    0x9324fd72UL
+  },
+  {
+    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
+    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
+    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
+    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
+    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
+    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
+    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
+    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
+    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
+    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
+    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
+    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
+    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
+    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
+    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
+    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
+    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
+    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
+    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
+    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
+    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
+    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
+    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
+    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
+    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
+    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
+    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
+    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
+    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
+    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
+    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
+    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
+    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
+    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
+    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
+    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
+    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
+    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
+    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
+    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
+    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
+    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
+    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
+    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
+    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
+    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
+    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
+    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
+    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
+    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
+    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
+    0xbe9834edUL
+  },
+  {
+    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
+    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
+    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
+    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
+    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
+    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
+    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
+    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
+    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
+    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
+    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
+    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
+    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
+    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
+    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
+    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
+    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
+    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
+    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
+    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
+    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
+    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
+    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
+    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
+    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
+    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
+    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
+    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
+    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
+    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
+    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
+    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
+    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
+    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
+    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
+    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
+    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
+    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
+    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
+    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
+    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
+    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
+    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
+    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
+    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
+    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
+    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
+    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
+    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
+    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
+    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
+    0xde0506f1UL
+  },
+  {
+    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
+    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
+    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
+    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
+    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
+    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
+    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
+    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
+    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
+    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
+    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
+    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
+    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
+    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
+    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
+    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
+    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
+    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
+    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
+    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
+    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
+    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
+    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
+    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
+    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
+    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
+    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
+    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
+    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
+    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
+    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
+    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
+    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
+    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
+    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
+    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
+    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
+    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
+    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
+    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
+    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
+    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
+    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
+    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
+    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
+    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
+    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
+    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
+    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
+    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
+    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
+    0x8def022dUL
+  },
+  {
+    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
+    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
+    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
+    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
+    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
+    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
+    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
+    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
+    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
+    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
+    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
+    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
+    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
+    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
+    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
+    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
+    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
+    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
+    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
+    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
+    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
+    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
+    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
+    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
+    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
+    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
+    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
+    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
+    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
+    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
+    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
+    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
+    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
+    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
+    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
+    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
+    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
+    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
+    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
+    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
+    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
+    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
+    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
+    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
+    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
+    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
+    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
+    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
+    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
+    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
+    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
+    0x72fd2493UL
+  },
+  {
+    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
+    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
+    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
+    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
+    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
+    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
+    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
+    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
+    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
+    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
+    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
+    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
+    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
+    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
+    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
+    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
+    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
+    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
+    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
+    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
+    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
+    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
+    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
+    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
+    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
+    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
+    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
+    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
+    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
+    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
+    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
+    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
+    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
+    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
+    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
+    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
+    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
+    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
+    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
+    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
+    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
+    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
+    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
+    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
+    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
+    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
+    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
+    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
+    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
+    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
+    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
+    0xed3498beUL
+  },
+  {
+    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
+    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
+    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
+    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
+    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
+    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
+    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
+    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
+    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
+    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
+    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
+    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
+    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
+    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
+    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
+    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
+    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
+    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
+    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
+    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
+    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
+    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
+    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
+    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
+    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
+    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
+    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
+    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
+    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
+    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
+    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
+    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
+    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
+    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
+    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
+    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
+    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
+    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
+    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
+    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
+    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
+    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
+    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
+    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
+    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
+    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
+    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
+    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
+    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
+    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
+    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
+    0xf10605deUL
+#endif
+  }
+};
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/deflate.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/deflate.c
new file mode 100644 (file)
index 0000000..8bd480e
--- /dev/null
@@ -0,0 +1,1965 @@
+/* deflate.c -- compress data using the deflation algorithm
+ * Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ *  ALGORITHM
+ *
+ *      The "deflation" process depends on being able to identify portions
+ *      of the input text which are identical to earlier input (within a
+ *      sliding window trailing behind the input currently being processed).
+ *
+ *      The most straightforward technique turns out to be the fastest for
+ *      most input files: try all possible matches and select the longest.
+ *      The key feature of this algorithm is that insertions into the string
+ *      dictionary are very simple and thus fast, and deletions are avoided
+ *      completely. Insertions are performed at each input character, whereas
+ *      string matches are performed only when the previous match ends. So it
+ *      is preferable to spend more time in matches to allow very fast string
+ *      insertions and avoid deletions. The matching algorithm for small
+ *      strings is inspired from that of Rabin & Karp. A brute force approach
+ *      is used to find longer strings when a small match has been found.
+ *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
+ *      (by Leonid Broukhis).
+ *         A previous version of this file used a more sophisticated algorithm
+ *      (by Fiala and Greene) which is guaranteed to run in linear amortized
+ *      time, but has a larger average cost, uses more memory and is patented.
+ *      However the F&G algorithm may be faster for some highly redundant
+ *      files if the parameter max_chain_length (described below) is too large.
+ *
+ *  ACKNOWLEDGEMENTS
+ *
+ *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
+ *      I found it in 'freeze' written by Leonid Broukhis.
+ *      Thanks to many people for bug reports and testing.
+ *
+ *  REFERENCES
+ *
+ *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
+ *      Available in http://tools.ietf.org/html/rfc1951
+ *
+ *      A description of the Rabin and Karp algorithm is given in the book
+ *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
+ *
+ *      Fiala,E.R., and Greene,D.H.
+ *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
+ *
+ */
+
+/* @(#) $Id$ */
+
+#include "deflate.h"
+
+const char deflate_copyright[] =
+   " deflate 1.2.6 Copyright 1995-2012 Jean-loup Gailly and Mark Adler ";
+/*
+  If you use the zlib library in a product, an acknowledgment is welcome
+  in the documentation of your product. If for some reason you cannot
+  include such an acknowledgment, I would appreciate that you keep this
+  copyright string in the executable of your product.
+ */
+
+/* ===========================================================================
+ *  Function prototypes.
+ */
+typedef enum {
+    need_more,      /* block not completed, need more input or more output */
+    block_done,     /* block flush performed */
+    finish_started, /* finish started, need only more output at next deflate */
+    finish_done     /* finish done, accept no more input or output */
+} block_state;
+
+typedef block_state (*compress_func) OF((deflate_state *s, int flush));
+/* Compression function. Returns the block state after the call. */
+
+local void fill_window    OF((deflate_state *s));
+local block_state deflate_stored OF((deflate_state *s, int flush));
+local block_state deflate_fast   OF((deflate_state *s, int flush));
+#ifndef FASTEST
+local block_state deflate_slow   OF((deflate_state *s, int flush));
+#endif
+local block_state deflate_rle    OF((deflate_state *s, int flush));
+local block_state deflate_huff   OF((deflate_state *s, int flush));
+local void lm_init        OF((deflate_state *s));
+local void putShortMSB    OF((deflate_state *s, uInt b));
+local void flush_pending  OF((z_streamp strm));
+local int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
+#ifdef ASMV
+      void match_init OF((void)); /* asm code initialization */
+      uInt longest_match  OF((deflate_state *s, IPos cur_match));
+#else
+local uInt longest_match  OF((deflate_state *s, IPos cur_match));
+#endif
+
+#ifdef DEBUG
+local  void check_match OF((deflate_state *s, IPos start, IPos match,
+                            int length));
+#endif
+
+/* ===========================================================================
+ * Local data
+ */
+
+#define NIL 0
+/* Tail of hash chains */
+
+#ifndef TOO_FAR
+#  define TOO_FAR 4096
+#endif
+/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
+
+/* Values for max_lazy_match, good_match and max_chain_length, depending on
+ * the desired pack level (0..9). The values given below have been tuned to
+ * exclude worst case performance for pathological files. Better values may be
+ * found for specific files.
+ */
+typedef struct config_s {
+   ush good_length; /* reduce lazy search above this match length */
+   ush max_lazy;    /* do not perform lazy search above this match length */
+   ush nice_length; /* quit search above this match length */
+   ush max_chain;
+   compress_func func;
+} config;
+
+#ifdef FASTEST
+local const config configuration_table[2] = {
+/*      good lazy nice chain */
+/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
+/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
+#else
+local const config configuration_table[10] = {
+/*      good lazy nice chain */
+/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
+/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
+/* 2 */ {4,    5, 16,    8, deflate_fast},
+/* 3 */ {4,    6, 32,   32, deflate_fast},
+
+/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
+/* 5 */ {8,   16, 32,   32, deflate_slow},
+/* 6 */ {8,   16, 128, 128, deflate_slow},
+/* 7 */ {8,   32, 128, 256, deflate_slow},
+/* 8 */ {32, 128, 258, 1024, deflate_slow},
+/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
+#endif
+
+/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
+ * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
+ * meaning.
+ */
+
+#define EQUAL 0
+/* result of memcmp for equal strings */
+
+#ifndef NO_DUMMY_DECL
+struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
+#endif
+
+/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
+#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0))
+
+/* ===========================================================================
+ * Update a hash value with the given input byte
+ * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
+ *    input characters, so that a running hash key can be computed from the
+ *    previous key instead of complete recalculation each time.
+ */
+#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
+
+
+/* ===========================================================================
+ * Insert string str in the dictionary and set match_head to the previous head
+ * of the hash chain (the most recent string with same hash key). Return
+ * the previous length of the hash chain.
+ * If this file is compiled with -DFASTEST, the compression level is forced
+ * to 1, and no hash chains are maintained.
+ * IN  assertion: all calls to to INSERT_STRING are made with consecutive
+ *    input characters and the first MIN_MATCH bytes of str are valid
+ *    (except for the last MIN_MATCH-1 bytes of the input file).
+ */
+#ifdef FASTEST
+#define INSERT_STRING(s, str, match_head) \
+   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
+    match_head = s->head[s->ins_h], \
+    s->head[s->ins_h] = (Pos)(str))
+#else
+#define INSERT_STRING(s, str, match_head) \
+   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
+    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
+    s->head[s->ins_h] = (Pos)(str))
+#endif
+
+/* ===========================================================================
+ * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
+ * prev[] will be initialized on the fly.
+ */
+#define CLEAR_HASH(s) \
+    s->head[s->hash_size-1] = NIL; \
+    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
+
+/* ========================================================================= */
+int ZEXPORT deflateInit_(strm, level, version, stream_size)
+    z_streamp strm;
+    int level;
+    const char *version;
+    int stream_size;
+{
+    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
+                         Z_DEFAULT_STRATEGY, version, stream_size);
+    /* To do: ignore strm->next_in if we use it as window */
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
+                  version, stream_size)
+    z_streamp strm;
+    int  level;
+    int  method;
+    int  windowBits;
+    int  memLevel;
+    int  strategy;
+    const char *version;
+    int stream_size;
+{
+    deflate_state *s;
+    int wrap = 1;
+    static const char my_version[] = ZLIB_VERSION;
+
+    ushf *overlay;
+    /* We overlay pending_buf and d_buf+l_buf. This works since the average
+     * output size for (length,distance) codes is <= 24 bits.
+     */
+
+    if (version == Z_NULL || version[0] != my_version[0] ||
+        stream_size != sizeof(z_stream)) {
+        return Z_VERSION_ERROR;
+    }
+    if (strm == Z_NULL) return Z_STREAM_ERROR;
+
+    strm->msg = Z_NULL;
+    if (strm->zalloc == (alloc_func)0) {
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+#endif
+    }
+    if (strm->zfree == (free_func)0)
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zfree = zcfree;
+#endif
+
+#ifdef FASTEST
+    if (level != 0) level = 1;
+#else
+    if (level == Z_DEFAULT_COMPRESSION) level = 6;
+#endif
+
+    if (windowBits < 0) { /* suppress zlib wrapper */
+        wrap = 0;
+        windowBits = -windowBits;
+    }
+#ifdef GZIP
+    else if (windowBits > 15) {
+        wrap = 2;       /* write gzip wrapper instead */
+        windowBits -= 16;
+    }
+#endif
+    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
+        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
+        strategy < 0 || strategy > Z_FIXED) {
+        return Z_STREAM_ERROR;
+    }
+    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
+    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
+    if (s == Z_NULL) return Z_MEM_ERROR;
+    strm->state = (struct internal_state FAR *)s;
+    s->strm = strm;
+
+    s->wrap = wrap;
+    s->gzhead = Z_NULL;
+    s->w_bits = windowBits;
+    s->w_size = 1 << s->w_bits;
+    s->w_mask = s->w_size - 1;
+
+    s->hash_bits = memLevel + 7;
+    s->hash_size = 1 << s->hash_bits;
+    s->hash_mask = s->hash_size - 1;
+    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
+
+    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
+    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
+    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
+
+    s->high_water = 0;      /* nothing written to s->window yet */
+
+    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
+
+    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
+    s->pending_buf = (uchf *) overlay;
+    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
+
+    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
+        s->pending_buf == Z_NULL) {
+        s->status = FINISH_STATE;
+        strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
+        deflateEnd (strm);
+        return Z_MEM_ERROR;
+    }
+    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
+    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
+
+    s->level = level;
+    s->strategy = strategy;
+    s->method = (Byte)method;
+
+    return deflateReset(strm);
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
+    z_streamp strm;
+    const Bytef *dictionary;
+    uInt  dictLength;
+{
+    deflate_state *s;
+    uInt str, n;
+    int wrap;
+    unsigned avail;
+    unsigned char *next;
+
+    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL)
+        return Z_STREAM_ERROR;
+    s = strm->state;
+    wrap = s->wrap;
+    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
+        return Z_STREAM_ERROR;
+
+    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
+    if (wrap == 1)
+        strm->adler = adler32(strm->adler, dictionary, dictLength);
+    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
+
+    /* if dictionary would fill window, just replace the history */
+    if (dictLength >= s->w_size) {
+        if (wrap == 0) {            /* already empty otherwise */
+            CLEAR_HASH(s);
+            s->strstart = 0;
+            s->block_start = 0L;
+            s->insert = 0;
+        }
+        dictionary += dictLength - s->w_size;  /* use the tail */
+        dictLength = s->w_size;
+    }
+
+    /* insert dictionary into window and hash */
+    avail = strm->avail_in;
+    next = strm->next_in;
+    strm->avail_in = dictLength;
+    strm->next_in = (Bytef *)dictionary;
+    fill_window(s);
+    while (s->lookahead >= MIN_MATCH) {
+        str = s->strstart;
+        n = s->lookahead - (MIN_MATCH-1);
+        do {
+            UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
+#ifndef FASTEST
+            s->prev[str & s->w_mask] = s->head[s->ins_h];
+#endif
+            s->head[s->ins_h] = (Pos)str;
+            str++;
+        } while (--n);
+        s->strstart = str;
+        s->lookahead = MIN_MATCH-1;
+        fill_window(s);
+    }
+    s->strstart += s->lookahead;
+    s->block_start = (long)s->strstart;
+    s->insert = s->lookahead;
+    s->lookahead = 0;
+    s->match_length = s->prev_length = MIN_MATCH-1;
+    s->match_available = 0;
+    strm->next_in = next;
+    strm->avail_in = avail;
+    s->wrap = wrap;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateResetKeep (strm)
+    z_streamp strm;
+{
+    deflate_state *s;
+
+    if (strm == Z_NULL || strm->state == Z_NULL ||
+        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
+        return Z_STREAM_ERROR;
+    }
+
+    strm->total_in = strm->total_out = 0;
+    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
+    strm->data_type = Z_UNKNOWN;
+
+    s = (deflate_state *)strm->state;
+    s->pending = 0;
+    s->pending_out = s->pending_buf;
+
+    if (s->wrap < 0) {
+        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
+    }
+    s->status = s->wrap ? INIT_STATE : BUSY_STATE;
+    strm->adler =
+#ifdef GZIP
+        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
+#endif
+        adler32(0L, Z_NULL, 0);
+    s->last_flush = Z_NO_FLUSH;
+
+    _tr_init(s);
+
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateReset (strm)
+    z_streamp strm;
+{
+    int ret;
+
+    ret = deflateResetKeep(strm);
+    if (ret == Z_OK)
+        lm_init(strm->state);
+    return ret;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateSetHeader (strm, head)
+    z_streamp strm;
+    gz_headerp head;
+{
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    if (strm->state->wrap != 2) return Z_STREAM_ERROR;
+    strm->state->gzhead = head;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflatePending (strm, pending, bits)
+    unsigned *pending;
+    int *bits;
+    z_streamp strm;
+{
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    if (pending != Z_NULL)
+        *pending = strm->state->pending;
+    if (bits != Z_NULL)
+        *bits = strm->state->bi_valid;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflatePrime (strm, bits, value)
+    z_streamp strm;
+    int bits;
+    int value;
+{
+    deflate_state *s;
+    int put;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    s = strm->state;
+    if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
+        return Z_BUF_ERROR;
+    do {
+        put = Buf_size - s->bi_valid;
+        if (put > bits)
+            put = bits;
+        s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
+        s->bi_valid += put;
+        _tr_flush_bits(s);
+        value >>= put;
+        bits -= put;
+    } while (bits);
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateParams(strm, level, strategy)
+    z_streamp strm;
+    int level;
+    int strategy;
+{
+    deflate_state *s;
+    compress_func func;
+    int err = Z_OK;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    s = strm->state;
+
+#ifdef FASTEST
+    if (level != 0) level = 1;
+#else
+    if (level == Z_DEFAULT_COMPRESSION) level = 6;
+#endif
+    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
+        return Z_STREAM_ERROR;
+    }
+    func = configuration_table[s->level].func;
+
+    if ((strategy != s->strategy || func != configuration_table[level].func) &&
+        strm->total_in != 0) {
+        /* Flush the last buffer: */
+        err = deflate(strm, Z_BLOCK);
+    }
+    if (s->level != level) {
+        s->level = level;
+        s->max_lazy_match   = configuration_table[level].max_lazy;
+        s->good_match       = configuration_table[level].good_length;
+        s->nice_match       = configuration_table[level].nice_length;
+        s->max_chain_length = configuration_table[level].max_chain;
+    }
+    s->strategy = strategy;
+    return err;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
+    z_streamp strm;
+    int good_length;
+    int max_lazy;
+    int nice_length;
+    int max_chain;
+{
+    deflate_state *s;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    s = strm->state;
+    s->good_match = good_length;
+    s->max_lazy_match = max_lazy;
+    s->nice_match = nice_length;
+    s->max_chain_length = max_chain;
+    return Z_OK;
+}
+
+/* =========================================================================
+ * For the default windowBits of 15 and memLevel of 8, this function returns
+ * a close to exact, as well as small, upper bound on the compressed size.
+ * They are coded as constants here for a reason--if the #define's are
+ * changed, then this function needs to be changed as well.  The return
+ * value for 15 and 8 only works for those exact settings.
+ *
+ * For any setting other than those defaults for windowBits and memLevel,
+ * the value returned is a conservative worst case for the maximum expansion
+ * resulting from using fixed blocks instead of stored blocks, which deflate
+ * can emit on compressed data for some combinations of the parameters.
+ *
+ * This function could be more sophisticated to provide closer upper bounds for
+ * every combination of windowBits and memLevel.  But even the conservative
+ * upper bound of about 14% expansion does not seem onerous for output buffer
+ * allocation.
+ */
+uLong ZEXPORT deflateBound(strm, sourceLen)
+    z_streamp strm;
+    uLong sourceLen;
+{
+    deflate_state *s;
+    uLong complen, wraplen;
+    Bytef *str;
+
+    /* conservative upper bound for compressed data */
+    complen = sourceLen +
+              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
+
+    /* if can't get parameters, return conservative bound plus zlib wrapper */
+    if (strm == Z_NULL || strm->state == Z_NULL)
+        return complen + 6;
+
+    /* compute wrapper length */
+    s = strm->state;
+    switch (s->wrap) {
+    case 0:                                 /* raw deflate */
+        wraplen = 0;
+        break;
+    case 1:                                 /* zlib wrapper */
+        wraplen = 6 + (s->strstart ? 4 : 0);
+        break;
+    case 2:                                 /* gzip wrapper */
+        wraplen = 18;
+        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
+            if (s->gzhead->extra != Z_NULL)
+                wraplen += 2 + s->gzhead->extra_len;
+            str = s->gzhead->name;
+            if (str != Z_NULL)
+                do {
+                    wraplen++;
+                } while (*str++);
+            str = s->gzhead->comment;
+            if (str != Z_NULL)
+                do {
+                    wraplen++;
+                } while (*str++);
+            if (s->gzhead->hcrc)
+                wraplen += 2;
+        }
+        break;
+    default:                                /* for compiler happiness */
+        wraplen = 6;
+    }
+
+    /* if not default parameters, return conservative bound */
+    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
+        return complen + wraplen;
+
+    /* default settings: return tight bound for that case */
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+           (sourceLen >> 25) + 13 - 6 + wraplen;
+}
+
+/* =========================================================================
+ * Put a short in the pending buffer. The 16-bit value is put in MSB order.
+ * IN assertion: the stream state is correct and there is enough room in
+ * pending_buf.
+ */
+local void putShortMSB (s, b)
+    deflate_state *s;
+    uInt b;
+{
+    put_byte(s, (Byte)(b >> 8));
+    put_byte(s, (Byte)(b & 0xff));
+}
+
+/* =========================================================================
+ * Flush as much pending output as possible. All deflate() output goes
+ * through this function so some applications may wish to modify it
+ * to avoid allocating a large strm->next_out buffer and copying into it.
+ * (See also read_buf()).
+ */
+local void flush_pending(strm)
+    z_streamp strm;
+{
+    unsigned len;
+    deflate_state *s = strm->state;
+
+    _tr_flush_bits(s);
+    len = s->pending;
+    if (len > strm->avail_out) len = strm->avail_out;
+    if (len == 0) return;
+
+    zmemcpy(strm->next_out, s->pending_out, len);
+    strm->next_out  += len;
+    s->pending_out  += len;
+    strm->total_out += len;
+    strm->avail_out  -= len;
+    s->pending -= len;
+    if (s->pending == 0) {
+        s->pending_out = s->pending_buf;
+    }
+}
+
+/* ========================================================================= */
+int ZEXPORT deflate (strm, flush)
+    z_streamp strm;
+    int flush;
+{
+    int old_flush; /* value of flush param for previous deflate call */
+    deflate_state *s;
+
+    if (strm == Z_NULL || strm->state == Z_NULL ||
+        flush > Z_BLOCK || flush < 0) {
+        return Z_STREAM_ERROR;
+    }
+    s = strm->state;
+
+    if (strm->next_out == Z_NULL ||
+        (strm->next_in == Z_NULL && strm->avail_in != 0) ||
+        (s->status == FINISH_STATE && flush != Z_FINISH)) {
+        ERR_RETURN(strm, Z_STREAM_ERROR);
+    }
+    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
+
+    s->strm = strm; /* just in case */
+    old_flush = s->last_flush;
+    s->last_flush = flush;
+
+    /* Write the header */
+    if (s->status == INIT_STATE) {
+#ifdef GZIP
+        if (s->wrap == 2) {
+            strm->adler = crc32(0L, Z_NULL, 0);
+            put_byte(s, 31);
+            put_byte(s, 139);
+            put_byte(s, 8);
+            if (s->gzhead == Z_NULL) {
+                put_byte(s, 0);
+                put_byte(s, 0);
+                put_byte(s, 0);
+                put_byte(s, 0);
+                put_byte(s, 0);
+                put_byte(s, s->level == 9 ? 2 :
+                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
+                             4 : 0));
+                put_byte(s, OS_CODE);
+                s->status = BUSY_STATE;
+            }
+            else {
+                put_byte(s, (s->gzhead->text ? 1 : 0) +
+                            (s->gzhead->hcrc ? 2 : 0) +
+                            (s->gzhead->extra == Z_NULL ? 0 : 4) +
+                            (s->gzhead->name == Z_NULL ? 0 : 8) +
+                            (s->gzhead->comment == Z_NULL ? 0 : 16)
+                        );
+                put_byte(s, (Byte)(s->gzhead->time & 0xff));
+                put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
+                put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
+                put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
+                put_byte(s, s->level == 9 ? 2 :
+                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
+                             4 : 0));
+                put_byte(s, s->gzhead->os & 0xff);
+                if (s->gzhead->extra != Z_NULL) {
+                    put_byte(s, s->gzhead->extra_len & 0xff);
+                    put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
+                }
+                if (s->gzhead->hcrc)
+                    strm->adler = crc32(strm->adler, s->pending_buf,
+                                        s->pending);
+                s->gzindex = 0;
+                s->status = EXTRA_STATE;
+            }
+        }
+        else
+#endif
+        {
+            uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
+            uInt level_flags;
+
+            if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
+                level_flags = 0;
+            else if (s->level < 6)
+                level_flags = 1;
+            else if (s->level == 6)
+                level_flags = 2;
+            else
+                level_flags = 3;
+            header |= (level_flags << 6);
+            if (s->strstart != 0) header |= PRESET_DICT;
+            header += 31 - (header % 31);
+
+            s->status = BUSY_STATE;
+            putShortMSB(s, header);
+
+            /* Save the adler32 of the preset dictionary: */
+            if (s->strstart != 0) {
+                putShortMSB(s, (uInt)(strm->adler >> 16));
+                putShortMSB(s, (uInt)(strm->adler & 0xffff));
+            }
+            strm->adler = adler32(0L, Z_NULL, 0);
+        }
+    }
+#ifdef GZIP
+    if (s->status == EXTRA_STATE) {
+        if (s->gzhead->extra != Z_NULL) {
+            uInt beg = s->pending;  /* start of bytes to update crc */
+
+            while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
+                if (s->pending == s->pending_buf_size) {
+                    if (s->gzhead->hcrc && s->pending > beg)
+                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                            s->pending - beg);
+                    flush_pending(strm);
+                    beg = s->pending;
+                    if (s->pending == s->pending_buf_size)
+                        break;
+                }
+                put_byte(s, s->gzhead->extra[s->gzindex]);
+                s->gzindex++;
+            }
+            if (s->gzhead->hcrc && s->pending > beg)
+                strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                    s->pending - beg);
+            if (s->gzindex == s->gzhead->extra_len) {
+                s->gzindex = 0;
+                s->status = NAME_STATE;
+            }
+        }
+        else
+            s->status = NAME_STATE;
+    }
+    if (s->status == NAME_STATE) {
+        if (s->gzhead->name != Z_NULL) {
+            uInt beg = s->pending;  /* start of bytes to update crc */
+            int val;
+
+            do {
+                if (s->pending == s->pending_buf_size) {
+                    if (s->gzhead->hcrc && s->pending > beg)
+                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                            s->pending - beg);
+                    flush_pending(strm);
+                    beg = s->pending;
+                    if (s->pending == s->pending_buf_size) {
+                        val = 1;
+                        break;
+                    }
+                }
+                val = s->gzhead->name[s->gzindex++];
+                put_byte(s, val);
+            } while (val != 0);
+            if (s->gzhead->hcrc && s->pending > beg)
+                strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                    s->pending - beg);
+            if (val == 0) {
+                s->gzindex = 0;
+                s->status = COMMENT_STATE;
+            }
+        }
+        else
+            s->status = COMMENT_STATE;
+    }
+    if (s->status == COMMENT_STATE) {
+        if (s->gzhead->comment != Z_NULL) {
+            uInt beg = s->pending;  /* start of bytes to update crc */
+            int val;
+
+            do {
+                if (s->pending == s->pending_buf_size) {
+                    if (s->gzhead->hcrc && s->pending > beg)
+                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                            s->pending - beg);
+                    flush_pending(strm);
+                    beg = s->pending;
+                    if (s->pending == s->pending_buf_size) {
+                        val = 1;
+                        break;
+                    }
+                }
+                val = s->gzhead->comment[s->gzindex++];
+                put_byte(s, val);
+            } while (val != 0);
+            if (s->gzhead->hcrc && s->pending > beg)
+                strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                    s->pending - beg);
+            if (val == 0)
+                s->status = HCRC_STATE;
+        }
+        else
+            s->status = HCRC_STATE;
+    }
+    if (s->status == HCRC_STATE) {
+        if (s->gzhead->hcrc) {
+            if (s->pending + 2 > s->pending_buf_size)
+                flush_pending(strm);
+            if (s->pending + 2 <= s->pending_buf_size) {
+                put_byte(s, (Byte)(strm->adler & 0xff));
+                put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
+                strm->adler = crc32(0L, Z_NULL, 0);
+                s->status = BUSY_STATE;
+            }
+        }
+        else
+            s->status = BUSY_STATE;
+    }
+#endif
+
+    /* Flush as much pending output as possible */
+    if (s->pending != 0) {
+        flush_pending(strm);
+        if (strm->avail_out == 0) {
+            /* Since avail_out is 0, deflate will be called again with
+             * more output space, but possibly with both pending and
+             * avail_in equal to zero. There won't be anything to do,
+             * but this is not an error situation so make sure we
+             * return OK instead of BUF_ERROR at next call of deflate:
+             */
+            s->last_flush = -1;
+            return Z_OK;
+        }
+
+    /* Make sure there is something to do and avoid duplicate consecutive
+     * flushes. For repeated and useless calls with Z_FINISH, we keep
+     * returning Z_STREAM_END instead of Z_BUF_ERROR.
+     */
+    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
+               flush != Z_FINISH) {
+        ERR_RETURN(strm, Z_BUF_ERROR);
+    }
+
+    /* User must not provide more input after the first FINISH: */
+    if (s->status == FINISH_STATE && strm->avail_in != 0) {
+        ERR_RETURN(strm, Z_BUF_ERROR);
+    }
+
+    /* Start a new block or continue the current one.
+     */
+    if (strm->avail_in != 0 || s->lookahead != 0 ||
+        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
+        block_state bstate;
+
+        bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
+                    (s->strategy == Z_RLE ? deflate_rle(s, flush) :
+                        (*(configuration_table[s->level].func))(s, flush));
+
+        if (bstate == finish_started || bstate == finish_done) {
+            s->status = FINISH_STATE;
+        }
+        if (bstate == need_more || bstate == finish_started) {
+            if (strm->avail_out == 0) {
+                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
+            }
+            return Z_OK;
+            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
+             * of deflate should use the same flush parameter to make sure
+             * that the flush is complete. So we don't have to output an
+             * empty block here, this will be done at next call. This also
+             * ensures that for a very small output buffer, we emit at most
+             * one empty block.
+             */
+        }
+        if (bstate == block_done) {
+            if (flush == Z_PARTIAL_FLUSH) {
+                _tr_align(s);
+            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
+                _tr_stored_block(s, (char*)0, 0L, 0);
+                /* For a full flush, this empty block will be recognized
+                 * as a special marker by inflate_sync().
+                 */
+                if (flush == Z_FULL_FLUSH) {
+                    CLEAR_HASH(s);             /* forget history */
+                    if (s->lookahead == 0) {
+                        s->strstart = 0;
+                        s->block_start = 0L;
+                        s->insert = 0;
+                    }
+                }
+            }
+            flush_pending(strm);
+            if (strm->avail_out == 0) {
+              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
+              return Z_OK;
+            }
+        }
+    }
+    Assert(strm->avail_out > 0, "bug2");
+
+    if (flush != Z_FINISH) return Z_OK;
+    if (s->wrap <= 0) return Z_STREAM_END;
+
+    /* Write the trailer */
+#ifdef GZIP
+    if (s->wrap == 2) {
+        put_byte(s, (Byte)(strm->adler & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
+        put_byte(s, (Byte)(strm->total_in & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
+    }
+    else
+#endif
+    {
+        putShortMSB(s, (uInt)(strm->adler >> 16));
+        putShortMSB(s, (uInt)(strm->adler & 0xffff));
+    }
+    flush_pending(strm);
+    /* If avail_out is zero, the application will call deflate again
+     * to flush the rest.
+     */
+    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
+    return s->pending != 0 ? Z_OK : Z_STREAM_END;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateEnd (strm)
+    z_streamp strm;
+{
+    int status;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+
+    status = strm->state->status;
+    if (status != INIT_STATE &&
+        status != EXTRA_STATE &&
+        status != NAME_STATE &&
+        status != COMMENT_STATE &&
+        status != HCRC_STATE &&
+        status != BUSY_STATE &&
+        status != FINISH_STATE) {
+      return Z_STREAM_ERROR;
+    }
+
+    /* Deallocate in reverse order of allocations: */
+    TRY_FREE(strm, strm->state->pending_buf);
+    TRY_FREE(strm, strm->state->head);
+    TRY_FREE(strm, strm->state->prev);
+    TRY_FREE(strm, strm->state->window);
+
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+
+    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
+}
+
+/* =========================================================================
+ * Copy the source state to the destination state.
+ * To simplify the source, this is not supported for 16-bit MSDOS (which
+ * doesn't have enough memory anyway to duplicate compression states).
+ */
+int ZEXPORT deflateCopy (dest, source)
+    z_streamp dest;
+    z_streamp source;
+{
+#ifdef MAXSEG_64K
+    return Z_STREAM_ERROR;
+#else
+    deflate_state *ds;
+    deflate_state *ss;
+    ushf *overlay;
+
+
+    if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
+        return Z_STREAM_ERROR;
+    }
+
+    ss = source->state;
+
+    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
+
+    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
+    if (ds == Z_NULL) return Z_MEM_ERROR;
+    dest->state = (struct internal_state FAR *) ds;
+    zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
+    ds->strm = dest;
+
+    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
+    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
+    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
+    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
+    ds->pending_buf = (uchf *) overlay;
+
+    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
+        ds->pending_buf == Z_NULL) {
+        deflateEnd (dest);
+        return Z_MEM_ERROR;
+    }
+    /* following zmemcpy do not work for 16-bit MSDOS */
+    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
+    zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
+    zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
+    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
+
+    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
+    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
+    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
+
+    ds->l_desc.dyn_tree = ds->dyn_ltree;
+    ds->d_desc.dyn_tree = ds->dyn_dtree;
+    ds->bl_desc.dyn_tree = ds->bl_tree;
+
+    return Z_OK;
+#endif /* MAXSEG_64K */
+}
+
+/* ===========================================================================
+ * Read a new buffer from the current input stream, update the adler32
+ * and total number of bytes read.  All deflate() input goes through
+ * this function so some applications may wish to modify it to avoid
+ * allocating a large strm->next_in buffer and copying from it.
+ * (See also flush_pending()).
+ */
+local int read_buf(strm, buf, size)
+    z_streamp strm;
+    Bytef *buf;
+    unsigned size;
+{
+    unsigned len = strm->avail_in;
+
+    if (len > size) len = size;
+    if (len == 0) return 0;
+
+    strm->avail_in  -= len;
+
+    zmemcpy(buf, strm->next_in, len);
+    if (strm->state->wrap == 1) {
+        strm->adler = adler32(strm->adler, buf, len);
+    }
+#ifdef GZIP
+    else if (strm->state->wrap == 2) {
+        strm->adler = crc32(strm->adler, buf, len);
+    }
+#endif
+    strm->next_in  += len;
+    strm->total_in += len;
+
+    return (int)len;
+}
+
+/* ===========================================================================
+ * Initialize the "longest match" routines for a new zlib stream
+ */
+local void lm_init (s)
+    deflate_state *s;
+{
+    s->window_size = (ulg)2L*s->w_size;
+
+    CLEAR_HASH(s);
+
+    /* Set the default configuration parameters:
+     */
+    s->max_lazy_match   = configuration_table[s->level].max_lazy;
+    s->good_match       = configuration_table[s->level].good_length;
+    s->nice_match       = configuration_table[s->level].nice_length;
+    s->max_chain_length = configuration_table[s->level].max_chain;
+
+    s->strstart = 0;
+    s->block_start = 0L;
+    s->lookahead = 0;
+    s->insert = 0;
+    s->match_length = s->prev_length = MIN_MATCH-1;
+    s->match_available = 0;
+    s->ins_h = 0;
+#ifndef FASTEST
+#ifdef ASMV
+    match_init(); /* initialize the asm code */
+#endif
+#endif
+}
+
+#ifndef FASTEST
+/* ===========================================================================
+ * Set match_start to the longest match starting at the given string and
+ * return its length. Matches shorter or equal to prev_length are discarded,
+ * in which case the result is equal to prev_length and match_start is
+ * garbage.
+ * IN assertions: cur_match is the head of the hash chain for the current
+ *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
+ * OUT assertion: the match length is not greater than s->lookahead.
+ */
+#ifndef ASMV
+/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
+ * match.S. The code will be functionally equivalent.
+ */
+local uInt longest_match(s, cur_match)
+    deflate_state *s;
+    IPos cur_match;                             /* current match */
+{
+    unsigned chain_length = s->max_chain_length;/* max hash chain length */
+    register Bytef *scan = s->window + s->strstart; /* current string */
+    register Bytef *match;                       /* matched string */
+    register int len;                           /* length of current match */
+    int best_len = s->prev_length;              /* best match length so far */
+    int nice_match = s->nice_match;             /* stop if match long enough */
+    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
+        s->strstart - (IPos)MAX_DIST(s) : NIL;
+    /* Stop when cur_match becomes <= limit. To simplify the code,
+     * we prevent matches with the string of window index 0.
+     */
+    Posf *prev = s->prev;
+    uInt wmask = s->w_mask;
+
+#ifdef UNALIGNED_OK
+    /* Compare two bytes at a time. Note: this is not always beneficial.
+     * Try with and without -DUNALIGNED_OK to check.
+     */
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
+    register ush scan_start = *(ushf*)scan;
+    register ush scan_end   = *(ushf*)(scan+best_len-1);
+#else
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
+    register Byte scan_end1  = scan[best_len-1];
+    register Byte scan_end   = scan[best_len];
+#endif
+
+    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
+     * It is easy to get rid of this optimization if necessary.
+     */
+    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
+
+    /* Do not waste too much time if we already have a good match: */
+    if (s->prev_length >= s->good_match) {
+        chain_length >>= 2;
+    }
+    /* Do not look for matches beyond the end of the input. This is necessary
+     * to make deflate deterministic.
+     */
+    if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
+
+    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
+
+    do {
+        Assert(cur_match < s->strstart, "no future");
+        match = s->window + cur_match;
+
+        /* Skip to next match if the match length cannot increase
+         * or if the match length is less than 2.  Note that the checks below
+         * for insufficient lookahead only occur occasionally for performance
+         * reasons.  Therefore uninitialized memory will be accessed, and
+         * conditional jumps will be made that depend on those values.
+         * However the length of the match is limited to the lookahead, so
+         * the output of deflate is not affected by the uninitialized values.
+         */
+#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
+        /* This code assumes sizeof(unsigned short) == 2. Do not use
+         * UNALIGNED_OK if your compiler uses a different size.
+         */
+        if (*(ushf*)(match+best_len-1) != scan_end ||
+            *(ushf*)match != scan_start) continue;
+
+        /* It is not necessary to compare scan[2] and match[2] since they are
+         * always equal when the other bytes match, given that the hash keys
+         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
+         * strstart+3, +5, ... up to strstart+257. We check for insufficient
+         * lookahead only every 4th comparison; the 128th check will be made
+         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
+         * necessary to put more guard bytes at the end of the window, or
+         * to check more often for insufficient lookahead.
+         */
+        Assert(scan[2] == match[2], "scan[2]?");
+        scan++, match++;
+        do {
+        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 scan < strend);
+        /* The funny "do {}" generates better code on most compilers */
+
+        /* Here, scan <= window+strstart+257 */
+        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+        if (*scan == *match) scan++;
+
+        len = (MAX_MATCH - 1) - (int)(strend-scan);
+        scan = strend - (MAX_MATCH-1);
+
+#else /* UNALIGNED_OK */
+
+        if (match[best_len]   != scan_end  ||
+            match[best_len-1] != scan_end1 ||
+            *match            != *scan     ||
+            *++match          != scan[1])      continue;
+
+        /* The check at best_len-1 can be removed because it will be made
+         * again later. (This heuristic is not always a win.)
+         * It is not necessary to compare scan[2] and match[2] since they
+         * are always equal when the other bytes match, given that
+         * the hash keys are equal and that HASH_BITS >= 8.
+         */
+        scan += 2, match++;
+        Assert(*scan == *match, "match[2]?");
+
+        /* We check for insufficient lookahead only every 8th comparison;
+         * the 256th check will be made at strstart+258.
+         */
+        do {
+        } while (*++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 scan < strend);
+
+        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+
+        len = MAX_MATCH - (int)(strend - scan);
+        scan = strend - MAX_MATCH;
+
+#endif /* UNALIGNED_OK */
+
+        if (len > best_len) {
+            s->match_start = cur_match;
+            best_len = len;
+            if (len >= nice_match) break;
+#ifdef UNALIGNED_OK
+            scan_end = *(ushf*)(scan+best_len-1);
+#else
+            scan_end1  = scan[best_len-1];
+            scan_end   = scan[best_len];
+#endif
+        }
+    } while ((cur_match = prev[cur_match & wmask]) > limit
+             && --chain_length != 0);
+
+    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
+    return s->lookahead;
+}
+#endif /* ASMV */
+
+#else /* FASTEST */
+
+/* ---------------------------------------------------------------------------
+ * Optimized version for FASTEST only
+ */
+local uInt longest_match(s, cur_match)
+    deflate_state *s;
+    IPos cur_match;                             /* current match */
+{
+    register Bytef *scan = s->window + s->strstart; /* current string */
+    register Bytef *match;                       /* matched string */
+    register int len;                           /* length of current match */
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
+
+    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
+     * It is easy to get rid of this optimization if necessary.
+     */
+    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
+
+    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
+
+    Assert(cur_match < s->strstart, "no future");
+
+    match = s->window + cur_match;
+
+    /* Return failure if the match length is less than 2:
+     */
+    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
+
+    /* The check at best_len-1 can be removed because it will be made
+     * again later. (This heuristic is not always a win.)
+     * It is not necessary to compare scan[2] and match[2] since they
+     * are always equal when the other bytes match, given that
+     * the hash keys are equal and that HASH_BITS >= 8.
+     */
+    scan += 2, match += 2;
+    Assert(*scan == *match, "match[2]?");
+
+    /* We check for insufficient lookahead only every 8th comparison;
+     * the 256th check will be made at strstart+258.
+     */
+    do {
+    } while (*++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             scan < strend);
+
+    Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+
+    len = MAX_MATCH - (int)(strend - scan);
+
+    if (len < MIN_MATCH) return MIN_MATCH - 1;
+
+    s->match_start = cur_match;
+    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
+}
+
+#endif /* FASTEST */
+
+#ifdef DEBUG
+/* ===========================================================================
+ * Check that the match at match_start is indeed a match.
+ */
+local void check_match(s, start, match, length)
+    deflate_state *s;
+    IPos start, match;
+    int length;
+{
+    /* check that the match is indeed a match */
+    if (zmemcmp(s->window + match,
+                s->window + start, length) != EQUAL) {
+        fprintf(stderr, " start %u, match %u, length %d\n",
+                start, match, length);
+        do {
+            fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
+        } while (--length != 0);
+        z_error("invalid match");
+    }
+    if (z_verbose > 1) {
+        fprintf(stderr,"\\[%d,%d]", start-match, length);
+        do { putc(s->window[start++], stderr); } while (--length != 0);
+    }
+}
+#else
+#  define check_match(s, start, match, length)
+#endif /* DEBUG */
+
+/* ===========================================================================
+ * Fill the window when the lookahead becomes insufficient.
+ * Updates strstart and lookahead.
+ *
+ * IN assertion: lookahead < MIN_LOOKAHEAD
+ * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
+ *    At least one byte has been read, or avail_in == 0; reads are
+ *    performed for at least two bytes (required for the zip translate_eol
+ *    option -- not supported here).
+ */
+local void fill_window(s)
+    deflate_state *s;
+{
+    register unsigned n, m;
+    register Posf *p;
+    unsigned more;    /* Amount of free space at the end of the window. */
+    uInt wsize = s->w_size;
+
+    Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
+
+    do {
+        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
+
+        /* Deal with !@#$% 64K limit: */
+        if (sizeof(int) <= 2) {
+            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
+                more = wsize;
+
+            } else if (more == (unsigned)(-1)) {
+                /* Very unlikely, but possible on 16 bit machine if
+                 * strstart == 0 && lookahead == 1 (input done a byte at time)
+                 */
+                more--;
+            }
+        }
+
+        /* If the window is almost full and there is insufficient lookahead,
+         * move the upper half to the lower one to make room in the upper half.
+         */
+        if (s->strstart >= wsize+MAX_DIST(s)) {
+
+            zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
+            s->match_start -= wsize;
+            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
+            s->block_start -= (long) wsize;
+
+            /* Slide the hash table (could be avoided with 32 bit values
+               at the expense of memory usage). We slide even when level == 0
+               to keep the hash table consistent if we switch back to level > 0
+               later. (Using level 0 permanently is not an optimal usage of
+               zlib, so we don't care about this pathological case.)
+             */
+            n = s->hash_size;
+            p = &s->head[n];
+            do {
+                m = *--p;
+                *p = (Pos)(m >= wsize ? m-wsize : NIL);
+            } while (--n);
+
+            n = wsize;
+#ifndef FASTEST
+            p = &s->prev[n];
+            do {
+                m = *--p;
+                *p = (Pos)(m >= wsize ? m-wsize : NIL);
+                /* If n is not on any hash chain, prev[n] is garbage but
+                 * its value will never be used.
+                 */
+            } while (--n);
+#endif
+            more += wsize;
+        }
+        if (s->strm->avail_in == 0) break;
+
+        /* If there was no sliding:
+         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
+         *    more == window_size - lookahead - strstart
+         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
+         * => more >= window_size - 2*WSIZE + 2
+         * In the BIG_MEM or MMAP case (not yet supported),
+         *   window_size == input_size + MIN_LOOKAHEAD  &&
+         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
+         * Otherwise, window_size == 2*WSIZE so more >= 2.
+         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
+         */
+        Assert(more >= 2, "more < 2");
+
+        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
+        s->lookahead += n;
+
+        /* Initialize the hash value now that we have some input: */
+        if (s->lookahead + s->insert >= MIN_MATCH) {
+            uInt str = s->strstart - s->insert;
+            s->ins_h = s->window[str];
+            UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
+#if MIN_MATCH != 3
+            Call UPDATE_HASH() MIN_MATCH-3 more times
+#endif
+            while (s->insert) {
+                UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
+#ifndef FASTEST
+                s->prev[str & s->w_mask] = s->head[s->ins_h];
+#endif
+                s->head[s->ins_h] = (Pos)str;
+                str++;
+                s->insert--;
+                if (s->lookahead + s->insert < MIN_MATCH)
+                    break;
+            }
+        }
+        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
+         * but this is not important since only literal bytes will be emitted.
+         */
+
+    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
+
+    /* If the WIN_INIT bytes after the end of the current data have never been
+     * written, then zero those bytes in order to avoid memory check reports of
+     * the use of uninitialized (or uninitialised as Julian writes) bytes by
+     * the longest match routines.  Update the high water mark for the next
+     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
+     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
+     */
+    if (s->high_water < s->window_size) {
+        ulg curr = s->strstart + (ulg)(s->lookahead);
+        ulg init;
+
+        if (s->high_water < curr) {
+            /* Previous high water mark below current data -- zero WIN_INIT
+             * bytes or up to end of window, whichever is less.
+             */
+            init = s->window_size - curr;
+            if (init > WIN_INIT)
+                init = WIN_INIT;
+            zmemzero(s->window + curr, (unsigned)init);
+            s->high_water = curr + init;
+        }
+        else if (s->high_water < (ulg)curr + WIN_INIT) {
+            /* High water mark at or above current data, but below current data
+             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
+             * to end of window, whichever is less.
+             */
+            init = (ulg)curr + WIN_INIT - s->high_water;
+            if (init > s->window_size - s->high_water)
+                init = s->window_size - s->high_water;
+            zmemzero(s->window + s->high_water, (unsigned)init);
+            s->high_water += init;
+        }
+    }
+
+    Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
+           "not enough room for search");
+}
+
+/* ===========================================================================
+ * Flush the current block, with given end-of-file flag.
+ * IN assertion: strstart is set to the end of the current match.
+ */
+#define FLUSH_BLOCK_ONLY(s, last) { \
+   _tr_flush_block(s, (s->block_start >= 0L ? \
+                   (charf *)&s->window[(unsigned)s->block_start] : \
+                   (charf *)Z_NULL), \
+                (ulg)((long)s->strstart - s->block_start), \
+                (last)); \
+   s->block_start = s->strstart; \
+   flush_pending(s->strm); \
+   Tracev((stderr,"[FLUSH]")); \
+}
+
+/* Same but force premature exit if necessary. */
+#define FLUSH_BLOCK(s, last) { \
+   FLUSH_BLOCK_ONLY(s, last); \
+   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
+}
+
+/* ===========================================================================
+ * Copy without compression as much as possible from the input stream, return
+ * the current block state.
+ * This function does not insert new strings in the dictionary since
+ * uncompressible data is probably not useful. This function is used
+ * only for the level=0 compression option.
+ * NOTE: this function should be optimized to avoid extra copying from
+ * window to pending_buf.
+ */
+local block_state deflate_stored(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
+     * to pending_buf_size, and each stored block has a 5 byte header:
+     */
+    ulg max_block_size = 0xffff;
+    ulg max_start;
+
+    if (max_block_size > s->pending_buf_size - 5) {
+        max_block_size = s->pending_buf_size - 5;
+    }
+
+    /* Copy as much as possible from input to output: */
+    for (;;) {
+        /* Fill the window as much as possible: */
+        if (s->lookahead <= 1) {
+
+            Assert(s->strstart < s->w_size+MAX_DIST(s) ||
+                   s->block_start >= (long)s->w_size, "slide too late");
+
+            fill_window(s);
+            if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
+
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+        Assert(s->block_start >= 0L, "block gone");
+
+        s->strstart += s->lookahead;
+        s->lookahead = 0;
+
+        /* Emit a stored block if pending_buf will be full: */
+        max_start = s->block_start + max_block_size;
+        if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
+            /* strstart == 0 is possible when wraparound on 16-bit machine */
+            s->lookahead = (uInt)(s->strstart - max_start);
+            s->strstart = (uInt)max_start;
+            FLUSH_BLOCK(s, 0);
+        }
+        /* Flush if we may have to slide, otherwise block_start may become
+         * negative and the data will be gone:
+         */
+        if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
+            FLUSH_BLOCK(s, 0);
+        }
+    }
+    s->insert = 0;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if ((long)s->strstart > s->block_start)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
+
+/* ===========================================================================
+ * Compress as much as possible from the input stream, return the current
+ * block state.
+ * This function does not perform lazy evaluation of matches and inserts
+ * new strings in the dictionary only for unmatched strings or for short
+ * matches. It is used only for the fast compression options.
+ */
+local block_state deflate_fast(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    IPos hash_head;       /* head of the hash chain */
+    int bflush;           /* set if current block must be flushed */
+
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the next match, plus MIN_MATCH bytes to insert the
+         * string following the next match.
+         */
+        if (s->lookahead < MIN_LOOKAHEAD) {
+            fill_window(s);
+            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* Insert the string window[strstart .. strstart+2] in the
+         * dictionary, and set hash_head to the head of the hash chain:
+         */
+        hash_head = NIL;
+        if (s->lookahead >= MIN_MATCH) {
+            INSERT_STRING(s, s->strstart, hash_head);
+        }
+
+        /* Find the longest match, discarding those <= prev_length.
+         * At this point we have always match_length < MIN_MATCH
+         */
+        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
+            /* To simplify the code, we prevent matches with the string
+             * of window index 0 (in particular we have to avoid a match
+             * of the string with itself at the start of the input file).
+             */
+            s->match_length = longest_match (s, hash_head);
+            /* longest_match() sets match_start */
+        }
+        if (s->match_length >= MIN_MATCH) {
+            check_match(s, s->strstart, s->match_start, s->match_length);
+
+            _tr_tally_dist(s, s->strstart - s->match_start,
+                           s->match_length - MIN_MATCH, bflush);
+
+            s->lookahead -= s->match_length;
+
+            /* Insert new strings in the hash table only if the match length
+             * is not too large. This saves time but degrades compression.
+             */
+#ifndef FASTEST
+            if (s->match_length <= s->max_insert_length &&
+                s->lookahead >= MIN_MATCH) {
+                s->match_length--; /* string at strstart already in table */
+                do {
+                    s->strstart++;
+                    INSERT_STRING(s, s->strstart, hash_head);
+                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
+                     * always MIN_MATCH bytes ahead.
+                     */
+                } while (--s->match_length != 0);
+                s->strstart++;
+            } else
+#endif
+            {
+                s->strstart += s->match_length;
+                s->match_length = 0;
+                s->ins_h = s->window[s->strstart];
+                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
+#if MIN_MATCH != 3
+                Call UPDATE_HASH() MIN_MATCH-3 more times
+#endif
+                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
+                 * matter since it will be recomputed at next deflate call.
+                 */
+            }
+        } else {
+            /* No match, output a literal byte */
+            Tracevv((stderr,"%c", s->window[s->strstart]));
+            _tr_tally_lit (s, s->window[s->strstart], bflush);
+            s->lookahead--;
+            s->strstart++;
+        }
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if (s->last_lit)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
+
+#ifndef FASTEST
+/* ===========================================================================
+ * Same as above, but achieves better compression. We use a lazy
+ * evaluation for matches: a match is finally adopted only if there is
+ * no better match at the next window position.
+ */
+local block_state deflate_slow(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    IPos hash_head;          /* head of hash chain */
+    int bflush;              /* set if current block must be flushed */
+
+    /* Process the input block. */
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the next match, plus MIN_MATCH bytes to insert the
+         * string following the next match.
+         */
+        if (s->lookahead < MIN_LOOKAHEAD) {
+            fill_window(s);
+            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* Insert the string window[strstart .. strstart+2] in the
+         * dictionary, and set hash_head to the head of the hash chain:
+         */
+        hash_head = NIL;
+        if (s->lookahead >= MIN_MATCH) {
+            INSERT_STRING(s, s->strstart, hash_head);
+        }
+
+        /* Find the longest match, discarding those <= prev_length.
+         */
+        s->prev_length = s->match_length, s->prev_match = s->match_start;
+        s->match_length = MIN_MATCH-1;
+
+        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
+            s->strstart - hash_head <= MAX_DIST(s)) {
+            /* To simplify the code, we prevent matches with the string
+             * of window index 0 (in particular we have to avoid a match
+             * of the string with itself at the start of the input file).
+             */
+            s->match_length = longest_match (s, hash_head);
+            /* longest_match() sets match_start */
+
+            if (s->match_length <= 5 && (s->strategy == Z_FILTERED
+#if TOO_FAR <= 32767
+                || (s->match_length == MIN_MATCH &&
+                    s->strstart - s->match_start > TOO_FAR)
+#endif
+                )) {
+
+                /* If prev_match is also MIN_MATCH, match_start is garbage
+                 * but we will ignore the current match anyway.
+                 */
+                s->match_length = MIN_MATCH-1;
+            }
+        }
+        /* If there was a match at the previous step and the current
+         * match is not better, output the previous match:
+         */
+        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
+            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
+            /* Do not insert strings in hash table beyond this. */
+
+            check_match(s, s->strstart-1, s->prev_match, s->prev_length);
+
+            _tr_tally_dist(s, s->strstart -1 - s->prev_match,
+                           s->prev_length - MIN_MATCH, bflush);
+
+            /* Insert in hash table all strings up to the end of the match.
+             * strstart-1 and strstart are already inserted. If there is not
+             * enough lookahead, the last two strings are not inserted in
+             * the hash table.
+             */
+            s->lookahead -= s->prev_length-1;
+            s->prev_length -= 2;
+            do {
+                if (++s->strstart <= max_insert) {
+                    INSERT_STRING(s, s->strstart, hash_head);
+                }
+            } while (--s->prev_length != 0);
+            s->match_available = 0;
+            s->match_length = MIN_MATCH-1;
+            s->strstart++;
+
+            if (bflush) FLUSH_BLOCK(s, 0);
+
+        } else if (s->match_available) {
+            /* If there was no match at the previous position, output a
+             * single literal. If there was a match but the current match
+             * is longer, truncate the previous match to a single literal.
+             */
+            Tracevv((stderr,"%c", s->window[s->strstart-1]));
+            _tr_tally_lit(s, s->window[s->strstart-1], bflush);
+            if (bflush) {
+                FLUSH_BLOCK_ONLY(s, 0);
+            }
+            s->strstart++;
+            s->lookahead--;
+            if (s->strm->avail_out == 0) return need_more;
+        } else {
+            /* There is no previous match to compare with, wait for
+             * the next step to decide.
+             */
+            s->match_available = 1;
+            s->strstart++;
+            s->lookahead--;
+        }
+    }
+    Assert (flush != Z_NO_FLUSH, "no flush?");
+    if (s->match_available) {
+        Tracevv((stderr,"%c", s->window[s->strstart-1]));
+        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
+        s->match_available = 0;
+    }
+    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if (s->last_lit)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
+#endif /* FASTEST */
+
+/* ===========================================================================
+ * For Z_RLE, simply look for runs of bytes, generate matches only of distance
+ * one.  Do not maintain a hash table.  (It will be regenerated if this run of
+ * deflate switches away from Z_RLE.)
+ */
+local block_state deflate_rle(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    int bflush;             /* set if current block must be flushed */
+    uInt prev;              /* byte at distance one to match */
+    Bytef *scan, *strend;   /* scan goes up to strend for length of run */
+
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the longest run, plus one for the unrolled loop.
+         */
+        if (s->lookahead <= MAX_MATCH) {
+            fill_window(s);
+            if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* See how many times the previous byte repeats */
+        s->match_length = 0;
+        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
+            scan = s->window + s->strstart - 1;
+            prev = *scan;
+            if (prev == *++scan && prev == *++scan && prev == *++scan) {
+                strend = s->window + s->strstart + MAX_MATCH;
+                do {
+                } while (prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         scan < strend);
+                s->match_length = MAX_MATCH - (int)(strend - scan);
+                if (s->match_length > s->lookahead)
+                    s->match_length = s->lookahead;
+            }
+            Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
+        }
+
+        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
+        if (s->match_length >= MIN_MATCH) {
+            check_match(s, s->strstart, s->strstart - 1, s->match_length);
+
+            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
+
+            s->lookahead -= s->match_length;
+            s->strstart += s->match_length;
+            s->match_length = 0;
+        } else {
+            /* No match, output a literal byte */
+            Tracevv((stderr,"%c", s->window[s->strstart]));
+            _tr_tally_lit (s, s->window[s->strstart], bflush);
+            s->lookahead--;
+            s->strstart++;
+        }
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    s->insert = 0;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if (s->last_lit)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
+
+/* ===========================================================================
+ * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
+ * (It will be regenerated if this run of deflate switches away from Huffman.)
+ */
+local block_state deflate_huff(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    int bflush;             /* set if current block must be flushed */
+
+    for (;;) {
+        /* Make sure that we have a literal to write. */
+        if (s->lookahead == 0) {
+            fill_window(s);
+            if (s->lookahead == 0) {
+                if (flush == Z_NO_FLUSH)
+                    return need_more;
+                break;      /* flush the current block */
+            }
+        }
+
+        /* Output a literal byte */
+        s->match_length = 0;
+        Tracevv((stderr,"%c", s->window[s->strstart]));
+        _tr_tally_lit (s, s->window[s->strstart], bflush);
+        s->lookahead--;
+        s->strstart++;
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    s->insert = 0;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if (s->last_lit)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/deflate.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/deflate.h
new file mode 100644 (file)
index 0000000..fbac44d
--- /dev/null
@@ -0,0 +1,346 @@
+/* deflate.h -- internal compression state
+ * Copyright (C) 1995-2012 Jean-loup Gailly
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* @(#) $Id$ */
+
+#ifndef DEFLATE_H
+#define DEFLATE_H
+
+#include "zutil.h"
+
+/* define NO_GZIP when compiling if you want to disable gzip header and
+   trailer creation by deflate().  NO_GZIP would be used to avoid linking in
+   the crc code when it is not needed.  For shared libraries, gzip encoding
+   should be left enabled. */
+#ifndef NO_GZIP
+#  define GZIP
+#endif
+
+/* ===========================================================================
+ * Internal compression state.
+ */
+
+#define LENGTH_CODES 29
+/* number of length codes, not counting the special END_BLOCK code */
+
+#define LITERALS  256
+/* number of literal bytes 0..255 */
+
+#define L_CODES (LITERALS+1+LENGTH_CODES)
+/* number of Literal or Length codes, including the END_BLOCK code */
+
+#define D_CODES   30
+/* number of distance codes */
+
+#define BL_CODES  19
+/* number of codes used to transfer the bit lengths */
+
+#define HEAP_SIZE (2*L_CODES+1)
+/* maximum heap size */
+
+#define MAX_BITS 15
+/* All codes must not exceed MAX_BITS bits */
+
+#define Buf_size 16
+/* size of bit buffer in bi_buf */
+
+#define INIT_STATE    42
+#define EXTRA_STATE   69
+#define NAME_STATE    73
+#define COMMENT_STATE 91
+#define HCRC_STATE   103
+#define BUSY_STATE   113
+#define FINISH_STATE 666
+/* Stream status */
+
+
+/* Data structure describing a single value and its code string. */
+typedef struct ct_data_s {
+    union {
+        ush  freq;       /* frequency count */
+        ush  code;       /* bit string */
+    } fc;
+    union {
+        ush  dad;        /* father node in Huffman tree */
+        ush  len;        /* length of bit string */
+    } dl;
+} FAR ct_data;
+
+#define Freq fc.freq
+#define Code fc.code
+#define Dad  dl.dad
+#define Len  dl.len
+
+typedef struct static_tree_desc_s  static_tree_desc;
+
+typedef struct tree_desc_s {
+    ct_data *dyn_tree;           /* the dynamic tree */
+    int     max_code;            /* largest code with non zero frequency */
+    static_tree_desc *stat_desc; /* the corresponding static tree */
+} FAR tree_desc;
+
+typedef ush Pos;
+typedef Pos FAR Posf;
+typedef unsigned IPos;
+
+/* A Pos is an index in the character window. We use short instead of int to
+ * save space in the various tables. IPos is used only for parameter passing.
+ */
+
+typedef struct internal_state {
+    z_streamp strm;      /* pointer back to this zlib stream */
+    int   status;        /* as the name implies */
+    Bytef *pending_buf;  /* output still pending */
+    ulg   pending_buf_size; /* size of pending_buf */
+    Bytef *pending_out;  /* next pending byte to output to the stream */
+    uInt   pending;      /* nb of bytes in the pending buffer */
+    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */
+    gz_headerp  gzhead;  /* gzip header information to write */
+    uInt   gzindex;      /* where in extra, name, or comment */
+    Byte  method;        /* STORED (for zip only) or DEFLATED */
+    int   last_flush;    /* value of flush param for previous deflate call */
+
+                /* used by deflate.c: */
+
+    uInt  w_size;        /* LZ77 window size (32K by default) */
+    uInt  w_bits;        /* log2(w_size)  (8..16) */
+    uInt  w_mask;        /* w_size - 1 */
+
+    Bytef *window;
+    /* Sliding window. Input bytes are read into the second half of the window,
+     * and move to the first half later to keep a dictionary of at least wSize
+     * bytes. With this organization, matches are limited to a distance of
+     * wSize-MAX_MATCH bytes, but this ensures that IO is always
+     * performed with a length multiple of the block size. Also, it limits
+     * the window size to 64K, which is quite useful on MSDOS.
+     * To do: use the user input buffer as sliding window.
+     */
+
+    ulg window_size;
+    /* Actual size of window: 2*wSize, except when the user input buffer
+     * is directly used as sliding window.
+     */
+
+    Posf *prev;
+    /* Link to older string with same hash index. To limit the size of this
+     * array to 64K, this link is maintained only for the last 32K strings.
+     * An index in this array is thus a window index modulo 32K.
+     */
+
+    Posf *head; /* Heads of the hash chains or NIL. */
+
+    uInt  ins_h;          /* hash index of string to be inserted */
+    uInt  hash_size;      /* number of elements in hash table */
+    uInt  hash_bits;      /* log2(hash_size) */
+    uInt  hash_mask;      /* hash_size-1 */
+
+    uInt  hash_shift;
+    /* Number of bits by which ins_h must be shifted at each input
+     * step. It must be such that after MIN_MATCH steps, the oldest
+     * byte no longer takes part in the hash key, that is:
+     *   hash_shift * MIN_MATCH >= hash_bits
+     */
+
+    long block_start;
+    /* Window position at the beginning of the current output block. Gets
+     * negative when the window is moved backwards.
+     */
+
+    uInt match_length;           /* length of best match */
+    IPos prev_match;             /* previous match */
+    int match_available;         /* set if previous match exists */
+    uInt strstart;               /* start of string to insert */
+    uInt match_start;            /* start of matching string */
+    uInt lookahead;              /* number of valid bytes ahead in window */
+
+    uInt prev_length;
+    /* Length of the best match at previous step. Matches not greater than this
+     * are discarded. This is used in the lazy match evaluation.
+     */
+
+    uInt max_chain_length;
+    /* To speed up deflation, hash chains are never searched beyond this
+     * length.  A higher limit improves compression ratio but degrades the
+     * speed.
+     */
+
+    uInt max_lazy_match;
+    /* Attempt to find a better match only when the current match is strictly
+     * smaller than this value. This mechanism is used only for compression
+     * levels >= 4.
+     */
+#   define max_insert_length  max_lazy_match
+    /* Insert new strings in the hash table only if the match length is not
+     * greater than this length. This saves time but degrades compression.
+     * max_insert_length is used only for compression levels <= 3.
+     */
+
+    int level;    /* compression level (1..9) */
+    int strategy; /* favor or force Huffman coding*/
+
+    uInt good_match;
+    /* Use a faster search when the previous match is longer than this */
+
+    int nice_match; /* Stop searching when current match exceeds this */
+
+                /* used by trees.c: */
+    /* Didn't use ct_data typedef below to suppress compiler warning */
+    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
+    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
+    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
+
+    struct tree_desc_s l_desc;               /* desc. for literal tree */
+    struct tree_desc_s d_desc;               /* desc. for distance tree */
+    struct tree_desc_s bl_desc;              /* desc. for bit length tree */
+
+    ush bl_count[MAX_BITS+1];
+    /* number of codes at each bit length for an optimal tree */
+
+    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
+    int heap_len;               /* number of elements in the heap */
+    int heap_max;               /* element of largest frequency */
+    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
+     * The same heap array is used to build all trees.
+     */
+
+    uch depth[2*L_CODES+1];
+    /* Depth of each subtree used as tie breaker for trees of equal frequency
+     */
+
+    uchf *l_buf;          /* buffer for literals or lengths */
+
+    uInt  lit_bufsize;
+    /* Size of match buffer for literals/lengths.  There are 4 reasons for
+     * limiting lit_bufsize to 64K:
+     *   - frequencies can be kept in 16 bit counters
+     *   - if compression is not successful for the first block, all input
+     *     data is still in the window so we can still emit a stored block even
+     *     when input comes from standard input.  (This can also be done for
+     *     all blocks if lit_bufsize is not greater than 32K.)
+     *   - if compression is not successful for a file smaller than 64K, we can
+     *     even emit a stored file instead of a stored block (saving 5 bytes).
+     *     This is applicable only for zip (not gzip or zlib).
+     *   - creating new Huffman trees less frequently may not provide fast
+     *     adaptation to changes in the input data statistics. (Take for
+     *     example a binary file with poorly compressible code followed by
+     *     a highly compressible string table.) Smaller buffer sizes give
+     *     fast adaptation but have of course the overhead of transmitting
+     *     trees more frequently.
+     *   - I can't count above 4
+     */
+
+    uInt last_lit;      /* running index in l_buf */
+
+    ushf *d_buf;
+    /* Buffer for distances. To simplify the code, d_buf and l_buf have
+     * the same number of elements. To use different lengths, an extra flag
+     * array would be necessary.
+     */
+
+    ulg opt_len;        /* bit length of current block with optimal trees */
+    ulg static_len;     /* bit length of current block with static trees */
+    uInt matches;       /* number of string matches in current block */
+    uInt insert;        /* bytes at end of window left to insert */
+
+#ifdef DEBUG
+    ulg compressed_len; /* total bit length of compressed file mod 2^32 */
+    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */
+#endif
+
+    ush bi_buf;
+    /* Output buffer. bits are inserted starting at the bottom (least
+     * significant bits).
+     */
+    int bi_valid;
+    /* Number of valid bits in bi_buf.  All bits above the last valid bit
+     * are always zero.
+     */
+
+    ulg high_water;
+    /* High water mark offset in window for initialized bytes -- bytes above
+     * this are set to zero in order to avoid memory check warnings when
+     * longest match routines access bytes past the input.  This is then
+     * updated to the new high water mark.
+     */
+
+} FAR deflate_state;
+
+/* Output a byte on the stream.
+ * IN assertion: there is enough room in pending_buf.
+ */
+#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
+
+
+#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
+/* Minimum amount of lookahead, except at the end of the input file.
+ * See deflate.c for comments about the MIN_MATCH+1.
+ */
+
+#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
+/* In order to simplify the code, particularly on 16 bit machines, match
+ * distances are limited to MAX_DIST instead of WSIZE.
+ */
+
+#define WIN_INIT MAX_MATCH
+/* Number of bytes after end of data in window to initialize in order to avoid
+   memory checker errors from longest match routines */
+
+        /* in trees.c */
+void ZLIB_INTERNAL _tr_init OF((deflate_state *s));
+int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
+void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
+                        ulg stored_len, int last));
+void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));
+void ZLIB_INTERNAL _tr_align OF((deflate_state *s));
+void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
+                        ulg stored_len, int last));
+
+#define d_code(dist) \
+   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
+/* Mapping from a distance to a distance code. dist is the distance - 1 and
+ * must not have side effects. _dist_code[256] and _dist_code[257] are never
+ * used.
+ */
+
+#ifndef DEBUG
+/* Inline versions of _tr_tally for speed: */
+
+#if defined(GEN_TREES_H) || !defined(STDC)
+  extern uch ZLIB_INTERNAL _length_code[];
+  extern uch ZLIB_INTERNAL _dist_code[];
+#else
+  extern const uch ZLIB_INTERNAL _length_code[];
+  extern const uch ZLIB_INTERNAL _dist_code[];
+#endif
+
+# define _tr_tally_lit(s, c, flush) \
+  { uch cc = (c); \
+    s->d_buf[s->last_lit] = 0; \
+    s->l_buf[s->last_lit++] = cc; \
+    s->dyn_ltree[cc].Freq++; \
+    flush = (s->last_lit == s->lit_bufsize-1); \
+   }
+# define _tr_tally_dist(s, distance, length, flush) \
+  { uch len = (length); \
+    ush dist = (distance); \
+    s->d_buf[s->last_lit] = dist; \
+    s->l_buf[s->last_lit++] = len; \
+    dist--; \
+    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
+    s->dyn_dtree[d_code(dist)].Freq++; \
+    flush = (s->last_lit == s->lit_bufsize-1); \
+  }
+#else
+# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
+# define _tr_tally_dist(s, distance, length, flush) \
+              flush = _tr_tally(s, distance, length)
+#endif
+
+#endif /* DEFLATE_H */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/algorithm.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/algorithm.txt
new file mode 100644 (file)
index 0000000..c97f495
--- /dev/null
@@ -0,0 +1,209 @@
+1. Compression algorithm (deflate)
+
+The deflation algorithm used by gzip (also zip and zlib) is a variation of
+LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in
+the input data.  The second occurrence of a string is replaced by a
+pointer to the previous string, in the form of a pair (distance,
+length).  Distances are limited to 32K bytes, and lengths are limited
+to 258 bytes. When a string does not occur anywhere in the previous
+32K bytes, it is emitted as a sequence of literal bytes.  (In this
+description, `string' must be taken as an arbitrary sequence of bytes,
+and is not restricted to printable characters.)
+
+Literals or match lengths are compressed with one Huffman tree, and
+match distances are compressed with another tree. The trees are stored
+in a compact form at the start of each block. The blocks can have any
+size (except that the compressed data for one block must fit in
+available memory). A block is terminated when deflate() determines that
+it would be useful to start another block with fresh trees. (This is
+somewhat similar to the behavior of LZW-based _compress_.)
+
+Duplicated strings are found using a hash table. All input strings of
+length 3 are inserted in the hash table. A hash index is computed for
+the next 3 bytes. If the hash chain for this index is not empty, all
+strings in the chain are compared with the current input string, and
+the longest match is selected.
+
+The hash chains are searched starting with the most recent strings, to
+favor small distances and thus take advantage of the Huffman encoding.
+The hash chains are singly linked. There are no deletions from the
+hash chains, the algorithm simply discards matches that are too old.
+
+To avoid a worst-case situation, very long hash chains are arbitrarily
+truncated at a certain length, determined by a runtime option (level
+parameter of deflateInit). So deflate() does not always find the longest
+possible match but generally finds a match which is long enough.
+
+deflate() also defers the selection of matches with a lazy evaluation
+mechanism. After a match of length N has been found, deflate() searches for
+a longer match at the next input byte. If a longer match is found, the
+previous match is truncated to a length of one (thus producing a single
+literal byte) and the process of lazy evaluation begins again. Otherwise,
+the original match is kept, and the next match search is attempted only N
+steps later.
+
+The lazy match evaluation is also subject to a runtime parameter. If
+the current match is long enough, deflate() reduces the search for a longer
+match, thus speeding up the whole process. If compression ratio is more
+important than speed, deflate() attempts a complete second search even if
+the first match is already long enough.
+
+The lazy match evaluation is not performed for the fastest compression
+modes (level parameter 1 to 3). For these fast modes, new strings
+are inserted in the hash table only when no match was found, or
+when the match is not too long. This degrades the compression ratio
+but saves time since there are both fewer insertions and fewer searches.
+
+
+2. Decompression algorithm (inflate)
+
+2.1 Introduction
+
+The key question is how to represent a Huffman code (or any prefix code) so
+that you can decode fast.  The most important characteristic is that shorter
+codes are much more common than longer codes, so pay attention to decoding the
+short codes fast, and let the long codes take longer to decode.
+
+inflate() sets up a first level table that covers some number of bits of
+input less than the length of longest code.  It gets that many bits from the
+stream, and looks it up in the table.  The table will tell if the next
+code is that many bits or less and how many, and if it is, it will tell
+the value, else it will point to the next level table for which inflate()
+grabs more bits and tries to decode a longer code.
+
+How many bits to make the first lookup is a tradeoff between the time it
+takes to decode and the time it takes to build the table.  If building the
+table took no time (and if you had infinite memory), then there would only
+be a first level table to cover all the way to the longest code.  However,
+building the table ends up taking a lot longer for more bits since short
+codes are replicated many times in such a table.  What inflate() does is
+simply to make the number of bits in the first table a variable, and  then
+to set that variable for the maximum speed.
+
+For inflate, which has 286 possible codes for the literal/length tree, the size
+of the first table is nine bits.  Also the distance trees have 30 possible
+values, and the size of the first table is six bits.  Note that for each of
+those cases, the table ended up one bit longer than the ``average'' code
+length, i.e. the code length of an approximately flat code which would be a
+little more than eight bits for 286 symbols and a little less than five bits
+for 30 symbols.
+
+
+2.2 More details on the inflate table lookup
+
+Ok, you want to know what this cleverly obfuscated inflate tree actually
+looks like.  You are correct that it's not a Huffman tree.  It is simply a
+lookup table for the first, let's say, nine bits of a Huffman symbol.  The
+symbol could be as short as one bit or as long as 15 bits.  If a particular
+symbol is shorter than nine bits, then that symbol's translation is duplicated
+in all those entries that start with that symbol's bits.  For example, if the
+symbol is four bits, then it's duplicated 32 times in a nine-bit table.  If a
+symbol is nine bits long, it appears in the table once.
+
+If the symbol is longer than nine bits, then that entry in the table points
+to another similar table for the remaining bits.  Again, there are duplicated
+entries as needed.  The idea is that most of the time the symbol will be short
+and there will only be one table look up.  (That's whole idea behind data
+compression in the first place.)  For the less frequent long symbols, there
+will be two lookups.  If you had a compression method with really long
+symbols, you could have as many levels of lookups as is efficient.  For
+inflate, two is enough.
+
+So a table entry either points to another table (in which case nine bits in
+the above example are gobbled), or it contains the translation for the symbol
+and the number of bits to gobble.  Then you start again with the next
+ungobbled bit.
+
+You may wonder: why not just have one lookup table for how ever many bits the
+longest symbol is?  The reason is that if you do that, you end up spending
+more time filling in duplicate symbol entries than you do actually decoding.
+At least for deflate's output that generates new trees every several 10's of
+kbytes.  You can imagine that filling in a 2^15 entry table for a 15-bit code
+would take too long if you're only decoding several thousand symbols.  At the
+other extreme, you could make a new table for every bit in the code.  In fact,
+that's essentially a Huffman tree.  But then you spend too much time
+traversing the tree while decoding, even for short symbols.
+
+So the number of bits for the first lookup table is a trade of the time to
+fill out the table vs. the time spent looking at the second level and above of
+the table.
+
+Here is an example, scaled down:
+
+The code being decoded, with 10 symbols, from 1 to 6 bits long:
+
+A: 0
+B: 10
+C: 1100
+D: 11010
+E: 11011
+F: 11100
+G: 11101
+H: 11110
+I: 111110
+J: 111111
+
+Let's make the first table three bits long (eight entries):
+
+000: A,1
+001: A,1
+010: A,1
+011: A,1
+100: B,2
+101: B,2
+110: -> table X (gobble 3 bits)
+111: -> table Y (gobble 3 bits)
+
+Each entry is what the bits decode as and how many bits that is, i.e. how
+many bits to gobble.  Or the entry points to another table, with the number of
+bits to gobble implicit in the size of the table.
+
+Table X is two bits long since the longest code starting with 110 is five bits
+long:
+
+00: C,1
+01: C,1
+10: D,2
+11: E,2
+
+Table Y is three bits long since the longest code starting with 111 is six
+bits long:
+
+000: F,2
+001: F,2
+010: G,2
+011: G,2
+100: H,2
+101: H,2
+110: I,3
+111: J,3
+
+So what we have here are three tables with a total of 20 entries that had to
+be constructed.  That's compared to 64 entries for a single table.  Or
+compared to 16 entries for a Huffman tree (six two entry tables and one four
+entry table).  Assuming that the code ideally represents the probability of
+the symbols, it takes on the average 1.25 lookups per symbol.  That's compared
+to one lookup for the single table, or 1.66 lookups per symbol for the
+Huffman tree.
+
+There, I think that gives you a picture of what's going on.  For inflate, the
+meaning of a particular symbol is often more than just a letter.  It can be a
+byte (a "literal"), or it can be either a length or a distance which
+indicates a base value and a number of bits to fetch after the code that is
+added to the base value.  Or it might be the special end-of-block code.  The
+data structures created in inftrees.c try to encode all that information
+compactly in the tables.
+
+
+Jean-loup Gailly        Mark Adler
+jloup@gzip.org          madler@alumni.caltech.edu
+
+
+References:
+
+[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data
+Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3,
+pp. 337-343.
+
+``DEFLATE Compressed Data Format Specification'' available in
+http://tools.ietf.org/html/rfc1951
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1950.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1950.txt
new file mode 100644 (file)
index 0000000..ce6428a
--- /dev/null
@@ -0,0 +1,619 @@
+
+
+
+
+
+
+Network Working Group                                         P. Deutsch
+Request for Comments: 1950                           Aladdin Enterprises
+Category: Informational                                      J-L. Gailly
+                                                                Info-ZIP
+                                                                May 1996
+
+
+         ZLIB Compressed Data Format Specification version 3.3
+
+Status of This Memo
+
+   This memo provides information for the Internet community.  This memo
+   does not specify an Internet standard of any kind.  Distribution of
+   this memo is unlimited.
+
+IESG Note:
+
+   The IESG takes no position on the validity of any Intellectual
+   Property Rights statements contained in this document.
+
+Notices
+
+   Copyright (c) 1996 L. Peter Deutsch and Jean-Loup Gailly
+
+   Permission is granted to copy and distribute this document for any
+   purpose and without charge, including translations into other
+   languages and incorporation into compilations, provided that the
+   copyright notice and this notice are preserved, and that any
+   substantive changes or deletions from the original are clearly
+   marked.
+
+   A pointer to the latest version of this and related documentation in
+   HTML format can be found at the URL
+   <ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html>.
+
+Abstract
+
+   This specification defines a lossless compressed data format.  The
+   data can be produced or consumed, even for an arbitrarily long
+   sequentially presented input data stream, using only an a priori
+   bounded amount of intermediate storage.  The format presently uses
+   the DEFLATE compression method but can be easily extended to use
+   other compression methods.  It can be implemented readily in a manner
+   not covered by patents.  This specification also defines the ADLER-32
+   checksum (an extension and improvement of the Fletcher checksum),
+   used for detection of data corruption, and provides an algorithm for
+   computing it.
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 1]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+Table of Contents
+
+   1. Introduction ................................................... 2
+      1.1. Purpose ................................................... 2
+      1.2. Intended audience ......................................... 3
+      1.3. Scope ..................................................... 3
+      1.4. Compliance ................................................ 3
+      1.5.  Definitions of terms and conventions used ................ 3
+      1.6. Changes from previous versions ............................ 3
+   2. Detailed specification ......................................... 3
+      2.1. Overall conventions ....................................... 3
+      2.2. Data format ............................................... 4
+      2.3. Compliance ................................................ 7
+   3. References ..................................................... 7
+   4. Source code .................................................... 8
+   5. Security Considerations ........................................ 8
+   6. Acknowledgements ............................................... 8
+   7. Authors' Addresses ............................................. 8
+   8. Appendix: Rationale ............................................ 9
+   9. Appendix: Sample code ..........................................10
+
+1. Introduction
+
+   1.1. Purpose
+
+      The purpose of this specification is to define a lossless
+      compressed data format that:
+
+          * Is independent of CPU type, operating system, file system,
+            and character set, and hence can be used for interchange;
+
+          * Can be produced or consumed, even for an arbitrarily long
+            sequentially presented input data stream, using only an a
+            priori bounded amount of intermediate storage, and hence can
+            be used in data communications or similar structures such as
+            Unix filters;
+
+          * Can use a number of different compression methods;
+
+          * Can be implemented readily in a manner not covered by
+            patents, and hence can be practiced freely.
+
+      The data format defined by this specification does not attempt to
+      allow random access to compressed data.
+
+
+
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 2]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+   1.2. Intended audience
+
+      This specification is intended for use by implementors of software
+      to compress data into zlib format and/or decompress data from zlib
+      format.
+
+      The text of the specification assumes a basic background in
+      programming at the level of bits and other primitive data
+      representations.
+
+   1.3. Scope
+
+      The specification specifies a compressed data format that can be
+      used for in-memory compression of a sequence of arbitrary bytes.
+
+   1.4. Compliance
+
+      Unless otherwise indicated below, a compliant decompressor must be
+      able to accept and decompress any data set that conforms to all
+      the specifications presented here; a compliant compressor must
+      produce data sets that conform to all the specifications presented
+      here.
+
+   1.5.  Definitions of terms and conventions used
+
+      byte: 8 bits stored or transmitted as a unit (same as an octet).
+      (For this specification, a byte is exactly 8 bits, even on
+      machines which store a character on a number of bits different
+      from 8.) See below, for the numbering of bits within a byte.
+
+   1.6. Changes from previous versions
+
+      Version 3.1 was the first public release of this specification.
+      In version 3.2, some terminology was changed and the Adler-32
+      sample code was rewritten for clarity.  In version 3.3, the
+      support for a preset dictionary was introduced, and the
+      specification was converted to RFC style.
+
+2. Detailed specification
+
+   2.1. Overall conventions
+
+      In the diagrams below, a box like this:
+
+         +---+
+         |   | <-- the vertical bars might be missing
+         +---+
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 3]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+      represents one byte; a box like this:
+
+         +==============+
+         |              |
+         +==============+
+
+      represents a variable number of bytes.
+
+      Bytes stored within a computer do not have a "bit order", since
+      they are always treated as a unit.  However, a byte considered as
+      an integer between 0 and 255 does have a most- and least-
+      significant bit, and since we write numbers with the most-
+      significant digit on the left, we also write bytes with the most-
+      significant bit on the left.  In the diagrams below, we number the
+      bits of a byte so that bit 0 is the least-significant bit, i.e.,
+      the bits are numbered:
+
+         +--------+
+         |76543210|
+         +--------+
+
+      Within a computer, a number may occupy multiple bytes.  All
+      multi-byte numbers in the format described here are stored with
+      the MOST-significant byte first (at the lower memory address).
+      For example, the decimal number 520 is stored as:
+
+             0     1
+         +--------+--------+
+         |00000010|00001000|
+         +--------+--------+
+          ^        ^
+          |        |
+          |        + less significant byte = 8
+          + more significant byte = 2 x 256
+
+   2.2. Data format
+
+      A zlib stream has the following structure:
+
+           0   1
+         +---+---+
+         |CMF|FLG|   (more-->)
+         +---+---+
+
+
+
+
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 4]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+      (if FLG.FDICT set)
+
+           0   1   2   3
+         +---+---+---+---+
+         |     DICTID    |   (more-->)
+         +---+---+---+---+
+
+         +=====================+---+---+---+---+
+         |...compressed data...|    ADLER32    |
+         +=====================+---+---+---+---+
+
+      Any data which may appear after ADLER32 are not part of the zlib
+      stream.
+
+      CMF (Compression Method and flags)
+         This byte is divided into a 4-bit compression method and a 4-
+         bit information field depending on the compression method.
+
+            bits 0 to 3  CM     Compression method
+            bits 4 to 7  CINFO  Compression info
+
+      CM (Compression method)
+         This identifies the compression method used in the file. CM = 8
+         denotes the "deflate" compression method with a window size up
+         to 32K.  This is the method used by gzip and PNG (see
+         references [1] and [2] in Chapter 3, below, for the reference
+         documents).  CM = 15 is reserved.  It might be used in a future
+         version of this specification to indicate the presence of an
+         extra field before the compressed data.
+
+      CINFO (Compression info)
+         For CM = 8, CINFO is the base-2 logarithm of the LZ77 window
+         size, minus eight (CINFO=7 indicates a 32K window size). Values
+         of CINFO above 7 are not allowed in this version of the
+         specification.  CINFO is not defined in this specification for
+         CM not equal to 8.
+
+      FLG (FLaGs)
+         This flag byte is divided as follows:
+
+            bits 0 to 4  FCHECK  (check bits for CMF and FLG)
+            bit  5       FDICT   (preset dictionary)
+            bits 6 to 7  FLEVEL  (compression level)
+
+         The FCHECK value must be such that CMF and FLG, when viewed as
+         a 16-bit unsigned integer stored in MSB order (CMF*256 + FLG),
+         is a multiple of 31.
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 5]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+      FDICT (Preset dictionary)
+         If FDICT is set, a DICT dictionary identifier is present
+         immediately after the FLG byte. The dictionary is a sequence of
+         bytes which are initially fed to the compressor without
+         producing any compressed output. DICT is the Adler-32 checksum
+         of this sequence of bytes (see the definition of ADLER32
+         below).  The decompressor can use this identifier to determine
+         which dictionary has been used by the compressor.
+
+      FLEVEL (Compression level)
+         These flags are available for use by specific compression
+         methods.  The "deflate" method (CM = 8) sets these flags as
+         follows:
+
+            0 - compressor used fastest algorithm
+            1 - compressor used fast algorithm
+            2 - compressor used default algorithm
+            3 - compressor used maximum compression, slowest algorithm
+
+         The information in FLEVEL is not needed for decompression; it
+         is there to indicate if recompression might be worthwhile.
+
+      compressed data
+         For compression method 8, the compressed data is stored in the
+         deflate compressed data format as described in the document
+         "DEFLATE Compressed Data Format Specification" by L. Peter
+         Deutsch. (See reference [3] in Chapter 3, below)
+
+         Other compressed data formats are not specified in this version
+         of the zlib specification.
+
+      ADLER32 (Adler-32 checksum)
+         This contains a checksum value of the uncompressed data
+         (excluding any dictionary data) computed according to Adler-32
+         algorithm. This algorithm is a 32-bit extension and improvement
+         of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073
+         standard. See references [4] and [5] in Chapter 3, below)
+
+         Adler-32 is composed of two sums accumulated per byte: s1 is
+         the sum of all bytes, s2 is the sum of all s1 values. Both sums
+         are done modulo 65521. s1 is initialized to 1, s2 to zero.  The
+         Adler-32 checksum is stored as s2*65536 + s1 in most-
+         significant-byte first (network) order.
+
+
+
+
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 6]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+   2.3. Compliance
+
+      A compliant compressor must produce streams with correct CMF, FLG
+      and ADLER32, but need not support preset dictionaries.  When the
+      zlib data format is used as part of another standard data format,
+      the compressor may use only preset dictionaries that are specified
+      by this other data format.  If this other format does not use the
+      preset dictionary feature, the compressor must not set the FDICT
+      flag.
+
+      A compliant decompressor must check CMF, FLG, and ADLER32, and
+      provide an error indication if any of these have incorrect values.
+      A compliant decompressor must give an error indication if CM is
+      not one of the values defined in this specification (only the
+      value 8 is permitted in this version), since another value could
+      indicate the presence of new features that would cause subsequent
+      data to be interpreted incorrectly.  A compliant decompressor must
+      give an error indication if FDICT is set and DICTID is not the
+      identifier of a known preset dictionary.  A decompressor may
+      ignore FLEVEL and still be compliant.  When the zlib data format
+      is being used as a part of another standard format, a compliant
+      decompressor must support all the preset dictionaries specified by
+      the other format. When the other format does not use the preset
+      dictionary feature, a compliant decompressor must reject any
+      stream in which the FDICT flag is set.
+
+3. References
+
+   [1] Deutsch, L.P.,"GZIP Compressed Data Format Specification",
+       available in ftp://ftp.uu.net/pub/archiving/zip/doc/
+
+   [2] Thomas Boutell, "PNG (Portable Network Graphics) specification",
+       available in ftp://ftp.uu.net/graphics/png/documents/
+
+   [3] Deutsch, L.P.,"DEFLATE Compressed Data Format Specification",
+       available in ftp://ftp.uu.net/pub/archiving/zip/doc/
+
+   [4] Fletcher, J. G., "An Arithmetic Checksum for Serial
+       Transmissions," IEEE Transactions on Communications, Vol. COM-30,
+       No. 1, January 1982, pp. 247-252.
+
+   [5] ITU-T Recommendation X.224, Annex D, "Checksum Algorithms,"
+       November, 1993, pp. 144, 145. (Available from
+       gopher://info.itu.ch). ITU-T X.244 is also the same as ISO 8073.
+
+
+
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 7]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+4. Source code
+
+   Source code for a C language implementation of a "zlib" compliant
+   library is available at ftp://ftp.uu.net/pub/archiving/zip/zlib/.
+
+5. Security Considerations
+
+   A decoder that fails to check the ADLER32 checksum value may be
+   subject to undetected data corruption.
+
+6. Acknowledgements
+
+   Trademarks cited in this document are the property of their
+   respective owners.
+
+   Jean-Loup Gailly and Mark Adler designed the zlib format and wrote
+   the related software described in this specification.  Glenn
+   Randers-Pehrson converted this document to RFC and HTML format.
+
+7. Authors' Addresses
+
+   L. Peter Deutsch
+   Aladdin Enterprises
+   203 Santa Margarita Ave.
+   Menlo Park, CA 94025
+
+   Phone: (415) 322-0103 (AM only)
+   FAX:   (415) 322-1734
+   EMail: <ghost@aladdin.com>
+
+
+   Jean-Loup Gailly
+
+   EMail: <gzip@prep.ai.mit.edu>
+
+   Questions about the technical content of this specification can be
+   sent by email to
+
+   Jean-Loup Gailly <gzip@prep.ai.mit.edu> and
+   Mark Adler <madler@alumni.caltech.edu>
+
+   Editorial comments on this specification can be sent by email to
+
+   L. Peter Deutsch <ghost@aladdin.com> and
+   Glenn Randers-Pehrson <randeg@alumni.rpi.edu>
+
+
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 8]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+8. Appendix: Rationale
+
+   8.1. Preset dictionaries
+
+      A preset dictionary is specially useful to compress short input
+      sequences. The compressor can take advantage of the dictionary
+      context to encode the input in a more compact manner. The
+      decompressor can be initialized with the appropriate context by
+      virtually decompressing a compressed version of the dictionary
+      without producing any output. However for certain compression
+      algorithms such as the deflate algorithm this operation can be
+      achieved without actually performing any decompression.
+
+      The compressor and the decompressor must use exactly the same
+      dictionary. The dictionary may be fixed or may be chosen among a
+      certain number of predefined dictionaries, according to the kind
+      of input data. The decompressor can determine which dictionary has
+      been chosen by the compressor by checking the dictionary
+      identifier. This document does not specify the contents of
+      predefined dictionaries, since the optimal dictionaries are
+      application specific. Standard data formats using this feature of
+      the zlib specification must precisely define the allowed
+      dictionaries.
+
+   8.2. The Adler-32 algorithm
+
+      The Adler-32 algorithm is much faster than the CRC32 algorithm yet
+      still provides an extremely low probability of undetected errors.
+
+      The modulo on unsigned long accumulators can be delayed for 5552
+      bytes, so the modulo operation time is negligible.  If the bytes
+      are a, b, c, the second sum is 3a + 2b + c + 3, and so is position
+      and order sensitive, unlike the first sum, which is just a
+      checksum.  That 65521 is prime is important to avoid a possible
+      large class of two-byte errors that leave the check unchanged.
+      (The Fletcher checksum uses 255, which is not prime and which also
+      makes the Fletcher check insensitive to single byte changes 0 <->
+      255.)
+
+      The sum s1 is initialized to 1 instead of zero to make the length
+      of the sequence part of s2, so that the length does not have to be
+      checked separately. (Any sequence of zeroes has a Fletcher
+      checksum of zero.)
+
+
+
+
+
+
+
+
+Deutsch & Gailly             Informational                      [Page 9]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+9. Appendix: Sample code
+
+   The following C code computes the Adler-32 checksum of a data buffer.
+   It is written for clarity, not for speed.  The sample code is in the
+   ANSI C programming language. Non C users may find it easier to read
+   with these hints:
+
+      &      Bitwise AND operator.
+      >>     Bitwise right shift operator. When applied to an
+             unsigned quantity, as here, right shift inserts zero bit(s)
+             at the left.
+      <<     Bitwise left shift operator. Left shift inserts zero
+             bit(s) at the right.
+      ++     "n++" increments the variable n.
+      %      modulo operator: a % b is the remainder of a divided by b.
+
+      #define BASE 65521 /* largest prime smaller than 65536 */
+
+      /*
+         Update a running Adler-32 checksum with the bytes buf[0..len-1]
+       and return the updated checksum. The Adler-32 checksum should be
+       initialized to 1.
+
+       Usage example:
+
+         unsigned long adler = 1L;
+
+         while (read_buffer(buffer, length) != EOF) {
+           adler = update_adler32(adler, buffer, length);
+         }
+         if (adler != original_adler) error();
+      */
+      unsigned long update_adler32(unsigned long adler,
+         unsigned char *buf, int len)
+      {
+        unsigned long s1 = adler & 0xffff;
+        unsigned long s2 = (adler >> 16) & 0xffff;
+        int n;
+
+        for (n = 0; n < len; n++) {
+          s1 = (s1 + buf[n]) % BASE;
+          s2 = (s2 + s1)     % BASE;
+        }
+        return (s2 << 16) + s1;
+      }
+
+      /* Return the adler32 of the bytes buf[0..len-1] */
+
+
+
+
+Deutsch & Gailly             Informational                     [Page 10]
+\f
+RFC 1950       ZLIB Compressed Data Format Specification        May 1996
+
+
+      unsigned long adler32(unsigned char *buf, int len)
+      {
+        return update_adler32(1L, buf, len);
+      }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Deutsch & Gailly             Informational                     [Page 11]
+\f
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1951.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1951.txt
new file mode 100644 (file)
index 0000000..403c8c7
--- /dev/null
@@ -0,0 +1,955 @@
+
+
+
+
+
+
+Network Working Group                                         P. Deutsch
+Request for Comments: 1951                           Aladdin Enterprises
+Category: Informational                                         May 1996
+
+
+        DEFLATE Compressed Data Format Specification version 1.3
+
+Status of This Memo
+
+   This memo provides information for the Internet community.  This memo
+   does not specify an Internet standard of any kind.  Distribution of
+   this memo is unlimited.
+
+IESG Note:
+
+   The IESG takes no position on the validity of any Intellectual
+   Property Rights statements contained in this document.
+
+Notices
+
+   Copyright (c) 1996 L. Peter Deutsch
+
+   Permission is granted to copy and distribute this document for any
+   purpose and without charge, including translations into other
+   languages and incorporation into compilations, provided that the
+   copyright notice and this notice are preserved, and that any
+   substantive changes or deletions from the original are clearly
+   marked.
+
+   A pointer to the latest version of this and related documentation in
+   HTML format can be found at the URL
+   <ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html>.
+
+Abstract
+
+   This specification defines a lossless compressed data format that
+   compresses data using a combination of the LZ77 algorithm and Huffman
+   coding, with efficiency comparable to the best currently available
+   general-purpose compression methods.  The data can be produced or
+   consumed, even for an arbitrarily long sequentially presented input
+   data stream, using only an a priori bounded amount of intermediate
+   storage.  The format can be implemented readily in a manner not
+   covered by patents.
+
+
+
+
+
+
+
+
+Deutsch                      Informational                      [Page 1]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+Table of Contents
+
+   1. Introduction ................................................... 2
+      1.1. Purpose ................................................... 2
+      1.2. Intended audience ......................................... 3
+      1.3. Scope ..................................................... 3
+      1.4. Compliance ................................................ 3
+      1.5.  Definitions of terms and conventions used ................ 3
+      1.6. Changes from previous versions ............................ 4
+   2. Compressed representation overview ............................. 4
+   3. Detailed specification ......................................... 5
+      3.1. Overall conventions ....................................... 5
+          3.1.1. Packing into bytes .................................. 5
+      3.2. Compressed block format ................................... 6
+          3.2.1. Synopsis of prefix and Huffman coding ............... 6
+          3.2.2. Use of Huffman coding in the "deflate" format ....... 7
+          3.2.3. Details of block format ............................. 9
+          3.2.4. Non-compressed blocks (BTYPE=00) ................... 11
+          3.2.5. Compressed blocks (length and distance codes) ...... 11
+          3.2.6. Compression with fixed Huffman codes (BTYPE=01) .... 12
+          3.2.7. Compression with dynamic Huffman codes (BTYPE=10) .. 13
+      3.3. Compliance ............................................... 14
+   4. Compression algorithm details ................................. 14
+   5. References .................................................... 16
+   6. Security Considerations ....................................... 16
+   7. Source code ................................................... 16
+   8. Acknowledgements .............................................. 16
+   9. Author's Address .............................................. 17
+
+1. Introduction
+
+   1.1. Purpose
+
+      The purpose of this specification is to define a lossless
+      compressed data format that:
+          * Is independent of CPU type, operating system, file system,
+            and character set, and hence can be used for interchange;
+          * Can be produced or consumed, even for an arbitrarily long
+            sequentially presented input data stream, using only an a
+            priori bounded amount of intermediate storage, and hence
+            can be used in data communications or similar structures
+            such as Unix filters;
+          * Compresses data with efficiency comparable to the best
+            currently available general-purpose compression methods,
+            and in particular considerably better than the "compress"
+            program;
+          * Can be implemented readily in a manner not covered by
+            patents, and hence can be practiced freely;
+
+
+
+Deutsch                      Informational                      [Page 2]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+          * Is compatible with the file format produced by the current
+            widely used gzip utility, in that conforming decompressors
+            will be able to read data produced by the existing gzip
+            compressor.
+
+      The data format defined by this specification does not attempt to:
+
+          * Allow random access to compressed data;
+          * Compress specialized data (e.g., raster graphics) as well
+            as the best currently available specialized algorithms.
+
+      A simple counting argument shows that no lossless compression
+      algorithm can compress every possible input data set.  For the
+      format defined here, the worst case expansion is 5 bytes per 32K-
+      byte block, i.e., a size increase of 0.015% for large data sets.
+      English text usually compresses by a factor of 2.5 to 3;
+      executable files usually compress somewhat less; graphical data
+      such as raster images may compress much more.
+
+   1.2. Intended audience
+
+      This specification is intended for use by implementors of software
+      to compress data into "deflate" format and/or decompress data from
+      "deflate" format.
+
+      The text of the specification assumes a basic background in
+      programming at the level of bits and other primitive data
+      representations.  Familiarity with the technique of Huffman coding
+      is helpful but not required.
+
+   1.3. Scope
+
+      The specification specifies a method for representing a sequence
+      of bytes as a (usually shorter) sequence of bits, and a method for
+      packing the latter bit sequence into bytes.
+
+   1.4. Compliance
+
+      Unless otherwise indicated below, a compliant decompressor must be
+      able to accept and decompress any data set that conforms to all
+      the specifications presented here; a compliant compressor must
+      produce data sets that conform to all the specifications presented
+      here.
+
+   1.5.  Definitions of terms and conventions used
+
+      Byte: 8 bits stored or transmitted as a unit (same as an octet).
+      For this specification, a byte is exactly 8 bits, even on machines
+
+
+
+Deutsch                      Informational                      [Page 3]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+      which store a character on a number of bits different from eight.
+      See below, for the numbering of bits within a byte.
+
+      String: a sequence of arbitrary bytes.
+
+   1.6. Changes from previous versions
+
+      There have been no technical changes to the deflate format since
+      version 1.1 of this specification.  In version 1.2, some
+      terminology was changed.  Version 1.3 is a conversion of the
+      specification to RFC style.
+
+2. Compressed representation overview
+
+   A compressed data set consists of a series of blocks, corresponding
+   to successive blocks of input data.  The block sizes are arbitrary,
+   except that non-compressible blocks are limited to 65,535 bytes.
+
+   Each block is compressed using a combination of the LZ77 algorithm
+   and Huffman coding. The Huffman trees for each block are independent
+   of those for previous or subsequent blocks; the LZ77 algorithm may
+   use a reference to a duplicated string occurring in a previous block,
+   up to 32K input bytes before.
+
+   Each block consists of two parts: a pair of Huffman code trees that
+   describe the representation of the compressed data part, and a
+   compressed data part.  (The Huffman trees themselves are compressed
+   using Huffman encoding.)  The compressed data consists of a series of
+   elements of two types: literal bytes (of strings that have not been
+   detected as duplicated within the previous 32K input bytes), and
+   pointers to duplicated strings, where a pointer is represented as a
+   pair <length, backward distance>.  The representation used in the
+   "deflate" format limits distances to 32K bytes and lengths to 258
+   bytes, but does not limit the size of a block, except for
+   uncompressible blocks, which are limited as noted above.
+
+   Each type of value (literals, distances, and lengths) in the
+   compressed data is represented using a Huffman code, using one code
+   tree for literals and lengths and a separate code tree for distances.
+   The code trees for each block appear in a compact form just before
+   the compressed data for that block.
+
+
+
+
+
+
+
+
+
+
+Deutsch                      Informational                      [Page 4]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+3. Detailed specification
+
+   3.1. Overall conventions In the diagrams below, a box like this:
+
+         +---+
+         |   | <-- the vertical bars might be missing
+         +---+
+
+      represents one byte; a box like this:
+
+         +==============+
+         |              |
+         +==============+
+
+      represents a variable number of bytes.
+
+      Bytes stored within a computer do not have a "bit order", since
+      they are always treated as a unit.  However, a byte considered as
+      an integer between 0 and 255 does have a most- and least-
+      significant bit, and since we write numbers with the most-
+      significant digit on the left, we also write bytes with the most-
+      significant bit on the left.  In the diagrams below, we number the
+      bits of a byte so that bit 0 is the least-significant bit, i.e.,
+      the bits are numbered:
+
+         +--------+
+         |76543210|
+         +--------+
+
+      Within a computer, a number may occupy multiple bytes.  All
+      multi-byte numbers in the format described here are stored with
+      the least-significant byte first (at the lower memory address).
+      For example, the decimal number 520 is stored as:
+
+             0        1
+         +--------+--------+
+         |00001000|00000010|
+         +--------+--------+
+          ^        ^
+          |        |
+          |        + more significant byte = 2 x 256
+          + less significant byte = 8
+
+      3.1.1. Packing into bytes
+
+         This document does not address the issue of the order in which
+         bits of a byte are transmitted on a bit-sequential medium,
+         since the final data format described here is byte- rather than
+
+
+
+Deutsch                      Informational                      [Page 5]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+         bit-oriented.  However, we describe the compressed block format
+         in below, as a sequence of data elements of various bit
+         lengths, not a sequence of bytes.  We must therefore specify
+         how to pack these data elements into bytes to form the final
+         compressed byte sequence:
+
+             * Data elements are packed into bytes in order of
+               increasing bit number within the byte, i.e., starting
+               with the least-significant bit of the byte.
+             * Data elements other than Huffman codes are packed
+               starting with the least-significant bit of the data
+               element.
+             * Huffman codes are packed starting with the most-
+               significant bit of the code.
+
+         In other words, if one were to print out the compressed data as
+         a sequence of bytes, starting with the first byte at the
+         *right* margin and proceeding to the *left*, with the most-
+         significant bit of each byte on the left as usual, one would be
+         able to parse the result from right to left, with fixed-width
+         elements in the correct MSB-to-LSB order and Huffman codes in
+         bit-reversed order (i.e., with the first bit of the code in the
+         relative LSB position).
+
+   3.2. Compressed block format
+
+      3.2.1. Synopsis of prefix and Huffman coding
+
+         Prefix coding represents symbols from an a priori known
+         alphabet by bit sequences (codes), one code for each symbol, in
+         a manner such that different symbols may be represented by bit
+         sequences of different lengths, but a parser can always parse
+         an encoded string unambiguously symbol-by-symbol.
+
+         We define a prefix code in terms of a binary tree in which the
+         two edges descending from each non-leaf node are labeled 0 and
+         1 and in which the leaf nodes correspond one-for-one with (are
+         labeled with) the symbols of the alphabet; then the code for a
+         symbol is the sequence of 0's and 1's on the edges leading from
+         the root to the leaf labeled with that symbol.  For example:
+
+
+
+
+
+
+
+
+
+
+
+Deutsch                      Informational                      [Page 6]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+                          /\              Symbol    Code
+                         0  1             ------    ----
+                        /    \                A      00
+                       /\     B               B       1
+                      0  1                    C     011
+                     /    \                   D     010
+                    A     /\
+                         0  1
+                        /    \
+                       D      C
+
+         A parser can decode the next symbol from an encoded input
+         stream by walking down the tree from the root, at each step
+         choosing the edge corresponding to the next input bit.
+
+         Given an alphabet with known symbol frequencies, the Huffman
+         algorithm allows the construction of an optimal prefix code
+         (one which represents strings with those symbol frequencies
+         using the fewest bits of any possible prefix codes for that
+         alphabet).  Such a code is called a Huffman code.  (See
+         reference [1] in Chapter 5, references for additional
+         information on Huffman codes.)
+
+         Note that in the "deflate" format, the Huffman codes for the
+         various alphabets must not exceed certain maximum code lengths.
+         This constraint complicates the algorithm for computing code
+         lengths from symbol frequencies.  Again, see Chapter 5,
+         references for details.
+
+      3.2.2. Use of Huffman coding in the "deflate" format
+
+         The Huffman codes used for each alphabet in the "deflate"
+         format have two additional rules:
+
+             * All codes of a given bit length have lexicographically
+               consecutive values, in the same order as the symbols
+               they represent;
+
+             * Shorter codes lexicographically precede longer codes.
+
+
+
+
+
+
+
+
+
+
+
+
+Deutsch                      Informational                      [Page 7]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+         We could recode the example above to follow this rule as
+         follows, assuming that the order of the alphabet is ABCD:
+
+            Symbol  Code
+            ------  ----
+            A       10
+            B       0
+            C       110
+            D       111
+
+         I.e., 0 precedes 10 which precedes 11x, and 110 and 111 are
+         lexicographically consecutive.
+
+         Given this rule, we can define the Huffman code for an alphabet
+         just by giving the bit lengths of the codes for each symbol of
+         the alphabet in order; this is sufficient to determine the
+         actual codes.  In our example, the code is completely defined
+         by the sequence of bit lengths (2, 1, 3, 3).  The following
+         algorithm generates the codes as integers, intended to be read
+         from most- to least-significant bit.  The code lengths are
+         initially in tree[I].Len; the codes are produced in
+         tree[I].Code.
+
+         1)  Count the number of codes for each code length.  Let
+             bl_count[N] be the number of codes of length N, N >= 1.
+
+         2)  Find the numerical value of the smallest code for each
+             code length:
+
+                code = 0;
+                bl_count[0] = 0;
+                for (bits = 1; bits <= MAX_BITS; bits++) {
+                    code = (code + bl_count[bits-1]) << 1;
+                    next_code[bits] = code;
+                }
+
+         3)  Assign numerical values to all codes, using consecutive
+             values for all codes of the same length with the base
+             values determined at step 2. Codes that are never used
+             (which have a bit length of zero) must not be assigned a
+             value.
+
+                for (n = 0;  n <= max_code; n++) {
+                    len = tree[n].Len;
+                    if (len != 0) {
+                        tree[n].Code = next_code[len];
+                        next_code[len]++;
+                    }
+
+
+
+Deutsch                      Informational                      [Page 8]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+                }
+
+         Example:
+
+         Consider the alphabet ABCDEFGH, with bit lengths (3, 3, 3, 3,
+         3, 2, 4, 4).  After step 1, we have:
+
+            N      bl_count[N]
+            -      -----------
+            2      1
+            3      5
+            4      2
+
+         Step 2 computes the following next_code values:
+
+            N      next_code[N]
+            -      ------------
+            1      0
+            2      0
+            3      2
+            4      14
+
+         Step 3 produces the following code values:
+
+            Symbol Length   Code
+            ------ ------   ----
+            A       3        010
+            B       3        011
+            C       3        100
+            D       3        101
+            E       3        110
+            F       2         00
+            G       4       1110
+            H       4       1111
+
+      3.2.3. Details of block format
+
+         Each block of compressed data begins with 3 header bits
+         containing the following data:
+
+            first bit       BFINAL
+            next 2 bits     BTYPE
+
+         Note that the header bits do not necessarily begin on a byte
+         boundary, since a block does not necessarily occupy an integral
+         number of bytes.
+
+
+
+
+
+Deutsch                      Informational                      [Page 9]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+         BFINAL is set if and only if this is the last block of the data
+         set.
+
+         BTYPE specifies how the data are compressed, as follows:
+
+            00 - no compression
+            01 - compressed with fixed Huffman codes
+            10 - compressed with dynamic Huffman codes
+            11 - reserved (error)
+
+         The only difference between the two compressed cases is how the
+         Huffman codes for the literal/length and distance alphabets are
+         defined.
+
+         In all cases, the decoding algorithm for the actual data is as
+         follows:
+
+            do
+               read block header from input stream.
+               if stored with no compression
+                  skip any remaining bits in current partially
+                     processed byte
+                  read LEN and NLEN (see next section)
+                  copy LEN bytes of data to output
+               otherwise
+                  if compressed with dynamic Huffman codes
+                     read representation of code trees (see
+                        subsection below)
+                  loop (until end of block code recognized)
+                     decode literal/length value from input stream
+                     if value < 256
+                        copy value (literal byte) to output stream
+                     otherwise
+                        if value = end of block (256)
+                           break from loop
+                        otherwise (value = 257..285)
+                           decode distance from input stream
+
+                           move backwards distance bytes in the output
+                           stream, and copy length bytes from this
+                           position to the output stream.
+                  end loop
+            while not last block
+
+         Note that a duplicated string reference may refer to a string
+         in a previous block; i.e., the backward distance may cross one
+         or more block boundaries.  However a distance cannot refer past
+         the beginning of the output stream.  (An application using a
+
+
+
+Deutsch                      Informational                     [Page 10]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+         preset dictionary might discard part of the output stream; a
+         distance can refer to that part of the output stream anyway)
+         Note also that the referenced string may overlap the current
+         position; for example, if the last 2 bytes decoded have values
+         X and Y, a string reference with <length = 5, distance = 2>
+         adds X,Y,X,Y,X to the output stream.
+
+         We now specify each compression method in turn.
+
+      3.2.4. Non-compressed blocks (BTYPE=00)
+
+         Any bits of input up to the next byte boundary are ignored.
+         The rest of the block consists of the following information:
+
+              0   1   2   3   4...
+            +---+---+---+---+================================+
+            |  LEN  | NLEN  |... LEN bytes of literal data...|
+            +---+---+---+---+================================+
+
+         LEN is the number of data bytes in the block.  NLEN is the
+         one's complement of LEN.
+
+      3.2.5. Compressed blocks (length and distance codes)
+
+         As noted above, encoded data blocks in the "deflate" format
+         consist of sequences of symbols drawn from three conceptually
+         distinct alphabets: either literal bytes, from the alphabet of
+         byte values (0..255), or <length, backward distance> pairs,
+         where the length is drawn from (3..258) and the distance is
+         drawn from (1..32,768).  In fact, the literal and length
+         alphabets are merged into a single alphabet (0..285), where
+         values 0..255 represent literal bytes, the value 256 indicates
+         end-of-block, and values 257..285 represent length codes
+         (possibly in conjunction with extra bits following the symbol
+         code) as follows:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Deutsch                      Informational                     [Page 11]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+                 Extra               Extra               Extra
+            Code Bits Length(s) Code Bits Lengths   Code Bits Length(s)
+            ---- ---- ------     ---- ---- -------   ---- ---- -------
+             257   0     3       267   1   15,16     277   4   67-82
+             258   0     4       268   1   17,18     278   4   83-98
+             259   0     5       269   2   19-22     279   4   99-114
+             260   0     6       270   2   23-26     280   4  115-130
+             261   0     7       271   2   27-30     281   5  131-162
+             262   0     8       272   2   31-34     282   5  163-194
+             263   0     9       273   3   35-42     283   5  195-226
+             264   0    10       274   3   43-50     284   5  227-257
+             265   1  11,12      275   3   51-58     285   0    258
+             266   1  13,14      276   3   59-66
+
+         The extra bits should be interpreted as a machine integer
+         stored with the most-significant bit first, e.g., bits 1110
+         represent the value 14.
+
+                  Extra           Extra               Extra
+             Code Bits Dist  Code Bits   Dist     Code Bits Distance
+             ---- ---- ----  ---- ----  ------    ---- ---- --------
+               0   0    1     10   4     33-48    20    9   1025-1536
+               1   0    2     11   4     49-64    21    9   1537-2048
+               2   0    3     12   5     65-96    22   10   2049-3072
+               3   0    4     13   5     97-128   23   10   3073-4096
+               4   1   5,6    14   6    129-192   24   11   4097-6144
+               5   1   7,8    15   6    193-256   25   11   6145-8192
+               6   2   9-12   16   7    257-384   26   12  8193-12288
+               7   2  13-16   17   7    385-512   27   12 12289-16384
+               8   3  17-24   18   8    513-768   28   13 16385-24576
+               9   3  25-32   19   8   769-1024   29   13 24577-32768
+
+      3.2.6. Compression with fixed Huffman codes (BTYPE=01)
+
+         The Huffman codes for the two alphabets are fixed, and are not
+         represented explicitly in the data.  The Huffman code lengths
+         for the literal/length alphabet are:
+
+                   Lit Value    Bits        Codes
+                   ---------    ----        -----
+                     0 - 143     8          00110000 through
+                                            10111111
+                   144 - 255     9          110010000 through
+                                            111111111
+                   256 - 279     7          0000000 through
+                                            0010111
+                   280 - 287     8          11000000 through
+                                            11000111
+
+
+
+Deutsch                      Informational                     [Page 12]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+         The code lengths are sufficient to generate the actual codes,
+         as described above; we show the codes in the table for added
+         clarity.  Literal/length values 286-287 will never actually
+         occur in the compressed data, but participate in the code
+         construction.
+
+         Distance codes 0-31 are represented by (fixed-length) 5-bit
+         codes, with possible additional bits as shown in the table
+         shown in Paragraph 3.2.5, above.  Note that distance codes 30-
+         31 will never actually occur in the compressed data.
+
+      3.2.7. Compression with dynamic Huffman codes (BTYPE=10)
+
+         The Huffman codes for the two alphabets appear in the block
+         immediately after the header bits and before the actual
+         compressed data, first the literal/length code and then the
+         distance code.  Each code is defined by a sequence of code
+         lengths, as discussed in Paragraph 3.2.2, above.  For even
+         greater compactness, the code length sequences themselves are
+         compressed using a Huffman code.  The alphabet for code lengths
+         is as follows:
+
+               0 - 15: Represent code lengths of 0 - 15
+                   16: Copy the previous code length 3 - 6 times.
+                       The next 2 bits indicate repeat length
+                             (0 = 3, ... , 3 = 6)
+                          Example:  Codes 8, 16 (+2 bits 11),
+                                    16 (+2 bits 10) will expand to
+                                    12 code lengths of 8 (1 + 6 + 5)
+                   17: Repeat a code length of 0 for 3 - 10 times.
+                       (3 bits of length)
+                   18: Repeat a code length of 0 for 11 - 138 times
+                       (7 bits of length)
+
+         A code length of 0 indicates that the corresponding symbol in
+         the literal/length or distance alphabet will not occur in the
+         block, and should not participate in the Huffman code
+         construction algorithm given earlier.  If only one distance
+         code is used, it is encoded using one bit, not zero bits; in
+         this case there is a single code length of one, with one unused
+         code.  One distance code of zero bits means that there are no
+         distance codes used at all (the data is all literals).
+
+         We can now define the format of the block:
+
+               5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286)
+               5 Bits: HDIST, # of Distance codes - 1        (1 - 32)
+               4 Bits: HCLEN, # of Code Length codes - 4     (4 - 19)
+
+
+
+Deutsch                      Informational                     [Page 13]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+               (HCLEN + 4) x 3 bits: code lengths for the code length
+                  alphabet given just above, in the order: 16, 17, 18,
+                  0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
+
+                  These code lengths are interpreted as 3-bit integers
+                  (0-7); as above, a code length of 0 means the
+                  corresponding symbol (literal/length or distance code
+                  length) is not used.
+
+               HLIT + 257 code lengths for the literal/length alphabet,
+                  encoded using the code length Huffman code
+
+               HDIST + 1 code lengths for the distance alphabet,
+                  encoded using the code length Huffman code
+
+               The actual compressed data of the block,
+                  encoded using the literal/length and distance Huffman
+                  codes
+
+               The literal/length symbol 256 (end of data),
+                  encoded using the literal/length Huffman code
+
+         The code length repeat codes can cross from HLIT + 257 to the
+         HDIST + 1 code lengths.  In other words, all code lengths form
+         a single sequence of HLIT + HDIST + 258 values.
+
+   3.3. Compliance
+
+      A compressor may limit further the ranges of values specified in
+      the previous section and still be compliant; for example, it may
+      limit the range of backward pointers to some value smaller than
+      32K.  Similarly, a compressor may limit the size of blocks so that
+      a compressible block fits in memory.
+
+      A compliant decompressor must accept the full range of possible
+      values defined in the previous section, and must accept blocks of
+      arbitrary size.
+
+4. Compression algorithm details
+
+   While it is the intent of this document to define the "deflate"
+   compressed data format without reference to any particular
+   compression algorithm, the format is related to the compressed
+   formats produced by LZ77 (Lempel-Ziv 1977, see reference [2] below);
+   since many variations of LZ77 are patented, it is strongly
+   recommended that the implementor of a compressor follow the general
+   algorithm presented here, which is known not to be patented per se.
+   The material in this section is not part of the definition of the
+
+
+
+Deutsch                      Informational                     [Page 14]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+   specification per se, and a compressor need not follow it in order to
+   be compliant.
+
+   The compressor terminates a block when it determines that starting a
+   new block with fresh trees would be useful, or when the block size
+   fills up the compressor's block buffer.
+
+   The compressor uses a chained hash table to find duplicated strings,
+   using a hash function that operates on 3-byte sequences.  At any
+   given point during compression, let XYZ be the next 3 input bytes to
+   be examined (not necessarily all different, of course).  First, the
+   compressor examines the hash chain for XYZ.  If the chain is empty,
+   the compressor simply writes out X as a literal byte and advances one
+   byte in the input.  If the hash chain is not empty, indicating that
+   the sequence XYZ (or, if we are unlucky, some other 3 bytes with the
+   same hash function value) has occurred recently, the compressor
+   compares all strings on the XYZ hash chain with the actual input data
+   sequence starting at the current point, and selects the longest
+   match.
+
+   The compressor searches the hash chains starting with the most recent
+   strings, to favor small distances and thus take advantage of the
+   Huffman encoding.  The hash chains are singly linked. There are no
+   deletions from the hash chains; the algorithm simply discards matches
+   that are too old.  To avoid a worst-case situation, very long hash
+   chains are arbitrarily truncated at a certain length, determined by a
+   run-time parameter.
+
+   To improve overall compression, the compressor optionally defers the
+   selection of matches ("lazy matching"): after a match of length N has
+   been found, the compressor searches for a longer match starting at
+   the next input byte.  If it finds a longer match, it truncates the
+   previous match to a length of one (thus producing a single literal
+   byte) and then emits the longer match.  Otherwise, it emits the
+   original match, and, as described above, advances N bytes before
+   continuing.
+
+   Run-time parameters also control this "lazy match" procedure.  If
+   compression ratio is most important, the compressor attempts a
+   complete second search regardless of the length of the first match.
+   In the normal case, if the current match is "long enough", the
+   compressor reduces the search for a longer match, thus speeding up
+   the process.  If speed is most important, the compressor inserts new
+   strings in the hash table only when no match was found, or when the
+   match is not "too long".  This degrades the compression ratio but
+   saves time since there are both fewer insertions and fewer searches.
+
+
+
+
+
+Deutsch                      Informational                     [Page 15]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+5. References
+
+   [1] Huffman, D. A., "A Method for the Construction of Minimum
+       Redundancy Codes", Proceedings of the Institute of Radio
+       Engineers, September 1952, Volume 40, Number 9, pp. 1098-1101.
+
+   [2] Ziv J., Lempel A., "A Universal Algorithm for Sequential Data
+       Compression", IEEE Transactions on Information Theory, Vol. 23,
+       No. 3, pp. 337-343.
+
+   [3] Gailly, J.-L., and Adler, M., ZLIB documentation and sources,
+       available in ftp://ftp.uu.net/pub/archiving/zip/doc/
+
+   [4] Gailly, J.-L., and Adler, M., GZIP documentation and sources,
+       available as gzip-*.tar in ftp://prep.ai.mit.edu/pub/gnu/
+
+   [5] Schwartz, E. S., and Kallick, B. "Generating a canonical prefix
+       encoding." Comm. ACM, 7,3 (Mar. 1964), pp. 166-169.
+
+   [6] Hirschberg and Lelewer, "Efficient decoding of prefix codes,"
+       Comm. ACM, 33,4, April 1990, pp. 449-459.
+
+6. Security Considerations
+
+   Any data compression method involves the reduction of redundancy in
+   the data.  Consequently, any corruption of the data is likely to have
+   severe effects and be difficult to correct.  Uncompressed text, on
+   the other hand, will probably still be readable despite the presence
+   of some corrupted bytes.
+
+   It is recommended that systems using this data format provide some
+   means of validating the integrity of the compressed data.  See
+   reference [3], for example.
+
+7. Source code
+
+   Source code for a C language implementation of a "deflate" compliant
+   compressor and decompressor is available within the zlib package at
+   ftp://ftp.uu.net/pub/archiving/zip/zlib/.
+
+8. Acknowledgements
+
+   Trademarks cited in this document are the property of their
+   respective owners.
+
+   Phil Katz designed the deflate format.  Jean-Loup Gailly and Mark
+   Adler wrote the related software described in this specification.
+   Glenn Randers-Pehrson converted this document to RFC and HTML format.
+
+
+
+Deutsch                      Informational                     [Page 16]
+\f
+RFC 1951      DEFLATE Compressed Data Format Specification      May 1996
+
+
+9. Author's Address
+
+   L. Peter Deutsch
+   Aladdin Enterprises
+   203 Santa Margarita Ave.
+   Menlo Park, CA 94025
+
+   Phone: (415) 322-0103 (AM only)
+   FAX:   (415) 322-1734
+   EMail: <ghost@aladdin.com>
+
+   Questions about the technical content of this specification can be
+   sent by email to:
+
+   Jean-Loup Gailly <gzip@prep.ai.mit.edu> and
+   Mark Adler <madler@alumni.caltech.edu>
+
+   Editorial comments on this specification can be sent by email to:
+
+   L. Peter Deutsch <ghost@aladdin.com> and
+   Glenn Randers-Pehrson <randeg@alumni.rpi.edu>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Deutsch                      Informational                     [Page 17]
+\f
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1952.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/rfc1952.txt
new file mode 100644 (file)
index 0000000..a8e51b4
--- /dev/null
@@ -0,0 +1,675 @@
+
+
+
+
+
+
+Network Working Group                                         P. Deutsch
+Request for Comments: 1952                           Aladdin Enterprises
+Category: Informational                                         May 1996
+
+
+               GZIP file format specification version 4.3
+
+Status of This Memo
+
+   This memo provides information for the Internet community.  This memo
+   does not specify an Internet standard of any kind.  Distribution of
+   this memo is unlimited.
+
+IESG Note:
+
+   The IESG takes no position on the validity of any Intellectual
+   Property Rights statements contained in this document.
+
+Notices
+
+   Copyright (c) 1996 L. Peter Deutsch
+
+   Permission is granted to copy and distribute this document for any
+   purpose and without charge, including translations into other
+   languages and incorporation into compilations, provided that the
+   copyright notice and this notice are preserved, and that any
+   substantive changes or deletions from the original are clearly
+   marked.
+
+   A pointer to the latest version of this and related documentation in
+   HTML format can be found at the URL
+   <ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html>.
+
+Abstract
+
+   This specification defines a lossless compressed data format that is
+   compatible with the widely used GZIP utility.  The format includes a
+   cyclic redundancy check value for detecting data corruption.  The
+   format presently uses the DEFLATE method of compression but can be
+   easily extended to use other compression methods.  The format can be
+   implemented readily in a manner not covered by patents.
+
+
+
+
+
+
+
+
+
+
+Deutsch                      Informational                      [Page 1]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+Table of Contents
+
+   1. Introduction ................................................... 2
+      1.1. Purpose ................................................... 2
+      1.2. Intended audience ......................................... 3
+      1.3. Scope ..................................................... 3
+      1.4. Compliance ................................................ 3
+      1.5. Definitions of terms and conventions used ................. 3
+      1.6. Changes from previous versions ............................ 3
+   2. Detailed specification ......................................... 4
+      2.1. Overall conventions ....................................... 4
+      2.2. File format ............................................... 5
+      2.3. Member format ............................................. 5
+          2.3.1. Member header and trailer ........................... 6
+              2.3.1.1. Extra field ................................... 8
+              2.3.1.2. Compliance .................................... 9
+      3. References .................................................. 9
+      4. Security Considerations .................................... 10
+      5. Acknowledgements ........................................... 10
+      6. Author's Address ........................................... 10
+      7. Appendix: Jean-Loup Gailly's gzip utility .................. 11
+      8. Appendix: Sample CRC Code .................................. 11
+
+1. Introduction
+
+   1.1. Purpose
+
+      The purpose of this specification is to define a lossless
+      compressed data format that:
+
+          * Is independent of CPU type, operating system, file system,
+            and character set, and hence can be used for interchange;
+          * Can compress or decompress a data stream (as opposed to a
+            randomly accessible file) to produce another data stream,
+            using only an a priori bounded amount of intermediate
+            storage, and hence can be used in data communications or
+            similar structures such as Unix filters;
+          * Compresses data with efficiency comparable to the best
+            currently available general-purpose compression methods,
+            and in particular considerably better than the "compress"
+            program;
+          * Can be implemented readily in a manner not covered by
+            patents, and hence can be practiced freely;
+          * Is compatible with the file format produced by the current
+            widely used gzip utility, in that conforming decompressors
+            will be able to read data produced by the existing gzip
+            compressor.
+
+
+
+
+Deutsch                      Informational                      [Page 2]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+      The data format defined by this specification does not attempt to:
+
+          * Provide random access to compressed data;
+          * Compress specialized data (e.g., raster graphics) as well as
+            the best currently available specialized algorithms.
+
+   1.2. Intended audience
+
+      This specification is intended for use by implementors of software
+      to compress data into gzip format and/or decompress data from gzip
+      format.
+
+      The text of the specification assumes a basic background in
+      programming at the level of bits and other primitive data
+      representations.
+
+   1.3. Scope
+
+      The specification specifies a compression method and a file format
+      (the latter assuming only that a file can store a sequence of
+      arbitrary bytes).  It does not specify any particular interface to
+      a file system or anything about character sets or encodings
+      (except for file names and comments, which are optional).
+
+   1.4. Compliance
+
+      Unless otherwise indicated below, a compliant decompressor must be
+      able to accept and decompress any file that conforms to all the
+      specifications presented here; a compliant compressor must produce
+      files that conform to all the specifications presented here.  The
+      material in the appendices is not part of the specification per se
+      and is not relevant to compliance.
+
+   1.5. Definitions of terms and conventions used
+
+      byte: 8 bits stored or transmitted as a unit (same as an octet).
+      (For this specification, a byte is exactly 8 bits, even on
+      machines which store a character on a number of bits different
+      from 8.)  See below for the numbering of bits within a byte.
+
+   1.6. Changes from previous versions
+
+      There have been no technical changes to the gzip format since
+      version 4.1 of this specification.  In version 4.2, some
+      terminology was changed, and the sample CRC code was rewritten for
+      clarity and to eliminate the requirement for the caller to do pre-
+      and post-conditioning.  Version 4.3 is a conversion of the
+      specification to RFC style.
+
+
+
+Deutsch                      Informational                      [Page 3]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+2. Detailed specification
+
+   2.1. Overall conventions
+
+      In the diagrams below, a box like this:
+
+         +---+
+         |   | <-- the vertical bars might be missing
+         +---+
+
+      represents one byte; a box like this:
+
+         +==============+
+         |              |
+         +==============+
+
+      represents a variable number of bytes.
+
+      Bytes stored within a computer do not have a "bit order", since
+      they are always treated as a unit.  However, a byte considered as
+      an integer between 0 and 255 does have a most- and least-
+      significant bit, and since we write numbers with the most-
+      significant digit on the left, we also write bytes with the most-
+      significant bit on the left.  In the diagrams below, we number the
+      bits of a byte so that bit 0 is the least-significant bit, i.e.,
+      the bits are numbered:
+
+         +--------+
+         |76543210|
+         +--------+
+
+      This document does not address the issue of the order in which
+      bits of a byte are transmitted on a bit-sequential medium, since
+      the data format described here is byte- rather than bit-oriented.
+
+      Within a computer, a number may occupy multiple bytes.  All
+      multi-byte numbers in the format described here are stored with
+      the least-significant byte first (at the lower memory address).
+      For example, the decimal number 520 is stored as:
+
+             0        1
+         +--------+--------+
+         |00001000|00000010|
+         +--------+--------+
+          ^        ^
+          |        |
+          |        + more significant byte = 2 x 256
+          + less significant byte = 8
+
+
+
+Deutsch                      Informational                      [Page 4]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+   2.2. File format
+
+      A gzip file consists of a series of "members" (compressed data
+      sets).  The format of each member is specified in the following
+      section.  The members simply appear one after another in the file,
+      with no additional information before, between, or after them.
+
+   2.3. Member format
+
+      Each member has the following structure:
+
+         +---+---+---+---+---+---+---+---+---+---+
+         |ID1|ID2|CM |FLG|     MTIME     |XFL|OS | (more-->)
+         +---+---+---+---+---+---+---+---+---+---+
+
+      (if FLG.FEXTRA set)
+
+         +---+---+=================================+
+         | XLEN  |...XLEN bytes of "extra field"...| (more-->)
+         +---+---+=================================+
+
+      (if FLG.FNAME set)
+
+         +=========================================+
+         |...original file name, zero-terminated...| (more-->)
+         +=========================================+
+
+      (if FLG.FCOMMENT set)
+
+         +===================================+
+         |...file comment, zero-terminated...| (more-->)
+         +===================================+
+
+      (if FLG.FHCRC set)
+
+         +---+---+
+         | CRC16 |
+         +---+---+
+
+         +=======================+
+         |...compressed blocks...| (more-->)
+         +=======================+
+
+           0   1   2   3   4   5   6   7
+         +---+---+---+---+---+---+---+---+
+         |     CRC32     |     ISIZE     |
+         +---+---+---+---+---+---+---+---+
+
+
+
+
+Deutsch                      Informational                      [Page 5]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+      2.3.1. Member header and trailer
+
+         ID1 (IDentification 1)
+         ID2 (IDentification 2)
+            These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139
+            (0x8b, \213), to identify the file as being in gzip format.
+
+         CM (Compression Method)
+            This identifies the compression method used in the file.  CM
+            = 0-7 are reserved.  CM = 8 denotes the "deflate"
+            compression method, which is the one customarily used by
+            gzip and which is documented elsewhere.
+
+         FLG (FLaGs)
+            This flag byte is divided into individual bits as follows:
+
+               bit 0   FTEXT
+               bit 1   FHCRC
+               bit 2   FEXTRA
+               bit 3   FNAME
+               bit 4   FCOMMENT
+               bit 5   reserved
+               bit 6   reserved
+               bit 7   reserved
+
+            If FTEXT is set, the file is probably ASCII text.  This is
+            an optional indication, which the compressor may set by
+            checking a small amount of the input data to see whether any
+            non-ASCII characters are present.  In case of doubt, FTEXT
+            is cleared, indicating binary data. For systems which have
+            different file formats for ascii text and binary data, the
+            decompressor can use FTEXT to choose the appropriate format.
+            We deliberately do not specify the algorithm used to set
+            this bit, since a compressor always has the option of
+            leaving it cleared and a decompressor always has the option
+            of ignoring it and letting some other program handle issues
+            of data conversion.
+
+            If FHCRC is set, a CRC16 for the gzip header is present,
+            immediately before the compressed data. The CRC16 consists
+            of the two least significant bytes of the CRC32 for all
+            bytes of the gzip header up to and not including the CRC16.
+            [The FHCRC bit was never set by versions of gzip up to
+            1.2.4, even though it was documented with a different
+            meaning in gzip 1.2.4.]
+
+            If FEXTRA is set, optional extra fields are present, as
+            described in a following section.
+
+
+
+Deutsch                      Informational                      [Page 6]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+            If FNAME is set, an original file name is present,
+            terminated by a zero byte.  The name must consist of ISO
+            8859-1 (LATIN-1) characters; on operating systems using
+            EBCDIC or any other character set for file names, the name
+            must be translated to the ISO LATIN-1 character set.  This
+            is the original name of the file being compressed, with any
+            directory components removed, and, if the file being
+            compressed is on a file system with case insensitive names,
+            forced to lower case. There is no original file name if the
+            data was compressed from a source other than a named file;
+            for example, if the source was stdin on a Unix system, there
+            is no file name.
+
+            If FCOMMENT is set, a zero-terminated file comment is
+            present.  This comment is not interpreted; it is only
+            intended for human consumption.  The comment must consist of
+            ISO 8859-1 (LATIN-1) characters.  Line breaks should be
+            denoted by a single line feed character (10 decimal).
+
+            Reserved FLG bits must be zero.
+
+         MTIME (Modification TIME)
+            This gives the most recent modification time of the original
+            file being compressed.  The time is in Unix format, i.e.,
+            seconds since 00:00:00 GMT, Jan.  1, 1970.  (Note that this
+            may cause problems for MS-DOS and other systems that use
+            local rather than Universal time.)  If the compressed data
+            did not come from a file, MTIME is set to the time at which
+            compression started.  MTIME = 0 means no time stamp is
+            available.
+
+         XFL (eXtra FLags)
+            These flags are available for use by specific compression
+            methods.  The "deflate" method (CM = 8) sets these flags as
+            follows:
+
+               XFL = 2 - compressor used maximum compression,
+                         slowest algorithm
+               XFL = 4 - compressor used fastest algorithm
+
+         OS (Operating System)
+            This identifies the type of file system on which compression
+            took place.  This may be useful in determining end-of-line
+            convention for text files.  The currently defined values are
+            as follows:
+
+
+
+
+
+
+Deutsch                      Informational                      [Page 7]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+                 0 - FAT filesystem (MS-DOS, OS/2, NT/Win32)
+                 1 - Amiga
+                 2 - VMS (or OpenVMS)
+                 3 - Unix
+                 4 - VM/CMS
+                 5 - Atari TOS
+                 6 - HPFS filesystem (OS/2, NT)
+                 7 - Macintosh
+                 8 - Z-System
+                 9 - CP/M
+                10 - TOPS-20
+                11 - NTFS filesystem (NT)
+                12 - QDOS
+                13 - Acorn RISCOS
+               255 - unknown
+
+         XLEN (eXtra LENgth)
+            If FLG.FEXTRA is set, this gives the length of the optional
+            extra field.  See below for details.
+
+         CRC32 (CRC-32)
+            This contains a Cyclic Redundancy Check value of the
+            uncompressed data computed according to CRC-32 algorithm
+            used in the ISO 3309 standard and in section 8.1.1.6.2 of
+            ITU-T recommendation V.42.  (See http://www.iso.ch for
+            ordering ISO documents. See gopher://info.itu.ch for an
+            online version of ITU-T V.42.)
+
+         ISIZE (Input SIZE)
+            This contains the size of the original (uncompressed) input
+            data modulo 2^32.
+
+      2.3.1.1. Extra field
+
+         If the FLG.FEXTRA bit is set, an "extra field" is present in
+         the header, with total length XLEN bytes.  It consists of a
+         series of subfields, each of the form:
+
+            +---+---+---+---+==================================+
+            |SI1|SI2|  LEN  |... LEN bytes of subfield data ...|
+            +---+---+---+---+==================================+
+
+         SI1 and SI2 provide a subfield ID, typically two ASCII letters
+         with some mnemonic value.  Jean-Loup Gailly
+         <gzip@prep.ai.mit.edu> is maintaining a registry of subfield
+         IDs; please send him any subfield ID you wish to use.  Subfield
+         IDs with SI2 = 0 are reserved for future use.  The following
+         IDs are currently defined:
+
+
+
+Deutsch                      Informational                      [Page 8]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+            SI1         SI2         Data
+            ----------  ----------  ----
+            0x41 ('A')  0x70 ('P')  Apollo file type information
+
+         LEN gives the length of the subfield data, excluding the 4
+         initial bytes.
+
+      2.3.1.2. Compliance
+
+         A compliant compressor must produce files with correct ID1,
+         ID2, CM, CRC32, and ISIZE, but may set all the other fields in
+         the fixed-length part of the header to default values (255 for
+         OS, 0 for all others).  The compressor must set all reserved
+         bits to zero.
+
+         A compliant decompressor must check ID1, ID2, and CM, and
+         provide an error indication if any of these have incorrect
+         values.  It must examine FEXTRA/XLEN, FNAME, FCOMMENT and FHCRC
+         at least so it can skip over the optional fields if they are
+         present.  It need not examine any other part of the header or
+         trailer; in particular, a decompressor may ignore FTEXT and OS
+         and always produce binary output, and still be compliant.  A
+         compliant decompressor must give an error indication if any
+         reserved bit is non-zero, since such a bit could indicate the
+         presence of a new field that would cause subsequent data to be
+         interpreted incorrectly.
+
+3. References
+
+   [1] "Information Processing - 8-bit single-byte coded graphic
+       character sets - Part 1: Latin alphabet No.1" (ISO 8859-1:1987).
+       The ISO 8859-1 (Latin-1) character set is a superset of 7-bit
+       ASCII. Files defining this character set are available as
+       iso_8859-1.* in ftp://ftp.uu.net/graphics/png/documents/
+
+   [2] ISO 3309
+
+   [3] ITU-T recommendation V.42
+
+   [4] Deutsch, L.P.,"DEFLATE Compressed Data Format Specification",
+       available in ftp://ftp.uu.net/pub/archiving/zip/doc/
+
+   [5] Gailly, J.-L., GZIP documentation, available as gzip-*.tar in
+       ftp://prep.ai.mit.edu/pub/gnu/
+
+   [6] Sarwate, D.V., "Computation of Cyclic Redundancy Checks via Table
+       Look-Up", Communications of the ACM, 31(8), pp.1008-1013.
+
+
+
+
+Deutsch                      Informational                      [Page 9]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+   [7] Schwaderer, W.D., "CRC Calculation", April 85 PC Tech Journal,
+       pp.118-133.
+
+   [8] ftp://ftp.adelaide.edu.au/pub/rocksoft/papers/crc_v3.txt,
+       describing the CRC concept.
+
+4. Security Considerations
+
+   Any data compression method involves the reduction of redundancy in
+   the data.  Consequently, any corruption of the data is likely to have
+   severe effects and be difficult to correct.  Uncompressed text, on
+   the other hand, will probably still be readable despite the presence
+   of some corrupted bytes.
+
+   It is recommended that systems using this data format provide some
+   means of validating the integrity of the compressed data, such as by
+   setting and checking the CRC-32 check value.
+
+5. Acknowledgements
+
+   Trademarks cited in this document are the property of their
+   respective owners.
+
+   Jean-Loup Gailly designed the gzip format and wrote, with Mark Adler,
+   the related software described in this specification.  Glenn
+   Randers-Pehrson converted this document to RFC and HTML format.
+
+6. Author's Address
+
+   L. Peter Deutsch
+   Aladdin Enterprises
+   203 Santa Margarita Ave.
+   Menlo Park, CA 94025
+
+   Phone: (415) 322-0103 (AM only)
+   FAX:   (415) 322-1734
+   EMail: <ghost@aladdin.com>
+
+   Questions about the technical content of this specification can be
+   sent by email to:
+
+   Jean-Loup Gailly <gzip@prep.ai.mit.edu> and
+   Mark Adler <madler@alumni.caltech.edu>
+
+   Editorial comments on this specification can be sent by email to:
+
+   L. Peter Deutsch <ghost@aladdin.com> and
+   Glenn Randers-Pehrson <randeg@alumni.rpi.edu>
+
+
+
+Deutsch                      Informational                     [Page 10]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+7. Appendix: Jean-Loup Gailly's gzip utility
+
+   The most widely used implementation of gzip compression, and the
+   original documentation on which this specification is based, were
+   created by Jean-Loup Gailly <gzip@prep.ai.mit.edu>.  Since this
+   implementation is a de facto standard, we mention some more of its
+   features here.  Again, the material in this section is not part of
+   the specification per se, and implementations need not follow it to
+   be compliant.
+
+   When compressing or decompressing a file, gzip preserves the
+   protection, ownership, and modification time attributes on the local
+   file system, since there is no provision for representing protection
+   attributes in the gzip file format itself.  Since the file format
+   includes a modification time, the gzip decompressor provides a
+   command line switch that assigns the modification time from the file,
+   rather than the local modification time of the compressed input, to
+   the decompressed output.
+
+8. Appendix: Sample CRC Code
+
+   The following sample code represents a practical implementation of
+   the CRC (Cyclic Redundancy Check). (See also ISO 3309 and ITU-T V.42
+   for a formal specification.)
+
+   The sample code is in the ANSI C programming language. Non C users
+   may find it easier to read with these hints:
+
+      &      Bitwise AND operator.
+      ^      Bitwise exclusive-OR operator.
+      >>     Bitwise right shift operator. When applied to an
+             unsigned quantity, as here, right shift inserts zero
+             bit(s) at the left.
+      !      Logical NOT operator.
+      ++     "n++" increments the variable n.
+      0xNNN  0x introduces a hexadecimal (base 16) constant.
+             Suffix L indicates a long value (at least 32 bits).
+
+      /* Table of CRCs of all 8-bit messages. */
+      unsigned long crc_table[256];
+
+      /* Flag: has the table been computed? Initially false. */
+      int crc_table_computed = 0;
+
+      /* Make the table for a fast CRC. */
+      void make_crc_table(void)
+      {
+        unsigned long c;
+
+
+
+Deutsch                      Informational                     [Page 11]
+\f
+RFC 1952             GZIP File Format Specification             May 1996
+
+
+        int n, k;
+        for (n = 0; n < 256; n++) {
+          c = (unsigned long) n;
+          for (k = 0; k < 8; k++) {
+            if (c & 1) {
+              c = 0xedb88320L ^ (c >> 1);
+            } else {
+              c = c >> 1;
+            }
+          }
+          crc_table[n] = c;
+        }
+        crc_table_computed = 1;
+      }
+
+      /*
+         Update a running crc with the bytes buf[0..len-1] and return
+       the updated crc. The crc should be initialized to zero. Pre- and
+       post-conditioning (one's complement) is performed within this
+       function so it shouldn't be done by the caller. Usage example:
+
+         unsigned long crc = 0L;
+
+         while (read_buffer(buffer, length) != EOF) {
+           crc = update_crc(crc, buffer, length);
+         }
+         if (crc != original_crc) error();
+      */
+      unsigned long update_crc(unsigned long crc,
+                      unsigned char *buf, int len)
+      {
+        unsigned long c = crc ^ 0xffffffffL;
+        int n;
+
+        if (!crc_table_computed)
+          make_crc_table();
+        for (n = 0; n < len; n++) {
+          c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
+        }
+        return c ^ 0xffffffffL;
+      }
+
+      /* Return the CRC of the bytes buf[0..len-1]. */
+      unsigned long crc(unsigned char *buf, int len)
+      {
+        return update_crc(0L, buf, len);
+      }
+
+
+
+
+Deutsch                      Informational                     [Page 12]
+\f
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/txtvsbin.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/doc/txtvsbin.txt
new file mode 100644 (file)
index 0000000..3d0f063
--- /dev/null
@@ -0,0 +1,107 @@
+A Fast Method for Identifying Plain Text Files
+==============================================
+
+
+Introduction
+------------
+
+Given a file coming from an unknown source, it is sometimes desirable
+to find out whether the format of that file is plain text.  Although
+this may appear like a simple task, a fully accurate detection of the
+file type requires heavy-duty semantic analysis on the file contents.
+It is, however, possible to obtain satisfactory results by employing
+various heuristics.
+
+Previous versions of PKZip and other zip-compatible compression tools
+were using a crude detection scheme: if more than 80% (4/5) of the bytes
+found in a certain buffer are within the range [7..127], the file is
+labeled as plain text, otherwise it is labeled as binary.  A prominent
+limitation of this scheme is the restriction to Latin-based alphabets.
+Other alphabets, like Greek, Cyrillic or Asian, make extensive use of
+the bytes within the range [128..255], and texts using these alphabets
+are most often misidentified by this scheme; in other words, the rate
+of false negatives is sometimes too high, which means that the recall
+is low.  Another weakness of this scheme is a reduced precision, due to
+the false positives that may occur when binary files containing large
+amounts of textual characters are misidentified as plain text.
+
+In this article we propose a new, simple detection scheme that features
+a much increased precision and a near-100% recall.  This scheme is
+designed to work on ASCII, Unicode and other ASCII-derived alphabets,
+and it handles single-byte encodings (ISO-8859, MacRoman, KOI8, etc.)
+and variable-sized encodings (ISO-2022, UTF-8, etc.).  Wider encodings
+(UCS-2/UTF-16 and UCS-4/UTF-32) are not handled, however.
+
+
+The Algorithm
+-------------
+
+The algorithm works by dividing the set of bytecodes [0..255] into three
+categories:
+- The white list of textual bytecodes:
+  9 (TAB), 10 (LF), 13 (CR), 32 (SPACE) to 255.
+- The gray list of tolerated bytecodes:
+  7 (BEL), 8 (BS), 11 (VT), 12 (FF), 26 (SUB), 27 (ESC).
+- The black list of undesired, non-textual bytecodes:
+  0 (NUL) to 6, 14 to 31.
+
+If a file contains at least one byte that belongs to the white list and
+no byte that belongs to the black list, then the file is categorized as
+plain text; otherwise, it is categorized as binary.  (The boundary case,
+when the file is empty, automatically falls into the latter category.)
+
+
+Rationale
+---------
+
+The idea behind this algorithm relies on two observations.
+
+The first observation is that, although the full range of 7-bit codes
+[0..127] is properly specified by the ASCII standard, most control
+characters in the range [0..31] are not used in practice.  The only
+widely-used, almost universally-portable control codes are 9 (TAB),
+10 (LF) and 13 (CR).  There are a few more control codes that are
+recognized on a reduced range of platforms and text viewers/editors:
+7 (BEL), 8 (BS), 11 (VT), 12 (FF), 26 (SUB) and 27 (ESC); but these
+codes are rarely (if ever) used alone, without being accompanied by
+some printable text.  Even the newer, portable text formats such as
+XML avoid using control characters outside the list mentioned here.
+
+The second observation is that most of the binary files tend to contain
+control characters, especially 0 (NUL).  Even though the older text
+detection schemes observe the presence of non-ASCII codes from the range
+[128..255], the precision rarely has to suffer if this upper range is
+labeled as textual, because the files that are genuinely binary tend to
+contain both control characters and codes from the upper range.  On the
+other hand, the upper range needs to be labeled as textual, because it
+is used by virtually all ASCII extensions.  In particular, this range is
+used for encoding non-Latin scripts.
+
+Since there is no counting involved, other than simply observing the
+presence or the absence of some byte values, the algorithm produces
+consistent results, regardless what alphabet encoding is being used.
+(If counting were involved, it could be possible to obtain different
+results on a text encoded, say, using ISO-8859-16 versus UTF-8.)
+
+There is an extra category of plain text files that are "polluted" with
+one or more black-listed codes, either by mistake or by peculiar design
+considerations.  In such cases, a scheme that tolerates a small fraction
+of black-listed codes would provide an increased recall (i.e. more true
+positives).  This, however, incurs a reduced precision overall, since
+false positives are more likely to appear in binary files that contain
+large chunks of textual data.  Furthermore, "polluted" plain text should
+be regarded as binary by general-purpose text detection schemes, because
+general-purpose text processing algorithms might not be applicable.
+Under this premise, it is safe to say that our detection method provides
+a near-100% recall.
+
+Experiments have been run on many files coming from various platforms
+and applications.  We tried plain text files, system logs, source code,
+formatted office documents, compiled object code, etc.  The results
+confirm the optimistic assumptions about the capabilities of this
+algorithm.
+
+
+--
+Cosmin Truta
+Last updated: 2006-May-28
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/README.examples b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/README.examples
new file mode 100644 (file)
index 0000000..56a3171
--- /dev/null
@@ -0,0 +1,49 @@
+This directory contains examples of the use of zlib and other relevant
+programs and documentation.
+
+enough.c
+    calculation and justification of ENOUGH parameter in inftrees.h
+    - calculates the maximum table space used in inflate tree
+      construction over all possible Huffman codes
+
+fitblk.c
+    compress just enough input to nearly fill a requested output size
+    - zlib isn't designed to do this, but fitblk does it anyway
+
+gun.c
+    uncompress a gzip file
+    - illustrates the use of inflateBack() for high speed file-to-file
+      decompression using call-back functions
+    - is approximately twice as fast as gzip -d
+    - also provides Unix uncompress functionality, again twice as fast
+
+gzappend.c
+    append to a gzip file
+    - illustrates the use of the Z_BLOCK flush parameter for inflate()
+    - illustrates the use of deflatePrime() to start at any bit
+
+gzjoin.c
+    join gzip files without recalculating the crc or recompressing
+    - illustrates the use of the Z_BLOCK flush parameter for inflate()
+    - illustrates the use of crc32_combine()
+
+gzlog.c
+gzlog.h
+    efficiently and robustly maintain a message log file in gzip format
+    - illustrates use of raw deflate, Z_PARTIAL_FLUSH, deflatePrime(),
+      and deflateSetDictionary()
+    - illustrates use of a gzip header extra field
+
+zlib_how.html
+    painfully comprehensive description of zpipe.c (see below)
+    - describes in excruciating detail the use of deflate() and inflate()
+
+zpipe.c
+    reads and writes zlib streams from stdin to stdout
+    - illustrates the proper use of deflate() and inflate()
+    - deeply commented in zlib_how.html (see above)
+
+zran.c
+    index a zlib or gzip stream and randomly access it
+    - illustrates the use of Z_BLOCK, inflatePrime(), and
+      inflateSetDictionary() to provide random access
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/enough.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/enough.c
new file mode 100644 (file)
index 0000000..c40410b
--- /dev/null
@@ -0,0 +1,569 @@
+/* enough.c -- determine the maximum size of inflate's Huffman code tables over
+ * all possible valid and complete Huffman codes, subject to a length limit.
+ * Copyright (C) 2007, 2008 Mark Adler
+ * Version 1.3  17 February 2008  Mark Adler
+ */
+
+/* Version history:
+   1.0   3 Jan 2007  First version (derived from codecount.c version 1.4)
+   1.1   4 Jan 2007  Use faster incremental table usage computation
+                     Prune examine() search on previously visited states
+   1.2   5 Jan 2007  Comments clean up
+                     As inflate does, decrease root for short codes
+                     Refuse cases where inflate would increase root
+   1.3  17 Feb 2008  Add argument for initial root table size
+                     Fix bug for initial root table size == max - 1
+                     Use a macro to compute the history index
+ */
+
+/*
+   Examine all possible Huffman codes for a given number of symbols and a
+   maximum code length in bits to determine the maximum table size for zilb's
+   inflate.  Only complete Huffman codes are counted.
+
+   Two codes are considered distinct if the vectors of the number of codes per
+   length are not identical.  So permutations of the symbol assignments result
+   in the same code for the counting, as do permutations of the assignments of
+   the bit values to the codes (i.e. only canonical codes are counted).
+
+   We build a code from shorter to longer lengths, determining how many symbols
+   are coded at each length.  At each step, we have how many symbols remain to
+   be coded, what the last code length used was, and how many bit patterns of
+   that length remain unused. Then we add one to the code length and double the
+   number of unused patterns to graduate to the next code length.  We then
+   assign all portions of the remaining symbols to that code length that
+   preserve the properties of a correct and eventually complete code.  Those
+   properties are: we cannot use more bit patterns than are available; and when
+   all the symbols are used, there are exactly zero possible bit patterns
+   remaining.
+
+   The inflate Huffman decoding algorithm uses two-level lookup tables for
+   speed.  There is a single first-level table to decode codes up to root bits
+   in length (root == 9 in the current inflate implementation).  The table
+   has 1 << root entries and is indexed by the next root bits of input.  Codes
+   shorter than root bits have replicated table entries, so that the correct
+   entry is pointed to regardless of the bits that follow the short code.  If
+   the code is longer than root bits, then the table entry points to a second-
+   level table.  The size of that table is determined by the longest code with
+   that root-bit prefix.  If that longest code has length len, then the table
+   has size 1 << (len - root), to index the remaining bits in that set of
+   codes.  Each subsequent root-bit prefix then has its own sub-table.  The
+   total number of table entries required by the code is calculated
+   incrementally as the number of codes at each bit length is populated.  When
+   all of the codes are shorter than root bits, then root is reduced to the
+   longest code length, resulting in a single, smaller, one-level table.
+
+   The inflate algorithm also provides for small values of root (relative to
+   the log2 of the number of symbols), where the shortest code has more bits
+   than root.  In that case, root is increased to the length of the shortest
+   code.  This program, by design, does not handle that case, so it is verified
+   that the number of symbols is less than 2^(root + 1).
+
+   In order to speed up the examination (by about ten orders of magnitude for
+   the default arguments), the intermediate states in the build-up of a code
+   are remembered and previously visited branches are pruned.  The memory
+   required for this will increase rapidly with the total number of symbols and
+   the maximum code length in bits.  However this is a very small price to pay
+   for the vast speedup.
+
+   First, all of the possible Huffman codes are counted, and reachable
+   intermediate states are noted by a non-zero count in a saved-results array.
+   Second, the intermediate states that lead to (root + 1) bit or longer codes
+   are used to look at all sub-codes from those junctures for their inflate
+   memory usage.  (The amount of memory used is not affected by the number of
+   codes of root bits or less in length.)  Third, the visited states in the
+   construction of those sub-codes and the associated calculation of the table
+   size is recalled in order to avoid recalculating from the same juncture.
+   Beginning the code examination at (root + 1) bit codes, which is enabled by
+   identifying the reachable nodes, accounts for about six of the orders of
+   magnitude of improvement for the default arguments.  About another four
+   orders of magnitude come from not revisiting previous states.  Out of
+   approximately 2x10^16 possible Huffman codes, only about 2x10^6 sub-codes
+   need to be examined to cover all of the possible table memory usage cases
+   for the default arguments of 286 symbols limited to 15-bit codes.
+
+   Note that an unsigned long long type is used for counting.  It is quite easy
+   to exceed the capacity of an eight-byte integer with a large number of
+   symbols and a large maximum code length, so multiple-precision arithmetic
+   would need to replace the unsigned long long arithmetic in that case.  This
+   program will abort if an overflow occurs.  The big_t type identifies where
+   the counting takes place.
+
+   An unsigned long long type is also used for calculating the number of
+   possible codes remaining at the maximum length.  This limits the maximum
+   code length to the number of bits in a long long minus the number of bits
+   needed to represent the symbols in a flat code.  The code_t type identifies
+   where the bit pattern counting takes place.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#define local static
+
+/* special data types */
+typedef unsigned long long big_t;   /* type for code counting */
+typedef unsigned long long code_t;  /* type for bit pattern counting */
+struct tab {                        /* type for been here check */
+    size_t len;         /* length of bit vector in char's */
+    char *vec;          /* allocated bit vector */
+};
+
+/* The array for saving results, num[], is indexed with this triplet:
+
+      syms: number of symbols remaining to code
+      left: number of available bit patterns at length len
+      len: number of bits in the codes currently being assigned
+
+   Those indices are constrained thusly when saving results:
+
+      syms: 3..totsym (totsym == total symbols to code)
+      left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6)
+      len: 1..max - 1 (max == maximum code length in bits)
+
+   syms == 2 is not saved since that immediately leads to a single code.  left
+   must be even, since it represents the number of available bit patterns at
+   the current length, which is double the number at the previous length.
+   left ends at syms-1 since left == syms immediately results in a single code.
+   (left > sym is not allowed since that would result in an incomplete code.)
+   len is less than max, since the code completes immediately when len == max.
+
+   The offset into the array is calculated for the three indices with the
+   first one (syms) being outermost, and the last one (len) being innermost.
+   We build the array with length max-1 lists for the len index, with syms-3
+   of those for each symbol.  There are totsym-2 of those, with each one
+   varying in length as a function of sym.  See the calculation of index in
+   count() for the index, and the calculation of size in main() for the size
+   of the array.
+
+   For the deflate example of 286 symbols limited to 15-bit codes, the array
+   has 284,284 entries, taking up 2.17 MB for an 8-byte big_t.  More than
+   half of the space allocated for saved results is actually used -- not all
+   possible triplets are reached in the generation of valid Huffman codes.
+ */
+
+/* The array for tracking visited states, done[], is itself indexed identically
+   to the num[] array as described above for the (syms, left, len) triplet.
+   Each element in the array is further indexed by the (mem, rem) doublet,
+   where mem is the amount of inflate table space used so far, and rem is the
+   remaining unused entries in the current inflate sub-table.  Each indexed
+   element is simply one bit indicating whether the state has been visited or
+   not.  Since the ranges for mem and rem are not known a priori, each bit
+   vector is of a variable size, and grows as needed to accommodate the visited
+   states.  mem and rem are used to calculate a single index in a triangular
+   array.  Since the range of mem is expected in the default case to be about
+   ten times larger than the range of rem, the array is skewed to reduce the
+   memory usage, with eight times the range for mem than for rem.  See the
+   calculations for offset and bit in beenhere() for the details.
+
+   For the deflate example of 286 symbols limited to 15-bit codes, the bit
+   vectors grow to total approximately 21 MB, in addition to the 4.3 MB done[]
+   array itself.
+ */
+
+/* Globals to avoid propagating constants or constant pointers recursively */
+local int max;          /* maximum allowed bit length for the codes */
+local int root;         /* size of base code table in bits */
+local int large;        /* largest code table so far */
+local size_t size;      /* number of elements in num and done */
+local int *code;        /* number of symbols assigned to each bit length */
+local big_t *num;       /* saved results array for code counting */
+local struct tab *done; /* states already evaluated array */
+
+/* Index function for num[] and done[] */
+#define INDEX(i,j,k) (((size_t)((i-1)>>1)*((i-2)>>1)+(j>>1)-1)*(max-1)+k-1)
+
+/* Free allocated space.  Uses globals code, num, and done. */
+local void cleanup(void)
+{
+    size_t n;
+
+    if (done != NULL) {
+        for (n = 0; n < size; n++)
+            if (done[n].len)
+                free(done[n].vec);
+        free(done);
+    }
+    if (num != NULL)
+        free(num);
+    if (code != NULL)
+        free(code);
+}
+
+/* Return the number of possible Huffman codes using bit patterns of lengths
+   len through max inclusive, coding syms symbols, with left bit patterns of
+   length len unused -- return -1 if there is an overflow in the counting.
+   Keep a record of previous results in num to prevent repeating the same
+   calculation.  Uses the globals max and num. */
+local big_t count(int syms, int len, int left)
+{
+    big_t sum;          /* number of possible codes from this juncture */
+    big_t got;          /* value returned from count() */
+    int least;          /* least number of syms to use at this juncture */
+    int most;           /* most number of syms to use at this juncture */
+    int use;            /* number of bit patterns to use in next call */
+    size_t index;       /* index of this case in *num */
+
+    /* see if only one possible code */
+    if (syms == left)
+        return 1;
+
+    /* note and verify the expected state */
+    assert(syms > left && left > 0 && len < max);
+
+    /* see if we've done this one already */
+    index = INDEX(syms, left, len);
+    got = num[index];
+    if (got)
+        return got;         /* we have -- return the saved result */
+
+    /* we need to use at least this many bit patterns so that the code won't be
+       incomplete at the next length (more bit patterns than symbols) */
+    least = (left << 1) - syms;
+    if (least < 0)
+        least = 0;
+
+    /* we can use at most this many bit patterns, lest there not be enough
+       available for the remaining symbols at the maximum length (if there were
+       no limit to the code length, this would become: most = left - 1) */
+    most = (((code_t)left << (max - len)) - syms) /
+            (((code_t)1 << (max - len)) - 1);
+
+    /* count all possible codes from this juncture and add them up */
+    sum = 0;
+    for (use = least; use <= most; use++) {
+        got = count(syms - use, len + 1, (left - use) << 1);
+        sum += got;
+        if (got == -1 || sum < got)         /* overflow */
+            return -1;
+    }
+
+    /* verify that all recursive calls are productive */
+    assert(sum != 0);
+
+    /* save the result and return it */
+    num[index] = sum;
+    return sum;
+}
+
+/* Return true if we've been here before, set to true if not.  Set a bit in a
+   bit vector to indicate visiting this state.  Each (syms,len,left) state
+   has a variable size bit vector indexed by (mem,rem).  The bit vector is
+   lengthened if needed to allow setting the (mem,rem) bit. */
+local int beenhere(int syms, int len, int left, int mem, int rem)
+{
+    size_t index;       /* index for this state's bit vector */
+    size_t offset;      /* offset in this state's bit vector */
+    int bit;            /* mask for this state's bit */
+    size_t length;      /* length of the bit vector in bytes */
+    char *vector;       /* new or enlarged bit vector */
+
+    /* point to vector for (syms,left,len), bit in vector for (mem,rem) */
+    index = INDEX(syms, left, len);
+    mem -= 1 << root;
+    offset = (mem >> 3) + rem;
+    offset = ((offset * (offset + 1)) >> 1) + rem;
+    bit = 1 << (mem & 7);
+
+    /* see if we've been here */
+    length = done[index].len;
+    if (offset < length && (done[index].vec[offset] & bit) != 0)
+        return 1;       /* done this! */
+
+    /* we haven't been here before -- set the bit to show we have now */
+
+    /* see if we need to lengthen the vector in order to set the bit */
+    if (length <= offset) {
+        /* if we have one already, enlarge it, zero out the appended space */
+        if (length) {
+            do {
+                length <<= 1;
+            } while (length <= offset);
+            vector = realloc(done[index].vec, length);
+            if (vector != NULL)
+                memset(vector + done[index].len, 0, length - done[index].len);
+        }
+
+        /* otherwise we need to make a new vector and zero it out */
+        else {
+            length = 1 << (len - root);
+            while (length <= offset)
+                length <<= 1;
+            vector = calloc(length, sizeof(char));
+        }
+
+        /* in either case, bail if we can't get the memory */
+        if (vector == NULL) {
+            fputs("abort: unable to allocate enough memory\n", stderr);
+            cleanup();
+            exit(1);
+        }
+
+        /* install the new vector */
+        done[index].len = length;
+        done[index].vec = vector;
+    }
+
+    /* set the bit */
+    done[index].vec[offset] |= bit;
+    return 0;
+}
+
+/* Examine all possible codes from the given node (syms, len, left).  Compute
+   the amount of memory required to build inflate's decoding tables, where the
+   number of code structures used so far is mem, and the number remaining in
+   the current sub-table is rem.  Uses the globals max, code, root, large, and
+   done. */
+local void examine(int syms, int len, int left, int mem, int rem)
+{
+    int least;          /* least number of syms to use at this juncture */
+    int most;           /* most number of syms to use at this juncture */
+    int use;            /* number of bit patterns to use in next call */
+
+    /* see if we have a complete code */
+    if (syms == left) {
+        /* set the last code entry */
+        code[len] = left;
+
+        /* complete computation of memory used by this code */
+        while (rem < left) {
+            left -= rem;
+            rem = 1 << (len - root);
+            mem += rem;
+        }
+        assert(rem == left);
+
+        /* if this is a new maximum, show the entries used and the sub-code */
+        if (mem > large) {
+            large = mem;
+            printf("max %d: ", mem);
+            for (use = root + 1; use <= max; use++)
+                if (code[use])
+                    printf("%d[%d] ", code[use], use);
+            putchar('\n');
+            fflush(stdout);
+        }
+
+        /* remove entries as we drop back down in the recursion */
+        code[len] = 0;
+        return;
+    }
+
+    /* prune the tree if we can */
+    if (beenhere(syms, len, left, mem, rem))
+        return;
+
+    /* we need to use at least this many bit patterns so that the code won't be
+       incomplete at the next length (more bit patterns than symbols) */
+    least = (left << 1) - syms;
+    if (least < 0)
+        least = 0;
+
+    /* we can use at most this many bit patterns, lest there not be enough
+       available for the remaining symbols at the maximum length (if there were
+       no limit to the code length, this would become: most = left - 1) */
+    most = (((code_t)left << (max - len)) - syms) /
+            (((code_t)1 << (max - len)) - 1);
+
+    /* occupy least table spaces, creating new sub-tables as needed */
+    use = least;
+    while (rem < use) {
+        use -= rem;
+        rem = 1 << (len - root);
+        mem += rem;
+    }
+    rem -= use;
+
+    /* examine codes from here, updating table space as we go */
+    for (use = least; use <= most; use++) {
+        code[len] = use;
+        examine(syms - use, len + 1, (left - use) << 1,
+                mem + (rem ? 1 << (len - root) : 0), rem << 1);
+        if (rem == 0) {
+            rem = 1 << (len - root);
+            mem += rem;
+        }
+        rem--;
+    }
+
+    /* remove entries as we drop back down in the recursion */
+    code[len] = 0;
+}
+
+/* Look at all sub-codes starting with root + 1 bits.  Look at only the valid
+   intermediate code states (syms, left, len).  For each completed code,
+   calculate the amount of memory required by inflate to build the decoding
+   tables. Find the maximum amount of memory required and show the code that
+   requires that maximum.  Uses the globals max, root, and num. */
+local void enough(int syms)
+{
+    int n;              /* number of remaing symbols for this node */
+    int left;           /* number of unused bit patterns at this length */
+    size_t index;       /* index of this case in *num */
+
+    /* clear code */
+    for (n = 0; n <= max; n++)
+        code[n] = 0;
+
+    /* look at all (root + 1) bit and longer codes */
+    large = 1 << root;              /* base table */
+    if (root < max)                 /* otherwise, there's only a base table */
+        for (n = 3; n <= syms; n++)
+            for (left = 2; left < n; left += 2)
+            {
+                /* look at all reachable (root + 1) bit nodes, and the
+                   resulting codes (complete at root + 2 or more) */
+                index = INDEX(n, left, root + 1);
+                if (root + 1 < max && num[index])       /* reachable node */
+                    examine(n, root + 1, left, 1 << root, 0);
+
+                /* also look at root bit codes with completions at root + 1
+                   bits (not saved in num, since complete), just in case */
+                if (num[index - 1] && n <= left << 1)
+                    examine((n - left) << 1, root + 1, (n - left) << 1,
+                            1 << root, 0);
+            }
+
+    /* done */
+    printf("done: maximum of %d table entries\n", large);
+}
+
+/*
+   Examine and show the total number of possible Huffman codes for a given
+   maximum number of symbols, initial root table size, and maximum code length
+   in bits -- those are the command arguments in that order.  The default
+   values are 286, 9, and 15 respectively, for the deflate literal/length code.
+   The possible codes are counted for each number of coded symbols from two to
+   the maximum.  The counts for each of those and the total number of codes are
+   shown.  The maximum number of inflate table entires is then calculated
+   across all possible codes.  Each new maximum number of table entries and the
+   associated sub-code (starting at root + 1 == 10 bits) is shown.
+
+   To count and examine Huffman codes that are not length-limited, provide a
+   maximum length equal to the number of symbols minus one.
+
+   For the deflate literal/length code, use "enough".  For the deflate distance
+   code, use "enough 30 6".
+
+   This uses the %llu printf format to print big_t numbers, which assumes that
+   big_t is an unsigned long long.  If the big_t type is changed (for example
+   to a multiple precision type), the method of printing will also need to be
+   updated.
+ */
+int main(int argc, char **argv)
+{
+    int syms;           /* total number of symbols to code */
+    int n;              /* number of symbols to code for this run */
+    big_t got;          /* return value of count() */
+    big_t sum;          /* accumulated number of codes over n */
+
+    /* set up globals for cleanup() */
+    code = NULL;
+    num = NULL;
+    done = NULL;
+
+    /* get arguments -- default to the deflate literal/length code */
+    syms = 286;
+        root = 9;
+    max = 15;
+    if (argc > 1) {
+        syms = atoi(argv[1]);
+        if (argc > 2) {
+            root = atoi(argv[2]);
+                        if (argc > 3)
+                                max = atoi(argv[3]);
+                }
+    }
+    if (argc > 4 || syms < 2 || root < 1 || max < 1) {
+        fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n",
+                          stderr);
+        return 1;
+    }
+
+    /* if not restricting the code length, the longest is syms - 1 */
+    if (max > syms - 1)
+        max = syms - 1;
+
+    /* determine the number of bits in a code_t */
+    n = 0;
+    while (((code_t)1 << n) != 0)
+        n++;
+
+    /* make sure that the calculation of most will not overflow */
+    if (max > n || syms - 2 >= (((code_t)0 - 1) >> (max - 1))) {
+        fputs("abort: code length too long for internal types\n", stderr);
+        return 1;
+    }
+
+    /* reject impossible code requests */
+    if (syms - 1 > ((code_t)1 << max) - 1) {
+        fprintf(stderr, "%d symbols cannot be coded in %d bits\n",
+                syms, max);
+        return 1;
+    }
+
+    /* allocate code vector */
+    code = calloc(max + 1, sizeof(int));
+    if (code == NULL) {
+        fputs("abort: unable to allocate enough memory\n", stderr);
+        return 1;
+    }
+
+    /* determine size of saved results array, checking for overflows,
+       allocate and clear the array (set all to zero with calloc()) */
+    if (syms == 2)              /* iff max == 1 */
+        num = NULL;             /* won't be saving any results */
+    else {
+        size = syms >> 1;
+        if (size > ((size_t)0 - 1) / (n = (syms - 1) >> 1) ||
+                (size *= n, size > ((size_t)0 - 1) / (n = max - 1)) ||
+                (size *= n, size > ((size_t)0 - 1) / sizeof(big_t)) ||
+                (num = calloc(size, sizeof(big_t))) == NULL) {
+            fputs("abort: unable to allocate enough memory\n", stderr);
+            cleanup();
+            return 1;
+        }
+    }
+
+    /* count possible codes for all numbers of symbols, add up counts */
+    sum = 0;
+    for (n = 2; n <= syms; n++) {
+        got = count(n, 1, 2);
+        sum += got;
+        if (got == -1 || sum < got) {       /* overflow */
+            fputs("abort: can't count that high!\n", stderr);
+            cleanup();
+            return 1;
+        }
+        printf("%llu %d-codes\n", got, n);
+    }
+    printf("%llu total codes for 2 to %d symbols", sum, syms);
+    if (max < syms - 1)
+        printf(" (%d-bit length limit)\n", max);
+    else
+        puts(" (no length limit)");
+
+    /* allocate and clear done array for beenhere() */
+    if (syms == 2)
+        done = NULL;
+    else if (size > ((size_t)0 - 1) / sizeof(struct tab) ||
+             (done = calloc(size, sizeof(struct tab))) == NULL) {
+        fputs("abort: unable to allocate enough memory\n", stderr);
+        cleanup();
+        return 1;
+    }
+
+    /* find and show maximum inflate table usage */
+        if (root > max)                 /* reduce root to max length */
+                root = max;
+    if (syms < ((code_t)1 << (root + 1)))
+        enough(syms);
+    else
+        puts("cannot handle minimum code lengths > root");
+
+    /* done */
+    cleanup();
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/fitblk.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/fitblk.c
new file mode 100644 (file)
index 0000000..c61de5c
--- /dev/null
@@ -0,0 +1,233 @@
+/* fitblk.c: example of fitting compressed output to a specified size
+   Not copyrighted -- provided to the public domain
+   Version 1.1  25 November 2004  Mark Adler */
+
+/* Version history:
+   1.0  24 Nov 2004  First version
+   1.1  25 Nov 2004  Change deflateInit2() to deflateInit()
+                     Use fixed-size, stack-allocated raw buffers
+                     Simplify code moving compression to subroutines
+                     Use assert() for internal errors
+                     Add detailed description of approach
+ */
+
+/* Approach to just fitting a requested compressed size:
+
+   fitblk performs three compression passes on a portion of the input
+   data in order to determine how much of that input will compress to
+   nearly the requested output block size.  The first pass generates
+   enough deflate blocks to produce output to fill the requested
+   output size plus a specfied excess amount (see the EXCESS define
+   below).  The last deflate block may go quite a bit past that, but
+   is discarded.  The second pass decompresses and recompresses just
+   the compressed data that fit in the requested plus excess sized
+   buffer.  The deflate process is terminated after that amount of
+   input, which is less than the amount consumed on the first pass.
+   The last deflate block of the result will be of a comparable size
+   to the final product, so that the header for that deflate block and
+   the compression ratio for that block will be about the same as in
+   the final product.  The third compression pass decompresses the
+   result of the second step, but only the compressed data up to the
+   requested size minus an amount to allow the compressed stream to
+   complete (see the MARGIN define below).  That will result in a
+   final compressed stream whose length is less than or equal to the
+   requested size.  Assuming sufficient input and a requested size
+   greater than a few hundred bytes, the shortfall will typically be
+   less than ten bytes.
+
+   If the input is short enough that the first compression completes
+   before filling the requested output size, then that compressed
+   stream is return with no recompression.
+
+   EXCESS is chosen to be just greater than the shortfall seen in a
+   two pass approach similar to the above.  That shortfall is due to
+   the last deflate block compressing more efficiently with a smaller
+   header on the second pass.  EXCESS is set to be large enough so
+   that there is enough uncompressed data for the second pass to fill
+   out the requested size, and small enough so that the final deflate
+   block of the second pass will be close in size to the final deflate
+   block of the third and final pass.  MARGIN is chosen to be just
+   large enough to assure that the final compression has enough room
+   to complete in all cases.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include "zlib.h"
+
+#define local static
+
+/* print nastygram and leave */
+local void quit(char *why)
+{
+    fprintf(stderr, "fitblk abort: %s\n", why);
+    exit(1);
+}
+
+#define RAWLEN 4096    /* intermediate uncompressed buffer size */
+
+/* compress from file to def until provided buffer is full or end of
+   input reached; return last deflate() return value, or Z_ERRNO if
+   there was read error on the file */
+local int partcompress(FILE *in, z_streamp def)
+{
+    int ret, flush;
+    unsigned char raw[RAWLEN];
+
+    flush = Z_NO_FLUSH;
+    do {
+        def->avail_in = fread(raw, 1, RAWLEN, in);
+        if (ferror(in))
+            return Z_ERRNO;
+        def->next_in = raw;
+        if (feof(in))
+            flush = Z_FINISH;
+        ret = deflate(def, flush);
+        assert(ret != Z_STREAM_ERROR);
+    } while (def->avail_out != 0 && flush == Z_NO_FLUSH);
+    return ret;
+}
+
+/* recompress from inf's input to def's output; the input for inf and
+   the output for def are set in those structures before calling;
+   return last deflate() return value, or Z_MEM_ERROR if inflate()
+   was not able to allocate enough memory when it needed to */
+local int recompress(z_streamp inf, z_streamp def)
+{
+    int ret, flush;
+    unsigned char raw[RAWLEN];
+
+    flush = Z_NO_FLUSH;
+    do {
+        /* decompress */
+        inf->avail_out = RAWLEN;
+        inf->next_out = raw;
+        ret = inflate(inf, Z_NO_FLUSH);
+        assert(ret != Z_STREAM_ERROR && ret != Z_DATA_ERROR &&
+               ret != Z_NEED_DICT);
+        if (ret == Z_MEM_ERROR)
+            return ret;
+
+        /* compress what was decompresed until done or no room */
+        def->avail_in = RAWLEN - inf->avail_out;
+        def->next_in = raw;
+        if (inf->avail_out != 0)
+            flush = Z_FINISH;
+        ret = deflate(def, flush);
+        assert(ret != Z_STREAM_ERROR);
+    } while (ret != Z_STREAM_END && def->avail_out != 0);
+    return ret;
+}
+
+#define EXCESS 256      /* empirically determined stream overage */
+#define MARGIN 8        /* amount to back off for completion */
+
+/* compress from stdin to fixed-size block on stdout */
+int main(int argc, char **argv)
+{
+    int ret;                /* return code */
+    unsigned size;          /* requested fixed output block size */
+    unsigned have;          /* bytes written by deflate() call */
+    unsigned char *blk;     /* intermediate and final stream */
+    unsigned char *tmp;     /* close to desired size stream */
+    z_stream def, inf;      /* zlib deflate and inflate states */
+
+    /* get requested output size */
+    if (argc != 2)
+        quit("need one argument: size of output block");
+    ret = strtol(argv[1], argv + 1, 10);
+    if (argv[1][0] != 0)
+        quit("argument must be a number");
+    if (ret < 8)            /* 8 is minimum zlib stream size */
+        quit("need positive size of 8 or greater");
+    size = (unsigned)ret;
+
+    /* allocate memory for buffers and compression engine */
+    blk = malloc(size + EXCESS);
+    def.zalloc = Z_NULL;
+    def.zfree = Z_NULL;
+    def.opaque = Z_NULL;
+    ret = deflateInit(&def, Z_DEFAULT_COMPRESSION);
+    if (ret != Z_OK || blk == NULL)
+        quit("out of memory");
+
+    /* compress from stdin until output full, or no more input */
+    def.avail_out = size + EXCESS;
+    def.next_out = blk;
+    ret = partcompress(stdin, &def);
+    if (ret == Z_ERRNO)
+        quit("error reading input");
+
+    /* if it all fit, then size was undersubscribed -- done! */
+    if (ret == Z_STREAM_END && def.avail_out >= EXCESS) {
+        /* write block to stdout */
+        have = size + EXCESS - def.avail_out;
+        if (fwrite(blk, 1, have, stdout) != have || ferror(stdout))
+            quit("error writing output");
+
+        /* clean up and print results to stderr */
+        ret = deflateEnd(&def);
+        assert(ret != Z_STREAM_ERROR);
+        free(blk);
+        fprintf(stderr,
+                "%u bytes unused out of %u requested (all input)\n",
+                size - have, size);
+        return 0;
+    }
+
+    /* it didn't all fit -- set up for recompression */
+    inf.zalloc = Z_NULL;
+    inf.zfree = Z_NULL;
+    inf.opaque = Z_NULL;
+    inf.avail_in = 0;
+    inf.next_in = Z_NULL;
+    ret = inflateInit(&inf);
+    tmp = malloc(size + EXCESS);
+    if (ret != Z_OK || tmp == NULL)
+        quit("out of memory");
+    ret = deflateReset(&def);
+    assert(ret != Z_STREAM_ERROR);
+
+    /* do first recompression close to the right amount */
+    inf.avail_in = size + EXCESS;
+    inf.next_in = blk;
+    def.avail_out = size + EXCESS;
+    def.next_out = tmp;
+    ret = recompress(&inf, &def);
+    if (ret == Z_MEM_ERROR)
+        quit("out of memory");
+
+    /* set up for next reocmpression */
+    ret = inflateReset(&inf);
+    assert(ret != Z_STREAM_ERROR);
+    ret = deflateReset(&def);
+    assert(ret != Z_STREAM_ERROR);
+
+    /* do second and final recompression (third compression) */
+    inf.avail_in = size - MARGIN;   /* assure stream will complete */
+    inf.next_in = tmp;
+    def.avail_out = size;
+    def.next_out = blk;
+    ret = recompress(&inf, &def);
+    if (ret == Z_MEM_ERROR)
+        quit("out of memory");
+    assert(ret == Z_STREAM_END);    /* otherwise MARGIN too small */
+
+    /* done -- write block to stdout */
+    have = size - def.avail_out;
+    if (fwrite(blk, 1, have, stdout) != have || ferror(stdout))
+        quit("error writing output");
+
+    /* clean up and print results to stderr */
+    free(tmp);
+    ret = inflateEnd(&inf);
+    assert(ret != Z_STREAM_ERROR);
+    ret = deflateEnd(&def);
+    assert(ret != Z_STREAM_ERROR);
+    free(blk);
+    fprintf(stderr,
+            "%u bytes unused out of %u requested (%lu input)\n",
+            size - have, size, def.total_in);
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gun.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gun.c
new file mode 100644 (file)
index 0000000..72b0882
--- /dev/null
@@ -0,0 +1,701 @@
+/* gun.c -- simple gunzip to give an example of the use of inflateBack()
+ * Copyright (C) 2003, 2005, 2008, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+   Version 1.6  17 January 2010  Mark Adler */
+
+/* Version history:
+   1.0  16 Feb 2003  First version for testing of inflateBack()
+   1.1  21 Feb 2005  Decompress concatenated gzip streams
+                     Remove use of "this" variable (C++ keyword)
+                     Fix return value for in()
+                     Improve allocation failure checking
+                     Add typecasting for void * structures
+                     Add -h option for command version and usage
+                     Add a bunch of comments
+   1.2  20 Mar 2005  Add Unix compress (LZW) decompression
+                     Copy file attributes from input file to output file
+   1.3  12 Jun 2005  Add casts for error messages [Oberhumer]
+   1.4   8 Dec 2006  LZW decompression speed improvements
+   1.5   9 Feb 2008  Avoid warning in latest version of gcc
+   1.6  17 Jan 2010  Avoid signed/unsigned comparison warnings
+ */
+
+/*
+   gun [ -t ] [ name ... ]
+
+   decompresses the data in the named gzip files.  If no arguments are given,
+   gun will decompress from stdin to stdout.  The names must end in .gz, -gz,
+   .z, -z, _z, or .Z.  The uncompressed data will be written to a file name
+   with the suffix stripped.  On success, the original file is deleted.  On
+   failure, the output file is deleted.  For most failures, the command will
+   continue to process the remaining names on the command line.  A memory
+   allocation failure will abort the command.  If -t is specified, then the
+   listed files or stdin will be tested as gzip files for integrity (without
+   checking for a proper suffix), no output will be written, and no files
+   will be deleted.
+
+   Like gzip, gun allows concatenated gzip streams and will decompress them,
+   writing all of the uncompressed data to the output.  Unlike gzip, gun allows
+   an empty file on input, and will produce no error writing an empty output
+   file.
+
+   gun will also decompress files made by Unix compress, which uses LZW
+   compression.  These files are automatically detected by virtue of their
+   magic header bytes.  Since the end of Unix compress stream is marked by the
+   end-of-file, they cannot be concantenated.  If a Unix compress stream is
+   encountered in an input file, it is the last stream in that file.
+
+   Like gunzip and uncompress, the file attributes of the orignal compressed
+   file are maintained in the final uncompressed file, to the extent that the
+   user permissions allow it.
+
+   On my Mac OS X PowerPC G4, gun is almost twice as fast as gunzip (version
+   1.2.4) is on the same file, when gun is linked with zlib 1.2.2.  Also the
+   LZW decompression provided by gun is about twice as fast as the standard
+   Unix uncompress command.
+ */
+
+/* external functions and related types and constants */
+#include <stdio.h>          /* fprintf() */
+#include <stdlib.h>         /* malloc(), free() */
+#include <string.h>         /* strerror(), strcmp(), strlen(), memcpy() */
+#include <errno.h>          /* errno */
+#include <fcntl.h>          /* open() */
+#include <unistd.h>         /* read(), write(), close(), chown(), unlink() */
+#include <sys/types.h>
+#include <sys/stat.h>       /* stat(), chmod() */
+#include <utime.h>          /* utime() */
+#include "zlib.h"           /* inflateBackInit(), inflateBack(), */
+                            /* inflateBackEnd(), crc32() */
+
+/* function declaration */
+#define local static
+
+/* buffer constants */
+#define SIZE 32768U         /* input and output buffer sizes */
+#define PIECE 16384         /* limits i/o chunks for 16-bit int case */
+
+/* structure for infback() to pass to input function in() -- it maintains the
+   input file and a buffer of size SIZE */
+struct ind {
+    int infile;
+    unsigned char *inbuf;
+};
+
+/* Load input buffer, assumed to be empty, and return bytes loaded and a
+   pointer to them.  read() is called until the buffer is full, or until it
+   returns end-of-file or error.  Return 0 on error. */
+local unsigned in(void *in_desc, unsigned char **buf)
+{
+    int ret;
+    unsigned len;
+    unsigned char *next;
+    struct ind *me = (struct ind *)in_desc;
+
+    next = me->inbuf;
+    *buf = next;
+    len = 0;
+    do {
+        ret = PIECE;
+        if ((unsigned)ret > SIZE - len)
+            ret = (int)(SIZE - len);
+        ret = (int)read(me->infile, next, ret);
+        if (ret == -1) {
+            len = 0;
+            break;
+        }
+        next += ret;
+        len += ret;
+    } while (ret != 0 && len < SIZE);
+    return len;
+}
+
+/* structure for infback() to pass to output function out() -- it maintains the
+   output file, a running CRC-32 check on the output and the total number of
+   bytes output, both for checking against the gzip trailer.  (The length in
+   the gzip trailer is stored modulo 2^32, so it's ok if a long is 32 bits and
+   the output is greater than 4 GB.) */
+struct outd {
+    int outfile;
+    int check;                  /* true if checking crc and total */
+    unsigned long crc;
+    unsigned long total;
+};
+
+/* Write output buffer and update the CRC-32 and total bytes written.  write()
+   is called until all of the output is written or an error is encountered.
+   On success out() returns 0.  For a write failure, out() returns 1.  If the
+   output file descriptor is -1, then nothing is written.
+ */
+local int out(void *out_desc, unsigned char *buf, unsigned len)
+{
+    int ret;
+    struct outd *me = (struct outd *)out_desc;
+
+    if (me->check) {
+        me->crc = crc32(me->crc, buf, len);
+        me->total += len;
+    }
+    if (me->outfile != -1)
+        do {
+            ret = PIECE;
+            if ((unsigned)ret > len)
+                ret = (int)len;
+            ret = (int)write(me->outfile, buf, ret);
+            if (ret == -1)
+                return 1;
+            buf += ret;
+            len -= ret;
+        } while (len != 0);
+    return 0;
+}
+
+/* next input byte macro for use inside lunpipe() and gunpipe() */
+#define NEXT() (have ? 0 : (have = in(indp, &next)), \
+                last = have ? (have--, (int)(*next++)) : -1)
+
+/* memory for gunpipe() and lunpipe() --
+   the first 256 entries of prefix[] and suffix[] are never used, could
+   have offset the index, but it's faster to waste the memory */
+unsigned char inbuf[SIZE];              /* input buffer */
+unsigned char outbuf[SIZE];             /* output buffer */
+unsigned short prefix[65536];           /* index to LZW prefix string */
+unsigned char suffix[65536];            /* one-character LZW suffix */
+unsigned char match[65280 + 2];         /* buffer for reversed match or gzip
+                                           32K sliding window */
+
+/* throw out what's left in the current bits byte buffer (this is a vestigial
+   aspect of the compressed data format derived from an implementation that
+   made use of a special VAX machine instruction!) */
+#define FLUSHCODE() \
+    do { \
+        left = 0; \
+        rem = 0; \
+        if (chunk > have) { \
+            chunk -= have; \
+            have = 0; \
+            if (NEXT() == -1) \
+                break; \
+            chunk--; \
+            if (chunk > have) { \
+                chunk = have = 0; \
+                break; \
+            } \
+        } \
+        have -= chunk; \
+        next += chunk; \
+        chunk = 0; \
+    } while (0)
+
+/* Decompress a compress (LZW) file from indp to outfile.  The compress magic
+   header (two bytes) has already been read and verified.  There are have bytes
+   of buffered input at next.  strm is used for passing error information back
+   to gunpipe().
+
+   lunpipe() will return Z_OK on success, Z_BUF_ERROR for an unexpected end of
+   file, read error, or write error (a write error indicated by strm->next_in
+   not equal to Z_NULL), or Z_DATA_ERROR for invalid input.
+ */
+local int lunpipe(unsigned have, unsigned char *next, struct ind *indp,
+                  int outfile, z_stream *strm)
+{
+    int last;                   /* last byte read by NEXT(), or -1 if EOF */
+    unsigned chunk;             /* bytes left in current chunk */
+    int left;                   /* bits left in rem */
+    unsigned rem;               /* unused bits from input */
+    int bits;                   /* current bits per code */
+    unsigned code;              /* code, table traversal index */
+    unsigned mask;              /* mask for current bits codes */
+    int max;                    /* maximum bits per code for this stream */
+    unsigned flags;             /* compress flags, then block compress flag */
+    unsigned end;               /* last valid entry in prefix/suffix tables */
+    unsigned temp;              /* current code */
+    unsigned prev;              /* previous code */
+    unsigned final;             /* last character written for previous code */
+    unsigned stack;             /* next position for reversed string */
+    unsigned outcnt;            /* bytes in output buffer */
+    struct outd outd;           /* output structure */
+    unsigned char *p;
+
+    /* set up output */
+    outd.outfile = outfile;
+    outd.check = 0;
+
+    /* process remainder of compress header -- a flags byte */
+    flags = NEXT();
+    if (last == -1)
+        return Z_BUF_ERROR;
+    if (flags & 0x60) {
+        strm->msg = (char *)"unknown lzw flags set";
+        return Z_DATA_ERROR;
+    }
+    max = flags & 0x1f;
+    if (max < 9 || max > 16) {
+        strm->msg = (char *)"lzw bits out of range";
+        return Z_DATA_ERROR;
+    }
+    if (max == 9)                           /* 9 doesn't really mean 9 */
+        max = 10;
+    flags &= 0x80;                          /* true if block compress */
+
+    /* clear table */
+    bits = 9;
+    mask = 0x1ff;
+    end = flags ? 256 : 255;
+
+    /* set up: get first 9-bit code, which is the first decompressed byte, but
+       don't create a table entry until the next code */
+    if (NEXT() == -1)                       /* no compressed data is ok */
+        return Z_OK;
+    final = prev = (unsigned)last;          /* low 8 bits of code */
+    if (NEXT() == -1)                       /* missing a bit */
+        return Z_BUF_ERROR;
+    if (last & 1) {                         /* code must be < 256 */
+        strm->msg = (char *)"invalid lzw code";
+        return Z_DATA_ERROR;
+    }
+    rem = (unsigned)last >> 1;              /* remaining 7 bits */
+    left = 7;
+    chunk = bits - 2;                       /* 7 bytes left in this chunk */
+    outbuf[0] = (unsigned char)final;       /* write first decompressed byte */
+    outcnt = 1;
+
+    /* decode codes */
+    stack = 0;
+    for (;;) {
+        /* if the table will be full after this, increment the code size */
+        if (end >= mask && bits < max) {
+            FLUSHCODE();
+            bits++;
+            mask <<= 1;
+            mask++;
+        }
+
+        /* get a code of length bits */
+        if (chunk == 0)                     /* decrement chunk modulo bits */
+            chunk = bits;
+        code = rem;                         /* low bits of code */
+        if (NEXT() == -1) {                 /* EOF is end of compressed data */
+            /* write remaining buffered output */
+            if (outcnt && out(&outd, outbuf, outcnt)) {
+                strm->next_in = outbuf;     /* signal write error */
+                return Z_BUF_ERROR;
+            }
+            return Z_OK;
+        }
+        code += (unsigned)last << left;     /* middle (or high) bits of code */
+        left += 8;
+        chunk--;
+        if (bits > left) {                  /* need more bits */
+            if (NEXT() == -1)               /* can't end in middle of code */
+                return Z_BUF_ERROR;
+            code += (unsigned)last << left; /* high bits of code */
+            left += 8;
+            chunk--;
+        }
+        code &= mask;                       /* mask to current code length */
+        left -= bits;                       /* number of unused bits */
+        rem = (unsigned)last >> (8 - left); /* unused bits from last byte */
+
+        /* process clear code (256) */
+        if (code == 256 && flags) {
+            FLUSHCODE();
+            bits = 9;                       /* initialize bits and mask */
+            mask = 0x1ff;
+            end = 255;                      /* empty table */
+            continue;                       /* get next code */
+        }
+
+        /* special code to reuse last match */
+        temp = code;                        /* save the current code */
+        if (code > end) {
+            /* Be picky on the allowed code here, and make sure that the code
+               we drop through (prev) will be a valid index so that random
+               input does not cause an exception.  The code != end + 1 check is
+               empirically derived, and not checked in the original uncompress
+               code.  If this ever causes a problem, that check could be safely
+               removed.  Leaving this check in greatly improves gun's ability
+               to detect random or corrupted input after a compress header.
+               In any case, the prev > end check must be retained. */
+            if (code != end + 1 || prev > end) {
+                strm->msg = (char *)"invalid lzw code";
+                return Z_DATA_ERROR;
+            }
+            match[stack++] = (unsigned char)final;
+            code = prev;
+        }
+
+        /* walk through linked list to generate output in reverse order */
+        p = match + stack;
+        while (code >= 256) {
+            *p++ = suffix[code];
+            code = prefix[code];
+        }
+        stack = p - match;
+        match[stack++] = (unsigned char)code;
+        final = code;
+
+        /* link new table entry */
+        if (end < mask) {
+            end++;
+            prefix[end] = (unsigned short)prev;
+            suffix[end] = (unsigned char)final;
+        }
+
+        /* set previous code for next iteration */
+        prev = temp;
+
+        /* write output in forward order */
+        while (stack > SIZE - outcnt) {
+            while (outcnt < SIZE)
+                outbuf[outcnt++] = match[--stack];
+            if (out(&outd, outbuf, outcnt)) {
+                strm->next_in = outbuf; /* signal write error */
+                return Z_BUF_ERROR;
+            }
+            outcnt = 0;
+        }
+        p = match + stack;
+        do {
+            outbuf[outcnt++] = *--p;
+        } while (p > match);
+        stack = 0;
+
+        /* loop for next code with final and prev as the last match, rem and
+           left provide the first 0..7 bits of the next code, end is the last
+           valid table entry */
+    }
+}
+
+/* Decompress a gzip file from infile to outfile.  strm is assumed to have been
+   successfully initialized with inflateBackInit().  The input file may consist
+   of a series of gzip streams, in which case all of them will be decompressed
+   to the output file.  If outfile is -1, then the gzip stream(s) integrity is
+   checked and nothing is written.
+
+   The return value is a zlib error code: Z_MEM_ERROR if out of memory,
+   Z_DATA_ERROR if the header or the compressed data is invalid, or if the
+   trailer CRC-32 check or length doesn't match, Z_BUF_ERROR if the input ends
+   prematurely or a write error occurs, or Z_ERRNO if junk (not a another gzip
+   stream) follows a valid gzip stream.
+ */
+local int gunpipe(z_stream *strm, int infile, int outfile)
+{
+    int ret, first, last;
+    unsigned have, flags, len;
+    unsigned char *next = NULL;
+    struct ind ind, *indp;
+    struct outd outd;
+
+    /* setup input buffer */
+    ind.infile = infile;
+    ind.inbuf = inbuf;
+    indp = &ind;
+
+    /* decompress concatenated gzip streams */
+    have = 0;                               /* no input data read in yet */
+    first = 1;                              /* looking for first gzip header */
+    strm->next_in = Z_NULL;                 /* so Z_BUF_ERROR means EOF */
+    for (;;) {
+        /* look for the two magic header bytes for a gzip stream */
+        if (NEXT() == -1) {
+            ret = Z_OK;
+            break;                          /* empty gzip stream is ok */
+        }
+        if (last != 31 || (NEXT() != 139 && last != 157)) {
+            strm->msg = (char *)"incorrect header check";
+            ret = first ? Z_DATA_ERROR : Z_ERRNO;
+            break;                          /* not a gzip or compress header */
+        }
+        first = 0;                          /* next non-header is junk */
+
+        /* process a compress (LZW) file -- can't be concatenated after this */
+        if (last == 157) {
+            ret = lunpipe(have, next, indp, outfile, strm);
+            break;
+        }
+
+        /* process remainder of gzip header */
+        ret = Z_BUF_ERROR;
+        if (NEXT() != 8) {                  /* only deflate method allowed */
+            if (last == -1) break;
+            strm->msg = (char *)"unknown compression method";
+            ret = Z_DATA_ERROR;
+            break;
+        }
+        flags = NEXT();                     /* header flags */
+        NEXT();                             /* discard mod time, xflgs, os */
+        NEXT();
+        NEXT();
+        NEXT();
+        NEXT();
+        NEXT();
+        if (last == -1) break;
+        if (flags & 0xe0) {
+            strm->msg = (char *)"unknown header flags set";
+            ret = Z_DATA_ERROR;
+            break;
+        }
+        if (flags & 4) {                    /* extra field */
+            len = NEXT();
+            len += (unsigned)(NEXT()) << 8;
+            if (last == -1) break;
+            while (len > have) {
+                len -= have;
+                have = 0;
+                if (NEXT() == -1) break;
+                len--;
+            }
+            if (last == -1) break;
+            have -= len;
+            next += len;
+        }
+        if (flags & 8)                      /* file name */
+            while (NEXT() != 0 && last != -1)
+                ;
+        if (flags & 16)                     /* comment */
+            while (NEXT() != 0 && last != -1)
+                ;
+        if (flags & 2) {                    /* header crc */
+            NEXT();
+            NEXT();
+        }
+        if (last == -1) break;
+
+        /* set up output */
+        outd.outfile = outfile;
+        outd.check = 1;
+        outd.crc = crc32(0L, Z_NULL, 0);
+        outd.total = 0;
+
+        /* decompress data to output */
+        strm->next_in = next;
+        strm->avail_in = have;
+        ret = inflateBack(strm, in, indp, out, &outd);
+        if (ret != Z_STREAM_END) break;
+        next = strm->next_in;
+        have = strm->avail_in;
+        strm->next_in = Z_NULL;             /* so Z_BUF_ERROR means EOF */
+
+        /* check trailer */
+        ret = Z_BUF_ERROR;
+        if (NEXT() != (int)(outd.crc & 0xff) ||
+            NEXT() != (int)((outd.crc >> 8) & 0xff) ||
+            NEXT() != (int)((outd.crc >> 16) & 0xff) ||
+            NEXT() != (int)((outd.crc >> 24) & 0xff)) {
+            /* crc error */
+            if (last != -1) {
+                strm->msg = (char *)"incorrect data check";
+                ret = Z_DATA_ERROR;
+            }
+            break;
+        }
+        if (NEXT() != (int)(outd.total & 0xff) ||
+            NEXT() != (int)((outd.total >> 8) & 0xff) ||
+            NEXT() != (int)((outd.total >> 16) & 0xff) ||
+            NEXT() != (int)((outd.total >> 24) & 0xff)) {
+            /* length error */
+            if (last != -1) {
+                strm->msg = (char *)"incorrect length check";
+                ret = Z_DATA_ERROR;
+            }
+            break;
+        }
+
+        /* go back and look for another gzip stream */
+    }
+
+    /* clean up and return */
+    return ret;
+}
+
+/* Copy file attributes, from -> to, as best we can.  This is best effort, so
+   no errors are reported.  The mode bits, including suid, sgid, and the sticky
+   bit are copied (if allowed), the owner's user id and group id are copied
+   (again if allowed), and the access and modify times are copied. */
+local void copymeta(char *from, char *to)
+{
+    struct stat was;
+    struct utimbuf when;
+
+    /* get all of from's Unix meta data, return if not a regular file */
+    if (stat(from, &was) != 0 || (was.st_mode & S_IFMT) != S_IFREG)
+        return;
+
+    /* set to's mode bits, ignore errors */
+    (void)chmod(to, was.st_mode & 07777);
+
+    /* copy owner's user and group, ignore errors */
+    (void)chown(to, was.st_uid, was.st_gid);
+
+    /* copy access and modify times, ignore errors */
+    when.actime = was.st_atime;
+    when.modtime = was.st_mtime;
+    (void)utime(to, &when);
+}
+
+/* Decompress the file inname to the file outnname, of if test is true, just
+   decompress without writing and check the gzip trailer for integrity.  If
+   inname is NULL or an empty string, read from stdin.  If outname is NULL or
+   an empty string, write to stdout.  strm is a pre-initialized inflateBack
+   structure.  When appropriate, copy the file attributes from inname to
+   outname.
+
+   gunzip() returns 1 if there is an out-of-memory error or an unexpected
+   return code from gunpipe().  Otherwise it returns 0.
+ */
+local int gunzip(z_stream *strm, char *inname, char *outname, int test)
+{
+    int ret;
+    int infile, outfile;
+
+    /* open files */
+    if (inname == NULL || *inname == 0) {
+        inname = "-";
+        infile = 0;     /* stdin */
+    }
+    else {
+        infile = open(inname, O_RDONLY, 0);
+        if (infile == -1) {
+            fprintf(stderr, "gun cannot open %s\n", inname);
+            return 0;
+        }
+    }
+    if (test)
+        outfile = -1;
+    else if (outname == NULL || *outname == 0) {
+        outname = "-";
+        outfile = 1;    /* stdout */
+    }
+    else {
+        outfile = open(outname, O_CREAT | O_TRUNC | O_WRONLY, 0666);
+        if (outfile == -1) {
+            close(infile);
+            fprintf(stderr, "gun cannot create %s\n", outname);
+            return 0;
+        }
+    }
+    errno = 0;
+
+    /* decompress */
+    ret = gunpipe(strm, infile, outfile);
+    if (outfile > 2) close(outfile);
+    if (infile > 2) close(infile);
+
+    /* interpret result */
+    switch (ret) {
+    case Z_OK:
+    case Z_ERRNO:
+        if (infile > 2 && outfile > 2) {
+            copymeta(inname, outname);          /* copy attributes */
+            unlink(inname);
+        }
+        if (ret == Z_ERRNO)
+            fprintf(stderr, "gun warning: trailing garbage ignored in %s\n",
+                    inname);
+        break;
+    case Z_DATA_ERROR:
+        if (outfile > 2) unlink(outname);
+        fprintf(stderr, "gun data error on %s: %s\n", inname, strm->msg);
+        break;
+    case Z_MEM_ERROR:
+        if (outfile > 2) unlink(outname);
+        fprintf(stderr, "gun out of memory error--aborting\n");
+        return 1;
+    case Z_BUF_ERROR:
+        if (outfile > 2) unlink(outname);
+        if (strm->next_in != Z_NULL) {
+            fprintf(stderr, "gun write error on %s: %s\n",
+                    outname, strerror(errno));
+        }
+        else if (errno) {
+            fprintf(stderr, "gun read error on %s: %s\n",
+                    inname, strerror(errno));
+        }
+        else {
+            fprintf(stderr, "gun unexpected end of file on %s\n",
+                    inname);
+        }
+        break;
+    default:
+        if (outfile > 2) unlink(outname);
+        fprintf(stderr, "gun internal error--aborting\n");
+        return 1;
+    }
+    return 0;
+}
+
+/* Process the gun command line arguments.  See the command syntax near the
+   beginning of this source file. */
+int main(int argc, char **argv)
+{
+    int ret, len, test;
+    char *outname;
+    unsigned char *window;
+    z_stream strm;
+
+    /* initialize inflateBack state for repeated use */
+    window = match;                         /* reuse LZW match buffer */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    ret = inflateBackInit(&strm, 15, window);
+    if (ret != Z_OK) {
+        fprintf(stderr, "gun out of memory error--aborting\n");
+        return 1;
+    }
+
+    /* decompress each file to the same name with the suffix removed */
+    argc--;
+    argv++;
+    test = 0;
+    if (argc && strcmp(*argv, "-h") == 0) {
+        fprintf(stderr, "gun 1.6 (17 Jan 2010)\n");
+        fprintf(stderr, "Copyright (C) 2003-2010 Mark Adler\n");
+        fprintf(stderr, "usage: gun [-t] [file1.gz [file2.Z ...]]\n");
+        return 0;
+    }
+    if (argc && strcmp(*argv, "-t") == 0) {
+        test = 1;
+        argc--;
+        argv++;
+    }
+    if (argc)
+        do {
+            if (test)
+                outname = NULL;
+            else {
+                len = (int)strlen(*argv);
+                if (strcmp(*argv + len - 3, ".gz") == 0 ||
+                    strcmp(*argv + len - 3, "-gz") == 0)
+                    len -= 3;
+                else if (strcmp(*argv + len - 2, ".z") == 0 ||
+                    strcmp(*argv + len - 2, "-z") == 0 ||
+                    strcmp(*argv + len - 2, "_z") == 0 ||
+                    strcmp(*argv + len - 2, ".Z") == 0)
+                    len -= 2;
+                else {
+                    fprintf(stderr, "gun error: no gz type on %s--skipping\n",
+                            *argv);
+                    continue;
+                }
+                outname = malloc(len + 1);
+                if (outname == NULL) {
+                    fprintf(stderr, "gun out of memory error--aborting\n");
+                    ret = 1;
+                    break;
+                }
+                memcpy(outname, *argv, len);
+                outname[len] = 0;
+            }
+            ret = gunzip(&strm, *argv, outname, test);
+            if (outname != NULL) free(outname);
+            if (ret) break;
+        } while (argv++, --argc);
+    else
+        ret = gunzip(&strm, NULL, NULL, test);
+
+    /* clean up */
+    inflateBackEnd(&strm);
+    return ret;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzappend.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzappend.c
new file mode 100644 (file)
index 0000000..e9e878e
--- /dev/null
@@ -0,0 +1,500 @@
+/* gzappend -- command to append to a gzip file
+
+  Copyright (C) 2003 Mark Adler, all rights reserved
+  version 1.1, 4 Nov 2003
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the author be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Mark Adler    madler@alumni.caltech.edu
+ */
+
+/*
+ * Change history:
+ *
+ * 1.0  19 Oct 2003     - First version
+ * 1.1   4 Nov 2003     - Expand and clarify some comments and notes
+ *                      - Add version and copyright to help
+ *                      - Send help to stdout instead of stderr
+ *                      - Add some preemptive typecasts
+ *                      - Add L to constants in lseek() calls
+ *                      - Remove some debugging information in error messages
+ *                      - Use new data_type definition for zlib 1.2.1
+ *                      - Simplfy and unify file operations
+ *                      - Finish off gzip file in gztack()
+ *                      - Use deflatePrime() instead of adding empty blocks
+ *                      - Keep gzip file clean on appended file read errors
+ *                      - Use in-place rotate instead of auxiliary buffer
+ *                        (Why you ask?  Because it was fun to write!)
+ */
+
+/*
+   gzappend takes a gzip file and appends to it, compressing files from the
+   command line or data from stdin.  The gzip file is written to directly, to
+   avoid copying that file, in case it's large.  Note that this results in the
+   unfriendly behavior that if gzappend fails, the gzip file is corrupted.
+
+   This program was written to illustrate the use of the new Z_BLOCK option of
+   zlib 1.2.x's inflate() function.  This option returns from inflate() at each
+   block boundary to facilitate locating and modifying the last block bit at
+   the start of the final deflate block.  Also whether using Z_BLOCK or not,
+   another required feature of zlib 1.2.x is that inflate() now provides the
+   number of unusued bits in the last input byte used.  gzappend will not work
+   with versions of zlib earlier than 1.2.1.
+
+   gzappend first decompresses the gzip file internally, discarding all but
+   the last 32K of uncompressed data, and noting the location of the last block
+   bit and the number of unused bits in the last byte of the compressed data.
+   The gzip trailer containing the CRC-32 and length of the uncompressed data
+   is verified.  This trailer will be later overwritten.
+
+   Then the last block bit is cleared by seeking back in the file and rewriting
+   the byte that contains it.  Seeking forward, the last byte of the compressed
+   data is saved along with the number of unused bits to initialize deflate.
+
+   A deflate process is initialized, using the last 32K of the uncompressed
+   data from the gzip file to initialize the dictionary.  If the total
+   uncompressed data was less than 32K, then all of it is used to initialize
+   the dictionary.  The deflate output bit buffer is also initialized with the
+   last bits from the original deflate stream.  From here on, the data to
+   append is simply compressed using deflate, and written to the gzip file.
+   When that is complete, the new CRC-32 and uncompressed length are written
+   as the trailer of the gzip file.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include "zlib.h"
+
+#define local static
+#define LGCHUNK 14
+#define CHUNK (1U << LGCHUNK)
+#define DSIZE 32768U
+
+/* print an error message and terminate with extreme prejudice */
+local void bye(char *msg1, char *msg2)
+{
+    fprintf(stderr, "gzappend error: %s%s\n", msg1, msg2);
+    exit(1);
+}
+
+/* return the greatest common divisor of a and b using Euclid's algorithm,
+   modified to be fast when one argument much greater than the other, and
+   coded to avoid unnecessary swapping */
+local unsigned gcd(unsigned a, unsigned b)
+{
+    unsigned c;
+
+    while (a && b)
+        if (a > b) {
+            c = b;
+            while (a - c >= c)
+                c <<= 1;
+            a -= c;
+        }
+        else {
+            c = a;
+            while (b - c >= c)
+                c <<= 1;
+            b -= c;
+        }
+    return a + b;
+}
+
+/* rotate list[0..len-1] left by rot positions, in place */
+local void rotate(unsigned char *list, unsigned len, unsigned rot)
+{
+    unsigned char tmp;
+    unsigned cycles;
+    unsigned char *start, *last, *to, *from;
+
+    /* normalize rot and handle degenerate cases */
+    if (len < 2) return;
+    if (rot >= len) rot %= len;
+    if (rot == 0) return;
+
+    /* pointer to last entry in list */
+    last = list + (len - 1);
+
+    /* do simple left shift by one */
+    if (rot == 1) {
+        tmp = *list;
+        memcpy(list, list + 1, len - 1);
+        *last = tmp;
+        return;
+    }
+
+    /* do simple right shift by one */
+    if (rot == len - 1) {
+        tmp = *last;
+        memmove(list + 1, list, len - 1);
+        *list = tmp;
+        return;
+    }
+
+    /* otherwise do rotate as a set of cycles in place */
+    cycles = gcd(len, rot);             /* number of cycles */
+    do {
+        start = from = list + cycles;   /* start index is arbitrary */
+        tmp = *from;                    /* save entry to be overwritten */
+        for (;;) {
+            to = from;                  /* next step in cycle */
+            from += rot;                /* go right rot positions */
+            if (from > last) from -= len;   /* (pointer better not wrap) */
+            if (from == start) break;   /* all but one shifted */
+            *to = *from;                /* shift left */
+        }
+        *to = tmp;                      /* complete the circle */
+    } while (--cycles);
+}
+
+/* structure for gzip file read operations */
+typedef struct {
+    int fd;                     /* file descriptor */
+    int size;                   /* 1 << size is bytes in buf */
+    unsigned left;              /* bytes available at next */
+    unsigned char *buf;         /* buffer */
+    unsigned char *next;        /* next byte in buffer */
+    char *name;                 /* file name for error messages */
+} file;
+
+/* reload buffer */
+local int readin(file *in)
+{
+    int len;
+
+    len = read(in->fd, in->buf, 1 << in->size);
+    if (len == -1) bye("error reading ", in->name);
+    in->left = (unsigned)len;
+    in->next = in->buf;
+    return len;
+}
+
+/* read from file in, exit if end-of-file */
+local int readmore(file *in)
+{
+    if (readin(in) == 0) bye("unexpected end of ", in->name);
+    return 0;
+}
+
+#define read1(in) (in->left == 0 ? readmore(in) : 0, \
+                   in->left--, *(in->next)++)
+
+/* skip over n bytes of in */
+local void skip(file *in, unsigned n)
+{
+    unsigned bypass;
+
+    if (n > in->left) {
+        n -= in->left;
+        bypass = n & ~((1U << in->size) - 1);
+        if (bypass) {
+            if (lseek(in->fd, (off_t)bypass, SEEK_CUR) == -1)
+                bye("seeking ", in->name);
+            n -= bypass;
+        }
+        readmore(in);
+        if (n > in->left)
+            bye("unexpected end of ", in->name);
+    }
+    in->left -= n;
+    in->next += n;
+}
+
+/* read a four-byte unsigned integer, little-endian, from in */
+unsigned long read4(file *in)
+{
+    unsigned long val;
+
+    val = read1(in);
+    val += (unsigned)read1(in) << 8;
+    val += (unsigned long)read1(in) << 16;
+    val += (unsigned long)read1(in) << 24;
+    return val;
+}
+
+/* skip over gzip header */
+local void gzheader(file *in)
+{
+    int flags;
+    unsigned n;
+
+    if (read1(in) != 31 || read1(in) != 139) bye(in->name, " not a gzip file");
+    if (read1(in) != 8) bye("unknown compression method in", in->name);
+    flags = read1(in);
+    if (flags & 0xe0) bye("unknown header flags set in", in->name);
+    skip(in, 6);
+    if (flags & 4) {
+        n = read1(in);
+        n += (unsigned)(read1(in)) << 8;
+        skip(in, n);
+    }
+    if (flags & 8) while (read1(in) != 0) ;
+    if (flags & 16) while (read1(in) != 0) ;
+    if (flags & 2) skip(in, 2);
+}
+
+/* decompress gzip file "name", return strm with a deflate stream ready to
+   continue compression of the data in the gzip file, and return a file
+   descriptor pointing to where to write the compressed data -- the deflate
+   stream is initialized to compress using level "level" */
+local int gzscan(char *name, z_stream *strm, int level)
+{
+    int ret, lastbit, left, full;
+    unsigned have;
+    unsigned long crc, tot;
+    unsigned char *window;
+    off_t lastoff, end;
+    file gz;
+
+    /* open gzip file */
+    gz.name = name;
+    gz.fd = open(name, O_RDWR, 0);
+    if (gz.fd == -1) bye("cannot open ", name);
+    gz.buf = malloc(CHUNK);
+    if (gz.buf == NULL) bye("out of memory", "");
+    gz.size = LGCHUNK;
+    gz.left = 0;
+
+    /* skip gzip header */
+    gzheader(&gz);
+
+    /* prepare to decompress */
+    window = malloc(DSIZE);
+    if (window == NULL) bye("out of memory", "");
+    strm->zalloc = Z_NULL;
+    strm->zfree = Z_NULL;
+    strm->opaque = Z_NULL;
+    ret = inflateInit2(strm, -15);
+    if (ret != Z_OK) bye("out of memory", " or library mismatch");
+
+    /* decompress the deflate stream, saving append information */
+    lastbit = 0;
+    lastoff = lseek(gz.fd, 0L, SEEK_CUR) - gz.left;
+    left = 0;
+    strm->avail_in = gz.left;
+    strm->next_in = gz.next;
+    crc = crc32(0L, Z_NULL, 0);
+    have = full = 0;
+    do {
+        /* if needed, get more input */
+        if (strm->avail_in == 0) {
+            readmore(&gz);
+            strm->avail_in = gz.left;
+            strm->next_in = gz.next;
+        }
+
+        /* set up output to next available section of sliding window */
+        strm->avail_out = DSIZE - have;
+        strm->next_out = window + have;
+
+        /* inflate and check for errors */
+        ret = inflate(strm, Z_BLOCK);
+        if (ret == Z_STREAM_ERROR) bye("internal stream error!", "");
+        if (ret == Z_MEM_ERROR) bye("out of memory", "");
+        if (ret == Z_DATA_ERROR)
+            bye("invalid compressed data--format violated in", name);
+
+        /* update crc and sliding window pointer */
+        crc = crc32(crc, window + have, DSIZE - have - strm->avail_out);
+        if (strm->avail_out)
+            have = DSIZE - strm->avail_out;
+        else {
+            have = 0;
+            full = 1;
+        }
+
+        /* process end of block */
+        if (strm->data_type & 128) {
+            if (strm->data_type & 64)
+                left = strm->data_type & 0x1f;
+            else {
+                lastbit = strm->data_type & 0x1f;
+                lastoff = lseek(gz.fd, 0L, SEEK_CUR) - strm->avail_in;
+            }
+        }
+    } while (ret != Z_STREAM_END);
+    inflateEnd(strm);
+    gz.left = strm->avail_in;
+    gz.next = strm->next_in;
+
+    /* save the location of the end of the compressed data */
+    end = lseek(gz.fd, 0L, SEEK_CUR) - gz.left;
+
+    /* check gzip trailer and save total for deflate */
+    if (crc != read4(&gz))
+        bye("invalid compressed data--crc mismatch in ", name);
+    tot = strm->total_out;
+    if ((tot & 0xffffffffUL) != read4(&gz))
+        bye("invalid compressed data--length mismatch in", name);
+
+    /* if not at end of file, warn */
+    if (gz.left || readin(&gz))
+        fprintf(stderr,
+            "gzappend warning: junk at end of gzip file overwritten\n");
+
+    /* clear last block bit */
+    lseek(gz.fd, lastoff - (lastbit != 0), SEEK_SET);
+    if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name);
+    *gz.buf = (unsigned char)(*gz.buf ^ (1 << ((8 - lastbit) & 7)));
+    lseek(gz.fd, -1L, SEEK_CUR);
+    if (write(gz.fd, gz.buf, 1) != 1) bye("writing after seek to ", name);
+
+    /* if window wrapped, build dictionary from window by rotating */
+    if (full) {
+        rotate(window, DSIZE, have);
+        have = DSIZE;
+    }
+
+    /* set up deflate stream with window, crc, total_in, and leftover bits */
+    ret = deflateInit2(strm, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
+    if (ret != Z_OK) bye("out of memory", "");
+    deflateSetDictionary(strm, window, have);
+    strm->adler = crc;
+    strm->total_in = tot;
+    if (left) {
+        lseek(gz.fd, --end, SEEK_SET);
+        if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name);
+        deflatePrime(strm, 8 - left, *gz.buf);
+    }
+    lseek(gz.fd, end, SEEK_SET);
+
+    /* clean up and return */
+    free(window);
+    free(gz.buf);
+    return gz.fd;
+}
+
+/* append file "name" to gzip file gd using deflate stream strm -- if last
+   is true, then finish off the deflate stream at the end */
+local void gztack(char *name, int gd, z_stream *strm, int last)
+{
+    int fd, len, ret;
+    unsigned left;
+    unsigned char *in, *out;
+
+    /* open file to compress and append */
+    fd = 0;
+    if (name != NULL) {
+        fd = open(name, O_RDONLY, 0);
+        if (fd == -1)
+            fprintf(stderr, "gzappend warning: %s not found, skipping ...\n",
+                    name);
+    }
+
+    /* allocate buffers */
+    in = fd == -1 ? NULL : malloc(CHUNK);
+    out = malloc(CHUNK);
+    if (out == NULL) bye("out of memory", "");
+
+    /* compress input file and append to gzip file */
+    do {
+        /* get more input */
+        len = fd == -1 ? 0 : read(fd, in, CHUNK);
+        if (len == -1) {
+            fprintf(stderr,
+                    "gzappend warning: error reading %s, skipping rest ...\n",
+                    name);
+            len = 0;
+        }
+        strm->avail_in = (unsigned)len;
+        strm->next_in = in;
+        if (len) strm->adler = crc32(strm->adler, in, (unsigned)len);
+
+        /* compress and write all available output */
+        do {
+            strm->avail_out = CHUNK;
+            strm->next_out = out;
+            ret = deflate(strm, last && len == 0 ? Z_FINISH : Z_NO_FLUSH);
+            left = CHUNK - strm->avail_out;
+            while (left) {
+                len = write(gd, out + CHUNK - strm->avail_out - left, left);
+                if (len == -1) bye("writing gzip file", "");
+                left -= (unsigned)len;
+            }
+        } while (strm->avail_out == 0 && ret != Z_STREAM_END);
+    } while (len != 0);
+
+    /* write trailer after last entry */
+    if (last) {
+        deflateEnd(strm);
+        out[0] = (unsigned char)(strm->adler);
+        out[1] = (unsigned char)(strm->adler >> 8);
+        out[2] = (unsigned char)(strm->adler >> 16);
+        out[3] = (unsigned char)(strm->adler >> 24);
+        out[4] = (unsigned char)(strm->total_in);
+        out[5] = (unsigned char)(strm->total_in >> 8);
+        out[6] = (unsigned char)(strm->total_in >> 16);
+        out[7] = (unsigned char)(strm->total_in >> 24);
+        len = 8;
+        do {
+            ret = write(gd, out + 8 - len, len);
+            if (ret == -1) bye("writing gzip file", "");
+            len -= ret;
+        } while (len);
+        close(gd);
+    }
+
+    /* clean up and return */
+    free(out);
+    if (in != NULL) free(in);
+    if (fd > 0) close(fd);
+}
+
+/* process the compression level option if present, scan the gzip file, and
+   append the specified files, or append the data from stdin if no other file
+   names are provided on the command line -- the gzip file must be writable
+   and seekable */
+int main(int argc, char **argv)
+{
+    int gd, level;
+    z_stream strm;
+
+    /* ignore command name */
+    argv++;
+
+    /* provide usage if no arguments */
+    if (*argv == NULL) {
+        printf("gzappend 1.1 (4 Nov 2003) Copyright (C) 2003 Mark Adler\n");
+        printf(
+            "usage: gzappend [-level] file.gz [ addthis [ andthis ... ]]\n");
+        return 0;
+    }
+
+    /* set compression level */
+    level = Z_DEFAULT_COMPRESSION;
+    if (argv[0][0] == '-') {
+        if (argv[0][1] < '0' || argv[0][1] > '9' || argv[0][2] != 0)
+            bye("invalid compression level", "");
+        level = argv[0][1] - '0';
+        if (*++argv == NULL) bye("no gzip file name after options", "");
+    }
+
+    /* prepare to append to gzip file */
+    gd = gzscan(*argv++, &strm, level);
+
+    /* append files on command line, or from stdin if none */
+    if (*argv == NULL)
+        gztack(NULL, gd, &strm, 1);
+    else
+        do {
+            gztack(*argv, gd, &strm, argv[1] == NULL);
+        } while (*++argv != NULL);
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzjoin.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzjoin.c
new file mode 100644 (file)
index 0000000..129347c
--- /dev/null
@@ -0,0 +1,448 @@
+/* gzjoin -- command to join gzip files into one gzip file
+
+  Copyright (C) 2004 Mark Adler, all rights reserved
+  version 1.0, 11 Dec 2004
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the author be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Mark Adler    madler@alumni.caltech.edu
+ */
+
+/*
+ * Change history:
+ *
+ * 1.0  11 Dec 2004     - First version
+ * 1.1  12 Jun 2005     - Changed ssize_t to long for portability
+ */
+
+/*
+   gzjoin takes one or more gzip files on the command line and writes out a
+   single gzip file that will uncompress to the concatenation of the
+   uncompressed data from the individual gzip files.  gzjoin does this without
+   having to recompress any of the data and without having to calculate a new
+   crc32 for the concatenated uncompressed data.  gzjoin does however have to
+   decompress all of the input data in order to find the bits in the compressed
+   data that need to be modified to concatenate the streams.
+
+   gzjoin does not do an integrity check on the input gzip files other than
+   checking the gzip header and decompressing the compressed data.  They are
+   otherwise assumed to be complete and correct.
+
+   Each joint between gzip files removes at least 18 bytes of previous trailer
+   and subsequent header, and inserts an average of about three bytes to the
+   compressed data in order to connect the streams.  The output gzip file
+   has a minimal ten-byte gzip header with no file name or modification time.
+
+   This program was written to illustrate the use of the Z_BLOCK option of
+   inflate() and the crc32_combine() function.  gzjoin will not compile with
+   versions of zlib earlier than 1.2.3.
+ */
+
+#include <stdio.h>      /* fputs(), fprintf(), fwrite(), putc() */
+#include <stdlib.h>     /* exit(), malloc(), free() */
+#include <fcntl.h>      /* open() */
+#include <unistd.h>     /* close(), read(), lseek() */
+#include "zlib.h"
+    /* crc32(), crc32_combine(), inflateInit2(), inflate(), inflateEnd() */
+
+#define local static
+
+/* exit with an error (return a value to allow use in an expression) */
+local int bail(char *why1, char *why2)
+{
+    fprintf(stderr, "gzjoin error: %s%s, output incomplete\n", why1, why2);
+    exit(1);
+    return 0;
+}
+
+/* -- simple buffered file input with access to the buffer -- */
+
+#define CHUNK 32768         /* must be a power of two and fit in unsigned */
+
+/* bin buffered input file type */
+typedef struct {
+    char *name;             /* name of file for error messages */
+    int fd;                 /* file descriptor */
+    unsigned left;          /* bytes remaining at next */
+    unsigned char *next;    /* next byte to read */
+    unsigned char *buf;     /* allocated buffer of length CHUNK */
+} bin;
+
+/* close a buffered file and free allocated memory */
+local void bclose(bin *in)
+{
+    if (in != NULL) {
+        if (in->fd != -1)
+            close(in->fd);
+        if (in->buf != NULL)
+            free(in->buf);
+        free(in);
+    }
+}
+
+/* open a buffered file for input, return a pointer to type bin, or NULL on
+   failure */
+local bin *bopen(char *name)
+{
+    bin *in;
+
+    in = malloc(sizeof(bin));
+    if (in == NULL)
+        return NULL;
+    in->buf = malloc(CHUNK);
+    in->fd = open(name, O_RDONLY, 0);
+    if (in->buf == NULL || in->fd == -1) {
+        bclose(in);
+        return NULL;
+    }
+    in->left = 0;
+    in->next = in->buf;
+    in->name = name;
+    return in;
+}
+
+/* load buffer from file, return -1 on read error, 0 or 1 on success, with
+   1 indicating that end-of-file was reached */
+local int bload(bin *in)
+{
+    long len;
+
+    if (in == NULL)
+        return -1;
+    if (in->left != 0)
+        return 0;
+    in->next = in->buf;
+    do {
+        len = (long)read(in->fd, in->buf + in->left, CHUNK - in->left);
+        if (len < 0)
+            return -1;
+        in->left += (unsigned)len;
+    } while (len != 0 && in->left < CHUNK);
+    return len == 0 ? 1 : 0;
+}
+
+/* get a byte from the file, bail if end of file */
+#define bget(in) (in->left ? 0 : bload(in), \
+                  in->left ? (in->left--, *(in->next)++) : \
+                    bail("unexpected end of file on ", in->name))
+
+/* get a four-byte little-endian unsigned integer from file */
+local unsigned long bget4(bin *in)
+{
+    unsigned long val;
+
+    val = bget(in);
+    val += (unsigned long)(bget(in)) << 8;
+    val += (unsigned long)(bget(in)) << 16;
+    val += (unsigned long)(bget(in)) << 24;
+    return val;
+}
+
+/* skip bytes in file */
+local void bskip(bin *in, unsigned skip)
+{
+    /* check pointer */
+    if (in == NULL)
+        return;
+
+    /* easy case -- skip bytes in buffer */
+    if (skip <= in->left) {
+        in->left -= skip;
+        in->next += skip;
+        return;
+    }
+
+    /* skip what's in buffer, discard buffer contents */
+    skip -= in->left;
+    in->left = 0;
+
+    /* seek past multiples of CHUNK bytes */
+    if (skip > CHUNK) {
+        unsigned left;
+
+        left = skip & (CHUNK - 1);
+        if (left == 0) {
+            /* exact number of chunks: seek all the way minus one byte to check
+               for end-of-file with a read */
+            lseek(in->fd, skip - 1, SEEK_CUR);
+            if (read(in->fd, in->buf, 1) != 1)
+                bail("unexpected end of file on ", in->name);
+            return;
+        }
+
+        /* skip the integral chunks, update skip with remainder */
+        lseek(in->fd, skip - left, SEEK_CUR);
+        skip = left;
+    }
+
+    /* read more input and skip remainder */
+    bload(in);
+    if (skip > in->left)
+        bail("unexpected end of file on ", in->name);
+    in->left -= skip;
+    in->next += skip;
+}
+
+/* -- end of buffered input functions -- */
+
+/* skip the gzip header from file in */
+local void gzhead(bin *in)
+{
+    int flags;
+
+    /* verify gzip magic header and compression method */
+    if (bget(in) != 0x1f || bget(in) != 0x8b || bget(in) != 8)
+        bail(in->name, " is not a valid gzip file");
+
+    /* get and verify flags */
+    flags = bget(in);
+    if ((flags & 0xe0) != 0)
+        bail("unknown reserved bits set in ", in->name);
+
+    /* skip modification time, extra flags, and os */
+    bskip(in, 6);
+
+    /* skip extra field if present */
+    if (flags & 4) {
+        unsigned len;
+
+        len = bget(in);
+        len += (unsigned)(bget(in)) << 8;
+        bskip(in, len);
+    }
+
+    /* skip file name if present */
+    if (flags & 8)
+        while (bget(in) != 0)
+            ;
+
+    /* skip comment if present */
+    if (flags & 16)
+        while (bget(in) != 0)
+            ;
+
+    /* skip header crc if present */
+    if (flags & 2)
+        bskip(in, 2);
+}
+
+/* write a four-byte little-endian unsigned integer to out */
+local void put4(unsigned long val, FILE *out)
+{
+    putc(val & 0xff, out);
+    putc((val >> 8) & 0xff, out);
+    putc((val >> 16) & 0xff, out);
+    putc((val >> 24) & 0xff, out);
+}
+
+/* Load up zlib stream from buffered input, bail if end of file */
+local void zpull(z_streamp strm, bin *in)
+{
+    if (in->left == 0)
+        bload(in);
+    if (in->left == 0)
+        bail("unexpected end of file on ", in->name);
+    strm->avail_in = in->left;
+    strm->next_in = in->next;
+}
+
+/* Write header for gzip file to out and initialize trailer. */
+local void gzinit(unsigned long *crc, unsigned long *tot, FILE *out)
+{
+    fwrite("\x1f\x8b\x08\0\0\0\0\0\0\xff", 1, 10, out);
+    *crc = crc32(0L, Z_NULL, 0);
+    *tot = 0;
+}
+
+/* Copy the compressed data from name, zeroing the last block bit of the last
+   block if clr is true, and adding empty blocks as needed to get to a byte
+   boundary.  If clr is false, then the last block becomes the last block of
+   the output, and the gzip trailer is written.  crc and tot maintains the
+   crc and length (modulo 2^32) of the output for the trailer.  The resulting
+   gzip file is written to out.  gzinit() must be called before the first call
+   of gzcopy() to write the gzip header and to initialize crc and tot. */
+local void gzcopy(char *name, int clr, unsigned long *crc, unsigned long *tot,
+                  FILE *out)
+{
+    int ret;                /* return value from zlib functions */
+    int pos;                /* where the "last block" bit is in byte */
+    int last;               /* true if processing the last block */
+    bin *in;                /* buffered input file */
+    unsigned char *start;   /* start of compressed data in buffer */
+    unsigned char *junk;    /* buffer for uncompressed data -- discarded */
+    z_off_t len;            /* length of uncompressed data (support > 4 GB) */
+    z_stream strm;          /* zlib inflate stream */
+
+    /* open gzip file and skip header */
+    in = bopen(name);
+    if (in == NULL)
+        bail("could not open ", name);
+    gzhead(in);
+
+    /* allocate buffer for uncompressed data and initialize raw inflate
+       stream */
+    junk = malloc(CHUNK);
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit2(&strm, -15);
+    if (junk == NULL || ret != Z_OK)
+        bail("out of memory", "");
+
+    /* inflate and copy compressed data, clear last-block bit if requested */
+    len = 0;
+    zpull(&strm, in);
+    start = strm.next_in;
+    last = start[0] & 1;
+    if (last && clr)
+        start[0] &= ~1;
+    strm.avail_out = 0;
+    for (;;) {
+        /* if input used and output done, write used input and get more */
+        if (strm.avail_in == 0 && strm.avail_out != 0) {
+            fwrite(start, 1, strm.next_in - start, out);
+            start = in->buf;
+            in->left = 0;
+            zpull(&strm, in);
+        }
+
+        /* decompress -- return early when end-of-block reached */
+        strm.avail_out = CHUNK;
+        strm.next_out = junk;
+        ret = inflate(&strm, Z_BLOCK);
+        switch (ret) {
+        case Z_MEM_ERROR:
+            bail("out of memory", "");
+        case Z_DATA_ERROR:
+            bail("invalid compressed data in ", in->name);
+        }
+
+        /* update length of uncompressed data */
+        len += CHUNK - strm.avail_out;
+
+        /* check for block boundary (only get this when block copied out) */
+        if (strm.data_type & 128) {
+            /* if that was the last block, then done */
+            if (last)
+                break;
+
+            /* number of unused bits in last byte */
+            pos = strm.data_type & 7;
+
+            /* find the next last-block bit */
+            if (pos != 0) {
+                /* next last-block bit is in last used byte */
+                pos = 0x100 >> pos;
+                last = strm.next_in[-1] & pos;
+                if (last && clr)
+                    strm.next_in[-1] &= ~pos;
+            }
+            else {
+                /* next last-block bit is in next unused byte */
+                if (strm.avail_in == 0) {
+                    /* don't have that byte yet -- get it */
+                    fwrite(start, 1, strm.next_in - start, out);
+                    start = in->buf;
+                    in->left = 0;
+                    zpull(&strm, in);
+                }
+                last = strm.next_in[0] & 1;
+                if (last && clr)
+                    strm.next_in[0] &= ~1;
+            }
+        }
+    }
+
+    /* update buffer with unused input */
+    in->left = strm.avail_in;
+    in->next = strm.next_in;
+
+    /* copy used input, write empty blocks to get to byte boundary */
+    pos = strm.data_type & 7;
+    fwrite(start, 1, in->next - start - 1, out);
+    last = in->next[-1];
+    if (pos == 0 || !clr)
+        /* already at byte boundary, or last file: write last byte */
+        putc(last, out);
+    else {
+        /* append empty blocks to last byte */
+        last &= ((0x100 >> pos) - 1);       /* assure unused bits are zero */
+        if (pos & 1) {
+            /* odd -- append an empty stored block */
+            putc(last, out);
+            if (pos == 1)
+                putc(0, out);               /* two more bits in block header */
+            fwrite("\0\0\xff\xff", 1, 4, out);
+        }
+        else {
+            /* even -- append 1, 2, or 3 empty fixed blocks */
+            switch (pos) {
+            case 6:
+                putc(last | 8, out);
+                last = 0;
+            case 4:
+                putc(last | 0x20, out);
+                last = 0;
+            case 2:
+                putc(last | 0x80, out);
+                putc(0, out);
+            }
+        }
+    }
+
+    /* update crc and tot */
+    *crc = crc32_combine(*crc, bget4(in), len);
+    *tot += (unsigned long)len;
+
+    /* clean up */
+    inflateEnd(&strm);
+    free(junk);
+    bclose(in);
+
+    /* write trailer if this is the last gzip file */
+    if (!clr) {
+        put4(*crc, out);
+        put4(*tot, out);
+    }
+}
+
+/* join the gzip files on the command line, write result to stdout */
+int main(int argc, char **argv)
+{
+    unsigned long crc, tot;     /* running crc and total uncompressed length */
+
+    /* skip command name */
+    argc--;
+    argv++;
+
+    /* show usage if no arguments */
+    if (argc == 0) {
+        fputs("gzjoin usage: gzjoin f1.gz [f2.gz [f3.gz ...]] > fjoin.gz\n",
+              stderr);
+        return 0;
+    }
+
+    /* join gzip files on command line and write to stdout */
+    gzinit(&crc, &tot, stdout);
+    while (argc--)
+        gzcopy(*argv++, argc, &crc, &tot, stdout);
+
+    /* done */
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzlog.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzlog.c
new file mode 100644 (file)
index 0000000..d70aaca
--- /dev/null
@@ -0,0 +1,1058 @@
+/*
+ * gzlog.c
+ * Copyright (C) 2004, 2008 Mark Adler, all rights reserved
+ * For conditions of distribution and use, see copyright notice in gzlog.h
+ * version 2.0, 25 Apr 2008
+ */
+
+/*
+   gzlog provides a mechanism for frequently appending short strings to a gzip
+   file that is efficient both in execution time and compression ratio.  The
+   strategy is to write the short strings in an uncompressed form to the end of
+   the gzip file, only compressing when the amount of uncompressed data has
+   reached a given threshold.
+
+   gzlog also provides protection against interruptions in the process due to
+   system crashes.  The status of the operation is recorded in an extra field
+   in the gzip file, and is only updated once the gzip file is brought to a
+   valid state.  The last data to be appended or compressed is saved in an
+   auxiliary file, so that if the operation is interrupted, it can be completed
+   the next time an append operation is attempted.
+
+   gzlog maintains another auxiliary file with the last 32K of data from the
+   compressed portion, which is preloaded for the compression of the subsequent
+   data.  This minimizes the impact to the compression ratio of appending.
+ */
+
+/*
+   Operations Concept:
+
+   Files (log name "foo"):
+   foo.gz -- gzip file with the complete log
+   foo.add -- last message to append or last data to compress
+   foo.dict -- dictionary of the last 32K of data for next compression
+   foo.temp -- temporary dictionary file for compression after this one
+   foo.lock -- lock file for reading and writing the other files
+   foo.repairs -- log file for log file recovery operations (not compressed)
+
+   gzip file structure:
+   - fixed-length (no file name) header with extra field (see below)
+   - compressed data ending initially with empty stored block
+   - uncompressed data filling out originally empty stored block and
+     subsequent stored blocks as needed (16K max each)
+   - gzip trailer
+   - no junk at end (no other gzip streams)
+
+   When appending data, the information in the first three items above plus the
+   foo.add file are sufficient to recover an interrupted append operation.  The
+   extra field has the necessary information to restore the start of the last
+   stored block and determine where to append the data in the foo.add file, as
+   well as the crc and length of the gzip data before the append operation.
+
+   The foo.add file is created before the gzip file is marked for append, and
+   deleted after the gzip file is marked as complete.  So if the append
+   operation is interrupted, the data to add will still be there.  If due to
+   some external force, the foo.add file gets deleted between when the append
+   operation was interrupted and when recovery is attempted, the gzip file will
+   still be restored, but without the appended data.
+
+   When compressing data, the information in the first two items above plus the
+   foo.add file are sufficient to recover an interrupted compress operation.
+   The extra field has the necessary information to find the end of the
+   compressed data, and contains both the crc and length of just the compressed
+   data and of the complete set of data including the contents of the foo.add
+   file.
+
+   Again, the foo.add file is maintained during the compress operation in case
+   of an interruption.  If in the unlikely event the foo.add file with the data
+   to be compressed is missing due to some external force, a gzip file with
+   just the previous compressed data will be reconstructed.  In this case, all
+   of the data that was to be compressed is lost (approximately one megabyte).
+   This will not occur if all that happened was an interruption of the compress
+   operation.
+
+   The third state that is marked is the replacement of the old dictionary with
+   the new dictionary after a compress operation.  Once compression is
+   complete, the gzip file is marked as being in the replace state.  This
+   completes the gzip file, so an interrupt after being so marked does not
+   result in recompression.  Then the dictionary file is replaced, and the gzip
+   file is marked as completed.  This state prevents the possibility of
+   restarting compression with the wrong dictionary file.
+
+   All three operations are wrapped by a lock/unlock procedure.  In order to
+   gain exclusive access to the log files, first a foo.lock file must be
+   exclusively created.  When all operations are complete, the lock is
+   released by deleting the foo.lock file.  If when attempting to create the
+   lock file, it already exists and the modify time of the lock file is more
+   than five minutes old (set by the PATIENCE define below), then the old
+   lock file is considered stale and deleted, and the exclusive creation of
+   the lock file is retried.  To assure that there are no false assessments
+   of the staleness of the lock file, the operations periodically touch the
+   lock file to update the modified date.
+
+   Following is the definition of the extra field with all of the information
+   required to enable the above append and compress operations and their
+   recovery if interrupted.  Multi-byte values are stored little endian
+   (consistent with the gzip format).  File pointers are eight bytes long.
+   The crc's and lengths for the gzip trailer are four bytes long.  (Note that
+   the length at the end of a gzip file is used for error checking only, and
+   for large files is actually the length modulo 2^32.)  The stored block
+   length is two bytes long.  The gzip extra field two-byte identification is
+   "ap" for append.  It is assumed that writing the extra field to the file is
+   an "atomic" operation.  That is, either all of the extra field is written
+   to the file, or none of it is, if the operation is interrupted right at the
+   point of updating the extra field.  This is a reasonable assumption, since
+   the extra field is within the first 52 bytes of the file, which is smaller
+   than any expected block size for a mass storage device (usually 512 bytes or
+   larger).
+
+   Extra field (35 bytes):
+   - Pointer to first stored block length -- this points to the two-byte length
+     of the first stored block, which is followed by the two-byte, one's
+     complement of that length.  The stored block length is preceded by the
+     three-bit header of the stored block, which is the actual start of the
+     stored block in the deflate format.  See the bit offset field below.
+   - Pointer to the last stored block length.  This is the same as above, but
+     for the last stored block of the uncompressed data in the gzip file.
+     Initially this is the same as the first stored block length pointer.
+     When the stored block gets to 16K (see the MAX_STORE define), then a new
+     stored block as added, at which point the last stored block length pointer
+     is different from the first stored block length pointer.  When they are
+     different, the first bit of the last stored block header is eight bits, or
+     one byte back from the block length.
+   - Compressed data crc and length.  This is the crc and length of the data
+     that is in the compressed portion of the deflate stream.  These are used
+     only in the event that the foo.add file containing the data to compress is
+     lost after a compress operation is interrupted.
+   - Total data crc and length.  This is the crc and length of all of the data
+     stored in the gzip file, compressed and uncompressed.  It is used to
+     reconstruct the gzip trailer when compressing, as well as when recovering
+     interrupted operations.
+   - Final stored block length.  This is used to quickly find where to append,
+     and allows the restoration of the original final stored block state when
+     an append operation is interrupted.
+   - First stored block start as the number of bits back from the final stored
+     block first length byte.  This value is in the range of 3..10, and is
+     stored as the low three bits of the final byte of the extra field after
+     subtracting three (0..7).  This allows the last-block bit of the stored
+     block header to be updated when a new stored block is added, for the case
+     when the first stored block and the last stored block are the same.  (When
+     they are different, the numbers of bits back is known to be eight.)  This
+     also allows for new compressed data to be appended to the old compressed
+     data in the compress operation, overwriting the previous first stored
+     block, or for the compressed data to be terminated and a valid gzip file
+     reconstructed on the off chance that a compression operation was
+     interrupted and the data to compress in the foo.add file was deleted.
+   - The operation in process.  This is the next two bits in the last byte (the
+     bits under the mask 0x18).  The are interpreted as 0: nothing in process,
+     1: append in process, 2: compress in process, 3: replace in process.
+   - The top three bits of the last byte in the extra field are reserved and
+     are currently set to zero.
+
+   Main procedure:
+   - Exclusively create the foo.lock file using the O_CREAT and O_EXCL modes of
+     the system open() call.  If the modify time of an existing lock file is
+     more than PATIENCE seconds old, then the lock file is deleted and the
+     exclusive create is retried.
+   - Load the extra field from the foo.gz file, and see if an operation was in
+     progress but not completed.  If so, apply the recovery procedure below.
+   - Perform the append procedure with the provided data.
+   - If the uncompressed data in the foo.gz file is 1MB or more, apply the
+     compress procedure.
+   - Delete the foo.lock file.
+
+   Append procedure:
+   - Put what to append in the foo.add file so that the operation can be
+     restarted if this procedure is interrupted.
+   - Mark the foo.gz extra field with the append operation in progress.
+   + Restore the original last-block bit and stored block length of the last
+     stored block from the information in the extra field, in case a previous
+     append operation was interrupted.
+   - Append the provided data to the last stored block, creating new stored
+     blocks as needed and updating the stored blocks last-block bits and
+     lengths.
+   - Update the crc and length with the new data, and write the gzip trailer.
+   - Write over the extra field (with a single write operation) with the new
+     pointers, lengths, and crc's, and mark the gzip file as not in process.
+     Though there is still a foo.add file, it will be ignored since nothing
+     is in process.  If a foo.add file is leftover from a previously
+     completed operation, it is truncated when writing new data to it.
+   - Delete the foo.add file.
+
+   Compress and replace procedures:
+   - Read all of the uncompressed data in the stored blocks in foo.gz and write
+     it to foo.add.  Also write foo.temp with the last 32K of that data to
+     provide a dictionary for the next invocation of this procedure.
+   - Rewrite the extra field marking foo.gz with a compression in process.
+   * If there is no data provided to compress (due to a missing foo.add file
+     when recovering), reconstruct and truncate the foo.gz file to contain
+     only the previous compressed data and proceed to the step after the next
+     one.  Otherwise ...
+   - Compress the data with the dictionary in foo.dict, and write to the
+     foo.gz file starting at the bit immediately following the last previously
+     compressed block.  If there is no foo.dict, proceed anyway with the
+     compression at slightly reduced efficiency.  (For the foo.dict file to be
+     missing requires some external failure beyond simply the interruption of
+     a compress operation.)  During this process, the foo.lock file is
+     periodically touched to assure that that file is not considered stale by
+     another process before we're done.  The deflation is terminated with a
+     non-last empty static block (10 bits long), that is then located and
+     written over by a last-bit-set empty stored block.
+   - Append the crc and length of the data in the gzip file (previously
+     calculated during the append operations).
+   - Write over the extra field with the updated stored block offsets, bits
+     back, crc's, and lengths, and mark foo.gz as in process for a replacement
+     of the dictionary.
+   @ Delete the foo.add file.
+   - Replace foo.dict with foo.temp.
+   - Write over the extra field, marking foo.gz as complete.
+
+   Recovery procedure:
+   - If not a replace recovery, read in the foo.add file, and provide that data
+     to the appropriate recovery below.  If there is no foo.add file, provide
+     a zero data length to the recovery.  In that case, the append recovery
+     restores the foo.gz to the previous compressed + uncompressed data state.
+     For the the compress recovery, a missing foo.add file results in foo.gz
+     being restored to the previous compressed-only data state.
+   - Append recovery:
+     - Pick up append at + step above
+   - Compress recovery:
+     - Pick up compress at * step above
+   - Replace recovery:
+     - Pick up compress at @ step above
+   - Log the repair with a date stamp in foo.repairs
+ */
+
+#include <sys/types.h>
+#include <stdio.h>      /* rename, fopen, fprintf, fclose */
+#include <stdlib.h>     /* malloc, free */
+#include <string.h>     /* strlen, strrchr, strcpy, strncpy, strcmp */
+#include <fcntl.h>      /* open */
+#include <unistd.h>     /* lseek, read, write, close, unlink, sleep, */
+                        /* ftruncate, fsync */
+#include <errno.h>      /* errno */
+#include <time.h>       /* time, ctime */
+#include <sys/stat.h>   /* stat */
+#include <sys/time.h>   /* utimes */
+#include "zlib.h"       /* crc32 */
+
+#include "gzlog.h"      /* header for external access */
+
+#define local static
+typedef unsigned int uint;
+typedef unsigned long ulong;
+
+/* Macro for debugging to deterministically force recovery operations */
+#ifdef DEBUG
+    #include <setjmp.h>         /* longjmp */
+    jmp_buf gzlog_jump;         /* where to go back to */
+    int gzlog_bail = 0;         /* which point to bail at (1..8) */
+    int gzlog_count = -1;       /* number of times through to wait */
+#   define BAIL(n) do { if (n == gzlog_bail && gzlog_count-- == 0) \
+                            longjmp(gzlog_jump, gzlog_bail); } while (0)
+#else
+#   define BAIL(n)
+#endif
+
+/* how old the lock file can be in seconds before considering it stale */
+#define PATIENCE 300
+
+/* maximum stored block size in Kbytes -- must be in 1..63 */
+#define MAX_STORE 16
+
+/* number of stored Kbytes to trigger compression (must be >= 32 to allow
+   dictionary construction, and <= 204 * MAX_STORE, in order for >> 10 to
+   discard the stored block headers contribution of five bytes each) */
+#define TRIGGER 1024
+
+/* size of a deflate dictionary (this cannot be changed) */
+#define DICT 32768U
+
+/* values for the operation (2 bits) */
+#define NO_OP 0
+#define APPEND_OP 1
+#define COMPRESS_OP 2
+#define REPLACE_OP 3
+
+/* macros to extract little-endian integers from an unsigned byte buffer */
+#define PULL2(p) ((p)[0]+((uint)((p)[1])<<8))
+#define PULL4(p) (PULL2(p)+((ulong)PULL2(p+2)<<16))
+#define PULL8(p) (PULL4(p)+((off_t)PULL4(p+4)<<32))
+
+/* macros to store integers into a byte buffer in little-endian order */
+#define PUT2(p,a) do {(p)[0]=a;(p)[1]=(a)>>8;} while(0)
+#define PUT4(p,a) do {PUT2(p,a);PUT2(p+2,a>>16);} while(0)
+#define PUT8(p,a) do {PUT4(p,a);PUT4(p+4,a>>32);} while(0)
+
+/* internal structure for log information */
+#define LOGID "\106\035\172"    /* should be three non-zero characters */
+struct log {
+    char id[4];     /* contains LOGID to detect inadvertent overwrites */
+    int fd;         /* file descriptor for .gz file, opened read/write */
+    char *path;     /* allocated path, e.g. "/var/log/foo" or "foo" */
+    char *end;      /* end of path, for appending suffices such as ".gz" */
+    off_t first;    /* offset of first stored block first length byte */
+    int back;       /* location of first block id in bits back from first */
+    uint stored;    /* bytes currently in last stored block */
+    off_t last;     /* offset of last stored block first length byte */
+    ulong ccrc;     /* crc of compressed data */
+    ulong clen;     /* length (modulo 2^32) of compressed data */
+    ulong tcrc;     /* crc of total data */
+    ulong tlen;     /* length (modulo 2^32) of total data */
+    time_t lock;    /* last modify time of our lock file */
+};
+
+/* gzip header for gzlog */
+local unsigned char log_gzhead[] = {
+    0x1f, 0x8b,                 /* magic gzip id */
+    8,                          /* compression method is deflate */
+    4,                          /* there is an extra field (no file name) */
+    0, 0, 0, 0,                 /* no modification time provided */
+    0, 0xff,                    /* no extra flags, no OS specified */
+    39, 0, 'a', 'p', 35, 0      /* extra field with "ap" subfield */
+                                /* 35 is EXTRA, 39 is EXTRA + 4 */
+};
+
+#define HEAD sizeof(log_gzhead)     /* should be 16 */
+
+/* initial gzip extra field content (52 == HEAD + EXTRA + 1) */
+local unsigned char log_gzext[] = {
+    52, 0, 0, 0, 0, 0, 0, 0,    /* offset of first stored block length */
+    52, 0, 0, 0, 0, 0, 0, 0,    /* offset of last stored block length */
+    0, 0, 0, 0, 0, 0, 0, 0,     /* compressed data crc and length */
+    0, 0, 0, 0, 0, 0, 0, 0,     /* total data crc and length */
+    0, 0,                       /* final stored block data length */
+    5                           /* op is NO_OP, last bit 8 bits back */
+};
+
+#define EXTRA sizeof(log_gzext)     /* should be 35 */
+
+/* initial gzip data and trailer */
+local unsigned char log_gzbody[] = {
+    1, 0, 0, 0xff, 0xff,        /* empty stored block (last) */
+    0, 0, 0, 0,                 /* crc */
+    0, 0, 0, 0                  /* uncompressed length */
+};
+
+#define BODY sizeof(log_gzbody)
+
+/* Exclusively create foo.lock in order to negotiate exclusive access to the
+   foo.* files.  If the modify time of an existing lock file is greater than
+   PATIENCE seconds in the past, then consider the lock file to have been
+   abandoned, delete it, and try the exclusive create again.  Save the lock
+   file modify time for verification of ownership.  Return 0 on success, or -1
+   on failure, usually due to an access restriction or invalid path.  Note that
+   if stat() or unlink() fails, it may be due to another process noticing the
+   abandoned lock file a smidge sooner and deleting it, so those are not
+   flagged as an error. */
+local int log_lock(struct log *log)
+{
+    int fd;
+    struct stat st;
+
+    strcpy(log->end, ".lock");
+    while ((fd = open(log->path, O_CREAT | O_EXCL, 0644)) < 0) {
+        if (errno != EEXIST)
+            return -1;
+        if (stat(log->path, &st) == 0 && time(NULL) - st.st_mtime > PATIENCE) {
+            unlink(log->path);
+            continue;
+        }
+        sleep(2);       /* relinquish the CPU for two seconds while waiting */
+    }
+    close(fd);
+    if (stat(log->path, &st) == 0)
+        log->lock = st.st_mtime;
+    return 0;
+}
+
+/* Update the modify time of the lock file to now, in order to prevent another
+   task from thinking that the lock is stale.  Save the lock file modify time
+   for verification of ownership. */
+local void log_touch(struct log *log)
+{
+    struct stat st;
+
+    strcpy(log->end, ".lock");
+    utimes(log->path, NULL);
+    if (stat(log->path, &st) == 0)
+        log->lock = st.st_mtime;
+}
+
+/* Check the log file modify time against what is expected.  Return true if
+   this is not our lock.  If it is our lock, touch it to keep it. */
+local int log_check(struct log *log)
+{
+    struct stat st;
+
+    strcpy(log->end, ".lock");
+    if (stat(log->path, &st) || st.st_mtime != log->lock)
+        return 1;
+    log_touch(log);
+    return 0;
+}
+
+/* Unlock a previously acquired lock, but only if it's ours. */
+local void log_unlock(struct log *log)
+{
+    if (log_check(log))
+        return;
+    strcpy(log->end, ".lock");
+    unlink(log->path);
+    log->lock = 0;
+}
+
+/* Check the gzip header and read in the extra field, filling in the values in
+   the log structure.  Return op on success or -1 if the gzip header was not as
+   expected.  op is the current operation in progress last written to the extra
+   field.  This assumes that the gzip file has already been opened, with the
+   file descriptor log->fd. */
+local int log_head(struct log *log)
+{
+    int op;
+    unsigned char buf[HEAD + EXTRA];
+
+    if (lseek(log->fd, 0, SEEK_SET) < 0 ||
+        read(log->fd, buf, HEAD + EXTRA) != HEAD + EXTRA ||
+        memcmp(buf, log_gzhead, HEAD)) {
+        return -1;
+    }
+    log->first = PULL8(buf + HEAD);
+    log->last = PULL8(buf + HEAD + 8);
+    log->ccrc = PULL4(buf + HEAD + 16);
+    log->clen = PULL4(buf + HEAD + 20);
+    log->tcrc = PULL4(buf + HEAD + 24);
+    log->tlen = PULL4(buf + HEAD + 28);
+    log->stored = PULL2(buf + HEAD + 32);
+    log->back = 3 + (buf[HEAD + 34] & 7);
+    op = (buf[HEAD + 34] >> 3) & 3;
+    return op;
+}
+
+/* Write over the extra field contents, marking the operation as op.  Use fsync
+   to assure that the device is written to, and in the requested order.  This
+   operation, and only this operation, is assumed to be atomic in order to
+   assure that the log is recoverable in the event of an interruption at any
+   point in the process.  Return -1 if the write to foo.gz failed. */
+local int log_mark(struct log *log, int op)
+{
+    int ret;
+    unsigned char ext[EXTRA];
+
+    PUT8(ext, log->first);
+    PUT8(ext + 8, log->last);
+    PUT4(ext + 16, log->ccrc);
+    PUT4(ext + 20, log->clen);
+    PUT4(ext + 24, log->tcrc);
+    PUT4(ext + 28, log->tlen);
+    PUT2(ext + 32, log->stored);
+    ext[34] = log->back - 3 + (op << 3);
+    fsync(log->fd);
+    ret = lseek(log->fd, HEAD, SEEK_SET) < 0 ||
+          write(log->fd, ext, EXTRA) != EXTRA ? -1 : 0;
+    fsync(log->fd);
+    return ret;
+}
+
+/* Rewrite the last block header bits and subsequent zero bits to get to a byte
+   boundary, setting the last block bit if last is true, and then write the
+   remainder of the stored block header (length and one's complement).  Leave
+   the file pointer after the end of the last stored block data.  Return -1 if
+   there is a read or write failure on the foo.gz file */
+local int log_last(struct log *log, int last)
+{
+    int back, len, mask;
+    unsigned char buf[6];
+
+    /* determine the locations of the bytes and bits to modify */
+    back = log->last == log->first ? log->back : 8;
+    len = back > 8 ? 2 : 1;                 /* bytes back from log->last */
+    mask = 0x80 >> ((back - 1) & 7);        /* mask for block last-bit */
+
+    /* get the byte to modify (one or two back) into buf[0] -- don't need to
+       read the byte if the last-bit is eight bits back, since in that case
+       the entire byte will be modified */
+    buf[0] = 0;
+    if (back != 8 && (lseek(log->fd, log->last - len, SEEK_SET) < 0 ||
+                      read(log->fd, buf, 1) != 1))
+        return -1;
+
+    /* change the last-bit of the last stored block as requested -- note
+       that all bits above the last-bit are set to zero, per the type bits
+       of a stored block being 00 and per the convention that the bits to
+       bring the stream to a byte boundary are also zeros */
+    buf[1] = 0;
+    buf[2 - len] = (*buf & (mask - 1)) + (last ? mask : 0);
+
+    /* write the modified stored block header and lengths, move the file
+       pointer to after the last stored block data */
+    PUT2(buf + 2, log->stored);
+    PUT2(buf + 4, log->stored ^ 0xffff);
+    return lseek(log->fd, log->last - len, SEEK_SET) < 0 ||
+           write(log->fd, buf + 2 - len, len + 4) != len + 4 ||
+           lseek(log->fd, log->stored, SEEK_CUR) < 0 ? -1 : 0;
+}
+
+/* Append len bytes from data to the locked and open log file.  len may be zero
+   if recovering and no .add file was found.  In that case, the previous state
+   of the foo.gz file is restored.  The data is appended uncompressed in
+   deflate stored blocks.  Return -1 if there was an error reading or writing
+   the foo.gz file. */
+local int log_append(struct log *log, unsigned char *data, size_t len)
+{
+    uint put;
+    off_t end;
+    unsigned char buf[8];
+
+    /* set the last block last-bit and length, in case recovering an
+       interrupted append, then position the file pointer to append to the
+       block */
+    if (log_last(log, 1))
+        return -1;
+
+    /* append, adding stored blocks and updating the offset of the last stored
+       block as needed, and update the total crc and length */
+    while (len) {
+        /* append as much as we can to the last block */
+        put = (MAX_STORE << 10) - log->stored;
+        if (put > len)
+            put = (uint)len;
+        if (put) {
+            if (write(log->fd, data, put) != put)
+                return -1;
+            BAIL(1);
+            log->tcrc = crc32(log->tcrc, data, put);
+            log->tlen += put;
+            log->stored += put;
+            data += put;
+            len -= put;
+        }
+
+        /* if we need to, add a new empty stored block */
+        if (len) {
+            /* mark current block as not last */
+            if (log_last(log, 0))
+                return -1;
+
+            /* point to new, empty stored block */
+            log->last += 4 + log->stored + 1;
+            log->stored = 0;
+        }
+
+        /* mark last block as last, update its length */
+        if (log_last(log, 1))
+            return -1;
+        BAIL(2);
+    }
+
+    /* write the new crc and length trailer, and truncate just in case (could
+       be recovering from partial append with a missing foo.add file) */
+    PUT4(buf, log->tcrc);
+    PUT4(buf + 4, log->tlen);
+    if (write(log->fd, buf, 8) != 8 ||
+        (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end))
+        return -1;
+
+    /* write the extra field, marking the log file as done, delete .add file */
+    if (log_mark(log, NO_OP))
+        return -1;
+    strcpy(log->end, ".add");
+    unlink(log->path);          /* ignore error, since may not exist */
+    return 0;
+}
+
+/* Replace the foo.dict file with the foo.temp file.  Also delete the foo.add
+   file, since the compress operation may have been interrupted before that was
+   done.  Returns 1 if memory could not be allocated, or -1 if reading or
+   writing foo.gz fails, or if the rename fails for some reason other than
+   foo.temp not existing.  foo.temp not existing is a permitted error, since
+   the replace operation may have been interrupted after the rename is done,
+   but before foo.gz is marked as complete. */
+local int log_replace(struct log *log)
+{
+    int ret;
+    char *dest;
+
+    /* delete foo.add file */
+    strcpy(log->end, ".add");
+    unlink(log->path);         /* ignore error, since may not exist */
+    BAIL(3);
+
+    /* rename foo.name to foo.dict, replacing foo.dict if it exists */
+    strcpy(log->end, ".dict");
+    dest = malloc(strlen(log->path) + 1);
+    if (dest == NULL)
+        return -2;
+    strcpy(dest, log->path);
+    strcpy(log->end, ".temp");
+    ret = rename(log->path, dest);
+    free(dest);
+    if (ret && errno != ENOENT)
+        return -1;
+    BAIL(4);
+
+    /* mark the foo.gz file as done */
+    return log_mark(log, NO_OP);
+}
+
+/* Compress the len bytes at data and append the compressed data to the
+   foo.gz deflate data immediately after the previous compressed data.  This
+   overwrites the previous uncompressed data, which was stored in foo.add
+   and is the data provided in data[0..len-1].  If this operation is
+   interrupted, it picks up at the start of this routine, with the foo.add
+   file read in again.  If there is no data to compress (len == 0), then we
+   simply terminate the foo.gz file after the previously compressed data,
+   appending a final empty stored block and the gzip trailer.  Return -1 if
+   reading or writing the log.gz file failed, or -2 if there was a memory
+   allocation failure. */
+local int log_compress(struct log *log, unsigned char *data, size_t len)
+{
+    int fd;
+    uint got, max;
+    ssize_t dict;
+    off_t end;
+    z_stream strm;
+    unsigned char buf[DICT];
+
+    /* compress and append compressed data */
+    if (len) {
+        /* set up for deflate, allocating memory */
+        strm.zalloc = Z_NULL;
+        strm.zfree = Z_NULL;
+        strm.opaque = Z_NULL;
+        if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8,
+                         Z_DEFAULT_STRATEGY) != Z_OK)
+            return -2;
+
+        /* read in dictionary (last 32K of data that was compressed) */
+        strcpy(log->end, ".dict");
+        fd = open(log->path, O_RDONLY, 0);
+        if (fd >= 0) {
+            dict = read(fd, buf, DICT);
+            close(fd);
+            if (dict < 0) {
+                deflateEnd(&strm);
+                return -1;
+            }
+            if (dict)
+                deflateSetDictionary(&strm, buf, (uint)dict);
+        }
+        log_touch(log);
+
+        /* prime deflate with last bits of previous block, position write
+           pointer to write those bits and overwrite what follows */
+        if (lseek(log->fd, log->first - (log->back > 8 ? 2 : 1),
+                SEEK_SET) < 0 ||
+            read(log->fd, buf, 1) != 1 || lseek(log->fd, -1, SEEK_CUR) < 0) {
+            deflateEnd(&strm);
+            return -1;
+        }
+        deflatePrime(&strm, (8 - log->back) & 7, *buf);
+
+        /* compress, finishing with a partial non-last empty static block */
+        strm.next_in = data;
+        max = (((uint)0 - 1) >> 1) + 1; /* in case int smaller than size_t */
+        do {
+            strm.avail_in = len > max ? max : (uint)len;
+            len -= strm.avail_in;
+            do {
+                strm.avail_out = DICT;
+                strm.next_out = buf;
+                deflate(&strm, len ? Z_NO_FLUSH : Z_PARTIAL_FLUSH);
+                got = DICT - strm.avail_out;
+                if (got && write(log->fd, buf, got) != got) {
+                    deflateEnd(&strm);
+                    return -1;
+                }
+                log_touch(log);
+            } while (strm.avail_out == 0);
+        } while (len);
+        deflateEnd(&strm);
+        BAIL(5);
+
+        /* find start of empty static block -- scanning backwards the first one
+           bit is the second bit of the block, if the last byte is zero, then
+           we know the byte before that has a one in the top bit, since an
+           empty static block is ten bits long */
+        if ((log->first = lseek(log->fd, -1, SEEK_CUR)) < 0 ||
+            read(log->fd, buf, 1) != 1)
+            return -1;
+        log->first++;
+        if (*buf) {
+            log->back = 1;
+            while ((*buf & ((uint)1 << (8 - log->back++))) == 0)
+                ;       /* guaranteed to terminate, since *buf != 0 */
+        }
+        else
+            log->back = 10;
+
+        /* update compressed crc and length */
+        log->ccrc = log->tcrc;
+        log->clen = log->tlen;
+    }
+    else {
+        /* no data to compress -- fix up existing gzip stream */
+        log->tcrc = log->ccrc;
+        log->tlen = log->clen;
+    }
+
+    /* complete and truncate gzip stream */
+    log->last = log->first;
+    log->stored = 0;
+    PUT4(buf, log->tcrc);
+    PUT4(buf + 4, log->tlen);
+    if (log_last(log, 1) || write(log->fd, buf, 8) != 8 ||
+        (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end))
+        return -1;
+    BAIL(6);
+
+    /* mark as being in the replace operation */
+    if (log_mark(log, REPLACE_OP))
+        return -1;
+
+    /* execute the replace operation and mark the file as done */
+    return log_replace(log);
+}
+
+/* log a repair record to the .repairs file */
+local void log_log(struct log *log, int op, char *record)
+{
+    time_t now;
+    FILE *rec;
+
+    now = time(NULL);
+    strcpy(log->end, ".repairs");
+    rec = fopen(log->path, "a");
+    if (rec == NULL)
+        return;
+    fprintf(rec, "%.24s %s recovery: %s\n", ctime(&now), op == APPEND_OP ?
+            "append" : (op == COMPRESS_OP ? "compress" : "replace"), record);
+    fclose(rec);
+    return;
+}
+
+/* Recover the interrupted operation op.  First read foo.add for recovering an
+   append or compress operation.  Return -1 if there was an error reading or
+   writing foo.gz or reading an existing foo.add, or -2 if there was a memory
+   allocation failure. */
+local int log_recover(struct log *log, int op)
+{
+    int fd, ret = 0;
+    unsigned char *data = NULL;
+    size_t len = 0;
+    struct stat st;
+
+    /* log recovery */
+    log_log(log, op, "start");
+
+    /* load foo.add file if expected and present */
+    if (op == APPEND_OP || op == COMPRESS_OP) {
+        strcpy(log->end, ".add");
+        if (stat(log->path, &st) == 0 && st.st_size) {
+            len = (size_t)(st.st_size);
+            if (len != st.st_size || (data = malloc(st.st_size)) == NULL) {
+                log_log(log, op, "allocation failure");
+                return -2;
+            }
+            if ((fd = open(log->path, O_RDONLY, 0)) < 0) {
+                log_log(log, op, ".add file read failure");
+                return -1;
+            }
+            ret = read(fd, data, len) != len;
+            close(fd);
+            if (ret) {
+                log_log(log, op, ".add file read failure");
+                return -1;
+            }
+            log_log(log, op, "loaded .add file");
+        }
+        else
+            log_log(log, op, "missing .add file!");
+    }
+
+    /* recover the interrupted operation */
+    switch (op) {
+    case APPEND_OP:
+        ret = log_append(log, data, len);
+        break;
+    case COMPRESS_OP:
+        ret = log_compress(log, data, len);
+        break;
+    case REPLACE_OP:
+        ret = log_replace(log);
+    }
+
+    /* log status */
+    log_log(log, op, ret ? "failure" : "complete");
+
+    /* clean up */
+    if (data != NULL)
+        free(data);
+    return ret;
+}
+
+/* Close the foo.gz file (if open) and release the lock. */
+local void log_close(struct log *log)
+{
+    if (log->fd >= 0)
+        close(log->fd);
+    log->fd = -1;
+    log_unlock(log);
+}
+
+/* Open foo.gz, verify the header, and load the extra field contents, after
+   first creating the foo.lock file to gain exclusive access to the foo.*
+   files.  If foo.gz does not exist or is empty, then write the initial header,
+   extra, and body content of an empty foo.gz log file.  If there is an error
+   creating the lock file due to access restrictions, or an error reading or
+   writing the foo.gz file, or if the foo.gz file is not a proper log file for
+   this object (e.g. not a gzip file or does not contain the expected extra
+   field), then return true.  If there is an error, the lock is released.
+   Otherwise, the lock is left in place. */
+local int log_open(struct log *log)
+{
+    int op;
+
+    /* release open file resource if left over -- can occur if lock lost
+       between gzlog_open() and gzlog_write() */
+    if (log->fd >= 0)
+        close(log->fd);
+    log->fd = -1;
+
+    /* negotiate exclusive access */
+    if (log_lock(log) < 0)
+        return -1;
+
+    /* open the log file, foo.gz */
+    strcpy(log->end, ".gz");
+    log->fd = open(log->path, O_RDWR | O_CREAT, 0644);
+    if (log->fd < 0) {
+        log_close(log);
+        return -1;
+    }
+
+    /* if new, initialize foo.gz with an empty log, delete old dictionary */
+    if (lseek(log->fd, 0, SEEK_END) == 0) {
+        if (write(log->fd, log_gzhead, HEAD) != HEAD ||
+            write(log->fd, log_gzext, EXTRA) != EXTRA ||
+            write(log->fd, log_gzbody, BODY) != BODY) {
+            log_close(log);
+            return -1;
+        }
+        strcpy(log->end, ".dict");
+        unlink(log->path);
+    }
+
+    /* verify log file and load extra field information */
+    if ((op = log_head(log)) < 0) {
+        log_close(log);
+        return -1;
+    }
+
+    /* check for interrupted process and if so, recover */
+    if (op != NO_OP && log_recover(log, op)) {
+        log_close(log);
+        return -1;
+    }
+
+    /* touch the lock file to prevent another process from grabbing it */
+    log_touch(log);
+    return 0;
+}
+
+/* See gzlog.h for the description of the external methods below */
+gzlog *gzlog_open(char *path)
+{
+    size_t n;
+    struct log *log;
+
+    /* check arguments */
+    if (path == NULL || *path == 0)
+        return NULL;
+
+    /* allocate and initialize log structure */
+    log = malloc(sizeof(struct log));
+    if (log == NULL)
+        return NULL;
+    strcpy(log->id, LOGID);
+    log->fd = -1;
+
+    /* save path and end of path for name construction */
+    n = strlen(path);
+    log->path = malloc(n + 9);              /* allow for ".repairs" */
+    if (log->path == NULL) {
+        free(log);
+        return NULL;
+    }
+    strcpy(log->path, path);
+    log->end = log->path + n;
+
+    /* gain exclusive access and verify log file -- may perform a
+       recovery operation if needed */
+    if (log_open(log)) {
+        free(log->path);
+        free(log);
+        return NULL;
+    }
+
+    /* return pointer to log structure */
+    return log;
+}
+
+/* gzlog_compress() return values:
+    0: all good
+   -1: file i/o error (usually access issue)
+   -2: memory allocation failure
+   -3: invalid log pointer argument */
+int gzlog_compress(gzlog *logd)
+{
+    int fd, ret;
+    uint block;
+    size_t len, next;
+    unsigned char *data, buf[5];
+    struct log *log = logd;
+
+    /* check arguments */
+    if (log == NULL || strcmp(log->id, LOGID) || len < 0)
+        return -3;
+
+    /* see if we lost the lock -- if so get it again and reload the extra
+       field information (it probably changed), recover last operation if
+       necessary */
+    if (log_check(log) && log_open(log))
+        return -1;
+
+    /* create space for uncompressed data */
+    len = ((size_t)(log->last - log->first) & ~(((size_t)1 << 10) - 1)) +
+          log->stored;
+    if ((data = malloc(len)) == NULL)
+        return -2;
+
+    /* do statement here is just a cheap trick for error handling */
+    do {
+        /* read in the uncompressed data */
+        if (lseek(log->fd, log->first - 1, SEEK_SET) < 0)
+            break;
+        next = 0;
+        while (next < len) {
+            if (read(log->fd, buf, 5) != 5)
+                break;
+            block = PULL2(buf + 1);
+            if (next + block > len ||
+                read(log->fd, (char *)data + next, block) != block)
+                break;
+            next += block;
+        }
+        if (lseek(log->fd, 0, SEEK_CUR) != log->last + 4 + log->stored)
+            break;
+        log_touch(log);
+
+        /* write the uncompressed data to the .add file */
+        strcpy(log->end, ".add");
+        fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+        if (fd < 0)
+            break;
+        ret = write(fd, data, len) != len;
+        if (ret | close(fd))
+            break;
+        log_touch(log);
+
+        /* write the dictionary for the next compress to the .temp file */
+        strcpy(log->end, ".temp");
+        fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+        if (fd < 0)
+            break;
+        next = DICT > len ? len : DICT;
+        ret = write(fd, (char *)data + len - next, next) != next;
+        if (ret | close(fd))
+            break;
+        log_touch(log);
+
+        /* roll back to compressed data, mark the compress in progress */
+        log->last = log->first;
+        log->stored = 0;
+        if (log_mark(log, COMPRESS_OP))
+            break;
+        BAIL(7);
+
+        /* compress and append the data (clears mark) */
+        ret = log_compress(log, data, len);
+        free(data);
+        return ret;
+    } while (0);
+
+    /* broke out of do above on i/o error */
+    free(data);
+    return -1;
+}
+
+/* gzlog_write() return values:
+    0: all good
+   -1: file i/o error (usually access issue)
+   -2: memory allocation failure
+   -3: invalid log pointer argument */
+int gzlog_write(gzlog *logd, void *data, size_t len)
+{
+    int fd, ret;
+    struct log *log = logd;
+
+    /* check arguments */
+    if (log == NULL || strcmp(log->id, LOGID) || len < 0)
+        return -3;
+    if (data == NULL || len == 0)
+        return 0;
+
+    /* see if we lost the lock -- if so get it again and reload the extra
+       field information (it probably changed), recover last operation if
+       necessary */
+    if (log_check(log) && log_open(log))
+        return -1;
+
+    /* create and write .add file */
+    strcpy(log->end, ".add");
+    fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+    if (fd < 0)
+        return -1;
+    ret = write(fd, data, len) != len;
+    if (ret | close(fd))
+        return -1;
+    log_touch(log);
+
+    /* mark log file with append in progress */
+    if (log_mark(log, APPEND_OP))
+        return -1;
+    BAIL(8);
+
+    /* append data (clears mark) */
+    if (log_append(log, data, len))
+        return -1;
+
+    /* check to see if it's time to compress -- if not, then done */
+    if (((log->last - log->first) >> 10) + (log->stored >> 10) < TRIGGER)
+        return 0;
+
+    /* time to compress */
+    return gzlog_compress(log);
+}
+
+/* gzlog_close() return values:
+    0: ok
+   -3: invalid log pointer argument */
+int gzlog_close(gzlog *logd)
+{
+    struct log *log = logd;
+
+    /* check arguments */
+    if (log == NULL || strcmp(log->id, LOGID))
+        return -3;
+
+    /* close the log file and release the lock */
+    log_close(log);
+
+    /* free structure and return */
+    if (log->path != NULL)
+        free(log->path);
+    strcpy(log->id, "bad");
+    free(log);
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzlog.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/gzlog.h
new file mode 100644 (file)
index 0000000..c461426
--- /dev/null
@@ -0,0 +1,89 @@
+/* gzlog.h
+  Copyright (C) 2004, 2008 Mark Adler, all rights reserved
+  version 2.0, 25 Apr 2008
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the author be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Mark Adler    madler@alumni.caltech.edu
+ */
+
+/* Version History:
+   1.0  26 Nov 2004  First version
+   2.0  25 Apr 2008  Complete redesign for recovery of interrupted operations
+                     Interface changed slightly in that now path is a prefix
+                     Compression now occurs as needed during gzlog_write()
+                     gzlog_write() now always leaves the log file as valid gzip
+ */
+
+/*
+   The gzlog object allows writing short messages to a gzipped log file,
+   opening the log file locked for small bursts, and then closing it.  The log
+   object works by appending stored (uncompressed) data to the gzip file until
+   1 MB has been accumulated.  At that time, the stored data is compressed, and
+   replaces the uncompressed data in the file.  The log file is truncated to
+   its new size at that time.  After each write operation, the log file is a
+   valid gzip file that can decompressed to recover what was written.
+
+   The gzlog operations can be interupted at any point due to an application or
+   system crash, and the log file will be recovered the next time the log is
+   opened with gzlog_open().
+ */
+
+#ifndef GZLOG_H
+#define GZLOG_H
+
+/* gzlog object type */
+typedef void gzlog;
+
+/* Open a gzlog object, creating the log file if it does not exist.  Return
+   NULL on error.  Note that gzlog_open() could take a while to complete if it
+   has to wait to verify that a lock is stale (possibly for five minutes), or
+   if there is significant contention with other instantiations of this object
+   when locking the resource.  path is the prefix of the file names created by
+   this object.  If path is "foo", then the log file will be "foo.gz", and
+   other auxiliary files will be created and destroyed during the process:
+   "foo.dict" for a compression dictionary, "foo.temp" for a temporary (next)
+   dictionary, "foo.add" for data being added or compressed, "foo.lock" for the
+   lock file, and "foo.repairs" to log recovery operations performed due to
+   interrupted gzlog operations.  A gzlog_open() followed by a gzlog_close()
+   will recover a previously interrupted operation, if any. */
+gzlog *gzlog_open(char *path);
+
+/* Write to a gzlog object.  Return zero on success, -1 if there is a file i/o
+   error on any of the gzlog files (this should not happen if gzlog_open()
+   succeeded, unless the device has run out of space or leftover auxiliary
+   files have permissions or ownership that prevent their use), -2 if there is
+   a memory allocation failure, or -3 if the log argument is invalid (e.g. if
+   it was not created by gzlog_open()).  This function will write data to the
+   file uncompressed, until 1 MB has been accumulated, at which time that data
+   will be compressed.  The log file will be a valid gzip file upon successful
+   return. */
+int gzlog_write(gzlog *log, void *data, size_t len);
+
+/* Force compression of any uncompressed data in the log.  This should be used
+   sparingly, if at all.  The main application would be when a log file will
+   not be appended to again.  If this is used to compress frequently while
+   appending, it will both significantly increase the execution time and
+   reduce the compression ratio.  The return codes are the same as for
+   gzlog_write(). */
+int gzlog_compress(gzlog *log);
+
+/* Close a gzlog object.  Return zero on success, -3 if the log argument is
+   invalid.  The log object is freed, and so cannot be referenced again. */
+int gzlog_close(gzlog *log);
+
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zlib_how.html b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zlib_how.html
new file mode 100644 (file)
index 0000000..444ff1c
--- /dev/null
@@ -0,0 +1,545 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
+  "http://www.w3.org/TR/REC-html40/loose.dtd">
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+<title>zlib Usage Example</title>
+<!--  Copyright (c) 2004, 2005 Mark Adler.  -->
+</head>
+<body bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#00A000">
+<h2 align="center"> zlib Usage Example </h2>
+We often get questions about how the <tt>deflate()</tt> and <tt>inflate()</tt> functions should be used.
+Users wonder when they should provide more input, when they should use more output,
+what to do with a <tt>Z_BUF_ERROR</tt>, how to make sure the process terminates properly, and
+so on.  So for those who have read <tt>zlib.h</tt> (a few times), and
+would like further edification, below is an annotated example in C of simple routines to compress and decompress
+from an input file to an output file using <tt>deflate()</tt> and <tt>inflate()</tt> respectively.  The
+annotations are interspersed between lines of the code.  So please read between the lines.
+We hope this helps explain some of the intricacies of <em>zlib</em>.
+<p>
+Without further adieu, here is the program <a href="zpipe.c"><tt>zpipe.c</tt></a>:
+<pre><b>
+/* zpipe.c: example of proper use of zlib's inflate() and deflate()
+   Not copyrighted -- provided to the public domain
+   Version 1.4  11 December 2005  Mark Adler */
+
+/* Version history:
+   1.0  30 Oct 2004  First version
+   1.1   8 Nov 2004  Add void casting for unused return values
+                     Use switch statement for inflate() return values
+   1.2   9 Nov 2004  Add assertions to document zlib guarantees
+   1.3   6 Apr 2005  Remove incorrect assertion in inf()
+   1.4  11 Dec 2005  Add hack to avoid MSDOS end-of-line conversions
+                     Avoid some compiler warnings for input and output buffers
+ */
+</b></pre><!-- -->
+We now include the header files for the required definitions.  From
+<tt>stdio.h</tt> we use <tt>fopen()</tt>, <tt>fread()</tt>, <tt>fwrite()</tt>,
+<tt>feof()</tt>, <tt>ferror()</tt>, and <tt>fclose()</tt> for file i/o, and
+<tt>fputs()</tt> for error messages.  From <tt>string.h</tt> we use
+<tt>strcmp()</tt> for command line argument processing.
+From <tt>assert.h</tt> we use the <tt>assert()</tt> macro.
+From <tt>zlib.h</tt>
+we use the basic compression functions <tt>deflateInit()</tt>,
+<tt>deflate()</tt>, and <tt>deflateEnd()</tt>, and the basic decompression
+functions <tt>inflateInit()</tt>, <tt>inflate()</tt>, and
+<tt>inflateEnd()</tt>.
+<pre><b>
+#include &lt;stdio.h&gt;
+#include &lt;string.h&gt;
+#include &lt;assert.h&gt;
+#include "zlib.h"
+</b></pre><!-- -->
+This is an ugly hack required to avoid corruption of the input and output data on
+Windows/MS-DOS systems.  Without this, those systems would assume that the input and output
+files are text, and try to convert the end-of-line characters from one standard to
+another.  That would corrupt binary data, and in particular would render the compressed data unusable.
+This sets the input and output to binary which suppresses the end-of-line conversions.
+<tt>SET_BINARY_MODE()</tt> will be used later on <tt>stdin</tt> and <tt>stdout</tt>, at the beginning of <tt>main()</tt>.
+<pre><b>
+#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
+#  include &lt;fcntl.h&gt;
+#  include &lt;io.h&gt;
+#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+#else
+#  define SET_BINARY_MODE(file)
+#endif
+</b></pre><!-- -->
+<tt>CHUNK</tt> is simply the buffer size for feeding data to and pulling data
+from the <em>zlib</em> routines.  Larger buffer sizes would be more efficient,
+especially for <tt>inflate()</tt>.  If the memory is available, buffers sizes
+on the order of 128K or 256K bytes should be used.
+<pre><b>
+#define CHUNK 16384
+</b></pre><!-- -->
+The <tt>def()</tt> routine compresses data from an input file to an output file.  The output data
+will be in the <em>zlib</em> format, which is different from the <em>gzip</em> or <em>zip</em>
+formats.  The <em>zlib</em> format has a very small header of only two bytes to identify it as
+a <em>zlib</em> stream and to provide decoding information, and a four-byte trailer with a fast
+check value to verify the integrity of the uncompressed data after decoding.
+<pre><b>
+/* Compress from file source to file dest until EOF on source.
+   def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
+   allocated for processing, Z_STREAM_ERROR if an invalid compression
+   level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
+   version of the library linked do not match, or Z_ERRNO if there is
+   an error reading or writing the files. */
+int def(FILE *source, FILE *dest, int level)
+{
+</b></pre>
+Here are the local variables for <tt>def()</tt>.  <tt>ret</tt> will be used for <em>zlib</em>
+return codes.  <tt>flush</tt> will keep track of the current flushing state for <tt>deflate()</tt>,
+which is either no flushing, or flush to completion after the end of the input file is reached.
+<tt>have</tt> is the amount of data returned from <tt>deflate()</tt>.  The <tt>strm</tt> structure
+is used to pass information to and from the <em>zlib</em> routines, and to maintain the
+<tt>deflate()</tt> state.  <tt>in</tt> and <tt>out</tt> are the input and output buffers for
+<tt>deflate()</tt>.
+<pre><b>
+    int ret, flush;
+    unsigned have;
+    z_stream strm;
+    unsigned char in[CHUNK];
+    unsigned char out[CHUNK];
+</b></pre><!-- -->
+The first thing we do is to initialize the <em>zlib</em> state for compression using
+<tt>deflateInit()</tt>.  This must be done before the first use of <tt>deflate()</tt>.
+The <tt>zalloc</tt>, <tt>zfree</tt>, and <tt>opaque</tt> fields in the <tt>strm</tt>
+structure must be initialized before calling <tt>deflateInit()</tt>.  Here they are
+set to the <em>zlib</em> constant <tt>Z_NULL</tt> to request that <em>zlib</em> use
+the default memory allocation routines.  An application may also choose to provide
+custom memory allocation routines here.  <tt>deflateInit()</tt> will allocate on the
+order of 256K bytes for the internal state.
+(See <a href="zlib_tech.html"><em>zlib Technical Details</em></a>.)
+<p>
+<tt>deflateInit()</tt> is called with a pointer to the structure to be initialized and
+the compression level, which is an integer in the range of -1 to 9.  Lower compression
+levels result in faster execution, but less compression.  Higher levels result in
+greater compression, but slower execution.  The <em>zlib</em> constant Z_DEFAULT_COMPRESSION,
+equal to -1,
+provides a good compromise between compression and speed and is equivalent to level 6.
+Level 0 actually does no compression at all, and in fact expands the data slightly to produce
+the <em>zlib</em> format (it is not a byte-for-byte copy of the input).
+More advanced applications of <em>zlib</em>
+may use <tt>deflateInit2()</tt> here instead.  Such an application may want to reduce how
+much memory will be used, at some price in compression.  Or it may need to request a
+<em>gzip</em> header and trailer instead of a <em>zlib</em> header and trailer, or raw
+encoding with no header or trailer at all.
+<p>
+We must check the return value of <tt>deflateInit()</tt> against the <em>zlib</em> constant
+<tt>Z_OK</tt> to make sure that it was able to
+allocate memory for the internal state, and that the provided arguments were valid.
+<tt>deflateInit()</tt> will also check that the version of <em>zlib</em> that the <tt>zlib.h</tt>
+file came from matches the version of <em>zlib</em> actually linked with the program.  This
+is especially important for environments in which <em>zlib</em> is a shared library.
+<p>
+Note that an application can initialize multiple, independent <em>zlib</em> streams, which can
+operate in parallel.  The state information maintained in the structure allows the <em>zlib</em>
+routines to be reentrant.
+<pre><b>
+    /* allocate deflate state */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    ret = deflateInit(&amp;strm, level);
+    if (ret != Z_OK)
+        return ret;
+</b></pre><!-- -->
+With the pleasantries out of the way, now we can get down to business.  The outer <tt>do</tt>-loop
+reads all of the input file and exits at the bottom of the loop once end-of-file is reached.
+This loop contains the only call of <tt>deflate()</tt>.  So we must make sure that all of the
+input data has been processed and that all of the output data has been generated and consumed
+before we fall out of the loop at the bottom.
+<pre><b>
+    /* compress until end of file */
+    do {
+</b></pre>
+We start off by reading data from the input file.  The number of bytes read is put directly
+into <tt>avail_in</tt>, and a pointer to those bytes is put into <tt>next_in</tt>.  We also
+check to see if end-of-file on the input has been reached.  If we are at the end of file, then <tt>flush</tt> is set to the
+<em>zlib</em> constant <tt>Z_FINISH</tt>, which is later passed to <tt>deflate()</tt> to
+indicate that this is the last chunk of input data to compress.  We need to use <tt>feof()</tt>
+to check for end-of-file as opposed to seeing if fewer than <tt>CHUNK</tt> bytes have been read.  The
+reason is that if the input file length is an exact multiple of <tt>CHUNK</tt>, we will miss
+the fact that we got to the end-of-file, and not know to tell <tt>deflate()</tt> to finish
+up the compressed stream.  If we are not yet at the end of the input, then the <em>zlib</em>
+constant <tt>Z_NO_FLUSH</tt> will be passed to <tt>deflate</tt> to indicate that we are still
+in the middle of the uncompressed data.
+<p>
+If there is an error in reading from the input file, the process is aborted with
+<tt>deflateEnd()</tt> being called to free the allocated <em>zlib</em> state before returning
+the error.  We wouldn't want a memory leak, now would we?  <tt>deflateEnd()</tt> can be called
+at any time after the state has been initialized.  Once that's done, <tt>deflateInit()</tt> (or
+<tt>deflateInit2()</tt>) would have to be called to start a new compression process.  There is
+no point here in checking the <tt>deflateEnd()</tt> return code.  The deallocation can't fail.
+<pre><b>
+        strm.avail_in = fread(in, 1, CHUNK, source);
+        if (ferror(source)) {
+            (void)deflateEnd(&amp;strm);
+            return Z_ERRNO;
+        }
+        flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
+        strm.next_in = in;
+</b></pre><!-- -->
+The inner <tt>do</tt>-loop passes our chunk of input data to <tt>deflate()</tt>, and then
+keeps calling <tt>deflate()</tt> until it is done producing output.  Once there is no more
+new output, <tt>deflate()</tt> is guaranteed to have consumed all of the input, i.e.,
+<tt>avail_in</tt> will be zero.
+<pre><b>
+        /* run deflate() on input until output buffer not full, finish
+           compression if all of source has been read in */
+        do {
+</b></pre>
+Output space is provided to <tt>deflate()</tt> by setting <tt>avail_out</tt> to the number
+of available output bytes and <tt>next_out</tt> to a pointer to that space.
+<pre><b>
+            strm.avail_out = CHUNK;
+            strm.next_out = out;
+</b></pre>
+Now we call the compression engine itself, <tt>deflate()</tt>.  It takes as many of the
+<tt>avail_in</tt> bytes at <tt>next_in</tt> as it can process, and writes as many as
+<tt>avail_out</tt> bytes to <tt>next_out</tt>.  Those counters and pointers are then
+updated past the input data consumed and the output data written.  It is the amount of
+output space available that may limit how much input is consumed.
+Hence the inner loop to make sure that
+all of the input is consumed by providing more output space each time.  Since <tt>avail_in</tt>
+and <tt>next_in</tt> are updated by <tt>deflate()</tt>, we don't have to mess with those
+between <tt>deflate()</tt> calls until it's all used up.
+<p>
+The parameters to <tt>deflate()</tt> are a pointer to the <tt>strm</tt> structure containing
+the input and output information and the internal compression engine state, and a parameter
+indicating whether and how to flush data to the output.  Normally <tt>deflate</tt> will consume
+several K bytes of input data before producing any output (except for the header), in order
+to accumulate statistics on the data for optimum compression.  It will then put out a burst of
+compressed data, and proceed to consume more input before the next burst.  Eventually,
+<tt>deflate()</tt>
+must be told to terminate the stream, complete the compression with provided input data, and
+write out the trailer check value.  <tt>deflate()</tt> will continue to compress normally as long
+as the flush parameter is <tt>Z_NO_FLUSH</tt>.  Once the <tt>Z_FINISH</tt> parameter is provided,
+<tt>deflate()</tt> will begin to complete the compressed output stream.  However depending on how
+much output space is provided, <tt>deflate()</tt> may have to be called several times until it
+has provided the complete compressed stream, even after it has consumed all of the input.  The flush
+parameter must continue to be <tt>Z_FINISH</tt> for those subsequent calls.
+<p>
+There are other values of the flush parameter that are used in more advanced applications.  You can
+force <tt>deflate()</tt> to produce a burst of output that encodes all of the input data provided
+so far, even if it wouldn't have otherwise, for example to control data latency on a link with
+compressed data.  You can also ask that <tt>deflate()</tt> do that as well as erase any history up to
+that point so that what follows can be decompressed independently, for example for random access
+applications.  Both requests will degrade compression by an amount depending on how often such
+requests are made.
+<p>
+<tt>deflate()</tt> has a return value that can indicate errors, yet we do not check it here.  Why
+not?  Well, it turns out that <tt>deflate()</tt> can do no wrong here.  Let's go through
+<tt>deflate()</tt>'s return values and dispense with them one by one.  The possible values are
+<tt>Z_OK</tt>, <tt>Z_STREAM_END</tt>, <tt>Z_STREAM_ERROR</tt>, or <tt>Z_BUF_ERROR</tt>.  <tt>Z_OK</tt>
+is, well, ok.  <tt>Z_STREAM_END</tt> is also ok and will be returned for the last call of
+<tt>deflate()</tt>.  This is already guaranteed by calling <tt>deflate()</tt> with <tt>Z_FINISH</tt>
+until it has no more output.  <tt>Z_STREAM_ERROR</tt> is only possible if the stream is not
+initialized properly, but we did initialize it properly.  There is no harm in checking for
+<tt>Z_STREAM_ERROR</tt> here, for example to check for the possibility that some
+other part of the application inadvertently clobbered the memory containing the <em>zlib</em> state.
+<tt>Z_BUF_ERROR</tt> will be explained further below, but
+suffice it to say that this is simply an indication that <tt>deflate()</tt> could not consume
+more input or produce more output.  <tt>deflate()</tt> can be called again with more output space
+or more available input, which it will be in this code.
+<pre><b>
+            ret = deflate(&amp;strm, flush);    /* no bad return value */
+            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
+</b></pre>
+Now we compute how much output <tt>deflate()</tt> provided on the last call, which is the
+difference between how much space was provided before the call, and how much output space
+is still available after the call.  Then that data, if any, is written to the output file.
+We can then reuse the output buffer for the next call of <tt>deflate()</tt>.  Again if there
+is a file i/o error, we call <tt>deflateEnd()</tt> before returning to avoid a memory leak.
+<pre><b>
+            have = CHUNK - strm.avail_out;
+            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
+                (void)deflateEnd(&amp;strm);
+                return Z_ERRNO;
+            }
+</b></pre>
+The inner <tt>do</tt>-loop is repeated until the last <tt>deflate()</tt> call fails to fill the
+provided output buffer.  Then we know that <tt>deflate()</tt> has done as much as it can with
+the provided input, and that all of that input has been consumed.  We can then fall out of this
+loop and reuse the input buffer.
+<p>
+The way we tell that <tt>deflate()</tt> has no more output is by seeing that it did not fill
+the output buffer, leaving <tt>avail_out</tt> greater than zero.  However suppose that
+<tt>deflate()</tt> has no more output, but just so happened to exactly fill the output buffer!
+<tt>avail_out</tt> is zero, and we can't tell that <tt>deflate()</tt> has done all it can.
+As far as we know, <tt>deflate()</tt>
+has more output for us.  So we call it again.  But now <tt>deflate()</tt> produces no output
+at all, and <tt>avail_out</tt> remains unchanged as <tt>CHUNK</tt>.  That <tt>deflate()</tt> call
+wasn't able to do anything, either consume input or produce output, and so it returns
+<tt>Z_BUF_ERROR</tt>.  (See, I told you I'd cover this later.)  However this is not a problem at
+all.  Now we finally have the desired indication that <tt>deflate()</tt> is really done,
+and so we drop out of the inner loop to provide more input to <tt>deflate()</tt>.
+<p>
+With <tt>flush</tt> set to <tt>Z_FINISH</tt>, this final set of <tt>deflate()</tt> calls will
+complete the output stream.  Once that is done, subsequent calls of <tt>deflate()</tt> would return
+<tt>Z_STREAM_ERROR</tt> if the flush parameter is not <tt>Z_FINISH</tt>, and do no more processing
+until the state is reinitialized.
+<p>
+Some applications of <em>zlib</em> have two loops that call <tt>deflate()</tt>
+instead of the single inner loop we have here.  The first loop would call
+without flushing and feed all of the data to <tt>deflate()</tt>.  The second loop would call
+<tt>deflate()</tt> with no more
+data and the <tt>Z_FINISH</tt> parameter to complete the process.  As you can see from this
+example, that can be avoided by simply keeping track of the current flush state.
+<pre><b>
+        } while (strm.avail_out == 0);
+        assert(strm.avail_in == 0);     /* all input will be used */
+</b></pre><!-- -->
+Now we check to see if we have already processed all of the input file.  That information was
+saved in the <tt>flush</tt> variable, so we see if that was set to <tt>Z_FINISH</tt>.  If so,
+then we're done and we fall out of the outer loop.  We're guaranteed to get <tt>Z_STREAM_END</tt>
+from the last <tt>deflate()</tt> call, since we ran it until the last chunk of input was
+consumed and all of the output was generated.
+<pre><b>
+        /* done when last data in file processed */
+    } while (flush != Z_FINISH);
+    assert(ret == Z_STREAM_END);        /* stream will be complete */
+</b></pre><!-- -->
+The process is complete, but we still need to deallocate the state to avoid a memory leak
+(or rather more like a memory hemorrhage if you didn't do this).  Then
+finally we can return with a happy return value.
+<pre><b>
+    /* clean up and return */
+    (void)deflateEnd(&amp;strm);
+    return Z_OK;
+}
+</b></pre><!-- -->
+Now we do the same thing for decompression in the <tt>inf()</tt> routine. <tt>inf()</tt>
+decompresses what is hopefully a valid <em>zlib</em> stream from the input file and writes the
+uncompressed data to the output file.  Much of the discussion above for <tt>def()</tt>
+applies to <tt>inf()</tt> as well, so the discussion here will focus on the differences between
+the two.
+<pre><b>
+/* Decompress from file source to file dest until stream ends or EOF.
+   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
+   allocated for processing, Z_DATA_ERROR if the deflate data is
+   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
+   the version of the library linked do not match, or Z_ERRNO if there
+   is an error reading or writing the files. */
+int inf(FILE *source, FILE *dest)
+{
+</b></pre>
+The local variables have the same functionality as they do for <tt>def()</tt>.  The
+only difference is that there is no <tt>flush</tt> variable, since <tt>inflate()</tt>
+can tell from the <em>zlib</em> stream itself when the stream is complete.
+<pre><b>
+    int ret;
+    unsigned have;
+    z_stream strm;
+    unsigned char in[CHUNK];
+    unsigned char out[CHUNK];
+</b></pre><!-- -->
+The initialization of the state is the same, except that there is no compression level,
+of course, and two more elements of the structure are initialized.  <tt>avail_in</tt>
+and <tt>next_in</tt> must be initialized before calling <tt>inflateInit()</tt>.  This
+is because the application has the option to provide the start of the zlib stream in
+order for <tt>inflateInit()</tt> to have access to information about the compression
+method to aid in memory allocation.  In the current implementation of <em>zlib</em>
+(up through versions 1.2.x), the method-dependent memory allocations are deferred to the first call of
+<tt>inflate()</tt> anyway.  However those fields must be initialized since later versions
+of <em>zlib</em> that provide more compression methods may take advantage of this interface.
+In any case, no decompression is performed by <tt>inflateInit()</tt>, so the
+<tt>avail_out</tt> and <tt>next_out</tt> fields do not need to be initialized before calling.
+<p>
+Here <tt>avail_in</tt> is set to zero and <tt>next_in</tt> is set to <tt>Z_NULL</tt> to
+indicate that no input data is being provided.
+<pre><b>
+    /* allocate inflate state */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit(&amp;strm);
+    if (ret != Z_OK)
+        return ret;
+</b></pre><!-- -->
+The outer <tt>do</tt>-loop decompresses input until <tt>inflate()</tt> indicates
+that it has reached the end of the compressed data and has produced all of the uncompressed
+output.  This is in contrast to <tt>def()</tt> which processes all of the input file.
+If end-of-file is reached before the compressed data self-terminates, then the compressed
+data is incomplete and an error is returned.
+<pre><b>
+    /* decompress until deflate stream ends or end of file */
+    do {
+</b></pre>
+We read input data and set the <tt>strm</tt> structure accordingly.  If we've reached the
+end of the input file, then we leave the outer loop and report an error, since the
+compressed data is incomplete.  Note that we may read more data than is eventually consumed
+by <tt>inflate()</tt>, if the input file continues past the <em>zlib</em> stream.
+For applications where <em>zlib</em> streams are embedded in other data, this routine would
+need to be modified to return the unused data, or at least indicate how much of the input
+data was not used, so the application would know where to pick up after the <em>zlib</em> stream.
+<pre><b>
+        strm.avail_in = fread(in, 1, CHUNK, source);
+        if (ferror(source)) {
+            (void)inflateEnd(&amp;strm);
+            return Z_ERRNO;
+        }
+        if (strm.avail_in == 0)
+            break;
+        strm.next_in = in;
+</b></pre><!-- -->
+The inner <tt>do</tt>-loop has the same function it did in <tt>def()</tt>, which is to
+keep calling <tt>inflate()</tt> until has generated all of the output it can with the
+provided input.
+<pre><b>
+        /* run inflate() on input until output buffer not full */
+        do {
+</b></pre>
+Just like in <tt>def()</tt>, the same output space is provided for each call of <tt>inflate()</tt>.
+<pre><b>
+            strm.avail_out = CHUNK;
+            strm.next_out = out;
+</b></pre>
+Now we run the decompression engine itself.  There is no need to adjust the flush parameter, since
+the <em>zlib</em> format is self-terminating. The main difference here is that there are
+return values that we need to pay attention to.  <tt>Z_DATA_ERROR</tt>
+indicates that <tt>inflate()</tt> detected an error in the <em>zlib</em> compressed data format,
+which means that either the data is not a <em>zlib</em> stream to begin with, or that the data was
+corrupted somewhere along the way since it was compressed.  The other error to be processed is
+<tt>Z_MEM_ERROR</tt>, which can occur since memory allocation is deferred until <tt>inflate()</tt>
+needs it, unlike <tt>deflate()</tt>, whose memory is allocated at the start by <tt>deflateInit()</tt>.
+<p>
+Advanced applications may use
+<tt>deflateSetDictionary()</tt> to prime <tt>deflate()</tt> with a set of likely data to improve the
+first 32K or so of compression.  This is noted in the <em>zlib</em> header, so <tt>inflate()</tt>
+requests that that dictionary be provided before it can start to decompress.  Without the dictionary,
+correct decompression is not possible.  For this routine, we have no idea what the dictionary is,
+so the <tt>Z_NEED_DICT</tt> indication is converted to a <tt>Z_DATA_ERROR</tt>.
+<p>
+<tt>inflate()</tt> can also return <tt>Z_STREAM_ERROR</tt>, which should not be possible here,
+but could be checked for as noted above for <tt>def()</tt>.  <tt>Z_BUF_ERROR</tt> does not need to be
+checked for here, for the same reasons noted for <tt>def()</tt>.  <tt>Z_STREAM_END</tt> will be
+checked for later.
+<pre><b>
+            ret = inflate(&amp;strm, Z_NO_FLUSH);
+            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
+            switch (ret) {
+            case Z_NEED_DICT:
+                ret = Z_DATA_ERROR;     /* and fall through */
+            case Z_DATA_ERROR:
+            case Z_MEM_ERROR:
+                (void)inflateEnd(&amp;strm);
+                return ret;
+            }
+</b></pre>
+The output of <tt>inflate()</tt> is handled identically to that of <tt>deflate()</tt>.
+<pre><b>
+            have = CHUNK - strm.avail_out;
+            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
+                (void)inflateEnd(&amp;strm);
+                return Z_ERRNO;
+            }
+</b></pre>
+The inner <tt>do</tt>-loop ends when <tt>inflate()</tt> has no more output as indicated
+by not filling the output buffer, just as for <tt>deflate()</tt>.  In this case, we cannot
+assert that <tt>strm.avail_in</tt> will be zero, since the deflate stream may end before the file
+does.
+<pre><b>
+        } while (strm.avail_out == 0);
+</b></pre><!-- -->
+The outer <tt>do</tt>-loop ends when <tt>inflate()</tt> reports that it has reached the
+end of the input <em>zlib</em> stream, has completed the decompression and integrity
+check, and has provided all of the output.  This is indicated by the <tt>inflate()</tt>
+return value <tt>Z_STREAM_END</tt>.  The inner loop is guaranteed to leave <tt>ret</tt>
+equal to <tt>Z_STREAM_END</tt> if the last chunk of the input file read contained the end
+of the <em>zlib</em> stream.  So if the return value is not <tt>Z_STREAM_END</tt>, the
+loop continues to read more input.
+<pre><b>
+        /* done when inflate() says it's done */
+    } while (ret != Z_STREAM_END);
+</b></pre><!-- -->
+At this point, decompression successfully completed, or we broke out of the loop due to no
+more data being available from the input file.  If the last <tt>inflate()</tt> return value
+is not <tt>Z_STREAM_END</tt>, then the <em>zlib</em> stream was incomplete and a data error
+is returned.  Otherwise, we return with a happy return value.  Of course, <tt>inflateEnd()</tt>
+is called first to avoid a memory leak.
+<pre><b>
+    /* clean up and return */
+    (void)inflateEnd(&amp;strm);
+    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
+}
+</b></pre><!-- -->
+That ends the routines that directly use <em>zlib</em>.  The following routines make this
+a command-line program by running data through the above routines from <tt>stdin</tt> to
+<tt>stdout</tt>, and handling any errors reported by <tt>def()</tt> or <tt>inf()</tt>.
+<p>
+<tt>zerr()</tt> is used to interpret the possible error codes from <tt>def()</tt>
+and <tt>inf()</tt>, as detailed in their comments above, and print out an error message.
+Note that these are only a subset of the possible return values from <tt>deflate()</tt>
+and <tt>inflate()</tt>.
+<pre><b>
+/* report a zlib or i/o error */
+void zerr(int ret)
+{
+    fputs("zpipe: ", stderr);
+    switch (ret) {
+    case Z_ERRNO:
+        if (ferror(stdin))
+            fputs("error reading stdin\n", stderr);
+        if (ferror(stdout))
+            fputs("error writing stdout\n", stderr);
+        break;
+    case Z_STREAM_ERROR:
+        fputs("invalid compression level\n", stderr);
+        break;
+    case Z_DATA_ERROR:
+        fputs("invalid or incomplete deflate data\n", stderr);
+        break;
+    case Z_MEM_ERROR:
+        fputs("out of memory\n", stderr);
+        break;
+    case Z_VERSION_ERROR:
+        fputs("zlib version mismatch!\n", stderr);
+    }
+}
+</b></pre><!-- -->
+Here is the <tt>main()</tt> routine used to test <tt>def()</tt> and <tt>inf()</tt>.  The
+<tt>zpipe</tt> command is simply a compression pipe from <tt>stdin</tt> to <tt>stdout</tt>, if
+no arguments are given, or it is a decompression pipe if <tt>zpipe -d</tt> is used.  If any other
+arguments are provided, no compression or decompression is performed.  Instead a usage
+message is displayed.  Examples are <tt>zpipe < foo.txt > foo.txt.z</tt> to compress, and
+<tt>zpipe -d < foo.txt.z > foo.txt</tt> to decompress.
+<pre><b>
+/* compress or decompress from stdin to stdout */
+int main(int argc, char **argv)
+{
+    int ret;
+
+    /* avoid end-of-line conversions */
+    SET_BINARY_MODE(stdin);
+    SET_BINARY_MODE(stdout);
+
+    /* do compression if no arguments */
+    if (argc == 1) {
+        ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION);
+        if (ret != Z_OK)
+            zerr(ret);
+        return ret;
+    }
+
+    /* do decompression if -d specified */
+    else if (argc == 2 &amp;&amp; strcmp(argv[1], "-d") == 0) {
+        ret = inf(stdin, stdout);
+        if (ret != Z_OK)
+            zerr(ret);
+        return ret;
+    }
+
+    /* otherwise, report usage */
+    else {
+        fputs("zpipe usage: zpipe [-d] &lt; source &gt; dest\n", stderr);
+        return 1;
+    }
+}
+</b></pre>
+<hr>
+<i>Copyright (c) 2004, 2005 by Mark Adler<br>Last modified 11 December 2005</i>
+</body>
+</html>
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zpipe.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zpipe.c
new file mode 100644 (file)
index 0000000..83535d1
--- /dev/null
@@ -0,0 +1,205 @@
+/* zpipe.c: example of proper use of zlib's inflate() and deflate()
+   Not copyrighted -- provided to the public domain
+   Version 1.4  11 December 2005  Mark Adler */
+
+/* Version history:
+   1.0  30 Oct 2004  First version
+   1.1   8 Nov 2004  Add void casting for unused return values
+                     Use switch statement for inflate() return values
+   1.2   9 Nov 2004  Add assertions to document zlib guarantees
+   1.3   6 Apr 2005  Remove incorrect assertion in inf()
+   1.4  11 Dec 2005  Add hack to avoid MSDOS end-of-line conversions
+                     Avoid some compiler warnings for input and output buffers
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include "zlib.h"
+
+#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
+#  include <fcntl.h>
+#  include <io.h>
+#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+#else
+#  define SET_BINARY_MODE(file)
+#endif
+
+#define CHUNK 16384
+
+/* Compress from file source to file dest until EOF on source.
+   def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
+   allocated for processing, Z_STREAM_ERROR if an invalid compression
+   level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
+   version of the library linked do not match, or Z_ERRNO if there is
+   an error reading or writing the files. */
+int def(FILE *source, FILE *dest, int level)
+{
+    int ret, flush;
+    unsigned have;
+    z_stream strm;
+    unsigned char in[CHUNK];
+    unsigned char out[CHUNK];
+
+    /* allocate deflate state */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    ret = deflateInit(&strm, level);
+    if (ret != Z_OK)
+        return ret;
+
+    /* compress until end of file */
+    do {
+        strm.avail_in = fread(in, 1, CHUNK, source);
+        if (ferror(source)) {
+            (void)deflateEnd(&strm);
+            return Z_ERRNO;
+        }
+        flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
+        strm.next_in = in;
+
+        /* run deflate() on input until output buffer not full, finish
+           compression if all of source has been read in */
+        do {
+            strm.avail_out = CHUNK;
+            strm.next_out = out;
+            ret = deflate(&strm, flush);    /* no bad return value */
+            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
+            have = CHUNK - strm.avail_out;
+            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
+                (void)deflateEnd(&strm);
+                return Z_ERRNO;
+            }
+        } while (strm.avail_out == 0);
+        assert(strm.avail_in == 0);     /* all input will be used */
+
+        /* done when last data in file processed */
+    } while (flush != Z_FINISH);
+    assert(ret == Z_STREAM_END);        /* stream will be complete */
+
+    /* clean up and return */
+    (void)deflateEnd(&strm);
+    return Z_OK;
+}
+
+/* Decompress from file source to file dest until stream ends or EOF.
+   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
+   allocated for processing, Z_DATA_ERROR if the deflate data is
+   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
+   the version of the library linked do not match, or Z_ERRNO if there
+   is an error reading or writing the files. */
+int inf(FILE *source, FILE *dest)
+{
+    int ret;
+    unsigned have;
+    z_stream strm;
+    unsigned char in[CHUNK];
+    unsigned char out[CHUNK];
+
+    /* allocate inflate state */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit(&strm);
+    if (ret != Z_OK)
+        return ret;
+
+    /* decompress until deflate stream ends or end of file */
+    do {
+        strm.avail_in = fread(in, 1, CHUNK, source);
+        if (ferror(source)) {
+            (void)inflateEnd(&strm);
+            return Z_ERRNO;
+        }
+        if (strm.avail_in == 0)
+            break;
+        strm.next_in = in;
+
+        /* run inflate() on input until output buffer not full */
+        do {
+            strm.avail_out = CHUNK;
+            strm.next_out = out;
+            ret = inflate(&strm, Z_NO_FLUSH);
+            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
+            switch (ret) {
+            case Z_NEED_DICT:
+                ret = Z_DATA_ERROR;     /* and fall through */
+            case Z_DATA_ERROR:
+            case Z_MEM_ERROR:
+                (void)inflateEnd(&strm);
+                return ret;
+            }
+            have = CHUNK - strm.avail_out;
+            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
+                (void)inflateEnd(&strm);
+                return Z_ERRNO;
+            }
+        } while (strm.avail_out == 0);
+
+        /* done when inflate() says it's done */
+    } while (ret != Z_STREAM_END);
+
+    /* clean up and return */
+    (void)inflateEnd(&strm);
+    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
+}
+
+/* report a zlib or i/o error */
+void zerr(int ret)
+{
+    fputs("zpipe: ", stderr);
+    switch (ret) {
+    case Z_ERRNO:
+        if (ferror(stdin))
+            fputs("error reading stdin\n", stderr);
+        if (ferror(stdout))
+            fputs("error writing stdout\n", stderr);
+        break;
+    case Z_STREAM_ERROR:
+        fputs("invalid compression level\n", stderr);
+        break;
+    case Z_DATA_ERROR:
+        fputs("invalid or incomplete deflate data\n", stderr);
+        break;
+    case Z_MEM_ERROR:
+        fputs("out of memory\n", stderr);
+        break;
+    case Z_VERSION_ERROR:
+        fputs("zlib version mismatch!\n", stderr);
+    }
+}
+
+/* compress or decompress from stdin to stdout */
+int main(int argc, char **argv)
+{
+    int ret;
+
+    /* avoid end-of-line conversions */
+    SET_BINARY_MODE(stdin);
+    SET_BINARY_MODE(stdout);
+
+    /* do compression if no arguments */
+    if (argc == 1) {
+        ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION);
+        if (ret != Z_OK)
+            zerr(ret);
+        return ret;
+    }
+
+    /* do decompression if -d specified */
+    else if (argc == 2 && strcmp(argv[1], "-d") == 0) {
+        ret = inf(stdin, stdout);
+        if (ret != Z_OK)
+            zerr(ret);
+        return ret;
+    }
+
+    /* otherwise, report usage */
+    else {
+        fputs("zpipe usage: zpipe [-d] < source > dest\n", stderr);
+        return 1;
+    }
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zran.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/examples/zran.c
new file mode 100644 (file)
index 0000000..617a130
--- /dev/null
@@ -0,0 +1,404 @@
+/* zran.c -- example of zlib/gzip stream indexing and random access
+ * Copyright (C) 2005 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+   Version 1.0  29 May 2005  Mark Adler */
+
+/* Illustrate the use of Z_BLOCK, inflatePrime(), and inflateSetDictionary()
+   for random access of a compressed file.  A file containing a zlib or gzip
+   stream is provided on the command line.  The compressed stream is decoded in
+   its entirety, and an index built with access points about every SPAN bytes
+   in the uncompressed output.  The compressed file is left open, and can then
+   be read randomly, having to decompress on the average SPAN/2 uncompressed
+   bytes before getting to the desired block of data.
+
+   An access point can be created at the start of any deflate block, by saving
+   the starting file offset and bit of that block, and the 32K bytes of
+   uncompressed data that precede that block.  Also the uncompressed offset of
+   that block is saved to provide a referece for locating a desired starting
+   point in the uncompressed stream.  build_index() works by decompressing the
+   input zlib or gzip stream a block at a time, and at the end of each block
+   deciding if enough uncompressed data has gone by to justify the creation of
+   a new access point.  If so, that point is saved in a data structure that
+   grows as needed to accommodate the points.
+
+   To use the index, an offset in the uncompressed data is provided, for which
+   the latest accees point at or preceding that offset is located in the index.
+   The input file is positioned to the specified location in the index, and if
+   necessary the first few bits of the compressed data is read from the file.
+   inflate is initialized with those bits and the 32K of uncompressed data, and
+   the decompression then proceeds until the desired offset in the file is
+   reached.  Then the decompression continues to read the desired uncompressed
+   data from the file.
+
+   Another approach would be to generate the index on demand.  In that case,
+   requests for random access reads from the compressed data would try to use
+   the index, but if a read far enough past the end of the index is required,
+   then further index entries would be generated and added.
+
+   There is some fair bit of overhead to starting inflation for the random
+   access, mainly copying the 32K byte dictionary.  So if small pieces of the
+   file are being accessed, it would make sense to implement a cache to hold
+   some lookahead and avoid many calls to extract() for small lengths.
+
+   Another way to build an index would be to use inflateCopy().  That would
+   not be constrained to have access points at block boundaries, but requires
+   more memory per access point, and also cannot be saved to file due to the
+   use of pointers in the state.  The approach here allows for storage of the
+   index in a file.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "zlib.h"
+
+#define local static
+
+#define SPAN 1048576L       /* desired distance between access points */
+#define WINSIZE 32768U      /* sliding window size */
+#define CHUNK 16384         /* file input buffer size */
+
+/* access point entry */
+struct point {
+    off_t out;          /* corresponding offset in uncompressed data */
+    off_t in;           /* offset in input file of first full byte */
+    int bits;           /* number of bits (1-7) from byte at in - 1, or 0 */
+    unsigned char window[WINSIZE];  /* preceding 32K of uncompressed data */
+};
+
+/* access point list */
+struct access {
+    int have;           /* number of list entries filled in */
+    int size;           /* number of list entries allocated */
+    struct point *list; /* allocated list */
+};
+
+/* Deallocate an index built by build_index() */
+local void free_index(struct access *index)
+{
+    if (index != NULL) {
+        free(index->list);
+        free(index);
+    }
+}
+
+/* Add an entry to the access point list.  If out of memory, deallocate the
+   existing list and return NULL. */
+local struct access *addpoint(struct access *index, int bits,
+    off_t in, off_t out, unsigned left, unsigned char *window)
+{
+    struct point *next;
+
+    /* if list is empty, create it (start with eight points) */
+    if (index == NULL) {
+        index = malloc(sizeof(struct access));
+        if (index == NULL) return NULL;
+        index->list = malloc(sizeof(struct point) << 3);
+        if (index->list == NULL) {
+            free(index);
+            return NULL;
+        }
+        index->size = 8;
+        index->have = 0;
+    }
+
+    /* if list is full, make it bigger */
+    else if (index->have == index->size) {
+        index->size <<= 1;
+        next = realloc(index->list, sizeof(struct point) * index->size);
+        if (next == NULL) {
+            free_index(index);
+            return NULL;
+        }
+        index->list = next;
+    }
+
+    /* fill in entry and increment how many we have */
+    next = index->list + index->have;
+    next->bits = bits;
+    next->in = in;
+    next->out = out;
+    if (left)
+        memcpy(next->window, window + WINSIZE - left, left);
+    if (left < WINSIZE)
+        memcpy(next->window + left, window, WINSIZE - left);
+    index->have++;
+
+    /* return list, possibly reallocated */
+    return index;
+}
+
+/* Make one entire pass through the compressed stream and build an index, with
+   access points about every span bytes of uncompressed output -- span is
+   chosen to balance the speed of random access against the memory requirements
+   of the list, about 32K bytes per access point.  Note that data after the end
+   of the first zlib or gzip stream in the file is ignored.  build_index()
+   returns the number of access points on success (>= 1), Z_MEM_ERROR for out
+   of memory, Z_DATA_ERROR for an error in the input file, or Z_ERRNO for a
+   file read error.  On success, *built points to the resulting index. */
+local int build_index(FILE *in, off_t span, struct access **built)
+{
+    int ret;
+    off_t totin, totout;        /* our own total counters to avoid 4GB limit */
+    off_t last;                 /* totout value of last access point */
+    struct access *index;       /* access points being generated */
+    z_stream strm;
+    unsigned char input[CHUNK];
+    unsigned char window[WINSIZE];
+
+    /* initialize inflate */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit2(&strm, 47);      /* automatic zlib or gzip decoding */
+    if (ret != Z_OK)
+        return ret;
+
+    /* inflate the input, maintain a sliding window, and build an index -- this
+       also validates the integrity of the compressed data using the check
+       information at the end of the gzip or zlib stream */
+    totin = totout = last = 0;
+    index = NULL;               /* will be allocated by first addpoint() */
+    strm.avail_out = 0;
+    do {
+        /* get some compressed data from input file */
+        strm.avail_in = fread(input, 1, CHUNK, in);
+        if (ferror(in)) {
+            ret = Z_ERRNO;
+            goto build_index_error;
+        }
+        if (strm.avail_in == 0) {
+            ret = Z_DATA_ERROR;
+            goto build_index_error;
+        }
+        strm.next_in = input;
+
+        /* process all of that, or until end of stream */
+        do {
+            /* reset sliding window if necessary */
+            if (strm.avail_out == 0) {
+                strm.avail_out = WINSIZE;
+                strm.next_out = window;
+            }
+
+            /* inflate until out of input, output, or at end of block --
+               update the total input and output counters */
+            totin += strm.avail_in;
+            totout += strm.avail_out;
+            ret = inflate(&strm, Z_BLOCK);      /* return at end of block */
+            totin -= strm.avail_in;
+            totout -= strm.avail_out;
+            if (ret == Z_NEED_DICT)
+                ret = Z_DATA_ERROR;
+            if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
+                goto build_index_error;
+            if (ret == Z_STREAM_END)
+                break;
+
+            /* if at end of block, consider adding an index entry (note that if
+               data_type indicates an end-of-block, then all of the
+               uncompressed data from that block has been delivered, and none
+               of the compressed data after that block has been consumed,
+               except for up to seven bits) -- the totout == 0 provides an
+               entry point after the zlib or gzip header, and assures that the
+               index always has at least one access point; we avoid creating an
+               access point after the last block by checking bit 6 of data_type
+             */
+            if ((strm.data_type & 128) && !(strm.data_type & 64) &&
+                (totout == 0 || totout - last > span)) {
+                index = addpoint(index, strm.data_type & 7, totin,
+                                 totout, strm.avail_out, window);
+                if (index == NULL) {
+                    ret = Z_MEM_ERROR;
+                    goto build_index_error;
+                }
+                last = totout;
+            }
+        } while (strm.avail_in != 0);
+    } while (ret != Z_STREAM_END);
+
+    /* clean up and return index (release unused entries in list) */
+    (void)inflateEnd(&strm);
+    index = realloc(index, sizeof(struct point) * index->have);
+    index->size = index->have;
+    *built = index;
+    return index->size;
+
+    /* return error */
+  build_index_error:
+    (void)inflateEnd(&strm);
+    if (index != NULL)
+        free_index(index);
+    return ret;
+}
+
+/* Use the index to read len bytes from offset into buf, return bytes read or
+   negative for error (Z_DATA_ERROR or Z_MEM_ERROR).  If data is requested past
+   the end of the uncompressed data, then extract() will return a value less
+   than len, indicating how much as actually read into buf.  This function
+   should not return a data error unless the file was modified since the index
+   was generated.  extract() may also return Z_ERRNO if there is an error on
+   reading or seeking the input file. */
+local int extract(FILE *in, struct access *index, off_t offset,
+                  unsigned char *buf, int len)
+{
+    int ret, skip;
+    z_stream strm;
+    struct point *here;
+    unsigned char input[CHUNK];
+    unsigned char discard[WINSIZE];
+
+    /* proceed only if something reasonable to do */
+    if (len < 0)
+        return 0;
+
+    /* find where in stream to start */
+    here = index->list;
+    ret = index->have;
+    while (--ret && here[1].out <= offset)
+        here++;
+
+    /* initialize file and inflate state to start there */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit2(&strm, -15);         /* raw inflate */
+    if (ret != Z_OK)
+        return ret;
+    ret = fseeko(in, here->in - (here->bits ? 1 : 0), SEEK_SET);
+    if (ret == -1)
+        goto extract_ret;
+    if (here->bits) {
+        ret = getc(in);
+        if (ret == -1) {
+            ret = ferror(in) ? Z_ERRNO : Z_DATA_ERROR;
+            goto extract_ret;
+        }
+        (void)inflatePrime(&strm, here->bits, ret >> (8 - here->bits));
+    }
+    (void)inflateSetDictionary(&strm, here->window, WINSIZE);
+
+    /* skip uncompressed bytes until offset reached, then satisfy request */
+    offset -= here->out;
+    strm.avail_in = 0;
+    skip = 1;                               /* while skipping to offset */
+    do {
+        /* define where to put uncompressed data, and how much */
+        if (offset == 0 && skip) {          /* at offset now */
+            strm.avail_out = len;
+            strm.next_out = buf;
+            skip = 0;                       /* only do this once */
+        }
+        if (offset > WINSIZE) {             /* skip WINSIZE bytes */
+            strm.avail_out = WINSIZE;
+            strm.next_out = discard;
+            offset -= WINSIZE;
+        }
+        else if (offset != 0) {             /* last skip */
+            strm.avail_out = (unsigned)offset;
+            strm.next_out = discard;
+            offset = 0;
+        }
+
+        /* uncompress until avail_out filled, or end of stream */
+        do {
+            if (strm.avail_in == 0) {
+                strm.avail_in = fread(input, 1, CHUNK, in);
+                if (ferror(in)) {
+                    ret = Z_ERRNO;
+                    goto extract_ret;
+                }
+                if (strm.avail_in == 0) {
+                    ret = Z_DATA_ERROR;
+                    goto extract_ret;
+                }
+                strm.next_in = input;
+            }
+            ret = inflate(&strm, Z_NO_FLUSH);       /* normal inflate */
+            if (ret == Z_NEED_DICT)
+                ret = Z_DATA_ERROR;
+            if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
+                goto extract_ret;
+            if (ret == Z_STREAM_END)
+                break;
+        } while (strm.avail_out != 0);
+
+        /* if reach end of stream, then don't keep trying to get more */
+        if (ret == Z_STREAM_END)
+            break;
+
+        /* do until offset reached and requested data read, or stream ends */
+    } while (skip);
+
+    /* compute number of uncompressed bytes read after offset */
+    ret = skip ? 0 : len - strm.avail_out;
+
+    /* clean up and return bytes read or error */
+  extract_ret:
+    (void)inflateEnd(&strm);
+    return ret;
+}
+
+/* Demonstrate the use of build_index() and extract() by processing the file
+   provided on the command line, and the extracting 16K from about 2/3rds of
+   the way through the uncompressed output, and writing that to stdout. */
+int main(int argc, char **argv)
+{
+    int len;
+    off_t offset;
+    FILE *in;
+    struct access *index = NULL;
+    unsigned char buf[CHUNK];
+
+    /* open input file */
+    if (argc != 2) {
+        fprintf(stderr, "usage: zran file.gz\n");
+        return 1;
+    }
+    in = fopen(argv[1], "rb");
+    if (in == NULL) {
+        fprintf(stderr, "zran: could not open %s for reading\n", argv[1]);
+        return 1;
+    }
+
+    /* build index */
+    len = build_index(in, SPAN, &index);
+    if (len < 0) {
+        fclose(in);
+        switch (len) {
+        case Z_MEM_ERROR:
+            fprintf(stderr, "zran: out of memory\n");
+            break;
+        case Z_DATA_ERROR:
+            fprintf(stderr, "zran: compressed data error in %s\n", argv[1]);
+            break;
+        case Z_ERRNO:
+            fprintf(stderr, "zran: read error on %s\n", argv[1]);
+            break;
+        default:
+            fprintf(stderr, "zran: error %d while building index\n", len);
+        }
+        return 1;
+    }
+    fprintf(stderr, "zran: built index with %d access points\n", len);
+
+    /* use index by reading some bytes from an arbitrary offset */
+    offset = (index->list[index->have - 1].out << 1) / 3;
+    len = extract(in, index, offset, buf, CHUNK);
+    if (len < 0)
+        fprintf(stderr, "zran: extraction failed: %s error\n",
+                len == Z_MEM_ERROR ? "out of memory" : "input corrupted");
+    else {
+        fwrite(buf, 1, len, stdout);
+        fprintf(stderr, "zran: extracted %d bytes at %llu\n", len, offset);
+    }
+
+    /* clean up and exit */
+    free_index(index);
+    fclose(in);
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzclose.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzclose.c
new file mode 100644 (file)
index 0000000..caeb99a
--- /dev/null
@@ -0,0 +1,25 @@
+/* gzclose.c -- zlib gzclose() function
+ * Copyright (C) 2004, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "gzguts.h"
+
+/* gzclose() is in a separate file so that it is linked in only if it is used.
+   That way the other gzclose functions can be used instead to avoid linking in
+   unneeded compression or decompression routines. */
+int ZEXPORT gzclose(file)
+    gzFile file;
+{
+#ifndef NO_GZCOMPRESS
+    gz_statep state;
+
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+
+    return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file);
+#else
+    return gzclose_r(file);
+#endif
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzguts.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzguts.h
new file mode 100644 (file)
index 0000000..3107c36
--- /dev/null
@@ -0,0 +1,190 @@
+/* gzguts.h -- zlib internal header definitions for gz* operations
+ * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#ifdef _LARGEFILE64_SOURCE
+#  ifndef _LARGEFILE_SOURCE
+#    define _LARGEFILE_SOURCE 1
+#  endif
+#  ifdef _FILE_OFFSET_BITS
+#    undef _FILE_OFFSET_BITS
+#  endif
+#endif
+
+#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ)
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
+#include <stdio.h>
+#include "zlib.h"
+#ifdef STDC
+#  include <string.h>
+#  include <stdlib.h>
+#  include <limits.h>
+#endif
+#include <fcntl.h>
+
+#ifdef __TURBOC__
+#  include <io.h>
+#endif
+
+#ifdef NO_DEFLATE       /* for compatibility with old definition */
+#  define NO_GZCOMPRESS
+#endif
+
+#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#if defined(__CYGWIN__)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#ifndef HAVE_VSNPRINTF
+#  ifdef MSDOS
+/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
+ but for now we just assume it doesn't. */
+#    define NO_vsnprintf
+#  endif
+#  ifdef __TURBOC__
+#    define NO_vsnprintf
+#  endif
+#  ifdef WIN32
+/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
+#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
+#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
+#         include <io.h>
+#         define vsnprintf _vsnprintf
+#      endif
+#    endif
+#  endif
+#  ifdef __SASC
+#    define NO_vsnprintf
+#  endif
+#  ifdef VMS
+#    define NO_vsnprintf
+#  endif
+#  ifdef __OS400__
+#    define NO_vsnprintf
+#  endif
+#  ifdef __MVS__
+#    define NO_vsnprintf
+#  endif
+#endif
+
+#ifndef local
+#  define local static
+#endif
+/* compile with -Dlocal if your debugger can't find static symbols */
+
+/* gz* functions always use library allocation functions */
+#ifndef STDC
+  extern voidp  malloc OF((uInt size));
+  extern void   free   OF((voidpf ptr));
+#endif
+
+/* get errno and strerror definition */
+#if defined UNDER_CE
+#  include <windows.h>
+#  define zstrerror() gz_strwinerror((DWORD)GetLastError())
+#else
+#  ifdef STDC
+#    include <errno.h>
+#    define zstrerror() strerror(errno)
+#  else
+#    define zstrerror() "stdio error (consult errno)"
+#  endif
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
+    ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+    ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+    ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+    ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+#endif
+
+/* default memLevel */
+#if MAX_MEM_LEVEL >= 8
+#  define DEF_MEM_LEVEL 8
+#else
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#endif
+
+/* default i/o buffer size -- double this for output when reading */
+#define GZBUFSIZE 8192
+
+/* gzip modes, also provide a little integrity check on the passed structure */
+#define GZ_NONE 0
+#define GZ_READ 7247
+#define GZ_WRITE 31153
+#define GZ_APPEND 1     /* mode set to GZ_WRITE after the file is opened */
+
+/* values for gz_state how */
+#define LOOK 0      /* look for a gzip header */
+#define COPY 1      /* copy input directly */
+#define GZIP 2      /* decompress a gzip stream */
+
+/* internal gzip file state data structure */
+typedef struct {
+        /* exposed contents for gzgetc() macro */
+    struct gzFile_s x;      /* "x" for exposed */
+                            /* x.have: number of bytes available at x.next */
+                            /* x.next: next output data to deliver or write */
+                            /* x.pos: current position in uncompressed data */
+        /* used for both reading and writing */
+    int mode;               /* see gzip modes above */
+    int fd;                 /* file descriptor */
+    char *path;             /* path or fd for error messages */
+    unsigned size;          /* buffer size, zero if not allocated yet */
+    unsigned want;          /* requested buffer size, default is GZBUFSIZE */
+    unsigned char *in;      /* input buffer */
+    unsigned char *out;     /* output buffer (double-sized when reading) */
+    int direct;             /* 0 if processing gzip, 1 if transparent */
+        /* just for reading */
+    int how;                /* 0: get header, 1: copy, 2: decompress */
+    z_off64_t start;        /* where the gzip data started, for rewinding */
+    int eof;                /* true if end of input file reached */
+    int past;               /* true if read requested past end */
+        /* just for writing */
+    int level;              /* compression level */
+    int strategy;           /* compression strategy */
+        /* seek request */
+    z_off64_t skip;         /* amount to skip (already rewound if backwards) */
+    int seek;               /* true if seek request pending */
+        /* error information */
+    int err;                /* error code */
+    char *msg;              /* error message */
+        /* zlib inflate or deflate stream */
+    z_stream strm;          /* stream structure in-place (not a pointer) */
+} gz_state;
+typedef gz_state FAR *gz_statep;
+
+/* shared functions */
+void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *));
+#if defined UNDER_CE
+char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error));
+#endif
+
+/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t
+   value -- needed when comparing unsigned to z_off64_t, which is signed
+   (possible z_off64_t types off_t, off64_t, and long are all signed) */
+#ifdef INT_MAX
+#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)
+#else
+unsigned ZLIB_INTERNAL gz_intmax OF((void));
+#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzlib.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzlib.c
new file mode 100644 (file)
index 0000000..7aedab8
--- /dev/null
@@ -0,0 +1,564 @@
+/* gzlib.c -- zlib functions common to reading and writing gzip files
+ * Copyright (C) 2004, 2010, 2011 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "gzguts.h"
+
+#if defined(_WIN32) && !defined(__BORLANDC__)
+#  define LSEEK _lseeki64
+#else
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#  define LSEEK lseek64
+#else
+#  define LSEEK lseek
+#endif
+#endif
+
+/* Local functions */
+local void gz_reset OF((gz_statep));
+local gzFile gz_open OF((const char *, int, const char *));
+
+#if defined UNDER_CE
+
+/* Map the Windows error number in ERROR to a locale-dependent error message
+   string and return a pointer to it.  Typically, the values for ERROR come
+   from GetLastError.
+
+   The string pointed to shall not be modified by the application, but may be
+   overwritten by a subsequent call to gz_strwinerror
+
+   The gz_strwinerror function does not change the current setting of
+   GetLastError. */
+char ZLIB_INTERNAL *gz_strwinerror (error)
+     DWORD error;
+{
+    static char buf[1024];
+
+    wchar_t *msgbuf;
+    DWORD lasterr = GetLastError();
+    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
+        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+        NULL,
+        error,
+        0, /* Default language */
+        (LPVOID)&msgbuf,
+        0,
+        NULL);
+    if (chars != 0) {
+        /* If there is an \r\n appended, zap it.  */
+        if (chars >= 2
+            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
+            chars -= 2;
+            msgbuf[chars] = 0;
+        }
+
+        if (chars > sizeof (buf) - 1) {
+            chars = sizeof (buf) - 1;
+            msgbuf[chars] = 0;
+        }
+
+        wcstombs(buf, msgbuf, chars + 1);
+        LocalFree(msgbuf);
+    }
+    else {
+        sprintf(buf, "unknown win32 error (%ld)", error);
+    }
+
+    SetLastError(lasterr);
+    return buf;
+}
+
+#endif /* UNDER_CE */
+
+/* Reset gzip file state */
+local void gz_reset(state)
+    gz_statep state;
+{
+    state->x.have = 0;              /* no output data available */
+    if (state->mode == GZ_READ) {   /* for reading ... */
+        state->eof = 0;             /* not at end of file */
+        state->past = 0;            /* have not read past end yet */
+        state->how = LOOK;          /* look for gzip header */
+    }
+    state->seek = 0;                /* no seek request pending */
+    gz_error(state, Z_OK, NULL);    /* clear error */
+    state->x.pos = 0;               /* no uncompressed data yet */
+    state->strm.avail_in = 0;       /* no input data yet */
+}
+
+/* Open a gzip file either by name or file descriptor. */
+local gzFile gz_open(path, fd, mode)
+    const char *path;
+    int fd;
+    const char *mode;
+{
+    gz_statep state;
+
+    /* check input */
+    if (path == NULL)
+        return NULL;
+
+    /* allocate gzFile structure to return */
+    state = malloc(sizeof(gz_state));
+    if (state == NULL)
+        return NULL;
+    state->size = 0;            /* no buffers allocated yet */
+    state->want = GZBUFSIZE;    /* requested buffer size */
+    state->msg = NULL;          /* no error message yet */
+
+    /* interpret mode */
+    state->mode = GZ_NONE;
+    state->level = Z_DEFAULT_COMPRESSION;
+    state->strategy = Z_DEFAULT_STRATEGY;
+    state->direct = 0;
+    while (*mode) {
+        if (*mode >= '0' && *mode <= '9')
+            state->level = *mode - '0';
+        else
+            switch (*mode) {
+            case 'r':
+                state->mode = GZ_READ;
+                break;
+#ifndef NO_GZCOMPRESS
+            case 'w':
+                state->mode = GZ_WRITE;
+                break;
+            case 'a':
+                state->mode = GZ_APPEND;
+                break;
+#endif
+            case '+':       /* can't read and write at the same time */
+                free(state);
+                return NULL;
+            case 'b':       /* ignore -- will request binary anyway */
+                break;
+            case 'f':
+                state->strategy = Z_FILTERED;
+                break;
+            case 'h':
+                state->strategy = Z_HUFFMAN_ONLY;
+                break;
+            case 'R':
+                state->strategy = Z_RLE;
+                break;
+            case 'F':
+                state->strategy = Z_FIXED;
+            case 'T':
+                state->direct = 1;
+            default:        /* could consider as an error, but just ignore */
+                ;
+            }
+        mode++;
+    }
+
+    /* must provide an "r", "w", or "a" */
+    if (state->mode == GZ_NONE) {
+        free(state);
+        return NULL;
+    }
+
+    /* can't force transparent read */
+    if (state->mode == GZ_READ) {
+        if (state->direct) {
+            free(state);
+            return NULL;
+        }
+        state->direct = 1;      /* for empty file */
+    }
+
+    /* save the path name for error messages */
+    state->path = malloc(strlen(path) + 1);
+    if (state->path == NULL) {
+        free(state);
+        return NULL;
+    }
+    strcpy(state->path, path);
+
+    /* open the file with the appropriate mode (or just use fd) */
+    state->fd = fd != -1 ? fd :
+        open(path,
+#ifdef O_LARGEFILE
+            O_LARGEFILE |
+#endif
+#ifdef O_BINARY
+            O_BINARY |
+#endif
+            (state->mode == GZ_READ ?
+                O_RDONLY :
+                (O_WRONLY | O_CREAT | (
+                    state->mode == GZ_WRITE ?
+                        O_TRUNC :
+                        O_APPEND))),
+            0666);
+    if (state->fd == -1) {
+        free(state->path);
+        free(state);
+        return NULL;
+    }
+    if (state->mode == GZ_APPEND)
+        state->mode = GZ_WRITE;         /* simplify later checks */
+
+    /* save the current position for rewinding (only if reading) */
+    if (state->mode == GZ_READ) {
+        state->start = LSEEK(state->fd, 0, SEEK_CUR);
+        if (state->start == -1) state->start = 0;
+    }
+
+    /* initialize stream */
+    gz_reset(state);
+
+    /* return stream */
+    return (gzFile)state;
+}
+
+/* -- see zlib.h -- */
+gzFile ZEXPORT gzopen(path, mode)
+    const char *path;
+    const char *mode;
+{
+    return gz_open(path, -1, mode);
+}
+
+/* -- see zlib.h -- */
+gzFile ZEXPORT gzopen64(path, mode)
+    const char *path;
+    const char *mode;
+{
+    return gz_open(path, -1, mode);
+}
+
+/* -- see zlib.h -- */
+gzFile ZEXPORT gzdopen(fd, mode)
+    int fd;
+    const char *mode;
+{
+    char *path;         /* identifier for error messages */
+    gzFile gz;
+
+    if (fd == -1 || (path = malloc(7 + 3 * sizeof(int))) == NULL)
+        return NULL;
+    sprintf(path, "<fd:%d>", fd);   /* for debugging */
+    gz = gz_open(path, fd, mode);
+    free(path);
+    return gz;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzbuffer(file, size)
+    gzFile file;
+    unsigned size;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return -1;
+
+    /* make sure we haven't already allocated memory */
+    if (state->size != 0)
+        return -1;
+
+    /* check and set requested size */
+    if (size < 2)
+        size = 2;               /* need two bytes to check magic header */
+    state->want = size;
+    return 0;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzrewind(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no error */
+    if (state->mode != GZ_READ ||
+            (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return -1;
+
+    /* back up and start over */
+    if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
+        return -1;
+    gz_reset(state);
+    return 0;
+}
+
+/* -- see zlib.h -- */
+z_off64_t ZEXPORT gzseek64(file, offset, whence)
+    gzFile file;
+    z_off64_t offset;
+    int whence;
+{
+    unsigned n;
+    z_off64_t ret;
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return -1;
+
+    /* check that there's no error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
+        return -1;
+
+    /* can only seek from start or relative to current position */
+    if (whence != SEEK_SET && whence != SEEK_CUR)
+        return -1;
+
+    /* normalize offset to a SEEK_CUR specification */
+    if (whence == SEEK_SET)
+        offset -= state->x.pos;
+    else if (state->seek)
+        offset += state->skip;
+    state->seek = 0;
+
+    /* if within raw area while reading, just go there */
+    if (state->mode == GZ_READ && state->how == COPY &&
+            state->x.pos + offset >= 0) {
+        ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR);
+        if (ret == -1)
+            return -1;
+        state->x.have = 0;
+        state->eof = 0;
+        state->past = 0;
+        state->seek = 0;
+        gz_error(state, Z_OK, NULL);
+        state->strm.avail_in = 0;
+        state->x.pos += offset;
+        return state->x.pos;
+    }
+
+    /* calculate skip amount, rewinding if needed for back seek when reading */
+    if (offset < 0) {
+        if (state->mode != GZ_READ)         /* writing -- can't go backwards */
+            return -1;
+        offset += state->x.pos;
+        if (offset < 0)                     /* before start of file! */
+            return -1;
+        if (gzrewind(file) == -1)           /* rewind, then skip to offset */
+            return -1;
+    }
+
+    /* if reading, skip what's in output buffer (one less gzgetc() check) */
+    if (state->mode == GZ_READ) {
+        n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
+            (unsigned)offset : state->x.have;
+        state->x.have -= n;
+        state->x.next += n;
+        state->x.pos += n;
+        offset -= n;
+    }
+
+    /* request skip (if not zero) */
+    if (offset) {
+        state->seek = 1;
+        state->skip = offset;
+    }
+    return state->x.pos + offset;
+}
+
+/* -- see zlib.h -- */
+z_off_t ZEXPORT gzseek(file, offset, whence)
+    gzFile file;
+    z_off_t offset;
+    int whence;
+{
+    z_off64_t ret;
+
+    ret = gzseek64(file, (z_off64_t)offset, whence);
+    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
+}
+
+/* -- see zlib.h -- */
+z_off64_t ZEXPORT gztell64(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return -1;
+
+    /* return position */
+    return state->x.pos + (state->seek ? state->skip : 0);
+}
+
+/* -- see zlib.h -- */
+z_off_t ZEXPORT gztell(file)
+    gzFile file;
+{
+    z_off64_t ret;
+
+    ret = gztell64(file);
+    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
+}
+
+/* -- see zlib.h -- */
+z_off64_t ZEXPORT gzoffset64(file)
+    gzFile file;
+{
+    z_off64_t offset;
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return -1;
+
+    /* compute and return effective offset in file */
+    offset = LSEEK(state->fd, 0, SEEK_CUR);
+    if (offset == -1)
+        return -1;
+    if (state->mode == GZ_READ)             /* reading */
+        offset -= state->strm.avail_in;     /* don't count buffered input */
+    return offset;
+}
+
+/* -- see zlib.h -- */
+z_off_t ZEXPORT gzoffset(file)
+    gzFile file;
+{
+    z_off64_t ret;
+
+    ret = gzoffset64(file);
+    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzeof(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return 0;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return 0;
+
+    /* return end-of-file state */
+    return state->mode == GZ_READ ? state->past : 0;
+}
+
+/* -- see zlib.h -- */
+const char * ZEXPORT gzerror(file, errnum)
+    gzFile file;
+    int *errnum;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return NULL;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return NULL;
+
+    /* return error information */
+    if (errnum != NULL)
+        *errnum = state->err;
+    return state->msg == NULL ? "" : state->msg;
+}
+
+/* -- see zlib.h -- */
+void ZEXPORT gzclearerr(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return;
+
+    /* clear error and end-of-file */
+    if (state->mode == GZ_READ) {
+        state->eof = 0;
+        state->past = 0;
+    }
+    gz_error(state, Z_OK, NULL);
+}
+
+/* Create an error message in allocated memory and set state->err and
+   state->msg accordingly.  Free any previous error message already there.  Do
+   not try to free or allocate space if the error is Z_MEM_ERROR (out of
+   memory).  Simply save the error message as a static string.  If there is an
+   allocation failure constructing the error message, then convert the error to
+   out of memory. */
+void ZLIB_INTERNAL gz_error(state, err, msg)
+    gz_statep state;
+    int err;
+    const char *msg;
+{
+    /* free previously allocated message and clear */
+    if (state->msg != NULL) {
+        if (state->err != Z_MEM_ERROR)
+            free(state->msg);
+        state->msg = NULL;
+    }
+
+    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
+    if (err != Z_OK && err != Z_BUF_ERROR)
+        state->x.have = 0;
+
+    /* set error code, and if no message, then done */
+    state->err = err;
+    if (msg == NULL)
+        return;
+
+    /* for an out of memory error, save as static string */
+    if (err == Z_MEM_ERROR) {
+        state->msg = (char *)msg;
+        return;
+    }
+
+    /* construct error message with path */
+    if ((state->msg = malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) {
+        state->err = Z_MEM_ERROR;
+        state->msg = (char *)"out of memory";
+        return;
+    }
+    strcpy(state->msg, state->path);
+    strcat(state->msg, ": ");
+    strcat(state->msg, msg);
+    return;
+}
+
+#ifndef INT_MAX
+/* portably return maximum value for an int (when limits.h presumed not
+   available) -- we need to do this to cover cases where 2's complement not
+   used, since C standard permits 1's complement and sign-bit representations,
+   otherwise we could just use ((unsigned)-1) >> 1 */
+unsigned ZLIB_INTERNAL gz_intmax()
+{
+    unsigned p, q;
+
+    p = 1;
+    do {
+        q = p;
+        p <<= 1;
+        p++;
+    } while (p > q);
+    return q >> 1;
+}
+#endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzread.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzread.c
new file mode 100644 (file)
index 0000000..46d40e0
--- /dev/null
@@ -0,0 +1,584 @@
+/* gzread.c -- zlib functions for reading gzip files
+ * Copyright (C) 2004, 2005, 2010, 2011 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "gzguts.h"
+
+/* Local functions */
+local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));
+local int gz_avail OF((gz_statep));
+local int gz_look OF((gz_statep));
+local int gz_decomp OF((gz_statep));
+local int gz_fetch OF((gz_statep));
+local int gz_skip OF((gz_statep, z_off64_t));
+
+/* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from
+   state->fd, and update state->eof, state->err, and state->msg as appropriate.
+   This function needs to loop on read(), since read() is not guaranteed to
+   read the number of bytes requested, depending on the type of descriptor. */
+local int gz_load(state, buf, len, have)
+    gz_statep state;
+    unsigned char *buf;
+    unsigned len;
+    unsigned *have;
+{
+    int ret;
+
+    *have = 0;
+    do {
+        ret = read(state->fd, buf + *have, len - *have);
+        if (ret <= 0)
+            break;
+        *have += ret;
+    } while (*have < len);
+    if (ret < 0) {
+        gz_error(state, Z_ERRNO, zstrerror());
+        return -1;
+    }
+    if (ret == 0)
+        state->eof = 1;
+    return 0;
+}
+
+/* Load up input buffer and set eof flag if last data loaded -- return -1 on
+   error, 0 otherwise.  Note that the eof flag is set when the end of the input
+   file is reached, even though there may be unused data in the buffer.  Once
+   that data has been used, no more attempts will be made to read the file.
+   If strm->avail_in != 0, then the current data is moved to the beginning of
+   the input buffer, and then the remainder of the buffer is loaded with the
+   available data from the input file. */
+local int gz_avail(state)
+    gz_statep state;
+{
+    unsigned got;
+    z_streamp strm = &(state->strm);
+
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
+        return -1;
+    if (state->eof == 0) {
+        if (strm->avail_in)
+            memmove(state->in, strm->next_in, strm->avail_in);
+        if (gz_load(state, state->in + strm->avail_in,
+                    state->size - strm->avail_in, &got) == -1)
+            return -1;
+        strm->avail_in += got;
+        strm->next_in = state->in;
+    }
+    return 0;
+}
+
+/* Look for gzip header, set up for inflate or copy.  state->x.have must be 0.
+   If this is the first time in, allocate required memory.  state->how will be
+   left unchanged if there is no more input data available, will be set to COPY
+   if there is no gzip header and direct copying will be performed, or it will
+   be set to GZIP for decompression.  If direct copying, then leftover input
+   data from the input buffer will be copied to the output buffer.  In that
+   case, all further file reads will be directly to either the output buffer or
+   a user buffer.  If decompressing, the inflate state will be initialized.
+   gz_look() will return 0 on success or -1 on failure. */
+local int gz_look(state)
+    gz_statep state;
+{
+    z_streamp strm = &(state->strm);
+
+    /* allocate read buffers and inflate memory */
+    if (state->size == 0) {
+        /* allocate buffers */
+        state->in = malloc(state->want);
+        state->out = malloc(state->want << 1);
+        if (state->in == NULL || state->out == NULL) {
+            if (state->out != NULL)
+                free(state->out);
+            if (state->in != NULL)
+                free(state->in);
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+        state->size = state->want;
+
+        /* allocate inflate memory */
+        state->strm.zalloc = Z_NULL;
+        state->strm.zfree = Z_NULL;
+        state->strm.opaque = Z_NULL;
+        state->strm.avail_in = 0;
+        state->strm.next_in = Z_NULL;
+        if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) {    /* gunzip */
+            free(state->out);
+            free(state->in);
+            state->size = 0;
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+    }
+
+    /* get at least the magic bytes in the input buffer */
+    if (strm->avail_in < 2) {
+        if (gz_avail(state) == -1)
+            return -1;
+        if (strm->avail_in == 0)
+            return 0;
+    }
+
+    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is
+       a logical dilemma here when considering the case of a partially written
+       gzip file, to wit, if a single 31 byte is written, then we cannot tell
+       whether this is a single-byte file, or just a partially written gzip
+       file -- for here we assume that if a gzip file is being written, then
+       the header will be written in a single operation, so that reading a
+       single byte is sufficient indication that it is not a gzip file) */
+    if (strm->avail_in > 1 &&
+            strm->next_in[0] == 31 && strm->next_in[1] == 139) {
+        inflateReset(strm);
+        state->how = GZIP;
+        state->direct = 0;
+        return 0;
+    }
+
+    /* no gzip header -- if we were decoding gzip before, then this is trailing
+       garbage.  Ignore the trailing garbage and finish. */
+    if (state->direct == 0) {
+        strm->avail_in = 0;
+        state->eof = 1;
+        state->x.have = 0;
+        return 0;
+    }
+
+    /* doing raw i/o, copy any leftover input to output -- this assumes that
+       the output buffer is larger than the input buffer, which also assures
+       space for gzungetc() */
+    state->x.next = state->out;
+    if (strm->avail_in) {
+        memcpy(state->x.next, strm->next_in, strm->avail_in);
+        state->x.have = strm->avail_in;
+        strm->avail_in = 0;
+    }
+    state->how = COPY;
+    state->direct = 1;
+    return 0;
+}
+
+/* Decompress from input to the provided next_out and avail_out in the state.
+   On return, state->x.have and state->x.next point to the just decompressed
+   data.  If the gzip stream completes, state->how is reset to LOOK to look for
+   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0
+   on success, -1 on failure. */
+local int gz_decomp(state)
+    gz_statep state;
+{
+    int ret = Z_OK;
+    unsigned had;
+    z_streamp strm = &(state->strm);
+
+    /* fill output buffer up to end of deflate stream */
+    had = strm->avail_out;
+    do {
+        /* get more input for inflate() */
+        if (strm->avail_in == 0 && gz_avail(state) == -1)
+            return -1;
+        if (strm->avail_in == 0) {
+            gz_error(state, Z_BUF_ERROR, "unexpected end of file");
+            break;
+        }
+
+        /* decompress and handle errors */
+        ret = inflate(strm, Z_NO_FLUSH);
+        if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
+            gz_error(state, Z_STREAM_ERROR,
+                     "internal error: inflate stream corrupt");
+            return -1;
+        }
+        if (ret == Z_MEM_ERROR) {
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */
+            gz_error(state, Z_DATA_ERROR,
+                     strm->msg == NULL ? "compressed data error" : strm->msg);
+            return -1;
+        }
+    } while (strm->avail_out && ret != Z_STREAM_END);
+
+    /* update available output */
+    state->x.have = had - strm->avail_out;
+    state->x.next = strm->next_out - state->x.have;
+
+    /* if the gzip stream completed successfully, look for another */
+    if (ret == Z_STREAM_END)
+        state->how = LOOK;
+
+    /* good decompression */
+    return 0;
+}
+
+/* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.
+   Data is either copied from the input file or decompressed from the input
+   file depending on state->how.  If state->how is LOOK, then a gzip header is
+   looked for to determine whether to copy or decompress.  Returns -1 on error,
+   otherwise 0.  gz_fetch() will leave state->how as COPY or GZIP unless the
+   end of the input file has been reached and all data has been processed.  */
+local int gz_fetch(state)
+    gz_statep state;
+{
+    z_streamp strm = &(state->strm);
+
+    do {
+        switch(state->how) {
+        case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */
+            if (gz_look(state) == -1)
+                return -1;
+            if (state->how == LOOK)
+                return 0;
+            break;
+        case COPY:      /* -> COPY */
+            if (gz_load(state, state->out, state->size << 1, &(state->x.have))
+                    == -1)
+                return -1;
+            state->x.next = state->out;
+            return 0;
+        case GZIP:      /* -> GZIP or LOOK (if end of gzip stream) */
+            strm->avail_out = state->size << 1;
+            strm->next_out = state->out;
+            if (gz_decomp(state) == -1)
+                return -1;
+        }
+    } while (state->x.have == 0 && (!state->eof || strm->avail_in));
+    return 0;
+}
+
+/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */
+local int gz_skip(state, len)
+    gz_statep state;
+    z_off64_t len;
+{
+    unsigned n;
+
+    /* skip over len bytes or reach end-of-file, whichever comes first */
+    while (len)
+        /* skip over whatever is in output buffer */
+        if (state->x.have) {
+            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?
+                (unsigned)len : state->x.have;
+            state->x.have -= n;
+            state->x.next += n;
+            state->x.pos += n;
+            len -= n;
+        }
+
+        /* output buffer empty -- return if we're at the end of the input */
+        else if (state->eof && state->strm.avail_in == 0)
+            break;
+
+        /* need more data to skip -- load up output buffer */
+        else {
+            /* get more output, looking for header if required */
+            if (gz_fetch(state) == -1)
+                return -1;
+        }
+    return 0;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzread(file, buf, len)
+    gzFile file;
+    voidp buf;
+    unsigned len;
+{
+    unsigned got, n;
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+            (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return -1;
+
+    /* since an int is returned, make sure len fits in one, otherwise return
+       with an error (this avoids the flaw in the interface) */
+    if ((int)len < 0) {
+        gz_error(state, Z_DATA_ERROR, "requested length does not fit in int");
+        return -1;
+    }
+
+    /* if len is zero, avoid unnecessary operations */
+    if (len == 0)
+        return 0;
+
+    /* process a skip request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_skip(state, state->skip) == -1)
+            return -1;
+    }
+
+    /* get len bytes to buf, or less than len if at the end */
+    got = 0;
+    do {
+        /* first just try copying data from the output buffer */
+        if (state->x.have) {
+            n = state->x.have > len ? len : state->x.have;
+            memcpy(buf, state->x.next, n);
+            state->x.next += n;
+            state->x.have -= n;
+        }
+
+        /* output buffer empty -- return if we're at the end of the input */
+        else if (state->eof && strm->avail_in == 0) {
+            state->past = 1;        /* tried to read past end */
+            break;
+        }
+
+        /* need output data -- for small len or new stream load up our output
+           buffer */
+        else if (state->how == LOOK || len < (state->size << 1)) {
+            /* get more output, looking for header if required */
+            if (gz_fetch(state) == -1)
+                return -1;
+            continue;       /* no progress yet -- go back to memcpy() above */
+            /* the copy above assures that we will leave with space in the
+               output buffer, allowing at least one gzungetc() to succeed */
+        }
+
+        /* large len -- read directly into user buffer */
+        else if (state->how == COPY) {      /* read directly */
+            if (gz_load(state, buf, len, &n) == -1)
+                return -1;
+        }
+
+        /* large len -- decompress directly into user buffer */
+        else {  /* state->how == GZIP */
+            strm->avail_out = len;
+            strm->next_out = buf;
+            if (gz_decomp(state) == -1)
+                return -1;
+            n = state->x.have;
+            state->x.have = 0;
+        }
+
+        /* update progress */
+        len -= n;
+        buf = (char *)buf + n;
+        got += n;
+        state->x.pos += n;
+    } while (len);
+
+    /* return number of bytes read into user buffer (will fit in int) */
+    return (int)got;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzgetc_(file)
+    gzFile file;
+{
+    int ret;
+    unsigned char buf[1];
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return -1;
+
+    /* try output buffer (no need to check for skip request) */
+    if (state->x.have) {
+        state->x.have--;
+        state->x.pos++;
+        return *(state->x.next)++;
+    }
+
+    /* nothing there -- try gzread() */
+    ret = gzread(file, buf, 1);
+    return ret < 1 ? -1 : buf[0];
+}
+
+#undef gzgetc
+int ZEXPORT gzgetc(file)
+gzFile file;
+{
+    return gzgetc_(file);
+}    
+
+/* -- see zlib.h -- */
+int ZEXPORT gzungetc(c, file)
+    int c;
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return -1;
+
+    /* process a skip request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_skip(state, state->skip) == -1)
+            return -1;
+    }
+
+    /* can't push EOF */
+    if (c < 0)
+        return -1;
+
+    /* if output buffer empty, put byte at end (allows more pushing) */
+    if (state->x.have == 0) {
+        state->x.have = 1;
+        state->x.next = state->out + (state->size << 1) - 1;
+        state->x.next[0] = c;
+        state->x.pos--;
+        state->past = 0;
+        return c;
+    }
+
+    /* if no room, give up (must have already done a gzungetc()) */
+    if (state->x.have == (state->size << 1)) {
+        gz_error(state, Z_DATA_ERROR, "out of room to push characters");
+        return -1;
+    }
+
+    /* slide output data if needed and insert byte before existing data */
+    if (state->x.next == state->out) {
+        unsigned char *src = state->out + state->x.have;
+        unsigned char *dest = state->out + (state->size << 1);
+        while (src > state->out)
+            *--dest = *--src;
+        state->x.next = dest;
+    }
+    state->x.have++;
+    state->x.next--;
+    state->x.next[0] = c;
+    state->x.pos--;
+    state->past = 0;
+    return c;
+}
+
+/* -- see zlib.h -- */
+char * ZEXPORT gzgets(file, buf, len)
+    gzFile file;
+    char *buf;
+    int len;
+{
+    unsigned left, n;
+    char *str;
+    unsigned char *eol;
+    gz_statep state;
+
+    /* check parameters and get internal structure */
+    if (file == NULL || buf == NULL || len < 1)
+        return NULL;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return NULL;
+
+    /* process a skip request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_skip(state, state->skip) == -1)
+            return NULL;
+    }
+
+    /* copy output bytes up to new line or len - 1, whichever comes first --
+       append a terminating zero to the string (we don't check for a zero in
+       the contents, let the user worry about that) */
+    str = buf;
+    left = (unsigned)len - 1;
+    if (left) do {
+        /* assure that something is in the output buffer */
+        if (state->x.have == 0 && gz_fetch(state) == -1)
+            return NULL;                /* error */
+        if (state->x.have == 0) {       /* end of file */
+            state->past = 1;            /* read past end */
+            break;                      /* return what we have */
+        }
+
+        /* look for end-of-line in current output buffer */
+        n = state->x.have > left ? left : state->x.have;
+        eol = memchr(state->x.next, '\n', n);
+        if (eol != NULL)
+            n = (unsigned)(eol - state->x.next) + 1;
+
+        /* copy through end-of-line, or remainder if not found */
+        memcpy(buf, state->x.next, n);
+        state->x.have -= n;
+        state->x.next += n;
+        state->x.pos += n;
+        left -= n;
+        buf += n;
+    } while (left && eol == NULL);
+
+    /* return terminated string, or if nothing, end of file */
+    if (buf == str)
+        return NULL;
+    buf[0] = 0;
+    return str;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzdirect(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return 0;
+    state = (gz_statep)file;
+
+    /* if the state is not known, but we can find out, then do so (this is
+       mainly for right after a gzopen() or gzdopen()) */
+    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)
+        (void)gz_look(state);
+
+    /* return 1 if transparent, 0 if processing a gzip stream */
+    return state->direct;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzclose_r(file)
+    gzFile file;
+{
+    int ret, err;
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+
+    /* check that we're reading */
+    if (state->mode != GZ_READ)
+        return Z_STREAM_ERROR;
+
+    /* free memory and close file */
+    if (state->size) {
+        inflateEnd(&(state->strm));
+        free(state->out);
+        free(state->in);
+    }
+    err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;
+    gz_error(state, Z_OK, NULL);
+    free(state->path);
+    ret = close(state->fd);
+    free(state);
+    return ret ? Z_ERRNO : err;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzwrite.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/gzwrite.c
new file mode 100644 (file)
index 0000000..caa35b6
--- /dev/null
@@ -0,0 +1,593 @@
+/* gzwrite.c -- zlib functions for writing gzip files
+ * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "gzguts.h"
+
+/* Local functions */
+local int gz_init OF((gz_statep));
+local int gz_comp OF((gz_statep, int));
+local int gz_zero OF((gz_statep, z_off64_t));
+
+/* Initialize state for writing a gzip file.  Mark initialization by setting
+   state->size to non-zero.  Return -1 on failure or 0 on success. */
+local int gz_init(state)
+    gz_statep state;
+{
+    int ret;
+    z_streamp strm = &(state->strm);
+
+    /* allocate input buffer */
+    state->in = malloc(state->want);
+    if (state->in == NULL) {
+        gz_error(state, Z_MEM_ERROR, "out of memory");
+        return -1;
+    }
+
+    /* only need output buffer and deflate state if compressing */
+    if (!state->direct) {
+        /* allocate output buffer */
+        state->out = malloc(state->want);
+        if (state->out == NULL) {
+            free(state->in);
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+
+        /* allocate deflate memory, set up for gzip compression */
+        strm->zalloc = Z_NULL;
+        strm->zfree = Z_NULL;
+        strm->opaque = Z_NULL;
+        ret = deflateInit2(strm, state->level, Z_DEFLATED,
+                           MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy);
+        if (ret != Z_OK) {
+            free(state->out);
+            free(state->in);
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+    }
+
+    /* mark state as initialized */
+    state->size = state->want;
+
+    /* initialize write buffer if compressing */
+    if (!state->direct) {
+        strm->avail_out = state->size;
+        strm->next_out = state->out;
+        state->x.next = strm->next_out;
+    }
+    return 0;
+}
+
+/* Compress whatever is at avail_in and next_in and write to the output file.
+   Return -1 if there is an error writing to the output file, otherwise 0.
+   flush is assumed to be a valid deflate() flush value.  If flush is Z_FINISH,
+   then the deflate() state is reset to start a new gzip stream.  If gz->direct
+   is true, then simply write to the output file without compressing, and
+   ignore flush. */
+local int gz_comp(state, flush)
+    gz_statep state;
+    int flush;
+{
+    int ret, got;
+    unsigned have;
+    z_streamp strm = &(state->strm);
+
+    /* allocate memory if this is the first time through */
+    if (state->size == 0 && gz_init(state) == -1)
+        return -1;
+
+    /* write directly if requested */
+    if (state->direct) {
+        got = write(state->fd, strm->next_in, strm->avail_in);
+        if (got < 0 || (unsigned)got != strm->avail_in) {
+            gz_error(state, Z_ERRNO, zstrerror());
+            return -1;
+        }
+        strm->avail_in = 0;
+        return 0;
+    }
+
+    /* run deflate() on provided input until it produces no more output */
+    ret = Z_OK;
+    do {
+        /* write out current buffer contents if full, or if flushing, but if
+           doing Z_FINISH then don't write until we get to Z_STREAM_END */
+        if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
+            (flush != Z_FINISH || ret == Z_STREAM_END))) {
+            have = (unsigned)(strm->next_out - state->x.next);
+            if (have && ((got = write(state->fd, state->x.next, have)) < 0 ||
+                         (unsigned)got != have)) {
+                gz_error(state, Z_ERRNO, zstrerror());
+                return -1;
+            }
+            if (strm->avail_out == 0) {
+                strm->avail_out = state->size;
+                strm->next_out = state->out;
+            }
+            state->x.next = strm->next_out;
+        }
+
+        /* compress */
+        have = strm->avail_out;
+        ret = deflate(strm, flush);
+        if (ret == Z_STREAM_ERROR) {
+            gz_error(state, Z_STREAM_ERROR,
+                      "internal error: deflate stream corrupt");
+            return -1;
+        }
+        have -= strm->avail_out;
+    } while (have);
+
+    /* if that completed a deflate stream, allow another to start */
+    if (flush == Z_FINISH)
+        deflateReset(strm);
+
+    /* all done, no errors */
+    return 0;
+}
+
+/* Compress len zeros to output.  Return -1 on error, 0 on success. */
+local int gz_zero(state, len)
+    gz_statep state;
+    z_off64_t len;
+{
+    int first;
+    unsigned n;
+    z_streamp strm = &(state->strm);
+
+    /* consume whatever's left in the input buffer */
+    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
+        return -1;
+
+    /* compress len zeros (len guaranteed > 0) */
+    first = 1;
+    while (len) {
+        n = GT_OFF(state->size) || (z_off64_t)state->size > len ?
+            (unsigned)len : state->size;
+        if (first) {
+            memset(state->in, 0, n);
+            first = 0;
+        }
+        strm->avail_in = n;
+        strm->next_in = state->in;
+        state->x.pos += n;
+        if (gz_comp(state, Z_NO_FLUSH) == -1)
+            return -1;
+        len -= n;
+    }
+    return 0;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzwrite(file, buf, len)
+    gzFile file;
+    voidpc buf;
+    unsigned len;
+{
+    unsigned put = len;
+    unsigned n;
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return 0;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return 0;
+
+    /* since an int is returned, make sure len fits in one, otherwise return
+       with an error (this avoids the flaw in the interface) */
+    if ((int)len < 0) {
+        gz_error(state, Z_DATA_ERROR, "requested length does not fit in int");
+        return 0;
+    }
+
+    /* if len is zero, avoid unnecessary operations */
+    if (len == 0)
+        return 0;
+
+    /* allocate memory if this is the first time through */
+    if (state->size == 0 && gz_init(state) == -1)
+        return 0;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return 0;
+    }
+
+    /* for small len, copy to input buffer, otherwise compress directly */
+    if (len < state->size) {
+        /* copy to input buffer, compress when full */
+        do {
+            if (strm->avail_in == 0)
+                strm->next_in = state->in;
+            n = state->size - strm->avail_in;
+            if (n > len)
+                n = len;
+            memcpy(strm->next_in + strm->avail_in, buf, n);
+            strm->avail_in += n;
+            state->x.pos += n;
+            buf = (char *)buf + n;
+            len -= n;
+            if (len && gz_comp(state, Z_NO_FLUSH) == -1)
+                return 0;
+        } while (len);
+    }
+    else {
+        /* consume whatever's left in the input buffer */
+        if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
+            return 0;
+
+        /* directly compress user buffer to file */
+        strm->avail_in = len;
+        strm->next_in = (voidp)buf;
+        state->x.pos += len;
+        if (gz_comp(state, Z_NO_FLUSH) == -1)
+            return 0;
+    }
+
+    /* input was all buffered or compressed (put will fit in int) */
+    return (int)put;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzputc(file, c)
+    gzFile file;
+    int c;
+{
+    unsigned char buf[1];
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return -1;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return -1;
+    }
+
+    /* try writing to input buffer for speed (state->size == 0 if buffer not
+       initialized) */
+    if (strm->avail_in < state->size) {
+        if (strm->avail_in == 0)
+            strm->next_in = state->in;
+        strm->next_in[strm->avail_in++] = c;
+        state->x.pos++;
+        return c & 0xff;
+    }
+
+    /* no room in buffer or not initialized, use gz_write() */
+    buf[0] = c;
+    if (gzwrite(file, buf, 1) != 1)
+        return -1;
+    return c & 0xff;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzputs(file, str)
+    gzFile file;
+    const char *str;
+{
+    int ret;
+    unsigned len;
+
+    /* write string */
+    len = (unsigned)strlen(str);
+    ret = gzwrite(file, str, len);
+    return ret == 0 && len != 0 ? -1 : ret;
+}
+
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#include <stdarg.h>
+
+/* -- see zlib.h -- */
+int ZEXPORTVA gzprintf (gzFile file, const char *format, ...)
+{
+    int size, len;
+    gz_statep state;
+    z_streamp strm;
+    va_list va;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return 0;
+
+    /* make sure we have some buffer space */
+    if (state->size == 0 && gz_init(state) == -1)
+        return 0;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return 0;
+    }
+
+    /* consume whatever's left in the input buffer */
+    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
+        return 0;
+
+    /* do the printf() into the input buffer, put length in len */
+    size = (int)(state->size);
+    state->in[size - 1] = 0;
+    va_start(va, format);
+#ifdef NO_vsnprintf
+#  ifdef HAS_vsprintf_void
+    (void)vsprintf(state->in, format, va);
+    va_end(va);
+    for (len = 0; len < size; len++)
+        if (state->in[len] == 0) break;
+#  else
+    len = vsprintf(state->in, format, va);
+    va_end(va);
+#  endif
+#else
+#  ifdef HAS_vsnprintf_void
+    (void)vsnprintf(state->in, size, format, va);
+    va_end(va);
+    len = strlen(state->in);
+#  else
+    len = vsnprintf((char *)(state->in), size, format, va);
+    va_end(va);
+#  endif
+#endif
+
+    /* check that printf() results fit in buffer */
+    if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
+        return 0;
+
+    /* update buffer and position, defer compression until needed */
+    strm->avail_in = (unsigned)len;
+    strm->next_in = state->in;
+    state->x.pos += len;
+    return len;
+}
+
+#else /* !STDC && !Z_HAVE_STDARG_H */
+
+/* -- see zlib.h -- */
+int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
+                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
+    gzFile file;
+    const char *format;
+    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
+        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
+{
+    int size, len;
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that can really pass pointer in ints */
+    if (sizeof(int) != sizeof(void *))
+        return 0;
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return 0;
+
+    /* make sure we have some buffer space */
+    if (state->size == 0 && gz_init(state) == -1)
+        return 0;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return 0;
+    }
+
+    /* consume whatever's left in the input buffer */
+    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
+        return 0;
+
+    /* do the printf() into the input buffer, put length in len */
+    size = (int)(state->size);
+    state->in[size - 1] = 0;
+#ifdef NO_snprintf
+#  ifdef HAS_sprintf_void
+    sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8,
+            a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+    for (len = 0; len < size; len++)
+        if (state->in[len] == 0) break;
+#  else
+    len = sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8,
+                a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+#  endif
+#else
+#  ifdef HAS_snprintf_void
+    snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8,
+             a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+    len = strlen(state->in);
+#  else
+    len = snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8,
+                 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+#  endif
+#endif
+
+    /* check that printf() results fit in buffer */
+    if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
+        return 0;
+
+    /* update buffer and position, defer compression until needed */
+    strm->avail_in = (unsigned)len;
+    strm->next_in = state->in;
+    state->x.pos += len;
+    return len;
+}
+
+#endif
+
+/* -- see zlib.h -- */
+int ZEXPORT gzflush(file, flush)
+    gzFile file;
+    int flush;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return Z_STREAM_ERROR;
+
+    /* check flush parameter */
+    if (flush < 0 || flush > Z_FINISH)
+        return Z_STREAM_ERROR;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return -1;
+    }
+
+    /* compress remaining data with requested flush */
+    gz_comp(state, flush);
+    return state->err;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzsetparams(file, level, strategy)
+    gzFile file;
+    int level;
+    int strategy;
+{
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return Z_STREAM_ERROR;
+
+    /* if no change is requested, then do nothing */
+    if (level == state->level && strategy == state->strategy)
+        return Z_OK;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return -1;
+    }
+
+    /* change compression parameters for subsequent input */
+    if (state->size) {
+        /* flush previous input with previous parameters before changing */
+        if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1)
+            return state->err;
+        deflateParams(strm, level, strategy);
+    }
+    state->level = level;
+    state->strategy = strategy;
+    return Z_OK;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzclose_w(file)
+    gzFile file;
+{
+    int ret = Z_OK;
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+
+    /* check that we're writing */
+    if (state->mode != GZ_WRITE)
+        return Z_STREAM_ERROR;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            ret = state->err;
+    }
+
+    /* flush, free memory, and close file */
+    if (gz_comp(state, Z_FINISH) == -1)
+        ret = state->err;
+    if (!state->direct) {
+        (void)deflateEnd(&(state->strm));
+        free(state->out);
+    }
+    free(state->in);
+    gz_error(state, Z_OK, NULL);
+    free(state->path);
+    if (close(state->fd) == -1)
+        ret = Z_ERRNO;
+    free(state);
+    return ret;
+}
+
+/* used by zlibVersion() to get the vsnprintf story from the horse's mouth */
+unsigned long ZEXPORT gzflags()
+{
+    unsigned long flags = 0;
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#  ifdef NO_vsnprintf
+    flags += 1L << 25;
+#    ifdef HAS_vsprintf_void
+    flags += 1L << 26;
+#    endif
+#  else
+#    ifdef HAS_vsnprintf_void
+    flags += 1L << 26;
+#    endif
+#  endif
+#else
+    flags += 1L << 24;
+#  ifdef NO_snprintf
+    flags += 1L << 25;
+#    ifdef HAS_sprintf_void
+    flags += 1L << 26;
+#    endif
+#  else
+#    ifdef HAS_snprintf_void
+    flags += 1L << 26;
+#    endif
+#  endif
+#endif
+    return flags;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/infback.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/infback.c
new file mode 100644 (file)
index 0000000..981aff1
--- /dev/null
@@ -0,0 +1,640 @@
+/* infback.c -- inflate using a call-back interface
+ * Copyright (C) 1995-2011 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+   This code is largely copied from inflate.c.  Normally either infback.o or
+   inflate.o would be linked into an application--not both.  The interface
+   with inffast.c is retained so that optimized assembler-coded versions of
+   inflate_fast() can be used with either inflate.c or infback.c.
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+/* function prototypes */
+local void fixedtables OF((struct inflate_state FAR *state));
+
+/*
+   strm provides memory allocation functions in zalloc and zfree, or
+   Z_NULL to use the library memory allocation functions.
+
+   windowBits is in the range 8..15, and window is a user-supplied
+   window and output buffer that is 2**windowBits bytes.
+ */
+int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
+z_streamp strm;
+int windowBits;
+unsigned char FAR *window;
+const char *version;
+int stream_size;
+{
+    struct inflate_state FAR *state;
+
+    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+        stream_size != (int)(sizeof(z_stream)))
+        return Z_VERSION_ERROR;
+    if (strm == Z_NULL || window == Z_NULL ||
+        windowBits < 8 || windowBits > 15)
+        return Z_STREAM_ERROR;
+    strm->msg = Z_NULL;                 /* in case we return an error */
+    if (strm->zalloc == (alloc_func)0) {
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+#endif
+    }
+    if (strm->zfree == (free_func)0)
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+    strm->zfree = zcfree;
+#endif
+    state = (struct inflate_state FAR *)ZALLOC(strm, 1,
+                                               sizeof(struct inflate_state));
+    if (state == Z_NULL) return Z_MEM_ERROR;
+    Tracev((stderr, "inflate: allocated\n"));
+    strm->state = (struct internal_state FAR *)state;
+    state->dmax = 32768U;
+    state->wbits = windowBits;
+    state->wsize = 1U << windowBits;
+    state->window = window;
+    state->wnext = 0;
+    state->whave = 0;
+    return Z_OK;
+}
+
+/*
+   Return state with length and distance decoding tables and index sizes set to
+   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
+   If BUILDFIXED is defined, then instead this routine builds the tables the
+   first time it's called, and returns those tables the first time and
+   thereafter.  This reduces the size of the code by about 2K bytes, in
+   exchange for a little execution time.  However, BUILDFIXED should not be
+   used for threaded applications, since the rewriting of the tables and virgin
+   may not be thread-safe.
+ */
+local void fixedtables(state)
+struct inflate_state FAR *state;
+{
+#ifdef BUILDFIXED
+    static int virgin = 1;
+    static code *lenfix, *distfix;
+    static code fixed[544];
+
+    /* build fixed huffman tables if first call (may not be thread safe) */
+    if (virgin) {
+        unsigned sym, bits;
+        static code *next;
+
+        /* literal/length table */
+        sym = 0;
+        while (sym < 144) state->lens[sym++] = 8;
+        while (sym < 256) state->lens[sym++] = 9;
+        while (sym < 280) state->lens[sym++] = 7;
+        while (sym < 288) state->lens[sym++] = 8;
+        next = fixed;
+        lenfix = next;
+        bits = 9;
+        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
+
+        /* distance table */
+        sym = 0;
+        while (sym < 32) state->lens[sym++] = 5;
+        distfix = next;
+        bits = 5;
+        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
+
+        /* do this just once */
+        virgin = 0;
+    }
+#else /* !BUILDFIXED */
+#   include "inffixed.h"
+#endif /* BUILDFIXED */
+    state->lencode = lenfix;
+    state->lenbits = 9;
+    state->distcode = distfix;
+    state->distbits = 5;
+}
+
+/* Macros for inflateBack(): */
+
+/* Load returned state from inflate_fast() */
+#define LOAD() \
+    do { \
+        put = strm->next_out; \
+        left = strm->avail_out; \
+        next = strm->next_in; \
+        have = strm->avail_in; \
+        hold = state->hold; \
+        bits = state->bits; \
+    } while (0)
+
+/* Set state from registers for inflate_fast() */
+#define RESTORE() \
+    do { \
+        strm->next_out = put; \
+        strm->avail_out = left; \
+        strm->next_in = next; \
+        strm->avail_in = have; \
+        state->hold = hold; \
+        state->bits = bits; \
+    } while (0)
+
+/* Clear the input bit accumulator */
+#define INITBITS() \
+    do { \
+        hold = 0; \
+        bits = 0; \
+    } while (0)
+
+/* Assure that some input is available.  If input is requested, but denied,
+   then return a Z_BUF_ERROR from inflateBack(). */
+#define PULL() \
+    do { \
+        if (have == 0) { \
+            have = in(in_desc, &next); \
+            if (have == 0) { \
+                next = Z_NULL; \
+                ret = Z_BUF_ERROR; \
+                goto inf_leave; \
+            } \
+        } \
+    } while (0)
+
+/* Get a byte of input into the bit accumulator, or return from inflateBack()
+   with an error if there is no input available. */
+#define PULLBYTE() \
+    do { \
+        PULL(); \
+        have--; \
+        hold += (unsigned long)(*next++) << bits; \
+        bits += 8; \
+    } while (0)
+
+/* Assure that there are at least n bits in the bit accumulator.  If there is
+   not enough available input to do that, then return from inflateBack() with
+   an error. */
+#define NEEDBITS(n) \
+    do { \
+        while (bits < (unsigned)(n)) \
+            PULLBYTE(); \
+    } while (0)
+
+/* Return the low n bits of the bit accumulator (n < 16) */
+#define BITS(n) \
+    ((unsigned)hold & ((1U << (n)) - 1))
+
+/* Remove n bits from the bit accumulator */
+#define DROPBITS(n) \
+    do { \
+        hold >>= (n); \
+        bits -= (unsigned)(n); \
+    } while (0)
+
+/* Remove zero to seven bits as needed to go to a byte boundary */
+#define BYTEBITS() \
+    do { \
+        hold >>= bits & 7; \
+        bits -= bits & 7; \
+    } while (0)
+
+/* Assure that some output space is available, by writing out the window
+   if it's full.  If the write fails, return from inflateBack() with a
+   Z_BUF_ERROR. */
+#define ROOM() \
+    do { \
+        if (left == 0) { \
+            put = state->window; \
+            left = state->wsize; \
+            state->whave = left; \
+            if (out(out_desc, put, left)) { \
+                ret = Z_BUF_ERROR; \
+                goto inf_leave; \
+            } \
+        } \
+    } while (0)
+
+/*
+   strm provides the memory allocation functions and window buffer on input,
+   and provides information on the unused input on return.  For Z_DATA_ERROR
+   returns, strm will also provide an error message.
+
+   in() and out() are the call-back input and output functions.  When
+   inflateBack() needs more input, it calls in().  When inflateBack() has
+   filled the window with output, or when it completes with data in the
+   window, it calls out() to write out the data.  The application must not
+   change the provided input until in() is called again or inflateBack()
+   returns.  The application must not change the window/output buffer until
+   inflateBack() returns.
+
+   in() and out() are called with a descriptor parameter provided in the
+   inflateBack() call.  This parameter can be a structure that provides the
+   information required to do the read or write, as well as accumulated
+   information on the input and output such as totals and check values.
+
+   in() should return zero on failure.  out() should return non-zero on
+   failure.  If either in() or out() fails, than inflateBack() returns a
+   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
+   was in() or out() that caused in the error.  Otherwise,  inflateBack()
+   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
+   error, or Z_MEM_ERROR if it could not allocate memory for the state.
+   inflateBack() can also return Z_STREAM_ERROR if the input parameters
+   are not correct, i.e. strm is Z_NULL or the state was not initialized.
+ */
+int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
+z_streamp strm;
+in_func in;
+void FAR *in_desc;
+out_func out;
+void FAR *out_desc;
+{
+    struct inflate_state FAR *state;
+    unsigned char FAR *next;    /* next input */
+    unsigned char FAR *put;     /* next output */
+    unsigned have, left;        /* available input and output */
+    unsigned long hold;         /* bit buffer */
+    unsigned bits;              /* bits in bit buffer */
+    unsigned copy;              /* number of stored or match bytes to copy */
+    unsigned char FAR *from;    /* where to copy match bytes from */
+    code here;                  /* current decoding table entry */
+    code last;                  /* parent table entry */
+    unsigned len;               /* length to copy for repeats, bits to drop */
+    int ret;                    /* return code */
+    static const unsigned short order[19] = /* permutation of code lengths */
+        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+    /* Check that the strm exists and that the state was initialized */
+    if (strm == Z_NULL || strm->state == Z_NULL)
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* Reset the state */
+    strm->msg = Z_NULL;
+    state->mode = TYPE;
+    state->last = 0;
+    state->whave = 0;
+    next = strm->next_in;
+    have = next != Z_NULL ? strm->avail_in : 0;
+    hold = 0;
+    bits = 0;
+    put = state->window;
+    left = state->wsize;
+
+    /* Inflate until end of block marked as last */
+    for (;;)
+        switch (state->mode) {
+        case TYPE:
+            /* determine and dispatch block type */
+            if (state->last) {
+                BYTEBITS();
+                state->mode = DONE;
+                break;
+            }
+            NEEDBITS(3);
+            state->last = BITS(1);
+            DROPBITS(1);
+            switch (BITS(2)) {
+            case 0:                             /* stored block */
+                Tracev((stderr, "inflate:     stored block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = STORED;
+                break;
+            case 1:                             /* fixed block */
+                fixedtables(state);
+                Tracev((stderr, "inflate:     fixed codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = LEN;              /* decode codes */
+                break;
+            case 2:                             /* dynamic block */
+                Tracev((stderr, "inflate:     dynamic codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = TABLE;
+                break;
+            case 3:
+                strm->msg = (char *)"invalid block type";
+                state->mode = BAD;
+            }
+            DROPBITS(2);
+            break;
+
+        case STORED:
+            /* get and verify stored block length */
+            BYTEBITS();                         /* go to byte boundary */
+            NEEDBITS(32);
+            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
+                strm->msg = (char *)"invalid stored block lengths";
+                state->mode = BAD;
+                break;
+            }
+            state->length = (unsigned)hold & 0xffff;
+            Tracev((stderr, "inflate:       stored length %u\n",
+                    state->length));
+            INITBITS();
+
+            /* copy stored block from input to output */
+            while (state->length != 0) {
+                copy = state->length;
+                PULL();
+                ROOM();
+                if (copy > have) copy = have;
+                if (copy > left) copy = left;
+                zmemcpy(put, next, copy);
+                have -= copy;
+                next += copy;
+                left -= copy;
+                put += copy;
+                state->length -= copy;
+            }
+            Tracev((stderr, "inflate:       stored end\n"));
+            state->mode = TYPE;
+            break;
+
+        case TABLE:
+            /* get dynamic table entries descriptor */
+            NEEDBITS(14);
+            state->nlen = BITS(5) + 257;
+            DROPBITS(5);
+            state->ndist = BITS(5) + 1;
+            DROPBITS(5);
+            state->ncode = BITS(4) + 4;
+            DROPBITS(4);
+#ifndef PKZIP_BUG_WORKAROUND
+            if (state->nlen > 286 || state->ndist > 30) {
+                strm->msg = (char *)"too many length or distance symbols";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            Tracev((stderr, "inflate:       table sizes ok\n"));
+
+            /* get code length code lengths (not a typo) */
+            state->have = 0;
+            while (state->have < state->ncode) {
+                NEEDBITS(3);
+                state->lens[order[state->have++]] = (unsigned short)BITS(3);
+                DROPBITS(3);
+            }
+            while (state->have < 19)
+                state->lens[order[state->have++]] = 0;
+            state->next = state->codes;
+            state->lencode = (code const FAR *)(state->next);
+            state->lenbits = 7;
+            ret = inflate_table(CODES, state->lens, 19, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid code lengths set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       code lengths ok\n"));
+
+            /* get length and distance code code lengths */
+            state->have = 0;
+            while (state->have < state->nlen + state->ndist) {
+                for (;;) {
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                if (here.val < 16) {
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
+                }
+                else {
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
+                        if (state->have == 0) {
+                            strm->msg = (char *)"invalid bit length repeat";
+                            state->mode = BAD;
+                            break;
+                        }
+                        len = (unsigned)(state->lens[state->have - 1]);
+                        copy = 3 + BITS(2);
+                        DROPBITS(2);
+                    }
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 3 + BITS(3);
+                        DROPBITS(3);
+                    }
+                    else {
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 11 + BITS(7);
+                        DROPBITS(7);
+                    }
+                    if (state->have + copy > state->nlen + state->ndist) {
+                        strm->msg = (char *)"invalid bit length repeat";
+                        state->mode = BAD;
+                        break;
+                    }
+                    while (copy--)
+                        state->lens[state->have++] = (unsigned short)len;
+                }
+            }
+
+            /* handle error breaks in while */
+            if (state->mode == BAD) break;
+
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
+            state->next = state->codes;
+            state->lencode = (code const FAR *)(state->next);
+            state->lenbits = 9;
+            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid literal/lengths set";
+                state->mode = BAD;
+                break;
+            }
+            state->distcode = (code const FAR *)(state->next);
+            state->distbits = 6;
+            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
+                            &(state->next), &(state->distbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid distances set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       codes ok\n"));
+            state->mode = LEN;
+
+        case LEN:
+            /* use inflate_fast() if we have enough input and output */
+            if (have >= 6 && left >= 258) {
+                RESTORE();
+                if (state->whave < state->wsize)
+                    state->whave = state->wsize - left;
+                inflate_fast(strm, state->wsize);
+                LOAD();
+                break;
+            }
+
+            /* get a literal, length, or end-of-block code */
+            for (;;) {
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->lencode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(here.bits);
+            state->length = (unsigned)here.val;
+
+            /* process literal */
+            if (here.op == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                        "inflate:         literal '%c'\n" :
+                        "inflate:         literal 0x%02x\n", here.val));
+                ROOM();
+                *put++ = (unsigned char)(state->length);
+                left--;
+                state->mode = LEN;
+                break;
+            }
+
+            /* process end of block */
+            if (here.op & 32) {
+                Tracevv((stderr, "inflate:         end of block\n"));
+                state->mode = TYPE;
+                break;
+            }
+
+            /* invalid code */
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid literal/length code";
+                state->mode = BAD;
+                break;
+            }
+
+            /* length code -- get extra bits, if any */
+            state->extra = (unsigned)(here.op) & 15;
+            if (state->extra != 0) {
+                NEEDBITS(state->extra);
+                state->length += BITS(state->extra);
+                DROPBITS(state->extra);
+            }
+            Tracevv((stderr, "inflate:         length %u\n", state->length));
+
+            /* get distance code */
+            for (;;) {
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if ((here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->distcode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(here.bits);
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+            state->offset = (unsigned)here.val;
+
+            /* get distance extra bits, if any */
+            state->extra = (unsigned)(here.op) & 15;
+            if (state->extra != 0) {
+                NEEDBITS(state->extra);
+                state->offset += BITS(state->extra);
+                DROPBITS(state->extra);
+            }
+            if (state->offset > state->wsize - (state->whave < state->wsize ?
+                                                left : 0)) {
+                strm->msg = (char *)"invalid distance too far back";
+                state->mode = BAD;
+                break;
+            }
+            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
+
+            /* copy match from window to output */
+            do {
+                ROOM();
+                copy = state->wsize - state->offset;
+                if (copy < left) {
+                    from = put + copy;
+                    copy = left - copy;
+                }
+                else {
+                    from = put - state->offset;
+                    copy = left;
+                }
+                if (copy > state->length) copy = state->length;
+                state->length -= copy;
+                left -= copy;
+                do {
+                    *put++ = *from++;
+                } while (--copy);
+            } while (state->length != 0);
+            break;
+
+        case DONE:
+            /* inflate stream terminated properly -- write leftover output */
+            ret = Z_STREAM_END;
+            if (left < state->wsize) {
+                if (out(out_desc, state->window, state->wsize - left))
+                    ret = Z_BUF_ERROR;
+            }
+            goto inf_leave;
+
+        case BAD:
+            ret = Z_DATA_ERROR;
+            goto inf_leave;
+
+        default:                /* can't happen, but makes compilers happy */
+            ret = Z_STREAM_ERROR;
+            goto inf_leave;
+        }
+
+    /* Return unused input */
+  inf_leave:
+    strm->next_in = next;
+    strm->avail_in = have;
+    return ret;
+}
+
+int ZEXPORT inflateBackEnd(strm)
+z_streamp strm;
+{
+    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
+        return Z_STREAM_ERROR;
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+    Tracev((stderr, "inflate: end\n"));
+    return Z_OK;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffast.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffast.c
new file mode 100644 (file)
index 0000000..2f1d60b
--- /dev/null
@@ -0,0 +1,340 @@
+/* inffast.c -- fast decoding
+ * Copyright (C) 1995-2008, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+#ifndef ASMINF
+
+/* Allow machine dependent optimization for post-increment or pre-increment.
+   Based on testing to date,
+   Pre-increment preferred for:
+   - PowerPC G3 (Adler)
+   - MIPS R5000 (Randers-Pehrson)
+   Post-increment preferred for:
+   - none
+   No measurable difference:
+   - Pentium III (Anderson)
+   - M68060 (Nikl)
+ */
+#ifdef POSTINC
+#  define OFF 0
+#  define PUP(a) *(a)++
+#else
+#  define OFF 1
+#  define PUP(a) *++(a)
+#endif
+
+/*
+   Decode literal, length, and distance codes and write out the resulting
+   literal and match bytes until either not enough input or output is
+   available, an end-of-block is encountered, or a data error is encountered.
+   When large enough input and output buffers are supplied to inflate(), for
+   example, a 16K input buffer and a 64K output buffer, more than 95% of the
+   inflate execution time is spent in this routine.
+
+   Entry assumptions:
+
+        state->mode == LEN
+        strm->avail_in >= 6
+        strm->avail_out >= 258
+        start >= strm->avail_out
+        state->bits < 8
+
+   On return, state->mode is one of:
+
+        LEN -- ran out of enough output space or enough available input
+        TYPE -- reached end of block code, inflate() to interpret next block
+        BAD -- error in block data
+
+   Notes:
+
+    - The maximum input bits used by a length/distance pair is 15 bits for the
+      length code, 5 bits for the length extra, 15 bits for the distance code,
+      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
+      Therefore if strm->avail_in >= 6, then there is enough input to avoid
+      checking for available input while decoding.
+
+    - The maximum bytes that a single length/distance pair can output is 258
+      bytes, which is the maximum length that can be coded.  inflate_fast()
+      requires strm->avail_out >= 258 for each loop to avoid checking for
+      output space.
+ */
+void ZLIB_INTERNAL inflate_fast(strm, start)
+z_streamp strm;
+unsigned start;         /* inflate()'s starting value for strm->avail_out */
+{
+    struct inflate_state FAR *state;
+    unsigned char FAR *in;      /* local strm->next_in */
+    unsigned char FAR *last;    /* while in < last, enough input available */
+    unsigned char FAR *out;     /* local strm->next_out */
+    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */
+    unsigned char FAR *end;     /* while out < end, enough space available */
+#ifdef INFLATE_STRICT
+    unsigned dmax;              /* maximum distance from zlib header */
+#endif
+    unsigned wsize;             /* window size or zero if not using window */
+    unsigned whave;             /* valid bytes in the window */
+    unsigned wnext;             /* window write index */
+    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
+    unsigned long hold;         /* local strm->hold */
+    unsigned bits;              /* local strm->bits */
+    code const FAR *lcode;      /* local strm->lencode */
+    code const FAR *dcode;      /* local strm->distcode */
+    unsigned lmask;             /* mask for first level of length codes */
+    unsigned dmask;             /* mask for first level of distance codes */
+    code here;                  /* retrieved table entry */
+    unsigned op;                /* code bits, operation, extra bits, or */
+                                /*  window position, window bytes to copy */
+    unsigned len;               /* match length, unused bytes */
+    unsigned dist;              /* match distance */
+    unsigned char FAR *from;    /* where to copy match from */
+
+    /* copy state to local variables */
+    state = (struct inflate_state FAR *)strm->state;
+    in = strm->next_in - OFF;
+    last = in + (strm->avail_in - 5);
+    out = strm->next_out - OFF;
+    beg = out - (start - strm->avail_out);
+    end = out + (strm->avail_out - 257);
+#ifdef INFLATE_STRICT
+    dmax = state->dmax;
+#endif
+    wsize = state->wsize;
+    whave = state->whave;
+    wnext = state->wnext;
+    window = state->window;
+    hold = state->hold;
+    bits = state->bits;
+    lcode = state->lencode;
+    dcode = state->distcode;
+    lmask = (1U << state->lenbits) - 1;
+    dmask = (1U << state->distbits) - 1;
+
+    /* decode literals and length/distances until end-of-block or not enough
+       input data or output space */
+    do {
+        if (bits < 15) {
+            hold += (unsigned long)(PUP(in)) << bits;
+            bits += 8;
+            hold += (unsigned long)(PUP(in)) << bits;
+            bits += 8;
+        }
+        here = lcode[hold & lmask];
+      dolen:
+        op = (unsigned)(here.bits);
+        hold >>= op;
+        bits -= op;
+        op = (unsigned)(here.op);
+        if (op == 0) {                          /* literal */
+            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                    "inflate:         literal '%c'\n" :
+                    "inflate:         literal 0x%02x\n", here.val));
+            PUP(out) = (unsigned char)(here.val);
+        }
+        else if (op & 16) {                     /* length base */
+            len = (unsigned)(here.val);
+            op &= 15;                           /* number of extra bits */
+            if (op) {
+                if (bits < op) {
+                    hold += (unsigned long)(PUP(in)) << bits;
+                    bits += 8;
+                }
+                len += (unsigned)hold & ((1U << op) - 1);
+                hold >>= op;
+                bits -= op;
+            }
+            Tracevv((stderr, "inflate:         length %u\n", len));
+            if (bits < 15) {
+                hold += (unsigned long)(PUP(in)) << bits;
+                bits += 8;
+                hold += (unsigned long)(PUP(in)) << bits;
+                bits += 8;
+            }
+            here = dcode[hold & dmask];
+          dodist:
+            op = (unsigned)(here.bits);
+            hold >>= op;
+            bits -= op;
+            op = (unsigned)(here.op);
+            if (op & 16) {                      /* distance base */
+                dist = (unsigned)(here.val);
+                op &= 15;                       /* number of extra bits */
+                if (bits < op) {
+                    hold += (unsigned long)(PUP(in)) << bits;
+                    bits += 8;
+                    if (bits < op) {
+                        hold += (unsigned long)(PUP(in)) << bits;
+                        bits += 8;
+                    }
+                }
+                dist += (unsigned)hold & ((1U << op) - 1);
+#ifdef INFLATE_STRICT
+                if (dist > dmax) {
+                    strm->msg = (char *)"invalid distance too far back";
+                    state->mode = BAD;
+                    break;
+                }
+#endif
+                hold >>= op;
+                bits -= op;
+                Tracevv((stderr, "inflate:         distance %u\n", dist));
+                op = (unsigned)(out - beg);     /* max distance in output */
+                if (dist > op) {                /* see if copy from window */
+                    op = dist - op;             /* distance back in window */
+                    if (op > whave) {
+                        if (state->sane) {
+                            strm->msg =
+                                (char *)"invalid distance too far back";
+                            state->mode = BAD;
+                            break;
+                        }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                        if (len <= op - whave) {
+                            do {
+                                PUP(out) = 0;
+                            } while (--len);
+                            continue;
+                        }
+                        len -= op - whave;
+                        do {
+                            PUP(out) = 0;
+                        } while (--op > whave);
+                        if (op == 0) {
+                            from = out - dist;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--len);
+                            continue;
+                        }
+#endif
+                    }
+                    from = window - OFF;
+                    if (wnext == 0) {           /* very common case */
+                        from += wsize - op;
+                        if (op < len) {         /* some from window */
+                            len -= op;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--op);
+                            from = out - dist;  /* rest from output */
+                        }
+                    }
+                    else if (wnext < op) {      /* wrap around window */
+                        from += wsize + wnext - op;
+                        op -= wnext;
+                        if (op < len) {         /* some from end of window */
+                            len -= op;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--op);
+                            from = window - OFF;
+                            if (wnext < len) {  /* some from start of window */
+                                op = wnext;
+                                len -= op;
+                                do {
+                                    PUP(out) = PUP(from);
+                                } while (--op);
+                                from = out - dist;      /* rest from output */
+                            }
+                        }
+                    }
+                    else {                      /* contiguous in window */
+                        from += wnext - op;
+                        if (op < len) {         /* some from window */
+                            len -= op;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--op);
+                            from = out - dist;  /* rest from output */
+                        }
+                    }
+                    while (len > 2) {
+                        PUP(out) = PUP(from);
+                        PUP(out) = PUP(from);
+                        PUP(out) = PUP(from);
+                        len -= 3;
+                    }
+                    if (len) {
+                        PUP(out) = PUP(from);
+                        if (len > 1)
+                            PUP(out) = PUP(from);
+                    }
+                }
+                else {
+                    from = out - dist;          /* copy direct from output */
+                    do {                        /* minimum length is three */
+                        PUP(out) = PUP(from);
+                        PUP(out) = PUP(from);
+                        PUP(out) = PUP(from);
+                        len -= 3;
+                    } while (len > 2);
+                    if (len) {
+                        PUP(out) = PUP(from);
+                        if (len > 1)
+                            PUP(out) = PUP(from);
+                    }
+                }
+            }
+            else if ((op & 64) == 0) {          /* 2nd level distance code */
+                here = dcode[here.val + (hold & ((1U << op) - 1))];
+                goto dodist;
+            }
+            else {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+        }
+        else if ((op & 64) == 0) {              /* 2nd level length code */
+            here = lcode[here.val + (hold & ((1U << op) - 1))];
+            goto dolen;
+        }
+        else if (op & 32) {                     /* end-of-block */
+            Tracevv((stderr, "inflate:         end of block\n"));
+            state->mode = TYPE;
+            break;
+        }
+        else {
+            strm->msg = (char *)"invalid literal/length code";
+            state->mode = BAD;
+            break;
+        }
+    } while (in < last && out < end);
+
+    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
+    len = bits >> 3;
+    in -= len;
+    bits -= len << 3;
+    hold &= (1U << bits) - 1;
+
+    /* update state and return */
+    strm->next_in = in + OFF;
+    strm->next_out = out + OFF;
+    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
+    strm->avail_out = (unsigned)(out < end ?
+                                 257 + (end - out) : 257 - (out - end));
+    state->hold = hold;
+    state->bits = bits;
+    return;
+}
+
+/*
+   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
+   - Using bit fields for code structure
+   - Different op definition to avoid & for extra bits (do & for table bits)
+   - Three separate decoding do-loops for direct, window, and wnext == 0
+   - Special case for distance > 1 copies to do overlapped load and store copy
+   - Explicit branch predictions (based on measured branch probabilities)
+   - Deferring match copy and interspersed it with decoding subsequent codes
+   - Swapping literal/length else
+   - Swapping window/direct else
+   - Larger unrolled copy loops (three is about right)
+   - Moving len -= 3 statement into middle of loop
+ */
+
+#endif /* !ASMINF */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffast.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffast.h
new file mode 100644 (file)
index 0000000..e5c1aa4
--- /dev/null
@@ -0,0 +1,11 @@
+/* inffast.h -- header to use inffast.c
+ * Copyright (C) 1995-2003, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffixed.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inffixed.h
new file mode 100644 (file)
index 0000000..d628327
--- /dev/null
@@ -0,0 +1,94 @@
+    /* inffixed.h -- table for decoding fixed codes
+     * Generated automatically by makefixed().
+     */
+
+    /* WARNING: this file should *not* be used by applications.
+       It is part of the implementation of this library and is
+       subject to change. Applications should only use zlib.h.
+     */
+
+    static const code lenfix[512] = {
+        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
+        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
+        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
+        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
+        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
+        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
+        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
+        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
+        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
+        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
+        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
+        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
+        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
+        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
+        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
+        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
+        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
+        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
+        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
+        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
+        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
+        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
+        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
+        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
+        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
+        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
+        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
+        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
+        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
+        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
+        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
+        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
+        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
+        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
+        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
+        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
+        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
+        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
+        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
+        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
+        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
+        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
+        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
+        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
+        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
+        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
+        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
+        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
+        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
+        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
+        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
+        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
+        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
+        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
+        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
+        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
+        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
+        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
+        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
+        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
+        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
+        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
+        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
+        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
+        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
+        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
+        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
+        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
+        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
+        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
+        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
+        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
+        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
+        {0,9,255}
+    };
+
+    static const code distfix[32] = {
+        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
+        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
+        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
+        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
+        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
+        {22,5,193},{64,5,0}
+    };
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inflate.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inflate.c
new file mode 100644 (file)
index 0000000..cc89517
--- /dev/null
@@ -0,0 +1,1501 @@
+/* inflate.c -- zlib decompression
+ * Copyright (C) 1995-2011 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ * Change history:
+ *
+ * 1.2.beta0    24 Nov 2002
+ * - First version -- complete rewrite of inflate to simplify code, avoid
+ *   creation of window when not needed, minimize use of window when it is
+ *   needed, make inffast.c even faster, implement gzip decoding, and to
+ *   improve code readability and style over the previous zlib inflate code
+ *
+ * 1.2.beta1    25 Nov 2002
+ * - Use pointers for available input and output checking in inffast.c
+ * - Remove input and output counters in inffast.c
+ * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
+ * - Remove unnecessary second byte pull from length extra in inffast.c
+ * - Unroll direct copy to three copies per loop in inffast.c
+ *
+ * 1.2.beta2    4 Dec 2002
+ * - Change external routine names to reduce potential conflicts
+ * - Correct filename to inffixed.h for fixed tables in inflate.c
+ * - Make hbuf[] unsigned char to match parameter type in inflate.c
+ * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
+ *   to avoid negation problem on Alphas (64 bit) in inflate.c
+ *
+ * 1.2.beta3    22 Dec 2002
+ * - Add comments on state->bits assertion in inffast.c
+ * - Add comments on op field in inftrees.h
+ * - Fix bug in reuse of allocated window after inflateReset()
+ * - Remove bit fields--back to byte structure for speed
+ * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
+ * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
+ * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
+ * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
+ * - Use local copies of stream next and avail values, as well as local bit
+ *   buffer and bit count in inflate()--for speed when inflate_fast() not used
+ *
+ * 1.2.beta4    1 Jan 2003
+ * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
+ * - Move a comment on output buffer sizes from inffast.c to inflate.c
+ * - Add comments in inffast.c to introduce the inflate_fast() routine
+ * - Rearrange window copies in inflate_fast() for speed and simplification
+ * - Unroll last copy for window match in inflate_fast()
+ * - Use local copies of window variables in inflate_fast() for speed
+ * - Pull out common wnext == 0 case for speed in inflate_fast()
+ * - Make op and len in inflate_fast() unsigned for consistency
+ * - Add FAR to lcode and dcode declarations in inflate_fast()
+ * - Simplified bad distance check in inflate_fast()
+ * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
+ *   source file infback.c to provide a call-back interface to inflate for
+ *   programs like gzip and unzip -- uses window as output buffer to avoid
+ *   window copying
+ *
+ * 1.2.beta5    1 Jan 2003
+ * - Improved inflateBack() interface to allow the caller to provide initial
+ *   input in strm.
+ * - Fixed stored blocks bug in inflateBack()
+ *
+ * 1.2.beta6    4 Jan 2003
+ * - Added comments in inffast.c on effectiveness of POSTINC
+ * - Typecasting all around to reduce compiler warnings
+ * - Changed loops from while (1) or do {} while (1) to for (;;), again to
+ *   make compilers happy
+ * - Changed type of window in inflateBackInit() to unsigned char *
+ *
+ * 1.2.beta7    27 Jan 2003
+ * - Changed many types to unsigned or unsigned short to avoid warnings
+ * - Added inflateCopy() function
+ *
+ * 1.2.0        9 Mar 2003
+ * - Changed inflateBack() interface to provide separate opaque descriptors
+ *   for the in() and out() functions
+ * - Changed inflateBack() argument and in_func typedef to swap the length
+ *   and buffer address return values for the input function
+ * - Check next_in and next_out for Z_NULL on entry to inflate()
+ *
+ * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+#ifdef MAKEFIXED
+#  ifndef BUILDFIXED
+#    define BUILDFIXED
+#  endif
+#endif
+
+/* function prototypes */
+local void fixedtables OF((struct inflate_state FAR *state));
+local int updatewindow OF((z_streamp strm, unsigned out));
+#ifdef BUILDFIXED
+   void makefixed OF((void));
+#endif
+local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
+                              unsigned len));
+
+int ZEXPORT inflateResetKeep(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    strm->total_in = strm->total_out = state->total = 0;
+    strm->msg = Z_NULL;
+    if (state->wrap)        /* to support ill-conceived Java test suite */
+        strm->adler = state->wrap & 1;
+    state->mode = HEAD;
+    state->last = 0;
+    state->havedict = 0;
+    state->dmax = 32768U;
+    state->head = Z_NULL;
+    state->hold = 0;
+    state->bits = 0;
+    state->lencode = state->distcode = state->next = state->codes;
+    state->sane = 1;
+    state->back = -1;
+    Tracev((stderr, "inflate: reset\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateReset(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    state->wsize = 0;
+    state->whave = 0;
+    state->wnext = 0;
+    return inflateResetKeep(strm);
+}
+
+int ZEXPORT inflateReset2(strm, windowBits)
+z_streamp strm;
+int windowBits;
+{
+    int wrap;
+    struct inflate_state FAR *state;
+
+    /* get the state */
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* extract wrap request from windowBits parameter */
+    if (windowBits < 0) {
+        wrap = 0;
+        windowBits = -windowBits;
+    }
+    else {
+        wrap = (windowBits >> 4) + 1;
+#ifdef GUNZIP
+        if (windowBits < 48)
+            windowBits &= 15;
+#endif
+    }
+
+    /* set number of window bits, free window if different */
+    if (windowBits && (windowBits < 8 || windowBits > 15))
+        return Z_STREAM_ERROR;
+    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
+        ZFREE(strm, state->window);
+        state->window = Z_NULL;
+    }
+
+    /* update state and reset the rest of it */
+    state->wrap = wrap;
+    state->wbits = (unsigned)windowBits;
+    return inflateReset(strm);
+}
+
+int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
+z_streamp strm;
+int windowBits;
+const char *version;
+int stream_size;
+{
+    int ret;
+    struct inflate_state FAR *state;
+
+    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+        stream_size != (int)(sizeof(z_stream)))
+        return Z_VERSION_ERROR;
+    if (strm == Z_NULL) return Z_STREAM_ERROR;
+    strm->msg = Z_NULL;                 /* in case we return an error */
+    if (strm->zalloc == (alloc_func)0) {
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+#endif
+    }
+    if (strm->zfree == (free_func)0)
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zfree = zcfree;
+#endif
+    state = (struct inflate_state FAR *)
+            ZALLOC(strm, 1, sizeof(struct inflate_state));
+    if (state == Z_NULL) return Z_MEM_ERROR;
+    Tracev((stderr, "inflate: allocated\n"));
+    strm->state = (struct internal_state FAR *)state;
+    state->window = Z_NULL;
+    ret = inflateReset2(strm, windowBits);
+    if (ret != Z_OK) {
+        ZFREE(strm, state);
+        strm->state = Z_NULL;
+    }
+    return ret;
+}
+
+int ZEXPORT inflateInit_(strm, version, stream_size)
+z_streamp strm;
+const char *version;
+int stream_size;
+{
+    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
+}
+
+int ZEXPORT inflatePrime(strm, bits, value)
+z_streamp strm;
+int bits;
+int value;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (bits < 0) {
+        state->hold = 0;
+        state->bits = 0;
+        return Z_OK;
+    }
+    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
+    value &= (1L << bits) - 1;
+    state->hold += value << state->bits;
+    state->bits += bits;
+    return Z_OK;
+}
+
+/*
+   Return state with length and distance decoding tables and index sizes set to
+   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
+   If BUILDFIXED is defined, then instead this routine builds the tables the
+   first time it's called, and returns those tables the first time and
+   thereafter.  This reduces the size of the code by about 2K bytes, in
+   exchange for a little execution time.  However, BUILDFIXED should not be
+   used for threaded applications, since the rewriting of the tables and virgin
+   may not be thread-safe.
+ */
+local void fixedtables(state)
+struct inflate_state FAR *state;
+{
+#ifdef BUILDFIXED
+    static int virgin = 1;
+    static code *lenfix, *distfix;
+    static code fixed[544];
+
+    /* build fixed huffman tables if first call (may not be thread safe) */
+    if (virgin) {
+        unsigned sym, bits;
+        static code *next;
+
+        /* literal/length table */
+        sym = 0;
+        while (sym < 144) state->lens[sym++] = 8;
+        while (sym < 256) state->lens[sym++] = 9;
+        while (sym < 280) state->lens[sym++] = 7;
+        while (sym < 288) state->lens[sym++] = 8;
+        next = fixed;
+        lenfix = next;
+        bits = 9;
+        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
+
+        /* distance table */
+        sym = 0;
+        while (sym < 32) state->lens[sym++] = 5;
+        distfix = next;
+        bits = 5;
+        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
+
+        /* do this just once */
+        virgin = 0;
+    }
+#else /* !BUILDFIXED */
+#   include "inffixed.h"
+#endif /* BUILDFIXED */
+    state->lencode = lenfix;
+    state->lenbits = 9;
+    state->distcode = distfix;
+    state->distbits = 5;
+}
+
+#ifdef MAKEFIXED
+#include <stdio.h>
+
+/*
+   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
+   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
+   those tables to stdout, which would be piped to inffixed.h.  A small program
+   can simply call makefixed to do this:
+
+    void makefixed(void);
+
+    int main(void)
+    {
+        makefixed();
+        return 0;
+    }
+
+   Then that can be linked with zlib built with MAKEFIXED defined and run:
+
+    a.out > inffixed.h
+ */
+void makefixed()
+{
+    unsigned low, size;
+    struct inflate_state state;
+
+    fixedtables(&state);
+    puts("    /* inffixed.h -- table for decoding fixed codes");
+    puts("     * Generated automatically by makefixed().");
+    puts("     */");
+    puts("");
+    puts("    /* WARNING: this file should *not* be used by applications.");
+    puts("       It is part of the implementation of this library and is");
+    puts("       subject to change. Applications should only use zlib.h.");
+    puts("     */");
+    puts("");
+    size = 1U << 9;
+    printf("    static const code lenfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 7) == 0) printf("\n        ");
+        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
+               state.lencode[low].bits, state.lencode[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n    };");
+    size = 1U << 5;
+    printf("\n    static const code distfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 6) == 0) printf("\n        ");
+        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
+               state.distcode[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n    };");
+}
+#endif /* MAKEFIXED */
+
+/*
+   Update the window with the last wsize (normally 32K) bytes written before
+   returning.  If window does not exist yet, create it.  This is only called
+   when a window is already in use, or when output has been written during this
+   inflate call, but the end of the deflate stream has not been reached yet.
+   It is also called to create a window for dictionary data when a dictionary
+   is loaded.
+
+   Providing output buffers larger than 32K to inflate() should provide a speed
+   advantage, since only the last 32K of output is copied to the sliding window
+   upon return from inflate(), and since all distances after the first 32K of
+   output will fall in the output data, making match copies simpler and faster.
+   The advantage may be dependent on the size of the processor's data caches.
+ */
+local int updatewindow(strm, out)
+z_streamp strm;
+unsigned out;
+{
+    struct inflate_state FAR *state;
+    unsigned copy, dist;
+
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* if it hasn't been done already, allocate space for the window */
+    if (state->window == Z_NULL) {
+        state->window = (unsigned char FAR *)
+                        ZALLOC(strm, 1U << state->wbits,
+                               sizeof(unsigned char));
+        if (state->window == Z_NULL) return 1;
+    }
+
+    /* if window not in use yet, initialize */
+    if (state->wsize == 0) {
+        state->wsize = 1U << state->wbits;
+        state->wnext = 0;
+        state->whave = 0;
+    }
+
+    /* copy state->wsize or less output bytes into the circular window */
+    copy = out - strm->avail_out;
+    if (copy >= state->wsize) {
+        zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
+        state->wnext = 0;
+        state->whave = state->wsize;
+    }
+    else {
+        dist = state->wsize - state->wnext;
+        if (dist > copy) dist = copy;
+        zmemcpy(state->window + state->wnext, strm->next_out - copy, dist);
+        copy -= dist;
+        if (copy) {
+            zmemcpy(state->window, strm->next_out - copy, copy);
+            state->wnext = copy;
+            state->whave = state->wsize;
+        }
+        else {
+            state->wnext += dist;
+            if (state->wnext == state->wsize) state->wnext = 0;
+            if (state->whave < state->wsize) state->whave += dist;
+        }
+    }
+    return 0;
+}
+
+/* Macros for inflate(): */
+
+/* check function to use adler32() for zlib or crc32() for gzip */
+#ifdef GUNZIP
+#  define UPDATE(check, buf, len) \
+    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
+#else
+#  define UPDATE(check, buf, len) adler32(check, buf, len)
+#endif
+
+/* check macros for header crc */
+#ifdef GUNZIP
+#  define CRC2(check, word) \
+    do { \
+        hbuf[0] = (unsigned char)(word); \
+        hbuf[1] = (unsigned char)((word) >> 8); \
+        check = crc32(check, hbuf, 2); \
+    } while (0)
+
+#  define CRC4(check, word) \
+    do { \
+        hbuf[0] = (unsigned char)(word); \
+        hbuf[1] = (unsigned char)((word) >> 8); \
+        hbuf[2] = (unsigned char)((word) >> 16); \
+        hbuf[3] = (unsigned char)((word) >> 24); \
+        check = crc32(check, hbuf, 4); \
+    } while (0)
+#endif
+
+/* Load registers with state in inflate() for speed */
+#define LOAD() \
+    do { \
+        put = strm->next_out; \
+        left = strm->avail_out; \
+        next = strm->next_in; \
+        have = strm->avail_in; \
+        hold = state->hold; \
+        bits = state->bits; \
+    } while (0)
+
+/* Restore state from registers in inflate() */
+#define RESTORE() \
+    do { \
+        strm->next_out = put; \
+        strm->avail_out = left; \
+        strm->next_in = next; \
+        strm->avail_in = have; \
+        state->hold = hold; \
+        state->bits = bits; \
+    } while (0)
+
+/* Clear the input bit accumulator */
+#define INITBITS() \
+    do { \
+        hold = 0; \
+        bits = 0; \
+    } while (0)
+
+/* Get a byte of input into the bit accumulator, or return from inflate()
+   if there is no input available. */
+#define PULLBYTE() \
+    do { \
+        if (have == 0) goto inf_leave; \
+        have--; \
+        hold += (unsigned long)(*next++) << bits; \
+        bits += 8; \
+    } while (0)
+
+/* Assure that there are at least n bits in the bit accumulator.  If there is
+   not enough available input to do that, then return from inflate(). */
+#define NEEDBITS(n) \
+    do { \
+        while (bits < (unsigned)(n)) \
+            PULLBYTE(); \
+    } while (0)
+
+/* Return the low n bits of the bit accumulator (n < 16) */
+#define BITS(n) \
+    ((unsigned)hold & ((1U << (n)) - 1))
+
+/* Remove n bits from the bit accumulator */
+#define DROPBITS(n) \
+    do { \
+        hold >>= (n); \
+        bits -= (unsigned)(n); \
+    } while (0)
+
+/* Remove zero to seven bits as needed to go to a byte boundary */
+#define BYTEBITS() \
+    do { \
+        hold >>= bits & 7; \
+        bits -= bits & 7; \
+    } while (0)
+
+/* Reverse the bytes in a 32-bit value */
+#define REVERSE(q) \
+    ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
+     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
+
+/*
+   inflate() uses a state machine to process as much input data and generate as
+   much output data as possible before returning.  The state machine is
+   structured roughly as follows:
+
+    for (;;) switch (state) {
+    ...
+    case STATEn:
+        if (not enough input data or output space to make progress)
+            return;
+        ... make progress ...
+        state = STATEm;
+        break;
+    ...
+    }
+
+   so when inflate() is called again, the same case is attempted again, and
+   if the appropriate resources are provided, the machine proceeds to the
+   next state.  The NEEDBITS() macro is usually the way the state evaluates
+   whether it can proceed or should return.  NEEDBITS() does the return if
+   the requested bits are not available.  The typical use of the BITS macros
+   is:
+
+        NEEDBITS(n);
+        ... do something with BITS(n) ...
+        DROPBITS(n);
+
+   where NEEDBITS(n) either returns from inflate() if there isn't enough
+   input left to load n bits into the accumulator, or it continues.  BITS(n)
+   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
+   the low n bits off the accumulator.  INITBITS() clears the accumulator
+   and sets the number of available bits to zero.  BYTEBITS() discards just
+   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
+   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
+
+   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
+   if there is no input available.  The decoding of variable length codes uses
+   PULLBYTE() directly in order to pull just enough bytes to decode the next
+   code, and no more.
+
+   Some states loop until they get enough input, making sure that enough
+   state information is maintained to continue the loop where it left off
+   if NEEDBITS() returns in the loop.  For example, want, need, and keep
+   would all have to actually be part of the saved state in case NEEDBITS()
+   returns:
+
+    case STATEw:
+        while (want < need) {
+            NEEDBITS(n);
+            keep[want++] = BITS(n);
+            DROPBITS(n);
+        }
+        state = STATEx;
+    case STATEx:
+
+   As shown above, if the next state is also the next case, then the break
+   is omitted.
+
+   A state may also return if there is not enough output space available to
+   complete that state.  Those states are copying stored data, writing a
+   literal byte, and copying a matching string.
+
+   When returning, a "goto inf_leave" is used to update the total counters,
+   update the check value, and determine whether any progress has been made
+   during that inflate() call in order to return the proper return code.
+   Progress is defined as a change in either strm->avail_in or strm->avail_out.
+   When there is a window, goto inf_leave will update the window with the last
+   output written.  If a goto inf_leave occurs in the middle of decompression
+   and there is no window currently, goto inf_leave will create one and copy
+   output to the window for the next call of inflate().
+
+   In this implementation, the flush parameter of inflate() only affects the
+   return code (per zlib.h).  inflate() always writes as much as possible to
+   strm->next_out, given the space available and the provided input--the effect
+   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
+   the allocation of and copying into a sliding window until necessary, which
+   provides the effect documented in zlib.h for Z_FINISH when the entire input
+   stream available.  So the only thing the flush parameter actually does is:
+   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
+   will return Z_BUF_ERROR if it has not reached the end of the stream.
+ */
+
+int ZEXPORT inflate(strm, flush)
+z_streamp strm;
+int flush;
+{
+    struct inflate_state FAR *state;
+    unsigned char FAR *next;    /* next input */
+    unsigned char FAR *put;     /* next output */
+    unsigned have, left;        /* available input and output */
+    unsigned long hold;         /* bit buffer */
+    unsigned bits;              /* bits in bit buffer */
+    unsigned in, out;           /* save starting available input and output */
+    unsigned copy;              /* number of stored or match bytes to copy */
+    unsigned char FAR *from;    /* where to copy match bytes from */
+    code here;                  /* current decoding table entry */
+    code last;                  /* parent table entry */
+    unsigned len;               /* length to copy for repeats, bits to drop */
+    int ret;                    /* return code */
+#ifdef GUNZIP
+    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
+#endif
+    static const unsigned short order[19] = /* permutation of code lengths */
+        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+    if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
+        (strm->next_in == Z_NULL && strm->avail_in != 0))
+        return Z_STREAM_ERROR;
+
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
+    LOAD();
+    in = have;
+    out = left;
+    ret = Z_OK;
+    for (;;)
+        switch (state->mode) {
+        case HEAD:
+            if (state->wrap == 0) {
+                state->mode = TYPEDO;
+                break;
+            }
+            NEEDBITS(16);
+#ifdef GUNZIP
+            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
+                state->check = crc32(0L, Z_NULL, 0);
+                CRC2(state->check, hold);
+                INITBITS();
+                state->mode = FLAGS;
+                break;
+            }
+            state->flags = 0;           /* expect zlib header */
+            if (state->head != Z_NULL)
+                state->head->done = -1;
+            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
+#else
+            if (
+#endif
+                ((BITS(8) << 8) + (hold >> 8)) % 31) {
+                strm->msg = (char *)"incorrect header check";
+                state->mode = BAD;
+                break;
+            }
+            if (BITS(4) != Z_DEFLATED) {
+                strm->msg = (char *)"unknown compression method";
+                state->mode = BAD;
+                break;
+            }
+            DROPBITS(4);
+            len = BITS(4) + 8;
+            if (state->wbits == 0)
+                state->wbits = len;
+            else if (len > state->wbits) {
+                strm->msg = (char *)"invalid window size";
+                state->mode = BAD;
+                break;
+            }
+            state->dmax = 1U << len;
+            Tracev((stderr, "inflate:   zlib header ok\n"));
+            strm->adler = state->check = adler32(0L, Z_NULL, 0);
+            state->mode = hold & 0x200 ? DICTID : TYPE;
+            INITBITS();
+            break;
+#ifdef GUNZIP
+        case FLAGS:
+            NEEDBITS(16);
+            state->flags = (int)(hold);
+            if ((state->flags & 0xff) != Z_DEFLATED) {
+                strm->msg = (char *)"unknown compression method";
+                state->mode = BAD;
+                break;
+            }
+            if (state->flags & 0xe000) {
+                strm->msg = (char *)"unknown header flags set";
+                state->mode = BAD;
+                break;
+            }
+            if (state->head != Z_NULL)
+                state->head->text = (int)((hold >> 8) & 1);
+            if (state->flags & 0x0200) CRC2(state->check, hold);
+            INITBITS();
+            state->mode = TIME;
+        case TIME:
+            NEEDBITS(32);
+            if (state->head != Z_NULL)
+                state->head->time = hold;
+            if (state->flags & 0x0200) CRC4(state->check, hold);
+            INITBITS();
+            state->mode = OS;
+        case OS:
+            NEEDBITS(16);
+            if (state->head != Z_NULL) {
+                state->head->xflags = (int)(hold & 0xff);
+                state->head->os = (int)(hold >> 8);
+            }
+            if (state->flags & 0x0200) CRC2(state->check, hold);
+            INITBITS();
+            state->mode = EXLEN;
+        case EXLEN:
+            if (state->flags & 0x0400) {
+                NEEDBITS(16);
+                state->length = (unsigned)(hold);
+                if (state->head != Z_NULL)
+                    state->head->extra_len = (unsigned)hold;
+                if (state->flags & 0x0200) CRC2(state->check, hold);
+                INITBITS();
+            }
+            else if (state->head != Z_NULL)
+                state->head->extra = Z_NULL;
+            state->mode = EXTRA;
+        case EXTRA:
+            if (state->flags & 0x0400) {
+                copy = state->length;
+                if (copy > have) copy = have;
+                if (copy) {
+                    if (state->head != Z_NULL &&
+                        state->head->extra != Z_NULL) {
+                        len = state->head->extra_len - state->length;
+                        zmemcpy(state->head->extra + len, next,
+                                len + copy > state->head->extra_max ?
+                                state->head->extra_max - len : copy);
+                    }
+                    if (state->flags & 0x0200)
+                        state->check = crc32(state->check, next, copy);
+                    have -= copy;
+                    next += copy;
+                    state->length -= copy;
+                }
+                if (state->length) goto inf_leave;
+            }
+            state->length = 0;
+            state->mode = NAME;
+        case NAME:
+            if (state->flags & 0x0800) {
+                if (have == 0) goto inf_leave;
+                copy = 0;
+                do {
+                    len = (unsigned)(next[copy++]);
+                    if (state->head != Z_NULL &&
+                            state->head->name != Z_NULL &&
+                            state->length < state->head->name_max)
+                        state->head->name[state->length++] = len;
+                } while (len && copy < have);
+                if (state->flags & 0x0200)
+                    state->check = crc32(state->check, next, copy);
+                have -= copy;
+                next += copy;
+                if (len) goto inf_leave;
+            }
+            else if (state->head != Z_NULL)
+                state->head->name = Z_NULL;
+            state->length = 0;
+            state->mode = COMMENT;
+        case COMMENT:
+            if (state->flags & 0x1000) {
+                if (have == 0) goto inf_leave;
+                copy = 0;
+                do {
+                    len = (unsigned)(next[copy++]);
+                    if (state->head != Z_NULL &&
+                            state->head->comment != Z_NULL &&
+                            state->length < state->head->comm_max)
+                        state->head->comment[state->length++] = len;
+                } while (len && copy < have);
+                if (state->flags & 0x0200)
+                    state->check = crc32(state->check, next, copy);
+                have -= copy;
+                next += copy;
+                if (len) goto inf_leave;
+            }
+            else if (state->head != Z_NULL)
+                state->head->comment = Z_NULL;
+            state->mode = HCRC;
+        case HCRC:
+            if (state->flags & 0x0200) {
+                NEEDBITS(16);
+                if (hold != (state->check & 0xffff)) {
+                    strm->msg = (char *)"header crc mismatch";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+            }
+            if (state->head != Z_NULL) {
+                state->head->hcrc = (int)((state->flags >> 9) & 1);
+                state->head->done = 1;
+            }
+            strm->adler = state->check = crc32(0L, Z_NULL, 0);
+            state->mode = TYPE;
+            break;
+#endif
+        case DICTID:
+            NEEDBITS(32);
+            strm->adler = state->check = REVERSE(hold);
+            INITBITS();
+            state->mode = DICT;
+        case DICT:
+            if (state->havedict == 0) {
+                RESTORE();
+                return Z_NEED_DICT;
+            }
+            strm->adler = state->check = adler32(0L, Z_NULL, 0);
+            state->mode = TYPE;
+        case TYPE:
+            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
+        case TYPEDO:
+            if (state->last) {
+                BYTEBITS();
+                state->mode = CHECK;
+                break;
+            }
+            NEEDBITS(3);
+            state->last = BITS(1);
+            DROPBITS(1);
+            switch (BITS(2)) {
+            case 0:                             /* stored block */
+                Tracev((stderr, "inflate:     stored block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = STORED;
+                break;
+            case 1:                             /* fixed block */
+                fixedtables(state);
+                Tracev((stderr, "inflate:     fixed codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = LEN_;             /* decode codes */
+                if (flush == Z_TREES) {
+                    DROPBITS(2);
+                    goto inf_leave;
+                }
+                break;
+            case 2:                             /* dynamic block */
+                Tracev((stderr, "inflate:     dynamic codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = TABLE;
+                break;
+            case 3:
+                strm->msg = (char *)"invalid block type";
+                state->mode = BAD;
+            }
+            DROPBITS(2);
+            break;
+        case STORED:
+            BYTEBITS();                         /* go to byte boundary */
+            NEEDBITS(32);
+            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
+                strm->msg = (char *)"invalid stored block lengths";
+                state->mode = BAD;
+                break;
+            }
+            state->length = (unsigned)hold & 0xffff;
+            Tracev((stderr, "inflate:       stored length %u\n",
+                    state->length));
+            INITBITS();
+            state->mode = COPY_;
+            if (flush == Z_TREES) goto inf_leave;
+        case COPY_:
+            state->mode = COPY;
+        case COPY:
+            copy = state->length;
+            if (copy) {
+                if (copy > have) copy = have;
+                if (copy > left) copy = left;
+                if (copy == 0) goto inf_leave;
+                zmemcpy(put, next, copy);
+                have -= copy;
+                next += copy;
+                left -= copy;
+                put += copy;
+                state->length -= copy;
+                break;
+            }
+            Tracev((stderr, "inflate:       stored end\n"));
+            state->mode = TYPE;
+            break;
+        case TABLE:
+            NEEDBITS(14);
+            state->nlen = BITS(5) + 257;
+            DROPBITS(5);
+            state->ndist = BITS(5) + 1;
+            DROPBITS(5);
+            state->ncode = BITS(4) + 4;
+            DROPBITS(4);
+#ifndef PKZIP_BUG_WORKAROUND
+            if (state->nlen > 286 || state->ndist > 30) {
+                strm->msg = (char *)"too many length or distance symbols";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            Tracev((stderr, "inflate:       table sizes ok\n"));
+            state->have = 0;
+            state->mode = LENLENS;
+        case LENLENS:
+            while (state->have < state->ncode) {
+                NEEDBITS(3);
+                state->lens[order[state->have++]] = (unsigned short)BITS(3);
+                DROPBITS(3);
+            }
+            while (state->have < 19)
+                state->lens[order[state->have++]] = 0;
+            state->next = state->codes;
+            state->lencode = (code const FAR *)(state->next);
+            state->lenbits = 7;
+            ret = inflate_table(CODES, state->lens, 19, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid code lengths set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       code lengths ok\n"));
+            state->have = 0;
+            state->mode = CODELENS;
+        case CODELENS:
+            while (state->have < state->nlen + state->ndist) {
+                for (;;) {
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                if (here.val < 16) {
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
+                }
+                else {
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
+                        if (state->have == 0) {
+                            strm->msg = (char *)"invalid bit length repeat";
+                            state->mode = BAD;
+                            break;
+                        }
+                        len = state->lens[state->have - 1];
+                        copy = 3 + BITS(2);
+                        DROPBITS(2);
+                    }
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 3 + BITS(3);
+                        DROPBITS(3);
+                    }
+                    else {
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 11 + BITS(7);
+                        DROPBITS(7);
+                    }
+                    if (state->have + copy > state->nlen + state->ndist) {
+                        strm->msg = (char *)"invalid bit length repeat";
+                        state->mode = BAD;
+                        break;
+                    }
+                    while (copy--)
+                        state->lens[state->have++] = (unsigned short)len;
+                }
+            }
+
+            /* handle error breaks in while */
+            if (state->mode == BAD) break;
+
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
+            state->next = state->codes;
+            state->lencode = (code const FAR *)(state->next);
+            state->lenbits = 9;
+            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid literal/lengths set";
+                state->mode = BAD;
+                break;
+            }
+            state->distcode = (code const FAR *)(state->next);
+            state->distbits = 6;
+            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
+                            &(state->next), &(state->distbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid distances set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       codes ok\n"));
+            state->mode = LEN_;
+            if (flush == Z_TREES) goto inf_leave;
+        case LEN_:
+            state->mode = LEN;
+        case LEN:
+            if (have >= 6 && left >= 258) {
+                RESTORE();
+                inflate_fast(strm, out);
+                LOAD();
+                if (state->mode == TYPE)
+                    state->back = -1;
+                break;
+            }
+            state->back = 0;
+            for (;;) {
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->lencode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+                state->back += last.bits;
+            }
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            state->length = (unsigned)here.val;
+            if ((int)(here.op) == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                        "inflate:         literal '%c'\n" :
+                        "inflate:         literal 0x%02x\n", here.val));
+                state->mode = LIT;
+                break;
+            }
+            if (here.op & 32) {
+                Tracevv((stderr, "inflate:         end of block\n"));
+                state->back = -1;
+                state->mode = TYPE;
+                break;
+            }
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid literal/length code";
+                state->mode = BAD;
+                break;
+            }
+            state->extra = (unsigned)(here.op) & 15;
+            state->mode = LENEXT;
+        case LENEXT:
+            if (state->extra) {
+                NEEDBITS(state->extra);
+                state->length += BITS(state->extra);
+                DROPBITS(state->extra);
+                state->back += state->extra;
+            }
+            Tracevv((stderr, "inflate:         length %u\n", state->length));
+            state->was = state->length;
+            state->mode = DIST;
+        case DIST:
+            for (;;) {
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if ((here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->distcode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+                state->back += last.bits;
+            }
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+            state->offset = (unsigned)here.val;
+            state->extra = (unsigned)(here.op) & 15;
+            state->mode = DISTEXT;
+        case DISTEXT:
+            if (state->extra) {
+                NEEDBITS(state->extra);
+                state->offset += BITS(state->extra);
+                DROPBITS(state->extra);
+                state->back += state->extra;
+            }
+#ifdef INFLATE_STRICT
+            if (state->offset > state->dmax) {
+                strm->msg = (char *)"invalid distance too far back";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
+            state->mode = MATCH;
+        case MATCH:
+            if (left == 0) goto inf_leave;
+            copy = out - left;
+            if (state->offset > copy) {         /* copy from window */
+                copy = state->offset - copy;
+                if (copy > state->whave) {
+                    if (state->sane) {
+                        strm->msg = (char *)"invalid distance too far back";
+                        state->mode = BAD;
+                        break;
+                    }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                    Trace((stderr, "inflate.c too far\n"));
+                    copy -= state->whave;
+                    if (copy > state->length) copy = state->length;
+                    if (copy > left) copy = left;
+                    left -= copy;
+                    state->length -= copy;
+                    do {
+                        *put++ = 0;
+                    } while (--copy);
+                    if (state->length == 0) state->mode = LEN;
+                    break;
+#endif
+                }
+                if (copy > state->wnext) {
+                    copy -= state->wnext;
+                    from = state->window + (state->wsize - copy);
+                }
+                else
+                    from = state->window + (state->wnext - copy);
+                if (copy > state->length) copy = state->length;
+            }
+            else {                              /* copy from output */
+                from = put - state->offset;
+                copy = state->length;
+            }
+            if (copy > left) copy = left;
+            left -= copy;
+            state->length -= copy;
+            do {
+                *put++ = *from++;
+            } while (--copy);
+            if (state->length == 0) state->mode = LEN;
+            break;
+        case LIT:
+            if (left == 0) goto inf_leave;
+            *put++ = (unsigned char)(state->length);
+            left--;
+            state->mode = LEN;
+            break;
+        case CHECK:
+            if (state->wrap) {
+                NEEDBITS(32);
+                out -= left;
+                strm->total_out += out;
+                state->total += out;
+                if (out)
+                    strm->adler = state->check =
+                        UPDATE(state->check, put - out, out);
+                out = left;
+                if ((
+#ifdef GUNZIP
+                     state->flags ? hold :
+#endif
+                     REVERSE(hold)) != state->check) {
+                    strm->msg = (char *)"incorrect data check";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+                Tracev((stderr, "inflate:   check matches trailer\n"));
+            }
+#ifdef GUNZIP
+            state->mode = LENGTH;
+        case LENGTH:
+            if (state->wrap && state->flags) {
+                NEEDBITS(32);
+                if (hold != (state->total & 0xffffffffUL)) {
+                    strm->msg = (char *)"incorrect length check";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+                Tracev((stderr, "inflate:   length matches trailer\n"));
+            }
+#endif
+            state->mode = DONE;
+        case DONE:
+            ret = Z_STREAM_END;
+            goto inf_leave;
+        case BAD:
+            ret = Z_DATA_ERROR;
+            goto inf_leave;
+        case MEM:
+            return Z_MEM_ERROR;
+        case SYNC:
+        default:
+            return Z_STREAM_ERROR;
+        }
+
+    /*
+       Return from inflate(), updating the total counts and the check value.
+       If there was no progress during the inflate() call, return a buffer
+       error.  Call updatewindow() to create and/or update the window state.
+       Note: a memory error from inflate() is non-recoverable.
+     */
+  inf_leave:
+    RESTORE();
+    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
+            (state->mode < CHECK || flush != Z_FINISH)))
+        if (updatewindow(strm, out)) {
+            state->mode = MEM;
+            return Z_MEM_ERROR;
+        }
+    in -= strm->avail_in;
+    out -= strm->avail_out;
+    strm->total_in += in;
+    strm->total_out += out;
+    state->total += out;
+    if (state->wrap && out)
+        strm->adler = state->check =
+            UPDATE(state->check, strm->next_out - out, out);
+    strm->data_type = state->bits + (state->last ? 64 : 0) +
+                      (state->mode == TYPE ? 128 : 0) +
+                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
+    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
+        ret = Z_BUF_ERROR;
+    return ret;
+}
+
+int ZEXPORT inflateEnd(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->window != Z_NULL) ZFREE(strm, state->window);
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+    Tracev((stderr, "inflate: end\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
+z_streamp strm;
+const Bytef *dictionary;
+uInt dictLength;
+{
+    struct inflate_state FAR *state;
+    unsigned long id;
+    unsigned char *next;
+    unsigned avail;
+    int ret;
+
+    /* check state */
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->wrap != 0 && state->mode != DICT)
+        return Z_STREAM_ERROR;
+
+    /* check for correct dictionary id */
+    if (state->mode == DICT) {
+        id = adler32(0L, Z_NULL, 0);
+        id = adler32(id, dictionary, dictLength);
+        if (id != state->check)
+            return Z_DATA_ERROR;
+    }
+
+    /* copy dictionary to window using updatewindow(), which will amend the
+       existing dictionary if appropriate */
+    next = strm->next_out;
+    avail = strm->avail_out;
+    strm->next_out = (Bytef *)dictionary + dictLength;
+    strm->avail_out = 0;
+    ret = updatewindow(strm, dictLength);
+    strm->avail_out = avail;
+    strm->next_out = next;
+    if (ret) {
+        state->mode = MEM;
+        return Z_MEM_ERROR;
+    }
+    state->havedict = 1;
+    Tracev((stderr, "inflate:   dictionary set\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateGetHeader(strm, head)
+z_streamp strm;
+gz_headerp head;
+{
+    struct inflate_state FAR *state;
+
+    /* check state */
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
+
+    /* save header structure */
+    state->head = head;
+    head->done = 0;
+    return Z_OK;
+}
+
+/*
+   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
+   or when out of input.  When called, *have is the number of pattern bytes
+   found in order so far, in 0..3.  On return *have is updated to the new
+   state.  If on return *have equals four, then the pattern was found and the
+   return value is how many bytes were read including the last byte of the
+   pattern.  If *have is less than four, then the pattern has not been found
+   yet and the return value is len.  In the latter case, syncsearch() can be
+   called again with more data and the *have state.  *have is initialized to
+   zero for the first call.
+ */
+local unsigned syncsearch(have, buf, len)
+unsigned FAR *have;
+unsigned char FAR *buf;
+unsigned len;
+{
+    unsigned got;
+    unsigned next;
+
+    got = *have;
+    next = 0;
+    while (next < len && got < 4) {
+        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
+            got++;
+        else if (buf[next])
+            got = 0;
+        else
+            got = 4 - got;
+        next++;
+    }
+    *have = got;
+    return next;
+}
+
+int ZEXPORT inflateSync(strm)
+z_streamp strm;
+{
+    unsigned len;               /* number of bytes to look at or looked at */
+    unsigned long in, out;      /* temporary to save total_in and total_out */
+    unsigned char buf[4];       /* to restore bit buffer to byte string */
+    struct inflate_state FAR *state;
+
+    /* check parameters */
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
+
+    /* if first time, start search in bit buffer */
+    if (state->mode != SYNC) {
+        state->mode = SYNC;
+        state->hold <<= state->bits & 7;
+        state->bits -= state->bits & 7;
+        len = 0;
+        while (state->bits >= 8) {
+            buf[len++] = (unsigned char)(state->hold);
+            state->hold >>= 8;
+            state->bits -= 8;
+        }
+        state->have = 0;
+        syncsearch(&(state->have), buf, len);
+    }
+
+    /* search available input */
+    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
+    strm->avail_in -= len;
+    strm->next_in += len;
+    strm->total_in += len;
+
+    /* return no joy or set up to restart inflate() on a new block */
+    if (state->have != 4) return Z_DATA_ERROR;
+    in = strm->total_in;  out = strm->total_out;
+    inflateReset(strm);
+    strm->total_in = in;  strm->total_out = out;
+    state->mode = TYPE;
+    return Z_OK;
+}
+
+/*
+   Returns true if inflate is currently at the end of a block generated by
+   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
+   implementation to provide an additional safety check. PPP uses
+   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
+   block. When decompressing, PPP checks that at the end of input packet,
+   inflate is waiting for these length bytes.
+ */
+int ZEXPORT inflateSyncPoint(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    return state->mode == STORED && state->bits == 0;
+}
+
+int ZEXPORT inflateCopy(dest, source)
+z_streamp dest;
+z_streamp source;
+{
+    struct inflate_state FAR *state;
+    struct inflate_state FAR *copy;
+    unsigned char FAR *window;
+    unsigned wsize;
+
+    /* check input */
+    if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
+        source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)source->state;
+
+    /* allocate space */
+    copy = (struct inflate_state FAR *)
+           ZALLOC(source, 1, sizeof(struct inflate_state));
+    if (copy == Z_NULL) return Z_MEM_ERROR;
+    window = Z_NULL;
+    if (state->window != Z_NULL) {
+        window = (unsigned char FAR *)
+                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
+        if (window == Z_NULL) {
+            ZFREE(source, copy);
+            return Z_MEM_ERROR;
+        }
+    }
+
+    /* copy state */
+    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
+    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
+    if (state->lencode >= state->codes &&
+        state->lencode <= state->codes + ENOUGH - 1) {
+        copy->lencode = copy->codes + (state->lencode - state->codes);
+        copy->distcode = copy->codes + (state->distcode - state->codes);
+    }
+    copy->next = copy->codes + (state->next - state->codes);
+    if (window != Z_NULL) {
+        wsize = 1U << state->wbits;
+        zmemcpy(window, state->window, wsize);
+    }
+    copy->window = window;
+    dest->state = (struct internal_state FAR *)copy;
+    return Z_OK;
+}
+
+int ZEXPORT inflateUndermine(strm, subvert)
+z_streamp strm;
+int subvert;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    state->sane = !subvert;
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+    return Z_OK;
+#else
+    state->sane = 1;
+    return Z_DATA_ERROR;
+#endif
+}
+
+long ZEXPORT inflateMark(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;
+    state = (struct inflate_state FAR *)strm->state;
+    return ((long)(state->back) << 16) +
+        (state->mode == COPY ? state->length :
+            (state->mode == MATCH ? state->was - state->length : 0));
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inflate.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inflate.h
new file mode 100644 (file)
index 0000000..95f4986
--- /dev/null
@@ -0,0 +1,122 @@
+/* inflate.h -- internal inflate state definition
+ * Copyright (C) 1995-2009 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* define NO_GZIP when compiling if you want to disable gzip header and
+   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in
+   the crc code when it is not needed.  For shared libraries, gzip decoding
+   should be left enabled. */
+#ifndef NO_GZIP
+#  define GUNZIP
+#endif
+
+/* Possible inflate modes between inflate() calls */
+typedef enum {
+    HEAD,       /* i: waiting for magic header */
+    FLAGS,      /* i: waiting for method and flags (gzip) */
+    TIME,       /* i: waiting for modification time (gzip) */
+    OS,         /* i: waiting for extra flags and operating system (gzip) */
+    EXLEN,      /* i: waiting for extra length (gzip) */
+    EXTRA,      /* i: waiting for extra bytes (gzip) */
+    NAME,       /* i: waiting for end of file name (gzip) */
+    COMMENT,    /* i: waiting for end of comment (gzip) */
+    HCRC,       /* i: waiting for header crc (gzip) */
+    DICTID,     /* i: waiting for dictionary check value */
+    DICT,       /* waiting for inflateSetDictionary() call */
+        TYPE,       /* i: waiting for type bits, including last-flag bit */
+        TYPEDO,     /* i: same, but skip check to exit inflate on new block */
+        STORED,     /* i: waiting for stored size (length and complement) */
+        COPY_,      /* i/o: same as COPY below, but only first time in */
+        COPY,       /* i/o: waiting for input or output to copy stored block */
+        TABLE,      /* i: waiting for dynamic block table lengths */
+        LENLENS,    /* i: waiting for code length code lengths */
+        CODELENS,   /* i: waiting for length/lit and distance code lengths */
+            LEN_,       /* i: same as LEN below, but only first time in */
+            LEN,        /* i: waiting for length/lit/eob code */
+            LENEXT,     /* i: waiting for length extra bits */
+            DIST,       /* i: waiting for distance code */
+            DISTEXT,    /* i: waiting for distance extra bits */
+            MATCH,      /* o: waiting for output space to copy string */
+            LIT,        /* o: waiting for output space to write literal */
+    CHECK,      /* i: waiting for 32-bit check value */
+    LENGTH,     /* i: waiting for 32-bit length (gzip) */
+    DONE,       /* finished check, done -- remain here until reset */
+    BAD,        /* got a data error -- remain here until reset */
+    MEM,        /* got an inflate() memory error -- remain here until reset */
+    SYNC        /* looking for synchronization bytes to restart inflate() */
+} inflate_mode;
+
+/*
+    State transitions between above modes -
+
+    (most modes can go to BAD or MEM on error -- not shown for clarity)
+
+    Process header:
+        HEAD -> (gzip) or (zlib) or (raw)
+        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
+                  HCRC -> TYPE
+        (zlib) -> DICTID or TYPE
+        DICTID -> DICT -> TYPE
+        (raw) -> TYPEDO
+    Read deflate blocks:
+            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
+            STORED -> COPY_ -> COPY -> TYPE
+            TABLE -> LENLENS -> CODELENS -> LEN_
+            LEN_ -> LEN
+    Read deflate codes in fixed or dynamic block:
+                LEN -> LENEXT or LIT or TYPE
+                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
+                LIT -> LEN
+    Process trailer:
+        CHECK -> LENGTH -> DONE
+ */
+
+/* state maintained between inflate() calls.  Approximately 10K bytes. */
+struct inflate_state {
+    inflate_mode mode;          /* current inflate mode */
+    int last;                   /* true if processing last block */
+    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip */
+    int havedict;               /* true if dictionary provided */
+    int flags;                  /* gzip header method and flags (0 if zlib) */
+    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */
+    unsigned long check;        /* protected copy of check value */
+    unsigned long total;        /* protected copy of output count */
+    gz_headerp head;            /* where to save gzip header information */
+        /* sliding window */
+    unsigned wbits;             /* log base 2 of requested window size */
+    unsigned wsize;             /* window size or zero if not using window */
+    unsigned whave;             /* valid bytes in the window */
+    unsigned wnext;             /* window write index */
+    unsigned char FAR *window;  /* allocated sliding window, if needed */
+        /* bit accumulator */
+    unsigned long hold;         /* input bit accumulator */
+    unsigned bits;              /* number of bits in "in" */
+        /* for string and stored block copying */
+    unsigned length;            /* literal or length of data to copy */
+    unsigned offset;            /* distance back to copy string from */
+        /* for table and code decoding */
+    unsigned extra;             /* extra bits needed */
+        /* fixed and dynamic code tables */
+    code const FAR *lencode;    /* starting table for length/literal codes */
+    code const FAR *distcode;   /* starting table for distance codes */
+    unsigned lenbits;           /* index bits for lencode */
+    unsigned distbits;          /* index bits for distcode */
+        /* dynamic table building */
+    unsigned ncode;             /* number of code length code lengths */
+    unsigned nlen;              /* number of length code lengths */
+    unsigned ndist;             /* number of distance code lengths */
+    unsigned have;              /* number of code lengths in lens[] */
+    code FAR *next;             /* next available space in codes[] */
+    unsigned short lens[320];   /* temporary storage for code lengths */
+    unsigned short work[288];   /* work area for code table building */
+    code codes[ENOUGH];         /* space for code tables */
+    int sane;                   /* if false, allow invalid distance too far */
+    int back;                   /* bits back of last unprocessed length/lit */
+    unsigned was;               /* initial length of match */
+};
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inftrees.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inftrees.c
new file mode 100644 (file)
index 0000000..60bbd58
--- /dev/null
@@ -0,0 +1,306 @@
+/* inftrees.c -- generate Huffman trees for efficient decoding
+ * Copyright (C) 1995-2012 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+
+#define MAXBITS 15
+
+const char inflate_copyright[] =
+   " inflate 1.2.6 Copyright 1995-2012 Mark Adler ";
+/*
+  If you use the zlib library in a product, an acknowledgment is welcome
+  in the documentation of your product. If for some reason you cannot
+  include such an acknowledgment, I would appreciate that you keep this
+  copyright string in the executable of your product.
+ */
+
+/*
+   Build a set of tables to decode the provided canonical Huffman code.
+   The code lengths are lens[0..codes-1].  The result starts at *table,
+   whose indices are 0..2^bits-1.  work is a writable array of at least
+   lens shorts, which is used as a work area.  type is the type of code
+   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
+   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
+   on return points to the next available entry's address.  bits is the
+   requested root table index bits, and on return it is the actual root
+   table index bits.  It will differ if the request is greater than the
+   longest code or if it is less than the shortest code.
+ */
+int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
+codetype type;
+unsigned short FAR *lens;
+unsigned codes;
+code FAR * FAR *table;
+unsigned FAR *bits;
+unsigned short FAR *work;
+{
+    unsigned len;               /* a code's length in bits */
+    unsigned sym;               /* index of code symbols */
+    unsigned min, max;          /* minimum and maximum code lengths */
+    unsigned root;              /* number of index bits for root table */
+    unsigned curr;              /* number of index bits for current table */
+    unsigned drop;              /* code bits to drop for sub-table */
+    int left;                   /* number of prefix codes available */
+    unsigned used;              /* code entries in table used */
+    unsigned huff;              /* Huffman code */
+    unsigned incr;              /* for incrementing code, index */
+    unsigned fill;              /* index for replicating entries */
+    unsigned low;               /* low bits for current root entry */
+    unsigned mask;              /* mask for low root bits */
+    code here;                  /* table entry for duplication */
+    code FAR *next;             /* next available space in table */
+    const unsigned short FAR *base;     /* base value table to use */
+    const unsigned short FAR *extra;    /* extra bits table to use */
+    int end;                    /* use base and extra for symbol > end */
+    unsigned short count[MAXBITS+1];    /* number of codes of each length */
+    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
+    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
+        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
+    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
+        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
+        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 203, 69};
+    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
+        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+        8193, 12289, 16385, 24577, 0, 0};
+    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
+        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
+        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
+        28, 28, 29, 29, 64, 64};
+
+    /*
+       Process a set of code lengths to create a canonical Huffman code.  The
+       code lengths are lens[0..codes-1].  Each length corresponds to the
+       symbols 0..codes-1.  The Huffman code is generated by first sorting the
+       symbols by length from short to long, and retaining the symbol order
+       for codes with equal lengths.  Then the code starts with all zero bits
+       for the first code of the shortest length, and the codes are integer
+       increments for the same length, and zeros are appended as the length
+       increases.  For the deflate format, these bits are stored backwards
+       from their more natural integer increment ordering, and so when the
+       decoding tables are built in the large loop below, the integer codes
+       are incremented backwards.
+
+       This routine assumes, but does not check, that all of the entries in
+       lens[] are in the range 0..MAXBITS.  The caller must assure this.
+       1..MAXBITS is interpreted as that code length.  zero means that that
+       symbol does not occur in this code.
+
+       The codes are sorted by computing a count of codes for each length,
+       creating from that a table of starting indices for each length in the
+       sorted table, and then entering the symbols in order in the sorted
+       table.  The sorted table is work[], with that space being provided by
+       the caller.
+
+       The length counts are used for other purposes as well, i.e. finding
+       the minimum and maximum length codes, determining if there are any
+       codes at all, checking for a valid set of lengths, and looking ahead
+       at length counts to determine sub-table sizes when building the
+       decoding tables.
+     */
+
+    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
+    for (len = 0; len <= MAXBITS; len++)
+        count[len] = 0;
+    for (sym = 0; sym < codes; sym++)
+        count[lens[sym]]++;
+
+    /* bound code lengths, force root to be within code lengths */
+    root = *bits;
+    for (max = MAXBITS; max >= 1; max--)
+        if (count[max] != 0) break;
+    if (root > max) root = max;
+    if (max == 0) {                     /* no symbols to code at all */
+        here.op = (unsigned char)64;    /* invalid code marker */
+        here.bits = (unsigned char)1;
+        here.val = (unsigned short)0;
+        *(*table)++ = here;             /* make a table to force an error */
+        *(*table)++ = here;
+        *bits = 1;
+        return 0;     /* no symbols, but wait for decoding to report error */
+    }
+    for (min = 1; min < max; min++)
+        if (count[min] != 0) break;
+    if (root < min) root = min;
+
+    /* check for an over-subscribed or incomplete set of lengths */
+    left = 1;
+    for (len = 1; len <= MAXBITS; len++) {
+        left <<= 1;
+        left -= count[len];
+        if (left < 0) return -1;        /* over-subscribed */
+    }
+    if (left > 0 && (type == CODES || max != 1))
+        return -1;                      /* incomplete set */
+
+    /* generate offsets into symbol table for each length for sorting */
+    offs[1] = 0;
+    for (len = 1; len < MAXBITS; len++)
+        offs[len + 1] = offs[len] + count[len];
+
+    /* sort symbols by length, by symbol order within each length */
+    for (sym = 0; sym < codes; sym++)
+        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
+
+    /*
+       Create and fill in decoding tables.  In this loop, the table being
+       filled is at next and has curr index bits.  The code being used is huff
+       with length len.  That code is converted to an index by dropping drop
+       bits off of the bottom.  For codes where len is less than drop + curr,
+       those top drop + curr - len bits are incremented through all values to
+       fill the table with replicated entries.
+
+       root is the number of index bits for the root table.  When len exceeds
+       root, sub-tables are created pointed to by the root entry with an index
+       of the low root bits of huff.  This is saved in low to check for when a
+       new sub-table should be started.  drop is zero when the root table is
+       being filled, and drop is root when sub-tables are being filled.
+
+       When a new sub-table is needed, it is necessary to look ahead in the
+       code lengths to determine what size sub-table is needed.  The length
+       counts are used for this, and so count[] is decremented as codes are
+       entered in the tables.
+
+       used keeps track of how many table entries have been allocated from the
+       provided *table space.  It is checked for LENS and DIST tables against
+       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
+       the initial root table size constants.  See the comments in inftrees.h
+       for more information.
+
+       sym increments through all symbols, and the loop terminates when
+       all codes of length max, i.e. all codes, have been processed.  This
+       routine permits incomplete codes, so another loop after this one fills
+       in the rest of the decoding tables with invalid code markers.
+     */
+
+    /* set up for code type */
+    switch (type) {
+    case CODES:
+        base = extra = work;    /* dummy value--not used */
+        end = 19;
+        break;
+    case LENS:
+        base = lbase;
+        base -= 257;
+        extra = lext;
+        extra -= 257;
+        end = 256;
+        break;
+    default:            /* DISTS */
+        base = dbase;
+        extra = dext;
+        end = -1;
+    }
+
+    /* initialize state for loop */
+    huff = 0;                   /* starting code */
+    sym = 0;                    /* starting code symbol */
+    len = min;                  /* starting code length */
+    next = *table;              /* current table to fill in */
+    curr = root;                /* current table index bits */
+    drop = 0;                   /* current bits to drop from code for index */
+    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
+    used = 1U << root;          /* use root table entries */
+    mask = used - 1;            /* mask for comparing low */
+
+    /* check available table space */
+    if ((type == LENS && used >= ENOUGH_LENS) ||
+        (type == DISTS && used >= ENOUGH_DISTS))
+        return 1;
+
+    /* process all codes and make table entries */
+    for (;;) {
+        /* create table entry */
+        here.bits = (unsigned char)(len - drop);
+        if ((int)(work[sym]) < end) {
+            here.op = (unsigned char)0;
+            here.val = work[sym];
+        }
+        else if ((int)(work[sym]) > end) {
+            here.op = (unsigned char)(extra[work[sym]]);
+            here.val = base[work[sym]];
+        }
+        else {
+            here.op = (unsigned char)(32 + 64);         /* end of block */
+            here.val = 0;
+        }
+
+        /* replicate for those indices with low len bits equal to huff */
+        incr = 1U << (len - drop);
+        fill = 1U << curr;
+        min = fill;                 /* save offset to next table */
+        do {
+            fill -= incr;
+            next[(huff >> drop) + fill] = here;
+        } while (fill != 0);
+
+        /* backwards increment the len-bit code huff */
+        incr = 1U << (len - 1);
+        while (huff & incr)
+            incr >>= 1;
+        if (incr != 0) {
+            huff &= incr - 1;
+            huff += incr;
+        }
+        else
+            huff = 0;
+
+        /* go to next symbol, update count, len */
+        sym++;
+        if (--(count[len]) == 0) {
+            if (len == max) break;
+            len = lens[work[sym]];
+        }
+
+        /* create new sub-table if needed */
+        if (len > root && (huff & mask) != low) {
+            /* if first time, transition to sub-tables */
+            if (drop == 0)
+                drop = root;
+
+            /* increment past last table */
+            next += min;            /* here min is 1 << curr */
+
+            /* determine length of next table */
+            curr = len - drop;
+            left = (int)(1 << curr);
+            while (curr + drop < max) {
+                left -= count[curr + drop];
+                if (left <= 0) break;
+                curr++;
+                left <<= 1;
+            }
+
+            /* check for enough space */
+            used += 1U << curr;
+            if ((type == LENS && used >= ENOUGH_LENS) ||
+                (type == DISTS && used >= ENOUGH_DISTS))
+                return 1;
+
+            /* point entry in root table to sub-table */
+            low = huff & mask;
+            (*table)[low].op = (unsigned char)curr;
+            (*table)[low].bits = (unsigned char)root;
+            (*table)[low].val = (unsigned short)(next - *table);
+        }
+    }
+
+    /* fill in remaining table entry if code is incomplete (guaranteed to have
+       at most one remaining entry, since if the code is incomplete, the
+       maximum code length that was allowed to get this far is one bit) */
+    if (huff != 0) {
+        here.op = (unsigned char)64;            /* invalid code marker */
+        here.bits = (unsigned char)(len - drop);
+        here.val = (unsigned short)0;
+        next[huff] = here;
+    }
+
+    /* set return parameters */
+    *table += used;
+    *bits = root;
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inftrees.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/inftrees.h
new file mode 100644 (file)
index 0000000..baa53a0
--- /dev/null
@@ -0,0 +1,62 @@
+/* inftrees.h -- header to use inftrees.c
+ * Copyright (C) 1995-2005, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* Structure for decoding tables.  Each entry provides either the
+   information needed to do the operation requested by the code that
+   indexed that table entry, or it provides a pointer to another
+   table that indexes more bits of the code.  op indicates whether
+   the entry is a pointer to another table, a literal, a length or
+   distance, an end-of-block, or an invalid code.  For a table
+   pointer, the low four bits of op is the number of index bits of
+   that table.  For a length or distance, the low four bits of op
+   is the number of extra bits to get after the code.  bits is
+   the number of bits in this code or part of the code to drop off
+   of the bit buffer.  val is the actual byte to output in the case
+   of a literal, the base length or distance, or the offset from
+   the current table to the next table.  Each entry is four bytes. */
+typedef struct {
+    unsigned char op;           /* operation, extra bits, table bits */
+    unsigned char bits;         /* bits in this part of the code */
+    unsigned short val;         /* offset in table or code value */
+} code;
+
+/* op values as set by inflate_table():
+    00000000 - literal
+    0000tttt - table link, tttt != 0 is the number of table index bits
+    0001eeee - length or distance, eeee is the number of extra bits
+    01100000 - end of block
+    01000000 - invalid code
+ */
+
+/* Maximum size of the dynamic table.  The maximum number of code structures is
+   1444, which is the sum of 852 for literal/length codes and 592 for distance
+   codes.  These values were found by exhaustive searches using the program
+   examples/enough.c found in the zlib distribtution.  The arguments to that
+   program are the number of symbols, the initial root table size, and the
+   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
+   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
+   The initial root table size (9 or 6) is found in the fifth argument of the
+   inflate_table() calls in inflate.c and infback.c.  If the root table size is
+   changed, then these maximum sizes would be need to be recalculated and
+   updated. */
+#define ENOUGH_LENS 852
+#define ENOUGH_DISTS 592
+#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
+
+/* Type of code to build for inflate_table() */
+typedef enum {
+    CODES,
+    LENS,
+    DISTS
+} codetype;
+
+int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
+                             unsigned codes, code FAR * FAR *table,
+                             unsigned FAR *bits, unsigned short FAR *work));
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/make_vms.com b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/make_vms.com
new file mode 100644 (file)
index 0000000..11be527
--- /dev/null
@@ -0,0 +1,804 @@
+$! make libz under VMS written by
+$! Martin P.J. Zinser
+$!
+$! In case of problems with the install you might contact me at
+$! zinser@zinser.no-ip.info(preferred) or
+$! zinser@sysdev.deutsche-boerse.com (work)
+$!
+$! Make procedure history for Zlib
+$!
+$!------------------------------------------------------------------------------
+$! Version history
+$! 0.01 20060120 First version to receive a number
+$! 0.02 20061008 Adapt to new Makefile.in
+$! 0.03 20091224 Add support for large file check
+$! 0.04 20100110 Add new gzclose, gzlib, gzread, gzwrite
+$! 0.05 20100221 Exchange zlibdefs.h by zconf.h.in
+$!
+$ on error then goto err_exit
+$ set proc/parse=ext
+$!
+$ true  = 1
+$ false = 0
+$ tmpnam = "temp_" + f$getjpi("","pid")
+$ tt = tmpnam + ".txt"
+$ tc = tmpnam + ".c"
+$ th = tmpnam + ".h"
+$ define/nolog tconfig 'th'
+$ its_decc = false
+$ its_vaxc = false
+$ its_gnuc = false
+$ s_case   = False
+$!
+$! Setup variables holding "config" information
+$!
+$ Make    = ""
+$ name     = "Zlib"
+$ version  = "?.?.?"
+$ v_string = "ZLIB_VERSION"
+$ v_file   = "zlib.h"
+$ ccopt   = ""
+$ lopts   = ""
+$ dnsrl   = ""
+$ aconf_in_file = "zconf.h.in#zconf.h_in"
+$ conf_check_string = ""
+$ linkonly = false
+$ optfile  = name + ".opt"
+$ libdefs  = ""
+$ axp      = f$getsyi("HW_MODEL").ge.1024 .and. f$getsyi("HW_MODEL").lt.4096
+$!
+$ whoami = f$parse(f$enviornment("Procedure"),,,,"NO_CONCEAL")
+$ mydef  = F$parse(whoami,,,"DEVICE")
+$ mydir  = f$parse(whoami,,,"DIRECTORY") - "]["
+$ myproc = f$parse(whoami,,,"Name") + f$parse(whoami,,,"type")
+$!
+$! Check for MMK/MMS
+$!
+$ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS"
+$ If F$Type (MMK) .eqs. "STRING" Then Make = "MMK"
+$!
+$!
+$ gosub find_version
+$!
+$  open/write topt tmp.opt
+$  open/write optf 'optfile'
+$!
+$ gosub check_opts
+$!
+$! Look for the compiler used
+$!
+$ gosub check_compiler
+$ close topt
+$!
+$ if its_decc
+$ then
+$   ccopt = "/prefix=all" + ccopt
+$   if f$trnlnm("SYS") .eqs. ""
+$   then
+$     if axp
+$     then
+$       define sys sys$library:
+$     else
+$       ccopt = "/decc" + ccopt
+$       define sys decc$library_include:
+$     endif
+$   endif
+$ endif
+$ if its_vaxc .or. its_gnuc
+$ then
+$    if f$trnlnm("SYS").eqs."" then define sys sys$library:
+$ endif
+$!
+$! Build a fake configure input header
+$!
+$ open/write conf_hin config.hin
+$ write conf_hin "#undef _LARGEFILE64_SOURCE"
+$ close conf_hin
+$!
+$!
+$ i = 0
+$FIND_ACONF:
+$ fname = f$element(i,"#",aconf_in_file)
+$ if fname .eqs. "#" then goto AMISS_ERR
+$ if f$search(fname) .eqs. ""
+$ then
+$   i = i + 1
+$   goto find_aconf
+$ endif
+$ open/read/err=aconf_err aconf_in 'fname'
+$ open/write aconf zconf.h
+$ACONF_LOOP:
+$ read/end_of_file=aconf_exit aconf_in line
+$ work = f$edit(line, "compress,trim")
+$ if f$extract(0,6,work) .nes. "#undef"
+$ then
+$   if f$extract(0,12,work) .nes. "#cmakedefine"
+$   then
+$       write aconf line
+$   endif
+$ else
+$   cdef = f$element(1," ",work)
+$   gosub check_config
+$ endif
+$ goto aconf_loop
+$ACONF_EXIT:
+$ write aconf "#define VMS 1"
+$ write aconf "#include <unistd.h>"
+$ write aconf "#include <unixio.h>"
+$ write aconf "#ifdef _LARGEFILE"
+$ write aconf "#define off64_t __off64_t"
+$ write aconf "#define fopen64 fopen"
+$ write aconf "#define fseeko64 fseeko"
+$ write aconf "#define lseek64 lseek"
+$ write aconf "#define ftello64 ftell"
+$ write aconf "#endif"
+$ close aconf_in
+$ close aconf
+$ if f$search("''th'") .nes. "" then delete 'th';*
+$! Build the thing plain or with mms
+$!
+$ write sys$output "Compiling Zlib sources ..."
+$ if make.eqs.""
+$  then
+$   dele example.obj;*,minigzip.obj;*
+$   CALL MAKE adler32.OBJ "CC ''CCOPT' adler32" -
+                adler32.c zlib.h zconf.h
+$   CALL MAKE compress.OBJ "CC ''CCOPT' compress" -
+                compress.c zlib.h zconf.h
+$   CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" -
+                crc32.c zlib.h zconf.h
+$   CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" -
+                deflate.c deflate.h zutil.h zlib.h zconf.h
+$   CALL MAKE gzclose.OBJ "CC ''CCOPT' gzclose" -
+                gzclose.c zutil.h zlib.h zconf.h
+$   CALL MAKE gzlib.OBJ "CC ''CCOPT' gzlib" -
+                gzlib.c zutil.h zlib.h zconf.h
+$   CALL MAKE gzread.OBJ "CC ''CCOPT' gzread" -
+                gzread.c zutil.h zlib.h zconf.h
+$   CALL MAKE gzwrite.OBJ "CC ''CCOPT' gzwrite" -
+                gzwrite.c zutil.h zlib.h zconf.h
+$   CALL MAKE infback.OBJ "CC ''CCOPT' infback" -
+                infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h
+$   CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" -
+                inffast.c zutil.h zlib.h zconf.h inffast.h
+$   CALL MAKE inflate.OBJ "CC ''CCOPT' inflate" -
+                inflate.c zutil.h zlib.h zconf.h infblock.h
+$   CALL MAKE inftrees.OBJ "CC ''CCOPT' inftrees" -
+                inftrees.c zutil.h zlib.h zconf.h inftrees.h
+$   CALL MAKE trees.OBJ "CC ''CCOPT' trees" -
+                trees.c deflate.h zutil.h zlib.h zconf.h
+$   CALL MAKE uncompr.OBJ "CC ''CCOPT' uncompr" -
+                uncompr.c zlib.h zconf.h
+$   CALL MAKE zutil.OBJ "CC ''CCOPT' zutil" -
+                zutil.c zutil.h zlib.h zconf.h
+$   write sys$output "Building Zlib ..."
+$   CALL MAKE libz.OLB "lib/crea libz.olb *.obj" *.OBJ
+$   write sys$output "Building example..."
+$   CALL MAKE example.OBJ "CC ''CCOPT' example" -
+                test/example.c zlib.h zconf.h
+$   call make example.exe "LINK example,libz.olb/lib" example.obj libz.olb
+$   if f$search("x11vms:xvmsutils.olb") .nes. ""
+$   then
+$     write sys$output "Building minigzip..."
+$     CALL MAKE minigzip.OBJ "CC ''CCOPT' minigzip" -
+                test/minigzip.c zlib.h zconf.h
+$     call make minigzip.exe -
+                "LINK minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib" -
+                minigzip.obj libz.olb
+$   endif
+$  else
+$   gosub crea_mms
+$   write sys$output "Make ''name' ''version' with ''Make' "
+$   'make'
+$  endif
+$!
+$! Alpha gets a shareable image
+$!
+$ If axp
+$ Then
+$   gosub crea_olist
+$   write sys$output "Creating libzshr.exe"
+$   call anal_obj_axp modules.opt _link.opt
+$   if s_case
+$   then
+$      open/append optf modules.opt
+$      write optf "case_sensitive=YES"
+$      close optf
+$   endif
+$   LINK_'lopts'/SHARE=libzshr.exe modules.opt/opt,_link.opt/opt
+$ endif
+$ write sys$output "Zlib build completed"
+$ exit
+$CC_ERR:
+$ write sys$output "C compiler required to build ''name'"
+$ goto err_exit
+$ERR_EXIT:
+$ set message/facil/ident/sever/text
+$ close/nolog optf
+$ close/nolog topt
+$ close/nolog conf_hin
+$ close/nolog aconf_in
+$ close/nolog aconf
+$ close/nolog out
+$ close/nolog min
+$ close/nolog mod
+$ close/nolog h_in
+$ write sys$output "Exiting..."
+$ exit 2
+$!
+$!
+$MAKE: SUBROUTINE   !SUBROUTINE TO CHECK DEPENDENCIES
+$ V = 'F$Verify(0)
+$! P1 = What we are trying to make
+$! P2 = Command to make it
+$! P3 - P8  What it depends on
+$
+$ If F$Search(P1) .Eqs. "" Then Goto Makeit
+$ Time = F$CvTime(F$File(P1,"RDT"))
+$arg=3
+$Loop:
+$       Argument = P'arg
+$       If Argument .Eqs. "" Then Goto Exit
+$       El=0
+$Loop2:
+$       File = F$Element(El," ",Argument)
+$       If File .Eqs. " " Then Goto Endl
+$       AFile = ""
+$Loop3:
+$       OFile = AFile
+$       AFile = F$Search(File)
+$       If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
+$       If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
+$       Goto Loop3
+$NextEL:
+$       El = El + 1
+$       Goto Loop2
+$EndL:
+$ arg=arg+1
+$ If arg .Le. 8 Then Goto Loop
+$ Goto Exit
+$
+$Makeit:
+$ VV=F$VERIFY(0)
+$ write sys$output P2
+$ 'P2
+$ VV='F$Verify(VV)
+$Exit:
+$ If V Then Set Verify
+$ENDSUBROUTINE
+$!------------------------------------------------------------------------------
+$!
+$! Check command line options and set symbols accordingly
+$!
+$!------------------------------------------------------------------------------
+$! Version history
+$! 0.01 20041206 First version to receive a number
+$! 0.02 20060126 Add new "HELP" target
+$ CHECK_OPTS:
+$ i = 1
+$ OPT_LOOP:
+$ if i .lt. 9
+$ then
+$   cparm = f$edit(p'i',"upcase")
+$!
+$! Check if parameter actually contains something
+$!
+$   if f$edit(cparm,"trim") .nes. ""
+$   then
+$     if cparm .eqs. "DEBUG"
+$     then
+$       ccopt = ccopt + "/noopt/deb"
+$       lopts = lopts + "/deb"
+$     endif
+$     if f$locate("CCOPT=",cparm) .lt. f$length(cparm)
+$     then
+$       start = f$locate("=",cparm) + 1
+$       len   = f$length(cparm) - start
+$       ccopt = ccopt + f$extract(start,len,cparm)
+$       if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) -
+          then s_case = true
+$     endif
+$     if cparm .eqs. "LINK" then linkonly = true
+$     if f$locate("LOPTS=",cparm) .lt. f$length(cparm)
+$     then
+$       start = f$locate("=",cparm) + 1
+$       len   = f$length(cparm) - start
+$       lopts = lopts + f$extract(start,len,cparm)
+$     endif
+$     if f$locate("CC=",cparm) .lt. f$length(cparm)
+$     then
+$       start  = f$locate("=",cparm) + 1
+$       len    = f$length(cparm) - start
+$       cc_com = f$extract(start,len,cparm)
+        if (cc_com .nes. "DECC") .and. -
+           (cc_com .nes. "VAXC") .and. -
+           (cc_com .nes. "GNUC")
+$       then
+$         write sys$output "Unsupported compiler choice ''cc_com' ignored"
+$         write sys$output "Use DECC, VAXC, or GNUC instead"
+$       else
+$         if cc_com .eqs. "DECC" then its_decc = true
+$         if cc_com .eqs. "VAXC" then its_vaxc = true
+$         if cc_com .eqs. "GNUC" then its_gnuc = true
+$       endif
+$     endif
+$     if f$locate("MAKE=",cparm) .lt. f$length(cparm)
+$     then
+$       start  = f$locate("=",cparm) + 1
+$       len    = f$length(cparm) - start
+$       mmks = f$extract(start,len,cparm)
+$       if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS")
+$       then
+$         make = mmks
+$       else
+$         write sys$output "Unsupported make choice ''mmks' ignored"
+$         write sys$output "Use MMK or MMS instead"
+$       endif
+$     endif
+$     if cparm .eqs. "HELP" then gosub bhelp
+$   endif
+$   i = i + 1
+$   goto opt_loop
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Look for the compiler used
+$!
+$! Version history
+$! 0.01 20040223 First version to receive a number
+$! 0.02 20040229 Save/set value of decc$no_rooted_search_lists
+$! 0.03 20060202 Extend handling of GNU C
+$! 0.04 20090402 Compaq -> hp
+$CHECK_COMPILER:
+$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
+$ then
+$   its_decc = (f$search("SYS$SYSTEM:DECC$COMPILER.EXE") .nes. "")
+$   its_vaxc = .not. its_decc .and. (F$Search("SYS$System:VAXC.Exe") .nes. "")
+$   its_gnuc = .not. (its_decc .or. its_vaxc) .and. (f$trnlnm("gnu_cc") .nes. "")
+$ endif
+$!
+$! Exit if no compiler available
+$!
+$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
+$ then goto CC_ERR
+$ else
+$   if its_decc
+$   then
+$     write sys$output "CC compiler check ... hp C"
+$     if f$trnlnm("decc$no_rooted_search_lists") .nes. ""
+$     then
+$       dnrsl = f$trnlnm("decc$no_rooted_search_lists")
+$     endif
+$     define/nolog decc$no_rooted_search_lists 1
+$   else
+$     if its_vaxc then write sys$output "CC compiler check ... VAX C"
+$     if its_gnuc
+$     then
+$         write sys$output "CC compiler check ... GNU C"
+$         if f$trnlnm(topt) then write topt "gnu_cc:[000000]gcclib.olb/lib"
+$         if f$trnlnm(optf) then write optf "gnu_cc:[000000]gcclib.olb/lib"
+$         cc = "gcc"
+$     endif
+$     if f$trnlnm(topt) then write topt "sys$share:vaxcrtl.exe/share"
+$     if f$trnlnm(optf) then write optf "sys$share:vaxcrtl.exe/share"
+$   endif
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! If MMS/MMK are available dump out the descrip.mms if required
+$!
+$CREA_MMS:
+$ write sys$output "Creating descrip.mms..."
+$ create descrip.mms
+$ open/append out descrip.mms
+$ copy sys$input: out
+$ deck
+# descrip.mms: MMS description file for building zlib on VMS
+# written by Martin P.J. Zinser
+# <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com>
+
+OBJS = adler32.obj, compress.obj, crc32.obj, gzclose.obj, gzlib.obj\
+       gzread.obj, gzwrite.obj, uncompr.obj, infback.obj\
+       deflate.obj, trees.obj, zutil.obj, inflate.obj, \
+       inftrees.obj, inffast.obj
+
+$ eod
+$ write out "CFLAGS=", ccopt
+$ write out "LOPTS=", lopts
+$ copy sys$input: out
+$ deck
+
+all : example.exe minigzip.exe libz.olb
+        @ write sys$output " Example applications available"
+
+libz.olb : libz.olb($(OBJS))
+       @ write sys$output " libz available"
+
+example.exe : example.obj libz.olb
+              link $(LOPTS) example,libz.olb/lib
+
+minigzip.exe : minigzip.obj libz.olb
+              link $(LOPTS) minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib
+
+clean :
+       delete *.obj;*,libz.olb;*,*.opt;*,*.exe;*
+
+
+# Other dependencies.
+adler32.obj  : adler32.c zutil.h zlib.h zconf.h
+compress.obj : compress.c zlib.h zconf.h
+crc32.obj    : crc32.c zutil.h zlib.h zconf.h
+deflate.obj  : deflate.c deflate.h zutil.h zlib.h zconf.h
+example.obj  : test/example.c zlib.h zconf.h
+gzclose.obj  : gzclose.c zutil.h zlib.h zconf.h
+gzlib.obj    : gzlib.c zutil.h zlib.h zconf.h
+gzread.obj   : gzread.c zutil.h zlib.h zconf.h
+gzwrite.obj  : gzwrite.c zutil.h zlib.h zconf.h
+inffast.obj  : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h
+inflate.obj  : inflate.c zutil.h zlib.h zconf.h
+inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h
+minigzip.obj : test/minigzip.c zlib.h zconf.h
+trees.obj    : trees.c deflate.h zutil.h zlib.h zconf.h
+uncompr.obj  : uncompr.c zlib.h zconf.h
+zutil.obj    : zutil.c zutil.h zlib.h zconf.h
+infback.obj  : infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h
+$ eod
+$ close out
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Read list of core library sources from makefile.in and create options
+$! needed to build shareable image
+$!
+$CREA_OLIST:
+$ open/read min makefile.in
+$ open/write mod modules.opt
+$ src_check = "OBJC ="
+$MRLOOP:
+$ read/end=mrdone min rec
+$ if (f$extract(0,6,rec) .nes. src_check) then goto mrloop
+$ rec = rec - src_check
+$ gosub extra_filnam
+$ if (f$element(1,"\",rec) .eqs. "\") then goto mrdone
+$MRSLOOP:
+$ read/end=mrdone min rec
+$ gosub extra_filnam
+$ if (f$element(1,"\",rec) .nes. "\") then goto mrsloop
+$MRDONE:
+$ close min
+$ close mod
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Take record extracted in crea_olist and split it into single filenames
+$!
+$EXTRA_FILNAM:
+$ myrec = f$edit(rec - "\", "trim,compress")
+$ i = 0
+$FELOOP:
+$ srcfil = f$element(i," ", myrec)
+$ if (srcfil .nes. " ")
+$ then
+$   write mod f$parse(srcfil,,,"NAME"), ".obj"
+$   i = i + 1
+$   goto feloop
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Find current Zlib version number
+$!
+$FIND_VERSION:
+$ open/read h_in 'v_file'
+$hloop:
+$ read/end=hdone h_in rec
+$ rec = f$edit(rec,"TRIM")
+$ if (f$extract(0,1,rec) .nes. "#") then goto hloop
+$ rec = f$edit(rec - "#", "TRIM")
+$ if f$element(0," ",rec) .nes. "define" then goto hloop
+$ if f$element(1," ",rec) .eqs. v_string
+$ then
+$   version = 'f$element(2," ",rec)'
+$   goto hdone
+$ endif
+$ goto hloop
+$hdone:
+$ close h_in
+$ return
+$!------------------------------------------------------------------------------
+$!
+$CHECK_CONFIG:
+$!
+$ in_ldef = f$locate(cdef,libdefs)
+$ if (in_ldef .lt. f$length(libdefs))
+$ then
+$   write aconf "#define ''cdef' 1"
+$   libdefs = f$extract(0,in_ldef,libdefs) + -
+              f$extract(in_ldef + f$length(cdef) + 1, -
+                        f$length(libdefs) - in_ldef - f$length(cdef) - 1, -
+                        libdefs)
+$ else
+$   if (f$type('cdef') .eqs. "INTEGER")
+$   then
+$     write aconf "#define ''cdef' ", 'cdef'
+$   else
+$     if (f$type('cdef') .eqs. "STRING")
+$     then
+$       write aconf "#define ''cdef' ", """", '''cdef'', """"
+$     else
+$       gosub check_cc_def
+$     endif
+$   endif
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Check if this is a define relating to the properties of the C/C++
+$! compiler
+$!
+$ CHECK_CC_DEF:
+$ if (cdef .eqs. "_LARGEFILE64_SOURCE")
+$ then
+$   copy sys$input: 'tc'
+$   deck
+#include "tconfig"
+#define _LARGEFILE
+#include <stdio.h>
+
+int main(){
+FILE *fp;
+  fp = fopen("temp.txt","r");
+  fseeko(fp,1,SEEK_SET);
+  fclose(fp);
+}
+
+$   eod
+$   test_inv = false
+$   comm_h = false
+$   gosub cc_prop_check
+$   return
+$ endif
+$ write aconf "/* ", line, " */"
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Check for properties of C/C++ compiler
+$!
+$! Version history
+$! 0.01 20031020 First version to receive a number
+$! 0.02 20031022 Added logic for defines with value
+$! 0.03 20040309 Make sure local config file gets not deleted
+$! 0.04 20041230 Also write include for configure run
+$! 0.05 20050103 Add processing of "comment defines"
+$CC_PROP_CHECK:
+$ cc_prop = true
+$ is_need = false
+$ is_need = (f$extract(0,4,cdef) .eqs. "NEED") .or. (test_inv .eq. true)
+$ if f$search(th) .eqs. "" then create 'th'
+$ set message/nofac/noident/nosever/notext
+$ on error then continue
+$ cc 'tmpnam'
+$ if .not. ($status)  then cc_prop = false
+$ on error then continue
+$! The headers might lie about the capabilities of the RTL
+$ link 'tmpnam',tmp.opt/opt
+$ if .not. ($status)  then cc_prop = false
+$ set message/fac/ident/sever/text
+$ on error then goto err_exit
+$ delete/nolog 'tmpnam'.*;*/exclude='th'
+$ if (cc_prop .and. .not. is_need) .or. -
+     (.not. cc_prop .and. is_need)
+$ then
+$   write sys$output "Checking for ''cdef'... yes"
+$   if f$type('cdef_val'_yes) .nes. ""
+$   then
+$     if f$type('cdef_val'_yes) .eqs. "INTEGER" -
+         then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_yes)
+$     if f$type('cdef_val'_yes) .eqs. "STRING" -
+         then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_yes)
+$   else
+$     call write_config f$fao("#define !AS 1",cdef)
+$   endif
+$   if (cdef .eqs. "HAVE_FSEEKO") .or. (cdef .eqs. "_LARGE_FILES") .or. -
+       (cdef .eqs. "_LARGEFILE64_SOURCE") then -
+      call write_config f$string("#define _LARGEFILE 1")
+$ else
+$   write sys$output "Checking for ''cdef'... no"
+$   if (comm_h)
+$   then
+      call write_config f$fao("/* !AS */",line)
+$   else
+$     if f$type('cdef_val'_no) .nes. ""
+$     then
+$       if f$type('cdef_val'_no) .eqs. "INTEGER" -
+           then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_no)
+$       if f$type('cdef_val'_no) .eqs. "STRING" -
+           then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_no)
+$     else
+$       call write_config f$fao("#undef !AS",cdef)
+$     endif
+$   endif
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Check for properties of C/C++ compiler with multiple result values
+$!
+$! Version history
+$! 0.01 20040127 First version
+$! 0.02 20050103 Reconcile changes from cc_prop up to version 0.05
+$CC_MPROP_CHECK:
+$ cc_prop = true
+$ i    = 1
+$ idel = 1
+$ MT_LOOP:
+$ if f$type(result_'i') .eqs. "STRING"
+$ then
+$   set message/nofac/noident/nosever/notext
+$   on error then continue
+$   cc 'tmpnam'_'i'
+$   if .not. ($status)  then cc_prop = false
+$   on error then continue
+$! The headers might lie about the capabilities of the RTL
+$   link 'tmpnam'_'i',tmp.opt/opt
+$   if .not. ($status)  then cc_prop = false
+$   set message/fac/ident/sever/text
+$   on error then goto err_exit
+$   delete/nolog 'tmpnam'_'i'.*;*
+$   if (cc_prop)
+$   then
+$     write sys$output "Checking for ''cdef'... ", mdef_'i'
+$     if f$type(mdef_'i') .eqs. "INTEGER" -
+         then call write_config f$fao("#define !AS !UL",cdef,mdef_'i')
+$     if f$type('cdef_val'_yes) .eqs. "STRING" -
+         then call write_config f$fao("#define !AS !AS",cdef,mdef_'i')
+$     goto msym_clean
+$   else
+$     i = i + 1
+$     goto mt_loop
+$   endif
+$ endif
+$ write sys$output "Checking for ''cdef'... no"
+$ call write_config f$fao("#undef !AS",cdef)
+$ MSYM_CLEAN:
+$ if (idel .le. msym_max)
+$ then
+$   delete/sym mdef_'idel'
+$   idel = idel + 1
+$   goto msym_clean
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Analyze Object files for OpenVMS AXP to extract Procedure and Data
+$! information to build a symbol vector for a shareable image
+$! All the "brains" of this logic was suggested by Hartmut Becker
+$! (Hartmut.Becker@compaq.com). All the bugs were introduced by me
+$! (zinser@zinser.no-ip.info), so if you do have problem reports please do not
+$! bother Hartmut/HP, but get in touch with me
+$!
+$! Version history
+$! 0.01 20040406 Skip over shareable images in option file
+$! 0.02 20041109 Fix option file for shareable images with case_sensitive=YES
+$! 0.03 20050107 Skip over Identification labels in option file
+$! 0.04 20060117 Add uppercase alias to code compiled with /name=as_is
+$!
+$ ANAL_OBJ_AXP: Subroutine
+$ V = 'F$Verify(0)
+$ SAY := "WRITE_ SYS$OUTPUT"
+$
+$ IF F$SEARCH("''P1'") .EQS. ""
+$ THEN
+$    SAY "ANAL_OBJ_AXP-E-NOSUCHFILE:  Error, inputfile ''p1' not available"
+$    goto exit_aa
+$ ENDIF
+$ IF "''P2'" .EQS. ""
+$ THEN
+$    SAY "ANAL_OBJ_AXP:  Error, no output file provided"
+$    goto exit_aa
+$ ENDIF
+$
+$ open/read in 'p1
+$ create a.tmp
+$ open/append atmp a.tmp
+$ loop:
+$ read/end=end_loop in line
+$ if f$locate("/SHARE",f$edit(line,"upcase")) .lt. f$length(line)
+$ then
+$   write sys$output "ANAL_SKP_SHR-i-skipshare, ''line'"
+$   goto loop
+$ endif
+$ if f$locate("IDENTIFICATION=",f$edit(line,"upcase")) .lt. f$length(line)
+$ then
+$   write sys$output "ANAL_OBJ_AXP-i-ident: Identification ", -
+                     f$element(1,"=",line)
+$   goto loop
+$ endif
+$ f= f$search(line)
+$ if f .eqs. ""
+$ then
+$      write sys$output "ANAL_OBJ_AXP-w-nosuchfile, ''line'"
+$      goto loop
+$ endif
+$ define/user sys$output nl:
+$ define/user sys$error nl:
+$ anal/obj/gsd 'f /out=x.tmp
+$ open/read xtmp x.tmp
+$ XLOOP:
+$ read/end=end_xloop xtmp xline
+$ xline = f$edit(xline,"compress")
+$ write atmp xline
+$ goto xloop
+$ END_XLOOP:
+$ close xtmp
+$ goto loop
+$ end_loop:
+$ close in
+$ close atmp
+$ if f$search("a.tmp") .eqs. "" -
+       then $ exit
+$ ! all global definitions
+$ search a.tmp "symbol:","EGSY$V_DEF 1","EGSY$V_NORM 1"/out=b.tmp
+$ ! all procedures
+$ search b.tmp "EGSY$V_NORM 1"/wind=(0,1) /out=c.tmp
+$ search c.tmp "symbol:"/out=d.tmp
+$ define/user sys$output nl:
+$ edito/edt/command=sys$input d.tmp
+sub/symbol: "/symbol_vector=(/whole
+sub/"/=PROCEDURE)/whole
+exit
+$ ! all data
+$ search b.tmp "EGSY$V_DEF 1"/wind=(0,1) /out=e.tmp
+$ search e.tmp "symbol:"/out=f.tmp
+$ define/user sys$output nl:
+$ edito/edt/command=sys$input f.tmp
+sub/symbol: "/symbol_vector=(/whole
+sub/"/=DATA)/whole
+exit
+$ sort/nodupl d.tmp,f.tmp g.tmp
+$ open/read raw_vector g.tmp
+$ open/write case_vector 'p2'
+$ RAWLOOP:
+$ read/end=end_rawloop raw_vector raw_element
+$ write case_vector raw_element
+$ if f$locate("=PROCEDURE)",raw_element) .lt. f$length(raw_element)
+$ then
+$     name = f$element(1,"=",raw_element) - "("
+$     if f$edit(name,"UPCASE") .nes. name then -
+          write case_vector f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)", -
+                                 f$edit(name,"UPCASE"), name)
+$ endif
+$ if f$locate("=DATA)",raw_element) .lt. f$length(raw_element)
+$ then
+$     name = f$element(1,"=",raw_element) - "("
+$     if f$edit(name,"UPCASE") .nes. name then -
+          write case_vector f$fao(" symbol_vector=(!AS/!AS=DATA)", -
+                                 f$edit(name,"UPCASE"), name)
+$ endif
+$ goto rawloop
+$ END_RAWLOOP:
+$ close raw_vector
+$ close case_vector
+$ delete a.tmp;*,b.tmp;*,c.tmp;*,d.tmp;*,e.tmp;*,f.tmp;*,g.tmp;*
+$ if f$search("x.tmp") .nes. "" -
+       then $ delete x.tmp;*
+$!
+$ EXIT_AA:
+$ if V then set verify
+$ endsubroutine
+$!------------------------------------------------------------------------------
+$!
+$! Write configuration to both permanent and temporary config file
+$!
+$! Version history
+$! 0.01 20031029 First version to receive a number
+$!
+$WRITE_CONFIG: SUBROUTINE
+$  write aconf 'p1'
+$  open/append confh 'th'
+$  write confh 'p1'
+$  close confh
+$ENDSUBROUTINE
+$!------------------------------------------------------------------------------
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.bor b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.bor
new file mode 100644 (file)
index 0000000..3d12a2c
--- /dev/null
@@ -0,0 +1,115 @@
+# Makefile for zlib
+# Borland C++
+# Last updated: 15-Mar-2003
+
+# To use, do "make -fmakefile.bor"
+# To compile in small model, set below: MODEL=s
+
+# WARNING: the small model is supported but only for small values of
+# MAX_WBITS and MAX_MEM_LEVEL. For example:
+#    -DMAX_WBITS=11 -DDEF_WBITS=11 -DMAX_MEM_LEVEL=3
+# If you wish to reduce the memory requirements (default 256K for big
+# objects plus a few K), you can add to the LOC macro below:
+#   -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14
+# See zconf.h for details about the memory requirements.
+
+# ------------ Turbo C++, Borland C++ ------------
+
+#    Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7)
+#    should be added to the environment via "set LOCAL_ZLIB=-DFOO" or added
+#    to the declaration of LOC here:
+LOC = $(LOCAL_ZLIB)
+
+# type for CPU required: 0: 8086, 1: 80186, 2: 80286, 3: 80386, etc.
+CPU_TYP = 0
+
+# memory model: one of s, m, c, l (small, medium, compact, large)
+MODEL=l
+
+# replace bcc with tcc for Turbo C++ 1.0, with bcc32 for the 32 bit version
+CC=bcc
+LD=bcc
+AR=tlib
+
+# compiler flags
+# replace "-O2" by "-O -G -a -d" for Turbo C++ 1.0
+CFLAGS=-O2 -Z -m$(MODEL) $(LOC)
+
+LDFLAGS=-m$(MODEL) -f-
+
+
+# variables
+ZLIB_LIB = zlib_$(MODEL).lib
+
+OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj
+OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
+OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj
+OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
+
+
+# targets
+all: $(ZLIB_LIB) example.exe minigzip.exe
+
+.c.obj:
+       $(CC) -c $(CFLAGS) $*.c
+
+adler32.obj: adler32.c zlib.h zconf.h
+
+compress.obj: compress.c zlib.h zconf.h
+
+crc32.obj: crc32.c zlib.h zconf.h crc32.h
+
+deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
+
+gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
+
+gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
+
+gzread.obj: gzread.c zlib.h zconf.h gzguts.h
+
+gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
+
+infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h
+
+inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h
+
+trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h
+
+uncompr.obj: uncompr.c zlib.h zconf.h
+
+zutil.obj: zutil.c zutil.h zlib.h zconf.h
+
+example.obj: test/example.c zlib.h zconf.h
+
+minigzip.obj: test/minigzip.c zlib.h zconf.h
+
+
+# the command line is cut to fit in the MS-DOS 128 byte limit:
+$(ZLIB_LIB): $(OBJ1) $(OBJ2)
+       -del $(ZLIB_LIB)
+       $(AR) $(ZLIB_LIB) $(OBJP1)
+       $(AR) $(ZLIB_LIB) $(OBJP2)
+
+example.exe: example.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB)
+
+minigzip.exe: minigzip.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB)
+
+test: example.exe minigzip.exe
+       example
+       echo hello world | minigzip | minigzip -d
+
+clean:
+       -del *.obj
+       -del *.lib
+       -del *.exe
+       -del zlib_*.bak
+       -del foo.gz
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.dj2 b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.dj2
new file mode 100644 (file)
index 0000000..29b0395
--- /dev/null
@@ -0,0 +1,104 @@
+# Makefile for zlib.  Modified for djgpp v2.0 by F. J. Donahoe, 3/15/96.
+# Copyright (C) 1995-1998 Jean-loup Gailly.
+# For conditions of distribution and use, see copyright notice in zlib.h
+
+# To compile, or to compile and test, type:
+#
+#   make -fmakefile.dj2;  make test -fmakefile.dj2
+#
+# To install libz.a, zconf.h and zlib.h in the djgpp directories, type:
+#
+#    make install -fmakefile.dj2
+#
+# after first defining LIBRARY_PATH and INCLUDE_PATH in djgpp.env as
+# in the sample below if the pattern of the DJGPP distribution is to
+# be followed.  Remember that, while <sp>'es around <=> are ignored in
+# makefiles, they are *not* in batch files or in djgpp.env.
+# - - - - -
+# [make]
+# INCLUDE_PATH=%\>;INCLUDE_PATH%%\DJDIR%\include
+# LIBRARY_PATH=%\>;LIBRARY_PATH%%\DJDIR%\lib
+# BUTT=-m486
+# - - - - -
+# Alternately, these variables may be defined below, overriding the values
+# in djgpp.env, as
+# INCLUDE_PATH=c:\usr\include
+# LIBRARY_PATH=c:\usr\lib
+
+CC=gcc
+
+#CFLAGS=-MMD -O
+#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
+#CFLAGS=-MMD -g -DDEBUG
+CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
+             -Wstrict-prototypes -Wmissing-prototypes
+
+# If cp.exe is available, replace "copy /Y" with "cp -fp" .
+CP=copy /Y
+# If gnu install.exe is available, replace $(CP) with ginstall.
+INSTALL=$(CP)
+# The default value of RM is "rm -f."  If "rm.exe" is found, comment out:
+RM=del
+LDLIBS=-L. -lz
+LD=$(CC) -s -o
+LDSHARED=$(CC)
+
+INCL=zlib.h zconf.h
+LIBS=libz.a
+
+AR=ar rcs
+
+prefix=/usr/local
+exec_prefix = $(prefix)
+
+OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \
+       uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o
+
+OBJA =
+# to use the asm code: make OBJA=match.o
+
+TEST_OBJS = example.o minigzip.o
+
+all: example.exe minigzip.exe
+
+check: test
+test: all
+       ./example
+       echo hello world | .\minigzip | .\minigzip -d
+
+%.o : %.c
+       $(CC) $(CFLAGS) -c $< -o $@
+
+libz.a: $(OBJS) $(OBJA)
+       $(AR) $@ $(OBJS) $(OBJA)
+
+%.exe : %.o $(LIBS)
+       $(LD) $@ $< $(LDLIBS)
+
+# INCLUDE_PATH and LIBRARY_PATH were set for [make] in djgpp.env .
+
+.PHONY : uninstall clean
+
+install: $(INCL) $(LIBS)
+       -@if not exist $(INCLUDE_PATH)\nul mkdir $(INCLUDE_PATH)
+       -@if not exist $(LIBRARY_PATH)\nul mkdir $(LIBRARY_PATH)
+       $(INSTALL) zlib.h $(INCLUDE_PATH)
+       $(INSTALL) zconf.h $(INCLUDE_PATH)
+       $(INSTALL) libz.a $(LIBRARY_PATH)
+
+uninstall:
+       $(RM) $(INCLUDE_PATH)\zlib.h
+       $(RM) $(INCLUDE_PATH)\zconf.h
+       $(RM) $(LIBRARY_PATH)\libz.a
+
+clean:
+       $(RM) *.d
+       $(RM) *.o
+       $(RM) *.exe
+       $(RM) libz.a
+       $(RM) foo.gz
+
+DEPS := $(wildcard *.d)
+ifneq ($(DEPS),)
+include $(DEPS)
+endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.emx b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.emx
new file mode 100644 (file)
index 0000000..9c1b57a
--- /dev/null
@@ -0,0 +1,69 @@
+# Makefile for zlib.  Modified for emx 0.9c by Chr. Spieler, 6/17/98.
+# Copyright (C) 1995-1998 Jean-loup Gailly.
+# For conditions of distribution and use, see copyright notice in zlib.h
+
+# To compile, or to compile and test, type:
+#
+#   make -fmakefile.emx;  make test -fmakefile.emx
+#
+
+CC=gcc
+
+#CFLAGS=-MMD -O
+#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
+#CFLAGS=-MMD -g -DDEBUG
+CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
+             -Wstrict-prototypes -Wmissing-prototypes
+
+# If cp.exe is available, replace "copy /Y" with "cp -fp" .
+CP=copy /Y
+# If gnu install.exe is available, replace $(CP) with ginstall.
+INSTALL=$(CP)
+# The default value of RM is "rm -f."  If "rm.exe" is found, comment out:
+RM=del
+LDLIBS=-L. -lzlib
+LD=$(CC) -s -o
+LDSHARED=$(CC)
+
+INCL=zlib.h zconf.h
+LIBS=zlib.a
+
+AR=ar rcs
+
+prefix=/usr/local
+exec_prefix = $(prefix)
+
+OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \
+       uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o
+
+TEST_OBJS = example.o minigzip.o
+
+all: example.exe minigzip.exe
+
+test: all
+       ./example
+       echo hello world | .\minigzip | .\minigzip -d
+
+%.o : %.c
+       $(CC) $(CFLAGS) -c $< -o $@
+
+zlib.a: $(OBJS)
+       $(AR) $@ $(OBJS)
+
+%.exe : %.o $(LIBS)
+       $(LD) $@ $< $(LDLIBS)
+
+
+.PHONY : clean
+
+clean:
+       $(RM) *.d
+       $(RM) *.o
+       $(RM) *.exe
+       $(RM) zlib.a
+       $(RM) foo.gz
+
+DEPS := $(wildcard *.d)
+ifneq ($(DEPS),)
+include $(DEPS)
+endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.msc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.msc
new file mode 100644 (file)
index 0000000..ae83786
--- /dev/null
@@ -0,0 +1,112 @@
+# Makefile for zlib
+# Microsoft C 5.1 or later
+# Last updated: 19-Mar-2003
+
+# To use, do "make makefile.msc"
+# To compile in small model, set below: MODEL=S
+
+# If you wish to reduce the memory requirements (default 256K for big
+# objects plus a few K), you can add to the LOC macro below:
+#   -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14
+# See zconf.h for details about the memory requirements.
+
+# ------------- Microsoft C 5.1 and later -------------
+
+#    Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7)
+#    should be added to the environment via "set LOCAL_ZLIB=-DFOO" or added
+#    to the declaration of LOC here:
+LOC = $(LOCAL_ZLIB)
+
+# Type for CPU required: 0: 8086, 1: 80186, 2: 80286, 3: 80386, etc.
+CPU_TYP = 0
+
+# Memory model: one of S, M, C, L (small, medium, compact, large)
+MODEL=L
+
+CC=cl
+CFLAGS=-nologo -A$(MODEL) -G$(CPU_TYP) -W3 -Oait -Gs $(LOC)
+#-Ox generates bad code with MSC 5.1
+LIB_CFLAGS=-Zl $(CFLAGS)
+
+LD=link
+LDFLAGS=/noi/e/st:0x1500/noe/farcall/packcode
+# "/farcall/packcode" are only useful for `large code' memory models
+# but should be a "no-op" for small code models.
+
+
+# variables
+ZLIB_LIB = zlib_$(MODEL).lib
+
+OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj
+OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
+
+
+# targets
+all:  $(ZLIB_LIB) example.exe minigzip.exe
+
+.c.obj:
+       $(CC) -c $(LIB_CFLAGS) $*.c
+
+adler32.obj: adler32.c zlib.h zconf.h
+
+compress.obj: compress.c zlib.h zconf.h
+
+crc32.obj: crc32.c zlib.h zconf.h crc32.h
+
+deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
+
+gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
+
+gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
+
+gzread.obj: gzread.c zlib.h zconf.h gzguts.h
+
+gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
+
+infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h
+
+inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h
+
+trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h
+
+uncompr.obj: uncompr.c zlib.h zconf.h
+
+zutil.obj: zutil.c zutil.h zlib.h zconf.h
+
+example.obj: test/example.c zlib.h zconf.h
+       $(CC) -c $(CFLAGS) $*.c
+
+minigzip.obj: test/minigzip.c zlib.h zconf.h
+       $(CC) -c $(CFLAGS) $*.c
+
+
+# the command line is cut to fit in the MS-DOS 128 byte limit:
+$(ZLIB_LIB): $(OBJ1) $(OBJ2)
+       if exist $(ZLIB_LIB) del $(ZLIB_LIB)
+       lib $(ZLIB_LIB) $(OBJ1);
+       lib $(ZLIB_LIB) $(OBJ2);
+
+example.exe: example.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) example.obj,,,$(ZLIB_LIB);
+
+minigzip.exe: minigzip.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) minigzip.obj,,,$(ZLIB_LIB);
+
+test: example.exe minigzip.exe
+       example
+       echo hello world | minigzip | minigzip -d
+
+clean:
+       -del *.obj
+       -del *.lib
+       -del *.exe
+       -del *.map
+       -del zlib_*.bak
+       -del foo.gz
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.tc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/msdos/Makefile.tc
new file mode 100644 (file)
index 0000000..5aec82a
--- /dev/null
@@ -0,0 +1,100 @@
+# Makefile for zlib
+# Turbo C 2.01, Turbo C++ 1.01
+# Last updated: 15-Mar-2003
+
+# To use, do "make -fmakefile.tc"
+# To compile in small model, set below: MODEL=s
+
+# WARNING: the small model is supported but only for small values of
+# MAX_WBITS and MAX_MEM_LEVEL. For example:
+#    -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3
+# If you wish to reduce the memory requirements (default 256K for big
+# objects plus a few K), you can add to CFLAGS below:
+#   -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14
+# See zconf.h for details about the memory requirements.
+
+# ------------ Turbo C 2.01, Turbo C++ 1.01 ------------
+MODEL=l
+CC=tcc
+LD=tcc
+AR=tlib
+# CFLAGS=-O2 -G -Z -m$(MODEL) -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3
+CFLAGS=-O2 -G -Z -m$(MODEL)
+LDFLAGS=-m$(MODEL) -f-
+
+
+# variables
+ZLIB_LIB = zlib_$(MODEL).lib
+
+OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj
+OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
+OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj
+OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
+
+
+# targets
+all: $(ZLIB_LIB) example.exe minigzip.exe
+
+.c.obj:
+       $(CC) -c $(CFLAGS) $*.c
+
+adler32.obj: adler32.c zlib.h zconf.h
+
+compress.obj: compress.c zlib.h zconf.h
+
+crc32.obj: crc32.c zlib.h zconf.h crc32.h
+
+deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
+
+gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
+
+gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
+
+gzread.obj: gzread.c zlib.h zconf.h gzguts.h
+
+gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
+
+infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h
+
+inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h
+
+trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h
+
+uncompr.obj: uncompr.c zlib.h zconf.h
+
+zutil.obj: zutil.c zutil.h zlib.h zconf.h
+
+example.obj: test/example.c zlib.h zconf.h
+
+minigzip.obj: test/minigzip.c zlib.h zconf.h
+
+
+# the command line is cut to fit in the MS-DOS 128 byte limit:
+$(ZLIB_LIB): $(OBJ1) $(OBJ2)
+       -del $(ZLIB_LIB)
+       $(AR) $(ZLIB_LIB) $(OBJP1)
+       $(AR) $(ZLIB_LIB) $(OBJP2)
+
+example.exe: example.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB)
+
+minigzip.exe: minigzip.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB)
+
+test: example.exe minigzip.exe
+       example
+       echo hello world | minigzip | minigzip -d
+
+clean:
+       -del *.obj
+       -del *.lib
+       -del *.exe
+       -del zlib_*.bak
+       -del foo.gz
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/nintendods/Makefile b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/nintendods/Makefile
new file mode 100644 (file)
index 0000000..21337d0
--- /dev/null
@@ -0,0 +1,126 @@
+#---------------------------------------------------------------------------------
+.SUFFIXES:
+#---------------------------------------------------------------------------------
+
+ifeq ($(strip $(DEVKITARM)),)
+$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
+endif
+
+include $(DEVKITARM)/ds_rules
+
+#---------------------------------------------------------------------------------
+# TARGET is the name of the output
+# BUILD is the directory where object files & intermediate files will be placed
+# SOURCES is a list of directories containing source code
+# DATA is a list of directories containing data files
+# INCLUDES is a list of directories containing header files
+#---------------------------------------------------------------------------------
+TARGET         :=      $(shell basename $(CURDIR))
+BUILD          :=      build
+SOURCES                :=      ../../
+DATA           :=      data
+INCLUDES       :=      include
+
+#---------------------------------------------------------------------------------
+# options for code generation
+#---------------------------------------------------------------------------------
+ARCH   :=      -mthumb -mthumb-interwork
+
+CFLAGS :=      -Wall -O2\
+               -march=armv5te -mtune=arm946e-s \
+               -fomit-frame-pointer -ffast-math \
+               $(ARCH)
+
+CFLAGS +=      $(INCLUDE) -DARM9
+CXXFLAGS       := $(CFLAGS) -fno-rtti -fno-exceptions
+
+ASFLAGS        :=      $(ARCH) -march=armv5te -mtune=arm946e-s
+LDFLAGS        =       -specs=ds_arm9.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
+
+#---------------------------------------------------------------------------------
+# list of directories containing libraries, this must be the top level containing
+# include and lib
+#---------------------------------------------------------------------------------
+LIBDIRS        :=      $(LIBNDS)
+
+#---------------------------------------------------------------------------------
+# no real need to edit anything past this point unless you need to add additional
+# rules for different file extensions
+#---------------------------------------------------------------------------------
+ifneq ($(BUILD),$(notdir $(CURDIR)))
+#---------------------------------------------------------------------------------
+
+export OUTPUT  :=      $(CURDIR)/lib/libz.a
+
+export VPATH   :=      $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
+                       $(foreach dir,$(DATA),$(CURDIR)/$(dir))
+
+export DEPSDIR :=      $(CURDIR)/$(BUILD)
+
+CFILES         :=      $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
+CPPFILES       :=      $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
+SFILES         :=      $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
+BINFILES       :=      $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
+
+#---------------------------------------------------------------------------------
+# use CXX for linking C++ projects, CC for standard C
+#---------------------------------------------------------------------------------
+ifeq ($(strip $(CPPFILES)),)
+#---------------------------------------------------------------------------------
+       export LD       :=      $(CC)
+#---------------------------------------------------------------------------------
+else
+#---------------------------------------------------------------------------------
+       export LD       :=      $(CXX)
+#---------------------------------------------------------------------------------
+endif
+#---------------------------------------------------------------------------------
+
+export OFILES  :=      $(addsuffix .o,$(BINFILES)) \
+                       $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
+
+export INCLUDE :=      $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
+                       $(foreach dir,$(LIBDIRS),-I$(dir)/include) \
+                       -I$(CURDIR)/$(BUILD)
+
+.PHONY: $(BUILD) clean all
+
+#---------------------------------------------------------------------------------
+all: $(BUILD)
+       @[ -d $@ ] || mkdir -p include
+       @cp ../../*.h include
+
+lib:
+       @[ -d $@ ] || mkdir -p $@
+       
+$(BUILD): lib
+       @[ -d $@ ] || mkdir -p $@
+       @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
+
+#---------------------------------------------------------------------------------
+clean:
+       @echo clean ...
+       @rm -fr $(BUILD) lib
+
+#---------------------------------------------------------------------------------
+else
+
+DEPENDS        :=      $(OFILES:.o=.d)
+
+#---------------------------------------------------------------------------------
+# main targets
+#---------------------------------------------------------------------------------
+$(OUTPUT)      :       $(OFILES)
+
+#---------------------------------------------------------------------------------
+%.bin.o        :       %.bin
+#---------------------------------------------------------------------------------
+       @echo $(notdir $<)
+       @$(bin2o)
+
+
+-include $(DEPENDS)
+
+#---------------------------------------------------------------------------------------
+endif
+#---------------------------------------------------------------------------------------
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/nintendods/README b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/nintendods/README
new file mode 100644 (file)
index 0000000..ba7a37d
--- /dev/null
@@ -0,0 +1,5 @@
+This Makefile requires devkitARM (http://www.devkitpro.org/category/devkitarm/) and works inside "contrib/nds". It is based on a devkitARM template.
+
+Eduardo Costa <eduardo.m.costa@gmail.com>
+January 3, 2009
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/Makefile.riscos b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/Makefile.riscos
new file mode 100644 (file)
index 0000000..57e29d3
--- /dev/null
@@ -0,0 +1,151 @@
+# Project:   zlib_1_03
+# Patched for zlib 1.1.2 rw@shadow.org.uk 19980430
+# test works out-of-the-box, installs `somewhere' on demand
+
+# Toolflags:
+CCflags = -c -depend !Depend -IC: -g -throwback  -DRISCOS  -fah
+C++flags = -c -depend !Depend -IC: -throwback
+Linkflags = -aif -c++ -o $@
+ObjAsmflags = -throwback -NoCache -depend !Depend
+CMHGflags =
+LibFileflags = -c -l -o $@
+Squeezeflags = -o $@
+
+# change the line below to where _you_ want the library installed.
+libdest = lib:zlib
+
+# Final targets:
+@.lib:   @.o.adler32 @.o.compress @.o.crc32 @.o.deflate @.o.gzio \
+        @.o.infblock @.o.infcodes @.o.inffast @.o.inflate @.o.inftrees @.o.infutil @.o.trees \
+        @.o.uncompr @.o.zutil
+        LibFile $(LibFileflags) @.o.adler32 @.o.compress @.o.crc32 @.o.deflate \
+        @.o.gzio @.o.infblock @.o.infcodes @.o.inffast @.o.inflate @.o.inftrees @.o.infutil \
+        @.o.trees @.o.uncompr @.o.zutil
+test:   @.minigzip @.example @.lib
+       @copy @.lib @.libc  A~C~DF~L~N~P~Q~RS~TV
+       @echo running tests: hang on.
+       @/@.minigzip -f -9 libc
+       @/@.minigzip -d libc-gz
+       @/@.minigzip -f -1 libc
+       @/@.minigzip -d libc-gz
+       @/@.minigzip -h -9 libc
+       @/@.minigzip -d libc-gz
+       @/@.minigzip -h -1 libc
+       @/@.minigzip -d libc-gz
+       @/@.minigzip -9 libc
+       @/@.minigzip -d libc-gz
+       @/@.minigzip -1 libc
+       @/@.minigzip -d libc-gz
+       @diff @.lib @.libc
+       @echo that should have reported '@.lib and @.libc identical' if you have diff.
+       @/@.example @.fred @.fred
+       @echo that will have given lots of hello!'s.
+
+@.minigzip:   @.o.minigzip @.lib C:o.Stubs
+        Link $(Linkflags) @.o.minigzip @.lib C:o.Stubs
+@.example:   @.o.example @.lib C:o.Stubs
+        Link $(Linkflags) @.o.example @.lib C:o.Stubs
+
+install: @.lib
+       cdir $(libdest)
+       cdir $(libdest).h
+       @copy @.h.zlib $(libdest).h.zlib A~C~DF~L~N~P~Q~RS~TV
+       @copy @.h.zconf $(libdest).h.zconf A~C~DF~L~N~P~Q~RS~TV
+       @copy @.lib $(libdest).lib  A~C~DF~L~N~P~Q~RS~TV
+       @echo okay, installed zlib in $(libdest)
+
+clean:; remove @.minigzip
+       remove @.example
+       remove @.libc
+       -wipe @.o.* F~r~cV
+       remove @.fred
+
+# User-editable dependencies:
+.c.o:
+        cc $(ccflags) -o $@ $<
+
+# Static dependencies:
+
+# Dynamic dependencies:
+o.example:     c.example
+o.example:     h.zlib
+o.example:     h.zconf
+o.minigzip:    c.minigzip
+o.minigzip:    h.zlib
+o.minigzip:    h.zconf
+o.adler32:     c.adler32
+o.adler32:     h.zlib
+o.adler32:     h.zconf
+o.compress:    c.compress
+o.compress:    h.zlib
+o.compress:    h.zconf
+o.crc32:       c.crc32
+o.crc32:       h.zlib
+o.crc32:       h.zconf
+o.deflate:     c.deflate
+o.deflate:     h.deflate
+o.deflate:     h.zutil
+o.deflate:     h.zlib
+o.deflate:     h.zconf
+o.gzio:        c.gzio
+o.gzio:        h.zutil
+o.gzio:        h.zlib
+o.gzio:        h.zconf
+o.infblock:    c.infblock
+o.infblock:    h.zutil
+o.infblock:    h.zlib
+o.infblock:    h.zconf
+o.infblock:    h.infblock
+o.infblock:    h.inftrees
+o.infblock:    h.infcodes
+o.infblock:    h.infutil
+o.infcodes:    c.infcodes
+o.infcodes:    h.zutil
+o.infcodes:    h.zlib
+o.infcodes:    h.zconf
+o.infcodes:    h.inftrees
+o.infcodes:    h.infblock
+o.infcodes:    h.infcodes
+o.infcodes:    h.infutil
+o.infcodes:    h.inffast
+o.inffast:     c.inffast
+o.inffast:     h.zutil
+o.inffast:     h.zlib
+o.inffast:     h.zconf
+o.inffast:     h.inftrees
+o.inffast:     h.infblock
+o.inffast:     h.infcodes
+o.inffast:     h.infutil
+o.inffast:     h.inffast
+o.inflate:     c.inflate
+o.inflate:     h.zutil
+o.inflate:     h.zlib
+o.inflate:     h.zconf
+o.inflate:     h.infblock
+o.inftrees:    c.inftrees
+o.inftrees:    h.zutil
+o.inftrees:    h.zlib
+o.inftrees:    h.zconf
+o.inftrees:    h.inftrees
+o.inftrees:    h.inffixed
+o.infutil:     c.infutil
+o.infutil:     h.zutil
+o.infutil:     h.zlib
+o.infutil:     h.zconf
+o.infutil:     h.infblock
+o.infutil:     h.inftrees
+o.infutil:     h.infcodes
+o.infutil:     h.infutil
+o.trees:       c.trees
+o.trees:       h.deflate
+o.trees:       h.zutil
+o.trees:       h.zlib
+o.trees:       h.zconf
+o.trees:       h.trees
+o.uncompr:     c.uncompr
+o.uncompr:     h.zlib
+o.uncompr:     h.zconf
+o.zutil:       c.zutil
+o.zutil:       h.zutil
+o.zutil:       h.zlib
+o.zutil:       h.zconf
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/README b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/README
new file mode 100644 (file)
index 0000000..800bf07
--- /dev/null
@@ -0,0 +1,3 @@
+This directory contains files that have not been updated for zlib 1.2.x
+
+(Volunteers are encouraged to help clean this up.  Thanks.)
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/descrip.mms b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/descrip.mms
new file mode 100644 (file)
index 0000000..7066da5
--- /dev/null
@@ -0,0 +1,48 @@
+# descrip.mms: MMS description file for building zlib on VMS
+# written by Martin P.J. Zinser <m.zinser@gsi.de>
+
+cc_defs =
+c_deb =
+
+.ifdef __DECC__
+pref = /prefix=all
+.endif
+
+OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj,\
+       deflate.obj, trees.obj, zutil.obj, inflate.obj, infblock.obj,\
+       inftrees.obj, infcodes.obj, infutil.obj, inffast.obj
+
+CFLAGS= $(C_DEB) $(CC_DEFS) $(PREF)
+
+all : example.exe minigzip.exe
+        @ write sys$output " Example applications available"
+libz.olb : libz.olb($(OBJS))
+       @ write sys$output " libz available"
+
+example.exe : example.obj libz.olb
+              link example,libz.olb/lib
+
+minigzip.exe : minigzip.obj libz.olb
+              link minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib
+
+clean :
+       delete *.obj;*,libz.olb;*
+
+
+# Other dependencies.
+adler32.obj : zutil.h zlib.h zconf.h
+compress.obj : zlib.h zconf.h
+crc32.obj : zutil.h zlib.h zconf.h
+deflate.obj : deflate.h zutil.h zlib.h zconf.h
+example.obj : zlib.h zconf.h
+gzio.obj : zutil.h zlib.h zconf.h
+infblock.obj : zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h
+infcodes.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h infcodes.h inffast.h
+inffast.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h inffast.h
+inflate.obj : zutil.h zlib.h zconf.h infblock.h
+inftrees.obj : zutil.h zlib.h zconf.h inftrees.h
+infutil.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h
+minigzip.obj : zlib.h zconf.h
+trees.obj : deflate.h zutil.h zlib.h zconf.h
+uncompr.obj : zlib.h zconf.h
+zutil.obj : zutil.h zlib.h zconf.h
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/os2/Makefile.os2 b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/os2/Makefile.os2
new file mode 100644 (file)
index 0000000..a105aaa
--- /dev/null
@@ -0,0 +1,136 @@
+# Makefile for zlib under OS/2 using GCC (PGCC)
+# For conditions of distribution and use, see copyright notice in zlib.h
+
+# To compile and test, type:
+#   cp Makefile.os2 ..
+#   cd ..
+#   make -f Makefile.os2 test
+
+# This makefile will build a static library z.lib, a shared library
+# z.dll and a import library zdll.lib. You can use either z.lib or
+# zdll.lib by specifying either -lz or -lzdll on gcc's command line
+
+CC=gcc -Zomf -s
+
+CFLAGS=-O6 -Wall
+#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
+#CFLAGS=-g -DDEBUG
+#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
+#           -Wstrict-prototypes -Wmissing-prototypes
+
+#################### BUG WARNING: #####################
+## infcodes.c hits a bug in pgcc-1.0, so you have to use either
+## -O# where # <= 4 or one of (-fno-ommit-frame-pointer or -fno-force-mem)
+## This bug is reportedly fixed in pgcc >1.0, but this was not tested
+CFLAGS+=-fno-force-mem
+
+LDFLAGS=-s -L. -lzdll -Zcrtdll
+LDSHARED=$(CC) -s -Zomf -Zdll -Zcrtdll
+
+VER=1.1.0
+ZLIB=z.lib
+SHAREDLIB=z.dll
+SHAREDLIBIMP=zdll.lib
+LIBS=$(ZLIB) $(SHAREDLIB) $(SHAREDLIBIMP)
+
+AR=emxomfar cr
+IMPLIB=emximp
+RANLIB=echo
+TAR=tar
+SHELL=bash
+
+prefix=/usr/local
+exec_prefix = $(prefix)
+
+OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
+       zutil.o inflate.o infblock.o inftrees.o infcodes.o infutil.o inffast.o
+
+TEST_OBJS = example.o minigzip.o
+
+DISTFILES = README INDEX ChangeLog configure Make*[a-z0-9] *.[ch] descrip.mms \
+  algorithm.txt zlib.3 msdos/Make*[a-z0-9] msdos/zlib.def msdos/zlib.rc \
+  nt/Makefile.nt nt/zlib.dnt  contrib/README.contrib contrib/*.txt \
+  contrib/asm386/*.asm contrib/asm386/*.c \
+  contrib/asm386/*.bat contrib/asm386/zlibvc.d?? contrib/iostream/*.cpp \
+  contrib/iostream/*.h  contrib/iostream2/*.h contrib/iostream2/*.cpp \
+  contrib/untgz/Makefile contrib/untgz/*.c contrib/untgz/*.w32
+
+all: example.exe minigzip.exe
+
+test: all
+       @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
+       echo hello world | ./minigzip | ./minigzip -d || \
+         echo '                *** minigzip test FAILED ***' ; \
+       if ./example; then \
+         echo '                *** zlib test OK ***'; \
+       else \
+         echo '                *** zlib test FAILED ***'; \
+       fi
+
+$(ZLIB): $(OBJS)
+       $(AR) $@ $(OBJS)
+       -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
+
+$(SHAREDLIB): $(OBJS) os2/z.def
+       $(LDSHARED) -o $@ $^
+
+$(SHAREDLIBIMP): os2/z.def
+       $(IMPLIB) -o $@ $^
+
+example.exe: example.o $(LIBS)
+       $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
+
+minigzip.exe: minigzip.o $(LIBS)
+       $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
+
+clean:
+       rm -f *.o *~ example minigzip libz.a libz.so* foo.gz
+
+distclean:     clean
+
+zip:
+       mv Makefile Makefile~; cp -p Makefile.in Makefile
+       rm -f test.c ztest*.c
+       v=`sed -n -e 's/\.//g' -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`;\
+       zip -ul9 zlib$$v $(DISTFILES)
+       mv Makefile~ Makefile
+
+dist:
+       mv Makefile Makefile~; cp -p Makefile.in Makefile
+       rm -f test.c ztest*.c
+       d=zlib-`sed -n '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`;\
+       rm -f $$d.tar.gz; \
+       if test ! -d ../$$d; then rm -f ../$$d; ln -s `pwd` ../$$d; fi; \
+       files=""; \
+       for f in $(DISTFILES); do files="$$files $$d/$$f"; done; \
+       cd ..; \
+       GZIP=-9 $(TAR) chofz $$d/$$d.tar.gz $$files; \
+       if test ! -d $$d; then rm -f $$d; fi
+       mv Makefile~ Makefile
+
+tags:
+       etags *.[ch]
+
+depend:
+       makedepend -- $(CFLAGS) -- *.[ch]
+
+# DO NOT DELETE THIS LINE -- make depend depends on it.
+
+adler32.o: zlib.h zconf.h
+compress.o: zlib.h zconf.h
+crc32.o: zlib.h zconf.h
+deflate.o: deflate.h zutil.h zlib.h zconf.h
+example.o: zlib.h zconf.h
+gzio.o: zutil.h zlib.h zconf.h
+infblock.o: infblock.h inftrees.h infcodes.h infutil.h zutil.h zlib.h zconf.h
+infcodes.o: zutil.h zlib.h zconf.h
+infcodes.o: inftrees.h infblock.h infcodes.h infutil.h inffast.h
+inffast.o: zutil.h zlib.h zconf.h inftrees.h
+inffast.o: infblock.h infcodes.h infutil.h inffast.h
+inflate.o: zutil.h zlib.h zconf.h infblock.h
+inftrees.o: zutil.h zlib.h zconf.h inftrees.h
+infutil.o: zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h
+minigzip.o: zlib.h zconf.h
+trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
+uncompr.o: zlib.h zconf.h
+zutil.o: zutil.h zlib.h zconf.h
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/os2/zlib.def b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/os2/zlib.def
new file mode 100644 (file)
index 0000000..4c753f1
--- /dev/null
@@ -0,0 +1,51 @@
+;
+; Slightly modified version of ../nt/zlib.dnt :-)
+;
+
+LIBRARY                Z
+DESCRIPTION    "Zlib compression library for OS/2"
+CODE           PRELOAD MOVEABLE DISCARDABLE
+DATA           PRELOAD MOVEABLE MULTIPLE
+
+EXPORTS
+    adler32
+    compress
+    crc32
+    deflate
+    deflateCopy
+    deflateEnd
+    deflateInit2_
+    deflateInit_
+    deflateParams
+    deflateReset
+    deflateSetDictionary
+    gzclose
+    gzdopen
+    gzerror
+    gzflush
+    gzopen
+    gzread
+    gzwrite
+    inflate
+    inflateEnd
+    inflateInit2_
+    inflateInit_
+    inflateReset
+    inflateSetDictionary
+    inflateSync
+    uncompress
+    zlibVersion
+    gzprintf
+    gzputc
+    gzgetc
+    gzseek
+    gzrewind
+    gztell
+    gzeof
+    gzsetparams
+    zError
+    inflateSyncPoint
+    get_crc_table
+    compress2
+    gzputs
+    gzgets
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/visual-basic.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/old/visual-basic.txt
new file mode 100644 (file)
index 0000000..57efe58
--- /dev/null
@@ -0,0 +1,160 @@
+See below some functions declarations for Visual Basic.
+
+Frequently Asked Question:
+
+Q: Each time I use the compress function I get the -5 error (not enough
+   room in the output buffer).
+
+A: Make sure that the length of the compressed buffer is passed by
+   reference ("as any"), not by value ("as long"). Also check that
+   before the call of compress this length is equal to the total size of
+   the compressed buffer and not zero.
+
+
+From: "Jon Caruana" <jon-net@usa.net>
+Subject: Re: How to port zlib declares to vb?
+Date: Mon, 28 Oct 1996 18:33:03 -0600
+
+Got the answer! (I haven't had time to check this but it's what I got, and
+looks correct):
+
+He has the following routines working:
+        compress
+        uncompress
+        gzopen
+        gzwrite
+        gzread
+        gzclose
+
+Declares follow: (Quoted from Carlos Rios <c_rios@sonda.cl>, in Vb4 form)
+
+#If Win16 Then   'Use Win16 calls.
+Declare Function compress Lib "ZLIB.DLL" (ByVal compr As
+        String, comprLen As Any, ByVal buf As String, ByVal buflen
+        As Long) As Integer
+Declare Function uncompress Lib "ZLIB.DLL" (ByVal uncompr
+        As String, uncomprLen As Any, ByVal compr As String, ByVal
+        lcompr As Long) As Integer
+Declare Function gzopen Lib "ZLIB.DLL" (ByVal filePath As
+        String, ByVal mode As String) As Long
+Declare Function gzread Lib "ZLIB.DLL" (ByVal file As
+        Long, ByVal uncompr As String, ByVal uncomprLen As Integer)
+        As Integer
+Declare Function gzwrite Lib "ZLIB.DLL" (ByVal file As
+        Long, ByVal uncompr As String, ByVal uncomprLen As Integer)
+        As Integer
+Declare Function gzclose Lib "ZLIB.DLL" (ByVal file As
+        Long) As Integer
+#Else
+Declare Function compress Lib "ZLIB32.DLL"
+        (ByVal compr As String, comprLen As Any, ByVal buf As
+        String, ByVal buflen As Long) As Integer
+Declare Function uncompress Lib "ZLIB32.DLL"
+        (ByVal uncompr As String, uncomprLen As Any, ByVal compr As
+        String, ByVal lcompr As Long) As Long
+Declare Function gzopen Lib "ZLIB32.DLL"
+        (ByVal file As String, ByVal mode As String) As Long
+Declare Function gzread Lib "ZLIB32.DLL"
+        (ByVal file As Long, ByVal uncompr As String, ByVal
+        uncomprLen As Long) As Long
+Declare Function gzwrite Lib "ZLIB32.DLL"
+        (ByVal file As Long, ByVal uncompr As String, ByVal
+        uncomprLen As Long) As Long
+Declare Function gzclose Lib "ZLIB32.DLL"
+        (ByVal file As Long) As Long
+#End If
+
+-Jon Caruana
+jon-net@usa.net
+Microsoft Sitebuilder Network Level 1 Member - HTML Writer's Guild Member
+
+
+Here is another example from Michael <michael_borgsys@hotmail.com> that he
+says conforms to the VB guidelines, and that solves the problem of not
+knowing the uncompressed size by storing it at the end of the file:
+
+'Calling the functions:
+'bracket meaning: <parameter> [optional] {Range of possible values}
+'Call subCompressFile(<path with filename to compress> [, <path with
+filename to write to>, [level of compression {1..9}]])
+'Call subUncompressFile(<path with filename to compress>)
+
+Option Explicit
+Private lngpvtPcnSml As Long 'Stores value for 'lngPercentSmaller'
+Private Const SUCCESS As Long = 0
+Private Const strFilExt As String = ".cpr"
+Private Declare Function lngfncCpr Lib "zlib.dll" Alias "compress2" (ByRef
+dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long,
+ByVal level As Integer) As Long
+Private Declare Function lngfncUcp Lib "zlib.dll" Alias "uncompress" (ByRef
+dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long)
+As Long
+
+Public Sub subCompressFile(ByVal strargOriFilPth As String, Optional ByVal
+strargCprFilPth As String, Optional ByVal intLvl As Integer = 9)
+    Dim strCprPth As String
+    Dim lngOriSiz As Long
+    Dim lngCprSiz As Long
+    Dim bytaryOri() As Byte
+    Dim bytaryCpr() As Byte
+    lngOriSiz = FileLen(strargOriFilPth)
+    ReDim bytaryOri(lngOriSiz - 1)
+    Open strargOriFilPth For Binary Access Read As #1
+        Get #1, , bytaryOri()
+    Close #1
+    strCprPth = IIf(strargCprFilPth = "", strargOriFilPth, strargCprFilPth)
+'Select file path and name
+    strCprPth = strCprPth & IIf(Right(strCprPth, Len(strFilExt)) =
+strFilExt, "", strFilExt) 'Add file extension if not exists
+    lngCprSiz = (lngOriSiz * 1.01) + 12 'Compression needs temporary a bit
+more space then original file size
+    ReDim bytaryCpr(lngCprSiz - 1)
+    If lngfncCpr(bytaryCpr(0), lngCprSiz, bytaryOri(0), lngOriSiz, intLvl) =
+SUCCESS Then
+        lngpvtPcnSml = (1# - (lngCprSiz / lngOriSiz)) * 100
+        ReDim Preserve bytaryCpr(lngCprSiz - 1)
+        Open strCprPth For Binary Access Write As #1
+            Put #1, , bytaryCpr()
+            Put #1, , lngOriSiz 'Add the the original size value to the end
+(last 4 bytes)
+        Close #1
+    Else
+        MsgBox "Compression error"
+    End If
+    Erase bytaryCpr
+    Erase bytaryOri
+End Sub
+
+Public Sub subUncompressFile(ByVal strargFilPth As String)
+    Dim bytaryCpr() As Byte
+    Dim bytaryOri() As Byte
+    Dim lngOriSiz As Long
+    Dim lngCprSiz As Long
+    Dim strOriPth As String
+    lngCprSiz = FileLen(strargFilPth)
+    ReDim bytaryCpr(lngCprSiz - 1)
+    Open strargFilPth For Binary Access Read As #1
+        Get #1, , bytaryCpr()
+    Close #1
+    'Read the original file size value:
+    lngOriSiz = bytaryCpr(lngCprSiz - 1) * (2 ^ 24) _
+              + bytaryCpr(lngCprSiz - 2) * (2 ^ 16) _
+              + bytaryCpr(lngCprSiz - 3) * (2 ^ 8) _
+              + bytaryCpr(lngCprSiz - 4)
+    ReDim Preserve bytaryCpr(lngCprSiz - 5) 'Cut of the original size value
+    ReDim bytaryOri(lngOriSiz - 1)
+    If lngfncUcp(bytaryOri(0), lngOriSiz, bytaryCpr(0), lngCprSiz) = SUCCESS
+Then
+        strOriPth = Left(strargFilPth, Len(strargFilPth) - Len(strFilExt))
+        Open strOriPth For Binary Access Write As #1
+            Put #1, , bytaryOri()
+        Close #1
+    Else
+        MsgBox "Uncompression error"
+    End If
+    Erase bytaryCpr
+    Erase bytaryOri
+End Sub
+Public Property Get lngPercentSmaller() As Long
+    lngPercentSmaller = lngpvtPcnSml
+End Property
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/qnx/package.qpg b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/qnx/package.qpg
new file mode 100644 (file)
index 0000000..4d7ea6a
--- /dev/null
@@ -0,0 +1,141 @@
+<QPG:Generation>
+   <QPG:Options>
+      <QPG:User unattended="no" verbosity="2" listfiles="yes"/>
+      <QPG:Defaults type="qnx_package"/>
+      <QPG:Source></QPG:Source>
+      <QPG:Release number="+"/>
+      <QPG:Build></QPG:Build>
+      <QPG:FileSorting strip="yes"/>
+      <QPG:Package targets="combine"/>
+      <QPG:Repository generate="yes"/>
+      <QPG:FinalDir></QPG:FinalDir>
+      <QPG:Cleanup></QPG:Cleanup>
+   </QPG:Options>
+
+   <QPG:Responsible>
+      <QPG:Company></QPG:Company>
+      <QPG:Department></QPG:Department>
+      <QPG:Group></QPG:Group>
+      <QPG:Team></QPG:Team>
+      <QPG:Employee></QPG:Employee>
+      <QPG:EmailAddress></QPG:EmailAddress>
+   </QPG:Responsible>
+
+   <QPG:Values>
+      <QPG:Files>
+         <QPG:Add file="../zconf.h" install="/opt/include/" user="root:sys" permission="644"/>
+         <QPG:Add file="../zlib.h" install="/opt/include/" user="root:sys" permission="644"/>
+         <QPG:Add file="../libz.so.1.2.6" install="/opt/lib/" user="root:bin" permission="644"/>
+         <QPG:Add file="libz.so" install="/opt/lib/" component="dev" filetype="symlink" linkto="libz.so.1.2.6"/>
+         <QPG:Add file="libz.so.1" install="/opt/lib/" filetype="symlink" linkto="libz.so.1.2.6"/>
+         <QPG:Add file="../libz.so.1.2.6" install="/opt/lib/" component="slib"/>
+      </QPG:Files>
+
+      <QPG:PackageFilter>
+         <QPM:PackageManifest>
+            <QPM:PackageDescription>
+               <QPM:PackageType>Library</QPM:PackageType>
+               <QPM:PackageReleaseNotes></QPM:PackageReleaseNotes>
+               <QPM:PackageReleaseUrgency>Medium</QPM:PackageReleaseUrgency>
+               <QPM:PackageRepository></QPM:PackageRepository>
+               <QPM:FileVersion>2.0</QPM:FileVersion>
+            </QPM:PackageDescription>
+
+            <QPM:ProductDescription>
+               <QPM:ProductName>zlib</QPM:ProductName>
+               <QPM:ProductIdentifier>zlib</QPM:ProductIdentifier>
+               <QPM:ProductEmail>alain.bonnefoy@icbt.com</QPM:ProductEmail>
+               <QPM:VendorName>Public</QPM:VendorName>
+               <QPM:VendorInstallName>public</QPM:VendorInstallName>
+               <QPM:VendorURL>www.gzip.org/zlib</QPM:VendorURL>
+               <QPM:VendorEmbedURL></QPM:VendorEmbedURL>
+               <QPM:VendorEmail></QPM:VendorEmail>
+               <QPM:AuthorName>Jean-Loup Gailly,Mark Adler</QPM:AuthorName>
+               <QPM:AuthorURL>www.gzip.org/zlib</QPM:AuthorURL>
+               <QPM:AuthorEmbedURL></QPM:AuthorEmbedURL>
+               <QPM:AuthorEmail>zlib@gzip.org</QPM:AuthorEmail>
+               <QPM:ProductIconSmall></QPM:ProductIconSmall>
+               <QPM:ProductIconLarge></QPM:ProductIconLarge>
+               <QPM:ProductDescriptionShort>A massively spiffy yet delicately unobtrusive compression library.</QPM:ProductDescriptionShort>
+               <QPM:ProductDescriptionLong>zlib is designed to be a free, general-purpose, legally unencumbered, lossless data compression library for use on virtually any computer hardware and operating system.</QPM:ProductDescriptionLong>
+               <QPM:ProductDescriptionURL>http://www.gzip.org/zlib</QPM:ProductDescriptionURL>
+               <QPM:ProductDescriptionEmbedURL></QPM:ProductDescriptionEmbedURL>
+            </QPM:ProductDescription>
+
+            <QPM:ReleaseDescription>
+               <QPM:ReleaseVersion>1.2.6</QPM:ReleaseVersion>
+               <QPM:ReleaseUrgency>Medium</QPM:ReleaseUrgency>
+               <QPM:ReleaseStability>Stable</QPM:ReleaseStability>
+               <QPM:ReleaseNoteMinor></QPM:ReleaseNoteMinor>
+               <QPM:ReleaseNoteMajor></QPM:ReleaseNoteMajor>
+               <QPM:ExcludeCountries>
+                  <QPM:Country></QPM:Country>
+               </QPM:ExcludeCountries>
+
+               <QPM:ReleaseCopyright>No License</QPM:ReleaseCopyright>
+            </QPM:ReleaseDescription>
+
+            <QPM:ContentDescription>
+               <QPM:ContentTopic xmlmultiple="true">Software Development/Libraries and Extensions/C Libraries</QPM:ContentTopic>
+               <QPM:ContentKeyword>zlib,compression</QPM:ContentKeyword>
+               <QPM:TargetOS>qnx6</QPM:TargetOS>
+               <QPM:HostOS>qnx6</QPM:HostOS>
+               <QPM:DisplayEnvironment xmlmultiple="true">None</QPM:DisplayEnvironment>
+               <QPM:TargetAudience xmlmultiple="true">Developer</QPM:TargetAudience>
+            </QPM:ContentDescription>
+         </QPM:PackageManifest>
+      </QPG:PackageFilter>
+
+      <QPG:PackageFilter proc="none" target="none">
+         <QPM:PackageManifest>
+            <QPM:ProductInstallationDependencies>
+               <QPM:ProductRequirements></QPM:ProductRequirements>
+            </QPM:ProductInstallationDependencies>
+
+            <QPM:ProductInstallationProcedure>
+               <QPM:Script xmlmultiple="true">
+                  <QPM:ScriptName></QPM:ScriptName>
+                  <QPM:ScriptType>Install</QPM:ScriptType>
+                  <QPM:ScriptTiming>Post</QPM:ScriptTiming>
+                  <QPM:ScriptBlocking>No</QPM:ScriptBlocking>
+                  <QPM:ScriptResult>Ignore</QPM:ScriptResult>
+                  <QPM:ShortDescription></QPM:ShortDescription>
+                  <QPM:UseBinaries>No</QPM:UseBinaries>
+                  <QPM:Priority>Optional</QPM:Priority>
+               </QPM:Script>
+            </QPM:ProductInstallationProcedure>
+         </QPM:PackageManifest>
+
+         <QPM:Launch>
+         </QPM:Launch>
+      </QPG:PackageFilter>
+
+      <QPG:PackageFilter type="core" component="none">
+         <QPM:PackageManifest>
+            <QPM:ProductInstallationProcedure>
+              <QPM:OrderDependency xmlmultiple="true">
+                 <QPM:Order>InstallOver</QPM:Order>
+                 <QPM:Product>zlib</QPM:Product>
+              </QPM:OrderDependency>
+            </QPM:ProductInstallationProcedure>
+         </QPM:PackageManifest>
+
+         <QPM:Launch>
+         </QPM:Launch>
+      </QPG:PackageFilter>
+
+      <QPG:PackageFilter type="core" component="dev">
+         <QPM:PackageManifest>
+            <QPM:ProductInstallationProcedure>
+              <QPM:OrderDependency xmlmultiple="true">
+                 <QPM:Order>InstallOver</QPM:Order>
+                 <QPM:Product>zlib-dev</QPM:Product>
+              </QPM:OrderDependency>
+            </QPM:ProductInstallationProcedure>
+         </QPM:PackageManifest>
+
+         <QPM:Launch>
+         </QPM:Launch>
+      </QPG:PackageFilter>
+   </QPG:Values>
+</QPG:Generation>
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/example.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/example.c
new file mode 100644 (file)
index 0000000..f515a48
--- /dev/null
@@ -0,0 +1,601 @@
+/* example.c -- usage example of the zlib compression library
+ * Copyright (C) 1995-2006, 2011 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#include "zlib.h"
+#include <stdio.h>
+
+#ifdef STDC
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+
+#if defined(VMS) || defined(RISCOS)
+#  define TESTFILE "foo-gz"
+#else
+#  define TESTFILE "foo.gz"
+#endif
+
+#define CHECK_ERR(err, msg) { \
+    if (err != Z_OK) { \
+        fprintf(stderr, "%s error: %d\n", msg, err); \
+        exit(1); \
+    } \
+}
+
+const char hello[] = "hello, hello!";
+/* "hello world" would be more standard, but the repeated "hello"
+ * stresses the compression code better, sorry...
+ */
+
+const char dictionary[] = "hello";
+uLong dictId; /* Adler32 value of the dictionary */
+
+void test_deflate       OF((Byte *compr, uLong comprLen));
+void test_inflate       OF((Byte *compr, uLong comprLen,
+                            Byte *uncompr, uLong uncomprLen));
+void test_large_deflate OF((Byte *compr, uLong comprLen,
+                            Byte *uncompr, uLong uncomprLen));
+void test_large_inflate OF((Byte *compr, uLong comprLen,
+                            Byte *uncompr, uLong uncomprLen));
+void test_flush         OF((Byte *compr, uLong *comprLen));
+void test_sync          OF((Byte *compr, uLong comprLen,
+                            Byte *uncompr, uLong uncomprLen));
+void test_dict_deflate  OF((Byte *compr, uLong comprLen));
+void test_dict_inflate  OF((Byte *compr, uLong comprLen,
+                            Byte *uncompr, uLong uncomprLen));
+int  main               OF((int argc, char *argv[]));
+
+
+#ifdef Z_SOLO
+
+void *myalloc OF((void *, unsigned, unsigned));
+void myfree OF((void *, void *));
+
+void *myalloc(q, n, m)
+    void *q;
+    unsigned n, m;
+{
+    q = Z_NULL;
+    return calloc(n, m);
+}
+
+void myfree(void *q, void *p)
+{
+    q = Z_NULL;
+    free(p);
+}
+
+static alloc_func zalloc = myalloc;
+static free_func zfree = myfree;
+
+#else /* !Z_SOLO */
+
+static alloc_func zalloc = (alloc_func)0;
+static free_func zfree = (free_func)0;
+
+void test_compress      OF((Byte *compr, uLong comprLen,
+                            Byte *uncompr, uLong uncomprLen));
+void test_gzio          OF((const char *fname,
+                            Byte *uncompr, uLong uncomprLen));
+
+/* ===========================================================================
+ * Test compress() and uncompress()
+ */
+void test_compress(compr, comprLen, uncompr, uncomprLen)
+    Byte *compr, *uncompr;
+    uLong comprLen, uncomprLen;
+{
+    int err;
+    uLong len = (uLong)strlen(hello)+1;
+
+    err = compress(compr, &comprLen, (const Bytef*)hello, len);
+    CHECK_ERR(err, "compress");
+
+    strcpy((char*)uncompr, "garbage");
+
+    err = uncompress(uncompr, &uncomprLen, compr, comprLen);
+    CHECK_ERR(err, "uncompress");
+
+    if (strcmp((char*)uncompr, hello)) {
+        fprintf(stderr, "bad uncompress\n");
+        exit(1);
+    } else {
+        printf("uncompress(): %s\n", (char *)uncompr);
+    }
+}
+
+/* ===========================================================================
+ * Test read/write of .gz files
+ */
+void test_gzio(fname, uncompr, uncomprLen)
+    const char *fname; /* compressed file name */
+    Byte *uncompr;
+    uLong uncomprLen;
+{
+#ifdef NO_GZCOMPRESS
+    fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n");
+#else
+    int err;
+    int len = (int)strlen(hello)+1;
+    gzFile file;
+    z_off_t pos;
+
+    file = gzopen(fname, "wb");
+    if (file == NULL) {
+        fprintf(stderr, "gzopen error\n");
+        exit(1);
+    }
+    gzputc(file, 'h');
+    if (gzputs(file, "ello") != 4) {
+        fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err));
+        exit(1);
+    }
+    if (gzprintf(file, ", %s!", "hello") != 8) {
+        fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err));
+        exit(1);
+    }
+    gzseek(file, 1L, SEEK_CUR); /* add one zero byte */
+    gzclose(file);
+
+    file = gzopen(fname, "rb");
+    if (file == NULL) {
+        fprintf(stderr, "gzopen error\n");
+        exit(1);
+    }
+    strcpy((char*)uncompr, "garbage");
+
+    if (gzread(file, uncompr, (unsigned)uncomprLen) != len) {
+        fprintf(stderr, "gzread err: %s\n", gzerror(file, &err));
+        exit(1);
+    }
+    if (strcmp((char*)uncompr, hello)) {
+        fprintf(stderr, "bad gzread: %s\n", (char*)uncompr);
+        exit(1);
+    } else {
+        printf("gzread(): %s\n", (char*)uncompr);
+    }
+
+    pos = gzseek(file, -8L, SEEK_CUR);
+    if (pos != 6 || gztell(file) != pos) {
+        fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n",
+                (long)pos, (long)gztell(file));
+        exit(1);
+    }
+
+    if (gzgetc(file) != ' ') {
+        fprintf(stderr, "gzgetc error\n");
+        exit(1);
+    }
+
+    if (gzungetc(' ', file) != ' ') {
+        fprintf(stderr, "gzungetc error\n");
+        exit(1);
+    }
+
+    gzgets(file, (char*)uncompr, (int)uncomprLen);
+    if (strlen((char*)uncompr) != 7) { /* " hello!" */
+        fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err));
+        exit(1);
+    }
+    if (strcmp((char*)uncompr, hello + 6)) {
+        fprintf(stderr, "bad gzgets after gzseek\n");
+        exit(1);
+    } else {
+        printf("gzgets() after gzseek: %s\n", (char*)uncompr);
+    }
+
+    gzclose(file);
+#endif
+}
+
+#endif /* Z_SOLO */
+
+/* ===========================================================================
+ * Test deflate() with small buffers
+ */
+void test_deflate(compr, comprLen)
+    Byte *compr;
+    uLong comprLen;
+{
+    z_stream c_stream; /* compression stream */
+    int err;
+    uLong len = (uLong)strlen(hello)+1;
+
+    c_stream.zalloc = zalloc;
+    c_stream.zfree = zfree;
+    c_stream.opaque = (voidpf)0;
+
+    err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
+    CHECK_ERR(err, "deflateInit");
+
+    c_stream.next_in  = (Bytef*)hello;
+    c_stream.next_out = compr;
+
+    while (c_stream.total_in != len && c_stream.total_out < comprLen) {
+        c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */
+        err = deflate(&c_stream, Z_NO_FLUSH);
+        CHECK_ERR(err, "deflate");
+    }
+    /* Finish the stream, still forcing small buffers: */
+    for (;;) {
+        c_stream.avail_out = 1;
+        err = deflate(&c_stream, Z_FINISH);
+        if (err == Z_STREAM_END) break;
+        CHECK_ERR(err, "deflate");
+    }
+
+    err = deflateEnd(&c_stream);
+    CHECK_ERR(err, "deflateEnd");
+}
+
+/* ===========================================================================
+ * Test inflate() with small buffers
+ */
+void test_inflate(compr, comprLen, uncompr, uncomprLen)
+    Byte *compr, *uncompr;
+    uLong comprLen, uncomprLen;
+{
+    int err;
+    z_stream d_stream; /* decompression stream */
+
+    strcpy((char*)uncompr, "garbage");
+
+    d_stream.zalloc = zalloc;
+    d_stream.zfree = zfree;
+    d_stream.opaque = (voidpf)0;
+
+    d_stream.next_in  = compr;
+    d_stream.avail_in = 0;
+    d_stream.next_out = uncompr;
+
+    err = inflateInit(&d_stream);
+    CHECK_ERR(err, "inflateInit");
+
+    while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) {
+        d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
+        err = inflate(&d_stream, Z_NO_FLUSH);
+        if (err == Z_STREAM_END) break;
+        CHECK_ERR(err, "inflate");
+    }
+
+    err = inflateEnd(&d_stream);
+    CHECK_ERR(err, "inflateEnd");
+
+    if (strcmp((char*)uncompr, hello)) {
+        fprintf(stderr, "bad inflate\n");
+        exit(1);
+    } else {
+        printf("inflate(): %s\n", (char *)uncompr);
+    }
+}
+
+/* ===========================================================================
+ * Test deflate() with large buffers and dynamic change of compression level
+ */
+void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
+    Byte *compr, *uncompr;
+    uLong comprLen, uncomprLen;
+{
+    z_stream c_stream; /* compression stream */
+    int err;
+
+    c_stream.zalloc = zalloc;
+    c_stream.zfree = zfree;
+    c_stream.opaque = (voidpf)0;
+
+    err = deflateInit(&c_stream, Z_BEST_SPEED);
+    CHECK_ERR(err, "deflateInit");
+
+    c_stream.next_out = compr;
+    c_stream.avail_out = (uInt)comprLen;
+
+    /* At this point, uncompr is still mostly zeroes, so it should compress
+     * very well:
+     */
+    c_stream.next_in = uncompr;
+    c_stream.avail_in = (uInt)uncomprLen;
+    err = deflate(&c_stream, Z_NO_FLUSH);
+    CHECK_ERR(err, "deflate");
+    if (c_stream.avail_in != 0) {
+        fprintf(stderr, "deflate not greedy\n");
+        exit(1);
+    }
+
+    /* Feed in already compressed data and switch to no compression: */
+    deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY);
+    c_stream.next_in = compr;
+    c_stream.avail_in = (uInt)comprLen/2;
+    err = deflate(&c_stream, Z_NO_FLUSH);
+    CHECK_ERR(err, "deflate");
+
+    /* Switch back to compressing mode: */
+    deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED);
+    c_stream.next_in = uncompr;
+    c_stream.avail_in = (uInt)uncomprLen;
+    err = deflate(&c_stream, Z_NO_FLUSH);
+    CHECK_ERR(err, "deflate");
+
+    err = deflate(&c_stream, Z_FINISH);
+    if (err != Z_STREAM_END) {
+        fprintf(stderr, "deflate should report Z_STREAM_END\n");
+        exit(1);
+    }
+    err = deflateEnd(&c_stream);
+    CHECK_ERR(err, "deflateEnd");
+}
+
+/* ===========================================================================
+ * Test inflate() with large buffers
+ */
+void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
+    Byte *compr, *uncompr;
+    uLong comprLen, uncomprLen;
+{
+    int err;
+    z_stream d_stream; /* decompression stream */
+
+    strcpy((char*)uncompr, "garbage");
+
+    d_stream.zalloc = zalloc;
+    d_stream.zfree = zfree;
+    d_stream.opaque = (voidpf)0;
+
+    d_stream.next_in  = compr;
+    d_stream.avail_in = (uInt)comprLen;
+
+    err = inflateInit(&d_stream);
+    CHECK_ERR(err, "inflateInit");
+
+    for (;;) {
+        d_stream.next_out = uncompr;            /* discard the output */
+        d_stream.avail_out = (uInt)uncomprLen;
+        err = inflate(&d_stream, Z_NO_FLUSH);
+        if (err == Z_STREAM_END) break;
+        CHECK_ERR(err, "large inflate");
+    }
+
+    err = inflateEnd(&d_stream);
+    CHECK_ERR(err, "inflateEnd");
+
+    if (d_stream.total_out != 2*uncomprLen + comprLen/2) {
+        fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out);
+        exit(1);
+    } else {
+        printf("large_inflate(): OK\n");
+    }
+}
+
+/* ===========================================================================
+ * Test deflate() with full flush
+ */
+void test_flush(compr, comprLen)
+    Byte *compr;
+    uLong *comprLen;
+{
+    z_stream c_stream; /* compression stream */
+    int err;
+    uInt len = (uInt)strlen(hello)+1;
+
+    c_stream.zalloc = zalloc;
+    c_stream.zfree = zfree;
+    c_stream.opaque = (voidpf)0;
+
+    err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
+    CHECK_ERR(err, "deflateInit");
+
+    c_stream.next_in  = (Bytef*)hello;
+    c_stream.next_out = compr;
+    c_stream.avail_in = 3;
+    c_stream.avail_out = (uInt)*comprLen;
+    err = deflate(&c_stream, Z_FULL_FLUSH);
+    CHECK_ERR(err, "deflate");
+
+    compr[3]++; /* force an error in first compressed block */
+    c_stream.avail_in = len - 3;
+
+    err = deflate(&c_stream, Z_FINISH);
+    if (err != Z_STREAM_END) {
+        CHECK_ERR(err, "deflate");
+    }
+    err = deflateEnd(&c_stream);
+    CHECK_ERR(err, "deflateEnd");
+
+    *comprLen = c_stream.total_out;
+}
+
+/* ===========================================================================
+ * Test inflateSync()
+ */
+void test_sync(compr, comprLen, uncompr, uncomprLen)
+    Byte *compr, *uncompr;
+    uLong comprLen, uncomprLen;
+{
+    int err;
+    z_stream d_stream; /* decompression stream */
+
+    strcpy((char*)uncompr, "garbage");
+
+    d_stream.zalloc = zalloc;
+    d_stream.zfree = zfree;
+    d_stream.opaque = (voidpf)0;
+
+    d_stream.next_in  = compr;
+    d_stream.avail_in = 2; /* just read the zlib header */
+
+    err = inflateInit(&d_stream);
+    CHECK_ERR(err, "inflateInit");
+
+    d_stream.next_out = uncompr;
+    d_stream.avail_out = (uInt)uncomprLen;
+
+    inflate(&d_stream, Z_NO_FLUSH);
+    CHECK_ERR(err, "inflate");
+
+    d_stream.avail_in = (uInt)comprLen-2;   /* read all compressed data */
+    err = inflateSync(&d_stream);           /* but skip the damaged part */
+    CHECK_ERR(err, "inflateSync");
+
+    err = inflate(&d_stream, Z_FINISH);
+    if (err != Z_DATA_ERROR) {
+        fprintf(stderr, "inflate should report DATA_ERROR\n");
+        /* Because of incorrect adler32 */
+        exit(1);
+    }
+    err = inflateEnd(&d_stream);
+    CHECK_ERR(err, "inflateEnd");
+
+    printf("after inflateSync(): hel%s\n", (char *)uncompr);
+}
+
+/* ===========================================================================
+ * Test deflate() with preset dictionary
+ */
+void test_dict_deflate(compr, comprLen)
+    Byte *compr;
+    uLong comprLen;
+{
+    z_stream c_stream; /* compression stream */
+    int err;
+
+    c_stream.zalloc = zalloc;
+    c_stream.zfree = zfree;
+    c_stream.opaque = (voidpf)0;
+
+    err = deflateInit(&c_stream, Z_BEST_COMPRESSION);
+    CHECK_ERR(err, "deflateInit");
+
+    err = deflateSetDictionary(&c_stream,
+                (const Bytef*)dictionary, (int)sizeof(dictionary));
+    CHECK_ERR(err, "deflateSetDictionary");
+
+    dictId = c_stream.adler;
+    c_stream.next_out = compr;
+    c_stream.avail_out = (uInt)comprLen;
+
+    c_stream.next_in = (Bytef*)hello;
+    c_stream.avail_in = (uInt)strlen(hello)+1;
+
+    err = deflate(&c_stream, Z_FINISH);
+    if (err != Z_STREAM_END) {
+        fprintf(stderr, "deflate should report Z_STREAM_END\n");
+        exit(1);
+    }
+    err = deflateEnd(&c_stream);
+    CHECK_ERR(err, "deflateEnd");
+}
+
+/* ===========================================================================
+ * Test inflate() with a preset dictionary
+ */
+void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
+    Byte *compr, *uncompr;
+    uLong comprLen, uncomprLen;
+{
+    int err;
+    z_stream d_stream; /* decompression stream */
+
+    strcpy((char*)uncompr, "garbage");
+
+    d_stream.zalloc = zalloc;
+    d_stream.zfree = zfree;
+    d_stream.opaque = (voidpf)0;
+
+    d_stream.next_in  = compr;
+    d_stream.avail_in = (uInt)comprLen;
+
+    err = inflateInit(&d_stream);
+    CHECK_ERR(err, "inflateInit");
+
+    d_stream.next_out = uncompr;
+    d_stream.avail_out = (uInt)uncomprLen;
+
+    for (;;) {
+        err = inflate(&d_stream, Z_NO_FLUSH);
+        if (err == Z_STREAM_END) break;
+        if (err == Z_NEED_DICT) {
+            if (d_stream.adler != dictId) {
+                fprintf(stderr, "unexpected dictionary");
+                exit(1);
+            }
+            err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
+                                       (int)sizeof(dictionary));
+        }
+        CHECK_ERR(err, "inflate with dict");
+    }
+
+    err = inflateEnd(&d_stream);
+    CHECK_ERR(err, "inflateEnd");
+
+    if (strcmp((char*)uncompr, hello)) {
+        fprintf(stderr, "bad inflate with dict\n");
+        exit(1);
+    } else {
+        printf("inflate with dictionary: %s\n", (char *)uncompr);
+    }
+}
+
+/* ===========================================================================
+ * Usage:  example [output.gz  [input.gz]]
+ */
+
+int main(argc, argv)
+    int argc;
+    char *argv[];
+{
+    Byte *compr, *uncompr;
+    uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */
+    uLong uncomprLen = comprLen;
+    static const char* myVersion = ZLIB_VERSION;
+
+    if (zlibVersion()[0] != myVersion[0]) {
+        fprintf(stderr, "incompatible zlib version\n");
+        exit(1);
+
+    } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) {
+        fprintf(stderr, "warning: different zlib version\n");
+    }
+
+    printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n",
+            ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags());
+
+    compr    = (Byte*)calloc((uInt)comprLen, 1);
+    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
+    /* compr and uncompr are cleared to avoid reading uninitialized
+     * data and to ensure that uncompr compresses well.
+     */
+    if (compr == Z_NULL || uncompr == Z_NULL) {
+        printf("out of memory\n");
+        exit(1);
+    }
+
+#ifdef Z_SOLO
+    argc = strlen(argv[0]);
+#else
+    test_compress(compr, comprLen, uncompr, uncomprLen);
+
+    test_gzio((argc > 1 ? argv[1] : TESTFILE),
+              uncompr, uncomprLen);
+#endif
+
+    test_deflate(compr, comprLen);
+    test_inflate(compr, comprLen, uncompr, uncomprLen);
+
+    test_large_deflate(compr, comprLen, uncompr, uncomprLen);
+    test_large_inflate(compr, comprLen, uncompr, uncomprLen);
+
+    test_flush(compr, &comprLen);
+    test_sync(compr, comprLen, uncompr, uncomprLen);
+    comprLen = uncomprLen;
+
+    test_dict_deflate(compr, comprLen);
+    test_dict_inflate(compr, comprLen, uncompr, uncomprLen);
+
+    free(compr);
+    free(uncompr);
+
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/infcover.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/infcover.c
new file mode 100644 (file)
index 0000000..fe3d920
--- /dev/null
@@ -0,0 +1,671 @@
+/* infcover.c -- test zlib's inflate routines with full code coverage
+ * Copyright (C) 2011 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* to use, do: ./configure --cover && make cover */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include "zlib.h"
+
+/* get definition of internal structure so we can mess with it (see pull()),
+   and so we can call inflate_trees() (see cover5()) */
+#define ZLIB_INTERNAL
+#include "inftrees.h"
+#include "inflate.h"
+
+#define local static
+
+/* -- memory tracking routines -- */
+
+/*
+   These memory tracking routines are provided to zlib and track all of zlib's
+   allocations and deallocations, check for LIFO operations, keep a current
+   and high water mark of total bytes requested, optionally set a limit on the
+   total memory that can be allocated, and when done check for memory leaks.
+
+   They are used as follows:
+
+   z_stream strm;
+   mem_setup(&strm)         initializes the memory tracking and sets the
+                            zalloc, zfree, and opaque members of strm to use
+                            memory tracking for all zlib operations on strm
+   mem_limit(&strm, limit)  sets a limit on the total bytes requested -- a
+                            request that exceeds this limit will result in an
+                            allocation failure (returns NULL) -- setting the
+                            limit to zero means no limit, which is the default
+                            after mem_setup()
+   mem_used(&strm, "msg")   prints to stderr "msg" and the total bytes used
+   mem_high(&strm, "msg")   prints to stderr "msg" and the high water mark
+   mem_done(&strm, "msg")   ends memory tracking, releases all allocations
+                            for the tracking as well as leaked zlib blocks, if
+                            any.  If there was anything unusual, such as leaked
+                            blocks, non-FIFO frees, or frees of addresses not
+                            allocated, then "msg" and information about the
+                            problem is printed to stderr.  If everything is
+                            normal, nothing is printed. mem_done resets the
+                            strm members to Z_NULL to use the default memory
+                            allocation routines on the next zlib initialization
+                            using strm.
+ */
+
+/* these items are strung together in a linked list, one for each allocation */
+struct mem_item {
+    void *ptr;                  /* pointer to allocated memory */
+    size_t size;                /* requested size of allocation */
+    struct mem_item *next;      /* pointer to next item in list, or NULL */
+};
+
+/* this structure is at the root of the linked list, and tracks statistics */
+struct mem_zone {
+    struct mem_item *first;     /* pointer to first item in list, or NULL */
+    size_t total, highwater;    /* total allocations, and largest total */
+    size_t limit;               /* memory allocation limit, or 0 if no limit */
+    int notlifo, rogue;         /* counts of non-LIFO frees and rogue frees */
+};
+
+/* memory allocation routine to pass to zlib */
+local void *mem_alloc(void *mem, unsigned count, unsigned size)
+{
+    void *ptr;
+    struct mem_item *item;
+    struct mem_zone *zone = mem;
+    size_t len = count * (size_t)size;
+
+    /* induced allocation failure */
+    if (zone == NULL || (zone->limit && zone->total + len > zone->limit))
+        return NULL;
+
+    /* perform allocation using the standard library, fill memory with a
+       non-zero value to make sure that the code isn't depending on zeros */
+    ptr = malloc(len);
+    if (ptr == NULL)
+        return NULL;
+    memset(ptr, 0xa5, len);
+
+    /* create a new item for the list */
+    item = malloc(sizeof(struct mem_item));
+    if (item == NULL) {
+        free(ptr);
+        return NULL;
+    }
+    item->ptr = ptr;
+    item->size = len;
+
+    /* insert item at the beginning of the list */
+    item->next = zone->first;
+    zone->first = item;
+
+    /* update the statistics */
+    zone->total += item->size;
+    if (zone->total > zone->highwater)
+        zone->highwater = zone->total;
+
+    /* return the allocated memory */
+    return ptr;
+}
+
+/* memory free routine to pass to zlib */
+local void mem_free(void *mem, void *ptr)
+{
+    struct mem_item *item, *next;
+    struct mem_zone *zone = mem;
+
+    /* if no zone, just do a free */
+    if (zone == NULL) {
+        free(ptr);
+        return;
+    }
+
+    /* point next to the item that matches ptr, or NULL if not found -- remove
+       the item from the linked list if found */
+    next = zone->first;
+    if (next) {
+        if (next->ptr == ptr)
+            zone->first = next->next;   /* first one is it, remove from list */
+        else {
+            do {                        /* search the linked list */
+                item = next;
+                next = item->next;
+            } while (next != NULL && next->ptr != ptr);
+            if (next) {                 /* if found, remove from linked list */
+                item->next = next->next;
+                zone->notlifo++;        /* not a LIFO free */
+            }
+
+        }
+    }
+
+    /* if found, update the statistics and free the item */
+    if (next) {
+        zone->total -= next->size;
+        free(next);
+    }
+
+    /* if not found, update the rogue count */
+    else
+        zone->rogue++;
+
+    /* in any case, do the requested free with the standard library function */
+    free(ptr);
+}
+
+/* set up a controlled memory allocation space for monitoring, set the stream
+   parameters to the controlled routines, with opaque pointing to the space */
+local void mem_setup(z_stream *strm)
+{
+    struct mem_zone *zone;
+
+    zone = malloc(sizeof(struct mem_zone));
+    assert(zone != NULL);
+    zone->first = NULL;
+    zone->total = 0;
+    zone->highwater = 0;
+    zone->limit = 0;
+    zone->notlifo = 0;
+    zone->rogue = 0;
+    strm->opaque = zone;
+    strm->zalloc = mem_alloc;
+    strm->zfree = mem_free;
+}
+
+/* set a limit on the total memory allocation, or 0 to remove the limit */
+local void mem_limit(z_stream *strm, size_t limit)
+{
+    struct mem_zone *zone = strm->opaque;
+
+    zone->limit = limit;
+}
+
+/* show the current total requested allocations in bytes */
+local void mem_used(z_stream *strm, char *prefix)
+{
+    struct mem_zone *zone = strm->opaque;
+
+    fprintf(stderr, "%s: %lu allocated\n", prefix, zone->total);
+}
+
+/* show the high water allocation in bytes */
+local void mem_high(z_stream *strm, char *prefix)
+{
+    struct mem_zone *zone = strm->opaque;
+
+    fprintf(stderr, "%s: %lu high water mark\n", prefix, zone->highwater);
+}
+
+/* release the memory allocation zone -- if there are any surprises, notify */
+local void mem_done(z_stream *strm, char *prefix)
+{
+    int count = 0;
+    struct mem_item *item, *next;
+    struct mem_zone *zone = strm->opaque;
+
+    /* show high water mark */
+    mem_high(strm, prefix);
+
+    /* free leftover allocations and item structures, if any */
+    item = zone->first;
+    while (item != NULL) {
+        free(item->ptr);
+        next = item->next;
+        free(item);
+        item = next;
+        count++;
+    }
+
+    /* issue alerts about anything unexpected */
+    if (count || zone->total)
+        fprintf(stderr, "** %s: %lu bytes in %d blocks not freed\n",
+                prefix, zone->total, count);
+    if (zone->notlifo)
+        fprintf(stderr, "** %s: %d frees not LIFO\n", prefix, zone->notlifo);
+    if (zone->rogue)
+        fprintf(stderr, "** %s: %d frees not recognized\n",
+                prefix, zone->rogue);
+
+    /* free the zone and delete from the stream */
+    free(zone);
+    strm->opaque = Z_NULL;
+    strm->zalloc = Z_NULL;
+    strm->zfree = Z_NULL;
+}
+
+/* -- inflate test routines -- */
+
+/* Decode a hexadecimal string, set *len to length, in[] to the bytes.  This
+   decodes liberally, in that hex digits can be adjacent, in which case two in
+   a row writes a byte.  Or they can delimited by any non-hex character, where
+   the delimiters are ignored except when a single hex digit is followed by a
+   delimiter in which case that single digit writes a byte.  The returned
+   data is allocated and must eventually be freed.  NULL is returned if out of
+   memory.  If the length is not needed, then len can be NULL. */
+local unsigned char *h2b(const char *hex, unsigned *len)
+{
+    unsigned char *in;
+    unsigned next, val;
+
+    in = malloc((strlen(hex) + 1) >> 1);
+    if (in == NULL)
+        return NULL;
+    next = 0;
+    val = 1;
+    do {
+        if (*hex >= '0' && *hex <= '9')
+            val = (val << 4) + *hex - '0';
+        else if (*hex >= 'A' && *hex <= 'F')
+            val = (val << 4) + *hex - 'A' + 10;
+        else if (*hex >= 'a' && *hex <= 'f')
+            val = (val << 4) + *hex - 'a' + 10;
+        else if (val != 1 && val < 32)  /* one digit followed by delimiter */
+            val += 240;                 /* make it look like two digits */
+        if (val > 255) {                /* have two digits */
+            in[next++] = val & 0xff;    /* save the decoded byte */
+            val = 1;                    /* start over */
+        }
+    } while (*hex++);       /* go through the loop with the terminating null */
+    if (len != NULL)
+        *len = next;
+    in = reallocf(in, next);
+    return in;
+}
+
+/* generic inflate() run, where hex is the hexadecimal input data, what is the
+   text to include in an error message, step is how much input data to feed
+   inflate() on each call, or zero to feed it all, win is the window bits
+   parameter to inflateInit2(), len is the size of the output buffer, and err
+   is the error code expected from the first inflate() call (the second
+   inflate() call is expected to return Z_STREAM_END).  If win is 47, then
+   header information is collected with inflateGetHeader().  If a zlib stream
+   is looking for a dictionary, then an empty dictionary is provided.
+   inflate() is run until all of the input data is consumed. */
+local void inf(char *hex, char *what, unsigned step, int win, unsigned len,
+               int err)
+{
+    int ret;
+    unsigned have;
+    unsigned char *in, *out;
+    z_stream strm, copy;
+    gz_header head;
+
+    mem_setup(&strm);
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit2(&strm, win);
+    if (ret != Z_OK) {
+        mem_done(&strm, what);
+        return;
+    }
+    out = malloc(len);                          assert(out != NULL);
+    if (win == 47) {
+        head.extra = out;
+        head.extra_max = len;
+        head.name = out;
+        head.name_max = len;
+        head.comment = out;
+        head.comm_max = len;
+        ret = inflateGetHeader(&strm, &head);   assert(ret == Z_OK);
+    }
+    in = h2b(hex, &have);                       assert(in != NULL);
+    if (step == 0 || step > have)
+        step = have;
+    strm.avail_in = step;
+    have -= step;
+    strm.next_in = in;
+    do {
+        strm.avail_out = len;
+        strm.next_out = out;
+        ret = inflate(&strm, Z_NO_FLUSH);       assert(err == 9 || ret == err);
+        if (ret != Z_OK && ret != Z_BUF_ERROR && ret != Z_NEED_DICT)
+            break;
+        if (ret == Z_NEED_DICT) {
+            ret = inflateSetDictionary(&strm, in, 1);
+                                                assert(ret == Z_DATA_ERROR);
+            mem_limit(&strm, 1);
+            ret = inflateSetDictionary(&strm, out, 0);
+                                                assert(ret == Z_MEM_ERROR);
+            mem_limit(&strm, 0);
+            ((struct inflate_state *)strm.state)->mode = DICT;
+            ret = inflateSetDictionary(&strm, out, 0);
+                                                assert(ret == Z_OK);
+            ret = inflate(&strm, Z_NO_FLUSH);   assert(ret == Z_BUF_ERROR);
+        }
+        ret = inflateCopy(&copy, &strm);        assert(ret == Z_OK);
+        ret = inflateEnd(&copy);                assert(ret == Z_OK);
+        err = 9;                        /* don't care next time around */
+        have += strm.avail_in;
+        strm.avail_in = step > have ? have : step;
+        have -= strm.avail_in;
+    } while (strm.avail_in);
+    free(in);
+    free(out);
+    ret = inflateReset2(&strm, -8);             assert(ret == Z_OK);
+    ret = inflateEnd(&strm);                    assert(ret == Z_OK);
+    mem_done(&strm, what);
+}
+
+/* cover all of the lines in inflate.c up to inflate() */
+local void cover_support(void)
+{
+    int ret;
+    z_stream strm;
+
+    mem_setup(&strm);
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit(&strm);                   assert(ret == Z_OK);
+    mem_used(&strm, "inflate init");
+    ret = inflatePrime(&strm, 5, 31);           assert(ret == Z_OK);
+    ret = inflatePrime(&strm, -1, 0);           assert(ret == Z_OK);
+    ret = inflateSetDictionary(&strm, Z_NULL, 0);
+                                                assert(ret == Z_STREAM_ERROR);
+    ret = inflateEnd(&strm);                    assert(ret == Z_OK);
+    mem_done(&strm, "prime");
+
+    inf("63 0", "force window allocation", 0, -15, 1, Z_OK);
+    inf("63 18 5", "force window replacement", 0, -8, 259, Z_OK);
+    inf("63 18 68 30 d0 0 0", "force split window update", 4, -8, 259, Z_OK);
+    inf("3 0", "use fixed blocks", 0, -15, 1, Z_STREAM_END);
+    inf("", "bad window size", 0, 1, 0, Z_STREAM_ERROR);
+
+    mem_setup(&strm);
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit_(&strm, ZLIB_VERSION - 1, (int)sizeof(z_stream));
+                                                assert(ret == Z_VERSION_ERROR);
+    mem_done(&strm, "wrong version");
+
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit(&strm);                   assert(ret == Z_OK);
+    ret = inflateEnd(&strm);                    assert(ret == Z_OK);
+    fputs("inflate built-in memory routines\n", stderr);
+}
+
+/* cover all inflate() header and trailer cases and code after inflate() */
+local void cover_wrap(void)
+{
+    int ret;
+    z_stream strm, copy;
+    unsigned char dict[257];
+
+    ret = inflate(Z_NULL, 0);                   assert(ret == Z_STREAM_ERROR);
+    ret = inflateEnd(Z_NULL);                   assert(ret == Z_STREAM_ERROR);
+    ret = inflateCopy(Z_NULL, Z_NULL);          assert(ret == Z_STREAM_ERROR);
+    fputs("inflate bad parameters\n", stderr);
+
+    inf("1f 8b 0 0", "bad gzip method", 0, 31, 0, Z_DATA_ERROR);
+    inf("1f 8b 8 80", "bad gzip flags", 0, 31, 0, Z_DATA_ERROR);
+    inf("77 85", "bad zlib method", 0, 15, 0, Z_DATA_ERROR);
+    inf("8 99", "set window size from header", 0, 0, 0, Z_OK);
+    inf("78 9c", "bad zlib window size", 0, 8, 0, Z_DATA_ERROR);
+    inf("78 9c 63 0 0 0 1 0 1", "check adler32", 0, 15, 1, Z_STREAM_END);
+    inf("1f 8b 8 1e 0 0 0 0 0 0 1 0 0 0 0 0 0", "bad header crc", 0, 47, 1,
+        Z_DATA_ERROR);
+    inf("1f 8b 8 2 0 0 0 0 0 0 1d 26 3 0 0 0 0 0 0 0 0 0", "check gzip length",
+        0, 47, 0, Z_STREAM_END);
+    inf("78 90", "bad zlib header check", 0, 47, 0, Z_DATA_ERROR);
+    inf("8 b8 0 0 0 1", "need dictionary", 0, 8, 0, Z_NEED_DICT);
+    inf("78 9c 63 0", "compute adler32", 0, 15, 1, Z_OK);
+
+    mem_setup(&strm);
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit2(&strm, -8);
+    strm.avail_in = 2;
+    strm.next_in = (void *)"\x63";
+    strm.avail_out = 1;
+    strm.next_out = (void *)&ret;
+    mem_limit(&strm, 1);
+    ret = inflate(&strm, Z_NO_FLUSH);           assert(ret == Z_MEM_ERROR);
+    ret = inflate(&strm, Z_NO_FLUSH);           assert(ret == Z_MEM_ERROR);
+    mem_limit(&strm, 0);
+    memset(dict, 0, 257);
+    ret = inflateSetDictionary(&strm, dict, 257);
+                                                assert(ret == Z_OK);
+    mem_limit(&strm, (sizeof(struct inflate_state) << 1) + 256);
+    ret = inflatePrime(&strm, 16, 0);           assert(ret == Z_OK);
+    strm.avail_in = 2;
+    strm.next_in = (void *)"\x80";
+    ret = inflateSync(&strm);                   assert(ret == Z_DATA_ERROR);
+    ret = inflate(&strm, Z_NO_FLUSH);           assert(ret == Z_STREAM_ERROR);
+    strm.avail_in = 4;
+    strm.next_in = (void *)"\0\0\xff\xff";
+    ret = inflateSync(&strm);                   assert(ret == Z_OK);
+    (void)inflateSyncPoint(&strm);
+    ret = inflateCopy(&copy, &strm);            assert(ret == Z_MEM_ERROR);
+    mem_limit(&strm, 0);
+    ret = inflateUndermine(&strm, 1);           assert(ret == Z_DATA_ERROR);
+    (void)inflateMark(&strm);
+    ret = inflateEnd(&strm);                    assert(ret == Z_OK);
+    mem_done(&strm, "miscellaneous, force memory errors");
+}
+
+/* input and output functions for inflateBack() */
+local unsigned pull(void *desc, unsigned char **buf)
+{
+    static unsigned int next = 0;
+    static unsigned char dat[] = {0x63, 0, 2, 0};
+    struct inflate_state *state;
+
+    if (desc == Z_NULL) {
+        next = 0;
+        return 0;   /* no input (already provided at next_in) */
+    }
+    state = (void *)((z_stream *)desc)->state;
+    if (state != Z_NULL)
+        state->mode = SYNC;     /* force an otherwise impossible situation */
+    return next < sizeof(dat) ? (*buf = dat + next++, 1) : 0;
+}
+
+local int push(void *desc, unsigned char *buf, unsigned len)
+{
+    buf += len;
+    return desc != Z_NULL;      /* force error if desc not null */
+}
+
+/* cover inflateBack() up to common deflate data cases and after those */
+local void cover_back(void)
+{
+    int ret;
+    z_stream strm;
+    unsigned char win[32768];
+
+    ret = inflateBackInit_(Z_NULL, 0, win, 0, 0);
+                                                assert(ret == Z_VERSION_ERROR);
+    ret = inflateBackInit(Z_NULL, 0, win);      assert(ret == Z_STREAM_ERROR);
+    ret = inflateBack(Z_NULL, Z_NULL, Z_NULL, Z_NULL, Z_NULL);
+                                                assert(ret == Z_STREAM_ERROR);
+    ret = inflateBackEnd(Z_NULL);               assert(ret == Z_STREAM_ERROR);
+    fputs("inflateBack bad parameters\n", stderr);
+
+    mem_setup(&strm);
+    ret = inflateBackInit(&strm, 15, win);      assert(ret == Z_OK);
+    strm.avail_in = 2;
+    strm.next_in = (void *)"\x03";
+    ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL);
+                                                assert(ret == Z_STREAM_END);
+        /* force output error */
+    strm.avail_in = 3;
+    strm.next_in = (void *)"\x63\x00";
+    ret = inflateBack(&strm, pull, Z_NULL, push, &strm);
+                                                assert(ret == Z_BUF_ERROR);
+        /* force mode error by mucking with state */
+    ret = inflateBack(&strm, pull, &strm, push, Z_NULL);
+                                                assert(ret == Z_STREAM_ERROR);
+    ret = inflateBackEnd(&strm);                assert(ret == Z_OK);
+    mem_done(&strm, "inflateBack bad state");
+
+    ret = inflateBackInit(&strm, 15, win);      assert(ret == Z_OK);
+    ret = inflateBackEnd(&strm);                assert(ret == Z_OK);
+    fputs("inflateBack built-in memory routines\n", stderr);
+}
+
+/* do a raw inflate of data in hexadecimal with both inflate and inflateBack */
+local int try(char *hex, char *id, int err)
+{
+    int ret;
+    unsigned len, size;
+    unsigned char *in, *out, *win;
+    char *prefix;
+    z_stream strm;
+
+    /* convert to hex */
+    in = h2b(hex, &len);
+    assert(in != NULL);
+
+    /* allocate work areas */
+    size = len << 3;
+    out = malloc(size);
+    assert(out != NULL);
+    win = malloc(32768);
+    assert(win != NULL);
+    prefix = malloc(strlen(id) + 6);
+    assert(prefix != NULL);
+
+    /* first with inflate */
+    strcpy(prefix, id);
+    strcat(prefix, "-late");
+    mem_setup(&strm);
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit2(&strm, err < 0 ? 47 : -15);
+    assert(ret == Z_OK);
+    strm.avail_in = len;
+    strm.next_in = in;
+    do {
+        strm.avail_out = size;
+        strm.next_out = out;
+        ret = inflate(&strm, Z_TREES);
+        assert(ret != Z_STREAM_ERROR && ret != Z_MEM_ERROR);
+        if (ret == Z_DATA_ERROR || ret == Z_NEED_DICT)
+            break;
+    } while (strm.avail_in || strm.avail_out == 0);
+    if (err) {
+        assert(ret == Z_DATA_ERROR);
+        assert(strcmp(id, strm.msg) == 0);
+    }
+    inflateEnd(&strm);
+    mem_done(&strm, prefix);
+
+    /* then with inflateBack */
+    if (err >= 0) {
+        strcpy(prefix, id);
+        strcat(prefix, "-back");
+        mem_setup(&strm);
+        ret = inflateBackInit(&strm, 15, win);
+        assert(ret == Z_OK);
+        strm.avail_in = len;
+        strm.next_in = in;
+        ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL);
+        assert(ret != Z_STREAM_ERROR);
+        if (err) {
+            assert(ret == Z_DATA_ERROR);
+            assert(strcmp(id, strm.msg) == 0);
+        }
+        inflateBackEnd(&strm);
+        mem_done(&strm, prefix);
+    }
+
+    /* clean up */
+    free(prefix);
+    free(win);
+    free(out);
+    free(in);
+    return ret;
+}
+
+/* cover deflate data cases in both inflate() and inflateBack() */
+local void cover_inflate(void)
+{
+    try("0 0 0 0 0", "invalid stored block lengths", 1);
+    try("3 0", "fixed", 0);
+    try("6", "invalid block type", 1);
+    try("1 1 0 fe ff 0", "stored", 0);
+    try("fc 0 0", "too many length or distance symbols", 1);
+    try("4 0 fe ff", "invalid code lengths set", 1);
+    try("4 0 24 49 0", "invalid bit length repeat", 1);
+    try("4 0 24 e9 ff ff", "invalid bit length repeat", 1);
+    try("4 0 24 e9 ff 6d", "invalid code -- missing end-of-block", 1);
+    try("4 80 49 92 24 49 92 24 71 ff ff 93 11 0",
+        "invalid literal/lengths set", 1);
+    try("4 80 49 92 24 49 92 24 f b4 ff ff c3 84", "invalid distances set", 1);
+    try("4 c0 81 8 0 0 0 0 20 7f eb b 0 0", "invalid literal/length code", 1);
+    try("2 7e ff ff", "invalid distance code", 1);
+    try("c c0 81 0 0 0 0 0 90 ff 6b 4 0", "invalid distance too far back", 1);
+
+    /* also trailer mismatch just in inflate() */
+    try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 1", "incorrect data check", -1);
+    try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 1",
+        "incorrect length check", -1);
+    try("5 c0 21 d 0 0 0 80 b0 fe 6d 2f 91 6c", "pull 17", 0);
+    try("5 e0 81 91 24 cb b2 2c 49 e2 f 2e 8b 9a 47 56 9f fb fe ec d2 ff 1f",
+        "long code", 0);
+    try("ed c0 1 1 0 0 0 40 20 ff 57 1b 42 2c 4f", "length extra", 0);
+    try("ed cf c1 b1 2c 47 10 c4 30 fa 6f 35 1d 1 82 59 3d fb be 2e 2a fc f c",
+        "long distance and extra", 0);
+    try("ed c0 81 0 0 0 0 80 a0 fd a9 17 a9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "
+        "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6", "window end", 0);
+    inf("2 8 20 80 0 3 0", "inflate_fast TYPE return", 0, -15, 258,
+        Z_STREAM_END);
+    inf("63 18 5 40 c 0", "window wrap", 3, -8, 300, Z_OK);
+}
+
+/* cover remaining lines in inftrees.c */
+local void cover_trees(void)
+{
+    int ret;
+    unsigned bits;
+    unsigned short lens[16], work[16];
+    code *next, table[ENOUGH_DISTS];
+
+    /* we need to call inflate_table() directly in order to manifest not-
+       enough errors, since zlib insures that enough is always enough */
+    for (bits = 0; bits < 15; bits++)
+        lens[bits] = (unsigned short)(bits + 1);
+    lens[15] = 15;
+    next = table;
+    bits = 15;
+    ret = inflate_table(DISTS, lens, 16, &next, &bits, work);
+                                                assert(ret == 1);
+    next = table;
+    bits = 1;
+    ret = inflate_table(DISTS, lens, 16, &next, &bits, work);
+                                                assert(ret == 1);
+    fputs("inflate_table not enough errors\n", stderr);
+}
+
+/* cover remaining inffast.c decoding and window copying */
+local void cover_fast(void)
+{
+    inf("e5 e0 81 ad 6d cb b2 2c c9 01 1e 59 63 ae 7d ee fb 4d fd b5 35 41 68"
+        " ff 7f 0f 0 0 0", "fast length extra bits", 0, -8, 258, Z_DATA_ERROR);
+    inf("25 fd 81 b5 6d 59 b6 6a 49 ea af 35 6 34 eb 8c b9 f6 b9 1e ef 67 49"
+        " 50 fe ff ff 3f 0 0", "fast distance extra bits", 0, -8, 258,
+        Z_DATA_ERROR);
+    inf("3 7e 0 0 0 0 0", "fast invalid distance code", 0, -8, 258,
+        Z_DATA_ERROR);
+    inf("1b 7 0 0 0 0 0", "fast invalid literal/length code", 0, -8, 258,
+        Z_DATA_ERROR);
+    inf("d c7 1 ae eb 38 c 4 41 a0 87 72 de df fb 1f b8 36 b1 38 5d ff ff 0",
+        "fast 2nd level codes and too far back", 0, -8, 258, Z_DATA_ERROR);
+    inf("63 18 5 8c 10 8 0 0 0 0", "very common case", 0, -8, 259, Z_OK);
+    inf("63 60 60 18 c9 0 8 18 18 18 26 c0 28 0 29 0 0 0",
+        "contiguous and wrap around window", 6, -8, 259, Z_OK);
+    inf("63 0 3 0 0 0 0 0", "copy direct from output", 0, -8, 259,
+        Z_STREAM_END);
+}
+
+int main(void)
+{
+    fprintf(stderr, "%s\n", zlibVersion());
+    cover_support();
+    cover_wrap();
+    cover_back();
+    cover_inflate();
+    cover_trees();
+    cover_fast();
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/minigzip.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/test/minigzip.c
new file mode 100644 (file)
index 0000000..8317344
--- /dev/null
@@ -0,0 +1,631 @@
+/* minigzip.c -- simulate gzip using the zlib compression library
+ * Copyright (C) 1995-2006, 2010, 2011 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ * minigzip is a minimal implementation of the gzip utility. This is
+ * only an example of using zlib and isn't meant to replace the
+ * full-featured gzip. No attempt is made to deal with file systems
+ * limiting names to 14 or 8+3 characters, etc... Error checking is
+ * very limited. So use minigzip only for testing; use gzip for the
+ * real thing. On MSDOS, use only on file names without extension
+ * or in pipe mode.
+ */
+
+/* @(#) $Id$ */
+
+#include "zlib.h"
+#include <stdio.h>
+
+#ifdef STDC
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+
+#ifdef USE_MMAP
+#  include <sys/types.h>
+#  include <sys/mman.h>
+#  include <sys/stat.h>
+#endif
+
+#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
+#  include <fcntl.h>
+#  include <io.h>
+#  ifdef UNDER_CE
+#    include <stdlib.h>
+#  endif
+#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+#else
+#  define SET_BINARY_MODE(file)
+#endif
+
+#ifdef VMS
+#  define unlink delete
+#  define GZ_SUFFIX "-gz"
+#endif
+#ifdef RISCOS
+#  define unlink remove
+#  define GZ_SUFFIX "-gz"
+#  define fileno(file) file->__file
+#endif
+#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
+#  include <unix.h> /* for fileno */
+#endif
+
+#if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE)
+#ifndef WIN32 /* unlink already in stdio.h for WIN32 */
+  extern int unlink OF((const char *));
+#endif
+#endif
+
+#if defined(UNDER_CE)
+#  include <windows.h>
+#  define perror(s) pwinerror(s)
+
+/* Map the Windows error number in ERROR to a locale-dependent error
+   message string and return a pointer to it.  Typically, the values
+   for ERROR come from GetLastError.
+
+   The string pointed to shall not be modified by the application,
+   but may be overwritten by a subsequent call to strwinerror
+
+   The strwinerror function does not change the current setting
+   of GetLastError.  */
+
+static char *strwinerror (error)
+     DWORD error;
+{
+    static char buf[1024];
+
+    wchar_t *msgbuf;
+    DWORD lasterr = GetLastError();
+    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
+        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+        NULL,
+        error,
+        0, /* Default language */
+        (LPVOID)&msgbuf,
+        0,
+        NULL);
+    if (chars != 0) {
+        /* If there is an \r\n appended, zap it.  */
+        if (chars >= 2
+            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
+            chars -= 2;
+            msgbuf[chars] = 0;
+        }
+
+        if (chars > sizeof (buf) - 1) {
+            chars = sizeof (buf) - 1;
+            msgbuf[chars] = 0;
+        }
+
+        wcstombs(buf, msgbuf, chars + 1);
+        LocalFree(msgbuf);
+    }
+    else {
+        sprintf(buf, "unknown win32 error (%ld)", error);
+    }
+
+    SetLastError(lasterr);
+    return buf;
+}
+
+static void pwinerror (s)
+    const char *s;
+{
+    if (s && *s)
+        fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ()));
+    else
+        fprintf(stderr, "%s\n", strwinerror(GetLastError ()));
+}
+
+#endif /* UNDER_CE */
+
+#ifndef GZ_SUFFIX
+#  define GZ_SUFFIX ".gz"
+#endif
+#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1)
+
+#define BUFLEN      16384
+#define MAX_NAME_LEN 1024
+
+#ifdef MAXSEG_64K
+#  define local static
+   /* Needed for systems with limitation on stack size. */
+#else
+#  define local
+#endif
+
+#ifdef Z_SOLO
+/* for Z_SOLO, create simplified gz* functions using deflate and inflate */
+
+#if defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE)
+#  include <unistd.h>       /* for unlink() */
+#endif
+
+void *myalloc OF((void *, unsigned, unsigned));
+void myfree OF((void *, void *));
+
+void *myalloc(q, n, m)
+    void *q;
+    unsigned n, m;
+{
+    q = Z_NULL;
+    return calloc(n, m);
+}
+
+void myfree(q, p)
+    void *q, *p;
+{
+    q = Z_NULL;
+    free(p);
+}
+
+typedef struct gzFile_s {
+    FILE *file;
+    int write;
+    int err;
+    char *msg;
+    z_stream strm;
+} *gzFile;
+
+gzFile gzopen OF((const char *, const char *));
+gzFile gzdopen OF((int, const char *));
+gzFile gz_open OF((const char *, int, const char *));
+
+gzFile gzopen(path, mode)
+const char *path;
+const char *mode;
+{
+    return gz_open(path, -1, mode);
+}
+
+gzFile gzdopen(fd, mode)
+int fd;
+const char *mode;
+{
+    return gz_open(NULL, fd, mode);
+}
+
+gzFile gz_open(path, fd, mode)
+    const char *path;
+    int fd;
+    const char *mode;
+{
+    gzFile gz;
+    int ret;
+
+    gz = malloc(sizeof(gzFile));
+    if (gz == NULL)
+        return NULL;
+    gz->write = strchr(mode, 'w') != NULL;
+    gz->strm.zalloc = myalloc;
+    gz->strm.zfree = myfree;
+    gz->strm.opaque = Z_NULL;
+    if (gz->write)
+        ret = deflateInit2(&(gz->strm), -1, 8, 15 + 16, 8, 0);
+    else {
+        gz->strm.next_in = 0;
+        gz->strm.avail_in = Z_NULL;
+        ret = inflateInit2(&(gz->strm), 15 + 16);
+    }
+    if (ret != Z_OK) {
+        free(gz);
+        return NULL;
+    }
+    gz->file = path == NULL ? fdopen(fd, gz->write ? "wb" : "rb") :
+                              fopen(path, gz->write ? "wb" : "rb");
+    if (gz->file == NULL) {
+        gz->write ? deflateEnd(&(gz->strm)) : inflateEnd(&(gz->strm));
+        free(gz);
+        return NULL;
+    }
+    gz->err = 0;
+    gz->msg = "";
+    return gz;
+}
+
+int gzwrite OF((gzFile, const void *, unsigned));
+
+int gzwrite(gz, buf, len)
+    gzFile gz;
+    const void *buf;
+    unsigned len;
+{
+    z_stream *strm;
+    unsigned char out[BUFLEN];
+
+    if (gz == NULL || !gz->write)
+        return 0;
+    strm = &(gz->strm);
+    strm->next_in = (void *)buf;
+    strm->avail_in = len;
+    do {
+        strm->next_out = out;
+        strm->avail_out = BUFLEN;
+        (void)deflate(strm, Z_NO_FLUSH);
+        fwrite(out, 1, BUFLEN - strm->avail_out, gz->file);
+    } while (strm->avail_out == 0);
+    return len;
+}
+
+int gzread OF((gzFile, void *, unsigned));
+
+int gzread(gz, buf, len)
+    gzFile gz;
+    void *buf;
+    unsigned len;
+{
+    int ret;
+    unsigned got;
+    unsigned char in[1];
+    z_stream *strm;
+
+    if (gz == NULL || gz->write)
+        return 0;
+    if (gz->err)
+        return 0;
+    strm = &(gz->strm);
+    strm->next_out = (void *)buf;
+    strm->avail_out = len;
+    do {
+        got = fread(in, 1, 1, gz->file);
+        if (got == 0)
+            break;
+        strm->next_in = in;
+        strm->avail_in = 1;
+        ret = inflate(strm, Z_NO_FLUSH);
+        if (ret == Z_DATA_ERROR) {
+            gz->err = Z_DATA_ERROR;
+            gz->msg = strm->msg;
+            return 0;
+        }
+        if (ret == Z_STREAM_END)
+            inflateReset(strm);
+    } while (strm->avail_out);
+    return len - strm->avail_out;
+}
+
+int gzclose OF((gzFile));
+
+int gzclose(gz)
+    gzFile gz;
+{
+    z_stream *strm;
+    unsigned char out[BUFLEN];
+
+    if (gz == NULL)
+        return Z_STREAM_ERROR;
+    strm = &(gz->strm);
+    if (gz->write) {
+        strm->next_in = Z_NULL;
+        strm->avail_in = 0;
+        do {
+            strm->next_out = out;
+            strm->avail_out = BUFLEN;
+            (void)deflate(strm, Z_FINISH);
+            fwrite(out, 1, BUFLEN - strm->avail_out, gz->file);
+        } while (strm->avail_out == 0);
+        deflateEnd(strm);
+    }
+    else
+        inflateEnd(strm);
+    fclose(gz->file);
+    free(gz);
+    return Z_OK;
+}
+
+const char *gzerror OF((gzFile, int *));
+
+const char *gzerror(gz, err)
+    gzFile gz;
+    int *err;
+{
+    *err = gz->err;
+    return gz->msg;
+}
+
+#endif
+
+char *prog;
+
+void error            OF((const char *msg));
+void gz_compress      OF((FILE   *in, gzFile out));
+#ifdef USE_MMAP
+int  gz_compress_mmap OF((FILE   *in, gzFile out));
+#endif
+void gz_uncompress    OF((gzFile in, FILE   *out));
+void file_compress    OF((char  *file, char *mode));
+void file_uncompress  OF((char  *file));
+int  main             OF((int argc, char *argv[]));
+
+/* ===========================================================================
+ * Display error message and exit
+ */
+void error(msg)
+    const char *msg;
+{
+    fprintf(stderr, "%s: %s\n", prog, msg);
+    exit(1);
+}
+
+/* ===========================================================================
+ * Compress input to output then close both files.
+ */
+
+void gz_compress(in, out)
+    FILE   *in;
+    gzFile out;
+{
+    local char buf[BUFLEN];
+    int len;
+    int err;
+
+#ifdef USE_MMAP
+    /* Try first compressing with mmap. If mmap fails (minigzip used in a
+     * pipe), use the normal fread loop.
+     */
+    if (gz_compress_mmap(in, out) == Z_OK) return;
+#endif
+    for (;;) {
+        len = (int)fread(buf, 1, sizeof(buf), in);
+        if (ferror(in)) {
+            perror("fread");
+            exit(1);
+        }
+        if (len == 0) break;
+
+        if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err));
+    }
+    fclose(in);
+    if (gzclose(out) != Z_OK) error("failed gzclose");
+}
+
+#ifdef USE_MMAP /* MMAP version, Miguel Albrecht <malbrech@eso.org> */
+
+/* Try compressing the input file at once using mmap. Return Z_OK if
+ * if success, Z_ERRNO otherwise.
+ */
+int gz_compress_mmap(in, out)
+    FILE   *in;
+    gzFile out;
+{
+    int len;
+    int err;
+    int ifd = fileno(in);
+    caddr_t buf;    /* mmap'ed buffer for the entire input file */
+    off_t buf_len;  /* length of the input file */
+    struct stat sb;
+
+    /* Determine the size of the file, needed for mmap: */
+    if (fstat(ifd, &sb) < 0) return Z_ERRNO;
+    buf_len = sb.st_size;
+    if (buf_len <= 0) return Z_ERRNO;
+
+    /* Now do the actual mmap: */
+    buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0);
+    if (buf == (caddr_t)(-1)) return Z_ERRNO;
+
+    /* Compress the whole file at once: */
+    len = gzwrite(out, (char *)buf, (unsigned)buf_len);
+
+    if (len != (int)buf_len) error(gzerror(out, &err));
+
+    munmap(buf, buf_len);
+    fclose(in);
+    if (gzclose(out) != Z_OK) error("failed gzclose");
+    return Z_OK;
+}
+#endif /* USE_MMAP */
+
+/* ===========================================================================
+ * Uncompress input to output then close both files.
+ */
+void gz_uncompress(in, out)
+    gzFile in;
+    FILE   *out;
+{
+    local char buf[BUFLEN];
+    int len;
+    int err;
+
+    for (;;) {
+        len = gzread(in, buf, sizeof(buf));
+        if (len < 0) error (gzerror(in, &err));
+        if (len == 0) break;
+
+        if ((int)fwrite(buf, 1, (unsigned)len, out) != len) {
+            error("failed fwrite");
+        }
+    }
+    if (fclose(out)) error("failed fclose");
+
+    if (gzclose(in) != Z_OK) error("failed gzclose");
+}
+
+
+/* ===========================================================================
+ * Compress the given file: create a corresponding .gz file and remove the
+ * original.
+ */
+void file_compress(file, mode)
+    char  *file;
+    char  *mode;
+{
+    local char outfile[MAX_NAME_LEN];
+    FILE  *in;
+    gzFile out;
+
+    if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) {
+        fprintf(stderr, "%s: filename too long\n", prog);
+        exit(1);
+    }
+
+    strcpy(outfile, file);
+    strcat(outfile, GZ_SUFFIX);
+
+    in = fopen(file, "rb");
+    if (in == NULL) {
+        perror(file);
+        exit(1);
+    }
+    out = gzopen(outfile, mode);
+    if (out == NULL) {
+        fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile);
+        exit(1);
+    }
+    gz_compress(in, out);
+
+    unlink(file);
+}
+
+
+/* ===========================================================================
+ * Uncompress the given file and remove the original.
+ */
+void file_uncompress(file)
+    char  *file;
+{
+    local char buf[MAX_NAME_LEN];
+    char *infile, *outfile;
+    FILE  *out;
+    gzFile in;
+    size_t len = strlen(file);
+
+    if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) {
+        fprintf(stderr, "%s: filename too long\n", prog);
+        exit(1);
+    }
+
+    strcpy(buf, file);
+
+    if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) {
+        infile = file;
+        outfile = buf;
+        outfile[len-3] = '\0';
+    } else {
+        outfile = file;
+        infile = buf;
+        strcat(infile, GZ_SUFFIX);
+    }
+    in = gzopen(infile, "rb");
+    if (in == NULL) {
+        fprintf(stderr, "%s: can't gzopen %s\n", prog, infile);
+        exit(1);
+    }
+    out = fopen(outfile, "wb");
+    if (out == NULL) {
+        perror(file);
+        exit(1);
+    }
+
+    gz_uncompress(in, out);
+
+    unlink(infile);
+}
+
+
+/* ===========================================================================
+ * Usage:  minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...]
+ *   -c : write to standard output
+ *   -d : decompress
+ *   -f : compress with Z_FILTERED
+ *   -h : compress with Z_HUFFMAN_ONLY
+ *   -r : compress with Z_RLE
+ *   -1 to -9 : compression level
+ */
+
+int main(argc, argv)
+    int argc;
+    char *argv[];
+{
+    int copyout = 0;
+    int uncompr = 0;
+    gzFile file;
+    char *bname, outmode[20];
+
+    strcpy(outmode, "wb6 ");
+
+    prog = argv[0];
+    bname = strrchr(argv[0], '/');
+    if (bname)
+      bname++;
+    else
+      bname = argv[0];
+    argc--, argv++;
+
+    if (!strcmp(bname, "gunzip"))
+      uncompr = 1;
+    else if (!strcmp(bname, "zcat"))
+      copyout = uncompr = 1;
+
+    while (argc > 0) {
+      if (strcmp(*argv, "-c") == 0)
+        copyout = 1;
+      else if (strcmp(*argv, "-d") == 0)
+        uncompr = 1;
+      else if (strcmp(*argv, "-f") == 0)
+        outmode[3] = 'f';
+      else if (strcmp(*argv, "-h") == 0)
+        outmode[3] = 'h';
+      else if (strcmp(*argv, "-r") == 0)
+        outmode[3] = 'R';
+      else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' &&
+               (*argv)[2] == 0)
+        outmode[2] = (*argv)[1];
+      else
+        break;
+      argc--, argv++;
+    }
+    if (outmode[3] == ' ')
+        outmode[3] = 0;
+    if (argc == 0) {
+        SET_BINARY_MODE(stdin);
+        SET_BINARY_MODE(stdout);
+        if (uncompr) {
+            file = gzdopen(fileno(stdin), "rb");
+            if (file == NULL) error("can't gzdopen stdin");
+            gz_uncompress(file, stdout);
+        } else {
+            file = gzdopen(fileno(stdout), outmode);
+            if (file == NULL) error("can't gzdopen stdout");
+            gz_compress(stdin, file);
+        }
+    } else {
+        if (copyout) {
+            SET_BINARY_MODE(stdout);
+        }
+        do {
+            if (uncompr) {
+                if (copyout) {
+                    file = gzopen(*argv, "rb");
+                    if (file == NULL)
+                        fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv);
+                    else
+                        gz_uncompress(file, stdout);
+                } else {
+                    file_uncompress(*argv);
+                }
+            } else {
+                if (copyout) {
+                    FILE * in = fopen(*argv, "rb");
+
+                    if (in == NULL) {
+                        perror(*argv);
+                    } else {
+                        file = gzdopen(fileno(stdout), outmode);
+                        if (file == NULL) error("can't gzdopen stdout");
+
+                        gz_compress(in, file);
+                    }
+
+                } else {
+                    file_compress(*argv, outmode);
+                }
+            }
+        } while (argv++, --argc);
+    }
+    return 0;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/treebuild.xml b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/treebuild.xml
new file mode 100644 (file)
index 0000000..89963a0
--- /dev/null
@@ -0,0 +1,116 @@
+<?xml version="1.0" ?>
+<package name="zlib" version="1.2.6">
+    <library name="zlib" dlversion="1.2.6" dlname="z">
+       <property name="description"> zip compression library </property>
+       <property name="include-target-dir" value="$(@PACKAGE/install-includedir)" />
+
+       <!-- fixme: not implemented yet -->
+       <property name="compiler/c/inline" value="yes" />
+
+       <include-file name="zlib.h" scope="public" mode="644" />
+       <include-file name="zconf.h" scope="public" mode="644" />
+
+       <source name="adler32.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+       </source>
+       <source name="compress.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+       </source>
+       <source name="crc32.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="crc32.h" />
+       </source>
+       <source name="gzclose.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="gzguts.h" />
+       </source>
+       <source name="gzlib.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="gzguts.h" />
+       </source>
+       <source name="gzread.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="gzguts.h" />
+       </source>
+       <source name="gzwrite.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="gzguts.h" />
+       </source>
+       <source name="uncompr.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+       </source>
+       <source name="deflate.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="zutil.h" />
+           <depend name="deflate.h" />
+       </source>
+       <source name="trees.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="zutil.h" />
+           <depend name="deflate.h" />
+           <depend name="trees.h" />
+       </source>
+       <source name="zutil.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="zutil.h" />
+       </source>
+       <source name="inflate.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="zutil.h" />
+           <depend name="inftrees.h" />
+           <depend name="inflate.h" />
+           <depend name="inffast.h" />
+       </source>
+       <source name="infback.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="zutil.h" />
+           <depend name="inftrees.h" />
+           <depend name="inflate.h" />
+           <depend name="inffast.h" />
+       </source>
+       <source name="inftrees.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="zutil.h" />
+           <depend name="inftrees.h" />
+       </source>
+       <source name="inffast.c">
+           <depend name="zlib.h" />
+           <depend name="zconf.h" />
+           <depend name="zutil.h" />
+           <depend name="inftrees.h" />
+           <depend name="inflate.h" />
+           <depend name="inffast.h" />
+       </source>
+    </library>
+</package>
+
+<!--
+CFLAGS=-O
+#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
+#CFLAGS=-g -DDEBUG
+#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
+#           -Wstrict-prototypes -Wmissing-prototypes
+
+# OBJA =
+# to use the asm code: make OBJA=match.o
+#
+match.o: match.S
+       $(CPP) match.S > _match.s
+       $(CC) -c _match.s
+       mv _match.o match.o
+       rm -f _match.s
+-->
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/trees.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/trees.c
new file mode 100644 (file)
index 0000000..8c32b21
--- /dev/null
@@ -0,0 +1,1224 @@
+/* trees.c -- output deflated data using Huffman coding
+ * Copyright (C) 1995-2012 Jean-loup Gailly
+ * detect_data_type() function provided freely by Cosmin Truta, 2006
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ *  ALGORITHM
+ *
+ *      The "deflation" process uses several Huffman trees. The more
+ *      common source values are represented by shorter bit sequences.
+ *
+ *      Each code tree is stored in a compressed form which is itself
+ * a Huffman encoding of the lengths of all the code strings (in
+ * ascending order by source values).  The actual code strings are
+ * reconstructed from the lengths in the inflate process, as described
+ * in the deflate specification.
+ *
+ *  REFERENCES
+ *
+ *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
+ *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
+ *
+ *      Storer, James A.
+ *          Data Compression:  Methods and Theory, pp. 49-50.
+ *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
+ *
+ *      Sedgewick, R.
+ *          Algorithms, p290.
+ *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
+ */
+
+/* @(#) $Id$ */
+
+/* #define GEN_TREES_H */
+
+#include "deflate.h"
+
+#ifdef DEBUG
+#  include <ctype.h>
+#endif
+
+/* ===========================================================================
+ * Constants
+ */
+
+#define MAX_BL_BITS 7
+/* Bit length codes must not exceed MAX_BL_BITS bits */
+
+#define END_BLOCK 256
+/* end of block literal code */
+
+#define REP_3_6      16
+/* repeat previous bit length 3-6 times (2 bits of repeat count) */
+
+#define REPZ_3_10    17
+/* repeat a zero length 3-10 times  (3 bits of repeat count) */
+
+#define REPZ_11_138  18
+/* repeat a zero length 11-138 times  (7 bits of repeat count) */
+
+local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
+   = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
+
+local const int extra_dbits[D_CODES] /* extra bits for each distance code */
+   = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
+
+local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
+   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
+
+local const uch bl_order[BL_CODES]
+   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
+/* The lengths of the bit length codes are sent in order of decreasing
+ * probability, to avoid transmitting the lengths for unused bit length codes.
+ */
+
+/* ===========================================================================
+ * Local data. These are initialized only once.
+ */
+
+#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
+
+#if defined(GEN_TREES_H) || !defined(STDC)
+/* non ANSI compilers may not accept trees.h */
+
+local ct_data static_ltree[L_CODES+2];
+/* The static literal tree. Since the bit lengths are imposed, there is no
+ * need for the L_CODES extra codes used during heap construction. However
+ * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
+ * below).
+ */
+
+local ct_data static_dtree[D_CODES];
+/* The static distance tree. (Actually a trivial tree since all codes use
+ * 5 bits.)
+ */
+
+uch _dist_code[DIST_CODE_LEN];
+/* Distance codes. The first 256 values correspond to the distances
+ * 3 .. 258, the last 256 values correspond to the top 8 bits of
+ * the 15 bit distances.
+ */
+
+uch _length_code[MAX_MATCH-MIN_MATCH+1];
+/* length code for each normalized match length (0 == MIN_MATCH) */
+
+local int base_length[LENGTH_CODES];
+/* First normalized length for each code (0 = MIN_MATCH) */
+
+local int base_dist[D_CODES];
+/* First normalized distance for each code (0 = distance of 1) */
+
+#else
+#  include "trees.h"
+#endif /* GEN_TREES_H */
+
+struct static_tree_desc_s {
+    const ct_data *static_tree;  /* static tree or NULL */
+    const intf *extra_bits;      /* extra bits for each code or NULL */
+    int     extra_base;          /* base index for extra_bits */
+    int     elems;               /* max number of elements in the tree */
+    int     max_length;          /* max bit length for the codes */
+};
+
+local static_tree_desc  static_l_desc =
+{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
+
+local static_tree_desc  static_d_desc =
+{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
+
+local static_tree_desc  static_bl_desc =
+{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
+
+/* ===========================================================================
+ * Local (static) routines in this file.
+ */
+
+local void tr_static_init OF((void));
+local void init_block     OF((deflate_state *s));
+local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
+local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
+local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
+local void build_tree     OF((deflate_state *s, tree_desc *desc));
+local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
+local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
+local int  build_bl_tree  OF((deflate_state *s));
+local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
+                              int blcodes));
+local void compress_block OF((deflate_state *s, ct_data *ltree,
+                              ct_data *dtree));
+local int  detect_data_type OF((deflate_state *s));
+local unsigned bi_reverse OF((unsigned value, int length));
+local void bi_windup      OF((deflate_state *s));
+local void bi_flush       OF((deflate_state *s));
+local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
+                              int header));
+
+#ifdef GEN_TREES_H
+local void gen_trees_header OF((void));
+#endif
+
+#ifndef DEBUG
+#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
+   /* Send a code of the given tree. c and tree must not have side effects */
+
+#else /* DEBUG */
+#  define send_code(s, c, tree) \
+     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
+       send_bits(s, tree[c].Code, tree[c].Len); }
+#endif
+
+/* ===========================================================================
+ * Output a short LSB first on the stream.
+ * IN assertion: there is enough room in pendingBuf.
+ */
+#define put_short(s, w) { \
+    put_byte(s, (uch)((w) & 0xff)); \
+    put_byte(s, (uch)((ush)(w) >> 8)); \
+}
+
+/* ===========================================================================
+ * Send a value on a given number of bits.
+ * IN assertion: length <= 16 and value fits in length bits.
+ */
+#ifdef DEBUG
+local void send_bits      OF((deflate_state *s, int value, int length));
+
+local void send_bits(s, value, length)
+    deflate_state *s;
+    int value;  /* value to send */
+    int length; /* number of bits */
+{
+    Tracevv((stderr," l %2d v %4x ", length, value));
+    Assert(length > 0 && length <= 15, "invalid length");
+    s->bits_sent += (ulg)length;
+
+    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
+     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
+     * unused bits in value.
+     */
+    if (s->bi_valid > (int)Buf_size - length) {
+        s->bi_buf |= (ush)value << s->bi_valid;
+        put_short(s, s->bi_buf);
+        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
+        s->bi_valid += length - Buf_size;
+    } else {
+        s->bi_buf |= (ush)value << s->bi_valid;
+        s->bi_valid += length;
+    }
+}
+#else /* !DEBUG */
+
+#define send_bits(s, value, length) \
+{ int len = length;\
+  if (s->bi_valid > (int)Buf_size - len) {\
+    int val = value;\
+    s->bi_buf |= (ush)val << s->bi_valid;\
+    put_short(s, s->bi_buf);\
+    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
+    s->bi_valid += len - Buf_size;\
+  } else {\
+    s->bi_buf |= (ush)(value) << s->bi_valid;\
+    s->bi_valid += len;\
+  }\
+}
+#endif /* DEBUG */
+
+
+/* the arguments must not have side effects */
+
+/* ===========================================================================
+ * Initialize the various 'constant' tables.
+ */
+local void tr_static_init()
+{
+#if defined(GEN_TREES_H) || !defined(STDC)
+    static int static_init_done = 0;
+    int n;        /* iterates over tree elements */
+    int bits;     /* bit counter */
+    int length;   /* length value */
+    int code;     /* code value */
+    int dist;     /* distance index */
+    ush bl_count[MAX_BITS+1];
+    /* number of codes at each bit length for an optimal tree */
+
+    if (static_init_done) return;
+
+    /* For some embedded targets, global variables are not initialized: */
+#ifdef NO_INIT_GLOBAL_POINTERS
+    static_l_desc.static_tree = static_ltree;
+    static_l_desc.extra_bits = extra_lbits;
+    static_d_desc.static_tree = static_dtree;
+    static_d_desc.extra_bits = extra_dbits;
+    static_bl_desc.extra_bits = extra_blbits;
+#endif
+
+    /* Initialize the mapping length (0..255) -> length code (0..28) */
+    length = 0;
+    for (code = 0; code < LENGTH_CODES-1; code++) {
+        base_length[code] = length;
+        for (n = 0; n < (1<<extra_lbits[code]); n++) {
+            _length_code[length++] = (uch)code;
+        }
+    }
+    Assert (length == 256, "tr_static_init: length != 256");
+    /* Note that the length 255 (match length 258) can be represented
+     * in two different ways: code 284 + 5 bits or code 285, so we
+     * overwrite length_code[255] to use the best encoding:
+     */
+    _length_code[length-1] = (uch)code;
+
+    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
+    dist = 0;
+    for (code = 0 ; code < 16; code++) {
+        base_dist[code] = dist;
+        for (n = 0; n < (1<<extra_dbits[code]); n++) {
+            _dist_code[dist++] = (uch)code;
+        }
+    }
+    Assert (dist == 256, "tr_static_init: dist != 256");
+    dist >>= 7; /* from now on, all distances are divided by 128 */
+    for ( ; code < D_CODES; code++) {
+        base_dist[code] = dist << 7;
+        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
+            _dist_code[256 + dist++] = (uch)code;
+        }
+    }
+    Assert (dist == 256, "tr_static_init: 256+dist != 512");
+
+    /* Construct the codes of the static literal tree */
+    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
+    n = 0;
+    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
+    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
+    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
+    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
+    /* Codes 286 and 287 do not exist, but we must include them in the
+     * tree construction to get a canonical Huffman tree (longest code
+     * all ones)
+     */
+    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
+
+    /* The static distance tree is trivial: */
+    for (n = 0; n < D_CODES; n++) {
+        static_dtree[n].Len = 5;
+        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
+    }
+    static_init_done = 1;
+
+#  ifdef GEN_TREES_H
+    gen_trees_header();
+#  endif
+#endif /* defined(GEN_TREES_H) || !defined(STDC) */
+}
+
+/* ===========================================================================
+ * Genererate the file trees.h describing the static trees.
+ */
+#ifdef GEN_TREES_H
+#  ifndef DEBUG
+#    include <stdio.h>
+#  endif
+
+#  define SEPARATOR(i, last, width) \
+      ((i) == (last)? "\n};\n\n" :    \
+       ((i) % (width) == (width)-1 ? ",\n" : ", "))
+
+void gen_trees_header()
+{
+    FILE *header = fopen("trees.h", "w");
+    int i;
+
+    Assert (header != NULL, "Can't open trees.h");
+    fprintf(header,
+            "/* header created automatically with -DGEN_TREES_H */\n\n");
+
+    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
+    for (i = 0; i < L_CODES+2; i++) {
+        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
+                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
+    }
+
+    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
+    for (i = 0; i < D_CODES; i++) {
+        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
+                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
+    }
+
+    fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
+    for (i = 0; i < DIST_CODE_LEN; i++) {
+        fprintf(header, "%2u%s", _dist_code[i],
+                SEPARATOR(i, DIST_CODE_LEN-1, 20));
+    }
+
+    fprintf(header,
+        "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
+    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
+        fprintf(header, "%2u%s", _length_code[i],
+                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
+    }
+
+    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
+    for (i = 0; i < LENGTH_CODES; i++) {
+        fprintf(header, "%1u%s", base_length[i],
+                SEPARATOR(i, LENGTH_CODES-1, 20));
+    }
+
+    fprintf(header, "local const int base_dist[D_CODES] = {\n");
+    for (i = 0; i < D_CODES; i++) {
+        fprintf(header, "%5u%s", base_dist[i],
+                SEPARATOR(i, D_CODES-1, 10));
+    }
+
+    fclose(header);
+}
+#endif /* GEN_TREES_H */
+
+/* ===========================================================================
+ * Initialize the tree data structures for a new zlib stream.
+ */
+void ZLIB_INTERNAL _tr_init(s)
+    deflate_state *s;
+{
+    tr_static_init();
+
+    s->l_desc.dyn_tree = s->dyn_ltree;
+    s->l_desc.stat_desc = &static_l_desc;
+
+    s->d_desc.dyn_tree = s->dyn_dtree;
+    s->d_desc.stat_desc = &static_d_desc;
+
+    s->bl_desc.dyn_tree = s->bl_tree;
+    s->bl_desc.stat_desc = &static_bl_desc;
+
+    s->bi_buf = 0;
+    s->bi_valid = 0;
+#ifdef DEBUG
+    s->compressed_len = 0L;
+    s->bits_sent = 0L;
+#endif
+
+    /* Initialize the first block of the first file: */
+    init_block(s);
+}
+
+/* ===========================================================================
+ * Initialize a new block.
+ */
+local void init_block(s)
+    deflate_state *s;
+{
+    int n; /* iterates over tree elements */
+
+    /* Initialize the trees. */
+    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
+    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
+    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
+
+    s->dyn_ltree[END_BLOCK].Freq = 1;
+    s->opt_len = s->static_len = 0L;
+    s->last_lit = s->matches = 0;
+}
+
+#define SMALLEST 1
+/* Index within the heap array of least frequent node in the Huffman tree */
+
+
+/* ===========================================================================
+ * Remove the smallest element from the heap and recreate the heap with
+ * one less element. Updates heap and heap_len.
+ */
+#define pqremove(s, tree, top) \
+{\
+    top = s->heap[SMALLEST]; \
+    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
+    pqdownheap(s, tree, SMALLEST); \
+}
+
+/* ===========================================================================
+ * Compares to subtrees, using the tree depth as tie breaker when
+ * the subtrees have equal frequency. This minimizes the worst case length.
+ */
+#define smaller(tree, n, m, depth) \
+   (tree[n].Freq < tree[m].Freq || \
+   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
+
+/* ===========================================================================
+ * Restore the heap property by moving down the tree starting at node k,
+ * exchanging a node with the smallest of its two sons if necessary, stopping
+ * when the heap property is re-established (each father smaller than its
+ * two sons).
+ */
+local void pqdownheap(s, tree, k)
+    deflate_state *s;
+    ct_data *tree;  /* the tree to restore */
+    int k;               /* node to move down */
+{
+    int v = s->heap[k];
+    int j = k << 1;  /* left son of k */
+    while (j <= s->heap_len) {
+        /* Set j to the smallest of the two sons: */
+        if (j < s->heap_len &&
+            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
+            j++;
+        }
+        /* Exit if v is smaller than both sons */
+        if (smaller(tree, v, s->heap[j], s->depth)) break;
+
+        /* Exchange v with the smallest son */
+        s->heap[k] = s->heap[j];  k = j;
+
+        /* And continue down the tree, setting j to the left son of k */
+        j <<= 1;
+    }
+    s->heap[k] = v;
+}
+
+/* ===========================================================================
+ * Compute the optimal bit lengths for a tree and update the total bit length
+ * for the current block.
+ * IN assertion: the fields freq and dad are set, heap[heap_max] and
+ *    above are the tree nodes sorted by increasing frequency.
+ * OUT assertions: the field len is set to the optimal bit length, the
+ *     array bl_count contains the frequencies for each bit length.
+ *     The length opt_len is updated; static_len is also updated if stree is
+ *     not null.
+ */
+local void gen_bitlen(s, desc)
+    deflate_state *s;
+    tree_desc *desc;    /* the tree descriptor */
+{
+    ct_data *tree        = desc->dyn_tree;
+    int max_code         = desc->max_code;
+    const ct_data *stree = desc->stat_desc->static_tree;
+    const intf *extra    = desc->stat_desc->extra_bits;
+    int base             = desc->stat_desc->extra_base;
+    int max_length       = desc->stat_desc->max_length;
+    int h;              /* heap index */
+    int n, m;           /* iterate over the tree elements */
+    int bits;           /* bit length */
+    int xbits;          /* extra bits */
+    ush f;              /* frequency */
+    int overflow = 0;   /* number of elements with bit length too large */
+
+    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
+
+    /* In a first pass, compute the optimal bit lengths (which may
+     * overflow in the case of the bit length tree).
+     */
+    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
+
+    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
+        n = s->heap[h];
+        bits = tree[tree[n].Dad].Len + 1;
+        if (bits > max_length) bits = max_length, overflow++;
+        tree[n].Len = (ush)bits;
+        /* We overwrite tree[n].Dad which is no longer needed */
+
+        if (n > max_code) continue; /* not a leaf node */
+
+        s->bl_count[bits]++;
+        xbits = 0;
+        if (n >= base) xbits = extra[n-base];
+        f = tree[n].Freq;
+        s->opt_len += (ulg)f * (bits + xbits);
+        if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
+    }
+    if (overflow == 0) return;
+
+    Trace((stderr,"\nbit length overflow\n"));
+    /* This happens for example on obj2 and pic of the Calgary corpus */
+
+    /* Find the first bit length which could increase: */
+    do {
+        bits = max_length-1;
+        while (s->bl_count[bits] == 0) bits--;
+        s->bl_count[bits]--;      /* move one leaf down the tree */
+        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
+        s->bl_count[max_length]--;
+        /* The brother of the overflow item also moves one step up,
+         * but this does not affect bl_count[max_length]
+         */
+        overflow -= 2;
+    } while (overflow > 0);
+
+    /* Now recompute all bit lengths, scanning in increasing frequency.
+     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
+     * lengths instead of fixing only the wrong ones. This idea is taken
+     * from 'ar' written by Haruhiko Okumura.)
+     */
+    for (bits = max_length; bits != 0; bits--) {
+        n = s->bl_count[bits];
+        while (n != 0) {
+            m = s->heap[--h];
+            if (m > max_code) continue;
+            if ((unsigned) tree[m].Len != (unsigned) bits) {
+                Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
+                s->opt_len += ((long)bits - (long)tree[m].Len)
+                              *(long)tree[m].Freq;
+                tree[m].Len = (ush)bits;
+            }
+            n--;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Generate the codes for a given tree and bit counts (which need not be
+ * optimal).
+ * IN assertion: the array bl_count contains the bit length statistics for
+ * the given tree and the field len is set for all tree elements.
+ * OUT assertion: the field code is set for all tree elements of non
+ *     zero code length.
+ */
+local void gen_codes (tree, max_code, bl_count)
+    ct_data *tree;             /* the tree to decorate */
+    int max_code;              /* largest code with non zero frequency */
+    ushf *bl_count;            /* number of codes at each bit length */
+{
+    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
+    ush code = 0;              /* running code value */
+    int bits;                  /* bit index */
+    int n;                     /* code index */
+
+    /* The distribution counts are first used to generate the code values
+     * without bit reversal.
+     */
+    for (bits = 1; bits <= MAX_BITS; bits++) {
+        next_code[bits] = code = (code + bl_count[bits-1]) << 1;
+    }
+    /* Check that the bit counts in bl_count are consistent. The last code
+     * must be all ones.
+     */
+    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
+            "inconsistent bit counts");
+    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
+
+    for (n = 0;  n <= max_code; n++) {
+        int len = tree[n].Len;
+        if (len == 0) continue;
+        /* Now reverse the bits */
+        tree[n].Code = bi_reverse(next_code[len]++, len);
+
+        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
+             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
+    }
+}
+
+/* ===========================================================================
+ * Construct one Huffman tree and assigns the code bit strings and lengths.
+ * Update the total bit length for the current block.
+ * IN assertion: the field freq is set for all tree elements.
+ * OUT assertions: the fields len and code are set to the optimal bit length
+ *     and corresponding code. The length opt_len is updated; static_len is
+ *     also updated if stree is not null. The field max_code is set.
+ */
+local void build_tree(s, desc)
+    deflate_state *s;
+    tree_desc *desc; /* the tree descriptor */
+{
+    ct_data *tree         = desc->dyn_tree;
+    const ct_data *stree  = desc->stat_desc->static_tree;
+    int elems             = desc->stat_desc->elems;
+    int n, m;          /* iterate over heap elements */
+    int max_code = -1; /* largest code with non zero frequency */
+    int node;          /* new node being created */
+
+    /* Construct the initial heap, with least frequent element in
+     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
+     * heap[0] is not used.
+     */
+    s->heap_len = 0, s->heap_max = HEAP_SIZE;
+
+    for (n = 0; n < elems; n++) {
+        if (tree[n].Freq != 0) {
+            s->heap[++(s->heap_len)] = max_code = n;
+            s->depth[n] = 0;
+        } else {
+            tree[n].Len = 0;
+        }
+    }
+
+    /* The pkzip format requires that at least one distance code exists,
+     * and that at least one bit should be sent even if there is only one
+     * possible code. So to avoid special checks later on we force at least
+     * two codes of non zero frequency.
+     */
+    while (s->heap_len < 2) {
+        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
+        tree[node].Freq = 1;
+        s->depth[node] = 0;
+        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
+        /* node is 0 or 1 so it does not have extra bits */
+    }
+    desc->max_code = max_code;
+
+    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
+     * establish sub-heaps of increasing lengths:
+     */
+    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
+
+    /* Construct the Huffman tree by repeatedly combining the least two
+     * frequent nodes.
+     */
+    node = elems;              /* next internal node of the tree */
+    do {
+        pqremove(s, tree, n);  /* n = node of least frequency */
+        m = s->heap[SMALLEST]; /* m = node of next least frequency */
+
+        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
+        s->heap[--(s->heap_max)] = m;
+
+        /* Create a new node father of n and m */
+        tree[node].Freq = tree[n].Freq + tree[m].Freq;
+        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
+                                s->depth[n] : s->depth[m]) + 1);
+        tree[n].Dad = tree[m].Dad = (ush)node;
+#ifdef DUMP_BL_TREE
+        if (tree == s->bl_tree) {
+            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
+                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
+        }
+#endif
+        /* and insert the new node in the heap */
+        s->heap[SMALLEST] = node++;
+        pqdownheap(s, tree, SMALLEST);
+
+    } while (s->heap_len >= 2);
+
+    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
+
+    /* At this point, the fields freq and dad are set. We can now
+     * generate the bit lengths.
+     */
+    gen_bitlen(s, (tree_desc *)desc);
+
+    /* The field len is now set, we can generate the bit codes */
+    gen_codes ((ct_data *)tree, max_code, s->bl_count);
+}
+
+/* ===========================================================================
+ * Scan a literal or distance tree to determine the frequencies of the codes
+ * in the bit length tree.
+ */
+local void scan_tree (s, tree, max_code)
+    deflate_state *s;
+    ct_data *tree;   /* the tree to be scanned */
+    int max_code;    /* and its largest code of non zero frequency */
+{
+    int n;                     /* iterates over all tree elements */
+    int prevlen = -1;          /* last emitted length */
+    int curlen;                /* length of current code */
+    int nextlen = tree[0].Len; /* length of next code */
+    int count = 0;             /* repeat count of the current code */
+    int max_count = 7;         /* max repeat count */
+    int min_count = 4;         /* min repeat count */
+
+    if (nextlen == 0) max_count = 138, min_count = 3;
+    tree[max_code+1].Len = (ush)0xffff; /* guard */
+
+    for (n = 0; n <= max_code; n++) {
+        curlen = nextlen; nextlen = tree[n+1].Len;
+        if (++count < max_count && curlen == nextlen) {
+            continue;
+        } else if (count < min_count) {
+            s->bl_tree[curlen].Freq += count;
+        } else if (curlen != 0) {
+            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
+            s->bl_tree[REP_3_6].Freq++;
+        } else if (count <= 10) {
+            s->bl_tree[REPZ_3_10].Freq++;
+        } else {
+            s->bl_tree[REPZ_11_138].Freq++;
+        }
+        count = 0; prevlen = curlen;
+        if (nextlen == 0) {
+            max_count = 138, min_count = 3;
+        } else if (curlen == nextlen) {
+            max_count = 6, min_count = 3;
+        } else {
+            max_count = 7, min_count = 4;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Send a literal or distance tree in compressed form, using the codes in
+ * bl_tree.
+ */
+local void send_tree (s, tree, max_code)
+    deflate_state *s;
+    ct_data *tree; /* the tree to be scanned */
+    int max_code;       /* and its largest code of non zero frequency */
+{
+    int n;                     /* iterates over all tree elements */
+    int prevlen = -1;          /* last emitted length */
+    int curlen;                /* length of current code */
+    int nextlen = tree[0].Len; /* length of next code */
+    int count = 0;             /* repeat count of the current code */
+    int max_count = 7;         /* max repeat count */
+    int min_count = 4;         /* min repeat count */
+
+    /* tree[max_code+1].Len = -1; */  /* guard already set */
+    if (nextlen == 0) max_count = 138, min_count = 3;
+
+    for (n = 0; n <= max_code; n++) {
+        curlen = nextlen; nextlen = tree[n+1].Len;
+        if (++count < max_count && curlen == nextlen) {
+            continue;
+        } else if (count < min_count) {
+            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
+
+        } else if (curlen != 0) {
+            if (curlen != prevlen) {
+                send_code(s, curlen, s->bl_tree); count--;
+            }
+            Assert(count >= 3 && count <= 6, " 3_6?");
+            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
+
+        } else if (count <= 10) {
+            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
+
+        } else {
+            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
+        }
+        count = 0; prevlen = curlen;
+        if (nextlen == 0) {
+            max_count = 138, min_count = 3;
+        } else if (curlen == nextlen) {
+            max_count = 6, min_count = 3;
+        } else {
+            max_count = 7, min_count = 4;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Construct the Huffman tree for the bit lengths and return the index in
+ * bl_order of the last bit length code to send.
+ */
+local int build_bl_tree(s)
+    deflate_state *s;
+{
+    int max_blindex;  /* index of last bit length code of non zero freq */
+
+    /* Determine the bit length frequencies for literal and distance trees */
+    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
+    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
+
+    /* Build the bit length tree: */
+    build_tree(s, (tree_desc *)(&(s->bl_desc)));
+    /* opt_len now includes the length of the tree representations, except
+     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
+     */
+
+    /* Determine the number of bit length codes to send. The pkzip format
+     * requires that at least 4 bit length codes be sent. (appnote.txt says
+     * 3 but the actual value used is 4.)
+     */
+    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
+        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
+    }
+    /* Update opt_len to include the bit length tree and counts */
+    s->opt_len += 3*(max_blindex+1) + 5+5+4;
+    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
+            s->opt_len, s->static_len));
+
+    return max_blindex;
+}
+
+/* ===========================================================================
+ * Send the header for a block using dynamic Huffman trees: the counts, the
+ * lengths of the bit length codes, the literal tree and the distance tree.
+ * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
+ */
+local void send_all_trees(s, lcodes, dcodes, blcodes)
+    deflate_state *s;
+    int lcodes, dcodes, blcodes; /* number of codes for each tree */
+{
+    int rank;                    /* index in bl_order */
+
+    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
+    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
+            "too many codes");
+    Tracev((stderr, "\nbl counts: "));
+    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
+    send_bits(s, dcodes-1,   5);
+    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
+    for (rank = 0; rank < blcodes; rank++) {
+        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
+        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
+    }
+    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
+
+    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
+    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
+
+    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
+    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
+}
+
+/* ===========================================================================
+ * Send a stored block
+ */
+void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
+    deflate_state *s;
+    charf *buf;       /* input block */
+    ulg stored_len;   /* length of input block */
+    int last;         /* one if this is the last block for a file */
+{
+    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
+#ifdef DEBUG
+    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
+    s->compressed_len += (stored_len + 4) << 3;
+#endif
+    copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
+}
+
+/* ===========================================================================
+ * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
+ */
+void ZLIB_INTERNAL _tr_flush_bits(s)
+    deflate_state *s;
+{
+    bi_flush(s);
+}
+
+/* ===========================================================================
+ * Send one empty static block to give enough lookahead for inflate.
+ * This takes 10 bits, of which 7 may remain in the bit buffer.
+ */
+void ZLIB_INTERNAL _tr_align(s)
+    deflate_state *s;
+{
+    send_bits(s, STATIC_TREES<<1, 3);
+    send_code(s, END_BLOCK, static_ltree);
+#ifdef DEBUG
+    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
+#endif
+    bi_flush(s);
+}
+
+/* ===========================================================================
+ * Determine the best encoding for the current block: dynamic trees, static
+ * trees or store, and output the encoded block to the zip file.
+ */
+void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
+    deflate_state *s;
+    charf *buf;       /* input block, or NULL if too old */
+    ulg stored_len;   /* length of input block */
+    int last;         /* one if this is the last block for a file */
+{
+    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
+    int max_blindex = 0;  /* index of last bit length code of non zero freq */
+
+    /* Build the Huffman trees unless a stored block is forced */
+    if (s->level > 0) {
+
+        /* Check if the file is binary or text */
+        if (s->strm->data_type == Z_UNKNOWN)
+            s->strm->data_type = detect_data_type(s);
+
+        /* Construct the literal and distance trees */
+        build_tree(s, (tree_desc *)(&(s->l_desc)));
+        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
+                s->static_len));
+
+        build_tree(s, (tree_desc *)(&(s->d_desc)));
+        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
+                s->static_len));
+        /* At this point, opt_len and static_len are the total bit lengths of
+         * the compressed block data, excluding the tree representations.
+         */
+
+        /* Build the bit length tree for the above two trees, and get the index
+         * in bl_order of the last bit length code to send.
+         */
+        max_blindex = build_bl_tree(s);
+
+        /* Determine the best encoding. Compute the block lengths in bytes. */
+        opt_lenb = (s->opt_len+3+7)>>3;
+        static_lenb = (s->static_len+3+7)>>3;
+
+        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
+                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
+                s->last_lit));
+
+        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
+
+    } else {
+        Assert(buf != (char*)0, "lost buf");
+        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
+    }
+
+#ifdef FORCE_STORED
+    if (buf != (char*)0) { /* force stored block */
+#else
+    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
+                       /* 4: two words for the lengths */
+#endif
+        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
+         * Otherwise we can't have processed more than WSIZE input bytes since
+         * the last block flush, because compression would have been
+         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
+         * transform a block into a stored block.
+         */
+        _tr_stored_block(s, buf, stored_len, last);
+
+#ifdef FORCE_STATIC
+    } else if (static_lenb >= 0) { /* force static trees */
+#else
+    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
+#endif
+        send_bits(s, (STATIC_TREES<<1)+last, 3);
+        compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
+#ifdef DEBUG
+        s->compressed_len += 3 + s->static_len;
+#endif
+    } else {
+        send_bits(s, (DYN_TREES<<1)+last, 3);
+        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
+                       max_blindex+1);
+        compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
+#ifdef DEBUG
+        s->compressed_len += 3 + s->opt_len;
+#endif
+    }
+    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
+    /* The above check is made mod 2^32, for files larger than 512 MB
+     * and uLong implemented on 32 bits.
+     */
+    init_block(s);
+
+    if (last) {
+        bi_windup(s);
+#ifdef DEBUG
+        s->compressed_len += 7;  /* align on byte boundary */
+#endif
+    }
+    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
+           s->compressed_len-7*last));
+}
+
+/* ===========================================================================
+ * Save the match info and tally the frequency counts. Return true if
+ * the current block must be flushed.
+ */
+int ZLIB_INTERNAL _tr_tally (s, dist, lc)
+    deflate_state *s;
+    unsigned dist;  /* distance of matched string */
+    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
+{
+    s->d_buf[s->last_lit] = (ush)dist;
+    s->l_buf[s->last_lit++] = (uch)lc;
+    if (dist == 0) {
+        /* lc is the unmatched char */
+        s->dyn_ltree[lc].Freq++;
+    } else {
+        s->matches++;
+        /* Here, lc is the match length - MIN_MATCH */
+        dist--;             /* dist = match distance - 1 */
+        Assert((ush)dist < (ush)MAX_DIST(s) &&
+               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
+               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
+
+        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
+        s->dyn_dtree[d_code(dist)].Freq++;
+    }
+
+#ifdef TRUNCATE_BLOCK
+    /* Try to guess if it is profitable to stop the current block here */
+    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
+        /* Compute an upper bound for the compressed length */
+        ulg out_length = (ulg)s->last_lit*8L;
+        ulg in_length = (ulg)((long)s->strstart - s->block_start);
+        int dcode;
+        for (dcode = 0; dcode < D_CODES; dcode++) {
+            out_length += (ulg)s->dyn_dtree[dcode].Freq *
+                (5L+extra_dbits[dcode]);
+        }
+        out_length >>= 3;
+        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
+               s->last_lit, in_length, out_length,
+               100L - out_length*100L/in_length));
+        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
+    }
+#endif
+    return (s->last_lit == s->lit_bufsize-1);
+    /* We avoid equality with lit_bufsize because of wraparound at 64K
+     * on 16 bit machines and because stored blocks are restricted to
+     * 64K-1 bytes.
+     */
+}
+
+/* ===========================================================================
+ * Send the block data compressed using the given Huffman trees
+ */
+local void compress_block(s, ltree, dtree)
+    deflate_state *s;
+    ct_data *ltree; /* literal tree */
+    ct_data *dtree; /* distance tree */
+{
+    unsigned dist;      /* distance of matched string */
+    int lc;             /* match length or unmatched char (if dist == 0) */
+    unsigned lx = 0;    /* running index in l_buf */
+    unsigned code;      /* the code to send */
+    int extra;          /* number of extra bits to send */
+
+    if (s->last_lit != 0) do {
+        dist = s->d_buf[lx];
+        lc = s->l_buf[lx++];
+        if (dist == 0) {
+            send_code(s, lc, ltree); /* send a literal byte */
+            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
+        } else {
+            /* Here, lc is the match length - MIN_MATCH */
+            code = _length_code[lc];
+            send_code(s, code+LITERALS+1, ltree); /* send the length code */
+            extra = extra_lbits[code];
+            if (extra != 0) {
+                lc -= base_length[code];
+                send_bits(s, lc, extra);       /* send the extra length bits */
+            }
+            dist--; /* dist is now the match distance - 1 */
+            code = d_code(dist);
+            Assert (code < D_CODES, "bad d_code");
+
+            send_code(s, code, dtree);       /* send the distance code */
+            extra = extra_dbits[code];
+            if (extra != 0) {
+                dist -= base_dist[code];
+                send_bits(s, dist, extra);   /* send the extra distance bits */
+            }
+        } /* literal or match pair ? */
+
+        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
+        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
+               "pendingBuf overflow");
+
+    } while (lx < s->last_lit);
+
+    send_code(s, END_BLOCK, ltree);
+}
+
+/* ===========================================================================
+ * Check if the data type is TEXT or BINARY, using the following algorithm:
+ * - TEXT if the two conditions below are satisfied:
+ *    a) There are no non-portable control characters belonging to the
+ *       "black list" (0..6, 14..25, 28..31).
+ *    b) There is at least one printable character belonging to the
+ *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
+ * - BINARY otherwise.
+ * - The following partially-portable control characters form a
+ *   "gray list" that is ignored in this detection algorithm:
+ *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
+ * IN assertion: the fields Freq of dyn_ltree are set.
+ */
+local int detect_data_type(s)
+    deflate_state *s;
+{
+    /* black_mask is the bit mask of black-listed bytes
+     * set bits 0..6, 14..25, and 28..31
+     * 0xf3ffc07f = binary 11110011111111111100000001111111
+     */
+    unsigned long black_mask = 0xf3ffc07fUL;
+    int n;
+
+    /* Check for non-textual ("black-listed") bytes. */
+    for (n = 0; n <= 31; n++, black_mask >>= 1)
+        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
+            return Z_BINARY;
+
+    /* Check for textual ("white-listed") bytes. */
+    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
+            || s->dyn_ltree[13].Freq != 0)
+        return Z_TEXT;
+    for (n = 32; n < LITERALS; n++)
+        if (s->dyn_ltree[n].Freq != 0)
+            return Z_TEXT;
+
+    /* There are no "black-listed" or "white-listed" bytes:
+     * this stream either is empty or has tolerated ("gray-listed") bytes only.
+     */
+    return Z_BINARY;
+}
+
+/* ===========================================================================
+ * Reverse the first len bits of a code, using straightforward code (a faster
+ * method would use a table)
+ * IN assertion: 1 <= len <= 15
+ */
+local unsigned bi_reverse(code, len)
+    unsigned code; /* the value to invert */
+    int len;       /* its bit length */
+{
+    register unsigned res = 0;
+    do {
+        res |= code & 1;
+        code >>= 1, res <<= 1;
+    } while (--len > 0);
+    return res >> 1;
+}
+
+/* ===========================================================================
+ * Flush the bit buffer, keeping at most 7 bits in it.
+ */
+local void bi_flush(s)
+    deflate_state *s;
+{
+    if (s->bi_valid == 16) {
+        put_short(s, s->bi_buf);
+        s->bi_buf = 0;
+        s->bi_valid = 0;
+    } else if (s->bi_valid >= 8) {
+        put_byte(s, (Byte)s->bi_buf);
+        s->bi_buf >>= 8;
+        s->bi_valid -= 8;
+    }
+}
+
+/* ===========================================================================
+ * Flush the bit buffer and align the output on a byte boundary
+ */
+local void bi_windup(s)
+    deflate_state *s;
+{
+    if (s->bi_valid > 8) {
+        put_short(s, s->bi_buf);
+    } else if (s->bi_valid > 0) {
+        put_byte(s, (Byte)s->bi_buf);
+    }
+    s->bi_buf = 0;
+    s->bi_valid = 0;
+#ifdef DEBUG
+    s->bits_sent = (s->bits_sent+7) & ~7;
+#endif
+}
+
+/* ===========================================================================
+ * Copy a stored block, storing first the length and its
+ * one's complement if requested.
+ */
+local void copy_block(s, buf, len, header)
+    deflate_state *s;
+    charf    *buf;    /* the input data */
+    unsigned len;     /* its length */
+    int      header;  /* true if block header must be written */
+{
+    bi_windup(s);        /* align on byte boundary */
+
+    if (header) {
+        put_short(s, (ush)len);
+        put_short(s, (ush)~len);
+#ifdef DEBUG
+        s->bits_sent += 2*16;
+#endif
+    }
+#ifdef DEBUG
+    s->bits_sent += (ulg)len<<3;
+#endif
+    while (len--) {
+        put_byte(s, *buf++);
+    }
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/trees.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/trees.h
new file mode 100644 (file)
index 0000000..d35639d
--- /dev/null
@@ -0,0 +1,128 @@
+/* header created automatically with -DGEN_TREES_H */
+
+local const ct_data static_ltree[L_CODES+2] = {
+{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},
+{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},
+{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},
+{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},
+{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},
+{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},
+{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},
+{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},
+{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},
+{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},
+{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},
+{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},
+{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},
+{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},
+{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},
+{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},
+{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},
+{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},
+{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},
+{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},
+{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},
+{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},
+{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},
+{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},
+{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},
+{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},
+{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},
+{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},
+{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},
+{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},
+{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},
+{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},
+{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},
+{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},
+{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},
+{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},
+{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},
+{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},
+{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},
+{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},
+{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},
+{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},
+{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},
+{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},
+{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},
+{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},
+{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},
+{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},
+{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},
+{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},
+{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},
+{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},
+{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},
+{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},
+{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},
+{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},
+{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},
+{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}
+};
+
+local const ct_data static_dtree[D_CODES] = {
+{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
+{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
+{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
+{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
+{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
+{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
+};
+
+const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
+ 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
+ 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
+10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
+13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
+18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
+23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
+};
+
+const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
+ 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
+13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
+17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
+19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
+22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
+23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
+};
+
+local const int base_length[LENGTH_CODES] = {
+0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
+64, 80, 96, 112, 128, 160, 192, 224, 0
+};
+
+local const int base_dist[D_CODES] = {
+    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
+   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
+ 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
+};
+
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/uncompr.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/uncompr.c
new file mode 100644 (file)
index 0000000..ad98be3
--- /dev/null
@@ -0,0 +1,59 @@
+/* uncompr.c -- decompress a memory buffer
+ * Copyright (C) 1995-2003, 2010 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#define ZLIB_INTERNAL
+#include "zlib.h"
+
+/* ===========================================================================
+     Decompresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer. Upon entry, destLen is the total
+   size of the destination buffer, which must be large enough to hold the
+   entire uncompressed data. (The size of the uncompressed data must have
+   been saved previously by the compressor and transmitted to the decompressor
+   by some mechanism outside the scope of this compression library.)
+   Upon exit, destLen is the actual size of the compressed buffer.
+
+     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer, or Z_DATA_ERROR if the input data was corrupted.
+*/
+int ZEXPORT uncompress (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+{
+    z_stream stream;
+    int err;
+
+    stream.next_in = (Bytef*)source;
+    stream.avail_in = (uInt)sourceLen;
+    /* Check for source > 64K on 16-bit machine: */
+    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
+
+    stream.next_out = dest;
+    stream.avail_out = (uInt)*destLen;
+    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
+
+    stream.zalloc = (alloc_func)0;
+    stream.zfree = (free_func)0;
+
+    err = inflateInit(&stream);
+    if (err != Z_OK) return err;
+
+    err = inflate(&stream, Z_FINISH);
+    if (err != Z_STREAM_END) {
+        inflateEnd(&stream);
+        if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
+            return Z_DATA_ERROR;
+        return err;
+    }
+    *destLen = stream.total_out;
+
+    err = inflateEnd(&stream);
+    return err;
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/watcom/watcom_f.mak b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/watcom/watcom_f.mak
new file mode 100644 (file)
index 0000000..37f4d74
--- /dev/null
@@ -0,0 +1,43 @@
+# Makefile for zlib
+# OpenWatcom flat model
+# Last updated: 28-Dec-2005
+
+# To use, do "wmake -f watcom_f.mak"
+
+C_SOURCE =  adler32.c  compress.c crc32.c   deflate.c    &
+           gzclose.c  gzlib.c    gzread.c  gzwrite.c    &
+            infback.c  inffast.c  inflate.c inftrees.c   &
+            trees.c    uncompr.c  zutil.c
+
+OBJS =      adler32.obj  compress.obj crc32.obj   deflate.obj    &
+           gzclose.obj  gzlib.obj    gzread.obj  gzwrite.obj    &
+            infback.obj  inffast.obj  inflate.obj inftrees.obj   &
+            trees.obj    uncompr.obj  zutil.obj
+
+CC       = wcc386
+LINKER   = wcl386
+CFLAGS   = -zq -mf -3r -fp3 -s -bt=dos -oilrtfm -fr=nul -wx
+ZLIB_LIB = zlib_f.lib
+
+.C.OBJ:
+        $(CC) $(CFLAGS) $[@
+
+all: $(ZLIB_LIB) example.exe minigzip.exe
+
+$(ZLIB_LIB): $(OBJS)
+       wlib -b -c $(ZLIB_LIB) -+adler32.obj  -+compress.obj -+crc32.obj
+       wlib -b -c $(ZLIB_LIB) -+gzclose.obj  -+gzlib.obj    -+gzread.obj   -+gzwrite.obj
+        wlib -b -c $(ZLIB_LIB) -+deflate.obj  -+infback.obj
+        wlib -b -c $(ZLIB_LIB) -+inffast.obj  -+inflate.obj  -+inftrees.obj
+        wlib -b -c $(ZLIB_LIB) -+trees.obj    -+uncompr.obj  -+zutil.obj
+
+example.exe: $(ZLIB_LIB) example.obj
+       $(LINKER) -ldos32a -fe=example.exe example.obj $(ZLIB_LIB)
+
+minigzip.exe: $(ZLIB_LIB) minigzip.obj
+       $(LINKER) -ldos32a -fe=minigzip.exe minigzip.obj $(ZLIB_LIB)
+
+clean: .SYMBOLIC
+          del *.obj
+          del $(ZLIB_LIB)
+          @echo Cleaning done
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/watcom/watcom_l.mak b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/watcom/watcom_l.mak
new file mode 100644 (file)
index 0000000..193eed7
--- /dev/null
@@ -0,0 +1,43 @@
+# Makefile for zlib
+# OpenWatcom large model
+# Last updated: 28-Dec-2005
+
+# To use, do "wmake -f watcom_l.mak"
+
+C_SOURCE =  adler32.c  compress.c crc32.c   deflate.c    &
+           gzclose.c  gzlib.c    gzread.c  gzwrite.c    &
+            infback.c  inffast.c  inflate.c inftrees.c   &
+            trees.c    uncompr.c  zutil.c
+
+OBJS =      adler32.obj  compress.obj crc32.obj   deflate.obj    &
+           gzclose.obj  gzlib.obj    gzread.obj  gzwrite.obj    &
+            infback.obj  inffast.obj  inflate.obj inftrees.obj   &
+            trees.obj    uncompr.obj  zutil.obj
+
+CC       = wcc
+LINKER   = wcl
+CFLAGS   = -zq -ml -s -bt=dos -oilrtfm -fr=nul -wx
+ZLIB_LIB = zlib_l.lib
+
+.C.OBJ:
+        $(CC) $(CFLAGS) $[@
+
+all: $(ZLIB_LIB) example.exe minigzip.exe
+
+$(ZLIB_LIB): $(OBJS)
+       wlib -b -c $(ZLIB_LIB) -+adler32.obj  -+compress.obj -+crc32.obj
+       wlib -b -c $(ZLIB_LIB) -+gzclose.obj  -+gzlib.obj    -+gzread.obj   -+gzwrite.obj
+        wlib -b -c $(ZLIB_LIB) -+deflate.obj  -+infback.obj
+        wlib -b -c $(ZLIB_LIB) -+inffast.obj  -+inflate.obj  -+inftrees.obj
+        wlib -b -c $(ZLIB_LIB) -+trees.obj    -+uncompr.obj  -+zutil.obj
+
+example.exe: $(ZLIB_LIB) example.obj
+       $(LINKER) -fe=example.exe example.obj $(ZLIB_LIB)
+
+minigzip.exe: $(ZLIB_LIB) minigzip.obj
+       $(LINKER) -fe=minigzip.exe minigzip.obj $(ZLIB_LIB)
+
+clean: .SYMBOLIC
+          del *.obj
+          del $(ZLIB_LIB)
+          @echo Cleaning done
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/DLL_FAQ.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/DLL_FAQ.txt
new file mode 100644 (file)
index 0000000..12c0090
--- /dev/null
@@ -0,0 +1,397 @@
+
+            Frequently Asked Questions about ZLIB1.DLL
+
+
+This document describes the design, the rationale, and the usage
+of the official DLL build of zlib, named ZLIB1.DLL.  If you have
+general questions about zlib, you should see the file "FAQ" found
+in the zlib distribution, or at the following location:
+  http://www.gzip.org/zlib/zlib_faq.html
+
+
+ 1. What is ZLIB1.DLL, and how can I get it?
+
+  - ZLIB1.DLL is the official build of zlib as a DLL.
+    (Please remark the character '1' in the name.)
+
+    Pointers to a precompiled ZLIB1.DLL can be found in the zlib
+    web site at:
+      http://www.zlib.net/
+
+    Applications that link to ZLIB1.DLL can rely on the following
+    specification:
+
+    * The exported symbols are exclusively defined in the source
+      files "zlib.h" and "zlib.def", found in an official zlib
+      source distribution.
+    * The symbols are exported by name, not by ordinal.
+    * The exported names are undecorated.
+    * The calling convention of functions is "C" (CDECL).
+    * The ZLIB1.DLL binary is linked to MSVCRT.DLL.
+
+    The archive in which ZLIB1.DLL is bundled contains compiled
+    test programs that must run with a valid build of ZLIB1.DLL.
+    It is recommended to download the prebuilt DLL from the zlib
+    web site, instead of building it yourself, to avoid potential
+    incompatibilities that could be introduced by your compiler
+    and build settings.  If you do build the DLL yourself, please
+    make sure that it complies with all the above requirements,
+    and it runs with the precompiled test programs, bundled with
+    the original ZLIB1.DLL distribution.
+
+    If, for any reason, you need to build an incompatible DLL,
+    please use a different file name.
+
+
+ 2. Why did you change the name of the DLL to ZLIB1.DLL?
+    What happened to the old ZLIB.DLL?
+
+  - The old ZLIB.DLL, built from zlib-1.1.4 or earlier, required
+    compilation settings that were incompatible to those used by
+    a static build.  The DLL settings were supposed to be enabled
+    by defining the macro ZLIB_DLL, before including "zlib.h".
+    Incorrect handling of this macro was silently accepted at
+    build time, resulting in two major problems:
+
+    * ZLIB_DLL was missing from the old makefile.  When building
+      the DLL, not all people added it to the build options.  In
+      consequence, incompatible incarnations of ZLIB.DLL started
+      to circulate around the net.
+
+    * When switching from using the static library to using the
+      DLL, applications had to define the ZLIB_DLL macro and
+      to recompile all the sources that contained calls to zlib
+      functions.  Failure to do so resulted in creating binaries
+      that were unable to run with the official ZLIB.DLL build.
+
+    The only possible solution that we could foresee was to make
+    a binary-incompatible change in the DLL interface, in order to
+    remove the dependency on the ZLIB_DLL macro, and to release
+    the new DLL under a different name.
+
+    We chose the name ZLIB1.DLL, where '1' indicates the major
+    zlib version number.  We hope that we will not have to break
+    the binary compatibility again, at least not as long as the
+    zlib-1.x series will last.
+
+    There is still a ZLIB_DLL macro, that can trigger a more
+    efficient build and use of the DLL, but compatibility no
+    longer dependents on it.
+
+
+ 3. Can I build ZLIB.DLL from the new zlib sources, and replace
+    an old ZLIB.DLL, that was built from zlib-1.1.4 or earlier?
+
+  - In principle, you can do it by assigning calling convention
+    keywords to the macros ZEXPORT and ZEXPORTVA.  In practice,
+    it depends on what you mean by "an old ZLIB.DLL", because the
+    old DLL exists in several mutually-incompatible versions.
+    You have to find out first what kind of calling convention is
+    being used in your particular ZLIB.DLL build, and to use the
+    same one in the new build.  If you don't know what this is all
+    about, you might be better off if you would just leave the old
+    DLL intact.
+
+
+ 4. Can I compile my application using the new zlib interface, and
+    link it to an old ZLIB.DLL, that was built from zlib-1.1.4 or
+    earlier?
+
+  - The official answer is "no"; the real answer depends again on
+    what kind of ZLIB.DLL you have.  Even if you are lucky, this
+    course of action is unreliable.
+
+    If you rebuild your application and you intend to use a newer
+    version of zlib (post- 1.1.4), it is strongly recommended to
+    link it to the new ZLIB1.DLL.
+
+
+ 5. Why are the zlib symbols exported by name, and not by ordinal?
+
+  - Although exporting symbols by ordinal is a little faster, it
+    is risky.  Any single glitch in the maintenance or use of the
+    DEF file that contains the ordinals can result in incompatible
+    builds and frustrating crashes.  Simply put, the benefits of
+    exporting symbols by ordinal do not justify the risks.
+
+    Technically, it should be possible to maintain ordinals in
+    the DEF file, and still export the symbols by name.  Ordinals
+    exist in every DLL, and even if the dynamic linking performed
+    at the DLL startup is searching for names, ordinals serve as
+    hints, for a faster name lookup.  However, if the DEF file
+    contains ordinals, the Microsoft linker automatically builds
+    an implib that will cause the executables linked to it to use
+    those ordinals, and not the names.  It is interesting to
+    notice that the GNU linker for Win32 does not suffer from this
+    problem.
+
+    It is possible to avoid the DEF file if the exported symbols
+    are accompanied by a "__declspec(dllexport)" attribute in the
+    source files.  You can do this in zlib by predefining the
+    ZLIB_DLL macro.
+
+
+ 6. I see that the ZLIB1.DLL functions use the "C" (CDECL) calling
+    convention.  Why not use the STDCALL convention?
+    STDCALL is the standard convention in Win32, and I need it in
+    my Visual Basic project!
+
+    (For readability, we use CDECL to refer to the convention
+     triggered by the "__cdecl" keyword, STDCALL to refer to
+     the convention triggered by "__stdcall", and FASTCALL to
+     refer to the convention triggered by "__fastcall".)
+
+  - Most of the native Windows API functions (without varargs) use
+    indeed the WINAPI convention (which translates to STDCALL in
+    Win32), but the standard C functions use CDECL.  If a user
+    application is intrinsically tied to the Windows API (e.g.
+    it calls native Windows API functions such as CreateFile()),
+    sometimes it makes sense to decorate its own functions with
+    WINAPI.  But if ANSI C or POSIX portability is a goal (e.g.
+    it calls standard C functions such as fopen()), it is not a
+    sound decision to request the inclusion of <windows.h>, or to
+    use non-ANSI constructs, for the sole purpose to make the user
+    functions STDCALL-able.
+
+    The functionality offered by zlib is not in the category of
+    "Windows functionality", but is more like "C functionality".
+
+    Technically, STDCALL is not bad; in fact, it is slightly
+    faster than CDECL, and it works with variable-argument
+    functions, just like CDECL.  It is unfortunate that, in spite
+    of using STDCALL in the Windows API, it is not the default
+    convention used by the C compilers that run under Windows.
+    The roots of the problem reside deep inside the unsafety of
+    the K&R-style function prototypes, where the argument types
+    are not specified; but that is another story for another day.
+
+    The remaining fact is that CDECL is the default convention.
+    Even if an explicit convention is hard-coded into the function
+    prototypes inside C headers, problems may appear.  The
+    necessity to expose the convention in users' callbacks is one
+    of these problems.
+
+    The calling convention issues are also important when using
+    zlib in other programming languages.  Some of them, like Ada
+    (GNAT) and Fortran (GNU G77), have C bindings implemented
+    initially on Unix, and relying on the C calling convention.
+    On the other hand, the pre- .NET versions of Microsoft Visual
+    Basic require STDCALL, while Borland Delphi prefers, although
+    it does not require, FASTCALL.
+
+    In fairness to all possible uses of zlib outside the C
+    programming language, we choose the default "C" convention.
+    Anyone interested in different bindings or conventions is
+    encouraged to maintain specialized projects.  The "contrib/"
+    directory from the zlib distribution already holds a couple
+    of foreign bindings, such as Ada, C++, and Delphi.
+
+
+ 7. I need a DLL for my Visual Basic project.  What can I do?
+
+  - Define the ZLIB_WINAPI macro before including "zlib.h", when
+    building both the DLL and the user application (except that
+    you don't need to define anything when using the DLL in Visual
+    Basic).  The ZLIB_WINAPI macro will switch on the WINAPI
+    (STDCALL) convention.  The name of this DLL must be different
+    than the official ZLIB1.DLL.
+
+    Gilles Vollant has contributed a build named ZLIBWAPI.DLL,
+    with the ZLIB_WINAPI macro turned on, and with the minizip
+    functionality built in.  For more information, please read
+    the notes inside "contrib/vstudio/readme.txt", found in the
+    zlib distribution.
+
+
+ 8. I need to use zlib in my Microsoft .NET project.  What can I
+    do?
+
+  - Henrik Ravn has contributed a .NET wrapper around zlib.  Look
+    into contrib/dotzlib/, inside the zlib distribution.
+
+
+ 9. If my application uses ZLIB1.DLL, should I link it to
+    MSVCRT.DLL?  Why?
+
+  - It is not required, but it is recommended to link your
+    application to MSVCRT.DLL, if it uses ZLIB1.DLL.
+
+    The executables (.EXE, .DLL, etc.) that are involved in the
+    same process and are using the C run-time library (i.e. they
+    are calling standard C functions), must link to the same
+    library.  There are several libraries in the Win32 system:
+    CRTDLL.DLL, MSVCRT.DLL, the static C libraries, etc.
+    Since ZLIB1.DLL is linked to MSVCRT.DLL, the executables that
+    depend on it should also be linked to MSVCRT.DLL.
+
+
+10. Why are you saying that ZLIB1.DLL and my application should
+    be linked to the same C run-time (CRT) library?  I linked my
+    application and my DLLs to different C libraries (e.g. my
+    application to a static library, and my DLLs to MSVCRT.DLL),
+    and everything works fine.
+
+  - If a user library invokes only pure Win32 API (accessible via
+    <windows.h> and the related headers), its DLL build will work
+    in any context.  But if this library invokes standard C API,
+    things get more complicated.
+
+    There is a single Win32 library in a Win32 system.  Every
+    function in this library resides in a single DLL module, that
+    is safe to call from anywhere.  On the other hand, there are
+    multiple versions of the C library, and each of them has its
+    own separate internal state.  Standalone executables and user
+    DLLs that call standard C functions must link to a C run-time
+    (CRT) library, be it static or shared (DLL).  Intermixing
+    occurs when an executable (not necessarily standalone) and a
+    DLL are linked to different CRTs, and both are running in the
+    same process.
+
+    Intermixing multiple CRTs is possible, as long as their
+    internal states are kept intact.  The Microsoft Knowledge Base
+    articles KB94248 "HOWTO: Use the C Run-Time" and KB140584
+    "HOWTO: Link with the Correct C Run-Time (CRT) Library"
+    mention the potential problems raised by intermixing.
+
+    If intermixing works for you, it's because your application
+    and DLLs are avoiding the corruption of each of the CRTs'
+    internal states, maybe by careful design, or maybe by fortune.
+
+    Also note that linking ZLIB1.DLL to non-Microsoft CRTs, such
+    as those provided by Borland, raises similar problems.
+
+
+11. Why are you linking ZLIB1.DLL to MSVCRT.DLL?
+
+  - MSVCRT.DLL exists on every Windows 95 with a new service pack
+    installed, or with Microsoft Internet Explorer 4 or later, and
+    on all other Windows 4.x or later (Windows 98, Windows NT 4,
+    or later).  It is freely distributable; if not present in the
+    system, it can be downloaded from Microsoft or from other
+    software provider for free.
+
+    The fact that MSVCRT.DLL does not exist on a virgin Windows 95
+    is not so problematic.  Windows 95 is scarcely found nowadays,
+    Microsoft ended its support a long time ago, and many recent
+    applications from various vendors, including Microsoft, do not
+    even run on it.  Furthermore, no serious user should run
+    Windows 95 without a proper update installed.
+
+
+12. Why are you not linking ZLIB1.DLL to
+    <<my favorite C run-time library>> ?
+
+  - We considered and abandoned the following alternatives:
+
+    * Linking ZLIB1.DLL to a static C library (LIBC.LIB, or
+      LIBCMT.LIB) is not a good option.  People are using the DLL
+      mainly to save disk space.  If you are linking your program
+      to a static C library, you may as well consider linking zlib
+      in statically, too.
+
+    * Linking ZLIB1.DLL to CRTDLL.DLL looks appealing, because
+      CRTDLL.DLL is present on every Win32 installation.
+      Unfortunately, it has a series of problems: it does not
+      work properly with Microsoft's C++ libraries, it does not
+      provide support for 64-bit file offsets, (and so on...),
+      and Microsoft discontinued its support a long time ago.
+
+    * Linking ZLIB1.DLL to MSVCR70.DLL or MSVCR71.DLL, supplied
+      with the Microsoft .NET platform, and Visual C++ 7.0/7.1,
+      raises problems related to the status of ZLIB1.DLL as a
+      system component.  According to the Microsoft Knowledge Base
+      article KB326922 "INFO: Redistribution of the Shared C
+      Runtime Component in Visual C++ .NET", MSVCR70.DLL and
+      MSVCR71.DLL are not supposed to function as system DLLs,
+      because they may clash with MSVCRT.DLL.  Instead, the
+      application's installer is supposed to put these DLLs
+      (if needed) in the application's private directory.
+      If ZLIB1.DLL depends on a non-system runtime, it cannot
+      function as a redistributable system component.
+
+    * Linking ZLIB1.DLL to non-Microsoft runtimes, such as
+      Borland's, or Cygwin's, raises problems related to the
+      reliable presence of these runtimes on Win32 systems.
+      It's easier to let the DLL build of zlib up to the people
+      who distribute these runtimes, and who may proceed as
+      explained in the answer to Question 14.
+
+
+13. If ZLIB1.DLL cannot be linked to MSVCR70.DLL or MSVCR71.DLL,
+    how can I build/use ZLIB1.DLL in Microsoft Visual C++ 7.0
+    (Visual Studio .NET) or newer?
+
+  - Due to the problems explained in the Microsoft Knowledge Base
+    article KB326922 (see the previous answer), the C runtime that
+    comes with the VC7 environment is no longer considered a
+    system component.  That is, it should not be assumed that this
+    runtime exists, or may be installed in a system directory.
+    Since ZLIB1.DLL is supposed to be a system component, it may
+    not depend on a non-system component.
+
+    In order to link ZLIB1.DLL and your application to MSVCRT.DLL
+    in VC7, you need the library of Visual C++ 6.0 or older.  If
+    you don't have this library at hand, it's probably best not to
+    use ZLIB1.DLL.
+
+    We are hoping that, in the future, Microsoft will provide a
+    way to build applications linked to a proper system runtime,
+    from the Visual C++ environment.  Until then, you have a
+    couple of alternatives, such as linking zlib in statically.
+    If your application requires dynamic linking, you may proceed
+    as explained in the answer to Question 14.
+
+
+14. I need to link my own DLL build to a CRT different than
+    MSVCRT.DLL.  What can I do?
+
+  - Feel free to rebuild the DLL from the zlib sources, and link
+    it the way you want.  You should, however, clearly state that
+    your build is unofficial.  You should give it a different file
+    name, and/or install it in a private directory that can be
+    accessed by your application only, and is not visible to the
+    others (i.e. it's neither in the PATH, nor in the SYSTEM or
+    SYSTEM32 directories).  Otherwise, your build may clash with
+    applications that link to the official build.
+
+    For example, in Cygwin, zlib is linked to the Cygwin runtime
+    CYGWIN1.DLL, and it is distributed under the name CYGZ.DLL.
+
+
+15. May I include additional pieces of code that I find useful,
+    link them in ZLIB1.DLL, and export them?
+
+  - No.  A legitimate build of ZLIB1.DLL must not include code
+    that does not originate from the official zlib source code.
+    But you can make your own private DLL build, under a different
+    file name, as suggested in the previous answer.
+
+    For example, zlib is a part of the VCL library, distributed
+    with Borland Delphi and C++ Builder.  The DLL build of VCL
+    is a redistributable file, named VCLxx.DLL.
+
+
+16. May I remove some functionality out of ZLIB1.DLL, by enabling
+    macros like NO_GZCOMPRESS or NO_GZIP at compile time?
+
+  - No.  A legitimate build of ZLIB1.DLL must provide the complete
+    zlib functionality, as implemented in the official zlib source
+    code.  But you can make your own private DLL build, under a
+    different file name, as suggested in the previous answer.
+
+
+17. I made my own ZLIB1.DLL build.  Can I test it for compliance?
+
+  - We prefer that you download the official DLL from the zlib
+    web site.  If you need something peculiar from this DLL, you
+    can send your suggestion to the zlib mailing list.
+
+    However, in case you do rebuild the DLL yourself, you can run
+    it with the test programs found in the DLL distribution.
+    Running these test programs is not a guarantee of compliance,
+    but a failure can imply a detected problem.
+
+**
+
+This document is written and maintained by
+Cosmin Truta <cosmint@cs.ubbcluj.ro>
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.bor b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.bor
new file mode 100644 (file)
index 0000000..d152bbb
--- /dev/null
@@ -0,0 +1,110 @@
+# Makefile for zlib
+# Borland C++ for Win32
+#
+# Usage:
+#  make -f win32/Makefile.bor
+#  make -f win32/Makefile.bor LOCAL_ZLIB=-DASMV OBJA=match.obj OBJPA=+match.obj
+
+# ------------ Borland C++ ------------
+
+# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7)
+# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or
+# added to the declaration of LOC here:
+LOC = $(LOCAL_ZLIB)
+
+CC = bcc32
+AS = bcc32
+LD = bcc32
+AR = tlib
+CFLAGS  = -a -d -k- -O2 $(LOC)
+ASFLAGS = $(LOC)
+LDFLAGS = $(LOC)
+
+
+# variables
+ZLIB_LIB = zlib.lib
+
+OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj
+OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
+#OBJA =
+OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj
+OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
+#OBJPA=
+
+
+# targets
+all: $(ZLIB_LIB) example.exe minigzip.exe
+
+.c.obj:
+       $(CC) -c $(CFLAGS) $<
+
+.asm.obj:
+       $(AS) -c $(ASFLAGS) $<
+
+adler32.obj: adler32.c zlib.h zconf.h
+
+compress.obj: compress.c zlib.h zconf.h
+
+crc32.obj: crc32.c zlib.h zconf.h crc32.h
+
+deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
+
+gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
+
+gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
+
+gzread.obj: gzread.c zlib.h zconf.h gzguts.h
+
+gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
+
+infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h
+
+inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h
+
+trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h
+
+uncompr.obj: uncompr.c zlib.h zconf.h
+
+zutil.obj: zutil.c zutil.h zlib.h zconf.h
+
+example.obj: test/example.c zlib.h zconf.h
+
+minigzip.obj: test/minigzip.c zlib.h zconf.h
+
+
+# For the sake of the old Borland make,
+# the command line is cut to fit in the MS-DOS 128 byte limit:
+$(ZLIB_LIB): $(OBJ1) $(OBJ2) $(OBJA)
+       -del $(ZLIB_LIB)
+       $(AR) $(ZLIB_LIB) $(OBJP1)
+       $(AR) $(ZLIB_LIB) $(OBJP2)
+       $(AR) $(ZLIB_LIB) $(OBJPA)
+
+
+# testing
+test: example.exe minigzip.exe
+       example
+       echo hello world | minigzip | minigzip -d
+
+example.exe: example.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB)
+
+minigzip.exe: minigzip.obj $(ZLIB_LIB)
+       $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB)
+
+
+# cleanup
+clean:
+       -del $(ZLIB_LIB)
+       -del *.obj
+       -del *.exe
+       -del *.tds
+       -del zlib.bak
+       -del foo.gz
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.emx b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.emx
new file mode 100644 (file)
index 0000000..4d6ab0e
--- /dev/null
@@ -0,0 +1,69 @@
+# Makefile for zlib.  Modified for emx/rsxnt by Chr. Spieler, 6/16/98.
+# Copyright (C) 1995-1998 Jean-loup Gailly.
+# For conditions of distribution and use, see copyright notice in zlib.h
+
+# To compile, or to compile and test, type:
+#
+#   make -fmakefile.emx;  make test -fmakefile.emx
+#
+
+CC=gcc -Zwin32
+
+#CFLAGS=-MMD -O
+#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
+#CFLAGS=-MMD -g -DDEBUG
+CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
+             -Wstrict-prototypes -Wmissing-prototypes
+
+# If cp.exe is available, replace "copy /Y" with "cp -fp" .
+CP=copy /Y
+# If gnu install.exe is available, replace $(CP) with ginstall.
+INSTALL=$(CP)
+# The default value of RM is "rm -f."  If "rm.exe" is found, comment out:
+RM=del
+LDLIBS=-L. -lzlib
+LD=$(CC) -s -o
+LDSHARED=$(CC)
+
+INCL=zlib.h zconf.h
+LIBS=zlib.a
+
+AR=ar rcs
+
+prefix=/usr/local
+exec_prefix = $(prefix)
+
+OBJS = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \
+       gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o
+
+TEST_OBJS = example.o minigzip.o
+
+all: example.exe minigzip.exe
+
+test: all
+       ./example
+       echo hello world | .\minigzip | .\minigzip -d
+
+%.o : %.c
+       $(CC) $(CFLAGS) -c $< -o $@
+
+zlib.a: $(OBJS)
+       $(AR) $@ $(OBJS)
+
+%.exe : %.o $(LIBS)
+       $(LD) $@ $< $(LDLIBS)
+
+
+.PHONY : clean
+
+clean:
+       $(RM) *.d
+       $(RM) *.o
+       $(RM) *.exe
+       $(RM) zlib.a
+       $(RM) foo.gz
+
+DEPS := $(wildcard *.d)
+ifneq ($(DEPS),)
+include $(DEPS)
+endif
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.gcc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.gcc
new file mode 100644 (file)
index 0000000..c4a6589
--- /dev/null
@@ -0,0 +1,180 @@
+# Makefile for zlib, derived from Makefile.dj2.
+# Modified for mingw32 by C. Spieler, 6/16/98.
+# Updated for zlib 1.2.x by Christian Spieler and Cosmin Truta, Mar-2003.
+# Last updated: 1-Aug-2003.
+# Tested under Cygwin and MinGW.
+
+# Copyright (C) 1995-2003 Jean-loup Gailly.
+# For conditions of distribution and use, see copyright notice in zlib.h
+
+# To compile, or to compile and test, type:
+#
+#   make -fmakefile.gcc;  make test testdll -fmakefile.gcc
+#
+# To use the asm code, type:
+#   cp contrib/asm?86/match.S ./match.S
+#   make LOC=-DASMV OBJA=match.o -fmakefile.gcc
+#
+# To install libz.a, zconf.h and zlib.h in the system directories, type:
+#
+#   make install -fmakefile.gcc
+
+# Note:
+# If the platform is *not* MinGW (e.g. it is Cygwin or UWIN),
+# the DLL name should be changed from "zlib1.dll".
+
+STATICLIB = libz.a
+SHAREDLIB = zlib1.dll
+IMPLIB    = libz.dll.a
+
+#
+# Set to 1 if shared object needs to be installed
+#
+SHARED_MODE=0
+
+#LOC = -DASMV
+#LOC = -DDEBUG -g
+
+PREFIX =
+CC = $(PREFIX)gcc
+CFLAGS = $(LOC) -O3 -Wall
+EXTRA_CFLAGS = -DNO_VIZ
+
+AS = $(CC)
+ASFLAGS = $(LOC) -Wall
+
+LD = $(CC)
+LDFLAGS = $(LOC)
+
+AR = $(PREFIX)ar
+ARFLAGS = rcs
+
+RC = $(PREFIX)windres
+RCFLAGS = --define GCC_WINDRES
+
+STRIP = $(PREFIX)strip
+
+CP = cp -fp
+# If GNU install is available, replace $(CP) with install.
+INSTALL = $(CP)
+RM = rm -f
+
+prefix ?= /usr/local
+exec_prefix = $(prefix)
+
+OBJS = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \
+       gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o
+OBJA =
+
+all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) example.exe minigzip.exe example_d.exe minigzip_d.exe
+
+test: example.exe minigzip.exe
+       ./example
+       echo hello world | ./minigzip | ./minigzip -d
+
+testdll: example_d.exe minigzip_d.exe
+       ./example_d
+       echo hello world | ./minigzip_d | ./minigzip_d -d
+
+.c.o:
+       $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -c -o $@ $<
+
+.S.o:
+       $(AS) $(ASFLAGS) -c -o $@ $<
+
+$(STATICLIB): $(OBJS) $(OBJA)
+       $(AR) $(ARFLAGS) $@ $(OBJS) $(OBJA)
+
+$(IMPLIB): $(SHAREDLIB)
+
+$(SHAREDLIB): win32/zlib.def $(OBJS) $(OBJA) zlibrc.o
+       $(CC) -shared -Wl,--out-implib,$(IMPLIB) $(LDFLAGS) \
+       -o $@ win32/zlib.def $(OBJS) $(OBJA) zlibrc.o
+       $(STRIP) $@
+
+example.exe: example.o $(STATICLIB)
+       $(LD) $(LDFLAGS) -o $@ example.o $(STATICLIB)
+       $(STRIP) $@
+
+minigzip.exe: minigzip.o $(STATICLIB)
+       $(LD) $(LDFLAGS) -o $@ minigzip.o $(STATICLIB)
+       $(STRIP) $@
+
+example_d.exe: example.o $(IMPLIB)
+       $(LD) $(LDFLAGS) -o $@ example.o $(IMPLIB)
+       $(STRIP) $@
+
+minigzip_d.exe: minigzip.o $(IMPLIB)
+       $(LD) $(LDFLAGS) -o $@ minigzip.o $(IMPLIB)
+       $(STRIP) $@
+
+example.o: test/example.c zlib.h zconf.h
+       $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -I. -c -o $@ test/example.c
+
+minigzip.o: test/minigzip.c zlib.h zconf.h
+       $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -I. -c -o $@ test/minigzip.c
+
+zlibrc.o: win32/zlib1.rc
+       $(RC) $(RCFLAGS) -o $@ win32/zlib1.rc
+
+
+# BINARY_PATH, INCLUDE_PATH and LIBRARY_PATH must be set.
+
+.PHONY: install uninstall clean
+
+install: zlib.h zconf.h $(STATICLIB) $(IMPLIB)
+       @if test -z "$(INCLUDE_PATH)" -o -z "$(LIBRARY_PATH)" -o -z "$(BINARY_PATH)"; then \
+               echo INCLUDE_PATH, LIBRARY_PATH, and BINARY_PATH must be specified; \
+               exit 1; \
+       fi
+       -@mkdir -p $(INCLUDE_PATH)
+       -@mkdir -p $(LIBRARY_PATH) $(LIBRARY_PATH)/pkgconfig
+       -if [ "$(SHARED_MODE)" = "1" ]; then \
+               mkdir -p $(BINARY_PATH); \
+               $(INSTALL) $(SHAREDLIB) $(BINARY_PATH); \
+               $(INSTALL) $(IMPLIB) $(LIBRARY_PATH); \
+       fi
+       -$(INSTALL) zlib.h $(INCLUDE_PATH)
+       -$(INSTALL) zconf.h $(INCLUDE_PATH)
+       -$(INSTALL) $(STATICLIB) $(LIBRARY_PATH)
+       sed \
+               -e 's|@prefix@|${prefix}|g' \
+               -e 's|@exec_prefix@|${exec_prefix}|g' \
+               -e 's|@libdir@|$(LIBRARY_PATH)|g' \
+               -e 's|@sharedlibdir@|$(LIBRARY_PATH)|g' \
+               -e 's|@includedir@|$(INCLUDE_PATH)|g' \
+               -e 's|@VERSION@|'`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' zlib.h`'|g' \
+               zlib.pc.in > $(LIBRARY_PATH)/pkgconfig/zlib.pc
+
+uninstall:
+       -if [ "$(SHARED_MODE)" = "1" ]; then \
+               $(RM) $(BINARY_PATH)/$(SHAREDLIB); \
+               $(RM) $(LIBRARY_PATH)/$(IMPLIB); \
+       fi
+       -$(RM) $(INCLUDE_PATH)/zlib.h
+       -$(RM) $(INCLUDE_PATH)/zconf.h
+       -$(RM) $(LIBRARY_PATH)/$(STATICLIB)
+
+clean:
+       -$(RM) $(STATICLIB)
+       -$(RM) $(SHAREDLIB)
+       -$(RM) $(IMPLIB)
+       -$(RM) *.o
+       -$(RM) *.exe
+       -$(RM) foo.gz
+
+adler32.o: zlib.h zconf.h
+compress.o: zlib.h zconf.h
+crc32.o: crc32.h zlib.h zconf.h
+deflate.o: deflate.h zutil.h zlib.h zconf.h
+gzclose.o: zlib.h zconf.h gzguts.h
+gzlib.o: zlib.h zconf.h gzguts.h
+gzread.o: zlib.h zconf.h gzguts.h
+gzwrite.o: zlib.h zconf.h gzguts.h
+inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inftrees.o: zutil.h zlib.h zconf.h inftrees.h
+trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
+uncompr.o: zlib.h zconf.h
+zutil.o: zutil.h zlib.h zconf.h
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.msc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/Makefile.msc
new file mode 100644 (file)
index 0000000..59bb0da
--- /dev/null
@@ -0,0 +1,160 @@
+# Makefile for zlib using Microsoft (Visual) C
+# zlib is copyright (C) 1995-2006 Jean-loup Gailly and Mark Adler
+#
+# Usage:
+#   nmake -f win32/Makefile.msc                          (standard build)
+#   nmake -f win32/Makefile.msc LOC=-DFOO                (nonstandard build)
+#   nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" \
+#         OBJA="inffas32.obj match686.obj"               (use ASM code, x86)
+#   nmake -f win32/Makefile.msc AS=ml64 LOC="-DASMV -DASMINF -I." \
+#         OBJA="inffasx64.obj gvmat64.obj inffas8664.obj"  (use ASM code, x64)
+
+# optional build flags
+LOC =
+
+# variables
+STATICLIB = zlib.lib
+SHAREDLIB = zlib1.dll
+IMPLIB    = zdll.lib
+
+CC = cl
+AS = ml
+LD = link
+AR = lib
+RC = rc
+CFLAGS  = -nologo -MD -W3 -O2 -Oy- -Zi -Fd"zlib" $(LOC)
+WFLAGS  = -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE
+ASFLAGS = -coff -Zi $(LOC)
+LDFLAGS = -nologo -debug -incremental:no -opt:ref
+ARFLAGS = -nologo
+RCFLAGS = /dWIN32 /r
+
+OBJS = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj \
+       gzwrite.obj infback.obj inflate.obj inftrees.obj inffast.obj trees.obj uncompr.obj zutil.obj
+OBJA =
+
+
+# targets
+all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) \
+     example.exe minigzip.exe example_d.exe minigzip_d.exe
+
+$(STATICLIB): $(OBJS) $(OBJA)
+       $(AR) $(ARFLAGS) -out:$@ $(OBJS) $(OBJA)
+
+$(IMPLIB): $(SHAREDLIB)
+
+$(SHAREDLIB): win32/zlib.def $(OBJS) $(OBJA) zlib1.res
+       $(LD) $(LDFLAGS) -def:win32/zlib.def -dll -implib:$(IMPLIB) \
+         -out:$@ -base:0x5A4C0000 $(OBJS) $(OBJA) zlib1.res
+       if exist $@.manifest \
+         mt -nologo -manifest $@.manifest -outputresource:$@;2
+
+example.exe: example.obj $(STATICLIB)
+       $(LD) $(LDFLAGS) example.obj $(STATICLIB)
+       if exist $@.manifest \
+         mt -nologo -manifest $@.manifest -outputresource:$@;1
+
+minigzip.exe: minigzip.obj $(STATICLIB)
+       $(LD) $(LDFLAGS) minigzip.obj $(STATICLIB)
+       if exist $@.manifest \
+         mt -nologo -manifest $@.manifest -outputresource:$@;1
+
+example_d.exe: example.obj $(IMPLIB)
+       $(LD) $(LDFLAGS) -out:$@ example.obj $(IMPLIB)
+       if exist $@.manifest \
+         mt -nologo -manifest $@.manifest -outputresource:$@;1
+
+minigzip_d.exe: minigzip.obj $(IMPLIB)
+       $(LD) $(LDFLAGS) -out:$@ minigzip.obj $(IMPLIB)
+       if exist $@.manifest \
+         mt -nologo -manifest $@.manifest -outputresource:$@;1
+
+.c.obj:
+       $(CC) -c $(WFLAGS) $(CFLAGS) $<
+
+{test}.c.obj:
+       $(CC) -c -I. $(WFLAGS) $(CFLAGS) $<
+
+{contrib/masmx64}.c.obj:
+       $(CC) -c $(WFLAGS) $(CFLAGS) $<
+
+{contrib/masmx64}.asm.obj:
+       $(AS) -c $(ASFLAGS) $<
+
+{contrib/masmx86}.asm.obj:
+       $(AS) -c $(ASFLAGS) $<
+
+adler32.obj: adler32.c zlib.h zconf.h
+
+compress.obj: compress.c zlib.h zconf.h
+
+crc32.obj: crc32.c zlib.h zconf.h crc32.h
+
+deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
+
+gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
+
+gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
+
+gzread.obj: gzread.c zlib.h zconf.h gzguts.h
+
+gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
+
+infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+             inffast.h inffixed.h
+
+inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+             inffast.h
+
+inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+             inffast.h inffixed.h
+
+inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h
+
+trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h
+
+uncompr.obj: uncompr.c zlib.h zconf.h
+
+zutil.obj: zutil.c zutil.h zlib.h zconf.h
+
+gvmat64.obj: contrib\masmx64\gvmat64.asm
+
+inffasx64.obj: contrib\masmx64\inffasx64.asm
+
+inffas8664.obj: contrib\masmx64\inffas8664.c zutil.h zlib.h zconf.h \
+               inftrees.h inflate.h inffast.h
+
+inffas32.obj: contrib\masmx86\inffas32.asm
+
+match686.obj: contrib\masmx86\match686.asm
+
+example.obj: test/example.c zlib.h zconf.h
+
+minigzip.obj: test/minigzip.c zlib.h zconf.h
+
+zlib1.res: win32/zlib1.rc
+       $(RC) $(RCFLAGS) /fo$@ win32/zlib1.rc
+
+
+# testing
+test: example.exe minigzip.exe
+       example
+       echo hello world | minigzip | minigzip -d
+
+testdll: example_d.exe minigzip_d.exe
+       example_d
+       echo hello world | minigzip_d | minigzip_d -d
+
+
+# cleanup
+clean:
+       -del $(STATICLIB)
+       -del $(SHAREDLIB)
+       -del $(IMPLIB)
+       -del *.obj
+       -del *.res
+       -del *.exp
+       -del *.exe
+       -del *.pdb
+       -del *.manifest
+       -del foo.gz
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/README-WIN32.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/README-WIN32.txt
new file mode 100644 (file)
index 0000000..1e4c093
--- /dev/null
@@ -0,0 +1,103 @@
+ZLIB DATA COMPRESSION LIBRARY
+
+zlib 1.2.4 is a general purpose data compression library.  All the code is
+thread safe.  The data format used by the zlib library is described by RFCs
+(Request for Comments) 1950 to 1952 in the files
+http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format)
+and rfc1952.txt (gzip format).
+
+All functions of the compression library are documented in the file zlib.h
+(volunteer to write man pages welcome, contact zlib@gzip.org).  Two compiled
+examples are distributed in this package, example and minigzip.  The example_d
+and minigzip_d flavors validate that the zlib1.dll file is working correctly.
+
+Questions about zlib should be sent to <zlib@gzip.org>.  The zlib home page
+is http://zlib.net/ .  Before reporting a problem, please check this site to
+verify that you have the latest version of zlib; otherwise get the latest
+version and check whether the problem still exists or not.
+
+PLEASE read DLL_FAQ.txt, and the the zlib FAQ http://zlib.net/zlib_faq.html
+before asking for help.
+
+
+Manifest:
+
+The package zlib-1.2.4-win32-x86.zip contains the following files:
+
+  README-WIN32.txt This document
+  ChangeLog        Changes since previous zlib packages
+  DLL_FAQ.txt      Frequently asked questions about zlib1.dll
+  zlib.3.pdf       Documentation of this library in Adobe Acrobat format
+
+  example.exe      A statically-bound example (using zlib.lib, not the dll)
+  example.pdb      Symbolic information for debugging example.exe
+
+  example_d.exe    A zlib1.dll bound example (using zdll.lib)
+  example_d.pdb    Symbolic information for debugging example_d.exe
+
+  minigzip.exe     A statically-bound test program (using zlib.lib, not the dll)
+  minigzip.pdb     Symbolic information for debugging minigzip.exe
+
+  minigzip_d.exe   A zlib1.dll bound test program (using zdll.lib)
+  minigzip_d.pdb   Symbolic information for debugging minigzip_d.exe
+
+  zlib.h           Install these files into the compilers' INCLUDE path to
+  zconf.h          compile programs which use zlib.lib or zdll.lib
+
+  zdll.lib         Install these files into the compilers' LIB path if linking
+  zdll.exp         a compiled program to the zlib1.dll binary
+
+  zlib.lib         Install these files into the compilers' LIB path to link zlib
+  zlib.pdb         into compiled programs, without zlib1.dll runtime dependency
+                   (zlib.pdb provides debugging info to the compile time linker)
+
+  zlib1.dll        Install this binary shared library into the system PATH, or
+                   the program's runtime directory (where the .exe resides)
+  zlib1.pdb        Install in the same directory as zlib1.dll, in order to debug
+                   an application crash using WinDbg or similar tools.
+
+All .pdb files above are entirely optional, but are very useful to a developer
+attempting to diagnose program misbehavior or a crash.  Many additional
+important files for developers can be found in the zlib124.zip source package
+available from http://zlib.net/ - review that package's README file for details.
+
+
+Acknowledgments:
+
+The deflate format used by zlib was defined by Phil Katz.  The deflate and
+zlib specifications were written by L.  Peter Deutsch.  Thanks to all the
+people who reported problems and suggested various improvements in zlib; they
+are too numerous to cite here.
+
+
+Copyright notice:
+
+  (C) 1995-2010 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+If you use the zlib library in a product, we would appreciate *not* receiving
+lengthy legal documents to sign.  The sources are provided for free but without
+warranty of any kind.  The library has been entirely written by Jean-loup
+Gailly and Mark Adler; it does not include third-party code.
+
+If you redistribute modified sources, we would appreciate that you include in
+the file ChangeLog history information documenting your changes.  Please read
+the FAQ for more information on the distribution of modified source versions.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/VisualC.txt b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/VisualC.txt
new file mode 100644 (file)
index 0000000..579a5fc
--- /dev/null
@@ -0,0 +1,3 @@
+
+To build zlib using the Microsoft Visual C++ environment,
+use the appropriate project from the projects/ directory.
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/zlib.def b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/zlib.def
new file mode 100644 (file)
index 0000000..d96c18a
--- /dev/null
@@ -0,0 +1,84 @@
+; zlib data compression library
+EXPORTS
+; basic functions
+    zlibVersion
+    deflate
+    deflateEnd
+    inflate
+    inflateEnd
+; advanced functions
+    deflateSetDictionary
+    deflateCopy
+    deflateReset
+    deflateParams
+    deflateTune
+    deflateBound
+    deflatePending
+    deflatePrime
+    deflateSetHeader
+    inflateSetDictionary
+    inflateSync
+    inflateCopy
+    inflateReset
+    inflateReset2
+    inflatePrime
+    inflateMark
+    inflateGetHeader
+    inflateBack
+    inflateBackEnd
+    zlibCompileFlags
+; utility functions
+    compress
+    compress2
+    compressBound
+    uncompress
+    gzopen
+    gzdopen
+    gzbuffer
+    gzsetparams
+    gzread
+    gzwrite
+    gzprintf
+    gzputs
+    gzgets
+    gzputc
+    gzgetc
+    gzungetc
+    gzflush
+    gzseek
+    gzrewind
+    gztell
+    gzoffset
+    gzeof
+    gzdirect
+    gzclose
+    gzclose_r
+    gzclose_w
+    gzerror
+    gzclearerr
+; large file functions
+    gzopen64
+    gzseek64
+    gztell64
+    gzoffset64
+    adler32_combine64
+    crc32_combine64
+; checksum functions
+    adler32
+    crc32
+    adler32_combine
+    crc32_combine
+; various hacks, don't look :)
+    deflateInit_
+    deflateInit2_
+    inflateInit_
+    inflateInit2_
+    inflateBackInit_
+    zError
+    inflateSyncPoint
+    get_crc_table
+    inflateUndermine
+    inflateResetKeep
+    deflateResetKeep
+    gzgetc_
+    gzflags
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/zlib1.rc b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/win32/zlib1.rc
new file mode 100644 (file)
index 0000000..0d1d7ff
--- /dev/null
@@ -0,0 +1,40 @@
+#include <winver.h>
+#include "../zlib.h"
+
+#ifdef GCC_WINDRES
+VS_VERSION_INFO                VERSIONINFO
+#else
+VS_VERSION_INFO                VERSIONINFO     MOVEABLE IMPURE LOADONCALL DISCARDABLE
+#endif
+  FILEVERSION          ZLIB_VER_MAJOR,ZLIB_VER_MINOR,ZLIB_VER_REVISION,0
+  PRODUCTVERSION       ZLIB_VER_MAJOR,ZLIB_VER_MINOR,ZLIB_VER_REVISION,0
+  FILEFLAGSMASK                VS_FFI_FILEFLAGSMASK
+#ifdef _DEBUG
+  FILEFLAGS            1
+#else
+  FILEFLAGS            0
+#endif
+  FILEOS               VOS__WINDOWS32
+  FILETYPE             VFT_DLL
+  FILESUBTYPE          0       // not used
+BEGIN
+  BLOCK "StringFileInfo"
+  BEGIN
+    BLOCK "040904E4"
+    //language ID = U.S. English, char set = Windows, Multilingual
+    BEGIN
+      VALUE "FileDescription", "zlib data compression library\0"
+      VALUE "FileVersion",     ZLIB_VERSION "\0"
+      VALUE "InternalName",    "zlib1.dll\0"
+      VALUE "LegalCopyright",  "(C) 1995-2006 Jean-loup Gailly & Mark Adler\0"
+      VALUE "OriginalFilename",        "zlib1.dll\0"
+      VALUE "ProductName",     "zlib\0"
+      VALUE "ProductVersion",  ZLIB_VERSION "\0"
+      VALUE "Comments",                "For more information visit http://www.zlib.net/\0"
+    END
+  END
+  BLOCK "VarFileInfo"
+  BEGIN
+    VALUE "Translation", 0x0409, 1252
+  END
+END
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h
new file mode 100644 (file)
index 0000000..51c80ac
--- /dev/null
@@ -0,0 +1,466 @@
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2011 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZCONF_H
+#define ZCONF_H
+
+/*
+ * If you *really* need a unique prefix for all types and library functions,
+ * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
+ */
+#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
+#  define Z_PREFIX_SET
+
+/* all linked symbols */
+#  define _dist_code            z__dist_code
+#  define _length_code          z__length_code
+#  define _tr_align             z__tr_align
+#  define _tr_flush_block       z__tr_flush_block
+#  define _tr_init              z__tr_init
+#  define _tr_stored_block      z__tr_stored_block
+#  define _tr_tally             z__tr_tally
+#  define adler32               z_adler32
+#  define adler32_combine       z_adler32_combine
+#  define adler32_combine64     z_adler32_combine64
+#  ifndef Z_SOLO
+#    define compress              z_compress
+#    define compress2             z_compress2
+#    define compressBound         z_compressBound
+#  endif
+#  define crc32                 z_crc32
+#  define crc32_combine         z_crc32_combine
+#  define crc32_combine64       z_crc32_combine64
+#  define deflate               z_deflate
+#  define deflateBound          z_deflateBound
+#  define deflateCopy           z_deflateCopy
+#  define deflateEnd            z_deflateEnd
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateInit_          z_deflateInit_
+#  define deflateParams         z_deflateParams
+#  define deflatePending        z_deflatePending
+#  define deflatePrime          z_deflatePrime
+#  define deflateReset          z_deflateReset
+#  define deflateResetKeep      z_deflateResetKeep
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateSetHeader      z_deflateSetHeader
+#  define deflateTune           z_deflateTune
+#  define deflate_copyright     z_deflate_copyright
+#  define get_crc_table         z_get_crc_table
+#  ifndef Z_SOLO
+#    define gz_error              z_gz_error
+#    define gz_intmax             z_gz_intmax
+#    define gz_strwinerror        z_gz_strwinerror
+#    define gzbuffer              z_gzbuffer
+#    define gzclearerr            z_gzclearerr
+#    define gzclose               z_gzclose
+#    define gzclose_r             z_gzclose_r
+#    define gzclose_w             z_gzclose_w
+#    define gzdirect              z_gzdirect
+#    define gzdopen               z_gzdopen
+#    define gzeof                 z_gzeof
+#    define gzerror               z_gzerror
+#    define gzflags               z_gzflags
+#    define gzflush               z_gzflush
+#    define gzgetc                z_gzgetc
+#    define gzgetc_               z_gzgetc_
+#    define gzgets                z_gzgets
+#    define gzoffset              z_gzoffset
+#    define gzoffset64            z_gzoffset64
+#    define gzopen                z_gzopen
+#    define gzopen64              z_gzopen64
+#    define gzprintf              z_gzprintf
+#    define gzputc                z_gzputc
+#    define gzputs                z_gzputs
+#    define gzread                z_gzread
+#    define gzrewind              z_gzrewind
+#    define gzseek                z_gzseek
+#    define gzseek64              z_gzseek64
+#    define gzsetparams           z_gzsetparams
+#    define gztell                z_gztell
+#    define gztell64              z_gztell64
+#    define gzungetc              z_gzungetc
+#    define gzwrite               z_gzwrite
+#  endif
+#  define inflate               z_inflate
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define inflateBackInit_      z_inflateBackInit_
+#  define inflateCopy           z_inflateCopy
+#  define inflateEnd            z_inflateEnd
+#  define inflateGetHeader      z_inflateGetHeader
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateInit_          z_inflateInit_
+#  define inflateMark           z_inflateMark
+#  define inflatePrime          z_inflatePrime
+#  define inflateReset          z_inflateReset
+#  define inflateReset2         z_inflateReset2
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateUndermine      z_inflateUndermine
+#  define inflateResetKeep      z_inflateResetKeep
+#  define inflate_copyright     z_inflate_copyright
+#  define inflate_fast          z_inflate_fast
+#  define inflate_table         z_inflate_table
+#  ifndef Z_SOLO
+#    define uncompress            z_uncompress
+#  endif
+#  define zError                z_zError
+#  ifndef Z_SOLO
+#    define zcalloc               z_zcalloc
+#    define zcfree                z_zcfree
+#  endif
+#  define zlibCompileFlags      z_zlibCompileFlags
+#  define zlibVersion           z_zlibVersion
+
+/* all zlib typedefs in zlib.h and zconf.h */
+#  define Byte                  z_Byte
+#  define Bytef                 z_Bytef
+#  define alloc_func            z_alloc_func
+#  define charf                 z_charf
+#  define free_func             z_free_func
+#  ifndef Z_SOLO
+#    define gzFile                z_gzFile
+#    define gz_header             z_gz_header
+#    define gz_headerp            z_gz_headerp
+#  endif
+#  define in_func               z_in_func
+#  define intf                  z_intf
+#  define out_func              z_out_func
+#  define uInt                  z_uInt
+#  define uIntf                 z_uIntf
+#  define uLong                 z_uLong
+#  define uLongf                z_uLongf
+#  define voidp                 z_voidp
+#  define voidpc                z_voidpc
+#  define voidpf                z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+#  ifndef Z_SOLO
+#    define gz_header_s           z_gz_header_s
+#  endif
+#  define internal_state        z_internal_state
+
+#endif
+
+#if defined(__MSDOS__) && !defined(MSDOS)
+#  define MSDOS
+#endif
+#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
+#  define OS2
+#endif
+#if defined(_WINDOWS) && !defined(WINDOWS)
+#  define WINDOWS
+#endif
+#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
+#  ifndef WIN32
+#    define WIN32
+#  endif
+#endif
+#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
+#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
+#    ifndef SYS16BIT
+#      define SYS16BIT
+#    endif
+#  endif
+#endif
+
+/*
+ * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
+ * than 64k bytes at a time (needed on systems with 16-bit int).
+ */
+#ifdef SYS16BIT
+#  define MAXSEG_64K
+#endif
+#ifdef MSDOS
+#  define UNALIGNED_OK
+#endif
+
+#ifdef __STDC_VERSION__
+#  ifndef STDC
+#    define STDC
+#  endif
+#  if __STDC_VERSION__ >= 199901L
+#    ifndef STDC99
+#      define STDC99
+#    endif
+#  endif
+#endif
+#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
+#  define STDC
+#endif
+
+#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
+#  define STDC
+#endif
+
+#ifndef STDC
+#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
+#    define const       /* note: need a more gentle solution here */
+#  endif
+#endif
+
+#if defined(ZLIB_CONST) && !defined(z_const)
+#  define z_const const
+#else
+#  define z_const
+#endif
+
+/* Some Mac compilers merge all .h files incorrectly: */
+#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
+#  define NO_DUMMY_DECL
+#endif
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+#  ifdef MAXSEG_64K
+#    define MAX_MEM_LEVEL 8
+#  else
+#    define MAX_MEM_LEVEL 9
+#  endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+#  define MAX_WBITS   15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+            (1 << (windowBits+2)) +  (1 << (memLevel+9))
+ that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+   The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus a few kilobytes
+ for small objects.
+*/
+
+                        /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#  ifdef STDC
+#    define OF(args)  args
+#  else
+#    define OF(args)  ()
+#  endif
+#endif
+
+#ifndef Z_ARG /* function prototypes for stdarg */
+#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#    define Z_ARG(args)  args
+#  else
+#    define Z_ARG(args)  ()
+#  endif
+#endif
+
+/* The following definitions for FAR are needed only for MSDOS mixed
+ * model programming (small or medium model with some far allocations).
+ * This was tested only with MSC; for other MSDOS compilers you may have
+ * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
+ * just define FAR to be empty.
+ */
+#ifdef SYS16BIT
+#  if defined(M_I86SM) || defined(M_I86MM)
+     /* MSC small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef _MSC_VER
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#  if (defined(__SMALL__) || defined(__MEDIUM__))
+     /* Turbo C small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef __BORLANDC__
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#endif
+
+#if defined(WINDOWS) || defined(WIN32)
+   /* If building or using zlib as a DLL, define ZLIB_DLL.
+    * This is not mandatory, but it offers a little performance increase.
+    */
+#  ifdef ZLIB_DLL
+#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
+#      ifdef ZLIB_INTERNAL
+#        define ZEXTERN extern __declspec(dllexport)
+#      else
+#        define ZEXTERN extern __declspec(dllimport)
+#      endif
+#    endif
+#  endif  /* ZLIB_DLL */
+   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
+    * define ZLIB_WINAPI.
+    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
+    */
+#  ifdef ZLIB_WINAPI
+#    ifdef FAR
+#      undef FAR
+#    endif
+#    include <windows.h>
+     /* No need for _export, use ZLIB.DEF instead. */
+     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
+#    define ZEXPORT WINAPI
+#    ifdef WIN32
+#      define ZEXPORTVA WINAPIV
+#    else
+#      define ZEXPORTVA FAR CDECL
+#    endif
+#  endif
+#endif
+
+#if defined (__BEOS__)
+#  ifdef ZLIB_DLL
+#    ifdef ZLIB_INTERNAL
+#      define ZEXPORT   __declspec(dllexport)
+#      define ZEXPORTVA __declspec(dllexport)
+#    else
+#      define ZEXPORT   __declspec(dllimport)
+#      define ZEXPORTVA __declspec(dllimport)
+#    endif
+#  endif
+#endif
+
+#ifndef ZEXTERN
+#  define ZEXTERN extern
+#endif
+#ifndef ZEXPORT
+#  define ZEXPORT
+#endif
+#ifndef ZEXPORTVA
+#  define ZEXPORTVA
+#endif
+
+#ifndef FAR
+#  define FAR
+#endif
+
+#if !defined(__MACTYPES__)
+typedef unsigned char  Byte;  /* 8 bits */
+#endif
+typedef unsigned int   uInt;  /* 16 bits or more */
+typedef unsigned long  uLong; /* 32 bits or more */
+
+#ifdef SMALL_MEDIUM
+   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
+#  define Bytef Byte FAR
+#else
+   typedef Byte  FAR Bytef;
+#endif
+typedef char  FAR charf;
+typedef int   FAR intf;
+typedef uInt  FAR uIntf;
+typedef uLong FAR uLongf;
+
+#ifdef STDC
+   typedef void const *voidpc;
+   typedef void FAR   *voidpf;
+   typedef void       *voidp;
+#else
+   typedef Byte const *voidpc;
+   typedef Byte FAR   *voidpf;
+   typedef Byte       *voidp;
+#endif
+
+#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_STDARG_H
+#endif
+
+#ifdef STDC
+#  ifndef Z_SOLO
+#    include <sys/types.h>      /* for off_t */
+#  endif
+#endif
+
+/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
+ * though the former does not conform to the LFS document), but considering
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
+ * equivalently requesting no 64-bit operations
+ */
+#if -_LARGEFILE64_SOURCE - -1 == 1
+#  undef _LARGEFILE64_SOURCE
+#endif
+
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#  define Z_LARGE
+#endif
+
+#if (defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE)) && !defined(Z_SOLO)
+#  include <unistd.h>       /* for SEEK_* and off_t */
+#  ifdef VMS
+#    include <unixio.h>     /* for off_t */
+#  endif
+#  ifndef z_off_t
+#    define z_off_t off_t
+#  endif
+#endif
+
+#if !defined(SEEK_SET) && !defined(Z_SOLO)
+#  define SEEK_SET        0       /* Seek from beginning of file.  */
+#  define SEEK_CUR        1       /* Seek from current position.  */
+#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
+#endif
+
+#ifndef z_off_t
+#  define z_off_t long
+#endif
+
+#if !defined(_WIN32) && (defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0)
+#  define z_off64_t off64_t
+#else
+#  if defined(_WIN32)
+#    define z_off64_t __int64
+#  else
+#  define z_off64_t z_off_t
+#endif
+#endif
+
+/* MVS linker does not support external names larger than 8 bytes */
+#if defined(__MVS__)
+  #pragma map(deflateInit_,"DEIN")
+  #pragma map(deflateInit2_,"DEIN2")
+  #pragma map(deflateEnd,"DEEND")
+  #pragma map(deflateBound,"DEBND")
+  #pragma map(inflateInit_,"ININ")
+  #pragma map(inflateInit2_,"ININ2")
+  #pragma map(inflateEnd,"INEND")
+  #pragma map(inflateSync,"INSY")
+  #pragma map(inflateSetDictionary,"INSEDI")
+  #pragma map(compressBound,"CMBND")
+  #pragma map(inflate_table,"INTABL")
+  #pragma map(inflate_fast,"INFA")
+  #pragma map(inflate_copyright,"INCOPY")
+#endif
+
+#endif /* ZCONF_H */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h.cmakein b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h.cmakein
new file mode 100644 (file)
index 0000000..3ea5531
--- /dev/null
@@ -0,0 +1,468 @@
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2011 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZCONF_H
+#define ZCONF_H
+#cmakedefine Z_PREFIX
+#cmakedefine Z_HAVE_UNISTD_H
+
+/*
+ * If you *really* need a unique prefix for all types and library functions,
+ * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
+ */
+#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
+#  define Z_PREFIX_SET
+
+/* all linked symbols */
+#  define _dist_code            z__dist_code
+#  define _length_code          z__length_code
+#  define _tr_align             z__tr_align
+#  define _tr_flush_block       z__tr_flush_block
+#  define _tr_init              z__tr_init
+#  define _tr_stored_block      z__tr_stored_block
+#  define _tr_tally             z__tr_tally
+#  define adler32               z_adler32
+#  define adler32_combine       z_adler32_combine
+#  define adler32_combine64     z_adler32_combine64
+#  ifndef Z_SOLO
+#    define compress              z_compress
+#    define compress2             z_compress2
+#    define compressBound         z_compressBound
+#  endif
+#  define crc32                 z_crc32
+#  define crc32_combine         z_crc32_combine
+#  define crc32_combine64       z_crc32_combine64
+#  define deflate               z_deflate
+#  define deflateBound          z_deflateBound
+#  define deflateCopy           z_deflateCopy
+#  define deflateEnd            z_deflateEnd
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateInit_          z_deflateInit_
+#  define deflateParams         z_deflateParams
+#  define deflatePending        z_deflatePending
+#  define deflatePrime          z_deflatePrime
+#  define deflateReset          z_deflateReset
+#  define deflateResetKeep      z_deflateResetKeep
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateSetHeader      z_deflateSetHeader
+#  define deflateTune           z_deflateTune
+#  define deflate_copyright     z_deflate_copyright
+#  define get_crc_table         z_get_crc_table
+#  ifndef Z_SOLO
+#    define gz_error              z_gz_error
+#    define gz_intmax             z_gz_intmax
+#    define gz_strwinerror        z_gz_strwinerror
+#    define gzbuffer              z_gzbuffer
+#    define gzclearerr            z_gzclearerr
+#    define gzclose               z_gzclose
+#    define gzclose_r             z_gzclose_r
+#    define gzclose_w             z_gzclose_w
+#    define gzdirect              z_gzdirect
+#    define gzdopen               z_gzdopen
+#    define gzeof                 z_gzeof
+#    define gzerror               z_gzerror
+#    define gzflags               z_gzflags
+#    define gzflush               z_gzflush
+#    define gzgetc                z_gzgetc
+#    define gzgetc_               z_gzgetc_
+#    define gzgets                z_gzgets
+#    define gzoffset              z_gzoffset
+#    define gzoffset64            z_gzoffset64
+#    define gzopen                z_gzopen
+#    define gzopen64              z_gzopen64
+#    define gzprintf              z_gzprintf
+#    define gzputc                z_gzputc
+#    define gzputs                z_gzputs
+#    define gzread                z_gzread
+#    define gzrewind              z_gzrewind
+#    define gzseek                z_gzseek
+#    define gzseek64              z_gzseek64
+#    define gzsetparams           z_gzsetparams
+#    define gztell                z_gztell
+#    define gztell64              z_gztell64
+#    define gzungetc              z_gzungetc
+#    define gzwrite               z_gzwrite
+#  endif
+#  define inflate               z_inflate
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define inflateBackInit_      z_inflateBackInit_
+#  define inflateCopy           z_inflateCopy
+#  define inflateEnd            z_inflateEnd
+#  define inflateGetHeader      z_inflateGetHeader
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateInit_          z_inflateInit_
+#  define inflateMark           z_inflateMark
+#  define inflatePrime          z_inflatePrime
+#  define inflateReset          z_inflateReset
+#  define inflateReset2         z_inflateReset2
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateUndermine      z_inflateUndermine
+#  define inflateResetKeep      z_inflateResetKeep
+#  define inflate_copyright     z_inflate_copyright
+#  define inflate_fast          z_inflate_fast
+#  define inflate_table         z_inflate_table
+#  ifndef Z_SOLO
+#    define uncompress            z_uncompress
+#  endif
+#  define zError                z_zError
+#  ifndef Z_SOLO
+#    define zcalloc               z_zcalloc
+#    define zcfree                z_zcfree
+#  endif
+#  define zlibCompileFlags      z_zlibCompileFlags
+#  define zlibVersion           z_zlibVersion
+
+/* all zlib typedefs in zlib.h and zconf.h */
+#  define Byte                  z_Byte
+#  define Bytef                 z_Bytef
+#  define alloc_func            z_alloc_func
+#  define charf                 z_charf
+#  define free_func             z_free_func
+#  ifndef Z_SOLO
+#    define gzFile                z_gzFile
+#    define gz_header             z_gz_header
+#    define gz_headerp            z_gz_headerp
+#  endif
+#  define in_func               z_in_func
+#  define intf                  z_intf
+#  define out_func              z_out_func
+#  define uInt                  z_uInt
+#  define uIntf                 z_uIntf
+#  define uLong                 z_uLong
+#  define uLongf                z_uLongf
+#  define voidp                 z_voidp
+#  define voidpc                z_voidpc
+#  define voidpf                z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+#  ifndef Z_SOLO
+#    define gz_header_s           z_gz_header_s
+#  endif
+#  define internal_state        z_internal_state
+
+#endif
+
+#if defined(__MSDOS__) && !defined(MSDOS)
+#  define MSDOS
+#endif
+#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
+#  define OS2
+#endif
+#if defined(_WINDOWS) && !defined(WINDOWS)
+#  define WINDOWS
+#endif
+#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
+#  ifndef WIN32
+#    define WIN32
+#  endif
+#endif
+#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
+#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
+#    ifndef SYS16BIT
+#      define SYS16BIT
+#    endif
+#  endif
+#endif
+
+/*
+ * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
+ * than 64k bytes at a time (needed on systems with 16-bit int).
+ */
+#ifdef SYS16BIT
+#  define MAXSEG_64K
+#endif
+#ifdef MSDOS
+#  define UNALIGNED_OK
+#endif
+
+#ifdef __STDC_VERSION__
+#  ifndef STDC
+#    define STDC
+#  endif
+#  if __STDC_VERSION__ >= 199901L
+#    ifndef STDC99
+#      define STDC99
+#    endif
+#  endif
+#endif
+#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
+#  define STDC
+#endif
+
+#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
+#  define STDC
+#endif
+
+#ifndef STDC
+#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
+#    define const       /* note: need a more gentle solution here */
+#  endif
+#endif
+
+#if defined(ZLIB_CONST) && !defined(z_const)
+#  define z_const const
+#else
+#  define z_const
+#endif
+
+/* Some Mac compilers merge all .h files incorrectly: */
+#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
+#  define NO_DUMMY_DECL
+#endif
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+#  ifdef MAXSEG_64K
+#    define MAX_MEM_LEVEL 8
+#  else
+#    define MAX_MEM_LEVEL 9
+#  endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+#  define MAX_WBITS   15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+            (1 << (windowBits+2)) +  (1 << (memLevel+9))
+ that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+   The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus a few kilobytes
+ for small objects.
+*/
+
+                        /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#  ifdef STDC
+#    define OF(args)  args
+#  else
+#    define OF(args)  ()
+#  endif
+#endif
+
+#ifndef Z_ARG /* function prototypes for stdarg */
+#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#    define Z_ARG(args)  args
+#  else
+#    define Z_ARG(args)  ()
+#  endif
+#endif
+
+/* The following definitions for FAR are needed only for MSDOS mixed
+ * model programming (small or medium model with some far allocations).
+ * This was tested only with MSC; for other MSDOS compilers you may have
+ * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
+ * just define FAR to be empty.
+ */
+#ifdef SYS16BIT
+#  if defined(M_I86SM) || defined(M_I86MM)
+     /* MSC small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef _MSC_VER
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#  if (defined(__SMALL__) || defined(__MEDIUM__))
+     /* Turbo C small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef __BORLANDC__
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#endif
+
+#if defined(WINDOWS) || defined(WIN32)
+   /* If building or using zlib as a DLL, define ZLIB_DLL.
+    * This is not mandatory, but it offers a little performance increase.
+    */
+#  ifdef ZLIB_DLL
+#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
+#      ifdef ZLIB_INTERNAL
+#        define ZEXTERN extern __declspec(dllexport)
+#      else
+#        define ZEXTERN extern __declspec(dllimport)
+#      endif
+#    endif
+#  endif  /* ZLIB_DLL */
+   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
+    * define ZLIB_WINAPI.
+    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
+    */
+#  ifdef ZLIB_WINAPI
+#    ifdef FAR
+#      undef FAR
+#    endif
+#    include <windows.h>
+     /* No need for _export, use ZLIB.DEF instead. */
+     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
+#    define ZEXPORT WINAPI
+#    ifdef WIN32
+#      define ZEXPORTVA WINAPIV
+#    else
+#      define ZEXPORTVA FAR CDECL
+#    endif
+#  endif
+#endif
+
+#if defined (__BEOS__)
+#  ifdef ZLIB_DLL
+#    ifdef ZLIB_INTERNAL
+#      define ZEXPORT   __declspec(dllexport)
+#      define ZEXPORTVA __declspec(dllexport)
+#    else
+#      define ZEXPORT   __declspec(dllimport)
+#      define ZEXPORTVA __declspec(dllimport)
+#    endif
+#  endif
+#endif
+
+#ifndef ZEXTERN
+#  define ZEXTERN extern
+#endif
+#ifndef ZEXPORT
+#  define ZEXPORT
+#endif
+#ifndef ZEXPORTVA
+#  define ZEXPORTVA
+#endif
+
+#ifndef FAR
+#  define FAR
+#endif
+
+#if !defined(__MACTYPES__)
+typedef unsigned char  Byte;  /* 8 bits */
+#endif
+typedef unsigned int   uInt;  /* 16 bits or more */
+typedef unsigned long  uLong; /* 32 bits or more */
+
+#ifdef SMALL_MEDIUM
+   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
+#  define Bytef Byte FAR
+#else
+   typedef Byte  FAR Bytef;
+#endif
+typedef char  FAR charf;
+typedef int   FAR intf;
+typedef uInt  FAR uIntf;
+typedef uLong FAR uLongf;
+
+#ifdef STDC
+   typedef void const *voidpc;
+   typedef void FAR   *voidpf;
+   typedef void       *voidp;
+#else
+   typedef Byte const *voidpc;
+   typedef Byte FAR   *voidpf;
+   typedef Byte       *voidp;
+#endif
+
+#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_STDARG_H
+#endif
+
+#ifdef STDC
+#  ifndef Z_SOLO
+#    include <sys/types.h>      /* for off_t */
+#  endif
+#endif
+
+/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
+ * though the former does not conform to the LFS document), but considering
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
+ * equivalently requesting no 64-bit operations
+ */
+#if -_LARGEFILE64_SOURCE - -1 == 1
+#  undef _LARGEFILE64_SOURCE
+#endif
+
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#  define Z_LARGE
+#endif
+
+#if (defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE)) && !defined(Z_SOLO)
+#  include <unistd.h>       /* for SEEK_* and off_t */
+#  ifdef VMS
+#    include <unixio.h>     /* for off_t */
+#  endif
+#  ifndef z_off_t
+#    define z_off_t off_t
+#  endif
+#endif
+
+#if !defined(SEEK_SET) && !defined(Z_SOLO)
+#  define SEEK_SET        0       /* Seek from beginning of file.  */
+#  define SEEK_CUR        1       /* Seek from current position.  */
+#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
+#endif
+
+#ifndef z_off_t
+#  define z_off_t long
+#endif
+
+#if !defined(_WIN32) && (defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0)
+#  define z_off64_t off64_t
+#else
+#  if defined(_WIN32)
+#    define z_off64_t __int64
+#  else
+#  define z_off64_t z_off_t
+#endif
+#endif
+
+/* MVS linker does not support external names larger than 8 bytes */
+#if defined(__MVS__)
+  #pragma map(deflateInit_,"DEIN")
+  #pragma map(deflateInit2_,"DEIN2")
+  #pragma map(deflateEnd,"DEEND")
+  #pragma map(deflateBound,"DEBND")
+  #pragma map(inflateInit_,"ININ")
+  #pragma map(inflateInit2_,"ININ2")
+  #pragma map(inflateEnd,"INEND")
+  #pragma map(inflateSync,"INSY")
+  #pragma map(inflateSetDictionary,"INSEDI")
+  #pragma map(compressBound,"CMBND")
+  #pragma map(inflate_table,"INTABL")
+  #pragma map(inflate_fast,"INFA")
+  #pragma map(inflate_copyright,"INCOPY")
+#endif
+
+#endif /* ZCONF_H */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h.in b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zconf.h.in
new file mode 100644 (file)
index 0000000..51c80ac
--- /dev/null
@@ -0,0 +1,466 @@
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2011 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZCONF_H
+#define ZCONF_H
+
+/*
+ * If you *really* need a unique prefix for all types and library functions,
+ * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
+ */
+#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
+#  define Z_PREFIX_SET
+
+/* all linked symbols */
+#  define _dist_code            z__dist_code
+#  define _length_code          z__length_code
+#  define _tr_align             z__tr_align
+#  define _tr_flush_block       z__tr_flush_block
+#  define _tr_init              z__tr_init
+#  define _tr_stored_block      z__tr_stored_block
+#  define _tr_tally             z__tr_tally
+#  define adler32               z_adler32
+#  define adler32_combine       z_adler32_combine
+#  define adler32_combine64     z_adler32_combine64
+#  ifndef Z_SOLO
+#    define compress              z_compress
+#    define compress2             z_compress2
+#    define compressBound         z_compressBound
+#  endif
+#  define crc32                 z_crc32
+#  define crc32_combine         z_crc32_combine
+#  define crc32_combine64       z_crc32_combine64
+#  define deflate               z_deflate
+#  define deflateBound          z_deflateBound
+#  define deflateCopy           z_deflateCopy
+#  define deflateEnd            z_deflateEnd
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateInit_          z_deflateInit_
+#  define deflateParams         z_deflateParams
+#  define deflatePending        z_deflatePending
+#  define deflatePrime          z_deflatePrime
+#  define deflateReset          z_deflateReset
+#  define deflateResetKeep      z_deflateResetKeep
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateSetHeader      z_deflateSetHeader
+#  define deflateTune           z_deflateTune
+#  define deflate_copyright     z_deflate_copyright
+#  define get_crc_table         z_get_crc_table
+#  ifndef Z_SOLO
+#    define gz_error              z_gz_error
+#    define gz_intmax             z_gz_intmax
+#    define gz_strwinerror        z_gz_strwinerror
+#    define gzbuffer              z_gzbuffer
+#    define gzclearerr            z_gzclearerr
+#    define gzclose               z_gzclose
+#    define gzclose_r             z_gzclose_r
+#    define gzclose_w             z_gzclose_w
+#    define gzdirect              z_gzdirect
+#    define gzdopen               z_gzdopen
+#    define gzeof                 z_gzeof
+#    define gzerror               z_gzerror
+#    define gzflags               z_gzflags
+#    define gzflush               z_gzflush
+#    define gzgetc                z_gzgetc
+#    define gzgetc_               z_gzgetc_
+#    define gzgets                z_gzgets
+#    define gzoffset              z_gzoffset
+#    define gzoffset64            z_gzoffset64
+#    define gzopen                z_gzopen
+#    define gzopen64              z_gzopen64
+#    define gzprintf              z_gzprintf
+#    define gzputc                z_gzputc
+#    define gzputs                z_gzputs
+#    define gzread                z_gzread
+#    define gzrewind              z_gzrewind
+#    define gzseek                z_gzseek
+#    define gzseek64              z_gzseek64
+#    define gzsetparams           z_gzsetparams
+#    define gztell                z_gztell
+#    define gztell64              z_gztell64
+#    define gzungetc              z_gzungetc
+#    define gzwrite               z_gzwrite
+#  endif
+#  define inflate               z_inflate
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define inflateBackInit_      z_inflateBackInit_
+#  define inflateCopy           z_inflateCopy
+#  define inflateEnd            z_inflateEnd
+#  define inflateGetHeader      z_inflateGetHeader
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateInit_          z_inflateInit_
+#  define inflateMark           z_inflateMark
+#  define inflatePrime          z_inflatePrime
+#  define inflateReset          z_inflateReset
+#  define inflateReset2         z_inflateReset2
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateUndermine      z_inflateUndermine
+#  define inflateResetKeep      z_inflateResetKeep
+#  define inflate_copyright     z_inflate_copyright
+#  define inflate_fast          z_inflate_fast
+#  define inflate_table         z_inflate_table
+#  ifndef Z_SOLO
+#    define uncompress            z_uncompress
+#  endif
+#  define zError                z_zError
+#  ifndef Z_SOLO
+#    define zcalloc               z_zcalloc
+#    define zcfree                z_zcfree
+#  endif
+#  define zlibCompileFlags      z_zlibCompileFlags
+#  define zlibVersion           z_zlibVersion
+
+/* all zlib typedefs in zlib.h and zconf.h */
+#  define Byte                  z_Byte
+#  define Bytef                 z_Bytef
+#  define alloc_func            z_alloc_func
+#  define charf                 z_charf
+#  define free_func             z_free_func
+#  ifndef Z_SOLO
+#    define gzFile                z_gzFile
+#    define gz_header             z_gz_header
+#    define gz_headerp            z_gz_headerp
+#  endif
+#  define in_func               z_in_func
+#  define intf                  z_intf
+#  define out_func              z_out_func
+#  define uInt                  z_uInt
+#  define uIntf                 z_uIntf
+#  define uLong                 z_uLong
+#  define uLongf                z_uLongf
+#  define voidp                 z_voidp
+#  define voidpc                z_voidpc
+#  define voidpf                z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+#  ifndef Z_SOLO
+#    define gz_header_s           z_gz_header_s
+#  endif
+#  define internal_state        z_internal_state
+
+#endif
+
+#if defined(__MSDOS__) && !defined(MSDOS)
+#  define MSDOS
+#endif
+#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
+#  define OS2
+#endif
+#if defined(_WINDOWS) && !defined(WINDOWS)
+#  define WINDOWS
+#endif
+#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
+#  ifndef WIN32
+#    define WIN32
+#  endif
+#endif
+#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
+#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
+#    ifndef SYS16BIT
+#      define SYS16BIT
+#    endif
+#  endif
+#endif
+
+/*
+ * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
+ * than 64k bytes at a time (needed on systems with 16-bit int).
+ */
+#ifdef SYS16BIT
+#  define MAXSEG_64K
+#endif
+#ifdef MSDOS
+#  define UNALIGNED_OK
+#endif
+
+#ifdef __STDC_VERSION__
+#  ifndef STDC
+#    define STDC
+#  endif
+#  if __STDC_VERSION__ >= 199901L
+#    ifndef STDC99
+#      define STDC99
+#    endif
+#  endif
+#endif
+#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
+#  define STDC
+#endif
+
+#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
+#  define STDC
+#endif
+
+#ifndef STDC
+#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
+#    define const       /* note: need a more gentle solution here */
+#  endif
+#endif
+
+#if defined(ZLIB_CONST) && !defined(z_const)
+#  define z_const const
+#else
+#  define z_const
+#endif
+
+/* Some Mac compilers merge all .h files incorrectly: */
+#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
+#  define NO_DUMMY_DECL
+#endif
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+#  ifdef MAXSEG_64K
+#    define MAX_MEM_LEVEL 8
+#  else
+#    define MAX_MEM_LEVEL 9
+#  endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+#  define MAX_WBITS   15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+            (1 << (windowBits+2)) +  (1 << (memLevel+9))
+ that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+   The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus a few kilobytes
+ for small objects.
+*/
+
+                        /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#  ifdef STDC
+#    define OF(args)  args
+#  else
+#    define OF(args)  ()
+#  endif
+#endif
+
+#ifndef Z_ARG /* function prototypes for stdarg */
+#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#    define Z_ARG(args)  args
+#  else
+#    define Z_ARG(args)  ()
+#  endif
+#endif
+
+/* The following definitions for FAR are needed only for MSDOS mixed
+ * model programming (small or medium model with some far allocations).
+ * This was tested only with MSC; for other MSDOS compilers you may have
+ * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
+ * just define FAR to be empty.
+ */
+#ifdef SYS16BIT
+#  if defined(M_I86SM) || defined(M_I86MM)
+     /* MSC small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef _MSC_VER
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#  if (defined(__SMALL__) || defined(__MEDIUM__))
+     /* Turbo C small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef __BORLANDC__
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#endif
+
+#if defined(WINDOWS) || defined(WIN32)
+   /* If building or using zlib as a DLL, define ZLIB_DLL.
+    * This is not mandatory, but it offers a little performance increase.
+    */
+#  ifdef ZLIB_DLL
+#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
+#      ifdef ZLIB_INTERNAL
+#        define ZEXTERN extern __declspec(dllexport)
+#      else
+#        define ZEXTERN extern __declspec(dllimport)
+#      endif
+#    endif
+#  endif  /* ZLIB_DLL */
+   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
+    * define ZLIB_WINAPI.
+    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
+    */
+#  ifdef ZLIB_WINAPI
+#    ifdef FAR
+#      undef FAR
+#    endif
+#    include <windows.h>
+     /* No need for _export, use ZLIB.DEF instead. */
+     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
+#    define ZEXPORT WINAPI
+#    ifdef WIN32
+#      define ZEXPORTVA WINAPIV
+#    else
+#      define ZEXPORTVA FAR CDECL
+#    endif
+#  endif
+#endif
+
+#if defined (__BEOS__)
+#  ifdef ZLIB_DLL
+#    ifdef ZLIB_INTERNAL
+#      define ZEXPORT   __declspec(dllexport)
+#      define ZEXPORTVA __declspec(dllexport)
+#    else
+#      define ZEXPORT   __declspec(dllimport)
+#      define ZEXPORTVA __declspec(dllimport)
+#    endif
+#  endif
+#endif
+
+#ifndef ZEXTERN
+#  define ZEXTERN extern
+#endif
+#ifndef ZEXPORT
+#  define ZEXPORT
+#endif
+#ifndef ZEXPORTVA
+#  define ZEXPORTVA
+#endif
+
+#ifndef FAR
+#  define FAR
+#endif
+
+#if !defined(__MACTYPES__)
+typedef unsigned char  Byte;  /* 8 bits */
+#endif
+typedef unsigned int   uInt;  /* 16 bits or more */
+typedef unsigned long  uLong; /* 32 bits or more */
+
+#ifdef SMALL_MEDIUM
+   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
+#  define Bytef Byte FAR
+#else
+   typedef Byte  FAR Bytef;
+#endif
+typedef char  FAR charf;
+typedef int   FAR intf;
+typedef uInt  FAR uIntf;
+typedef uLong FAR uLongf;
+
+#ifdef STDC
+   typedef void const *voidpc;
+   typedef void FAR   *voidpf;
+   typedef void       *voidp;
+#else
+   typedef Byte const *voidpc;
+   typedef Byte FAR   *voidpf;
+   typedef Byte       *voidp;
+#endif
+
+#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_STDARG_H
+#endif
+
+#ifdef STDC
+#  ifndef Z_SOLO
+#    include <sys/types.h>      /* for off_t */
+#  endif
+#endif
+
+/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
+ * though the former does not conform to the LFS document), but considering
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
+ * equivalently requesting no 64-bit operations
+ */
+#if -_LARGEFILE64_SOURCE - -1 == 1
+#  undef _LARGEFILE64_SOURCE
+#endif
+
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#  define Z_LARGE
+#endif
+
+#if (defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE)) && !defined(Z_SOLO)
+#  include <unistd.h>       /* for SEEK_* and off_t */
+#  ifdef VMS
+#    include <unixio.h>     /* for off_t */
+#  endif
+#  ifndef z_off_t
+#    define z_off_t off_t
+#  endif
+#endif
+
+#if !defined(SEEK_SET) && !defined(Z_SOLO)
+#  define SEEK_SET        0       /* Seek from beginning of file.  */
+#  define SEEK_CUR        1       /* Seek from current position.  */
+#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
+#endif
+
+#ifndef z_off_t
+#  define z_off_t long
+#endif
+
+#if !defined(_WIN32) && (defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0)
+#  define z_off64_t off64_t
+#else
+#  if defined(_WIN32)
+#    define z_off64_t __int64
+#  else
+#  define z_off64_t z_off_t
+#endif
+#endif
+
+/* MVS linker does not support external names larger than 8 bytes */
+#if defined(__MVS__)
+  #pragma map(deflateInit_,"DEIN")
+  #pragma map(deflateInit2_,"DEIN2")
+  #pragma map(deflateEnd,"DEEND")
+  #pragma map(deflateBound,"DEBND")
+  #pragma map(inflateInit_,"ININ")
+  #pragma map(inflateInit2_,"ININ2")
+  #pragma map(inflateEnd,"INEND")
+  #pragma map(inflateSync,"INSY")
+  #pragma map(inflateSetDictionary,"INSEDI")
+  #pragma map(compressBound,"CMBND")
+  #pragma map(inflate_table,"INTABL")
+  #pragma map(inflate_fast,"INFA")
+  #pragma map(inflate_copyright,"INCOPY")
+#endif
+
+#endif /* ZCONF_H */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.3 b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.3
new file mode 100644 (file)
index 0000000..d051c79
--- /dev/null
@@ -0,0 +1,151 @@
+.TH ZLIB 3 "29 Jan 2012"
+.SH NAME
+zlib \- compression/decompression library
+.SH SYNOPSIS
+[see
+.I zlib.h
+for full description]
+.SH DESCRIPTION
+The
+.I zlib
+library is a general purpose data compression library.
+The code is thread safe, assuming that the standard library functions
+used are thread safe, such as memory allocation routines.
+It provides in-memory compression and decompression functions,
+including integrity checks of the uncompressed data.
+This version of the library supports only one compression method (deflation)
+but other algorithms may be added later
+with the same stream interface.
+.LP
+Compression can be done in a single step if the buffers are large enough
+or can be done by repeated calls of the compression function.
+In the latter case,
+the application must provide more input and/or consume the output
+(providing more output space) before each call.
+.LP
+The library also supports reading and writing files in
+.IR gzip (1)
+(.gz) format
+with an interface similar to that of stdio.
+.LP
+The library does not install any signal handler.
+The decoder checks the consistency of the compressed data,
+so the library should never crash even in the case of corrupted input.
+.LP
+All functions of the compression library are documented in the file
+.IR zlib.h .
+The distribution source includes examples of use of the library
+in the files
+.I test/example.c
+and
+.IR test/minigzip.c,
+as well as other examples in the
+.IR examples/
+directory.
+.LP
+Changes to this version are documented in the file
+.I ChangeLog
+that accompanies the source.
+.LP
+.I zlib
+is available in Java using the java.util.zip package:
+.IP
+http://java.sun.com/developer/technicalArticles/Programming/compression/
+.LP
+A Perl interface to
+.IR zlib ,
+written by Paul Marquess (pmqs@cpan.org),
+is available at CPAN (Comprehensive Perl Archive Network) sites,
+including:
+.IP
+http://search.cpan.org/~pmqs/IO-Compress-Zlib/
+.LP
+A Python interface to
+.IR zlib ,
+written by A.M. Kuchling (amk@magnet.com),
+is available in Python 1.5 and later versions:
+.IP
+http://docs.python.org/library/zlib.html
+.LP
+.I zlib
+is built into
+.IR tcl:
+.IP
+http://wiki.tcl.tk/4610
+.LP
+An experimental package to read and write files in .zip format,
+written on top of
+.I zlib
+by Gilles Vollant (info@winimage.com),
+is available at:
+.IP
+http://www.winimage.com/zLibDll/minizip.html
+and also in the
+.I contrib/minizip
+directory of the main
+.I zlib
+source distribution.
+.SH "SEE ALSO"
+The
+.I zlib
+web site can be found at:
+.IP
+http://zlib.net/
+.LP
+The data format used by the zlib library is described by RFC
+(Request for Comments) 1950 to 1952 in the files:
+.IP
+http://tools.ietf.org/html/rfc1950 (for the zlib header and trailer format)
+.br
+http://tools.ietf.org/html/rfc1951 (for the deflate compressed data format)
+.br
+http://tools.ietf.org/html/rfc1952 (for the gzip header and trailer format)
+.LP
+Mark Nelson wrote an article about
+.I zlib
+for the Jan. 1997 issue of  Dr. Dobb's Journal;
+a copy of the article is available at:
+.IP
+http://marknelson.us/1997/01/01/zlib-engine/
+.SH "REPORTING PROBLEMS"
+Before reporting a problem,
+please check the
+.I zlib
+web site to verify that you have the latest version of
+.IR zlib ;
+otherwise,
+obtain the latest version and see if the problem still exists.
+Please read the
+.I zlib
+FAQ at:
+.IP
+http://zlib.net/zlib_faq.html
+.LP
+before asking for help.
+Send questions and/or comments to zlib@gzip.org,
+or (for the Windows DLL version) to Gilles Vollant (info@winimage.com).
+.SH AUTHORS
+Version 1.2.6
+Copyright (C) 1995-2012 Jean-loup Gailly (jloup@gzip.org)
+and Mark Adler (madler@alumni.caltech.edu).
+.LP
+This software is provided "as-is,"
+without any express or implied warranty.
+In no event will the authors be held liable for any damages
+arising from the use of this software.
+See the distribution directory with respect to requirements
+governing redistribution.
+The deflate format used by
+.I zlib
+was defined by Phil Katz.
+The deflate and
+.I zlib
+specifications were written by L. Peter Deutsch.
+Thanks to all the people who reported problems and suggested various
+improvements in
+.IR zlib ;
+who are too numerous to cite here.
+.LP
+UNIX manual page by R. P. C. Rodgers,
+U.S. National Library of Medicine (rodgers@nlm.nih.gov).
+.\" end of man page
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.3.pdf b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.3.pdf
new file mode 100644 (file)
index 0000000..ffa2a78
Binary files /dev/null and b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.3.pdf differ
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.h
new file mode 100644 (file)
index 0000000..79142d1
--- /dev/null
@@ -0,0 +1,1732 @@
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+  version 1.2.6, January 29th, 2012
+
+  Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+
+  The data format used by the zlib library is described by RFCs (Request for
+  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
+  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
+*/
+
+#ifndef ZLIB_H
+#define ZLIB_H
+
+#include "zconf.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ZLIB_VERSION "1.2.6"
+#define ZLIB_VERNUM 0x1260
+#define ZLIB_VER_MAJOR 1
+#define ZLIB_VER_MINOR 2
+#define ZLIB_VER_REVISION 6
+#define ZLIB_VER_SUBREVISION 0
+
+/*
+    The 'zlib' compression library provides in-memory compression and
+  decompression functions, including integrity checks of the uncompressed data.
+  This version of the library supports only one compression method (deflation)
+  but other algorithms will be added later and will have the same stream
+  interface.
+
+    Compression can be done in a single step if the buffers are large enough,
+  or can be done by repeated calls of the compression function.  In the latter
+  case, the application must provide more input and/or consume the output
+  (providing more output space) before each call.
+
+    The compressed data format used by default by the in-memory functions is
+  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
+  around a deflate stream, which is itself documented in RFC 1951.
+
+    The library also supports reading and writing files in gzip (.gz) format
+  with an interface similar to that of stdio using the functions that start
+  with "gz".  The gzip format is different from the zlib format.  gzip is a
+  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
+
+    This library can optionally read and write gzip streams in memory as well.
+
+    The zlib format was designed to be compact and fast for use in memory
+  and on communications channels.  The gzip format was designed for single-
+  file compression on file systems, has a larger header than zlib to maintain
+  directory information, and uses a different, slower check method than zlib.
+
+    The library does not install any signal handler.  The decoder checks
+  the consistency of the compressed data, so the library should never crash
+  even in case of corrupted input.
+*/
+
+typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
+typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
+
+struct internal_state;
+
+typedef struct z_stream_s {
+    z_const Bytef *next_in;     /* next input byte */
+    uInt     avail_in;  /* number of bytes available at next_in */
+    uLong    total_in;  /* total number of input bytes read so far */
+
+    Bytef    *next_out; /* next output byte should be put there */
+    uInt     avail_out; /* remaining free space at next_out */
+    uLong    total_out; /* total number of bytes output so far */
+
+    z_const char *msg;  /* last error message, NULL if no error */
+    struct internal_state FAR *state; /* not visible by applications */
+
+    alloc_func zalloc;  /* used to allocate the internal state */
+    free_func  zfree;   /* used to free the internal state */
+    voidpf     opaque;  /* private data object passed to zalloc and zfree */
+
+    int     data_type;  /* best guess about the data type: binary or text */
+    uLong   adler;      /* adler32 value of the uncompressed data */
+    uLong   reserved;   /* reserved for future use */
+} z_stream;
+
+typedef z_stream FAR *z_streamp;
+
+/*
+     gzip header information passed to and from zlib routines.  See RFC 1952
+  for more details on the meanings of these fields.
+*/
+typedef struct gz_header_s {
+    int     text;       /* true if compressed data believed to be text */
+    uLong   time;       /* modification time */
+    int     xflags;     /* extra flags (not used when writing a gzip file) */
+    int     os;         /* operating system */
+    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */
+    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */
+    uInt    extra_max;  /* space at extra (only when reading header) */
+    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */
+    uInt    name_max;   /* space at name (only when reading header) */
+    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */
+    uInt    comm_max;   /* space at comment (only when reading header) */
+    int     hcrc;       /* true if there was or will be a header crc */
+    int     done;       /* true when done reading gzip header (not used
+                           when writing a gzip file) */
+} gz_header;
+
+typedef gz_header FAR *gz_headerp;
+
+/*
+     The application must update next_in and avail_in when avail_in has dropped
+   to zero.  It must update next_out and avail_out when avail_out has dropped
+   to zero.  The application must initialize zalloc, zfree and opaque before
+   calling the init function.  All other fields are set by the compression
+   library and must not be updated by the application.
+
+     The opaque value provided by the application will be passed as the first
+   parameter for calls of zalloc and zfree.  This can be useful for custom
+   memory management.  The compression library attaches no meaning to the
+   opaque value.
+
+     zalloc must return Z_NULL if there is not enough memory for the object.
+   If zlib is used in a multi-threaded application, zalloc and zfree must be
+   thread safe.
+
+     On 16-bit systems, the functions zalloc and zfree must be able to allocate
+   exactly 65536 bytes, but will not be required to allocate more than this if
+   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers
+   returned by zalloc for objects of exactly 65536 bytes *must* have their
+   offset normalized to zero.  The default allocation function provided by this
+   library ensures this (see zutil.c).  To reduce memory requirements and avoid
+   any allocation of 64K objects, at the expense of compression ratio, compile
+   the library with -DMAX_WBITS=14 (see zconf.h).
+
+     The fields total_in and total_out can be used for statistics or progress
+   reports.  After compression, total_in holds the total size of the
+   uncompressed data and may be saved for use in the decompressor (particularly
+   if the decompressor wants to decompress everything in a single step).
+*/
+
+                        /* constants */
+
+#define Z_NO_FLUSH      0
+#define Z_PARTIAL_FLUSH 1
+#define Z_SYNC_FLUSH    2
+#define Z_FULL_FLUSH    3
+#define Z_FINISH        4
+#define Z_BLOCK         5
+#define Z_TREES         6
+/* Allowed flush values; see deflate() and inflate() below for details */
+
+#define Z_OK            0
+#define Z_STREAM_END    1
+#define Z_NEED_DICT     2
+#define Z_ERRNO        (-1)
+#define Z_STREAM_ERROR (-2)
+#define Z_DATA_ERROR   (-3)
+#define Z_MEM_ERROR    (-4)
+#define Z_BUF_ERROR    (-5)
+#define Z_VERSION_ERROR (-6)
+/* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
+ */
+
+#define Z_NO_COMPRESSION         0
+#define Z_BEST_SPEED             1
+#define Z_BEST_COMPRESSION       9
+#define Z_DEFAULT_COMPRESSION  (-1)
+/* compression levels */
+
+#define Z_FILTERED            1
+#define Z_HUFFMAN_ONLY        2
+#define Z_RLE                 3
+#define Z_FIXED               4
+#define Z_DEFAULT_STRATEGY    0
+/* compression strategy; see deflateInit2() below for details */
+
+#define Z_BINARY   0
+#define Z_TEXT     1
+#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */
+#define Z_UNKNOWN  2
+/* Possible values of the data_type field (though see inflate()) */
+
+#define Z_DEFLATED   8
+/* The deflate compression method (the only one supported in this version) */
+
+#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
+
+#define zlib_version zlibVersion()
+/* for compatibility with versions < 1.0.2 */
+
+
+                        /* basic functions */
+
+ZEXTERN const char * ZEXPORT zlibVersion OF((void));
+/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
+   If the first character differs, the library code actually used is not
+   compatible with the zlib.h header file used by the application.  This check
+   is automatically made by deflateInit and inflateInit.
+ */
+
+/*
+ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
+
+     Initializes the internal stream state for compression.  The fields
+   zalloc, zfree and opaque must be initialized before by the caller.  If
+   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
+   allocation functions.
+
+     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
+   1 gives best speed, 9 gives best compression, 0 gives no compression at all
+   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION
+   requests a default compromise between speed and compression (currently
+   equivalent to level 6).
+
+     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if level is not a valid compression level, or
+   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
+   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null
+   if there is no error message.  deflateInit does not perform any compression:
+   this will be done by deflate().
+*/
+
+
+ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
+/*
+    deflate compresses as much data as possible, and stops when the input
+  buffer becomes empty or the output buffer becomes full.  It may introduce
+  some output latency (reading input without producing any output) except when
+  forced to flush.
+
+    The detailed semantics are as follows.  deflate performs one or both of the
+  following actions:
+
+  - Compress more input starting at next_in and update next_in and avail_in
+    accordingly.  If not all input can be processed (because there is not
+    enough room in the output buffer), next_in and avail_in are updated and
+    processing will resume at this point for the next call of deflate().
+
+  - Provide more output starting at next_out and update next_out and avail_out
+    accordingly.  This action is forced if the parameter flush is non zero.
+    Forcing flush frequently degrades the compression ratio, so this parameter
+    should be set only when necessary (in interactive applications).  Some
+    output may be provided even if flush is not set.
+
+    Before the call of deflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating avail_in or avail_out accordingly; avail_out should
+  never be zero before the call.  The application can consume the compressed
+  output when it wants, for example when the output buffer is full (avail_out
+  == 0), or after each call of deflate().  If deflate returns Z_OK and with
+  zero avail_out, it must be called again after making room in the output
+  buffer because there might be more output pending.
+
+    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
+  decide how much data to accumulate before producing output, in order to
+  maximize compression.
+
+    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
+  flushed to the output buffer and the output is aligned on a byte boundary, so
+  that the decompressor can get all input data available so far.  (In
+  particular avail_in is zero after the call if enough output space has been
+  provided before the call.) Flushing may degrade compression for some
+  compression algorithms and so it should be used only when necessary.  This
+  completes the current deflate block and follows it with an empty stored block
+  that is three bits plus filler bits to the next byte, followed by four bytes
+  (00 00 ff ff).
+
+    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
+  output buffer, but the output is not aligned to a byte boundary.  All of the
+  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
+  This completes the current deflate block and follows it with an empty fixed
+  codes block that is 10 bits long.  This assures that enough bytes are output
+  in order for the decompressor to finish the block before the empty fixed code
+  block.
+
+    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
+  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
+  seven bits of the current block are held to be written as the next byte after
+  the next deflate block is completed.  In this case, the decompressor may not
+  be provided enough bits at this point in order to complete decompression of
+  the data provided so far to the compressor.  It may need to wait for the next
+  block to be emitted.  This is for advanced applications that need to control
+  the emission of deflate blocks.
+
+    If flush is set to Z_FULL_FLUSH, all output is flushed as with
+  Z_SYNC_FLUSH, and the compression state is reset so that decompression can
+  restart from this point if previous compressed data has been damaged or if
+  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade
+  compression.
+
+    If deflate returns with avail_out == 0, this function must be called again
+  with the same value of the flush parameter and more output space (updated
+  avail_out), until the flush is complete (deflate returns with non-zero
+  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
+  avail_out is greater than six to avoid repeated flush markers due to
+  avail_out == 0 on return.
+
+    If the parameter flush is set to Z_FINISH, pending input is processed,
+  pending output is flushed and deflate returns with Z_STREAM_END if there was
+  enough output space; if deflate returns with Z_OK, this function must be
+  called again with Z_FINISH and more output space (updated avail_out) but no
+  more input data, until it returns with Z_STREAM_END or an error.  After
+  deflate has returned Z_STREAM_END, the only possible operations on the stream
+  are deflateReset or deflateEnd.
+
+    Z_FINISH can be used immediately after deflateInit if all the compression
+  is to be done in a single step.  In this case, avail_out must be at least the
+  value returned by deflateBound (see below).  Then deflate is guaranteed to
+  return Z_STREAM_END.  If not enough output space is provided, deflate will
+  not return Z_STREAM_END, and it must be called again as described above.
+
+    deflate() sets strm->adler to the adler32 checksum of all input read
+  so far (that is, total_in bytes).
+
+    deflate() may update strm->data_type if it can make a good guess about
+  the input data type (Z_BINARY or Z_TEXT).  In doubt, the data is considered
+  binary.  This field is only for information purposes and does not affect the
+  compression algorithm in any manner.
+
+    deflate() returns Z_OK if some progress has been made (more input
+  processed or more output produced), Z_STREAM_END if all input has been
+  consumed and all output has been produced (only when flush is set to
+  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
+  if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible
+  (for example avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not
+  fatal, and deflate() can be called again with more input and more output
+  space to continue compressing.
+*/
+
+
+ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
+/*
+     All dynamically allocated data structures for this stream are freed.
+   This function discards any unprocessed input and does not flush any pending
+   output.
+
+     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
+   stream state was inconsistent, Z_DATA_ERROR if the stream was freed
+   prematurely (some input or output was discarded).  In the error case, msg
+   may be set but then points to a static string (which must not be
+   deallocated).
+*/
+
+
+/*
+ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
+
+     Initializes the internal stream state for decompression.  The fields
+   next_in, avail_in, zalloc, zfree and opaque must be initialized before by
+   the caller.  If next_in is not Z_NULL and avail_in is large enough (the
+   exact value depends on the compression method), inflateInit determines the
+   compression method from the zlib header and allocates all data structures
+   accordingly; otherwise the allocation will be deferred to the first call of
+   inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
+   use default allocation functions.
+
+     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit() does not process any header information -- that is deferred
+   until inflate() is called.
+*/
+
+
+ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
+/*
+    inflate decompresses as much data as possible, and stops when the input
+  buffer becomes empty or the output buffer becomes full.  It may introduce
+  some output latency (reading input without producing any output) except when
+  forced to flush.
+
+  The detailed semantics are as follows.  inflate performs one or both of the
+  following actions:
+
+  - Decompress more input starting at next_in and update next_in and avail_in
+    accordingly.  If not all input can be processed (because there is not
+    enough room in the output buffer), next_in is updated and processing will
+    resume at this point for the next call of inflate().
+
+  - Provide more output starting at next_out and update next_out and avail_out
+    accordingly.  inflate() provides as much output as possible, until there is
+    no more input data or no more space in the output buffer (see below about
+    the flush parameter).
+
+    Before the call of inflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating the next_* and avail_* values accordingly.  The
+  application can consume the uncompressed output when it wants, for example
+  when the output buffer is full (avail_out == 0), or after each call of
+  inflate().  If inflate returns Z_OK and with zero avail_out, it must be
+  called again after making room in the output buffer because there might be
+  more output pending.
+
+    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
+  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
+  output as possible to the output buffer.  Z_BLOCK requests that inflate()
+  stop if and when it gets to the next deflate block boundary.  When decoding
+  the zlib or gzip format, this will cause inflate() to return immediately
+  after the header and before the first block.  When doing a raw inflate,
+  inflate() will go ahead and process the first block, and will return when it
+  gets to the end of that block, or when it runs out of data.
+
+    The Z_BLOCK option assists in appending to or combining deflate streams.
+  Also to assist in this, on return inflate() will set strm->data_type to the
+  number of unused bits in the last byte taken from strm->next_in, plus 64 if
+  inflate() is currently decoding the last block in the deflate stream, plus
+  128 if inflate() returned immediately after decoding an end-of-block code or
+  decoding the complete header up to just before the first byte of the deflate
+  stream.  The end-of-block will not be indicated until all of the uncompressed
+  data from that block has been written to strm->next_out.  The number of
+  unused bits may in general be greater than seven, except when bit 7 of
+  data_type is set, in which case the number of unused bits will be less than
+  eight.  data_type is set as noted here every time inflate() returns for all
+  flush options, and so can be used to determine the amount of currently
+  consumed input in bits.
+
+    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
+  end of each deflate block header is reached, before any actual data in that
+  block is decoded.  This allows the caller to determine the length of the
+  deflate block header for later use in random access within a deflate block.
+  256 is added to the value of strm->data_type when inflate() returns
+  immediately after reaching the end of the deflate block header.
+
+    inflate() should normally be called until it returns Z_STREAM_END or an
+  error.  However if all decompression is to be performed in a single step (a
+  single call of inflate), the parameter flush should be set to Z_FINISH.  In
+  this case all pending input is processed and all pending output is flushed;
+  avail_out must be large enough to hold all the uncompressed data.  (The size
+  of the uncompressed data may have been saved by the compressor for this
+  purpose.) The next operation on this stream must be inflateEnd to deallocate
+  the decompression state.  The use of Z_FINISH is not required to perform an
+  inflation in one step.  However it may be used to inform inflate that a
+  faster approach can be used for the single inflate() call.  Z_FINISH also
+  informs inflate to not maintain a sliding window if the stream completes,
+  which reduces inflate's memory footprint.
+
+     In this implementation, inflate() always flushes as much output as
+  possible to the output buffer, and always uses the faster approach on the
+  first call.  So the effects of the flush parameter in this implementation are
+  on the return value of inflate() as noted below, when inflate() returns early
+  when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
+  memory for a sliding window when Z_FINISH is used.
+
+     If a preset dictionary is needed after this call (see inflateSetDictionary
+  below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
+  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
+  strm->adler to the Adler-32 checksum of all output produced so far (that is,
+  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
+  below.  At the end of the stream, inflate() checks that its computed adler32
+  checksum is equal to that saved by the compressor and returns Z_STREAM_END
+  only if the checksum is correct.
+
+    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
+  deflate data.  The header type is detected automatically, if requested when
+  initializing with inflateInit2().  Any information contained in the gzip
+  header is not retained, so applications that need that information should
+  instead use raw inflate, see inflateInit2() below, or inflateBack() and
+  perform their own processing of the gzip header and trailer.  When processing
+  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
+  producted so far.  The CRC-32 is checked against the gzip trailer.
+
+    inflate() returns Z_OK if some progress has been made (more input processed
+  or more output produced), Z_STREAM_END if the end of the compressed data has
+  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
+  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
+  corrupted (input stream not conforming to the zlib format or incorrect check
+  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
+  next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory,
+  Z_BUF_ERROR if no progress is possible or if there was not enough room in the
+  output buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and
+  inflate() can be called again with more input and more output space to
+  continue decompressing.  If Z_DATA_ERROR is returned, the application may
+  then call inflateSync() to look for a good compression block if a partial
+  recovery of the data is desired.
+*/
+
+
+ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
+/*
+     All dynamically allocated data structures for this stream are freed.
+   This function discards any unprocessed input and does not flush any pending
+   output.
+
+     inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
+   was inconsistent.  In the error case, msg may be set but then points to a
+   static string (which must not be deallocated).
+*/
+
+
+                        /* Advanced functions */
+
+/*
+    The following functions are needed only in some special applications.
+*/
+
+/*
+ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
+                                     int  level,
+                                     int  method,
+                                     int  windowBits,
+                                     int  memLevel,
+                                     int  strategy));
+
+     This is another version of deflateInit with more compression options.  The
+   fields next_in, zalloc, zfree and opaque must be initialized before by the
+   caller.
+
+     The method parameter is the compression method.  It must be Z_DEFLATED in
+   this version of the library.
+
+     The windowBits parameter is the base two logarithm of the window size
+   (the size of the history buffer).  It should be in the range 8..15 for this
+   version of the library.  Larger values of this parameter result in better
+   compression at the expense of memory usage.  The default value is 15 if
+   deflateInit is used instead.
+
+     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits
+   determines the window size.  deflate() will then generate raw deflate data
+   with no zlib header or trailer, and will not compute an adler32 check value.
+
+     windowBits can also be greater than 15 for optional gzip encoding.  Add
+   16 to windowBits to write a simple gzip header and trailer around the
+   compressed data instead of a zlib wrapper.  The gzip header will have no
+   file name, no extra data, no comment, no modification time (set to zero), no
+   header crc, and the operating system will be set to 255 (unknown).  If a
+   gzip stream is being written, strm->adler is a crc32 instead of an adler32.
+
+     The memLevel parameter specifies how much memory should be allocated
+   for the internal compression state.  memLevel=1 uses minimum memory but is
+   slow and reduces compression ratio; memLevel=9 uses maximum memory for
+   optimal speed.  The default value is 8.  See zconf.h for total memory usage
+   as a function of windowBits and memLevel.
+
+     The strategy parameter is used to tune the compression algorithm.  Use the
+   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
+   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
+   string match), or Z_RLE to limit match distances to one (run-length
+   encoding).  Filtered data consists mostly of small values with a somewhat
+   random distribution.  In this case, the compression algorithm is tuned to
+   compress them better.  The effect of Z_FILTERED is to force more Huffman
+   coding and less string matching; it is somewhat intermediate between
+   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
+   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
+   strategy parameter only affects the compression ratio but not the
+   correctness of the compressed output even if it is not set appropriately.
+   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
+   decoder for special applications.
+
+     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
+   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
+   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
+   set to null if there is no error message.  deflateInit2 does not perform any
+   compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
+                                             const Bytef *dictionary,
+                                             uInt  dictLength));
+/*
+     Initializes the compression dictionary from the given byte sequence
+   without producing any compressed output.  When using the zlib format, this
+   function must be called immediately after deflateInit, deflateInit2 or
+   deflateReset, and before any call of deflate.  When doing raw deflate, this
+   function must be called either before any call of deflate, or immediately
+   after the completion of a deflate block, i.e. after all input has been
+   consumed and all output has been delivered when using any of the flush
+   options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH.  The
+   compressor and decompressor must use exactly the same dictionary (see
+   inflateSetDictionary).
+
+     The dictionary should consist of strings (byte sequences) that are likely
+   to be encountered later in the data to be compressed, with the most commonly
+   used strings preferably put towards the end of the dictionary.  Using a
+   dictionary is most useful when the data to be compressed is short and can be
+   predicted with good accuracy; the data can then be compressed better than
+   with the default empty dictionary.
+
+     Depending on the size of the compression data structures selected by
+   deflateInit or deflateInit2, a part of the dictionary may in effect be
+   discarded, for example if the dictionary is larger than the window size
+   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
+   useful should be put at the end of the dictionary, not at the front.  In
+   addition, the current implementation of deflate will use at most the window
+   size minus 262 bytes of the provided dictionary.
+
+     Upon return of this function, strm->adler is set to the adler32 value
+   of the dictionary; the decompressor may later use this value to determine
+   which dictionary has been used by the compressor.  (The adler32 value
+   applies to the whole dictionary even if only a subset of the dictionary is
+   actually used by the compressor.) If a raw deflate was requested, then the
+   adler32 value is not computed and strm->adler is not set.
+
+     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
+   inconsistent (for example if deflate has already been called for this stream
+   or if not at a block boundary for raw deflate).  deflateSetDictionary does
+   not perform any compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
+                                    z_streamp source));
+/*
+     Sets the destination stream as a complete copy of the source stream.
+
+     This function can be useful when several compression strategies will be
+   tried, for example when there are several ways of pre-processing the input
+   data with a filter.  The streams that will be discarded should then be freed
+   by calling deflateEnd.  Note that deflateCopy duplicates the internal
+   compression state which can be quite large, so this strategy is slow and can
+   consume lots of memory.
+
+     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
+   destination.
+*/
+
+ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
+/*
+     This function is equivalent to deflateEnd followed by deflateInit,
+   but does not free and reallocate all the internal compression state.  The
+   stream will keep the same compression level and any other attributes that
+   may have been set by deflateInit2.
+
+     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
+                                      int level,
+                                      int strategy));
+/*
+     Dynamically update the compression level and compression strategy.  The
+   interpretation of level and strategy is as in deflateInit2.  This can be
+   used to switch between compression and straight copy of the input data, or
+   to switch to a different kind of input data requiring a different strategy.
+   If the compression level is changed, the input available so far is
+   compressed with the old level (and may be flushed); the new level will take
+   effect only at the next call of deflate().
+
+     Before the call of deflateParams, the stream state must be set as for
+   a call of deflate(), since the currently available input may have to be
+   compressed and flushed.  In particular, strm->avail_out must be non-zero.
+
+     deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
+   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if
+   strm->avail_out was zero.
+*/
+
+ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
+                                    int good_length,
+                                    int max_lazy,
+                                    int nice_length,
+                                    int max_chain));
+/*
+     Fine tune deflate's internal compression parameters.  This should only be
+   used by someone who understands the algorithm used by zlib's deflate for
+   searching for the best matching string, and even then only by the most
+   fanatic optimizer trying to squeeze out the last compressed bit for their
+   specific input data.  Read the deflate.c source code for the meaning of the
+   max_lazy, good_length, nice_length, and max_chain parameters.
+
+     deflateTune() can be called after deflateInit() or deflateInit2(), and
+   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
+ */
+
+ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
+                                       uLong sourceLen));
+/*
+     deflateBound() returns an upper bound on the compressed size after
+   deflation of sourceLen bytes.  It must be called after deflateInit() or
+   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
+   to allocate an output buffer for deflation in a single pass, and so would be
+   called before deflate().  If that first deflate() call is provided the
+   sourceLen input bytes, an output buffer allocated to the size returned by
+   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
+   to return Z_STREAM_END.  Note that it is possible for the compressed size to
+   be larger than the value returned by deflateBound() if flush options other
+   than Z_FINISH or Z_NO_FLUSH are used.
+*/
+
+ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm,
+                                       unsigned *pending,
+                                       int *bits));
+/*
+     deflatePending() returns the number of bytes and bits of output that have
+   been generated, but not yet provided in the available output.  The bytes not
+   provided would be due to the available output space having being consumed.
+   The number of bits of output not provided are between 0 and 7, where they
+   await more bits to join them in order to fill out a full byte.  If pending
+   or bits are Z_NULL, then those values are not set.
+
+     deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+ */
+
+ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
+                                     int bits,
+                                     int value));
+/*
+     deflatePrime() inserts bits in the deflate output stream.  The intent
+   is that this function is used to start off the deflate output with the bits
+   leftover from a previous deflate stream when appending to it.  As such, this
+   function can only be used for raw deflate, and must be used before the first
+   deflate() call after a deflateInit2() or deflateReset().  bits must be less
+   than or equal to 16, and that many of the least significant bits of value
+   will be inserted in the output.
+
+     deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
+   room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
+   source stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
+                                         gz_headerp head));
+/*
+     deflateSetHeader() provides gzip header information for when a gzip
+   stream is requested by deflateInit2().  deflateSetHeader() may be called
+   after deflateInit2() or deflateReset() and before the first call of
+   deflate().  The text, time, os, extra field, name, and comment information
+   in the provided gz_header structure are written to the gzip header (xflag is
+   ignored -- the extra flags are set according to the compression level).  The
+   caller must assure that, if not Z_NULL, name and comment are terminated with
+   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
+   available there.  If hcrc is true, a gzip header crc is included.  Note that
+   the current versions of the command-line version of gzip (up through version
+   1.3.x) do not support header crc's, and will report that it is a "multi-part
+   gzip file" and give up.
+
+     If deflateSetHeader is not used, the default gzip header has text false,
+   the time set to zero, and os set to 255, with no extra, name, or comment
+   fields.  The gzip header is returned to the default state by deflateReset().
+
+     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
+                                     int  windowBits));
+
+     This is another version of inflateInit with an extra parameter.  The
+   fields next_in, avail_in, zalloc, zfree and opaque must be initialized
+   before by the caller.
+
+     The windowBits parameter is the base two logarithm of the maximum window
+   size (the size of the history buffer).  It should be in the range 8..15 for
+   this version of the library.  The default value is 15 if inflateInit is used
+   instead.  windowBits must be greater than or equal to the windowBits value
+   provided to deflateInit2() while compressing, or it must be equal to 15 if
+   deflateInit2() was not used.  If a compressed stream with a larger window
+   size is given as input, inflate() will return with the error code
+   Z_DATA_ERROR instead of trying to allocate a larger window.
+
+     windowBits can also be zero to request that inflate use the window size in
+   the zlib header of the compressed stream.
+
+     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
+   determines the window size.  inflate() will then process raw deflate data,
+   not looking for a zlib or gzip header, not generating a check value, and not
+   looking for any check values for comparison at the end of the stream.  This
+   is for use with other formats that use the deflate compressed data format
+   such as zip.  Those formats provide their own check values.  If a custom
+   format is developed using the raw deflate format for compressed data, it is
+   recommended that a check value such as an adler32 or a crc32 be applied to
+   the uncompressed data as is done in the zlib, gzip, and zip formats.  For
+   most applications, the zlib format should be used as is.  Note that comments
+   above on the use in deflateInit2() applies to the magnitude of windowBits.
+
+     windowBits can also be greater than 15 for optional gzip decoding.  Add
+   32 to windowBits to enable zlib and gzip decoding with automatic header
+   detection, or add 16 to decode only the gzip format (the zlib format will
+   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a
+   crc32 instead of an adler32.
+
+     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit2 does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit2() does not process any header information -- that is
+   deferred until inflate() is called.
+*/
+
+ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
+                                             const Bytef *dictionary,
+                                             uInt  dictLength));
+/*
+     Initializes the decompression dictionary from the given uncompressed byte
+   sequence.  This function must be called immediately after a call of inflate,
+   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor
+   can be determined from the adler32 value returned by that call of inflate.
+   The compressor and decompressor must use exactly the same dictionary (see
+   deflateSetDictionary).  For raw inflate, this function can be called at any
+   time to set the dictionary.  If the provided dictionary is smaller than the
+   window and there is already data in the window, then the provided dictionary
+   will amend what's there.  The application must insure that the dictionary
+   that was used for compression is provided.
+
+     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
+   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+   expected one (incorrect adler32 value).  inflateSetDictionary does not
+   perform any decompression: this will be done by subsequent calls of
+   inflate().
+*/
+
+ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
+/*
+     Skips invalid compressed data until a possible full flush point (see above
+   for the description of deflate with Z_FULL_FLUSH) can be found, or until all
+   available input is skipped.  No output is provided.
+
+     inflateSync searches for a 00 00 FF FF pattern in the compressed data.
+   All full flush points have this pattern, but not all occurences of this
+   pattern are full flush points.
+
+     inflateSync returns Z_OK if a possible full flush point has been found,
+   Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
+   has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
+   In the success case, the application may save the current current value of
+   total_in which indicates where valid compressed data was found.  In the
+   error case, the application may repeatedly call inflateSync, providing more
+   input each time, until success or end of the input data.
+*/
+
+ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
+                                    z_streamp source));
+/*
+     Sets the destination stream as a complete copy of the source stream.
+
+     This function can be useful when randomly accessing a large stream.  The
+   first pass through the stream can periodically record the inflate state,
+   allowing restarting inflate at those points when randomly accessing the
+   stream.
+
+     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
+   destination.
+*/
+
+ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
+/*
+     This function is equivalent to inflateEnd followed by inflateInit,
+   but does not free and reallocate all the internal decompression state.  The
+   stream will keep attributes that may have been set by inflateInit2.
+
+     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
+                                      int windowBits));
+/*
+     This function is the same as inflateReset, but it also permits changing
+   the wrap and window size requests.  The windowBits parameter is interpreted
+   the same as it is for inflateInit2.
+
+     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
+   the windowBits parameter is invalid.
+*/
+
+ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
+                                     int bits,
+                                     int value));
+/*
+     This function inserts bits in the inflate input stream.  The intent is
+   that this function is used to start inflating at a bit position in the
+   middle of a byte.  The provided bits will be used before any bytes are used
+   from next_in.  This function should only be used with raw inflate, and
+   should be used before the first inflate() call after inflateInit2() or
+   inflateReset().  bits must be less than or equal to 16, and that many of the
+   least significant bits of value will be inserted in the input.
+
+     If bits is negative, then the input stream bit buffer is emptied.  Then
+   inflatePrime() can be called again to put bits in the buffer.  This is used
+   to clear out bits leftover after feeding inflate a block description prior
+   to feeding inflate codes.
+
+     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
+/*
+     This function returns two values, one in the lower 16 bits of the return
+   value, and the other in the remaining upper bits, obtained by shifting the
+   return value down 16 bits.  If the upper value is -1 and the lower value is
+   zero, then inflate() is currently decoding information outside of a block.
+   If the upper value is -1 and the lower value is non-zero, then inflate is in
+   the middle of a stored block, with the lower value equaling the number of
+   bytes from the input remaining to copy.  If the upper value is not -1, then
+   it is the number of bits back from the current bit position in the input of
+   the code (literal or length/distance pair) currently being processed.  In
+   that case the lower value is the number of bytes already emitted for that
+   code.
+
+     A code is being processed if inflate is waiting for more input to complete
+   decoding of the code, or if it has completed decoding but is waiting for
+   more output space to write the literal or match data.
+
+     inflateMark() is used to mark locations in the input data for random
+   access, which may be at bit positions, and to note those cases where the
+   output of a code may span boundaries of random access blocks.  The current
+   location in the input stream can be determined from avail_in and data_type
+   as noted in the description for the Z_BLOCK flush parameter for inflate.
+
+     inflateMark returns the value noted above or -1 << 16 if the provided
+   source stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
+                                         gz_headerp head));
+/*
+     inflateGetHeader() requests that gzip header information be stored in the
+   provided gz_header structure.  inflateGetHeader() may be called after
+   inflateInit2() or inflateReset(), and before the first call of inflate().
+   As inflate() processes the gzip stream, head->done is zero until the header
+   is completed, at which time head->done is set to one.  If a zlib stream is
+   being decoded, then head->done is set to -1 to indicate that there will be
+   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
+   used to force inflate() to return immediately after header processing is
+   complete and before any actual data is decompressed.
+
+     The text, time, xflags, and os fields are filled in with the gzip header
+   contents.  hcrc is set to true if there is a header CRC.  (The header CRC
+   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
+   contains the maximum number of bytes to write to extra.  Once done is true,
+   extra_len contains the actual extra field length, and extra contains the
+   extra field, or that field truncated if extra_max is less than extra_len.
+   If name is not Z_NULL, then up to name_max characters are written there,
+   terminated with a zero unless the length is greater than name_max.  If
+   comment is not Z_NULL, then up to comm_max characters are written there,
+   terminated with a zero unless the length is greater than comm_max.  When any
+   of extra, name, or comment are not Z_NULL and the respective field is not
+   present in the header, then that field is set to Z_NULL to signal its
+   absence.  This allows the use of deflateSetHeader() with the returned
+   structure to duplicate the header.  However if those fields are set to
+   allocated memory, then the application will need to save those pointers
+   elsewhere so that they can be eventually freed.
+
+     If inflateGetHeader is not used, then the header information is simply
+   discarded.  The header is always checked for validity, including the header
+   CRC if present.  inflateReset() will reset the process to discard the header
+   information.  The application would need to call inflateGetHeader() again to
+   retrieve the header from the next gzip stream.
+
+     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
+                                        unsigned char FAR *window));
+
+     Initialize the internal stream state for decompression using inflateBack()
+   calls.  The fields zalloc, zfree and opaque in strm must be initialized
+   before the call.  If zalloc and zfree are Z_NULL, then the default library-
+   derived memory allocation routines are used.  windowBits is the base two
+   logarithm of the window size, in the range 8..15.  window is a caller
+   supplied buffer of that size.  Except for special applications where it is
+   assured that deflate was used with small window sizes, windowBits must be 15
+   and a 32K byte window must be supplied to be able to decompress general
+   deflate streams.
+
+     See inflateBack() for the usage of these routines.
+
+     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
+   the parameters are invalid, Z_MEM_ERROR if the internal state could not be
+   allocated, or Z_VERSION_ERROR if the version of the library does not match
+   the version of the header file.
+*/
+
+typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
+typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
+
+ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
+                                    in_func in, void FAR *in_desc,
+                                    out_func out, void FAR *out_desc));
+/*
+     inflateBack() does a raw inflate with a single call using a call-back
+   interface for input and output.  This is more efficient than inflate() for
+   file i/o applications in that it avoids copying between the output and the
+   sliding window by simply making the window itself the output buffer.  This
+   function trusts the application to not change the output buffer passed by
+   the output function, at least until inflateBack() returns.
+
+     inflateBackInit() must be called first to allocate the internal state
+   and to initialize the state with the user-provided window buffer.
+   inflateBack() may then be used multiple times to inflate a complete, raw
+   deflate stream with each call.  inflateBackEnd() is then called to free the
+   allocated state.
+
+     A raw deflate stream is one with no zlib or gzip header or trailer.
+   This routine would normally be used in a utility that reads zip or gzip
+   files and writes out uncompressed files.  The utility would decode the
+   header and process the trailer on its own, hence this routine expects only
+   the raw deflate stream to decompress.  This is different from the normal
+   behavior of inflate(), which expects either a zlib or gzip header and
+   trailer around the deflate stream.
+
+     inflateBack() uses two subroutines supplied by the caller that are then
+   called by inflateBack() for input and output.  inflateBack() calls those
+   routines until it reads a complete deflate stream and writes out all of the
+   uncompressed data, or until it encounters an error.  The function's
+   parameters and return types are defined above in the in_func and out_func
+   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the
+   number of bytes of provided input, and a pointer to that input in buf.  If
+   there is no input available, in() must return zero--buf is ignored in that
+   case--and inflateBack() will return a buffer error.  inflateBack() will call
+   out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].  out()
+   should return zero on success, or non-zero on failure.  If out() returns
+   non-zero, inflateBack() will return with an error.  Neither in() nor out()
+   are permitted to change the contents of the window provided to
+   inflateBackInit(), which is also the buffer that out() uses to write from.
+   The length written by out() will be at most the window size.  Any non-zero
+   amount of input may be provided by in().
+
+     For convenience, inflateBack() can be provided input on the first call by
+   setting strm->next_in and strm->avail_in.  If that input is exhausted, then
+   in() will be called.  Therefore strm->next_in must be initialized before
+   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
+   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
+   must also be initialized, and then if strm->avail_in is not zero, input will
+   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].
+
+     The in_desc and out_desc parameters of inflateBack() is passed as the
+   first parameter of in() and out() respectively when they are called.  These
+   descriptors can be optionally used to pass any information that the caller-
+   supplied in() and out() functions need to do their job.
+
+     On return, inflateBack() will set strm->next_in and strm->avail_in to
+   pass back any unused input that was provided by the last in() call.  The
+   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
+   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
+   in the deflate stream (in which case strm->msg is set to indicate the nature
+   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
+   In the case of Z_BUF_ERROR, an input or output error can be distinguished
+   using strm->next_in which will be Z_NULL only if in() returned an error.  If
+   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
+   non-zero.  (in() will always be called before out(), so strm->next_in is
+   assured to be defined if out() returns non-zero.) Note that inflateBack()
+   cannot return Z_OK.
+*/
+
+ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
+/*
+     All memory allocated by inflateBackInit() is freed.
+
+     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
+   state was inconsistent.
+*/
+
+ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
+/* Return flags indicating compile-time options.
+
+    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
+     1.0: size of uInt
+     3.2: size of uLong
+     5.4: size of voidpf (pointer)
+     7.6: size of z_off_t
+
+    Compiler, assembler, and debug options:
+     8: DEBUG
+     9: ASMV or ASMINF -- use ASM code
+     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
+     11: 0 (reserved)
+
+    One-time table building (smaller code, but not thread-safe if true):
+     12: BUILDFIXED -- build static block decoding tables when needed
+     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
+     14,15: 0 (reserved)
+
+    Library content (indicates missing functionality):
+     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
+                          deflate code when not needed)
+     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
+                    and decode gzip streams (to avoid linking crc code)
+     18-19: 0 (reserved)
+
+    Operation variations (changes in library functionality):
+     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
+     21: FASTEST -- deflate algorithm with only one, lowest compression level
+     22,23: 0 (reserved)
+
+    The sprintf variant used by gzprintf (zero is best):
+     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
+     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
+     26: 0 = returns value, 1 = void -- 1 means inferred string length returned
+
+    Remainder:
+     27-31: 0 (reserved)
+ */
+
+#ifndef Z_SOLO
+
+                        /* utility functions */
+
+/*
+     The following utility functions are implemented on top of the basic
+   stream-oriented functions.  To simplify the interface, some default options
+   are assumed (compression level and memory usage, standard memory allocation
+   functions).  The source code of these utility functions can be modified if
+   you need special options.
+*/
+
+ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
+                                 const Bytef *source, uLong sourceLen));
+/*
+     Compresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be at least the value returned by
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
+   compressed buffer.
+
+     compress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer.
+*/
+
+ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
+                                  const Bytef *source, uLong sourceLen,
+                                  int level));
+/*
+     Compresses the source buffer into the destination buffer.  The level
+   parameter has the same meaning as in deflateInit.  sourceLen is the byte
+   length of the source buffer.  Upon entry, destLen is the total size of the
+   destination buffer, which must be at least the value returned by
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
+   compressed buffer.
+
+     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+   Z_STREAM_ERROR if the level parameter is invalid.
+*/
+
+ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
+/*
+     compressBound() returns an upper bound on the compressed size after
+   compress() or compress2() on sourceLen bytes.  It would be used before a
+   compress() or compress2() call to allocate the destination buffer.
+*/
+
+ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
+                                   const Bytef *source, uLong sourceLen));
+/*
+     Decompresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be large enough to hold the entire
+   uncompressed data.  (The size of the uncompressed data must have been saved
+   previously by the compressor and transmitted to the decompressor by some
+   mechanism outside the scope of this compression library.) Upon exit, destLen
+   is the actual size of the uncompressed buffer.
+
+     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In
+   the case where there is not enough room, uncompress() will fill the output
+   buffer with the uncompressed data up to that point.
+*/
+
+                        /* gzip file access functions */
+
+/*
+     This library supports reading and writing files in gzip (.gz) format with
+   an interface similar to that of stdio, using the functions that start with
+   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
+   wrapper, documented in RFC 1952, wrapped around a deflate stream.
+*/
+
+typedef struct gzFile_s *gzFile;    /* semi-opaque gzip file descriptor */
+
+/*
+ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
+
+     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
+   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
+   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
+   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
+   for fixed code compression as in "wb9F".  (See the description of
+   deflateInit2 for more information about the strategy parameter.)  'T' will
+   request transparent writing or appending with no compression and not using
+   the gzip format.
+
+     "a" can be used instead of "w" to request that the gzip stream that will
+   be written be appended to the file.  "+" will result in an error, since
+   reading and writing to the same gzip file is not supported.
+
+     These functions, as well as gzip, will read and decode a sequence of gzip
+   streams in a file.  The append function of gzopen() can be used to create
+   such a file.  (Also see gzflush() for another way to do this.)  When
+   appending, gzopen does not test whether the file begins with a gzip stream,
+   nor does it look for the end of the gzip streams to begin appending.  gzopen
+   will simply append a gzip stream to the existing file.
+
+     gzopen can be used to read a file which is not in gzip format; in this
+   case gzread will directly read from the file without decompression.  When
+   reading, this will be detected automatically by looking for the magic two-
+   byte gzip header.
+
+     gzopen returns NULL if the file could not be opened, if there was
+   insufficient memory to allocate the gzFile state, or if an invalid mode was
+   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
+   errno can be checked to determine if the reason gzopen failed was that the
+   file could not be opened.
+*/
+
+ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
+/*
+     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
+   are obtained from calls like open, dup, creat, pipe or fileno (if the file
+   has been previously opened with fopen).  The mode parameter is as in gzopen.
+
+     The next call of gzclose on the returned gzFile will also close the file
+   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
+   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
+   mode);.  The duplicated descriptor should be saved to avoid a leak, since
+   gzdopen does not close fd if it fails.  If you are using fileno() to get the
+   file descriptor from a FILE *, then you will have to use dup() to avoid
+   double-close()ing the file descriptor.  Both gzclose() and fclose() will
+   close the associated file descriptor, so they need to have different file
+   descriptors.
+
+     gzdopen returns NULL if there was insufficient memory to allocate the
+   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
+   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
+   used until the next gz* read, write, seek, or close operation, so gzdopen
+   will not detect if fd is invalid (unless fd is -1).
+*/
+
+ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
+/*
+     Set the internal buffer size used by this library's functions.  The
+   default buffer size is 8192 bytes.  This function must be called after
+   gzopen() or gzdopen(), and before any other calls that read or write the
+   file.  The buffer memory allocation is always deferred to the first read or
+   write.  Two buffers are allocated, either both of the specified size when
+   writing, or one of the specified size and the other twice that size when
+   reading.  A larger buffer size of, for example, 64K or 128K bytes will
+   noticeably increase the speed of decompression (reading).
+
+     The new buffer size also affects the maximum length for gzprintf().
+
+     gzbuffer() returns 0 on success, or -1 on failure, such as being called
+   too late.
+*/
+
+ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
+/*
+     Dynamically update the compression level or strategy.  See the description
+   of deflateInit2 for the meaning of these parameters.
+
+     gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
+   opened for writing.
+*/
+
+ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
+/*
+     Reads the given number of uncompressed bytes from the compressed file.  If
+   the input file is not in gzip format, gzread copies the given number of
+   bytes into the buffer directly from the file.
+
+     After reaching the end of a gzip stream in the input, gzread will continue
+   to read, looking for another gzip stream.  Any number of gzip streams may be
+   concatenated in the input file, and will all be decompressed by gzread().
+   If something other than a gzip stream is encountered after a gzip stream,
+   that remaining trailing garbage is ignored (and no error is returned).
+
+     gzread can be used to read a gzip file that is being concurrently written.
+   Upon reaching the end of the input, gzread will return with the available
+   data.  If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
+   gzclearerr can be used to clear the end of file indicator in order to permit
+   gzread to be tried again.  Z_OK indicates that a gzip stream was completed
+   on the last gzread.  Z_BUF_ERROR indicates that the input file ended in the
+   middle of a gzip stream.  Note that gzread does not return -1 in the event
+   of an incomplete gzip stream.  This error is deferred until gzclose(), which
+   will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
+   stream.  Alternatively, gzerror can be used before gzclose to detect this
+   case.
+
+     gzread returns the number of uncompressed bytes actually read, less than
+   len for end of file, or -1 for error.
+*/
+
+ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
+                                voidpc buf, unsigned len));
+/*
+     Writes the given number of uncompressed bytes into the compressed file.
+   gzwrite returns the number of uncompressed bytes written or 0 in case of
+   error.
+*/
+
+ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...));
+/*
+     Converts, formats, and writes the arguments to the compressed file under
+   control of the format string, as in fprintf.  gzprintf returns the number of
+   uncompressed bytes actually written, or 0 in case of error.  The number of
+   uncompressed bytes written is limited to 8191, or one less than the buffer
+   size given to gzbuffer().  The caller should assure that this limit is not
+   exceeded.  If it is exceeded, then gzprintf() will return an error (0) with
+   nothing written.  In this case, there may also be a buffer overflow with
+   unpredictable consequences, which is possible only if zlib was compiled with
+   the insecure functions sprintf() or vsprintf() because the secure snprintf()
+   or vsnprintf() functions were not available.  This can be determined using
+   zlibCompileFlags().
+*/
+
+ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
+/*
+     Writes the given null-terminated string to the compressed file, excluding
+   the terminating null character.
+
+     gzputs returns the number of characters written, or -1 in case of error.
+*/
+
+ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
+/*
+     Reads bytes from the compressed file until len-1 characters are read, or a
+   newline character is read and transferred to buf, or an end-of-file
+   condition is encountered.  If any characters are read or if len == 1, the
+   string is terminated with a null character.  If no characters are read due
+   to an end-of-file or len < 1, then the buffer is left untouched.
+
+     gzgets returns buf which is a null-terminated string, or it returns NULL
+   for end-of-file or in case of error.  If there was an error, the contents at
+   buf are indeterminate.
+*/
+
+ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
+/*
+     Writes c, converted to an unsigned char, into the compressed file.  gzputc
+   returns the value that was written, or -1 in case of error.
+*/
+
+ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
+/*
+     Reads one byte from the compressed file.  gzgetc returns this byte or -1
+   in case of end of file or error.  This is implemented as a macro for speed.
+   As such, it does not do all of the checking the other functions do.  I.e.
+   it does not check to see if file is NULL, nor whether the structure file
+   points to has been clobbered or not.
+*/
+
+ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
+/*
+     Push one character back onto the stream to be read as the first character
+   on the next read.  At least one character of push-back is allowed.
+   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
+   fail if c is -1, and may fail if a character has been pushed but not read
+   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
+   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
+   The pushed character will be discarded if the stream is repositioned with
+   gzseek() or gzrewind().
+*/
+
+ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
+/*
+     Flushes all pending output into the compressed file.  The parameter flush
+   is as in the deflate() function.  The return value is the zlib error number
+   (see function gzerror below).  gzflush is only permitted when writing.
+
+     If the flush parameter is Z_FINISH, the remaining data is written and the
+   gzip stream is completed in the output.  If gzwrite() is called again, a new
+   gzip stream will be started in the output.  gzread() is able to read such
+   concatented gzip streams.
+
+     gzflush should be called only when strictly necessary because it will
+   degrade compression if called too often.
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
+                                   z_off_t offset, int whence));
+
+     Sets the starting position for the next gzread or gzwrite on the given
+   compressed file.  The offset represents a number of bytes in the
+   uncompressed data stream.  The whence parameter is defined as in lseek(2);
+   the value SEEK_END is not supported.
+
+     If the file is opened for reading, this function is emulated but can be
+   extremely slow.  If the file is opened for writing, only forward seeks are
+   supported; gzseek then compresses a sequence of zeroes up to the new
+   starting position.
+
+     gzseek returns the resulting offset location as measured in bytes from
+   the beginning of the uncompressed stream, or -1 in case of error, in
+   particular if the file is opened for writing and the new starting position
+   would be before the current position.
+*/
+
+ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
+/*
+     Rewinds the given file. This function is supported only for reading.
+
+     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
+
+     Returns the starting position for the next gzread or gzwrite on the given
+   compressed file.  This position represents a number of bytes in the
+   uncompressed data stream, and is zero when starting, even if appending or
+   reading a gzip stream from the middle of a file using gzdopen().
+
+     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
+
+     Returns the current offset in the file being read or written.  This offset
+   includes the count of bytes that precede the gzip stream, for example when
+   appending or when using gzdopen() for reading.  When reading, the offset
+   does not include as yet unused buffered input.  This information can be used
+   for a progress indicator.  On error, gzoffset() returns -1.
+*/
+
+ZEXTERN int ZEXPORT gzeof OF((gzFile file));
+/*
+     Returns true (1) if the end-of-file indicator has been set while reading,
+   false (0) otherwise.  Note that the end-of-file indicator is set only if the
+   read tried to go past the end of the input, but came up short.  Therefore,
+   just like feof(), gzeof() may return false even if there is no more data to
+   read, in the event that the last read request was for the exact number of
+   bytes remaining in the input file.  This will happen if the input file size
+   is an exact multiple of the buffer size.
+
+     If gzeof() returns true, then the read functions will return no more data,
+   unless the end-of-file indicator is reset by gzclearerr() and the input file
+   has grown since the previous end of file was detected.
+*/
+
+ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
+/*
+     Returns true (1) if file is being copied directly while reading, or false
+   (0) if file is a gzip stream being decompressed.
+
+     If the input file is empty, gzdirect() will return true, since the input
+   does not contain a gzip stream.
+
+     If gzdirect() is used immediately after gzopen() or gzdopen() it will
+   cause buffers to be allocated to allow reading the file to determine if it
+   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
+   gzdirect().
+
+     When writing, gzdirect() returns true (1) if transparent writing was
+   requested ("wT" for the gzopen() mode), or false (0) otherwise.  (Note:
+   gzdirect() is not needed when writing.  Transparent writing must be
+   explicitly requested, so the application already knows the answer.  When
+   linking statically, using gzdirect() will include all of the zlib code for
+   gzip file reading and decompression, which may not be desired.)
+*/
+
+ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
+/*
+     Flushes all pending output if necessary, closes the compressed file and
+   deallocates the (de)compression state.  Note that once file is closed, you
+   cannot call gzerror with file, since its structures have been deallocated.
+   gzclose must not be called more than once on the same file, just as free
+   must not be called more than once on the same allocation.
+
+     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
+   file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
+   last read ended in the middle of a gzip stream, or Z_OK on success.
+*/
+
+ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
+ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
+/*
+     Same as gzclose(), but gzclose_r() is only for use when reading, and
+   gzclose_w() is only for use when writing or appending.  The advantage to
+   using these instead of gzclose() is that they avoid linking in zlib
+   compression or decompression code that is not used when only reading or only
+   writing respectively.  If gzclose() is used, then both compression and
+   decompression code will be included the application when linking to a static
+   zlib library.
+*/
+
+ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
+/*
+     Returns the error message for the last error which occurred on the given
+   compressed file.  errnum is set to zlib error number.  If an error occurred
+   in the file system and not in the compression library, errnum is set to
+   Z_ERRNO and the application may consult errno to get the exact error code.
+
+     The application must not modify the returned string.  Future calls to
+   this function may invalidate the previously returned string.  If file is
+   closed, then the string previously returned by gzerror will no longer be
+   available.
+
+     gzerror() should be used to distinguish errors from end-of-file for those
+   functions above that do not distinguish those cases in their return values.
+*/
+
+ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
+/*
+     Clears the error and end-of-file flags for file.  This is analogous to the
+   clearerr() function in stdio.  This is useful for continuing to read a gzip
+   file that is being written concurrently.
+*/
+
+#endif /* !Z_SOLO */
+
+                        /* checksum functions */
+
+/*
+     These functions are not related to compression but are exported
+   anyway because they might be useful in applications using the compression
+   library.
+*/
+
+ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
+/*
+     Update a running Adler-32 checksum with the bytes buf[0..len-1] and
+   return the updated checksum.  If buf is Z_NULL, this function returns the
+   required initial value for the checksum.
+
+     An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+   much faster.
+
+   Usage example:
+
+     uLong adler = adler32(0L, Z_NULL, 0);
+
+     while (read_buffer(buffer, length) != EOF) {
+       adler = adler32(adler, buffer, length);
+     }
+     if (adler != original_adler) error();
+*/
+
+/*
+ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
+                                          z_off_t len2));
+
+     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
+   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
+   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
+   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.  Note
+   that the z_off_t type (like off_t) is a signed integer.  If len2 is
+   negative, the result has no meaning or utility.
+*/
+
+ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
+/*
+     Update a running CRC-32 with the bytes buf[0..len-1] and return the
+   updated CRC-32.  If buf is Z_NULL, this function returns the required
+   initial value for the for the crc.  Pre- and post-conditioning (one's
+   complement) is performed within this function so it shouldn't be done by the
+   application.
+
+   Usage example:
+
+     uLong crc = crc32(0L, Z_NULL, 0);
+
+     while (read_buffer(buffer, length) != EOF) {
+       crc = crc32(crc, buffer, length);
+     }
+     if (crc != original_crc) error();
+*/
+
+/*
+ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
+
+     Combine two CRC-32 check values into one.  For two sequences of bytes,
+   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
+   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
+   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
+   len2.
+*/
+
+
+                        /* various hacks, don't look :) */
+
+/* deflateInit and inflateInit are macros to allow checking the zlib version
+ * and the compiler's view of z_stream:
+ */
+ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
+                                     const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
+                                     const char *version, int stream_size));
+ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
+                                      int windowBits, int memLevel,
+                                      int strategy, const char *version,
+                                      int stream_size));
+ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
+                                      const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
+                                         unsigned char FAR *window,
+                                         const char *version,
+                                         int stream_size));
+#define deflateInit(strm, level) \
+        deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
+#define inflateInit(strm) \
+        inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
+#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+        deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+                      (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
+#define inflateInit2(strm, windowBits) \
+        inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
+                      (int)sizeof(z_stream))
+#define inflateBackInit(strm, windowBits, window) \
+        inflateBackInit_((strm), (windowBits), (window), \
+                      ZLIB_VERSION, (int)sizeof(z_stream))
+
+#ifndef Z_SOLO
+
+/* gzgetc() macro and its supporting function and exposed data structure.  Note
+ * that the real internal state is much larger than the exposed structure.
+ * This abbreviated structure exposes just enough for the gzgetc() macro.  The
+ * user should not mess with these exposed elements, since their names or
+ * behavior could change in the future, perhaps even capriciously.  They can
+ * only be used by the gzgetc() macro.  You have been warned.
+ */
+struct gzFile_s {
+    unsigned have;
+    unsigned char *next;
+    z_off64_t pos;
+};
+ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file));
+#define gzgetc(g) \
+    ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc_(g))
+
+/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
+ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
+ * both are true, the application gets the *64 functions, and the regular
+ * functions are changed to 64 bits) -- in case these are set on systems
+ * without large file support, _LFS64_LARGEFILE must also be true
+ */
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
+   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
+#endif
+
+#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0
+#  ifdef Z_PREFIX_SET
+#    define z_gzopen z_gzopen64
+#    define z_gzseek z_gzseek64
+#    define z_gztell z_gztell64
+#    define z_gzoffset z_gzoffset64
+#    define z_adler32_combine z_adler32_combine64
+#    define z_crc32_combine z_crc32_combine64
+#  else
+#    define gzopen gzopen64
+#    define gzseek gzseek64
+#    define gztell gztell64
+#    define gzoffset gzoffset64
+#    define adler32_combine adler32_combine64
+#    define crc32_combine crc32_combine64
+#  endif
+#  ifndef _LARGEFILE64_SOURCE
+     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
+     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
+     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
+     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#  endif
+#else
+   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
+   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
+   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
+   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+#endif
+
+#else /* Z_SOLO */
+
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+
+#endif /* !Z_SOLO */
+
+/* hack for buggy compilers */
+#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
+    struct internal_state {int dummy;};
+#endif
+
+/* undocumented functions */
+ZEXTERN const char   * ZEXPORT zError           OF((int));
+ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
+ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
+ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
+ZEXTERN int            ZEXPORT inflateResetKeep OF((z_streamp));
+ZEXTERN int            ZEXPORT deflateResetKeep OF((z_streamp));
+#ifndef Z_SOLO
+  ZEXTERN unsigned long  ZEXPORT gzflags          OF((void));
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ZLIB_H */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.map b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.map
new file mode 100644 (file)
index 0000000..54fa553
--- /dev/null
@@ -0,0 +1,79 @@
+ZLIB_1.2.0 {
+  global:
+    compressBound;
+    deflateBound;
+    inflateBack;
+    inflateBackEnd;
+    inflateBackInit_;
+    inflateCopy;
+  local:
+    deflate_copyright;
+    inflate_copyright;
+    inflate_fast;
+    inflate_table;
+    zcalloc;
+    zcfree;
+    z_errmsg;
+    gz_error;
+    gz_intmax;
+    _*;
+};
+
+ZLIB_1.2.0.2 {
+    gzclearerr;
+    gzungetc;
+    zlibCompileFlags;
+} ZLIB_1.2.0;
+
+ZLIB_1.2.0.8 {
+    deflatePrime;
+} ZLIB_1.2.0.2;
+
+ZLIB_1.2.2 {
+    adler32_combine;
+    crc32_combine;
+    deflateSetHeader;
+    inflateGetHeader;
+} ZLIB_1.2.0.8;
+
+ZLIB_1.2.2.3 {
+    deflateTune;
+    gzdirect;
+} ZLIB_1.2.2;
+
+ZLIB_1.2.2.4 {
+    inflatePrime;
+} ZLIB_1.2.2.3;
+
+ZLIB_1.2.3.3 {
+    adler32_combine64;
+    crc32_combine64;
+    gzopen64;
+    gzseek64;
+    gztell64;
+    inflateUndermine;
+} ZLIB_1.2.2.4;
+
+ZLIB_1.2.3.4 {
+    inflateReset2;
+    inflateMark;
+} ZLIB_1.2.3.3;
+
+ZLIB_1.2.3.5 {
+    gzbuffer;
+    gzoffset;
+    gzoffset64;
+    gzclose_r;
+    gzclose_w;
+} ZLIB_1.2.3.4;
+
+ZLIB_1.2.5.1 {
+    deflatePending;
+} ZLIB_1.2.3.5;
+
+ZLIB_1.2.5.2 {
+    deflateResetKeep;
+    gzflags;
+    gzgetc_;
+    inflateResetKeep;
+} ZLIB_1.2.5.1;
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.pc.in b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib.pc.in
new file mode 100644 (file)
index 0000000..7e5acf9
--- /dev/null
@@ -0,0 +1,13 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+sharedlibdir=@sharedlibdir@
+includedir=@includedir@
+
+Name: zlib
+Description: zlib compression library
+Version: @VERSION@
+
+Requires:
+Libs: -L${libdir} -L${sharedlibdir} -lz
+Cflags: -I${includedir}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib2ansi b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zlib2ansi
new file mode 100644 (file)
index 0000000..15e3e16
--- /dev/null
@@ -0,0 +1,152 @@
+#!/usr/bin/perl
+
+# Transform K&R C function definitions into ANSI equivalent.
+#
+# Author: Paul Marquess
+# Version: 1.0
+# Date: 3 October 2006
+
+# TODO
+#
+# Asumes no function pointer parameters. unless they are typedefed.
+# Assumes no literal strings that look like function definitions
+# Assumes functions start at the beginning of a line
+
+use strict;
+use warnings;
+
+local $/;
+$_ = <>;
+
+my $sp = qr{ \s* (?: /\* .*? \*/ )? \s* }x; # assume no nested comments
+
+my $d1    = qr{ $sp (?: [\w\*\s]+ $sp)* $sp \w+ $sp [\[\]\s]* $sp }x ;
+my $decl  = qr{ $sp (?: \w+ $sp )+ $d1 }xo ;
+my $dList = qr{ $sp $decl (?: $sp , $d1 )* $sp ; $sp }xo ;
+
+
+while (s/^
+            (                  # Start $1
+                (              #   Start $2
+                    .*?        #     Minimal eat content
+                    ( ^ \w [\w\s\*]+ )    #     $3 -- function name
+                    \s*        #     optional whitespace
+                )              # $2 - Matched up to before parameter list
+
+                \( \s*         # Literal "(" + optional whitespace
+                ( [^\)]+ )     # $4 - one or more anythings except ")"
+                \s* \)         # optional whitespace surrounding a Literal ")"
+
+                ( (?: $dList )+ ) # $5
+
+                $sp ^ {        # literal "{" at start of line
+            )                  # Remember to $1
+        //xsom
+      )
+{
+    my $all = $1 ;
+    my $prefix = $2;
+    my $param_list = $4 ;
+    my $params = $5;
+
+    StripComments($params);
+    StripComments($param_list);
+    $param_list =~ s/^\s+//;
+    $param_list =~ s/\s+$//;
+
+    my $i = 0 ;
+    my %pList = map { $_ => $i++ }
+                split /\s*,\s*/, $param_list;
+    my $pMatch = '(\b' . join('|', keys %pList) . '\b)\W*$' ;
+
+    my @params = split /\s*;\s*/, $params;
+    my @outParams = ();
+    foreach my $p (@params)
+    {
+        if ($p =~ /,/)
+        {
+            my @bits = split /\s*,\s*/, $p;
+            my $first = shift @bits;
+            $first =~ s/^\s*//;
+            push @outParams, $first;
+            $first =~ /^(\w+\s*)/;
+            my $type = $1 ;
+            push @outParams, map { $type . $_ } @bits;
+        }
+        else
+        {
+            $p =~ s/^\s+//;
+            push @outParams, $p;
+        }
+    }
+
+
+    my %tmp = map { /$pMatch/;  $_ => $pList{$1}  }
+              @outParams ;
+
+    @outParams = map  { "    $_" }
+                 sort { $tmp{$a} <=> $tmp{$b} }
+                 @outParams ;
+
+    print $prefix ;
+    print "(\n" . join(",\n", @outParams) . ")\n";
+    print "{" ;
+
+}
+
+# Output any trailing code.
+print ;
+exit 0;
+
+
+sub StripComments
+{
+
+  no warnings;
+
+  # Strip C & C++ coments
+  # From the perlfaq
+  $_[0] =~
+
+    s{
+       /\*         ##  Start of /* ... */ comment
+       [^*]*\*+    ##  Non-* followed by 1-or-more *'s
+       (
+         [^/*][^*]*\*+
+       )*          ##  0-or-more things which don't start with /
+                   ##    but do end with '*'
+       /           ##  End of /* ... */ comment
+
+     |         ##     OR  C++ Comment
+       //          ## Start of C++ comment //
+       [^\n]*      ## followed by 0-or-more non end of line characters
+
+     |         ##     OR  various things which aren't comments:
+
+       (
+         "           ##  Start of " ... " string
+         (
+           \\.           ##  Escaped char
+         |               ##    OR
+           [^"\\]        ##  Non "\
+         )*
+         "           ##  End of " ... " string
+
+       |         ##     OR
+
+         '           ##  Start of ' ... ' string
+         (
+           \\.           ##  Escaped char
+         |               ##    OR
+           [^'\\]        ##  Non '\
+         )*
+         '           ##  End of ' ... ' string
+
+       |         ##     OR
+
+         .           ##  Anything other char
+         [^/"'\\]*   ##  Chars which doesn't start a comment, string or escape
+       )
+     }{$2}gxs;
+
+}
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zutil.c b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zutil.c
new file mode 100644 (file)
index 0000000..8a1d242
--- /dev/null
@@ -0,0 +1,301 @@
+/* zutil.c -- target dependent utility functions for the compression library
+ * Copyright (C) 1995-2005, 2010, 2011 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#include "zutil.h"
+
+#ifndef NO_DUMMY_DECL
+struct internal_state      {int dummy;}; /* for buggy compilers */
+#endif
+
+const char * const z_errmsg[10] = {
+"need dictionary",     /* Z_NEED_DICT       2  */
+"stream end",          /* Z_STREAM_END      1  */
+"",                    /* Z_OK              0  */
+"file error",          /* Z_ERRNO         (-1) */
+"stream error",        /* Z_STREAM_ERROR  (-2) */
+"data error",          /* Z_DATA_ERROR    (-3) */
+"insufficient memory", /* Z_MEM_ERROR     (-4) */
+"buffer error",        /* Z_BUF_ERROR     (-5) */
+"incompatible version",/* Z_VERSION_ERROR (-6) */
+""};
+
+
+const char * ZEXPORT zlibVersion()
+{
+    return ZLIB_VERSION;
+}
+
+uLong ZEXPORT zlibCompileFlags()
+{
+    uLong flags;
+
+    flags = 0;
+    switch ((int)(sizeof(uInt))) {
+    case 2:     break;
+    case 4:     flags += 1;     break;
+    case 8:     flags += 2;     break;
+    default:    flags += 3;
+    }
+    switch ((int)(sizeof(uLong))) {
+    case 2:     break;
+    case 4:     flags += 1 << 2;        break;
+    case 8:     flags += 2 << 2;        break;
+    default:    flags += 3 << 2;
+    }
+    switch ((int)(sizeof(voidpf))) {
+    case 2:     break;
+    case 4:     flags += 1 << 4;        break;
+    case 8:     flags += 2 << 4;        break;
+    default:    flags += 3 << 4;
+    }
+    switch ((int)(sizeof(z_off_t))) {
+    case 2:     break;
+    case 4:     flags += 1 << 6;        break;
+    case 8:     flags += 2 << 6;        break;
+    default:    flags += 3 << 6;
+    }
+#ifdef DEBUG
+    flags += 1 << 8;
+#endif
+#if defined(ASMV) || defined(ASMINF)
+    flags += 1 << 9;
+#endif
+#ifdef ZLIB_WINAPI
+    flags += 1 << 10;
+#endif
+#ifdef BUILDFIXED
+    flags += 1 << 12;
+#endif
+#ifdef DYNAMIC_CRC_TABLE
+    flags += 1 << 13;
+#endif
+#ifdef NO_GZCOMPRESS
+    flags += 1L << 16;
+#endif
+#ifdef NO_GZIP
+    flags += 1L << 17;
+#endif
+#ifdef PKZIP_BUG_WORKAROUND
+    flags += 1L << 20;
+#endif
+#ifdef FASTEST
+    flags += 1L << 21;
+#endif
+#ifdef Z_SOLO
+    return flags;
+#else
+    return flags + gzflags();
+#endif
+}
+
+#ifdef DEBUG
+
+#  ifndef verbose
+#    define verbose 0
+#  endif
+int ZLIB_INTERNAL z_verbose = verbose;
+
+void ZLIB_INTERNAL z_error (m)
+    char *m;
+{
+    fprintf(stderr, "%s\n", m);
+    exit(1);
+}
+#endif
+
+/* exported to allow conversion of error code to string for compress() and
+ * uncompress()
+ */
+const char * ZEXPORT zError(err)
+    int err;
+{
+    return ERR_MSG(err);
+}
+
+#if defined(_WIN32_WCE)
+    /* The Microsoft C Run-Time Library for Windows CE doesn't have
+     * errno.  We define it as a global variable to simplify porting.
+     * Its value is always 0 and should not be used.
+     */
+    int errno = 0;
+#endif
+
+#ifndef HAVE_MEMCPY
+
+void ZLIB_INTERNAL zmemcpy(dest, source, len)
+    Bytef* dest;
+    const Bytef* source;
+    uInt  len;
+{
+    if (len == 0) return;
+    do {
+        *dest++ = *source++; /* ??? to be unrolled */
+    } while (--len != 0);
+}
+
+int ZLIB_INTERNAL zmemcmp(s1, s2, len)
+    const Bytef* s1;
+    const Bytef* s2;
+    uInt  len;
+{
+    uInt j;
+
+    for (j = 0; j < len; j++) {
+        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
+    }
+    return 0;
+}
+
+void ZLIB_INTERNAL zmemzero(dest, len)
+    Bytef* dest;
+    uInt  len;
+{
+    if (len == 0) return;
+    do {
+        *dest++ = 0;  /* ??? to be unrolled */
+    } while (--len != 0);
+}
+#endif
+
+#ifndef Z_SOLO
+
+#ifdef SYS16BIT
+
+#ifdef __TURBOC__
+/* Turbo C in 16-bit mode */
+
+#  define MY_ZCALLOC
+
+/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
+ * and farmalloc(64K) returns a pointer with an offset of 8, so we
+ * must fix the pointer. Warning: the pointer must be put back to its
+ * original form in order to free it, use zcfree().
+ */
+
+#define MAX_PTR 10
+/* 10*64K = 640K */
+
+local int next_ptr = 0;
+
+typedef struct ptr_table_s {
+    voidpf org_ptr;
+    voidpf new_ptr;
+} ptr_table;
+
+local ptr_table table[MAX_PTR];
+/* This table is used to remember the original form of pointers
+ * to large buffers (64K). Such pointers are normalized with a zero offset.
+ * Since MSDOS is not a preemptive multitasking OS, this table is not
+ * protected from concurrent access. This hack doesn't work anyway on
+ * a protected system like OS/2. Use Microsoft C instead.
+ */
+
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)
+{
+    voidpf buf = opaque; /* just to make some compilers happy */
+    ulg bsize = (ulg)items*size;
+
+    /* If we allocate less than 65520 bytes, we assume that farmalloc
+     * will return a usable pointer which doesn't have to be normalized.
+     */
+    if (bsize < 65520L) {
+        buf = farmalloc(bsize);
+        if (*(ush*)&buf != 0) return buf;
+    } else {
+        buf = farmalloc(bsize + 16L);
+    }
+    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
+    table[next_ptr].org_ptr = buf;
+
+    /* Normalize the pointer to seg:0 */
+    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
+    *(ush*)&buf = 0;
+    table[next_ptr++].new_ptr = buf;
+    return buf;
+}
+
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
+{
+    int n;
+    if (*(ush*)&ptr != 0) { /* object < 64K */
+        farfree(ptr);
+        return;
+    }
+    /* Find the original pointer */
+    for (n = 0; n < next_ptr; n++) {
+        if (ptr != table[n].new_ptr) continue;
+
+        farfree(table[n].org_ptr);
+        while (++n < next_ptr) {
+            table[n-1] = table[n];
+        }
+        next_ptr--;
+        return;
+    }
+    ptr = opaque; /* just to make some compilers happy */
+    Assert(0, "zcfree: ptr not found");
+}
+
+#endif /* __TURBOC__ */
+
+
+#ifdef M_I86
+/* Microsoft C in 16-bit mode */
+
+#  define MY_ZCALLOC
+
+#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
+#  define _halloc  halloc
+#  define _hfree   hfree
+#endif
+
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)
+{
+    if (opaque) opaque = 0; /* to make compiler happy */
+    return _halloc((long)items, size);
+}
+
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
+{
+    if (opaque) opaque = 0; /* to make compiler happy */
+    _hfree(ptr);
+}
+
+#endif /* M_I86 */
+
+#endif /* SYS16BIT */
+
+
+#ifndef MY_ZCALLOC /* Any system without a special alloc function */
+
+#ifndef STDC
+extern voidp  malloc OF((uInt size));
+extern voidp  calloc OF((uInt items, uInt size));
+extern void   free   OF((voidpf ptr));
+#endif
+
+voidpf ZLIB_INTERNAL zcalloc (opaque, items, size)
+    voidpf opaque;
+    unsigned items;
+    unsigned size;
+{
+    if (opaque) items += size - size; /* make compiler happy */
+    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
+                              (voidpf)calloc(items, size);
+}
+
+void ZLIB_INTERNAL zcfree (opaque, ptr)
+    voidpf opaque;
+    voidpf ptr;
+{
+    free(ptr);
+    if (opaque) return; /* make compiler happy */
+}
+
+#endif /* MY_ZCALLOC */
+
+#endif /* !Z_SOLO */
diff --git a/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zutil.h b/1.8/org.simantics.fmu/FMUSolution/zlib-1.2.6/zutil.h
new file mode 100644 (file)
index 0000000..dff1112
--- /dev/null
@@ -0,0 +1,248 @@
+/* zutil.h -- internal interface and configuration of the compression library
+ * Copyright (C) 1995-2011 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZUTIL_H
+#define ZUTIL_H
+
+#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ)
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
+#include "zlib.h"
+
+#if defined(STDC) && !defined(Z_SOLO)
+#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
+#    include <stddef.h>
+#  endif
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+
+#ifdef Z_SOLO
+   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */
+#endif
+
+#ifndef local
+#  define local static
+#endif
+/* compile with -Dlocal if your debugger can't find static symbols */
+
+typedef unsigned char  uch;
+typedef uch FAR uchf;
+typedef unsigned short ush;
+typedef ush FAR ushf;
+typedef unsigned long  ulg;
+
+extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
+/* (size given to avoid silly warnings with Visual C++) */
+
+#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
+
+#define ERR_RETURN(strm,err) \
+  return (strm->msg = (char*)ERR_MSG(err), (err))
+/* To be used only when the state is known to be valid */
+
+        /* common constants */
+
+#ifndef DEF_WBITS
+#  define DEF_WBITS MAX_WBITS
+#endif
+/* default windowBits for decompression. MAX_WBITS is for compression only */
+
+#if MAX_MEM_LEVEL >= 8
+#  define DEF_MEM_LEVEL 8
+#else
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#endif
+/* default memLevel */
+
+#define STORED_BLOCK 0
+#define STATIC_TREES 1
+#define DYN_TREES    2
+/* The three kinds of block type */
+
+#define MIN_MATCH  3
+#define MAX_MATCH  258
+/* The minimum and maximum match lengths */
+
+#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
+
+        /* target dependencies */
+
+#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
+#  define OS_CODE  0x00
+#  ifndef Z_SOLO
+#    if defined(__TURBOC__) || defined(__BORLANDC__)
+#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
+         /* Allow compilation with ANSI keywords only enabled */
+         void _Cdecl farfree( void *block );
+         void *_Cdecl farmalloc( unsigned long nbytes );
+#      else
+#        include <alloc.h>
+#      endif
+#    else /* MSC or DJGPP */
+#      include <malloc.h>
+#    endif
+#  endif
+#endif
+
+#ifdef AMIGA
+#  define OS_CODE  0x01
+#endif
+
+#if defined(VAXC) || defined(VMS)
+#  define OS_CODE  0x02
+#  define F_OPEN(name, mode) \
+     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
+#endif
+
+#if defined(ATARI) || defined(atarist)
+#  define OS_CODE  0x05
+#endif
+
+#ifdef OS2
+#  define OS_CODE  0x06
+#  if defined(M_I86) && !defined(Z_SOLO)
+#    include <malloc.h>
+#  endif
+#endif
+
+#if defined(MACOS) || defined(TARGET_OS_MAC)
+#  define OS_CODE  0x07
+#  ifndef Z_SOLO
+#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
+#      include <unix.h> /* for fdopen */
+#    else
+#      ifndef fdopen
+#        define fdopen(fd,mode) NULL /* No fdopen() */
+#      endif
+#    endif
+#  endif
+#endif
+
+#ifdef TOPS20
+#  define OS_CODE  0x0a
+#endif
+
+#ifdef WIN32
+#  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */
+#    define OS_CODE  0x0b
+#  endif
+#endif
+
+#ifdef __50SERIES /* Prime/PRIMOS */
+#  define OS_CODE  0x0f
+#endif
+
+#if defined(_BEOS_) || defined(RISCOS)
+#  define fdopen(fd,mode) NULL /* No fdopen() */
+#endif
+
+#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
+#  if defined(_WIN32_WCE)
+#    define fdopen(fd,mode) NULL /* No fdopen() */
+#    ifndef _PTRDIFF_T_DEFINED
+       typedef int ptrdiff_t;
+#      define _PTRDIFF_T_DEFINED
+#    endif
+#  else
+#    define fdopen(fd,type)  _fdopen(fd,type)
+#  endif
+#endif
+
+#if defined(__BORLANDC__) && !defined(MSDOS)
+  #pragma warn -8004
+  #pragma warn -8008
+  #pragma warn -8066
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_WIN32) && (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
+    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#endif
+
+        /* common defaults */
+
+#ifndef OS_CODE
+#  define OS_CODE  0x03  /* assume Unix */
+#endif
+
+#ifndef F_OPEN
+#  define F_OPEN(name, mode) fopen((name), (mode))
+#endif
+
+         /* functions */
+
+#if defined(pyr) || defined(Z_SOLO)
+#  define NO_MEMCPY
+#endif
+#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
+ /* Use our own functions for small and medium model with MSC <= 5.0.
+  * You may have to use the same strategy for Borland C (untested).
+  * The __SC__ check is for Symantec.
+  */
+#  define NO_MEMCPY
+#endif
+#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
+#  define HAVE_MEMCPY
+#endif
+#ifdef HAVE_MEMCPY
+#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */
+#    define zmemcpy _fmemcpy
+#    define zmemcmp _fmemcmp
+#    define zmemzero(dest, len) _fmemset(dest, 0, len)
+#  else
+#    define zmemcpy memcpy
+#    define zmemcmp memcmp
+#    define zmemzero(dest, len) memset(dest, 0, len)
+#  endif
+#else
+   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
+   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
+   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
+#endif
+
+/* Diagnostic functions */
+#ifdef DEBUG
+#  include <stdio.h>
+   extern int ZLIB_INTERNAL z_verbose;
+   extern void ZLIB_INTERNAL z_error OF((char *m));
+#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
+#  define Trace(x) {if (z_verbose>=0) fprintf x ;}
+#  define Tracev(x) {if (z_verbose>0) fprintf x ;}
+#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}
+#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
+#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
+#else
+#  define Assert(cond,msg)
+#  define Trace(x)
+#  define Tracev(x)
+#  define Tracevv(x)
+#  define Tracec(c,x)
+#  define Tracecv(c,x)
+#endif
+
+#ifndef Z_SOLO
+   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
+                                    unsigned size));
+   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
+#endif
+
+#define ZALLOC(strm, items, size) \
+           (*((strm)->zalloc))((strm)->opaque, (items), (size))
+#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
+#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
+
+#endif /* ZUTIL_H */
diff --git a/1.8/org.simantics.fmu/META-INF/MANIFEST.MF b/1.8/org.simantics.fmu/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..21efdee
--- /dev/null
@@ -0,0 +1,13 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: FMU Simulator
+Bundle-SymbolicName: org.simantics.fmu
+Bundle-Version: 1.1.0.qualifier
+Bundle-Activator: org.simantics.fmu.Activator
+Bundle-Vendor: Semantum Oy
+Require-Bundle: org.eclipse.core.runtime,
+ org.simantics.utils;bundle-version="1.1.0",
+ org.simantics;bundle-version="1.0.0"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-ActivationPolicy: lazy
+Export-Package: org.simantics.fmu
diff --git a/1.8/org.simantics.fmu/build.properties b/1.8/org.simantics.fmu/build.properties
new file mode 100644 (file)
index 0000000..41eb6ad
--- /dev/null
@@ -0,0 +1,4 @@
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .\r
diff --git a/1.8/org.simantics.fmu/src/org/simantics/fmu/Activator.java b/1.8/org.simantics.fmu/src/org/simantics/fmu/Activator.java
new file mode 100644 (file)
index 0000000..d93e3c5
--- /dev/null
@@ -0,0 +1,30 @@
+package org.simantics.fmu;\r
+\r
+import org.osgi.framework.BundleActivator;\r
+import org.osgi.framework.BundleContext;\r
+\r
+public class Activator implements BundleActivator {\r
+\r
+       private static BundleContext context;\r
+\r
+       static BundleContext getContext() {\r
+               return context;\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)\r
+        */\r
+       public void start(BundleContext bundleContext) throws Exception {\r
+               Activator.context = bundleContext;\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)\r
+        */\r
+       public void stop(BundleContext bundleContext) throws Exception {\r
+               Activator.context = null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.fmu/src/org/simantics/fmu/FMUControlJNI.java b/1.8/org.simantics.fmu/src/org/simantics/fmu/FMUControlJNI.java
new file mode 100644 (file)
index 0000000..0ea50c2
--- /dev/null
@@ -0,0 +1,688 @@
+package org.simantics.fmu;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.io.RandomAccessFile;\r
+import java.nio.channels.FileChannel;\r
+import java.nio.channels.FileLock;\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.runtime.FileLocator;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.osgi.framework.Bundle;\r
+import org.simantics.Simantics;\r
+import org.simantics.utils.FileUtils;\r
+\r
+\r
+public class FMUControlJNI {\r
+\r
+    /**\r
+     * Static variables\r
+     */\r
+    private static int      ERROR               = 0;\r
+    private static int      OK                  = 1;\r
+    private static String   UNSATISFIED_LINK    = "Method not found. DLL might not be loaded properly.";    \r
+    private static String   TEMP_FMU_DIRECTORY_NAME = "fmu";    \r
+    public static String    TEMP_FMU_COMMON_DIRECTORY;  \r
+    public static String    LOCK_FILE_NAME      = "fmu.lock";\r
+\r
+    public static Object syncObject = new Object();\r
+\r
+    /**\r
+     * Static: load native libraries required for the FMU simulation to work.\r
+     */\r
+    static {\r
+        File[] libraries = new File[3];\r
+\r
+        Bundle bundle = Platform.getBundle("org.simantics.fmu.me.win32");\r
+\r
+        if (bundle != null) {\r
+            try{\r
+                String root = FileLocator.getBundleFile(bundle).getAbsolutePath();\r
+                libraries[0] = new File(root, "libraries/zlibwapi.dll");\r
+                libraries[1] = new File(root, "libraries/miniunz.dll");\r
+                libraries[2] = new File(root, "libraries/FMUSimulator.dll");\r
+            }\r
+            catch (Exception e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+\r
+        for(File library : libraries) {\r
+            if(library == null) {\r
+                System.err.println("FMU library not loaded. FMU simulation not working.");\r
+                continue;\r
+            } else if(!library.isFile()) {\r
+                System.err.println(library.getAbsolutePath() + " not found");\r
+            } else {\r
+                try {\r
+                    System.load(library.getAbsolutePath());\r
+                } catch (Throwable t) {\r
+                    System.err.println(t.getMessage());\r
+                }\r
+            } \r
+        }\r
+    }\r
+\r
+    /**\r
+     * Static: initialize fmu temp folder\r
+     */\r
+    static {\r
+        File dir = Simantics.getTemporaryDirectory(TEMP_FMU_DIRECTORY_NAME);\r
+        TEMP_FMU_COMMON_DIRECTORY = dir.getAbsolutePath(); \r
+    }\r
+\r
+\r
+    private String fmuDir;\r
+\r
+    public String TEMP_FOLDER_1;\r
+    public String TEMP_FOLDER_2;\r
+    public String TEMP_FMU_DIRECTORY;\r
+    private String dirName;\r
+\r
+    public FMUControlJNI() {\r
+        // Create a directory for this control\r
+        File tempDir = new File(TEMP_FMU_COMMON_DIRECTORY, UUID.randomUUID().toString());\r
+        tempDir.mkdir();\r
+        TEMP_FMU_DIRECTORY = tempDir.getAbsolutePath();\r
+\r
+        // Create two directories inside the temp directory for this control\r
+        dirName = UUID.randomUUID().toString();\r
+        File fmuDir = new File(TEMP_FMU_DIRECTORY, dirName);\r
+        fmuDir.mkdir();\r
+\r
+        TEMP_FOLDER_1 = fmuDir.toString();\r
+        TEMP_FOLDER_2 = fmuDir.toString() + "_2";\r
+\r
+        // Lock fmu directory in temp directory\r
+        lockFMUDirectory();\r
+    }\r
+\r
+    public String getModelID() {\r
+        return dirName;\r
+    }\r
+\r
+    public String getFmuDir() {\r
+        return fmuDir;\r
+    }\r
+\r
+    /**\r
+     * Load fmu from a given file path. Releases the (possible) previously\r
+     * loaded fmu.\r
+     * \r
+     * @param path absolute file path for fmu file\r
+     * @throws FMUJNIException\r
+     */\r
+    private int fmuN = 0;\r
+    private boolean fmuLoaded = false;\r
+    public void loadFMUFile(String path) throws FMUJNIException {\r
+\r
+        synchronized(syncObject) {\r
+\r
+            if(fmuN % 2 == 0) {\r
+                fmuDir = TEMP_FOLDER_1;\r
+                fmuN++;\r
+            } else {\r
+                fmuDir = TEMP_FOLDER_2;\r
+                fmuN = 0;\r
+            }\r
+\r
+            File tempDir = new File(fmuDir);\r
+            if(tempDir.isDirectory()) {\r
+                try {\r
+                    FileUtils.deleteAll(tempDir);\r
+                } catch (IOException e) {\r
+                    throw new FMUJNIException("Could not create temp folder for fmu");\r
+                }\r
+                tempDir.mkdir();\r
+            } else {\r
+                tempDir.mkdir();\r
+            }\r
+\r
+\r
+            try {\r
+                String tmpPath = tempDir.getAbsolutePath();\r
+                if(!tmpPath.endsWith("\\"))\r
+                    tmpPath = tmpPath + "\\";\r
+                int ret = loadFMUFile_(getModelID(), path, tmpPath);\r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+                fmuLoaded = true;\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native int loadFMUFile_(String id, String path, String toDir);\r
+\r
+    /**\r
+     * Set a step length for simulation\r
+     * \r
+     * @param step Step length for simulation\r
+     * @throws FMUJNIException\r
+     */\r
+    public void setStepLength(double step) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = setStepLength_(getModelID(), step);\r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native int setStepLength_(String id, double step);\r
+\r
+    /**\r
+     * Instantiates a simulation. \r
+     * <p>\r
+     * Make sure that an FMU is loaded first.\r
+     * @throws FMUJNIException\r
+     */\r
+    public void instantiateSimulation() throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = instantiateSimulation_(getModelID()); \r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native int instantiateSimulation_(String id);\r
+\r
+    \r
+    /**\r
+     * Initializes a simulation. \r
+     * <p>\r
+     * Make sure that simulation is instantiated first!\r
+     * @throws FMUJNIException\r
+     */\r
+    public void initializeSimulation() throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = initializeSimulation_(getModelID()); \r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native int initializeSimulation_(String id);\r
+\r
+    /**\r
+     * Subscribe a set of variables from a loaded simulation.\r
+     * <p>\r
+     * Make sure that an FMU is loaded first.\r
+     * @param variables Array of variables\r
+     * @throws FMUJNIException\r
+     */\r
+    public void subscribe(String[] variables) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = subscribe_(getModelID(), variables, variables.length); \r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native int subscribe_(String id, String[] variables, int size);\r
+\r
+\r
+    /**\r
+     * Set a new (Real, double) value for a variable. If the variable is a \r
+     * parameter, the change is effective immediately.\r
+     *  \r
+     * @param name Variable\r
+     * @param value New (Real, double) value\r
+     * @throws FMUJNIException\r
+     */\r
+    public void setRealValue(String name, double value) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = setRealValue_(getModelID(), name, value); \r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native int setRealValue_(String id, String name, double value);\r
+\r
+    /**\r
+     * Set a new (integer) value for a variable. If the variable is a \r
+     * parameter, the change is effective immediately.\r
+     *  \r
+     * @param name Variable\r
+     * @param value New (integer) value\r
+     * @throws FMUJNIException\r
+     */\r
+    public void setIntegerValue(String name, int value) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = setIntegerValue_(getModelID(), name, value); \r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+    private native int setIntegerValue_(String id, String name, int value);\r
+\r
+    /**\r
+     * Set a new (boolean) value for a variable. If the variable is a \r
+     * parameter, the change is effective immediately.\r
+     *  \r
+     * @param name Variable\r
+     * @param value New (boolean) value\r
+     * @throws FMUJNIException\r
+     */\r
+    public void setBooleanValue(String name, boolean value) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = setBooleanValue_(getModelID(), name, value); \r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+    private native int setBooleanValue_(String id, String name, boolean value);\r
+\r
+    public void setTime(double time) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = setTime_(getModelID(), time); \r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+    private native int setTime_(String id, double time);\r
+\r
+    /**\r
+     * Simulate one step forward. The step length can be set with\r
+     * setStepLength()\r
+     * \r
+     * @throws FMUJNIException\r
+     */\r
+    public void simulateStep() throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                int ret = simulateStep_(getModelID()); \r
+                if(ret == ERROR)\r
+                    throw new FMUJNIException(getLastErrorMessage());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+    private native int simulateStep_(String id);\r
+\r
+    /**\r
+     * Get an array containing the current values for subscribed variables. The\r
+     * values are in the same order as in the subscription.\r
+     * \r
+     * @param results An array the size of subscribed results\r
+     * @return\r
+     */\r
+    public double[] getSubscribedResults(double[] results) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                return getSubscribedResults_(getModelID(), results);\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native double[] getSubscribedResults_(String id, double[] results);\r
+\r
+    /**\r
+     * Unload FMU and the dll:s that it requires.\r
+     * <p>\r
+     * To be called after all FMU simulations are ended. \r
+     * If the fmu is loaded again / changed, call to loadFMUFile is sufficient. loadFMUFile \r
+     * releases the previous fmu.dll  \r
+     * \r
+     * @throws FMUJNIException\r
+     */\r
+    public void unloadFMU() throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                unlockFMUDirectory();\r
+                if(fmuLoaded) {\r
+                    int ret = unloadFMU_(getModelID()); \r
+                    if(ret == ERROR)\r
+                        throw new FMUJNIException(getLastErrorMessage());\r
+                }\r
+                removeFMUDirectoryContents();\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+    private native int unloadFMU_(String id);\r
+    \r
+    /**\r
+     * Checks if fmu has been initialized\r
+     * @return current simulation time\r
+     */\r
+    public boolean isInitialized() throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+            try {\r
+                return isInitialized_(getModelID());\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native boolean isInitialized_(String id);\r
+\r
+    /**\r
+     * Get the current simulation time\r
+     * @return current simulation time\r
+     */\r
+    public double getTime() throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                return getTime_(getModelID());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native double getTime_(String id);\r
+\r
+    /**\r
+     * Get all variables in a loaded model\r
+     * @return all variables in a loaded model\r
+     */\r
+    public String[] getAllVariables() throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                return getAllVariables_(getModelID());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native String[] getAllVariables_(String id);\r
+\r
+    /**\r
+     * Get all variables from model that match the filter (and time variable)\r
+     * \r
+     * @param regexp Regular expression filter\r
+     * @return An array of variable names that match regexp filter (and time-variable)\r
+     * @throws FMUJNIException\r
+     */\r
+    public String[] filterVariables(String regexp) throws FMUJNIException {       \r
+        synchronized(syncObject) {\r
+            try {\r
+\r
+                return filterVariables_(getModelID(), regexp + "|time");\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native String[] filterVariables_(String id, String regexp);\r
+\r
+    /**\r
+     * Get the last error message\r
+     * @return Last error message\r
+     */\r
+    public String getLastErrorMessage() throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+\r
+                return getLastErrorMessage_(getModelID());\r
+\r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native String getLastErrorMessage_(String id);\r
+\r
+    /**\r
+     * Get a real (double) value for variable\r
+     * @param name Name of the variable\r
+     * @return value\r
+     * @throws FMUJNIException\r
+     */\r
+    public double getRealValue(String name) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+                // TODO: printtaa id ja name, jotta saadaan virheessä kiinni \r
+                return getRealValue_(getModelID(), name); \r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native double getRealValue_(String id, String name);\r
+\r
+    /**\r
+     * Get a string value for variable\r
+     * @param name Name of the variable\r
+     * @return value\r
+     * @throws FMUJNIException\r
+     */\r
+    public String getStringValue(String name) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+                return getStringValue_(getModelID(), name); \r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native String getStringValue_(String id, String name);\r
+\r
+    /**\r
+     * Get an integer value for variable\r
+     * @param name Name of the variable\r
+     * @return value\r
+     * @throws FMUJNIException\r
+     */\r
+    public int getIntegerValue(String name) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+                return getIntegerValue_(getModelID(), name); \r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native int getIntegerValue_(String id, String name);\r
+\r
+    /**\r
+     * Get a real (double) value for variable\r
+     * @param name Name of the variable\r
+     * @return value\r
+     * @throws FMUJNIException\r
+     */\r
+    public boolean getBooleanValue(String name) throws FMUJNIException {\r
+        synchronized(syncObject) {\r
+\r
+            try {\r
+                return getBooleanValue_(getModelID(), name); \r
+            } catch (UnsatisfiedLinkError err) {\r
+                throw new FMUJNIException(UNSATISFIED_LINK);\r
+            } catch (Exception e) {\r
+                throw new FMUJNIException(e.getMessage());\r
+            }\r
+        }\r
+    }\r
+\r
+    private native boolean getBooleanValue_(String id, String name);\r
+\r
+    private FileChannel channel; \r
+    private FileLock lock;\r
+\r
+    @SuppressWarnings("resource")\r
+    private boolean lockFMUDirectory() {\r
+\r
+        try {\r
+            // Get a file channel for the lock file\r
+            File lockFile = new File(TEMP_FMU_DIRECTORY, LOCK_FILE_NAME);\r
+            if(!lockFile.isFile())\r
+                lockFile.createNewFile();\r
+\r
+            channel = new RandomAccessFile(lockFile, "rw").getChannel();\r
+\r
+            // Use the file channel to create a lock on the file.\r
+            // This method blocks until it can retrieve the lock.\r
+            lock = channel.lock();\r
+\r
+            //          // Try acquiring the lock without blocking. This method returns\r
+            //          // null or throws an exception if the file is already locked.\r
+            //          try {\r
+            //              lock = channel.tryLock();\r
+            //          } catch (OverlappingFileLockException e) {\r
+            //              // File is already locked in this thread or virtual machine\r
+            //          }\r
+        } catch (IOException e) {\r
+            return false;\r
+        }\r
+\r
+        return true;\r
+    }\r
+\r
+    private boolean unlockFMUDirectory() {\r
+        try {\r
+            // Release the lock\r
+            if(lock != null)\r
+                lock.release();\r
+\r
+            // Close the file\r
+            if(channel != null)\r
+                channel.close();\r
+        } catch (IOException e) {\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
+\r
+    private boolean removeFMUDirectoryContents() {\r
+        // Remove contents\r
+        try {\r
+            File tempDir = new File(TEMP_FMU_DIRECTORY);\r
+            FileUtils.deleteAll(tempDir);\r
+            tempDir.delete();\r
+        } catch (IOException e) {\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.fmu/src/org/simantics/fmu/FMUJNIException.java b/1.8/org.simantics.fmu/src/org/simantics/fmu/FMUJNIException.java
new file mode 100644 (file)
index 0000000..b781bd9
--- /dev/null
@@ -0,0 +1,14 @@
+package org.simantics.fmu;\r
+\r
+/**\r
+ * Exception thrown when native fmu calls fail\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FMUJNIException extends Exception {\r
+    private static final long serialVersionUID = -7164064752664568008L;\r
+\r
+    public FMUJNIException(String message) {\r
+        super(message);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.fmu/src/org_simantics_fmu_FMUControlJNI.h b/1.8/org.simantics.fmu/src/org_simantics_fmu_FMUControlJNI.h
new file mode 100644 (file)
index 0000000..2059987
--- /dev/null
@@ -0,0 +1,181 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */\r
+#include <jni.h>\r
+/* Header for class org_simantics_fmu_FMUControlJNI */\r
+\r
+#ifndef _Included_org_simantics_fmu_FMUControlJNI\r
+#define _Included_org_simantics_fmu_FMUControlJNI\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    loadFMUFile_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_loadFMUFile_1\r
+  (JNIEnv *, jobject, jstring, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setStepLength_\r
+ * Signature: (Ljava/lang/String;D)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setStepLength_1\r
+  (JNIEnv *, jobject, jstring, jdouble);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    instantiateSimulation_\r
+ * Signature: (Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_instantiateSimulation_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    initializeSimulation_\r
+ * Signature: (Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_initializeSimulation_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    subscribe_\r
+ * Signature: (Ljava/lang/String;[Ljava/lang/String;I)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_subscribe_1\r
+  (JNIEnv *, jobject, jstring, jobjectArray, jint);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setRealValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;D)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setRealValue_1\r
+  (JNIEnv *, jobject, jstring, jstring, jdouble);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setIntegerValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;I)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setIntegerValue_1\r
+  (JNIEnv *, jobject, jstring, jstring, jint);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setBooleanValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;Z)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setBooleanValue_1\r
+  (JNIEnv *, jobject, jstring, jstring, jboolean);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    setTime_\r
+ * Signature: (Ljava/lang/String;D)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_setTime_1\r
+  (JNIEnv *, jobject, jstring, jdouble);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    simulateStep_\r
+ * Signature: (Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_simulateStep_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getSubscribedResults_\r
+ * Signature: (Ljava/lang/String;[D)[D\r
+ */\r
+JNIEXPORT jdoubleArray JNICALL Java_org_simantics_fmu_FMUControlJNI_getSubscribedResults_1\r
+  (JNIEnv *, jobject, jstring, jdoubleArray);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    unloadFMU_\r
+ * Signature: (Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_unloadFMU_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    isInitialized_\r
+ * Signature: (Ljava/lang/String;)Z\r
+ */\r
+JNIEXPORT jboolean JNICALL Java_org_simantics_fmu_FMUControlJNI_isInitialized_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getTime_\r
+ * Signature: (Ljava/lang/String;)D\r
+ */\r
+JNIEXPORT jdouble JNICALL Java_org_simantics_fmu_FMUControlJNI_getTime_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getAllVariables_\r
+ * Signature: (Ljava/lang/String;)[Ljava/lang/String;\r
+ */\r
+JNIEXPORT jobjectArray JNICALL Java_org_simantics_fmu_FMUControlJNI_getAllVariables_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    filterVariables_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;\r
+ */\r
+JNIEXPORT jobjectArray JNICALL Java_org_simantics_fmu_FMUControlJNI_filterVariables_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getLastErrorMessage_\r
+ * Signature: (Ljava/lang/String;)Ljava/lang/String;\r
+ */\r
+JNIEXPORT jstring JNICALL Java_org_simantics_fmu_FMUControlJNI_getLastErrorMessage_1\r
+  (JNIEnv *, jobject, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getRealValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)D\r
+ */\r
+JNIEXPORT jdouble JNICALL Java_org_simantics_fmu_FMUControlJNI_getRealValue_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getStringValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;\r
+ */\r
+JNIEXPORT jstring JNICALL Java_org_simantics_fmu_FMUControlJNI_getStringValue_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getIntegerValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_simantics_fmu_FMUControlJNI_getIntegerValue_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+/*\r
+ * Class:     org_simantics_fmu_FMUControlJNI\r
+ * Method:    getBooleanValue_\r
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)Z\r
+ */\r
+JNIEXPORT jboolean JNICALL Java_org_simantics_fmu_FMUControlJNI_getBooleanValue_1\r
+  (JNIEnv *, jobject, jstring, jstring);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/1.8/org.simantics.h2d/.classpath b/1.8/org.simantics.h2d/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.h2d/.hgignore b/1.8/org.simantics.h2d/.hgignore
new file mode 100644 (file)
index 0000000..73df90f
--- /dev/null
@@ -0,0 +1,5 @@
+syntax: regexp\r
+^bin/\r
+\r
+syntax: glob\r
+*.svn/*
\ No newline at end of file
diff --git a/1.8/org.simantics.h2d/.project b/1.8/org.simantics.h2d/.project
new file mode 100644 (file)
index 0000000..e91c226
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.h2d</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.h2d/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.h2d/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..aa42399
--- /dev/null
@@ -0,0 +1,8 @@
+#Sun Nov 08 17:02:25 EET 2009\r
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.h2d/META-INF/MANIFEST.MF b/1.8/org.simantics.h2d/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..4dbd46e
--- /dev/null
@@ -0,0 +1,19 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: H2d
+Bundle-SymbolicName: org.simantics.h2d
+Bundle-Version: 1.0.0.qualifier
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: org.simantics.scenegraph;bundle-version="0.9.0",
+ gnu.trove2;bundle-version="2.0.4",
+ org.simantics.objmap;bundle-version="0.1.0"
+Export-Package: org.simantics.h2d.action,
+ org.simantics.h2d.canvas,
+ org.simantics.h2d.diagram,
+ org.simantics.h2d.editor,
+ org.simantics.h2d.editor.impl,
+ org.simantics.h2d.element,
+ org.simantics.h2d.element.handler,
+ org.simantics.h2d.event,
+ org.simantics.h2d.event.handler,
+ org.simantics.h2d.node
diff --git a/1.8/org.simantics.h2d/build.properties b/1.8/org.simantics.h2d/build.properties
new file mode 100644 (file)
index 0000000..efa0dd2
--- /dev/null
@@ -0,0 +1,16 @@
+###############################################################################\r
+# Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+# in Industry THTH ry.\r
+# All rights reserved. This program and the accompanying materials\r
+# are made available under the terms of the Eclipse Public License v1.0\r
+# which accompanies this distribution, and is available at\r
+# http://www.eclipse.org/legal/epl-v10.html\r
+#\r
+# Contributors:\r
+#     VTT Technical Research Centre of Finland - initial API and implementation\r
+###############################################################################\r
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .\r
+src.includes = doc/\r
diff --git a/1.8/org.simantics.h2d/doc/manual.mediawiki b/1.8/org.simantics.h2d/doc/manual.mediawiki
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/action/IAction.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/action/IAction.java
new file mode 100644 (file)
index 0000000..2e04984
--- /dev/null
@@ -0,0 +1,25 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.action;\r
+\r
+import org.simantics.h2d.event.handler.IEventHandler;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+\r
+/**\r
+ * Action is a non-instantenous user operation on diagram. \r
+ * @see org.simantics.h2d.editor.IDiagramEditor#addAction\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IAction extends IEventHandler {\r
+       void init(G2DParentNode parent);\r
+       void remove();\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/canvas/EditorCanvas.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/canvas/EditorCanvas.java
new file mode 100644 (file)
index 0000000..0d0fdab
--- /dev/null
@@ -0,0 +1,251 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.canvas;\r
+\r
+import java.awt.Canvas;\r
+import java.awt.Color;\r
+import java.awt.Dimension;\r
+import java.awt.Graphics;\r
+import java.awt.Graphics2D;\r
+import java.awt.RenderingHints;\r
+import java.awt.event.ComponentAdapter;\r
+import java.awt.event.ComponentEvent;\r
+import java.awt.event.KeyEvent;\r
+import java.awt.event.KeyListener;\r
+import java.awt.event.MouseEvent;\r
+import java.awt.event.MouseListener;\r
+import java.awt.event.MouseMotionListener;\r
+import java.awt.event.MouseWheelEvent;\r
+import java.awt.event.MouseWheelListener;\r
+import java.awt.geom.Point2D;\r
+import java.awt.image.VolatileImage;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.event.ClickEvent;\r
+import org.simantics.h2d.event.DragEvent;\r
+import org.simantics.h2d.event.DragEventPhase;\r
+import org.simantics.h2d.event.KeyboardEvent;\r
+import org.simantics.h2d.event.Modifiers;\r
+import org.simantics.h2d.event.ReleaseEvent;\r
+import org.simantics.h2d.event.WheelEvent;\r
+import org.simantics.scenegraph.g2d.G2DRenderingHints;\r
+\r
+\r
+public class EditorCanvas extends Canvas {\r
+\r
+    private static final long serialVersionUID = -387207508390377519L;\r
+\r
+    IDiagramEditor editor;\r
+       EventHandler eventHandler = new EventHandler();\r
+       //BufferedImage background;\r
+\r
+       public EditorCanvas(IDiagramEditor editor) {\r
+               this.editor = editor;\r
+               editor.setCanvas(this);\r
+               \r
+               /*G2DSceneGraph sceneGraph = editor.getSceneGraph();\r
+               addMouseListener(sceneGraph);\r
+        addMouseMotionListener(sceneGraph);\r
+        addMouseWheelListener(sceneGraph);\r
+        addKeyListener(sceneGraph);\r
+        */\r
+               addMouseListener(eventHandler);\r
+               addMouseMotionListener(eventHandler);\r
+               addMouseWheelListener(eventHandler);\r
+               addKeyListener(eventHandler);\r
+               \r
+               addComponentListener(new ComponentAdapter() {\r
+            @Override\r
+            public void componentResized(ComponentEvent e) {\r
+                repaint();\r
+            }\r
+        });\r
+               \r
+               /*try {\r
+                       background = ImageIO.read(new File("c:/paper.png"));\r
+               } catch (IOException e1) {\r
+                       // TODO Auto-generated catch block\r
+                       e1.printStackTrace();\r
+               }*/\r
+       }\r
+       \r
+    @Override\r
+    public void update(Graphics g) {\r
+        paint(g);\r
+    }\r
+       \r
+    private VolatileImage doubleBuffer;\r
+       @Override\r
+       public void paint(Graphics _g) {        \r
+        do {\r
+            if (doubleBuffer == null\r
+                    || doubleBuffer.getWidth() != getWidth()\r
+                    || doubleBuffer.getHeight() != getHeight()\r
+                    || doubleBuffer.validate(getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE)\r
+            {\r
+                doubleBuffer = createVolatileImage(getWidth(), getHeight());\r
+                editor.setViewDimensions(new Dimension(getWidth(), getHeight()));\r
+            }\r
+\r
+            Graphics2D g = (Graphics2D)doubleBuffer.getGraphics();\r
+\r
+            g.setBackground(Color.WHITE);\r
+            g.setColor(Color.WHITE);\r
+            //g.setPaint(new GradientPaint(0.f, 0.f, Color.white, 2000.f, 1600.f, Color.BLUE, false));\r
+            //g.setPaint(new TexturePaint(background, getBounds()));\r
+            g.fillRect(0, 0, doubleBuffer.getWidth(), doubleBuffer.getHeight());\r
+\r
+            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\r
+            g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);\r
+            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\r
+            g.setRenderingHint(G2DRenderingHints.KEY_CONTROL_BOUNDS, getBounds());\r
+\r
+            g.setClip(0, 0, getWidth(), getHeight());\r
+\r
+            editor.getSceneGraph().render(g);\r
+            g.dispose();\r
+        } while (doubleBuffer.contentsLost());\r
+\r
+               _g.drawImage(doubleBuffer, 0, 0, this);\r
+       }\r
+       \r
+       class EventHandler implements MouseListener, MouseMotionListener, MouseWheelListener, KeyListener {\r
+\r
+               DragEvent dragEvent;\r
+               \r
+               @Override\r
+               public void mouseClicked(MouseEvent e) {\r
+                       ClickEvent event = new ClickEvent(\r
+                                       Modifiers.modifierString(e.getButton(), e.isControlDown(), e.isAltDown(), e.isShiftDown()),\r
+                                       editor.screenToDiagram(e.getPoint()),\r
+                                       e.getLocationOnScreen()\r
+                                       );\r
+                       event.pickedElements = dragEvent.pickedElements;\r
+                       editor.handleEvent(event);\r
+               }\r
+\r
+               @Override\r
+               public void mouseEntered(MouseEvent e) {\r
+                       // TODO Auto-generated method stub\r
+                       \r
+               }\r
+\r
+               @Override\r
+               public void mouseExited(MouseEvent e) {\r
+                       // TODO Auto-generated method stub\r
+                       \r
+               }\r
+\r
+               @Override\r
+               public void mousePressed(MouseEvent e) {\r
+                       editor.getSceneGraph().mousePressed(e);\r
+                       if(e.isConsumed())\r
+                               return;\r
+                       dragEvent = new DragEvent(\r
+                                       Modifiers.modifierString(e.getButton(), e.isControlDown(), e.isAltDown(), e.isShiftDown()),\r
+                                       editor.screenToDiagram(e.getPoint())\r
+                                       );\r
+                       dragEvent.pickedElements = editor.pickElements(dragEvent.start);\r
+               }\r
+\r
+               @Override\r
+               public void mouseReleased(MouseEvent e) {\r
+                       editor.getSceneGraph().mouseReleased(e);\r
+                       if(e.isConsumed())\r
+                               return;\r
+                       if(dragEvent != null && dragEvent.phase == DragEventPhase.dragUpdate) {\r
+                               dragEvent.phase = DragEventPhase.dragEnd;\r
+                               editor.handleEvent(dragEvent);\r
+                       }                       \r
+            \r
+            if(dragEvent != null) {\r
+                ReleaseEvent event = new ReleaseEvent(\r
+                        Modifiers.modifierString(e.getButton(), e.isControlDown(), e.isAltDown(), e.isShiftDown()),\r
+                        editor.screenToDiagram(e.getPoint()),\r
+                        e.getLocationOnScreen()\r
+                        );\r
+                \r
+                event.pickedElements = dragEvent.pickedElements;\r
+                editor.handleEvent(event);\r
+            }\r
+               }\r
+\r
+               @Override\r
+               public void mouseDragged(MouseEvent e) {\r
+                       editor.getSceneGraph().mouseDragged(e);\r
+                       if(e.isConsumed())\r
+                               return;\r
+                       currentPosition = e.getPoint();\r
+                       if(dragEvent != null) { // TODO why this is needed?\r
+                       dragEvent.currentModifiers = \r
+                               Modifiers.modifierString(e.getButton(), e.isControlDown(), e.isAltDown(), e.isShiftDown());\r
+                       dragEvent.current = editor.screenToDiagram(e.getPoint());\r
+                       }\r
+                       editor.handleEvent(dragEvent);\r
+\r
+                       if(dragEvent != null && dragEvent.phase == DragEventPhase.dragBegin) {\r
+                               dragEvent.phase = DragEventPhase.dragUpdate;\r
+                               editor.handleEvent(dragEvent);\r
+                       }\r
+               }\r
+               \r
+               Point2D currentPosition = new Point2D.Double(0.0, 0.0);\r
+\r
+               @Override\r
+               public void mouseMoved(MouseEvent e) {\r
+                       currentPosition = e.getPoint();\r
+               }\r
+\r
+               @Override\r
+               public void mouseWheelMoved(MouseWheelEvent e) {\r
+                       editor.handleEvent(new WheelEvent(\r
+                                       Modifiers.modifierString(e.getButton(), e.isControlDown(), e.isAltDown(), e.isShiftDown()),\r
+                                       editor.screenToDiagram(e.getPoint()),\r
+                                       e.getWheelRotation()\r
+                                       ));\r
+               }\r
+\r
+               @Override\r
+               public void keyPressed(KeyEvent e) {\r
+                       editor.getSceneGraph().keyPressed(e);\r
+                       if(e.isConsumed())\r
+                               return;\r
+                       \r
+                       String keyText = KeyEvent.getKeyText(e.getKeyCode());\r
+                       if(e.getModifiers() != 0)\r
+                               keyText = KeyEvent.getKeyModifiersText(e.getModifiers()) \r
+                                       + "+" + keyText;\r
+                       KeyboardEvent event = new KeyboardEvent(\r
+                                       keyText,\r
+                                       editor.screenToDiagram(currentPosition)\r
+                                       );\r
+                       event.pickedElements = editor.pickElements(event.point);\r
+                       if(editor.handleEvent(event))\r
+                               e.consume();\r
+               }\r
+\r
+               @Override\r
+               public void keyReleased(KeyEvent e) {\r
+                       editor.getSceneGraph().keyReleased(e);\r
+               }\r
+\r
+               @Override\r
+               public void keyTyped(KeyEvent e) {\r
+                       editor.getSceneGraph().keyTyped(e);\r
+               } \r
+       }\r
+\r
+    public IDiagramEditor getEditor() {\r
+        return editor;\r
+    }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/Diagram.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/Diagram.java
new file mode 100644 (file)
index 0000000..673a5be
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.diagram;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.Vector;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+\r
+@GraphType("http://www.simantics.org/Sysdyn-1.0/Configuration")\r
+public class Diagram implements IDiagram {\r
+\r
+    @RelatedValue("http://www.simantics.org/Layer0-1.0/ConsistsOf")\r
+       public List<IElement> elements = new Vector<IElement>();\r
+       ArrayList<IDiagramListener> listeners = new ArrayList<IDiagramListener>();\r
+       \r
+       @Override\r
+       public void addElement(IElement element) {\r
+               elements.add(element);\r
+               for(IDiagramListener listener : listeners)\r
+                       listener.elementAdded(element);\r
+       }\r
+\r
+       @Override\r
+       public List<IElement> getElements() {\r
+               return elements;\r
+       }\r
+\r
+       @Override\r
+       public void addDiagramListener(IDiagramListener listener) {\r
+               listeners.add(listener);\r
+       }\r
+\r
+       @Override\r
+       public void removeElement(IElement element) {\r
+               elements.remove(element);\r
+               for(IDiagramListener listener : listeners)\r
+                       listener.elementRemoved(element);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/IDiagram.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/IDiagram.java
new file mode 100644 (file)
index 0000000..8263651
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.diagram;\r
+\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+/**\r
+ * Diagram is the whole that is edited in a diagram editor.\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IDiagram {\r
+       List<IElement> getElements();\r
+       void addElement(IElement element);\r
+       void removeElement(IElement element);\r
+       void addDiagramListener(IDiagramListener listener);     \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/IDiagramListener.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/diagram/IDiagramListener.java
new file mode 100644 (file)
index 0000000..9f061e0
--- /dev/null
@@ -0,0 +1,21 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.diagram;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+public interface IDiagramListener {\r
+\r
+       void elementAdded(IElement element);\r
+       void elementRemoved(IElement element);\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/IDiagramEditor.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/IDiagramEditor.java
new file mode 100644 (file)
index 0000000..987f400
--- /dev/null
@@ -0,0 +1,97 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.editor;\r
+\r
+import java.awt.Canvas;\r
+import java.awt.Dimension;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Dimension2D;\r
+import java.awt.geom.Point2D;\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.action.IAction;\r
+import org.simantics.h2d.diagram.IDiagram;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.event.IEvent;\r
+import org.simantics.h2d.event.handler.IEventHandler;\r
+import org.simantics.scenegraph.g2d.G2DSceneGraph;\r
+\r
+public interface IDiagramEditor {\r
+\r
+       IDiagram getDiagram();\r
+       \r
+       /**\r
+        * Returns the root of the scenegraph that renders the diagram.\r
+        */\r
+       G2DSceneGraph getSceneGraph();\r
+       \r
+       /**\r
+        * Handles an external event. \r
+        * @return True if the event was consumed.\r
+        */\r
+       boolean handleEvent(IEvent event);\r
+       \r
+       /** \r
+        * Returns the current view transform (from diagram coordinates to screen coordinates) defined as:\r
+        * <pre>diagramToScreen(p) = (p - offset) / scale</pre>\r
+        */\r
+       AffineTransform getViewTransform();\r
+       \r
+       /**\r
+        * Returns the current view offset. That is the diagram coordinates of the top left point of the canvas.\r
+        */\r
+       Point2D getOffset();\r
+       \r
+       /**\r
+        * Returns the current view scale. That is <pre>lengthInDiagramCoordinates / lengthInScreenCoordinates</pre>.\r
+        */\r
+       double getScale();\r
+       \r
+       /**\r
+        * Maps a point from screen coordinates to diagram coordinates.\r
+        */\r
+       Point2D screenToDiagram(Point2D point);\r
+       \r
+       /**\r
+        * Sets a new view transform. \r
+        * @param offset New offset\r
+        * @param scale New scale\r
+        *\r
+        * @see #getOffset\r
+        * @see #getScale\r
+        */\r
+       void setViewTransform(Point2D offset, double scale);\r
+       \r
+       void setViewDimensions(Dimension2D dimension);\r
+       Dimension getViewDimension();\r
+       \r
+       // Events\r
+       void addEventHandler(int priority, String eventType, IEventHandler handler);\r
+       void addEventHandler(int priority, IEventHandler handler);\r
+       \r
+       void addAction(IAction action);\r
+       void removeAction(IAction action);\r
+       \r
+       void requestRepaint();\r
+       void setCanvas(Canvas canvas);\r
+       \r
+       /**\r
+        * Returns current selection\r
+        */\r
+       ISelection getSelection();\r
+\r
+       /**\r
+        * Returns all elements at the point. Pick uses a hard coded tolerance that is calculated in screen coordinates.\r
+        */\r
+       List<IElement> pickElements(Point2D point);             \r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/ISelection.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/ISelection.java
new file mode 100644 (file)
index 0000000..f4f1426
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.editor;\r
+\r
+import java.util.Collection;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+public interface ISelection extends Iterable<IElement> {\r
+\r
+        boolean contains(IElement el);\r
+        boolean containsOneOf(Collection<IElement> els);\r
+        void clear();\r
+        void set(Collection<IElement> els);\r
+        void set(IElement el);\r
+        boolean add(IElement el);\r
+        boolean addAll(Collection<IElement> els);\r
+        boolean toggle(IElement el);\r
+        boolean remove(IElement el);\r
+        boolean isEmpty();\r
+        int size();\r
+        IElement getSingleElement();\r
+\r
+        void addSelectionListener(ISelectionListener listener);\r
+        void removeSelectionListener(ISelectionListener listener);\r
+        \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/ISelectionListener.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/ISelectionListener.java
new file mode 100644 (file)
index 0000000..3e6fe05
--- /dev/null
@@ -0,0 +1,18 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.editor;\r
+\r
+public interface ISelectionListener {\r
+\r
+    void selectionChanged(ISelection selection);\r
+    \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/DiagramEditor.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/DiagramEditor.java
new file mode 100644 (file)
index 0000000..172cf50
--- /dev/null
@@ -0,0 +1,186 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.editor.impl;\r
+\r
+import java.awt.Canvas;\r
+import java.awt.Dimension;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Dimension2D;\r
+import java.awt.geom.Point2D;\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import javax.swing.JComponent;\r
+\r
+import org.simantics.h2d.action.IAction;\r
+import org.simantics.h2d.diagram.IDiagram;\r
+import org.simantics.h2d.diagram.IDiagramListener;\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.editor.ISelection;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.event.IEvent;\r
+import org.simantics.h2d.event.handler.IEventHandler;\r
+import org.simantics.scenegraph.g2d.G2DSceneGraph;\r
+\r
+public class DiagramEditor implements IDiagramEditor {\r
+\r
+       public static final double PICK_TOLERANCE = 5.0;\r
+\r
+       IDiagram diagram;\r
+       \r
+       // Viewpoint\r
+       Point2D offset;\r
+       double scale;\r
+       AffineTransform viewTransform = new AffineTransform();\r
+       Dimension dimension = new Dimension(800, 600);\r
+               \r
+       ISelection selection;\r
+       \r
+       ArrayList<IAction> actionStack = new ArrayList<IAction>(); \r
+       \r
+       SceneGraphManager sgManager;\r
+       EventHandlerManager eventHandlerManager = new EventHandlerManager();\r
+       \r
+       Canvas canvas;\r
+       \r
+       public void setCanvas(Canvas canvas) {\r
+               this.canvas = canvas;\r
+       }\r
+       \r
+       public DiagramEditor(JComponent rootPane, IDiagram diagram) {\r
+               this.diagram = diagram;\r
+               sgManager = new SceneGraphManager(rootPane);            \r
+               \r
+               setViewTransform(new Point2D.Double(), 13.0 / 48.0);\r
+               sgManager.setViewTransform(viewTransform);\r
+               \r
+               selection = new Selection(sgManager.selectionNode);\r
+               \r
+               for(IElement element : diagram.getElements())\r
+                       element.init(sgManager.elementsNode);\r
+               diagram.addDiagramListener(new IDiagramListener() {\r
+                       \r
+                       @Override\r
+                       public void elementAdded(IElement element) {\r
+                               element.init(sgManager.elementsNode);\r
+                       }\r
+\r
+                       @Override\r
+                       public void elementRemoved(IElement element) {\r
+                               element.remove();\r
+                       }\r
+                       \r
+               });\r
+       }       \r
+       \r
+       @Override\r
+       public G2DSceneGraph getSceneGraph() {\r
+               return sgManager.sceneGraph;\r
+       }\r
+\r
+       @Override\r
+       public boolean handleEvent(IEvent event) {\r
+               for(int i=actionStack.size()-1;i>=0;--i)\r
+                       if(actionStack.get(i).handle(this, event))\r
+                               return true;\r
+               return eventHandlerManager.handle(this, event); \r
+       }\r
+\r
+       @Override\r
+       public void addEventHandler(int priority, String eventType, IEventHandler handler) {\r
+               eventHandlerManager.addEventHandler(priority, eventType, handler);\r
+       }\r
+\r
+       @Override\r
+       public void addEventHandler(int priority, IEventHandler handler) {\r
+               eventHandlerManager.addEventHandler(priority, handler);\r
+       }\r
+\r
+       @Override\r
+       public ISelection getSelection() {\r
+               return selection;\r
+       }\r
+\r
+       @Override\r
+       public Point2D getOffset() {\r
+               return offset;\r
+       }\r
+\r
+       @Override\r
+       public double getScale() {\r
+               return scale;\r
+       }\r
+\r
+       @Override\r
+       public AffineTransform getViewTransform() {\r
+               return viewTransform;\r
+       }\r
+       \r
+       @Override\r
+       public void setViewTransform(Point2D offset, double scale) {\r
+               this.offset = offset;\r
+               this.scale = scale;\r
+               viewTransform.setTransform(1.0/scale, 0.0, 0.0, 1.0/scale, \r
+                               -offset.getX()/scale, -offset.getY()/scale);\r
+       }\r
+\r
+       @Override\r
+       public Point2D screenToDiagram(Point2D point) {\r
+               return new Point2D.Double(point.getX()*scale + offset.getX(), point.getY()*scale + offset.getY());\r
+       }\r
+\r
+       @Override\r
+       public IDiagram getDiagram() {\r
+               return diagram;\r
+       }\r
+\r
+       @Override\r
+       public List<IElement> pickElements(Point2D point) {\r
+               double tolerance = PICK_TOLERANCE*scale;\r
+               ArrayList<IElement> result = new ArrayList<IElement>();\r
+               for(IElement element : getDiagram().getElements()) {                                    \r
+                       if(element.hitTest(point.getX(), point.getY(), tolerance))\r
+                               result.add(element);\r
+               }\r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public void addAction(IAction action) {\r
+               actionStack.add(action);\r
+               action.init(sgManager.actionNode);\r
+               requestRepaint();\r
+       }\r
+       \r
+       @Override\r
+       public void removeAction(IAction action) {\r
+               actionStack.remove(action);\r
+               action.remove();\r
+               requestRepaint();\r
+       }\r
+\r
+       @Override\r
+       public Dimension getViewDimension() {\r
+               return dimension;\r
+       }\r
+\r
+       @Override\r
+       public void setViewDimensions(Dimension2D dimension) {\r
+               this.dimension.setSize(dimension);\r
+       }\r
+\r
+       @Override\r
+       public void requestRepaint() {\r
+               canvas.repaint();\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/EventHandlerManager.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/EventHandlerManager.java
new file mode 100644 (file)
index 0000000..7688096
--- /dev/null
@@ -0,0 +1,127 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.editor.impl;\r
+\r
+import gnu.trove.THashMap;\r
+\r
+import java.util.LinkedList;\r
+import java.util.ListIterator;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.event.IEvent;\r
+import org.simantics.h2d.event.handler.IEventHandler;\r
+\r
+class EventHandlerManager implements IEventHandler {\r
+       LinkedList<PrioritizedEventHandler> handlers = new LinkedList<PrioritizedEventHandler>();\r
+       \r
+       public void addEventHandler(int priority, String eventType, IEventHandler handler) {\r
+               ListIterator<PrioritizedEventHandler> it = handlers.listIterator();\r
+               while(it.hasNext()) {\r
+                       PrioritizedEventHandler group = it.next();\r
+                       if(group.priority == priority)\r
+                               group.put(eventType, handler);\r
+                       else if(group.priority < priority) {\r
+                               it.previous();\r
+                               break;\r
+                       }\r
+               }\r
+               \r
+               // Add a new level\r
+               MapEventHandler map = new MapEventHandler(priority);\r
+               map.put(eventType, handler);\r
+               it.add(map);\r
+       }\r
+\r
+       public void addEventHandler(int priority, IEventHandler handler) {\r
+               ListIterator<PrioritizedEventHandler> it = handlers.listIterator();\r
+               while(it.hasNext()) {\r
+                       PrioritizedEventHandler group = it.next();\r
+                       if(group.priority == priority)\r
+                               throw new IllegalArgumentException("Tried add an event handler of type of priority " + priority + \r
+                                       ", but this conflicts with an event handler(s) with the same priority.");\r
+                       else if(group.priority < priority) {\r
+                               it.previous();\r
+                               break;\r
+                       }\r
+               }\r
+               \r
+               // Add a new level\r
+               it.add(new SingletonEventHandler(priority, handler));\r
+       }\r
+       \r
+       static abstract class PrioritizedEventHandler {\r
+               public final int priority;\r
+\r
+               public PrioritizedEventHandler(int priority) {  \r
+                       this.priority = priority;\r
+               }\r
+\r
+               public abstract void put(String type, IEventHandler handler);\r
+               public abstract boolean handle(String type, IDiagramEditor editor, IEvent event);\r
+               \r
+       }\r
+       \r
+       static class SingletonEventHandler extends PrioritizedEventHandler {\r
+\r
+               IEventHandler handler;\r
+               \r
+               public SingletonEventHandler(int priority, IEventHandler handler) {\r
+                       super(priority);\r
+                       this.handler = handler;\r
+               }\r
+\r
+               @Override\r
+               public boolean handle(String type, IDiagramEditor editor, IEvent event) {\r
+                       return handler.handle(editor, event);\r
+               }\r
+\r
+               @Override\r
+               public void put(String type, IEventHandler handler) {\r
+                       throw new IllegalArgumentException("Tried add an event handler of type " + type + " and priority " + priority + \r
+                               ", but this conflicts with an event handler with the same priority.");  \r
+               }\r
+\r
+       }\r
+       \r
+       static class MapEventHandler extends PrioritizedEventHandler {\r
+\r
+               THashMap<String, IEventHandler> handlers = new THashMap<String, IEventHandler>();\r
+               public MapEventHandler(int priority) {\r
+                       super(priority);\r
+               }       \r
+               \r
+               @Override\r
+               public void put(String type, IEventHandler handler) {\r
+                       if(handlers.contains(type))\r
+                               throw new IllegalArgumentException("Tried add an event handler of type " + type + " and priority " + priority + \r
+                                               ", but this conflicts with an event handler with the same priority and type.");\r
+                       handlers.put(type, handler);\r
+               }\r
+               \r
+               @Override\r
+               public boolean handle(String type, IDiagramEditor editor, IEvent event) {\r
+                       IEventHandler handler = handlers.get(type);\r
+                       return handler != null && handler.handle(editor, event);\r
+               }\r
+\r
+       }\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent event) {\r
+               String type = event.getType();\r
+               for(PrioritizedEventHandler level : handlers) {\r
+                       if(level.handle(type, editor, event))\r
+                               return true;                    \r
+               }               \r
+               return false;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/SceneGraphManager.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/SceneGraphManager.java
new file mode 100644 (file)
index 0000000..cf207c7
--- /dev/null
@@ -0,0 +1,52 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.editor.impl;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import javax.swing.JComponent;\r
+\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.G2DSceneGraph;\r
+import org.simantics.scenegraph.g2d.nodes.PageBorderNode;\r
+import org.simantics.scenegraph.g2d.nodes.TransformNode;\r
+\r
+class SceneGraphManager {\r
+    G2DSceneGraph sceneGraph;\r
+    TransformNode diagramCoordinatesNode;\r
+    G2DParentNode elementsNode;\r
+    G2DParentNode selectionNode;\r
+    G2DParentNode actionNode;\r
+\r
+    public SceneGraphManager(JComponent rootPane) {\r
+        sceneGraph = new G2DSceneGraph();\r
+        //sceneGraph.setRootPane(rootPane);\r
+        diagramCoordinatesNode = sceneGraph.addNode(TransformNode.class);\r
+\r
+        PageBorderNode border = diagramCoordinatesNode.addNode(PageBorderNode.class);\r
+        border.init(new Rectangle2D.Double(0.0, 0.0, 297.0, 210.0), new Rectangle2D.Double(10.0, 10.0, 277.0, 190.0), Boolean.TRUE);\r
+\r
+        elementsNode = diagramCoordinatesNode.addNode(G2DParentNode.class);\r
+        elementsNode.setZIndex(0);\r
+\r
+        selectionNode = diagramCoordinatesNode.addNode(G2DParentNode.class);\r
+        selectionNode.setZIndex(1);\r
+\r
+        actionNode = diagramCoordinatesNode.addNode(G2DParentNode.class);\r
+        actionNode.setZIndex(2);\r
+    }\r
+\r
+    void setViewTransform(AffineTransform viewTransform) {\r
+        diagramCoordinatesNode.setTransform(viewTransform);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/Selection.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/editor/impl/Selection.java
new file mode 100644 (file)
index 0000000..632d454
--- /dev/null
@@ -0,0 +1,186 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.editor.impl;\r
+\r
+import gnu.trove.THashSet;\r
+\r
+import java.awt.Color;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Iterator;\r
+import java.util.concurrent.CopyOnWriteArrayList;\r
+\r
+import org.simantics.h2d.editor.ISelection;\r
+import org.simantics.h2d.editor.ISelectionListener;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.element.IElementListener;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.nodes.SelectionNode;\r
+\r
+class Selection implements ISelection {\r
+       static final AffineTransform IDENTITY = new AffineTransform();\r
+       \r
+       THashSet<IElement> elements = new THashSet<IElement>();\r
+       G2DParentNode selectionParentNode;      \r
+       \r
+       CopyOnWriteArrayList<ISelectionListener> listeners = \r
+           new CopyOnWriteArrayList<ISelectionListener>();\r
+       \r
+       static class SelectionUpdater implements IElementListener {\r
+               SelectionNode node;\r
+               IElement element;\r
+               \r
+               public SelectionUpdater(SelectionNode node, IElement element) {\r
+                       this.node = node;\r
+                       this.element = element;\r
+                       \r
+                       elementUpdated(element);                        \r
+                       element.addListener(this);\r
+               }\r
+\r
+               @Override\r
+               public void elementUpdated(IElement element) {\r
+                       Rectangle2D bounds = new Rectangle2D.Double();\r
+                       element.getBounds(bounds);\r
+                       node.init(IDENTITY, bounds, Color.GRAY);\r
+               }               \r
+               \r
+               public void remove() {\r
+                       element.removeListener(this);\r
+               }\r
+\r
+        @Override\r
+        public void elementRemoved(IElement element) {\r
+            // TODO ?\r
+        }\r
+               \r
+       }\r
+       \r
+       ArrayList<SelectionUpdater> updaters = new ArrayList<SelectionUpdater>();\r
+       \r
+       public Selection(G2DParentNode selectionParentNode) {\r
+               this.selectionParentNode = selectionParentNode;\r
+       }       \r
+       \r
+       private void updateSceneGraph() {               \r
+               // Clear old selection\r
+               selectionParentNode.removeNodes();\r
+               for(SelectionUpdater updater : updaters)\r
+                       updater.remove();\r
+               updaters.clear();\r
+               \r
+               // Create new selection\r
+               //System.out.println("selection: " + elements.size());\r
+               for(IElement element : elements)\r
+                       updaters.add(new SelectionUpdater(selectionParentNode.addNode(SelectionNode.class), element));\r
+               \r
+               // Notify listeners\r
+               // TODO this is in wrong place\r
+               for(ISelectionListener listener : listeners)\r
+                   listener.selectionChanged(this);\r
+       }       \r
+\r
+       public boolean contains(IElement el) {\r
+               return elements.contains(el);\r
+       }\r
+       \r
+       public boolean containsOneOf(Collection<IElement> els) {\r
+               for(IElement el : els)\r
+                       if(elements.contains(el))\r
+                               return true;\r
+               return false;\r
+       }\r
+       \r
+       public void clear() {\r
+               if(!elements.isEmpty()) {\r
+                       elements.clear();\r
+                       updateSceneGraph();\r
+               }\r
+       }\r
+       \r
+       public void set(Collection<IElement> els) {\r
+               elements.clear();\r
+               elements.addAll(els);\r
+               updateSceneGraph();\r
+       }\r
+       \r
+       public void set(IElement el) {\r
+               elements.clear();\r
+               elements.add(el);\r
+               updateSceneGraph();\r
+       }\r
+       \r
+       public boolean add(IElement el) {\r
+               boolean result = elements.add(el);\r
+               updateSceneGraph();\r
+               return result;\r
+       }\r
+       \r
+       public boolean addAll(Collection<IElement> els) {\r
+               boolean result = elements.addAll(els);\r
+               updateSceneGraph();\r
+               return result;\r
+       }\r
+       \r
+       public boolean toggle(IElement el) {\r
+               if(elements.contains(el)) {\r
+                       elements.remove(el);\r
+                       updateSceneGraph();\r
+                       return false;\r
+               }\r
+               else {\r
+                       elements.add(el);\r
+                       updateSceneGraph();\r
+                       return true;\r
+               }\r
+       }\r
+       \r
+       public boolean remove(IElement el) {\r
+               boolean result = elements.remove(el);\r
+               updateSceneGraph();\r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public Iterator<IElement> iterator() {\r
+               return elements.iterator();\r
+       }\r
+\r
+       @Override\r
+       public boolean isEmpty() {\r
+               return elements.isEmpty();\r
+       }\r
+\r
+       @Override\r
+       public int size() {\r
+               return elements.size();\r
+       }\r
+\r
+       @Override\r
+       public IElement getSingleElement() {\r
+               for(IElement element : elements)\r
+                       return element;\r
+               return null;\r
+       }\r
+\r
+    @Override\r
+    public void addSelectionListener(ISelectionListener listener) {\r
+        listeners.add(listener);\r
+    }\r
+\r
+    @Override\r
+    public void removeSelectionListener(ISelectionListener listener) {\r
+        listeners.remove(listener);        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/ChainingElementListener.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/ChainingElementListener.java
new file mode 100644 (file)
index 0000000..ce5bc99
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element;\r
+\r
+\r
+class ChainingElementListener implements IElementListener {\r
+       IElementListener listener1;\r
+       IElementListener listener2;\r
+       \r
+       ChainingElementListener(IElementListener listener1,\r
+                       IElementListener listener2) {\r
+               this.listener1 = listener1;\r
+               this.listener2 = listener2;\r
+       }\r
+\r
+       @Override\r
+       public void elementUpdated(IElement element) {\r
+               listener1.elementUpdated(element);\r
+               listener2.elementUpdated(element);              \r
+       }\r
+\r
+    @Override\r
+    public void elementRemoved(IElement element) {\r
+        listener1.elementRemoved(element);\r
+        listener2.elementRemoved(element);      \r
+    }\r
+    \r
+       static IElementListener addListener(IElementListener currentListener, IElementListener newListener) {\r
+               if(currentListener == null)\r
+                       return newListener;\r
+               else \r
+                       return new ChainingElementListener(currentListener, newListener);\r
+       }\r
+       \r
+       static IElementListener removeListener(IElementListener currentListener, IElementListener listenerToRemove) {\r
+               if(currentListener == null || currentListener == listenerToRemove)\r
+                       return null;\r
+               else if(currentListener instanceof ChainingElementListener) {\r
+                       ChainingElementListener chain = (ChainingElementListener)currentListener;\r
+                       if(chain.listener2 == listenerToRemove)\r
+                               return chain.listener1;\r
+                       else {\r
+                               IElementListener l = removeListener(chain.listener1, listenerToRemove);\r
+                               if(l == null)\r
+                                       return chain.listener2;\r
+                               chain.listener1 = l;\r
+                       }\r
+               }\r
+               return currentListener;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/Element.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/Element.java
new file mode 100644 (file)
index 0000000..96bc225
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element;\r
+\r
+\r
+public abstract class Element implements IElement {\r
+\r
+       IElementListener listener;\r
+       \r
+       @SuppressWarnings("unchecked")\r
+       @Override\r
+       public <T> T getInterface(Class<T> clazz) {\r
+               if(clazz.isInstance(this))\r
+                       return (T) this;\r
+               return null;\r
+       }\r
+       \r
+       protected void fireElementUpdated() {\r
+               if(listener != null)\r
+                       listener.elementUpdated(this);\r
+       }\r
+\r
+       @Override\r
+       public void addListener(IElementListener listener) {\r
+               this.listener = ChainingElementListener.addListener(this.listener, listener);\r
+       }\r
+       \r
+       @Override\r
+       public void removeListener(IElementListener listener) {\r
+               this.listener = ChainingElementListener.removeListener(this.listener, listener);\r
+       }\r
+       \r
+       @Override\r
+       public void remove() {\r
+               if(listener != null)\r
+                       listener.elementRemoved(this);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/IElement.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/IElement.java
new file mode 100644 (file)
index 0000000..5a2e39a
--- /dev/null
@@ -0,0 +1,46 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element;\r
+\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+\r
+/**\r
+ * Element is a part of a diagram that has its own type and properties.\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IElement {\r
+       <T> T getInterface(Class<T> clazz);\r
+       \r
+    void init(G2DParentNode parent);\r
+    void remove();\r
+       \r
+       /**\r
+        * Updates the parameter <code>bounds</code> so that it contains \r
+        * the bounding box of the element. \r
+        */\r
+       void getBounds(Rectangle2D bounds);\r
+       \r
+       /**\r
+        * Returns true, if the interior of the element intersects\r
+        * a circle at <code>(x,y)</code> with radius <code>tolerance</code>.\r
+        * Returns false, if the element and a circle at <code>(x,y)</code> with \r
+        * radius <code>sqrt(2)*tolerance</code> are disjoint. Otherwise may return true\r
+        * or false depending on the implementation.\r
+        */\r
+       boolean hitTest(double x, double y, double tolerance);\r
+       \r
+       void addListener(IElementListener listener);\r
+       void removeListener(IElementListener listener);\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/IElementListener.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/IElementListener.java
new file mode 100644 (file)
index 0000000..438629d
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element;\r
+\r
+\r
+public interface IElementListener {\r
+       /**\r
+        * Called when the publicy available properties of the elements are changed.\r
+        * @param element\r
+        */\r
+       public void elementUpdated(IElement element);\r
+       \r
+       public void elementRemoved(IElement element);\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Connectable.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Connectable.java
new file mode 100644 (file)
index 0000000..5d03f16
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element.handler;\r
+\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+\r
+\r
+public interface Connectable extends IElementHandler, IElement {\r
+\r
+       void getBounds(Rectangle2D bounds);\r
+       Point2D getOrigo();\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/IElementHandler.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/IElementHandler.java
new file mode 100644 (file)
index 0000000..93c6a69
--- /dev/null
@@ -0,0 +1,20 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element.handler;\r
+\r
+/**\r
+ * The base interface of all element handler interfaces. Needed only for\r
+ * documenting purposes.\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IElementHandler {\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Movable.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Movable.java
new file mode 100644 (file)
index 0000000..e8722c7
--- /dev/null
@@ -0,0 +1,23 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element.handler;\r
+\r
+\r
+\r
+public interface Movable extends IElementHandler {\r
+\r
+       /**\r
+        * Moves the element by the given delta.\r
+        */\r
+       void move(double deltaX, double deltaY);\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Rotatable.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/Rotatable.java
new file mode 100644 (file)
index 0000000..386a97d
--- /dev/null
@@ -0,0 +1,23 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element.handler;\r
+\r
+\r
+\r
+public interface Rotatable extends IElementHandler {\r
+\r
+       /**\r
+        * Rotates the element <code>amount</code> times 90 degrees clockwise.\r
+        */\r
+       void rotate(int amount);\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/ShadowDrawable.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/element/handler/ShadowDrawable.java
new file mode 100644 (file)
index 0000000..d9245a0
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.element.handler;\r
+\r
+import java.awt.Graphics2D;\r
+import java.awt.geom.AffineTransform;\r
+\r
+public interface ShadowDrawable {\r
+       \r
+       /**\r
+        * Draws the shadow of the element.\r
+        */\r
+       void draw(Graphics2D g, AffineTransform transform);\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/ClickEvent.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/ClickEvent.java
new file mode 100644 (file)
index 0000000..34957cd
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+import java.awt.geom.Point2D;\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+\r
+public class ClickEvent implements ILocatableEvent {   \r
+       final public String modifiers;\r
+\r
+       // Click location in diagram coordinates\r
+       final public Point2D point;\r
+       final public Point2D dispPoint;\r
+\r
+       public List<IElement> pickedElements;\r
+       \r
+       public ClickEvent(String modifiers, Point2D point, Point2D dispPoint) {\r
+               this.modifiers = modifiers;\r
+               this.dispPoint = dispPoint;\r
+               this.point = point;\r
+       }\r
+\r
+       @Override\r
+       public String getType() {\r
+               return getType(modifiers);\r
+       }\r
+       \r
+       public static String getType(String modifiers) {\r
+               return "click(" + modifiers + ")";\r
+       }\r
+       \r
+       @Override\r
+       public Point2D getLocation() {\r
+               return point;\r
+       }\r
+\r
+       @Override\r
+       public List<IElement> getPickedElements() {\r
+               return pickedElements;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/DragEvent.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/DragEvent.java
new file mode 100644 (file)
index 0000000..11bf28c
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+import java.awt.geom.Point2D;\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+\r
+public class DragEvent implements ILocatableEvent {\r
+       public DragEventPhase phase;\r
+       \r
+       public String startModifiers;\r
+       public String currentModifiers;\r
+       \r
+       public Point2D start;\r
+       public Point2D current;\r
+       \r
+       public List<IElement> pickedElements;\r
+\r
+       public DragEvent(String startModifiers, Point2D start) {\r
+               this.phase = DragEventPhase.dragBegin;\r
+               this.startModifiers = startModifiers;\r
+               this.currentModifiers = startModifiers;\r
+               this.start = start;\r
+               this.current = start;\r
+       }\r
+\r
+       @Override\r
+       public String getType() {\r
+               return getType(startModifiers);\r
+       }\r
+       \r
+       public static String getType(String modifiers) {\r
+               return "drag(" + modifiers + ")";\r
+       }\r
+\r
+       @Override\r
+       public Point2D getLocation() {\r
+               return start;\r
+       }\r
+\r
+       @Override\r
+       public List<IElement> getPickedElements() {\r
+               return pickedElements;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/DragEventPhase.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/DragEventPhase.java
new file mode 100644 (file)
index 0000000..714c9ad
--- /dev/null
@@ -0,0 +1,16 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+public enum DragEventPhase {\r
+       dragBegin, dragUpdate, dragEnd \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/IDragHandler.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/IDragHandler.java
new file mode 100644 (file)
index 0000000..07ef210
--- /dev/null
@@ -0,0 +1,17 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+public interface IDragHandler {\r
+       public void handleMove();\r
+       public void handleRelease();\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/IEvent.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/IEvent.java
new file mode 100644 (file)
index 0000000..fa29389
--- /dev/null
@@ -0,0 +1,16 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+public interface IEvent {\r
+       String getType();\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/ILocatableEvent.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/ILocatableEvent.java
new file mode 100644 (file)
index 0000000..cbb0330
--- /dev/null
@@ -0,0 +1,22 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+import java.awt.geom.Point2D;\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+public interface ILocatableEvent extends IEvent {\r
+       Point2D getLocation();\r
+       List<IElement> getPickedElements();\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/KeyboardEvent.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/KeyboardEvent.java
new file mode 100644 (file)
index 0000000..26a7ccc
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+import java.awt.geom.Point2D;\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+\r
+public class KeyboardEvent implements ILocatableEvent {        \r
+       final public String key;\r
+\r
+       // Click location in diagram coordinates\r
+       final public Point2D point;\r
+\r
+       public List<IElement> pickedElements;\r
+       \r
+\r
+       public KeyboardEvent(String key, Point2D point) {\r
+               this.key = key;\r
+               this.point = point;\r
+       }\r
+\r
+\r
+       @Override\r
+       public String getType() {\r
+               return getType(key);\r
+       }\r
+       \r
+       public static String getType(String key) {\r
+               return "key(" + key + ")";\r
+       }\r
+       \r
+       @Override\r
+       public Point2D getLocation() {\r
+               return point;\r
+       }\r
+\r
+       @Override\r
+       public List<IElement> getPickedElements() {\r
+               return pickedElements;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/Modifiers.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/Modifiers.java
new file mode 100644 (file)
index 0000000..d6005e6
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+import java.awt.event.MouseEvent;\r
+\r
+public class Modifiers {\r
+\r
+       public static String modifierString(\r
+                       int button,\r
+                       boolean ctrl,\r
+                       boolean alt,\r
+                       boolean shift\r
+                       ) {\r
+               StringBuilder b = new StringBuilder();\r
+               if(ctrl)\r
+                       b.append("ctrl+");\r
+               if(alt)\r
+                       b.append("alt+");\r
+               if(shift)\r
+                       b.append("shift+");\r
+               if(button == MouseEvent.BUTTON1)\r
+                       b.append("left");\r
+               else if(button == MouseEvent.BUTTON2)\r
+                       b.append("middle");\r
+               else if(button == MouseEvent.BUTTON3)\r
+                       b.append("right");              \r
+               return b.toString();\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/ReleaseEvent.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/ReleaseEvent.java
new file mode 100644 (file)
index 0000000..c6d57de
--- /dev/null
@@ -0,0 +1,42 @@
+package org.simantics.h2d.event;\r
+\r
+import java.awt.geom.Point2D;\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.element.IElement;\r
+\r
+public class ReleaseEvent implements ILocatableEvent {\r
+    final public String modifiers;\r
+\r
+    // Release location in diagram coordinates\r
+    final public Point2D point;\r
+    final public Point2D dispPoint;\r
+\r
+    public List<IElement> pickedElements;\r
+\r
+    public ReleaseEvent(String modifiers, Point2D point, Point2D dispPoint) {\r
+        this.modifiers = modifiers;\r
+        this.dispPoint = dispPoint;\r
+        this.point = point;\r
+    }\r
+    \r
+    @Override\r
+    public Point2D getLocation() {\r
+        return point;\r
+    }\r
+\r
+    @Override\r
+    public List<IElement> getPickedElements() {\r
+        return pickedElements;\r
+    }\r
+\r
+    @Override\r
+    public String getType() {\r
+        return getType(modifiers);\r
+    }\r
+    \r
+    public static String getType(String modifiers) {\r
+        return "release(" + modifiers + ")";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/WheelEvent.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/WheelEvent.java
new file mode 100644 (file)
index 0000000..ee2de8a
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event;\r
+\r
+import java.awt.geom.Point2D;\r
+\r
+\r
+public class WheelEvent implements IEvent {    \r
+       final public String modifiers;\r
+\r
+       // Click location in diagram coordinates\r
+       final public Point2D point;\r
+       \r
+       final public int amount;\r
+\r
+       public WheelEvent(String modifiers, Point2D point, int amount) {\r
+               this.modifiers = modifiers;\r
+               this.point = point;\r
+               this.amount = amount;\r
+       }\r
+\r
+       @Override\r
+       public String getType() {\r
+               return getType(modifiers);\r
+       }\r
+       \r
+       public static String getType(String modifiers) {\r
+               return "wheel(" + modifiers + ")";\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/BoxSelection.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/BoxSelection.java
new file mode 100644 (file)
index 0000000..ae5f9bb
--- /dev/null
@@ -0,0 +1,68 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.editor.ISelection;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.event.DragEvent;\r
+import org.simantics.h2d.node.RectangleNode;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+\r
+public class BoxSelection extends DragEventHandler {\r
+\r
+       Rectangle2D rectangle = new Rectangle2D.Double();\r
+       RectangleNode selectionNode;\r
+       \r
+       @Override\r
+       protected void update(IDiagramEditor editor, DragEvent event) {\r
+               rectangle.setFrameFromDiagonal(event.start, event.current);\r
+               editor.requestRepaint();\r
+       }\r
+\r
+       @Override\r
+       protected void end(IDiagramEditor editor, DragEvent event) {\r
+               Rectangle2D.Double elementBounds = new Rectangle2D.Double();\r
+               ISelection selection = editor.getSelection();\r
+               System.out.println(event.currentModifiers);\r
+               \r
+               Collection<IElement> toBeSelected = new ArrayList<IElement>();\r
+               for(IElement element : editor.getDiagram().getElements()) {\r
+            element.getBounds(elementBounds);\r
+            if(rectangle.contains(elementBounds))\r
+                toBeSelected.add(element);\r
+        }\r
+               \r
+               if(event.currentModifiers.equals("ctrl+"))\r
+                   selection.addAll(toBeSelected);\r
+               else\r
+                   selection.set(toBeSelected);\r
+               editor.requestRepaint();                \r
+       }\r
+       \r
+       @Override\r
+       public void init(G2DParentNode parent) {\r
+               selectionNode = parent.addNode(RectangleNode.class);\r
+               selectionNode.init(rectangle);\r
+       }\r
+       \r
+       @Override\r
+       public void remove() {          \r
+               selectionNode.remove();\r
+               selectionNode = null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/DefaultEventHandlers.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/DefaultEventHandlers.java
new file mode 100644 (file)
index 0000000..cdf1af9
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+\r
+public class DefaultEventHandlers {\r
+\r
+       private DefaultEventHandlers() {}\r
+       \r
+       public static void configure(IDiagramEditor editor) {\r
+               editor.addEventHandler(1, "click(left)", new PickSelection());\r
+               editor.addEventHandler(1, "click(ctrl+left)", new ToggleSelection());\r
+               editor.addEventHandler(1, "drag(shift+left)", new Pan());\r
+               editor.addEventHandler(1, "drag(alt+shift+middle)", new Pan());\r
+               editor.addEventHandler(1, "drag(alt+middle)", new Pan());\r
+               editor.addEventHandler(1, "drag(shift+right)", new Pan());\r
+               editor.addEventHandler(1, "wheel()", new Zoom());\r
+               editor.addEventHandler(1, "key(1)", new ZoomToFit());\r
+               editor.addEventHandler(1, "key(Period)", new RotateCounterclockwise());\r
+               editor.addEventHandler(1, "key(Comma)", new RotateClockwise());\r
+               editor.addEventHandler(1, "key(Ctrl+D)", new Delete());\r
+                               \r
+               editor.addEventHandler(0, new ElementEventDelegator());\r
+               \r
+               editor.addEventHandler(-1, "drag(left)", new MoveSelected());\r
+               editor.addEventHandler(-2, "drag(left)", new BoxSelection());\r
+               editor.addEventHandler(-2, "drag(ctrl+left)", new BoxSelection());\r
+               \r
+               // Prints all unhandled events\r
+               //editor.addEventHandler(-1000, new EventPrinter());\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Delete.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Delete.java
new file mode 100644 (file)
index 0000000..713d565
--- /dev/null
@@ -0,0 +1,32 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import org.simantics.h2d.diagram.IDiagram;\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.event.IEvent;\r
+\r
+public class Delete implements IEventHandler {\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent event) {\r
+               IDiagram diagram = editor.getDiagram();\r
+               for(IElement element : editor.getSelection()) {\r
+                       diagram.removeElement(element);\r
+               }\r
+               editor.getSelection().clear();\r
+               editor.requestRepaint();\r
+               return true;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/DragEventHandler.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/DragEventHandler.java
new file mode 100644 (file)
index 0000000..1cf9af7
--- /dev/null
@@ -0,0 +1,78 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import org.simantics.h2d.action.IAction;\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.event.DragEvent;\r
+import org.simantics.h2d.event.IEvent;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+\r
+public abstract class DragEventHandler implements IAction {\r
+\r
+       boolean isActive = false;\r
+       \r
+       protected boolean begin(IDiagramEditor editor, DragEvent event) {\r
+               return true;\r
+       }\r
+       \r
+       protected void update(IDiagramEditor editor, DragEvent event) {\r
+       }\r
+       \r
+       protected void end(IDiagramEditor editor, DragEvent event) {\r
+       }\r
+       \r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent _event) {\r
+               if(_event instanceof DragEvent) {\r
+                       DragEvent event = (DragEvent)_event;\r
+                       \r
+                       switch(event.phase) {\r
+                       case dragBegin:\r
+                               if(isActive)\r
+                                       return true;                            \r
+                               if(begin(editor, event)) {\r
+                                       isActive = true;\r
+                                       editor.addAction(this);\r
+                                       return true;\r
+                               }\r
+                               else\r
+                                       return false;\r
+                               \r
+                       case dragUpdate:\r
+                               if(!isActive)\r
+                                       return false;\r
+                               update(editor, event);\r
+                               return true;\r
+                               \r
+                       case dragEnd:\r
+                               if(!isActive)\r
+                                       return false;\r
+                               isActive = false;\r
+                               editor.removeAction(this);\r
+                               end(editor, event);\r
+                               return true;\r
+                       }       \r
+                       \r
+               }\r
+               return false;\r
+       }\r
+\r
+       @Override\r
+       public void init(G2DParentNode parent) {\r
+       }\r
+\r
+       @Override\r
+       public void remove() {\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ElementEventDelegator.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ElementEventDelegator.java
new file mode 100644 (file)
index 0000000..2117746
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.event.IEvent;\r
+import org.simantics.h2d.event.ILocatableEvent;\r
+import org.simantics.h2d.event.KeyboardEvent;\r
+\r
+public class ElementEventDelegator implements IEventHandler {\r
+       \r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent _event) {\r
+               if(_event instanceof KeyboardEvent) {\r
+                       IEventHandler uniqueHandler = null;\r
+                       for(IElement element : editor.getSelection()) {\r
+                               IEventHandler handler = element.getInterface(IEventHandler.class);\r
+                               if(handler != null) {\r
+                                       if(uniqueHandler != null)\r
+                                               return true; // nobody cannot consume the event\r
+                                       uniqueHandler = handler;\r
+                               }\r
+                       }\r
+                       if(uniqueHandler != null)\r
+                               return uniqueHandler.handle(editor, _event);\r
+               }\r
+               else if(_event instanceof ILocatableEvent) {\r
+                       ILocatableEvent event = (ILocatableEvent)_event;\r
+                       for(IElement element : event.getPickedElements()) {\r
+                               IEventHandler handler = element.getInterface(IEventHandler.class);\r
+                               if(handler != null && handler.handle(editor, event))\r
+                                       return true;\r
+                       }\r
+               }\r
+               return false;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/EventPrinter.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/EventPrinter.java
new file mode 100644 (file)
index 0000000..8dbf80a
--- /dev/null
@@ -0,0 +1,25 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.event.IEvent;\r
+\r
+public class EventPrinter implements IEventHandler {\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent event) {\r
+               System.out.println(event.getType());\r
+               return false;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/IEventHandler.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/IEventHandler.java
new file mode 100644 (file)
index 0000000..d30f61b
--- /dev/null
@@ -0,0 +1,21 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.event.IEvent;\r
+\r
+public interface IEventHandler {\r
+\r
+       boolean handle(IDiagramEditor editor, IEvent event);\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/MoveSelected.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/MoveSelected.java
new file mode 100644 (file)
index 0000000..5726b8c
--- /dev/null
@@ -0,0 +1,88 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.editor.ISelection;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.element.handler.Movable;\r
+import org.simantics.h2d.event.DragEvent;\r
+import org.simantics.h2d.node.RectangleNode;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.nodes.TransformNode;\r
+\r
+public class MoveSelected extends DragEventHandler {\r
+\r
+       double deltaX, deltaY;  \r
+       TransformNode shadowNode;\r
+       ISelection selection;\r
+       \r
+       @Override\r
+       protected boolean begin(IDiagramEditor editor, DragEvent event) {\r
+               List<IElement> pick = event.pickedElements;\r
+               if(pick.isEmpty())\r
+                       return false;\r
+               selection = editor.getSelection();\r
+               boolean pickContainsSelected = false;\r
+               for(IElement element : pick)\r
+                       if(selection.contains(element)) {\r
+                               pickContainsSelected = true;\r
+                               break;\r
+                       }               \r
+               if(!pickContainsSelected) {\r
+                       selection.clear();\r
+                       selection.add(pick.get(0));\r
+               }\r
+               return true;\r
+       }\r
+       \r
+       @Override\r
+       protected void update(IDiagramEditor editor, DragEvent event) {\r
+               deltaX = event.current.getX() - event.start.getX();\r
+               deltaY = event.current.getY() - event.start.getY();\r
+               shadowNode.setTransform(new AffineTransform(1.0, 0.0, 0.0, 1.0, deltaX, deltaY));\r
+               editor.requestRepaint();\r
+       }\r
+       \r
+       @Override\r
+       protected void end(IDiagramEditor editor, DragEvent event) {\r
+               for(IElement element : selection)\r
+                       if(element instanceof Movable) {\r
+                               ((Movable)element).move(deltaX, deltaY);\r
+                       }\r
+               selection = null;\r
+               editor.requestRepaint();\r
+       }\r
+       \r
+       @Override\r
+       public void init(G2DParentNode parent) {\r
+               shadowNode = parent.addNode(TransformNode.class);\r
+               \r
+               for(IElement element : selection) {\r
+                       Rectangle2D elementBounds = new Rectangle2D.Double();\r
+                       element.getBounds(elementBounds);\r
+                       RectangleNode shadow = shadowNode.addNode(RectangleNode.class);\r
+                       shadow.init(elementBounds);\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public void remove() {\r
+               shadowNode.remove();\r
+               shadowNode = null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Pan.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Pan.java
new file mode 100644 (file)
index 0000000..a490e58
--- /dev/null
@@ -0,0 +1,34 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import java.awt.geom.Point2D;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.event.DragEvent;\r
+\r
+public class Pan extends DragEventHandler {\r
+\r
+       @Override\r
+       protected void update(IDiagramEditor editor, DragEvent event) {\r
+               Point2D offset = editor.getOffset();\r
+               double scale = editor.getScale();\r
+               editor.setViewTransform(\r
+                               new Point2D.Double(\r
+                                               offset.getX() + event.start.getX() - event.current.getX(),\r
+                                               offset.getY() + event.start.getY() - event.current.getY()\r
+                                       ), \r
+                                       scale);\r
+               editor.requestRepaint();\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/PickSelection.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/PickSelection.java
new file mode 100644 (file)
index 0000000..199e0de
--- /dev/null
@@ -0,0 +1,62 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.editor.ISelection;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.event.ClickEvent;\r
+import org.simantics.h2d.event.IEvent;\r
+\r
+public class PickSelection implements IEventHandler {\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent _event) {\r
+               ClickEvent event = (ClickEvent)_event;                          \r
+               List<IElement> pick = event.pickedElements;\r
+               ISelection selection = editor.getSelection();\r
+               if(pick.isEmpty()) {\r
+                       selection.clear();\r
+                       editor.requestRepaint();\r
+               }\r
+               else {\r
+                       if(selection.containsOneOf(pick)) {\r
+                               if(pick.size() > 1 && selection.size()==1) {\r
+                                       /*\r
+                                        * If there are multiple elements under mouse and the current\r
+                                        * selection is exactly one of them then rotate thru all one\r
+                                        * element selection possibilities.\r
+                                        */\r
+                                       IElement s = selection.getSingleElement();\r
+                                       for(int i=0;i<pick.size();++i) {\r
+                                               if(s.equals(pick.get(i))) {\r
+                                                       if(i < pick.size()-1) {\r
+                                                               selection.set(pick.get(i+1));\r
+                                                               return true;\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                                       selection.set(pick.get(0));\r
+                                       editor.requestRepaint();\r
+                               }\r
+                       }\r
+                       else {\r
+                               selection.set(pick.get(0));\r
+                               editor.requestRepaint();\r
+                       }\r
+               }               \r
+               return true;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/RotateClockwise.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/RotateClockwise.java
new file mode 100644 (file)
index 0000000..7f7c6ba
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.element.handler.Rotatable;\r
+import org.simantics.h2d.event.IEvent;\r
+\r
+public class RotateClockwise implements IEventHandler {\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent event) {\r
+               for(IElement element : editor.getSelection()) {\r
+                       Rotatable rotatable = element.getInterface(Rotatable.class);\r
+                       rotatable.rotate(1);\r
+               }\r
+               editor.requestRepaint();\r
+               return true;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/RotateCounterclockwise.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/RotateCounterclockwise.java
new file mode 100644 (file)
index 0000000..5132058
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.element.handler.Rotatable;\r
+import org.simantics.h2d.event.IEvent;\r
+\r
+public class RotateCounterclockwise implements IEventHandler {\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent event) {\r
+               for(IElement element : editor.getSelection()) {\r
+                       Rotatable rotatable = element.getInterface(Rotatable.class);\r
+                       rotatable.rotate(-1);\r
+               }\r
+               editor.requestRepaint();\r
+               return true;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ToggleSelection.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ToggleSelection.java
new file mode 100644 (file)
index 0000000..020e890
--- /dev/null
@@ -0,0 +1,34 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import java.util.List;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.event.ClickEvent;\r
+import org.simantics.h2d.event.IEvent;\r
+\r
+public class ToggleSelection implements IEventHandler {\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent _event) {\r
+               ClickEvent event = (ClickEvent)_event;                          \r
+               List<IElement> pick = event.pickedElements;             \r
+               if(!pick.isEmpty()) {\r
+                       editor.getSelection().toggle(pick.get(0));\r
+                       editor.requestRepaint();\r
+               }\r
+               return true;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Zoom.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/Zoom.java
new file mode 100644 (file)
index 0000000..0113bdf
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import java.awt.geom.Point2D;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.event.IEvent;\r
+import org.simantics.h2d.event.WheelEvent;\r
+\r
+public class Zoom implements IEventHandler {\r
+\r
+       public final static double ZOOM_PER_CLICK = 1.2;\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent _event) {\r
+               final WheelEvent event = (WheelEvent)_event;\r
+               Point2D offset = editor.getOffset();\r
+               double scale = editor.getScale();\r
+               double scaleRatio = Math.pow(ZOOM_PER_CLICK, event.amount);\r
+               \r
+               editor.setViewTransform(\r
+                               new Point2D.Double(\r
+                                       offset.getX() * scaleRatio + event.point.getX() * (1.0 - scaleRatio),\r
+                                       offset.getY() * scaleRatio + event.point.getY() * (1.0 - scaleRatio)\r
+                               ), \r
+                               scale * scaleRatio);\r
+               editor.requestRepaint();\r
+               return true;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ZoomToFit.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/event/handler/ZoomToFit.java
new file mode 100644 (file)
index 0000000..7d0378b
--- /dev/null
@@ -0,0 +1,56 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.event.handler;\r
+\r
+import java.awt.Dimension;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.h2d.editor.IDiagramEditor;\r
+import org.simantics.h2d.element.IElement;\r
+import org.simantics.h2d.event.IEvent;\r
+\r
+public class ZoomToFit implements IEventHandler {\r
+\r
+       @Override\r
+       public boolean handle(IDiagramEditor editor, IEvent event) {\r
+               Rectangle2D diagramBounds = null;\r
+               Rectangle2D elementBounds = new Rectangle2D.Double();\r
+               for(IElement element : editor.getDiagram().getElements()) {\r
+                       element.getBounds(elementBounds);\r
+                       if(diagramBounds == null) {\r
+                               diagramBounds = new Rectangle2D.Double();\r
+                               diagramBounds.setFrame(elementBounds);\r
+                       }\r
+                       else {\r
+                               Rectangle2D.union(diagramBounds, elementBounds, diagramBounds);\r
+                       }\r
+               }\r
+               if(diagramBounds != null) {\r
+                       Dimension dimension = editor.getViewDimension();\r
+                       \r
+                       double scale = Math.max(\r
+                                       diagramBounds.getWidth() / dimension.getWidth(),\r
+                                       diagramBounds.getHeight() / dimension.getHeight()\r
+                                       );                      \r
+                       \r
+                       Point2D offset = new Point2D.Double(\r
+                                       diagramBounds.getCenterX() - dimension.getWidth() * scale * 0.5,\r
+                                       diagramBounds.getCenterY() - dimension.getHeight() * scale * 0.5\r
+                               );\r
+                       editor.setViewTransform(offset, scale);\r
+               }\r
+               editor.requestRepaint();\r
+               return true;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/node/FilledShapeNode.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/node/FilledShapeNode.java
new file mode 100644 (file)
index 0000000..1732270
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.node;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.Shape;
+import java.awt.geom.Rectangle2D;
+
+import org.simantics.scenegraph.g2d.G2DNode;
+
+public class FilledShapeNode extends G2DNode {
+
+    private static final long serialVersionUID = -7540487222025677413L;
+
+    protected Shape shape = null;
+    protected Color color = Color.BLACK;
+
+    @SyncField("shape")
+    public void setShape(Shape shape) {
+        this.shape = shape;
+    }
+
+    @SyncField("color")
+    public void setColor(Color color) {
+        this.color = color;
+    }
+
+    @Override
+    public void render(Graphics2D g2d) {
+        if(shape == null) return;
+        if(color != null) g2d.setColor(color);
+
+        g2d.fill(shape);
+    }
+
+    @Override
+    public Rectangle2D getBoundsInLocal() {
+        if(shape == null)
+            return null;
+        return shape.getBounds2D();
+    }
+
+}
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/node/ITextListener.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/node/ITextListener.java
new file mode 100644 (file)
index 0000000..0dcd768
--- /dev/null
@@ -0,0 +1,18 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.node;\r
+\r
+public interface ITextListener {\r
+\r
+       void textChanged();\r
+       \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/node/LineNode.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/node/LineNode.java
new file mode 100644 (file)
index 0000000..d7ebb06
--- /dev/null
@@ -0,0 +1,60 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.node;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.scenegraph.g2d.G2DNode;\r
+\r
+public class LineNode extends G2DNode {\r
+       \r
+       private static final long serialVersionUID = 654692698101485672L;\r
+\r
+       Point2D begin;\r
+       Point2D end;\r
+    protected Path2D path;\r
+\r
+    @SyncField({"begin","end"})\r
+    public void init(Point2D begin, Point2D end) {\r
+        this.begin = begin;\r
+        this.end = end;\r
+        update();\r
+    }\r
+    \r
+    protected void update() {\r
+       path = new Path2D.Double();\r
+       path.moveTo(begin.getX(), begin.getY());\r
+       path.lineTo(end.getX(), end.getY());\r
+    }\r
+\r
+    @Override\r
+    public void render(Graphics2D g) {\r
+        if(path == null) return;\r
+        g.setColor(Color.BLACK);\r
+        double scale = g.getTransform().getScaleX();\r
+        g.setStroke(new BasicStroke( (float)(1.0 / scale) ));\r
+        g.draw(path);\r
+    }\r
+\r
+       @Override\r
+       public Rectangle2D getBoundsInLocal() {\r
+               Rectangle2D bounds = new Rectangle2D.Double();\r
+               bounds.setFrameFromDiagonal(begin, end);\r
+               return bounds;\r
+       }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/node/RectangleNode.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/node/RectangleNode.java
new file mode 100644 (file)
index 0000000..da8daaa
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.node;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.scenegraph.g2d.G2DNode;\r
+\r
+public class RectangleNode extends G2DNode {\r
+       \r
+       private static final long serialVersionUID = 654692698101485672L;\r
+\r
+    protected Rectangle2D bounds = null;\r
+\r
+    @SyncField("bounds")\r
+    public void init(Rectangle2D bounds) {\r
+        this.bounds = bounds;\r
+    }\r
+\r
+    @Override\r
+    public void render(Graphics2D g) {\r
+        if(bounds == null) return;\r
+        g.transform(transform);\r
+        g.setColor(Color.BLACK);\r
+        double scale = g.getTransform().getScaleX();\r
+        g.setStroke(new BasicStroke( (float)(1.0 / scale) ));\r
+\r
+        g.draw(bounds);\r
+    }\r
+\r
+       @Override\r
+       public Rectangle2D getBoundsInLocal() {\r
+               return bounds;\r
+       }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/node/ShapeNode.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/node/ShapeNode.java
new file mode 100644 (file)
index 0000000..495fb61
--- /dev/null
@@ -0,0 +1,102 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.node;
+
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.awt.RenderingHints;\r
+import java.awt.Shape;\r
+import java.awt.Stroke;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.scenegraph.g2d.G2DNode;\r
+import org.simantics.scenegraph.utils.GeometryUtils;\r
+
+public class ShapeNode extends G2DNode {
+
+    /**
+     * 
+     */
+    private static final long serialVersionUID = 8508750881358776559L;
+
+    protected Shape shape = null;
+    protected Stroke stroke = new BasicStroke(1);
+    protected Color color = Color.BLACK;
+    protected boolean fill = false;
+    protected boolean scaleStroke = false;
+    protected boolean scaleShape = false;
+
+    @SyncField("shape")
+    public void setShape(Shape shape) {
+        this.shape = shape;
+        repaint();
+    }
+
+    @SyncField("stroke")
+    public void setStroke(Stroke stroke) {
+        this.stroke = stroke;
+    }
+
+    @SyncField("color")
+    public void setColor(Color color) {
+        this.color = color;
+    }
+
+    @SyncField("fill")
+    public void setFill(boolean fill) {
+        this.fill = fill;
+    }
+
+    @SyncField("scaleStroke")
+    public void setScaleStroke(boolean scaleStroke) {
+        this.scaleStroke = scaleStroke;
+    }
+
+    @SyncField("scaleShape")
+    public void setScaleShape(boolean scaleShape) {
+        this.scaleShape = scaleShape;
+    }
+
+    @Override
+    public void render(Graphics2D g2d) {
+        if(shape == null) return;
+
+        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // FIXME
+        if(color != null) g2d.setColor(color);
+        if(stroke != null) {
+            if(scaleStroke && stroke instanceof BasicStroke) {
+                BasicStroke bs = GeometryUtils.scaleStroke(stroke, (float) (1.0 / GeometryUtils.getScale(g2d.getTransform())));
+                g2d.setStroke(bs);
+            } else {
+                g2d.setStroke(stroke);
+            }
+        }
+        if(scaleShape) {
+            double xs = g2d.getTransform().getScaleX();
+            double ys = g2d.getTransform().getScaleY();
+            g2d.scale(1/xs, 1/ys);
+        }
+
+        if(fill) {
+            g2d.fill(shape);
+        } else {
+            g2d.draw(shape);
+        }
+
+    }
+
+    @Override
+    public Rectangle2D getBoundsInLocal() {
+        return shape.getBounds2D();
+    }
+}
diff --git a/1.8/org.simantics.h2d/src/org/simantics/h2d/node/TextNode.java b/1.8/org.simantics.h2d/src/org/simantics/h2d/node/TextNode.java
new file mode 100644 (file)
index 0000000..6575c35
--- /dev/null
@@ -0,0 +1,276 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.h2d.node;\r
+\r
+import java.awt.AWTEvent;\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.awt.Graphics2D;\r
+import java.awt.Toolkit;\r
+import java.awt.datatransfer.Clipboard;\r
+import java.awt.datatransfer.DataFlavor;\r
+import java.awt.datatransfer.StringSelection;\r
+import java.awt.datatransfer.Transferable;\r
+import java.awt.event.KeyEvent;\r
+import java.awt.event.MouseEvent;\r
+import java.awt.font.FontRenderContext;\r
+import java.awt.geom.Line2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.scenegraph.g2d.G2DNode;\r
+\r
+public class TextNode extends G2DNode {\r
+\r
+    //static final FontRenderContext FRC = new FontRenderContext(\r
+    //         new AffineTransform(1.0,0.0,0.0,1.0,0.0,0.0), true, true);\r
+\r
+    private static final long serialVersionUID = 654692698101485672L;\r
+\r
+    protected String text = null;\r
+    protected Font font = null;\r
+    protected Color color = null;\r
+    protected double x;\r
+    protected double y;\r
+    protected double scale;\r
+\r
+    boolean editAllowed;\r
+    int caret = 0;\r
+    int selectionTail = 0;\r
+\r
+    ITextListener textListener;\r
+\r
+    /**\r
+     * Enables or disables edit mode. It also sets\r
+     * the caret at the end of text all selects the\r
+     * whole text (this is the usual convention when \r
+     * beginning to edit one line texts).\r
+     * @param editAllowed\r
+     */\r
+    public void setEditMode(boolean editAllowed) {\r
+        this.editAllowed = editAllowed;\r
+        caret = text.length();\r
+        selectionTail = 0;\r
+    }\r
+\r
+    @SyncField({"text", "font", "color", "x", "y", "scale"})\r
+    public void init(String text, Font font, Color color, double x, double y, double scale) {\r
+        this.text = text;\r
+        this.font = font;\r
+        this.color = color;\r
+        this.x = x;\r
+        this.y = y;\r
+        this.scale = scale;\r
+    }\r
+\r
+    @SyncField({"color"})\r
+    public void setColor(Color color) {\r
+        this.color = color;\r
+    }\r
+\r
+    public String getText() {\r
+        return text;\r
+    }\r
+\r
+    private double getLength(FontRenderContext frc, String str) {\r
+        Rectangle2D bounds = font.getStringBounds(str, frc);\r
+        return bounds.getWidth();\r
+    }\r
+\r
+    @Override\r
+    public void render(Graphics2D g) {\r
+        if(text == null || font == null || color == null) return;\r
+        g.setFont(font);\r
+        g.translate(x, y);\r
+        g.scale(scale, scale);\r
+\r
+        if(editAllowed) {\r
+            FontRenderContext frc = g.getFontRenderContext();\r
+\r
+            int selectionMin = Math.min(caret, selectionTail);\r
+            int selectionMax = Math.max(caret, selectionTail);   \r
+            double selectionMinPos = getLength(frc, text.substring(0, selectionMin));\r
+            double selectionMaxPos = getLength(frc, text.substring(0, selectionMax));\r
+\r
+            // Selection background\r
+            g.setColor(new Color(0x316ac5));\r
+            g.fill(new Rectangle2D.Double(selectionMinPos, -12.0, \r
+                    selectionMaxPos-selectionMinPos, 12.0));\r
+\r
+            // Text\r
+            g.setColor(color);    \r
+            g.drawString(text.substring(0, selectionMin), 0f, 0f);\r
+            g.drawString(text.substring(selectionMax), (float)selectionMaxPos, 0f);\r
+\r
+            g.setColor(Color.WHITE);\r
+            g.drawString(text.substring(selectionMin, selectionMax), (float)selectionMinPos, 0f);\r
+\r
+            // Caret\r
+            double caretPos = getLength(frc, text.substring(0, caret));\r
+            //g.setXORMode(Color.BLACK);\r
+            g.setColor(Color.BLACK);\r
+            g.draw(new Line2D.Double(caretPos, 0, caretPos, -12.0));           \r
+        }\r
+        else {\r
+            g.setColor(color);    \r
+            g.drawString(text, 0f, 0f);\r
+        }      \r
+    }\r
+\r
+    /**\r
+     * Replaces the current selection with the content or inserts\r
+     * the content at caret. After the insertion the caret\r
+     * will be at the end of inserted text and selection will\r
+     * be empty.\r
+     * @param content\r
+     */\r
+    @SyncField("text")\r
+    protected void insert(String content) {\r
+        if(!content.contains(" ")) {\r
+            int selectionMin = Math.min(caret, selectionTail);\r
+            int selectionMax = Math.max(caret, selectionTail);    \r
+\r
+            String begin = text.substring(0, selectionMin);\r
+            String end = text.substring(selectionMax);\r
+            text = begin + content + end;\r
+            caret = selectionMin + content.length();\r
+            selectionTail = caret;\r
+        }\r
+    }\r
+\r
+\r
+    @ServerSide\r
+    protected void fireTextChanged() {\r
+        if(textListener != null)\r
+            textListener.textChanged();\r
+    }\r
+\r
+    public void setTextListener(ITextListener listener) {\r
+        this.textListener = listener;\r
+    }\r
+\r
+    private void handleKeyPressed(KeyEvent event) {\r
+        char c = event.getKeyChar();\r
+        //System.out.println("Key pressed " + c + " " + event.getKeyCode());\r
+        if(event.isControlDown())\r
+            switch(event.getKeyCode()) {\r
+                case KeyEvent.VK_C:\r
+                    if(caret != selectionTail) {\r
+                        int selectionMin = Math.min(caret, selectionTail);\r
+                        int selectionMax = Math.max(caret, selectionTail);\r
+                        setCliboardContent(text.substring(selectionMin, selectionMax));\r
+                    }\r
+                    break;\r
+\r
+                case KeyEvent.VK_V:                            \r
+                {\r
+                    String content = getCliboardContent();\r
+                    if(content != null)\r
+                        insert(content);       \r
+                }\r
+                break;\r
+                default:\r
+                    return;\r
+            }                          \r
+        else if(event.isAltDown())\r
+            return;\r
+        else\r
+            switch(event.getKeyCode()) {\r
+                case KeyEvent.VK_LEFT:\r
+                    if(caret > 0) {\r
+                        --caret;\r
+                        if(!event.isShiftDown())\r
+                            selectionTail = caret;\r
+                    }\r
+                    break;\r
+                case KeyEvent.VK_RIGHT:\r
+                    if(caret < text.length()) {\r
+                        ++caret;\r
+                        if(!event.isShiftDown())\r
+                            selectionTail = caret;\r
+                    }\r
+                    break;\r
+                case KeyEvent.VK_HOME:\r
+                    caret = 0;\r
+                    if(!event.isShiftDown())\r
+                        selectionTail = caret;\r
+                    break;\r
+                case KeyEvent.VK_END:\r
+                    caret = text.length();\r
+                    if(!event.isShiftDown())\r
+                        selectionTail = caret;\r
+                    break;\r
+\r
+                case KeyEvent.VK_BACK_SPACE:\r
+                    if(caret == selectionTail && caret > 0)\r
+                        --caret;\r
+                    insert("");        \r
+                    break;\r
+\r
+                case KeyEvent.VK_DELETE:\r
+                    if(caret == selectionTail && caret < text.length())\r
+                        ++caret;\r
+                    insert("");        \r
+                    break;                             \r
+\r
+                default:\r
+                    if(c == 65535 || Character.getType(c) == Character.CONTROL)\r
+                        return;\r
+                    //System.out.println("Char " + (int)c + " " + Character.getType(c));\r
+                    insert(new String(new char[] {c}));                                                                                                        \r
+            }\r
+        // FIXME This is called even if just caret was moved.\r
+        // This is currently necessary for repaints.\r
+        fireTextChanged();\r
+        event.consume();\r
+    }\r
+\r
+    private void handleMousePressed(MouseEvent event) {\r
+        // TODO                \r
+    }\r
+\r
+    @Override\r
+    public void handleEvent(AWTEvent event) {\r
+        if(editAllowed) {\r
+            if(caret > text.length())\r
+                caret = text.length();\r
+            switch(event.getID()) {                    \r
+                case KeyEvent.KEY_PRESSED: \r
+                    handleKeyPressed((KeyEvent)event);\r
+                    break;\r
+                case MouseEvent.MOUSE_PRESSED: \r
+                    handleMousePressed((MouseEvent)event);\r
+                    break;\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public Rectangle2D getBoundsInLocal() {\r
+        return null;\r
+    }\r
+\r
+    public String getCliboardContent() {\r
+        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();\r
+        Transferable clipData = clipboard.getContents(this);\r
+        try {\r
+            return (String) (clipData.getTransferData(DataFlavor.stringFlavor));\r
+        } catch (Exception ee) {\r
+            return null;\r
+        }\r
+    }\r
+\r
+    public void setCliboardContent(String content) {\r
+        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();\r
+        StringSelection data = new StringSelection(content);\r
+        clipboard.setContents(data, data);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart.ontology/.classpath b/1.8/org.simantics.jfreechart.ontology/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.jfreechart.ontology/.project b/1.8/org.simantics.jfreechart.ontology/.project
new file mode 100644 (file)
index 0000000..36a196b
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.jfreechart.ontology</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.simantics.graph.builder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+               <nature>org.simantics.graph.nature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.jfreechart.ontology/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.jfreechart.ontology/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..8fdbeb7
--- /dev/null
@@ -0,0 +1,8 @@
+#Mon Nov 14 12:29:34 EET 2011\r
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.jfreechart.ontology/META-INF/MANIFEST.MF b/1.8/org.simantics.jfreechart.ontology/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..68f6c52
--- /dev/null
@@ -0,0 +1,18 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: JFreeChart
+Bundle-SymbolicName: org.simantics.jfreechart.ontology
+Bundle-Version: 1.0.0.qualifier
+Require-Bundle: org.simantics.layer0,
+ org.simantics.layer0x.ontology;bundle-version="1.0.0",
+ org.simantics.g2d.ontology;bundle-version="1.0.0",
+ org.simantics.diagram.ontology;bundle-version="2.1.0",
+ org.simantics.structural.ontology;bundle-version="1.1.0",
+ org.simantics.modeling.ontology;bundle-version="1.1.0",
+ org.simantics.project.ontology;bundle-version="1.2.0",
+ org.simantics.image2.ontology;bundle-version="1.2.0",
+ org.simantics.action.ontology;bundle-version="1.1.0",
+ org.simantics.viewpoint.ontology;bundle-version="1.2.0",
+ org.simantics.color.ontology;bundle-version="1.1.0"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.simantics.sysdyn
diff --git a/1.8/org.simantics.jfreechart.ontology/build.properties b/1.8/org.simantics.jfreechart.ontology/build.properties
new file mode 100644 (file)
index 0000000..ecdc7c3
--- /dev/null
@@ -0,0 +1,5 @@
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               graph.tg\r
diff --git a/1.8/org.simantics.jfreechart.ontology/graph.tg b/1.8/org.simantics.jfreechart.ontology/graph.tg
new file mode 100644 (file)
index 0000000..5a57c74
Binary files /dev/null and b/1.8/org.simantics.jfreechart.ontology/graph.tg differ
diff --git a/1.8/org.simantics.jfreechart.ontology/graph/ChartViewpoints.pgraph b/1.8/org.simantics.jfreechart.ontology/graph/ChartViewpoints.pgraph
new file mode 100644 (file)
index 0000000..e0cb5e3
--- /dev/null
@@ -0,0 +1,117 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+VP = <http://www.simantics.org/Viewpoint-1.2>\r
+PROJECT = <http://www.simantics.org/Project-1.2>\r
+MOD = <http://www.simantics.org/Modeling-1.2>\r
+IMAGE = <http://www.simantics.org/Image2-1.2>\r
+COLOR = <http://www.simantics.org/Color-1.1>\r
+ACT = <http://www.simantics.org/Action-1.1>\r
+JFREE = <http://www.simantics.org/JFreeChart-1.0>\r
+\r
+\r
+///////////////////////////////////////////////\r
+// XY Line axis: axis and variables viewpoint\r
+///////////////////////////////////////////////\r
+CBC = JFREE.ChartAxisAndVariablesBrowseContext : VP.BrowseContext\r
+CAC = JFREE.ChartAxisAndVariablesActionContext : VP.BrowseContext\r
+\r
+CBC.AxisChildRule : VP.ChildRule\r
+CBC.VariableChildRule : VP.ChildRule\r
+CBC.SeriesLabelRule : VP.LabelRule\r
+CBC.AxisLabelRule : VP.LabelRule\r
+CBC.SeriesLabelDecorationRule : VP.LabelDecorationRule\r
+\r
+CBC\r
+    @VP.customChildRule JFREE.Chart CBC.AxisChildRule\r
+        JFREE.Axis : VP.ResourceNodeType\r
+    @VP.customChildRule JFREE.Axis CBC.VariableChildRule\r
+        JFREE.Series : VP.ResourceNodeType\r
+\r
+CBC        \r
+    @VP.customLabelRule             JFREE.Axis          CBC.AxisLabelRule\r
+    @VP.customLabelRule             JFREE.Series        CBC.SeriesLabelRule\r
+    \r
+CBC\r
+    @VP.customLabelDecorationRule   JFREE.Series        CBC.SeriesLabelDecorationRule \r
+    \r
+CBC\r
+    @VP.dropActionContribution JFREE.Axis CAC.Actions.SeriesDropAction 1.0    \r
+    @VP.dropActionContribution JFREE.Series CAC.Actions.SeriesDropAction 1.0      \r
+    @VP.dropActionContribution JFREE.Axis CAC.Actions.AxisDropAction 2.0    \r
+    @VP.dropActionContribution JFREE.Series CAC.Actions.AxisDropAction 2.0          \r
+    \r
+CBC\r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType JFREE.Chart\r
+        VP.VisualsContribution.HasRule VP.PassThruSorterRule     \r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType JFREE.Axis\r
+        VP.VisualsContribution.HasRule VP.PassThruSorterRule\r
+   \r
+    \r
+CAC.Actions : L0.Library\r
+CAC.Actions.SeriesDropAction : ACT.DropAction    \r
+CAC.Actions.AxisDropAction : ACT.DropAction    \r
+\r
+\r
+///////////////////////////////////////////////\r
+// Bar chart: Variables viewpoint\r
+///////////////////////////////////////////////\r
+BSBC = JFREE.BarSeriesBrowseContext : VP.BrowseContext\r
+BSAC = JFREE.BarSeriesActionContext : VP.BrowseContext\r
+\r
+BSBC.SeriesChildRule : VP.ChildRule\r
+BSBC.SeriesLabelRule : VP.LabelRule\r
+BSBC.SeriesLabelDecorationRule : VP.LabelDecorationRule\r
+    \r
+BSBC\r
+    @VP.customChildRule JFREE.Chart BSBC.SeriesChildRule\r
+        JFREE.Series\r
+\r
+BSBC        \r
+    @VP.customLabelRule             JFREE.Series        BSBC.SeriesLabelRule\r
+    \r
+BSBC\r
+    @VP.customLabelDecorationRule   JFREE.Series        BSBC.SeriesLabelDecorationRule     \r
+    \r
+BSBC\r
+    @VP.dropActionContribution JFREE.Series BSAC.Actions.SeriesDropAction 1.0      \r
+    \r
+BSBC\r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType JFREE.Chart\r
+        VP.VisualsContribution.HasRule VP.PassThruSorterRule\r
+   \r
+BSAC.Actions : L0.Library\r
+BSAC.Actions.SeriesDropAction : ACT.DropAction    \r
+\r
+\r
+///////////////////////////////////////////////\r
+// Pie chart: Variables viewpoint\r
+///////////////////////////////////////////////\r
+PSBC = JFREE.PieSeriesBrowseContext : VP.BrowseContext\r
+PSAC = JFREE.PieSeriesActionContext : VP.BrowseContext\r
+\r
+PSBC.SeriesChildRule : VP.ChildRule\r
+PSBC.SeriesLabelRule : VP.LabelRule\r
+PSBC.SeriesLabelDecorationRule : VP.LabelDecorationRule\r
+    \r
+PSBC\r
+    @VP.customChildRule JFREE.Chart PSBC.SeriesChildRule\r
+        JFREE.Series\r
+\r
+PSBC        \r
+    @VP.customLabelRule             JFREE.Series        PSBC.SeriesLabelRule\r
+    \r
+PSBC\r
+    @VP.customLabelDecorationRule   JFREE.Series        PSBC.SeriesLabelDecorationRule     \r
+    \r
+PSBC\r
+    @VP.dropActionContribution JFREE.Series PSAC.Actions.SeriesDropAction 1.0      \r
+    \r
+PSBC\r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType JFREE.Chart\r
+        VP.VisualsContribution.HasRule VP.PassThruSorterRule\r
+   \r
+PSAC.Actions : L0.Library\r
+PSAC.Actions.SeriesDropAction : ACT.DropAction    \r
diff --git a/1.8/org.simantics.jfreechart.ontology/graph/JFreeChart.pgraph b/1.8/org.simantics.jfreechart.ontology/graph/JFreeChart.pgraph
new file mode 100644 (file)
index 0000000..f185b41
--- /dev/null
@@ -0,0 +1,141 @@
+L0 = <http://www.simantics.org/Layer0-1.1>
+L0X = <http://www.simantics.org/Layer0X-1.1>
+G2D = <http://www.simantics.org/G2D-1.1>
+DIA = <http://www.simantics.org/Diagram-2.2>
+MOD = <http://www.simantics.org/Modeling-1.2>
+STR = <http://www.simantics.org/Structural-1.2>
+
+//#####################################################################
+// Ontology for defining JFreeChart charts
+//#####################################################################
+
+JFREE = <http://www.simantics.org/JFreeChart-1.0> : L0.Ontology
+    @L0.new
+    L0.HasResourceClass "org.simantics.sysdyn.JFreeChartResource"
+
+//#####################################################################
+// Charts
+//#####################################################################
+JFREE.Chart <T L0.Entity
+    >-- JFREE.title --> JFREE.Title <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.subtitles --> L0.List <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Chart.borderColor --> G2D.Color <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Chart.visibleBorder --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Chart.borderWidth --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Chart.visibleLegend --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Chart.time --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+
+//#####################################################################
+// Titles
+//#####################################################################
+JFREE.Title <T L0.Entity
+    >-- JFREE.visible --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Title.position --> L0.Boolean <R L0.IsWeaklyRelatedTo
+    
+JFREE.TextTitle <T JFREE.Title
+JFREE.ImageTitle <T JFREE.Title
+JFREE.LegendTitle <T JFREE.Title
+JFREE.PaintScaleLegend <T JFREE.Title
+JFREE.CompositeTitle <T JFREE.Title
+
+
+//#####################################################################
+// Plots
+//#####################################################################
+
+JFREE.Plot <T L0.Entity
+    >-- JFREE.Plot.domainAxis --> JFREE.Axis <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Plot.rangeAxis --> JFREE.Axis <R L0.HasProperty
+    >-- JFREE.backgroundColor --> G2D.Color <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Plot.visibleGrid --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Plot.rangeAxisList --> L0.List <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Plot.visibleLabels --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Plot.orientation --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    
+JFREE.CategoryPlot <T JFREE.Plot
+JFREE.XYPlot <T JFREE.Plot
+JFREE.PiePlot <T JFREE.Plot
+
+//#####################################################################
+// Axis
+//#####################################################################
+
+JFREE.Axis <T L0.Entity
+    >-- JFREE.color --> G2D.Color <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Axis.min --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Axis.max --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Axis.visibleTickLabels --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Axis.visibleTickMarks --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Axis.visibleAxisLine --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Axis.visibleLabel --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Axis.rotateLabelDegrees --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    
+JFREE.CategoryAxis <T JFREE.Axis
+JFREE.ValueAxis <T JFREE.Axis
+JFREE.NumberAxis <T JFREE.Axis
+
+//#####################################################################
+// Datasets
+//#####################################################################
+JFREE.Dataset <T L0.Entity
+    >-- JFREE.Dataset.seriesList --> L0.List <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Dataset.renderer --> JFREE.Renderer <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Dataset.mapToDomainAxis --> JFREE.Axis <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Dataset.mapToRangeAxis --> JFREE.Axis <R L0.HasProperty : L0.FunctionalRelation
+
+JFREE.XYDataset <T JFREE.Dataset
+JFREE.CategoryDataset <T JFREE.Dataset
+JFREE.PieDataset <T JFREE.Dataset
+
+//#####################################################################
+// Series
+//#####################################################################
+
+JFREE.Series <T L0.Entity
+    >-- JFREE.color
+    >-- JFREE.variableRVI --> L0.String <R L0.HasProperty
+    >-- JFREE.variableFilter --> L0.StringArray <R L0.HasProperty
+    >-- JFREE.Series.rangeList --> L0.List <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Series.lineWidth --> L0.Integer <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Series.exploded --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    >-- JFREE.Series.time --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+
+//#####################################################################
+// Renderers
+//#####################################################################
+
+JFREE.Renderer <T L0.Entity
+
+JFREE.XYLineRenderer <T JFREE.Renderer
+JFREE.XYAreaRenderer <T JFREE.Renderer
+
+JFREE.BarRenderer <T JFREE.Renderer
+JFREE.StackedBarRenderer <T JFREE.Renderer
+
+JFREE.DeviationRenderer <T JFREE.Renderer
+    
+//#####################################################################
+// Position
+//#####################################################################
+JFREE.Position <T L0.Entity
+JFREE.Bottom <T JFREE.Position
+JFREE.Top <T JFREE.Position
+JFREE.Left <T JFREE.Position
+JFREE.Right <T JFREE.Position
+
+
+//#####################################################################
+// Symbol
+//#####################################################################
+JFREE.ChartElement <T DIA.Element
+    L0.HasDescription "Element for displaying charts in diagrams"
+    >-- JFREE.ChartElement.component --> JFREE.Chart <R L0.IsWeaklyRelatedTo
+    
+//#####################################################################
+// Filtering
+//#####################################################################
+JFREE.Filter <T L0.Library
+JFREE.Filter.used <R L0.HasProperty : L0.FunctionalRelation
+   L0.HasRange L0.Boolean
+JFREE.Filter.fraction <R L0.HasProperty : L0.FunctionalRelation
+   L0.HasRange L0.Double
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart.ontology/src/org/simantics/sysdyn/JFreeChartResource.java b/1.8/org.simantics.jfreechart.ontology/src/org/simantics/sysdyn/JFreeChartResource.java
new file mode 100644 (file)
index 0000000..88ccbc8
--- /dev/null
@@ -0,0 +1,442 @@
+package org.simantics.sysdyn;\r
+\r
+import org.simantics.db.RequestProcessor;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.service.QueryControl;\r
+\r
+public class JFreeChartResource {\r
+    \r
+    public final Resource Axis;\r
+    public final Resource Axis_max;\r
+    public final Resource Axis_max_Inverse;\r
+    public final Resource Axis_min;\r
+    public final Resource Axis_min_Inverse;\r
+    public final Resource Axis_rotateLabelDegrees;\r
+    public final Resource Axis_rotateLabelDegrees_Inverse;\r
+    public final Resource Axis_visibleAxisLine;\r
+    public final Resource Axis_visibleAxisLine_Inverse;\r
+    public final Resource Axis_visibleLabel;\r
+    public final Resource Axis_visibleLabel_Inverse;\r
+    public final Resource Axis_visibleTickLabels;\r
+    public final Resource Axis_visibleTickLabels_Inverse;\r
+    public final Resource Axis_visibleTickMarks;\r
+    public final Resource Axis_visibleTickMarks_Inverse;\r
+    public final Resource BarRenderer;\r
+    public final Resource BarSeriesActionContext;\r
+    public final Resource BarSeriesActionContext_Actions;\r
+    public final Resource BarSeriesActionContext_Actions_SeriesDropAction;\r
+    public final Resource BarSeriesBrowseContext;\r
+    public final Resource BarSeriesBrowseContext_SeriesChildRule;\r
+    public final Resource BarSeriesBrowseContext_SeriesLabelDecorationRule;\r
+    public final Resource BarSeriesBrowseContext_SeriesLabelRule;\r
+    public final Resource Bottom;\r
+    public final Resource CategoryAxis;\r
+    public final Resource CategoryDataset;\r
+    public final Resource CategoryPlot;\r
+    public final Resource Chart;\r
+    public final Resource ChartAxisAndVariablesActionContext;\r
+    public final Resource ChartAxisAndVariablesActionContext_Actions;\r
+    public final Resource ChartAxisAndVariablesActionContext_Actions_AxisDropAction;\r
+    public final Resource ChartAxisAndVariablesActionContext_Actions_SeriesDropAction;\r
+    public final Resource ChartAxisAndVariablesBrowseContext;\r
+    public final Resource ChartAxisAndVariablesBrowseContext_AxisChildRule;\r
+    public final Resource ChartAxisAndVariablesBrowseContext_AxisLabelRule;\r
+    public final Resource ChartAxisAndVariablesBrowseContext_SeriesLabelDecorationRule;\r
+    public final Resource ChartAxisAndVariablesBrowseContext_SeriesLabelRule;\r
+    public final Resource ChartAxisAndVariablesBrowseContext_VariableChildRule;\r
+    public final Resource ChartElement;\r
+    public final Resource ChartElement_component;\r
+    public final Resource Chart_borderColor;\r
+    public final Resource Chart_borderColor_Inverse;\r
+    public final Resource Chart_borderWidth;\r
+    public final Resource Chart_borderWidth_Inverse;\r
+    public final Resource Chart_time;\r
+    public final Resource Chart_time_Inverse;\r
+    public final Resource Chart_visibleBorder;\r
+    public final Resource Chart_visibleBorder_Inverse;\r
+    public final Resource Chart_visibleLegend;\r
+    public final Resource Chart_visibleLegend_Inverse;\r
+    public final Resource CompositeTitle;\r
+    public final Resource Dataset;\r
+    public final Resource Dataset_mapToDomainAxis;\r
+    public final Resource Dataset_mapToDomainAxis_Inverse;\r
+    public final Resource Dataset_mapToRangeAxis;\r
+    public final Resource Dataset_mapToRangeAxis_Inverse;\r
+    public final Resource Dataset_renderer;\r
+    public final Resource Dataset_renderer_Inverse;\r
+    public final Resource Dataset_seriesList;\r
+    public final Resource Dataset_seriesList_Inverse;\r
+    public final Resource DeviationRenderer;\r
+    public final Resource Filter;\r
+    public final Resource Filter_fraction;\r
+    public final Resource Filter_fraction_Inverse;\r
+    public final Resource Filter_used;\r
+    public final Resource Filter_used_Inverse;\r
+    public final Resource ImageTitle;\r
+    public final Resource Left;\r
+    public final Resource LegendTitle;\r
+    public final Resource NumberAxis;\r
+    public final Resource PaintScaleLegend;\r
+    public final Resource PieDataset;\r
+    public final Resource PiePlot;\r
+    public final Resource PieSeriesActionContext;\r
+    public final Resource PieSeriesActionContext_Actions;\r
+    public final Resource PieSeriesActionContext_Actions_SeriesDropAction;\r
+    public final Resource PieSeriesBrowseContext;\r
+    public final Resource PieSeriesBrowseContext_SeriesChildRule;\r
+    public final Resource PieSeriesBrowseContext_SeriesLabelDecorationRule;\r
+    public final Resource PieSeriesBrowseContext_SeriesLabelRule;\r
+    public final Resource Plot;\r
+    public final Resource Plot_domainAxis;\r
+    public final Resource Plot_domainAxis_Inverse;\r
+    public final Resource Plot_orientation;\r
+    public final Resource Plot_orientation_Inverse;\r
+    public final Resource Plot_rangeAxis;\r
+    public final Resource Plot_rangeAxisList;\r
+    public final Resource Plot_rangeAxisList_Inverse;\r
+    public final Resource Plot_rangeAxis_Inverse;\r
+    public final Resource Plot_visibleGrid;\r
+    public final Resource Plot_visibleGrid_Inverse;\r
+    public final Resource Plot_visibleLabels;\r
+    public final Resource Plot_visibleLabels_Inverse;\r
+    public final Resource Position;\r
+    public final Resource Renderer;\r
+    public final Resource Right;\r
+    public final Resource Series;\r
+    public final Resource Series_exploded;\r
+    public final Resource Series_exploded_Inverse;\r
+    public final Resource Series_lineWidth;\r
+    public final Resource Series_lineWidth_Inverse;\r
+    public final Resource Series_rangeList;\r
+    public final Resource Series_rangeList_Inverse;\r
+    public final Resource Series_time;\r
+    public final Resource Series_time_Inverse;\r
+    public final Resource StackedBarRenderer;\r
+    public final Resource TextTitle;\r
+    public final Resource Title;\r
+    public final Resource Title_position;\r
+    public final Resource Top;\r
+    public final Resource ValueAxis;\r
+    public final Resource XYAreaRenderer;\r
+    public final Resource XYDataset;\r
+    public final Resource XYLineRenderer;\r
+    public final Resource XYPlot;\r
+    public final Resource backgroundColor;\r
+    public final Resource backgroundColor_Inverse;\r
+    public final Resource color;\r
+    public final Resource color_Inverse;\r
+    public final Resource subtitles;\r
+    public final Resource subtitles_Inverse;\r
+    public final Resource title;\r
+    public final Resource title_Inverse;\r
+    public final Resource variableFilter;\r
+    public final Resource variableFilter_Inverse;\r
+    public final Resource variableRVI;\r
+    public final Resource variableRVI_Inverse;\r
+    public final Resource visible;\r
+    public final Resource visible_Inverse;\r
+        \r
+    public static class URIs {\r
+        public static final String Axis = "http://www.simantics.org/JFreeChart-1.0/Axis";\r
+        public static final String Axis_max = "http://www.simantics.org/JFreeChart-1.0/Axis/max";\r
+        public static final String Axis_max_Inverse = "http://www.simantics.org/JFreeChart-1.0/Axis/max/Inverse";\r
+        public static final String Axis_min = "http://www.simantics.org/JFreeChart-1.0/Axis/min";\r
+        public static final String Axis_min_Inverse = "http://www.simantics.org/JFreeChart-1.0/Axis/min/Inverse";\r
+        public static final String Axis_rotateLabelDegrees = "http://www.simantics.org/JFreeChart-1.0/Axis/rotateLabelDegrees";\r
+        public static final String Axis_rotateLabelDegrees_Inverse = "http://www.simantics.org/JFreeChart-1.0/Axis/rotateLabelDegrees/Inverse";\r
+        public static final String Axis_visibleAxisLine = "http://www.simantics.org/JFreeChart-1.0/Axis/visibleAxisLine";\r
+        public static final String Axis_visibleAxisLine_Inverse = "http://www.simantics.org/JFreeChart-1.0/Axis/visibleAxisLine/Inverse";\r
+        public static final String Axis_visibleLabel = "http://www.simantics.org/JFreeChart-1.0/Axis/visibleLabel";\r
+        public static final String Axis_visibleLabel_Inverse = "http://www.simantics.org/JFreeChart-1.0/Axis/visibleLabel/Inverse";\r
+        public static final String Axis_visibleTickLabels = "http://www.simantics.org/JFreeChart-1.0/Axis/visibleTickLabels";\r
+        public static final String Axis_visibleTickLabels_Inverse = "http://www.simantics.org/JFreeChart-1.0/Axis/visibleTickLabels/Inverse";\r
+        public static final String Axis_visibleTickMarks = "http://www.simantics.org/JFreeChart-1.0/Axis/visibleTickMarks";\r
+        public static final String Axis_visibleTickMarks_Inverse = "http://www.simantics.org/JFreeChart-1.0/Axis/visibleTickMarks/Inverse";\r
+        public static final String BarRenderer = "http://www.simantics.org/JFreeChart-1.0/BarRenderer";\r
+        public static final String BarSeriesActionContext = "http://www.simantics.org/JFreeChart-1.0/BarSeriesActionContext";\r
+        public static final String BarSeriesActionContext_Actions = "http://www.simantics.org/JFreeChart-1.0/BarSeriesActionContext/Actions";\r
+        public static final String BarSeriesActionContext_Actions_SeriesDropAction = "http://www.simantics.org/JFreeChart-1.0/BarSeriesActionContext/Actions/SeriesDropAction";\r
+        public static final String BarSeriesBrowseContext = "http://www.simantics.org/JFreeChart-1.0/BarSeriesBrowseContext";\r
+        public static final String BarSeriesBrowseContext_SeriesChildRule = "http://www.simantics.org/JFreeChart-1.0/BarSeriesBrowseContext/SeriesChildRule";\r
+        public static final String BarSeriesBrowseContext_SeriesLabelDecorationRule = "http://www.simantics.org/JFreeChart-1.0/BarSeriesBrowseContext/SeriesLabelDecorationRule";\r
+        public static final String BarSeriesBrowseContext_SeriesLabelRule = "http://www.simantics.org/JFreeChart-1.0/BarSeriesBrowseContext/SeriesLabelRule";\r
+        public static final String Bottom = "http://www.simantics.org/JFreeChart-1.0/Bottom";\r
+        public static final String CategoryAxis = "http://www.simantics.org/JFreeChart-1.0/CategoryAxis";\r
+        public static final String CategoryDataset = "http://www.simantics.org/JFreeChart-1.0/CategoryDataset";\r
+        public static final String CategoryPlot = "http://www.simantics.org/JFreeChart-1.0/CategoryPlot";\r
+        public static final String Chart = "http://www.simantics.org/JFreeChart-1.0/Chart";\r
+        public static final String ChartAxisAndVariablesActionContext = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesActionContext";\r
+        public static final String ChartAxisAndVariablesActionContext_Actions = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesActionContext/Actions";\r
+        public static final String ChartAxisAndVariablesActionContext_Actions_AxisDropAction = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesActionContext/Actions/AxisDropAction";\r
+        public static final String ChartAxisAndVariablesActionContext_Actions_SeriesDropAction = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesActionContext/Actions/SeriesDropAction";\r
+        public static final String ChartAxisAndVariablesBrowseContext = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesBrowseContext";\r
+        public static final String ChartAxisAndVariablesBrowseContext_AxisChildRule = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesBrowseContext/AxisChildRule";\r
+        public static final String ChartAxisAndVariablesBrowseContext_AxisLabelRule = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesBrowseContext/AxisLabelRule";\r
+        public static final String ChartAxisAndVariablesBrowseContext_SeriesLabelDecorationRule = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesBrowseContext/SeriesLabelDecorationRule";\r
+        public static final String ChartAxisAndVariablesBrowseContext_SeriesLabelRule = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesBrowseContext/SeriesLabelRule";\r
+        public static final String ChartAxisAndVariablesBrowseContext_VariableChildRule = "http://www.simantics.org/JFreeChart-1.0/ChartAxisAndVariablesBrowseContext/VariableChildRule";\r
+        public static final String ChartElement = "http://www.simantics.org/JFreeChart-1.0/ChartElement";\r
+        public static final String ChartElement_component = "http://www.simantics.org/JFreeChart-1.0/ChartElement/component";\r
+        public static final String Chart_borderColor = "http://www.simantics.org/JFreeChart-1.0/Chart/borderColor";\r
+        public static final String Chart_borderColor_Inverse = "http://www.simantics.org/JFreeChart-1.0/Chart/borderColor/Inverse";\r
+        public static final String Chart_borderWidth = "http://www.simantics.org/JFreeChart-1.0/Chart/borderWidth";\r
+        public static final String Chart_borderWidth_Inverse = "http://www.simantics.org/JFreeChart-1.0/Chart/borderWidth/Inverse";\r
+        public static final String Chart_time = "http://www.simantics.org/JFreeChart-1.0/Chart/time";\r
+        public static final String Chart_time_Inverse = "http://www.simantics.org/JFreeChart-1.0/Chart/time/Inverse";\r
+        public static final String Chart_visibleBorder = "http://www.simantics.org/JFreeChart-1.0/Chart/visibleBorder";\r
+        public static final String Chart_visibleBorder_Inverse = "http://www.simantics.org/JFreeChart-1.0/Chart/visibleBorder/Inverse";\r
+        public static final String Chart_visibleLegend = "http://www.simantics.org/JFreeChart-1.0/Chart/visibleLegend";\r
+        public static final String Chart_visibleLegend_Inverse = "http://www.simantics.org/JFreeChart-1.0/Chart/visibleLegend/Inverse";\r
+        public static final String CompositeTitle = "http://www.simantics.org/JFreeChart-1.0/CompositeTitle";\r
+        public static final String Dataset = "http://www.simantics.org/JFreeChart-1.0/Dataset";\r
+        public static final String Dataset_mapToDomainAxis = "http://www.simantics.org/JFreeChart-1.0/Dataset/mapToDomainAxis";\r
+        public static final String Dataset_mapToDomainAxis_Inverse = "http://www.simantics.org/JFreeChart-1.0/Dataset/mapToDomainAxis/Inverse";\r
+        public static final String Dataset_mapToRangeAxis = "http://www.simantics.org/JFreeChart-1.0/Dataset/mapToRangeAxis";\r
+        public static final String Dataset_mapToRangeAxis_Inverse = "http://www.simantics.org/JFreeChart-1.0/Dataset/mapToRangeAxis/Inverse";\r
+        public static final String Dataset_renderer = "http://www.simantics.org/JFreeChart-1.0/Dataset/renderer";\r
+        public static final String Dataset_renderer_Inverse = "http://www.simantics.org/JFreeChart-1.0/Dataset/renderer/Inverse";\r
+        public static final String Dataset_seriesList = "http://www.simantics.org/JFreeChart-1.0/Dataset/seriesList";\r
+        public static final String Dataset_seriesList_Inverse = "http://www.simantics.org/JFreeChart-1.0/Dataset/seriesList/Inverse";\r
+        public static final String DeviationRenderer = "http://www.simantics.org/JFreeChart-1.0/DeviationRenderer";\r
+        public static final String Filter = "http://www.simantics.org/JFreeChart-1.0/Filter";\r
+        public static final String Filter_fraction = "http://www.simantics.org/JFreeChart-1.0/Filter/fraction";\r
+        public static final String Filter_fraction_Inverse = "http://www.simantics.org/JFreeChart-1.0/Filter/fraction/Inverse";\r
+        public static final String Filter_used = "http://www.simantics.org/JFreeChart-1.0/Filter/used";\r
+        public static final String Filter_used_Inverse = "http://www.simantics.org/JFreeChart-1.0/Filter/used/Inverse";\r
+        public static final String ImageTitle = "http://www.simantics.org/JFreeChart-1.0/ImageTitle";\r
+        public static final String Left = "http://www.simantics.org/JFreeChart-1.0/Left";\r
+        public static final String LegendTitle = "http://www.simantics.org/JFreeChart-1.0/LegendTitle";\r
+        public static final String NumberAxis = "http://www.simantics.org/JFreeChart-1.0/NumberAxis";\r
+        public static final String PaintScaleLegend = "http://www.simantics.org/JFreeChart-1.0/PaintScaleLegend";\r
+        public static final String PieDataset = "http://www.simantics.org/JFreeChart-1.0/PieDataset";\r
+        public static final String PiePlot = "http://www.simantics.org/JFreeChart-1.0/PiePlot";\r
+        public static final String PieSeriesActionContext = "http://www.simantics.org/JFreeChart-1.0/PieSeriesActionContext";\r
+        public static final String PieSeriesActionContext_Actions = "http://www.simantics.org/JFreeChart-1.0/PieSeriesActionContext/Actions";\r
+        public static final String PieSeriesActionContext_Actions_SeriesDropAction = "http://www.simantics.org/JFreeChart-1.0/PieSeriesActionContext/Actions/SeriesDropAction";\r
+        public static final String PieSeriesBrowseContext = "http://www.simantics.org/JFreeChart-1.0/PieSeriesBrowseContext";\r
+        public static final String PieSeriesBrowseContext_SeriesChildRule = "http://www.simantics.org/JFreeChart-1.0/PieSeriesBrowseContext/SeriesChildRule";\r
+        public static final String PieSeriesBrowseContext_SeriesLabelDecorationRule = "http://www.simantics.org/JFreeChart-1.0/PieSeriesBrowseContext/SeriesLabelDecorationRule";\r
+        public static final String PieSeriesBrowseContext_SeriesLabelRule = "http://www.simantics.org/JFreeChart-1.0/PieSeriesBrowseContext/SeriesLabelRule";\r
+        public static final String Plot = "http://www.simantics.org/JFreeChart-1.0/Plot";\r
+        public static final String Plot_domainAxis = "http://www.simantics.org/JFreeChart-1.0/Plot/domainAxis";\r
+        public static final String Plot_domainAxis_Inverse = "http://www.simantics.org/JFreeChart-1.0/Plot/domainAxis/Inverse";\r
+        public static final String Plot_orientation = "http://www.simantics.org/JFreeChart-1.0/Plot/orientation";\r
+        public static final String Plot_orientation_Inverse = "http://www.simantics.org/JFreeChart-1.0/Plot/orientation/Inverse";\r
+        public static final String Plot_rangeAxis = "http://www.simantics.org/JFreeChart-1.0/Plot/rangeAxis";\r
+        public static final String Plot_rangeAxisList = "http://www.simantics.org/JFreeChart-1.0/Plot/rangeAxisList";\r
+        public static final String Plot_rangeAxisList_Inverse = "http://www.simantics.org/JFreeChart-1.0/Plot/rangeAxisList/Inverse";\r
+        public static final String Plot_rangeAxis_Inverse = "http://www.simantics.org/JFreeChart-1.0/Plot/rangeAxis/Inverse";\r
+        public static final String Plot_visibleGrid = "http://www.simantics.org/JFreeChart-1.0/Plot/visibleGrid";\r
+        public static final String Plot_visibleGrid_Inverse = "http://www.simantics.org/JFreeChart-1.0/Plot/visibleGrid/Inverse";\r
+        public static final String Plot_visibleLabels = "http://www.simantics.org/JFreeChart-1.0/Plot/visibleLabels";\r
+        public static final String Plot_visibleLabels_Inverse = "http://www.simantics.org/JFreeChart-1.0/Plot/visibleLabels/Inverse";\r
+        public static final String Position = "http://www.simantics.org/JFreeChart-1.0/Position";\r
+        public static final String Renderer = "http://www.simantics.org/JFreeChart-1.0/Renderer";\r
+        public static final String Right = "http://www.simantics.org/JFreeChart-1.0/Right";\r
+        public static final String Series = "http://www.simantics.org/JFreeChart-1.0/Series";\r
+        public static final String Series_exploded = "http://www.simantics.org/JFreeChart-1.0/Series/exploded";\r
+        public static final String Series_exploded_Inverse = "http://www.simantics.org/JFreeChart-1.0/Series/exploded/Inverse";\r
+        public static final String Series_lineWidth = "http://www.simantics.org/JFreeChart-1.0/Series/lineWidth";\r
+        public static final String Series_lineWidth_Inverse = "http://www.simantics.org/JFreeChart-1.0/Series/lineWidth/Inverse";\r
+        public static final String Series_rangeList = "http://www.simantics.org/JFreeChart-1.0/Series/rangeList";\r
+        public static final String Series_rangeList_Inverse = "http://www.simantics.org/JFreeChart-1.0/Series/rangeList/Inverse";\r
+        public static final String Series_time = "http://www.simantics.org/JFreeChart-1.0/Series/time";\r
+        public static final String Series_time_Inverse = "http://www.simantics.org/JFreeChart-1.0/Series/time/Inverse";\r
+        public static final String StackedBarRenderer = "http://www.simantics.org/JFreeChart-1.0/StackedBarRenderer";\r
+        public static final String TextTitle = "http://www.simantics.org/JFreeChart-1.0/TextTitle";\r
+        public static final String Title = "http://www.simantics.org/JFreeChart-1.0/Title";\r
+        public static final String Title_position = "http://www.simantics.org/JFreeChart-1.0/Title/position";\r
+        public static final String Top = "http://www.simantics.org/JFreeChart-1.0/Top";\r
+        public static final String ValueAxis = "http://www.simantics.org/JFreeChart-1.0/ValueAxis";\r
+        public static final String XYAreaRenderer = "http://www.simantics.org/JFreeChart-1.0/XYAreaRenderer";\r
+        public static final String XYDataset = "http://www.simantics.org/JFreeChart-1.0/XYDataset";\r
+        public static final String XYLineRenderer = "http://www.simantics.org/JFreeChart-1.0/XYLineRenderer";\r
+        public static final String XYPlot = "http://www.simantics.org/JFreeChart-1.0/XYPlot";\r
+        public static final String backgroundColor = "http://www.simantics.org/JFreeChart-1.0/backgroundColor";\r
+        public static final String backgroundColor_Inverse = "http://www.simantics.org/JFreeChart-1.0/backgroundColor/Inverse";\r
+        public static final String color = "http://www.simantics.org/JFreeChart-1.0/color";\r
+        public static final String color_Inverse = "http://www.simantics.org/JFreeChart-1.0/color/Inverse";\r
+        public static final String subtitles = "http://www.simantics.org/JFreeChart-1.0/subtitles";\r
+        public static final String subtitles_Inverse = "http://www.simantics.org/JFreeChart-1.0/subtitles/Inverse";\r
+        public static final String title = "http://www.simantics.org/JFreeChart-1.0/title";\r
+        public static final String title_Inverse = "http://www.simantics.org/JFreeChart-1.0/title/Inverse";\r
+        public static final String variableFilter = "http://www.simantics.org/JFreeChart-1.0/variableFilter";\r
+        public static final String variableFilter_Inverse = "http://www.simantics.org/JFreeChart-1.0/variableFilter/Inverse";\r
+        public static final String variableRVI = "http://www.simantics.org/JFreeChart-1.0/variableRVI";\r
+        public static final String variableRVI_Inverse = "http://www.simantics.org/JFreeChart-1.0/variableRVI/Inverse";\r
+        public static final String visible = "http://www.simantics.org/JFreeChart-1.0/visible";\r
+        public static final String visible_Inverse = "http://www.simantics.org/JFreeChart-1.0/visible/Inverse";\r
+    }\r
+    \r
+    public static Resource getResourceOrNull(ReadGraph graph, String uri) {\r
+        try {\r
+            return graph.getResource(uri);\r
+        } catch(DatabaseException e) {\r
+            System.err.println(e.getMessage());\r
+            return null;\r
+        }\r
+    }\r
+    \r
+    public JFreeChartResource(ReadGraph graph) {\r
+        Axis = getResourceOrNull(graph, URIs.Axis);\r
+        Axis_max = getResourceOrNull(graph, URIs.Axis_max);\r
+        Axis_max_Inverse = getResourceOrNull(graph, URIs.Axis_max_Inverse);\r
+        Axis_min = getResourceOrNull(graph, URIs.Axis_min);\r
+        Axis_min_Inverse = getResourceOrNull(graph, URIs.Axis_min_Inverse);\r
+        Axis_rotateLabelDegrees = getResourceOrNull(graph, URIs.Axis_rotateLabelDegrees);\r
+        Axis_rotateLabelDegrees_Inverse = getResourceOrNull(graph, URIs.Axis_rotateLabelDegrees_Inverse);\r
+        Axis_visibleAxisLine = getResourceOrNull(graph, URIs.Axis_visibleAxisLine);\r
+        Axis_visibleAxisLine_Inverse = getResourceOrNull(graph, URIs.Axis_visibleAxisLine_Inverse);\r
+        Axis_visibleLabel = getResourceOrNull(graph, URIs.Axis_visibleLabel);\r
+        Axis_visibleLabel_Inverse = getResourceOrNull(graph, URIs.Axis_visibleLabel_Inverse);\r
+        Axis_visibleTickLabels = getResourceOrNull(graph, URIs.Axis_visibleTickLabels);\r
+        Axis_visibleTickLabels_Inverse = getResourceOrNull(graph, URIs.Axis_visibleTickLabels_Inverse);\r
+        Axis_visibleTickMarks = getResourceOrNull(graph, URIs.Axis_visibleTickMarks);\r
+        Axis_visibleTickMarks_Inverse = getResourceOrNull(graph, URIs.Axis_visibleTickMarks_Inverse);\r
+        BarRenderer = getResourceOrNull(graph, URIs.BarRenderer);\r
+        BarSeriesActionContext = getResourceOrNull(graph, URIs.BarSeriesActionContext);\r
+        BarSeriesActionContext_Actions = getResourceOrNull(graph, URIs.BarSeriesActionContext_Actions);\r
+        BarSeriesActionContext_Actions_SeriesDropAction = getResourceOrNull(graph, URIs.BarSeriesActionContext_Actions_SeriesDropAction);\r
+        BarSeriesBrowseContext = getResourceOrNull(graph, URIs.BarSeriesBrowseContext);\r
+        BarSeriesBrowseContext_SeriesChildRule = getResourceOrNull(graph, URIs.BarSeriesBrowseContext_SeriesChildRule);\r
+        BarSeriesBrowseContext_SeriesLabelDecorationRule = getResourceOrNull(graph, URIs.BarSeriesBrowseContext_SeriesLabelDecorationRule);\r
+        BarSeriesBrowseContext_SeriesLabelRule = getResourceOrNull(graph, URIs.BarSeriesBrowseContext_SeriesLabelRule);\r
+        Bottom = getResourceOrNull(graph, URIs.Bottom);\r
+        CategoryAxis = getResourceOrNull(graph, URIs.CategoryAxis);\r
+        CategoryDataset = getResourceOrNull(graph, URIs.CategoryDataset);\r
+        CategoryPlot = getResourceOrNull(graph, URIs.CategoryPlot);\r
+        Chart = getResourceOrNull(graph, URIs.Chart);\r
+        ChartAxisAndVariablesActionContext = getResourceOrNull(graph, URIs.ChartAxisAndVariablesActionContext);\r
+        ChartAxisAndVariablesActionContext_Actions = getResourceOrNull(graph, URIs.ChartAxisAndVariablesActionContext_Actions);\r
+        ChartAxisAndVariablesActionContext_Actions_AxisDropAction = getResourceOrNull(graph, URIs.ChartAxisAndVariablesActionContext_Actions_AxisDropAction);\r
+        ChartAxisAndVariablesActionContext_Actions_SeriesDropAction = getResourceOrNull(graph, URIs.ChartAxisAndVariablesActionContext_Actions_SeriesDropAction);\r
+        ChartAxisAndVariablesBrowseContext = getResourceOrNull(graph, URIs.ChartAxisAndVariablesBrowseContext);\r
+        ChartAxisAndVariablesBrowseContext_AxisChildRule = getResourceOrNull(graph, URIs.ChartAxisAndVariablesBrowseContext_AxisChildRule);\r
+        ChartAxisAndVariablesBrowseContext_AxisLabelRule = getResourceOrNull(graph, URIs.ChartAxisAndVariablesBrowseContext_AxisLabelRule);\r
+        ChartAxisAndVariablesBrowseContext_SeriesLabelDecorationRule = getResourceOrNull(graph, URIs.ChartAxisAndVariablesBrowseContext_SeriesLabelDecorationRule);\r
+        ChartAxisAndVariablesBrowseContext_SeriesLabelRule = getResourceOrNull(graph, URIs.ChartAxisAndVariablesBrowseContext_SeriesLabelRule);\r
+        ChartAxisAndVariablesBrowseContext_VariableChildRule = getResourceOrNull(graph, URIs.ChartAxisAndVariablesBrowseContext_VariableChildRule);\r
+        ChartElement = getResourceOrNull(graph, URIs.ChartElement);\r
+        ChartElement_component = getResourceOrNull(graph, URIs.ChartElement_component);\r
+        Chart_borderColor = getResourceOrNull(graph, URIs.Chart_borderColor);\r
+        Chart_borderColor_Inverse = getResourceOrNull(graph, URIs.Chart_borderColor_Inverse);\r
+        Chart_borderWidth = getResourceOrNull(graph, URIs.Chart_borderWidth);\r
+        Chart_borderWidth_Inverse = getResourceOrNull(graph, URIs.Chart_borderWidth_Inverse);\r
+        Chart_time = getResourceOrNull(graph, URIs.Chart_time);\r
+        Chart_time_Inverse = getResourceOrNull(graph, URIs.Chart_time_Inverse);\r
+        Chart_visibleBorder = getResourceOrNull(graph, URIs.Chart_visibleBorder);\r
+        Chart_visibleBorder_Inverse = getResourceOrNull(graph, URIs.Chart_visibleBorder_Inverse);\r
+        Chart_visibleLegend = getResourceOrNull(graph, URIs.Chart_visibleLegend);\r
+        Chart_visibleLegend_Inverse = getResourceOrNull(graph, URIs.Chart_visibleLegend_Inverse);\r
+        CompositeTitle = getResourceOrNull(graph, URIs.CompositeTitle);\r
+        Dataset = getResourceOrNull(graph, URIs.Dataset);\r
+        Dataset_mapToDomainAxis = getResourceOrNull(graph, URIs.Dataset_mapToDomainAxis);\r
+        Dataset_mapToDomainAxis_Inverse = getResourceOrNull(graph, URIs.Dataset_mapToDomainAxis_Inverse);\r
+        Dataset_mapToRangeAxis = getResourceOrNull(graph, URIs.Dataset_mapToRangeAxis);\r
+        Dataset_mapToRangeAxis_Inverse = getResourceOrNull(graph, URIs.Dataset_mapToRangeAxis_Inverse);\r
+        Dataset_renderer = getResourceOrNull(graph, URIs.Dataset_renderer);\r
+        Dataset_renderer_Inverse = getResourceOrNull(graph, URIs.Dataset_renderer_Inverse);\r
+        Dataset_seriesList = getResourceOrNull(graph, URIs.Dataset_seriesList);\r
+        Dataset_seriesList_Inverse = getResourceOrNull(graph, URIs.Dataset_seriesList_Inverse);\r
+        DeviationRenderer = getResourceOrNull(graph, URIs.DeviationRenderer);\r
+        Filter = getResourceOrNull(graph, URIs.Filter);\r
+        Filter_fraction = getResourceOrNull(graph, URIs.Filter_fraction);\r
+        Filter_fraction_Inverse = getResourceOrNull(graph, URIs.Filter_fraction_Inverse);\r
+        Filter_used = getResourceOrNull(graph, URIs.Filter_used);\r
+        Filter_used_Inverse = getResourceOrNull(graph, URIs.Filter_used_Inverse);\r
+        ImageTitle = getResourceOrNull(graph, URIs.ImageTitle);\r
+        Left = getResourceOrNull(graph, URIs.Left);\r
+        LegendTitle = getResourceOrNull(graph, URIs.LegendTitle);\r
+        NumberAxis = getResourceOrNull(graph, URIs.NumberAxis);\r
+        PaintScaleLegend = getResourceOrNull(graph, URIs.PaintScaleLegend);\r
+        PieDataset = getResourceOrNull(graph, URIs.PieDataset);\r
+        PiePlot = getResourceOrNull(graph, URIs.PiePlot);\r
+        PieSeriesActionContext = getResourceOrNull(graph, URIs.PieSeriesActionContext);\r
+        PieSeriesActionContext_Actions = getResourceOrNull(graph, URIs.PieSeriesActionContext_Actions);\r
+        PieSeriesActionContext_Actions_SeriesDropAction = getResourceOrNull(graph, URIs.PieSeriesActionContext_Actions_SeriesDropAction);\r
+        PieSeriesBrowseContext = getResourceOrNull(graph, URIs.PieSeriesBrowseContext);\r
+        PieSeriesBrowseContext_SeriesChildRule = getResourceOrNull(graph, URIs.PieSeriesBrowseContext_SeriesChildRule);\r
+        PieSeriesBrowseContext_SeriesLabelDecorationRule = getResourceOrNull(graph, URIs.PieSeriesBrowseContext_SeriesLabelDecorationRule);\r
+        PieSeriesBrowseContext_SeriesLabelRule = getResourceOrNull(graph, URIs.PieSeriesBrowseContext_SeriesLabelRule);\r
+        Plot = getResourceOrNull(graph, URIs.Plot);\r
+        Plot_domainAxis = getResourceOrNull(graph, URIs.Plot_domainAxis);\r
+        Plot_domainAxis_Inverse = getResourceOrNull(graph, URIs.Plot_domainAxis_Inverse);\r
+        Plot_orientation = getResourceOrNull(graph, URIs.Plot_orientation);\r
+        Plot_orientation_Inverse = getResourceOrNull(graph, URIs.Plot_orientation_Inverse);\r
+        Plot_rangeAxis = getResourceOrNull(graph, URIs.Plot_rangeAxis);\r
+        Plot_rangeAxisList = getResourceOrNull(graph, URIs.Plot_rangeAxisList);\r
+        Plot_rangeAxisList_Inverse = getResourceOrNull(graph, URIs.Plot_rangeAxisList_Inverse);\r
+        Plot_rangeAxis_Inverse = getResourceOrNull(graph, URIs.Plot_rangeAxis_Inverse);\r
+        Plot_visibleGrid = getResourceOrNull(graph, URIs.Plot_visibleGrid);\r
+        Plot_visibleGrid_Inverse = getResourceOrNull(graph, URIs.Plot_visibleGrid_Inverse);\r
+        Plot_visibleLabels = getResourceOrNull(graph, URIs.Plot_visibleLabels);\r
+        Plot_visibleLabels_Inverse = getResourceOrNull(graph, URIs.Plot_visibleLabels_Inverse);\r
+        Position = getResourceOrNull(graph, URIs.Position);\r
+        Renderer = getResourceOrNull(graph, URIs.Renderer);\r
+        Right = getResourceOrNull(graph, URIs.Right);\r
+        Series = getResourceOrNull(graph, URIs.Series);\r
+        Series_exploded = getResourceOrNull(graph, URIs.Series_exploded);\r
+        Series_exploded_Inverse = getResourceOrNull(graph, URIs.Series_exploded_Inverse);\r
+        Series_lineWidth = getResourceOrNull(graph, URIs.Series_lineWidth);\r
+        Series_lineWidth_Inverse = getResourceOrNull(graph, URIs.Series_lineWidth_Inverse);\r
+        Series_rangeList = getResourceOrNull(graph, URIs.Series_rangeList);\r
+        Series_rangeList_Inverse = getResourceOrNull(graph, URIs.Series_rangeList_Inverse);\r
+        Series_time = getResourceOrNull(graph, URIs.Series_time);\r
+        Series_time_Inverse = getResourceOrNull(graph, URIs.Series_time_Inverse);\r
+        StackedBarRenderer = getResourceOrNull(graph, URIs.StackedBarRenderer);\r
+        TextTitle = getResourceOrNull(graph, URIs.TextTitle);\r
+        Title = getResourceOrNull(graph, URIs.Title);\r
+        Title_position = getResourceOrNull(graph, URIs.Title_position);\r
+        Top = getResourceOrNull(graph, URIs.Top);\r
+        ValueAxis = getResourceOrNull(graph, URIs.ValueAxis);\r
+        XYAreaRenderer = getResourceOrNull(graph, URIs.XYAreaRenderer);\r
+        XYDataset = getResourceOrNull(graph, URIs.XYDataset);\r
+        XYLineRenderer = getResourceOrNull(graph, URIs.XYLineRenderer);\r
+        XYPlot = getResourceOrNull(graph, URIs.XYPlot);\r
+        backgroundColor = getResourceOrNull(graph, URIs.backgroundColor);\r
+        backgroundColor_Inverse = getResourceOrNull(graph, URIs.backgroundColor_Inverse);\r
+        color = getResourceOrNull(graph, URIs.color);\r
+        color_Inverse = getResourceOrNull(graph, URIs.color_Inverse);\r
+        subtitles = getResourceOrNull(graph, URIs.subtitles);\r
+        subtitles_Inverse = getResourceOrNull(graph, URIs.subtitles_Inverse);\r
+        title = getResourceOrNull(graph, URIs.title);\r
+        title_Inverse = getResourceOrNull(graph, URIs.title_Inverse);\r
+        variableFilter = getResourceOrNull(graph, URIs.variableFilter);\r
+        variableFilter_Inverse = getResourceOrNull(graph, URIs.variableFilter_Inverse);\r
+        variableRVI = getResourceOrNull(graph, URIs.variableRVI);\r
+        variableRVI_Inverse = getResourceOrNull(graph, URIs.variableRVI_Inverse);\r
+        visible = getResourceOrNull(graph, URIs.visible);\r
+        visible_Inverse = getResourceOrNull(graph, URIs.visible_Inverse);\r
+    }\r
+    \r
+    public static JFreeChartResource getInstance(ReadGraph graph) {\r
+        Session session = graph.getSession();\r
+        JFreeChartResource ret = session.peekService(JFreeChartResource.class);\r
+        if(ret == null) {\r
+            QueryControl qc = graph.getService(QueryControl.class);\r
+            ret = new JFreeChartResource(qc.getIndependentGraph(graph));\r
+            session.registerService(JFreeChartResource.class, ret);\r
+        }\r
+        return ret;\r
+    }\r
+    \r
+    public static JFreeChartResource getInstance(RequestProcessor session) throws DatabaseException {\r
+        JFreeChartResource ret = session.peekService(JFreeChartResource.class);\r
+        if(ret == null) {\r
+            ret = session.syncRequest(new Read<JFreeChartResource>() {\r
+                public JFreeChartResource perform(ReadGraph graph) throws DatabaseException {\r
+                    QueryControl qc = graph.getService(QueryControl.class);\r
+                    return new JFreeChartResource(qc.getIndependentGraph(graph));\r
+                }\r
+            });\r
+            session.registerService(JFreeChartResource.class, ret);\r
+        }\r
+        return ret;\r
+    }\r
+    \r
+}\r
+\r
diff --git a/1.8/org.simantics.jfreechart/.classpath b/1.8/org.simantics.jfreechart/.classpath
new file mode 100644 (file)
index 0000000..ed5bcd8
--- /dev/null
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry exported="true" kind="lib" path="batik/batik-awt-util.jar"/>\r
+       <classpathentry exported="true" kind="lib" path="batik/batik-dom.jar"/>\r
+       <classpathentry exported="true" kind="lib" path="batik/batik-ext.jar"/>\r
+       <classpathentry exported="true" kind="lib" path="batik/batik-svg-dom.jar"/>\r
+       <classpathentry exported="true" kind="lib" path="batik/batik-svggen.jar"/>\r
+       <classpathentry exported="true" kind="lib" path="batik/batik-util.jar"/>\r
+       <classpathentry exported="true" kind="lib" path="batik/batik-xml.jar"/>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.jfreechart/.project b/1.8/org.simantics.jfreechart/.project
new file mode 100644 (file)
index 0000000..9c948e2
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.jfreechart</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.jfreechart/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.jfreechart/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..f287d53
--- /dev/null
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.jfreechart/META-INF/MANIFEST.MF b/1.8/org.simantics.jfreechart/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..fb0ab09
--- /dev/null
@@ -0,0 +1,45 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Jfreechart
+Bundle-SymbolicName: org.simantics.jfreechart;singleton:=true
+Bundle-Version: 1.0.0.qualifier
+Bundle-Activator: org.simantics.jfreechart.internal.Activator
+Bundle-Vendor: VTT
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ org.jfree.jchart;bundle-version="1.0.13",
+ org.jfree.jcommon;bundle-version="1.0.16",
+ org.simantics.jfreechart.ontology;bundle-version="1.0.0",
+ org.simantics.db;bundle-version="1.1.0",
+ org.simantics.db.layer0;bundle-version="1.1.0",
+ org.simantics.layer0;bundle-version="1.1.0",
+ org.simantics.diagram;bundle-version="1.1.1",
+ org.simantics.diagram.ontology;bundle-version="2.2.0",
+ org.simantics.modeling;bundle-version="1.1.1",
+ org.simantics.ui;bundle-version="1.0.0",
+ org.simantics.browsing.ui.common;bundle-version="1.1.0",
+ org.simantics.browsing.ui.ontology;bundle-version="1.1.0",
+ org.simantics.browsing.ui.swt;bundle-version="1.1.0",
+ org.simantics.modeling.ui;bundle-version="1.1.1",
+ org.simantics.layer0.utils;bundle-version="1.1.0",
+ org.simantics.scenegraph.swing;bundle-version="1.0.0",
+ org.simantics.browsing.ui.model;bundle-version="1.0.0",
+ org.simantics.selectionview;bundle-version="1.0.0"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-ActivationPolicy: lazy
+Export-Package: org.simantics.jfreechart,
+ org.simantics.jfreechart.chart,
+ org.simantics.jfreechart.chart.element,
+ org.simantics.jfreechart.chart.ge,
+ org.simantics.jfreechart.chart.properties,
+ org.simantics.jfreechart.chart.properties.bar,
+ org.simantics.jfreechart.chart.properties.pie,
+ org.simantics.jfreechart.chart.properties.xyline
+Bundle-ClassPath: batik/batik-awt-util.jar,
+ batik/batik-dom.jar,
+ batik/batik-ext.jar,
+ batik/batik-svg-dom.jar,
+ batik/batik-svggen.jar,
+ batik/batik-util.jar,
+ batik/batik-xml.jar,
+ .
diff --git a/1.8/org.simantics.jfreechart/adapters.xml b/1.8/org.simantics.jfreechart/adapters.xml
new file mode 100644 (file)
index 0000000..54fd841
--- /dev/null
@@ -0,0 +1,155 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<!--\r
+    Copyright (c) 2010 Association for Decentralized Information Management in\r
+    Industry THTH ry.\r
+    All rights reserved. This program and the accompanying materials\r
+    are made available under the terms of the Eclipse Public License v1.0\r
+    which accompanies this distribution, and is available at\r
+    http://www.eclipse.org/legal/epl-v10.html\r
+   \r
+    Contributors:\r
+        VTT Technical Research Centre of Finland - initial API and implementation\r
+ -->\r
+\r
+<adapters>\r
+   <target interface="org.simantics.browsing.ui.model.children.ChildRule">\r
+             \r
+              \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/ChartAxisAndVariablesBrowseContext/AxisChildRule"\r
+            class="org.simantics.jfreechart.chart.ge.AxisChildRule"/>     \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/ChartAxisAndVariablesBrowseContext/VariableChildRule"\r
+            class="org.simantics.jfreechart.chart.ge.VariableChildRule"/>  \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/BarSeriesBrowseContext/SeriesChildRule"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesChildRule"/>           \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/PieSeriesBrowseContext/SeriesChildRule"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesChildRule"/>    \r
+                        \r
+    </target>\r
+   <target interface="org.simantics.browsing.ui.model.visuals.VisualsRule">\r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/ChartAxisAndVariablesBrowseContext/SeriesLabelRule"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesLabelRule"/>         \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/ChartAxisAndVariablesBrowseContext/AxisLabelRule"\r
+            class="org.simantics.jfreechart.chart.ge.AxisLabelRule"/> \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/BarSeriesBrowseContext/SeriesLabelRule"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesLabelRule"/>         \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/PieSeriesBrowseContext/SeriesLabelRule"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesLabelRule"/> \r
+            \r
+            <resource uri="http://www.simantics.org/JFreeChart-0.0/ChartAxisAndVariablesBrowseContext/SeriesLabelDecorationRule"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesLabelDecorationRule"/>   \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/BarSeriesBrowseContext/SeriesLabelDecorationRule"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesLabelDecorationRule"/>         \r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/PieSeriesBrowseContext/SeriesLabelDecorationRule"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesLabelDecorationRule"/>     \r
+   </target> \r
+            \r
+   <target interface="org.simantics.db.layer0.adapter.DropActionFactory">        \r
+   \r
+        <resource\r
+            uri="http://www.simantics.org/JFreeChart-0.0/ChartAxisAndVariablesActionContext/Actions/SeriesDropAction"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesDropAction" />\r
+        <resource\r
+            uri="http://www.simantics.org/JFreeChart-0.0/ChartAxisAndVariablesActionContext/Actions/AxisDropAction"\r
+            class="org.simantics.jfreechart.chart.ge.AxisDropAction" />            \r
+            \r
+        <resource\r
+            uri="http://www.simantics.org/JFreeChart-0.0/BarSeriesActionContext/Actions/SeriesDropAction"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesDropAction" />\r
+        <resource\r
+            uri="http://www.simantics.org/JFreeChart-0.0/PieSeriesActionContext/Actions/SeriesDropAction"\r
+            class="org.simantics.jfreechart.chart.ge.SeriesDropAction" />                        \r
+    </target> \r
+    \r
+  <!-- Charts -->\r
+    <target interface="org.simantics.diagram.adapter.ElementFactory">\r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/ChartElement"\r
+            class="org.simantics.jfreechart.chart.element.ChartElementFactory" />\r
+            \r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/ChartElement"\r
+            class="org.simantics.jfreechart.chart.element.ChartElementFactory" />\r
+    </target>\r
+                \r
+    <target interface="org.simantics.diagram.synchronization.graph.ElementWriter">\r
+        <resource uri="http://www.simantics.org/JFreeChart-0.0/ChartElement"\r
+            class="org.simantics.jfreechart.chart.element.ChartElementWriter" />\r
+    </target>\r
+                    \r
+    <target interface="org.simantics.jfreechart.chart.IJFreeChart">\r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/Chart"\r
+            class="org.simantics.jfreechart.chart.JFreeChart">\r
+            <graph />\r
+            <this />\r
+        </type>\r
+    </target>  \r
+    \r
+   \r
+    \r
+     <target interface="org.simantics.jfreechart.chart.ITitle">\r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/TextTitle"\r
+            class="org.simantics.jfreechart.chart.TextTitle">\r
+            <graph />\r
+            <this />\r
+        </type>\r
+    </target>\r
+    \r
+    <target interface="org.simantics.jfreechart.chart.IAxis">\r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/NumberAxis"\r
+            class="org.simantics.jfreechart.chart.NumberAxis">\r
+            <graph />\r
+            <this />\r
+        </type>\r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/CategoryAxis"\r
+            class="org.simantics.jfreechart.chart.CategoryAxis">\r
+            <graph />\r
+            <this />\r
+        </type>        \r
+    </target>\r
+       \r
+    <target interface="org.simantics.jfreechart.chart.IPlot">\r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/XYPlot"\r
+            class="org.simantics.jfreechart.chart.XYPlot">\r
+            <graph />\r
+            <this />\r
+        </type>\r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/CategoryPlot"\r
+            class="org.simantics.jfreechart.chart.CategoryPlot">\r
+            <graph />\r
+            <this />\r
+        </type>      \r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/PiePlot"\r
+            class="org.simantics.jfreechart.chart.PiePlot">\r
+            <graph />\r
+            <this />\r
+        </type>               \r
+    </target>\r
+    \r
+     <target interface="org.simantics.jfreechart.chart.IRenderer">\r
+     \r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/XYLineRenderer"\r
+            class="org.simantics.jfreechart.chart.XYLineRenderer">\r
+            <graph />\r
+            <this />\r
+        </type>  \r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/XYAreaRenderer"\r
+            class="org.simantics.jfreechart.chart.XYAreaRenderer">\r
+            <graph />\r
+            <this />\r
+        </type>        \r
+                \r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/BarRenderer"\r
+            class="org.simantics.jfreechart.chart.BarRenderer">\r
+            <graph />\r
+            <this />\r
+        </type>\r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/StackedBarRenderer"\r
+            class="org.simantics.jfreechart.chart.StackedBarRenderer">\r
+            <graph />\r
+            <this />\r
+        </type>      \r
+        <type uri="http://www.simantics.org/JFreeChart-0.0/DeviationRenderer"\r
+            class="org.simantics.jfreechart.chart.DeviationRenderer">\r
+            <graph />\r
+            <this />\r
+        </type>           \r
+    </target> \r
+</adapters>
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart/batik/batik-1.7.zip b/1.8/org.simantics.jfreechart/batik/batik-1.7.zip
new file mode 100644 (file)
index 0000000..b1f32e7
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-1.7.zip differ
diff --git a/1.8/org.simantics.jfreechart/batik/batik-awt-util.jar b/1.8/org.simantics.jfreechart/batik/batik-awt-util.jar
new file mode 100644 (file)
index 0000000..e64605a
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-awt-util.jar differ
diff --git a/1.8/org.simantics.jfreechart/batik/batik-dom.jar b/1.8/org.simantics.jfreechart/batik/batik-dom.jar
new file mode 100644 (file)
index 0000000..32d5b46
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-dom.jar differ
diff --git a/1.8/org.simantics.jfreechart/batik/batik-ext.jar b/1.8/org.simantics.jfreechart/batik/batik-ext.jar
new file mode 100644 (file)
index 0000000..8c904e1
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-ext.jar differ
diff --git a/1.8/org.simantics.jfreechart/batik/batik-src-1.7.zip b/1.8/org.simantics.jfreechart/batik/batik-src-1.7.zip
new file mode 100644 (file)
index 0000000..77478cd
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-src-1.7.zip differ
diff --git a/1.8/org.simantics.jfreechart/batik/batik-svg-dom.jar b/1.8/org.simantics.jfreechart/batik/batik-svg-dom.jar
new file mode 100644 (file)
index 0000000..b4c8a62
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-svg-dom.jar differ
diff --git a/1.8/org.simantics.jfreechart/batik/batik-svggen.jar b/1.8/org.simantics.jfreechart/batik/batik-svggen.jar
new file mode 100644 (file)
index 0000000..4d6bb14
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-svggen.jar differ
diff --git a/1.8/org.simantics.jfreechart/batik/batik-util.jar b/1.8/org.simantics.jfreechart/batik/batik-util.jar
new file mode 100644 (file)
index 0000000..86d75e7
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-util.jar differ
diff --git a/1.8/org.simantics.jfreechart/batik/batik-xml.jar b/1.8/org.simantics.jfreechart/batik/batik-xml.jar
new file mode 100644 (file)
index 0000000..d05eb25
Binary files /dev/null and b/1.8/org.simantics.jfreechart/batik/batik-xml.jar differ
diff --git a/1.8/org.simantics.jfreechart/build.properties b/1.8/org.simantics.jfreechart/build.properties
new file mode 100644 (file)
index 0000000..3806e2b
--- /dev/null
@@ -0,0 +1,14 @@
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               plugin.xml,\\r
+               adapters.xml,\\r
+               icons/,\\r
+               batik/batik-awt-util.jar,\\r
+               batik/batik-dom.jar,\\r
+               batik/batik-ext.jar,\\r
+               batik/batik-svg-dom.jar,\\r
+               batik/batik-svggen.jar,\\r
+               batik/batik-util.jar,\\r
+               batik/batik-xml.jar\r
diff --git a/1.8/org.simantics.jfreechart/icons/chart_bar_light.png b/1.8/org.simantics.jfreechart/icons/chart_bar_light.png
new file mode 100644 (file)
index 0000000..6069b5c
Binary files /dev/null and b/1.8/org.simantics.jfreechart/icons/chart_bar_light.png differ
diff --git a/1.8/org.simantics.jfreechart/icons/chart_line_light.png b/1.8/org.simantics.jfreechart/icons/chart_line_light.png
new file mode 100644 (file)
index 0000000..2a77b24
Binary files /dev/null and b/1.8/org.simantics.jfreechart/icons/chart_line_light.png differ
diff --git a/1.8/org.simantics.jfreechart/icons/chart_pie_light.png b/1.8/org.simantics.jfreechart/icons/chart_pie_light.png
new file mode 100644 (file)
index 0000000..fa553c2
Binary files /dev/null and b/1.8/org.simantics.jfreechart/icons/chart_pie_light.png differ
diff --git a/1.8/org.simantics.jfreechart/icons/close.gif b/1.8/org.simantics.jfreechart/icons/close.gif
new file mode 100644 (file)
index 0000000..1aca259
Binary files /dev/null and b/1.8/org.simantics.jfreechart/icons/close.gif differ
diff --git a/1.8/org.simantics.jfreechart/icons/maximize.gif b/1.8/org.simantics.jfreechart/icons/maximize.gif
new file mode 100644 (file)
index 0000000..5e5999b
Binary files /dev/null and b/1.8/org.simantics.jfreechart/icons/maximize.gif differ
diff --git a/1.8/org.simantics.jfreechart/icons/minimize.gif b/1.8/org.simantics.jfreechart/icons/minimize.gif
new file mode 100644 (file)
index 0000000..7402dc9
Binary files /dev/null and b/1.8/org.simantics.jfreechart/icons/minimize.gif differ
diff --git a/1.8/org.simantics.jfreechart/plugin.xml b/1.8/org.simantics.jfreechart/plugin.xml
new file mode 100644 (file)
index 0000000..9db7546
--- /dev/null
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<?eclipse version="3.4"?>\r
+<plugin>\r
+   <extension\r
+         point="org.eclipse.ui.views">\r
+      <view\r
+            category="org.simantics.sysdyn.ui.category"\r
+            class="org.simantics.jfreechart.ChartPanel"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"\r
+            id="org.simantics.jfreechart.chartPanel"\r
+            name="Chart Panel"\r
+            restorable="true">\r
+      </view>\r
+   </extension>\r
+\r
+</plugin>\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartDropTarget.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartDropTarget.java
new file mode 100644 (file)
index 0000000..a218ada
--- /dev/null
@@ -0,0 +1,77 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart;\r
+\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.dnd.DND;\r
+import org.eclipse.swt.dnd.DropTargetAdapter;\r
+import org.eclipse.swt.dnd.DropTargetEvent;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.simantics.db.Resource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Drop target for dropping charts in chart panel\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartDropTarget extends DropTargetAdapter {\r
+    \r
+    private Composite separator;\r
+    private ChartPanelElement element;\r
+    private Display display;\r
+    private ChartPanel panel;\r
+    \r
+    public ChartDropTarget(Composite separator, ChartPanelElement element, ChartPanel panel) {\r
+        this.separator = separator;\r
+        this.display = separator.getDisplay();\r
+        this.element = element;\r
+        this.panel = panel;\r
+    }\r
+    \r
+\r
+\r
+    /**\r
+     * Display effect on the composite when drag entered\r
+     */\r
+    @Override\r
+    public void dragEnter(DropTargetEvent event) {\r
+        if ((event.operations & DND.DROP_COPY) != 0) {\r
+            event.detail = DND.DROP_COPY;\r
+        } else if ((event.operations & DND.DROP_MOVE) != 0) {\r
+            event.detail = DND.DROP_MOVE;\r
+        } else {\r
+            event.detail = DND.DROP_NONE;\r
+        }\r
+        separator.setBackground(display.getSystemColor(SWT.COLOR_DARK_GRAY));\r
+    }\r
+\r
+    /**\r
+     * Revert effect when drag leaves\r
+     */\r
+    @Override\r
+    public void dragLeave(DropTargetEvent event) { \r
+        separator.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));\r
+    }\r
+\r
+    /**\r
+     * Drop the data to chart panel\r
+     */\r
+    @Override\r
+    public void drop(DropTargetEvent event) {\r
+        Resource chartResource = AdaptionUtils.adaptToSingle(event.data, Resource.class);\r
+        if(chartResource != null)\r
+            panel.addChart(chartResource, element);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanel.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanel.java
new file mode 100644 (file)
index 0000000..a698efe
--- /dev/null
@@ -0,0 +1,471 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart;\r
+\r
+import java.util.ArrayList;\r
+import java.util.LinkedHashMap;\r
+\r
+import org.eclipse.jface.dialogs.IDialogSettings;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.dnd.DND;\r
+import org.eclipse.swt.dnd.DropTarget;\r
+import org.eclipse.swt.dnd.DropTargetAdapter;\r
+import org.eclipse.swt.dnd.DropTargetEvent;\r
+import org.eclipse.swt.dnd.Transfer;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.graphics.Rectangle;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.ui.IMemento;\r
+import org.eclipse.ui.IViewSite;\r
+import org.eclipse.ui.PartInitException;\r
+import org.eclipse.ui.part.ViewPart;\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.AsyncListener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.internal.Activator;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.dnd.LocalObjectTransfer;\r
+import org.simantics.utils.RunnableWithObject;\r
+\r
+/**\r
+ * Chart panel displays multiple charts in a single view. The view can be oriented \r
+ * vertically or horizontally, the default is vertical. Charts can be added, removed \r
+ * minimized or expanded. The order of the charts can be changed by dragging the charts.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartPanel extends ViewPart {\r
+\r
+    private Composite body;\r
+    private ScrolledComposite sc;\r
+\r
+    private IDialogSettings settings;\r
+    private LinkedHashMap<Resource, ChartPanelElement> charts;\r
+    private ArrayList<Resource> minimizedResources;\r
+\r
+    private ArrayList<ChartPanelElement> chartElements;\r
+\r
+    public static final String CHART_PANEL_SETTINGS = "CHART_PANEL_SETTINGS";\r
+    public static final String CHARTS = "CHART_PANEL_CHARTS";\r
+    public static final String MINIMIZED_CHARTS = "CHART_PANEL_MINIMIZED_CHARTS";\r
+    public static final String CHART_PANEL_ORIENTATION = "CHART_PANEL_ORIENTATION";\r
+\r
+    public static final String CHART_PANEL_VERTICAL = "CHART_PANEL_ORIENTATION_VERTICAL";\r
+    public static final String CHART_PANEL_HORIZONTAL = "CHART_PANEL_ORIENTATION_HORIZONTAL";\r
+\r
+    private boolean vertical = true;\r
+\r
+    /**\r
+     * Initialize the view. Load charts that have previously been open (if there are any).\r
+     */\r
+    @Override\r
+    public void init(IViewSite site, IMemento memento) throws PartInitException {\r
+        super.init(site, memento);\r
+\r
+        minimizedResources = new ArrayList<Resource>();\r
+\r
+        settings = Activator.getDefault().getDialogSettings().getSection(CHART_PANEL_SETTINGS);\r
+\r
+        // Initialize settings if there are no settings\r
+        if (settings == null) {\r
+            settings = Activator.getDefault().getDialogSettings().addNewSection(CHART_PANEL_SETTINGS);\r
+        }\r
+\r
+        if(settings.getArray(CHARTS) == null) {\r
+            String[] chartUris = new String[] {};\r
+            settings.put(CHARTS, chartUris);\r
+        }\r
+\r
+        if(settings.getArray(MINIMIZED_CHARTS) == null) {\r
+            String[] minimizedChartUris = new String[] {};\r
+            settings.put(MINIMIZED_CHARTS, minimizedChartUris);\r
+        }\r
+\r
+        // initialize chart lists\r
+        charts = new LinkedHashMap<Resource, ChartPanelElement>();\r
+\r
+        // add chart resources to chart lists from settings\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new ReadRequest() {\r
+\r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                    Resource chart = null;\r
+                    String[] chartURIs = settings.getArray(CHARTS);\r
+                    for(String uri : chartURIs) {\r
+                        chart = graph.getPossibleResource(uri);\r
+                        if(chart != null && graph.isInstanceOf(chart, jfree.Chart)) {\r
+                            charts.put(chart, null);\r
+                            setChartExistingListener(chart);\r
+                        }\r
+                    }\r
+\r
+                    String[] minimizedUris = settings.getArray(MINIMIZED_CHARTS);\r
+                    for(String uri : minimizedUris) {\r
+                        chart = graph.getPossibleResource(uri);\r
+                        if(chart != null && graph.isInstanceOf(chart, jfree.Chart)) {\r
+                            minimizedResources.add(chart);\r
+                        } \r
+                    }\r
+                }\r
+            });\r
+        } catch (DatabaseException e1) {\r
+            e1.printStackTrace();\r
+        }\r
+\r
+        // set the orientation of the panel\r
+        String orientation = settings.get(CHART_PANEL_ORIENTATION);\r
+        if(CHART_PANEL_VERTICAL.equals(orientation))\r
+            this.vertical = true;\r
+        else if(CHART_PANEL_HORIZONTAL.equals(orientation))\r
+            this.vertical = false;\r
+\r
+    }\r
+\r
+    /**\r
+     * Create a scrolled composite that will contain all the charts, then call the actual \r
+     * content creator.\r
+     */\r
+    @Override\r
+    public void createPartControl(Composite parent) {\r
+        sc = new ScrolledComposite(parent, SWT.NONE | SWT.H_SCROLL | SWT.V_SCROLL);\r
+        GridLayoutFactory.fillDefaults().spacing(0, 0).applyTo(sc);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);\r
+        sc.getVerticalBar().setIncrement(sc.getVerticalBar().getIncrement()*3);\r
+        sc.getHorizontalBar().setIncrement(sc.getHorizontalBar().getIncrement()*3);\r
+\r
+        body = new Composite(sc, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().margins(3, 0).spacing(0, 0).applyTo(body);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(body);\r
+\r
+        sc.setContent(body);\r
+        createContents();\r
+        \r
+        setupDropTarget();\r
+\r
+    }\r
+    \r
+    /**\r
+     * Creates the contents of this chart panel.\r
+     * Removes all old contents before creating new content\r
+     */\r
+    private void createContents() {\r
+        chartElements = new ArrayList<ChartPanelElement>();\r
+\r
+        for(Control child : body.getChildren()) {\r
+            child.dispose();\r
+        }\r
+        \r
+        // Set the initial layout\r
+        ElementContainer elementHolder;\r
+        for(Resource e : charts.keySet()) {\r
+            elementHolder = new ElementContainer(body, SWT.NONE);\r
+            elementHolder.setBackground(new Color(elementHolder.getDisplay(), 255, 0, 0));\r
+            ChartPanelElement element = new ChartPanelElement(elementHolder, this, e, SWT.NONE);\r
+            elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)element.getLayout()));\r
+            chartElements.add(element);\r
+            charts.put(e, element);\r
+            if(minimizedResources.contains(e)) {\r
+                element.toggleMinimize();\r
+            }\r
+        }\r
+\r
+        elementHolder = new ElementContainer(body, SWT.NONE);\r
+        elementHolder.setBackground(new Color(elementHolder.getDisplay(), 0, 255, 0));\r
+        ChartPanelElement element = new ChartPanelElement(elementHolder, this, null, SWT.NONE); // Last element is empty -> only the separator\r
+        elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)element.getLayout()));\r
+        chartElements.add(element);\r
+\r
+        layout();\r
+        saveState();\r
+\r
+    }\r
+\r
+    /**\r
+     * Lays out this panel (the body composite)\r
+     */\r
+    public void layout() {\r
+        if(vertical) {\r
+            GridLayoutFactory.fillDefaults().spacing(0, 0).applyTo(body);\r
+            GridDataFactory.fillDefaults().grab(true, true).applyTo(body);\r
+        } else {\r
+            // Need to calculate horizontal elements for gridLayout\r
+            int chartPanels = chartElements.size();\r
+            GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(chartPanels).applyTo(body);\r
+            GridDataFactory.fillDefaults().grab(true, true).applyTo(body);\r
+        }\r
+        body.layout();\r
+        sc.setMinSize(body.computeSize(SWT.DEFAULT, SWT.DEFAULT));\r
+    }\r
+\r
+    @Override\r
+    public void setFocus() {\r
+        if(!sc.isDisposed())\r
+            sc.setFocus();\r
+    }\r
+\r
+    @Override\r
+    public void saveState(IMemento memento) {\r
+        super.saveState(memento);\r
+        saveState();\r
+    }\r
+\r
+    /**\r
+     * Save the current state of the view to IDialogSettings \r
+     */\r
+    public void saveState() {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new ReadRequest() {\r
+\r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                    if (settings != null) {\r
+                        String[] uris = new String[chartElements.size() - 1];\r
+                        ArrayList<String> minimized = new ArrayList<String>();\r
+                        minimizedResources.clear();\r
+                        for(int i = 0; i < uris.length; i++) {\r
+                            ChartPanelElement e = chartElements.get(i);\r
+                            Resource r = e.getResource();\r
+                            if(r != null) {\r
+                                uris[i] = graph.getURI(r);\r
+                                if(e.isMinimized()) {\r
+                                    minimized.add(uris[i]);\r
+                                    minimizedResources.add(r);\r
+                                }\r
+                            } else {\r
+                                uris[i] = "";\r
+                            }\r
+                        }\r
+                        settings.put(CHARTS, uris);\r
+                        if(!minimized.isEmpty())\r
+                            settings.put(MINIMIZED_CHARTS, minimized.toArray(new String[minimized.size()]));\r
+                        else\r
+                            settings.put(MINIMIZED_CHARTS, new String[0]);\r
+\r
+                        if(vertical)\r
+                            settings.put(CHART_PANEL_ORIENTATION, CHART_PANEL_VERTICAL);\r
+                        else\r
+                            settings.put(CHART_PANEL_ORIENTATION, CHART_PANEL_HORIZONTAL);\r
+                    }\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Set the orientation for this chart panel.\r
+     * \r
+     * @param orientation Orientation (ChartPanel.CHART_PANEL_VERTICAL or ChartPanel.CHART_PANEL_HORIZONTAL)\r
+     */\r
+    public void setOrientation(String orientation) {\r
+        if(CHART_PANEL_VERTICAL.equals(orientation))\r
+            this.vertical = true;\r
+        else {\r
+            this.vertical = false;\r
+        }\r
+        createContents();\r
+    }\r
+\r
+    /**\r
+     * Removes a chart from this panel\r
+     * \r
+     * @param chart The chart to be removed\r
+     */\r
+    public void removeChart(Resource chart) {\r
+        ChartPanelElement element = charts.get(chart);\r
+        chartElements.remove(element);\r
+        element.getParent().dispose();\r
+        charts.remove(chart);\r
+        minimizedResources.remove(chart);\r
+        saveState();\r
+        layout();\r
+    }\r
+\r
+    /**\r
+     * Sets up drag-scrolling for a scrolled composite \r
+     * \r
+     * @param control\r
+     */\r
+    protected void setupDropTarget() {\r
+        DropTarget target = new DropTarget(sc, DND.DROP_MOVE);\r
+        target.setTransfer(new Transfer[] { LocalObjectTransfer.getTransfer() });\r
+\r
+        target.addDropListener(new DropTargetAdapter() {\r
+\r
+            private int activeMargin = 20;\r
+            private int moveAmount = 1;\r
+\r
+            @Override\r
+            public void dragOver(DropTargetEvent event) { \r
+                Point original = sc.getOrigin();\r
+                Point origin = sc.getOrigin();\r
+                Point pointer = sc.toControl(event.x, event.y);\r
+                Rectangle bounds = sc.getBounds();\r
+\r
+                if(pointer.y < activeMargin)\r
+                    origin.y = origin.y - moveAmount;\r
+                else if(bounds.height - pointer.y < activeMargin)\r
+                    origin.y = origin.y + moveAmount;\r
+                if(pointer.x < activeMargin)\r
+                    origin.x = origin.x - moveAmount;\r
+                else if(bounds.width - pointer.x < activeMargin)\r
+                    origin.x = origin.x + moveAmount;\r
+\r
+                if(origin != original) {\r
+                    sc.setOrigin (origin.x, origin.y);\r
+                    sc.redraw();\r
+                }\r
+            }\r
+\r
+        });\r
+        \r
+        DropTarget target2 = new DropTarget(body, DND.DROP_COPY | DND.DROP_MOVE);\r
+        target2.setTransfer(new Transfer[] {  LocalObjectTransfer.getTransfer() });\r
+        target2.addDropListener(new ChartDropTarget(body, null, this));\r
+\r
+    }\r
+\r
+    /**\r
+     * Is the panel vertically oriented\r
+     * @return Is the panel vertically oriented\r
+     */\r
+    public boolean isVertical() {\r
+        return vertical;\r
+    }\r
+    \r
+    /**\r
+     * Adds chart after given element. If element == null, adds chart to the top.\r
+     * \r
+     * @param element To which place the chart will be placed. (null allowed)\r
+     */\r
+    public void addChart(Resource chartResource, ChartPanelElement element) {\r
+        addChart(chartResource, element, true);\r
+    }\r
+\r
+    /**\r
+     * Adds chart after given element. If element == null, adds chart to the top.\r
+     * \r
+     * @param element To which place the chart will be placed. (null allowed)\r
+     * @param layout refresh layout. use with vertical layout. \r
+     */\r
+    public void addChart(Resource chartResource, ChartPanelElement element, boolean layout) {\r
+        if(element == null)\r
+            element = chartElements.get(chartElements.size() - 1);\r
+        int index = chartElements.indexOf(element);\r
+        if(index >= 0) {\r
+            ChartPanelElement e = chartElements.get(index);\r
+            ChartPanelElement newElement;\r
+\r
+            if(charts.containsKey(chartResource)) {\r
+                // Old element being moved to a new place\r
+                newElement = charts.get(chartResource);\r
+                int oldIndex = chartElements.indexOf(newElement);\r
+                if(newElement.equals(element) || oldIndex == index - 1)\r
+                    return; // Not moving anywhere, do nothing\r
+                Composite oldParent = newElement.getParent();\r
+                newElement.setParent(e.getParent());\r
+                oldParent.dispose();\r
+                if(oldIndex < index)\r
+                    index--;\r
+                chartElements.remove(newElement);\r
+            } else {\r
+                newElement = new ChartPanelElement(e.getParent(), this, chartResource, SWT.NONE);\r
+            }\r
+\r
+            // Add a new chart element to the location of the old element\r
+            chartElements.add(index, newElement);\r
+            charts.put(chartResource, newElement);\r
+\r
+            ElementContainer elementHolder;\r
+            // Move elements back after index\r
+            for(int i = index + 1 /*indexes after the new element*/; i < chartElements.size(); i++) {\r
+                e = chartElements.get(i);\r
+                if(i == chartElements.size() - 1) {\r
+                    // last element (the empty element) element to a new container\r
+                    elementHolder = new ElementContainer(body, SWT.NONE);\r
+                    elementHolder.setBackground(new Color(elementHolder.getDisplay(), 0, 0, 255));\r
+                    elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)e.getLayout()));\r
+                    e.setParent(elementHolder);\r
+                } else {\r
+                    // element to the next elements container\r
+                    elementHolder = (ElementContainer)chartElements.get(i + 1).getParent();\r
+                    e.setParent(elementHolder);\r
+                }\r
+            }\r
+            \r
+            layout();\r
+            saveState();\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Set a listener to listen if the chart resource has been removed.\r
+     * If the resource has been removed, close also the chart element in this panel.\r
+     * \r
+     * @param chart Listened chart resource\r
+     */\r
+    private void setChartExistingListener(final Resource chart) {\r
+        SimanticsUI.getSession().asyncRequest(new Read<Boolean>() {\r
+\r
+            @Override\r
+            public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                return graph.hasStatement(chart);\r
+            }\r
+        }, new AsyncListener<Boolean>() {\r
+\r
+            boolean disposed = false;\r
+\r
+            @Override\r
+            public void execute(AsyncReadGraph graph, Boolean result) {\r
+                if(result != null && result == false && body != null && !body.isDisposed()) {\r
+                    body.getDisplay().asyncExec(new RunnableWithObject(chart){\r
+                        public void run() {\r
+                            removeChart((Resource)getObject());\r
+                        }\r
+                    }) ;\r
+                    disposed = true;\r
+                }\r
+            }\r
+\r
+            @Override\r
+            public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                throwable.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                return !disposed && !charts.containsKey(chart);\r
+            }\r
+        });\r
+    }\r
+\r
+    public ArrayList<ChartPanelElement> getElements() {\r
+        return chartElements;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelElement.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelElement.java
new file mode 100644 (file)
index 0000000..3102514
--- /dev/null
@@ -0,0 +1,193 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.dnd.DND;\r
+import org.eclipse.swt.dnd.DropTarget;\r
+import org.eclipse.swt.dnd.Transfer;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.db.Resource;\r
+import org.simantics.jfreechart.chart.ChartComposite;\r
+import org.simantics.ui.dnd.LocalObjectTransfer;\r
+\r
+/**\r
+ * This class represents an expanded chart element in {@link ChartPanel}. It contains \r
+ * a header {@link ChartPanelHeader} and the actual chart.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartPanelElement extends Composite {\r
+\r
+    public static int CHART_MINIMUM_WIDTH = 300;\r
+    public static int CHART_MINIMUM_HEIGHT = 200;\r
+\r
+    private ChartPanel panel;\r
+    private ChartComposite chartComposite;\r
+    private Resource chartResource;\r
+    private boolean minimized = false;\r
+\r
+    public Resource getResource() {\r
+        return chartResource;\r
+    }\r
+\r
+    @Override\r
+    public Object getLayoutData () {\r
+        checkWidget();\r
+        Object oldData = super.getLayoutData();\r
+        if(oldData == null || !(oldData instanceof GridData)) {\r
+            oldData = GridDataFactory.fillDefaults().create();\r
+        }\r
+\r
+        int size = panel.getElements().size();\r
+        GridData data = (GridData) oldData;\r
+        // Horizontal data\r
+        data.widthHint = CHART_MINIMUM_WIDTH;\r
+        if(getResource() == null && size == 1) {\r
+            data.grabExcessHorizontalSpace = true;\r
+        } else if(getResource() == null && !panel.isVertical()){\r
+            data.grabExcessHorizontalSpace = false;\r
+            data.widthHint = SWT.DEFAULT;\r
+        } else if(minimized && !panel.isVertical()) {\r
+            data.grabExcessHorizontalSpace = false;\r
+            data.widthHint = SWT.DEFAULT;\r
+        } else {\r
+            data.grabExcessHorizontalSpace = true;\r
+        }\r
+\r
+        // Vertical data\r
+        if(getResource() == null && size == 1) {\r
+            data.grabExcessVerticalSpace = true;\r
+        } else if(!minimized && getResource() != null) {\r
+            data.grabExcessVerticalSpace = true;\r
+            data.heightHint = CHART_MINIMUM_HEIGHT;\r
+        } else if(!panel.isVertical()){\r
+            data.grabExcessVerticalSpace = true;\r
+        } else {\r
+            data.grabExcessVerticalSpace = false;\r
+            data.heightHint = SWT.DEFAULT;\r
+        }\r
+        return data;\r
+    }\r
+\r
+    /**\r
+     * Creates an expanded chart panel element into parent composite.\r
+     * \r
+     * @param parent The parent composite where the chart element is created\r
+     * @param panel The {@link ChartPanel} containing the chart element\r
+     * @param name The name of the chart\r
+     * @param style The Style of the created chart element\r
+     */\r
+    public ChartPanelElement(Composite parent, ChartPanel panel, Resource chartResource, int style) {\r
+        this(parent, panel, chartResource, false, style);\r
+    }\r
+\r
+    /**\r
+     *  Creates a chart panel element into parent composite.\r
+     * @param parent The parent composite where the chart element is created\r
+     * @param panel The {@link ChartPanel} containing the chart element\r
+     * @param name The name of the chart\r
+     * @param minimized Is the chart-section minimized\r
+     * @param style The Style of the created chart element\r
+     */\r
+    public ChartPanelElement(Composite parent, ChartPanel panel, Resource chartResource, boolean minimized, int style) {\r
+        super(parent, style | SWT.NONE );\r
+        \r
+        this.panel = panel;\r
+        this.chartResource = chartResource;\r
+        this.minimized = minimized;\r
+\r
+        if(panel.isVertical() || getResource() == null)\r
+            GridLayoutFactory.fillDefaults().spacing(0,0).applyTo(this);\r
+        else\r
+            GridLayoutFactory.fillDefaults().numColumns(2).spacing(0,0).applyTo(this);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(this);\r
+\r
+        // Separator for dropping other elements\r
+        ChartPanelSeparator separator = new ChartPanelSeparator(this, panel, this, SWT.NONE);\r
+\r
+        if (chartResource != null) {\r
+            Composite c = new Composite(this, SWT.NONE);\r
+            GridDataFactory.fillDefaults().grab(true, true).applyTo(c);\r
+            GridLayoutFactory.fillDefaults().spacing(0, 0).applyTo(c);\r
+            // Header\r
+            new ChartPanelHeader(c, this, chartResource, SWT.BORDER);\r
+\r
+            // Chart\r
+            chartComposite = new ChartComposite(c, chartResource, SWT.BORDER);\r
+        }\r
+        \r
+        DropTarget target = new DropTarget(this, DND.DROP_COPY | DND.DROP_MOVE);\r
+        target.setTransfer(new Transfer[] {  LocalObjectTransfer.getTransfer() });\r
+        target.addDropListener(new ChartDropTarget(separator, this, panel));\r
+\r
+    }\r
+\r
+    /**\r
+     * Returns the chart resource associated with this element\r
+     * @return chart resource\r
+     */\r
+    public Resource getChartResource() {\r
+        return this.chartResource;\r
+    }\r
+\r
+    /**\r
+     * Returns the minimized state of this element\r
+     * @return is the element minimized\r
+     */\r
+    public boolean isMinimized() {\r
+        return minimized;\r
+    }\r
+\r
+    /**\r
+     * Change the minimized state of this element\r
+     */\r
+    public void toggleMinimize() {\r
+        toggleMinimize(false);\r
+    }\r
+    /**\r
+     * Change the minimized state of this element\r
+     */\r
+    public void toggleMinimize(boolean callSave) {\r
+        minimized = Boolean.FALSE.equals(minimized);\r
+        GridData data = (GridData) chartComposite.getLayoutData();\r
+        if(panel.isVertical())\r
+            data.exclude = minimized;\r
+        else\r
+            data.exclude = false;\r
+        chartComposite.setVisible(!minimized);\r
+\r
+        Composite parent = getParent();\r
+        data = (GridData) getLayoutData();\r
+        GridData parentData = (GridData)parent.getLayoutData();\r
+        parentData.grabExcessHorizontalSpace = data.grabExcessHorizontalSpace;\r
+        parentData.grabExcessVerticalSpace = data.grabExcessVerticalSpace;\r
+        parentData.heightHint = data.heightHint;\r
+\r
+        if(callSave) {\r
+            panel.saveState();\r
+        }\r
+        panel.layout();\r
+    }\r
+\r
+    /**\r
+     * Remove this chart panel element from its panel\r
+     */\r
+    public void remove() {\r
+        panel.removeChart(chartResource);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelHeader.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelHeader.java
new file mode 100644 (file)
index 0000000..5935c34
--- /dev/null
@@ -0,0 +1,397 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.dnd.DND;\r
+import org.eclipse.swt.dnd.DragSource;\r
+import org.eclipse.swt.dnd.DragSourceEvent;\r
+import org.eclipse.swt.dnd.DragSourceListener;\r
+import org.eclipse.swt.dnd.Transfer;\r
+import org.eclipse.swt.events.DisposeEvent;\r
+import org.eclipse.swt.events.DisposeListener;\r
+import org.eclipse.swt.events.PaintEvent;\r
+import org.eclipse.swt.events.PaintListener;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.GC;\r
+import org.eclipse.swt.graphics.Image;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Canvas;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.ToolBar;\r
+import org.eclipse.swt.widgets.ToolItem;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.internal.Activator;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.dnd.LocalObjectTransfer;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * Header of a chart element in {@link ChartPanel}. Only this header is\r
+ * shown if a chart is minimized. If a chart is expanded, this header is added\r
+ * to the charts {@link ChartPanelElement}. \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartPanelHeader extends Composite {\r
+\r
+    public static int HEADER_MINIMUM_WIDTH = 250;\r
+    private ChartPanelElement element;\r
+    private Resource resource;\r
+    private Label name;\r
+    private Canvas iconCanvas;\r
+    private Image icon;\r
+    private ToolItem minimize, remove;\r
+    private Color defaultColor, darker, evenDarker;\r
+    private Image gradientBackgroundImage, borderImage;\r
+\r
+    private static ImageDescriptor closeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/close.gif"));\r
+    private static Image closeImage = closeDescriptor.createImage();\r
+\r
+    private static ImageDescriptor minimizeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/minimize.gif"));\r
+    private static Image minimizeImage = minimizeDescriptor.createImage();\r
+\r
+    private static ImageDescriptor maximizeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/maximize.gif"));\r
+    private static Image maximizeImage = maximizeDescriptor.createImage();\r
+\r
+    private static ImageDescriptor lineChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_line_light.png"));\r
+    private static Image lineChartImage = lineChartDescriptor.createImage();\r
+\r
+    private static ImageDescriptor barChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_bar_light.png"));\r
+    private static Image barChartImage = barChartDescriptor.createImage();\r
+\r
+    private static ImageDescriptor pieChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_pie_light.png"));\r
+    private static Image pieChartImage = pieChartDescriptor.createImage();\r
+\r
+\r
+    /**\r
+     * Chart panel header with minimize and close buttons.\r
+     * \r
+     * @param parent The composite where the header is added\r
+     * @param panel The {@link ChartPanel} containing the header\r
+     * @param name The name of the chart\r
+     * @param style he Style of the created chart element\r
+     */\r
+    public ChartPanelHeader(Composite c, ChartPanelElement element, Resource chartResource, int style) {\r
+        super(c, style);\r
+        this.resource = chartResource;\r
+        this.element = element;\r
+\r
+        GridLayoutFactory.fillDefaults().margins(3, 0).numColumns(3).applyTo(this);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this);\r
+\r
+        // Colors\r
+\r
+        // Chart icon\r
+        iconCanvas = new Canvas (this, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).hint(16, 16).applyTo(iconCanvas);\r
+        iconCanvas.addPaintListener (new PaintListener() {\r
+\r
+            @Override\r
+            public void paintControl(PaintEvent e) {\r
+                if(icon != null)\r
+                    e.gc.drawImage (icon, 0, 0);                \r
+            }\r
+        });\r
+\r
+        // Label for the chart name (also minimize/expand)\r
+        name = new Label(this, SWT.NONE);\r
+\r
+        try {\r
+            // name updater\r
+            Pair<String, Image> result = SimanticsUI.getSession().syncRequest(new Read<Pair<String, Image>>() {\r
+\r
+                @Override\r
+                public Pair<String, Image> perform(ReadGraph graph) throws DatabaseException {\r
+                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    String label = graph.getPossibleRelatedValue(resource, l0.HasLabel);\r
+                    Image image = null;\r
+                    Resource plot = graph.syncRequest(new PossibleObjectWithType(resource, l0.ConsistsOf, jfree.Plot));\r
+                    if(plot != null) {\r
+                        if(graph.isInstanceOf(plot, jfree.CategoryPlot))\r
+                            image = barChartImage;\r
+                        else if(graph.isInstanceOf(plot, jfree.PiePlot))\r
+                            image = pieChartImage;\r
+                        else\r
+                            image = lineChartImage;\r
+                    }\r
+                    return new Pair<String, Image>(label, image);\r
+                }\r
+\r
+            }, new Listener<Pair<String, Image>>() {\r
+\r
+                @Override\r
+                public void execute(final Pair<String, Image> result) {\r
+                    if(result == null)\r
+                        return;\r
+\r
+                    name.getDisplay().asyncExec(new Runnable() {\r
+\r
+                        @Override\r
+                        public void run() {\r
+                            if(!name.isDisposed() && result.first != null)\r
+                                name.setText(result.first);\r
+\r
+                            if(!iconCanvas.isDisposed() && result.second != null) {\r
+                                icon = result.second;\r
+                                iconCanvas.redraw();\r
+                                ChartPanelHeader.this.layout();\r
+                            }\r
+                        }\r
+                    });\r
+                }\r
+\r
+                @Override\r
+                public void exception(Throwable t) {\r
+                    t.printStackTrace();\r
+                }\r
+\r
+                @Override\r
+                public boolean isDisposed() {\r
+                    return name.isDisposed();\r
+                }\r
+\r
+            });\r
+            name.setText(result.first);\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+            name.setText("No label");\r
+        }\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name);\r
+\r
+        ToolBar toolbar = new ToolBar(this, SWT.FLAT);\r
+        // item for minimizing/expanding chart\r
+        minimize = new ToolItem(toolbar, SWT.PUSH);\r
+        minimize.addSelectionListener(new MinimizeListener());\r
+        if(isMinimized()) {\r
+            minimize.setToolTipText("Expand");\r
+            minimize.setImage(maximizeImage);\r
+        } else {\r
+            minimize.setToolTipText("Minimize");\r
+            minimize.setImage(minimizeImage);\r
+        }\r
+\r
+        // item for closing/removing the chart\r
+        remove = new ToolItem(toolbar, SWT.PUSH);\r
+        remove.setImage(closeImage);\r
+        remove.addSelectionListener(new RemoveChartListener());\r
+        remove.setToolTipText("Remove");\r
+\r
+\r
+        /* ********************************\r
+         * DnD \r
+         * ********************************/\r
+\r
+        // Allow data to be copied or moved from the drag source\r
+        int operations = DND.DROP_MOVE;\r
+        source = new DragSource(name, operations);\r
+\r
+        // Provide data in Text format\r
+        Transfer[] types = new Transfer[] {  LocalObjectTransfer.getTransfer() };\r
+        source.setTransfer(types);\r
+        dragSourceListener = new DragSourceListener() {\r
+\r
+            @Override\r
+            public void dragStart(DragSourceEvent event) {\r
+                if(name.isDisposed())\r
+                    event.doit = false;\r
+                event.detail = DND.DROP_LINK;\r
+\r
+            }\r
+\r
+            @Override\r
+            public void dragSetData(DragSourceEvent event) {\r
+                event.data = new StructuredSelection(resource);\r
+            }\r
+\r
+            @Override\r
+            public void dragFinished(DragSourceEvent event) {\r
+            }\r
+        };  \r
+        source.addDragListener(dragSourceListener);\r
+\r
+        name.addDisposeListener(new DisposeListener() {\r
+\r
+            @Override\r
+            public void widgetDisposed(DisposeEvent e) {\r
+                if(dragSourceListener != null && source != null && !source.isDisposed()) {\r
+                    source.removeDragListener(dragSourceListener);\r
+                }                \r
+            }\r
+        });\r
+        this.setBackgroundImage(getGradientBackgroundImage());\r
+        this.setBackgroundMode(SWT.INHERIT_FORCE);\r
+\r
+        this.addListener(SWT.MouseEnter, new EnterListener());\r
+        this.addListener(SWT.MouseExit, new ExitListener());\r
+\r
+        for(Control child : this.getChildren()) {\r
+            child.addListener(SWT.MouseEnter, new EnterListener());\r
+            child.addListener(SWT.MouseExit, new ExitListener());\r
+\r
+        }\r
+    }\r
+\r
+    private class EnterListener implements  org.eclipse.swt.widgets.Listener {\r
+        public void handleEvent(Event event) {\r
+            ChartPanelHeader.this.setBackgroundImage(getHighlightedGradientBackgroundImage());\r
+        }\r
+    }\r
+\r
+    private class ExitListener implements  org.eclipse.swt.widgets.Listener {\r
+        public void handleEvent(Event event) {\r
+            ChartPanelHeader.this.setBackgroundImage(getGradientBackgroundImage());\r
+        }\r
+    }\r
+\r
+    private void createColors() {\r
+        if(defaultColor == null) {\r
+            defaultColor = getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);\r
+            try {\r
+                defaultColor = new Color(getDisplay(), defaultColor.getRed() + 500, defaultColor.getGreen() + 10, defaultColor.getBlue() + 10);\r
+            } catch (IllegalArgumentException e) {\r
+                // Do nothing, use the default color\r
+            }\r
+        }\r
+\r
+        if(darker == null) {\r
+            try {\r
+                darker = new Color(getDisplay(), defaultColor.getRed() - 30, defaultColor.getGreen() - 30, defaultColor.getBlue() - 30);\r
+            } catch (IllegalArgumentException e) {\r
+                // Do nothing, use the default color\r
+                darker = defaultColor;\r
+            }\r
+        }\r
+        \r
+        if(evenDarker == null) {\r
+            try {\r
+                evenDarker = new Color(getDisplay(), defaultColor.getRed() - 50, defaultColor.getGreen() - 50, defaultColor.getBlue() - 50);\r
+            } catch (IllegalArgumentException e) {\r
+                // Do nothing, use the default color\r
+                evenDarker = defaultColor;\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    private Image getHighlightedGradientBackgroundImage() {\r
+        createColors();\r
+        this.layout();\r
+        Point size = this.getSize();\r
+\r
+        borderImage = new Image(this.getDisplay(), 1, Math.max(1, size.y));\r
+        GC gc = new GC(borderImage);\r
+        gc.setForeground(defaultColor);\r
+        gc.setBackground(evenDarker);\r
+        gc.fillGradientRectangle(0, 0, 1, size.y, true);\r
+        gc.dispose();\r
+\r
+        return borderImage;\r
+    }\r
+\r
+    private Image getGradientBackgroundImage() {\r
+        createColors();\r
+        this.layout();\r
+        Point size = this.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        if(gradientBackgroundImage == null) {\r
+            gradientBackgroundImage = new Image(this.getDisplay(), 1, Math.max(1, size.y));\r
+            GC gc = new GC(gradientBackgroundImage);\r
+            gc.setForeground(defaultColor);\r
+            gc.setBackground(darker);\r
+            gc.fillGradientRectangle(0, 0, 1, size.y, true);\r
+            gc.dispose();\r
+        }\r
+\r
+        return gradientBackgroundImage;\r
+    }\r
+\r
+    private DragSourceListener dragSourceListener;\r
+    private DragSource source;\r
+\r
+    /**\r
+     * Return true if this element is minimized, false if expanded\r
+     * @return true if this element is minimized, false if expanded\r
+     */\r
+    private boolean isMinimized() {\r
+        return element.isMinimized();\r
+    }\r
+\r
+    /**\r
+     * Listener to minimize chart button. Expands and minimizes \r
+     * the chart of this header.\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class MinimizeListener implements SelectionListener {\r
+        @Override\r
+        public void widgetSelected(SelectionEvent e) {\r
+            if(ChartPanelHeader.this.isDisposed())\r
+                return;\r
+\r
+            element.toggleMinimize(true);\r
+\r
+            if(!name.isDisposed() && !minimize.isDisposed()) {\r
+                if(isMinimized()) {\r
+                    minimize.setToolTipText("Expand");\r
+                } else {\r
+                    minimize.setToolTipText("Minimize");\r
+                }\r
+            }            \r
+        }\r
+\r
+        @Override\r
+        public void widgetDefaultSelected(SelectionEvent e) {\r
+            widgetSelected(e);\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Listener for removing this chart from the chart panel.\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class RemoveChartListener implements SelectionListener {\r
+        @Override\r
+        public void widgetSelected(SelectionEvent e) {\r
+            if(!ChartPanelHeader.this.isDisposed()) {\r
+                element.remove();\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void widgetDefaultSelected(SelectionEvent e) {\r
+            widgetSelected(e);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelSeparator.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelSeparator.java
new file mode 100644 (file)
index 0000000..5f7e5e0
--- /dev/null
@@ -0,0 +1,87 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.events.MouseAdapter;\r
+import org.eclipse.swt.events.MouseEvent;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.widgets.Composite;\r
+\r
+/**\r
+ * Class for separating charts in {@link ChartPanel}. Acts as a drop participant for adding\r
+ * and moving charts in {@link ChartPanel}.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartPanelSeparator extends Composite {\r
+\r
+    private ChartPanel panel;\r
+\r
+    @Override\r
+    public Object getLayoutData() {\r
+        checkWidget();\r
+        Object oldData = super.getLayoutData();\r
+        if(oldData == null || !(oldData instanceof GridData)) {\r
+            oldData = GridDataFactory.fillDefaults().create();\r
+        }\r
+        GridData data = (GridData) oldData;\r
+        // Empty panel -> drop area the size of the whole panel\r
+        if(panel.getElements().size() == 1 && panel.getElements().get(0).getResource() == null) {\r
+            data.grabExcessHorizontalSpace = true;\r
+            data.grabExcessVerticalSpace = true;\r
+        }\r
+        else {\r
+            if(panel.isVertical()) { \r
+                data.grabExcessHorizontalSpace = true;\r
+                data.grabExcessVerticalSpace = false;\r
+            } else {\r
+                data.grabExcessHorizontalSpace = false;\r
+                data.grabExcessVerticalSpace = true;\r
+            }\r
+        }\r
+        return data;\r
+    }\r
+\r
+    /**\r
+     * Set up a small horizontal or vertical separator depending on SWT style\r
+     * \r
+     * @param parent\r
+     * @param style\r
+     */\r
+    public ChartPanelSeparator(Composite parent, ChartPanel panel, ChartPanelElement element, int style) {\r
+        super(parent, style);\r
+        GridLayoutFactory.fillDefaults().margins(2, 2).applyTo(this);\r
+        GridDataFactory.fillDefaults().applyTo(this);\r
+        this.panel = panel;\r
+        addMouseListener(new SCFocusListener(panel));\r
+    }\r
+\r
+\r
+    /**\r
+     * Listener for directing focus to scrollableComposite\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class SCFocusListener extends MouseAdapter {\r
+        ChartPanel panel;\r
+        public SCFocusListener(ChartPanel panel) {\r
+            this.panel = panel;\r
+        }\r
+        public void mouseDown(MouseEvent e) {\r
+            panel.setFocus();\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPropertyOptions.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPropertyOptions.java
new file mode 100644 (file)
index 0000000..4b6314e
--- /dev/null
@@ -0,0 +1,8 @@
+package org.simantics.jfreechart;\r
+\r
+public class ChartPropertyOptions {\r
+       \r
+       public static final int SHOW_TIME   = 1 << 0;\r
+       public static final int SHOW_FILTER = 1 << 1;\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartSelectionTabContributor.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartSelectionTabContributor.java
new file mode 100644 (file)
index 0000000..f8b0d76
--- /dev/null
@@ -0,0 +1,162 @@
+package org.simantics.jfreechart;\r
+\r
+import java.util.Collection;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.jfreechart.chart.properties.ChartTab;\r
+import org.simantics.jfreechart.chart.properties.bar.BarAxisTab;\r
+import org.simantics.jfreechart.chart.properties.bar.BarGeneralPropertiesTab;\r
+import org.simantics.jfreechart.chart.properties.bar.BarSeriesTab;\r
+import org.simantics.jfreechart.chart.properties.bar.BarSeriesTab2;\r
+import org.simantics.jfreechart.chart.properties.pie.PieGeneralPropertiesTab;\r
+import org.simantics.jfreechart.chart.properties.pie.PieSeriesTab;\r
+import org.simantics.jfreechart.chart.properties.pie.PieSeriesTab2;\r
+import org.simantics.jfreechart.chart.properties.xyline.XYLineAxisAndVariablesTab;\r
+import org.simantics.jfreechart.chart.properties.xyline.XYLineGeneralPropertiesTab;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.selectionview.ComparableTabContributor;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+public class ChartSelectionTabContributor {\r
+\r
+       public static boolean contibuteTabs(ReadGraph backend, Resource r, List<ComparableTabContributor> tabs) throws DatabaseException{\r
+               return contibuteTabs(backend, r, tabs, ChartPropertyOptions.SHOW_TIME);\r
+       }\r
+       public static boolean contibuteTabs(ReadGraph backend, Resource r, List<ComparableTabContributor> tabs, int options) throws DatabaseException {\r
+               JFreeChartResource jfree = JFreeChartResource.getInstance(backend);\r
+               if(backend.isInstanceOf(r, jfree.ChartElement)) {\r
+            if(backend.hasStatement(r, jfree.ChartElement_component))\r
+                r = backend.getSingleObject(r, jfree.ChartElement_component);\r
+        }\r
+               \r
+               if (backend.isInstanceOf(r, jfree.Chart)) {\r
+\r
+             Collection<Resource> plots = backend.syncRequest(new ObjectsWithType(r, Layer0.getInstance(backend).ConsistsOf, jfree.Plot));\r
+             if(!plots.isEmpty()) {\r
+                 Resource plot = plots.iterator().next();\r
+\r
+                 if(backend.isInstanceOf(plot, jfree.XYPlot)) {\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new XYLineGeneralPropertiesTab(),\r
+                             10,\r
+                             r,\r
+                             "General"));\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new XYLineAxisAndVariablesTab(),\r
+                             9,\r
+                             r,\r
+                             "Axis and Variables"));\r
+                 } else if(backend.isInstanceOf(plot, jfree.CategoryPlot)) {\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new BarGeneralPropertiesTab(options),\r
+                             10,\r
+                             r,\r
+                             "General"));\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new BarSeriesTab(options),\r
+                             9,\r
+                             r,\r
+                             "Variables"));\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new BarAxisTab(),\r
+                             8,\r
+                             r,\r
+                             "Axis"));                        \r
+                 } else if(backend.isInstanceOf(plot, jfree.PiePlot)) {\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new PieGeneralPropertiesTab(options),\r
+                             10,\r
+                             r,\r
+                             "General"));\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new PieSeriesTab(options),\r
+                             9,\r
+                             r,\r
+                             "Variables"));\r
+                 }\r
+\r
+                 tabs.add(new ComparableTabContributor(\r
+                         new ChartTab(),\r
+                         1,\r
+                         r,\r
+                         "Chart"));\r
+                \r
+                 return true;\r
+             } \r
+         }\r
+               return false;\r
+       }\r
+       \r
+       public static boolean contibuteTabs2(ReadGraph backend, Resource r, List<ComparableTabContributor> tabs) throws DatabaseException{\r
+               return contibuteTabs2(backend, r, tabs, ChartPropertyOptions.SHOW_TIME);\r
+       }\r
+       \r
+       public static boolean contibuteTabs2(ReadGraph backend, Resource r, List<ComparableTabContributor> tabs, int options) throws DatabaseException {\r
+               JFreeChartResource jfree = JFreeChartResource.getInstance(backend);\r
+               if(backend.isInstanceOf(r, jfree.ChartElement)) {\r
+            if(backend.hasStatement(r, jfree.ChartElement_component))\r
+                r = backend.getSingleObject(r, jfree.ChartElement_component);\r
+        }\r
+               \r
+               if (backend.isInstanceOf(r, jfree.Chart)) {\r
+\r
+             Collection<Resource> plots = backend.syncRequest(new ObjectsWithType(r, Layer0.getInstance(backend).ConsistsOf, jfree.Plot));\r
+             if(!plots.isEmpty()) {\r
+                 Resource plot = plots.iterator().next();\r
+\r
+                 if(backend.isInstanceOf(plot, jfree.XYPlot)) {\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new XYLineGeneralPropertiesTab(),\r
+                             10,\r
+                             r,\r
+                             "General"));\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new XYLineAxisAndVariablesTab(),\r
+                             9,\r
+                             r,\r
+                             "Axis and Variables"));\r
+                 } else if(backend.isInstanceOf(plot, jfree.CategoryPlot)) {\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new BarGeneralPropertiesTab(options),\r
+                             10,\r
+                             r,\r
+                             "General"));\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new BarSeriesTab2(options),\r
+                             9,\r
+                             r,\r
+                             "Variables"));\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new BarAxisTab(),\r
+                             8,\r
+                             r,\r
+                             "Axis"));                        \r
+                 } else if(backend.isInstanceOf(plot, jfree.PiePlot)) {\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new PieGeneralPropertiesTab(options),\r
+                             10,\r
+                             r,\r
+                             "General"));\r
+                     tabs.add(new ComparableTabContributor(\r
+                             new PieSeriesTab2(options),\r
+                             9,\r
+                             r,\r
+                             "Variables"));\r
+                 }\r
+\r
+                 tabs.add(new ComparableTabContributor(\r
+                         new ChartTab(),\r
+                         1,\r
+                         r,\r
+                         "Chart"));\r
+                \r
+                 return true;\r
+             } \r
+         }\r
+               return false;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ElementContainer.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/ElementContainer.java
new file mode 100644 (file)
index 0000000..3775360
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+\r
+/**\r
+ * Container for a chart panel element. Needed for\r
+ * moving chart panel elements around using setParent()\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ElementContainer extends Composite {\r
+\r
+    @Override\r
+    public Object getLayoutData () {\r
+        Control[] children = getChildren();\r
+        if(children.length == 1) {\r
+            if(children[0] instanceof ChartPanelElement) {\r
+                ChartPanelElement element = (ChartPanelElement)children[0];\r
+                return element.getLayoutData();\r
+            }\r
+        }\r
+        return super.getLayoutData();\r
+    }\r
+    \r
+    public ElementContainer(Composite parent, int style) {\r
+        super(parent, style);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractAxis.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractAxis.java
new file mode 100644 (file)
index 0000000..4439a9c
--- /dev/null
@@ -0,0 +1,94 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import java.awt.Color;\r
+\r
+import org.jfree.chart.axis.Axis;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Abstract axis class for all JFreeChart axis\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public abstract class AbstractAxis implements IAxis {\r
+\r
+    protected Axis axis;\r
+    protected String label;\r
+    protected Boolean tMarksVisible, tLabelsVisible, labelVisible, lineVisible;\r
+    protected Color color;\r
+    protected Double min, max, rotate;\r
+\r
+    /**\r
+     * Creates a new axis\r
+     * @param graph ReadGraph\r
+     * @param axisResource resource of type JFreeChart.NumberAxis\r
+     */\r
+    public AbstractAxis(ReadGraph graph, Resource axisResource) {\r
+        try {\r
+            /*\r
+             *  Axis is practically always called from a listener, \r
+             *  so it is safe to always create a new axis every time. \r
+             *  \r
+             *  The parent listener takes care that the axis is updated. \r
+             *  (And the code stays much more readable)\r
+             */\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            label = graph.getPossibleRelatedValue(axisResource, l0.HasLabel);\r
+            tMarksVisible = graph.getPossibleRelatedValue(axisResource, jfree.Axis_visibleTickMarks, Bindings.BOOLEAN);\r
+            tLabelsVisible = graph.getPossibleRelatedValue(axisResource, jfree.Axis_visibleTickLabels, Bindings.BOOLEAN);\r
+            labelVisible = graph.getPossibleRelatedValue(axisResource, jfree.Axis_visibleLabel, Bindings.BOOLEAN);\r
+            lineVisible = graph.getPossibleRelatedValue(axisResource, jfree.Axis_visibleAxisLine, Bindings.BOOLEAN);\r
+            Resource c = graph.getPossibleObject(axisResource, jfree.color);\r
+            color = c == null ? null : G2DUtils.getColor(graph, c);\r
+            min = graph.getPossibleRelatedValue(axisResource, jfree.Axis_min, Bindings.DOUBLE);\r
+            max = graph.getPossibleRelatedValue(axisResource, jfree.Axis_max, Bindings.DOUBLE);\r
+            rotate = graph.getPossibleRelatedValue(axisResource, jfree.Axis_rotateLabelDegrees, Bindings.DOUBLE);\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void dispose() {\r
+        \r
+    }\r
+\r
+    @Override\r
+    public Axis getAxis() {\r
+        if(tMarksVisible != null && tMarksVisible == false)\r
+            axis.setTickMarksVisible(false);\r
+        if(tLabelsVisible != null && tLabelsVisible == false)\r
+            axis.setTickLabelsVisible(false);\r
+        if(lineVisible != null && lineVisible == false)\r
+            axis.setAxisLineVisible(false);\r
+        \r
+        if(color != null) {\r
+            axis.setAxisLinePaint(color);\r
+            axis.setLabelPaint(color);\r
+            axis.setTickLabelPaint(color);\r
+            axis.setTickMarkPaint(color);\r
+        }\r
+        // label exists and its visibility == null or true\r
+        if((labelVisible == null || labelVisible == true) && label != null)\r
+            axis.setLabel(label);\r
+        return axis;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractDataset.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractDataset.java
new file mode 100644 (file)
index 0000000..2207259
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+\r
+/**\r
+ * Abstract dataset class for all JFreeChart datasets\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public abstract class AbstractDataset implements IDataset {\r
+\r
+    protected Resource resource;\r
+    \r
+    public AbstractDataset(ReadGraph graph, Resource resource) throws DatabaseException {\r
+        this.resource = resource;\r
+    }\r
+    \r
+    @Override\r
+    public void dispose() {\r
+        \r
+    }\r
+\r
+    @Override\r
+    public Resource getResource() {\r
+        return resource;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractPlot.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractPlot.java
new file mode 100644 (file)
index 0000000..ebfba89
--- /dev/null
@@ -0,0 +1,219 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import javax.swing.SwingUtilities;\r
+\r
+import org.jfree.chart.axis.Axis;\r
+import org.jfree.chart.plot.Plot;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Abstract plot class for all JFreeChart plots\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public abstract class AbstractPlot implements IPlot {\r
+\r
+    protected Resource resource;\r
+    protected Plot plot;\r
+    protected PlotProperties currentProperties;\r
+    private PlotPropertyListener listener;\r
+\r
+\r
+    public AbstractPlot(ReadGraph graph, Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        if(currentProperties != null) {\r
+            for(IAxis axis : currentProperties.ranges)\r
+                axis.dispose();\r
+\r
+            for(IAxis axis : currentProperties.domains)\r
+                axis.dispose();\r
+\r
+            for(IDataset dataset : currentProperties.datasets)\r
+                dataset.dispose();\r
+        }\r
+        if(listener != null)\r
+            listener.dispose();\r
+    }\r
+\r
+    @Override\r
+    public Resource getResource() {\r
+        return resource;\r
+    }\r
+\r
+    protected abstract Plot newPlot();\r
+    protected abstract void setPlotProperties(PlotProperties properties);\r
+    protected abstract void getOtherProperties(ReadGraph graph, PlotProperties properties) throws DatabaseException;\r
+\r
+    @Override\r
+    public Plot getPlot() {\r
+        if(plot == null)\r
+            plot = newPlot();\r
+\r
+        if(listener == null || listener.isDisposed()) {\r
+            listener = new PlotPropertyListener();\r
+            SimanticsUI.getSession().asyncRequest(new Read<PlotProperties>() {\r
+\r
+                @Override\r
+                public PlotProperties perform(ReadGraph graph) throws DatabaseException {\r
+\r
+                    PlotProperties properties = new PlotProperties();\r
+\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+                    HashMap<Resource, IAxis> axisMap = new HashMap<Resource, IAxis>();\r
+\r
+                    // Get all range axis\r
+                    Resource rangeList = graph.getPossibleObject(resource, jfree.Plot_rangeAxisList);\r
+                    if(rangeList != null) {\r
+                        for(Resource axisResource : ListUtils.toList(graph, rangeList)) {\r
+                            IAxis axis = graph.adapt(axisResource, IAxis.class);\r
+                            if(axis.getAxis() instanceof Axis) {\r
+                                properties.ranges.add(axis);\r
+                                axisMap.put(axisResource, axis);\r
+                            }\r
+                        }\r
+                    }\r
+\r
+                    // Get all domain axis\r
+                    // There usually is only one domain axis, but this supports also multiple domain axis\r
+                    for(Resource axisResource : graph.syncRequest(new ObjectsWithType(resource, jfree.Plot_domainAxis, jfree.Axis))) {\r
+                        IAxis axis = graph.adapt(axisResource, IAxis.class);\r
+                        if(axis.getAxis() instanceof Axis) {\r
+                            properties.domains.add(axis);\r
+                            axisMap.put(axisResource, axis);\r
+                        }\r
+                    }\r
+\r
+                    // Get all datasets and map them to axis\r
+                    for(Resource datasetResource : graph.syncRequest(new ObjectsWithType(resource, l0.ConsistsOf, jfree.Dataset))) {\r
+                        IDataset dataset = graph.adapt(datasetResource, IDataset.class);\r
+                        if(dataset != null) {\r
+                            properties.datasets.add(dataset);\r
+                            Resource axisResource = graph.getPossibleObject(datasetResource, jfree.Dataset_mapToRangeAxis);\r
+                            IAxis axis;\r
+                            if(axisMap.containsKey(axisResource)) {\r
+                                axis = axisMap.get(axisResource);\r
+                                properties.rangeMappings.put(dataset, axis);\r
+                            }\r
+\r
+                            axisResource = graph.getPossibleObject(datasetResource, jfree.Dataset_mapToDomainAxis);\r
+                            if(axisMap.containsKey(axisResource)) {\r
+                                axis = axisMap.get(axisResource);\r
+                                properties.domainMappings.put(dataset, axis);\r
+                            }\r
+                        }\r
+                    }\r
+                    getOtherProperties(graph, properties);\r
+                    return properties;\r
+\r
+                }\r
+            }, listener);\r
+        }\r
+\r
+        return plot;\r
+    }\r
+    \r
+    @Override\r
+    public void configurePlot() {\r
+       // TODO Auto-generated method stub\r
+       \r
+    }\r
+\r
+    protected class PlotProperties {\r
+        public ArrayList<IAxis> ranges;\r
+        public ArrayList<IAxis> domains;\r
+        public ArrayList<IDataset> datasets;\r
+        public HashMap<IDataset, IAxis> rangeMappings;\r
+        public HashMap<IDataset, IAxis> domainMappings;\r
+        public HashMap<String, Object> otherProperties;\r
+        \r
+        public PlotProperties() {\r
+            datasets = new ArrayList<IDataset>();\r
+            rangeMappings = new HashMap<IDataset, IAxis>();\r
+            domainMappings = new HashMap<IDataset, IAxis>();\r
+            ranges = new ArrayList<IAxis>();\r
+            domains = new ArrayList<IAxis>();\r
+            otherProperties = new HashMap<String, Object>();\r
+        }\r
+\r
+        @Override\r
+        public boolean equals(Object other) {\r
+            if(!this.getClass().equals(other.getClass()))\r
+                return false;\r
+            PlotProperties p = (PlotProperties)other;\r
+            if(!ranges.equals(p.ranges))\r
+                return false;\r
+            if(!domains.equals(p.domains))\r
+                return false;\r
+            if(!datasets.equals(p.datasets))\r
+                return false;\r
+            if(!rangeMappings.equals(p.rangeMappings))\r
+                return false;\r
+            if(!domainMappings.equals(p.domainMappings))\r
+                return false;\r
+            if(!otherProperties.equals(p.otherProperties))\r
+                return false;\r
+            return true;\r
+        }\r
+    }\r
+\r
+    private class PlotPropertyListener implements Listener<PlotProperties> {\r
+\r
+        private boolean disposed = false;\r
+\r
+        public void dispose() {\r
+            disposed = true;\r
+        }\r
+        @Override\r
+        public void execute(final PlotProperties result) {\r
+            SwingUtilities.invokeLater(new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+                    setPlotProperties(result);\r
+                    configurePlot();\r
+                }\r
+            });\r
+        }\r
+\r
+        @Override\r
+        public void exception(Throwable t) {\r
+            t.printStackTrace();\r
+        }\r
+\r
+        @Override\r
+        public boolean isDisposed() {\r
+            return disposed;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractRenderer.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractRenderer.java
new file mode 100644 (file)
index 0000000..7621c35
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Abstract renderer class for all JFreeChart renderers\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public abstract class AbstractRenderer implements IRenderer {\r
+\r
+    protected Resource resource;\r
+    \r
+    public AbstractRenderer(ReadGraph graph, Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+    \r
+    @Override\r
+    public void dispose() {\r
+    }\r
+\r
+    @Override\r
+    public Resource getResource() {\r
+        return resource;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/BarRenderer.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/BarRenderer.java
new file mode 100644 (file)
index 0000000..30430d3
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.labels.StandardCategoryToolTipGenerator;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+\r
+/**\r
+ * Normal bar renderer\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class BarRenderer extends AbstractRenderer {\r
+\r
+    public BarRenderer(ReadGraph graph, Resource resource) {\r
+        super(graph, resource);\r
+    }\r
+\r
+    private org.jfree.chart.renderer.category.BarRenderer renderer;\r
+    \r
+    @Override\r
+    public org.jfree.chart.renderer.AbstractRenderer getRenderer() {\r
+        if(renderer == null) {\r
+            renderer = new org.jfree.chart.renderer.category.BarRenderer();\r
+            renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());\r
+        }\r
+        return renderer;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryAxis.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryAxis.java
new file mode 100644 (file)
index 0000000..6573161
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.axis.Axis;\r
+import org.jfree.chart.axis.CategoryLabelPositions;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Class representing a JFreeChart.CategoryAxis\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class CategoryAxis extends AbstractAxis {\r
+\r
+    public CategoryAxis(ReadGraph graph, Resource axisResource) {\r
+        super(graph, axisResource);\r
+    }\r
+\r
+    @Override\r
+    public Axis getAxis() {\r
+        axis = new org.jfree.chart.axis.CategoryAxis();\r
+        \r
+        if(rotate != null && rotate > 0) {\r
+            ((org.jfree.chart.axis.CategoryAxis)axis).setCategoryLabelPositions(\r
+                    CategoryLabelPositions.createUpRotationLabelPositions(Math.toRadians(rotate)));\r
+        }\r
+        \r
+        return super.getAxis();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryDataset.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryDataset.java
new file mode 100644 (file)
index 0000000..8b67400
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+\r
+/**\r
+ * Class representing a JFreeChart.CategoryDataset\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface CategoryDataset extends IDataset {\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryPlot.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/CategoryPlot.java
new file mode 100644 (file)
index 0000000..dd44e61
--- /dev/null
@@ -0,0 +1,122 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.axis.CategoryAxis;\r
+import org.jfree.chart.axis.ValueAxis;\r
+import org.jfree.chart.plot.Plot;\r
+import org.jfree.chart.plot.PlotOrientation;\r
+import org.jfree.chart.renderer.category.CategoryItemRenderer;\r
+import org.jfree.ui.RectangleInsets;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Class representing a CategoryPlot for JFreeChart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class CategoryPlot extends AbstractPlot {\r
+\r
+    public CategoryPlot(ReadGraph graph, Resource resource) {\r
+        super(graph, resource);\r
+    }\r
+\r
+    @Override\r
+    protected Plot newPlot() {\r
+        return new org.jfree.chart.plot.CategoryPlot(null, null, null, null);\r
+    }\r
+\r
+    @Override\r
+    protected void setPlotProperties(PlotProperties properties) {\r
+        if(!(plot instanceof org.jfree.chart.plot.CategoryPlot))\r
+            return;\r
+        \r
+        org.jfree.chart.plot.CategoryPlot cplot = (org.jfree.chart.plot.CategoryPlot) plot;\r
+        /* Support using multiple axis, but prefer using only one domain and \r
+         * one range axis\r
+         */\r
+        for(int i = 0; i < properties.ranges.size(); i++) {\r
+            cplot.setRangeAxis(i, (ValueAxis)properties.ranges.get(i).getAxis());\r
+        }\r
+        \r
+        for(int i = 0; i < properties.domains.size(); i++) {\r
+            cplot.setDomainAxis(i, (CategoryAxis)properties.domains.get(i).getAxis());\r
+        }\r
+       \r
+        \r
+        \r
+        IAxis axis;\r
+        for(int i = 0; i < properties.datasets.size(); i++) {\r
+            IDataset dataset = properties.datasets.get(i);\r
+            org.jfree.data.category.CategoryDataset ds = (org.jfree.data.category.CategoryDataset)dataset.getDataset();\r
+            cplot.setDataset(i, ds);\r
+//            System.out.println("setting dataset " + i + ": " + ds);\r
+            cplot.setRenderer(i, (CategoryItemRenderer)dataset.getRenderer());\r
+            axis = properties.rangeMappings.get(dataset);\r
+            if(axis != null && properties.ranges.contains(axis))\r
+                cplot.mapDatasetToRangeAxis(i, properties.ranges.indexOf(axis));\r
+            axis = properties.domainMappings.get(dataset);\r
+            if(axis != null && properties.ranges.contains(axis))\r
+                cplot.mapDatasetToDomainAxis(i, properties.domains.indexOf(axis));\r
+            \r
+            if (ds instanceof FilteredDataset) {\r
+               FilteredDataset f = (FilteredDataset)ds;\r
+               Boolean useFilter = (Boolean)properties.otherProperties.get("useFilter");\r
+                Double filterFraction = (Double)properties.otherProperties.get("filterFraction");\r
+                if (useFilter != null && filterFraction != null) {\r
+                       f.setFiltering(useFilter);\r
+                       f.setFilterFraction(filterFraction*0.01);\r
+                       f.updateFiltered();\r
+                } else {\r
+                       f.setFiltering(false);\r
+                }\r
+            }\r
+        }\r
+\r
+        Boolean visibleGrid = (Boolean)properties.otherProperties.get("visibleGrid");\r
+        if(visibleGrid != null) {\r
+            cplot.setRangeGridlinesVisible(visibleGrid);\r
+            cplot.setDomainGridlinesVisible(false);\r
+        }\r
+        \r
+        Boolean orientation = (Boolean)properties.otherProperties.get("orientation");\r
+        if(orientation != null) {\r
+               if (orientation)\r
+                       cplot.setOrientation(PlotOrientation.HORIZONTAL);\r
+               else\r
+                       cplot.setOrientation(PlotOrientation.VERTICAL);\r
+        }\r
+        \r
+        // Cleaner look: no outline borders\r
+        cplot.setInsets(new RectangleInsets(2,5,2,2), false);\r
+        cplot.setOutlineVisible(false);\r
+    }\r
+\r
+    @Override\r
+    protected void getOtherProperties(ReadGraph graph, PlotProperties properties) throws DatabaseException {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Boolean visibleGrid = graph.getPossibleRelatedValue(resource, jfree.Plot_visibleGrid);\r
+        properties.otherProperties.put("visibleGrid", visibleGrid);\r
+        Boolean orientation = graph.getPossibleRelatedValue(resource, jfree.Plot_orientation);\r
+        properties.otherProperties.put("orientation", orientation);\r
+        \r
+        Boolean useFilter = graph.getPossibleRelatedValue(resource, JFreeChartResource.getInstance(graph).Filter_used, Bindings.BOOLEAN);\r
+        Double  filterFraction = graph.getPossibleRelatedValue(resource, JFreeChartResource.getInstance(graph).Filter_fraction, Bindings.DOUBLE);\r
+        properties.otherProperties.put("useFilter", useFilter);\r
+        properties.otherProperties.put("filterFraction", filterFraction);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite.java
new file mode 100644 (file)
index 0000000..6d571f5
--- /dev/null
@@ -0,0 +1,161 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import java.awt.Frame;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.awt.SWT_AWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.jfree.chart.ChartPanel;\r
+import org.jfree.chart.JFreeChart;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.AsyncListener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.RunnableWithObject;\r
+\r
+/**\r
+ * Composite containing a single chart defined by a JFreeChart.Chart\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartComposite extends Composite {\r
+\r
+    private Frame frame;\r
+    private ChartPanel panel;\r
+    private Composite composite;\r
+    private IJFreeChart chart;\r
+\r
+    /**\r
+     * A new ChartComposite with a definition in chartResourceURI\r
+     * @param parent Composite\r
+     * @param chartResourceURI URI for a JFreeChart.Chart definition\r
+     * @param style SWT style\r
+     */\r
+    public ChartComposite(Composite parent, final String chartResourceURI, int style) {\r
+        super(parent, style | SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
+\r
+        try {\r
+            Resource chartResource = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                @Override\r
+                public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                    return graph.getPossibleResource(chartResourceURI);\r
+                }\r
+\r
+            });\r
+            if(chartResource != null)\r
+                CreateContent(chartResource);\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+\r
+    /**\r
+     * A new ChartComposite with a chartResource definition\r
+     * @param parent Composite\r
+     * @param chartResource JFreeChart.Chart resource\r
+     * @param style SWT style\r
+     */\r
+    public ChartComposite(Composite parent, final Resource chartResource, int style) {\r
+        super(parent, style | SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
+        CreateContent(chartResource);\r
+    }\r
+\r
+    /**\r
+     * Creates and displays the chart defined in chartResource\r
+     * @param chartResource\r
+     */\r
+    private void CreateContent(final Resource chartResource) {\r
+        composite = this;\r
+\r
+        GridLayoutFactory.fillDefaults().applyTo(composite);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        frame = SWT_AWT.new_Frame(composite);\r
+\r
+        // Add a listener displaying the contents of the chart. Chart is re-drawn if the definition changes\r
+        Simantics.getSession().asyncRequest(new Read<IJFreeChart>() {\r
+\r
+            @Override\r
+            public IJFreeChart perform(ReadGraph graph) throws DatabaseException {\r
+                // Adapt chartResource to a chart (XY, pie, bar, ...)\r
+                if(graph.isInstanceOf(chartResource, JFreeChartResource.getInstance(graph).Chart)) {\r
+                    if(chart != null)\r
+                        chart.dispose();\r
+                    chart = graph.adapt(chartResource, IJFreeChart.class);\r
+                    return chart;\r
+                } else {\r
+                    return null;\r
+                }\r
+            }\r
+\r
+        } , new AsyncListener<IJFreeChart>() {\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                return composite.isDisposed();\r
+            }\r
+\r
+            @Override\r
+            public void execute(AsyncReadGraph graph, IJFreeChart chart) {\r
+                if(chart == null || composite.isDisposed())\r
+                    return;\r
+                \r
+                JFreeChart jfreeChart = chart.getChart();\r
+                // Display the result chart\r
+                if (composite.isDisposed())\r
+                       return;\r
+                composite.getDisplay().asyncExec(new RunnableWithObject(jfreeChart) {\r
+\r
+                    @Override\r
+                    public void run() {\r
+                        if(composite.isDisposed())\r
+                            return;\r
+                        if(panel != null)\r
+                            frame.remove(panel);\r
+                        composite.layout();\r
+                        JFreeChart chart = (JFreeChart)getObject();\r
+                        //panel = new ChartPanel(chart, false, true, true, true, true);\r
+                        panel = new ChartPanel(chart,\r
+                                                      ChartPanel.DEFAULT_WIDTH,\r
+                                                      ChartPanel.DEFAULT_HEIGHT,\r
+                                                      ChartPanel.DEFAULT_MINIMUM_DRAW_WIDTH,\r
+                                                      ChartPanel.DEFAULT_MINIMUM_DRAW_HEIGHT,\r
+                                                      ChartPanel.DEFAULT_MAXIMUM_DRAW_WIDTH, \r
+                                                      ChartPanel.DEFAULT_MAXIMUM_DRAW_HEIGHT,\r
+                                                      false,\r
+                                                      false, true, true, true, true);\r
+                        frame.add(panel);\r
+//                        frame.repaint();\r
+                        frame.validate();\r
+                    }\r
+                });\r
+            }\r
+\r
+            @Override\r
+            public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                throwable.printStackTrace();\r
+\r
+            }\r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite2.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite2.java
new file mode 100644 (file)
index 0000000..20a2c1c
--- /dev/null
@@ -0,0 +1,162 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import java.awt.BorderLayout;\r
+import java.awt.Component;\r
+import java.awt.GridLayout;\r
+\r
+import javax.swing.JPanel;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.jfree.chart.ChartPanel;\r
+import org.jfree.chart.JFreeChart;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.AsyncListener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.threads.AWTThread;\r
+import org.simantics.utils.threads.ThreadUtils;\r
+import org.simantics.utils.ui.SWTAWTComponent;\r
+\r
+/**\r
+ * Composite containing a single chart defined by a JFreeChart.Chart\r
+ * \r
+ * Similar to ChartComposite, but uses SWTAWTComponent as a base implementation. \r
+ * \r
+ * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+ * \r
+ */\r
+public class ChartComposite2 extends SWTAWTComponent {\r
+\r
+       private JPanel jPanel;\r
+    private ChartPanel chartPanel;\r
+    private IJFreeChart chart;\r
+\r
+    public ChartComposite2(Composite parent, final String chartResourceURI, int style) {\r
+               super(parent, style);\r
+               try {\r
+            Resource chartResource = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                @Override\r
+                public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                    return graph.getPossibleResource(chartResourceURI);\r
+                }\r
+\r
+            });\r
+            if(chartResource != null)\r
+                CreateContent(chartResource);\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+               syncPopulate();\r
+       }\r
+    \r
+    public ChartComposite2(Composite parent, final Resource chartResource, int style) {\r
+       super(parent, style);\r
+       CreateContent(chartResource);\r
+       syncPopulate();\r
+    }\r
+\r
+       @Override\r
+    protected Component createSwingComponent() {\r
+       jPanel = new JPanel();\r
+       jPanel.setLayout(new GridLayout(1, 1));\r
+       if (chartPanel != null)\r
+               jPanel.add(chartPanel);\r
+       jPanel.doLayout();\r
+       return jPanel;\r
+    }\r
+       \r
+       private void setPanel(final ChartPanel panel) {\r
+               ThreadUtils.asyncExec(AWTThread.getThreadAccess(), new Runnable() {\r
+                       \r
+                       @Override\r
+                       public void run() {\r
+                               if (jPanel == null) {\r
+                                       chartPanel = panel;\r
+                               } else {\r
+                                       jPanel.removeAll();\r
+\r
+                                       chartPanel = panel;\r
+                                       jPanel.add(chartPanel, BorderLayout.CENTER);\r
+                                       jPanel.add(chartPanel);\r
+                                       jPanel.doLayout();\r
+                               }\r
+                               \r
+                       }\r
+               });\r
+       }\r
+\r
+    /**\r
+     * Creates and displays the chart defined in chartResource\r
+     * @param chartResource\r
+     */\r
+    private void CreateContent(final Resource chartResource) {\r
+\r
+        // Add a listener displaying the contents of the chart. Chart is re-drawn if the definition changes\r
+        Simantics.getSession().asyncRequest(new Read<IJFreeChart>() {\r
+\r
+            @Override\r
+            public IJFreeChart perform(ReadGraph graph) throws DatabaseException {\r
+                // Adapt chartResource to a chart (XY, pie, bar, ...)\r
+                if(graph.isInstanceOf(chartResource, JFreeChartResource.getInstance(graph).Chart)) {\r
+                    if(chart != null)\r
+                        chart.dispose();\r
+                    chart = graph.adapt(chartResource, IJFreeChart.class);\r
+                    return chart;\r
+                } else {\r
+                    return null;\r
+                }\r
+            }\r
+\r
+        } , new AsyncListener<IJFreeChart>() {\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                return ChartComposite2.this.isDisposed();\r
+            }\r
+\r
+            @Override\r
+            public void execute(AsyncReadGraph graph, IJFreeChart chart) {\r
+                if(chart == null || ChartComposite2.this.isDisposed())\r
+                    return;\r
+                \r
+                JFreeChart jfreeChart = chart.getChart();\r
+\r
+                ChartPanel panel = new ChartPanel(jfreeChart,\r
+                              ChartPanel.DEFAULT_WIDTH,\r
+                              ChartPanel.DEFAULT_HEIGHT,\r
+                              ChartPanel.DEFAULT_MINIMUM_DRAW_WIDTH,\r
+                              ChartPanel.DEFAULT_MINIMUM_DRAW_HEIGHT,\r
+                              ChartPanel.DEFAULT_MAXIMUM_DRAW_WIDTH, \r
+                              ChartPanel.DEFAULT_MAXIMUM_DRAW_HEIGHT,\r
+                              false,\r
+                              false, true, true, true, true);\r
+                setPanel(panel);\r
+               \r
+            }\r
+\r
+            @Override\r
+            public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                throwable.printStackTrace();\r
+\r
+            }\r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartUtils.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartUtils.java
new file mode 100644 (file)
index 0000000..94eb56d
--- /dev/null
@@ -0,0 +1,192 @@
+package org.simantics.jfreechart.chart;\r
+\r
+import java.awt.Dimension;\r
+import java.awt.geom.Rectangle2D;\r
+import java.io.File;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.io.OutputStream;\r
+import java.io.OutputStreamWriter;\r
+import java.io.Writer;\r
+import java.util.ArrayList;\r
+import java.util.UUID;\r
+\r
+import org.apache.batik.dom.GenericDOMImplementation;\r
+import org.apache.batik.svggen.SVGGraphics2D;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleActiveExperiment;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.w3c.dom.DOMImplementation;\r
+import org.w3c.dom.Document;\r
+\r
+/**\r
+ * Utilities for handling charts\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ChartUtils {\r
+    \r
+       public static final String emptyVariableName = "<Write variable name>";\r
+\r
+    /**\r
+     * Creates a new range axis of type jfree.NumberAxis to a plot\r
+     * \r
+     * @param graph WriteGraph\r
+     * @param plot Plot resource\r
+     * @return Created number axis, null if not successful\r
+     * @throws DatabaseException\r
+     */\r
+    public static Resource createNumberRangeAxis(WriteGraph graph, Resource plot) throws DatabaseException {\r
+        Resource axis = null;\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+        if(plot != null) {\r
+            // Create range axis\r
+            axis = GraphUtils.create2(graph, jfree.NumberAxis,\r
+                    l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
+                    l0.HasLabel, NameUtils.findFreshLabel(graph, "Y-axis", plot),\r
+                    jfree.Plot_rangeAxis_Inverse, plot,\r
+                    l0.PartOf, plot);\r
+            \r
+            // Add range axis to the plot's range axis list\r
+            Resource axisList = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
+            ArrayList<Resource> list = new ArrayList<Resource>();\r
+            list.add(axis);\r
+            if(axisList == null) {\r
+                axisList = ListUtils.create(graph, list);\r
+                graph.claim(plot, jfree.Plot_rangeAxisList, axisList);\r
+            } else {\r
+                ListUtils.insertBack(graph, axisList, list);\r
+            }\r
+        }\r
+        \r
+        return axis;\r
+        \r
+    }\r
+    \r
+    /**\r
+     * Create a XYDataset and map it to axis\r
+     * @param graph WriteGraph\r
+     * @param plot Plot resource containing the dataset\r
+     * @param domainAxis Mapped domain axis for the dataset\r
+     * @param rangeAxis Mapped range axis for the dataset\r
+     * @return created dataset or null if not successful\r
+     * @throws DatabaseException\r
+     */\r
+    public static Resource createXYDataset(WriteGraph graph, Resource plot, Resource domainAxis, Resource rangeAxis) throws DatabaseException {\r
+        if(plot == null || domainAxis == null || rangeAxis == null)\r
+            return null;\r
+        \r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        \r
+        \r
+        // Create a dataset for the axis\r
+        Resource dataset = GraphUtils.create2(graph, jfree.XYDataset,\r
+                l0.HasName, "XYDataset" + UUID.randomUUID().toString(),\r
+                jfree.Dataset_mapToDomainAxis, domainAxis,\r
+                jfree.Dataset_mapToRangeAxis, rangeAxis,\r
+                jfree.Dataset_renderer, GraphUtils.create2(graph, jfree.XYLineRenderer),\r
+                l0.PartOf, plot);\r
+        \r
+        return dataset;\r
+    }\r
+\r
+    /**\r
+     * Creates a new series to a dataset\r
+     * @param graph WriteGraph\r
+     * @param dataset Dataset for the new series\r
+     * @return created series or null if unsuccessful\r
+     * @throws DatabaseException\r
+     */\r
+    public static Resource createSeries(WriteGraph graph, Resource dataset, String rvi) throws DatabaseException {\r
+        if(dataset == null) return null;\r
+        \r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        // Create series\r
+        Resource series = GraphUtils.create2(graph, jfree.Series,\r
+                l0.HasName, "Series" + UUID.randomUUID().toString(),\r
+                jfree.variableRVI, rvi == null ? " " + emptyVariableName : rvi,\r
+                l0.PartOf, dataset);\r
+\r
+        // Add series to the dataset's series list\r
+        Resource seriesList = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+        ArrayList<Resource> list = new ArrayList<Resource>();\r
+        list.add(series);\r
+        if(seriesList == null) {\r
+            seriesList = ListUtils.create(graph, list);\r
+            graph.claim(dataset, jfree.Dataset_seriesList, seriesList);\r
+        } else {\r
+            ListUtils.insertBack(graph, seriesList, list);\r
+        }\r
+        \r
+        return series;\r
+    }\r
+\r
+    /**\r
+     * Find the current realization uri\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param chartComponent A resource from a chart (consistsOf relation in a chart)\r
+     * @return current realization uri\r
+     * @throws DatabaseException\r
+     */\r
+    public static String getCurrentRealizationURI(ReadGraph graph, Resource chartComponent) throws DatabaseException {\r
+        // Find the model where the chart is located\r
+        Resource model = graph.syncRequest(new PossibleModel(chartComponent)); \r
+        if(model == null)\r
+            return null;\r
+        \r
+        // Find the variable realization of the current experiment\r
+        String realizationURI = null;\r
+        Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));\r
+        if (realization == null) {\r
+            Layer0X L0X = Layer0X.getInstance(graph);\r
+            realization = graph.getPossibleObject(model, L0X.HasBaseRealization);\r
+        }\r
+        if (realization != null)\r
+            realizationURI = graph.getURI(realization);\r
+        \r
+        return realizationURI;        \r
+    }\r
+    \r
+    public static void writeSVG(org.jfree.chart.JFreeChart chart, Rectangle2D bounds, Writer out) throws IOException {\r
+        // Get a DOMImplementation.\r
+        DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();\r
+\r
+        // Create an instance of org.w3c.dom.Document.\r
+        Document document = domImpl.createDocument(null, "svg", null);\r
+\r
+        // Create an instance of the SVG Generator.\r
+        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);\r
+\r
+        // Paint chart panel\r
+        svgGenerator.setSVGCanvasSize(new Dimension((int)bounds.getWidth(), (int)bounds.getHeight()));\r
+        chart.draw(svgGenerator, bounds);\r
+\r
+        // Finally, write to out\r
+        svgGenerator.stream(out, false);\r
+\r
+    }\r
+\r
+    public static void writeSVG(org.jfree.chart.JFreeChart chart, Rectangle2D bounds, File file) throws IOException {\r
+        OutputStream outputStream = new FileOutputStream(file);\r
+        Writer out = new OutputStreamWriter(outputStream, "UTF-8");\r
+        writeSVG(chart, bounds, out);\r
+        outputStream.flush();\r
+        outputStream.close();
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/DeviationRenderer.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/DeviationRenderer.java
new file mode 100644 (file)
index 0000000..716bb68
--- /dev/null
@@ -0,0 +1,35 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.labels.StandardXYToolTipGenerator;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+public class DeviationRenderer extends AbstractRenderer {\r
+\r
+    public DeviationRenderer(ReadGraph graph, Resource resource) {\r
+        super(graph, resource);\r
+    }\r
+\r
+    private org.jfree.chart.renderer.xy.DeviationRenderer renderer;\r
+    \r
+    @Override\r
+    public org.jfree.chart.renderer.AbstractRenderer getRenderer() {\r
+        if(renderer == null) {\r
+            renderer = new org.jfree.chart.renderer.xy.DeviationRenderer();\r
+            renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());\r
+        }\r
+        return renderer;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ExtendedNumberAxis.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ExtendedNumberAxis.java
new file mode 100644 (file)
index 0000000..0587a58
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.data.Range;\r
+\r
+/**\r
+ * NumberAxis that supports adding only one bound, lower or upper.\r
+ * The standard NumberAxis disables auto adjusting if even one of the bounds is set\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ExtendedNumberAxis  extends org.jfree.chart.axis.NumberAxis {\r
+    private static final long serialVersionUID = 3066266986472919998L;\r
+\r
+    private Double lower = null;\r
+    private Double upper = null;\r
+    /**\r
+     * Use own lower and upper bounds to support using only one of them\r
+     */\r
+    protected void autoAdjustRange() {\r
+        super.autoAdjustRange();\r
+        Range range = getRange();\r
+        Double lower = this.lower == null ? range.getLowerBound() : this.lower;\r
+        Double upper = this.upper == null ? range.getUpperBound() : this.upper;\r
+        if(lower > upper)\r
+            upper = lower + 1;\r
+        if(upper - lower < getAutoRangeMinimumSize())\r
+            upper = lower + getAutoRangeMinimumSize();\r
+        \r
+        setRange(new Range(lower, upper), false, false);\r
+\r
+    }\r
+\r
+    public void setLower(Double lower) {\r
+        this.lower = lower;\r
+    }\r
+\r
+    public void setUpper(Double upper) {\r
+        this.upper = upper;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteredDataset.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteredDataset.java
new file mode 100644 (file)
index 0000000..a5770ff
--- /dev/null
@@ -0,0 +1,29 @@
+package org.simantics.jfreechart.chart;\r
+\r
+/**\r
+ * Interface for configuring data filtering.\r
+ * \r
+ * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+ *\r
+ */\r
+public interface FilteredDataset {\r
+\r
+       public boolean isFiltering();\r
+       public void setFiltering(boolean filtering);\r
+       \r
+       \r
+       public double getFilterFraction();\r
+       /**\r
+        * Sets filtering fraction 0 <= fraction <= 1\r
+        * With filtering fraction 0 nothing gets filtered.\r
+        * With filtering fraction 1 everything gets filtered.\r
+        * \r
+        * @param filterFraction\r
+        */\r
+       public void setFilterFraction(double filterFraction);\r
+       \r
+       public void updateFiltered();\r
+       \r
+       @SuppressWarnings("rawtypes")\r
+       public Comparable getOther();\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteringCategoryDataset.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteringCategoryDataset.java
new file mode 100644 (file)
index 0000000..df61955
--- /dev/null
@@ -0,0 +1,188 @@
+package org.simantics.jfreechart.chart;\r
+\r
+/**\r
+ * Filters CategoryDataset by creating "Other" item for filtered data.\r
+ * \r
+ * Filtering uses sum of absolute values as a comparison point and compares absolute values.\r
+ * If negative values are filtered, their absolute value is added to the others category.  \r
+ * \r
+ * \r
+ * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+ *\r
+ */\r
+import java.util.List;\r
+\r
+import org.jfree.data.category.DefaultCategoryDataset;\r
+import org.jfree.data.general.AbstractDataset;\r
+\r
+@SuppressWarnings("rawtypes")\r
+public class FilteringCategoryDataset extends AbstractDataset implements org.jfree.data.category.CategoryDataset, FilteredDataset{\r
+       \r
+       private static final long serialVersionUID = -4955124650051030544L;\r
+       \r
+       org.jfree.data.category.CategoryDataset original;\r
+       DefaultCategoryDataset filtered;\r
+       org.jfree.data.category.CategoryDataset used;\r
+       \r
+       boolean filterRows = true;\r
+       boolean filtering = true;\r
+       double filterFraction = 0.05;\r
+       private Comparable other;\r
+       \r
+       public FilteringCategoryDataset(org.jfree.data.category.CategoryDataset dataset, Comparable other) {\r
+               this.original = dataset;\r
+               this.filtered = new DefaultCategoryDataset();\r
+               this.other = other;\r
+               this.used = filtered;\r
+               updateFiltered();\r
+       }\r
+       \r
+       @Override\r
+       public boolean isFiltering() {\r
+               return filtering;\r
+       }\r
+       \r
+       @Override\r
+       public void setFiltering(boolean filtering) {\r
+               this.filtering = filtering;\r
+               if (filtering)\r
+                       used = filtered;\r
+               else\r
+                       used = original;\r
+               fireDatasetChanged();\r
+       }\r
+       \r
+       public void setFilterFraction(double filterFraction) {\r
+               this.filterFraction = filterFraction;\r
+       }\r
+       \r
+       public double getFilterFraction() {\r
+               return filterFraction;\r
+       }\r
+       \r
+       /**\r
+        * Filter rows or columns.\r
+        * @param filterRows\r
+        */\r
+       public void setFilterRows(boolean filterRows) {\r
+               this.filterRows = filterRows;\r
+       }\r
+       \r
+       public boolean isFilterRows() {\r
+               return filterRows;\r
+       }\r
+       \r
+       public void updateFiltered() {\r
+               filtered.clear();\r
+               if (filterRows) {\r
+                       for (Object column : original.getColumnKeys()) {\r
+                               Double total = 0.0;\r
+                               Double other = 0.0;\r
+                               for (Object row : original.getRowKeys()) {\r
+                                       Number value =  original.getValue((Comparable) row, (Comparable)column);\r
+                                       if (value != null)\r
+                                               total+=Math.abs(value.doubleValue());\r
+                               }\r
+                               total *= filterFraction;\r
+                               for (Object row : original.getRowKeys()) {\r
+                                       Number value = original.getValue((Comparable) row, (Comparable)column);\r
+                                       if (value == null)\r
+                                               continue;\r
+                                       if (Math.abs(value.doubleValue()) > total) {\r
+                                               filtered.addValue(value, (Comparable) row, (Comparable)column);\r
+                                       } else {\r
+                                               // TODO : what is proper way to handle negative values?\r
+                                               other += Math.abs(value.doubleValue()); \r
+                                       }\r
+                               }\r
+                               if (other > 0.0) {\r
+                                       filtered.addValue(other, this.other, (Comparable)column);\r
+                               }\r
+                       }\r
+               } else {\r
+                       for (Object row : original.getRowKeys()) {\r
+                               Double total = 0.0;\r
+                               Double other = 0.0;\r
+                               for (Object column : original.getColumnKeys()) {\r
+                                       Number value = original.getValue((Comparable) row, (Comparable)column);\r
+                                       if (value != null)\r
+                                               total += Math.abs(value.doubleValue());\r
+                               }\r
+                               total *= filterFraction;\r
+                               for (Object column : original.getColumnKeys()) {\r
+                                       Number value = original.getValue((Comparable) row, (Comparable)column);\r
+                                       if (value == null)\r
+                                               continue;\r
+                                       if (Math.abs(value.doubleValue()) > total) {\r
+                                               filtered.addValue(value, (Comparable) row, (Comparable)column);\r
+                                       } else {\r
+                                               // TODO : what is proper way to handle negative values?\r
+                                               other += Math.abs(value.doubleValue()); \r
+                                       }\r
+                               }\r
+                               if (other > 0.0) {\r
+                                       filtered.addValue(other, (Comparable)row, this.other);\r
+                               }\r
+                       }\r
+               }\r
+               fireDatasetChanged();\r
+       }\r
+       \r
+       @Override\r
+       public int getColumnCount() {\r
+               return used.getColumnCount();\r
+       }\r
+       \r
+       @Override\r
+       public int getRowCount() {\r
+               return used.getRowCount();\r
+       }\r
+       \r
+       @Override\r
+       public Number getValue(Comparable rowKey, Comparable columnKey) {\r
+               return used.getValue(rowKey, columnKey);\r
+       }\r
+       \r
+       @Override\r
+       public Number getValue(int row, int column) {\r
+               return used.getValue(row, column);\r
+       }\r
+       \r
+       @Override\r
+       public List getColumnKeys() {\r
+               return used.getColumnKeys();\r
+       }       \r
+       \r
+       @Override\r
+       public Comparable getColumnKey(int column) {\r
+               return used.getColumnKey(column);\r
+       }\r
+       \r
+       @Override\r
+       public List getRowKeys() {\r
+               return used.getRowKeys();\r
+       }\r
+       \r
+       @Override\r
+       public Comparable getRowKey(int row) {\r
+               return used.getRowKey(row);\r
+       }\r
+       \r
+       @Override\r
+       public int getRowIndex(Comparable key) {\r
+               return used.getRowIndex(key);\r
+       }\r
+       \r
+       @Override\r
+       public int getColumnIndex(Comparable key) {\r
+               return used.getColumnIndex(key);\r
+       }\r
+       \r
+       public Comparable getOther() {\r
+               return other;\r
+       }\r
+       \r
+       \r
+       \r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteringPieDataset.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/FilteringPieDataset.java
new file mode 100644 (file)
index 0000000..acc6f3b
--- /dev/null
@@ -0,0 +1,120 @@
+package org.simantics.jfreechart.chart;\r
+\r
+import java.util.List;\r
+\r
+import org.jfree.data.general.AbstractDataset;\r
+import org.jfree.data.general.DefaultPieDataset;\r
+import org.jfree.data.general.PieDataset;\r
+\r
+/**\r
+ * Filters PieDataset by creating "Other" item for filtered data.\r
+ * \r
+ * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+ *\r
+ */\r
+@SuppressWarnings("rawtypes")\r
+public class FilteringPieDataset extends AbstractDataset implements PieDataset, FilteredDataset{\r
+       \r
+       private static final long serialVersionUID = -4955124650051030544L;\r
+       \r
+       PieDataset original;\r
+       DefaultPieDataset filtered;\r
+       PieDataset used;\r
+       \r
+\r
+       boolean filtering = true;\r
+       double filterFraction = 0.05;\r
+       \r
+       private Comparable other = "other";\r
+       \r
+       public FilteringPieDataset(PieDataset dataset, Comparable other) {\r
+               this.original = dataset;\r
+               this.filtered = new DefaultPieDataset();\r
+               this.other = other;\r
+               this.used = filtered;\r
+               updateFiltered();\r
+       }\r
+       \r
+       @Override\r
+       public boolean isFiltering() {\r
+               return filtering;\r
+       }\r
+       \r
+       @Override\r
+       public void setFiltering(boolean filtering) {\r
+               this.filtering = filtering;\r
+               if (filtering)\r
+                       used = filtered;\r
+               else\r
+                       used = original;\r
+               fireDatasetChanged();\r
+       }\r
+       \r
+\r
+       public void setFilterFraction(double filterFraction) {\r
+               this.filterFraction = filterFraction;\r
+       }\r
+       \r
+       public double getFilterFraction() {\r
+               return filterFraction;\r
+       }\r
+       \r
+       public void updateFiltered() {\r
+               filtered.clear();\r
+               Double total = 0.0;\r
+               Double other = 0.0;\r
+               for (Object key : original.getKeys()) {\r
+                       total += original.getValue((Comparable) key).doubleValue();\r
+               }\r
+               total *= filterFraction;\r
+               for (Object key : original.getKeys()) {\r
+                       Number value = original.getValue((Comparable) key).doubleValue();\r
+                       \r
+                       if (value.doubleValue() > total) {\r
+                               filtered.setValue((Comparable) key,value);\r
+                       } else {\r
+                               other += value.doubleValue(); \r
+                       }\r
+               }\r
+               if (other > 0.0) {\r
+                       filtered.setValue(this.other, other);\r
+               }\r
+               fireDatasetChanged();\r
+               \r
+       }\r
+       \r
+       @Override\r
+       public List getKeys() {\r
+               return used.getKeys();\r
+       }\r
+       \r
+       @Override\r
+       public int getItemCount() {\r
+               return used.getItemCount();\r
+       }\r
+       \r
+       @Override\r
+       public Comparable getKey(int index) {\r
+               return used.getKey(index);\r
+       }\r
+       \r
+       @Override\r
+       public int getIndex(Comparable key) {\r
+               return used.getIndex(key);\r
+       }\r
+       \r
+       @Override\r
+       public Number getValue(Comparable key) {\r
+               return used.getValue(key);\r
+       }\r
+       \r
+       @Override\r
+       public Number getValue(int index) {\r
+               return used.getValue(index);\r
+       }\r
+       \r
+       public Comparable getOther() {\r
+               return other;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IAxis.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IAxis.java
new file mode 100644 (file)
index 0000000..c92f243
--- /dev/null
@@ -0,0 +1,33 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.axis.Axis;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+/**\r
+ * Interface for JFreeChart.Axis type resource\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface IAxis extends IJFreeChartComponent {\r
+    \r
+    /**\r
+     * Returns the axis\r
+     * \r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    public Axis getAxis();\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IDataset.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IDataset.java
new file mode 100644 (file)
index 0000000..6af906e
--- /dev/null
@@ -0,0 +1,46 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.renderer.AbstractRenderer;\r
+import org.jfree.data.general.Dataset;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Interface for JFreeChart.Dataset type resource\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface IDataset extends IJFreeChartComponent {\r
+    \r
+    /**\r
+     * Returns the JFreeChart dataset represented by the associated resource\r
+     * \r
+     * @return JFreeChart dataset\r
+     */\r
+    public Dataset getDataset();\r
+    \r
+    \r
+    /**\r
+     * Returns the renderer for this dataset\r
+     * \r
+     * @return JFreeChart renderer\r
+     */\r
+    public AbstractRenderer getRenderer();\r
+\r
+    /**\r
+     * Returns the resource of this dataset\r
+     * \r
+     * @return\r
+     */\r
+    public Resource getResource();\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IJFreeChart.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IJFreeChart.java
new file mode 100644 (file)
index 0000000..f03d7b4
--- /dev/null
@@ -0,0 +1,32 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.JFreeChart;\r
+import org.simantics.db.exception.DatabaseException;\r
+/**\r
+ * Interface for JFreeChart.Chart type resource\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface IJFreeChart extends IJFreeChartComponent {\r
+\r
+    /**\r
+     * Returns the chart\r
+     * \r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    public JFreeChart getChart();\r
+    \r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IJFreeChartComponent.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IJFreeChartComponent.java
new file mode 100644 (file)
index 0000000..27e1d4c
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+/**\r
+ * Interface for all components that are used to create JFreeCharts based on org.simantics.jfreechart ontology \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface IJFreeChartComponent {\r
+    \r
+    /**\r
+     * Dispose this component. Disposing a component may be useful \r
+     * if the component contains listeners that need to be disposed.\r
+     */\r
+    public void dispose();\r
+    \r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IPlot.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IPlot.java
new file mode 100644 (file)
index 0000000..c040a5f
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.plot.Plot;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+/**\r
+ * Interface for JFreeChart.Plot type resource\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface IPlot extends IJFreeChartComponent {\r
+\r
+    /**\r
+     * Returns the plot\r
+     * \r
+     * @return Title\r
+     * @throws DatabaseException\r
+     */\r
+    public Plot getPlot();\r
+    \r
+    /**\r
+     * Returns the resource of this plot\r
+     * \r
+     * @return\r
+     */\r
+    public Resource getResource();\r
+    \r
+    public void configurePlot();\r
+    \r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IRenderer.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/IRenderer.java
new file mode 100644 (file)
index 0000000..7f68e8f
--- /dev/null
@@ -0,0 +1,37 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.renderer.AbstractRenderer;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Interface for JFreeChart.Renderer type resource\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface IRenderer extends IJFreeChartComponent {\r
+    \r
+    /**\r
+     * Returns the JFreeChart AbstractRenderer represented by the associated resource\r
+     * \r
+     * @return JFreeChart renderer\r
+     */\r
+    public AbstractRenderer getRenderer();\r
+    \r
+    /**\r
+     * Returns the resource of this renderer\r
+     * @return\r
+     */\r
+    public Resource getResource();\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ITitle.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ITitle.java
new file mode 100644 (file)
index 0000000..aa50612
--- /dev/null
@@ -0,0 +1,33 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.title.Title;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+/**\r
+ * Interface for JFreeChart.Title type resource\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface ITitle extends IJFreeChartComponent {\r
+    \r
+    /**\r
+     * Returns the title\r
+     * \r
+     * @return Title\r
+     * @throws DatabaseException\r
+     */\r
+    public Title getTitle();\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/JFreeChart.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/JFreeChart.java
new file mode 100644 (file)
index 0000000..ea8df3d
--- /dev/null
@@ -0,0 +1,182 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.util.Collection;\r
+\r
+import javax.swing.SwingUtilities;\r
+\r
+import org.jfree.chart.title.LegendTitle;\r
+import org.jfree.chart.title.TextTitle;\r
+import org.jfree.ui.RectangleInsets;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * Class representing a complete JFreeChart.Chart\r
+ * \r
+ * This class supports all types of charts. The details of the chart are \r
+ * defined in plots and other adapted classes.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class JFreeChart implements IJFreeChart {\r
+\r
+    private org.jfree.chart.JFreeChart jfreechart;\r
+    private IPlot plot;\r
+    private ITitle title;\r
+    private Resource chartResource;\r
+\r
+    /**\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param chartResource Resource of type JFreeChart.Chart\r
+     */\r
+    public JFreeChart(ReadGraph graph, Resource chartResource) {\r
+        this.chartResource = chartResource;\r
+\r
+        try {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            Collection<Resource> plotsCollection = graph.syncRequest(new ObjectsWithType(chartResource, l0.ConsistsOf, jfree.Plot));\r
+            for(Resource plotResource : plotsCollection) {\r
+                this.plot = graph.adapt(plotResource, IPlot.class);\r
+            } \r
+\r
+        } catch(DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+\r
+\r
+    JFreeChartListener listener;\r
+\r
+    /**\r
+     * Returns a new chart using the information collected in the constructor\r
+     */\r
+    @Override\r
+    public org.jfree.chart.JFreeChart getChart() {\r
+        if(plot == null)\r
+            return null;\r
+\r
+        if(jfreechart == null)\r
+            jfreechart = new org.jfree.chart.JFreeChart(plot.getPlot());\r
+\r
+        if(listener == null) {\r
+            listener = new JFreeChartListener();\r
+            SimanticsUI.getSession().asyncRequest(new Read<Pair<ITitle, Boolean>>() {\r
+\r
+                @Override\r
+                public Pair<ITitle, Boolean> perform(ReadGraph graph) throws DatabaseException {\r
+                    if(chartResource == null || !graph.hasStatement(chartResource))\r
+                        return null;\r
+                    \r
+                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+                    Resource titleResource = graph.syncRequest(new PossibleObjectWithType(chartResource, l0.ConsistsOf, jfree.Title));\r
+                    title = graph.adapt(titleResource, ITitle.class);\r
+                    Boolean legendVisible = graph.getPossibleRelatedValue(chartResource, jfree.Chart_visibleLegend, Bindings.BOOLEAN);\r
+                    return new Pair<ITitle, Boolean>(title, legendVisible);\r
+                }\r
+            }, listener);\r
+        }\r
+\r
+        return jfreechart;\r
+    }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        // Call dispose to title and plots to disable their possible listeners\r
+        if(title != null)\r
+            title.dispose();\r
+        if(listener != null)\r
+            listener.dispose();\r
+        if(plot != null)\r
+            plot.dispose();\r
+    }\r
+\r
+\r
+    private class JFreeChartListener implements Listener<Pair<ITitle, Boolean>> {\r
+\r
+        private boolean disposed = false;\r
+        private LegendTitle legend;\r
+\r
+        public void dispose() {\r
+            disposed = true;\r
+        }\r
+\r
+        @Override\r
+        public void execute(final Pair<ITitle, Boolean> result) {\r
+            if(result == null)\r
+                return;\r
+            \r
+            SwingUtilities.invokeLater(new Runnable() {\r
+                @Override\r
+                public void run() {\r
+                    if(jfreechart == null)\r
+                        return;\r
+\r
+                    jfreechart.setBackgroundPaint(Color.WHITE);\r
+                    \r
+                    if(jfreechart.getLegend() != null && !jfreechart.getLegend().equals(legend)) {\r
+                        legend = jfreechart.getLegend(); \r
+                        legend.setBorder(0, 0, 0, 0);\r
+                        int size = legend.getItemFont().getSize();\r
+                        legend.setItemFont(new Font("helvetica", Font.PLAIN, size));\r
+                    }\r
+\r
+                    if(Boolean.FALSE.equals(result.second)) {\r
+                        jfreechart.removeLegend();\r
+                    } else if (jfreechart.getLegend() == null && legend != null){\r
+                        jfreechart.addLegend(legend);\r
+                    }\r
+\r
+                    TextTitle  t = (org.jfree.chart.title.TextTitle)result.first.getTitle();\r
+                    if(t.isVisible()) {\r
+                        t.setFont(new Font("georgia", Font.BOLD, 13));\r
+                        t.setPadding(new RectangleInsets(4, 0, 0, 0));\r
+                        jfreechart.setTitle(t);\r
+                    } else {\r
+                        jfreechart.setTitle((TextTitle)null);\r
+                    }\r
+                }\r
+            });\r
+        }\r
+\r
+        @Override\r
+        public void exception(Throwable t) {\r
+            t.printStackTrace();\r
+        }\r
+\r
+        @Override\r
+        public boolean isDisposed() {\r
+            return disposed;\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/NumberAxis.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/NumberAxis.java
new file mode 100644 (file)
index 0000000..a4216e1
--- /dev/null
@@ -0,0 +1,45 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.axis.Axis;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Class representing a JFreeChart.NumberAxis\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NumberAxis extends AbstractAxis {\r
+\r
+    /**\r
+     *\r
+     * @param graph ReadGraph\r
+     * @param axisResource resource of type JFreeChart.NumberAxis\r
+     */\r
+    public NumberAxis(ReadGraph graph, Resource axisResource) {\r
+        super(graph, axisResource);\r
+    }\r
+\r
+\r
+    @Override\r
+    public Axis getAxis() {\r
+        axis = new ExtendedNumberAxis();\r
+        ((org.jfree.chart.axis.NumberAxis)axis).setAutoRangeIncludesZero(false);\r
+        ((ExtendedNumberAxis)axis).setLower(min);\r
+        ((ExtendedNumberAxis)axis).setUpper(max);\r
+        return super.getAxis();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/PieDataset.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/PieDataset.java
new file mode 100644 (file)
index 0000000..c45eb95
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import java.awt.Color;\r
+import java.util.HashMap;\r
+\r
+/**\r
+ * Class representing a PieDataset in JFreeChart ontology\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface PieDataset<T extends Comparable<T>> extends IDataset {\r
+\r
+\r
+    /**\r
+     * Map of colors for different slices in a pie chart. Name \r
+     * indicates the key of the value.\r
+     * @return  Map of colors for different slices in a pie chart\r
+     */\r
+    public HashMap<T, Color> getColorMap();\r
+\r
+\r
+    /**\r
+     * Map of exploded statuses for slices in a pie chart. Name\r
+     * indicates the key of the slice.\r
+     * @return\r
+     */\r
+    public HashMap<T, Boolean> getExplodedMap();\r
+    \r
+   \r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/PiePlot.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/PiePlot.java
new file mode 100644 (file)
index 0000000..9c4f119
--- /dev/null
@@ -0,0 +1,172 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.util.HashMap;\r
+\r
+import org.jfree.chart.labels.StandardPieSectionLabelGenerator;\r
+import org.jfree.chart.labels.StandardPieToolTipGenerator;\r
+import org.jfree.chart.plot.DefaultDrawingSupplier;\r
+import org.jfree.chart.plot.Plot;\r
+import org.jfree.data.general.Dataset;\r
+import org.jfree.data.general.DatasetChangeEvent;\r
+import org.jfree.data.general.DatasetChangeListener;\r
+import org.jfree.ui.RectangleInsets;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Class representing a PiePlot in JFreeChart ontology\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PiePlot extends AbstractPlot {\r
+\r
+    private org.jfree.data.general.PieDataset pieDataset;\r
+    private DatasetChangeListener listener;\r
+    \r
+    public PiePlot(ReadGraph graph, Resource resource) {\r
+        super(graph, resource);\r
+    }\r
+\r
+    /**\r
+     * Pie plot class with a stricter equals condition\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class MyPiePlot extends org.jfree.chart.plot.PiePlot {\r
+\r
+        private static final long serialVersionUID = -5917620061541212934L;\r
+\r
+        @Override\r
+        public boolean equals(Object obj) {\r
+            boolean result = super.equals(obj);\r
+            if(result == true) {\r
+                org.jfree.chart.plot.PiePlot that = (org.jfree.chart.plot.PiePlot) obj;\r
+                if (this.getDataset() != that.getDataset()) {\r
+                    return false; // Normally plot does not check this. We need this to properly update the charts\r
+                }\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    protected Plot newPlot() {\r
+        MyPiePlot plot = new MyPiePlot();\r
+        plot.setToolTipGenerator(new StandardPieToolTipGenerator());\r
+        return plot;\r
+    }\r
+\r
+    @Override\r
+    protected void getOtherProperties(ReadGraph graph, PlotProperties properties) throws DatabaseException {\r
+        Boolean labelsVisible = graph.getPossibleRelatedValue(resource, JFreeChartResource.getInstance(graph).Plot_visibleLabels, Bindings.BOOLEAN);\r
+        properties.otherProperties.put("labelsVisible", labelsVisible);\r
+        \r
+        Boolean useFilter = graph.getPossibleRelatedValue(resource, JFreeChartResource.getInstance(graph).Filter_used, Bindings.BOOLEAN);\r
+        Double  filterFraction = graph.getPossibleRelatedValue(resource, JFreeChartResource.getInstance(graph).Filter_fraction, Bindings.DOUBLE);\r
+        properties.otherProperties.put("useFilter", useFilter);\r
+        properties.otherProperties.put("filterFraction", filterFraction);\r
+    }\r
+    \r
+    @SuppressWarnings({ "unchecked", "rawtypes" })\r
+    @Override\r
+    protected void setPlotProperties(PlotProperties properties) {\r
+        if(!(plot instanceof MyPiePlot))\r
+            return;\r
+        \r
+        final MyPiePlot piePlot = (MyPiePlot)plot;\r
+        \r
+        if(!properties.datasets.isEmpty()) {\r
+            // We assume that a pie plot has only one dataset\r
+            final IDataset ds = properties.datasets.get(0);\r
+            Dataset dataset = ((PieDataset)ds).getDataset();\r
+            \r
+            if(dataset == null)\r
+                return;\r
+\r
+            if(pieDataset != null && listener != null) {\r
+                pieDataset.removeChangeListener(listener);\r
+            }\r
+            \r
+            pieDataset = (org.jfree.data.general.PieDataset)dataset;\r
+            piePlot.setDataset(pieDataset);\r
+            \r
+            if (pieDataset instanceof FilteredDataset) {\r
+               FilteredDataset f = (FilteredDataset)pieDataset;\r
+               Boolean useFilter = (Boolean)properties.otherProperties.get("useFilter");\r
+                Double filterFraction = (Double)properties.otherProperties.get("filterFraction");\r
+                if (useFilter != null && filterFraction != null) {\r
+                       f.setFiltering(useFilter);\r
+                       f.setFilterFraction(filterFraction*0.01);\r
+                       f.updateFiltered();\r
+                } else {\r
+                       f.setFiltering(false);\r
+                }\r
+            }\r
+            \r
+            Boolean labelsVisible = (Boolean)properties.otherProperties.get("labelsVisible");\r
+            if(Boolean.FALSE.equals(labelsVisible))\r
+                piePlot.setLabelGenerator(null);\r
+            else if(piePlot.getLabelGenerator() == null)\r
+                piePlot.setLabelGenerator(new StandardPieSectionLabelGenerator());\r
+            \r
+            listener = new DatasetChangeListener() {\r
+                \r
+                               @Override\r
+                public void datasetChanged(DatasetChangeEvent event) {\r
+                    HashMap<Comparable<?>, Color> colorMap = ((PieDataset)ds).getColorMap();\r
+                    HashMap<Comparable<?>, Boolean> explodedMap = ((PieDataset)ds).getExplodedMap();\r
+                    \r
+                    for(Object o : piePlot.getDataset().getKeys()) {\r
+                        if(o instanceof Comparable) {\r
+                            Comparable<?> key = (Comparable<?>)o;\r
+                            if(explodedMap.containsKey(key) && explodedMap.get(key)) {\r
+                                piePlot.setExplodePercent(key, 0.3);\r
+\r
+                            } else {\r
+                                piePlot.setExplodePercent(key, 0);\r
+                            }\r
+                        }\r
+                    }\r
+                    \r
+                    for(Comparable<?> name : explodedMap.keySet()) {\r
+                        Boolean exploded = explodedMap.get(name);\r
+                        if(Boolean.TRUE.equals(exploded))\r
+                            piePlot.setExplodePercent(name, 0.3);\r
+                    } \r
+                    piePlot.clearSectionPaints(false);\r
+                    piePlot.setDrawingSupplier(new DefaultDrawingSupplier());\r
+                    for(Comparable<?> name : colorMap.keySet())\r
+                        piePlot.setSectionPaint(name, colorMap.get(name));\r
+                }\r
+            };\r
+            \r
+            pieDataset.addChangeListener(listener);\r
+        }\r
+        \r
+        // Cleaner look: no outline borders\r
+        piePlot.setInsets(new RectangleInsets(0,0,0,0), false);\r
+        piePlot.setOutlineVisible(false);\r
+        piePlot.setLabelBackgroundPaint(Color.WHITE);\r
+        piePlot.setLabelFont(new Font("helvetica", Font.PLAIN, 11));\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/StackedBarRenderer.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/StackedBarRenderer.java
new file mode 100644 (file)
index 0000000..a7da60c
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.labels.StandardCategoryToolTipGenerator;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Stacked bar renderer\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class StackedBarRenderer extends AbstractRenderer {\r
+\r
+    public StackedBarRenderer(ReadGraph graph, Resource resource) {\r
+        super(graph, resource);\r
+    }\r
+\r
+    private org.jfree.chart.renderer.category.StackedBarRenderer renderer;\r
+    \r
+    @Override\r
+    public org.jfree.chart.renderer.AbstractRenderer getRenderer() {\r
+        if(renderer == null) {\r
+            renderer = new org.jfree.chart.renderer.category.StackedBarRenderer();\r
+            renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());\r
+        }\r
+        return renderer;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/TextTitle.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/TextTitle.java
new file mode 100644 (file)
index 0000000..bdb73de
--- /dev/null
@@ -0,0 +1,87 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.title.Title;\r
+import org.jfree.ui.RectangleEdge;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Class representing a JFreeChart.TextTitle\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class TextTitle implements ITitle {\r
+    \r
+    private org.jfree.chart.title.TextTitle textTitle;\r
+    private RectangleEdge position;\r
+    private String text;\r
+    private Boolean visible;\r
+    \r
+    public TextTitle(ReadGraph graph, Resource titleResource) {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        try {\r
+            text = graph.getPossibleRelatedValue(titleResource, l0.HasLabel, Bindings.STRING);\r
+            Resource pos = graph.getPossibleObject(titleResource, jfree.Title_position);\r
+            position = getRectangleEdgePosition(graph, pos);\r
+            visible = graph.getPossibleRelatedValue(titleResource, jfree.visible, Bindings.BOOLEAN);\r
+\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Get the RectangleEdge representation for Resource position (JFreeChart.Position)\r
+     * @param graph ReadGraph \r
+     * @param position Resource of type JFreeChart.Position\r
+     * @return RectangleEdge representation for Resource position\r
+     */\r
+    private RectangleEdge getRectangleEdgePosition(ReadGraph graph, Resource position) {\r
+        if(position == null)\r
+            return null;\r
+        \r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        if(position.equals(jfree.Top))\r
+            return RectangleEdge.TOP;\r
+        else if(position.equals(jfree.Bottom))\r
+            return RectangleEdge.BOTTOM;\r
+        else if(position.equals(jfree.Left))\r
+            return RectangleEdge.LEFT;\r
+        else if(position.equals(jfree.Right))\r
+            return RectangleEdge.RIGHT;\r
+        else\r
+            return null;\r
+                    \r
+    }\r
+\r
+    @Override\r
+    public Title getTitle() {\r
+        textTitle = new org.jfree.chart.title.TextTitle(text);\r
+        if(position != null)\r
+            textTitle.setPosition(position);\r
+        if(visible != null)\r
+            textTitle.setVisible(visible);\r
+        return textTitle;\r
+    }\r
+\r
+    @Override\r
+    public void dispose() {\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYAreaRenderer.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYAreaRenderer.java
new file mode 100644 (file)
index 0000000..6c68034
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.labels.StandardXYToolTipGenerator;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Renderer representing jfree chart renderer for xy areas\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class XYAreaRenderer extends AbstractRenderer {\r
+\r
+    private org.jfree.chart.renderer.xy.XYAreaRenderer renderer;\r
+    \r
+    public XYAreaRenderer(ReadGraph graph, Resource resource) {\r
+        super(graph, resource);\r
+    }\r
+\r
+    @Override\r
+    public org.jfree.chart.renderer.AbstractRenderer getRenderer() {\r
+        if(renderer == null) {\r
+            renderer = new org.jfree.chart.renderer.xy.XYAreaRenderer();\r
+            renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());\r
+        }\r
+        return renderer;\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYDataset.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYDataset.java
new file mode 100644 (file)
index 0000000..d7433d6
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+\r
+/**\r
+ * Class representing a JFreeChart.XYDataset\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface XYDataset extends IDataset {\r
+\r
+  \r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYLineRenderer.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYLineRenderer.java
new file mode 100644 (file)
index 0000000..7d5abb2
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.labels.StandardXYToolTipGenerator;\r
+import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Renderer representing jfree chart renderer for xy lines\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class XYLineRenderer extends AbstractRenderer {\r
+\r
+    XYLineAndShapeRenderer renderer;\r
+    \r
+    public XYLineRenderer(ReadGraph graph, Resource resource) {\r
+        super(graph, resource);\r
+    }\r
+\r
+    @Override\r
+    public org.jfree.chart.renderer.AbstractRenderer getRenderer() {\r
+        if(renderer == null) {\r
+            renderer = new XYLineAndShapeRenderer(true, false);\r
+            renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());\r
+        }\r
+        return renderer;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYPlot.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/XYPlot.java
new file mode 100644 (file)
index 0000000..4ffae63
--- /dev/null
@@ -0,0 +1,106 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart;\r
+\r
+import org.jfree.chart.axis.ValueAxis;\r
+import org.jfree.chart.plot.Plot;\r
+import org.jfree.chart.plot.PlotOrientation;\r
+import org.jfree.chart.renderer.xy.XYItemRenderer;\r
+import org.jfree.data.xy.XYDataset;\r
+import org.jfree.ui.RectangleInsets;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Class representing a JFreeChart.XYPlot\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class XYPlot extends AbstractPlot {\r
+\r
+    public XYPlot(ReadGraph graph, Resource plotResource) {\r
+        super(graph, plotResource);\r
+    }\r
+\r
+    @Override\r
+    protected Plot newPlot() {\r
+        return new org.jfree.chart.plot.XYPlot(null, null, null, null);\r
+    }\r
+\r
+    @Override\r
+    protected void getOtherProperties(ReadGraph graph, PlotProperties properties) throws DatabaseException {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Boolean visibleGrid = graph.getPossibleRelatedValue(resource, jfree.Plot_visibleGrid);\r
+        properties.otherProperties.put("visibleGrid", visibleGrid);\r
+        if(!properties.datasets.isEmpty()) {\r
+            IDataset idataset = properties.datasets.get(0);\r
+            Resource renderer = graph.getPossibleObject(idataset.getResource(), jfree.Dataset_renderer);\r
+            if(renderer != null) {\r
+                properties.otherProperties.put("renderer", graph.adapt(renderer, IRenderer.class));\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    protected void setPlotProperties(PlotProperties properties) {\r
+        if(!(plot instanceof org.jfree.chart.plot.XYPlot))\r
+            return;\r
+\r
+        org.jfree.chart.plot.XYPlot xyplot = (org.jfree.chart.plot.XYPlot)plot;\r
+        xyplot.clearDomainAxes();\r
+        xyplot.clearRangeAxes();\r
+\r
+        for(int i = 0; i < properties.ranges.size(); i++) {\r
+            xyplot.setRangeAxis(i, (ValueAxis)properties.ranges.get(i).getAxis());\r
+        }\r
+\r
+        for(int i = 0; i < properties.domains.size(); i++) {\r
+            xyplot.setDomainAxis(i, (ValueAxis)properties.domains.get(i).getAxis());\r
+        }\r
+\r
+        IAxis axis;\r
+        for(int i = 0; i < properties.datasets.size(); i++) {\r
+            IDataset dataset = properties.datasets.get(i);\r
+            xyplot.setDataset(i, (XYDataset)dataset.getDataset());\r
+            xyplot.setRenderer(i, (XYItemRenderer)dataset.getRenderer());\r
+            axis = properties.rangeMappings.get(dataset);\r
+            if(axis != null && properties.ranges.contains(axis))\r
+                xyplot.mapDatasetToRangeAxis(i, properties.ranges.indexOf(axis));\r
+            axis = properties.domainMappings.get(dataset);\r
+            if(axis != null && properties.ranges.contains(axis))\r
+                xyplot.mapDatasetToDomainAxis(i, properties.domains.indexOf(axis));\r
+        }\r
+\r
+        Boolean visibleGrid = (Boolean)properties.otherProperties.get("visibleGrid");\r
+        if(visibleGrid == null)\r
+            visibleGrid = true;\r
+        \r
+        Boolean orientation = (Boolean)properties.otherProperties.get("orientation");\r
+        if(orientation != null) {\r
+               if (orientation)\r
+                       xyplot.setOrientation(PlotOrientation.HORIZONTAL);\r
+               else\r
+                       xyplot.setOrientation(PlotOrientation.VERTICAL);\r
+        }\r
+\r
+        xyplot.setRangeGridlinesVisible(visibleGrid);\r
+        xyplot.setDomainGridlinesVisible(visibleGrid);\r
+\r
+        // Cleaner look: no outline borders\r
+        xyplot.setInsets(new RectangleInsets(2,5,2,10), false);\r
+        xyplot.setOutlineVisible(false);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartBoundsOutline.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartBoundsOutline.java
new file mode 100644 (file)
index 0000000..990ff4f
--- /dev/null
@@ -0,0 +1,37 @@
+package org.simantics.jfreechart.chart.element;\r
+\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.LifeCycle;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+\r
+/**\r
+ * Outline with default bounds. Needed to avoid crashing when trying to rotate chart elements.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartBoundsOutline extends BoundsOutline implements LifeCycle {\r
+    private static final long serialVersionUID = -3819495313008722843L;\r
+    \r
+    Rectangle2D defaultBounds;\r
+    \r
+    public ChartBoundsOutline(Rectangle2D defaultBounds) {\r
+        this.defaultBounds = defaultBounds;\r
+    }\r
+\r
+    @Override\r
+    public void onElementCreated(IElement e) {\r
+        e.setHint(ElementHints.KEY_BOUNDS, defaultBounds);\r
+    }\r
+\r
+    @Override\r
+    public void onElementDestroyed(IElement e) {}\r
+    @Override\r
+    public void onElementActivated(IDiagram d, IElement e) {}\r
+    @Override\r
+    public void onElementDeactivated(IDiagram d, IElement e) {}\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartElementFactory.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartElementFactory.java
new file mode 100644 (file)
index 0000000..c1eb01a
--- /dev/null
@@ -0,0 +1,186 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.element;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.QuadCurve2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.jfree.chart.JFreeChart;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.adapter.ElementFactory;\r
+import org.simantics.diagram.adapter.SyncElementFactory;\r
+import org.simantics.diagram.elements.ElementPropertySetter;\r
+import org.simantics.diagram.synchronization.CompositeHintSynchronizer;\r
+import org.simantics.diagram.synchronization.IHintSynchronizer;\r
+import org.simantics.diagram.synchronization.SynchronizationHints;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.diagram.synchronization.graph.RemoveElement;\r
+import org.simantics.diagram.synchronization.graph.TransformSynchronizer;\r
+import org.simantics.diagram.ui.DiagramModelHints;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.LifeCycle;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.jfreechart.chart.IJFreeChart;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;\r
+\r
+/**\r
+ * Element factory for creating chart elements to diagrams\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartElementFactory extends SyncElementFactory {\r
+\r
+    private static final String         CLASS_ID            = "Chart";\r
+    public  static final ElementFactory INSTANCE            = new ChartElementFactory();\r
+    public  static final Image          STATIC_IMAGE        = new ShapeImage(getChartShape(), null, new BasicStroke(1f), true);\r
+    public  static final double         SYMBOL_CHART_SIZE   = 10.0;\r
+    public  static final Key            KEY_CHART_COMPONENT = new KeyOf(Resource.class, "CHART_COMPONENT");     \r
+    public  static final Key            KEY_CHART           = new KeyOf(JFreeChart.class, "CHART");       \r
+    \r
+    static Shape getChartShape() {\r
+        \r
+        Path2D path = new Path2D.Double();\r
+        // First create the axis for a chart symbol\r
+        path.moveTo(-SYMBOL_CHART_SIZE, -SYMBOL_CHART_SIZE);\r
+        path.lineTo(-SYMBOL_CHART_SIZE,  SYMBOL_CHART_SIZE);\r
+        path.lineTo( SYMBOL_CHART_SIZE,  SYMBOL_CHART_SIZE);\r
+\r
+        // Then a curve to the chart\r
+        QuadCurve2D curve = new QuadCurve2D.Double(\r
+                -SYMBOL_CHART_SIZE + 1,  SYMBOL_CHART_SIZE - 1,\r
+                SYMBOL_CHART_SIZE - 5,  SYMBOL_CHART_SIZE - 5,\r
+                SYMBOL_CHART_SIZE - 1, -SYMBOL_CHART_SIZE + 3);\r
+\r
+        // Connect shapes\r
+        path.append(curve, false);\r
+        return path;\r
+    }\r
+\r
+    // Hint synchronizer for synchronizing transform and bounds\r
+    private static final IHintSynchronizer HINT_SYNCHRONIZER = new CompositeHintSynchronizer(\r
+            TransformSynchronizer.INSTANCE);\r
+\r
+    public static ElementClass create(ReadGraph graph, Resource chart) throws DatabaseException {\r
+        return ElementClass.compile(\r
+                new ChartSceneGraph(),\r
+                new Initializer(chart),\r
+                new StaticObjectAdapter(JFreeChartResource.getInstance(graph).ChartElement),\r
+                DefaultTransform.INSTANCE,\r
+                StaticSymbolImageInitializer.INSTANCE,\r
+                new StaticSymbolImpl(STATIC_IMAGE),\r
+                new ChartBoundsOutline(new Rectangle2D.Double(-20, -20, 60, 40)),\r
+                new ElementPropertySetter(ChartSceneGraph.KEY_SG_NODE)\r
+                ).setId(CLASS_ID);\r
+    }\r
+\r
+    public ElementClass create(ReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType) throws DatabaseException {\r
+        return create(graph, null);\r
+    }\r
+\r
+    @Override\r
+    public void load(ReadGraph g, ICanvasContext canvas, final IDiagram diagram, Resource element, final IElement e) throws DatabaseException {\r
+\r
+        Resource chartResource;\r
+        ElementPropertySetter ps = e.getElementClass().getSingleItem(ElementPropertySetter.class);\r
+        ps.loadProperties(e, element, g);\r
+        \r
+        AffineTransform at = DiagramGraphUtil.getAffineTransform(g, element);\r
+        // Hack for disabling all rotations in chart elements\r
+        double x = at.getTranslateX();\r
+        double y = at.getTranslateY();\r
+        at.setToRotation(0);\r
+        at.setToTranslation(x, y);\r
+        ElementUtils.setTransform(e, at); // Set hint transform without rotations\r
+        ps.overrideProperty(e, "Transform", at); // Set property Transform without rotations\r
+        \r
+        e.setHint(SynchronizationHints.HINT_SYNCHRONIZER, HINT_SYNCHRONIZER);\r
+        \r
+\r
+        Object o = e.getHint(KEY_CHART_COMPONENT);\r
+        if(o == null || !(o instanceof Resource)) {\r
+            chartResource = g.getPossibleObject(element, JFreeChartResource.getInstance(g).ChartElement_component);\r
+        } else {\r
+            chartResource = (Resource)o;\r
+        }\r
+\r
+        if(chartResource == null || !g.hasStatement(chartResource))  {\r
+            // Remove element if there is no chart resource for it        \r
+            g.asyncRequest(new WriteRequest() {\r
+                \r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                    new RemoveElement(\r
+                            (Resource)diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE),\r
+                            (Resource)e.getHint(ElementHints.KEY_OBJECT))\r
+                    .perform(graph);\r
+                }\r
+            });\r
+            return;\r
+        }\r
+\r
+        IJFreeChart ichart = g.adapt(chartResource, IJFreeChart.class);\r
+\r
+        if(ichart != null) {\r
+            JFreeChart chart = ichart.getChart();\r
+            e.setHint(KEY_CHART, chart);\r
+        }\r
+\r
+    }\r
+\r
+\r
+    /**\r
+     * Initializer for setting a chart component for element\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    static class Initializer implements LifeCycle {\r
+        private static final long serialVersionUID = -5822080013184271204L;\r
+        Object component;\r
+\r
+        Initializer(Object component) {\r
+            this.component = component;\r
+        }\r
+\r
+        @Override\r
+        public void onElementCreated(IElement e) {\r
+            if(component != null) e.setHint(KEY_CHART_COMPONENT, component);\r
+        }\r
+\r
+        @Override\r
+        public void onElementActivated(IDiagram d, IElement e) {}\r
+        @Override\r
+        public void onElementDeactivated(IDiagram d, IElement e) {}\r
+        @Override\r
+        public void onElementDestroyed(IElement e) {}\r
+    };\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartElementWriter.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartElementWriter.java
new file mode 100644 (file)
index 0000000..2fe7fc1
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.element;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.synchronization.graph.ElementWriter;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Element writer for chart elements. ChartElementWriter stores\r
+ * the reference to a chart definition into the element resource\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartElementWriter implements ElementWriter {\r
+\r
+    @Override\r
+    public void addToGraph(WriteGraph graph, IElement element, Resource elementResource) throws DatabaseException {\r
+        Resource chartComponent = element.getHint(ChartElementFactory.KEY_CHART_COMPONENT);\r
+        if (chartComponent == null)\r
+            throw new IllegalArgumentException("KEY_CHART_COMPONENT hint not set");\r
+        \r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        graph.claim(elementResource, jfree.ChartElement_component, chartComponent);\r
+    }\r
+\r
+    @Override\r
+    public void removeFromGraph(WriteGraph graph, Resource elementResource) throws DatabaseException {\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartNode.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartNode.java
new file mode 100644 (file)
index 0000000..0071503
--- /dev/null
@@ -0,0 +1,292 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.element;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.awt.Stroke;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Line2D;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import javax.swing.JPanel;\r
+\r
+import org.jfree.chart.ChartPanel;\r
+import org.jfree.chart.JFreeChart;\r
+import org.simantics.scenegraph.ISelectionPainterNode;\r
+import org.simantics.scenegraph.g2d.events.EventTypes;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonReleasedEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseDragBegin;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;\r
+import org.simantics.scenegraph.swing.ComponentNode;\r
+import org.simantics.scenegraph.utils.GeometryUtils;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+\r
+/**\r
+ * Chart node for displaying jfreechart charts in diagrams\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartNode extends ComponentNode<JPanel> implements ISelectionPainterNode {\r
+\r
+    private static final long serialVersionUID = 5013911689968911010L;\r
+    private boolean hover = false;\r
+    private boolean dragging = false;\r
+\r
+    private ResizeListener resizeListener; \r
+\r
+    protected transient JFreeChart chart = null;\r
+\r
+    public boolean dragging() {\r
+        return dragging;\r
+    }\r
+\r
+    public void setChart(JFreeChart chart) {\r
+        this.chart = chart;\r
+    }\r
+\r
+    public void setResizeListener(ResizeListener listener) {\r
+        this.resizeListener = listener;\r
+    }\r
+\r
+    @SyncField({"hover"})\r
+    public void setHover(boolean hover) {\r
+        this.hover = hover;\r
+        repaint();\r
+    }\r
+\r
+    @Override\r
+    public void cleanup() {\r
+        removeEventHandler(this);\r
+        super.cleanup();\r
+    }\r
+\r
+    @Override\r
+    public void init() {\r
+        super.init();\r
+    }\r
+\r
+    public static void expand(Rectangle2D rectangle, double scaleX, double scaleY) {\r
+        GeometryUtils.expandRectangle(rectangle,\r
+                5 * scaleY > 5 ? 5 * scaleY : 5, \r
+                        3 * scaleY > 3 ? 3 * scaleY : 3, \r
+                                3 * scaleX > 3 ? 3 * scaleX : 3, \r
+                                        3 * scaleX > 3 ? 3 * scaleX : 3);\r
+    }\r
+\r
+    @Override\r
+    public void render(Graphics2D g2d) {\r
+        if (component == null && chart != null) {\r
+            // Need the chart, so this cannot be done during initialization\r
+            component = new ChartPanel(chart, false);\r
+            ((ChartPanel)component).setRefreshBuffer(false);\r
+            component.setIgnoreRepaint(true); \r
+            component.setDoubleBuffered(false);\r
+            if(bounds != null) {\r
+                component.setBounds(0, 0, 0, 0);\r
+            }\r
+            super.init();\r
+            addEventHandler(this);\r
+        }\r
+\r
+        if (component != null) {\r
+            AffineTransform ot = g2d.getTransform();\r
+            g2d.transform(transform);\r
+            double scaleX = g2d.getTransform().getScaleX();\r
+            double scaleY = g2d.getTransform().getScaleY();\r
+\r
+            AffineTransform at = new AffineTransform(transform);\r
+            synchronized(transform) {\r
+                at.setToTranslation(bounds.getMinX(), bounds.getMinY());\r
+                at.scale(1/scaleX, 1/scaleY);\r
+            }\r
+            g2d.transform(at);\r
+            int width = (int)(bounds.getWidth() * scaleX);\r
+            int height = (int)(bounds.getHeight() * scaleY);\r
+\r
+            if(hover || dragging) {\r
+                // Borders\r
+                Color orig = g2d.getColor();\r
+                BasicStroke oldStroke = (BasicStroke) g2d.getStroke();\r
+                g2d.setColor(Color.LIGHT_GRAY);\r
+                Rectangle2D b = new Rectangle2D.Double(0, 0, width, height);\r
+                Rectangle2D r = b.getBounds2D();\r
+                expand(r, 1 * scaleX, 1 * scaleY);\r
+                g2d.fill(r);\r
+\r
+                // Lower right corner for dragging\r
+                double x = r.getMaxX() - (0.33 * scaleX);\r
+                double y = r.getMaxY() - (0.33 * scaleY);\r
+\r
+                if(r.getMaxX() - x > 0.4) {                \r
+                    // if there is enough space, use decorated corner\r
+                    BasicStroke hilightStroke = new BasicStroke(oldStroke.getLineWidth() * 3);\r
+                    for(int i = 1; i < 4; i++) {\r
+                        Line2D line = new Line2D.Double(\r
+                                x - (i * scaleX), \r
+                                y, \r
+                                x, \r
+                                y - (i * scaleY));\r
+\r
+                        g2d.setStroke(hilightStroke);\r
+                        g2d.setColor(Color.GRAY);\r
+                        g2d.draw(line);\r
+\r
+                        g2d.setStroke(oldStroke);\r
+                        g2d.setColor(Color.BLACK);\r
+                        g2d.draw(line);\r
+                    }\r
+\r
+\r
+                } else {\r
+                    // not enough space, use a non-decorated corner\r
+                    float f = 3;\r
+                    Rectangle2D corner = new Rectangle2D.Double(r.getMaxX() - f, r.getMaxY() - f, f, f);\r
+                    g2d.setColor(Color.DARK_GRAY);\r
+                    g2d.fill(corner);\r
+                }\r
+\r
+                g2d.setStroke(oldStroke);\r
+                g2d.setColor(orig);\r
+            }\r
+\r
+            boolean selected = NodeUtil.isSelected(this, 1);\r
+            if (selected) {\r
+                Color orig = g2d.getColor();\r
+                Stroke origStroke = g2d.getStroke();\r
+\r
+                g2d.setColor(Color.RED);\r
+                double s = GeometryUtils.getScale(g2d.getTransform());\r
+                g2d.setStroke(new BasicStroke(1f * s < 1f ? 1f : 1f * (float)s));\r
+\r
+                Rectangle2D b = new Rectangle2D.Double(0, 0, width, height);\r
+                Rectangle2D r = b.getBounds2D();\r
+                expand(r, scaleX, scaleY);\r
+                g2d.draw(r);\r
+\r
+                g2d.setColor(orig);\r
+                g2d.setStroke(origStroke);\r
+            }\r
+\r
+            synchronized(component) {\r
+                component.setLocation((int)g2d.getTransform().getTranslateX(), (int)g2d.getTransform().getTranslateY());\r
+                if(component.getSize().getWidth() != width || component.getSize().getHeight() != height) {\r
+                    component.setSize(width, height);\r
+                }\r
+                component.paint(g2d);\r
+            }\r
+\r
+            g2d.setTransform(ot);\r
+        } else {\r
+            /*\r
+             *  Component == null\r
+             *  \r
+             *  The related chart definition ha been removed. \r
+             */\r
+            System.out.println("TÄÄLLÄ, TÄÄLLÄ");\r
+        }\r
+    }\r
+\r
+    @Override\r
+    protected boolean mouseButtonPressed(MouseButtonPressedEvent event) {\r
+        Point2D local = controlToLocal( event.controlPosition );\r
+        local = parentToLocal(local);\r
+        Rectangle2D bounds = getBoundsInLocal().getBounds2D();\r
+        expand(bounds, 1, 1);\r
+        double control = 3.0;\r
+        Rectangle2D corner = new Rectangle2D.Double(bounds.getMaxX() - control, bounds.getMaxY() - control, control, control);\r
+        if (hover && corner.contains(local)) {\r
+            dragging = true;\r
+            return true;\r
+        }\r
+        return super.mouseButtonPressed(event);\r
+    }\r
+\r
+\r
+    @Override\r
+    protected boolean mouseMoved(MouseMovedEvent e) {\r
+        if(dragging) {\r
+            Point2D local = controlToLocal( e.controlPosition );\r
+            local = parentToLocal(local);\r
+\r
+            Rectangle2D bounds = getBoundsInLocal().getBounds2D();\r
+\r
+            if(Math.abs(bounds.getMaxX() - local.getX()) > 3 ||\r
+                    Math.abs(bounds.getMaxY() - local.getY()) > 3) {\r
+                resize(local);\r
+            }\r
+            return true;\r
+        }\r
+        return false;\r
+    }\r
+\r
+    public boolean hitCorner(Point2D point) {\r
+        Rectangle2D bounds = getBoundsInLocal().getBounds2D();\r
+        expand(bounds, 1, 1);\r
+        double control = 3.0;\r
+        Rectangle2D corner = new Rectangle2D.Double(bounds.getMaxX() - control, bounds.getMaxY() - control, control, control);\r
+        return corner.contains(point);\r
+    }\r
+\r
+    private void resize(Point2D local) {\r
+        Rectangle2D bounds = getBoundsInLocal().getBounds2D();\r
+        double x = bounds.getX();\r
+        double y = bounds.getY();\r
+        double dx = local.getX() - bounds.getMaxX();\r
+        double dy = local.getY() - bounds.getMaxY();\r
+        double w = bounds.getWidth() + dx;\r
+        double h = bounds.getHeight() + dy;\r
+        bounds.setRect(\r
+                x, \r
+                y, \r
+                w > 20 ? w : 20, \r
+                        h > 20 ? h : 20\r
+                );\r
+        setBounds(bounds);\r
+    }\r
+\r
+    @Override\r
+    protected boolean mouseDragged(MouseDragBegin e) {\r
+        if(dragging) {\r
+            return true; // Eat event for faster resize\r
+        } else {\r
+            return false;\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    protected boolean mouseButtonReleased(MouseButtonReleasedEvent e) {\r
+        if(dragging) {\r
+            Point2D local = controlToLocal( e.controlPosition );\r
+            local = parentToLocal(local);\r
+            if(Math.abs(bounds.getMaxX() - local.getX()) > 3 ||\r
+                    Math.abs(bounds.getMaxY() - local.getY()) > 3) {\r
+                resize(local);\r
+            }\r
+            dragging = false;\r
+            if(resizeListener != null)\r
+                resizeListener.elementResized(bounds);\r
+        }\r
+        return false;\r
+    }\r
+\r
+    @Override\r
+    public int getEventMask() {\r
+        return EventTypes.MouseButtonPressedMask\r
+                | EventTypes.MouseMovedMask\r
+                | EventTypes.MouseButtonReleasedMask\r
+                ;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartSceneGraph.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ChartSceneGraph.java
new file mode 100644 (file)
index 0000000..7ca9692
--- /dev/null
@@ -0,0 +1,159 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.element;\r
+\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.jfree.chart.JFreeChart;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.DiagramUtils;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.SceneGraphNodeKey;\r
+import org.simantics.g2d.element.handler.HandleMouseEvent;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.PropertySetter;\r
+import org.simantics.g2d.element.handler.SceneGraph;\r
+import org.simantics.scenegraph.Node;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.IG2DNode;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseEnterEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseExitEvent;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintListener;\r
+import org.simantics.utils.datastructures.hints.IHintObservable;\r
+\r
+/**\r
+ * Chart scenegraph for chart elements in diagrams\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartSceneGraph  implements SceneGraph, HandleMouseEvent, InternalSize {\r
+    private static final long serialVersionUID = 1875762898776996989L;\r
+\r
+    public static final Key KEY_SG_NODE = new SceneGraphNodeKey(Node.class, "CHART_SG_NODE");\r
+    public static final Key KEY_SG_SELECTION_NODE = new SceneGraphNodeKey(Node.class, "CHART_SG_SELECTION_NODE");\r
+\r
+    protected IHintListener hoverHintListener;\r
+\r
+    public ChartSceneGraph() {\r
+    }\r
+\r
+    /**\r
+     * Expands bounds a little to allow selecting and grabbing a chart element\r
+     * from outside the chart graphics\r
+     */\r
+    @Override\r
+    public Rectangle2D getBounds(IElement e, Rectangle2D s) {\r
+        if (s==null) s = new Rectangle2D.Double();\r
+\r
+        IG2DNode node = (IG2DNode)e.getHint(KEY_SG_NODE);\r
+        AffineTransform at = (AffineTransform)e.getHint(ElementHints.KEY_TRANSFORM);\r
+        if(at != null && node != null && node.getBoundsInLocal() != null) {\r
+            Shape shape = node.getBoundsInLocal();\r
+            Rectangle2D r = shape.getBounds2D();\r
+            double scaleX = at.getScaleX();\r
+            double scaleY = at.getScaleY();\r
+            ChartNode.expand(r, 1 * scaleX, 1 * scaleY);\r
+            shape = r;\r
+            s.setFrame(shape.getBounds2D());\r
+        } else {\r
+            s.setFrame((Rectangle2D)e.getHint(ElementHints.KEY_BOUNDS));\r
+        }\r
+        return s;\r
+    }\r
+\r
+    @Override\r
+    public void cleanup(IElement e) {\r
+        if(hoverHintListener != null)\r
+            e.removeHintListener(hoverHintListener);\r
+\r
+        Node node = e.removeHint(KEY_SG_NODE);\r
+        if (node != null)\r
+            node.remove();\r
+    }\r
+\r
+    @Override\r
+    public void init(final IElement e, G2DParentNode parent) {\r
+        ChartNode node = e.getHint(KEY_SG_NODE);\r
+        if(node == null) {\r
+            // Create a new chart node\r
+            node = parent.getOrCreateNode("chart_"+e.hashCode(), ChartNode.class);\r
+\r
+            Rectangle2D bounds = (Rectangle2D)e.getHint(ElementHints.KEY_BOUNDS);\r
+            if(bounds == null) {\r
+                bounds = new Rectangle2D.Double(-40, -40, 80, 80);\r
+                e.setHint(ElementHints.KEY_BOUNDS, bounds);\r
+            }\r
+            node.setBounds(bounds);\r
+\r
+            JFreeChart chart = e.getHint(ChartElementFactory.KEY_CHART);\r
+            if(chart != null)\r
+                node.setChart(chart);\r
+\r
+            // Add a resize listener for updating bounds information to graph after resizing\r
+            node.setResizeListener(new ResizeListener() {\r
+\r
+                @Override\r
+                public void elementResized(Rectangle2D newBounds) {\r
+                    e.setHint(ElementHints.KEY_BOUNDS, newBounds);\r
+                    IDiagram diagram = ElementUtils.getDiagram(e);\r
+                    DiagramUtils.synchronizeHintsToBackend(diagram, e);\r
+                }\r
+            });\r
+\r
+            e.setHint(KEY_SG_NODE, node);\r
+        }\r
+\r
+        // Hover listening\r
+        hoverHintListener = new IHintListener() {\r
+            @Override\r
+            public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {\r
+\r
+            }\r
+\r
+            @Override\r
+            public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
+                if(key == ElementHints.KEY_HOVER) {\r
+                    IElement e = (IElement)sender;\r
+                    ChartNode name = (ChartNode) e.getHint(KEY_SG_NODE);\r
+                    if (name != null)\r
+                        name.setHover(Boolean.TRUE.equals(e.getHint(ElementHints.KEY_HOVER)));\r
+                }\r
+            }\r
+        };\r
+        e.addHintListener(hoverHintListener);\r
+\r
+        update(e);\r
+    }\r
+\r
+    public void update(IElement e) {\r
+        PropertySetter setter = e.getElementClass().getSingleItem(PropertySetter.class);\r
+        setter.syncPropertiesToNode(e);\r
+    }\r
+\r
+    \r
+    @Override\r
+    public boolean handleMouseEvent(IElement e, ICanvasContext ctx, MouseEvent me) {\r
+        if (me instanceof MouseEnterEvent) {\r
+            e.setHint(ElementHints.KEY_HOVER, true);\r
+        } else if (me instanceof MouseExitEvent) {\r
+            e.setHint(ElementHints.KEY_HOVER, false);\r
+        }\r
+        return false;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/PopulateChartDropParticipant.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/PopulateChartDropParticipant.java
new file mode 100644 (file)
index 0000000..2d7c5a9
--- /dev/null
@@ -0,0 +1,116 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.element;\r
+\r
+import java.awt.datatransfer.Transferable;\r
+import java.awt.datatransfer.UnsupportedFlavorException;\r
+import java.awt.dnd.DnDConstants;\r
+import java.awt.dnd.DropTargetDragEvent;\r
+import java.awt.geom.AffineTransform;\r
+import java.io.IOException;\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.common.request.UnaryRead;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;\r
+import org.simantics.g2d.dnd.DnDHints;\r
+import org.simantics.g2d.dnd.ElementClassDragItem;\r
+import org.simantics.g2d.dnd.IDnDContext;\r
+import org.simantics.g2d.dnd.IDropTargetParticipant;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.modeling.ui.diagramEditor.PopulateElementDropParticipant;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.dnd.LocalObjectTransfer;\r
+import org.simantics.ui.dnd.LocalObjectTransferable;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Drop participant for dropping chart definitions into diagrams\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PopulateChartDropParticipant extends PopulateElementDropParticipant implements IDropTargetParticipant {\r
+\r
+    public PopulateChartDropParticipant(GraphToDiagramSynchronizer synchronizer) {\r
+        super(synchronizer);\r
+    }\r
+\r
+    @Override\r
+    public void dragEnter(DropTargetDragEvent dtde, final IDnDContext dp) {\r
+        Transferable tr = dtde.getTransferable();\r
+        if (tr.isDataFlavorSupported(LocalObjectTransferable.FLAVOR)) {\r
+\r
+            Session session = synchronizer.getSession();\r
+\r
+            Object obj = null;\r
+\r
+            try {\r
+                obj = tr.getTransferData(LocalObjectTransferable.FLAVOR);\r
+                \r
+                // Create a structural selection from transfer data\r
+                if (!(obj instanceof IStructuredSelection)) {\r
+                    obj = LocalObjectTransfer.getTransfer().getObject();\r
+                }\r
+\r
+                if (obj instanceof IStructuredSelection) {\r
+\r
+                    IStructuredSelection sel = (IStructuredSelection) obj;\r
+                    \r
+                    // Can drop only one chart at the time\r
+                    if (sel.size() == 1) {\r
+                        \r
+                        // Get the chart definition\r
+                        Resource chart = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
+                        if (chart == null)\r
+                            return;\r
+\r
+                        ElementClassDragItem item = session.syncRequest(new UnaryRead<Resource,ElementClassDragItem>(chart) {\r
+\r
+                            @Override\r
+                            public ElementClassDragItem perform(ReadGraph graph) throws DatabaseException {\r
+                                if(graph.isInstanceOf(parameter, JFreeChartResource.getInstance(graph).Chart)) {\r
+                                    ElementClassDragItem item = new ElementClassDragItem(ChartElementFactory.create(graph, parameter));\r
+                                    AffineTransform initialTr = AffineTransform.getScaleInstance(1, 1);\r
+                                    item.getHintContext().setHint(ElementHints.KEY_TRANSFORM, initialTr);\r
+                                    return item;\r
+                                } else {\r
+                                    return null;\r
+                                }\r
+\r
+                            }\r
+                        });\r
+\r
+                        if(item != null) {\r
+                            dp.add(item);\r
+                            dp.getHints().setHint(DnDHints.KEY_DND_GRID_COLUMNS, Integer.valueOf(1));\r
+                        }\r
+\r
+                    }\r
+\r
+                }\r
+\r
+            } catch (UnsupportedFlavorException e) {\r
+                e.printStackTrace();\r
+            } catch (IOException e) {\r
+                e.printStackTrace();\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+\r
+        }\r
+\r
+        dtde.acceptDrag(DnDConstants.ACTION_COPY);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ResizeListener.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/element/ResizeListener.java
new file mode 100644 (file)
index 0000000..4c31a6b
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.element;\r
+\r
+import java.awt.geom.Rectangle2D;\r
+\r
+/**\r
+ * Interface for listeners listening resize events in chart nodes\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface ResizeListener {\r
+    \r
+    /**\r
+     * Triggered when a node has been resized\r
+     * @param newBounds new bounds for the node\r
+     */\r
+    public void elementResized(Rectangle2D newBounds);\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisChildRule.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisChildRule.java
new file mode 100644 (file)
index 0000000..af8071f
--- /dev/null
@@ -0,0 +1,68 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.ge;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * ChildRule for finding the axis of a JFreeChart\r
+ *  \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class AxisChildRule implements ChildRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {\r
+        ArrayList<Resource> result = new ArrayList<Resource>();\r
+        if(!(parent instanceof Resource))\r
+            return result;\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        /*\r
+         * 1. chart may have multiple plots\r
+         * 2. plot may have multiple axis\r
+         */\r
+        for(Resource plot : graph.syncRequest(new ObjectsWithType((Resource)parent, l0.ConsistsOf, jfree.Plot))) {\r
+            Resource rangeAxisList = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
+            if(rangeAxisList != null)\r
+                for(Resource axis : ListUtils.toList(graph, rangeAxisList)) {\r
+                    result.add(axis);\r
+                }\r
+        }\r
+        return result;\r
+\r
+\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getParents(ReadGraph graph, Object child) throws DatabaseException {\r
+        return new ArrayList<Resource>();\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisDropAction.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisDropAction.java
new file mode 100644 (file)
index 0000000..20f79bb
--- /dev/null
@@ -0,0 +1,104 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.ge;\r
+\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.DropActionFactory;\r
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Action for dropping axis on top of other axis or series in {@link AxisAndVariablesExplorerComposite}\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class AxisDropAction  implements DropActionFactory {\r
+\r
+    @Override\r
+    public Runnable create(ReadGraph g, Object target, Object source) throws DatabaseException {\r
+        // Make sure that both target and source are resources\r
+        Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);\r
+        Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);\r
+        \r
+        if(t == null || s == null)\r
+            return null;\r
+        \r
+        // Make sure that source and target are of correct type\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
+        if(!g.isInstanceOf(s, jfree.Axis))\r
+            return null;\r
+        if(!g.isInstanceOf(t, jfree.Series) && !g.isInstanceOf(t, jfree.Axis))\r
+            return null;\r
+        \r
+        return getRunnable(t, s);\r
+    }\r
+\r
+    /**\r
+     * Get the runnable for doing the drop action \r
+     * \r
+     * @param t target resource\r
+     * @param s source resource\r
+     * @return Runnable\r
+     */\r
+    private Runnable getRunnable(final Resource t, final Resource s) {\r
+        Runnable runnable = new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        if(t == null || s == null) return;\r
+                        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        Resource target = t;\r
+                        Resource source = s;\r
+                        \r
+                        // Dragged axis always exists in the same list with target axis, so it is safe to get the target index\r
+                        Resource plot = graph.getPossibleObject(source, l0.PartOf);\r
+                        Resource axisListResource = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
+                        List<Resource> axisList = ListUtils.toList(graph, axisListResource);\r
+                        if(graph.isInstanceOf(target, jfree.Series)) {\r
+                            // Dropped a axis over a series -> get the axis of the series\r
+                            Resource dataset = graph.getPossibleObject(target, l0.PartOf);\r
+                            target = graph.getPossibleObject(dataset, jfree.Dataset_mapToRangeAxis);\r
+                        }\r
+                        \r
+                        // move axis to target position\r
+                        int targetIndex = axisList.indexOf(target);\r
+                        axisList.remove(source);\r
+                        axisList.add(targetIndex, source);\r
+                        \r
+                        // Update the range axis list\r
+                        graph.deny(plot, jfree.Plot_rangeAxisList);\r
+                        axisListResource = ListUtils.create(graph, axisList);\r
+                        graph.claim(plot, jfree.Plot_rangeAxisList, axisListResource);\r
+                    }\r
+\r
+                });\r
+            }\r
+        };\r
+        return runnable;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisLabelRule.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisLabelRule.java
new file mode 100644 (file)
index 0000000..d501c6b
--- /dev/null
@@ -0,0 +1,67 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.ge;\r
+\r
+import java.util.Collections;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.labels.LabelRule;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Label rule for range axis label\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class AxisLabelRule implements LabelRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    /**\r
+     * Range axis label\r
+     * \r
+     * Options:\r
+     * 1. Label\r
+     * 2. Default\r
+     */\r
+    @Override\r
+    public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        Resource resource = (Resource)content;\r
+        String label = graph.getPossibleRelatedValue(resource, l0.HasLabel, Bindings.STRING);\r
+        if(label == null || label.isEmpty()) {\r
+            label = "Range";\r
+            Resource plot = graph.getPossibleObject(resource, l0.PartOf);\r
+            if(plot != null) {\r
+                Resource axisListResource = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
+                if(axisListResource != null) {\r
+                    List<Resource> axisList = ListUtils.toList(graph, axisListResource);\r
+                    if(axisList.contains(resource))\r
+                        label = label + " " + (axisList.indexOf(resource) + 1);\r
+                }\r
+            }\r
+        }\r
+        return Collections.singletonMap(ColumnKeys.SINGLE, label);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesChildRule.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesChildRule.java
new file mode 100644 (file)
index 0000000..3e058fb
--- /dev/null
@@ -0,0 +1,67 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.ge;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Child rule for obtaining series in a chart. \r
+ * Assumes that the chart has only one plot and that plot has only one dataset\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SeriesChildRule implements ChildRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {\r
+        ArrayList<Resource> result = new ArrayList<Resource>();\r
+        if(!(parent instanceof Resource))\r
+            return result;\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        /*\r
+         * 1. we assume that there is only one plot\r
+         * 2. we assume that the only plot has only one dataset\r
+         */\r
+        Resource plot = graph.syncRequest(new PossibleObjectWithType((Resource)parent, l0.ConsistsOf, jfree.Plot));\r
+        \r
+        Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+        \r
+        Resource seriesList = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+        if(seriesList != null)\r
+            for(Resource series : ListUtils.toList(graph, seriesList)) {\r
+                result.add(series);\r
+            }\r
+        return result;\r
+    }\r
+    \r
+    @Override\r
+    public Collection<?> getParents(ReadGraph graph, Object child) throws DatabaseException {\r
+        return new ArrayList<Resource>();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesDropAction.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesDropAction.java
new file mode 100644 (file)
index 0000000..5870cd5
--- /dev/null
@@ -0,0 +1,139 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.ge;\r
+\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.DropActionFactory;\r
+import org.simantics.jfreechart.chart.properties.xyline.XYLineAxisAndVariablesTab;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Drop action for explorer in {@link XYLineAxisAndVariablesTab}. This action is used for dropping \r
+ * both series on axis or another sries\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SeriesDropAction implements DropActionFactory {\r
+\r
+    @Override\r
+    public Runnable create(ReadGraph g, Object target, Object source) throws DatabaseException {\r
+        // Make sure that both target and source are resources\r
+        Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);\r
+        Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);\r
+        \r
+        if(t == null || s == null)\r
+            return null;\r
+        \r
+        // Make sure that source and target are of correct type\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
+        if(!g.isInstanceOf(s, jfree.Series))\r
+            return null;\r
+        if(!g.isInstanceOf(t, jfree.Series) && !g.isInstanceOf(t, jfree.Axis))\r
+            return null;\r
+        \r
+        return getRunnable(t, s);\r
+    }\r
+\r
+    /**\r
+     * Get the runnable for doing the drop action \r
+     * \r
+     * @param t target resource\r
+     * @param s source resource\r
+     * @return Runnable\r
+     */\r
+    private Runnable getRunnable(final Resource t, final Resource s) {\r
+        Runnable runnable = new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        if(t == null || s == null) return;\r
+                        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        Resource target = t;\r
+                        Resource source = s;\r
+                        Resource droppedOnSeries = null;\r
+\r
+                        // Dropped a series over a series -> get target dataset\r
+                        if(graph.isInstanceOf(target, jfree.Series)) {\r
+                            droppedOnSeries = target;\r
+                            Resource dataset = graph.getPossibleObject(target, l0.PartOf);\r
+                            if(dataset != null)\r
+                                target = dataset;\r
+                        }\r
+\r
+                        // Dropped a series over an axis -> get target dataset\r
+                        if(graph.isInstanceOf(target, jfree.Axis)) {\r
+                            Resource dataset = graph.syncRequest(new PossibleObjectWithType(target, jfree.Dataset_mapToRangeAxis_Inverse, jfree.Dataset));\r
+                            if(dataset != null)\r
+                                target = dataset;\r
+                        }\r
+\r
+                        // Move series to a dataset\r
+                        if(graph.isInstanceOf(target, jfree.Dataset)) {\r
+                            // Remove from old dataset if it was different than the new one\r
+                            Resource sourceDataset = graph.getPossibleObject(source, l0.PartOf);\r
+                            if(sourceDataset != null && !sourceDataset.equals(target)) {\r
+                                Resource sourceSeriesList = graph.getPossibleObject(sourceDataset, jfree.Dataset_seriesList);\r
+                                if(sourceSeriesList != null)\r
+                                    ListUtils.removeElement(graph, sourceSeriesList, source);\r
+                            }\r
+                            graph.deny(source, l0.PartOf);\r
+\r
+                            // Add to new dataset\r
+                            Resource targetSeriesList = graph.getPossibleObject(target, jfree.Dataset_seriesList);\r
+                            if(targetSeriesList == null) {\r
+                                targetSeriesList = ListUtils.create(graph, Collections.<Resource>emptyList());\r
+                                graph.claim(target, jfree.Dataset_seriesList, targetSeriesList);\r
+                            }\r
+\r
+\r
+                            // Series was dropped on another series. Move the dropped series to that place and recreate the list\r
+                            if(droppedOnSeries != null) {\r
+                                List<Resource> list = ListUtils.toList(graph, targetSeriesList);\r
+                                int targetIndex = list.indexOf(droppedOnSeries);\r
+                                if(list.contains(source))\r
+                                    list.remove(source);\r
+                                list.add(targetIndex, source);\r
+                                graph.deny(target, jfree.Dataset_seriesList);\r
+                                targetSeriesList = ListUtils.create(graph, list);\r
+                                graph.claim(target, jfree.Dataset_seriesList, targetSeriesList);\r
+                            } else {\r
+                                ListUtils.insertFront(graph, targetSeriesList, Collections.singleton(source));\r
+                            }\r
+\r
+                            graph.claim(target, l0.ConsistsOf, source);\r
+                        }\r
+                    }\r
+                });\r
+            }\r
+        };\r
+        return runnable;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesLabelDecorationRule.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesLabelDecorationRule.java
new file mode 100644 (file)
index 0000000..b7b9a37
--- /dev/null
@@ -0,0 +1,63 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.ge;\r
+\r
+import org.eclipse.jface.resource.FontDescriptor;\r
+import org.simantics.browsing.ui.content.LabelDecorator;\r
+import org.simantics.browsing.ui.model.labeldecorators.LabelDecorationRule;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class SeriesLabelDecorationRule implements LabelDecorationRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public LabelDecorator getLabelDecorator(ReadGraph graph, Object content) throws DatabaseException {\r
+        Resource resource = AdaptionUtils.adaptToSingle(content, Resource.class);\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+        if (resource != null && graph.isInstanceOf(resource, jfree.Series)) {\r
+            final String[] filter = graph.getPossibleRelatedValue(resource, jfree.variableFilter, Bindings.STRING_ARRAY);\r
+            if(filter != null) {\r
+                return new LabelDecorator.Stub() {\r
+                    @Override\r
+                    public String decorateLabel(String label, String column, int itemIndex) {\r
+                        label += " [";\r
+                        for(int i = 0; i < filter.length; i++) {\r
+                            label += filter[i];\r
+                            if(i < filter.length - 1)\r
+                                label += ", ";\r
+                        }\r
+                        label += "]";\r
+                        return label;\r
+                    }\r
+\r
+                    @SuppressWarnings("unchecked")\r
+                    @Override\r
+                    public <F> F decorateFont(F font, String column, int itemIndex) {\r
+                        return (F) ((FontDescriptor) font);\r
+                    }\r
+                };\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesLabelRule.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesLabelRule.java
new file mode 100644 (file)
index 0000000..399c4d0
--- /dev/null
@@ -0,0 +1,65 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.ge;\r
+\r
+import java.util.Collections;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.labels.LabelRule;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.jfreechart.chart.properties.IAllVariablesOfModel;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Label rule for dataset series\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SeriesLabelRule implements LabelRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    /**\r
+     * Options:\r
+     * 1. Label\r
+     * 2. Variable rvi\r
+     * 3. Default\r
+     */\r
+    @Override\r
+    public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        Resource resource = (Resource)content;\r
+        String label = graph.getPossibleRelatedValue(resource, l0.HasLabel, Bindings.STRING);\r
+        if(label == null || label.isEmpty()) {\r
+               IAllVariablesOfModel vom = graph.adapt(resource, IAllVariablesOfModel.class);\r
+               \r
+               String rvi = graph.getPossibleRelatedValue(resource, jfree.variableRVI);\r
+               if (rvi != null) {\r
+                       label =vom.getVariablesLabel(graph, rvi);\r
+                       if (label == null)\r
+                               label = rvi;\r
+               } else\r
+                label = "Set variable";\r
+        }\r
+        return Collections.singletonMap(ColumnKeys.SINGLE, label);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/VariableChildRule.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/VariableChildRule.java
new file mode 100644 (file)
index 0000000..afe693d
--- /dev/null
@@ -0,0 +1,75 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.ge;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * ChildRule for finding the series of an axis\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class VariableChildRule implements ChildRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {\r
+        ArrayList<Resource> result = new ArrayList<Resource>();\r
+        if(!(parent instanceof Resource))\r
+            return result;\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        Resource axis = (Resource)parent;\r
+        /*\r
+         * 1. Axis belongs to a plot\r
+         * 2. Plot may have multiple datasets\r
+         * 3. Dataset is mapped to a single range axis\r
+         * 3. Dataset may have multiple seires\r
+         */\r
+        Resource plot = graph.getPossibleObject(axis, jfree.Plot_rangeAxis_Inverse);\r
+        if(plot == null)\r
+            return result;\r
+\r
+        for(Resource dataset : graph.syncRequest(new ObjectsWithType(plot, l0.ConsistsOf, jfree.Dataset))) {\r
+            if(graph.hasStatement(dataset, jfree.Dataset_mapToRangeAxis, axis)) {\r
+                Resource seriesList = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+                if(seriesList != null)\r
+                    for(Resource series : ListUtils.toList(graph, seriesList)) {\r
+                        result.add(series);\r
+                    }\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getParents(ReadGraph graph, Object child) throws DatabaseException {\r
+        return new ArrayList<Resource>();\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AdjustableTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AdjustableTab.java
new file mode 100644 (file)
index 0000000..7fffd39
--- /dev/null
@@ -0,0 +1,111 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.swt.events.ControlEvent;\r
+import org.eclipse.swt.events.ControlListener;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.selectionview.StandardProperties;\r
+\r
+/**\r
+ * Tab adjusting the layout depending on its dimensions.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public abstract class AdjustableTab extends LabelPropertyTabContributor {\r
+\r
+       private Composite spp;\r
+       private ControlListener controlListener;\r
+       private static final int WIDE_SCREEN_WIDTH = 1100;\r
+       protected Composite composite;\r
+       \r
+       @Override\r
+       public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport _support) {\r
+               // Get size of the available area.\r
+               spp = body;\r
+               do {\r
+                       spp = spp.getParent();\r
+               } while (!(spp instanceof StandardProperties));\r
+               \r
+               // Add listener to change the layout when the composite resizes.\r
+               spp.addControlListener(controlListener = new ControlListener(){\r
+\r
+                       @Override\r
+                       public void controlMoved(ControlEvent e) {}\r
+\r
+                       @Override\r
+                       public void controlResized(ControlEvent e) {\r
+                               createLayout();\r
+                       }\r
+               });\r
+               \r
+               // Create the controls and their initial layout.\r
+               createAndAddControls(body, site, context, _support);\r
+               createLayout(); \r
+       }\r
+\r
+       /**\r
+        * Create controls and add them to the tab.\r
+        * @param body the composite where the controls are added.\r
+        * @param site\r
+        * @param context\r
+        * @param _support\r
+        */\r
+       protected abstract void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport _support);\r
+\r
+       /**\r
+        *  Create layout for controls.\r
+        */\r
+       protected void createLayout() {\r
+               if (composite == null || composite.isDisposed())\r
+                       return;\r
+               \r
+               Point size = spp.getSize();\r
+               if (size.x > size.y) {\r
+                       createControlLayoutHorizontal((size.x > WIDE_SCREEN_WIDTH));\r
+               } else {\r
+                       createControlLayoutVertical();\r
+               }\r
+       }\r
+       \r
+       /**\r
+        * Determine if the layout uses vertical layout\r
+        * @return true iff the layout uses vertical layout\r
+        */\r
+       protected boolean isVertical() {\r
+               Point size = spp.getSize();\r
+               return size.x < size.y;\r
+       }\r
+       \r
+       /**\r
+        * Create vertical layout for controls.\r
+        */\r
+       protected abstract void createControlLayoutVertical();\r
+\r
+       /**\r
+        * Create horizontal layout for controls.\r
+        * @param wideScreen true iff the control is wider than WIDE_SCREEN_WIDTH\r
+        */\r
+       protected abstract void createControlLayoutHorizontal(boolean wideScreen);\r
+\r
+//     @Override\r
+//     public void dispose() {\r
+//             if(controlListener != null && spp != null)\r
+//                     spp.removeControlListener(controlListener);\r
+//     }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AllVariablesOfModel.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AllVariablesOfModel.java
new file mode 100644 (file)
index 0000000..f3fcd7d
--- /dev/null
@@ -0,0 +1,57 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+\r
+public class AllVariablesOfModel implements Read<Collection<ChartVariable>> {\r
+       \r
+       public Resource model;\r
+       \r
+       /**\r
+        * Queries all variables of a model \r
+        * @param res the model.\r
+        */\r
+       public AllVariablesOfModel(Resource res) {\r
+               this.model = res;\r
+       }\r
+       \r
+       public Resource getModel() {\r
+               return model;\r
+       }\r
+       \r
+       @Override\r
+       public Collection<ChartVariable> perform(ReadGraph graph) throws DatabaseException {\r
+               if(!graph.hasStatement(model))\r
+                return Collections.emptyList();\r
+               IAllVariablesOfModel query = graph.adapt(model, IAllVariablesOfModel.class);\r
+               return graph.syncRequest(query.getVariablesQuery());\r
+       }\r
+       \r
+       public static AllVariablesOfModel withRandomResource(ISessionContext context, final Resource resource) throws DatabaseException {\r
+               Resource model  = context.getSession().syncRequest(new Read<Resource>() {\r
+\r
+               @Override\r
+               public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                   Resource r = resource;\r
+                   while((r = graph.getPossibleObject(r, Layer0.getInstance(graph).PartOf)) != null) {\r
+                       if(graph.isInstanceOf(r, SimulationResource.getInstance(graph).Model))\r
+                           return r;\r
+                   }\r
+                   return null;\r
+               }\r
+               \r
+           });\r
+               if (model == null)\r
+                       return null;\r
+               return new AllVariablesOfModel(model);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AxisHidePropertyComposite.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/AxisHidePropertyComposite.java
new file mode 100644 (file)
index 0000000..02960a8
--- /dev/null
@@ -0,0 +1,67 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Class containing properties for hiding pars of an axis\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class AxisHidePropertyComposite extends Composite {\r
+\r
+    public AxisHidePropertyComposite(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
+        super(parent, style);\r
+        \r
+        GridLayoutFactory.fillDefaults().applyTo(this);\r
+        \r
+        Group hideGroup  = new Group(this, SWT.NONE);\r
+        hideGroup.setText("Hide");\r
+        GridDataFactory.fillDefaults().applyTo(hideGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(hideGroup);\r
+        \r
+        Button label = new Button(hideGroup, support, SWT.CHECK);\r
+        label.setText("Label");\r
+        label.setSelectionFactory(new BooleanPropertyFactory(null, JFreeChartResource.URIs.Axis_visibleLabel, true));\r
+        label.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Axis_visibleLabel));\r
+        GridDataFactory.fillDefaults().applyTo(label.getWidget());\r
+\r
+        Button tmarks = new Button(hideGroup, support, SWT.CHECK);\r
+        tmarks.setText("Tick marks");\r
+        tmarks.setSelectionFactory(new BooleanPropertyFactory(null, JFreeChartResource.URIs.Axis_visibleTickMarks, true));\r
+        tmarks.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Axis_visibleTickMarks));\r
+        GridDataFactory.fillDefaults().applyTo(tmarks.getWidget());\r
+        \r
+        Button axisLine = new Button(hideGroup, support, SWT.CHECK);\r
+        axisLine.setText("Axis line");\r
+        axisLine.setSelectionFactory(new BooleanPropertyFactory(null, JFreeChartResource.URIs.Axis_visibleAxisLine, true));\r
+        axisLine.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Axis_visibleAxisLine));\r
+        GridDataFactory.fillDefaults().applyTo(axisLine.getWidget());\r
+\r
+        Button tlabels = new Button(hideGroup, support, SWT.CHECK);\r
+        tlabels.setText("Tick labels");\r
+        tlabels.setSelectionFactory(new BooleanPropertyFactory(null, JFreeChartResource.URIs.Axis_visibleTickLabels, true));\r
+        tlabels.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Axis_visibleTickLabels));\r
+        GridDataFactory.fillDefaults().applyTo(tlabels.getWidget());\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/BooleanPropertyFactory.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/BooleanPropertyFactory.java
new file mode 100644 (file)
index 0000000..751a134
--- /dev/null
@@ -0,0 +1,130 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.utils.datastructures.Quad;\r
+\r
+/**\r
+ * PropertyFactory for finding a boolean property. Supports also finding the \r
+ * property from a first occurrence of resource ConsistsOf type HasProperty   \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class BooleanPropertyFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+\r
+    final private String propertyURI;\r
+    final private String typeURI;\r
+    final private Boolean inverse;\r
+    final private Boolean defaultValue;\r
+    \r
+    /**\r
+     * PropertyFactory for finding a boolean property with propertyURI\r
+     * \r
+     * @param propertyURI URI for the boolean property\r
+     */\r
+    public BooleanPropertyFactory(String propertyURI) {\r
+        this(null, propertyURI, false);\r
+    }\r
+    \r
+    /**\r
+     * PropertyFactory for finding a boolean property with propertyURI.\r
+     * \r
+     * Supports inverting the result (e.g. if required information is IsHidden, but database contains IsVisible)\r
+     * \r
+     * @param propertyURI URI for the boolean property\r
+     * @param inverse Invert the result?\r
+     */\r
+    public BooleanPropertyFactory(String propertyURI, boolean inverse) {\r
+        this(null, propertyURI, inverse);\r
+    }\r
+\r
+    /**\r
+     * PropertyFactory for finding a boolean property with propertyURI.\r
+     *  \r
+     * Finds the property for first ObjectWithType(resource, L0.ConsistsOf, type)\r
+     *  \r
+     * Supports inverting the result (e.g. if required information is IsHidden, but database contains IsVisible)\r
+     *  \r
+     * @param typeURI URI for a resource (resource ConsistsOf type) (null allowed)\r
+     * @param propertyURI URI for the boolean property\r
+     * @param inverse Invert the result?\r
+     */\r
+    public BooleanPropertyFactory(String typeURI, String propertyURI, boolean inverse) {\r
+        this(typeURI, propertyURI, inverse, false);\r
+    }\r
+    \r
+    /**\r
+     * PropertyFactory for finding a boolean property with propertyURI.\r
+     *  \r
+     * Finds the property for first ObjectWithType(resource, L0.ConsistsOf, type)\r
+     *  \r
+     * Supports inverting the result (e.g. if required information is IsHidden, but database contains IsVisible)\r
+     * \r
+     * @param typeURI URI for a resource (resource ConsistsOf type) (null allowed -> not used)\r
+     * @param propertyURI URI for the boolean property\r
+     * @param inverse Invert the result?\r
+     * @param defaultValue default value\r
+     */\r
+    public BooleanPropertyFactory(String typeURI, String propertyURI, boolean inverse, boolean defaultValue) {\r
+        this.propertyURI = propertyURI;\r
+        this.inverse = inverse;\r
+        this.typeURI = typeURI;\r
+        this.defaultValue = defaultValue;\r
+    }\r
+\r
+    @Override\r
+    public Object getIdentity(Object inputContents) {\r
+        return new Quad<Resource, String, Object, Boolean>((Resource) inputContents, propertyURI, getClass(), defaultValue);\r
+    }\r
+\r
+    @Override\r
+    public Boolean perform(ReadGraph graph, Resource r) throws DatabaseException {\r
+        if(typeURI == null) {\r
+            // if no typeUri, use the default resource r\r
+            return getValue(graph, r);\r
+        } else {\r
+            // typeURI was defined, find the property for the first occurence of ConsistsOf type\r
+            Resource type =  graph.getResource(typeURI);\r
+            for(Resource o : graph.syncRequest(new ObjectsWithType(r, Layer0.getInstance(graph).ConsistsOf, type))) {\r
+                // Returns the value for the first occurrence\r
+                return getValue(graph, o);\r
+            }\r
+        }\r
+        // if nothing was found with typeURI\r
+        return false;\r
+    }\r
+    \r
+    /**\r
+     * Return the value for a Boolean literal possibly inverted (or default if resource != Boolean literal) \r
+     * \r
+     * @param graph ReadGraph\r
+     * @param resource Literal Boolean resource \r
+     * @return value of the parameter (or default or inverted)\r
+     * @throws DatabaseException\r
+     */\r
+    private Boolean getValue(ReadGraph graph, Resource resource) throws DatabaseException {\r
+        Boolean value = graph.getPossibleRelatedValue(resource, graph.getResource(propertyURI), Bindings.BOOLEAN);\r
+        if(value != null) {\r
+            return !inverse.equals(value);\r
+        } else {\r
+            return defaultValue;\r
+        }\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/BooleanSelectionListener.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/BooleanSelectionListener.java
new file mode 100644 (file)
index 0000000..3fe269b
--- /dev/null
@@ -0,0 +1,93 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.layer0.Layer0;\r
+\r
+/**\r
+ * Class for setting a boolean value when a selection occurs. (check box buttons)\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class BooleanSelectionListener extends SelectionListenerImpl<Resource> {\r
+\r
+    final private String propertyURI;\r
+    final private String typeUri;\r
+    final private boolean defaultValue;\r
+    \r
+    /**\r
+     * Boolean selection listener for property with propertyURI\r
+     * \r
+     * @param context ISessionContext\r
+     * @param propertyURI uri of the boolean property\r
+     */\r
+    public BooleanSelectionListener(ISessionContext context, String propertyURI) {\r
+        this(context, null, propertyURI, false);\r
+    }\r
+\r
+    /**\r
+     * Boolean selection listener for property with propertyURI\r
+     * Sets the property for all ObjectWithType(resource, L0.ConsistsOf, type)\r
+     * \r
+     * @param context ISessionContext\r
+     * @param typeUri URI for a resource (resource ConsistsOf type) (null allowed -> not used)\r
+     * @param propertyURI uri of the boolean property\r
+     * @param defaultValue expected value if the property does not exist\r
+     */\r
+    public BooleanSelectionListener(ISessionContext context, String typeUri, String propertyURI, boolean defaultValue) {\r
+        super(context);\r
+        this.propertyURI = propertyURI;\r
+        this.typeUri = typeUri;\r
+        this.defaultValue = defaultValue;\r
+    }\r
+    \r
+    public BooleanSelectionListener(ISessionContext context, String typeUri, String propertyURI) {\r
+       this(context, typeUri, propertyURI, false);\r
+    }\r
+\r
+\r
+    @Override\r
+    public void apply(WriteGraph graph, Resource chart) throws DatabaseException {\r
+        if(typeUri == null) {\r
+            setValue(graph, chart);\r
+        } else {\r
+            Resource type =  graph.getResource(typeUri);\r
+            for(Resource object : graph.syncRequest(new ObjectsWithType(chart, Layer0.getInstance(graph).ConsistsOf, type))) {\r
+                setValue(graph, object);\r
+            }\r
+        }\r
+            \r
+    }\r
+    \r
+    /**\r
+     * Set boolean value for Boolean literal resource (inverts the current value).\r
+     * @param graph ReadGraph\r
+     * @param resource Boolean literal resource\r
+     * @throws DatabaseException\r
+     */\r
+    private void setValue(WriteGraph graph, Resource resource) throws DatabaseException {\r
+        Resource property =  graph.getResource(propertyURI);\r
+        Boolean value = graph.getPossibleRelatedValue(resource, property, Bindings.BOOLEAN);\r
+        if (value == null)\r
+               graph.claimLiteral(resource, property, !defaultValue);\r
+        else\r
+               graph.claimLiteral(resource, property, Boolean.FALSE.equals(value));\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartTab.java
new file mode 100644 (file)
index 0000000..d8d20f0
--- /dev/null
@@ -0,0 +1,45 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.ChartComposite;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Tab for displaying a chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartTab extends LabelPropertyTabContributor implements Widget {\r
+\r
+    private Composite parent;\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        support.register(this);\r
+        this.parent = body;\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, final Object input) {\r
+        Resource chart = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        new ChartComposite(parent, chart, SWT.BORDER);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariable.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariable.java
new file mode 100644 (file)
index 0000000..20ee638
--- /dev/null
@@ -0,0 +1,60 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+public class ChartVariable implements Comparable<ChartVariable>{\r
+       \r
+       private String rvi;\r
+       private String label;\r
+       \r
+       public ChartVariable(String rvi) {\r
+               this.rvi = rvi;\r
+       }\r
+       \r
+       public ChartVariable(String rvi, String label) {\r
+               this.rvi = rvi;\r
+               this.label = label;\r
+       }\r
+       \r
+       public String getRvi() {\r
+               return rvi;\r
+       }\r
+       \r
+       public String getLabel() {\r
+               return label;\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               if (label != null)\r
+                       return label;\r
+               return rvi;\r
+       }\r
+       \r
+       @Override\r
+       public int hashCode() {\r
+               return rvi.hashCode();\r
+       }\r
+       \r
+       @Override\r
+       public boolean equals(Object obj) {\r
+               if (obj == null)\r
+                       return false;\r
+               if (obj.getClass() != getClass())\r
+                       return false;\r
+               ChartVariable other = (ChartVariable)obj;\r
+               return rvi.equals(other.rvi);\r
+       }\r
+       \r
+       @Override\r
+       public int compareTo(ChartVariable o) {\r
+               int rvicomp = rvi.compareTo(o.rvi);\r
+               if (rvicomp == 0)\r
+                       return 0;\r
+               if (label != null && o.label != null) {\r
+                       int labelcomp =  label.compareTo(o.label);\r
+                       if (labelcomp != 0)\r
+                               return labelcomp;\r
+               }\r
+               return rvicomp;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariableFactory.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariableFactory.java
new file mode 100644 (file)
index 0000000..fea5415
--- /dev/null
@@ -0,0 +1,34 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+public class ChartVariableFactory extends ReadFactoryImpl<Resource, ChartVariable>{\r
+       \r
+       private Map<String,ChartVariable> map;\r
+       \r
+       public ChartVariableFactory(Collection<ChartVariable> data) {\r
+               map = new HashMap<String, ChartVariable>();\r
+               for (ChartVariable v : data) {\r
+                       map.put(v.getRvi(), v);\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public ChartVariable perform(ReadGraph graph, Resource input)\r
+                       throws DatabaseException {\r
+                String rvi = graph.getPossibleRelatedValue(input, JFreeChartResource.getInstance(graph).variableRVI);\r
+                if (rvi == null)\r
+                        return null;\r
+                return map.get(rvi);\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariableModifier.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ChartVariableModifier.java
new file mode 100644 (file)
index 0000000..a1e13dd
--- /dev/null
@@ -0,0 +1,95 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.jface.bindings.keys.KeyStroke;\r
+import org.eclipse.jface.bindings.keys.ParseException;\r
+import org.eclipse.jface.fieldassist.ContentProposalAdapter;\r
+import org.eclipse.jface.fieldassist.IContentProposal;\r
+import org.eclipse.jface.fieldassist.IContentProposalListener;\r
+import org.eclipse.jface.fieldassist.IContentProposalListener2;\r
+import org.eclipse.jface.fieldassist.TextContentAdapter;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+public class ChartVariableModifier extends StringChooserModifyListenerImpl<Resource, ChartVariable> {\r
+       \r
+        private boolean active;\r
+        private Control control;\r
+        \r
+        private char[] alphaNumericCharacters = {\r
+                       'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','Ã¥','ä','ö',\r
+                       'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Ã…','Ä','Ö',\r
+                       '1','2','3','4','5','6','7','8','9','0','.','_'};\r
+        \r
+        public ChartVariableModifier(Control control, WidgetSupport support) {\r
+               this.control = control;\r
+               this.active = true;\r
+               \r
+               KeyStroke keyStroke = null;\r
+               try {\r
+                   keyStroke = KeyStroke.getInstance("Ctrl+Space");\r
+               } catch (ParseException e1) {\r
+                   e1.printStackTrace();\r
+               }\r
+               \r
+               //SimpleContentProposalProvider scpp = new VariableProposalProvider(control, support);\r
+               VariableProposalProvider scpp = new VariableProposalProvider(control, support);\r
+               scpp.setFiltering(true);\r
+\r
+               ContentProposalAdapter adapter = new ContentProposalAdapter(\r
+                       control, new TextContentAdapter(), scpp, keyStroke, alphaNumericCharacters);\r
+               adapter.setAutoActivationDelay(0);\r
+               adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);\r
+               adapter.addContentProposalListener(new IContentProposalListener2() {\r
+\r
+                   @Override\r
+                   public void proposalPopupOpened(ContentProposalAdapter adapter) {\r
+                       if(ChartVariableModifier.this != null)\r
+                               ChartVariableModifier.this.deactivate();\r
+                   }\r
+\r
+                   @Override\r
+                   public void proposalPopupClosed(ContentProposalAdapter adapter) {\r
+                       if(ChartVariableModifier.this != null)\r
+                               ChartVariableModifier.this.activate();\r
+                   }\r
+               });\r
+\r
+               adapter.addContentProposalListener(new IContentProposalListener() {\r
+\r
+                       \r
+                   @Override\r
+                   public void proposalAccepted(IContentProposal proposal) {\r
+                       if(ChartVariableModifier.this.control != null && !ChartVariableModifier.this.control.isDisposed())\r
+                               ChartVariableModifier.this.modifySelection(new StringChooserModifyEvent<ChartVariable>(ChartVariableModifier.this.control, new ChartVariable(proposal.getContent(), proposal.getLabel()), proposal.getLabel()));\r
+                   }\r
+               });\r
+           \r
+           \r
+           }\r
+        \r
+        @Override\r
+       public void applyObject(WriteGraph graph, Resource resource, ChartVariable object, String text) throws DatabaseException {\r
+                   if(active) {\r
+                   JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                   graph.claimLiteral(resource, jfree.variableRVI, object.getRvi(), Bindings.STRING);\r
+                   graph.deny(resource, jfree.variableFilter);\r
+               }\r
+               \r
+       }\r
+           \r
+\r
+\r
+    public void deactivate() {\r
+        active = false;\r
+    }\r
+\r
+    public void activate() {\r
+        active = true;\r
+    }   \r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ColorPicker.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/ColorPicker.java
new file mode 100644 (file)
index 0000000..e5f003f
--- /dev/null
@@ -0,0 +1,388 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.eclipse.swt.widgets.ColorDialog;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.RunnableWithObject;\r
+import org.simantics.utils.datastructures.Triple;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.gfx.ColorImageDescriptor;\r
+\r
+/**\r
+ * Composite for selecting a color for a chart component\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ColorPicker extends Composite implements Widget {\r
+\r
+    Button defaultColor, customColor, color;\r
+    \r
+    /**\r
+     * Create a composite containing radio buttons for default or custom color. Color chooser button is active\r
+     * when the custom radio button is selected. Color chooser uses {@link ColorDialog} to select a color \r
+     * \r
+     * @param parent Composite\r
+     * @param context ISessionContext\r
+     * @param support WidgetSupport\r
+     * @param style SWT style\r
+     */\r
+    public ColorPicker(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
+        this(parent, context, support, style, true);\r
+    }\r
+\r
+    /**\r
+     * Create a composite containing radio buttons for default or custom color. Color chooser button is active\r
+     * when the custom radio button is selected. Color chooser uses {@link ColorDialog} to select a color \r
+     * \r
+     * @param parent Composite\r
+     * @param context ISessionContext\r
+     * @param support WidgetSupport\r
+     * @param style SWT style\r
+     * @param defaultColor provide default color widget?\r
+     */\r
+    public ColorPicker(Composite parent, ISessionContext context, WidgetSupport support, int style, boolean defaultColor) {\r
+        super(parent, style);\r
+        support.register(this);\r
+        \r
+        if(support.getParameter(WidgetSupport.RESOURCE_MANAGER) == null) {\r
+            LocalResourceManager resourceManager = new LocalResourceManager(JFaceResources.getResources(), this);\r
+            support.setParameter(WidgetSupport.RESOURCE_MANAGER, resourceManager);\r
+        }\r
+        \r
+        if(defaultColor) {\r
+            GridLayoutFactory.fillDefaults().numColumns(4).applyTo(this);\r
+\r
+            this.defaultColor = new Button(this, support, SWT.RADIO);\r
+            this.defaultColor.setText("default");\r
+            this.defaultColor.setSelectionFactory(new DefaultColorSelectionFactory(false));\r
+            this.defaultColor.addSelectionListener(new DefaultColorSelectionListener(context));\r
+            GridDataFactory.fillDefaults().applyTo(this.defaultColor.getWidget());\r
+\r
+            customColor = new Button(this, support, SWT.RADIO);\r
+            customColor.setText("custom");\r
+            customColor.setSelectionFactory(new DefaultColorSelectionFactory(true));\r
+            customColor.addSelectionListener(new DefaultColorSelectionListener(context));\r
+\r
+            GridDataFactory.fillDefaults().applyTo(customColor.getWidget());\r
+        } else {\r
+            GridLayoutFactory.fillDefaults().applyTo(this);\r
+        }\r
+        \r
+        \r
+        color = new Button(this, support, SWT.PUSH);\r
+        color.setImageFactory(new ColorImageFactoryFactory(this));\r
+        color.addSelectionListener(new ColorSelectionListener(context));\r
+        color.getWidget().setEnabled(false);\r
+        GridDataFactory.fillDefaults().applyTo(color.getWidget());\r
+    }\r
+\r
+    /**\r
+     * Method for finding the resource for which the color is selected. \r
+     * \r
+     * @param graph ReadGraph\r
+     * @param input input from WidgetSupport\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    protected Resource getResource(ReadGraph graph, Resource input) throws DatabaseException {\r
+        return input;\r
+    }\r
+    \r
+    /**\r
+     * Method for getting the relation with which the g2d.Color is related to a resource\r
+     * \r
+     * @param graph ReadGraph\r
+     * @return Color relation\r
+     * @throws DatabaseException\r
+     */\r
+    protected Resource getColorRelation(ReadGraph graph) throws DatabaseException {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        return jfree.color;\r
+    }\r
+    \r
+    \r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        \r
+        // Create a listener to define the enabled state of the color chooser button\r
+        context.getSession().asyncRequest(new Read<Float[]>() {\r
+\r
+            @Override\r
+            public Float[] perform(ReadGraph graph) throws DatabaseException {\r
+                if(graph.hasStatement(getResource(graph, resource), getColorRelation(graph))) {\r
+                    float[] components = graph.getPossibleRelatedValue(getResource(graph, resource), getColorRelation(graph));\r
+                    Float[] result = new Float[components.length];\r
+                    for(int i = 0; i < components.length; i++) result[i] = components[i];\r
+                    return result;\r
+                } else {\r
+                    return null;\r
+                }\r
+            }\r
+            \r
+        }, new Listener<Float[]>() {\r
+\r
+            @Override\r
+            public void execute(Float[] result) {\r
+                if(!color.getWidget().isDisposed()) {\r
+                    color.getWidget().getDisplay().asyncExec(new RunnableWithObject(result != null ? true : false) {\r
+                        @Override\r
+                        public void run() {\r
+                            if(!color.getWidget().isDisposed()) {\r
+                                if(!Boolean.TRUE.equals(getObject()))\r
+                                    color.getWidget().setEnabled(false);\r
+                                else\r
+                                    color.getWidget().setEnabled(true);\r
+                            }\r
+                        }\r
+                    });\r
+                }\r
+            }\r
+\r
+            @Override\r
+            public void exception(Throwable t) {\r
+                t.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                return color.getWidget().isDisposed();\r
+            }\r
+        });\r
+    }\r
+    \r
+\r
+    /**\r
+     * ImageFactory returning an image for color button\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class ColorImageFactoryFactory extends ReadFactoryImpl<Resource, ImageDescriptor> {\r
+        \r
+        private ColorPicker picker;\r
+        \r
+        public ColorImageFactoryFactory(ColorPicker colorPicker) {\r
+            this.picker = colorPicker;\r
+        }\r
+\r
+        @Override\r
+        public ImageDescriptor perform(ReadGraph graph, Resource input) throws DatabaseException {\r
+            RGB rgb = getColor(graph, getResource(graph, input));\r
+            return new ColorImageDescriptor(rgb.red, rgb.green, rgb.blue, 20, 20, false);\r
\r
+        }\r
+        \r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, ColorPicker, Class<?>>(inputContents, picker, getClass());\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Get RGB from a color literal resource. If resource is not a color resource, return blue (RGB 0, 0, 255)\r
+     * @param graph ReadGraph\r
+     * @param input Color literal resource (float[4])\r
+     * @return RGB color\r
+     * @throws DatabaseException\r
+     */\r
+    private RGB getColor(ReadGraph graph, Resource input) throws DatabaseException{\r
+        float[] colorComponents = graph.getPossibleRelatedValue(input, getColorRelation(graph));\r
+        RGB rgb;\r
+        if(colorComponents == null)\r
+            rgb = new RGB(0, 0, 255);\r
+        else\r
+            rgb = new RGB((int)(colorComponents[0] * 255.0f), \r
+                    (int)(colorComponents[1] * 255.0f), \r
+                    (int)(colorComponents[2] * 255.0f));\r
+        return rgb;\r
+    }\r
+\r
+\r
+    /**\r
+     * SelectionListener for color button. \r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class ColorSelectionListener extends SelectionListenerImpl<Resource> {\r
+\r
+        private SelectionEvent e;\r
+        private RGB rgb;\r
+        \r
+        /**\r
+         * \r
+         * @param context ISessionContext\r
+         */\r
+        public ColorSelectionListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        @Override\r
+        public void widgetSelected(SelectionEvent e) {\r
+            if(color.getWidget().isDisposed())\r
+                return;\r
+            // Save the event for coordinates\r
+            this.e = e;\r
+            super.widgetSelected(e);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            if(color.getWidget().isDisposed())\r
+                return;\r
+            \r
+            final Resource resource = getResource(graph, input);\r
+            final Display display = color.getWidget().getDisplay();\r
+            final RGB oldRGB = getColor(graph, resource);\r
+            \r
+            display.asyncExec(new RunnableWithObject(oldRGB) {\r
+                @Override\r
+                public void run() {\r
+                    // Use color dialog to select a color\r
+                    Shell shell = new Shell(display);\r
+                    ColorDialog cd = new ColorDialog(shell);\r
+                    Point point = color.getWidget().toDisplay(e.x - 150, e.y - 150);\r
+                    cd.getParent().setLocation(point.x, point.y);\r
+                    cd.setText("Select color");\r
+                    cd.setRGB((RGB)getObject());\r
+                    rgb = cd.open();\r
+                    if(rgb == null)\r
+                        return;\r
+                    \r
+                    SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                        \r
+                        @Override\r
+                        public void perform(WriteGraph graph) throws DatabaseException {\r
+                            G2DResource g2d = G2DResource.getInstance(graph);\r
+                            float[] components = new float[] {rgb.red / 255.0f,  rgb.green / 255.0f, rgb.blue / 255.0f, 1.0f};\r
+                            graph.claimLiteral(resource, getColorRelation(graph), g2d.Color, components);                            \r
+                        }\r
+                    });\r
+                    \r
+                }\r
+            });\r
+            \r
+            \r
+\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * SelectionFactory for default and custom color radio buttons\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class DefaultColorSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+\r
+        private final Boolean isCustom;\r
+\r
+        /**\r
+         * \r
+         * @param isCustom Is this custom button?\r
+         */\r
+        public DefaultColorSelectionFactory(Boolean isCustom) {\r
+            super();\r
+            this.isCustom = isCustom;\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Resource, Object, Boolean>((Resource) inputContents, getClass(), isCustom);\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource input) throws DatabaseException {\r
+            Resource r = graph.getPossibleObject(getResource(graph, input), getColorRelation(graph));\r
+            boolean result = false; // Default == not selected\r
+            if(r == null && !isCustom) {\r
+                // No color definition and default-button -> selected\r
+                result =  true;\r
+            } else if(r != null && isCustom) {\r
+                // color definition and custom button -> selected\r
+                result =  true;\r
+            }\r
+            return result;\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * SelectionListener for default and custom radio buttons\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class DefaultColorSelectionListener extends SelectionListenerImpl<Resource> {\r
+\r
+        private SelectionEvent e;\r
+\r
+        public DefaultColorSelectionListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        @Override\r
+        public void widgetSelected(SelectionEvent e) {\r
+            this.e = e; \r
+            super.widgetSelected(e);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            Resource resource = getResource(graph, input);\r
+            if(customColor.getWidget().equals(e.widget)) {\r
+                // Custom selected. If there is no color already, create a default Blue color\r
+                G2DResource g2d = G2DResource.getInstance(graph);\r
+                if(graph.getPossibleObject(resource, getColorRelation(graph)) == null) {\r
+                    float[] components = java.awt.Color.BLUE.getColorComponents(new float[4]);\r
+                    components[3] = 1.0f;\r
+                    graph.claimLiteral(resource, getColorRelation(graph), g2d.Color, components);\r
+                }\r
+            } else {\r
+                // Default selected, remove color definition\r
+                graph.deny(resource, getColorRelation(graph));\r
+            }\r
+        }\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoublePropertyFactory2.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoublePropertyFactory2.java
new file mode 100644 (file)
index 0000000..3bd4250
--- /dev/null
@@ -0,0 +1,119 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.utils.datastructures.Quad;\r
+\r
+/**\r
+ * PropertyFactory for finding a double property. Supports also finding the \r
+ * property from a first occurrence of resource ConsistsOf type HasProperty   \r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Marko Luukkainen\r
+ *\r
+ */\r
+public class DoublePropertyFactory2 extends ReadFactoryImpl<Resource, String> {\r
+\r
+    final private String propertyURI;\r
+    final private String typeURI;\r
+    final private Double defaultValue;\r
+    \r
+    /**\r
+     * PropertyFactory for finding a boolean property with propertyURI\r
+     * \r
+     * @param propertyURI URI for the boolean property\r
+     */\r
+    public DoublePropertyFactory2(String propertyURI) {\r
+        this(null, propertyURI);\r
+    }\r
+    \r
+\r
+    /**\r
+     * PropertyFactory for finding a boolean property with propertyURI.\r
+     *  \r
+     * Finds the property for first ObjectWithType(resource, L0.ConsistsOf, type)\r
+     *  \r
+     * Supports inverting the result (e.g. if required information is IsHidden, but database contains IsVisible)\r
+     *  \r
+     * @param typeURI URI for a resource (resource ConsistsOf type) (null allowed)\r
+     * @param propertyURI URI for the boolean property\r
+     * @param inverse Invert the result?\r
+     */\r
+    public DoublePropertyFactory2(String typeURI, String propertyURI) {\r
+        this(typeURI, propertyURI, 0.0);\r
+    }\r
+    \r
+    /**\r
+     * PropertyFactory for finding a boolean property with propertyURI.\r
+     *  \r
+     * Finds the property for first ObjectWithType(resource, L0.ConsistsOf, type)\r
+     *  \r
+     * Supports inverting the result (e.g. if required information is IsHidden, but database contains IsVisible)\r
+     * \r
+     * @param typeURI URI for a resource (resource ConsistsOf type) (null allowed -> not used)\r
+     * @param propertyURI URI for the boolean property\r
+     * @param inverse Invert the result?\r
+     * @param defaultValue default value\r
+     */\r
+    public DoublePropertyFactory2(String typeURI, String propertyURI, double defaultValue) {\r
+        this.propertyURI = propertyURI;\r
+        this.typeURI = typeURI;\r
+        this.defaultValue = defaultValue;\r
+    }\r
+\r
+    @Override\r
+    public Object getIdentity(Object inputContents) {\r
+        return new Quad<Resource, String, Object, Double>((Resource) inputContents, propertyURI, getClass(), defaultValue);\r
+    }\r
+\r
+    @Override\r
+    public String perform(ReadGraph graph, Resource r) throws DatabaseException {\r
+        if(typeURI == null) {\r
+            // if no typeUri, use the default resource r\r
+            return getValue(graph, r);\r
+        } else {\r
+            // typeURI was defined, find the property for the first occurence of ConsistsOf type\r
+            Resource type =  graph.getResource(typeURI);\r
+            for(Resource o : graph.syncRequest(new ObjectsWithType(r, Layer0.getInstance(graph).ConsistsOf, type))) {\r
+                // Returns the value for the first occurrence\r
+                return getValue(graph, o);\r
+            }\r
+        }\r
+        // if nothing was found with typeURI\r
+        return "";\r
+    }\r
+    \r
+    /**\r
+     * Return the value for a Boolean literal possibly inverted (or default if resource != Boolean literal) \r
+     * \r
+     * @param graph ReadGraph\r
+     * @param resource Literal Boolean resource \r
+     * @return value of the parameter (or default or inverted)\r
+     * @throws DatabaseException\r
+     */\r
+    private String getValue(ReadGraph graph, Resource resource) throws DatabaseException {\r
+        Double value = graph.getPossibleRelatedValue(resource, graph.getResource(propertyURI), Bindings.DOUBLE);\r
+        if(value != null) {\r
+            return value.toString();\r
+        } else if (defaultValue != null){\r
+            return defaultValue.toString();\r
+        }\r
+        return "";\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoublePropertyModifier2.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoublePropertyModifier2.java
new file mode 100644 (file)
index 0000000..a7dfe81
--- /dev/null
@@ -0,0 +1,49 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.layer0.Layer0;\r
+\r
+public class DoublePropertyModifier2 extends TextModifyListenerImpl<Resource> {\r
+\r
+       final private String typeUri;\r
+    final private String propertyURI;\r
+\r
+    public DoublePropertyModifier2(ISessionContext context, String propertyURI) {\r
+        this.propertyURI = propertyURI;\r
+        this.typeUri = null;\r
+    }\r
+    \r
+    public DoublePropertyModifier2(ISessionContext context, String typeURI, String propertyURI) {\r
+        this.propertyURI = propertyURI;\r
+        this.typeUri = typeURI;\r
+    }\r
+\r
+    @Override\r
+    public void applyText(WriteGraph graph, Resource input, String text) throws DatabaseException {\r
+        if (typeUri == null)\r
+               applyValue(graph, input, text);\r
+        else {\r
+               Resource type =  graph.getResource(typeUri);\r
+            for(Resource object : graph.syncRequest(new ObjectsWithType(input, Layer0.getInstance(graph).ConsistsOf, type))) {\r
+                applyValue(graph, object,text);\r
+            }\r
+        }\r
+       \r
+    }\r
+    \r
+    private void applyValue(WriteGraph graph, Resource input, String text) throws DatabaseException {\r
+       if (text == null || text.trim().isEmpty()) {\r
+            if (graph.hasStatement(input, graph.getResource(propertyURI)))\r
+                graph.denyValue(input, graph.getResource(propertyURI));\r
+        } else {\r
+            graph.claimLiteral(input, graph.getResource(propertyURI), Double.parseDouble(text), Bindings.DOUBLE);\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoubleValidator.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/DoubleValidator.java
new file mode 100644 (file)
index 0000000..e41c9b0
--- /dev/null
@@ -0,0 +1,54 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.jface.dialogs.IInputValidator;\r
+\r
+/**\r
+ * Validator for validating that an input is double.\r
+ * \r
+ * Can allow empty strings.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class DoubleValidator implements IInputValidator {\r
+    \r
+    boolean allowEmpty;\r
+    \r
+    /**\r
+     * New double validator. Does not allow empty strings\r
+     */\r
+    public DoubleValidator() {\r
+        this(false);\r
+    }\r
+    \r
+    /**\r
+     * New double validator.\r
+     * @param allowEmpty Are empty strings allowed\r
+     */\r
+    public DoubleValidator(boolean allowEmpty) {\r
+        this.allowEmpty = allowEmpty;\r
+    }\r
+    \r
+    @Override\r
+    public String isValid(String newText) {\r
+        if (allowEmpty && newText.trim().isEmpty())\r
+            return null;\r
+        try {\r
+            Double.parseDouble(newText);\r
+            return null;\r
+        } catch (NumberFormatException e) {\r
+            return e.getMessage();\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/IAllVariablesOfModel.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/IAllVariablesOfModel.java
new file mode 100644 (file)
index 0000000..9557315
--- /dev/null
@@ -0,0 +1,17 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+\r
+public interface IAllVariablesOfModel {\r
+       \r
+       \r
+       public Read<Collection<ChartVariable>> getVariablesQuery();\r
+       \r
+       public String getVariablesLabel(ReadGraph graph, String rvi) throws DatabaseException;\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/JFreeChartPropertyColorProvider.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/JFreeChartPropertyColorProvider.java
new file mode 100644 (file)
index 0000000..ab4c432
--- /dev/null
@@ -0,0 +1,57 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.jface.resource.ColorDescriptor;\r
+import org.eclipse.jface.resource.ResourceManager;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ITrackedColorProvider;\r
+\r
+/**\r
+ * ColorProvider providing coloring scheme for chart tab text widgets\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class JFreeChartPropertyColorProvider implements ITrackedColorProvider {\r
+    \r
+    private final ResourceManager resourceManager;\r
+    \r
+    private final ColorDescriptor highlightColor = ColorDescriptor.createFrom(new RGB(254, 255, 197));\r
+    private final ColorDescriptor inactiveColor = ColorDescriptor.createFrom(new RGB(255, 255, 255));\r
+    private final ColorDescriptor invalidInputColor = ColorDescriptor.createFrom(new RGB(255, 128, 128));\r
+\r
+    public JFreeChartPropertyColorProvider(ResourceManager resourceManager) {\r
+        this.resourceManager = resourceManager;\r
+    }\r
+    \r
+    @Override\r
+    public Color getEditingBackground() {\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public Color getHoverBackground() {\r
+        return resourceManager.createColor(highlightColor);\r
+    }\r
+\r
+    @Override\r
+    public Color getInactiveBackground() {\r
+        return resourceManager.createColor(inactiveColor);\r
+    }\r
+\r
+    @Override\r
+    public Color getInvalidBackground() {\r
+        return resourceManager.createColor(invalidInputColor);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/LabelPropertyTabContributor.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/LabelPropertyTabContributor.java
new file mode 100644 (file)
index 0000000..8c0441c
--- /dev/null
@@ -0,0 +1,66 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.selectionview.PropertyTabContributorImpl;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public abstract class LabelPropertyTabContributor extends PropertyTabContributorImpl {\r
+\r
+    @Override\r
+    public Read<String> getPartNameReadRequest(final ISelection forSelection) {\r
+\r
+        return new Read<String>() {\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                ModelingResources mr = ModelingResources.getInstance(graph);\r
+\r
+                       final Variable variable = AdaptionUtils.adaptToSingle(forSelection, Variable.class);\r
+                final Resource resource = AdaptionUtils.adaptToSingle(forSelection, Resource.class);\r
+                if(resource == null && variable == null) {\r
+                       return "Selection";\r
+                }\r
+                \r
+                Resource r;\r
+                if(variable != null) {\r
+                       r = (Resource)variable.getRepresents(graph);\r
+                } else {\r
+                       r = resource;\r
+                }\r
+                \r
+                if(graph.hasStatement(r, mr.ElementToComponent)) {\r
+                    r = graph.getSingleObject(r, mr.ElementToComponent);\r
+                }\r
+                String label = graph.getPossibleRelatedValue(r, l0.HasLabel);\r
+                if(label != null)\r
+                    return label;\r
+                label = graph.getPossibleRelatedValue(r, l0.HasName);\r
+                if(label != null)\r
+                    return label;\r
+                return "No name for selection";\r
+            }\r
+            \r
+        };\r
+        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RVIFactory.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RVIFactory.java
new file mode 100644 (file)
index 0000000..52a9a63
--- /dev/null
@@ -0,0 +1,33 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Class for providing RVI content to a text field with all '/' characters changed to '.'\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class RVIFactory extends ReadFactoryImpl<Resource, String> {\r
+\r
+    @Override\r
+    public String perform(ReadGraph graph, Resource input) throws DatabaseException {\r
+        String value = graph.getPossibleRelatedValue(input, JFreeChartResource.getInstance(graph).variableRVI);\r
+        return value != null ? value = value.substring(1).replace('/', '.') : "";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RVIModifier.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RVIModifier.java
new file mode 100644 (file)
index 0000000..3c87d5a
--- /dev/null
@@ -0,0 +1,135 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.jface.bindings.keys.KeyStroke;\r
+import org.eclipse.jface.bindings.keys.ParseException;\r
+import org.eclipse.jface.fieldassist.ContentProposalAdapter;\r
+import org.eclipse.jface.fieldassist.IContentProposal;\r
+import org.eclipse.jface.fieldassist.IContentProposalListener;\r
+import org.eclipse.jface.fieldassist.IContentProposalListener2;\r
+import org.eclipse.jface.fieldassist.TextContentAdapter;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Class for modifying variable name to rvi and saving it to database.\r
+ * \r
+ * Modifier also adds content proposal support to the control it is added to.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class RVIModifier extends TextModifyListenerImpl<Resource> {\r
+\r
+    private boolean active;\r
+    private Control control;\r
+    private String rviUri;\r
+    private String indexUri;\r
+    \r
+    private char[] alphaNumericCharacters = {\r
+        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','Ã¥','ä','ö',\r
+        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Ã…','Ä','Ö',\r
+        '1','2','3','4','5','6','7','8','9','0','.'};\r
+    \r
+    /**\r
+     * Create a new RVIModifier and attach a content proposal support to control\r
+     * @param control\r
+     * @param support\r
+     */\r
+    public RVIModifier(Control control, WidgetSupport support) {\r
+        this(control, support, JFreeChartResource.URIs.variableRVI, JFreeChartResource.URIs.variableFilter);\r
+    }\r
+        \r
+        \r
+    public RVIModifier(Control control, WidgetSupport support, String rviRelationUri, String indexUri) {\r
+        this.rviUri = rviRelationUri;\r
+        this.indexUri = indexUri;\r
+        \r
+        this.control = control;\r
+        this.active = true;\r
+        \r
+        KeyStroke keyStroke = null;\r
+        try {\r
+            keyStroke = KeyStroke.getInstance("Ctrl+Space");\r
+        } catch (ParseException e1) {\r
+            e1.printStackTrace();\r
+        }\r
+        \r
+        //SimpleContentProposalProvider scpp = new VariableProposalProvider(control, support);\r
+        VariableProposalProvider scpp = new VariableProposalProvider(control, support);\r
+        scpp.setFiltering(true);\r
+\r
+        ContentProposalAdapter adapter = new ContentProposalAdapter(\r
+                control, new TextContentAdapter(), scpp, keyStroke, alphaNumericCharacters);\r
+        adapter.setAutoActivationDelay(0);\r
+        adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);\r
+        adapter.addContentProposalListener(new IContentProposalListener2() {\r
+\r
+            @Override\r
+            public void proposalPopupOpened(ContentProposalAdapter adapter) {\r
+                if(RVIModifier.this != null)\r
+                    RVIModifier.this.deactivate();\r
+            }\r
+\r
+            @Override\r
+            public void proposalPopupClosed(ContentProposalAdapter adapter) {\r
+                if(RVIModifier.this != null)\r
+                    RVIModifier.this.activate();\r
+            }\r
+        });\r
+\r
+        adapter.addContentProposalListener(new IContentProposalListener() {\r
+\r
+            @Override\r
+            public void proposalAccepted(IContentProposal proposal) {\r
+                if(RVIModifier.this.control != null && !RVIModifier.this.control.isDisposed())\r
+                    RVIModifier.this.modifyText(new TrackedModifyEvent(RVIModifier.this.control, proposal.getContent()));\r
+            }\r
+        });\r
+    \r
+    \r
+    }\r
+    \r
+\r
+    @Override\r
+    public void applyText(WriteGraph graph, Resource resource, String text) throws DatabaseException {\r
+        if(active) {\r
+            text = "/" + text.replace('.', '/');\r
+            graph.claimLiteral(resource, getRVIRelation(graph), text, Bindings.STRING);\r
+            graph.deny(resource, getIndexRelation(graph));\r
+        }\r
+    }\r
+    \r
+    private Resource getRVIRelation(ReadGraph graph) throws DatabaseException {\r
+        return graph.getResource(rviUri);\r
+    }\r
+    \r
+    private Resource getIndexRelation(ReadGraph graph) throws DatabaseException {\r
+        return graph.getResource(indexUri);\r
+    }\r
+\r
+    public void deactivate() {\r
+        active = false;\r
+    }\r
+\r
+    public void activate() {\r
+        active = true;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RangeComposite.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RangeComposite.java
new file mode 100644 (file)
index 0000000..2b3ce82
--- /dev/null
@@ -0,0 +1,296 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.Iterator;\r
+import java.util.LinkedHashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.RunnableWithObject;\r
+import org.simantics.utils.datastructures.Triple;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Composite for range controls in chart series properties\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class RangeComposite extends Composite implements Widget {\r
+\r
+    private Composite composite;\r
+\r
+    public RangeComposite(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
+        super(parent, style);\r
+        support.register(this);\r
+        GridLayoutFactory.fillDefaults().spacing(3, 0).margins(3, 0).applyTo(this);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this);\r
+        composite = this;\r
+    }\r
+\r
+    @Override\r
+    public void setInput(final ISessionContext context, final Object input) {\r
+        if(composite == null || composite.isDisposed())\r
+            return;\r
+\r
+        final Resource series = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+\r
+        RangeHandlerFactory f;\r
+        try {\r
+            f = context.getSession().syncRequest(new Read<RangeHandlerFactory>() {\r
+                @Override\r
+                public RangeHandlerFactory perform(ReadGraph graph)\r
+                        throws DatabaseException {\r
+                    return graph.adapt(series, RangeHandlerFactory.class);\r
+                }\r
+            });\r
+\r
+        } catch (DatabaseException e) {\r
+            //ExceptionUtils.logAndShowError("Insert something intelligent here.", e);\r
+            return;\r
+        }\r
+\r
+        final RangeHandlerFactory factory = f;\r
+\r
+        /*\r
+         *  Listen to the enumerations assigned to the variable in this series.\r
+         *  Listener is needed because the user can change the variableRVI for the series\r
+         *  and that changes the options for range\r
+         */\r
+        context.getSession().asyncRequest(factory.getRequest(series), new Listener<LinkedHashMap<String, Resource>>() {\r
+\r
+            @Override\r
+            public void execute(LinkedHashMap<String, Resource> result) {\r
+                if(isDisposed())\r
+                    return;\r
+\r
+                // Always modify the composite, even with null result\r
+                composite.getDisplay().asyncExec(new RunnableWithObject(result) {\r
+                    @Override\r
+                    public void run() {\r
+                        if(composite == null || composite.isDisposed())\r
+                            return;\r
+\r
+                        // Remove all content (even with null result)\r
+                        for(Control child : composite.getChildren())\r
+                            child.dispose();\r
+                        \r
+                        composite.layout();\r
+\r
+                        if(getObject() == null) {\r
+                               // No range, print an em dash.\r
+                               Label label = new Label(composite, SWT.NONE);\r
+                            label.setText("\u2014");\r
+                            label.setEnabled(false);\r
+                            GridDataFactory.fillDefaults().applyTo(label);\r
+                            composite.layout();\r
+                            return;\r
+                        }\r
+\r
+                        // New widgetSupport for the combos\r
+                        WidgetSupportImpl support = new WidgetSupportImpl();\r
+\r
+                        Label label;\r
+                        TrackedCombo combo;\r
+                        LinkedHashMap<?, ?> result = (LinkedHashMap<?, ?>)getObject();\r
+                        Iterator<?> iterator = result.keySet().iterator();\r
+\r
+                        // Set the width of the combo \r
+                        GridLayout gl = (GridLayout)composite.getLayout();\r
+                        gl.numColumns = result.size();\r
+                        \r
+                        // For each array index (enumeration), create a label and a combo \r
+                        int index = 0;\r
+                        while(iterator.hasNext()) {\r
+                            Object key = iterator.next();\r
+                            Composite c = new Composite(composite, SWT.NONE);\r
+                            GridDataFactory.fillDefaults().applyTo(c);\r
+                            GridLayoutFactory.fillDefaults().applyTo(c);\r
+\r
+                            label = new Label(c, SWT.NONE);\r
+                            label.setText((String)key);\r
+                            GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.END).applyTo(label);\r
+\r
+                            combo = new TrackedCombo(c, support, SWT.READ_ONLY);\r
+                            combo.setItemFactory(factory.getRangeItemFactory(index, (Resource)result.get(key)));\r
+                            combo.setSelectionFactory(new RangeSelectionFactory(index));\r
+                            combo.addModifyListener(new RangeModifyListener(index, result.size()));\r
+                            GridDataFactory.fillDefaults().applyTo(combo.getWidget());\r
+                            index++;\r
+                        }\r
+\r
+                        // Set input for the combos\r
+                        support.fireInput(context, input);\r
+\r
+                        /*\r
+                         *  Find out if this composite is located in a scrolled composite. \r
+                         *  If it is, resize the scrolled composite\r
+                         */\r
+                        composite.layout();\r
+                        Composite previousParent = composite.getParent();\r
+                        for(int i = 0; i < 7 && previousParent != null; i++) {\r
+                            previousParent.layout();\r
+                            if(previousParent.getParent() instanceof ScrolledComposite) {\r
+                                ScrolledComposite sc = (ScrolledComposite) previousParent.getParent();\r
+                                Point size = previousParent.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+                                sc.setMinSize(size);\r
+                                break;\r
+                            }\r
+                            previousParent = previousParent.getParent();\r
+                        }\r
+                    }\r
+                });                    \r
+            }\r
+\r
+            @Override\r
+            public void exception(Throwable t) {\r
+                t.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                return composite == null || composite.isDisposed();\r
+            }\r
+        });\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class RangeSelectionFactory extends ReadFactoryImpl<Resource, String> {\r
+\r
+        int index;\r
+\r
+        /**\r
+         * \r
+         * @param index Index of the enumeration in the variable\r
+         */\r
+        public RangeSelectionFactory(int index) {\r
+            this.index = index;\r
+        }\r
+\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Integer, Class<?>>(inputContents, index, getClass());\r
+        }\r
+\r
+        @Override\r
+        public String perform(ReadGraph graph, Resource series) throws DatabaseException {\r
+            String[] filter = graph.getPossibleRelatedValue(series, getIndexRelation(graph), Bindings.STRING_ARRAY);\r
+\r
+\r
+            /*\r
+             * If no filter was found or the index is not applicable, return the first index\r
+             */\r
+            String result = null;\r
+            if(filter == null)\r
+                result = getFirstIndex(graph, series, index);\r
+            else if(filter.length < index)\r
+                result = getFirstIndex(graph, series, index);      \r
+            else\r
+                result = filter[index];\r
+\r
+            return result;\r
+        }\r
+\r
+    }\r
+\r
+\r
+\r
+    /**\r
+     * RangeModifyListener for modifying a range filter in chart series \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class RangeModifyListener  extends ComboModifyListenerImpl<Resource> {\r
+\r
+        private int index, size;\r
+\r
+        /**\r
+         * \r
+         * @param index Index of the modified range filter\r
+         * @param size Size of the whole filter (for situations where there is no filter)\r
+         */\r
+        public RangeModifyListener(int index, int size) {\r
+            this.index = index;\r
+            this.size = size;\r
+        }\r
+\r
+        @Override\r
+        public void applyText(WriteGraph graph, Resource series, String text) throws DatabaseException {\r
+            Resource filterRelation = getIndexRelation(graph);\r
+            String[] filter = graph.getPossibleRelatedValue(series, filterRelation, Bindings.STRING_ARRAY);\r
+\r
+            // If there is no filter, create a default filter with all indexes "All"\r
+            if(filter == null) {\r
+                filter = new String[size];\r
+                for(int i = 0; i < filter.length; i++) {\r
+                    filter[i] = getFirstIndex(graph, series, i);\r
+                }\r
+            }\r
+\r
+            // Modify the filter index\r
+            filter[index] = text;\r
+            graph.claimLiteral(series, filterRelation, filter, Bindings.STRING_ARRAY);\r
+        }\r
+    }\r
+\r
+    protected Resource getIndexRelation(ReadGraph graph) {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        return jfree.variableFilter;\r
+    }\r
+    \r
+    private static String getFirstIndex(ReadGraph graph, Resource series, int index) throws DatabaseException {\r
+        RangeHandlerFactory f = graph.adapt(series, RangeHandlerFactory.class);\r
+        LinkedHashMap<String, Resource> map = graph.syncRequest(f.getRequest(series));\r
+        if(map == null)\r
+            return null;\r
+        else {\r
+            Resource enumeration = null;\r
+            Iterator<Resource> iterator = map.values().iterator();\r
+            for(int i = 0; i <= index && iterator.hasNext(); i++) {\r
+                enumeration = iterator.next();\r
+            }\r
+            if(enumeration != null) {\r
+                Map<String, Object> indexmap = f.getRangeItemFactory(index, enumeration).perform(graph, null);\r
+                if(indexmap != null)\r
+                    return indexmap.values().iterator().next().toString();\r
+            }\r
+        }\r
+\r
+        return null;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RangeHandlerFactory.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/RangeHandlerFactory.java
new file mode 100644 (file)
index 0000000..f015878
--- /dev/null
@@ -0,0 +1,15 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.LinkedHashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.request.Read;\r
+\r
+public interface RangeHandlerFactory {\r
+       \r
+       public Read<LinkedHashMap<String, Resource>> getRequest(final Resource series);\r
+       \r
+       public ReadFactoryImpl<Resource, Map<String, Object>> getRangeItemFactory(int index, Resource res);\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooser.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooser.java
new file mode 100644 (file)
index 0000000..ce1b351
--- /dev/null
@@ -0,0 +1,600 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.runtime.Assert;\r
+import org.eclipse.core.runtime.ListenerList;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.jface.resource.ResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.DisposeEvent;\r
+import org.eclipse.swt.events.DisposeListener;\r
+import org.eclipse.swt.events.FocusEvent;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyEvent;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.MouseEvent;\r
+import org.eclipse.swt.events.MouseListener;\r
+import org.eclipse.swt.events.MouseTrackListener;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.Font;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.simantics.browsing.ui.swt.widgets.DefaultColorProvider;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ITrackedColorProvider;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactory;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+\r
+/**\r
+ * Widget for choosing and labeled object from a set of objects.\r
+ * \r
+ * Supports cases when multiple objects have the same label (as much as possible)\r
+ * \r
+ * \r
+ * Based on org.simantics.browsing.ui.swt.widgets.Trackedtext\r
+ * \r
+ * \r
+ * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+ *\r
+ */\r
+public class StringChooser<T> implements Widget{\r
+    private static final int      EDITING                 = 1 << 0;\r
+    private static final int      MODIFIED_DURING_EDITING = 1 << 1;\r
+\r
+    /**\r
+     * Used to tell whether or not a mouseDown has occurred after a focusGained\r
+     * event to be able to select the whole text field when it is pressed for\r
+     * the first time while the widget holds focus.\r
+     */\r
+    private static final int      MOUSE_DOWN_FIRST_TIME   = 1 << 2;\r
+    private static final int      MOUSE_INSIDE_CONTROL    = 1 << 3;\r
+    \r
+    private int                   caretPositionBeforeEdit;\r
+    \r
+    private String                textBeforeEdit;\r
+\r
+    private int                   state;\r
+\r
+       private Map<T,String> objectToLabel;\r
+       private Set<String> allowedLabels;\r
+       \r
+       private T selected;\r
+       \r
+    private final Display         display;\r
+\r
+    private final Text            text;\r
+    \r
+    private CompositeListener     listener;\r
+\r
+    private ListenerList          modifyListeners;\r
+\r
+    private ReadFactory<?, T>     objectFactory;\r
+    \r
+    private ITrackedColorProvider colorProvider;\r
+\r
+    private final ResourceManager resourceManager;\r
+    \r
+       private boolean moveCaretAfterEdit = true;\r
+       \r
+       private boolean selectAllOnStartEdit = true;\r
+       \r
+       public StringChooser(Composite parent, WidgetSupport support, int style) {\r
+               this.state = 0;\r
+        this.text = new Text(parent, style);\r
+        this.display = text.getDisplay();\r
+        this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), text);\r
+        this.colorProvider = new DefaultColorProvider(resourceManager);\r
+        if (support!=null) support.register(this);\r
+        initialize();\r
+       }\r
+       \r
+\r
+       \r
+       public ResourceManager getResourceManager() {\r
+       return resourceManager;\r
+    }\r
+       \r
+       public void setFont(Font font) {\r
+               text.setFont(font);\r
+       }\r
+       \r
+       public void setObjectFactory(ReadFactory<?, T> objectFactory) {\r
+               this.objectFactory = objectFactory;\r
+       }\r
+       \r
+       public void setMoveCaretAfterEdit(boolean value) {\r
+               this.moveCaretAfterEdit = value;\r
+       }\r
+       \r
+       public void setData(Map<T,String> data) {\r
+               this.objectToLabel = data;\r
+               this.allowedLabels = new HashSet<String>();\r
+               this.allowedLabels.addAll(objectToLabel.values());\r
+       }\r
+       \r
+       public void setData(Collection<T> data) {\r
+               this.objectToLabel = new HashMap<T, String>();\r
+               this.allowedLabels = new HashSet<String>();\r
+               for (T t : data) {\r
+                       String label = t.toString();\r
+                       objectToLabel.put(t, label);\r
+                       allowedLabels.add(label);\r
+               }\r
+       }\r
+       \r
+       public void setSelected(T selected) {\r
+               if (selected != null) {\r
+                       String label = objectToLabel.get(selected);\r
+                       if (label == null)\r
+                               return;\r
+                       this.selected = selected;\r
+                       this.text.setText(label);\r
+               } else {\r
+                       this.selected = null;\r
+                       this.text.setText("");\r
+               }\r
+       }\r
+       \r
+       public void setSelected(String label) {\r
+               // TODO : we could create a label to object map.\r
+               for (T t : objectToLabel.keySet()) {\r
+                       if (label.equals(objectToLabel.get(t))) {\r
+                               setSelected(t);\r
+                               return;\r
+                       }\r
+               }\r
+       }\r
+       \r
+       \r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+        if (modifyListeners != null) {\r
+            for (Object o : modifyListeners.getListeners()) {\r
+               if(o instanceof Widget) {\r
+                    ((Widget) o).setInput(context, input);\r
+               }\r
+            }\r
+        }\r
+               \r
+               if(objectFactory != null) {\r
+                       objectFactory.listen(context, input, new Listener<T>() {\r
+\r
+                               @Override\r
+                public void exception(final Throwable t) {\r
+                                       display.asyncExec(new Runnable() {\r
+\r
+                                               @Override\r
+                                               public void run() {\r
+                                                       if(isDisposed()) return;\r
+//                                                     System.out.println("Button received new text: " + text);\r
+                                                       text.setText(t.toString());\r
+                                               }\r
+\r
+                                       });\r
+                               }\r
+\r
+                               @Override\r
+                               public void execute(final T object) {\r
+                                       \r
+                                       if(text.isDisposed()) return;\r
+                                       \r
+                                       display.asyncExec(new Runnable() {\r
+\r
+                                               @Override\r
+                                               public void run() {\r
+                                                       if(isDisposed()) return;\r
+                                                       setSelected(object);\r
+//                                                     text.getParent().layout();\r
+//                                                     text.getParent().getParent().layout();\r
+                                               }\r
+\r
+                                       });\r
+                               }\r
+\r
+                               @Override\r
+                               public boolean isDisposed() {\r
+                                       return text.isDisposed();\r
+                               }\r
+\r
+                       });\r
+               }\r
+               \r
+       }\r
+       \r
+       /**\r
+     * Common initialization. Assumes that text is already created.\r
+     */\r
+    private void initialize() {\r
+        Assert.isNotNull(text);\r
+\r
+        text.setBackground(colorProvider.getInactiveBackground());\r
+        text.setDoubleClickEnabled(false);\r
+\r
+        listener = new CompositeListener();\r
+\r
+        text.addModifyListener(listener);\r
+        text.addDisposeListener(listener);\r
+        text.addKeyListener(listener);\r
+        text.addMouseTrackListener(listener);\r
+        text.addMouseListener(listener);\r
+        text.addFocusListener(listener);\r
+    }\r
+    \r
+    public void startEdit(boolean selectAll) {\r
+        if (isEditing()) {\r
+            // Print some debug incase we end are in an invalid state\r
+            System.out.println("TrackedText: BUG: startEdit called when in editing state");\r
+        }\r
+//        System.out.println("start edit: selectall=" + selectAll + ", text=" + text.getText() + ", caretpos=" + caretPositionBeforeEdit);\r
+\r
+        // Backup text-field data for reverting purposes\r
+        caretPositionBeforeEdit = text.getCaretPosition();\r
+        textBeforeEdit = text.getText();\r
+\r
+        // Signal editing state\r
+        setBackground(colorProvider.getEditingBackground());\r
+\r
+        if (selectAll) {\r
+            text.selectAll();\r
+        }\r
+        state |= EDITING | MOUSE_DOWN_FIRST_TIME;\r
+    }\r
+\r
+    @SuppressWarnings("unchecked")\r
+       private void applyEdit() {\r
+        try {\r
+            if (isTextValid() != null) {\r
+                text.setText(textBeforeEdit);\r
+            } else if (isModified() && !text.getText().equals(textBeforeEdit)) {\r
+               setSelected(text.getText());\r
+                //System.out.println("apply");\r
+                if (modifyListeners != null) {\r
+                    StringChooserModifyEvent<T> event = new StringChooserModifyEvent<T>(text, selected, text.getText());\r
+                    for (Object o : modifyListeners.getListeners()) {\r
+                        ((StringChooserModifyListener<T>) o).modifySelection(event);\r
+                    }\r
+                }\r
+            }\r
+        } catch (Throwable t) {\r
+            t.printStackTrace();\r
+        } finally {\r
+            endEdit();\r
+        }\r
+    }\r
+\r
+    private void endEdit() {\r
+        if (text.isDisposed())\r
+            return;\r
+\r
+        if (!isEditing()) {\r
+            // Print some debug incase we end are in an invalid state\r
+            //ExceptionUtils.logError(new Exception("BUG: endEdit called when not in editing state"));\r
+            //System.out.println();\r
+        }\r
+        setBackground(isMouseInsideControl() ? colorProvider.getHoverBackground() : colorProvider.getInactiveBackground());\r
+//        System.out.println("endEdit: " + text.getText() + ", caret: " + text.getCaretLocation() + ", selection: " + text.getSelection());\r
+        // Always move the caret to the end of the string\r
+        if(moveCaretAfterEdit)\r
+            text.setSelection(text.getCharCount());\r
+        state &= ~(EDITING | MOUSE_DOWN_FIRST_TIME);\r
+        setModified(false);\r
+    }\r
+\r
+    private void revertEdit() {\r
+        if (!isEditing()) {\r
+            // Print some debug incase we end are in an invalid state\r
+            //ExceptionUtils.logError(new Exception("BUG: revertEdit called when not in editing state"));\r
+            System.out.println("BUG: revertEdit called when not in editing state");\r
+        }\r
+        text.setText(textBeforeEdit);\r
+        text.setSelection(caretPositionBeforeEdit);\r
+        setBackground(isMouseInsideControl() ? colorProvider.getHoverBackground() : colorProvider.getInactiveBackground());\r
+        state &= ~(EDITING | MOUSE_DOWN_FIRST_TIME);\r
+        setModified(false);\r
+    }\r
+\r
+    private boolean isEditing() {\r
+        return (state & EDITING) != 0;\r
+    }\r
+\r
+    private void setModified(boolean modified) {\r
+        if (modified) {\r
+            state |= MODIFIED_DURING_EDITING;\r
+        } else {\r
+            state &= ~MODIFIED_DURING_EDITING;\r
+        }\r
+    }\r
+\r
+    private boolean isMouseInsideControl() {\r
+        return (state & MOUSE_INSIDE_CONTROL) != 0;\r
+    }\r
+\r
+    private void setMouseInsideControl(boolean inside) {\r
+        if (inside)\r
+            state |= MOUSE_INSIDE_CONTROL;\r
+        else\r
+            state &= ~MOUSE_INSIDE_CONTROL;\r
+    }\r
+\r
+    private boolean isModified() {\r
+        return (state & MODIFIED_DURING_EDITING) != 0;\r
+    }\r
+\r
+    public void setSelectAllOnStartEdit(boolean selectAll) {\r
+        this.selectAllOnStartEdit = selectAll;\r
+    }\r
+    \r
+    public void setEditable(boolean editable) {\r
+        if (editable) {\r
+            text.setEditable(true);\r
+            setBackground(isMouseInsideControl() ? colorProvider.getHoverBackground() : colorProvider.getInactiveBackground());\r
+        } else {\r
+            text.setEditable(false);\r
+            text.setBackground(null);\r
+        }\r
+    }\r
+\r
+    public void setText(String text) {\r
+        this.text.setText(text);\r
+    }\r
+\r
+    public void setTextWithoutNotify(String text) {\r
+        this.text.removeModifyListener(listener);\r
+        setText(text);\r
+        this.text.addModifyListener(listener);\r
+    }\r
+\r
+    public Text getWidget() {\r
+        return text;\r
+    }\r
+\r
+       public synchronized void addModifyListener(StringChooserModifyListener<T> listener) {\r
+        if (modifyListeners == null) {\r
+            modifyListeners = new ListenerList(ListenerList.IDENTITY);\r
+        }\r
+        modifyListeners.add(listener);\r
+    }\r
+\r
+       public synchronized void removeModifyListener(StringChooserModifyListener<T> listener) {\r
+        if (modifyListeners == null)\r
+            return;\r
+        modifyListeners.remove(listener);\r
+    }\r
+\r
+  \r
+\r
+    private String isTextValid() {\r
+        if (allowedLabels.contains(getWidget().getText()))\r
+               return null;\r
+        return "There is no such object.";\r
+    }\r
+\r
+    public void setColorProvider(ITrackedColorProvider provider) {\r
+        Assert.isNotNull(provider);\r
+        this.colorProvider = provider;\r
+    }\r
+\r
+    private void setBackground(Color background) {\r
+       if(text.isDisposed()) return;\r
+        if (!text.getEditable()) {\r
+            // Do not alter background when the widget is not editable.\r
+            return;\r
+        }\r
+        text.setBackground(background);\r
+    }\r
+    \r
+    public boolean isDisposed() {\r
+       return text.isDisposed();\r
+    }\r
+    \r
+    public Display getDisplay() {\r
+       return display;\r
+    }\r
+    \r
+    public String getText() {\r
+               return text.getText();\r
+       }\r
+    \r
+    public int getCaretPosition() {\r
+       return text.getCaretPosition();\r
+    }\r
+       \r
+       \r
+    /**\r
+     * A composite of many UI listeners for creating the functionality of this\r
+     * class.\r
+     */\r
+    private class CompositeListener\r
+    implements ModifyListener, DisposeListener, KeyListener, MouseTrackListener,\r
+    MouseListener, FocusListener\r
+    {\r
+        // Keyboard/editing events come in the following order:\r
+        //   1. keyPressed\r
+        //   2. verifyText\r
+        //   3. modifyText\r
+        //   4. keyReleased\r
+\r
+        @Override\r
+        public void modifyText(ModifyEvent e) {\r
+            //System.out.println("modifyText: " + e);\r
+            setModified(true);\r
+\r
+            String valid = isTextValid();\r
+            if (valid != null) {\r
+                setBackground(colorProvider.getInvalidBackground());\r
+            } else {\r
+                if (isEditing())\r
+                    setBackground(colorProvider.getEditingBackground());\r
+                else\r
+                    setBackground(colorProvider.getInactiveBackground());\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void widgetDisposed(DisposeEvent e) {\r
+            getWidget().removeModifyListener(this);\r
+        }\r
+\r
+        private boolean isMultiLine() {\r
+            return (text.getStyle() & SWT.MULTI) != 0;\r
+        }\r
+\r
+        private boolean hasMultiLineCommitModifier(KeyEvent e) {\r
+            return (e.stateMask & SWT.CTRL) != 0;\r
+        }\r
+\r
+        @Override\r
+        public void keyPressed(KeyEvent e) {\r
+            //System.out.println("keyPressed: " + e);\r
+            if (!isEditing()) {\r
+                // ESC, ENTER & keypad ENTER must not start editing\r
+                if (e.keyCode == SWT.ESC)\r
+                    return;\r
+\r
+                if (!isMultiLine()) {\r
+                    if (e.keyCode == SWT.F2 || e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {\r
+                        startEdit(selectAllOnStartEdit);\r
+                    } else if (e.character != '\0') {\r
+                        startEdit(false);\r
+                    }\r
+                } else {\r
+                    // In multi-line mode, TAB must not start editing!\r
+                    if (e.keyCode == SWT.F2) {\r
+                        startEdit(selectAllOnStartEdit);\r
+                    } else if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {\r
+                        if (hasMultiLineCommitModifier(e)) {\r
+                            e.doit = false;\r
+                        } else {\r
+                            startEdit(false);\r
+                        }\r
+                    } else if (e.keyCode == SWT.TAB) {\r
+                        text.traverse(((e.stateMask & SWT.SHIFT) != 0) ? SWT.TRAVERSE_TAB_PREVIOUS : SWT.TRAVERSE_TAB_NEXT);\r
+                        e.doit = false;\r
+                    } else if (e.character != '\0') {\r
+                        startEdit(false);\r
+                    }\r
+                }\r
+            } else {\r
+                // ESC reverts any changes made during this edit\r
+                if (e.keyCode == SWT.ESC) {\r
+                    revertEdit();\r
+                }\r
+                if (!isMultiLine()) {\r
+                    if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {\r
+                        applyEdit();\r
+                    }\r
+                } else {\r
+                    if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {\r
+                        if (hasMultiLineCommitModifier(e)) {\r
+                            applyEdit();\r
+                            e.doit = false;\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void keyReleased(KeyEvent e) {\r
+            //System.out.println("keyReleased: " + e);\r
+        }\r
+\r
+        @Override\r
+        public void mouseEnter(MouseEvent e) {\r
+            //System.out.println("mouseEnter");\r
+            if (!isEditing()) {\r
+                setBackground(colorProvider.getHoverBackground());\r
+            }\r
+            setMouseInsideControl(true);\r
+        }\r
+\r
+        @Override\r
+        public void mouseExit(MouseEvent e) {\r
+            //System.out.println("mouseExit");\r
+            if (!isEditing()) {\r
+                setBackground(colorProvider.getInactiveBackground());\r
+            }\r
+            setMouseInsideControl(false);\r
+        }\r
+\r
+        @Override\r
+        public void mouseHover(MouseEvent e) {\r
+            //System.out.println("mouseHover");\r
+            setMouseInsideControl(true);\r
+        }\r
+\r
+        @Override\r
+        public void mouseDoubleClick(MouseEvent e) {\r
+            //System.out.println("mouseDoubleClick: " + e);\r
+            if (e.button == 1) {\r
+                getWidget().selectAll();\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void mouseDown(MouseEvent e) {\r
+            //System.out.println("mouseDown: " + e);\r
+            if (!isEditing()) {\r
+                // In reality we should never get here, since focusGained\r
+                // always comes before mouseDown, but let's keep this\r
+                // fallback just to be safe.\r
+                if (e.button == 1) {\r
+                    startEdit(selectAllOnStartEdit);\r
+                }\r
+            } else {\r
+                if (e.button == 1 && (state & MOUSE_DOWN_FIRST_TIME) != 0) {\r
+                    if (!isMultiLine()) {\r
+                        // This is useless for multi-line texts\r
+                        getWidget().selectAll();\r
+                    }\r
+                    state &= ~MOUSE_DOWN_FIRST_TIME;\r
+                }\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void mouseUp(MouseEvent e) {\r
+        }\r
+\r
+        @Override\r
+        public void focusGained(FocusEvent e) {\r
+            //System.out.println("focusGained");\r
+            if (!isEditing()) {\r
+                if (!isMultiLine()) {\r
+                    // Always start edit on single line texts when focus is gained\r
+                    startEdit(selectAllOnStartEdit);\r
+                }\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void focusLost(FocusEvent e) {\r
+            //System.out.println("focusLost");\r
+            if (isEditing()) {\r
+                applyEdit();\r
+            }\r
+        }\r
+    }\r
+    \r
+    public void dispose() {\r
+       allowedLabels.clear();\r
+       allowedLabels = null;\r
+       objectFactory = null;\r
+       objectToLabel.clear();\r
+       objectToLabel = null;\r
+       \r
+    }\r
+    \r
+    \r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyEvent.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyEvent.java
new file mode 100644 (file)
index 0000000..c491665
--- /dev/null
@@ -0,0 +1,32 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.EventObject;\r
+\r
+import org.eclipse.swt.widgets.Widget;\r
+\r
+public class StringChooserModifyEvent<T>  extends EventObject {\r
+\r
+       private static final long serialVersionUID = 2630732165074702762L;\r
+       \r
+       private T object;\r
+       private String text;\r
+        \r
+       public StringChooserModifyEvent(Widget source, T object, String text) {\r
+                super(source);\r
+                this.object = object;\r
+                this.text = text;\r
+       }\r
+        \r
+       public Widget getWidget() {\r
+               return (Widget) getSource();\r
+       }\r
+       \r
+       public T getObject() {\r
+               return object;\r
+       }\r
+\r
+       public String getText() {\r
+               return text;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyListener.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyListener.java
new file mode 100644 (file)
index 0000000..b975640
--- /dev/null
@@ -0,0 +1,7 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+public interface StringChooserModifyListener<T> {\r
+\r
+       \r
+       void modifySelection(StringChooserModifyEvent<T> e);\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyListenerImpl.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/StringChooserModifyListenerImpl.java
new file mode 100644 (file)
index 0000000..8fa748d
--- /dev/null
@@ -0,0 +1,71 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.utils.ReflectionUtils;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+public abstract class StringChooserModifyListenerImpl<T,T2> implements StringChooserModifyListener<T2>, Widget {\r
+       protected ISessionContext context;\r
+       protected T lastInput = null;\r
+\r
+       protected final Class<?> clazz;\r
+\r
+       public StringChooserModifyListenerImpl() {\r
+               clazz = ReflectionUtils.getSingleParameterType(getClass());\r
+       }\r
+\r
+       private Object getInputContents(Object input, Class<?> inputClass) {\r
+               if (inputClass.isInstance(input))\r
+                       return input;\r
+               if (input instanceof ISelection)\r
+                       return ISelectionUtils.filterSingleSelection(input, inputClass);\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public void modifySelection(StringChooserModifyEvent<T2> e) {\r
+\r
+               Text text = (Text)e.getWidget();\r
+               final T2 object = e.getObject();\r
+               final String textValue = text.getText();\r
+               final T input = lastInput;\r
+\r
+               try {\r
+                       context.getSession().syncRequest(new WriteRequest() {\r
+\r
+                               @SuppressWarnings("unchecked")\r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       \r
+                                       if(clazz.isInstance(input)) {\r
+                                               applyObject(graph, (T)input, object, textValue);\r
+                                       } else {\r
+                                               T single = (T)getInputContents(input, clazz);\r
+                                               if(single != null)\r
+                                                       applyObject(graph, single, object, textValue);\r
+                                       }\r
+\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+       }\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object parameter) {\r
+               this.context = context;\r
+               lastInput = (T)parameter;\r
+       }\r
+\r
+       abstract public void applyObject(WriteGraph graph, T input, T2 object, String text) throws DatabaseException;\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TitleFactory.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TitleFactory.java
new file mode 100644 (file)
index 0000000..c02b3a5
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * TextFactory for chart title\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class TitleFactory extends ReadFactoryImpl<Resource, String>   {\r
+    @Override\r
+    public String perform(ReadGraph graph, Resource chart) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Resource title = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.TextTitle));\r
+        if(title == null)\r
+            return "";\r
+        else {\r
+            String label = graph.getPossibleRelatedValue(title, l0.HasLabel, Bindings.STRING);\r
+            return label == null ? "" : label;\r
+        }\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TitleModifier.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TitleModifier.java
new file mode 100644 (file)
index 0000000..543d173
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * TitleModifier for chart title\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class TitleModifier extends TextModifyListenerImpl<Resource> {\r
+\r
+    @Override\r
+    public void applyText(WriteGraph graph, Resource chart, String text) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        Resource title = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.TextTitle));\r
+        if(title == null) {\r
+            title = GraphUtils.create2(graph, jfree.TextTitle,\r
+                    jfree.Title_position, jfree.Top);\r
+        }\r
+        graph.claimLiteral(title, l0.HasLabel, text);\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TrackedSpinner.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/TrackedSpinner.java
new file mode 100644 (file)
index 0000000..74673a0
--- /dev/null
@@ -0,0 +1,179 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import org.eclipse.core.runtime.ListenerList;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Spinner;\r
+import org.simantics.browsing.ui.common.ErrorLogger;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactory;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.utils.ui.SWTUtils;\r
+\r
+/**\r
+ * Class for implementing Widget behavior for SWT Spinner in Simantics.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class TrackedSpinner implements Widget {\r
+\r
+    private Spinner         spinner;\r
+    private ListenerList    modifyListeners;\r
+    private ReadFactory<?, Integer> selectionFactory;\r
+\r
+\r
+    public TrackedSpinner(Composite parent, WidgetSupport support, int style) {\r
+        spinner = new Spinner(parent, style);\r
+        support.register(this);\r
+        \r
+        // Add a ModifyListener that uses all listeners in modifyListeners -list\r
+        spinner.addModifyListener(new ModifyListener() {\r
+            \r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                if (modifyListeners != null) {\r
+                    TrackedModifyEvent event = new TrackedModifyEvent(spinner, spinner.getText());\r
+                    for (Object o : modifyListeners.getListeners()) {\r
+                        ((TextModifyListener) o).modifyText(event);\r
+                    }\r
+                }                \r
+            }\r
+        });\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+\r
+        // Update all modifyListeners\r
+        if (modifyListeners != null) {\r
+            for (Object o : modifyListeners.getListeners()) {\r
+                if(o instanceof Widget) {\r
+                    ((Widget) o).setInput(context, input);\r
+                }\r
+            }\r
+        }\r
+\r
+        if (selectionFactory != null) {\r
+            // Get a value for the spinner\r
+            selectionFactory.listen(context, input, new Listener<Integer>() {\r
+                @Override\r
+                public void exception(Throwable t) {\r
+                    ErrorLogger.defaultLogError(t);\r
+                }\r
+                @Override\r
+                public void execute(final Integer selection) {\r
+                    SWTUtils.asyncExec(spinner, new Runnable() {\r
+                        @Override\r
+                        public void run() {\r
+                            if(isDisposed()) return;\r
+                            spinner.setSelection(selection);\r
+                        }\r
+                    });\r
+                }\r
+                @Override\r
+                public boolean isDisposed() {\r
+                    return spinner.isDisposed();\r
+                }\r
+            });\r
+        }\r
+\r
+    }\r
+    \r
+    /**\r
+     * Set a selection factory for the spinner\r
+     * \r
+     * @param selectionFactory ReadFactory<?, Integer> SelectionFactory\r
+     */\r
+    public void setSelectionFactory(ReadFactory<?, Integer> selectionFactory) {\r
+        this.selectionFactory = selectionFactory;\r
+    }\r
+    \r
+    /**\r
+     * Add a modifyListener for the spinner\r
+     * @param listener TextModifyListener\r
+     */\r
+    public synchronized void addModifyListener(TextModifyListener listener) {\r
+        if (modifyListeners == null) {\r
+            modifyListeners = new ListenerList(ListenerList.IDENTITY);\r
+        }\r
+        modifyListeners.add(listener);\r
+    }\r
+\r
+    /**\r
+     * Remove modifyListener from the spinner\r
+     * \r
+     * @param listener TextModifyListener\r
+     */\r
+    public synchronized void removeModifyListener(TextModifyListener listener) {\r
+        if (modifyListeners == null)\r
+            return;\r
+        modifyListeners.remove(listener);\r
+    }\r
+\r
+    /**\r
+     * Get the SWT Spinner of this TrackedSpinner widget\r
+     * @return\r
+     */\r
+    public Spinner getWidget() {\r
+        return spinner;\r
+    }\r
+    \r
+    /**\r
+     * Set minimum value \r
+     * @param value int minimum value\r
+     */\r
+    public void setMinimum(int value) {\r
+        spinner.setMinimum(value);\r
+    }\r
+    \r
+    /**\r
+     * Set maximum value\r
+     * @param value int maximum value\r
+     */\r
+    public void setMaximum(int value) {\r
+        spinner.setMaximum(value);\r
+    }\r
+    \r
+    /**\r
+     * Sets the receiver's selection, minimum value, maximum value, digits, increment and page increment all at once. \r
+     * \r
+     * @param selection the new selection value\r
+     * @param minimum the new minimum value\r
+     * @param maximum the new maximum value\r
+     * @param digits the new digits value\r
+     * @param increment the new increment value\r
+     * @param pageIncrement the new pageIncrement value\r
+     */\r
+    public void setValues(int selection, int  minimum, int  maximum, int digits, int increment, int pageIncrement) {\r
+        spinner.setValues(selection, minimum, maximum, digits, increment, pageIncrement);\r
+    }\r
+    \r
+    /**\r
+     * Sets the selection, which is the receiver's position, to the argument.\r
+     * If the argument is not within the range specified by minimum and maximum, \r
+     * it will be adjusted to fall within this range.\r
+     * \r
+     * @param value\r
+     */\r
+    public void setSelection(int value) {\r
+        spinner.setSelection(value);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableExistsValidator.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableExistsValidator.java
new file mode 100644 (file)
index 0000000..32abe9e
--- /dev/null
@@ -0,0 +1,129 @@
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.eclipse.jface.dialogs.IInputValidator;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Variable exists validator for tracked text widgets. \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class VariableExistsValidator implements IInputValidator, Widget {\r
+\r
+       protected Collection<ChartVariable> variables;\r
+    protected TrackedText text;\r
+    private boolean allowEmpty;\r
+    @SuppressWarnings("unused")\r
+    private boolean useLabels = false;\r
+    \r
+    /**\r
+     * Validate against all variables\r
+     * \r
+     * Do not allow empty input\r
+     * @param support WidgetSupport\r
+     * @param text Text widget\r
+     */\r
+    public VariableExistsValidator(WidgetSupport support, TrackedText text) {\r
+        this(support, text, false);\r
+    }\r
+    \r
+   \r
+    \r
+    /**\r
+     * Validate against all variables\r
+     * \r
+     * @param support WidgetSupport\r
+     * @param text Text widget\r
+     * @param allowEmpty Allow empty input text\r
+     */\r
+    public VariableExistsValidator(WidgetSupport support, TrackedText text, boolean allowEmpty) {\r
+        support.register(this);\r
+        this.variables = new ArrayList<ChartVariable>();\r
+        this.text = text;\r
+        this.allowEmpty = allowEmpty;\r
+    }\r
+    \r
+    public VariableExistsValidator(WidgetSupport support, TrackedText text, boolean allowEmpty, boolean useLabels) {\r
+        this(support, text, allowEmpty);\r
+        this.useLabels = useLabels;\r
+    }\r
+    \r
+    /**\r
+     * Returns null if there is a variable named newText in the model\r
+     */\r
+    @Override\r
+    public String isValid(String newText) {\r
+        if(newText == null || newText.isEmpty()) {\r
+            if(allowEmpty)\r
+                return null;\r
+            else\r
+                return "Empty name not allowed";\r
+        }\r
+        \r
+        synchronized (variables) {\r
+            for(ChartVariable variable : variables) {\r
+                if(newText.equals(variable.getLabel()))\r
+                    return null;\r
+                if(newText.equals(variable.getRvi()))\r
+                    return null;\r
+            }\r
+        }\r
+        \r
+        return "Not a valid variable name";\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        \r
+        if(resource == null) {\r
+            variables = new ArrayList<ChartVariable>();\r
+            return;\r
+        }\r
+        \r
+       \r
+        try {\r
+            /* Find the model resource. It can be found with PartOf \r
+               relations from series resource in a chart */\r
+           AllVariablesOfModel query = AllVariablesOfModel.withRandomResource(context, resource);\r
+            \r
+            if(query != null) {\r
+                // Find all variables and set them as the reference for isValid(String)\r
+                SimanticsUI.getSession().asyncRequest(query\r
+                , new Listener<Collection<ChartVariable>>() {\r
+\r
+                    @Override\r
+                    public void execute(Collection<ChartVariable> variables) {\r
+                        VariableExistsValidator.this.variables = variables;\r
+                    }\r
+\r
+                    @Override\r
+                    public void exception(Throwable t) {\r
+                        t.printStackTrace();\r
+                    }\r
+\r
+                    @Override\r
+                    public boolean isDisposed() {\r
+                        return text.isDisposed();\r
+                    }\r
+\r
+                }); \r
+            }\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableProposalProvider.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableProposalProvider.java
new file mode 100644 (file)
index 0000000..da399f6
--- /dev/null
@@ -0,0 +1,194 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Iterator;\r
+\r
+import org.eclipse.jface.fieldassist.ContentProposal;\r
+import org.eclipse.jface.fieldassist.IContentProposal;\r
+import org.eclipse.jface.fieldassist.IContentProposalProvider;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * \r
+ * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+ *\r
+ */\r
+public class VariableProposalProvider implements IContentProposalProvider, Widget {\r
+\r
+       /*\r
+        * The proposals provided.\r
+        */\r
+       private Collection<ChartVariable> proposals;\r
+\r
+       /*\r
+        * The proposals mapped to IContentProposal. Cached for speed in the case\r
+        * where filtering is not used.\r
+        */\r
+       private IContentProposal[] contentProposals;\r
+\r
+       /*\r
+        * Boolean that tracks whether filtering is used.\r
+        */\r
+       private boolean filterProposals = false;\r
+\r
+\r
+       private boolean compareRVI = false;\r
+       /**\r
+        * Return an array of Objects representing the valid content proposals for a\r
+        * field. \r
+        * \r
+        * @param contents\r
+        *            the current contents of the field (only consulted if filtering\r
+        *            is set to <code>true</code>)\r
+        * @param position\r
+        *            the current cursor position within the field (ignored)\r
+        * @return the array of Objects that represent valid proposals for the field\r
+        *         given its current content.\r
+        */\r
+       @SuppressWarnings("unchecked")\r
+       public IContentProposal[] getProposals(String contents, int position) {\r
+               if (filterProposals) {\r
+                       @SuppressWarnings("rawtypes")\r
+            ArrayList list = new ArrayList();\r
+                       if (compareRVI) {\r
+                               for (ChartVariable proposal : proposals) {\r
+                                       if (proposal.getRvi().length() >= contents.length() && proposal.getRvi().substring(0, contents.length()).equalsIgnoreCase(contents)) {\r
+                                               if (proposal.getLabel() != null)\r
+                                                       list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));\r
+                                               else\r
+                                                       list.add(new ContentProposal(proposal.getRvi()));\r
+                                       } else if (proposal.getLabel() != null && proposal.getLabel().length() >= contents.length() && proposal.getLabel().substring(0, contents.length()).equalsIgnoreCase(contents)) {\r
+                                               list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));\r
+                                       }\r
+                               }\r
+                       } else {\r
+                               for (ChartVariable proposal : proposals) {\r
+                                       if (proposal.getLabel() != null && proposal.getLabel().length() >= contents.length() && proposal.getLabel().substring(0, contents.length()).equalsIgnoreCase(contents)) {\r
+                                               list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       return (IContentProposal[]) list.toArray(new IContentProposal[list\r
+                                       .size()]);\r
+               }\r
+               if (contentProposals == null) {\r
+                       contentProposals = new IContentProposal[proposals.size()];\r
+                       Iterator<ChartVariable> iter = proposals.iterator();\r
+                       for (int i = 0; i < proposals.size(); i++) {\r
+                               ChartVariable proposal = iter.next();\r
+                               if (proposal.getLabel() != null)\r
+                                       contentProposals[i] = new ContentProposal(proposal.getRvi(),proposal.getLabel(),null);\r
+                               else\r
+                                       contentProposals[i] = new ContentProposal(proposal.getRvi());\r
+                       }\r
+               }\r
+               return contentProposals;\r
+       }\r
+\r
+       /**\r
+        * Set the Strings to be used as content proposals.\r
+        * \r
+        * @param items\r
+        *            the array of Strings to be used as proposals.\r
+        */\r
+       public void setProposals(Collection<ChartVariable> items) {\r
+               this.proposals = items;\r
+               contentProposals = null;\r
+       }\r
+\r
+       /**\r
+        * Set the boolean that controls whether proposals are filtered according to\r
+        * the current field content.\r
+        * \r
+        * @param filterProposals\r
+        *            <code>true</code> if the proposals should be filtered to\r
+        *            show only those that match the current contents of the field,\r
+        *            and <code>false</code> if the proposals should remain the\r
+        *            same, ignoring the field content.\r
+        * @since 3.3\r
+        */\r
+       public void setFiltering(boolean filterProposals) {\r
+               this.filterProposals = filterProposals;\r
+               // Clear any cached proposals.\r
+               contentProposals = null;\r
+       }\r
+       \r
+    /**\r
+     * Provides all variables a model contains. Given resource needs to be\r
+     * part of a model (i.e. using PartOf leads eventually to a SysdynModel).\r
+     *  \r
+     * @param control Control that is using this provider\r
+     * @param resource A resource that is part of a model\r
+     */\r
+    public VariableProposalProvider(final Control control, WidgetSupport support) {\r
+        this.proposals = new ArrayList<ChartVariable>();\r
+        support.register(this);\r
+        this.control = control;\r
+    }\r
+\r
+    private Resource resource;\r
+    private Control control;\r
+    \r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+\r
+        final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+        this.resource = resource;\r
+        /* Find the model resource. It can be found with PartOf \r
+        relations from series resource in a chart */\r
+       try {\r
+               AllVariablesOfModel query = AllVariablesOfModel.withRandomResource(context, resource);\r
+                SimanticsUI.getSession().asyncRequest(query\r
+               , new Listener<Collection<ChartVariable>>() {\r
+\r
+                   @Override\r
+                   public void execute(Collection<ChartVariable> result) {\r
+                       setProposals(result);\r
+                   }\r
+\r
+                   @Override\r
+                   public void exception(Throwable t) {\r
+                       t.printStackTrace();\r
+                   }\r
+\r
+                   @Override\r
+                   public boolean isDisposed() {\r
+                       return control == null || \r
+                               control.isDisposed() || \r
+                               !resource.equals(VariableProposalProvider.this.resource);\r
+                   }\r
+\r
+               }); \r
+       } catch (DatabaseException e) {\r
+               // TODO Auto-generated catch block\r
+               e.printStackTrace();\r
+       }\r
+        \r
+       \r
+        \r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarAxisTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarAxisTab.java
new file mode 100644 (file)
index 0000000..38f7d21
--- /dev/null
@@ -0,0 +1,430 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.bar;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Spinner;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.jfreechart.chart.properties.AxisHidePropertyComposite;\r
+import org.simantics.jfreechart.chart.properties.ColorPicker;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.TrackedSpinner;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Tab for bar chart axis properties\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class BarAxisTab extends AdjustableTab implements Widget {\r
+\r
+    private TrackedSpinner angle;\r
+    private Integer angleInt = null;\r
+    private WidgetSupportImpl domainAxisSupport = new WidgetSupportImpl();\r
+    private WidgetSupportImpl rangeAxisSupport = new WidgetSupportImpl();\r
+    private TrackedText rangelabel, rangemin, rangemax;\r
+    private ScrolledComposite sc;\r
+       private Group domainGroup;\r
+       private Label labelLabel;\r
+       private AxisHidePropertyComposite axisHide;\r
+       private Label angleLabel;\r
+       private Composite angleComposite;\r
+       private Label labelColor;\r
+       private ColorPicker colorPicker;\r
+       private Group rangeGroup;\r
+       private Label labelLabel2;\r
+       private Label labelMin;\r
+       private Composite minmax;\r
+       private Label labelMax;\r
+       private Label labelColor2;\r
+       private TrackedText rangelabel2;\r
+       private AxisHidePropertyComposite axisHide2;\r
+       private ColorPicker colorPicker2;\r
+       private Composite rangeComposite;\r
+       private Composite domainComposite;\r
+\r
+    /**\r
+     * ModifyListener for the angle {@link TrackedSpinner}\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class AngleModifyListener implements TextModifyListener, Widget {\r
+\r
+        private ISessionContext context;\r
+        private Object lastInput = null;\r
+\r
+        @Override\r
+        public void modifyText(TrackedModifyEvent e) {\r
+            if(context == null)\r
+                return;\r
+\r
+            // Get the text value from spinner and associated resource (input)\r
+            Spinner spinner = (Spinner)e.getWidget();\r
+            final String textValue = spinner.getText();\r
+            final Object input = lastInput;\r
+\r
+            try {\r
+                context.getSession().syncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                        Resource domainAxis = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+                        try {\r
+                            // usually reliable, since the spinner does all the checks\r
+                            Double value = Double.parseDouble(textValue); \r
+                            Double oldValue = graph.getPossibleRelatedValue(domainAxis, jfree.Axis_rotateLabelDegrees, Bindings.DOUBLE);\r
+                            if(oldValue == null || !oldValue.equals(value)) {\r
+                                graph.claimLiteral(domainAxis, jfree.Axis_rotateLabelDegrees, value, Bindings.DOUBLE);\r
+                                angleInt = value.intValue();\r
+                            }\r
+                        } catch (NumberFormatException e) {\r
+                            graph.claimLiteral(domainAxis, jfree.Axis_rotateLabelDegrees, 0.0, Bindings.DOUBLE);\r
+                            angleInt = 0;\r
+                        }\r
+                    }\r
+\r
+                });\r
+            } catch (DatabaseException e1) {\r
+                e1.printStackTrace();\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void setInput(ISessionContext context, Object parameter) {\r
+            this.context = context;\r
+            lastInput = parameter;\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Class for setting the value for angle {@link TrackedSpinner}\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class AngleSelectionFactory extends ReadFactoryImpl<Resource, Integer>   {\r
+\r
+        @Override\r
+        public Integer perform(ReadGraph graph, Resource domainAxis) throws DatabaseException {\r
+            if(angleInt == null) {\r
+                Double angle = 0.0;\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                if(domainAxis != null) {\r
+                    Double value = graph.getPossibleRelatedValue(domainAxis, jfree.Axis_rotateLabelDegrees);\r
+                    if(value != null)\r
+                        angle = value;\r
+                }\r
+                return angle.intValue();\r
+            } else {\r
+                return angleInt;\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public void setInput(final ISessionContext context, Object input) {\r
+        final Resource chart = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        if(chart == null)\r
+            return; \r
+\r
+        context.getSession().asyncRequest(new ReadRequest() {\r
+\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));\r
+                if(plot == null) return;\r
+                final Resource rangeAxis = graph.getPossibleObject(plot, jfree.Plot_rangeAxis);\r
+                final Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
+                if(rangeAxis == null && domainAxis == null) return;\r
+                Display.getDefault().asyncExec(new Runnable() {\r
+                                       \r
+                                       @Override\r
+                                       public void run() {\r
+                                               if (rangeAxis != null)\r
+                                                       rangeAxisSupport.fireInput(context, new StructuredSelection(rangeAxis));\r
+                                               if (domainAxis != null)\r
+                                                       domainAxisSupport.fireInput(context, new StructuredSelection(domainAxis));\r
+                                               \r
+                                       }\r
+                               });\r
+            }\r
+        });\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               support.register(this);\r
+\r
+        // Scrolled composite containing all of the properties in this tab\r
+        sc = new ScrolledComposite(body, SWT.NONE | SWT.H_SCROLL | SWT.V_SCROLL);\r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);\r
+\r
+        composite = new Composite(sc, SWT.NONE);\r
+\r
+        // Domain Axis properties\r
+        domainGroup = new Group(composite, SWT.NONE);\r
+        domainGroup.setText("Domain axis");\r
+\r
+        domainComposite = new Composite(domainGroup, SWT.NONE);\r
+        \r
+        // Label for x-axis\r
+        labelLabel = new Label(domainComposite, SWT.NONE);\r
+        labelLabel.setText("Label:");\r
+\r
+        rangelabel = new TrackedText(domainComposite, domainAxisSupport, SWT.BORDER);\r
+        rangelabel.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, ""));\r
+        rangelabel.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        rangelabel.setColorProvider(new JFreeChartPropertyColorProvider(rangelabel.getResourceManager()));\r
+        \r
+        angleLabel = new Label(domainComposite, SWT.NONE);\r
+        angleLabel.setText("Label angle:");\r
+\r
+        angleComposite = new Composite(domainComposite, SWT.NONE);\r
+        angle = new TrackedSpinner(angleComposite, domainAxisSupport, SWT.BORDER);\r
+        angle.setSelectionFactory(new AngleSelectionFactory());\r
+        angle.addModifyListener(new AngleModifyListener());\r
+        angle.setMinimum(0);\r
+        angle.setMaximum(90);\r
+        angle.getWidget().setIncrement(5);\r
+\r
+        // Domain Color\r
+        labelColor = new Label(domainComposite, SWT.NONE);\r
+        labelColor.setText("Color:");\r
+\r
+        colorPicker = new ColorPicker(domainComposite, context, domainAxisSupport, SWT.NONE);\r
+\r
+        axisHide = new AxisHidePropertyComposite(domainGroup, context, domainAxisSupport, SWT.NONE);\r
+\r
+        \r
+        // Range Axis properties\r
+        rangeGroup = new Group(composite, SWT.NONE);\r
+        rangeGroup.setText("Range axis");\r
+\r
+        rangeComposite = new Composite(rangeGroup, SWT.NONE);\r
+        \r
+        // Label for range axis\r
+        labelLabel2 = new Label(rangeComposite, SWT.NONE);\r
+        labelLabel2.setText("Label:");\r
+        labelLabel2.setAlignment(SWT.RIGHT);\r
+\r
+        rangelabel2 = new TrackedText(rangeComposite, rangeAxisSupport, SWT.BORDER);\r
+        rangelabel2.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, ""));\r
+        rangelabel2.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        rangelabel2.setColorProvider(new JFreeChartPropertyColorProvider(rangelabel2.getResourceManager()));\r
+\r
+\r
+        // Min and max values for range axis\r
+        labelMin = new Label(rangeComposite, SWT.NONE);\r
+        labelMin.setText("Min:");\r
+\r
+        minmax = new Composite(rangeComposite, SWT.NONE);\r
+        rangemin = new TrackedText(minmax, rangeAxisSupport, SWT.BORDER);\r
+        rangemin.setColorProvider(new JFreeChartPropertyColorProvider(rangemin.getResourceManager()));\r
+        rangemin.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Axis_min));\r
+        rangemin.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Axis_min));\r
+        rangemin.setInputValidator(new DoubleValidator(true));\r
+\r
+        labelMax = new Label(minmax, SWT.NONE);\r
+        labelMax.setText("Max:");\r
+        rangemax = new TrackedText(minmax, rangeAxisSupport, SWT.BORDER);\r
+        rangemax.setColorProvider(new JFreeChartPropertyColorProvider(rangemax.getResourceManager()));\r
+        rangemax.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Axis_max));\r
+        rangemax.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Axis_max));\r
+        rangemax.setInputValidator(new DoubleValidator(true));\r
+\r
+        // Range Color\r
+        labelColor2 = new Label(rangeComposite, SWT.NONE);\r
+        labelColor2.setText("Color:");\r
+\r
+        colorPicker2 = new ColorPicker(rangeComposite, context, rangeAxisSupport, SWT.NONE);\r
+\r
+        axisHide2 = new AxisHidePropertyComposite(rangeGroup, context, rangeAxisSupport, SWT.NONE);\r
+        \r
+        // Resize scrolled composite\r
+        sc.setContent(composite);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(sc);\r
+\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+\r
+        // Domain Axis properties\r
+        GridDataFactory.fillDefaults().grab(false, false).applyTo(domainGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(domainGroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(domainComposite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(domainComposite);\r
+\r
+        // Label for x-axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelLabel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(rangelabel.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(angleLabel);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(angleComposite);\r
+        GridLayoutFactory.fillDefaults().applyTo(angleComposite);\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).grab(false, true).applyTo(angle.getWidget());\r
+\r
+        // Domain Color\r
+        GridDataFactory.fillDefaults().grab(false, false).align(SWT.END, SWT.CENTER).applyTo(labelColor);\r
+\r
+        GridDataFactory.fillDefaults().grab(false, true).minSize(SWT.DEFAULT, 31).align(SWT.BEGINNING, SWT.CENTER).applyTo(colorPicker);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(axisHide);\r
+\r
+        domainGroup.layout();\r
+\r
+        // Range Axis properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(rangeGroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeComposite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(rangeComposite);\r
+\r
+        // Label for range axis\r
+        GridDataFactory.fillDefaults().hint(angleLabel.getBounds().width, SWT.DEFAULT).align(SWT.END, SWT.CENTER).applyTo(labelLabel2);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(rangelabel2.getWidget());\r
+\r
+        // Min and max values for range axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelMin);\r
+\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).grab(false, true).applyTo(minmax);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(minmax);\r
+        GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(rangemax.getWidget());\r
+        GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(rangemin.getWidget());\r
+        \r
+        // Range Color\r
+        GridDataFactory.fillDefaults().grab(false, false).align(SWT.END, SWT.CENTER).applyTo(labelColor2);\r
+\r
+        GridDataFactory.fillDefaults().grab(false, true).minSize(SWT.DEFAULT, 31).align(SWT.BEGINNING, SWT.CENTER).applyTo(colorPicker2);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(axisHide2);\r
+\r
+        // Resize scrolled composite\r
+        Point size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        sc.setMinSize(size);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(sc);\r
+\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+\r
+        // Domain Axis properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(domainGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(domainGroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(domainComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(4).applyTo(domainComposite);\r
+\r
+        // Label for x-axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelLabel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(rangelabel.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(angleLabel);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(angleComposite);\r
+        GridLayoutFactory.fillDefaults().applyTo(angleComposite);\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).grab(false, true).applyTo(angle.getWidget());\r
+\r
+        // Domain Color\r
+        GridDataFactory.fillDefaults().grab(true, false).align(SWT.END, SWT.CENTER).applyTo(labelColor);\r
+\r
+        GridDataFactory.fillDefaults().grab(false, true).minSize(SWT.DEFAULT, SWT.DEFAULT).align(SWT.BEGINNING, SWT.CENTER).applyTo(colorPicker);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(axisHide);\r
+\r
+        domainGroup.layout();\r
+\r
+        // Range Axis properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(rangeGroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(4).applyTo(rangeComposite);\r
+\r
+        // Label for range axis\r
+        GridDataFactory.fillDefaults().hint(angleLabel.getBounds().width, SWT.DEFAULT).align(SWT.END, SWT.CENTER).applyTo(labelLabel2);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(rangelabel2.getWidget());\r
+\r
+        // Min and max values for range axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelMin);\r
+\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).grab(false, true).applyTo(minmax);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(minmax);\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, SWT.DEFAULT).applyTo(rangemax.getWidget());\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, SWT.DEFAULT).applyTo(rangemin.getWidget());\r
+        \r
+        // Range Color\r
+        GridDataFactory.fillDefaults().grab(true, false).align(SWT.END, SWT.CENTER).applyTo(labelColor2);\r
+\r
+        GridDataFactory.fillDefaults().grab(false, true).minSize(SWT.DEFAULT, SWT.DEFAULT).align(SWT.BEGINNING, SWT.CENTER).applyTo(colorPicker2);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(axisHide2);\r
+\r
+        // Resize scrolled composite\r
+        Point size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        sc.setMinSize(size);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarGeneralPropertiesTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarGeneralPropertiesTab.java
new file mode 100644 (file)
index 0000000..370d14d
--- /dev/null
@@ -0,0 +1,505 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.bar;\r
+\r
+import java.util.LinkedHashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.layout.LayoutConstants;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.ChartPropertyOptions;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.jfreechart.chart.properties.BooleanPropertyFactory;\r
+import org.simantics.jfreechart.chart.properties.BooleanSelectionListener;\r
+import org.simantics.jfreechart.chart.properties.DoublePropertyFactory2;\r
+import org.simantics.jfreechart.chart.properties.DoublePropertyModifier2;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.TitleFactory;\r
+import org.simantics.jfreechart.chart.properties.TitleModifier;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+\r
+/**\r
+ * General properties of a bar chart\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class BarGeneralPropertiesTab extends AdjustableTab {\r
+\r
+    private ScrolledComposite sc;\r
+    private Button hgrid, htitle, hlegend;\r
+    private TrackedText name, title, time;\r
+    private TrackedCombo type;\r
+    private TrackedCombo orientation;\r
+\r
+    private boolean showTime = true;\r
+    private boolean showFilter = false;\r
+       private Group general;\r
+       private Composite labelColumn1;\r
+       private Composite propertyColumn1;\r
+       private Composite labelColumn2;\r
+       private Composite propertyColumn2;\r
+       private Label labelName;\r
+       private Label labelTitle;\r
+       private Label labelTime;\r
+       private Label labelType;\r
+       private Group typeGroup;\r
+       private Label labelOrientation;\r
+       private Group hideGroup;\r
+       private Label labelUse;\r
+       private Label labelPercent;\r
+       private Group filteringGroup;\r
+       private Button useFilter;\r
+       private TrackedText fraction;\r
+       private Point size;\r
+    \r
+    public BarGeneralPropertiesTab() {\r
+       \r
+    }\r
+    \r
+    public BarGeneralPropertiesTab(int options) {\r
+       showTime = ((options & ChartPropertyOptions.SHOW_TIME) > 0); \r
+       showFilter = ((options & ChartPropertyOptions.SHOW_FILTER) > 0);\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class TypeSelectionFactory extends ReadFactoryImpl<Resource, String> {\r
+        @Override\r
+        public String perform(ReadGraph graph, Resource chart) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.CategoryPlot));\r
+            if(plot != null) {\r
+                Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.CategoryDataset));\r
+\r
+                if(dataset != null) {\r
+                    Resource renderer = graph.syncRequest(new PossibleObjectWithType(dataset, jfree.Dataset_renderer, jfree.Renderer));\r
+\r
+                    if(renderer != null && graph.isInstanceOf(renderer, jfree.StackedBarRenderer))\r
+                        return "Stacked";\r
+                }\r
+            }\r
+            return "Normal";\r
+        }\r
+    }\r
+\r
+    /**\r
+     * RangeItemFactory finds all inexes of a given enumeration \r
+     * and adds "Sum" and "All" to the returned indexes\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class TypeItemFactory extends ReadFactoryImpl<Resource, Map<String, Object>> {\r
+        @Override\r
+        public Map<String, Object> perform(ReadGraph graph, Resource series) throws DatabaseException {\r
+            LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();\r
+            result.put("Normal", "Normal");\r
+            result.put("Stacked", "Stacked");\r
+            return result;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * TypeModifyListener for modifying the type of a bar chart \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class TypeModifyListener  extends ComboModifyListenerImpl<Resource> {\r
+        @Override\r
+        public void applyText(WriteGraph graph, Resource chart, String text) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.CategoryPlot));\r
+            if(plot == null)\r
+                return;\r
+\r
+            Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.CategoryDataset));\r
+            if(dataset == null)\r
+                return;\r
+\r
+            graph.deny(dataset, jfree.Dataset_renderer);\r
+\r
+            Resource renderer;\r
+            if(text.equals("Stacked"))\r
+                renderer = GraphUtils.create2(graph, jfree.StackedBarRenderer);\r
+            else\r
+                renderer = GraphUtils.create2(graph, jfree.BarRenderer);\r
+\r
+            graph.claim(dataset, jfree.Dataset_renderer, renderer);\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+     *\r
+     */\r
+    private class OrientationSelectionFactory extends ReadFactoryImpl<Resource, String> {\r
+        @Override\r
+        public String perform(ReadGraph graph, Resource chart) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.CategoryPlot));\r
+            if(plot != null) {\r
+               Boolean orientation = graph.getPossibleRelatedValue(plot, jfree.Plot_orientation);\r
+               if (orientation != null) {\r
+                       if (orientation)\r
+                               return "Horizontal";\r
+                       return "Vertical";                      \r
+               }\r
+                            }\r
+            return "Vertical";\r
+        }\r
+    }\r
+\r
+   /**\r
+    * \r
+    * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+    *\r
+    */\r
+    private class OrientationItemFactory extends ReadFactoryImpl<Resource, Map<String, Object>> {\r
+        @Override\r
+        public Map<String, Object> perform(ReadGraph graph, Resource series) throws DatabaseException {\r
+            LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();\r
+            result.put("Vertical", "Vertical");\r
+            result.put("Horizontal", "Horizontal");\r
+            return result;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
+     *\r
+     */\r
+    private class OrientationModifyListener  extends ComboModifyListenerImpl<Resource> {\r
+        @Override\r
+        public void applyText(WriteGraph graph, Resource chart, String text) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.CategoryPlot));\r
+            if(plot == null)\r
+                return;\r
+\r
+           \r
+            if(text.equals("Horizontal"))\r
+                graph.claimLiteral(plot, jfree.Plot_orientation,true);\r
+            else\r
+               graph.claimLiteral(plot, jfree.Plot_orientation,false);\r
+\r
+            \r
+        }\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        sc = new ScrolledComposite(body, SWT.NONE | SWT.H_SCROLL | SWT.V_SCROLL);\r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);\r
+\r
+        composite = new Composite(sc, SWT.NONE);\r
+\r
+        // General properties\r
+        general = new Group(composite, SWT.NONE);\r
+        general.setText("General");\r
+\r
+        // first column: labels\r
+        labelColumn1 = new Composite(general, SWT.NONE);\r
+        \r
+        // second column: name and title\r
+        propertyColumn1 = new Composite(general, SWT.NONE);\r
+        \r
+        // third column: labels\r
+        labelColumn2 = new Composite(general, SWT.NONE);\r
+        \r
+        // fourth column: type and time\r
+        propertyColumn2 = new Composite(general, SWT.NONE);\r
+        \r
+        // Name\r
+        labelName = new Label(labelColumn1, SWT.NONE);\r
+        labelName.setText("Name:");\r
+\r
+        name = new org.simantics.browsing.ui.swt.widgets.TrackedText(propertyColumn1, support, SWT.BORDER);\r
+        name.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));\r
+        name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        name.setColorProvider(new JFreeChartPropertyColorProvider(name.getResourceManager()));\r
+\r
+        labelTitle = new Label(labelColumn2, SWT.NONE);\r
+        labelTitle = new Label(propertyColumn2, SWT.NONE);\r
+        \r
+        // Title (Which is different than name)\r
+        labelTitle = new Label(labelColumn1, SWT.NONE);\r
+        labelTitle.setText("Title:");\r
+\r
+        title = new org.simantics.browsing.ui.swt.widgets.TrackedText(propertyColumn1, support, SWT.BORDER);\r
+        title.setTextFactory(new TitleFactory());\r
+        title.addModifyListener(new TitleModifier());\r
+        title.setColorProvider(new JFreeChartPropertyColorProvider(name.getResourceManager()));\r
+\r
+        if (showTime) {\r
+               // Time\r
+               labelTime = new Label(labelColumn2, SWT.NONE);\r
+               labelTime.setText("Time:");\r
+               \r
+               time = new org.simantics.browsing.ui.swt.widgets.TrackedText(propertyColumn2, support, SWT.BORDER);\r
+               time.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Chart_time));\r
+               time.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Chart_time));\r
+               time.setInputValidator(new DoubleValidator(true));\r
+        time.setColorProvider(new JFreeChartPropertyColorProvider(time.getResourceManager()));\r
+        }\r
+        \r
+        typeGroup = new Group(composite,SWT.NONE);\r
+        typeGroup.setText("Visuals");\r
+        \r
+        labelType = new Label(typeGroup, SWT.NONE);\r
+        labelType.setText("Type:");\r
+\r
+        type = new TrackedCombo(typeGroup, support, SWT.BORDER | SWT.READ_ONLY);\r
+        type.addModifyListener(new TypeModifyListener());\r
+        type.setItemFactory(new TypeItemFactory());\r
+        type.setSelectionFactory(new TypeSelectionFactory());\r
+        \r
+        labelOrientation = new Label(typeGroup, SWT.NONE);\r
+        labelOrientation.setText("Orientation:");\r
+        \r
+        orientation = new TrackedCombo(typeGroup, support, SWT.BORDER | SWT.READ_ONLY);\r
+        orientation.addModifyListener(new OrientationModifyListener());\r
+        orientation.setItemFactory(new OrientationItemFactory());\r
+        orientation.setSelectionFactory(new OrientationSelectionFactory());\r
+\r
+        \r
+        // Group for hide options\r
+        hideGroup = new Group(composite, SWT.NONE);\r
+        hideGroup.setText("Hide");\r
+\r
+        hgrid = new Button(hideGroup, support, SWT.CHECK);\r
+        hgrid.setText("Grid");\r
+        hgrid.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Plot_visibleGrid, true));\r
+        hgrid.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Plot_visibleGrid,true));\r
+        htitle = new Button(hideGroup, support, SWT.CHECK);\r
+        htitle.setText("Title");\r
+        htitle.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.TextTitle, JFreeChartResource.URIs.visible, true));\r
+        htitle.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.TextTitle, JFreeChartResource.URIs.visible,true));\r
+        hlegend = new Button(hideGroup, support, SWT.CHECK);\r
+        hlegend.setText("Legend");\r
+        hlegend.setSelectionFactory(new BooleanPropertyFactory(null, JFreeChartResource.URIs.Chart_visibleLegend, true));\r
+        hlegend.addSelectionListener(new BooleanSelectionListener(context, null, JFreeChartResource.URIs.Chart_visibleLegend,true));\r
+\r
+        if (showFilter) {\r
+               filteringGroup = new Group(composite, SWT.NONE);\r
+               filteringGroup.setText("Filter");\r
+               labelUse = new Label(filteringGroup, SWT.NONE);\r
+               labelUse.setText("Use:");\r
+               useFilter = new Button(filteringGroup, support, SWT.CHECK);\r
+               useFilter.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Filter_used, false));\r
+               useFilter.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Filter_used));\r
+               labelPercent = new Label(filteringGroup, SWT.NONE);\r
+               labelPercent.setText("Percent:");\r
+               fraction = new TrackedText(filteringGroup, support, SWT.BORDER);\r
+               fraction.setTextFactory(new DoublePropertyFactory2(JFreeChartResource.URIs.Plot,JFreeChartResource.URIs.Filter_fraction));\r
+               fraction.addModifyListener(new DoublePropertyModifier2(context, JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Filter_fraction));\r
+               fraction.setInputValidator(new DoubleValidator(true));\r
+               fraction.setColorProvider(new JFreeChartPropertyColorProvider(fraction.getResourceManager()));\r
+        }\r
+        \r
+        // Resize scrolled composite\r
+        sc.setContent(composite);\r
+        \r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+\r
+        if (showFilter)\r
+               GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+        else\r
+               GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+\r
+        // General properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(general);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(general);\r
+\r
+        // first column: labels\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelColumn1);\r
+        GridLayoutFactory.fillDefaults().applyTo(labelColumn1);\r
+        \r
+        // second column: name and title\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyColumn1);\r
+        GridLayoutFactory.fillDefaults().spacing(0, LayoutConstants.getSpacing().y).applyTo(propertyColumn1);\r
+        \r
+        // third column: labels\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelColumn2);\r
+        GridLayoutFactory.fillDefaults().spacing(0, LayoutConstants.getSpacing().y).applyTo(labelColumn2);\r
+        \r
+        // fourth column: type and time\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(propertyColumn2);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyColumn2);\r
+        \r
+        // Name\r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelName);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelTitle);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(title.getWidget());\r
+\r
+        if (showTime) {\r
+               // Time\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelTime);\r
+               \r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(time.getWidget());\r
+        }\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(typeGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(typeGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelType);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(type.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelOrientation);\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(type.getWidget());\r
+\r
+        // Group for hide options\r
+        GridDataFactory.fillDefaults().applyTo(hideGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(hideGroup);\r
+\r
+        if (showFilter) {\r
+               GridDataFactory.fillDefaults().applyTo(filteringGroup);\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(filteringGroup);\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelUse);\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelPercent);\r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(fraction.getWidget());\r
+        }\r
+        \r
+        size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        sc.setMinSize(size);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+\r
+        if (showFilter)\r
+               GridLayoutFactory.fillDefaults().numColumns(4).margins(3, 3).applyTo(composite);\r
+        else\r
+               GridLayoutFactory.fillDefaults().numColumns(3).margins(3, 3).applyTo(composite);\r
+\r
+        // General properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(general);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(4).applyTo(general);\r
+\r
+        // first column: labels\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelColumn1);\r
+        GridLayoutFactory.fillDefaults().applyTo(labelColumn1);\r
+        \r
+        // second column: name and title\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyColumn1);\r
+        GridLayoutFactory.fillDefaults().spacing(0, LayoutConstants.getSpacing().y).applyTo(propertyColumn1);\r
+        \r
+        // third column: labels\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelColumn2);\r
+        GridLayoutFactory.fillDefaults().spacing(0, LayoutConstants.getSpacing().y).applyTo(labelColumn2);\r
+        \r
+        // fourth column: type and time\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(propertyColumn2);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyColumn2);\r
+        \r
+        // Name\r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelName);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelTitle);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(title.getWidget());\r
+\r
+        if (showTime) {\r
+               // Time\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelTime);\r
+               \r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(time.getWidget());\r
+        }\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(typeGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(typeGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelType);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(type.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelOrientation);\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(type.getWidget());\r
+\r
+        // Group for hide options\r
+        GridDataFactory.fillDefaults().applyTo(hideGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(hideGroup);\r
+\r
+        if (showFilter) {\r
+               GridDataFactory.fillDefaults().applyTo(filteringGroup);\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(filteringGroup);\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelUse);\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelPercent);\r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(fraction.getWidget());\r
+        }\r
+        \r
+        size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        sc.setMinSize(size);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesPropertyComposite.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesPropertyComposite.java
new file mode 100644 (file)
index 0000000..ca8777e
--- /dev/null
@@ -0,0 +1,100 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.bar;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.ChartPropertyOptions;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.RVIFactory;\r
+import org.simantics.jfreechart.chart.properties.RVIModifier;\r
+import org.simantics.jfreechart.chart.properties.RangeComposite;\r
+import org.simantics.jfreechart.chart.properties.VariableExistsValidator;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Composite for modifying properties of a series in a bar chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class BarSeriesPropertyComposite extends Composite {\r
+    \r
+    private TrackedText variable, label, time;\r
+    \r
+    public BarSeriesPropertyComposite(Composite parent, final ISessionContext context, WidgetSupport support, int options, int style) {\r
+        super(parent, style);\r
+        \r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(this);\r
+\r
+        // Variable for the series\r
+        Label label = new Label(this, SWT.NONE);\r
+        label.setText("Variable:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        variable = new TrackedText(this, support, SWT.BORDER);\r
+        variable.setTextFactory(new RVIFactory());\r
+        variable.addModifyListener(new RVIModifier(variable.getWidget(), support));\r
+        variable.setInputValidator(new VariableExistsValidator(support, variable));\r
+        variable.setColorProvider(new JFreeChartPropertyColorProvider(this.variable.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this.variable.getWidget());\r
+\r
+        // Range\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Range:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        RangeComposite rangeComposite = new RangeComposite(this, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeComposite);\r
+        \r
+        \r
+        // Label to be displayed in chart for this series\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Label:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        this.label = new TrackedText(this, support, SWT.BORDER);\r
+        this.label.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, ""));\r
+        this.label.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        this.label.setColorProvider(new JFreeChartPropertyColorProvider(this.label.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this.label.getWidget());\r
+        \r
+        // Time\r
+        if ((options & ChartPropertyOptions.SHOW_TIME) > 0) {\r
+               label = new Label(this, SWT.NONE);\r
+               GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+               label.setText("Time:");\r
+               \r
+               Composite composite = new Composite(this, SWT.NONE);\r
+               GridDataFactory.fillDefaults().applyTo(composite);\r
+               GridLayoutFactory.fillDefaults().applyTo(composite);\r
+               \r
+               time = new org.simantics.browsing.ui.swt.widgets.TrackedText(composite, support, SWT.BORDER);\r
+               time.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Series_time));\r
+               time.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Series_time));\r
+               time.setInputValidator(new DoubleValidator(true));\r
+               time.setColorProvider(new JFreeChartPropertyColorProvider(time.getResourceManager()));\r
+               GridDataFactory.fillDefaults().applyTo(time.getWidget());\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesPropertyComposite2.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesPropertyComposite2.java
new file mode 100644 (file)
index 0000000..a9a1d48
--- /dev/null
@@ -0,0 +1,124 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.bar;\r
+\r
+import java.util.Collection;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.ChartPropertyOptions;\r
+import org.simantics.jfreechart.chart.properties.ChartVariable;\r
+import org.simantics.jfreechart.chart.properties.ChartVariableFactory;\r
+import org.simantics.jfreechart.chart.properties.ChartVariableModifier;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.RangeComposite;\r
+import org.simantics.jfreechart.chart.properties.StringChooser;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Composite for modifying properties of a series in a bar chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class BarSeriesPropertyComposite2 extends Composite {\r
+    \r
+    private TrackedText label, time;\r
+    private StringChooser<ChartVariable> variable;\r
+    \r
+    public BarSeriesPropertyComposite2(Composite parent, final ISessionContext context, WidgetSupport support, Collection<ChartVariable> variables, int options, int style) {\r
+        super(parent, style);\r
+        \r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(this);\r
+\r
+        // Variable for the series\r
+        Label label = new Label(this, SWT.NONE);\r
+        label.setText("Variable:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+//        variable = new TrackedText(this, support, SWT.BORDER);\r
+//       \r
+//     // FIXME: using bijectionmap and trackedText looses the variables that have the same label.\r
+//     BijectionMap<String , String> map = new BijectionMap<String, String>();\r
+//     for (ChartVariable variable : variables) {\r
+//                     map.map(variable.getRvi(), variable.toString());\r
+//             }\r
+//     variable.setTextFactory(new VariableFactory(map));\r
+//     variable.addModifyListener(new VariableModifier(variable.getWidget(), support));\r
+//     variable.setInputValidator(new VariableExistsValidator(support, variable, false, true));\r
+       \r
+\r
+        variable = new StringChooser<ChartVariable>(this, support, SWT.BORDER);\r
+        variable.setData(variables);\r
+        variable.setObjectFactory(new ChartVariableFactory(variables));\r
+        variable.addModifyListener(new ChartVariableModifier(variable.getWidget(), support));\r
+        \r
+        variable.setColorProvider(new JFreeChartPropertyColorProvider(this.variable.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this.variable.getWidget());\r
+\r
+        // Range\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Range:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        RangeComposite rangeComposite = new RangeComposite(this, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeComposite);\r
+        \r
+        \r
+        // Label to be displayed in chart for this series\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Label:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        this.label = new TrackedText(this, support, SWT.BORDER);\r
+        this.label.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, ""));\r
+        this.label.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        this.label.setColorProvider(new JFreeChartPropertyColorProvider(this.label.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this.label.getWidget());\r
+        \r
+        if ((options & ChartPropertyOptions.SHOW_TIME) > 0) {\r
+               // Time\r
+               label = new Label(this, SWT.NONE);\r
+               GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+               label.setText("Time:");\r
+               \r
+               Composite composite = new Composite(this, SWT.NONE);\r
+               GridDataFactory.fillDefaults().applyTo(composite);\r
+               GridLayoutFactory.fillDefaults().applyTo(composite);\r
+               \r
+               time = new org.simantics.browsing.ui.swt.widgets.TrackedText(composite, support, SWT.BORDER);\r
+               time.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Series_time));\r
+               time.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Series_time));\r
+               time.setInputValidator(new DoubleValidator(true));\r
+               time.setColorProvider(new JFreeChartPropertyColorProvider(time.getResourceManager()));\r
+               GridDataFactory.fillDefaults().applyTo(time.getWidget());\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void dispose() {\r
+       variable.dispose();\r
+       variable = null;\r
+       super.dispose();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesTab.java
new file mode 100644 (file)
index 0000000..5a9c55a
--- /dev/null
@@ -0,0 +1,241 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.bar;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Tab containing the series of a bar chart\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class BarSeriesTab extends AdjustableTab implements Widget {\r
+\r
+    private GraphExplorerComposite explorer;\r
+    private ScrolledComposite propertyContainer;\r
+    private WidgetSupportImpl additionalSupport;\r
+    private Button add, remove;\r
+    private Resource chartResource;\r
+    private BarSeriesPropertyComposite spc;\r
+    private int options;\r
+       private Composite buttonComposite;\r
+\r
+    public BarSeriesTab(int options) {\r
+        additionalSupport = new WidgetSupportImpl();\r
+        this.options = options;\r
+    }\r
+\r
+    /**\r
+     * Updates the content of propertyContainer  \r
+     * @param context\r
+     */\r
+    private void updateSelection(ISessionContext context) {\r
+        ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
+        IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
+        final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+\r
+        for(Control child : propertyContainer.getChildren()) {\r
+            child.dispose();\r
+        }\r
+        spc = new BarSeriesPropertyComposite(propertyContainer, context, additionalSupport, options,SWT.NONE);\r
+\r
+        additionalSupport.fireInput(context, selection);\r
+\r
+        propertyContainer.setContent(spc);\r
+        Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        propertyContainer.setMinSize(size);\r
+    }\r
+\r
+    /**\r
+     * SelectionListener for adding a new variable to a plot\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class NewVariableListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public NewVariableListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            Resource dataset = null;\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            if(input == null) {\r
+                if(chartResource != null) {\r
+                    Resource plot = graph.syncRequest(new PossibleObjectWithType(chartResource, l0.ConsistsOf, jfree.Plot));\r
+                    if(plot != null)\r
+                        dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+                }\r
+            } else {\r
+                if(graph.isInstanceOf(input, jfree.Series)) {\r
+                    dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                }\r
+            }\r
+\r
+            if(dataset != null) {\r
+                // Create series with no rvi\r
+                ChartUtils.createSeries(graph, dataset, null);\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * SelectionListener for remove button\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class RemoveListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public RemoveListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        /**\r
+         * Removes selected resource from explorer\r
+         */\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            if(input == null)\r
+                return; \r
+\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            Resource list = null;\r
+            if(graph.isInstanceOf(input, jfree.Series)) {\r
+                // Remove series from dataset and seriesList\r
+                Resource dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                if(dataset != null)\r
+                    list = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+\r
+                if(list != null)\r
+                    ListUtils.removeElement(graph, list, input);\r
+                RemoverUtil.remove(graph, input);\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        chartResource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       final ISessionContext context, WidgetSupport support) {\r
+               support.register(this);\r
+        composite = new Composite(body, SWT.NONE);\r
+\r
+        // (Ontology-based) GraphExplorer displaying variables in a bar chart\r
+        explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
+        explorer.setBrowseContexts(JFreeChartResource.URIs.BarSeriesBrowseContext);\r
+        explorer.setInputSource(new SingleSelectionInputSource(\r
+                Resource.class));\r
+        explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
+        explorer.finish();\r
+\r
+        ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
+            public void widgetSelected(SelectionEvent e) {\r
+                updateSelection(context);\r
+            }\r
+        });\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
+        propertyContainer.setExpandHorizontal(true);\r
+        propertyContainer.setExpandVertical(true);\r
+\r
+        // Buttons for adding and removing variables from a pie plot\r
+        buttonComposite = new Composite(composite, SWT.NONE);\r
+\r
+        add = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        add.setText("Add");\r
+        add.addSelectionListener(new NewVariableListener(context));\r
+\r
+        remove = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        remove.setText("Remove");\r
+        remove.addSelectionListener(new RemoveListener(context));\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().hint(150, 200).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().hint(150, 130).span(1, 1).grab(true, false).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+\r
+        // Buttons for adding and removing variables from a pie plot\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().span(1, 2).grab(true, true).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+\r
+        // Buttons for adding and removing variables from a pie plot\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesTab2.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/bar/BarSeriesTab2.java
new file mode 100644 (file)
index 0000000..24076dd
--- /dev/null
@@ -0,0 +1,227 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.bar;\r
+\r
+import java.util.Collection;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.jfreechart.chart.properties.AllVariablesOfModel;\r
+import org.simantics.jfreechart.chart.properties.ChartVariable;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+/**\r
+ * Tab containing the series of a bar chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class BarSeriesTab2 extends LabelPropertyTabContributor implements Widget {\r
+\r
+    private GraphExplorerComposite explorer;\r
+    private ScrolledComposite propertyContainer;\r
+    private WidgetSupportImpl additionalSupport;\r
+    private Button add, remove;\r
+    private Resource chartResource;\r
+    private BarSeriesPropertyComposite2 spc;\r
+    private int options;\r
+\r
+    public BarSeriesTab2(int options) {\r
+        additionalSupport = new WidgetSupportImpl();\r
+        this.options = options;\r
+    }\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, final ISessionContext context, WidgetSupport support) {\r
+        support.register(this);\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        // (Ontology-based) GraphExplorer displaying variables in a bar chart\r
+        explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
+        explorer.setBrowseContexts(JFreeChartResource.URIs.BarSeriesBrowseContext);\r
+        explorer.setInputSource(new SingleSelectionInputSource(\r
+                Resource.class));\r
+        explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
+        explorer.finish();\r
+\r
+        ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
+            public void widgetSelected(SelectionEvent e) {\r
+                updateSelection(context);\r
+            }\r
+        });\r
+        GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
+        GridDataFactory.fillDefaults().span(1, 2).grab(true, true).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+        propertyContainer.setExpandHorizontal(true);\r
+        propertyContainer.setExpandVertical(true);\r
+\r
+        // Buttons for adding and removing variables from a pie plot\r
+        Composite buttonComposite = new Composite(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+\r
+        add = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        add.setText("Add");\r
+        add.addSelectionListener(new NewVariableListener(context));\r
+\r
+        remove = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        remove.setText("Remove");\r
+        remove.addSelectionListener(new RemoveListener(context));\r
+    }\r
+\r
+    /**\r
+     * Updates the content of propertyContainer  \r
+     * @param context\r
+     */\r
+    private void updateSelection(ISessionContext context) {\r
+        ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
+        IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
+        final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+        \r
+        for(Control child : propertyContainer.getChildren()) {\r
+            child.dispose();\r
+        }\r
+        \r
+        try {\r
+               AllVariablesOfModel query = AllVariablesOfModel.withRandomResource(context, resource);\r
+               Collection<ChartVariable> variables = context.getSession().syncRequest(query);\r
+               \r
+               spc = new BarSeriesPropertyComposite2(propertyContainer, context, additionalSupport, variables, options, SWT.NONE);\r
+       \r
+               additionalSupport.fireInput(context, selection);\r
+       \r
+               propertyContainer.setContent(spc);\r
+               Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+               propertyContainer.setMinSize(size);\r
+        } catch (DatabaseException e) {\r
+               ExceptionUtils.logAndShowError(e);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * SelectionListener for adding a new variable to a plot\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class NewVariableListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public NewVariableListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            Resource dataset = null;\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            if(input == null) {\r
+                if(chartResource != null) {\r
+                    Resource plot = graph.syncRequest(new PossibleObjectWithType(chartResource, l0.ConsistsOf, jfree.Plot));\r
+                    if(plot != null)\r
+                        dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+                }\r
+            } else {\r
+                if(graph.isInstanceOf(input, jfree.Series)) {\r
+                    dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                }\r
+            }\r
+\r
+            if(dataset != null) {\r
+                // Create series with no rvi\r
+                ChartUtils.createSeries(graph, dataset, null);\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * SelectionListener for remove button\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class RemoveListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public RemoveListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        /**\r
+         * Removes selected resource from explorer\r
+         */\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            if(input == null)\r
+                return; \r
+\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            Resource list = null;\r
+            if(graph.isInstanceOf(input, jfree.Series)) {\r
+                // Remove series from dataset and seriesList\r
+                Resource dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                if(dataset != null)\r
+                    list = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+\r
+                if(list != null)\r
+                    ListUtils.removeElement(graph, list, input);\r
+                RemoverUtil.remove(graph, input);\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        chartResource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieGeneralPropertiesTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieGeneralPropertiesTab.java
new file mode 100644 (file)
index 0000000..3185932
--- /dev/null
@@ -0,0 +1,318 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.pie;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.layout.LayoutConstants;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.ChartPropertyOptions;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.jfreechart.chart.properties.BooleanPropertyFactory;\r
+import org.simantics.jfreechart.chart.properties.BooleanSelectionListener;\r
+import org.simantics.jfreechart.chart.properties.DoublePropertyFactory2;\r
+import org.simantics.jfreechart.chart.properties.DoublePropertyModifier2;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.TitleFactory;\r
+import org.simantics.jfreechart.chart.properties.TitleModifier;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * General properties of a pie chart\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class PieGeneralPropertiesTab extends AdjustableTab {\r
+\r
+    private ScrolledComposite sc;\r
+    private Button htitle, hlegend, hlabels;\r
+    private TrackedText name, title, time;\r
+    \r
+    private boolean showTime = true;\r
+    private boolean showFilter = false;\r
+       private Group general;\r
+       private Composite labelColumn1;\r
+       private Composite propertyColumn1;\r
+       private Composite labelColumn2;\r
+       private Composite propertyColumn2;\r
+       private Label labelName;\r
+       private Label labelTitle;\r
+       private Label labelTime;\r
+       private Group hideGroup;\r
+       private Group filteringGroup;\r
+       private Label labelUse;\r
+       private Label labelPercent;\r
+       private Button useFilter;\r
+       private TrackedText fraction;\r
+       private Point size;\r
+    \r
+    public PieGeneralPropertiesTab() {\r
+       \r
+    }\r
+    \r
+    public PieGeneralPropertiesTab(int options) {\r
+       showTime = ((options & ChartPropertyOptions.SHOW_TIME) > 0); \r
+       showFilter = ((options & ChartPropertyOptions.SHOW_FILTER) > 0);\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        sc = new ScrolledComposite(body, SWT.NONE | SWT.H_SCROLL | SWT.V_SCROLL);\r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);\r
+\r
+        composite = new Composite(sc, SWT.NONE);\r
+\r
+        // General properties\r
+        general = new Group(composite, SWT.NONE);\r
+        general.setText("General");\r
+\r
+        // first column: labels\r
+        labelColumn1 = new Composite(general, SWT.NONE);\r
+        \r
+        // first column: name and title\r
+        propertyColumn1 = new Composite(general, SWT.NONE);\r
+        \r
+        // first column: labels\r
+        labelColumn2 = new Composite(general, SWT.NONE);\r
+        \r
+        // first column: type and time\r
+        propertyColumn2 = new Composite(general, SWT.NONE);\r
+        \r
+        // Name\r
+        labelName = new Label(labelColumn1, SWT.NONE);\r
+        labelName.setText("Name:");\r
+\r
+        name = new org.simantics.browsing.ui.swt.widgets.TrackedText(propertyColumn1, support, SWT.BORDER);\r
+        name.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));\r
+        name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        name.setColorProvider(new JFreeChartPropertyColorProvider(name.getResourceManager()));\r
+\r
+        // Dummy data for now. Waiting for different pie chart types\r
+        labelTitle = new Label(labelColumn2, SWT.NONE);\r
+        labelTitle.setText("");\r
+        \r
+        labelTitle = new Label(propertyColumn2, SWT.NONE);\r
+        labelTitle.setText("");\r
+        \r
+        // Title (Which is different than name)\r
+        labelTitle = new Label(labelColumn1, SWT.NONE);\r
+        labelTitle.setText("Title:");\r
+\r
+        title = new org.simantics.browsing.ui.swt.widgets.TrackedText(propertyColumn1, support, SWT.BORDER);\r
+        title.setTextFactory(new TitleFactory());\r
+        title.addModifyListener(new TitleModifier());\r
+        title.setColorProvider(new JFreeChartPropertyColorProvider(name.getResourceManager()));\r
+\r
+        if (showTime) {\r
+               // Time\r
+               labelTime = new Label(labelColumn2, SWT.NONE);\r
+               labelTime.setText("Time:");\r
+               \r
+               time = new org.simantics.browsing.ui.swt.widgets.TrackedText(propertyColumn2, support, SWT.BORDER);\r
+               time.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Chart_time));\r
+               time.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Chart_time));\r
+               time.setInputValidator(new DoubleValidator(true));\r
+               time.setColorProvider(new JFreeChartPropertyColorProvider(time.getResourceManager()));\r
+        }\r
+        // Group for hide options\r
+        hideGroup = new Group(composite, SWT.NONE);\r
+        hideGroup.setText("Hide");\r
+\r
+        htitle = new Button(hideGroup, support, SWT.CHECK);\r
+        htitle.setText("Title");\r
+        htitle.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.TextTitle, JFreeChartResource.URIs.visible, true));\r
+        htitle.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.TextTitle, JFreeChartResource.URIs.visible,true));\r
+        hlegend = new Button(hideGroup, support, SWT.CHECK);\r
+        hlegend.setText("Legend");\r
+        hlegend.setSelectionFactory(new BooleanPropertyFactory(null, JFreeChartResource.URIs.Chart_visibleLegend, true));\r
+        hlegend.addSelectionListener(new BooleanSelectionListener(context, null, JFreeChartResource.URIs.Chart_visibleLegend,true));\r
+        hlabels = new Button(hideGroup, support, SWT.CHECK);\r
+        hlabels.setText("Section labels");\r
+        hlabels.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Plot_visibleLabels, true));\r
+        hlabels.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Plot_visibleLabels,true));\r
+        \r
+        if (showFilter) {\r
+               filteringGroup = new Group(composite, SWT.NONE);\r
+               filteringGroup.setText("Filter");\r
+               labelUse = new Label(filteringGroup, SWT.NONE);\r
+               labelUse.setText("Use:");\r
+               useFilter = new Button(filteringGroup, support, SWT.CHECK);\r
+               useFilter.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Filter_used, false));\r
+               useFilter.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Filter_used));\r
+               labelPercent = new Label(filteringGroup, SWT.NONE);\r
+               labelPercent.setText("Percent:");\r
+               fraction = new TrackedText(filteringGroup, support, SWT.BORDER);\r
+               fraction.setTextFactory(new DoublePropertyFactory2(JFreeChartResource.URIs.Plot,JFreeChartResource.URIs.Filter_fraction));\r
+               fraction.addModifyListener(new DoublePropertyModifier2(context, JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Filter_fraction));\r
+               fraction.setInputValidator(new DoubleValidator(true));\r
+               fraction.setColorProvider(new JFreeChartPropertyColorProvider(fraction.getResourceManager()));\r
+        }\r
+        \r
+        sc.setContent(composite);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+\r
+        if (showFilter)\r
+               GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+        else\r
+               GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+\r
+        // General properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(general);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(general);\r
+\r
+        // first column: labels\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelColumn1);\r
+        GridLayoutFactory.fillDefaults().applyTo(labelColumn1);\r
+        \r
+        // first column: name and title\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyColumn1);\r
+        GridLayoutFactory.fillDefaults().spacing(0, LayoutConstants.getSpacing().y).applyTo(propertyColumn1);\r
+        \r
+        // first column: labels\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelColumn2);\r
+        GridLayoutFactory.fillDefaults().spacing(0, LayoutConstants.getSpacing().y).applyTo(labelColumn2);\r
+        \r
+        // first column: type and time\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(propertyColumn2);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyColumn2);\r
+        \r
+        // Name\r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelName);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
+\r
+        // Dummy data for now. Waiting for different pie chart types\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelTitle);\r
+        \r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelTitle);\r
+        \r
+        // Title (Which is different than name)\r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelTitle);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(title.getWidget());\r
+\r
+        if (showTime) {\r
+               // Time\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelTime);\r
+               \r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(time.getWidget());\r
+        }\r
+        // Group for hide options\r
+        GridDataFactory.fillDefaults().applyTo(hideGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(hideGroup);\r
+\r
+        if (showFilter) {\r
+               GridDataFactory.fillDefaults().applyTo(filteringGroup);\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(filteringGroup);\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelUse);\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelPercent);\r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(fraction.getWidget());\r
+        }\r
+        \r
+        size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        sc.setMinSize(size);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+\r
+        if (showFilter)\r
+               GridLayoutFactory.fillDefaults().numColumns(3).margins(3, 3).applyTo(composite);\r
+        else\r
+               GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        // General properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(general);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(4).applyTo(general);\r
+\r
+        // first column: labels\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelColumn1);\r
+        GridLayoutFactory.fillDefaults().applyTo(labelColumn1);\r
+        \r
+        // first column: name and title\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyColumn1);\r
+        GridLayoutFactory.fillDefaults().spacing(0, LayoutConstants.getSpacing().y).applyTo(propertyColumn1);\r
+        \r
+        // first column: labels\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelColumn2);\r
+        GridLayoutFactory.fillDefaults().spacing(0, LayoutConstants.getSpacing().y).applyTo(labelColumn2);\r
+        \r
+        // first column: type and time\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(propertyColumn2);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyColumn2);\r
+        \r
+        // Name\r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelName);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
+\r
+        // Dummy data for now. Waiting for different pie chart types\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelTitle);\r
+        \r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(labelTitle);\r
+        \r
+        // Title (Which is different than name)\r
+        GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelTitle);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(title.getWidget());\r
+\r
+        if (showTime) {\r
+               // Time\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelTime);\r
+               \r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(time.getWidget());\r
+        }\r
+        // Group for hide options\r
+        GridDataFactory.fillDefaults().applyTo(hideGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(hideGroup);\r
+\r
+        if (showFilter) {\r
+               GridDataFactory.fillDefaults().applyTo(filteringGroup);\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(filteringGroup);\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelUse);\r
+               GridDataFactory.fillDefaults().grab(false, true).align(SWT.END, SWT.CENTER).applyTo(labelPercent);\r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(fraction.getWidget());\r
+        }\r
+        \r
+        size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        sc.setMinSize(size);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesPropertyComposite.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesPropertyComposite.java
new file mode 100644 (file)
index 0000000..1dd80e8
--- /dev/null
@@ -0,0 +1,123 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.pie;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.ChartPropertyOptions;\r
+import org.simantics.jfreechart.chart.properties.BooleanPropertyFactory;\r
+import org.simantics.jfreechart.chart.properties.BooleanSelectionListener;\r
+import org.simantics.jfreechart.chart.properties.ColorPicker;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.RVIFactory;\r
+import org.simantics.jfreechart.chart.properties.RVIModifier;\r
+import org.simantics.jfreechart.chart.properties.RangeComposite;\r
+import org.simantics.jfreechart.chart.properties.VariableExistsValidator;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Composite containing the properties of a series\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PieSeriesPropertyComposite extends Composite {\r
+    \r
+    private TrackedText variable, label, time;\r
+    \r
+    public PieSeriesPropertyComposite(Composite parent, ISessionContext context, WidgetSupport support, int options, int style) {\r
+        super(parent, style);\r
+        \r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(this);\r
+\r
+        // Variable for the series\r
+        Label label = new Label(this, SWT.NONE);\r
+        label.setText("Variable:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        variable = new TrackedText(this, support, SWT.BORDER);\r
+        variable.setTextFactory(new RVIFactory());\r
+        variable.addModifyListener(new RVIModifier(variable.getWidget(), support));\r
+        variable.setInputValidator(new VariableExistsValidator(support, variable));\r
+        variable.setColorProvider(new JFreeChartPropertyColorProvider(this.variable.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this.variable.getWidget());\r
+\r
+        // Range\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Range:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        RangeComposite rangeComposite = new RangeComposite(this, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeComposite);\r
+        \r
+        \r
+        // Label to be displayed in chart for this series\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Label:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        this.label = new TrackedText(this, support, SWT.BORDER);\r
+        this.label.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, ""));\r
+        this.label.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        this.label.setColorProvider(new JFreeChartPropertyColorProvider(this.label.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this.label.getWidget());\r
+\r
+        // Color\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Color:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+\r
+        Composite colorPicker = new ColorPicker(this, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(colorPicker);\r
+\r
+        // Time\r
+        if ((options & ChartPropertyOptions.SHOW_TIME) > 0) {\r
+               label = new Label(this, SWT.NONE);\r
+               GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+               label.setText("Time:");\r
+               \r
+               Composite composite = new Composite(this, SWT.NONE);\r
+               GridDataFactory.fillDefaults().applyTo(composite);\r
+               GridLayoutFactory.fillDefaults().applyTo(composite);\r
+               \r
+               time = new org.simantics.browsing.ui.swt.widgets.TrackedText(composite, support, SWT.BORDER);\r
+               time.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Series_time));\r
+               time.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Series_time));\r
+               time.setInputValidator(new DoubleValidator(true));\r
+               time.setColorProvider(new JFreeChartPropertyColorProvider(time.getResourceManager()));\r
+               GridDataFactory.fillDefaults().applyTo(time.getWidget());\r
+        }\r
+        // Exploded\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        \r
+        Button exploded = new Button(this, support, SWT.CHECK);\r
+        exploded.setText("Exploded");\r
+        exploded.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Series_exploded));\r
+        exploded.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.Series_exploded));\r
+        GridDataFactory.fillDefaults().applyTo(exploded.getWidget());\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesPropertyComposite2.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesPropertyComposite2.java
new file mode 100644 (file)
index 0000000..3f3c4af
--- /dev/null
@@ -0,0 +1,136 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.pie;\r
+\r
+import java.util.Collection;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.ChartPropertyOptions;\r
+import org.simantics.jfreechart.chart.properties.BooleanPropertyFactory;\r
+import org.simantics.jfreechart.chart.properties.BooleanSelectionListener;\r
+import org.simantics.jfreechart.chart.properties.ChartVariable;\r
+import org.simantics.jfreechart.chart.properties.ChartVariableFactory;\r
+import org.simantics.jfreechart.chart.properties.ChartVariableModifier;\r
+import org.simantics.jfreechart.chart.properties.ColorPicker;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.RangeComposite;\r
+import org.simantics.jfreechart.chart.properties.StringChooser;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Composite containing the properties of a series\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PieSeriesPropertyComposite2 extends Composite {\r
+    \r
+    private TrackedText label, time;\r
+    private StringChooser<ChartVariable> variable;\r
+    \r
+    public PieSeriesPropertyComposite2(Composite parent, ISessionContext context, WidgetSupport support, Collection<ChartVariable> variables,int options, int style) {\r
+        super(parent, style);\r
+        \r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(this);\r
+\r
+        // Variable for the series\r
+        Label label = new Label(this, SWT.NONE);\r
+        label.setText("Variable:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        \r
+        variable = new StringChooser<ChartVariable>(this, support, SWT.BORDER);\r
+        variable.setData(variables);\r
+        variable.setObjectFactory(new ChartVariableFactory(variables));\r
+        variable.addModifyListener(new ChartVariableModifier(variable.getWidget(), support));\r
+        \r
+        variable.setColorProvider(new JFreeChartPropertyColorProvider(this.variable.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this.variable.getWidget());\r
+\r
+        // Range\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Range:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        RangeComposite rangeComposite = new RangeComposite(this, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeComposite);\r
+        \r
+        \r
+        // Label to be displayed in chart for this series\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Label:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        this.label = new TrackedText(this, support, SWT.BORDER);\r
+        this.label.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, ""));\r
+        this.label.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        this.label.setColorProvider(new JFreeChartPropertyColorProvider(this.label.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(this.label.getWidget());\r
+\r
+        // Color\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Color:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+\r
+        Composite colorPicker = new ColorPicker(this, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(colorPicker);\r
+\r
+        if ((options & ChartPropertyOptions.SHOW_TIME) > 0) {\r
+               // Time\r
+               label = new Label(this, SWT.NONE);\r
+               GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+               label.setText("Time:");\r
+               \r
+               Composite composite = new Composite(this, SWT.NONE);\r
+               GridDataFactory.fillDefaults().applyTo(composite);\r
+               GridLayoutFactory.fillDefaults().applyTo(composite);\r
+               \r
+               time = new org.simantics.browsing.ui.swt.widgets.TrackedText(composite, support, SWT.BORDER);\r
+               time.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Series_time));\r
+               time.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Series_time));\r
+               time.setInputValidator(new DoubleValidator(true));\r
+               time.setColorProvider(new JFreeChartPropertyColorProvider(time.getResourceManager()));\r
+               GridDataFactory.fillDefaults().applyTo(time.getWidget());\r
+        }\r
+        // Exploded\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        \r
+        Button exploded = new Button(this, support, SWT.CHECK);\r
+        exploded.setText("Exploded");\r
+        exploded.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Series_exploded));\r
+        exploded.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.Series_exploded));\r
+        GridDataFactory.fillDefaults().applyTo(exploded.getWidget());\r
+    }\r
+    \r
+    @Override\r
+    public void dispose() {\r
+       variable.dispose();\r
+       variable = null;\r
+       super.dispose();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesTab.java
new file mode 100644 (file)
index 0000000..d5cf346
--- /dev/null
@@ -0,0 +1,240 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.pie;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Tab for modifying series in a pie chart configuration\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class PieSeriesTab extends AdjustableTab implements Widget {\r
+\r
+    private GraphExplorerComposite explorer;\r
+    private ScrolledComposite propertyContainer;\r
+    private WidgetSupportImpl additionalSupport;\r
+    private Button add, remove;\r
+    private Resource chartResource;\r
+    private int options;\r
+       private Composite buttonComposite;\r
+    \r
+    public PieSeriesTab(int options) {\r
+        additionalSupport = new WidgetSupportImpl();\r
+        this.options = options;\r
+    }\r
+\r
+    /**\r
+     * Updates the content of propertyContainer  \r
+     * @param context\r
+     */\r
+    private void updateSelection(ISessionContext context) {\r
+        ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
+        IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
+        final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+\r
+        for(Control child : propertyContainer.getChildren()) {\r
+            child.dispose();\r
+        }\r
+\r
+        PieSeriesPropertyComposite spc = new PieSeriesPropertyComposite(propertyContainer, context, additionalSupport, options,SWT.NONE);\r
+        propertyContainer.setContent(spc);\r
+        Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        propertyContainer.setMinSize(size);\r
+\r
+        additionalSupport.fireInput(context, selection);\r
+    }\r
+\r
+\r
+    /**\r
+     * SelectionListener for adding a new variable to a plot\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class NewVariableListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public NewVariableListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            Resource dataset = null;\r
+            if(input == null) {\r
+                if(chartResource != null) {\r
+                    Resource plot = graph.syncRequest(new PossibleObjectWithType(chartResource, l0.ConsistsOf, jfree.Plot));\r
+                    if(plot != null)\r
+                        dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+                }\r
+            } else {\r
+                if(graph.isInstanceOf(input, jfree.Series)) {\r
+                    dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                }\r
+            }\r
+            if(dataset != null) {\r
+                // Create series with no rvi\r
+                Resource series = ChartUtils.createSeries(graph, dataset, null);\r
+                graph.claimLiteral(series, jfree.Series_exploded, false);\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * SelectionListener for remove button\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class RemoveListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public RemoveListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        /**\r
+         * Removes selected resource from explorer\r
+         */\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            if(input == null)\r
+                return; \r
+\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            Resource list = null;\r
+            if(graph.isInstanceOf(input, jfree.Series)) {\r
+                // Remove series from dataset and seriesList\r
+                Resource dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                if(dataset != null)\r
+                    list = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+\r
+                if(list != null)\r
+                    ListUtils.removeElement(graph, list, input);\r
+                RemoverUtil.remove(graph, input);\r
+            }\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        chartResource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       final ISessionContext context, WidgetSupport support) {\r
+               support.register(this);\r
+        composite = new Composite(body, SWT.NONE);\r
+\r
+        // (Ontology-based) GraphExplorer displaying variables of a pie chart\r
+        explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
+        explorer.setBrowseContexts(JFreeChartResource.URIs.PieSeriesBrowseContext);\r
+        explorer.setInputSource(new SingleSelectionInputSource(\r
+                Resource.class));\r
+        explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
+        explorer.finish();\r
+\r
+        ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
+            public void widgetSelected(SelectionEvent e) {\r
+                updateSelection(context);\r
+            }\r
+        });\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
+        propertyContainer.setExpandHorizontal(true);\r
+        propertyContainer.setExpandVertical(true);\r
+\r
+\r
+        // Buttons for adding and removing variables from a pie plot\r
+        buttonComposite = new Composite(composite, SWT.NONE);\r
+\r
+        add = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        add.setText("Add");\r
+        add.addSelectionListener(new NewVariableListener(context));\r
+\r
+        remove = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        remove.setText("Remove");\r
+        remove.addSelectionListener(new RemoveListener(context));\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().hint(150, 200).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().hint(150, 190).span(1, 1).grab(true, false).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+\r
+        // Buttons for adding and removing variables from a pie plot\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().span(1, 2).grab(true, true).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+\r
+        // Buttons for adding and removing variables from a pie plot\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesTab2.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/pie/PieSeriesTab2.java
new file mode 100644 (file)
index 0000000..7103b6f
--- /dev/null
@@ -0,0 +1,223 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.pie;\r
+\r
+import java.util.Collection;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.jfreechart.chart.properties.AllVariablesOfModel;\r
+import org.simantics.jfreechart.chart.properties.ChartVariable;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+/**\r
+ * Tab for modifying series in a pie chart configuration\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PieSeriesTab2 extends LabelPropertyTabContributor implements Widget {\r
+\r
+    private GraphExplorerComposite explorer;\r
+    private ScrolledComposite propertyContainer;\r
+    private WidgetSupportImpl additionalSupport;\r
+    private Button add, remove;\r
+    private Resource chartResource;\r
+    private int options;\r
+\r
+    public PieSeriesTab2(int options) {\r
+        additionalSupport = new WidgetSupportImpl();\r
+        this.options = options;\r
+    }\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, final ISessionContext context, WidgetSupport support) {\r
+        support.register(this);\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        // (Ontology-based) GraphExplorer displaying variables of a pie chart\r
+        explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
+        explorer.setBrowseContexts(JFreeChartResource.URIs.PieSeriesBrowseContext);\r
+        explorer.setInputSource(new SingleSelectionInputSource(\r
+                Resource.class));\r
+        explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
+        explorer.finish();\r
+\r
+        ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
+            public void widgetSelected(SelectionEvent e) {\r
+                updateSelection(context);\r
+            }\r
+        });\r
+        GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
+        GridDataFactory.fillDefaults().span(1, 2).grab(true, true).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+        propertyContainer.setExpandHorizontal(true);\r
+        propertyContainer.setExpandVertical(true);\r
+\r
+\r
+        // Buttons for adding and removing variables from a pie plot\r
+        Composite buttonComposite = new Composite(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+\r
+        add = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        add.setText("Add");\r
+        add.addSelectionListener(new NewVariableListener(context));\r
+\r
+        remove = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        remove.setText("Remove");\r
+        remove.addSelectionListener(new RemoveListener(context));\r
+    }\r
+\r
+    /**\r
+     * Updates the content of propertyContainer  \r
+     * @param context\r
+     */\r
+    private void updateSelection(ISessionContext context) {\r
+        ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
+        IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
+        final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+\r
+        for(Control child : propertyContainer.getChildren()) {\r
+            child.dispose();\r
+        }\r
+\r
+        try {\r
+               AllVariablesOfModel query = AllVariablesOfModel.withRandomResource(context, resource);\r
+               Collection<ChartVariable> variables = context.getSession().syncRequest(query);\r
+               PieSeriesPropertyComposite2 spc = new PieSeriesPropertyComposite2(propertyContainer, context, additionalSupport, variables, options, SWT.NONE);\r
+               propertyContainer.setContent(spc);\r
+               Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+               propertyContainer.setMinSize(size);\r
+       \r
+               additionalSupport.fireInput(context, selection);\r
+        } catch (DatabaseException e) {\r
+               ExceptionUtils.logAndShowError(e);\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * SelectionListener for adding a new variable to a plot\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class NewVariableListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public NewVariableListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            Resource dataset = null;\r
+            if(input == null) {\r
+                if(chartResource != null) {\r
+                    Resource plot = graph.syncRequest(new PossibleObjectWithType(chartResource, l0.ConsistsOf, jfree.Plot));\r
+                    if(plot != null)\r
+                        dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+                }\r
+            } else {\r
+                if(graph.isInstanceOf(input, jfree.Series)) {\r
+                    dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                }\r
+            }\r
+            if(dataset != null) {\r
+                // Create series with no rvi\r
+                Resource series = ChartUtils.createSeries(graph, dataset, null);\r
+                graph.claimLiteral(series, jfree.Series_exploded, false);\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * SelectionListener for remove button\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class RemoveListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public RemoveListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        /**\r
+         * Removes selected resource from explorer\r
+         */\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            if(input == null)\r
+                return; \r
+\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            Resource list = null;\r
+            if(graph.isInstanceOf(input, jfree.Series)) {\r
+                // Remove series from dataset and seriesList\r
+                Resource dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                if(dataset != null)\r
+                    list = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+\r
+                if(list != null)\r
+                    ListUtils.removeElement(graph, list, input);\r
+                RemoverUtil.remove(graph, input);\r
+            }\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        chartResource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisAndVariablesExplorerComposite.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisAndVariablesExplorerComposite.java
new file mode 100644 (file)
index 0000000..04b0209
--- /dev/null
@@ -0,0 +1,91 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.xyline;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Map;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.common.ErrorLogger;\r
+import org.simantics.browsing.ui.model.InvalidContribution;\r
+import org.simantics.browsing.ui.model.dnd.DndBrowseContext;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.Procedure;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * ExplorerComposite allowing ontology-based DnD definitions. DnD Copied from {@link ModelBrowser2}\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class AxisAndVariablesExplorerComposite extends GraphExplorerComposite {\r
+\r
+    volatile DndBrowseContext dndBrowseContext;\r
+    \r
+    public AxisAndVariablesExplorerComposite(Map<String, Object> args, IWorkbenchSite site, Composite parent,\r
+            WidgetSupport support, int style) {\r
+        super(args, site, parent, support, style);\r
+        \r
+        SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException { \r
+                ArrayList<Resource> browseContexts = new ArrayList<Resource>();\r
+                for (String uri : getBrowseContexts()) {\r
+                    Resource browseContext = graph.getPossibleResource(uri);\r
+                    if (browseContext != null)\r
+                        browseContexts.add(browseContext);\r
+                }\r
+                try {\r
+                    dndBrowseContext = DndBrowseContext.create(graph, browseContexts);\r
+                } catch (InvalidContribution e) {\r
+                    ErrorLogger.defaultLogError(e);\r
+                }\r
+            }\r
+        });\r
+    }\r
+    \r
+    @Override\r
+    protected void handleDrop(final Object data, final NodeContext target) {\r
+        if (target == null)\r
+            return;\r
+\r
+        SimanticsUI.getSession().asyncRequest(new Read<Runnable>() {\r
+            @Override\r
+            public Runnable perform(ReadGraph graph) throws DatabaseException {\r
+                if (dndBrowseContext == null)\r
+                    return null;\r
+                return dndBrowseContext.getAction(graph, target, data);\r
+            }\r
+        }, new Procedure<Runnable>() {\r
+            @Override\r
+            public void execute(Runnable result) {\r
+                if (result != null)\r
+                    result.run();\r
+            }\r
+\r
+            @Override\r
+            public void exception(Throwable t) {\r
+                ErrorLogger.defaultLogError(t);\r
+            }\r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisPropertyComposite.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisPropertyComposite.java
new file mode 100644 (file)
index 0000000..366c29b
--- /dev/null
@@ -0,0 +1,122 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.xyline;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.AxisHidePropertyComposite;\r
+import org.simantics.jfreechart.chart.properties.ColorPicker;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+\r
+/**\r
+ * Composite for displaying axis properties in {@link XYLineAxisAndVariablesTab}\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class AxisPropertyComposite extends Composite {\r
+\r
+    TrackedText name, units, min, max;\r
+    Button tlabels, tmarks;\r
+    \r
+    public AxisPropertyComposite(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
+       super(parent, style);\r
+       init(parent, context, support, style, false);\r
+    }\r
+\r
+       public AxisPropertyComposite(Composite parent, ISessionContext context, WidgetSupport support, int style, boolean vertical) {\r
+        super(parent, style);\r
+        init(parent, context, support, style, vertical);\r
+    }\r
+       \r
+       private void init(Composite parent, ISessionContext context, WidgetSupport support, int style, boolean vertical) {\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(vertical ? 2 : 3).applyTo(this);\r
+        \r
+        // Label (units)\r
+        Label label = new Label(this, SWT.NONE);\r
+        label.setText("Label: ");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        \r
+        units = new TrackedText(this, support, SWT.BORDER);\r
+        units.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, "")); // FIXME: Units \r
+        units.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel)); // FIXME: Units \r
+        units.setColorProvider(new JFreeChartPropertyColorProvider(units.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).span(vertical ? 1 : 2, 1).applyTo(units.getWidget());\r
+        \r
+        \r
+        // Minimum and maximum values\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Min:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        Composite minmax = new Composite(this, SWT.NONE);\r
+        GridDataFactory.fillDefaults().applyTo(minmax);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(minmax);\r
+        min = new TrackedText(minmax, support, SWT.BORDER);\r
+        min.setColorProvider(new JFreeChartPropertyColorProvider(min.getResourceManager()));\r
+        min.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Axis_min));\r
+        min.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Axis_min));\r
+        min.setInputValidator(new DoubleValidator(true));\r
+        GridDataFactory.fillDefaults().hint(55, SWT.DEFAULT).applyTo(min.getWidget());\r
+        \r
+        label = new Label(minmax, SWT.NONE);\r
+        label.setText("Max:");\r
+        max = new TrackedText(minmax, support, SWT.BORDER);\r
+        max.setColorProvider(new JFreeChartPropertyColorProvider(max.getResourceManager()));\r
+        max.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Axis_max));\r
+        max.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Axis_max));\r
+        max.setInputValidator(new DoubleValidator(true));\r
+        GridDataFactory.fillDefaults().hint(55, SWT.DEFAULT).applyTo(max.getWidget());\r
+        \r
+        Composite hideComposite = null;\r
+        if (!vertical) {\r
+                   // Tick and label visibility\r
+               hideComposite = new Composite(this, SWT.NONE);\r
+                   GridDataFactory.fillDefaults().span(1, 2).applyTo(hideComposite);\r
+               }\r
+           \r
+        // Color\r
+        label = new Label(this, SWT.NONE);\r
+        label.setText("Color:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        Composite colorPicker = new ColorPicker(this, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(colorPicker);\r
+        \r
+        if (vertical) {\r
+                   // Tick and label visibility\r
+               hideComposite = new Composite(this, SWT.NONE);\r
+                   GridDataFactory.fillDefaults().span(2, 1).applyTo(hideComposite);\r
+               }\r
+        \r
+        // Fill hideComposite\r
+        GridLayoutFactory.fillDefaults().applyTo(hideComposite);\r
+           Composite axisHide = new AxisHidePropertyComposite(hideComposite, context, support, SWT.NONE);\r
+           GridDataFactory.fillDefaults().applyTo(axisHide);\r
+    \r
+       }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/SeriesPropertyComposite.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/SeriesPropertyComposite.java
new file mode 100644 (file)
index 0000000..9557db7
--- /dev/null
@@ -0,0 +1,212 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.xyline;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Spinner;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.ColorPicker;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.RVIFactory;\r
+import org.simantics.jfreechart.chart.properties.RVIModifier;\r
+import org.simantics.jfreechart.chart.properties.RangeComposite;\r
+import org.simantics.jfreechart.chart.properties.TrackedSpinner;\r
+import org.simantics.jfreechart.chart.properties.VariableExistsValidator;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Composite for displaying series properties in {@link XYLineAxisAndVariablesTab}\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SeriesPropertyComposite extends Composite {\r
+     \r
+    \r
+    public SeriesPropertyComposite(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
+        super(parent, style);\r
+        createContent(context, support);\r
+    }\r
+    \r
+    protected void createContent(ISessionContext context, WidgetSupport support) {\r
+\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(this);\r
+\r
+        // Variable for the series\r
+        variable(this, context, support);\r
+\r
+        // Range\r
+        range(this, context, support);\r
+        \r
+        // Label to be displayed in chart for this series \r
+        seriesLabel(this, context, support);\r
+\r
+        // Color\r
+        color(this, context, support);\r
+\r
+        // Line width\r
+        lineWidth(this, support);\r
+\r
+    }\r
+    \r
+    protected TrackedText variable(Composite container, ISessionContext context, WidgetSupport support) {\r
+        Label label = new Label(container, SWT.NONE);\r
+        label.setText("Variable:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        TrackedText variable = new TrackedText(container, support, SWT.BORDER);\r
+        variable.setTextFactory(new RVIFactory());\r
+        variable.addModifyListener(new RVIModifier(variable.getWidget(), support));\r
+        variable.setColorProvider(new JFreeChartPropertyColorProvider(variable.getResourceManager()));\r
+        variable.setInputValidator(new VariableExistsValidator(support, variable));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(variable.getWidget());\r
+        return variable;\r
+    }\r
+    \r
+    protected RangeComposite range(Composite container, ISessionContext context, WidgetSupport support) {\r
+        Label label = new Label(container, SWT.NONE);\r
+        label.setText("Range:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        RangeComposite rangeComposite = new RangeComposite(container, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeComposite);\r
+        return rangeComposite;\r
+    }\r
+    \r
+    protected TrackedText seriesLabel(Composite container, ISessionContext context, WidgetSupport support) {\r
+        Label label = new Label(container, SWT.NONE);\r
+        label.setText("Label:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        TrackedText labelText = new TrackedText(container, support, SWT.BORDER);\r
+        labelText.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, ""));\r
+        labelText.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        labelText.setColorProvider(new JFreeChartPropertyColorProvider(labelText.getResourceManager()));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(labelText.getWidget());\r
+        return labelText;\r
+    }\r
+    \r
+    protected ColorPicker color(Composite container, ISessionContext context, WidgetSupport support) {\r
+        Label label = new Label(container, SWT.NONE);\r
+        label.setText("Color:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+\r
+        ColorPicker colorPicker = new ColorPicker(container, context, support, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(colorPicker);\r
+        return colorPicker;\r
+    }\r
+    \r
+    protected TrackedSpinner lineWidth(Composite container, WidgetSupport support) {\r
+        Label label = new Label(container, SWT.NONE);\r
+        label.setText("Line width:");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+\r
+        TrackedSpinner width = new TrackedSpinner(container, support, SWT.BORDER);\r
+        width.setSelectionFactory(new WidthSelectionFactory());\r
+        width.addModifyListener(new WidthModifyListener());\r
+        width.setMinimum(1);\r
+        width.setMaximum(10);\r
+        return width;\r
+    }\r
+\r
+\r
+    /**\r
+     * ModifyListener for the width {@link TrackedSpinner}\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class WidthModifyListener implements TextModifyListener, Widget {\r
+\r
+        private ISessionContext context;\r
+        private Object lastInput = null;\r
+\r
+        @Override\r
+        public void modifyText(TrackedModifyEvent e) {\r
+            if(context == null)\r
+                return;\r
+\r
+            // Get the text value from spinner and associated resource (input)\r
+            Spinner spinner = (Spinner)e.getWidget();\r
+            final String textValue = spinner.getText();\r
+            final Object input = lastInput;\r
+\r
+            try {\r
+                context.getSession().syncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        // Apply with (textValue) to the series (input)\r
+                        Resource series = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+                        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                        try {\r
+                            // usually reliable, since the spinner does all the checks\r
+                            Integer value = Integer.parseInt(textValue); \r
+                            graph.claimLiteral(series, jfree.Series_lineWidth, value, Bindings.INTEGER);\r
+                        } catch (NumberFormatException e) {\r
+                            e.printStackTrace();\r
+                        }\r
+                    }\r
+\r
+                });\r
+            } catch (DatabaseException e1) {\r
+                e1.printStackTrace();\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void setInput(ISessionContext context, Object parameter) {\r
+            this.context = context;\r
+            lastInput = parameter;\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Class for setting the value for width {@link TrackedSpinner}\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class WidthSelectionFactory extends ReadFactoryImpl<Resource, Integer>   {\r
+\r
+        @Override\r
+        public Integer perform(ReadGraph graph, Resource axis) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Integer width = graph.getPossibleRelatedValue(axis, jfree.Series_lineWidth);\r
+            if(width == null)\r
+                // Default width == 1\r
+                width = 1;\r
+            return width;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineAxisAndVariablesTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineAxisAndVariablesTab.java
new file mode 100644 (file)
index 0000000..98d7107
--- /dev/null
@@ -0,0 +1,329 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.xyline;\r
+\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * PropertyTab displaying properties of axis and variables of a chart\r
+ *  \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class XYLineAxisAndVariablesTab extends AdjustableTab {\r
+\r
+    private GraphExplorerComposite explorer;\r
+    private ScrolledComposite propertyContainer;\r
+    private Button addAxis, addVariable, remove;\r
+    private WidgetSupportImpl additionalSupport;\r
+       private Composite buttonComposite;\r
+\r
+    public XYLineAxisAndVariablesTab() {\r
+        additionalSupport = new WidgetSupportImpl();\r
+    }\r
+\r
+    /**\r
+     * Updates the content of propertyContainer  \r
+     * @param context\r
+     */\r
+    private void updateSelection(ISessionContext context) {\r
+        ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
+        IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
+        final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+\r
+        // Get the type of the selected node (axis or series)\r
+        String typeUri = null;\r
+        try {\r
+            typeUri = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                @Override\r
+                public String perform(ReadGraph graph) throws DatabaseException {\r
+                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                    if(graph.isInstanceOf(resource, jfree.Axis))\r
+                        return graph.getURI(jfree.Axis);\r
+                    else if (graph.isInstanceOf(resource, jfree.Series))\r
+                        return graph.getURI(jfree.Series);\r
+                    return null;\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        // Create a PropertyComposite for the selected node\r
+        if(typeUri != null) {\r
+\r
+            for(Control child : propertyContainer.getChildren()) {\r
+                child.dispose();\r
+            }\r
+\r
+            if(typeUri.equals(JFreeChartResource.URIs.Axis)) {\r
+                AxisPropertyComposite apc = new AxisPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE, isVertical());\r
+                propertyContainer.setContent(apc);\r
+                Point size = apc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+                propertyContainer.setMinSize(size);\r
+            } else if(typeUri.equals(JFreeChartResource.URIs.Series)) {\r
+                SeriesPropertyComposite spc = new SeriesPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE);\r
+                propertyContainer.setContent(spc);\r
+                Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+                propertyContainer.setMinSize(size);\r
+            }\r
+        }\r
+\r
+        additionalSupport.fireInput(context, selection);\r
+    }\r
+\r
+    /**\r
+     * SelectionListener for adding a new range axis to a plot\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class NewAxisListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public NewAxisListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource chart) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));\r
+            if(plot != null) {\r
+                Resource rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);\r
+                if(rangeAxis != null) {\r
+                    Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
+                    ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * SelectionListener for adding a new variable to a plot\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class NewVariableListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public NewVariableListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            NodeContext nc = explorer.getExplorer().getRoot();\r
+            if(nc == null)\r
+                return;\r
+            \r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            \r
+            if(input == null) {\r
+                Resource chart = AdaptionUtils.adaptToSingle(nc, Resource.class);\r
+                if(chart == null) return;\r
+                Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));\r
+                if(plot == null) return;\r
+                Resource rangelist = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
+                if(rangelist == null) return;\r
+                List<Resource> list = ListUtils.toList(graph, rangelist);\r
+                if(list == null || list.isEmpty()) return;\r
+                input = list.get(0);\r
+            }\r
+            \r
+            Resource dataset;\r
+            if(graph.isInstanceOf(input, jfree.Series)) {\r
+                // Selected resource is series. Add to same dataset\r
+                dataset = graph.getPossibleObject(input, l0.PartOf);\r
+            } else {\r
+                // Selected resource is axis. Find the dataset it is mapped to or create dataset if not created already\r
+                dataset = graph.getPossibleObject(input, jfree.Dataset_mapToRangeAxis_Inverse);\r
+                if(dataset == null) {\r
+                    Resource plot = graph.getPossibleObject(input, l0.PartOf);\r
+                    if(plot == null) return;\r
+                    Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
+                    if(domainAxis == null) return;\r
+                    ChartUtils.createXYDataset(graph, plot, domainAxis, input);\r
+                }\r
+            }\r
+\r
+            if(dataset != null) {\r
+                // Create series with no rvi\r
+                ChartUtils.createSeries(graph, dataset, null);\r
+            }\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * SelectionListener for remove button\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class RemoveListener extends SelectionListenerImpl<Resource> {\r
+\r
+        public RemoveListener(ISessionContext context) {\r
+            super(context);\r
+        }\r
+\r
+        /**\r
+         * Removes selected resource from explorer\r
+         */\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+            if(input == null)\r
+                return; \r
+\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            Resource list = null;\r
+            if(graph.isInstanceOf(input, jfree.Series)) {\r
+                // Remove series from dataset and seriesList\r
+                Resource dataset = graph.getPossibleObject(input, l0.PartOf);\r
+                if(dataset != null)\r
+                    list = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+            } else {\r
+                // Remove associated dataset\r
+                Resource dataset = graph.getPossibleObject(input, jfree.Dataset_mapToRangeAxis_Inverse);\r
+                if(dataset != null) {\r
+                    graph.deny(dataset, jfree.Dataset_mapToDomainAxis);\r
+                    graph.deny(dataset, jfree.Dataset_mapToRangeAxis);\r
+                    RemoverUtil.remove(graph, dataset);\r
+                }\r
+\r
+                // Remove axis from plot and rangeAxisList\r
+                Resource plot = graph.getPossibleObject(input, l0.PartOf);\r
+                if(plot != null)\r
+                    list = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
+            }\r
+            if(list != null)\r
+                ListUtils.removeElement(graph, list, input);\r
+            RemoverUtil.remove(graph, input);\r
+        }\r
+    }\r
+\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       final ISessionContext context, WidgetSupport support) {\r
+               composite = new Composite(body, SWT.NONE);\r
+\r
+        // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis\r
+        explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
+        explorer.setBrowseContexts(JFreeChartResource.URIs.ChartAxisAndVariablesBrowseContext);\r
+        explorer.setInputSource(new SingleSelectionInputSource(\r
+                Resource.class));\r
+        explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
+        explorer.finish();\r
+\r
+        ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
+            public void widgetSelected(SelectionEvent e) {\r
+                updateSelection(context);\r
+            }\r
+        });\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
+        propertyContainer.setExpandHorizontal(true);\r
+        propertyContainer.setExpandVertical(true);\r
+\r
+        // Buttons for adding axis and variables and removing selected items from explorer\r
+        buttonComposite = new Composite(composite, SWT.NONE);\r
+\r
+        addAxis = new Button(buttonComposite, support, SWT.NONE);\r
+        addAxis.setText("Add axis");\r
+        addAxis.addSelectionListener(new NewAxisListener(context));\r
+\r
+        addVariable = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        addVariable.setText("Add variable");\r
+        addVariable.addSelectionListener(new NewVariableListener(context));\r
+\r
+        remove = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
+        remove.setText("Remove");\r
+        remove.addSelectionListener(new RemoveListener(context));\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().hint(220, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 210).span(1, 1).grab(true, false).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+\r
+        // Buttons for adding axis and variables and removing selected items from explorer\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, SWT.DEFAULT).span(1, 2).grab(true, true).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+\r
+        // Buttons for adding axis and variables and removing selected items from explorer\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineGeneralPropertiesTab.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineGeneralPropertiesTab.java
new file mode 100644 (file)
index 0000000..81581d1
--- /dev/null
@@ -0,0 +1,452 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.jfreechart.chart.properties.xyline;\r
+\r
+import java.util.Collection;\r
+import java.util.LinkedHashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.jfreechart.chart.properties.AxisHidePropertyComposite;\r
+import org.simantics.jfreechart.chart.properties.BooleanPropertyFactory;\r
+import org.simantics.jfreechart.chart.properties.BooleanSelectionListener;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.jfreechart.chart.properties.JFreeChartPropertyColorProvider;\r
+import org.simantics.jfreechart.chart.properties.RVIFactory;\r
+import org.simantics.jfreechart.chart.properties.RVIModifier;\r
+import org.simantics.jfreechart.chart.properties.TitleFactory;\r
+import org.simantics.jfreechart.chart.properties.TitleModifier;\r
+import org.simantics.jfreechart.chart.properties.VariableExistsValidator;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyFactory;\r
+import org.simantics.modeling.ui.chart.property.DoublePropertyModifier;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * PropertyTab displaying general properties and x-axis properties of a chart\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class XYLineGeneralPropertiesTab extends AdjustableTab implements Widget {\r
+\r
+    private ScrolledComposite sc;\r
+    private TrackedText name, title, xlabel, xvariable, xmin, xmax;\r
+    private TrackedCombo type;\r
+    private Button hgrid, htitle, hlegend;\r
+    private WidgetSupportImpl domainAxisSupport = new WidgetSupportImpl();\r
+       private Group general;\r
+       private Label nameLabel;\r
+       private Label labelTitle;\r
+       private Label labelType;\r
+       private Group hideGroup;\r
+       private Group xgroup;\r
+       private Label xVariableLabel;\r
+       private Label labelMin;\r
+       private AxisHidePropertyComposite axisHide;\r
+       private Label labelLabel;\r
+       private Label labelMax;\r
+       private Composite xColumn1;\r
+       private Composite xColumn2;\r
+\r
+    @Override\r
+    public void setInput(final ISessionContext context, Object input) {\r
+        final Resource chart = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        if(chart == null)\r
+            return; \r
+\r
+        context.getSession().asyncRequest(new ReadRequest() {\r
+\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));\r
+                if(plot == null) return;\r
+                final Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
+                if(domainAxis == null) return;\r
+                Display.getDefault().asyncExec(new Runnable() {\r
+                                       @Override\r
+                                       public void run() {\r
+                                               domainAxisSupport.fireInput(context, new StructuredSelection(domainAxis));\r
+                                       }\r
+                               });\r
+                \r
+            }\r
+        });\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class TypeSelectionFactory extends ReadFactoryImpl<Resource, String> {\r
+        @Override\r
+        public String perform(ReadGraph graph, Resource chart) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.XYPlot));\r
+            if(plot != null) {\r
+                Collection<Resource> datasets = graph.syncRequest(new ObjectsWithType(plot, l0.ConsistsOf, jfree.XYDataset));\r
+                if(!datasets.isEmpty()) {\r
+                    Resource dataset = datasets.iterator().next();\r
+                    if(dataset != null) {\r
+                        Resource renderer = graph.syncRequest(new PossibleObjectWithType(dataset, jfree.Dataset_renderer, jfree.Renderer));\r
+                        if(renderer != null && graph.isInstanceOf(renderer, jfree.XYAreaRenderer))\r
+                            return "Area";\r
+                    }\r
+                }\r
+            }\r
+            return "Line";\r
+        }\r
+    }\r
+\r
+    /**\r
+     * RangeItemFactory finds all inexes of a given enumeration \r
+     * and adds "Sum" and "All" to the returned indexes\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class TypeItemFactory extends ReadFactoryImpl<Resource, Map<String, Object>> {\r
+        @Override\r
+        public Map<String, Object> perform(ReadGraph graph, Resource series) throws DatabaseException {\r
+            LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();\r
+            result.put("Line", "Line");\r
+            result.put("Area", "Area");\r
+//            result.put("Stacked Area", "Stacked Area");\r
+            return result;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * TypeModifyListener for modifying the type of a bar chart \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class TypeModifyListener  extends ComboModifyListenerImpl<Resource> {\r
+        @Override\r
+        public void applyText(WriteGraph graph, Resource chart, String text) throws DatabaseException {\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.XYPlot));\r
+            if(plot == null)\r
+                return;\r
+\r
+            Collection<Resource> datasets = graph.syncRequest(new ObjectsWithType(plot, l0.ConsistsOf, jfree.XYDataset));\r
+            if(datasets == null || datasets.isEmpty())\r
+                return;\r
+\r
+            for(Resource dataset : datasets) {\r
+                graph.deny(dataset, jfree.Dataset_renderer);\r
+\r
+                Resource renderer;\r
+                if(text.equals("Area"))\r
+                    renderer = GraphUtils.create2(graph, jfree.XYAreaRenderer);\r
+                else\r
+                    renderer = GraphUtils.create2(graph, jfree.XYLineRenderer);\r
+\r
+                graph.claim(dataset, jfree.Dataset_renderer, renderer);\r
+            }\r
+        }\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               support.register(this);\r
+\r
+        // Scrolled composite containing all of the properties in this tab\r
+        sc = new ScrolledComposite(body, SWT.NONE | SWT.H_SCROLL | SWT.V_SCROLL);\r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);\r
+\r
+        composite = new Composite(sc, SWT.NONE);\r
+\r
+        // General properties\r
+        general = new Group(composite, SWT.NONE);\r
+        general.setText("General");\r
+\r
+        // Name\r
+        nameLabel = new Label(general, SWT.NONE);\r
+        nameLabel.setText("Name:");\r
+        nameLabel.setAlignment(SWT.RIGHT);\r
+\r
+        name = new org.simantics.browsing.ui.swt.widgets.TrackedText(general, support, SWT.BORDER);\r
+        name.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));\r
+        name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        name.setColorProvider(new JFreeChartPropertyColorProvider(name.getResourceManager()));\r
+\r
+        // Type\r
+        labelType = new Label(general, SWT.NONE);\r
+        labelType.setText("Type:");\r
+\r
+        type = new TrackedCombo(general, support, SWT.BORDER | SWT.READ_ONLY);\r
+        type.addModifyListener(new TypeModifyListener());\r
+        type.setItemFactory(new TypeItemFactory());\r
+        type.setSelectionFactory(new TypeSelectionFactory());\r
+\r
+        // Title (Which is different than name)\r
+        labelTitle = new Label(general, SWT.NONE);\r
+        labelTitle.setText("Title:");\r
+\r
+        title = new org.simantics.browsing.ui.swt.widgets.TrackedText(general, support, SWT.BORDER);\r
+        title.setTextFactory(new TitleFactory());\r
+        title.addModifyListener(new TitleModifier());\r
+        title.setColorProvider(new JFreeChartPropertyColorProvider(name.getResourceManager()));\r
+\r
+        // Group for hide options\r
+        hideGroup = new Group(composite, SWT.NONE);\r
+        hideGroup.setText("Hide");\r
+\r
+        hgrid = new Button(hideGroup, support, SWT.CHECK);\r
+        hgrid.setText("Grid");\r
+        hgrid.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Plot_visibleGrid, true));\r
+        hgrid.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.Plot, JFreeChartResource.URIs.Plot_visibleGrid,true));\r
+        htitle = new Button(hideGroup, support, SWT.CHECK);\r
+        htitle.setText("Title");\r
+        htitle.setSelectionFactory(new BooleanPropertyFactory(JFreeChartResource.URIs.TextTitle, JFreeChartResource.URIs.visible, true));\r
+        htitle.addSelectionListener(new BooleanSelectionListener(context, JFreeChartResource.URIs.TextTitle, JFreeChartResource.URIs.visible,true));\r
+        hlegend = new Button(hideGroup, support, SWT.CHECK);\r
+        hlegend.setText("Legend");\r
+        hlegend.setSelectionFactory(new BooleanPropertyFactory(null, JFreeChartResource.URIs.Chart_visibleLegend, true));\r
+        hlegend.addSelectionListener(new BooleanSelectionListener(context, null, JFreeChartResource.URIs.Chart_visibleLegend,true));\r
+\r
+\r
+        // X-Axis properties\r
+        xgroup = new Group(composite, SWT.NONE);\r
+        xgroup.setText("X-axis");\r
+\r
+        xColumn1 = new Composite(xgroup, SWT.NONE);\r
+        \r
+        // Variable for x-axis (default: empty == time)\r
+        xVariableLabel = new Label(xColumn1, SWT.NONE);\r
+        xVariableLabel.setText("Variable:");\r
+        \r
+        xvariable = new TrackedText(xColumn1, domainAxisSupport, SWT.BORDER);\r
+        xvariable.setTextFactory(new RVIFactory());\r
+        xvariable.addModifyListener(new RVIModifier(xvariable.getWidget(), domainAxisSupport));\r
+        xvariable.setColorProvider(new JFreeChartPropertyColorProvider(xvariable.getResourceManager()));\r
+        xvariable.setInputValidator(new VariableExistsValidator(support, xvariable, true));\r
+        \r
+        // Label for x-axis\r
+        labelLabel = new Label(xColumn1, SWT.NONE);\r
+        labelLabel.setText("Label:");\r
+        \r
+        xlabel = new TrackedText(xColumn1, domainAxisSupport, SWT.BORDER);\r
+        xlabel.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel, ""));\r
+        xlabel.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        xlabel.setColorProvider(new JFreeChartPropertyColorProvider(xlabel.getResourceManager()));\r
+\r
+        xColumn2 = new Composite(xgroup, SWT.NONE);\r
+        \r
+        // Min value for x-axis\r
+        labelMin = new Label(xColumn2, SWT.NONE);\r
+        labelMin.setText("Min:");\r
+        labelMin.setAlignment(SWT.RIGHT);\r
+\r
+        xmin = new TrackedText(xColumn2, domainAxisSupport, SWT.BORDER);\r
+        xmin.setColorProvider(new JFreeChartPropertyColorProvider(xmin.getResourceManager()));\r
+        xmin.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Axis_min));\r
+        xmin.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Axis_min));\r
+        xmin.setInputValidator(new DoubleValidator(true));\r
+        \r
+        // Max value for x-axis\r
+        labelMax = new Label(xColumn2, SWT.NONE);\r
+        labelMax.setText("Max:");\r
+        \r
+        xmax = new TrackedText(xColumn2, domainAxisSupport, SWT.BORDER);\r
+        xmax.setColorProvider(new JFreeChartPropertyColorProvider(xmax.getResourceManager()));\r
+        xmax.setTextFactory(new DoublePropertyFactory(JFreeChartResource.URIs.Axis_max));\r
+        xmax.addModifyListener(new DoublePropertyModifier(context, JFreeChartResource.URIs.Axis_max));\r
+        xmax.setInputValidator(new DoubleValidator(true));\r
+        \r
+        // Axis hide buttons\r
+        axisHide = new AxisHidePropertyComposite(composite, context, domainAxisSupport, SWT.NONE);\r
+\r
+        sc.setContent(composite);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+\r
+        GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+\r
+        // General properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(general);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(general);\r
+\r
+        // Name\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(nameLabel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
+\r
+        // Type\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelType);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(type.getWidget());\r
+\r
+        // Title (Which is different than name)\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelTitle);\r
+\r
+        GridDataFactory.fillDefaults().span(1, 1).grab(true, false).applyTo(title.getWidget());\r
+\r
+        // Group for hide options\r
+        GridDataFactory.fillDefaults().applyTo(hideGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(hideGroup);\r
+\r
+        // X-Axis properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(xgroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(xgroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(xColumn1);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(xColumn1);\r
+        \r
+        // Variable for x-axis (default: empty == time)\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(xVariableLabel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(xvariable.getWidget());\r
+        \r
+        // Label for x-axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelLabel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(xlabel.getWidget());\r
+\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(xColumn2);\r
+\r
+        // Min value for x-axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelMin);\r
+        GridDataFactory.fillDefaults().applyTo(xmin.getWidget());\r
+        \r
+        // Max value for x-axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelMax);\r
+        GridDataFactory.fillDefaults().applyTo(xmax.getWidget());\r
+        \r
+        // Axis hide buttons\r
+        GridDataFactory.fillDefaults().applyTo(axisHide);\r
+\r
+        // Set the same width to both label rows\r
+        composite.layout();\r
+        GridDataFactory.fillDefaults().hint(xVariableLabel.getBounds().width, SWT.DEFAULT).align(SWT.END, SWT.CENTER).applyTo(nameLabel);\r
+        GridDataFactory.fillDefaults().hint(xVariableLabel.getBounds().width, SWT.DEFAULT).align(SWT.END, SWT.CENTER).applyTo(labelMin);\r
+        \r
+        Point size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        sc.setMinSize(size);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+               // Scrolled composite containing all of the properties in this tab\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        // General properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(general);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(4).applyTo(general);\r
+\r
+        // Name\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(nameLabel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
+\r
+        // Type\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelType);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(type.getWidget());\r
+\r
+        // Title (Which is different than name)\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelTitle);\r
+\r
+        GridDataFactory.fillDefaults().span(3, 1).grab(true, false).applyTo(title.getWidget());\r
+\r
+        // Group for hide options\r
+        GridDataFactory.fillDefaults().applyTo(hideGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(hideGroup);\r
+\r
+        // X-Axis properties\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(xgroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(xgroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(xColumn1);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(xColumn1);\r
+        \r
+        // Variable for x-axis (default: empty == time)\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(xVariableLabel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(xvariable.getWidget());\r
+        \r
+        // Label for x-axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelLabel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(xlabel.getWidget());\r
+\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(xColumn2);\r
+\r
+        // Min value for x-axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelMin);\r
+        GridDataFactory.fillDefaults().applyTo(xmin.getWidget());\r
+        \r
+        // Max value for x-axis\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelMax);\r
+        GridDataFactory.fillDefaults().applyTo(xmax.getWidget());\r
+        \r
+        // Axis hide buttons\r
+        GridDataFactory.fillDefaults().applyTo(axisHide);\r
+\r
+        // Set the same width to both label rows\r
+        composite.layout();\r
+        GridDataFactory.fillDefaults().hint(xVariableLabel.getBounds().width, SWT.DEFAULT).align(SWT.END, SWT.CENTER).applyTo(nameLabel);\r
+       \r
+        Point size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        sc.setMinSize(size);\r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/internal/Activator.java b/1.8/org.simantics.jfreechart/src/org/simantics/jfreechart/internal/Activator.java
new file mode 100644 (file)
index 0000000..97597b7
--- /dev/null
@@ -0,0 +1,50 @@
+package org.simantics.jfreechart.internal;\r
+\r
+import org.eclipse.ui.plugin.AbstractUIPlugin;\r
+import org.osgi.framework.BundleContext;\r
+\r
+/**\r
+ * The activator class controls the plug-in life cycle\r
+ */\r
+public class Activator extends AbstractUIPlugin {\r
+\r
+       // The plug-in ID\r
+       public static final String PLUGIN_ID = "org.simantics.jfreechart"; //$NON-NLS-1$\r
+\r
+       // The shared instance\r
+       private static Activator plugin;\r
+       \r
+       /**\r
+        * The constructor\r
+        */\r
+       public Activator() {\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)\r
+        */\r
+       public void start(BundleContext context) throws Exception {\r
+               super.start(context);\r
+               plugin = this;\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)\r
+        */\r
+       public void stop(BundleContext context) throws Exception {\r
+               plugin = null;\r
+               super.stop(context);\r
+       }\r
+\r
+       /**\r
+        * Returns the shared instance\r
+        *\r
+        * @return the shared instance\r
+        */\r
+       public static Activator getDefault() {\r
+               return plugin;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.modelica/.classpath b/1.8/org.simantics.modelica/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.modelica/.project b/1.8/org.simantics.modelica/.project
new file mode 100644 (file)
index 0000000..2d4d7aa
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.modelica</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.modelica/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.modelica/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..f25d3a6
--- /dev/null
@@ -0,0 +1,8 @@
+#Tue Jan 26 16:43:56 EET 2010\r
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.modelica/META-INF/MANIFEST.MF b/1.8/org.simantics.modelica/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..48ba713
--- /dev/null
@@ -0,0 +1,18 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Modelica
+Bundle-SymbolicName: org.simantics.modelica;singleton:=true
+Bundle-Version: 1.1.0.qualifier
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: gnu.trove2;bundle-version="2.0.4",
+ org.eclipse.osgi;bundle-version="3.6.0",
+ org.eclipse.core.runtime;bundle-version="3.6.0",
+ org.simantics.utils;bundle-version="1.1.0",
+ org.simantics.utils.datastructures;bundle-version="1.1.0"
+Export-Package: org.simantics.modelica,
+ org.simantics.modelica.data,
+ org.simantics.modelica.preferences,
+ org.simantics.modelica.reader
+Bundle-Activator: org.simantics.modelica.Activator
+Bundle-ActivationPolicy: lazy
+Bundle-Vendor: VTT Technical Research Centre of Finland
diff --git a/1.8/org.simantics.modelica/build.properties b/1.8/org.simantics.modelica/build.properties
new file mode 100644 (file)
index 0000000..11ab1db
--- /dev/null
@@ -0,0 +1,16 @@
+###############################################################################\r
+# Copyright (c) 2010 Association for Decentralized Information Management in\r
+# Industry THTH ry.\r
+# All rights reserved. This program and the accompanying materials\r
+# are made available under the terms of the Eclipse Public License v1.0\r
+# which accompanies this distribution, and is available at\r
+# http://www.eclipse.org/legal/epl-v10.html\r
+#\r
+# Contributors:\r
+#     VTT Technical Research Centre of Finland - initial API and implementation\r
+###############################################################################\r
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               plugin.xml\r
diff --git a/1.8/org.simantics.modelica/plugin.xml b/1.8/org.simantics.modelica/plugin.xml
new file mode 100644 (file)
index 0000000..1e19229
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<?eclipse version="3.4"?>\r
+<plugin>\r
+   <extension\r
+         point="org.eclipse.core.runtime.preferences">\r
+      <initializer\r
+            class="org.simantics.modelica.preferences.ModelicaPreferenceInitializer">\r
+      </initializer>\r
+   </extension>\r
+\r
+\r
+</plugin>\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/Activator.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/Activator.java
new file mode 100644 (file)
index 0000000..bcbb8d5
--- /dev/null
@@ -0,0 +1,37 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica;\r
+\r
+import org.osgi.framework.BundleActivator;\r
+import org.osgi.framework.BundleContext;\r
+\r
+public class Activator implements BundleActivator {\r
+\r
+    public static final String PLUGIN_ID = "org.simantics.modelica";\r
+\r
+    static BundleContext context;\r
+       \r
+       @Override\r
+       public void start(BundleContext context) throws Exception {\r
+               Activator.context = context;\r
+       }\r
+\r
+       @Override\r
+       public void stop(BundleContext context) throws Exception {\r
+               Activator.context = null;\r
+       }\r
\r
+       public static BundleContext getContext() {\r
+               return context;\r
+       }
+       \r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/IModelicaMonitor.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/IModelicaMonitor.java
new file mode 100644 (file)
index 0000000..56e6ccc
--- /dev/null
@@ -0,0 +1,18 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica;\r
+\r
+public interface IModelicaMonitor {\r
+    public void message(String message);\r
+    public void clearConsole();\r
+    public void showConsole();\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/InitWriter.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/InitWriter.java
new file mode 100644 (file)
index 0000000..e7dee74
--- /dev/null
@@ -0,0 +1,180 @@
+package org.simantics.modelica;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.PrintStream;\r
+import java.util.HashMap;\r
+\r
+import javax.xml.parsers.DocumentBuilderFactory;\r
+import javax.xml.parsers.ParserConfigurationException;\r
+import javax.xml.transform.Transformer;\r
+import javax.xml.transform.TransformerConfigurationException;\r
+import javax.xml.transform.TransformerException;\r
+import javax.xml.transform.TransformerFactory;\r
+import javax.xml.transform.TransformerFactoryConfigurationError;\r
+import javax.xml.transform.dom.DOMSource;\r
+import javax.xml.transform.stream.StreamResult;\r
+import javax.xml.xpath.XPath;\r
+import javax.xml.xpath.XPathConstants;\r
+import javax.xml.xpath.XPathExpressionException;\r
+import javax.xml.xpath.XPathFactory;\r
+\r
+import org.w3c.dom.Document;\r
+import org.w3c.dom.Node;\r
+import org.w3c.dom.NodeList;\r
+import org.xml.sax.InputSource;\r
+import org.xml.sax.SAXException;\r
+\r
+/**\r
+ * Class to change values of parameters in modelica init.xml files\r
+ * \r
+ * @author tlteemu\r
+ */\r
+public class InitWriter {\r
+\r
+    /**\r
+     * Change the given init parameter values for XML init file\r
+     * @param file path to the init.xml file\r
+     * @param inits name-value map\r
+     * @return\r
+     */\r
+    public static boolean writeXML(String file, HashMap<String, String> inits) {\r
+        Document doc;\r
+        try {\r
+            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(file));\r
+\r
+            // Locate the node(s)\r
+            XPath xpath = XPathFactory.newInstance().newXPath();\r
+\r
+            for(String name : inits.keySet()) {\r
+                NodeList nodes = null;\r
+                try {\r
+                    // First try normal variables\r
+                    nodes = (NodeList)xpath.evaluate\r
+                            ("//fmiModelDescription/ModelVariables/ScalarVariable[@name='" + name + "']/Real/@start",\r
+                                    doc, \r
+                                    XPathConstants.NODESET);\r
+                    if(nodes.getLength() == 0) {\r
+                        // If normal variables were not found, try if it is an experiment attribute\r
+                        nodes = (NodeList)xpath.evaluate\r
+                                ("//fmiModelDescription/DefaultExperiment/@" + name,\r
+                                        doc, \r
+                                        XPathConstants.NODESET);\r
+                    }\r
+                } catch (XPathExpressionException e) {\r
+\r
+                }\r
+                if (nodes != null) {\r
+                    // make the change. There should be only one node.\r
+                    for (int idx = 0; idx < nodes.getLength(); idx++) {\r
+                        Node n = nodes.item(idx);\r
+                        n.setNodeValue(inits.get(name).replaceAll("\"", ""));\r
+                    }\r
+                }\r
+            }\r
+\r
+            // Save the result\r
+            Transformer xformer = TransformerFactory.newInstance().newTransformer();\r
+            xformer.transform\r
+            (new DOMSource(doc), new StreamResult(new File(file)));\r
+\r
+            return true;\r
+        } catch (SAXException e) {\r
+            e.printStackTrace();\r
+        } catch (IOException e) {\r
+            e.printStackTrace();\r
+        } catch (ParserConfigurationException e) {\r
+            e.printStackTrace();\r
+        } catch (TransformerConfigurationException e) {\r
+            e.printStackTrace();\r
+        } catch (TransformerFactoryConfigurationError e) {\r
+            e.printStackTrace();\r
+        } catch (TransformerException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        return false;\r
+\r
+    }\r
+\r
+    /**\r
+     * Change the given init parameter values for TXT init file\r
+     * @param file path to the init.xml file\r
+     * @param inits name-value map\r
+     * @return\r
+     */\r
+    public static boolean writeTXT(String file, HashMap<String, String> inits) {\r
+        HashMap<String, String> initials = new HashMap<String, String>();\r
+        HashMap<Integer, String> order = new HashMap<Integer, String>();\r
+\r
+        InputStream is;\r
+        try {\r
+            is = new FileInputStream(file);\r
+            int orderNumber = 0;\r
+            while(true) {\r
+                String line = getLine(is);\r
+                if(line == null)\r
+                    return false;\r
+                if(line.isEmpty())\r
+                    break;\r
+                if(line.contains("//")) {\r
+                    String[] nn = line.split("//", 2);\r
+                    String key = nn[1].trim();\r
+                    String value = nn[0].trim();\r
+                    if(inits.containsKey(key)) {\r
+                        value = inits.get(key);\r
+                    }\r
+                    initials.put(key, value);\r
+                    order.put(orderNumber, key);\r
+                }\r
+                orderNumber++;\r
+            }\r
+            is.close();\r
+\r
+            PrintStream s = new PrintStream(file);\r
+            for(int j = 0; j < orderNumber ; j++) {\r
+                String key = order.get(j);\r
+                if (key != null) {\r
+                    s.println(initials.get(key) + " // " + key);\r
+                } else {\r
+                    s.println("0.0");\r
+                }\r
+            }\r
+            s.close();\r
+\r
+            return true;\r
+        } catch (FileNotFoundException e) {\r
+            e.printStackTrace();\r
+        } catch (IOException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    private static String getLine(InputStream stream) {\r
+        if(stream == null)\r
+            return null;\r
+        StringBuilder b = new StringBuilder();\r
+        try {\r
+            while(true) {\r
+                int c = stream.read();\r
+                if(c == -1) {\r
+                    stream = null;\r
+                    return b.toString();\r
+                }\r
+                else if(c == '\n') \r
+                    return b.toString();\r
+                else if(c == '\r')\r
+                    ;\r
+                else\r
+                    b.append((char)c);\r
+            }\r
+        } catch (IOException e) {\r
+            return null;\r
+        }           \r
+\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaException.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaException.java
new file mode 100644 (file)
index 0000000..32c99c9
--- /dev/null
@@ -0,0 +1,22 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica;\r
+\r
+public class ModelicaException extends Exception {\r
+\r
+       private static final long serialVersionUID = 2712433918044442927L;\r
+       \r
+       public ModelicaException(String message) {\r
+               super(message);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaKeys.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaKeys.java
new file mode 100644 (file)
index 0000000..d867fe8
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica;\r
+\r
+/**\r
+ * Keys used by modelica to control simulations\r
+ * \r
+ * @author Teemu Lempinen\r
+ */\r
+public class ModelicaKeys {\r
+\r
+    public static String START_VALUE         = "startTime";\r
+    public static String STOP_VALUE          = "stopTime";\r
+    public static String OUTPUT_FORMAT       = "outputFormat";\r
+    public static String STEP_VALUE          = "stepSize";\r
+    public static String NUMBER_OF_INTERVALS = "numberOfIntervals";\r
+    public static String METHOD              = "method";\r
+    public static String TOLERANCE           = "tolerance";\r
+    public static String VARIABLE_FILTER     = "variableFilter";\r
+    public static String OUTPUT_INTERVAL     = "outputInterval";\r
+    \r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaManager.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/ModelicaManager.java
new file mode 100644 (file)
index 0000000..ae40d66
--- /dev/null
@@ -0,0 +1,817 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.BufferedWriter;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileWriter;\r
+import java.io.FilenameFilter;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.InputStreamReader;\r
+import java.io.PrintStream;\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import javax.xml.parsers.DocumentBuilderFactory;\r
+import javax.xml.parsers.ParserConfigurationException;\r
+import javax.xml.transform.Transformer;\r
+import javax.xml.transform.TransformerConfigurationException;\r
+import javax.xml.transform.TransformerException;\r
+import javax.xml.transform.TransformerFactory;\r
+import javax.xml.transform.TransformerFactoryConfigurationError;\r
+import javax.xml.transform.dom.DOMSource;\r
+import javax.xml.transform.stream.StreamResult;\r
+import javax.xml.xpath.XPath;\r
+import javax.xml.xpath.XPathConstants;\r
+import javax.xml.xpath.XPathExpressionException;\r
+import javax.xml.xpath.XPathFactory;\r
+\r
+import org.eclipse.core.runtime.FileLocator;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.preferences.ConfigurationScope;\r
+import org.osgi.framework.Bundle;\r
+import org.osgi.service.prefs.Preferences;\r
+import org.simantics.modelica.preferences.OpenModelicaPreferences;\r
+import org.w3c.dom.Document;\r
+import org.w3c.dom.Node;\r
+import org.xml.sax.InputSource;\r
+import org.xml.sax.SAXException;\r
+\r
+/**\r
+ * Manager for OpenModelica compiler\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Janne Kauttio\r
+ */\r
+public class ModelicaManager {\r
+\r
+       private static final String OM_BUILTIN = "OpenModelica1.9.0";\r
+\r
+       public enum OSType {\r
+               APPLE, LINUX, SUN, WINDOWS, UNKNOWN\r
+       }\r
+\r
+       public static final String OMC_VERSION = "OMC_VERSION"; \r
+       public static final String RESULT_FILE_NAME = "RESULT_FILE_NAME"; \r
+\r
+       /**\r
+        * Get operating system type\r
+        * \r
+        * @return OSType\r
+        */\r
+       private static OSType getOSType() {\r
+               String osName = System.getProperty("os.name").toLowerCase();\r
+               \r
+               if (osName.startsWith("mac os x"))\r
+                       return OSType.APPLE;\r
+               else if (osName.startsWith("linux"))\r
+                       return OSType.LINUX;\r
+               else if (osName.startsWith("sun"))\r
+                       return OSType.SUN;\r
+               else if (osName.startsWith("windows"))\r
+                       return OSType.WINDOWS;\r
+               \r
+               return OSType.UNKNOWN;\r
+       }\r
+       \r
+       private static boolean onWindows() {\r
+               return System.getProperty("os.name").toLowerCase().startsWith("windows");\r
+       }\r
+       \r
+       private static File getOMCBinary(File home) {\r
+               return new File(home, "bin" + File.separator + "omc" + (onWindows() ? ".exe" : ""));\r
+       }\r
+       \r
+       private static Process runWithEnvironment(File homeDir, File workDir, File executable, String... parameters) {\r
+               // construct the command\r
+               List<String> command = new ArrayList<String>();\r
+               command.add(executable.getAbsolutePath());\r
+               // this should iterate through the parameters in order\r
+               for (String parameter : parameters) {\r
+                       command.add(parameter);\r
+               }\r
+               \r
+               // create the process\r
+               ProcessBuilder builder = new ProcessBuilder(command);\r
+               builder.redirectErrorStream(true);\r
+               builder.directory(workDir);\r
+               \r
+               // set the environment\r
+               Map<String, String> env = builder.environment();\r
+               env.put("OPENMODELICAHOME", homeDir.getAbsolutePath());\r
+               \r
+               // TODO: these are probably not needed as most of the files do not exist\r
+               File lib = new File(homeDir, "lib");\r
+               File omlib = new File(lib, "omlibrary");\r
+               env.put("OPENMODELICALIBRARY", omlib.getAbsolutePath());\r
+               File bin = new File(homeDir, "bin");\r
+               env.put("OMPATH", bin.getAbsolutePath());\r
+               File mingw = new File(homeDir, "MinGW");\r
+               env.put("MINGW", mingw.getAbsolutePath());\r
+               \r
+               File mbin = new File(mingw, "bin");\r
+               File mlib = new File(mingw, "lib");\r
+               String path_allcaps = env.get("PATH") == null ? "" : env.get("PATH") + File.pathSeparator;\r
+               env.put("PATH", path_allcaps + bin.getAbsolutePath()\r
+                                + File.pathSeparator + mbin.getAbsolutePath()\r
+                    + File.pathSeparator + mlib.getAbsolutePath());\r
+               String path = env.get("Path") == null ? "" : env.get("Path") + File.pathSeparator;\r
+               env.put("Path", path + bin.getAbsolutePath()\r
+                                + File.pathSeparator + mbin.getAbsolutePath()\r
+                    + File.pathSeparator + mlib.getAbsolutePath());\r
+\r
+               env.put("MODELICAUSERCFLAGS", "-O0");\r
+               \r
+               // run the process\r
+               Process process = null;\r
+               try {\r
+                       process = builder.start();\r
+               }\r
+               catch (Exception e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+               return process;\r
+       }\r
+       \r
+       private static Process runOMC(File homeDir, File workDir, String... parameters) {\r
+               return runWithEnvironment(homeDir, workDir, getOMCBinary(homeDir), parameters);\r
+       }\r
+       \r
+       public static String getOMVersion(File home) {\r
+               return getProcessOutput(runOMC(home, home, "++v"));\r
+       }\r
+       \r
+       public static String getDefaultOMVersion() {\r
+               return getOMVersion(getOMHome());\r
+       }\r
+       \r
+       public static boolean isOldOMVersion() {\r
+               try {\r
+                       double version = Double.parseDouble(getOMVersion(getOMHome()).substring(0, 3));\r
+                       return version < 1.9;\r
+               }\r
+               catch (NumberFormatException e) {\r
+                       // if the version string could not be parsed, assume that the \r
+                       // version sufficiently new\r
+                       return false;\r
+               }\r
+       }\r
+       \r
+       /**\r
+        * Get Open Modelica home directory.\r
+        * \r
+        * @return Open Modelica home directory\r
+        */\r
+       public static File getOMHome() {\r
+               Preferences node = ConfigurationScope.INSTANCE.getNode(Activator.PLUGIN_ID);\r
+               String omHomePath = node.get(OpenModelicaPreferences.OM_HOME, null);\r
+               if (omHomePath != null) {\r
+                       File omHome = new File(omHomePath);\r
+                       if (omHome.isDirectory())\r
+                               return omHome;\r
+               }\r
+               \r
+               return getDefaultOMHome();\r
+       }\r
+       \r
+       public static File getDefaultOMHome() {\r
+               if (onWindows()) {\r
+                       File builtin = getBuiltinOMHome();\r
+                       if (builtin != null)\r
+                               return builtin;\r
+               }\r
+\r
+               File installed = getInstalledOMHome();\r
+               if (installed != null)\r
+                       return installed;\r
+               \r
+               // TODO: what is the correct error to throw?\r
+               throw new Error("OpenModelica could not be found");\r
+       }\r
+\r
+       public static File getInstalledOMHome() {\r
+               String omHomePath = System.getenv("OPENMODELICAHOME");\r
+               if (omHomePath != null) {\r
+                       File omHome = new File(omHomePath);\r
+                       if (omHome.isDirectory())\r
+                               return omHome;\r
+               }\r
+               return null;\r
+       }\r
+\r
+       public static File getBuiltinOMHome() {\r
+               Bundle bundle = Platform.getBundle("org.simantics.openmodelica.win32");\r
+               if (bundle != null) {\r
+                       try {\r
+                               File omHome = new File(FileLocator.getBundleFile(bundle), OM_BUILTIN);\r
+                               if (omHome.isDirectory())\r
+                                       return omHome;\r
+                       }\r
+                       catch (Exception e) {\r
+                               e.printStackTrace();\r
+                       }\r
+               }\r
+               return null;\r
+       }\r
+       \r
+       /**\r
+        * Gets the whole process output in one string\r
+        * \r
+        * @param process Process\r
+        * @return process output\r
+        */\r
+       public static String getProcessOutput(final Process process) {\r
+               try {\r
+                       BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));\r
+                       StringBuilder output = new StringBuilder();\r
+                       String line;\r
+                       boolean first = true;\r
+                       while ((line = input.readLine()) != null) {\r
+                               if(!first)\r
+                                       output.append(System.getProperty("line.separator"));\r
+                               first = false;\r
+                               output.append(line);\r
+                       }\r
+                       input.close();\r
+                       return output.toString();\r
+               } catch (Exception e) {\r
+                       e.printStackTrace();\r
+                       return null;\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Prints the output of an ongoing process to IModelicaMonitor.\r
+        * \r
+        * @param process Process\r
+        * @param monitor IModelicaMonitor\r
+        */\r
+       // TODO: clean up\r
+       public static void printProcessOutput(final Process process, final IModelicaMonitor monitor) {\r
+               Thread thread = new Thread() {\r
+                       @Override\r
+                       public void run() {\r
+                               InputStream stream = process.getInputStream();\r
+                               StringBuilder b = new StringBuilder();\r
+                               while(true) {\r
+                                       try {\r
+                                               int c;\r
+\r
+                                               c = stream.read();\r
+\r
+                                               if(c <= 0)\r
+                                                       break;\r
+                                               if(monitor != null) {\r
+                                                       if((char)c != '\n')\r
+                                                               b.append((char)c);\r
+                                                       else {\r
+                                                               System.out.println("OMC output: " + b.toString());\r
+                                                               String message = b.toString();\r
+                                                               message = message.trim();\r
+                                                               if(message.startsWith("\""))\r
+                                                                       message = message.substring(1);\r
+\r
+                                                               monitor.message(message);\r
+                                                               b.delete(0, b.length());\r
+                                                       }\r
+                                               }\r
+                                       } catch (IOException e) {\r
+                                               e.printStackTrace();\r
+                                               break;\r
+                                       }\r
+                               }\r
+                       }\r
+               };\r
+               \r
+               thread.run();\r
+       }\r
+\r
+       public static SimulationLocation createSimulationLocation(File modelDir, String modelName, String modelContent, File omHome, boolean isOldOMVersion) {          \r
+               if (!modelDir.isDirectory()) {\r
+                       return null;\r
+               }\r
+               \r
+               // there might be a better way to remove whitespace from the string \r
+               // but this apparently works fine in this context\r
+               modelName = modelName.replace(" ", "");\r
+               \r
+               SimulationLocation location = new SimulationLocation(modelDir, modelName);\r
+               \r
+               location.modelFile = location.getFileInLocation(".mo");\r
+               location.modelScriptFile = location.getFileInLocation(".mos");\r
+               \r
+               try {\r
+                       FileWriter writer = new FileWriter(location.modelFile);\r
+                       writer.write(modelContent);\r
+                       writer.close();\r
+               }\r
+               catch (IOException e) {\r
+                       e.printStackTrace();\r
+                       return null;\r
+               }\r
+               \r
+               // full model files are (apparently) only needed for old parameter comparison routines\r
+               if (isOldOMVersion) {\r
+                       location.fullModelDir = new File(location.getModelDir(), "fullModel");\r
+                       if (!location.fullModelDir.isDirectory()) {\r
+                               location.fullModelDir.mkdir();\r
+                       }\r
+                       location.fullModelFile = new File(location.fullModelDir, location.getModelName() + "_full.mo");\r
+                       location.fullModelScriptFile = new File(location.fullModelDir, location.getModelName() + "_full.mos");\r
+               }\r
+               \r
+               location.omHome = omHome;\r
+               \r
+               return location;\r
+       }\r
+       \r
+       public static void createSimulationScripts(SimulationLocation location, HashMap<String, String> parameters, String additionalScript) \r
+                       throws FileNotFoundException {\r
+               writeScriptFile(location, parameters, additionalScript);\r
+               \r
+               location.executableFile = location.getFileInLocation(onWindows() ? ".exe" : "");\r
+               location.initFile = location.getFileInLocation("_init.xml");\r
+               location.resultFile = location.getFileInLocation("_res." + parameters.get(ModelicaKeys.OUTPUT_FORMAT));\r
+               \r
+               if (isOldOMVersion()) {\r
+                       writeFullModelScriptFile(location, additionalScript);\r
+               }\r
+       }\r
+       \r
+       public static void createFMUSimulationScripts(SimulationLocation location, HashMap<String, String> parameters, String additionalScript) \r
+                       throws FileNotFoundException {\r
+               writeFMUScriptFile(location, additionalScript);\r
+               \r
+               location.executableFile = location.getFileInLocation(".fmu");\r
+               location.initFile = location.getFileInLocation("_init.xml");\r
+               location.resultFile = location.getFileInLocation("_res." + parameters.get(ModelicaKeys.OUTPUT_FORMAT));\r
+               \r
+               if (isOldOMVersion()) {\r
+                       writeFullModelScriptFile(location, additionalScript);\r
+               }\r
+       }\r
+       \r
+       /**\r
+        * \r
+        * @param location\r
+        * @param parameters\r
+        * @param additionalScript\r
+        * @throws FileNotFoundException\r
+        */\r
+       private static void writeScriptFile(SimulationLocation location, HashMap<String, String> parameters, String additionalScript) \r
+                       throws FileNotFoundException {\r
+               PrintStream s = new PrintStream(location.modelScriptFile);\r
+               s.println("loadFile(\"" + location.modelFile.getName() + "\");");\r
+               if(additionalScript != null)\r
+                       s.println(additionalScript);\r
+               s.print("buildModel(" + location.getModelName());\r
+               s.print(",startTime=" + parameters.get(ModelicaKeys.START_VALUE));\r
+               s.print(",stopTime=" + parameters.get(ModelicaKeys.STOP_VALUE));\r
+               s.print(",method=" + parameters.get(ModelicaKeys.METHOD));\r
+               s.print(",outputFormat=\"" + parameters.get(ModelicaKeys.OUTPUT_FORMAT) + "\"");\r
+               s.print(",cflags=\"-O0\""); // disable c-compiler optimization => faster compilation\r
+               if(parameters.containsKey(ModelicaKeys.TOLERANCE)) {\r
+                       s.print(",tolerance=" + parameters.get(ModelicaKeys.TOLERANCE));\r
+               }\r
+               if(parameters.containsKey(ModelicaKeys.NUMBER_OF_INTERVALS)) {\r
+                       s.print(",numberOfIntervals=" + parameters.get(ModelicaKeys.NUMBER_OF_INTERVALS));\r
+               }\r
+               if(parameters.containsKey(ModelicaKeys.VARIABLE_FILTER)) {\r
+                       s.print(",variableFilter=\"" + parameters.get(ModelicaKeys.VARIABLE_FILTER) + "\"");\r
+               }\r
+               s.print(");\n");\r
+               s.println("getErrorString();");\r
+               s.close();\r
+       }\r
+       \r
+       /**\r
+        * \r
+        * @param location\r
+        * @param additionalScript\r
+        * @throws FileNotFoundException\r
+        */\r
+       private static void writeFMUScriptFile(SimulationLocation location, String additionalScript) \r
+                       throws FileNotFoundException {\r
+               PrintStream s = new PrintStream(location.modelScriptFile);\r
+               s.println("loadFile(\"" + location.modelFile.getName() + "\");");\r
+               if(additionalScript != null)\r
+                       s.println(additionalScript);\r
+               s.println("translateModelFMU(" + location.getModelName() + ");");\r
+               s.println("getErrorString();");\r
+               s.close();\r
+       }\r
+\r
+       /**\r
+        * \r
+        * @param location\r
+        * @param additionalScript\r
+        * @throws FileNotFoundException\r
+        */\r
+       // TODO: try this\r
+       private static void writeFullModelScriptFile(SimulationLocation location, String additionalScript) \r
+                       throws FileNotFoundException {\r
+               PrintStream s = new PrintStream(location.fullModelScriptFile);\r
+               s.println("loadFile(\"" + location.modelFile.getName() + "\");");\r
+               if(additionalScript != null)\r
+                       s.println(additionalScript);\r
+               s.print("saveTotalSCode(");\r
+               s.print("\"" + location.fullModelDir.getName() + "/" + location.fullModelFile.getName() + "\"");\r
+               s.print(", ");\r
+               s.print(location.getModelName());\r
+               s.print(");\n");\r
+               s.println("getErrorString();");\r
+               s.close();\r
+       }\r
+\r
+       public static void buildFullModel(SimulationLocation location, IModelicaMonitor monitor) \r
+                       throws ModelicaException {\r
+               Process process = runOMC(location.omHome, location.getModelDir(), location.fullModelScriptFile.getAbsolutePath());\r
+               printProcessOutput(process, monitor);\r
+               \r
+               try {\r
+                       process.waitFor();\r
+               }\r
+               catch (InterruptedException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+               trimExtraFromFullModel(location);\r
+       }\r
+       \r
+       private static void trimExtraFromFullModel(SimulationLocation location) {\r
+               try {\r
+                       FileInputStream fs = new FileInputStream(location.fullModelFile);\r
+                       InputStreamReader in = new InputStreamReader(fs);\r
+                       BufferedReader br = new BufferedReader(in);\r
+                       StringBuffer sb = new StringBuffer();\r
+\r
+                       String textinLine;\r
+                       boolean openmodelicaflag = false;\r
+                       int breakpoint = 0;\r
+                       while((textinLine = br.readLine()) != null) {\r
+                               if(openmodelicaflag == true) {\r
+                                       breakpoint = sb.length();\r
+                                       openmodelicaflag = false;\r
+                               }\r
+\r
+                               if(textinLine.contains("end OpenModelica;"))\r
+                                       openmodelicaflag = true;\r
+\r
+                               sb.append(textinLine + "\n"); // if you don\92t put the \n you will have all the code on one line as fer said\r
+                       }\r
+\r
+                       br.close();\r
+                       in.close();\r
+                       fs.close();\r
+\r
+                       FileWriter fstream = new FileWriter(location.fullModelFile);\r
+                       BufferedWriter outobj = new BufferedWriter(fstream);\r
+                       outobj.write(sb.substring(breakpoint));\r
+                       outobj.close();\r
+                       fstream.close();\r
+               } catch (IOException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+       \r
+       /**\r
+        * Builds a model with omc. The location of required files is \r
+        * defined in simulationLocation.\r
+        *  \r
+        * @param location Location of model files\r
+        * @param monitor Monitor for printing build process output\r
+        * @throws ModelicaException\r
+        */\r
+       public static void buildModel(SimulationLocation location, IModelicaMonitor monitor) \r
+                       throws ModelicaException {\r
+               \r
+               Process process = runOMC(location.omHome, location.getModelDir(), location.modelScriptFile.getAbsolutePath());\r
+               printProcessOutput(process, monitor);\r
+               \r
+               try {\r
+                       process.waitFor();\r
+               }\r
+               catch (InterruptedException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+               if (!location.executableFile.isFile()) {\r
+                       // If executable file was not created, something went wrong\r
+                       throw new ModelicaException("executable file not created");\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Runs a model that has been built to simulationLocation. \r
+        * Some initial values can be set for a compiled model without \r
+        * re-compiling it.\r
+        * \r
+        * @param location Location of a built model  \r
+        * @param monitor Monitor for printing process output\r
+        * @param inits Initial values for a simulation run\r
+        * @param structureChanged \r
+        * @return Simulation process\r
+        * @throws IOException\r
+        */\r
+       public static Process runModelica(SimulationLocation location, IModelicaMonitor monitor, HashMap<String, String> experimentParameters, HashMap<String, String> parameterChanges) throws IOException {\r
+               ArrayList<String> commands = new ArrayList<String>();\r
+               try {\r
+                       if(experimentParameters.get(RESULT_FILE_NAME) != null) {\r
+                               commands.add("-r="+experimentParameters.get(RESULT_FILE_NAME));\r
+                       }\r
+\r
+                       // Write new initial values (parameters). No need to update xml if structure has changed. In that case also xml is up-to-date\r
+                       if(parameterChanges != null) {\r
+                               String version = experimentParameters.get(OMC_VERSION);\r
+                               // TODO: clean up\r
+                               if(version == null)\r
+                                       version = getOMVersion(location.omHome);\r
+\r
+                               Double versionNumber = 1.9;\r
+                               try {\r
+                                       versionNumber = Double.parseDouble(version.substring(0,3));\r
+                               } catch (NumberFormatException e) {}\r
+\r
+                               if(versionNumber < 1.9) {\r
+                                       writeInits(location, experimentParameters, null);\r
+                               } else {\r
+                                       // Handled in experiment\r
+                                       if(parameterChanges.size() == 1) {\r
+                                               commands.add("-override");\r
+                                               commands.add(parameterChanges.keySet().iterator().next() + "=" + parameterChanges.values().iterator().next());\r
+                                       } else {\r
+                                               // FIXME: if you change 1 parameter AND some experiment parameters, only the parameter change takes effect\r
+                                               updateInitFile(location, experimentParameters, parameterChanges);\r
+                                       }\r
+                               }\r
+\r
+                       }\r
+                       \r
+               }\r
+               catch (Exception e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+               // Commands to String[]\r
+               String[] commandString = new String[commands.size()];\r
+               for (int i = 0; i < commands.size(); ++i)\r
+                        commandString[i] = commands.get(i);\r
+               \r
+               return runWithEnvironment(location.omHome, location.getModelDir(), location.executableFile, commandString);\r
+       }\r
+\r
+       public static String getFlatModelText(SimulationLocation location, IModelicaMonitor monitor, List<String> additional) {\r
+               String[] command = new String[additional.size()+1];\r
+               command[0] = location.modelFile.getAbsolutePath();\r
+               for (int i = 0; i < additional.size(); i++) {\r
+                       command[i+1] = additional.get(i);\r
+               }\r
+               return getProcessOutput(runOMC(location.omHome, location.getModelDir(), command));\r
+       }\r
+\r
+\r
+       /**\r
+        *  Get all parameter variables and their values from model. \r
+        *  \r
+        * @param model model text\r
+        * @return a map containing all parameters and values\r
+        */\r
+       public static HashMap<String, String> getModelParameters(String model) {\r
+               HashMap<String, String> result = new HashMap<String, String>();\r
+               \r
+               try {\r
+                       BufferedReader in = new BufferedReader(new StringReader(model));\r
+                       \r
+                       String line;\r
+                       String name;\r
+                       String value;\r
+                       \r
+                       while ((line = in.readLine()) != null) {\r
+                               line = line.trim();\r
+                               if (line.startsWith("parameter") && line.contains("=") && line.contains(";")) {\r
+                                       String[] split = line.split(" = ");\r
+                                       name = split[0].trim();\r
+                                       name = name.substring(name.lastIndexOf(" ") + 1);\r
+                                       value = split[1].trim();\r
+                                       value = value.substring(0, value.indexOf(";"));\r
+                                       result.put(name, value);\r
+                               }\r
+                       }\r
+                       \r
+                       in.close();     \r
+               } catch (IOException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+               return result;\r
+       }\r
+\r
+\r
+       /**\r
+        * Updates inits.xml with the latest values. This is not needed if the model structure\r
+        * has changed. When model structure is changed, the model is compiled and a new xml is \r
+        * created.\r
+        * \r
+        * Works with version 1.8.1 and previous versions. 1.9 version does not support this, since\r
+        * the init.xml file format has been changed. With 1.9, use updateInitFile()\r
+        * \r
+        * @param simulationLocation Location of the model\r
+        * @param monitor \r
+        */\r
+       private static void writeInits(SimulationLocation simulationLocation, HashMap<String, String> experimentParameters, IModelicaMonitor monitor) {\r
+\r
+               try {\r
+                       // Create the full model code into one file\r
+                       buildFullModel(simulationLocation, null);\r
+\r
+                       // Create simulation files from the full description\r
+                       ArrayList<String> parameters = new ArrayList<String>();\r
+                       parameters.add("+s");\r
+                       parameters.add(simulationLocation.fullModelFile.getAbsolutePath());\r
+\r
+                       Process process = runOMC(simulationLocation.omHome, simulationLocation.fullModelDir, "+s", simulationLocation.fullModelFile.getAbsolutePath());\r
+\r
+                       process.waitFor();\r
+\r
+                       // Find the new init file\r
+                       FilenameFilter initFilter = new FilenameFilter() {\r
+                               @Override\r
+                               public boolean accept(File dir, String name) {\r
+                                       if(name.endsWith("_init.xml"))\r
+                                               return true;\r
+                                       else\r
+                                               return false;\r
+                               }\r
+                       };\r
+\r
+                       File initFile = null;\r
+                       for(File f : simulationLocation.fullModelDir.listFiles(initFilter)) {\r
+                               initFile = f;\r
+                               break;\r
+                       }\r
+\r
+                       if(initFile != null && initFile.isFile()) {\r
+                               // Replace original init contents with the new contents\r
+                               replaceInitFileContents(simulationLocation.initFile.getAbsolutePath(), initFile.getAbsolutePath(), experimentParameters);\r
+                       }\r
+\r
+               } catch (ModelicaException e) {\r
+                       e.printStackTrace();\r
+               } catch (InterruptedException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Replaces variable and experiment information from oldFile with contents of newFile.\r
+        * \r
+        * The file is not simply replaced because guid must match with guid in created exe.\r
+        * \r
+        * @param oldFile old init.xml\r
+        * @param newFile new init.xml\r
+        */\r
+       private static void replaceInitFileContents(String oldFile, String newFile, HashMap<String, String> experimentParameters) {\r
+               try {\r
+                       XPath xpath = XPathFactory.newInstance().newXPath();\r
+\r
+                       Document oldInit = DocumentBuilderFactory.newInstance()\r
+                                       .newDocumentBuilder().parse(new InputSource(oldFile));\r
+                       Document newInit = DocumentBuilderFactory.newInstance()\r
+                                       .newDocumentBuilder().parse(new InputSource(newFile));\r
+\r
+                       // Find the original model description. This will be modified\r
+                       Node oldModelDescription = (Node)xpath.evaluate("fmiModelDescription", oldInit, XPathConstants.NODE);\r
+\r
+                       //\r
+                       // VARIABLES\r
+                       //\r
+                       // First, remove old model variables\r
+                       Node oldModelVariables = (Node)xpath.evaluate("fmiModelDescription/ModelVariables", oldInit, XPathConstants.NODE);\r
+                       \r
+                       oldModelDescription.removeChild(oldModelVariables);\r
+\r
+                       // Second, find variables in the new model description\r
+                       Node newModelVariables = (Node)xpath.evaluate("fmiModelDescription/ModelVariables", newInit, XPathConstants.NODE);\r
+\r
+                       // Import new variables to old xml\r
+                       Node importedModelVariables = oldInit.importNode(newModelVariables, true);\r
+                       oldModelDescription.appendChild(importedModelVariables);\r
+\r
+                       //\r
+                       // EXPERIMENT PARAMETERS\r
+                       //\r
+                       for(String key : experimentParameters.keySet()) {\r
+                               // Find parameter\r
+                               Node parameter = (Node)xpath.evaluate\r
+                                               ("fmiModelDescription/DefaultExperiment/@" + key,\r
+                                                               oldInit, \r
+                                                               XPathConstants.NODE);\r
+\r
+                               if(parameter != null) {\r
+                                       // Change parameter value\r
+                                       parameter.setNodeValue(experimentParameters.get(key));\r
+                               }\r
+                       }\r
+\r
+                       // Write transformed init.xml\r
+                       Transformer xformer = TransformerFactory.newInstance().newTransformer();\r
+                       xformer.transform(new DOMSource(oldInit), new StreamResult(new File(oldFile)));\r
+\r
+               } catch (SAXException e) {\r
+                       e.printStackTrace();\r
+               } catch (IOException e) {\r
+                       e.printStackTrace();\r
+               } catch (ParserConfigurationException e) {\r
+                       e.printStackTrace();\r
+               } catch (XPathExpressionException e) {\r
+                       e.printStackTrace();\r
+               } catch (TransformerConfigurationException e) {\r
+                       e.printStackTrace();\r
+               } catch (TransformerFactoryConfigurationError e) {\r
+                       e.printStackTrace();\r
+               } catch (TransformerException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Updates init file contents with the given experiment and variable changes.\r
+        * \r
+        * @param simulationLocation Location of simulation files\r
+        * @param experimentParameters Experiment parameters\r
+        * @param changes Parameter variable changes\r
+        */\r
+       public static void updateInitFile(SimulationLocation simulationLocation, HashMap<String, String> experimentParameters, HashMap<String, String> changes) {\r
+               try {\r
+                       XPath xpath = XPathFactory.newInstance().newXPath();\r
+\r
+                       Document init = DocumentBuilderFactory.newInstance()\r
+                                       .newDocumentBuilder().parse(simulationLocation.initFile);\r
+\r
+                       //\r
+                       // EXPERIMENT PARAMETERS\r
+                       //\r
+                       for(String key : experimentParameters.keySet()) {\r
+                               // Find parameter\r
+                               Node parameter = (Node)xpath.evaluate\r
+                                               ("fmiModelDescription/DefaultExperiment/@" + key,\r
+                                                               init, \r
+                                                               XPathConstants.NODE);\r
+\r
+                               if(parameter != null) {\r
+                                       // Change parameter value\r
+                                       parameter.setNodeValue(experimentParameters.get(key));\r
+                               }\r
+                       }\r
+\r
+                       //\r
+                       // PARAMETER VARIABLES\r
+                       //\r
+                       for(String name : changes.keySet()) {\r
+                               Node node = (Node)xpath.evaluate\r
+                                               ("//fmiModelDescription/ModelVariables/ScalarVariable[@name='" + name + "']/Real/@start",\r
+                                                               init, \r
+                                                               XPathConstants.NODE);\r
+                               if(node != null) {\r
+                                       node.setNodeValue(changes.get(name));\r
+                               }\r
+                       } \r
+\r
+                       // Write transformed init.xml\r
+                       Transformer xformer = TransformerFactory.newInstance().newTransformer();\r
+                       xformer.transform(new DOMSource(init), new StreamResult(simulationLocation.initFile));\r
+\r
+               } catch (SAXException e) {\r
+                       e.printStackTrace();\r
+               } catch (IOException e) {\r
+                       e.printStackTrace();\r
+               } catch (ParserConfigurationException e) {\r
+                       e.printStackTrace();\r
+               } catch (XPathExpressionException e) {\r
+                       e.printStackTrace();\r
+               } catch (TransformerConfigurationException e) {\r
+                       e.printStackTrace();\r
+               } catch (TransformerFactoryConfigurationError e) {\r
+                       e.printStackTrace();\r
+               } catch (TransformerException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/SimulationLocation.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/SimulationLocation.java
new file mode 100644 (file)
index 0000000..70aa6f8
--- /dev/null
@@ -0,0 +1,108 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica;\r
+\r
+import java.io.File;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ * @author Janne Kauttio\r
+ */\r
+public class SimulationLocation {\r
+\r
+       private String modelName;\r
+       \r
+       public File modelDir;\r
+       public File modelFile;\r
+       public File modelScriptFile;\r
+       public File fullModelDir;\r
+       public File fullModelFile;\r
+       public File fullModelScriptFile;\r
+       public File initFile;\r
+       public File executableFile;\r
+       public File resultFile;\r
+       public File omHome;\r
+       \r
+       public SimulationLocation(File modelDir, String modelName) {\r
+               this.modelDir = modelDir;\r
+               this.modelName = modelName;\r
+       }\r
+       \r
+       public File getModelDir() {\r
+               return modelDir;\r
+       }\r
+       \r
+       public String getModelName() {\r
+               return modelName;\r
+       }\r
+       \r
+       public File getFileInLocation(String name, String affix) {\r
+               return new File(modelDir, name + affix);\r
+       }\r
+       \r
+       public File getFileInLocation(String affix) {\r
+               return getFileInLocation(modelName, affix);\r
+       }\r
+       \r
+       public SimulationLocation(File modelDir, File modelFile, File modelScriptFile,\r
+                       File resultFile, File initFile, File executableFile, File omHome) {\r
+               this.modelDir = modelDir;\r
+               this.modelFile = modelFile;\r
+               this.modelScriptFile = modelScriptFile;\r
+               this.fullModelDir = null;\r
+               this.fullModelFile = null;\r
+               this.fullModelScriptFile = null;\r
+               this.resultFile = resultFile;\r
+               this.initFile = initFile;\r
+               this.executableFile = executableFile;\r
+               this.omHome = omHome;\r
+       }\r
+       \r
+       public SimulationLocation(File modelDir, File model, File modelScriptFile,\r
+                       File fullModelDir, File fullModelFile, File fullModelScriptFile,\r
+                       File resultFile, File initFile, File executableFile, File omHome) {\r
+               this.modelDir = modelDir;\r
+               this.modelFile = model;\r
+               this.modelScriptFile = modelScriptFile;\r
+               this.fullModelDir = fullModelDir;\r
+               this.fullModelFile = fullModelFile;\r
+               this.fullModelScriptFile = fullModelScriptFile;\r
+               this.resultFile = resultFile;\r
+               this.initFile = initFile;\r
+               this.executableFile = executableFile;\r
+               this.omHome = omHome;\r
+       }\r
+\r
+       // TODO: remove this later\r
+//     public SimulationLocation(File modelDir, File modelScriptFile, File fullModelDir, File fullModelScriptFile,\r
+//                     File resultFile, File initFile, File executableFile) {\r
+//             this.modelDir = modelDir;\r
+//             this.modelScriptFile = modelScriptFile;\r
+//             this.fullModelDir = fullModelDir;\r
+//             this.fullModelScriptFile = fullModelScriptFile;\r
+//             this.resultFile = resultFile;\r
+//             this.initFile = initFile;\r
+//             this.executableFile = executableFile;\r
+//             this.fullModel = new File(getFullModelPath());\r
+//             this.omc = ModelicaManager.getOpenModelicaHome();\r
+//     }\r
+       \r
+       private String getFullModelPath() {\r
+               if(fullModelScriptFile == null)\r
+                       return null;\r
+\r
+               String fullScriptPath = fullModelScriptFile.getAbsolutePath();\r
+               return fullScriptPath.substring(0, fullScriptPath.length()-1); // ..._full.mos -> ..._full.mo\r
+       }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/CSVSimulationResult.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/CSVSimulationResult.java
new file mode 100644 (file)
index 0000000..8787adf
--- /dev/null
@@ -0,0 +1,77 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.data;\r
+\r
+import java.io.InputStream;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+/**\r
+ * class for supporting csv-format simulation results\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class CSVSimulationResult extends SimulationResult {\r
+\r
+       HashMap<String, DataSet> valueMap = new HashMap<String, DataSet>();\r
+       \r
+       /**\r
+        * Overridden method to support csv-formatted simulation results\r
+        */\r
+       @Override\r
+    public void read(InputStream stream, int outputInterval) {\r
+               errors.clear();\r
+               \r
+               // First line contains the variable names in format "name" (including quotes);\r
+               String line = getLine(stream);\r
+               if(line == null)\r
+                       return;\r
+               \r
+               line = line.substring(1, line.lastIndexOf("\""));\r
+               String[] names = line.split("\",\"");\r
+               \r
+               // Create lists for receiving values for each variable. Names still with quotes.\r
+               for(String name : names) {\r
+                       if(!name.isEmpty())\r
+                               valueMap.put(name, new DataSet(name, new double[numberOfLines], new double[numberOfLines]));\r
+               }\r
+\r
+               int row = 0;\r
+        // Data sets\r
+               while((line = getLine(stream)) != null) {      \r
+            if(line.isEmpty())\r
+                break;\r
+                       String[] values = line.split(",");\r
+                       for(int valueIndex = 0; valueIndex <values.length; valueIndex++) {\r
+                               if(values[valueIndex] != null && !values[valueIndex].isEmpty() && valueIndex < names.length) {\r
+                                       try {\r
+                                               valueMap.get(names[valueIndex]).values[row] = Double.parseDouble(values[valueIndex]);\r
+                                       } catch (NumberFormatException e) {\r
+                                               ArrayList<TimeValuePair> list = errors.get(names[valueIndex]);\r
+                                               if(list == null) {\r
+                                                       list = new ArrayList<TimeValuePair>();\r
+                                                       errors.put(names[valueIndex], list);\r
+                                               }\r
+                                               list.add(new TimeValuePair(values[0], values[valueIndex]));\r
+                                       }\r
+                               }\r
+                       }\r
+                       row++;\r
+               }\r
+        \r
+        // Add time values for each dataset and add them to variables. \r
+        for(DataSet ds : valueMap.values()) {\r
+            ds.times = valueMap.get("time").values;\r
+               variables.add(ds);\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/DataSet.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/DataSet.java
new file mode 100644 (file)
index 0000000..c1c4bae
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.data;\r
+\r
+/**\r
+ * Simulation result for one variable.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class DataSet {\r
+    public String name;\r
+    public double[] times;\r
+    public double[] values;\r
+    \r
+    public DataSet(String name, double[] times, double[] values) {\r
+        this.name = name;\r
+        this.times = times;\r
+        this.values = values;\r
+    }     \r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/DoubleMatrix.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/DoubleMatrix.java
new file mode 100644 (file)
index 0000000..d8ace79
--- /dev/null
@@ -0,0 +1,38 @@
+package org.simantics.modelica.data;\r
+\r
+/**\r
+ * Copied from Hannu's DoubleMatrix in org.simantics.modelica.data\r
+ * \r
+ * To be replaced with the original when SysDyn and Modelica tools \r
+ * are synchronized to use the same OpenModelica plugin\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class DoubleMatrix extends Matrix {\r
+    public final int rows;\r
+    public final int columns;\r
+    public final double[] data;\r
+\r
+    public DoubleMatrix(String name, int rows, int columns) {\r
+        super(name);\r
+        this.rows = rows;\r
+        this.columns = columns;\r
+        this.data = new double[rows*columns];\r
+    }\r
+\r
+    @Override\r
+    public String toString() {\r
+        StringBuilder b = new StringBuilder();\r
+        b.append("double " + name + "(" + rows + "," + columns + ")\n");\r
+        for(int i=0;i<columns;++i) {\r
+            for(int j=0;j<rows;++j) {\r
+                if(j > 0)\r
+                    b.append(' ');\r
+                b.append(data[i*rows + j]);                            \r
+            }\r
+            b.append('\n');\r
+        }\r
+        return b.toString();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/IntMatrix.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/IntMatrix.java
new file mode 100644 (file)
index 0000000..6f3d6d4
--- /dev/null
@@ -0,0 +1,49 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.data;\r
+\r
+/**\r
+ * Copied from Hannu's IntMatrix in org.simantics.modelica.data\r
+ * \r
+ * To be replaced with the original when SysDyn and Modelica tools \r
+ * are synchronized to use the same OpenModelica plugin\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class IntMatrix extends Matrix {\r
+    public final int rows;\r
+    public final int columns;\r
+    public final int[] data;\r
+\r
+    public IntMatrix(String name, int rows, int columns) {\r
+        super(name);\r
+        this.rows = rows;\r
+        this.columns = columns;\r
+        this.data = new int[rows*columns];\r
+    }\r
+\r
+    @Override\r
+    public String toString() {\r
+        StringBuilder b = new StringBuilder();\r
+        b.append("int " + name + "(" + rows + "," + columns + ")\n");\r
+        for(int i=0;i<columns;++i) {\r
+            for(int j=0;j<rows;++j) {\r
+                if(j > 0)\r
+                    b.append(' ');\r
+                b.append(data[i*rows + j]);                            \r
+            }\r
+            b.append('\n');\r
+        }\r
+        return b.toString();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/Mat4Reader.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/Mat4Reader.java
new file mode 100644 (file)
index 0000000..635fc77
--- /dev/null
@@ -0,0 +1,163 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.data;\r
+\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+/**\r
+ * Copied from Hannu's Mat4Reader in org.simantics.modelica.data\r
+ * \r
+ * To be replaced with the original when SysDyn and Modelica tools \r
+ * are synchronized to use the same OpenModelica plugin\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class Mat4Reader {\r
+\r
+    InputStream in;\r
+\r
+    public Mat4Reader(InputStream in) {\r
+        this.in = in;\r
+    }\r
+\r
+    private final int getInt() throws IOException {\r
+        int ch1 = in.read();\r
+        int ch2 = in.read();\r
+        int ch3 = in.read();\r
+        int ch4 = in.read();\r
+        return ((ch1 << 0) + (ch2 << 8) + (ch3 << 16) + (ch4 << 24));\r
+    }\r
+\r
+    private final long getLong() throws IOException {\r
+        int ch1 = in.read();\r
+        int ch2 = in.read();\r
+        int ch3 = in.read();\r
+        int ch4 = in.read();\r
+        int ch5 = in.read();\r
+        int ch6 = in.read();\r
+        int ch7 = in.read();\r
+        int ch8 = in.read();\r
+        return ((((long)ch1) << 0) + (((long)ch2) << 8) + (((long)ch3) << 16) + (((long)ch4) << 24) +\r
+                (((long)ch5) << 32) + (((long)ch6) << 40) + (((long)ch7) << 48) + (((long)ch8) << 56));\r
+    }\r
+\r
+    private final double getDouble() throws IOException {\r
+        return Double.longBitsToDouble(getLong());\r
+    }\r
+\r
+    private String getString(int length) throws IOException {\r
+        byte[] buffer = new byte[length];\r
+        int pos = 0;\r
+        while(pos < length)\r
+            pos += in.read(buffer, pos, length-pos);\r
+        return new String(buffer, "UTF-8");\r
+    }\r
+\r
+    public Matrix readMatrix() throws IOException {\r
+        int type = getInt();\r
+        int rows = getInt();\r
+        int columns = getInt();\r
+        int imagf = getInt();\r
+        int namlen = getInt();\r
+\r
+        String name = getString(namlen-1);\r
+        in.read();\r
+\r
+        if(imagf > 0)\r
+            throw new IOException("Imaginary part of the matrix is not supported (matrix " + name + ").");\r
+\r
+        switch(type) {\r
+        case 0: {\r
+            DoubleMatrix matrix = new DoubleMatrix(name, rows, columns);\r
+            int size = rows*columns;\r
+            double[] data = matrix.data;\r
+            for(int i=0;i<size;++i)\r
+                data[i] = getDouble();\r
+            return matrix;\r
+        } \r
+        case 20: {\r
+            IntMatrix matrix = new IntMatrix(name, rows, columns);\r
+            int size = rows*columns;\r
+            int[] data = matrix.data;\r
+            for(int i=0;i<size;++i)\r
+                data[i] = getInt();\r
+            return matrix;\r
+        }\r
+        case 51: {\r
+            StringMatrix matrix = new StringMatrix(name, columns);\r
+            String[] data = matrix.data;\r
+            for(int i=0;i<columns;++i)\r
+                data[i] = getString(rows).trim();\r
+            return matrix;\r
+        }\r
+        default:\r
+            throw new IOException("Matrix " + name + " has unsupported data type " + type + ".");\r
+        }\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @param in InputStream of a mat file\r
+     * @param outputInterval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc... \r
+     * @return\r
+     * @throws IOException\r
+     */\r
+    public static Map<String, double[]> read(InputStream in, int outputInterval) throws IOException {\r
+        Mat4Reader reader = new Mat4Reader(in);\r
+        reader.readMatrix(); // Header\r
+        StringMatrix names = (StringMatrix)reader.readMatrix(); // Variable names\r
+        reader.readMatrix(); // Variable descriptions\r
+        IntMatrix info = (IntMatrix)reader.readMatrix(); // Data info\r
+        if(info.rows != 4 || info.columns != names.rows )\r
+            throw new IOException("Invalid result data.");\r
+\r
+        HashMap<String, double[]> result = new HashMap<String, double[]>();\r
+        DoubleMatrix parameters = (DoubleMatrix)reader.readMatrix(); // Some result data matrix?\r
+        readDoubleMatrix(parameters, names, 1, 1, info, 1, result);\r
+        DoubleMatrix values = (DoubleMatrix)reader.readMatrix();\r
+        readDoubleMatrix(values, names, 2, 0, info, outputInterval, result);\r
+        in.close();\r
+        \r
+        return result;\r
+        \r
+    }\r
+    \r
+    private static void readDoubleMatrix(DoubleMatrix matrix, StringMatrix names, int dataMatrixNumber, int startIndex, IntMatrix info, int outputInterval, HashMap<String, double[]> result) {\r
+        double[] valueData = matrix.data;\r
+        int[] infoData = info.data;\r
+        int rows = matrix.rows;\r
+        //System.out.println("cols="+values.columns+", rows=" +values.rows+ ", data.length="+valueData.length);\r
+        for(int i=startIndex;i<info.columns;++i) {\r
+            if(infoData[i*4] != dataMatrixNumber)\r
+                continue;\r
+            // If values.columns % outputInterval != 0, the value in the last time step would not be displayed without adding a +1;\r
+            int size = matrix.columns % outputInterval != 0 ? matrix.columns / outputInterval + 1 : matrix.columns; \r
+            double[] v = new double[size];\r
+            int sc = infoData[i*4+1];\r
+            int c = sc > 0 ? sc-1 : -sc-1;\r
+            //System.out.println("i=" + i + ", sc=" + sc + ", c=" + c);\r
+            for(int j=0;j<v.length;++j) {\r
+                int adjusted = j * outputInterval;\r
+                if(adjusted >= matrix.columns) adjusted = matrix.columns - 1;\r
+                v[j] = valueData[rows * adjusted + c];\r
+            } if(sc < 0)\r
+                for(int j=0;j<v.length;++j)\r
+                    v[j] = -v[j];\r
+            result.put(names.data[i], v);\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/MatSimulationResult.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/MatSimulationResult.java
new file mode 100644 (file)
index 0000000..d748ffe
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.data;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.util.Map;\r
+\r
+import org.simantics.modelica.reader.MatFileReader;\r
+\r
+/**\r
+ * SimulationResult for Mat-formatted simulations results\r
+ *  \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+\r
+public class MatSimulationResult extends SimulationResult {\r
+    \r
+    @Override\r
+    public void read(InputStream stream, int interval) {\r
+        Map<String, double[]> valueMap = null;\r
+        try {\r
+            valueMap =  Mat4Reader.read(stream, interval);\r
+        } catch (IOException e) {\r
+            e.printStackTrace();\r
+            return;\r
+        }\r
+        \r
+        DataSet ds;\r
+        double[] allTimes = valueMap.get("time");\r
+        if(allTimes.length > 0) {\r
+            double[] parameterTimes = new double[] {allTimes[0], allTimes[allTimes.length - 1]};\r
+            for(String key : valueMap.keySet()) {\r
+                double[] values = valueMap.get(key);\r
+                if(values.length == 2)\r
+                    ds = new DataSet(key, parameterTimes, values);\r
+                else\r
+                    ds = new DataSet(key, allTimes, values);\r
+                variables.add(ds);\r
+            }\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void initRead(File file) throws FileNotFoundException, IOException {\r
+        super.initRead(file);\r
+        resultFileReader = new MatFileReader(file);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/Matrix.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/Matrix.java
new file mode 100644 (file)
index 0000000..1e68c1b
--- /dev/null
@@ -0,0 +1,29 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.data;\r
+\r
+/**\r
+ * Copied from Hannu's Matrix in org.simantics.modelica.data\r
+ * \r
+ * To be replaced with the original when SysDyn and Modelica tools \r
+ * are synchronized to use the same OpenModelica plugin\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public abstract class Matrix {\r
+    public final String name;\r
+\r
+    public Matrix(String name) {\r
+        this.name = name;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/SimulationResult.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/SimulationResult.java
new file mode 100644 (file)
index 0000000..092ea62
--- /dev/null
@@ -0,0 +1,520 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4180\r
+ *******************************************************************************/\r
+package org.simantics.modelica.data;\r
+\r
+import java.io.BufferedInputStream;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileReader;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.LineNumberReader;\r
+import java.util.ArrayList;\r
+import java.util.ConcurrentModificationException;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import javax.xml.parsers.DocumentBuilderFactory;\r
+import javax.xml.parsers.ParserConfigurationException;\r
+import javax.xml.transform.TransformerFactoryConfigurationError;\r
+import javax.xml.xpath.XPath;\r
+import javax.xml.xpath.XPathConstants;\r
+import javax.xml.xpath.XPathExpressionException;\r
+import javax.xml.xpath.XPathFactory;\r
+\r
+import org.simantics.modelica.reader.ResultFileReader;\r
+import org.w3c.dom.Document;\r
+import org.w3c.dom.Node;\r
+import org.w3c.dom.NodeList;\r
+import org.xml.sax.InputSource;\r
+import org.xml.sax.SAXException;\r
+\r
+/**\r
+ * Class that reads OpenModelica result files.\r
+ * \r
+ * SimulationResult class reads plt-files. Extended classes read other types.\r
+ * \r
+ * Will be replaced with a common OpenModelica plugin\r
+ * @author Hannu Niemistö\r
+ * @author Tuomas Miettinen\r
+ */\r
+public class SimulationResult {\r
+\r
+    protected List<DataSet> variables = new ArrayList<DataSet>();\r
+    protected List<DataSet> initials = new ArrayList<DataSet>();\r
+    protected int numberOfLines = 0;\r
+    protected ResultFileReader resultFileReader;\r
+    protected double[] allTimes;\r
+    protected int skip;\r
+\r
+    /**\r
+     * Private class used in displaying errors\r
+     */\r
+    protected class TimeValuePair {\r
+        public String time;\r
+        public String value;\r
+\r
+        public TimeValuePair(String time, String value) {\r
+            this.time = time;\r
+            this.value = value;\r
+        }\r
+    }\r
+\r
+    protected HashMap<String, ArrayList<TimeValuePair>> errors = new HashMap<String, ArrayList<TimeValuePair>>();\r
+\r
+    /**\r
+     * Get the next line in the plt-file\r
+     * @param stream plt-file input stream\r
+     * @return next line in the stream\r
+     */\r
+    static String getLine(InputStream stream) {\r
+        if(stream == null)\r
+            return null;\r
+        StringBuilder b = new StringBuilder();\r
+        try {\r
+            while(true) {\r
+                int c = stream.read();\r
+                if(c == -1) {\r
+                    stream = null;\r
+                    return b.toString();\r
+                }\r
+                else if(c == '\n')\r
+                    return b.toString();\r
+                else if(c == '\r')\r
+                    ;\r
+                else\r
+                    b.append((char)c);\r
+            }\r
+        } catch (IOException e) {\r
+            return null;\r
+        }\r
+\r
+    }\r
+\r
+\r
+    /**\r
+     * Read parameters that are located in the inits-file to the simulation result.\r
+     * Supports both txt and xml type inits.\r
+     * \r
+     * @param file inits-file\r
+     * @throws FileNotFoundException\r
+     * @throws IOException\r
+     */\r
+    public void readInits(File file) throws FileNotFoundException, IOException {\r
+\r
+        if(file.getName().endsWith("txt")) {\r
+            InputStream is = openStream(file);\r
+            readInitsTXT(is);\r
+            is.close();\r
+        } else if(file.getName().endsWith("xml")) {\r
+            readInitsXML(file.getAbsolutePath());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Read xml inits\r
+     * \r
+     * @param file xml-formatted inits file\r
+     */\r
+    public void readInitsXML(String file) {\r
+        Document doc;\r
+        try {\r
+            doc = DocumentBuilderFactory.newInstance()\r
+                    .newDocumentBuilder().parse(new InputSource(file));\r
+\r
+            XPath xpath = XPathFactory.newInstance().newXPath();\r
+\r
+            double[] times = new double[2];\r
+            Node node;\r
+            // Find start time\r
+            node = (Node)xpath.evaluate\r
+                    ("//fmiModelDescription/DefaultExperiment/@startTime",\r
+                            doc,\r
+                            XPathConstants.NODE);\r
+            times[0] = Double.parseDouble(node.getNodeValue());\r
+            // Find end time\r
+            node = (Node)xpath.evaluate\r
+                    ("//fmiModelDescription/DefaultExperiment/@stopTime",\r
+                            doc,\r
+                            XPathConstants.NODE);\r
+            times[1] = Double.parseDouble(node.getNodeValue());\r
+\r
+            NodeList nodes;\r
+\r
+            // Find parameters and constants\r
+            nodes = (NodeList)xpath.evaluate\r
+                    ("//fmiModelDescription/ModelVariables/ScalarVariable[@variability='parameter']",\r
+                            doc,\r
+                            XPathConstants.NODESET);\r
+\r
+            // Add parameters and constants to initials\r
+            for (int idx = 0; idx < nodes.getLength(); idx++) {\r
+                Node n = nodes.item(idx);\r
+                String name = n.getAttributes().getNamedItem("name").getNodeValue();\r
+                addToInitials(name, n, times);\r
+\r
+            }\r
+\r
+            // Find all alias variables\r
+            NodeList allAliasVariables = (NodeList)xpath.evaluate\r
+                    ("//fmiModelDescription/ModelVariables/ScalarVariable[@alias='alias']",\r
+                            doc,\r
+                            XPathConstants.NODESET);\r
+\r
+            for(int i = 0; i < allAliasVariables.getLength(); i++) {\r
+                Node n = allAliasVariables.item(i);\r
+                String name = n.getAttributes().getNamedItem("name").getNodeValue();\r
+\r
+                // Find the original variable\r
+                Node aliasVariableProperty = n.getAttributes().getNamedItem("aliasVariable");\r
+                String aliasVariableName = aliasVariableProperty.getNodeValue();\r
+                n = (Node)xpath.evaluate\r
+                        ("//fmiModelDescription/ModelVariables/ScalarVariable[@name='" + aliasVariableName +"' and @variability='parameter']",\r
+                                doc,\r
+                                XPathConstants.NODE);\r
+                // Add the value of the original value to initials with the name of the alias variable\r
+                if(n != null)\r
+                    addToInitials(name, n, times);\r
+            }\r
+\r
+\r
+        } catch (SAXException e) {\r
+            e.printStackTrace();\r
+        } catch (IOException e) {\r
+            e.printStackTrace();\r
+        } catch (ParserConfigurationException e) {\r
+            e.printStackTrace();\r
+        } catch (TransformerFactoryConfigurationError e) {\r
+            e.printStackTrace();\r
+        } catch (XPathExpressionException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Adds a new dataset to initials using start name, value from\r
+     * node and times.\r
+     * \r
+     * @param name Name for the dataset to be added to initials\r
+     * @param node Node containing the start value attribute\r
+     * @param times Array of times (length == 2)\r
+     */\r
+    private void addToInitials(String name, Node node, double[] times) {\r
+        // Find the start value for this\r
+        double[] values;\r
+        NodeList children;\r
+        children = node.getChildNodes();\r
+        for(int i = 0; i < children.getLength(); i++) {\r
+            Node child = children.item(i);\r
+            if(child.getNodeName().equals("Real")) {\r
+                Double d = Double.parseDouble(child.getAttributes().getNamedItem("start").getNodeValue());\r
+                values = new double[] {d,d};\r
+                initials.add(\r
+                        new DataSet(name,\r
+                                times ,\r
+                                values));\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Read txt inits\r
+     * @param stream txt-formatted init file\r
+     */\r
+    public void readInitsTXT(InputStream stream) {\r
+        HashMap<String, Double> mappedInitials = new HashMap<String, Double>();\r
+        while(true) {\r
+            String line = getLine(stream);\r
+            if(line == null)\r
+                return;\r
+            if(line.isEmpty())\r
+                break;\r
+\r
+            if(line.contains("//")) {\r
+                String[] nn = line.split("//", 2);\r
+                try {\r
+                    double value = Double.parseDouble(nn[0].trim());\r
+                    String key = nn[1].trim();\r
+                    mappedInitials.put(key, value);\r
+                } catch (NumberFormatException nfe) {\r
+                    continue; // Not a valid double\r
+                }\r
+\r
+            }\r
+\r
+        }\r
+\r
+        double startTime = mappedInitials.get("start value");\r
+        double stopTime = mappedInitials.get("stop value");\r
+        double[] times = new double[] {startTime, stopTime};\r
+\r
+        for(String key : mappedInitials.keySet()) {\r
+            double d = mappedInitials.get(key);\r
+            double[] values = new double[] {d, d};\r
+            initials.add(new DataSet(key, times , values));\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Read result file. Read all values in the result file.\r
+     * \r
+     * @param file result file\r
+     * @throws FileNotFoundException\r
+     * @throws IOException\r
+     */\r
+    public void read(File file) throws FileNotFoundException, IOException {\r
+        read(file, 1);\r
+    }\r
+\r
+    /**\r
+     * Initialize result file reading and read the whole result file\r
+     * \r
+     * @param file result file\r
+     * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc...\r
+     * @throws FileNotFoundException\r
+     * @throws IOException\r
+     */\r
+   public void read(File file, int interval) throws FileNotFoundException, IOException {\r
+        initRead(file);\r
+        readAll(file, interval);\r
+    }\r
+\r
+   /**\r
+    * Initialize result file reading\r
+    * \r
+    * @param file result file\r
+    * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc...\r
+    * @throws FileNotFoundException\r
+    * @throws IOException\r
+    */\r
+  public void initRead(File file) throws FileNotFoundException, IOException {\r
+        // First check the number of time steps.\r
+        // With *.mat result file this is not necessary\r
+        if (!(this instanceof MatSimulationResult)) {\r
+            FileReader fr = new FileReader(file);\r
+            LineNumberReader  lnr = new LineNumberReader(fr);\r
+            lnr.skip(Long.MAX_VALUE);\r
+            numberOfLines = lnr.getLineNumber() - 1; // minus the first row, which is for names\r
+            lnr.close();\r
+            fr.close();\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Read the whole result file\r
+     * \r
+     * @param file result file\r
+     * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc...\r
+     * @throws FileNotFoundException\r
+     * @throws IOException\r
+     */\r
+   public void readAll(File file, int interval)  throws FileNotFoundException, IOException {\r
+        InputStream is = openStream(file);\r
+        read(is, interval);\r
+        is.close();\r
+    }\r
+\r
+\r
+    protected InputStream openStream(File file) throws FileNotFoundException {\r
+        return new BufferedInputStream(new FileInputStream(file));\r
+    }\r
+\r
+    final static Pattern p1 = Pattern.compile("DataSet: ([^ ]*)");\r
+\r
+    /**\r
+     * Read result file. The basic implementation supports\r
+     * plt-formatted results. Overridden to support other formats.\r
+     * @param stream FileInputStream for the result file\r
+     * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc...\r
+     */\r
+    public void read(InputStream stream, int outputInterval) {\r
+        while(true) {\r
+            String line = getLine(stream);\r
+            if(line == null)\r
+                return;\r
+            if(line.isEmpty())\r
+                break;\r
+        }\r
+\r
+        // Data sets\r
+        while(true) {\r
+            Matcher matcher = p1.matcher(getLine(stream));\r
+            if(!matcher.matches())\r
+                return;\r
+            String name = matcher.group(1);\r
+            double[] dtimes = new double[numberOfLines];\r
+            double[] dvalues = new double[numberOfLines];\r
+            int i = 0;\r
+            while(true) {\r
+                String line = getLine(stream);\r
+                if(line == null)\r
+                    return;\r
+                if(line.isEmpty())\r
+                    break;\r
+                String[] nn = line.split(", ", 2);\r
+                dtimes[i] = Double.parseDouble(nn[0]);\r
+                dvalues[i] = Double.parseDouble(nn[1]);\r
+                i++;\r
+            }\r
+\r
+            variables.add(new DataSet(name, dtimes, dvalues));\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Filter result set\r
+     */\r
+    public void filter() {\r
+        ArrayList<DataSet> newVariables = new ArrayList<DataSet>();\r
+        for(DataSet dataSet : variables) {\r
+            if(!dataSet.name.contains("$") && !dataSet.name.contains("der("))\r
+                newVariables.add(dataSet);\r
+        }\r
+        variables = newVariables;\r
+    }\r
+\r
+    /**\r
+     * Get datasets for the variables in this result\r
+     * @return variable datasets\r
+     */\r
+    public List<DataSet> getVariableDataSets() {\r
+        return variables;\r
+    }\r
+\r
+    /**\r
+     * Get datasets for the initial values in this simulation\r
+     * @return initial value datasets\r
+     */\r
+    public List<DataSet> getInitialValueDataSets() {\r
+        return initials;\r
+    }\r
+\r
+    /**\r
+     * Gets DataSet for variable. Loops first the variables and then initials.\r
+     * @param name the name of the variable\r
+     * @return DataSet for the variable or null if DataSet not found\r
+     */\r
+    public DataSet getDataSet(String name) {\r
+        for(DataSet set : variables)\r
+            if(set.name.equals(name)) // Why on earth had these been changed to equalsIgnoreCase???\r
+                return set;\r
+        for(DataSet set : initials)\r
+            if(set.name.equals(name)) // Why on earth had these been changed to equalsIgnoreCase???\r
+                return set;\r
+        return null;\r
+    }\r
+\r
+\r
+    /**\r
+     * Return errors encountered during reading of the results.\r
+     * \r
+     * @return\r
+     */\r
+    public String getResultReadErrors() {\r
+        StringBuilder errorString = new StringBuilder();\r
+        if(!errors.isEmpty()) {\r
+            errorString.append("Number format errors (Time, Value):\n");\r
+            for(String key : errors.keySet()) {\r
+                errorString.append("\n" + key + ":\n");\r
+                for(TimeValuePair tv : errors.get(key)) {\r
+                    errorString.append("    " + tv.time + ", " + tv.value + "\n");\r
+                }\r
+            }\r
+        }\r
+        return errorString.toString();\r
+    }\r
+\r
+    /**\r
+     * Read a defined variable from result file\r
+     * \r
+     * @param file result file\r
+     * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc...\r
+     * @return The added dataset\r
+     * @throws FileNotFoundException\r
+     * @throws IOException\r
+     */\r
+    public DataSet readVariable(String variable, File file) throws FileNotFoundException, IOException {\r
+        if(resultFileReader == null)\r
+            return null;\r
+        \r
+        DataSet ds;\r
+        List<String> names = resultFileReader.getNames();\r
+        if (names.contains(variable)) {\r
+            double[] resArray = resultFileReader.readData(variable, 0, allTimes.length, skip);\r
+            double[] timesArray = allTimes;\r
+            if(resArray.length == 2 && timesArray.length > 2)\r
+                timesArray = new double[] {timesArray[0], timesArray[timesArray.length - 1]};\r
+            ds = new DataSet(variable, timesArray, resArray);\r
+            try {\r
+                   for (DataSet tempds : variables){\r
+                       if (tempds.name.equals(variable)) {\r
+                           // We should never need to go there unless some change in\r
+                           // the logic of reading variables are made.\r
+                           // Also helps in seeking memory leaks.\r
+                           return null;\r
+                       }\r
+                   }\r
+            } catch (ConcurrentModificationException e) {\r
+            }\r
+            variables.add(ds);\r
+            return ds;\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    /**\r
+     * Read a all missing variable from the result file\r
+     * \r
+     * @param file result file\r
+     * @throws FileNotFoundException\r
+     * @throws IOException\r
+     */\r
+    public void readMissingVariables(File file) throws FileNotFoundException, IOException {\r
+        List<String> names = resultFileReader.getNames();\r
+        for (String variable : names) {\r
+            boolean matchFound = false; \r
+            for (DataSet tempDs : variables) {\r
+                if (tempDs.name.equals(variable)) {\r
+                    matchFound = true;\r
+                    break;\r
+                }\r
+            }\r
+            if (matchFound) {\r
+                continue;\r
+            }\r
+            readVariable(variable, file);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Read time array from result file\r
+     * \r
+     * @param file result file\r
+     * @param interval the interval of results to be read. 1 reads all time steps, 2 reads every other time step, etc...\r
+     * @throws FileNotFoundException\r
+     * @throws IOException\r
+     */\r
+    public void readTime(File file, int interval) throws FileNotFoundException, IOException {\r
+        skip = interval - 1;\r
+        int totalCount = resultFileReader.getCount("time");\r
+        int count = totalCount / interval;\r
+        if (totalCount % interval != 0)\r
+            count++;\r
+        allTimes = resultFileReader.readData("time", 0, count, skip); \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/data/StringMatrix.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/data/StringMatrix.java
new file mode 100644 (file)
index 0000000..8cfbea0
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.data;\r
+\r
+/**\r
+ * Copied from Hannu's StringMatrix in org.simantics.modelica.data\r
+ * \r
+ * To be replaced with the original when SysDyn and Modelica tools \r
+ * are synchronized to use the same OpenModelica plugin\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class StringMatrix extends Matrix {\r
+    public final int rows;\r
+    public final String[] data;\r
+\r
+    public StringMatrix(String name, int rows) {\r
+        super(name);\r
+        this.rows = rows;\r
+        this.data = new String[rows];\r
+    }\r
+\r
+    @Override\r
+    public String toString() {\r
+        StringBuilder b = new StringBuilder();\r
+        b.append("char " + name + "(" + rows + ")\n");\r
+        for(String row : data)\r
+            b.append(row + "\n");\r
+        return b.toString();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/preferences/ModelicaPreferenceInitializer.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/preferences/ModelicaPreferenceInitializer.java
new file mode 100644 (file)
index 0000000..553aeab
--- /dev/null
@@ -0,0 +1,52 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.preferences;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;\r
+import org.eclipse.core.runtime.preferences.ConfigurationScope;\r
+import org.eclipse.core.runtime.preferences.IScopeContext;\r
+import org.osgi.service.prefs.Preferences;\r
+import org.simantics.modelica.Activator;\r
+import org.simantics.modelica.ModelicaManager;\r
+\r
+public class ModelicaPreferenceInitializer extends AbstractPreferenceInitializer {  \r
+\r
+       @Override  \r
+       public void initializeDefaultPreferences() {\r
+               IScopeContext context = ConfigurationScope.INSTANCE;\r
+               Preferences node = context.getNode(Activator.PLUGIN_ID);\r
+               String omHome = node.get(OpenModelicaPreferences.OM_HOME, null);\r
+               if (omHome == null) {\r
+                       // OM_HOME not set\r
+                       useDefault(node);\r
+               } else {\r
+                       File dir = new File(omHome);\r
+                       if(dir == null || !dir.isDirectory())\r
+                               // OM_HOME is not a directory\r
+                               useDefault(node);\r
+                       // TODO: does not make much sense\r
+//                     try {\r
+//                             ModelicaManager.getOpenModelicaVersion();\r
+//                     } catch (IOException e) {\r
+//                             // OpenModelica not found from directory\r
+//                             useDefault(node);\r
+//                     }\r
+               }\r
+       }  \r
+\r
+       private void useDefault(Preferences node) {\r
+               node.put(OpenModelicaPreferences.OM_HOME, ModelicaManager.getDefaultOMHome().getAbsolutePath());\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/preferences/OpenModelicaPreferences.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/preferences/OpenModelicaPreferences.java
new file mode 100644 (file)
index 0000000..e8b0e6a
--- /dev/null
@@ -0,0 +1,18 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.modelica.preferences;\r
+\r
+public class OpenModelicaPreferences {\r
+    \r
+    public static String OM_HOME = "OPENMODELICA_HOME";\r
+\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/reader/MatFileReader.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/reader/MatFileReader.java
new file mode 100644 (file)
index 0000000..79db0d6
--- /dev/null
@@ -0,0 +1,619 @@
+package org.simantics.modelica.reader;\r
+\r
+import java.io.BufferedInputStream;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.simantics.modelica.data.DoubleMatrix;\r
+import org.simantics.modelica.data.IntMatrix;\r
+import org.simantics.modelica.data.Matrix;\r
+import org.simantics.modelica.data.StringMatrix;\r
+import org.simantics.utils.datastructures.MapList;\r
+\r
+public class MatFileReader implements ResultFileReader {\r
+       private final File file;\r
+       \r
+       private final List<String> names = new ArrayList<String>();\r
+       private final Map<String, Integer> indices = new HashMap<String, Integer>();\r
+       \r
+       private HashMap<String, double[]> parameterValues;\r
+       \r
+       long readBytes = 0; // tracking read data\r
+       long dataMark  = 0; // mark for actual data\r
+       \r
+       IntMatrix info;\r
+       int[] infoData;\r
+       \r
+       MatrixHeader dataHeader;\r
+       \r
+       public MatFileReader(File file) throws IOException {\r
+               this.file = file;\r
+               readVariables();\r
+       }\r
+       \r
+       @Override\r
+    public List<String> getNames() {\r
+               return names;\r
+       }\r
+       \r
+       @Override\r
+    public int getCount(String item) {\r
+               return dataHeader.columns;\r
+       }\r
+       \r
+       /**\r
+        * Reads all data of a given item\r
+        */\r
+       @Override\r
+    public double[] readData(String item) throws IOException {\r
+               readBytes = 0;\r
+               Integer index = indices.get(item);\r
+               if (index == null)\r
+                   if (parameterValues.containsKey(item)) {\r
+                       return parameterValues.get(item);\r
+                   } else {\r
+                       throw new IOException("Unknown item: " + item);\r
+                   }\r
+               InputStream in = openStream();\r
+               skip(dataMark, in);\r
+               \r
+               Object data = readRow(dataHeader, index, in);\r
+               \r
+               in.close();\r
+               \r
+               return (double[])data;\r
+       }\r
+       \r
+       /**\r
+        * Reads data of a given item\r
+        * @param item name of a item.\r
+        * @param start index of starting sample.\r
+        * @param count number of samples to read.\r
+        * @param skip number of samples to skip. 0 : all data is read. 1: every second sample is read.\r
+        * @return\r
+        * @throws IOException\r
+        */\r
+       @Override\r
+    public double[] readData(String item, int start, int count, int skip) throws IOException {\r
+               readBytes = 0;\r
+               Integer index = indices.get(item);\r
+               if (index == null)\r
+               if (parameterValues.containsKey(item)) {\r
+                       return parameterValues.get(item);\r
+               } else {\r
+                   throw new IOException("Unknown item: " + item);\r
+               }\r
+               InputStream in = openStream();\r
+               skip(dataMark, in);\r
+               \r
+               Object data = readRow(dataHeader, index, start, count, skip, in);\r
+               \r
+               in.close();\r
+               \r
+               return (double[])data;\r
+\r
+       }\r
+       \r
+       @Override\r
+    public double[][] readData(List<String> items) throws IOException {\r
+           readBytes = 0;\r
+               List<Integer> indexes = new ArrayList<Integer>(items.size());\r
+               for (String item : items) {\r
+                       Integer index = indices.get(item);\r
+                       if (index == null)\r
+                           // Parameters cannot be accessed via this method; instead, \r
+                           // methods with only a single item should be used\r
+                       throw new IOException("Unknown item: " + item);\r
+                       indexes.add(index);\r
+               }\r
+               \r
+               InputStream in = openStream();\r
+               skip(dataMark, in);\r
+               \r
+               \r
+               \r
+               Object data = readRows(dataHeader, indexes, in);\r
+               \r
+               in.close();\r
+               \r
+               return (double[][])data;\r
+\r
+       }\r
+       \r
+       private InputStream openStream() throws FileNotFoundException {\r
+               return new BufferedInputStream(new FileInputStream(file));\r
+       }\r
+       \r
+       @Override\r
+       public double[][] readData(List<String> items, int start, int count,\r
+                       int skip) throws IOException {\r
+               readBytes = 0;\r
+               \r
+               List<Integer> indexes = new ArrayList<Integer>(items.size());\r
+               for (String item : items) {\r
+                       Integer index = indices.get(item);\r
+                       if (index == null)\r
+                           // Parameters cannot be accessed via this method; instead, \r
+                // methods with only a single item should be used\r
+                throw new IOException("Unknown item: " + item);\r
+                       indexes.add(index);\r
+               }\r
+               \r
+               InputStream in = openStream();\r
+               skip(dataMark, in);\r
+               \r
+               \r
+               \r
+               Object data = readRows(dataHeader, indexes,start,count,skip, in);\r
+               \r
+               in.close();\r
+               \r
+               return (double[][])data;\r
+       }\r
+       \r
+       private void readVariables() throws IOException {\r
+               InputStream in = openStream();\r
+               readMatrix(in); // Header\r
+               StringMatrix names = (StringMatrix)readMatrix(in); // Variable names\r
+           readMatrix(in); // Variable descriptions\r
+           \r
+           for (int i = 0; i < names.data.length; i++) {\r
+               String s = names.data[i];\r
+               this.names.add(s);\r
+               indices.put(s, i);\r
+           }\r
+           \r
+         \r
+           \r
+               info = (IntMatrix)readMatrix(in); // Data info\r
+               \r
+        if(info.rows != 4 || info.columns != names.rows )\r
+            throw new IOException("Invalid result data.");\r
+       \r
+        infoData = info.data;\r
+        \r
+        //Read parameters\r
+        parameterValues = new HashMap<String, double[]>();\r
+        DoubleMatrix parameters = (DoubleMatrix)readMatrix(in); // Some result data matrix?\r
+        readDoubleMatrix(parameters, names, 1, 1, info, 1, parameterValues);\r
+        \r
+        dataHeader = new MatrixHeader(in);\r
+        \r
+        dataMark = readBytes;\r
+       \r
+        in.close();\r
+        \r
+        // filter incompatible? data.\r
+        for (int i = this.names.size() -1; i >=  0; i--) {\r
+               if (infoData[i * 4] != 2) {\r
+                       String name = this.names.get(i);\r
+                       // Remove parameters from indices but not from names list\r
+                       this.indices.remove(name);\r
+               }\r
+                       \r
+        }\r
+        \r
+        Collections.sort(this.names);\r
+        \r
+       }\r
+\r
+       private final int getInt(InputStream in) throws IOException {\r
+        int ch1 = in.read();\r
+        int ch2 = in.read();\r
+        int ch3 = in.read();\r
+        int ch4 = in.read();\r
+        readBytes += 4;\r
+        return ((ch1 << 0) + (ch2 << 8) + (ch3 << 16) + (ch4 << 24));\r
+    }\r
+\r
+    private final long getLong(InputStream in) throws IOException {\r
+        int ch1 = in.read();\r
+        int ch2 = in.read();\r
+        int ch3 = in.read();\r
+        int ch4 = in.read();\r
+        int ch5 = in.read();\r
+        int ch6 = in.read();\r
+        int ch7 = in.read();\r
+        int ch8 = in.read();\r
+        readBytes += 8;\r
+        return ((((long)ch1) << 0) + (((long)ch2) << 8) + (((long)ch3) << 16) + (((long)ch4) << 24) +\r
+                (((long)ch5) << 32) + (((long)ch6) << 40) + (((long)ch7) << 48) + (((long)ch8) << 56));\r
+    }\r
+\r
+    private final double getDouble(InputStream in) throws IOException {\r
+        return Double.longBitsToDouble(getLong(in));\r
+    }\r
+\r
+    private String getString(InputStream in,int length) throws IOException {\r
+        byte[] buffer = new byte[length];\r
+        int pos = 0;\r
+        while(pos < length)\r
+            pos += in.read(buffer, pos, length-pos);\r
+        readBytes += length;\r
+        return new String(buffer, "UTF-8");\r
+    }\r
+\r
+    private Matrix readMatrix(InputStream in) throws IOException {\r
+       \r
+       int type = getInt(in);\r
+        int rows = getInt(in);\r
+        int columns = getInt(in);\r
+        int imagf = getInt(in);\r
+        int namlen = getInt(in);\r
+\r
+        String name = getString(in,namlen-1);\r
+        in.read();\r
+        readBytes++;\r
+\r
+        if(imagf > 0)\r
+            throw new IOException("Imaginary part of the matrix is not supported (matrix " + name + ").");\r
+\r
+        switch(type) {\r
+        case 0: {\r
+            DoubleMatrix matrix = new DoubleMatrix(name, rows, columns);\r
+            int size = rows*columns;\r
+            double[] data = matrix.data;\r
+            for(int i=0;i<size;++i)\r
+                data[i] = getDouble(in);\r
+            return matrix;\r
+        } \r
+        case 20: {\r
+            IntMatrix matrix = new IntMatrix(name, rows, columns);\r
+            int size = rows*columns;\r
+            int[] data = matrix.data;\r
+            for(int i=0;i<size;++i)\r
+                data[i] = getInt(in);\r
+            return matrix;\r
+        }\r
+        case 51: {\r
+            StringMatrix matrix = new StringMatrix(name, columns);\r
+            String[] data = matrix.data;\r
+            for(int i=0;i<columns;++i)\r
+                data[i] = getString(in,rows).trim();\r
+            return matrix;\r
+        }\r
+        default:\r
+            throw new IOException("Matrix " + name + " has unsupported data type " + type + ".");\r
+        }\r
+    }\r
+    \r
+    private Matrix readMatrix(MatrixHeader header, InputStream in) throws IOException {\r
+        switch(header.type) {\r
+        case 0: {\r
+            DoubleMatrix matrix = new DoubleMatrix(header.name, header.rows,header.columns);\r
+            int size = header.rows*header.columns;\r
+            double[] data = matrix.data;\r
+            for(int i=0;i<size;++i)\r
+                data[i] = getDouble(in);\r
+            return matrix;\r
+        } \r
+        case 20: {\r
+            IntMatrix matrix = new IntMatrix(header.name, header.rows, header.columns);\r
+            int size = header.rows*header.columns;\r
+            int[] data = matrix.data;\r
+            for(int i=0;i<size;++i)\r
+                data[i] = getInt(in);\r
+            return matrix;\r
+        }\r
+        case 51: {\r
+            StringMatrix matrix = new StringMatrix(header.name, header.columns);\r
+            String[] data = matrix.data;\r
+            for(int i=0;i<header.columns;++i)\r
+                data[i] = getString(in,header.rows).trim();\r
+            return matrix;\r
+        }\r
+        default:\r
+            throw new IOException("Matrix " + header.name + " has unsupported data type " + header.type + ".");\r
+        }\r
+    }\r
+    \r
+       private double[] readRow(MatrixHeader header, int column, InputStream in)throws IOException {\r
+               if (header.type != 0)\r
+               throw new IOException("Only double type supported");\r
+               if (infoData[column * 4] != 2)\r
+                       throw new IOException(); // this is checked in initialization phase.\r
+               int size = header.columns;\r
+               int rows = header.rows;\r
+               double[] v = new double[size];\r
+               int sc = infoData[column * 4 + 1];\r
+               int c = sc > 0 ? sc-1 : -sc-1;\r
+\r
+       skip(c * 8, in);\r
+       for (int j = 0; j < v.length; ++j) {\r
+               \r
+               double d = getDouble(in);\r
+               v[j] = d;\r
+               skip((rows-1)*8,in);\r
+               }\r
+       \r
+       if(sc < 0)\r
+            for(int j=0;j<v.length;++j)\r
+                v[j] = -v[j];\r
+        return v;\r
+    }\r
+       \r
+       private double[] readRow(MatrixHeader header, int row, int start, int count, int skip, InputStream in)throws IOException {\r
+\r
+               if (header.type != 0)\r
+               throw new IOException("Only double type supported");\r
+               \r
+               if (infoData[row * 4] != 2)\r
+                       throw new IOException();  // this is checked in initialization phase.\r
+               int size = header.columns;\r
+               if (start+count*(skip+1)-skip > size)\r
+                       throw new IndexOutOfBoundsException(); // TODO: we could just read available data, instead of throwing exception.\r
+               int rows = header.rows;\r
+               double[] v = new double[count];\r
+               int sc = infoData[row * 4 + 1];\r
+               long c = sc > 0 ? sc-1 : -sc-1;\r
+\r
+       skip((c+((long)start*(long)rows)) * 8L, in);\r
+       for (int j = 0; j < v.length; ++j) {\r
+               \r
+               double d = getDouble(in);\r
+               v[j] = d;\r
+               skip((rows*skip + rows-1)*8,in);\r
+               }\r
+       \r
+       if(sc < 0)\r
+            for(int j=0;j<v.length;++j)\r
+                v[j] = -v[j];\r
+        return v;\r
+    }\r
+       \r
+       private double[][] readRows(MatrixHeader header, List<Integer> unSortedRows, InputStream in)throws IOException {\r
+\r
+               if (header.type != 0)\r
+               throw new IOException("Only double type supported");\r
+               for (int row : unSortedRows)\r
+                       if (infoData[row * 4] != 2)\r
+                               throw new IOException();  // this is checked in initialization phase.\r
+               int size = header.columns;\r
+               int rows = header.rows;\r
+               int usc[] = new int[unSortedRows.size()];\r
+               int uc[] = new int[unSortedRows.size()];\r
+               double vs[][] = new double[unSortedRows.size()][];\r
+               for (int i = 0; i < unSortedRows.size(); i++) {\r
+                       int row = unSortedRows.get(i);\r
+                       //vs[i] = new double[size];\r
+                       usc[i] = infoData[row * 4 + 1];\r
+                       uc[i] = usc[i] > 0 ? usc[i]-1 : -usc[i]-1;\r
+               }\r
+               \r
+               MapList<Integer, Integer> cToRow = new MapList<Integer, Integer>();\r
+               List<Integer> sortedCs = new ArrayList<Integer>();\r
+               for (int i = 0; i < unSortedRows.size(); i++) {\r
+                       cToRow.add(uc[i], unSortedRows.get(i));\r
+                       sortedCs.add(uc[i]);\r
+               }\r
+               \r
+               List<Integer> sortedRows = new ArrayList<Integer>();\r
+               int sc[] = new int[sortedCs.size()];\r
+               int c[] = new int[sortedCs.size()];\r
+               \r
+               Collections.sort(sortedCs);\r
+\r
+               for (int i = 0; i < sortedCs.size(); i++) {\r
+                       int row = cToRow.getValues(sortedCs.get(i)).get(0);\r
+                       sortedRows.add(row);\r
+                       sc[i] = usc[unSortedRows.indexOf(row)];\r
+                       c[i] = uc[unSortedRows.indexOf(row)];\r
+                       vs[i] = new double[size];\r
+               }\r
+\r
+       skip(c[0] * 8L, in);\r
+       for (int j = 0; j < size; ++j) {\r
+               for (int index = 0; index < sortedRows.size(); index++) {\r
+                               \r
+                               double d = getDouble(in);\r
+                               vs[index][j] = d;\r
+                       \r
+                               if (index < sortedRows.size() - 1) {\r
+                                       skip((c[index+1] - c[index] -1 )*8, in);\r
+                               } else {\r
+                                       skip((rows - c[index]-1 + c[0])*8,in);\r
+                               }\r
+               }\r
+               }\r
+\r
+       \r
+       for (int i = 0; i < sortedRows.size(); i++) {\r
+               if(sc[i] < 0)\r
+             for(int j=0;j<vs[i].length;++j)\r
+                 vs[i][j] = -vs[i][j];\r
+         \r
+       }\r
+\r
+       for (int i = 0; i < unSortedRows.size(); i++) {\r
+               int rRow = unSortedRows.get(i);\r
+               \r
+               if (i < sortedRows.size())  {\r
+                       int row = sortedRows.get(i);\r
+                       if (row != rRow) {\r
+                               int ri = sortedRows.indexOf(rRow);\r
+                               double v[] = vs[i];\r
+                                       vs[i] = vs[ri];\r
+                                       vs[ri] = v;\r
+                                       sortedRows.set(i, rRow);\r
+                                       sortedRows.set(ri, row);\r
+                               \r
+                       }\r
+               } else {\r
+                       int uci = uc[i];\r
+                       int row = cToRow.getValues(uci).get(0);\r
+                       int ri = sortedRows.indexOf(row);\r
+                       vs[i] = vs[ri];\r
+               }\r
+       }\r
+       \r
+       return vs;\r
+    }\r
+    \r
+       \r
+       private double[][] readRows(MatrixHeader header, List<Integer> unSortedRows, int start, int count, int skip, InputStream in)throws IOException {\r
+               \r
+               if (header.type != 0)\r
+               throw new IOException("Only double type supported");\r
+               for (int row : unSortedRows)\r
+                       if (infoData[row * 4] != 2)\r
+                               throw new IOException(); // this is checked in initialization phase.\r
+               \r
+               int size = header.columns;\r
+               int rows = header.rows;\r
+               \r
+               if (start+count*(skip+1) > size)\r
+                       throw new IndexOutOfBoundsException(); // TODO: we could just read available data, instead of throwing exception.\r
+               \r
+               int usc[] = new int[unSortedRows.size()];\r
+               int uc[] = new int[unSortedRows.size()];\r
+               double vs[][] = new double[unSortedRows.size()][];\r
+               for (int i = 0; i < unSortedRows.size(); i++) {\r
+                       int row = unSortedRows.get(i);\r
+                       usc[i] = infoData[row * 4 + 1];\r
+                       uc[i] = usc[i] > 0 ? usc[i]-1 : -usc[i]-1;\r
+               }\r
+               \r
+               MapList<Integer, Integer> cToRow = new MapList<Integer, Integer>();\r
+               List<Integer> sortedCs = new ArrayList<Integer>();\r
+               for (int i = 0; i < unSortedRows.size(); i++) {\r
+                       cToRow.add(uc[i], unSortedRows.get(i));\r
+                       if (!sortedCs.contains(uc[i]))\r
+                               sortedCs.add(uc[i]);\r
+               }\r
+               \r
+               List<Integer> sortedRows = new ArrayList<Integer>();\r
+               int sc[] = new int[sortedCs.size()];\r
+               int c[] = new int[sortedCs.size()];\r
+               \r
+               Collections.sort(sortedCs);\r
+               for (int i = 0; i < sortedCs.size(); i++) {\r
+                       int row = cToRow.getValues(sortedCs.get(i)).get(0);\r
+                       sortedRows.add(row);\r
+                       sc[i] = usc[unSortedRows.indexOf(row)];\r
+                       c[i] = uc[unSortedRows.indexOf(row)];\r
+                       vs[i] = new double[count];\r
+               }\r
+               \r
+               long s = start;\r
+               s *= rows;\r
+               s *= 8L;\r
+               skip(s, in);\r
+       skip(c[0] * 8, in);\r
+       for (int j = 0; j < count; ++j) {\r
+               for (int index = 0; index < sortedRows.size(); index++) {\r
+                               \r
+                               double d = getDouble(in);\r
+                               vs[index][j] = d;\r
+                       \r
+                               if (index < sortedRows.size() - 1) {\r
+                                       skip((c[index+1] - c[index] -1 )*8, in);\r
+                               } else {\r
+                                       skip((rows - c[index]-1 + c[0])*8,in);\r
+                               }\r
+               }\r
+               if (skip > 0)\r
+                       skip((skip*rows)*8,in);\r
+               }\r
+\r
+       \r
+       for (int i = 0; i < sortedRows.size(); i++) {\r
+               if(sc[i] < 0)\r
+             for(int j=0;j<vs[i].length;++j)\r
+                 vs[i][j] = -vs[i][j];\r
+         \r
+       }\r
+       for (int i = 0; i < unSortedRows.size(); i++) {\r
+               int rRow = unSortedRows.get(i);\r
+               \r
+               if (i < sortedRows.size())  {\r
+                       int row = sortedRows.get(i);\r
+                       if (row != rRow) {\r
+                               int ri = sortedRows.indexOf(rRow);\r
+                               double v[] = vs[i];\r
+                                       vs[i] = vs[ri];\r
+                                       vs[ri] = v;\r
+                                       sortedRows.set(i, rRow);\r
+                                       sortedRows.set(ri, row);\r
+                               \r
+                       }\r
+               } else {\r
+                       int uci = uc[i];\r
+                       int row = cToRow.getValues(uci).get(0);\r
+                       int ri = sortedRows.indexOf(row);\r
+                       vs[i] = vs[ri];\r
+               }\r
+       }\r
+       \r
+       return vs;\r
+    }\r
+    private void skip(long skipBytes, InputStream in) throws IOException {\r
+       long skip = 0; \r
+       while (skip < skipBytes) {\r
+               skip += in.skip(skipBytes-skip);\r
+       }\r
+    }\r
+    \r
+    private static void readDoubleMatrix(DoubleMatrix matrix, StringMatrix names, int dataMatrixNumber, int startIndex, IntMatrix info, int outputInterval, HashMap<String, double[]> result) {\r
+        double[] valueData = matrix.data;\r
+        int[] infoData = info.data;\r
+        int rows = matrix.rows;\r
+\r
+        for(int i=startIndex;i<info.columns;++i) {\r
+            if(infoData[i*4] != dataMatrixNumber)\r
+                continue;\r
+            // If values.columns % outputInterval != 0, the value in the last time step would not be displayed without adding a +1;\r
+            int size = matrix.columns % outputInterval != 0 ? matrix.columns / outputInterval + 1 : matrix.columns; \r
+            double[] v = new double[size];\r
+            int sc = infoData[i*4+1];\r
+            int c = sc > 0 ? sc-1 : -sc-1;\r
+            for(int j=0;j<v.length;++j) {\r
+                int adjusted = j * outputInterval;\r
+                if(adjusted >= matrix.columns) adjusted = matrix.columns - 1;\r
+                v[j] = valueData[rows * adjusted + c];\r
+            } if(sc < 0)\r
+                for(int j=0;j<v.length;++j)\r
+                    v[j] = -v[j];\r
+            result.put(names.data[i], v);\r
+        }\r
+    }\r
+    \r
+    private class MatrixHeader {\r
+       \r
+       int type;\r
+        int rows;\r
+        int columns;\r
+        int imagf;\r
+        int namlen;\r
+        \r
+        String name;\r
+        \r
+        public MatrixHeader(InputStream in) throws IOException{\r
+               //int s = readBytes;\r
+               type = getInt(in);\r
+            rows = getInt(in);\r
+            columns = getInt(in);\r
+            imagf = getInt(in);\r
+            namlen = getInt(in);\r
+\r
+            name = getString(in,namlen-1);\r
+            in.read();\r
+            readBytes++;\r
+            if(imagf > 0)\r
+                throw new IOException("Imaginary part of the matrix is not supported (matrix " + name + ").");\r
+            \r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+       return file.getName();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.modelica/src/org/simantics/modelica/reader/ResultFileReader.java b/1.8/org.simantics.modelica/src/org/simantics/modelica/reader/ResultFileReader.java
new file mode 100644 (file)
index 0000000..e82619e
--- /dev/null
@@ -0,0 +1,42 @@
+package org.simantics.modelica.reader;\r
+\r
+import java.io.IOException;\r
+import java.util.List;\r
+\r
+public interface ResultFileReader {\r
+       \r
+       /**\r
+        * List items in the file.\r
+        * @return\r
+        */\r
+       public List<String> getNames();\r
+       \r
+       /**\r
+        * Return number of samples.\r
+        * @param item\r
+        * @return\r
+        */\r
+       public int getCount(String item);\r
+       \r
+       /**\r
+        * Reads all data of a given item\r
+        * @param item\r
+        * @return\r
+        * @throws IOException\r
+        */\r
+       public double[] readData(String item) throws IOException;\r
+       public double[][] readData(List<String> items) throws IOException;\r
+\r
+       /**\r
+        * Reads data of a given item\r
+        * @param item name of a item.\r
+        * @param start index of starting sample.\r
+        * @param count number of samples to read.\r
+        * @param skip number of samples to skip. 0 : all data is read. 1: every second sample is read.\r
+        * @return\r
+        * @throws IOException\r
+        */\r
+       public double[] readData(String item, int start, int count, int skip) throws IOException;\r
+       public double[][] readData(List<String> items, int start, int count, int skip) throws IOException;\r
+       \r
+}\r
diff --git a/1.8/org.simantics.objmap/.classpath b/1.8/org.simantics.objmap/.classpath
new file mode 100644 (file)
index 0000000..23e107f
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="src" path="examples"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.objmap/.hgignore b/1.8/org.simantics.objmap/.hgignore
new file mode 100644 (file)
index 0000000..73df90f
--- /dev/null
@@ -0,0 +1,5 @@
+syntax: regexp\r
+^bin/\r
+\r
+syntax: glob\r
+*.svn/*
\ No newline at end of file
diff --git a/1.8/org.simantics.objmap/.project b/1.8/org.simantics.objmap/.project
new file mode 100644 (file)
index 0000000..82c191c
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.objmap</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.objmap/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.objmap/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..fc058b8
--- /dev/null
@@ -0,0 +1,8 @@
+#Wed Nov 11 10:38:27 EET 2009\r
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.objmap/META-INF/MANIFEST.MF b/1.8/org.simantics.objmap/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..2b3664f
--- /dev/null
@@ -0,0 +1,20 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Objmap
+Bundle-SymbolicName: org.simantics.objmap
+Bundle-Version: 0.1.0.qualifier
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: gnu.trove2;bundle-version="2.0.4",
+ org.apache.log4j;bundle-version="1.2.15",
+ org.simantics.layer0;bundle-version="1.0.0",
+ org.simantics.db.common;bundle-version="1.1.0"
+Export-Package: org.simantics.objmap,
+ org.simantics.objmap.annotations,
+ org.simantics.objmap.annotations.meta,
+ org.simantics.objmap.rules,
+ org.simantics.objmap.rules.adapters,
+ org.simantics.objmap.rules.domain,
+ org.simantics.objmap.rules.factory,
+ org.simantics.objmap.rules.range,
+ org.simantics.objmap.schema
+Bundle-Vendor: VTT Technical Research Centre of Finland
diff --git a/1.8/org.simantics.objmap/build.properties b/1.8/org.simantics.objmap/build.properties
new file mode 100644 (file)
index 0000000..de6a2f5
--- /dev/null
@@ -0,0 +1,17 @@
+###############################################################################\r
+# Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+# in Industry THTH ry.\r
+# All rights reserved. This program and the accompanying materials\r
+# are made available under the terms of the Eclipse Public License v1.0\r
+# which accompanies this distribution, and is available at\r
+# http://www.eclipse.org/legal/epl-v10.html\r
+#\r
+# Contributors:\r
+#     VTT Technical Research Centre of Finland - initial API and implementation\r
+###############################################################################\r
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .\r
+src.includes = doc/,\\r
+               examples/\r
diff --git a/1.8/org.simantics.objmap/doc/bidirectionalModel.graphml b/1.8/org.simantics.objmap/doc/bidirectionalModel.graphml
new file mode 100644 (file)
index 0000000..2a52aa1
--- /dev/null
@@ -0,0 +1,108 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>\r
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.0/ygraphml.xsd">\r
+  <!--Created by yFiles for Java 2.7-->\r
+  <key for="graphml" id="d0" yfiles.type="resources"/>\r
+  <key attr.name="url" attr.type="string" for="node" id="d1"/>\r
+  <key attr.name="description" attr.type="string" for="node" id="d2">\r
+    <default/>\r
+  </key>\r
+  <key for="node" id="d3" yfiles.type="nodegraphics"/>\r
+  <key attr.name="url" attr.type="string" for="edge" id="d4"/>\r
+  <key attr.name="description" attr.type="string" for="edge" id="d5">\r
+    <default/>\r
+  </key>\r
+  <key for="edge" id="d6" yfiles.type="edgegraphics"/>\r
+  <graph edgedefault="directed" id="G">\r
+    <node id="n0">\r
+      <data key="d2"/>\r
+      <data key="d3">\r
+        <y:ShapeNode>\r
+          <y:Geometry height="30.0" width="127.0" x="186.0" y="200.0"/>\r
+          <y:Fill color="#FFFFFF" transparent="false"/>\r
+          <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+          <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="106.720703125" x="10.1396484375" y="5.6494140625">Intermediate model</y:NodeLabel>\r
+          <y:Shape type="rectangle"/>\r
+        </y:ShapeNode>\r
+      </data>\r
+    </node>\r
+    <node id="n1">\r
+      <data key="d2"/>\r
+      <data key="d3">\r
+        <y:ShapeNode>\r
+          <y:Geometry height="30.0" width="103.0" x="-21.0" y="200.0"/>\r
+          <y:Fill color="#FFFFFF" transparent="false"/>\r
+          <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+          <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="55.369140625" x="23.8154296875" y="5.6494140625">Database</y:NodeLabel>\r
+          <y:Shape type="rectangle"/>\r
+        </y:ShapeNode>\r
+      </data>\r
+    </node>\r
+    <node id="n2">\r
+      <data key="d2"/>\r
+      <data key="d3">\r
+        <y:ShapeNode>\r
+          <y:Geometry height="30.0" width="103.0" x="417.0" y="200.0"/>\r
+          <y:Fill color="#FFFFFF" transparent="false"/>\r
+          <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+          <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="35.34765625" x="33.826171875" y="5.6494140625">Editor</y:NodeLabel>\r
+          <y:Shape type="rectangle"/>\r
+        </y:ShapeNode>\r
+      </data>\r
+    </node>\r
+    <edge id="e0" source="n1" target="n0">\r
+      <data key="d6">\r
+        <y:PolyLineEdge>\r
+          <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">\r
+            <y:Point x="134.75500000000028" y="185.0425000000001"/>\r
+          </y:Path>\r
+          <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+          <y:Arrows source="none" target="standard"/>\r
+          <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="six_pos" modelPosition="head" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="34.017578125" x="13.93121093750014" y="-34.47918379864251">reads</y:EdgeLabel>\r
+          <y:BendStyle smoothed="false"/>\r
+        </y:PolyLineEdge>\r
+      </data>\r
+    </edge>\r
+    <edge id="e1" source="n0" target="n2">\r
+      <data key="d6">\r
+        <y:PolyLineEdge>\r
+          <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">\r
+            <y:Point x="363.0000000000002" y="190.6400000000001"/>\r
+          </y:Path>\r
+          <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+          <y:Arrows source="none" target="standard"/>\r
+          <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="six_pos" modelPosition="shead" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="56.01953125" x="1.5527343750001137" y="-33.057650409984035">visualizes</y:EdgeLabel>\r
+          <y:BendStyle smoothed="false"/>\r
+        </y:PolyLineEdge>\r
+      </data>\r
+    </edge>\r
+    <edge id="e2" source="n2" target="n0">\r
+      <data key="d6">\r
+        <y:PolyLineEdge>\r
+          <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">\r
+            <y:Point x="365.0000000000002" y="237.3600000000001"/>\r
+          </y:Path>\r
+          <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+          <y:Arrows source="none" target="standard"/>\r
+          <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="six_pos" modelPosition="stail" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="48.68359375" x="-54.904296874999886" y="13.861448547068562">modifies</y:EdgeLabel>\r
+          <y:BendStyle smoothed="false"/>\r
+        </y:PolyLineEdge>\r
+      </data>\r
+    </edge>\r
+    <edge id="e3" source="n0" target="n1">\r
+      <data key="d6">\r
+        <y:PolyLineEdge>\r
+          <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">\r
+            <y:Point x="133.78500000000014" y="234.19250000000017"/>\r
+          </y:Path>\r
+          <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+          <y:Arrows source="none" target="standard"/>\r
+          <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="six_pos" modelPosition="tail" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="35.3359375" x="-48.33796874999993" y="10.017335507498103">writes</y:EdgeLabel>\r
+          <y:BendStyle smoothed="false"/>\r
+        </y:PolyLineEdge>\r
+      </data>\r
+    </edge>\r
+  </graph>\r
+  <data key="d0">\r
+    <y:Resources/>\r
+  </data>\r
+</graphml>\r
diff --git a/1.8/org.simantics.objmap/doc/bidirectionalModel.png b/1.8/org.simantics.objmap/doc/bidirectionalModel.png
new file mode 100644 (file)
index 0000000..77bcc30
Binary files /dev/null and b/1.8/org.simantics.objmap/doc/bidirectionalModel.png differ
diff --git a/1.8/org.simantics.objmap/doc/main.mediawiki b/1.8/org.simantics.objmap/doc/main.mediawiki
new file mode 100644 (file)
index 0000000..97c2fb3
--- /dev/null
@@ -0,0 +1,26 @@
+'''org.simantics.objmap'''  is a framework for bidirectional synchronization between Simantics database and Java objects. \r
+\r
+See [[org.simantics.template_Manual|Manual]] for details.\r
+\r
+= Dependencies=\r
+\r
+* [[org.simantics.db]]\r
+* gnu.trove2\r
+\r
+There is a plan to split the plugin into two plugins such that the other will be database-independent and contain all annotations.\r
+\r
+=Download=\r
+\r
+{| style="background-color: #e9e9e9; border: 1px solid #aaaaaa; width: 75%;"\r
+| '''Version'''\r
+| '''Date'''\r
+| '''Download'''\r
+|- style="background-color: #f9f9f9; " |\r
+| 0.1.0\r
+| 12.11.2009\r
+| [[Media:org.simantics.objmap-0.1.0.zip|org.simantics.objmap-0.1.0.zip]] \r
+|}\r
+\r
+=Current Development=\r
+The current version is released mostly for comments and is not yet ready for deployment. The development plan is at the end of the [[org.simantics.objmap_Manual#TODO|manual]]. \r
+\r
diff --git a/1.8/org.simantics.objmap/doc/manual.mediawiki b/1.8/org.simantics.objmap/doc/manual.mediawiki
new file mode 100644 (file)
index 0000000..c3bab96
--- /dev/null
@@ -0,0 +1,167 @@
+= Introduction =\r
+\r
+When implementing an editor in Simantics platform, it is very common that the graph representation cannot be directly used, but the editor needs to create an intermediate model of the subgraph it edits. Some reasons for this:\r
+* Accessing the database directly is not fast enough.\r
+* An editor using the database directly holds frequently long read locks and cannot operate during write transactions.\r
+* The editor needs to store auxiliary objects attached to the model.\r
+* Editor modifies the intermediate model speculatively before the modification is committed to the database or canceled.\r
+* The modifications in database cannot be applied in the editor immediately (for example during rendering).\r
+* Third-party component requires certain classes to be used.\r
+* Editor needs to be backend agnostic and cannot directly use database api.\r
+\r
+There are two different approaches for implementing the intermediate model:\r
+; Triangle model\r
+: The editor modifies the database directly and the changes in the database are eventually propagated to the intermediate model. The editor doesn't change the intermediate model directly.\r
+[[Image:triangleModel.png]] \r
+; Bidirectional model\r
+: The editor operates only using the intermediate model and modifications are updated from intermediate model to the database and vice versa. \r
+[[Image:bidirectionalModel.png]] \r
+\r
+By experience, the triangle model is easier to implement correctly in particular when resources are linked to each other in complex fashion. The  <code>org.simantics.objmap</code>-plugin tries to make the implementation of bidirectional model easier by providing a framework for defining declaratively the update procedure between database and intermediate model. It can also be used with triangle model only for one direction or with hybrid model where some operations are implemented using the intermediate model and other modifying the database directly.\r
+\r
+= Design principles =\r
+\r
+; Symmetric\r
+: For every operation from database to Java objects there is a corresponding operation from Java objects to database. This makes the framework easier to learn and undestand. \r
+; Non-intrusive\r
+: The Java objects used with the framework do not need to implement any specific interface or follow some specific naming convention. The mapping schema can be defined using annotations or separately from the class definition.\r
+; Support for different use scenarios\r
+:* bidirectional / unidirectional\r
+:* one shot / continuous\r
+:* automatic listening / manual updating\r
+; One-to-one\r
+: For every resource there is a single corresponding Java object and vise versa. This makes the framework easier to understand. It is not a transformation framework.  \r
+\r
+= Concepts =\r
+\r
+''Mapping'' consists of a set of resources called a ''domain'', a set of Java objects called a ''range'' and a collection of ''links''. Each link is attached to exactly one domain and range element and each domain and range element has at most one link attached to it. Additionally the link has a ''link type''  that contains requirements for the domain and range elements in the same link.\r
+\r
+[[Image:objectMappingTerminology.png]]\r
+\r
+A mapping is ''up-to-date'' if every domain and range element has a link and all links satisfy the requirements of their link types. The links of up-to-date mapping form a bijection from domain to range.\r
+\r
+A ''mapping schema'' associates all domain and range elements with a link type. It is used to add new domain and range elements to the mapping.\r
+\r
+= Mapping interface =\r
+\r
+The plugin represents a mapping with interface <code>org.simantics.objmap.IMapping</code>. The interface is symmetric in the sense that every operation on the domain of the mapping has also a counterpart that operates on the range. Typically, if one of the operations requires a read graph, its counterpart requires a write graph. We will describe only the methods operating on the domain of the mapping:\r
+\r
+ Set<Resource> getDomain();\r
\r
+Returns the domain of the mapping. All set operations are supported. Adding a new domain element does not automatically create a link to it. Removal of a domain element removes also a link and the target element, but does not remove the element from the database.  \r
+    \r
+ Collection<Resource> updateDomain(WriteGraph g) throws MappingException;\r
\r
+Updates all domain elements whose counterpart is modified and creates new domain elements for previously added range elements. Returns the collection of domain elements that were modified or created in the update process.\r
+\r
+ Object get(Resource domainElement);\r
+    \r
+Returns the counterpart of a domain element or null if the element does not belong to the domain or does not have a link.    \r
+    \r
+ Object map(ReadGraph g, Resource domainElement) throws MappingException;\r
+\r
+A convenience method that adds a domain element to the mapping and immediately updates the mapping and returns the corresponding range element.  \r
+\r
+ void domainModified(Resource domainElement);\r
\r
+Tells the mapping that the domain element has been modified.  \r
+\r
+ boolean isDomainModified();\r
\r
+Tells if some domain elements have been modified or added. \r
\r
+ Collection<Resource> getConflictingDomainElements();\r
+\r
+Returns a collection of domain elements which have been modified and also their counterparts in the mapping are modified. These elements are in conflict in the sense that the updating domain and range in different orders may produce different results.\r
+\r
+ void addMappingListener(IMappingListener listener);\r
+ void removeMappingListener(IMappingListener listener);\r
+\r
+Adds or removes a listener for domain and range modifications.\r
+\r
+= Defining a mapping schema =\r
+\r
+The primary way for defining a mapping schema is to use Java annotations. The current annotation support is still lacking. Only the following annotations are supported:\r
+; GraphType(uri)\r
+: Specifies the domain type that the class corresponds to.\r
+; RelatedValue(uri)\r
+: Specifies a correspondence between a field and functional property.\r
+; RelatedElement(uri)\r
+: Specifies a correspondence between a field and functional relation\r
+; RelatedElements(uri)\r
+: Specifies a correspondence between a field and a relation. The type of the field has to be a collection.\r
+\r
+== Example ==\r
+    \r
+Suppose we have the following annotated classes:\r
+ @GraphType("http://www.simantics.org/Sysdyn#Configuration")\r
+ static class Configuration {\r
+     @RelatedElements("http://www.vtt.fi/Simantics/Layer0/1.0/Relations#ConsistsOf")\r
+     Collection<Component> components; \r
+ }\r
\r
+ static abstract class Component {        \r
+ }\r
\r
+ @GraphType("http://www.simantics.org/Sysdyn#Dependency")\r
+ static class Dependency extends Component {\r
+     @RelatedElement("http://www.simantics.org/Sysdyn#HasTail")\r
+     Variable tail;\r
+     @RelatedElement("http://www.simantics.org/Sysdyn#HasHead")\r
+     Auxiliary head;\r
+ }\r
\r
+ static abstract class Variable extends Component {\r
+     @RelatedValue("http://www.vtt.fi/Simantics/Layer0/1.0/Relations#HasName")\r
+     String name;\r
+ }\r
\r
+ @GraphType("http://www.simantics.org/Sysdyn#Auxiliary")\r
+ static class Auxiliary extends Variable {\r
+ }\r
+\r
+Them the schema can be defined as follows:\r
+ SimpleSchema schema = new SimpleSchema();\r
+ schema.addLinkType(MappingSchemas.fromAnnotations(g, Configuration.class));\r
+ schema.addLinkType(MappingSchemas.fromAnnotations(g, Dependency.class));\r
+ schema.addLinkType(MappingSchemas.fromAnnotations(g, Auxiliary.class));\r
+\r
+= Using the mapping interface =\r
+\r
+Assume that a mapping scheme <code>scheme</code> has already been defined and <code>modelRoot</code> is the root resource of the model that the editor edits. Then the model is created as follows:\r
+ IMapping mapping = Mappings.create(scheme);\r
+ in read transaction {\r
+     MyModel model = (MyModel)mapping.map(graph, modelRoot);\r
+ } \r
\r
+There are different ways how the mapping can be updated. The following code forces update for all domain elements. \r
+ in read transaction {\r
+     for(Resource r : mapping.getDomain())\r
+         mapping.domainModified(r);\r
+     mapping.updateRange(graph);\r
+ }\r
\r
+If the range elements have some kind of "dirty" flags, the update can be optimized:\r
+ in write transaction {\r
+     for(Object obj : mapping.getRange())\r
+         if(obj implements MyObject && ((MyObject)obj).isDirty())\r
+             mapping.rangeModified(obj);\r
+     mapping.updateDomain(graph);\r
+ }\r
\r
+Often the editor has to update some auxiliary structures when the mapping modifies the range. This can be implemented for example as:\r
+ for(Object obj : mapping.updateRange(graph))\r
+     if(obj implements MyObject)\r
+         ((MyObject)obj).updateAuxiliary();\r
+\r
+The most convenient way for updating the target would be to add graph request listeners for each domain element in the mapping. This is not yet implemented although the current interface should support this without modifications. Currently the only way to listen the database changes is to listen the request that is used to call the updateRange-method.\r
+\r
+= Development plan =\r
+\r
+By priority:\r
+* Automatic listening of database changes: marks domain elements modified.\r
+* More complete annotations\r
+* Utilizing declarations in ontologies: for example full URIs of relations are not needed because relations are declared in types. Also the validity of annotation can be checked.\r
+* A separate plugin containing only mapping annotations so that the plugin can be used without introducing a dependency to org.simantics.db.\r
+* Composition annotation that can be used to remove elements whose parents are removed or update elements whose parents are marked modified.  \r
+* Support for copy-paste and other extra mapping issues. \r
diff --git a/1.8/org.simantics.objmap/doc/objectMappingTerminology.graphml b/1.8/org.simantics.objmap/doc/objectMappingTerminology.graphml
new file mode 100644 (file)
index 0000000..c3cc6b2
--- /dev/null
@@ -0,0 +1,202 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>\r
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.0/ygraphml.xsd">\r
+  <!--Created by yFiles for Java 2.7-->\r
+  <key for="graphml" id="d0" yfiles.type="resources"/>\r
+  <key attr.name="url" attr.type="string" for="node" id="d1"/>\r
+  <key attr.name="description" attr.type="string" for="node" id="d2">\r
+    <default/>\r
+  </key>\r
+  <key for="node" id="d3" yfiles.type="nodegraphics"/>\r
+  <key attr.name="url" attr.type="string" for="edge" id="d4"/>\r
+  <key attr.name="description" attr.type="string" for="edge" id="d5">\r
+    <default/>\r
+  </key>\r
+  <key for="edge" id="d6" yfiles.type="edgegraphics"/>\r
+  <graph edgedefault="directed" id="G">\r
+    <node id="n0" yfiles.foldertype="group">\r
+      <data key="d2"/>\r
+      <data key="d3">\r
+        <y:ProxyAutoBoundsNode>\r
+          <y:Realizers active="0">\r
+            <y:GroupNode>\r
+              <y:Geometry height="92.0" width="532.0" x="99.0" y="298.0"/>\r
+              <y:Fill color="#F5F5F5" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="node_width" backgroundColor="#EBEBEB" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="22.37646484375" modelName="free" modelPosition="anywhere" textColor="#000000" visible="true" width="532.0" x="0.0" y="0.0">mapping</y:NodeLabel>\r
+              <y:Shape type="rectangle"/>\r
+              <y:State closed="false" innerGraphDisplayEnabled="false"/>\r
+              <y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>\r
+              <y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="20" topF="20.0"/>\r
+            </y:GroupNode>\r
+            <y:GroupNode>\r
+              <y:Geometry height="80.0" width="100.0" x="-50.0" y="-30.0"/>\r
+              <y:Fill color="#CAECFF84" transparent="false"/>\r
+              <y:BorderStyle color="#666699" type="dotted" width="1.0"/>\r
+              <y:NodeLabel alignment="right" autoSizePolicy="node_width" backgroundColor="#99CCFF" borderDistance="0.0" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasLineColor="false" height="4.0" modelName="internal" modelPosition="t" textColor="#000000" visible="true" width="100.0" x="0.0" y="0.0"/>\r
+              <y:Shape type="roundrectangle"/>\r
+              <y:State closed="true" innerGraphDisplayEnabled="false"/>\r
+              <y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>\r
+              <y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>\r
+            </y:GroupNode>\r
+          </y:Realizers>\r
+        </y:ProxyAutoBoundsNode>\r
+      </data>\r
+      <graph edgedefault="directed" id="n0:">\r
+        <node id="n0::n0">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="513.0" y="333.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="4.0" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="4.0" x="49.5" y="13.0"/>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <node id="n0::n1">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="507.0" y="339.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="4.0" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="4.0" x="49.5" y="13.0"/>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <node id="n0::n2">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="319.5" y="333.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="4.0" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="4.0" x="49.5" y="13.0"/>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <node id="n0::n3">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="313.5" y="339.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="4.0" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="4.0" x="49.5" y="13.0"/>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <node id="n0::n4">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="126.0" y="333.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="4.0" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="4.0" x="49.5" y="13.0"/>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <node id="n0::n5">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="120.0" y="339.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="4.0" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="4.0" x="49.5" y="13.0"/>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <node id="n0::n6">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="114.0" y="345.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="89.3828125" x="6.80859375" y="5.6494140625">domain element</y:NodeLabel>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <node id="n0::n7">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="307.5" y="345.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="22.005859375" x="40.4970703125" y="5.6494140625">link</y:NodeLabel>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <node id="n0::n8">\r
+          <data key="d3">\r
+            <y:ShapeNode>\r
+              <y:Geometry height="30.0" width="103.0" x="501.0" y="345.0"/>\r
+              <y:Fill color="#FFFFFF" transparent="false"/>\r
+              <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+              <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.716796875" x="11.1416015625" y="5.6494140625">range element</y:NodeLabel>\r
+              <y:Shape type="rectangle"/>\r
+            </y:ShapeNode>\r
+          </data>\r
+        </node>\r
+        <edge id="n0::e0" source="n0::n7" target="n0::n8">\r
+          <data key="d6">\r
+            <y:PolyLineEdge>\r
+              <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>\r
+              <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+              <y:Arrows source="none" target="standard"/>\r
+              <y:BendStyle smoothed="false"/>\r
+            </y:PolyLineEdge>\r
+          </data>\r
+        </edge>\r
+        <edge id="n0::e1" source="n0::n7" target="n0::n6">\r
+          <data key="d6">\r
+            <y:PolyLineEdge>\r
+              <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>\r
+              <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+              <y:Arrows source="none" target="standard"/>\r
+              <y:BendStyle smoothed="false"/>\r
+            </y:PolyLineEdge>\r
+          </data>\r
+        </edge>\r
+      </graph>\r
+    </node>\r
+    <node id="n1">\r
+      <data key="d3">\r
+        <y:ShapeNode>\r
+          <y:Geometry height="30.0" width="103.0" x="313.5" y="426.58361904761904"/>\r
+          <y:Fill color="#FFFFFF" transparent="false"/>\r
+          <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+          <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="4.0" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="4.0" x="49.5" y="13.0"/>\r
+          <y:Shape type="rectangle"/>\r
+        </y:ShapeNode>\r
+      </data>\r
+    </node>\r
+    <node id="n2">\r
+      <data key="d3">\r
+        <y:ShapeNode>\r
+          <y:Geometry height="30.0" width="103.0" x="307.5" y="433.9028571428571"/>\r
+          <y:Fill color="#FFFFFF" transparent="false"/>\r
+          <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+          <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="48.021484375" x="27.4892578125" y="5.6494140625">link type</y:NodeLabel>\r
+          <y:Shape type="rectangle"/>\r
+        </y:ShapeNode>\r
+      </data>\r
+    </node>\r
+    <edge id="e0" source="n0::n7" target="n2">\r
+      <data key="d6">\r
+        <y:PolyLineEdge>\r
+          <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>\r
+          <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+          <y:Arrows source="none" target="standard"/>\r
+          <y:BendStyle smoothed="false"/>\r
+        </y:PolyLineEdge>\r
+      </data>\r
+    </edge>\r
+  </graph>\r
+  <data key="d0">\r
+    <y:Resources/>\r
+  </data>\r
+</graphml>\r
diff --git a/1.8/org.simantics.objmap/doc/objectMappingTerminology.png b/1.8/org.simantics.objmap/doc/objectMappingTerminology.png
new file mode 100644 (file)
index 0000000..e9ee1fb
Binary files /dev/null and b/1.8/org.simantics.objmap/doc/objectMappingTerminology.png differ
diff --git a/1.8/org.simantics.objmap/doc/triangleModel.graphml b/1.8/org.simantics.objmap/doc/triangleModel.graphml
new file mode 100644 (file)
index 0000000..9ab3b29
--- /dev/null
@@ -0,0 +1,89 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>\r
+<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.0/ygraphml.xsd">\r
+  <!--Created by yFiles for Java 2.7-->\r
+  <key for="graphml" id="d0" yfiles.type="resources"/>\r
+  <key attr.name="url" attr.type="string" for="node" id="d1"/>\r
+  <key attr.name="description" attr.type="string" for="node" id="d2">\r
+    <default/>\r
+  </key>\r
+  <key for="node" id="d3" yfiles.type="nodegraphics"/>\r
+  <key attr.name="url" attr.type="string" for="edge" id="d4"/>\r
+  <key attr.name="description" attr.type="string" for="edge" id="d5">\r
+    <default/>\r
+  </key>\r
+  <key for="edge" id="d6" yfiles.type="edgegraphics"/>\r
+  <graph edgedefault="directed" id="G">\r
+    <node id="n0">\r
+      <data key="d2"/>\r
+      <data key="d3">\r
+        <y:ShapeNode>\r
+          <y:Geometry height="30.0" width="127.0" x="186.0" y="200.0"/>\r
+          <y:Fill color="#FFFFFF" transparent="false"/>\r
+          <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+          <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="106.720703125" x="10.1396484375" y="5.6494140625">Intermediate model</y:NodeLabel>\r
+          <y:Shape type="rectangle"/>\r
+        </y:ShapeNode>\r
+      </data>\r
+    </node>\r
+    <node id="n1">\r
+      <data key="d2"/>\r
+      <data key="d3">\r
+        <y:ShapeNode>\r
+          <y:Geometry height="30.0" width="103.0" x="80.0" y="315.0"/>\r
+          <y:Fill color="#FFFFFF" transparent="false"/>\r
+          <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+          <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="55.369140625" x="23.8154296875" y="5.6494140625">Database</y:NodeLabel>\r
+          <y:Shape type="rectangle"/>\r
+        </y:ShapeNode>\r
+      </data>\r
+    </node>\r
+    <node id="n2">\r
+      <data key="d2"/>\r
+      <data key="d3">\r
+        <y:ShapeNode>\r
+          <y:Geometry height="30.0" width="103.0" x="320.0" y="315.0"/>\r
+          <y:Fill color="#FFFFFF" transparent="false"/>\r
+          <y:BorderStyle color="#000000" type="line" width="1.0"/>\r
+          <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="35.34765625" x="33.826171875" y="5.6494140625">Editor</y:NodeLabel>\r
+          <y:Shape type="rectangle"/>\r
+        </y:ShapeNode>\r
+      </data>\r
+    </node>\r
+    <edge id="e0" source="n1" target="n0">\r
+      <data key="d6">\r
+        <y:PolyLineEdge>\r
+          <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>\r
+          <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+          <y:Arrows source="none" target="standard"/>\r
+          <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="six_pos" modelPosition="tail" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="34.017578125" x="55.20320262079653" y="-51.8505859375">reads</y:EdgeLabel>\r
+          <y:BendStyle smoothed="false"/>\r
+        </y:PolyLineEdge>\r
+      </data>\r
+    </edge>\r
+    <edge id="e1" source="n0" target="n2">\r
+      <data key="d6">\r
+        <y:PolyLineEdge>\r
+          <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>\r
+          <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+          <y:Arrows source="none" target="standard"/>\r
+          <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="six_pos" modelPosition="tail" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="56.01953125" x="57.00669661812162" y="33.1494140625">visualizes</y:EdgeLabel>\r
+          <y:BendStyle smoothed="false"/>\r
+        </y:PolyLineEdge>\r
+      </data>\r
+    </edge>\r
+    <edge id="e2" source="n2" target="n1">\r
+      <data key="d6">\r
+        <y:PolyLineEdge>\r
+          <y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>\r
+          <y:LineStyle color="#000000" type="line" width="1.0"/>\r
+          <y:Arrows source="none" target="standard"/>\r
+          <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="six_pos" modelPosition="tail" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="48.68359375" x="-92.841796875" y="2.0">modifies</y:EdgeLabel>\r
+          <y:BendStyle smoothed="false"/>\r
+        </y:PolyLineEdge>\r
+      </data>\r
+    </edge>\r
+  </graph>\r
+  <data key="d0">\r
+    <y:Resources/>\r
+  </data>\r
+</graphml>\r
diff --git a/1.8/org.simantics.objmap/doc/triangleModel.png b/1.8/org.simantics.objmap/doc/triangleModel.png
new file mode 100644 (file)
index 0000000..0918ef8
Binary files /dev/null and b/1.8/org.simantics.objmap/doc/triangleModel.png differ
diff --git a/1.8/org.simantics.objmap/examples/org/simantics/objmap/examples/SysdynExample.java b/1.8/org.simantics.objmap/examples/org/simantics/objmap/examples/SysdynExample.java
new file mode 100644 (file)
index 0000000..bb6df66
--- /dev/null
@@ -0,0 +1,62 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.examples;\r
+\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.IMappingSchema;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.objmap.schema.MappingSchemas;\r
+import org.simantics.objmap.schema.SimpleSchema;\r
+\r
+public class SysdynExample {\r
+\r
+    @GraphType("http://www.simantics.org/Sysdyn-1.1/Configuration")\r
+    static class Configuration {\r
+        @RelatedElements("http://www.simantics.org/Layer0-1.0/ConsistsOf")\r
+        Collection<Component> components;\r
+    }\r
+\r
+    static abstract class Component {\r
+    }\r
+\r
+    @GraphType("http://www.simantics.org/Sysdyn-1.1/Dependency")\r
+    static class Dependency extends Component {\r
+        @RelatedElement("http://www.simantics.org/Sysdyn-1.1/HasTail")\r
+        Variable tail;\r
+        @RelatedElement("http://www.simantics.org/Sysdyn-1.1/HasHead")\r
+        Auxiliary head;\r
+    }\r
+\r
+    static abstract class Variable extends Component {\r
+        @RelatedValue("http://www.simantics.org/Layer0-1.0/HasName")\r
+        String name;\r
+    }\r
+\r
+    @GraphType("http://www.simantics.org/Sysdyn-1.1/Auxiliary")\r
+    static class Auxiliary extends Variable {\r
+    }\r
+\r
+    public static IMappingSchema createSchema(ReadGraph g) throws DatabaseException, InstantiationException, IllegalAccessException {\r
+        SimpleSchema schema = new SimpleSchema();\r
+        schema.addLinkType(MappingSchemas.fromAnnotations(g, Configuration.class));\r
+        schema.addLinkType(MappingSchemas.fromAnnotations(g, Dependency.class));\r
+        schema.addLinkType(MappingSchemas.fromAnnotations(g, Auxiliary.class));\r
+        return schema;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/IFunction.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/IFunction.java
new file mode 100644 (file)
index 0000000..8a7f9fe
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap;\r
+\r
+/**\r
+ * A generic function object that throws MappingExceptions.\r
+ * \r
+ * @author Hannu Niemistö\r
+ *\r
+ * @param <D> Domain of the function\r
+ * @param <R> Range of the function\r
+ */\r
+public interface IFunction<D, R> {\r
+       R get(D element) throws MappingException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/ILinkType.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/ILinkType.java
new file mode 100644 (file)
index 0000000..91a985a
--- /dev/null
@@ -0,0 +1,32 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+\r
+/**\r
+ * Contains rules for how a link should be created and maintained.\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface ILinkType extends IMappingRule {\r
+    /**\r
+     * Creates a domain element based on known range element.\r
+     */\r
+       Resource createDomainElement(WriteGraph g, Object rangeElement) throws MappingException;\r
+       \r
+       /**\r
+     * Creates a range element based on known domain element.\r
+     */\r
+       Object createRangeElement(ReadGraph g, Resource domainElement) throws MappingException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/IMapping.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/IMapping.java
new file mode 100644 (file)
index 0000000..bb22a3b
--- /dev/null
@@ -0,0 +1,138 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap;\r
+\r
+import java.util.Collection;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.Disposable;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+\r
+/**\r
+ * A mapping consists of domain (a set of resources), range (a set of Java objects) and\r
+ * a set of links relating them. The mapping is used to propagate modifications of\r
+ * domain elements to range and vice versa. \r
+ * \r
+ * @see <a href="http://www.simantics.org/wiki/index.php/org.simantics.objmap_Manual#Concepts">Manual</a>\r
+ * \r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IMapping extends Disposable {\r
+\r
+    /**\r
+     * Returns the domain of the mapping. All set operations are supported.\r
+     * Adding a new domain element does not automatically create a link to it.\r
+     * Removal of a domain element removes also a link and the target element,\r
+     * but does not remove the element from the database.\r
+     */\r
+    Set<Resource> getDomain();\r
+\r
+    /**\r
+     * Returns the range of the mapping. All set operations are supported.\r
+     * Adding a new range element does not automatically create a link to it.\r
+     * Removal of a range element removes also a link and the domain element,\r
+     * but does not remove the domain element from the database.\r
+     */\r
+    Set<Object> getRange();\r
+\r
+    /**\r
+     * Updates all domain elements whose counterpart is modified and creates new\r
+     * domain elements for previously added range elements. Returns the\r
+     * collection of domain elements that were modified or created in the update\r
+     * process.\r
+     */\r
+    Collection<Resource> updateDomain(WriteGraph g) throws MappingException;\r
+\r
+    /**\r
+     * Updates all range elements whose counterpart is modified and creates new\r
+     * range elements for previously added domain elements. Returns the\r
+     * collection of range elements that were modified or created in the update\r
+     * process.\r
+     */\r
+    Collection<Object> updateRange(ReadGraph g) throws MappingException;\r
+\r
+    /**\r
+     * Returns the counterpart of a domain element or null if the element does\r
+     * not belong to the domain or does not have a link.\r
+     */\r
+    Object get(Resource domainElement);\r
+\r
+    /**\r
+     * Returns the counterpart of a range element or null if the element does\r
+     * not belong to the range or does not have a link.\r
+     */\r
+    Resource inverseGet(Object rangeElement);\r
+\r
+    /**\r
+     * A convenience method that adds a domain element to the mapping and\r
+     * immediately updates the mapping and returns the corresponding range\r
+     * element.\r
+     */\r
+    Object map(ReadGraph g, Resource domainElement) throws MappingException;\r
+\r
+    /**\r
+     * A convenience method that adds a range element to the mapping and\r
+     * immediately updates the mapping and returns the corresponding domain\r
+     * element.\r
+     */\r
+    Resource inverseMap(WriteGraph g, Object rangeElement)\r
+            throws MappingException;\r
+\r
+    /**\r
+     * Tells the mapping that the domain element has been modified.\r
+     */\r
+    void domainModified(Resource domainElement);\r
+\r
+    /**\r
+     * Tells the mapping that the range element has been modified.\r
+     */\r
+    void rangeModified(Object rangeElement);\r
+\r
+    /**\r
+     * Tells if some domain elements have been modified or added.\r
+     */\r
+    boolean isDomainModified();\r
+\r
+    /**\r
+     * Tells if some range elements have been modified or added.\r
+     */\r
+    boolean isRangeModified();\r
+\r
+    /**\r
+     * Returns a collection of domain elements which have been modified and also\r
+     * their counterparts in the mapping are modified. These elements are in\r
+     * conflict in the sense that the updating domain and range in different\r
+     * orders may produce different results.\r
+     */\r
+    Collection<Resource> getConflictingDomainElements();\r
+\r
+    /**\r
+     * Returns a collection of range elements which have been modified and also\r
+     * their counterparts in the mapping are modified. These elements are in\r
+     * conflict in the sense that the updating domain and range in different\r
+     * orders may produce different results.\r
+     */\r
+    Collection<Object> getConflictingRangeElements();\r
+\r
+    /**\r
+     * Adds a listener for domain and range modifications.\r
+     */\r
+    void addMappingListener(IMappingListener listener);\r
+\r
+    /**\r
+     * Removes a previously added listener.\r
+     */\r
+    void removeMappingListener(IMappingListener listener);\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingListener.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingListener.java
new file mode 100644 (file)
index 0000000..b7c3970
--- /dev/null
@@ -0,0 +1,30 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap;\r
+\r
+/**\r
+ * Listens modifications in a mapping.\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IMappingListener {\r
+    /**\r
+     * Called when some domain element is modified or created\r
+     * and the mapping was previously up to date.\r
+     */\r
+       void domainModified();\r
+       \r
+       /**\r
+     * Called when some range element is modified or created\r
+     * and the mapping was previously up to date.\r
+     */\r
+       void rangeModified();\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingRule.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingRule.java
new file mode 100644 (file)
index 0000000..75f3bb5
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+\r
+/**\r
+ * A rule for how domain and range elements are related to each other. \r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IMappingRule {\r
+    /**\r
+     * Modifies the domain element so that it corresponds to the range element.\r
+     * @param g write transaction\r
+     * @param map unidirectional view of the current mapping\r
+     * @param domainElement the domain element that is updated\r
+     * @param rangeElement the range element that corresponds to the domain element\r
+     * @return true if the rule made some modifications\r
+     * @throws MappingException \r
+     */    \r
+       boolean updateDomain(WriteGraph g, IFunction<Object, Resource> map, Resource domainElement, Object rangeElement) throws MappingException;\r
+\r
+       /**\r
+        * Modifies the range element so that it corresponds to the domain element.\r
+        * @param g read transaction\r
+        * @param map unidirectional view of the current mapping\r
+        * @param domainElement the domain element that corresponds to the range element\r
+        * @param rangeElement the range element that is updated\r
+        * @return true if the rule made some modifications\r
+        * @throws MappingException\r
+        */\r
+       boolean updateRange(ReadGraph g, IFunction<Resource, Object> map, Resource domainElement, Object rangeElement) throws MappingException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingSchema.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/IMappingSchema.java
new file mode 100644 (file)
index 0000000..a403954
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Specifies the link types of new elements added to a mapping.\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IMappingSchema {\r
+    /**\r
+     * @return Link type that should be used for the element.\r
+     */\r
+       ILinkType linkTypeOfDomainElement(ReadGraph g, Resource element) throws MappingException;\r
+       \r
+       /**\r
+     * @return Link type that should be used for the element.\r
+     */\r
+       ILinkType linkTypeOfRangeElement(Object element) throws MappingException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/MappingException.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/MappingException.java
new file mode 100644 (file)
index 0000000..290345e
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap;\r
+\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+/**\r
+ * An exception thrown for any error during mapping methods.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class MappingException extends DatabaseException {\r
+\r
+       private static final long serialVersionUID = -4026122899414272427L;\r
+\r
+       public MappingException() {\r
+               super();\r
+       }\r
+\r
+       public MappingException(String message, Throwable cause) {\r
+               super(message, cause);\r
+       }\r
+\r
+       public MappingException(String message) {\r
+               super(message);\r
+       }\r
+\r
+       public MappingException(Throwable cause) {\r
+               super(cause);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/Mappings.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/Mappings.java
new file mode 100644 (file)
index 0000000..a0153d0
--- /dev/null
@@ -0,0 +1,49 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap;\r
+\r
+import org.simantics.objmap.impl.Mapping;\r
+import org.simantics.objmap.impl.UnidirectionalMapping;\r
+\r
+/**\r
+ * Static utility methods for mappings. \r
+ * @author Hannu Niemistö\r
+ */\r
+public class Mappings {\r
+       private Mappings() {}\r
+       \r
+       /**\r
+        * Creates a new mapping based on the given mapping schema. \r
+        * The created mapping is not thread-safe and will not\r
+        * listen database changes automatically.\r
+        */\r
+       public static IMapping createWithoutListening(IMappingSchema schema) {\r
+               return new Mapping(schema, false);\r
+       }\r
+       \r
+       /**\r
+     * Creates a new mapping based on the given mapping schema. \r
+     * The created mapping is not thread-safe. It listens database\r
+     * changes automatically.\r
+     */\r
+       public static IMapping createWithListening(IMappingSchema schema) {\r
+        return new Mapping(schema, true);\r
+    }\r
+       \r
+       /**\r
+        * Creates a mapping that supports only the direction from domain to range.\r
+        * Does not listen the database.\r
+        */\r
+       public static IMapping createUnidirectional(IMappingSchema schema) {\r
+           return new UnidirectionalMapping(schema);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/Composition.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/Composition.java
new file mode 100644 (file)
index 0000000..e260c94
--- /dev/null
@@ -0,0 +1,22 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target({ElementType.FIELD,ElementType.METHOD})\r
+public @interface Composition {\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/GraphType.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/GraphType.java
new file mode 100644 (file)
index 0000000..532539b
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+/**\r
+ * Specifies the domain type that the class corresponds to. \r
+ * @author Hannu Niemistö\r
+ */\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.TYPE) \r
+public @interface GraphType {\r
+       String value();\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/OptionalRelatedElements.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/OptionalRelatedElements.java
new file mode 100644 (file)
index 0000000..da74792
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.annotations.factories.OptionalRelatedElementsRuleFactory;\r
+import org.simantics.objmap.annotations.meta.HasFieldRuleFactory;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.FIELD)\r
+@HasFieldRuleFactory(OptionalRelatedElementsRuleFactory.class)\r
+public @interface OptionalRelatedElements {\r
+       String value();\r
+       boolean composition() default false;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedElement.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedElement.java
new file mode 100644 (file)
index 0000000..901db26
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.annotations.factories.RelatedElementRuleFactory;\r
+import org.simantics.objmap.annotations.meta.HasFieldRuleFactory;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.FIELD)\r
+@HasFieldRuleFactory(RelatedElementRuleFactory.class)\r
+public @interface RelatedElement {\r
+       String value();\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedElements.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedElements.java
new file mode 100644 (file)
index 0000000..d7e6885
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.annotations.factories.RelatedElementsRuleFactory;\r
+import org.simantics.objmap.annotations.meta.HasFieldRuleFactory;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.FIELD)\r
+@HasFieldRuleFactory(RelatedElementsRuleFactory.class)\r
+public @interface RelatedElements {\r
+       String value();\r
+       boolean composition() default false;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedListElements.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedListElements.java
new file mode 100644 (file)
index 0000000..0c38770
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.annotations.factories.RelatedListElementsRuleFactory;\r
+import org.simantics.objmap.annotations.meta.HasFieldRuleFactory;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.FIELD)\r
+@HasFieldRuleFactory(RelatedListElementsRuleFactory.class)\r
+public @interface RelatedListElements {\r
+    String value();\r
+}\r
+\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedOrderedSetElements.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedOrderedSetElements.java
new file mode 100644 (file)
index 0000000..21b3e17
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.annotations.factories.RelatedOrderedSetElementsRuleFactory;\r
+import org.simantics.objmap.annotations.meta.HasFieldRuleFactory;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.FIELD)\r
+@HasFieldRuleFactory(RelatedOrderedSetElementsRuleFactory.class)\r
+public @interface RelatedOrderedSetElements {\r
+       boolean composition() default false;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedValue.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/RelatedValue.java
new file mode 100644 (file)
index 0000000..23d3e9a
--- /dev/null
@@ -0,0 +1,35 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.annotations.factories.RelatedValueRuleFactory;\r
+import org.simantics.objmap.annotations.meta.HasFieldRuleFactory;\r
+import org.simantics.objmap.rules.adapters.IdentityAdapter;\r
+import org.simantics.objmap.rules.adapters.ValueAdapter;\r
+\r
+/**\r
+ * Specifies a correspondence between a field and \r
+ * functional property.\r
+ * @author Hannu Niemistö\r
+ */\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.FIELD)\r
+@HasFieldRuleFactory(RelatedValueRuleFactory.class)\r
+public @interface RelatedValue {\r
+    String value();\r
+    Class<? extends ValueAdapter> adapter() default IdentityAdapter.class;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/UpdateMethod.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/UpdateMethod.java
new file mode 100644 (file)
index 0000000..f8431f5
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.annotations.factories.UpdateMethodFactory;\r
+import org.simantics.objmap.annotations.meta.HasMethodRuleFactory;\r
+\r
+/**\r
+ * Specifies that the annotated method should be called\r
+ * to update range object.\r
+ * @author Hannu Niemistö\r
+ */\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.METHOD)\r
+@HasMethodRuleFactory(UpdateMethodFactory.class)\r
+public @interface UpdateMethod {\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/DataTypeUtils.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/DataTypeUtils.java
new file mode 100644 (file)
index 0000000..97cbf18
--- /dev/null
@@ -0,0 +1,57 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.factories;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.layer0.Layer0;\r
+\r
+public class DataTypeUtils {\r
+    \r
+    public static Resource dataTypeOfClass(ReadGraph g, Class<?> clazz) {\r
+        Layer0 b = Layer0.getInstance(g);\r
+        if(clazz.equals(Double.class) || clazz.equals(double.class))\r
+            return b.Double;\r
+        else if(clazz.equals(String.class))\r
+            return b.String;\r
+        else if(clazz.equals(Integer.class) || clazz.equals(int.class))\r
+            return b.Integer;\r
+        else if(clazz.equals(Float.class) || clazz.equals(float.class))\r
+            return b.Float;\r
+        else if(clazz.equals(Boolean.class) || clazz.equals(boolean.class))\r
+            return b.Boolean;\r
+        else if(clazz.equals(Long.class) || clazz.equals(long.class))\r
+            return b.Long;\r
+        else if(clazz.equals(Byte.class) || clazz.equals(byte.class))\r
+            return b.Byte;\r
+        \r
+        else if(clazz.equals(double[].class))\r
+            return b.DoubleArray;\r
+        else if(clazz.equals(int[].class))\r
+            return b.IntegerArray;\r
+        else if(clazz.equals(byte[].class))\r
+            return b.ByteArray;\r
+        else if(clazz.equals(float[].class))\r
+            return b.FloatArray;\r
+        else if(clazz.equals(boolean[].class))\r
+            return b.BooleanArray;\r
+        else if(clazz.equals(String[].class))\r
+            return b.StringArray;\r
+        else if(clazz.equals(long[].class))\r
+            return b.LongArray;\r
+        else {\r
+               System.out.println("Couldn't find a data type for " + clazz);\r
+            return null;\r
+        }\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/OptionalRelatedElementsRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/OptionalRelatedElementsRuleFactory.java
new file mode 100644 (file)
index 0000000..e1974fe
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.factories;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.exception.ValidationException;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.annotations.OptionalRelatedElements;\r
+import org.simantics.objmap.rules.MappedElementsRule;\r
+import org.simantics.objmap.rules.domain.RelatedObjectsAccessor;\r
+import org.simantics.objmap.rules.factory.IFieldRuleFactory;\r
+import org.simantics.objmap.rules.range.FieldAccessorWithDefault;\r
+\r
+public class OptionalRelatedElementsRuleFactory implements IFieldRuleFactory {\r
+\r
+    @Override\r
+    public IMappingRule create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException, ValidationException, ServiceException {\r
+        OptionalRelatedElements annotation = (OptionalRelatedElements)_annotation;\r
+        return new MappedElementsRule(\r
+                new RelatedObjectsAccessor(g.getResource(annotation.value()),\r
+                        annotation.composition()),\r
+                new FieldAccessorWithDefault<Collection<Object>>(field, Collections.emptyList())\r
+                );\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedElementRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedElementRuleFactory.java
new file mode 100644 (file)
index 0000000..6d128ea
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.factories;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.exception.ValidationException;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.rules.MappedElementRule;\r
+import org.simantics.objmap.rules.domain.RelatedObjectAccessor;\r
+import org.simantics.objmap.rules.factory.IFieldRuleFactory;\r
+import org.simantics.objmap.rules.range.FieldAccessor;\r
+\r
+public class RelatedElementRuleFactory implements IFieldRuleFactory {\r
+\r
+    @Override\r
+    public IMappingRule create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException, ValidationException, ServiceException {\r
+        RelatedElement annotation = (RelatedElement)_annotation;\r
+        return new MappedElementRule(\r
+                new RelatedObjectAccessor(g.getResource(annotation.value())),\r
+                new FieldAccessor<Object>(field)\r
+                );\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedElementsRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedElementsRuleFactory.java
new file mode 100644 (file)
index 0000000..4412785
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.factories;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.exception.ValidationException;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.objmap.rules.MappedElementsRule;\r
+import org.simantics.objmap.rules.domain.RelatedObjectsAccessor;\r
+import org.simantics.objmap.rules.factory.IFieldRuleFactory;\r
+import org.simantics.objmap.rules.range.FieldAccessor;\r
+\r
+public class RelatedElementsRuleFactory implements IFieldRuleFactory {\r
+\r
+    @Override\r
+    public IMappingRule create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException, ValidationException, ServiceException {\r
+        RelatedElements annotation = (RelatedElements)_annotation;\r
+        return new MappedElementsRule(\r
+                new RelatedObjectsAccessor(g.getResource(annotation.value()),\r
+                        annotation.composition()),\r
+                new FieldAccessor<Collection<Object>>(field)\r
+                );\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedListElementsRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedListElementsRuleFactory.java
new file mode 100644 (file)
index 0000000..eff5354
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.factories;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.exception.ValidationException;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.annotations.RelatedListElements;\r
+import org.simantics.objmap.rules.MappedElementsRule;\r
+import org.simantics.objmap.rules.domain.RelatedListElementsAccessor;\r
+import org.simantics.objmap.rules.factory.IFieldRuleFactory;\r
+import org.simantics.objmap.rules.range.FieldAccessor;\r
+\r
+public class RelatedListElementsRuleFactory  implements IFieldRuleFactory {\r
+\r
+    @Override\r
+    public IMappingRule create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException, ValidationException, ServiceException {\r
+        RelatedListElements annotation = (RelatedListElements)_annotation;\r
+        return new MappedElementsRule(\r
+                new RelatedListElementsAccessor(g.getResource(annotation.value())),\r
+                new FieldAccessor<Collection<Object>>(field)\r
+                );\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedOrderedSetElementsRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedOrderedSetElementsRuleFactory.java
new file mode 100644 (file)
index 0000000..fb78847
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.factories;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.exception.ValidationException;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.annotations.RelatedOrderedSetElements;\r
+import org.simantics.objmap.rules.MappedElementsRule;\r
+import org.simantics.objmap.rules.domain.RelatedOrderedSetElementsAccessor;\r
+import org.simantics.objmap.rules.factory.IFieldRuleFactory;\r
+import org.simantics.objmap.rules.range.FieldAccessor;\r
+\r
+public class RelatedOrderedSetElementsRuleFactory implements IFieldRuleFactory {\r
+\r
+    @Override\r
+    public IMappingRule create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException, ValidationException, ServiceException {\r
+        RelatedOrderedSetElements annotation = (RelatedOrderedSetElements)_annotation;\r
+        return new MappedElementsRule(\r
+                new RelatedOrderedSetElementsAccessor(annotation.composition()),\r
+                new FieldAccessor<Collection<Object>>(field)\r
+                );\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedValueRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/RelatedValueRuleFactory.java
new file mode 100644 (file)
index 0000000..828bb59
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.factories;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.exception.ValidationException;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.objmap.rules.ValueRule;\r
+import org.simantics.objmap.rules.adapters.IdentityAdapter;\r
+import org.simantics.objmap.rules.adapters.ValueAdapter;\r
+import org.simantics.objmap.rules.domain.RelatedValueAccessor;\r
+import org.simantics.objmap.rules.factory.IFieldRuleFactory;\r
+import org.simantics.objmap.rules.range.AdaptedRangeAccessor;\r
+import org.simantics.objmap.rules.range.FieldAccessor;\r
+import org.simantics.objmap.rules.range.IRangeAccessor;\r
+\r
+public class RelatedValueRuleFactory implements IFieldRuleFactory {\r
+\r
+    @Override\r
+    public IMappingRule create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException,\r
+            ValidationException, ServiceException {\r
+        RelatedValue annotation = (RelatedValue) _annotation;\r
+        Class<? extends ValueAdapter> adapterClass = annotation.adapter();\r
+        IRangeAccessor<Object> rangeAccessor = new FieldAccessor<Object>(field);\r
+        Resource valueType;\r
+        if (adapterClass == IdentityAdapter.class) {\r
+            valueType = DataTypeUtils.dataTypeOfClass(g, field.getType());\r
+        } else {\r
+            try {\r
+                ValueAdapter adapter = adapterClass.newInstance();\r
+                rangeAccessor = new AdaptedRangeAccessor(rangeAccessor, adapter);\r
+                valueType = adapter.rangeTypeToDomainType(g, field.getType());\r
+            } catch (InstantiationException e) {\r
+                throw new RuntimeException(e);\r
+            } catch (IllegalAccessException e) {\r
+                throw new RuntimeException(e);\r
+            }\r
+        }\r
+        return new ValueRule(new RelatedValueAccessor(g.getResource(annotation.value()), valueType), rangeAccessor);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/UpdateMethodFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/factories/UpdateMethodFactory.java
new file mode 100644 (file)
index 0000000..5cab576
--- /dev/null
@@ -0,0 +1,62 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.factories;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Method;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.IFunction;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.MappingException;\r
+import org.simantics.objmap.rules.factory.IMethodRuleFactory;\r
+\r
+public class UpdateMethodFactory implements IMethodRuleFactory {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+    @Override\r
+    public IMappingRule create(ReadGraph g, \r
+            Annotation annotation, \r
+            final Method method)\r
+            throws DatabaseException {\r
+        method.setAccessible(true);\r
+        return new IMappingRule() {\r
+            \r
+            @Override\r
+            public boolean updateRange(ReadGraph g, IFunction<Resource, Object> map,\r
+                    Resource domainElement, Object rangeElement)\r
+                    throws MappingException {\r
+                LOGGER.info("    UpdateMethodFactory.updateRange");      \r
+                try {\r
+                    return (Boolean)method.invoke(rangeElement, g, domainElement);\r
+                } catch (Exception e) {\r
+                    // TODO Auto-generated catch block\r
+                    e.printStackTrace();\r
+                }\r
+                return false;\r
+            }\r
+            \r
+            @Override\r
+            public boolean updateDomain(WriteGraph g, IFunction<Object, Resource> map,\r
+                    Resource domainElement, Object rangeElement)\r
+                    throws MappingException {\r
+                return false;\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasClassRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasClassRuleFactory.java
new file mode 100644 (file)
index 0000000..304c8e2
--- /dev/null
@@ -0,0 +1,25 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.meta;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.rules.factory.IClassRuleFactory;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.ANNOTATION_TYPE) \r
+public @interface HasClassRuleFactory {\r
+    Class<? extends IClassRuleFactory> value();\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasFieldRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasFieldRuleFactory.java
new file mode 100644 (file)
index 0000000..877606a
--- /dev/null
@@ -0,0 +1,25 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.meta;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.rules.factory.IFieldRuleFactory;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.ANNOTATION_TYPE) \r
+public @interface HasFieldRuleFactory {\r
+    Class<? extends IFieldRuleFactory> value();\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasMethodRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/annotations/meta/HasMethodRuleFactory.java
new file mode 100644 (file)
index 0000000..ecdc521
--- /dev/null
@@ -0,0 +1,25 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.annotations.meta;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.rules.factory.IMethodRuleFactory;\r
+\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.ANNOTATION_TYPE) \r
+public @interface HasMethodRuleFactory {\r
+    Class<? extends IMethodRuleFactory> value();\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/impl/Link.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/impl/Link.java
new file mode 100644 (file)
index 0000000..42aed77
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+/**\r
+ * \r
+ */\r
+package org.simantics.objmap.impl;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.objmap.ILinkType;\r
+\r
+/**\r
+ * An indication that the domain element corresponds to the range element\r
+ * in the mapping. The link type describes how source and target objects\r
+ * are updated. There are additionally flags for dirtiness of the link.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class Link {\r
+       public ILinkType type;\r
+       public Resource domainElement;\r
+       public Object rangeElement;\r
+       \r
+       public boolean domainModified = false;\r
+       public boolean rangeModified = false;\r
+       public boolean removed = false;\r
+       \r
+       public Link(ILinkType type, Resource domainElement, Object rangeElement) {\r
+               this.type = type;\r
+               this.domainElement = domainElement;\r
+               this.rangeElement = rangeElement;               \r
+       }               \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/impl/Mapping.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/impl/Mapping.java
new file mode 100644 (file)
index 0000000..abb726e
--- /dev/null
@@ -0,0 +1,426 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.impl;\r
+\r
+import gnu.trove.THashMap;\r
+import gnu.trove.TObjectIdentityHashingStrategy;\r
+\r
+import java.util.AbstractSet;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Iterator;\r
+import java.util.Set;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.IFunction;\r
+import org.simantics.objmap.ILinkType;\r
+import org.simantics.objmap.IMapping;\r
+import org.simantics.objmap.IMappingListener;\r
+import org.simantics.objmap.IMappingSchema;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * An implementation of IMapping. The class should not be created\r
+ * directly but using methods in Mappings.\r
+ * @see org.simantics.objmap.Mappings\r
+ * @author Hannu Niemistö\r
+ */\r
+public class Mapping implements IMapping {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+       private static final TObjectIdentityHashingStrategy<Object> IDENTITY_HASHING =\r
+               new TObjectIdentityHashingStrategy<Object>();\r
+       \r
+       IMappingSchema schema;\r
+       \r
+       THashMap<Resource, Link> domain = new THashMap<Resource, Link>();\r
+       THashMap<Object, Link> range = new THashMap<Object, Link>(IDENTITY_HASHING);\r
+       ArrayList<IMappingListener> listeners = new ArrayList<IMappingListener>();\r
+       \r
+       ArrayList<Link> modifiedDomainLinks = new ArrayList<Link>();\r
+       ArrayList<Link> modifiedRangeLinks = new ArrayList<Link>();\r
+       boolean disposed = false;\r
+       \r
+       boolean listensDomain; \r
+       \r
+       public Mapping(IMappingSchema schema, boolean listensDomain) {\r
+               this.schema = schema;\r
+               this.listensDomain = listensDomain;\r
+       }\r
+\r
+       private void removeLink(Link link) {\r
+               if(link.domainModified)\r
+                       modifiedDomainLinks.remove(link);\r
+               if(link.rangeModified)\r
+                       modifiedRangeLinks.remove(link);\r
+               link.removed = true;\r
+       }\r
+       \r
+       private void createDomain(WriteGraph g, Link link) throws MappingException {\r
+           LOGGER.info("        createDomain for " + link.rangeElement);\r
+               ILinkType type = schema.linkTypeOfRangeElement(link.rangeElement);\r
+               Resource domainElement = type.createDomainElement(g, link.rangeElement);\r
+               \r
+               link.type = type;\r
+               link.domainElement = domainElement;\r
+               domain.put(domainElement, link);\r
+               \r
+        // TODO Should we do this only if the mapping is listening?\r
+        domainModified(link);\r
+       }\r
+       \r
+       private void createRange(ReadGraph g, Link link) throws MappingException {\r
+               ILinkType type = schema.linkTypeOfDomainElement(g, link.domainElement);         \r
+               Object rangeElement = type.createRangeElement(g, link.domainElement);\r
+               \r
+               link.type = type;\r
+               link.rangeElement = rangeElement;\r
+               range.put(rangeElement, link);\r
+       }\r
+       \r
+       Set<Resource> domainSet = new AbstractSet<Resource>() {\r
+\r
+               public boolean add(Resource e) {\r
+                       if(domain.containsKey(e))\r
+                               return false;\r
+                       Link link = new Link(null, e, null);\r
+                       domain.put(e, link);\r
+                       modifiedDomainLinks.add(link);\r
+                       return true;\r
+               }\r
+               \r
+               public boolean contains(Object o) {\r
+                       return domain.contains(o);\r
+               }\r
+               \r
+               public boolean remove(Object o) {\r
+                       Link link = domain.remove(o);                   \r
+                       if(link == null)\r
+                               return false;\r
+                       removeLink(link);\r
+                       if(link.rangeElement != null)\r
+                               range.remove(link.rangeElement);\r
+                       return true;    \r
+               }\r
+               \r
+               @Override\r
+               public Iterator<Resource> iterator() {\r
+                   // FIXME does not implement Iterator.remove correctly\r
+                       return domain.keySet().iterator();\r
+               }\r
+\r
+               @Override\r
+               public int size() {\r
+                       return domain.size();\r
+               }\r
+               \r
+       };\r
+       \r
+       Set<Object> rangeSet = new AbstractSet<Object>() {\r
+\r
+               public boolean add(Object e) {\r
+                       if(range.containsKey(e))\r
+                               return false;\r
+                       Link link = new Link(null, null, e);\r
+                       range.put(e, link);\r
+                       modifiedRangeLinks.add(link);\r
+                       return true;\r
+               }\r
+               \r
+               public boolean contains(Object o) {\r
+                       return range.contains(o);\r
+               }\r
+               \r
+               public boolean remove(Object o) {\r
+                       Link link = range.remove(o);                    \r
+                       if(link == null)\r
+                               return false;\r
+                       removeLink(link);\r
+                       if(link.domainElement != null)\r
+                               domain.remove(link.domainElement);\r
+                       return true;\r
+               }\r
+               \r
+               @Override\r
+               public Iterator<Object> iterator() {\r
+                   // FIXME does not implement Iterator.remove correctly\r
+                       return range.keySet().iterator();\r
+               }\r
+\r
+               @Override\r
+               public int size() {\r
+                       return range.size();\r
+               }\r
+               \r
+       };\r
+       \r
+       class DomainToRange implements IFunction<Resource, Object> {\r
+\r
+               ReadGraph g;\r
+               \r
+               public DomainToRange(ReadGraph g) {\r
+                       this.g = g;\r
+               }\r
+\r
+               @Override\r
+               public Object get(Resource element) throws MappingException {\r
+                       Link link = domain.get(element);\r
+                       if(link == null) {\r
+                           link = new Link(null, element, null);\r
+                   link.domainModified = true;\r
+                   modifiedDomainLinks.add(link);\r
+                           domain.put(element, link);           \r
+                           createRange(g, link);       \r
+                       }\r
+                       else if(link.type == null) \r
+                               createRange(g, link);\r
+            return link.rangeElement;\r
+               }\r
+               \r
+       };\r
+       \r
+       class RangeToDomain implements IFunction<Object, Resource> {\r
+\r
+               WriteGraph g;\r
+               \r
+               public RangeToDomain(WriteGraph g) {\r
+                       this.g = g;\r
+               }\r
+               \r
+               @Override\r
+               public Resource get(Object element) throws MappingException {\r
+                       Link link = range.get(element);\r
+                       if(link == null) {\r
+                           link = new Link(null, null, element);\r
+                           link.rangeModified = true;\r
+                modifiedRangeLinks.add(link);\r
+                           range.put(element, link);\r
+                           createDomain(g, link);                              \r
+                       }\r
+                       else if(link.type == null)\r
+                               createDomain(g, link);\r
+                       return link.domainElement;\r
+               }\r
+               \r
+       };\r
+       \r
+       @Override\r
+       public Set<Resource> getDomain() {\r
+               return domainSet;\r
+       }\r
+       \r
+       @Override\r
+       public Set<Object> getRange() {\r
+               return rangeSet;\r
+       }\r
+       \r
+       @Override\r
+       public synchronized Collection<Resource> updateDomain(WriteGraph g) throws MappingException {\r
+           LOGGER.info("Mapping.updateDomain");\r
+               RangeToDomain map = new RangeToDomain(g);\r
+               ArrayList<Resource> updated = new ArrayList<Resource>();\r
+               while(!modifiedRangeLinks.isEmpty()) {\r
+                   LOGGER.info("    modifiedRangeLinks.size() = " + modifiedRangeLinks.size());\r
+                   \r
+                       Link link = modifiedRangeLinks.remove(modifiedRangeLinks.size()-1);\r
+                       link.rangeModified = false;\r
+                       /*if(link.domainModified) {\r
+                               link.domainModified = false;\r
+                               modifiedDomainLinks.remove(link);\r
+                       }*/\r
+                       \r
+                       if(link.type == null) {\r
+                               createDomain(g, link);\r
+                       }\r
+                       \r
+                       if(link.type.updateDomain(g, map, link.domainElement, link.rangeElement))\r
+                               updated.add(link.domainElement);\r
+               }               \r
+               return updated;\r
+       }\r
+       \r
+       @Override\r
+       public synchronized Collection<Object> updateRange(ReadGraph g) throws MappingException {\r
+           LOGGER.info("Mapping.updateRange");\r
+               DomainToRange map = new DomainToRange(g);\r
+               ArrayList<Object> updated = new ArrayList<Object>();\r
+               while(!modifiedDomainLinks.isEmpty()) {             \r
+                   LOGGER.info("    modifiedDomainLinks.size() = " + modifiedDomainLinks.size());\r
+                   \r
+                       Link link = modifiedDomainLinks.remove(modifiedDomainLinks.size()-1);\r
+                       link.domainModified = false;\r
+                       /*if(link.rangeModified) {\r
+                               link.rangeModified = false;\r
+                               modifiedRangeLinks.remove(link);\r
+                       }*/\r
+                       \r
+                       if(link.type == null) {\r
+                               createRange(g, link);\r
+                       }\r
+                       \r
+                       if(listensDomain) {\r
+                           RangeUpdateRequest request = new RangeUpdateRequest(link, map, this);\r
+                           try {\r
+                    boolean modified = g.syncRequest(request, request);\r
+                    if(modified) {\r
+                        updated.add(link.rangeElement);\r
+                    }\r
+                } catch (DatabaseException e) {\r
+                    throw new MappingException(e);\r
+                }\r
+\r
+                       }\r
+                       else\r
+                           if(link.type.updateRange(g, map, link.domainElement, link.rangeElement))\r
+                               updated.add(link.rangeElement);\r
+               }       \r
+               return updated;\r
+       }\r
+\r
+       @Override\r
+       public Object get(Resource domainElement) {\r
+               Link link = domain.get(domainElement);\r
+               if(link == null)\r
+                       return null;\r
+               return link.rangeElement;\r
+       }\r
+\r
+       @Override\r
+       public Resource inverseGet(Object rangeElement) {\r
+               Link link = range.get(rangeElement);\r
+               if(link == null)\r
+                       return null;\r
+               return link.domainElement;\r
+       }\r
+\r
+       @Override\r
+       public Resource inverseMap(WriteGraph g, Object rangeElement) throws MappingException {\r
+               getRange().add(rangeElement);\r
+               updateDomain(g);\r
+               return inverseGet(rangeElement);\r
+       }\r
+\r
+       @Override\r
+       public Object map(ReadGraph g, Resource domainElement) throws MappingException {\r
+               getDomain().add(domainElement);\r
+               updateRange(g);\r
+               return get(domainElement);\r
+       }\r
+\r
+       void domainModified(Link link) {\r
+           if(!link.domainModified) {          \r
+               synchronized(modifiedDomainLinks) {\r
+                   LOGGER.info("        domainModified for " + link.rangeElement);\r
+                link.domainModified = true;\r
+                modifiedDomainLinks.add(link);\r
+                if(modifiedDomainLinks.size() == 1) {\r
+                    for(IMappingListener listener : listeners)\r
+                        listener.domainModified();\r
+                }\r
+               }\r
+        }\r
+       }\r
+       \r
+       @Override\r
+       public void domainModified(Resource domainElement) {\r
+               Link link = domain.get(domainElement);\r
+               if(link != null)\r
+                   domainModified(link);\r
+       }\r
+\r
+       void rangeModified(Link link) {\r
+           if(!link.rangeModified) {\r
+               synchronized(modifiedRangeLinks) {\r
+                link.rangeModified = true;\r
+                modifiedRangeLinks.add(link);\r
+                if(modifiedRangeLinks.size() == 1) {\r
+                    for(IMappingListener listener : listeners)\r
+                        listener.rangeModified();\r
+                }\r
+               }\r
+        }\r
+       }\r
+       \r
+       @Override\r
+       public void rangeModified(Object rangeElement) {\r
+               Link link = range.get(rangeElement);\r
+               if(link != null)\r
+                   rangeModified(link);\r
+       }\r
+\r
+       @Override\r
+       public boolean isDomainModified() {\r
+               return !modifiedDomainLinks.isEmpty();\r
+       }\r
+\r
+       @Override\r
+       public boolean isRangeModified() {\r
+               return !modifiedRangeLinks.isEmpty();\r
+       }\r
+\r
+       @Override\r
+       public void addMappingListener(IMappingListener listener) {\r
+               listeners.add(listener);\r
+       }\r
+\r
+       @Override\r
+       public void removeMappingListener(IMappingListener listener) {\r
+               listeners.remove(listener);             \r
+       }\r
+\r
+       @Override\r
+       public Collection<Resource> getConflictingDomainElements() {\r
+               ArrayList<Resource> result = new ArrayList<Resource>();\r
+               if(modifiedDomainLinks.size() < modifiedRangeLinks.size()) {\r
+                       for(Link link : modifiedDomainLinks)\r
+                               if(link.rangeModified)\r
+                                       result.add(link.domainElement);\r
+               }\r
+               else {\r
+                       for(Link link : modifiedRangeLinks)\r
+                               if(link.domainModified)\r
+                                       result.add(link.domainElement);\r
+               }\r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public Collection<Object> getConflictingRangeElements() {\r
+               ArrayList<Object> result = new ArrayList<Object>();\r
+               if(modifiedDomainLinks.size() < modifiedRangeLinks.size()) {\r
+                       for(Link link : modifiedDomainLinks)\r
+                               if(link.rangeModified)\r
+                                       result.add(link.rangeElement);\r
+               }\r
+               else {\r
+                       for(Link link : modifiedRangeLinks)\r
+                               if(link.domainModified)\r
+                                       result.add(link.rangeElement);\r
+               }\r
+               return result;\r
+       }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        disposed = true;\r
+    }\r
+    \r
+    public boolean isDisposed() {\r
+        return disposed;\r
+    }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/impl/RangeUpdateRequest.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/impl/RangeUpdateRequest.java
new file mode 100644 (file)
index 0000000..4c19065
--- /dev/null
@@ -0,0 +1,75 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.impl;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.SyncListener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.objmap.IFunction;\r
+import org.simantics.objmap.MappingException;\r
+\r
+public class RangeUpdateRequest implements Read<Boolean>, SyncListener<Boolean> {\r
+\r
+    Link link;\r
+    /*\r
+     * Note that this map uses a read request that it has got from caller and \r
+     * not the one that is used in updateRange. This is intentional.\r
+     */\r
+    IFunction<Resource, Object> map; // map==null is used to flag that request is performed once\r
+    Mapping mapping; // mapping==null is used as a flag the request disposed\r
+    \r
+    public RangeUpdateRequest(Link link, IFunction<Resource, Object> map, Mapping mapping) {\r
+        this.link = link;\r
+        this.map = map;\r
+        this.mapping = mapping;\r
+    }\r
+\r
+    @Override\r
+    public Boolean perform(ReadGraph g) throws DatabaseException {\r
+        if(map != null) {\r
+            boolean updated = link.type.updateRange(g, map, link.domainElement, link.rangeElement);\r
+            map = null;\r
+            return updated;\r
+        }\r
+        else if(mapping != null) {\r
+            mapping.domainModified(link);\r
+            mapping = null;\r
+            return Boolean.FALSE;\r
+        }\r
+        else\r
+            return null;\r
+    }\r
+    \r
+    @Override\r
+    public void exception(ReadGraph graph, Throwable throwable)\r
+            throws DatabaseException {\r
+        if(throwable instanceof DatabaseException)\r
+            throw (DatabaseException)throwable;\r
+        else\r
+            throw new MappingException(throwable);\r
+    }\r
+\r
+    @Override\r
+    public void execute(ReadGraph graph, Boolean result)\r
+            throws DatabaseException {       \r
+    }\r
+\r
+    @Override\r
+    public boolean isDisposed() {\r
+        return mapping == null || link.removed || mapping.isDisposed();\r
+    }\r
+    \r
+    \r
+    \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/impl/UnidirectionalMapping.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/impl/UnidirectionalMapping.java
new file mode 100644 (file)
index 0000000..fd41f40
--- /dev/null
@@ -0,0 +1,265 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.impl;\r
+\r
+import gnu.trove.THashMap;\r
+import gnu.trove.TObjectIdentityHashingStrategy;\r
+\r
+import java.util.AbstractSet;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Iterator;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.objmap.IFunction;\r
+import org.simantics.objmap.ILinkType;\r
+import org.simantics.objmap.IMapping;\r
+import org.simantics.objmap.IMappingListener;\r
+import org.simantics.objmap.IMappingSchema;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * An implementation of IMapping. The class should not be created\r
+ * directly but using methods in Mappings.\r
+ * @see org.simantics.objmap.Mappings\r
+ * @author Hannu Niemistö\r
+ */\r
+public class UnidirectionalMapping implements IMapping {\r
+\r
+       private static final TObjectIdentityHashingStrategy<Object> IDENTITY_HASHING =\r
+               new TObjectIdentityHashingStrategy<Object>();\r
+       \r
+       IMappingSchema schema;\r
+       \r
+       THashMap<Resource, Link> domain = new THashMap<Resource, Link>();\r
+       ArrayList<IMappingListener> listeners = new ArrayList<IMappingListener>();\r
+       \r
+       ArrayList<Link> modifiedDomainLinks = new ArrayList<Link>();\r
+       boolean disposed = false;\r
+       \r
+       public UnidirectionalMapping(IMappingSchema schema) {\r
+               this.schema = schema;\r
+       }\r
+\r
+       private void removeLink(Link link) {\r
+               if(link.domainModified)\r
+                       modifiedDomainLinks.remove(link);\r
+               link.removed = true;\r
+       }\r
+       \r
+       private void createDomain(WriteGraph g, Link link) throws MappingException {\r
+               ILinkType type = schema.linkTypeOfRangeElement(link.rangeElement);\r
+               Resource domainElement = type.createDomainElement(g, link.rangeElement);\r
+               \r
+               link.type = type;\r
+               link.domainElement = domainElement;\r
+               domain.put(domainElement, link);\r
+       }\r
+       \r
+       private void createRange(ReadGraph g, Link link) throws MappingException {\r
+               ILinkType type = schema.linkTypeOfDomainElement(g, link.domainElement);         \r
+               Object rangeElement = type.createRangeElement(g, link.domainElement);\r
+               \r
+               link.type = type;\r
+               link.rangeElement = rangeElement;\r
+       }\r
+       \r
+       Set<Resource> domainSet = new AbstractSet<Resource>() {\r
+\r
+               public boolean add(Resource e) {\r
+                       if(domain.containsKey(e))\r
+                               return false;\r
+                       Link link = new Link(null, e, null);\r
+                       domain.put(e, link);\r
+                       modifiedDomainLinks.add(link);\r
+                       return true;\r
+               }\r
+               \r
+               public boolean contains(Object o) {\r
+                       return domain.contains(o);\r
+               }\r
+               \r
+               public boolean remove(Object o) {\r
+                       Link link = domain.remove(o);                   \r
+                       if(link == null)\r
+                               return false;\r
+                       removeLink(link);\r
+                       return true;    \r
+               }\r
+               \r
+               @Override\r
+               public Iterator<Resource> iterator() {\r
+                   // FIXME does not implement Iterator.remove correctly\r
+                       return domain.keySet().iterator();\r
+               }\r
+\r
+               @Override\r
+               public int size() {\r
+                       return domain.size();\r
+               }\r
+               \r
+       };\r
+       \r
+       class DomainToRange implements IFunction<Resource, Object> {\r
+\r
+               ReadGraph g;\r
+               \r
+               public DomainToRange(ReadGraph g) {\r
+                       this.g = g;\r
+               }\r
+\r
+               @Override\r
+               public Object get(Resource element) throws MappingException {\r
+                       Link link = domain.get(element);\r
+                       if(link == null) {\r
+                               ILinkType type = schema.linkTypeOfDomainElement(g, element);\r
+                               Object rangeElement = type.createRangeElement(g, element);\r
+                               \r
+                               link = new Link(type, element, rangeElement);\r
+                               domain.put(element, link);              \r
+                               link.domainModified = true;\r
+                               modifiedDomainLinks.add(link);\r
+                               \r
+                               return rangeElement;                            \r
+                       }\r
+                       else {\r
+                               if(link.type == null) \r
+                                       createRange(g, link);\r
+                               return link.rangeElement;\r
+                       }\r
+               }\r
+               \r
+       };\r
+       \r
+       @Override\r
+       public Set<Resource> getDomain() {\r
+               return domainSet;\r
+       }\r
+       \r
+       @Override\r
+       public Set<Object> getRange() {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public Collection<Resource> updateDomain(WriteGraph g) throws MappingException {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       @Override\r
+       public Collection<Object> updateRange(ReadGraph g) throws MappingException {\r
+               DomainToRange map = new DomainToRange(g);\r
+               ArrayList<Object> updated = new ArrayList<Object>();\r
+               while(!modifiedDomainLinks.isEmpty()) {\r
+                       Link link = modifiedDomainLinks.remove(modifiedDomainLinks.size()-1);\r
+                       link.domainModified = false;                    \r
+                       if(link.type == null) {\r
+                               createRange(g, link);\r
+                       }\r
+                       \r
+                       link.type.updateRange(g, map, link.domainElement, link.rangeElement);\r
+                       updated.add(link.rangeElement);\r
+               }       \r
+               return updated;\r
+       }\r
+\r
+       @Override\r
+       public Object get(Resource domainElement) {\r
+               Link link = domain.get(domainElement);\r
+               if(link == null)\r
+                       return null;\r
+               return link.rangeElement;\r
+       }\r
+\r
+       @Override\r
+       public Resource inverseGet(Object rangeElement) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+\r
+       @Override\r
+       public Resource inverseMap(WriteGraph g, Object rangeElement) throws MappingException {\r
+           throw new UnsupportedOperationException();\r
+       }\r
+\r
+       @Override\r
+       public Object map(ReadGraph g, Resource domainElement) throws MappingException {\r
+               getDomain().add(domainElement);\r
+               updateRange(g);\r
+               return get(domainElement);\r
+       }\r
+\r
+       void domainModified(Link link) {\r
+           if(!link.domainModified) {\r
+            link.domainModified = true;\r
+            modifiedDomainLinks.add(link);\r
+            if(modifiedDomainLinks.size() == 1) {\r
+                for(IMappingListener listener : listeners)\r
+                    listener.domainModified();\r
+            }\r
+        }\r
+       }\r
+       \r
+       @Override\r
+       public void domainModified(Resource domainElement) {\r
+               Link link = domain.get(domainElement);\r
+               if(link != null)\r
+                   domainModified(link);\r
+       }\r
+\r
+       @Override\r
+       public boolean isDomainModified() {\r
+               return !modifiedDomainLinks.isEmpty();\r
+       }\r
+\r
+       @Override\r
+       public boolean isRangeModified() {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+\r
+       @Override\r
+       public void addMappingListener(IMappingListener listener) {\r
+               listeners.add(listener);\r
+       }\r
+\r
+       @Override\r
+       public void removeMappingListener(IMappingListener listener) {\r
+               listeners.remove(listener);             \r
+       }\r
+\r
+       @Override\r
+       public Collection<Resource> getConflictingDomainElements() {\r
+           throw new UnsupportedOperationException();\r
+       }\r
+\r
+       @Override\r
+       public Collection<Object> getConflictingRangeElements() {\r
+           throw new UnsupportedOperationException();\r
+       }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        disposed = true;\r
+    }\r
+    \r
+    public boolean isDisposed() {\r
+        return disposed;\r
+    }\r
+\r
+    @Override\r
+    public void rangeModified(Object rangeElement) {\r
+        throw new UnsupportedOperationException();\r
+    }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/MappedElementRule.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/MappedElementRule.java
new file mode 100644 (file)
index 0000000..9ce3359
--- /dev/null
@@ -0,0 +1,62 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.objmap.IFunction;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.MappingException;\r
+import org.simantics.objmap.rules.domain.IDomainAccessor;\r
+import org.simantics.objmap.rules.range.IRangeAccessor;\r
+\r
+/**\r
+ * A rule that synchronizes collection of elements between\r
+ * domain and range accessors. Elements are mapped from\r
+ * between domain and range during the synchronization.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class MappedElementRule implements IMappingRule {\r
+    \r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+       IDomainAccessor<Resource> domainAccessor;\r
+       IRangeAccessor<Object> rangeAccessor;\r
+       \r
+       public MappedElementRule(IDomainAccessor<Resource> domainAccessor,\r
+            IRangeAccessor<Object> rangeAccessor) {\r
+        this.domainAccessor = domainAccessor;\r
+        this.rangeAccessor = rangeAccessor;\r
+    }\r
+\r
+    @Override\r
+       public boolean updateDomain(WriteGraph g, IFunction<Object, Resource> map,\r
+                       Resource domainElement, Object rangeElement)\r
+                       throws MappingException {\r
+        LOGGER.info("    MappedElementRule.updateDomain");\r
+           Object value = rangeAccessor.get(rangeElement);\r
+           Resource mappedValue = value == null ? null : map.get(value);\r
+               return domainAccessor.set(g, domainElement, mappedValue);\r
+       }\r
+\r
+       @Override\r
+       public boolean updateRange(ReadGraph g, IFunction<Resource, Object> map,\r
+                       Resource domainElement, Object rangeElement)\r
+                       throws MappingException {\r
+        LOGGER.info("    MappedElementRule.updateRange");   \r
+           Resource value = domainAccessor.get(g, domainElement);\r
+        Object mappedValue = value == null ? null : map.get(value);\r
+        return rangeAccessor.set(rangeElement, mappedValue);\r
+       }       \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/MappedElementsRule.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/MappedElementsRule.java
new file mode 100644 (file)
index 0000000..750926d
--- /dev/null
@@ -0,0 +1,73 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.objmap.IFunction;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.MappingException;\r
+import org.simantics.objmap.rules.domain.IDomainAccessor;\r
+import org.simantics.objmap.rules.range.IRangeAccessor;\r
+\r
+/**\r
+ * A rule that synchronizes collection of elements between\r
+ * domain and range accessors. Elements are mapped from\r
+ * between domain and range during the synchronization.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class MappedElementsRule implements IMappingRule {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+\r
+    IDomainAccessor<Collection<Resource>> domainAccessor;\r
+    IRangeAccessor<Collection<Object>> rangeAccessor;\r
+\r
+    public MappedElementsRule(IDomainAccessor<Collection<Resource>> domainAccessor,\r
+            IRangeAccessor<Collection<Object>> rangeAccessor) {\r
+        this.domainAccessor = domainAccessor;\r
+        this.rangeAccessor = rangeAccessor;\r
+    }\r
+\r
+    @Override\r
+    public boolean updateDomain(WriteGraph g, IFunction<Object, Resource> map,\r
+            Resource domainElement, Object rangeElement)\r
+    throws MappingException {\r
+        LOGGER.info("    MappedElementsRule.updateDomain");\r
+        // Snapshot the accessed range value for concurrency safety.\r
+        // NOTE: still assumes that the accessed collection is concurrent or\r
+        // synchronized for toArray to be atomic.\r
+        Collection<Object> value = rangeAccessor.get(rangeElement);\r
+        Object[] rangeSnapshot = value.toArray();\r
+        ArrayList<Resource> mappedValue = new ArrayList<Resource>(rangeSnapshot.length);\r
+        for (Object obj : rangeSnapshot)\r
+            mappedValue.add(map.get(obj));\r
+        return domainAccessor.set(g, domainElement, mappedValue);\r
+    }\r
+\r
+    @Override\r
+    public boolean updateRange(ReadGraph g, IFunction<Resource, Object> map,\r
+            Resource domainElement, Object rangeElement)\r
+    throws MappingException {\r
+        LOGGER.info("    MappedElementsRule.updateRange");\r
+        Collection<Resource> value = domainAccessor.get(g, domainElement);\r
+        ArrayList<Object> mappedValue = new ArrayList<Object>(value.size());\r
+        for(Resource r : value)\r
+            mappedValue.add(map.get(r));\r
+        return rangeAccessor.set(rangeElement, mappedValue);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/ValueRule.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/ValueRule.java
new file mode 100644 (file)
index 0000000..8135d2d
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.objmap.IFunction;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.MappingException;\r
+import org.simantics.objmap.rules.domain.IDomainAccessor;\r
+import org.simantics.objmap.rules.range.IRangeAccessor;\r
+\r
+/**\r
+ * A rule that synchronizes values between domain and\r
+ * range accessors.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class ValueRule implements IMappingRule {\r
+    \r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+       IDomainAccessor<Object> domainAccessor;\r
+       IRangeAccessor<Object> rangeAccessor;\r
+       \r
+       public ValueRule(IDomainAccessor<Object> domainAccessor,\r
+                       IRangeAccessor<Object> rangeAccessor) {\r
+               this.domainAccessor = domainAccessor;\r
+               this.rangeAccessor = rangeAccessor;\r
+       }\r
+\r
+       @Override\r
+       public boolean updateDomain(WriteGraph g, IFunction<Object, Resource> map,\r
+                       Resource domainElement, Object rangeElement)\r
+                       throws MappingException {\r
+        LOGGER.info("    ValueRule.updateDomain");         \r
+               Object value = rangeAccessor.get(rangeElement);\r
+               return domainAccessor.set(g, domainElement, value);\r
+       }\r
+\r
+       @Override\r
+       public boolean updateRange(ReadGraph g, IFunction<Resource, Object> map,\r
+                       Resource domainElement, Object rangeElement)\r
+                       throws MappingException {\r
+        LOGGER.info("    ValueRule.updateRange");\r
+               Object value = domainAccessor.get(g, domainElement);\r
+               return rangeAccessor.set(rangeElement, value);\r
+       }       \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/adapters/IdentityAdapter.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/adapters/IdentityAdapter.java
new file mode 100644 (file)
index 0000000..913357b
--- /dev/null
@@ -0,0 +1,23 @@
+package org.simantics.objmap.rules.adapters;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+public enum IdentityAdapter implements ValueAdapter {\r
+    INSTANCE;\r
+\r
+    @Override\r
+    public Object domainToRange(Object domainValue) {\r
+        return domainValue;\r
+    }\r
+\r
+    @Override\r
+    public Object rangeToDomain(Object rangeValue) {\r
+        return rangeValue;\r
+    }\r
+\r
+    @Override\r
+    public Resource rangeTypeToDomainType(ReadGraph graph, Class<?> rangeType) {\r
+        return null;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/adapters/ValueAdapter.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/adapters/ValueAdapter.java
new file mode 100644 (file)
index 0000000..85e4016
--- /dev/null
@@ -0,0 +1,10 @@
+package org.simantics.objmap.rules.adapters;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+\r
+public interface ValueAdapter {\r
+    Resource rangeTypeToDomainType(ReadGraph graph, Class<?> rangeType);\r
+    Object domainToRange(Object domainValue);\r
+    Object rangeToDomain(Object rangeValue);\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/IDomainAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/IDomainAccessor.java
new file mode 100644 (file)
index 0000000..4dc94dd
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.domain;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * Provides access to some property of domain elements.\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IDomainAccessor<T> {\r
+       T get(ReadGraph g, Resource element) throws MappingException;\r
+       boolean set(WriteGraph g, Resource element, T value) throws MappingException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/MappingUtils.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/MappingUtils.java
new file mode 100644 (file)
index 0000000..927d012
--- /dev/null
@@ -0,0 +1,92 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.domain;\r
+\r
+import java.util.Arrays;\r
+import java.util.Collection;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+/**\r
+ * Static utility methods for rule implementations.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class MappingUtils {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+    /**\r
+     * Adds and removes statements to/from the database so that <code>objects</code>\r
+     * will be exactly the objects connected to <code>subject</code> by <code>predicate</code>.\r
+     * Returns true if the method made modifications to the database.\r
+     */\r
+       public static boolean synchronizeStatements(WriteGraph g, Resource subject, Resource predicate, Resource[] objects,\r
+               boolean deleteExtraObjects) \r
+               throws DatabaseException {\r
+               Collection<Resource> currentObjects0 = g.getObjects(subject, predicate);\r
+               Resource[] currentObjects = currentObjects0.toArray(new Resource[currentObjects0.size()]);\r
+               \r
+               Arrays.sort(objects);\r
+               Arrays.sort(currentObjects);\r
+               \r
+               boolean modified = false;\r
+               int i=0, j=0;   \r
+               if(currentObjects.length > 0 && objects.length > 0)\r
+               while(true) {\r
+                       int cmp = currentObjects[i].compareTo(objects[j]);\r
+                       if(cmp < 0) {\r
+                           LOGGER.info("            remove statement");\r
+                           if(deleteExtraObjects)\r
+                               g.deny(currentObjects[i]);\r
+                           else\r
+                               g.denyStatement(subject, predicate, currentObjects[i]);                                 \r
+                               modified = true;\r
+                               ++i;\r
+                               if(i >= currentObjects.length)\r
+                                       break;\r
+                       }\r
+                       else if(cmp > 0) {\r
+                           LOGGER.info("            add statement");\r
+                               g.claim(subject, predicate, objects[j]);\r
+                               modified = true;\r
+                               ++j;\r
+                               if(j >= objects.length)\r
+                                       break;\r
+                       }\r
+                       else {\r
+                               ++i; ++j;\r
+                               if(i >= currentObjects.length)\r
+                                       break;\r
+                               if(j >= objects.length)\r
+                                       break;\r
+                       }\r
+               }\r
+               while(i < currentObjects.length) {\r
+                   if(deleteExtraObjects)\r
+                g.deny(currentObjects[i]);\r
+            else\r
+                g.denyStatement(subject, predicate, currentObjects[i]);\r
+                       modified = true;\r
+                       ++i;\r
+               }\r
+               while(j < objects.length) {\r
+                       g.claim(subject, predicate, objects[j]);\r
+                       modified = true;\r
+                       ++j;\r
+               }\r
+               return modified;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedListElementsAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedListElementsAccessor.java
new file mode 100644 (file)
index 0000000..59b544f
--- /dev/null
@@ -0,0 +1,71 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.domain;\r
+\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.MappingException;\r
+\r
+public class RelatedListElementsAccessor implements IDomainAccessor<Collection<Resource>> {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+    Resource relation;\r
+\r
+       public RelatedListElementsAccessor(Resource relation) {\r
+        super();\r
+        this.relation = relation;\r
+    }\r
+\r
+    @Override\r
+       public Collection<Resource> get(ReadGraph g, Resource element) throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedListElementsAccessor.get");\r
+                   Resource listResource = g.getPossibleObject(element, relation);\r
+                   if(listResource != null)\r
+                       return ListUtils.toList(g, listResource);\r
+                   else\r
+                       return Collections.emptyList();\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public boolean set(WriteGraph g, Resource element, Collection<Resource> value)\r
+                       throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedListElementsAccessor.set");\r
+               Resource listResource = g.getPossibleObject(element, relation);\r
+               if(listResource != null)\r
+                   ListUtils.createExisting(g, listResource, value);\r
+               else {\r
+                   listResource = ListUtils.create(g, value);\r
+                   g.claim(element, relation, listResource);\r
+               }\r
+                   \r
+                   return true;\r
+                   // FIXME Implement deleteExtraObjects\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedObjectAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedObjectAccessor.java
new file mode 100644 (file)
index 0000000..10761d6
--- /dev/null
@@ -0,0 +1,71 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.domain;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * Accesses a resource attached to the element by given functional relation.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class RelatedObjectAccessor implements IDomainAccessor<Resource> {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+       Resource relation;\r
+       \r
+       public RelatedObjectAccessor(Resource relation) {\r
+               this.relation = relation;\r
+       }\r
+\r
+       @Override\r
+       public Resource get(ReadGraph g, Resource element) throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedObjectAccessor.get");\r
+                       return g.getPossibleObject(element, relation);\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public boolean set(WriteGraph g, Resource element, Resource value)\r
+                       throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedObjectAccessor.set");\r
+                   Resource resource = g.getPossibleObject(element, relation);\r
+                       if(resource == null) {\r
+                           if(value == null)\r
+                               return false;\r
+                           g.claim(element, relation, value);\r
+                           return true;\r
+                       }\r
+                       else if(resource.equals(value))\r
+                           return false;\r
+                       else {\r
+                           g.deny(element, relation);\r
+                           if(value != null)\r
+                               g.claim(element, relation, value);\r
+                           return true;\r
+                       }\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedObjectsAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedObjectsAccessor.java
new file mode 100644 (file)
index 0000000..c7b6cab
--- /dev/null
@@ -0,0 +1,63 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.domain;\r
+\r
+import java.util.Collection;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * Accesses the set of objects attached to the element by the given relation.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class RelatedObjectsAccessor implements IDomainAccessor<Collection<Resource>> {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+       Resource relation;\r
+       boolean deleteExtraObjects;\r
+\r
+       public RelatedObjectsAccessor(Resource relation, boolean deleteExtraObjects) {\r
+        super();\r
+        this.relation = relation;\r
+        this.deleteExtraObjects = deleteExtraObjects;\r
+    }\r
+\r
+    @Override\r
+       public Collection<Resource> get(ReadGraph g, Resource element) throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedObjectsAccessor.get");\r
+                       return g.getObjects(element, relation);\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public boolean set(WriteGraph g, Resource element, Collection<Resource> value)\r
+                       throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedObjectsAccessor.set");\r
+                       return MappingUtils.synchronizeStatements(g, element, relation, \r
+                               value.toArray(new Resource[value.size()]), deleteExtraObjects);\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedOrderedSetElementsAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedOrderedSetElementsAccessor.java
new file mode 100644 (file)
index 0000000..35c5e3f
--- /dev/null
@@ -0,0 +1,66 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.domain;\r
+\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * Accesses the set of objects attached to the element by the given relation.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class RelatedOrderedSetElementsAccessor implements IDomainAccessor<Collection<Resource>> {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+       boolean deleteExtraObjects;\r
+\r
+       public RelatedOrderedSetElementsAccessor(boolean deleteExtraObjects) {\r
+        super();\r
+        this.deleteExtraObjects = deleteExtraObjects;\r
+    }\r
+\r
+    @Override\r
+       public Collection<Resource> get(ReadGraph g, Resource element) throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedOrderedSetElementsAccessor.get");\r
+                   if(g.hasStatement(element))\r
+                       return OrderedSetUtils.toList(g, element);\r
+                   else\r
+                       return Collections.emptyList();\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public boolean set(WriteGraph g, Resource element, Collection<Resource> value)\r
+                       throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedOrderedSetElementsAccessor.set");\r
+                   return OrderedSetUtils.set(g, element, value);\r
+                   // FIXME Implement deleteExtraObjects\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedValueAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/domain/RelatedValueAccessor.java
new file mode 100644 (file)
index 0000000..4cf7ecd
--- /dev/null
@@ -0,0 +1,84 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.domain;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * Accesses a value attached to the element by given functional relation.\r
+ * @author Hannu Niemist�\r
+ */\r
+public class RelatedValueAccessor implements IDomainAccessor<Object> {\r
+\r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+       Resource relation;\r
+       Resource valueType;\r
+\r
+       public RelatedValueAccessor(Resource relation, Resource valueType) {\r
+               this.relation = relation;\r
+               this.valueType = valueType;\r
+       }\r
+\r
+       @Override\r
+       public Object get(ReadGraph g, Resource element) throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedValueAccessor.get");\r
+                       Resource valueResource = g.getPossibleObject(element, relation);\r
+                       if(valueResource == null)\r
+                               return null;\r
+                       return g.getValue(valueResource);\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public boolean set(WriteGraph g, Resource element, Object value)\r
+                       throws MappingException {\r
+               try {\r
+                   LOGGER.info("        RelatedValueAccessor.set");\r
+                       Resource valueResource = g.getPossibleObject(element, relation);\r
+                       if(valueResource == null) {\r
+                               if(value == null)\r
+                                       return false;\r
+                               valueResource = g.newResource();\r
+                               g.claim(valueResource, Layer0.getInstance(g).InstanceOf, null,\r
+                                               valueType);\r
+                               g.claim(element, relation, valueResource);\r
+                               g.claimValue(valueResource, value);                             \r
+                               return true;\r
+                       }\r
+                       else {\r
+                               if(value == null) {\r
+                                       g.deny(valueResource);\r
+                                       return true;\r
+                               }                               \r
+                               Object currentValue = g.getValue(valueResource);\r
+                               if(currentValue.equals(value))\r
+                                       return false;\r
+                               g.claimValue(valueResource, value);\r
+                               return true;\r
+                       }\r
+               } catch (DatabaseException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IClassRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IClassRuleFactory.java
new file mode 100644 (file)
index 0000000..b9b6906
--- /dev/null
@@ -0,0 +1,22 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.factory;\r
+\r
+import java.lang.annotation.Annotation;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.IMappingRule;\r
+\r
+public interface IClassRuleFactory {\r
+    IMappingRule create(ReadGraph g, Annotation annotation, Class<?> clazz) throws DatabaseException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IFieldRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IFieldRuleFactory.java
new file mode 100644 (file)
index 0000000..02688e0
--- /dev/null
@@ -0,0 +1,23 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.factory;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.IMappingRule;\r
+\r
+public interface IFieldRuleFactory {\r
+    IMappingRule create(ReadGraph g, Annotation annotation, Field field) throws DatabaseException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IMethodRuleFactory.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/factory/IMethodRuleFactory.java
new file mode 100644 (file)
index 0000000..32bb98b
--- /dev/null
@@ -0,0 +1,23 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.factory;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Method;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.IMappingRule;\r
+\r
+public interface IMethodRuleFactory {\r
+    IMappingRule create(ReadGraph g, Annotation annotation, Method method) throws DatabaseException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/AdaptedRangeAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/AdaptedRangeAccessor.java
new file mode 100644 (file)
index 0000000..a6df00b
--- /dev/null
@@ -0,0 +1,25 @@
+package org.simantics.objmap.rules.range;\r
+\r
+import org.simantics.objmap.MappingException;\r
+import org.simantics.objmap.rules.adapters.ValueAdapter;\r
+\r
+public class AdaptedRangeAccessor implements IRangeAccessor<Object> {\r
+    IRangeAccessor<Object> baseAccessor;\r
+    ValueAdapter adapter;\r
+    \r
+    public AdaptedRangeAccessor(IRangeAccessor<Object> baseAccessror,\r
+            ValueAdapter adapter) {\r
+        this.baseAccessor = baseAccessror;\r
+        this.adapter = adapter;\r
+    }\r
+\r
+    @Override\r
+    public Object get(Object element) throws MappingException {\r
+        return adapter.rangeToDomain(baseAccessor.get(element));    \r
+    }\r
+    \r
+    @Override\r
+    public boolean set(Object element, Object value) throws MappingException {\r
+        return baseAccessor.set(element, adapter.domainToRange(value));\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/FieldAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/FieldAccessor.java
new file mode 100644 (file)
index 0000000..e731e3e
--- /dev/null
@@ -0,0 +1,75 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.range;\r
+\r
+import java.lang.reflect.Field;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * Accesses the given field of the element.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class FieldAccessor<T> implements IRangeAccessor<T> {\r
+    \r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+       Field field;\r
+\r
+       public FieldAccessor(Field field) {\r
+               this.field = field;\r
+       }\r
+\r
+       @Override\r
+       public T get(Object element) throws MappingException {\r
+               try {\r
+                   @SuppressWarnings("unchecked")\r
+                       T result = (T)field.get(element);\r
+                   \r
+               if(LOGGER.isInfoEnabled())\r
+                   LOGGER.info("        FieldAccessor.get " +\r
+                           field.getName() + " -> " + result\r
+                   );\r
+               \r
+                       return result;\r
+               } catch (IllegalArgumentException e) {\r
+                       throw new MappingException(e);\r
+               } catch (IllegalAccessException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+       }\r
+\r
+       @Override\r
+       public boolean set(Object element, T value) throws MappingException {\r
+               try {\r
+                       Object currentValue = field.get(element);\r
+                       \r
+            if(LOGGER.isInfoEnabled())\r
+                LOGGER.info("        FieldAccessor.set " +\r
+                        field.getName() + " " + currentValue +  \r
+                        " -> " + value\r
+                );\r
+                       \r
+                       if(value == null \r
+                               ? (currentValue == null || field.getType().isPrimitive()) \r
+                               : value.equals(currentValue))\r
+                               return false;                   \r
+                       field.set(element, value);\r
+                       return true;\r
+               } catch (IllegalArgumentException e) {\r
+                       throw new MappingException(e);\r
+               } catch (IllegalAccessException e) {\r
+                       throw new MappingException(e);\r
+               }\r
+       }       \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/FieldAccessorWithDefault.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/FieldAccessorWithDefault.java
new file mode 100644 (file)
index 0000000..688de95
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.range;\r
+\r
+import java.lang.reflect.Field;\r
+\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * Accesses the given field of the element.\r
+ * @author Hannu Niemist�\r
+ */\r
+public class FieldAccessorWithDefault<T> extends FieldAccessor<T> {\r
+    \r
+       T defaultValue;\r
+\r
+       public FieldAccessorWithDefault(Field field, T defaultValue) {\r
+        super(field);\r
+        this.defaultValue = defaultValue;\r
+    }\r
+\r
+    @Override\r
+       public T get(Object element) throws MappingException {\r
+               T value = super.get(element);\r
+               if(value == null)\r
+                   return defaultValue;\r
+               else\r
+                   return value;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/IRangeAccessor.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/rules/range/IRangeAccessor.java
new file mode 100644 (file)
index 0000000..01625a1
--- /dev/null
@@ -0,0 +1,23 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.rules.range;\r
+\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * Provides access to some property of range elements.\r
+ * @author Hannu Niemistö\r
+ */\r
+public interface IRangeAccessor<T> {\r
+       T get(Object element) throws MappingException;\r
+       boolean set(Object element, T value) throws MappingException;\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/schema/MappingSchemas.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/schema/MappingSchemas.java
new file mode 100644 (file)
index 0000000..09984fe
--- /dev/null
@@ -0,0 +1,94 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.schema;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+import java.lang.reflect.Method;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.objmap.annotations.meta.HasClassRuleFactory;\r
+import org.simantics.objmap.annotations.meta.HasFieldRuleFactory;\r
+import org.simantics.objmap.annotations.meta.HasMethodRuleFactory;\r
+\r
+/**\r
+ * Static utility methods for mapping schemas\r
+ * @author Hannu Niemistö\r
+ */\r
+public class MappingSchemas {\r
+    \r
+    /**\r
+     * Creates a new SimpleLinkType based on the annotations in the given class.\r
+     * @throws IllegalAccessException \r
+     * @throws InstantiationException \r
+     * @see GraphType\r
+     * @see RelatedValue\r
+     */\r
+       public static SimpleLinkType fromAnnotations(ReadGraph g, Class<?> clazz) throws DatabaseException, InstantiationException, IllegalAccessException {\r
+           GraphType graphType = clazz.getAnnotation(GraphType.class);\r
+           \r
+           ArrayList<IMappingRule> rules = new ArrayList<IMappingRule>();\r
+           collectRulesFromAnnotations(g, clazz, rules);\r
+           \r
+           return new SimpleLinkType(\r
+                   g.getResource(graphType.value()), \r
+                clazz, rules);    \r
+       }\r
+       \r
+       public static void collectRulesFromAnnotations(ReadGraph g, Class<?> clazz, Collection<IMappingRule> rules) throws DatabaseException, InstantiationException, IllegalAccessException {\r
+           Class<?> superclass = clazz.getSuperclass();\r
+           if(superclass != null)\r
+               collectRulesFromAnnotations(g, superclass, rules);\r
+               \r
+        for(Annotation annotation : clazz.getAnnotations()) {\r
+            HasClassRuleFactory factory = \r
+                annotation.annotationType().getAnnotation(HasClassRuleFactory.class);\r
+            if(factory != null) {\r
+                rules.add(factory.value().newInstance()\r
+                        .create(g, annotation, clazz));\r
+            }\r
+        }\r
+\r
+        for(Field f : clazz.getDeclaredFields()) {\r
+            f.setAccessible(true);\r
+\r
+            for(Annotation annotation : f.getAnnotations()) {\r
+                HasFieldRuleFactory factory = \r
+                    annotation.annotationType().getAnnotation(HasFieldRuleFactory.class);\r
+                if(factory != null) {\r
+                    rules.add(factory.value().newInstance()\r
+                            .create(g, annotation, f));\r
+                }\r
+            }\r
+        }\r
+\r
+        for(Method m : clazz.getDeclaredMethods()) {\r
+            m.setAccessible(true);\r
+\r
+            for(Annotation annotation : m.getAnnotations()) {\r
+                HasMethodRuleFactory factory = \r
+                    annotation.annotationType().getAnnotation(HasMethodRuleFactory.class);\r
+                if(factory != null) {\r
+                    rules.add(factory.value().newInstance()\r
+                            .create(g, annotation, m));\r
+                }\r
+            }\r
+        }\r
+    }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/schema/SimpleLinkType.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/schema/SimpleLinkType.java
new file mode 100644 (file)
index 0000000..7cbfbb3
--- /dev/null
@@ -0,0 +1,133 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.schema;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.apache.log4j.Logger;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.IFunction;\r
+import org.simantics.objmap.ILinkType;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * A link type that is associated with single domain and range type (class).\r
+ * SimpleLinkType is composed of simpler rules whose combination determines\r
+ * its update policy.\r
+ * @author Hannu Niemist�\r
+ */\r
+public class SimpleLinkType implements ILinkType {\r
+    \r
+    static Logger LOGGER = Logger.getLogger("org.simantics.objmap");\r
+    \r
+    public Resource domainType;\r
+    public Class<?> rangeType;\r
+    ArrayList<IMappingRule> rules;\r
+    \r
+    public SimpleLinkType(Resource domainType, Class<?> rangeType,\r
+            ArrayList<IMappingRule> rules) {\r
+        this.domainType = domainType;\r
+        this.rangeType = rangeType;\r
+        this.rules = rules;\r
+    }\r
+\r
+    public SimpleLinkType(Resource domainType, Class<?> rangeType) {\r
+        this(domainType, rangeType, new ArrayList<IMappingRule>());\r
+    }\r
+\r
+    /**\r
+     * Adds a new rule to this link type that is enforced\r
+     * during updates.\r
+     */\r
+    public void addRule(IMappingRule rule) {\r
+        rules.add(rule);\r
+    }\r
+    \r
+    @Override\r
+    public Resource createDomainElement(WriteGraph g, Object rangeElement)\r
+            throws MappingException {\r
+        try {\r
+            if(LOGGER.isInfoEnabled())\r
+                LOGGER.info("SimpleLinkType.createDomainElement " +\r
+                        rangeElement.toString()\r
+                );\r
+            Resource result = g.newResource();\r
+            g.claim(result, Layer0.getInstance(g).InstanceOf, null, domainType);\r
+            return result;\r
+        } catch(DatabaseException e) {\r
+            throw new MappingException(e);\r
+        }\r
+    }\r
+    @Override\r
+    public Object createRangeElement(ReadGraph g, Resource domainElement)\r
+            throws MappingException {\r
+        try {\r
+            if(LOGGER.isInfoEnabled())\r
+                try { \r
+                    LOGGER.info("SimpleLinkType.createRangeElement " +\r
+                               NameUtils.getSafeName(g, domainElement)\r
+                            );\r
+                } catch(DatabaseException e) {\r
+                    throw new MappingException(e);\r
+                }\r
+            return rangeType.newInstance();\r
+        } catch (InstantiationException e) {\r
+            throw new MappingException(e);\r
+        } catch (IllegalAccessException e) {\r
+            throw new MappingException(e);\r
+        }\r
+    }\r
+    @Override\r
+    public boolean updateDomain(WriteGraph g, IFunction<Object, Resource> map,\r
+            Resource domainElement, Object rangeElement)\r
+            throws MappingException {\r
+        if(LOGGER.isInfoEnabled())\r
+            try { \r
+                LOGGER.info("SimpleLinkType.updateDomain " +\r
+                        NameUtils.getSafeName(g, domainElement) + " " +\r
+                        rangeElement.toString()\r
+                        );\r
+            } catch(DatabaseException e) {\r
+                throw new MappingException(e);\r
+            }\r
+        \r
+        boolean updated = false;\r
+        for(IMappingRule rule : rules)\r
+               updated |= rule.updateDomain(g, map, domainElement, rangeElement);\r
+        return updated;\r
+    }\r
+    @Override\r
+    public boolean updateRange(ReadGraph g, IFunction<Resource, Object> map,\r
+            Resource domainElement, Object rangeElement)\r
+            throws MappingException {\r
+        if(LOGGER.isInfoEnabled())\r
+            try { \r
+                LOGGER.info("SimpleLinkType.updateRange " +\r
+                               NameUtils.getSafeName(g, domainElement) + " " +\r
+                        rangeElement.toString()\r
+                        );\r
+            } catch(DatabaseException e) {\r
+                throw new MappingException(e);\r
+            }\r
+        \r
+        boolean updated = false;\r
+        for(IMappingRule rule : rules)\r
+            updated |= rule.updateRange(g, map, domainElement, rangeElement);\r
+        return updated;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.objmap/src/org/simantics/objmap/schema/SimpleSchema.java b/1.8/org.simantics.objmap/src/org/simantics/objmap/schema/SimpleSchema.java
new file mode 100644 (file)
index 0000000..5c15c00
--- /dev/null
@@ -0,0 +1,70 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.objmap.schema;\r
+\r
+import gnu.trove.THashMap;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.ILinkType;\r
+import org.simantics.objmap.IMappingSchema;\r
+import org.simantics.objmap.MappingException;\r
+\r
+/**\r
+ * An implementation of IMappingSchema that contains\r
+ * only SimpleLinkTypes. The link type of any domain\r
+ * element is based solely on its type in database and\r
+ * the link type of any range element is based on its class.\r
+ * @author Hannu Niemistö\r
+ */\r
+public class SimpleSchema implements IMappingSchema {\r
+\r
+    THashMap<Resource, SimpleLinkType> domainLinkTypes = \r
+        new THashMap<Resource, SimpleLinkType>();\r
+    THashMap<Class<?>, SimpleLinkType> rangeLinkTypes = \r
+        new THashMap<Class<?>, SimpleLinkType>();\r
+    \r
+    public void addLinkType(SimpleLinkType linkType) {\r
+        domainLinkTypes.put(linkType.domainType, linkType);\r
+        rangeLinkTypes.put(linkType.rangeType, linkType);\r
+    }\r
+    \r
+    @Override\r
+    public ILinkType linkTypeOfDomainElement(ReadGraph g, Resource element) throws MappingException {        \r
+        try {\r
+               \r
+               for(Resource type : g.getTypes(element)) {\r
+\r
+                       ILinkType linkType = domainLinkTypes.get(type);\r
+                       if(linkType != null) return linkType;\r
+                       \r
+               }\r
+               \r
+               throw new MappingException("Didn't find a link type for " +\r
+                               NameUtils.getSafeName(g, element) + ".");\r
+                               \r
+        } catch (DatabaseException e) {\r
+            throw new MappingException(e);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public ILinkType linkTypeOfRangeElement(Object element) throws MappingException {\r
+       ILinkType type = rangeLinkTypes.get(element.getClass());\r
+               if(type == null) \r
+                       throw new MappingException("Didn't find a link type for " +     element + ".");\r
+               return type;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.feature/.project b/1.8/org.simantics.sysdyn.feature/.project
new file mode 100644 (file)
index 0000000..60643f3
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.sysdyn.feature</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.FeatureBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.FeatureNature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.sysdyn.feature/build.properties b/1.8/org.simantics.sysdyn.feature/build.properties
new file mode 100644 (file)
index 0000000..6ec1948
--- /dev/null
@@ -0,0 +1,16 @@
+###############################################################################\r
+# Copyright (c) 2014 Association for Decentralized Information Management in\r
+# Industry THTH ry.\r
+# All rights reserved. This program and the accompanying materials\r
+# are made available under the terms of the Eclipse Public License v1.0\r
+# which accompanies this distribution, and is available at\r
+# http://www.eclipse.org/legal/epl-v10.html\r
+#\r
+# Contributors:\r
+#     VTT Technical Research Centre of Finland - initial API and implementation\r
+###############################################################################\r
+bin.includes = feature.xml\r
+root=rootfiles/\r
+\r
+root.win32.win32.x86.folder.jre=jre/win32.x86\r
+root.win32.win32.x86_64.folder.jre=jre/win32.x86_64
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.feature/feature.xml b/1.8/org.simantics.sysdyn.feature/feature.xml
new file mode 100644 (file)
index 0000000..3aac231
--- /dev/null
@@ -0,0 +1,156 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<!--
+    Copyright (c) 2010 Association for Decentralized Information Management in
+    Industry THTH ry.
+    All rights reserved. This program and the accompanying materials
+    are made available under the terms of the Eclipse Public License v1.0
+    which accompanies this distribution, and is available at
+    http://www.eclipse.org/legal/epl-v10.html
+   
+    Contributors:
+        VTT Technical Research Centre of Finland - initial API and implementation
+ -->\r
+<feature\r
+      id="org.simantics.sysdyn"\r
+      label="Simantics System Dynamics Feature"\r
+      version="1.8.0.qualifier"\r
+      provider-name="VTT Technical Research Centre of Finland">\r
+\r
+   <description url="http://www.example.com/description">\r
+      [Enter Feature Description here.]\r
+   </description>\r
+\r
+   <copyright url="http://www.example.com/copyright">\r
+      [Enter Copyright Description here.]\r
+   </copyright>\r
+\r
+   <license url="http://www.example.com/license">\r
+      [Enter License Description here.]\r
+   </license>\r
+\r
+   <includes\r
+         id="org.eclipse.equinox.executable"\r
+         version="0.0.0"/>\r
+\r
+   <includes\r
+         id="org.simantics.help"\r
+         version="0.0.0"/>\r
+\r
+   <includes\r
+         id="org.simantics.issues"\r
+         version="0.0.0"/>\r
+\r
+   <includes\r
+         id="org.simantics.modeling"\r
+         version="0.0.0"/>\r
+\r
+   <includes\r
+         id="org.simantics.issues.ui"\r
+         version="0.0.0"/>\r
+\r
+   <includes\r
+         id="org.simantics.workbench"\r
+         version="0.0.0"/>\r
+\r
+   <includes\r
+         id="org.simantics.eclipsec.launcher"\r
+         version="0.0.0"/>\r
+\r
+   <plugin\r
+         id="org.simantics.objmap"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.simantics.sysdyn"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.simantics.sysdyn.ui"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.simantics.modelica"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.simantics.sysdyn.ontology"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="freemarker"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.antlr.runtime"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.simantics.openmodelica.win32"\r
+         os="win32"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"/>\r
+\r
+   <plugin\r
+         id="org.simantics.jfreechart.ontology"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.eclipse.nebula.widgets.tablecombo"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.simantics.fmu"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="org.simantics.fmu.me.win32"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"/>\r
+\r
+   <plugin\r
+         id="org.simantics.jfreechart"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+   <plugin\r
+         id="fi.semantum.sysdyn.solver"\r
+         download-size="0"\r
+         install-size="0"\r
+         version="0.0.0"\r
+         unpack="false"/>\r
+\r
+</feature>\r
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Bathtub.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Bathtub.sysdyn
new file mode 100644 (file)
index 0000000..39b0dd7
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Bathtub.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Bathtub.sysdynModule b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Bathtub.sysdynModule
new file mode 100644 (file)
index 0000000..31429c2
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Bathtub.sysdynModule differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Ceiling.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Ceiling.sysdyn
new file mode 100644 (file)
index 0000000..4a25312
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Ceiling.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Decay.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Decay.sysdyn
new file mode 100644 (file)
index 0000000..0244333
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Decay.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Decay.sysdynModule b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Decay.sysdynModule
new file mode 100644 (file)
index 0000000..78e03cc
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Decay.sysdynModule differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Extrapolation.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Extrapolation.sysdyn
new file mode 100644 (file)
index 0000000..beb195c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Extrapolation.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Extrapolation.sysdynModule b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Extrapolation.sysdynModule
new file mode 100644 (file)
index 0000000..37e1772
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Extrapolation.sysdynModule differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Floor.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Floor.sysdyn
new file mode 100644 (file)
index 0000000..5e0ebb3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Floor.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/MoleculeFunctions.sysdynFunctions b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/MoleculeFunctions.sysdynFunctions
new file mode 100644 (file)
index 0000000..9cff2bc
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/MoleculeFunctions.sysdynFunctions differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Multivariate Anchoring And Adjustment.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Multivariate Anchoring And Adjustment.sysdyn
new file mode 100644 (file)
index 0000000..3f021b0
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Multivariate Anchoring And Adjustment.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Protected Sea Ancoring And Adjustment.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Protected Sea Ancoring And Adjustment.sysdyn
new file mode 100644 (file)
index 0000000..709a93a
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Protected Sea Ancoring And Adjustment.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Sea Anchoring And Adjustment.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Sea Anchoring And Adjustment.sysdyn
new file mode 100644 (file)
index 0000000..0ea9942
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Sea Anchoring And Adjustment.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Smooth.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Smooth.sysdyn
new file mode 100644 (file)
index 0000000..14ff753
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Smooth.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Smooth.sysdynModule b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Smooth.sysdynModule
new file mode 100644 (file)
index 0000000..450f52c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Smooth.sysdynModule differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/SmoothThirdOrder.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/SmoothThirdOrder.sysdyn
new file mode 100644 (file)
index 0000000..bacab11
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/SmoothThirdOrder.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/SmoothThirdOrder.sysdynModule b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/SmoothThirdOrder.sysdynModule
new file mode 100644 (file)
index 0000000..30c80f3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/SmoothThirdOrder.sysdynModule differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Tester For Molecules.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Tester For Molecules.sysdyn
new file mode 100644 (file)
index 0000000..7c98f04
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Tester For Molecules.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Trend.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Trend.sysdyn
new file mode 100644 (file)
index 0000000..79a1c5d
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Trend.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Trend.sysdynModule b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Trend.sysdynModule
new file mode 100644 (file)
index 0000000..0a195ce
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Trend.sysdynModule differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Univariate Anchoring And Adjustment.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Univariate Anchoring And Adjustment.sysdyn
new file mode 100644 (file)
index 0000000..70d58f1
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/Univariate Anchoring And Adjustment.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/WeighedAverage.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/WeighedAverage.sysdyn
new file mode 100644 (file)
index 0000000..c69c7c0
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/WeighedAverage.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/references.txt b/1.8/org.simantics.sysdyn.feature/rootfiles/molecules/references.txt
new file mode 100644 (file)
index 0000000..09ad135
--- /dev/null
@@ -0,0 +1,3 @@
+The molecules in this folder are collected from:\r
+\r
+Hines, Jim. 2005. Molecules of Structure - Building Blocks for System Dynamics Models. Version 2.02. Available at: http://www.systemswiki.org/images/a/a8/Molecule.pdf .\r
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/msvcr100.dll b/1.8/org.simantics.sysdyn.feature/rootfiles/msvcr100.dll
new file mode 100644 (file)
index 0000000..3e82b1a
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/msvcr100.dll differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/puzzle_green.ico b/1.8/org.simantics.sysdyn.feature/rootfiles/puzzle_green.ico
new file mode 100644 (file)
index 0000000..61e3f86
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/puzzle_green.ico differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Discovery And Exploitation Of Resources.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Discovery And Exploitation Of Resources.sysdyn
new file mode 100644 (file)
index 0000000..e90a36a
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Discovery And Exploitation Of Resources.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Global Carbon Cycle.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Global Carbon Cycle.sysdyn
new file mode 100644 (file)
index 0000000..9afc06a
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Global Carbon Cycle.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Predator And Limited Prey.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Predator And Limited Prey.sysdyn
new file mode 100644 (file)
index 0000000..7d2d2fe
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Predator And Limited Prey.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Resource Exploitation Use Recycling.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Resource Exploitation Use Recycling.sysdyn
new file mode 100644 (file)
index 0000000..33a8815
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Resource Exploitation Use Recycling.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Tourists Environments And Hotel Facilities.sysdyn b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Tourists Environments And Hotel Facilities.sysdyn
new file mode 100644 (file)
index 0000000..def1fc4
Binary files /dev/null and b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/Tourists Environments And Hotel Facilities.sysdyn differ
diff --git a/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/references.txt b/1.8/org.simantics.sysdyn.feature/rootfiles/sampleModels/references.txt
new file mode 100644 (file)
index 0000000..77f7b30
--- /dev/null
@@ -0,0 +1,12 @@
+The sample models in this folder are collected from the "System Zoo" books by Bossel:\r
+\r
+Hartmut Bossel. 2007. System Zoo 2 Simulation Models - Climate, Ecosystems, Resources. BoD.\r
+* Discovery And Exploitation Of Resources\r
+* Global Carbon Cycle\r
+* Predator And Limited Prey\r
+* Resource Exploitation Use Recycling\r
+* Tourists Environments And Hotel Facilities\r
+\r
+Hartmut Bossel. 2007. System Zoo 3 Simulation Models - Economy, Society, Development. BoD.\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ontology/.classpath b/1.8/org.simantics.sysdyn.ontology/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.sysdyn.ontology/.project b/1.8/org.simantics.sysdyn.ontology/.project
new file mode 100644 (file)
index 0000000..b975ea9
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.sysdyn.ontology</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.simantics.graph.builder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+               <nature>org.simantics.graph.nature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.sysdyn.ontology/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.sysdyn.ontology/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..888b17e
--- /dev/null
@@ -0,0 +1,8 @@
+#Thu Jul 22 15:15:41 EEST 2010\r
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.sysdyn.ontology/META-INF/MANIFEST.MF b/1.8/org.simantics.sysdyn.ontology/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..dfa33be
--- /dev/null
@@ -0,0 +1,25 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: http://www.simantics.org/Sysdyn
+Bundle-SymbolicName: org.simantics.sysdyn.ontology
+Bundle-Version: 1.1.0.qualifier
+Require-Bundle: org.simantics.layer0,
+ org.simantics.diagram.ontology;bundle-version="1.0.0",
+ org.simantics.structural.ontology;bundle-version="1.0.0",
+ org.simantics.modeling.ontology;bundle-version="1.0.0",
+ org.simantics.g2d.ontology;bundle-version="1.0.0",
+ org.simantics.project.ontology;bundle-version="1.0.0",
+ org.simantics.viewpoint.ontology;bundle-version="1.0.0",
+ org.simantics.layer0x.ontology;bundle-version="1.0.0",
+ org.simantics.issues.ontology;bundle-version="1.1.0",
+ org.simantics.jfreechart.ontology;bundle-version="0.1.0",
+ org.simantics.action.ontology;bundle-version="1.0.0",
+ org.simantics.image2.ontology;bundle-version="1.1.0",
+ org.simantics.color.ontology;bundle-version="1.0.0",
+ org.simantics.simulation.ontology;bundle-version="1.0.0",
+ org.simantics.silk.ontology;bundle-version="1.0.0",
+ org.simantics.spreadsheet.ontology;bundle-version="1.1.0",
+ org.simantics.workbench.ontology;bundle-version="1.2.0"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.simantics.sysdyn
+Bundle-Vendor: VTT Technical Reserarch Centre of Finland
diff --git a/1.8/org.simantics.sysdyn.ontology/Sysdyn ontolgy changes.doc b/1.8/org.simantics.sysdyn.ontology/Sysdyn ontolgy changes.doc
new file mode 100644 (file)
index 0000000..2f41a3c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ontology/Sysdyn ontolgy changes.doc differ
diff --git a/1.8/org.simantics.sysdyn.ontology/build.properties b/1.8/org.simantics.sysdyn.ontology/build.properties
new file mode 100644 (file)
index 0000000..098c3fd
--- /dev/null
@@ -0,0 +1,18 @@
+###############################################################################\r
+# Copyright (c) 2010 Association for Decentralized Information Management in\r
+# Industry THTH ry.\r
+# All rights reserved. This program and the accompanying materials\r
+# are made available under the terms of the Eclipse Public License v1.0\r
+# which accompanies this distribution, and is available at\r
+# http://www.eclipse.org/legal/epl-v10.html\r
+#\r
+# Contributors:\r
+#     VTT Technical Research Centre of Finland - initial API and implementation\r
+###############################################################################\r
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               graphs/*.tg,\\r
+               graph.tg\r
+src.includes = graph/\r
diff --git a/1.8/org.simantics.sysdyn.ontology/graph.tg b/1.8/org.simantics.sysdyn.ontology/graph.tg
new file mode 100644 (file)
index 0000000..98d3e2d
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ontology/graph.tg differ
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/Charts.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/Charts.pgraph
new file mode 100644 (file)
index 0000000..533391f
--- /dev/null
@@ -0,0 +1,20 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+VP = <http://www.simantics.org/Viewpoint-1.2>\r
+JFREE = <http://www.simantics.org/JFreeChart-1.0>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+G2D = <http://www.simantics.org/G2D-1.1>\r
+\r
+CHARTS = SYSDYN.Charts : L0.Library\r
+\r
+CHARTS.SensitivityDataset <T JFREE.Dataset\r
+    >-- CHARTS.SensitivityDataset.confidenceBounds --> L0.List <R L0.IsComposedOf : L0.FunctionalRelation\r
+    >-- CHARTS.SensitivityDataset.median --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation\r
+    @L0.assert CHARTS.SensitivityDataset.median true\r
+    \r
+\r
+CHARTS.SensitivityDataset.ConfidenceBound <T L0.Entity\r
+    >-- CHARTS.SensitivityDataset.ConfidenceBound.percent --> L0.Double <R L0.HasProperty : L0.FunctionalRelation\r
+    >-- CHARTS.SensitivityDataset.ConfidenceBound.color --> G2D.Color <R L0.HasProperty : L0.FunctionalRelation\r
+\r
+\r
+CHARTS.SensitivityPlot <T JFREE.XYPlot\r
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/CommentSymbols.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/CommentSymbols.pgraph
new file mode 100644 (file)
index 0000000..adfd0b9
--- /dev/null
@@ -0,0 +1,34 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+G2D = <http://www.simantics.org/G2D-1.1>\r
+DIA = <http://www.simantics.org/Diagram-2.2>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+IMAGE = <http://www.simantics.org/Image2-1.2>\r
+MOD = <http://www.simantics.org/Modeling-1.2>\r
+\r
+GENERAL = SYSDYN.SymbolReferences.CommentSymbols : DIA.SymbolReferenceLibrary\r
+    L0.HasDescription "General graphical components"\r
+\r
+SYSDYN.AdditionalSymbols : L0.Library\r
+\r
+SYSDYN.AdditionalSymbols.MultilineText <T DIA.TextElement\r
+    L0.HasLabel "Comment"\r
+    L0.IsDependencyOf GENERAL\r
+    G2D.HasSVGDocument """<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" overflow="visible" version="1.1"><g style="fill:#000000;fill-opacity:1;stroke:none"><path d="m 4.2699962,-2.1489344 -0.4716797,0 C 3.7572928,-2.3129896 3.6832369,-2.5078137 3.5761485,-2.733407 3.4690444,-2.9589851 3.3494156,-3.1720383 3.2172618,-3.3725672 3.0805357,-3.5821941 2.9312845,-3.7656249 2.7695079,-3.9228601 2.6077171,-4.0800777 2.4516301,-4.1700841 2.3012462,-4.1928797 2.1599637,-4.2110997 1.9822295,-4.2247716 1.768043,-4.2338953 1.5538445,-4.2430007 1.3556025,-4.247558 1.1733165,-4.2475672 l -0.3964844,0 0,7.7587891 c -5.05e-6,0.1503919 0.031896,0.2882498 0.0957031,0.4135742 0.0637969,0.1253264 0.17545037,0.2221687 0.33496097,0.2905273 0.082026,0.031902 0.2540632,0.075196 0.5161132,0.1298829 0.2620381,0.054688 0.4659766,0.08431 0.6118165,0.088867 l 0,0.4853516 -4.5800782,0 0,-0.4853516 c 0.127602,-0.00911 0.3224261,-0.027343 0.5844727,-0.054687 0.2620414,-0.027343 0.4431935,-0.061523 0.543457,-0.102539 0.15038733,-0.059244 0.26090154,-0.1446932 0.33154298,-0.2563477 0.0706345,-0.1116526 0.10595343,-0.2609038 0.10595704,-0.4477539 l 0,-7.8203125 -0.39648442,0 c -0.1412791,9.2e-6 -0.3167346,0.00343 -0.5263671,0.010254 -0.2096379,0.00685 -0.4101586,0.021656 -0.6015625,0.044434 -0.1503926,0.018238 -0.3064797,0.1082447 -0.4682618,0.2700196 -0.1617853,0.1617925 -0.3110364,0.3452233 -0.4477539,0.5502929 -0.1367197,0.2050862 -0.2574879,0.4226967 -0.3623047,0.6528321 -0.1048184,0.2301506 -0.177735,0.4204173 -0.21875,0.5708007 l -0.4785156,0 0,-2.6318359 8.4492188,0 z" /></g></svg>""" : L0.String\r
+\r
+SYSDYN.Loop <T SYSDYN.Component <T DIA.FontProvider <T DIA.ColorProvider //<T DIA.TextElement\r
+    >-- SYSDYN.Loop.Comment --> L0.String <R L0.ConsistsOf : L0.FunctionalRelation\r
+    >-- SYSDYN.Loop.Items --> L0.List <R L0.DependsOn : L0.FunctionalRelation\r
+    @L0.assert SYSDYN.Loop.Comment "$$AUTO$$"\r
+    @L0.assert G2D.HasFont SYSDYN.DefaultFont     \r
+    @L0.assert G2D.HasColor \r
+        [0.0,0.0,1.0,1.0] : G2D.Color  \r
+        \r
+SYSDYN.LoopSymbol <T SYSDYN.SysdynSymbol\r
+    @MOD.defSymbol "Loop" SYSDYN.Loop\r
+    >-- SYSDYN.LoopSymbol.Clockwise --> L0.Boolean <R L0.ConsistsOf : L0.FunctionalRelation\r
+    @L0.assert SYSDYN.LoopSymbol.Clockwise L0.True\r
+    L0.HasDescription "(Shift+L)"\r
+    L0.IsDependencyOf GENERAL\r
+    G2D.HasSVGDocument \r
+        _ : IMAGE.SvgImage \r
+            @L0.loadString "svg/loop.svg"
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/Migration.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/Migration.pgraph
new file mode 100644 (file)
index 0000000..cf2c2db
--- /dev/null
@@ -0,0 +1,189 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+\r
+move : L0.Template\r
+    @template %subject %base %from %to\r
+        %subject : L0.NamespaceMigrationStep.Prefix        \r
+            L0.NamespaceMigrationStep.Prefix.base %base\r
+            L0.NamespaceMigrationStep.Prefix.from %from\r
+            L0.NamespaceMigrationStep.Prefix.to %to\r
+            \r
+MIGRATION = SYSDYN.Migration : L0.Library\r
+            \r
+MIGRATION.fromModel1 : L0.Migration\r
+  L0.Migration.format "sysdynModel"\r
+  L0.Migration.from 1\r
+  L0.Migration.step FROM16TO17\r
+  L0.Migration.priority 1.0\r
+  \r
+MIGRATION.fromModule1 : L0.Migration\r
+  L0.Migration.format "sysdynModule"\r
+  L0.Migration.from 1\r
+  L0.Migration.step FROM16TO17\r
+  L0.Migration.priority 1.0\r
+\r
+MIGRATION.fromFunctionLibrary1 : L0.Migration\r
+  L0.Migration.format "sysdynFunctionLibrary"\r
+  L0.Migration.from 1\r
+  L0.Migration.step FROM16TO17\r
+  L0.Migration.priority 1.0    \r
+              \r
+FROM16TO17 = MIGRATION."from1.6to1.7" : L0.MigrationSequence\r
+    @L0.list\r
+        FROM16TO17.Ontologies\r
+        FROM16TO17.Spreadsheets\r
+        FROM16TO17.SysdynChanges\r
+        FROM16TO17.OrderedSetsToLists\r
+        FROM16TO17.Custom : L0.MigrationStep\r
+\r
+FROM16TO17.Ontologies : L0.NamespaceMigrationStep\r
+  @L0.list\r
+    _\r
+      @move "http://www.simantics.org/Layer0-" "1.0" "1.1"\r
+    _\r
+      @move "http://www.simantics.org/Layer0X-" "1.0" "1.1"\r
+    _\r
+      @move"http://www.simantics.org/G2D-" "1.0" "1.1"\r
+    _\r
+      @move"http://www.simantics.org/Structural-" "1.0" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/Structural-" "1.1" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/Diagram-" "2.1" "2.2"\r
+    _\r
+      @move"http://www.simantics.org/Simulation-" "1.0" "1.1"\r
+    _\r
+      @move"http://www.simantics.org/Diagram-" "1.0" "1.1"\r
+    _\r
+      @move"http://www.simantics.org/Modeling-" "1.1" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/Project-" "1.1" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/Spreadsheet-" "1.1" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/Viewpoint-" "1.1" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/Image2-" "1.1" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/Color-" "1.0" "1.1"\r
+    _\r
+      @move"http://www.simantics.org/Action-" "1.0" "1.1"\r
+    _\r
+      @move"http://www.simantics.org/Silk-" "1.0" "1.1"\r
+    _\r
+      @move"http://www.simantics.org/Issue-" "1.1" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/User-" "1.0" "1.1"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Components" "www.semantum.fi/Simupedia-1.0/Components"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Symbols" "www.semantum.fi/Simupedia-1.0/Symbols"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Properties" "www.semantum.fi/Simupedia-1.0/Properties"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/DiagramRelations" "www.simantics.org/Documentation-1.2/DiagramRelations"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Relations" "www.simantics.org/Documentation-1.2/Relations"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Terminals" "www.simantics.org/Documentation-1.2/Terminals"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Role" "www.semantum.fi/Simupedia-1.0/Role"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/RelationTypeConstraint" "www.simantics.org/Documentation-1.2/RelationTypeConstraint"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Component" "www.semantum.fi/Simupedia-1.0/Components/Component"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/DocumentComponent" "www.simantics.org/Documentation-1.2/DocumentComponent"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/roleList" "www.semantum.fi/Simupedia-1.0/roleList"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/CommandConnectionType" "www.simantics.org/Documentation-1.2/CommandConnectionType"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/DataDefinitionConnectionType" "www.simantics.org/Documentation-1.2/DataDefinitionConnectionType"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/DataConnectionType" "www.simantics.org/Documentation-1.2/DataConnectionType"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Functions" "www.semantum.fi/Simupedia-1.0/Functions"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/DocumentDiagram" "www.simantics.org/Documentation-1.2/DocumentDiagram"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/ConnectionType" "www.simantics.org/Documentation-1.2/ConnectionType"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Document/IsConnectedToChild" "www.simantics.org/Documentation-1.2/Document/IsConnectedToChild"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1/Document" "www.semantum.fi/Simupedia-1.0/Document"\r
+    _\r
+      @move"http://" "www.simantics.org/Documentation-1.1" "www.simantics.org/Documentation-1.2"\r
+    _\r
+      @move"http://" "www.simantics.org/DocumentWorkbench-1.0" "www.semantum.fi/SimupediaWorkbench-1.0"\r
+      \r
+      \r
+      \r
+    _\r
+      @move"http://www.simantics.org/Document-" "1.1" "1.2"\r
+    _\r
+      @move"http://www.simantics.org/SelectionView-" "1.1" "1.2"\r
+      \r
+FROM16TO17.Spreadsheets : L0.NamespaceMigrationStep\r
+  @L0.list\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "HasContent" "Cell/content"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "FitRows" "Dimensions/fitRows"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "FitColumns" "Dimensions/fitColumns"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "ColumnCount" "Dimensions/columnCount"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "ColumnLabels" "Headers/columnLabels"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "RowCount" "Dimensions/rowCount"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "ColumnWidths" "Headers/columnWidths"      \r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "ContentOf" "Cell/content/Inverse"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "FitRowsOf" "Dimensions/fitRows/Inverse"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "FitColumnsOf" "Dimensions/fitColumns/Inverse"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "ColumnCountOf" "Dimensions/columnCount/Inverse"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "ColumnLabelsOf" "Headers/columnLabels/Inverse"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "RowCountOf" "Dimensions/rowCount/Inverse"\r
+    _\r
+      @move "http://www.simantics.org/Spreadsheet-1.2/" "ColumnWidthsOf" "Headers/columnWidths/Inverse"        \r
+\r
+FROM16TO17.SysdynChanges : L0.NamespaceMigrationStep\r
+  @L0.list\r
+    _\r
+      @move "http://www.simantics.org/Sysdyn-1.1/" "HasTail" "Variable/HasTail"\r
+    _\r
+      @move "http://www.simantics.org/Sysdyn-1.1/" "HasHead" "Variable/HasHead"\r
+    _\r
+      @move "http://www.simantics.org/Sysdyn-1.1/" "SharedModuleOntolofgy" "SharedModuleOntology"\r
+    _\r
+      @move "http://www.simantics.org/Sysdyn-1.1/" "HasUnit" "Variable/unit"\r
+      \r
+                  \r
+FROM16TO17.OrderedSetsToLists : L0.OrderedSetToListMigrationStep\r
+    @L0.list\r
+        _ : L0.OrderedSetToListMigrationStep.Change\r
+            L0.OrderedSetToListMigrationStep.entityType "http://www.simantics.org/Sysdyn-1.1/Variable"\r
+            L0.OrderedSetToListMigrationStep.orderedSetRelation "http://www.simantics.org/Sysdyn-1.1/Variable/expressions"\r
+            L0.OrderedSetToListMigrationStep.orderedSetType "http://www.simantics.org/Sysdyn-1.1/Expressions"\r
+            L0.OrderedSetToListMigrationStep.listRelation "http://www.simantics.org/Sysdyn-1.1/Variable/expressionList"\r
+            L0.OrderedSetToListMigrationStep.listType "http://www.simantics.org/Layer0-1.1/List"\r
+        _ : L0.OrderedSetToListMigrationStep.Change\r
+            L0.OrderedSetToListMigrationStep.entityType "http://www.simantics.org/Sysdyn-1.1/Variable"\r
+            L0.OrderedSetToListMigrationStep.orderedSetRelation "http://www.simantics.org/Sysdyn-1.1/Variable/arrayIndexes"\r
+            L0.OrderedSetToListMigrationStep.orderedSetType "http://www.simantics.org/Sysdyn-1.1/ArrayIndexes"\r
+            L0.OrderedSetToListMigrationStep.listRelation "http://www.simantics.org/Sysdyn-1.1/Variable/arrayIndexesList"\r
+            L0.OrderedSetToListMigrationStep.listType "http://www.simantics.org/Layer0-1.1/List"\r
+        _ : L0.OrderedSetToListMigrationStep.Change\r
+            L0.OrderedSetToListMigrationStep.entityType "http://www.simantics.org/Sysdyn-1.1/Enumeration"\r
+            L0.OrderedSetToListMigrationStep.orderedSetRelation "http://www.simantics.org/Sysdyn-1.1/Enumeration/enumerationIndexes"\r
+            L0.OrderedSetToListMigrationStep.orderedSetType "http://www.simantics.org/Sysdyn-1.1/EnumerationIndexes"\r
+            L0.OrderedSetToListMigrationStep.listRelation "http://www.simantics.org/Sysdyn-1.1/Enumeration/enumerationIndexList"\r
+            L0.OrderedSetToListMigrationStep.listType "http://www.simantics.org/Layer0-1.1/List"\r
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/ModelicaArrayFunctions.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/ModelicaArrayFunctions.pgraph
new file mode 100644 (file)
index 0000000..847db26
--- /dev/null
@@ -0,0 +1,536 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+\r
+MAF = <http://www.simantics.org/Sysdyn-1.1/Built-in Functions/Modelica Array Functions> : SYSDYN.SysdynModelicaFunctionLibrary\r
+\r
+\r
+\r
+MAF.scalar : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """scalar(A)\r
+\r
+Returns a one-element array as scalar.\r
+\r
+Returns the single element of array A. size(A,i) = 1 is required for 1 <= i <= ndims(A)."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.scalar.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.scalar.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+\r
+\r
+\r
+MAF.vector : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """vector(A)\r
+\r
+Returns an array with one non-singleton dimension as vector.\r
+\r
+Returns a 1-vector, if A is a scalar and otherwise returns a vector containing all the elements of the array, provided there is at most one dimension size > 1.\r
+\r
+Examples:\r
+Real A[1,2,1] = {{{3},{4}}};\r
+Real v[2] = vector(A);  // = {3,4}"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.vector.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.vector.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MAF.matrix : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """matrix(A)\r
+\r
+Returns the first two dimensions of an array as matrix.\r
+\r
+Returns promote(A,2), if A is a scalar or vector and otherwise returns the elements of the first two dimensions as a matrix. size(A,i) = 1 is required for 2 < i <= ndims(A).\r
+Function promote(A,n) fills dimensions of size 1 from the right to array A upto dimension n, where "n > ndims(A)" is required. Let C = promote(A,n), with nA = ndims(A), then\r
+ndims(C) = n,\r
+size(C,j) = size(A,j) for 1 <= j <= nA,\r
+size(C,j) = 1 for nA+1 <= j <= n,\r
+C[i_1, ..., i_nA, 1, ..., 1] = A[i_1, ..., i_nA]."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.matrix.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.matrix.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MAF.ndims : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """ndims(A)\r
+\r
+Return number of array dimensions.\r
+\r
+Returns the number of dimensions k of array expression A, with k >= 0."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.ndims.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.ndims.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Integer"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    \r
+    \r
+    \r
+MAF.size : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """size(A,i)\r
+size(A)\r
+\r
+Returns dimensions of an array.\r
+\r
+The first form returns the size of dimension i of array expression A where i shall be > 0 and <= ndims(A).\r
+\r
+The second form returns a vector of length ndims(A) containing the dimension sizes of A.\r
+\r
+Examples:\r
+Real A[8,4,5];\r
+Integer n3   = size(A,3);  // = 5\r
+Integer n[:] = size(A);    // = {8,4,5}"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.size.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+            MAF.size.i : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional true\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.size.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    \r
+    \r
+    \r
+MAF.array : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """array(A,B,C,...)\r
+\r
+The constructor function array(A,B,C,...) constructs an array from its arguments.\r
+\r
+The constructor function array(A,B,C,...) constructs an array from its arguments according to the following rules:\r
+  * Size matching: All arguments must have the same sizes, i.e., size(A)=size(B)=size(C)=...\r
+  * All arguments must be type compatible expressions giving the type of the elements. The data type of the result array is the maximally expanded type of the arguments. Real and Integer subtypes can be mixed resulting in a Real result array where the Integer numbers have been transformed to Real numbers.\r
+  * Each application of this constructor function adds a one-sized dimension to the left in the result compared to the dimensions of the argument arrays, i.e., ndims(array(A,B,C)) = ndims(A) + 1 = ndims(B) + 1, ...\r
+  * {A, B, C, ...} is a shorthand notation for array(A, B, C, ...).\r
+  * There must be at least one argument [i.e., array() or {} are not defined]."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.array.A : SYSDYN.SysdynModelicaFunction.VariableLengthInput\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+                SYSDYN.SysdynModelicaFunction.VariableLengthInput.shownLabels _ : L0.List\r
+                    @L0.list\r
+                        MAF.array.A.A : L0.String\r
+                        MAF.array.A.B : L0.String\r
+                        MAF.array.A.C : L0.String\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.array.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MAF.cat : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """cat(k,A,B,C,...)\r
+\r
+The function cat(k,A,B,C,...)concatenates arrays A,B,C,... along dimension k.\r
+\r
+The function cat(k,A,B,C,...)concatenates arrays A,B,C,... along dimension k according to the following rules:\r
+  * Arrays A, B, C, ... must have the same number of dimensions, i.e., ndims(A) = ndims(B) = ...\r
+  * Arrays A, B, C, ... must be type compatible expressions giving the type of the elements of the result. The maximally expanded types should be equivalent. Real and Integer subtypes can be mixed resulting in a Real result array where the Integer numbers have been transformed to Real numbers.\r
+  * k has to characterize an existing dimension, i.e., 1 <= k <= ndims(A) = ndims(B) = ndims(C); k shall be an integer number.\r
+  * Size matching: Arrays A, B, C, ... must have identical array sizes with the exception of the size of dimension k, i.e., size(A,j) = size(B,j), for 1 <= j <= ndims(A) and j <> k.\r
+    \r
+Examples:\r
+Real[2,3] r1 = cat(1, {{1.0, 2.0, 3}}, {{4, 5, 6}});\r
+Real[2,6] r2 = cat(2, r1, 2*r1);"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.cat.k : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+            MAF.cat.A : SYSDYN.SysdynModelicaFunction.VariableLengthInput\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+                SYSDYN.SysdynModelicaFunction.VariableLengthInput.shownLabels _ : L0.List\r
+                    @L0.list\r
+                        MAF.cat.A.A : L0.String\r
+                        MAF.cat.A.B : L0.String\r
+                        MAF.cat.A.C : L0.String\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.cat.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+\r
+\r
+    \r
+MAF.zeros : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """zeros(n1, n2, n3, ...)\r
+\r
+Returns a zero array.\r
+\r
+Returns the n1 x n2 x n3 x ... Integer array with all elements equal to zero (ni >= 0)."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.zeros.n : SYSDYN.SysdynModelicaFunction.VariableLengthInput\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+                SYSDYN.SysdynModelicaFunction.VariableLengthInput.shownLabels _ : L0.List\r
+                    @L0.list\r
+                        MAF.zeros.n.n1 : L0.String\r
+                        MAF.zeros.n.n2 : L0.String\r
+                        MAF.zeros.n.n3 : L0.String\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.zeros.o : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Integer"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Integer n annotation(__OpenModelica_varArgs = true);\r
+    output Integer o[:];"""\r
+    \r
+    \r
+    \r
+MAF.ones : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """ones(n1, n2, n3, ...)\r
+\r
+Returns an array with "1" elements.\r
+\r
+Return the n1 x n2 x n3 x ... Integer array with all elements equal to one (ni >=0 )."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.ones.n : SYSDYN.SysdynModelicaFunction.VariableLengthInput\r
+                SYSDYN.Variable.type "Integer"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+                SYSDYN.SysdynModelicaFunction.VariableLengthInput.shownLabels _ : L0.List\r
+                    @L0.list\r
+                        MAF.ones.n.n1 : L0.String\r
+                        MAF.ones.n.n2 : L0.String\r
+                        MAF.ones.n.n3 : L0.String\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.ones.o : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Integer"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Integer n annotation(__OpenModelica_varArgs = true);\r
+    output Integer o[:];"""\r
+    \r
+    \r
+    \r
+MAF.fill : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """fill(s, n1, n2, n3, ...)\r
+\r
+Return a Real, Integer, Boolean or String array with all elements equal\r
+\r
+Returns the n1 x n2 x n3 x ... array with all elements equal to scalar or array expression s (ni >= 0). The returned array has the same type as s. Recursive definition:\r
+fill(s,n1,n2,n3, ...) = fill(fill(s,n2,n3, ...), n1);\r
+fill(s,n) = {s,s,..., s}\r
+\r
+Examples:\r
+Real    mr[2,2] = fill(-1,2,2);  // = [-1,-1;-1,-1]\r
+Boolean vb[3]   = fill(true,3);  // = {true, true, true}"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.fill.s : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MAF.fill.n : SYSDYN.SysdynModelicaFunction.VariableLengthInput\r
+                SYSDYN.Variable.type "Integer"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+                SYSDYN.SysdynModelicaFunction.VariableLengthInput.shownLabels _ : L0.List\r
+                    @L0.list\r
+                        MAF.fill.n.n1 : L0.String\r
+                        MAF.fill.n.n2 : L0.String\r
+                        MAF.fill.n.n3 : L0.String\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.fill.o : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input OpenModelica.Internal.BuiltinType s;\r
+    input Integer n annotation(__OpenModelica_varArgs = true);\r
+    output OpenModelica.Internal.BuiltinType o[:];"""\r
+    \r
+    \r
+    \r
+MAF.identity : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """identity(n)\r
+\r
+Returns the identity matrix of the desired size.\r
+\r
+Returns the n x n Integer identity matrix, with ones on the diagonal and zeros at the other places."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.identity.n : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Integer "\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.identity.outArray : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Integer "\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Integer n;\r
+    output Integer[n,n] outArray;"""\r
+    \r
+    \r
+    \r
+MAF.diagonal : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """diagonal(v)\r
+\r
+Returns a diagonal matrix.\r
+\r
+Returns a square matrix with the elements of vector v on the diagonal and all other elements zero."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.diagonal.v : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.diagonal.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MAF.linspace : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """linspace(x1, x2, n)\r
+\r
+Return Real vector with equally spaced elements.\r
+\r
+Returns a Real vector with n equally spaced elements, such that\r
+v[i] = x1 + (x2-x1)*(i-1)/(n-1) for 1 <= i <= n.\r
+It is required that n >= 2. The arguments x1 and x2 shall be Real or Integer scalar expressions.\r
+\r
+Example:\r
+Real v[:] = linspace(1,7,4);  // = {1, 3, 5, 7}"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.linspace.x1 : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MAF.linspace.x2 : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MAF.linspace.n : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Integer"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.linspace.v : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real x1 "start";\r
+    input Real x2 "end";\r
+    input Integer n "number";\r
+    output Real v[n];"""\r
+    \r
+    \r
+    \r
+MAF.min : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """min(A)\r
+\r
+Returns the smallest element.\r
+\r
+Returns the smallest element of array expression A."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.min.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.min.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MAF.max : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """max(A)\r
+\r
+Returns the largest element.\r
+\r
+Returns the largest element of array expression A."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.max.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.max.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MAF.sum : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """sum(A)\r
+sum(e(i, ..., j) for i in u, ..., j in v)\r
+\r
+Returns the scalar sum.\r
+\r
+The first form returns the scalar sum of all the elements of array expression A:\r
+A[1,...,1]+A[2,...,1]+....+A[end,...,1]+A[end,...,end]\r
+\r
+The second form is a reduction expression and returns the sum of the expression e(i, ..., j) evaluated for all combinations of i in u, ..., j in v:\r
+e(u[1],...,v[1]) + e(u[2],...,v[1]) + ... +\r
+e(u[end],...,v[1]) + ... + e(u[end],...,v[end])\r
+The type of sum(e(i, ..., j) for i in u, ..., j in v) is the same as the type of e(i,...j).\r
+\r
+Example:\r
+sum(i for i in 1:10)  // Gives  1+2+...+10=55\r
+    // Read it as: compute the sum of i for i in the range 1 to 10."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.sum.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.sum.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MAF.product : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """product(A)\r
+product(e(i, ..., j) for i in u, ..., j in v)\r
+\r
+Returns the scalar product\r
+\r
+The first form returns the scalar product of all the elements of array expression A:\r
+A[1,...,1]*A[2,...,1]*....*A[end,...,1]*A[end,...,end]\r
+\r
+The second form is a reduction expression and returns the product of the expression e(i, ..., j) evaluated for all combinations of i in u, ..., j in v:\r
+e(u[1],...,v[1]) * e(u[2],...,v[1]) * ... *\r
+e(u[end],...,v[1]) * ... * e(u[end],...,v[end])\r
+The type of product(e(i, ..., j) for i in u, ..., j in v) is the same as the type of e(i,...j).\r
+\r
+Example:\r
+{product(j for j in 1:i) for i in 0:4} // = {1,1,2,6,24}"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.product.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.product.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    \r
+    \r
+    \r
+MAF.transpose : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """transpose(A)\r
+\r
+Transpose of a matrix or permutation of the first two dimensions of an array\r
+\r
+Permutes the first two dimensions of array A. It is an error, if array A does not have at least 2 dimensions."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.transpose.A : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.transpose.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MAF.cross : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """cross(x,y)\r
+\r
+Return cross product of two vectors.\r
+\r
+Returns the 3-vector cross product of the 3-vectors x and y.\r
+cross(x,y) = vector( [ x[2]*y[3]-x[3]*y[2];\r
+                   x[3]*y[1]-x[1]*y[3];\r
+                   x[1]*y[2]-x[2]*y[1] ] );"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.cross.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MAF.cross.y : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'q"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.cross.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p*'q"\r
+    \r
+    \r
+    \r
+MAF.skew : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """skew(x)\r
+\r
+Returns the skew matrix that is associated with a vector\r
+\r
+Returns the 3 x 3 skew symmetric matrix associated with a 3-vector, i.e.,\r
+cross(x,y) = skew(x)*y;\r
+skew(x) = [ 0   , -x[3],  x[2];\r
+           x[3],  0   , -x[1];\r
+           -x[2],  x[1],  0   ];"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MAF.skew.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MAF.skew.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+                
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/ModelicaFunctions.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/ModelicaFunctions.pgraph
new file mode 100644 (file)
index 0000000..c692447
--- /dev/null
@@ -0,0 +1,804 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+\r
+MF = <http://www.simantics.org/Sysdyn-1.1/Built-in Functions/Modelica Functions> : SYSDYN.SysdynModelicaFunctionLibrary\r
+\r
+\r
+\r
+MF.abs : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """abs(v)\r
+\r
+Absolute value.\r
+\r
+Returns the absolute value of v. Is expanded into "(if v >= 0 then v else -v)" (into "noEvent(if v >= 0 then v else -v)", to be precise). Argument v needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.abs.v : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.abs.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    \r
+    \r
+    \r
+MF.acos : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """acos(u)\r
+\r
+Inverse cosine.\r
+\r
+Returns the inverse of cos of u, with -1 <= u <= +1. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.acos.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.acos.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u;\r
+    output Real y;"""\r
+\r
+\r
+\r
+MF.asin : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """asin(u)\r
+\r
+Inverse sine.\r
+\r
+Returns the inverse of sin of u, with -1 <= u <= +1. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.asin.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.asin.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u;\r
+    output Real y;"""\r
+\r
+\r
+\r
+MF.atan : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """atan(u)\r
+\r
+Inverse tangent.\r
+\r
+Returns the inverse of tan of u, with -INF < u < INF. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.atan.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.atan.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.atan2 : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """atan2(u1,u2)\r
+\r
+Four quadrant inverse tangent.\r
+\r
+Returns y = atan2(u1,u2) such that tan(y) = u1/u2 and y is in the range -pi < y <= pi. u2 may be zero, provided u1 is not zero. Usually u1, u2 is provided in such a form that u1 = sin(y) and u2 = cos(y). Arguments u1 and u2 need to be Integer or Real expressions."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.atan2.u1 : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+            MF.atan2.u2 : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.atan2.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u1;\r
+    input Real u2;\r
+    output Real z;"""\r
+        \r
+        \r
+        \r
+MF.ceil : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """ceil(x)\r
+\r
+Round a Real number towards plus infinity\r
+\r
+Returns the smallest integer not less than x (i.e. the closest integer above x)."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.ceil.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.ceil.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real x;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.cos : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """cos(u)\r
+\r
+Cosine.\r
+\r
+Returns the cosine of u, with -INF < u < INF Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.cos.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.cos.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.cosh : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """cosh(u)\r
+\r
+Hyperbolic cosine.\r
+\r
+Returns the cosh of u, with -INF < u < INF. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.cosh.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.cosh.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.delay : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """delay(expr, delayTime, delayMax)\r
+delay(expr, delayTime)\r
+\r
+Returns the value of expr at the time time-delayTime. The value of expr is returned when time <= time.start + delayTime.\r
+\r
+Returns "expr(time - delayTime)" for time > time.start + delayTime and "expr(time.start)" for time <= time.start + delayTime. The arguments, i.e., expr, delayTime and delayMax, need to be subtypes of Real. delayMax needs to be additionally a parameter expression. The following relation shall hold: 0 <= delayTime <= delayMax, otherwise an error occurs. If delayMax is not supplied in the argument list, delayTime need to be a parameter expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.delay.expr : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MF.delay.delayTime : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+            MF.delay.delayMax : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional true\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.delay.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+        \r
+        \r
+        \r
+MF.der : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """der(expr)\r
+\r
+Time derivative of expr. expr must be have continuous-time variability.\r
+\r
+The time derivative of expression expr. If the expression expr is a scalar it needs to be a subtype of Real. The expression and all its subexpressions must be differentiable. If expr is an array, the operator is applied to all elements of the array. For Real parameters and constants the result is a zero scalar or array of the same size as the variable.\r
+\r
+Example:\r
+  Real x, xdot1, xdot2;\r
+equation\r
+  xdot1 = der(x);\r
+  xdot2 = der(x*sin(x));"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.der.expr : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.der.dexpr : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p/TIME"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """  input Real expr(unit = "'p");\r
+  output Real dexpr(unit = "'p/s");"""\r
+        \r
+        \r
+        \r
+MF.div : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """div(x, y)\r
+\r
+Integer part of division of two Real numbers.\r
+\r
+Returns the algebraic quotient x/y with any fractional part discarted (also known as truncation toward zero). E.g. div(10,3) = 3."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.div.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MF.div.y : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'q"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.div.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p/'q"\r
+        \r
+        \r
+        \r
+MF.edge : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """edge(b)\r
+\r
+Indicate rising edge\r
+\r
+Returns true when the value of the boolean expression b changes. Expanded into (b and not pre(b))."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.edge.b : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Boolean"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.edge.edgeEvent : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Boolean"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Boolean b;\r
+    output Boolean edgeEvent;"""\r
+        \r
+        \r
+        \r
+MF.exp : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """exp(u)\r
+\r
+Exponential, base e.\r
+\r
+Returns the base e exponential of u, with -INF < u < INF Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.exp.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.exp.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u(unit = "1");\r
+    output Real y(unit = "1");"""\r
+        \r
+        \r
+        \r
+MF.floor : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """floor(x)\r
+\r
+Round Real number towards minus infinity\r
+\r
+Returns the largest integer not greater than x (i.e. the closest integer below x)."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.floor.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.floor.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real x;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.initial : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """initial()\r
+\r
+True during initialization.\r
+\r
+Returns true during the initialization phase and false otherwise."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.initial.isInitial : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Boolean"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    output Boolean isInitial;"""\r
+\r
+\r
+\r
+MF.log : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """log(u)\r
+\r
+Natural (base e) logarithm.\r
+\r
+Returns the base e logarithm of u, with u > 0. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.log.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.log.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u(unit = "1");\r
+    output Real y(unit = "1");"""\r
+        \r
+        \r
+        \r
+MF.log10 : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """log10(u)\r
+\r
+Base 10 logarithm. (u > 0)\r
+\r
+Returns the base 10 logarithm of u, with u > 0. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.log10.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.log10.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u(unit = "1");\r
+    output Real y(unit = "1");"""\r
+        \r
+        \r
+        \r
+MF.max : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """max(x,y)\r
+max(e(i, ..., j) for i in u, ..., j in v)\r
+\r
+Returns the largest element.\r
+\r
+The first form returns the largest element of the scalars x and y.\r
+\r
+The second form is a reduction expression and returns the largest value of the scalar expression e(i, ..., j) evaluated for all combinations of i in u, ..., j in v\r
+\r
+Example:\r
+max(i^2 for i in {3,7,6})  // = 49"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.max.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MF.max.y : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.max.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+        \r
+        \r
+        \r
+MF.min : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """min(x,y)\r
+min(e(i, ..., j) for i in u, ..., j in v)\r
+\r
+Returns the smallest element.\r
+\r
+The first form returns the smallest element of the scalars x and y.\r
+\r
+The second form is a reduction expression and returns the smallest value of the scalar expression e(i, ..., j) evaluated for all combinations of i in u, ..., j in v\r
+    \r
+Example:\r
+min(i^2 for i in {3,7,6})  // = 9"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.min.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MF.min.y : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.min.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+        \r
+        \r
+        \r
+MF.mod : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """mod(x, y)\r
+\r
+Integer modulus of a division of two Real numbers.\r
+\r
+Returns the integer modulus of x/y: mod(x,y) = x - floor(x/y) * y."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.mod.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MF.mod.y : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.mod.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+        \r
+        \r
+        \r
+MF.noEvent : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """noEvent(expr)\r
+\r
+Turn off event triggering.\r
+\r
+noEvent around an expression causes the expression to NOT generate event.\r
+Important:\r
+If you want a condition to be checked only on time steps, use noEvent.\r
+(e.g. if noEvent(value >= 1) then ... else ...)"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.noEvent.expr : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.noEvent.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+        \r
+        \r
+        \r
+MF.pre : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """pre(y)\r
+\r
+Returns the preceding value of y from time event that has occured before current time.\r
+\r
+Returns the "left limit" y(tpre) of variable y(t) at a time instant t. At an event instant, y(tpre) is the value of y after the last event iteration at time instant t. The pre operator can be applied if the following three conditions are fulfilled simultaneously:\r
+  * variable y is a subtype of a simple type\r
+  * y is a discrete-time expression\r
+  * the operator is not applied in a function class\r
+The first value of pre(y) is determined in the initialization phase.\r
+A new event is triggered if at least for one variable v "pre(v) <> v" after the active model equations are evaluated at an event instant. In this case the model is at once reevaluated. This evaluation sequence is called "event iteration". The integration is restarted, if for all v used in pre-operators the following condition holds: "pre(v) == v"."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.pre.y : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.pre.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+\r
+\r
+        \r
+MF.rem : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """rem(x, y)\r
+\r
+Integer remainder of the division of two Real numbers.\r
+\r
+Returns the integer remainder of x/y: rem(x,y) = x - div(x,y) * y."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.rem.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MF.rem.y : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.rem.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+        \r
+        \r
+        \r
+MF.sample : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """sample(start, interval)\r
+\r
+Trigger time events.\r
+\r
+Returns true and triggers time events at times start + i * interval (i=0,1,...)."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.sample.start : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+            MF.sample.interval : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.sample.isSample : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Boolean"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    parameter input Real start(fixed = false);\r
+    parameter input Real interval(fixed = false);\r
+    output Boolean isSample;"""\r
+        \r
+        \r
+        \r
+MF.semiLinear : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """semiLinear(x, positiveSlope, negativeSlope)\r
+\r
+Returns "if x >= 0 then positiveSlope*x else negativeSlope*x" and handle x=0 in a meaningful way.\r
+\r
+Returns "if x >= 0 then positiveSlope*x else negativeSlope*x". In some situations, equations with the semiLinear function become underdetermined if the first argument (x) becomes zero, i.e., there are an infinite number of solutions. It is recommended that the following rules are used to transform the equations during the translation phase in order to select one meaningful solution in such cases:\r
+                \r
+Rule 1: The equations\r
+y = semiLinear(x, sa, s1);\r
+y = semiLinear(x, s1, s2);\r
+y = semiLinear(x, s2, s3);\r
+   ...\r
+y = semiLinear(x, sN, sb);\r
+may be replaced by\r
+s1 = if x >= 0 then sa else sb\r
+s2 = s1;\r
+s3 = s2;\r
+   ...\r
+sN = sN-1;\r
+y = semiLinear(x, sa, sb);\r
+\r
+Rule 2: The equations\r
+x = 0;\r
+y = 0;\r
+y = semiLinear(x, sa, sb);\r
+may be replaced by\r
+x = 0\r
+y = 0;\r
+sa = sb;"""    \r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.semiLinear.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            MF.semiLinear.positiveSlope : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'q"\r
+            MF.semiLinear.negativeSlope : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'q"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.semiLinear.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p*'q"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real x;\r
+    input Real positiveSlope;\r
+    input Real negativeSlope;\r
+    output Real result;"""\r
+\r
+\r
+\r
+MF.sign : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """sign(v)\r
+\r
+Sign function of a Real or Integer number.\r
+\r
+Returns -1 if v is negative, 1 if v is positive. Expanded into "(if v > 0 then 1 else if v < 0 then -1 else 0)"."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.sign.v : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.sign.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Integer"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real v;\r
+    output Integer result;"""\r
+        \r
+        \r
+        \r
+MF.sin : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """sin(u)\r
+\r
+Sine.\r
+\r
+Returns the sine of u, with -INF < u < INF. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.sin.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.sin.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real x;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.sinh : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """sinh(u)\r
+\r
+Hyperbolic sine.\r
+\r
+Returns the sinh of u, with -INF < u < INF. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.sinh.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.sinh.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real x;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.smooth : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """smooth(p, expr)\r
+\r
+Indicate smoothness of expression.\r
+\r
+If p>=0 smooth(p, expr) returns expr and states that expr is p times continuously differentiable, i.e.: expr is continuous in all real variables appearing in the expression and all partial derivatives with respect to all appearing real variables exist and are continuous up to order p.\r
+The only allowed types for expr in smooth are: real expressions, arrays of allowed expressions, and records containing only components of allowed expressions."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.smooth.p : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+            MF.smooth.expr : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.smooth.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+        \r
+        \r
+        \r
+MF.sqrt : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """sqrt(v)\r
+\r
+Square root.\r
+\r
+Square root of v. The value of v must be greater or equal to 0 or an assertion error occurs."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.sqrt.v : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.sqrt.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real v(unit = "'p");\r
+    output Real y(unit = "'p(1/2)");"""\r
+        \r
+        \r
+        \r
+MF.tan : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """tan(u)\r
+\r
+Tangent.\r
+\r
+Returns the tangent of u, with -INF < u < INF (if u is a multiple of (2n-1)*pi/2, y = tan(u) is +/- infinity). Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.tan.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.tan.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real u;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.tanh : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """tanh(u)\r
+\r
+Hyperbolic tangent.\r
+\r
+Returns the tanh of u, with -INF < u < INF. Argument u needs to be an Integer or Real expression."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            MF.tanh.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.tanh.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    input Real x;\r
+    output Real y;"""\r
+        \r
+        \r
+        \r
+MF.terminal : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """terminal()\r
+\r
+True after successful analysis\r
+\r
+Returns true at the end of a successful simulation."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            MF.terminal.isTerminal : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Boolean"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface """    output Boolean isTerminal;"""\r
+        
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/Profiles.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/Profiles.pgraph
new file mode 100644 (file)
index 0000000..2fe4a7b
--- /dev/null
@@ -0,0 +1,45 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+L0X = <http://www.simantics.org/Layer0X-1.1>\r
+DIA = <http://www.simantics.org/Diagram-2.2>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+\r
+PROFILES = SYSDYN.Profiles : L0.Library\r
+\r
+\r
+// TEMPLATE\r
+groupStyleEntry : L0.Template\r
+    @template %subject %style %group\r
+        %subject : DIA.GroupStyleProfileEntry\r
+            DIA.ProfileEntry.HasStyle %style\r
+            DIA.ProfileEntry.HasGroup %group\r
+\r
+\r
+// PROFILES\r
+SYSDYN.SimulationPlaybackProfile <T DIA.Profile\r
+SYSDYN.DefaultProfile <T DIA.Profile\r
+\r
+// STYLES\r
+SYSDYN.SimulationPlaybackStyle : DIA.Style\r
+SYSDYN.IssueStyle : DIA.Style\r
+SYSDYN.ShadowStyle : DIA.Style\r
+\r
+// GROUPS\r
+SYSDYN.AllElementsGroup : DIA.TypeGroup\r
+    L0.HasLabel "Element"\r
+    DIA.TypeGroup.HasType DIA.Element\r
+    \r
+// ENTRIES\r
+PROFILES.SimulationPlaybackColours\r
+    L0.HasLabel "Playback colours"\r
+    @groupStyleEntry SYSDYN.SimulationPlaybackStyle SYSDYN.AllElementsGroup\r
+    \r
+PROFILES.IssueWarnings\r
+    L0.HasLabel "Issue warnings"\r
+    @groupStyleEntry SYSDYN.IssueStyle SYSDYN.AllElementsGroup\r
+\r
+PROFILES.ShadowVisualizations\r
+    L0.HasLabel "Shadow variable visualizations"\r
+    @groupStyleEntry SYSDYN.ShadowStyle SYSDYN.AllElementsGroup\r
+\r
+      \r
+    
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/PropertyViewpoints.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/PropertyViewpoints.pgraph
new file mode 100644 (file)
index 0000000..f9f5246
--- /dev/null
@@ -0,0 +1,86 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+VP = <http://www.simantics.org/Viewpoint-1.2>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+\r
+/////////////////////////////////\r
+/// History datasets\r
+/////////////////////////////////\r
+HDBC = SYSDYN.HistoryDataset.HistoryDatasetVariablesBrowseContext : VP.BrowseContext\r
+\r
+HDBC.StringNodeType <T VP.NodeType\r
+    @L0.assert VP.HasContentType "java.lang.String"\r
+\r
+HDBC.VariableChildRule : VP.ChildRule\r
+HDBC.VariableLabelRule : VP.LabelRule\r
+\r
+HDBC\r
+    @VP.customChildRule SYSDYN.HistoryDataset HDBC.VariableChildRule\r
+        SYSDYN.HistoryDataset.FoundVariableNameNode : HDBC.StringNodeType\r
+\r
+HDBC        \r
+    @VP.customLabelRule SYSDYN.HistoryDataset.FoundVariableNameNode HDBC.VariableLabelRule\r
+    \r
+HDBC    \r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType SYSDYN.HistoryDataset\r
+        VP.VisualsContribution.HasRule VP.PassThruSorterRule\r
+    \r
+/////////////////////////////////\r
+/// Module parameters\r
+/////////////////////////////////\r
+\r
+POBC = SYSDYN.Module.ParameterOverrideBrowseContext : VP.BrowseContext\r
+\r
+POBC.NodeType <T VP.NodeType\r
+    @L0.assert VP.HasContentType "java.lang.Object"\r
+\r
+POBC.ParameterChildRule : VP.ChildRule\r
+POBC.ParameterLabelRule : VP.LabelRule\r
+POBC.ParameterLabelDecorationRule : VP.LabelDecorationRule\r
+POBC.ParameterModifierRule : VP.ModifierRule\r
+POBC.ParameterSorterRule : VP.SorterRule\r
+\r
+POBC\r
+    @VP.customChildRule L0.Entity POBC.ParameterChildRule\r
+        POBC.Node : POBC.NodeType\r
+\r
+POBC        \r
+    @VP.customLabelRule POBC.Node POBC.ParameterLabelRule\r
+    \r
+POBC        \r
+    @VP.customModifierRule POBC.Node POBC.ParameterModifierRule\r
+    \r
+POBC \r
+    @VP.customLabelDecorationRule POBC.Node POBC.ParameterLabelDecorationRule    \r
+    \r
+POBC    \r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType L0.Entity\r
+        VP.VisualsContribution.HasRule POBC.ParameterSorterRule\r
+\r
+/////////////////////////////////////////////\r
+/// Sensitivity experiment parameters\r
+/////////////////////////////////////////////\r
+SPBC = SYSDYN.SensitivityAnalysisExperiment.ParameterBrowseContext : VP.BrowseContext\r
+SPAC = SYSDYN.SensitivityAnalysisExperiment.ParameterActionContext : VP.BrowseContext\r
+\r
+SPBC.ParameterChildRule : VP.ChildRule\r
+SPBC.ParameterLabelRule : VP.LabelRule\r
+//SPBC.ParameterLabelDecorationRule : VP.LabelDecorationRule\r
+    \r
+SPBC\r
+    @VP.customChildRule SYSDYN.SensitivityAnalysisExperiment SPBC.ParameterChildRule\r
+        SYSDYN.SensitivityAnalysisExperiment.Parameter\r
+\r
+SPBC        \r
+    @VP.customLabelRule             SYSDYN.SensitivityAnalysisExperiment.Parameter        SPBC.ParameterLabelRule\r
+    \r
+//SPBC\r
+//    @VP.customLabelDecorationRule   SYSDYN.SensitivityAnalysisExperiment.Parameter        SPBC.ParameterLabelDecorationRule     \r
+    \r
+SPBC\r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType SYSDYN.SensitivityAnalysisExperiment\r
+        VP.VisualsContribution.HasRule VP.PassThruSorterRule\r
+   \r
+SPAC.Actions : L0.Library\r
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph
new file mode 100644 (file)
index 0000000..63dd7f0
--- /dev/null
@@ -0,0 +1,629 @@
+L0 = <http://www.simantics.org/Layer0-1.1>
+L0X = <http://www.simantics.org/Layer0X-1.1>
+G2D = <http://www.simantics.org/G2D-1.1>
+STR = <http://www.simantics.org/Structural-1.2>
+DIA = <http://www.simantics.org/Diagram-2.2>
+SIMU = <http://www.simantics.org/Simulation-1.1>
+MOD = <http://www.simantics.org/Modeling-1.2>
+PROJ = <http://www.simantics.org/Project-1.2>
+JFREE = <http://www.simantics.org/JFreeChart-1.0>
+SHEET = <http://www.simantics.org/Spreadsheet-1.2>
+WORKBENCH = <http://www.simantics.org/Workbench-1.2>
+//#####################################################################
+// Defines ontology and attaches it to SimanticsDomain
+//#####################################################################
+
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1> : L0.Ontology
+    @L0.new
+    L0.HasResourceClass "org.simantics.sysdyn.SysdynResource"
+
+SYSDYN.ImportedOntologies : PROJ.NamespaceRequirement
+    L0.HasDescription "Specifies the ontologies required by a Sysdyn project."
+    PROJ.RequiresNamespace
+        "http://www.simantics.org/Sysdyn-1.1" : L0.URI
+        "http://www.simantics.org/Layer0-1.1" : L0.URI
+        "http://www.simantics.org/SelectionView-1.2" : L0.URI
+        "http://www.simantics.org/Annotation-1.0" : L0.URI
+                
+SYSDYN.SharedFunctionOntology <T L0.Ontology
+SYSDYN.SharedModuleOntology <T L0.Ontology      
+
+FUNCTIONS = SYSDYN.Functions : L0.Library
+    @L0.new  
+
+//#####################################################################
+// Model
+//#####################################################################    
+
+SYSDYN.SysdynModel <T MOD.StructuralModel
+    >-- SYSDYN.SysdynModel.startTime --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModel.stopTime --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModel.simulationStepLength --> L0.Double <R L0.HasProperty : L0.FunctionalRelation    
+    >-- SYSDYN.SysdynModel.outputInterval --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModel.tolerance --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModel.solver --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModel.variableFilter --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModel.fmuFile --> L0.ByteArray <R L0.HasProperty
+    >-- SYSDYN.SysdynModel.timeUnit --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModel.lastExportFileName --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModel.lastExportFilePath --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+//    >-- SYSDYN.SysdynModel.exeFile --> L0.ByteArray <R L0.HasProperty
+    @L0.assert SYSDYN.SysdynModel.startTime 0.0
+    @L0.assert SYSDYN.SysdynModel.stopTime 10.0
+    @L0.assert SYSDYN.SysdynModel.solver "euler"
+    @L0.assert SYSDYN.SysdynModel.timeUnit "month"    
+    
+//#####################################################################
+// Configuration
+//#####################################################################
+
+SYSDYN.Symbols : L0.Library
+SYSDYN.SysdynConnectionType : STR.ConnectionType
+
+SYSDYN.DiagramToCompositeMapping <T L0X.Trigger
+
+SYSDYN.ConfigurationDiagram <T DIA.Diagram
+    @L0.assert STR.HasModelingRules SYSDYN.SysdynDiagramModelingRules 
+    DIA.HasSymbolContribution _ : DIA.IndexRootSymbolContribution
+    DIA.HasSymbolContribution _ : DIA.BasicSymbolContribution
+        DIA.BasicSymbolContributionHasSymbolLibrary
+            BasicSymbols
+            SYSDYN.SymbolReferences.CommentSymbols
+    >-- SYSDYN.ConfigurationDiagram.selection --> DIA.Element <R L0.HasProperty
+            
+SYSDYN.ConfigurationDiagramTemplate : MOD.DiagramTemplate
+    MOD.HasDiagramType SYSDYN.ConfigurationDiagram            
+
+SYSDYN.SysdynDiagramModelingRules : MOD.MappedModelingRules
+    MOD.HasBaseRules STR.StandardModelingRules
+
+SYSDYN.SymbolReferences : DIA.SymbolReferenceLibrary
+BasicSymbols = SYSDYN.SymbolReferences.BasicSymbols : DIA.SymbolReferenceLibrary
+
+SYSDYN.Configuration <T STR.Composite <T L0X.Realization <T L0.RVIContext
+    @L0.assert L0.HasLabel "Configuration"
+    // TODO [L0.ConsistsOf all (Variable or Dependency or Module)]
+
+SYSDYN.HistoryRealization <T L0X.Realization
+SYSDYN.DefaultRealization <T L0X.Realization
+
+SYSDYN.ModulesSearchFunction : L0.Function
+  L0.HasLabel "Sysdyn Search" : L0.String
+
+SYSDYN.SearchContribution : WORKBENCH.SearchContribution
+  WORKBENCH.hasSearchFunction SYSDYN.ModulesSearchFunction
+
+//#####################################################################
+// Variables
+//#####################################################################
+SYSDYN.Component <T STR.Component
+SYSDYN.Variable <T SYSDYN.Component  
+    >-- SYSDYN.Variable.type --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.Variable.expressions --> SYSDYN.Expressions <R L0.IsComposedOf : L0.FunctionalRelation
+    >-- SYSDYN.Variable.expressionList --> L0.List <R L0.IsComposedOf : L0.FunctionalRelation
+    >-- SYSDYN.Variable.arrayIndexes --> SYSDYN.ArrayIndexes <R L0.IsComposedOf : L0.FunctionalRelation
+    >-- SYSDYN.Variable.arrayIndexesList --> L0.List <R L0.IsComposedOf : L0.FunctionalRelation    
+    >-- SYSDYN.Variable.unit --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.Variable.variability --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.Variable.isTailOf --> STR.Connection <R STR.IsConnectedTo
+        L0.InverseOf SYSDYN.Variable.HasTail 
+        STR.AllowsConnectionType SYSDYN.SysdynConnectionType
+        STR.HasAttachmentRelation DIA.HasPlainConnector
+    >-- SYSDYN.Variable.isHeadOf --> STR.Connection <R STR.IsConnectedTo
+        L0.InverseOf SYSDYN.Variable.HasHead
+        STR.AllowsConnectionType SYSDYN.SysdynConnectionType
+        STR.HasAttachmentRelation DIA.HasArrowConnector   
+    @L0.assert L0.HasDataType $Double
+    >-- SYSDYN.Variable.value <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Variable.value 
+        _ : L0.Value    
+            L0.domainProperties FUNCTIONS.valuePropertyProperties : L0.ExternalValue
+            L0.valueAccessor FUNCTIONS.valuePropertyValue : L0.ExternalValue
+    >-- SYSDYN.Variable.values <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Variable.values 
+        _ : L0.Value    
+            L0.domainProperties FUNCTIONS.valuePropertyProperties : L0.ExternalValue
+            L0.valueAccessor FUNCTIONS.valuePropertyValue : L0.ExternalValue
+    >-- SYSDYN.Variable.times <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Variable.times
+        _ : L0.Value
+            L0.domainProperties FUNCTIONS.valuePropertyProperties : L0.ExternalValue
+            L0.valueAccessor FUNCTIONS.valuePropertyValue : L0.ExternalValue
+    >-- SYSDYN.Variable.names <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Variable.names 
+        _ : L0.Value    
+            L0.domainProperties FUNCTIONS.valuePropertyProperties : L0.ExternalValue
+            L0.valueAccessor FUNCTIONS.valuePropertyValue : L0.ExternalValue
+    >-- SYSDYN.Variable.activeDatasets <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Variable.activeDatasets 
+        _ : L0.Value    
+            L0.domainProperties FUNCTIONS.valuePropertyProperties : L0.ExternalValue
+            L0.valueAccessor FUNCTIONS.valuePropertyValue : L0.ExternalValue    
+    >-- SYSDYN.Variable.time <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Variable.time 
+        _ : L0.Value    
+            L0.domainProperties FUNCTIONS.valuePropertyProperties : L0.ExternalValue
+            L0.valueAccessor FUNCTIONS.valuePropertyValue : L0.ExternalValue
+
+    >-- SYSDYN.Variable.equation <R L0.HasProperty : L0.FunctionalRelation
+        L0.valueAccessor FUNCTIONS.equationPropertyValue : L0.ExternalValue
+    @L0.assert SYSDYN.Variable.equation 
+        _ : L0.Value
+
+    
+FUNCTIONS.runChildren : L0.ExternalValue
+    
+SYSDYN.HasRangeStart <R L0.HasProperty
+    L0.HasRange L0.Double    
+
+SYSDYN.HasRangeEnd <R L0.HasProperty
+    L0.HasRange L0.Double  
+
+SYSDYN.HasRangeStep <R L0.HasProperty
+    L0.HasRange L0.Double  
+
+SYSDYN.IndependentVariable <T SYSDYN.Variable     
+    >-- SYSDYN.IndependentVariable.unit --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.IndependentVariable.rangeStart --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.IndependentVariable.rangeEnd --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.IndependentVariable.rangeStep --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    // To be used in transient graphs for showing the correct experiment in equation editor
+    >-- SYSDYN.IndependentVariable.activeExpression --> SYSDYN.Expression <R L0.IsWeaklyRelatedTo : L0.FunctionalRelation
+    >-- SYSDYN.IndependentVariable.isUninitialized --> SYSDYN.IndependentVariable <R L0.HasProperty
+
+SYSDYN.Auxiliary <T SYSDYN.IndependentVariable
+    @L0.assert SYSDYN.Variable.type "Real"
+
+SYSDYN.Valve <T SYSDYN.IndependentVariable
+    @L0.assert SYSDYN.Variable.type "Real"
+                
+SYSDYN.Stock <T SYSDYN.IndependentVariable
+    @L0.assert SYSDYN.Variable.type "Real"
+                
+SYSDYN.Cloud <T SYSDYN.Variable
+
+SYSDYN.Input <T SYSDYN.Variable
+    >-- SYSDYN.Input.defaultInputValue --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Input.defaultInputValue 0.0
+    @L0.assert SYSDYN.Variable.type "Real"
+    
+SYSDYN.Enumeration <T SYSDYN.Variable
+    >-- SYSDYN.Enumeration.enumerationIndexes --> SYSDYN.EnumerationIndexes <R L0.DependsOn : L0.FunctionalRelation
+    >-- SYSDYN.Enumeration.enumerationIndexList --> L0.List <R L0.DependsOn : L0.FunctionalRelation    
+    >-- SYSDYN.Enumeration.isReplaceable --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation 
+    @L0.assert SYSDYN.Variable.type "type"
+    @L0.assert SYSDYN.Enumeration.isReplaceable false
+    
+SYSDYN.Shadow <T SYSDYN.Variable
+    >-- SYSDYN.Shadow.original --> SYSDYN.IndependentVariable <R L0.DependsOn : L0.FunctionalRelation    
+
+//#####################################################################
+// Modules
+//#####################################################################
+
+SYSDYN.Module <T SYSDYN.Component
+    >-- SYSDYN.Module.redeclaration --> SYSDYN.Redeclaration  <R L0.IsComposedOf
+    >-- SYSDYN.Module.parameterOverride --> SYSDYN.Module.ParameterOverride <R L0.IsComposedOf
+
+SYSDYN.ModuleSymbol <T DIA.FontProvider <T DIA.ColorProvider
+    @MOD.defSymbol "ModuleSymbol" SYSDYN.Module
+    STR.IsDefinedBy _ : DIA.Composite
+        @L0.orderedSet  
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.ModuleSymbol SYSDYN.IsHeadOfTerminal
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.ModuleSymbol SYSDYN.IsTailOfTerminal
+
+SYSDYN.Module.ParameterOverride <T L0.Entity
+    >-- SYSDYN.Module.ParameterOverride.overriddenParameter --> SYSDYN.IndependentVariable <R L0.IsWeaklyRelatedTo : L0.FunctionalRelation
+    >-- SYSDYN.Module.ParameterOverride.overrideExpression --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+
+SYSDYN.IsOutput <R L0.IsRelatedTo : L0.Tag
+    @L0.symmetric
+
+
+SYSDYN.SysdynModuleLibrary <T L0.Library  
+    @L0.singleProperty L0.HasName  
+    
+    
+//#####################################################################
+// Connections and Relations
+//#####################################################################
+SYSDYN.Dependency <T STR.Connection
+    >-- SYSDYN.Dependency.angle --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.Dependency.refersTo --> SYSDYN.Variable <R L0.IsRelatedTo : L0.FunctionalRelation
+    @L0.singleProperty SYSDYN.Variable.HasHead
+    @L0.singleProperty SYSDYN.Variable.HasTail
+
+SYSDYN.Flow <T STR.Connection
+    @L0.singleProperty SYSDYN.Variable.HasHead
+    @L0.singleProperty SYSDYN.Variable.HasTail
+
+
+//#####################################################################
+// Expression
+//#####################################################################
+
+SYSDYN.Expressions <T L0.OrderedSet <R L0.HasNext
+
+SYSDYN.Expression <T L0.Entity
+    >-- SYSDYN.Expression.equation --> L0.String <R L0.HasProperty
+    >-- SYSDYN.Expression.arrayRange --> L0.String <R L0.HasProperty : L0.TotalFunction
+
+SYSDYN.HasEquationOrEmpty <R SYSDYN.Expression.equation
+
+SYSDYN.NormalExpression <T SYSDYN.Expression
+    @L0.singleProperty SYSDYN.Expression.equation    
+
+SYSDYN.ParameterExpression <T SYSDYN.Expression
+    @L0.singleProperty SYSDYN.Expression.equation   
+
+SYSDYN.ConstantExpression <T SYSDYN.Expression
+    @L0.singleProperty SYSDYN.Expression.equation   
+
+SYSDYN.DelayExpression <T SYSDYN.Expression
+    >-- SYSDYN.DelayExpression.expression --> L0.String <R SYSDYN.Expression.equation : L0.FunctionalRelation
+    >-- SYSDYN.DelayExpression.order --> L0.Integer <R SYSDYN.Expression.equation : L0.FunctionalRelation
+    >-- SYSDYN.DelayExpression.delayTime --> L0.String <R SYSDYN.Expression.equation : L0.FunctionalRelation
+    >-- SYSDYN.DelayExpression.initialValue --> L0.String <R SYSDYN.HasEquationOrEmpty : L0.FunctionalRelation
+    >-- SYSDYN.DelayExpression.isInformationDelay --> SYSDYN.DelayExpression <R L0.IsRelatedTo : L0.Tag
+        @L0.symmetric
+        
+SYSDYN.StockExpression <T SYSDYN.Expression
+    >-- SYSDYN.StockExpression.useCustomIntegral --> SYSDYN.StockExpression <R L0.IsRelatedTo : L0.Tag
+        @L0.symmetric
+    >-- SYSDYN.StockExpression.integralEquation --> L0.String <R SYSDYN.Expression.equation : L0.FunctionalRelation
+    >-- SYSDYN.StockExpression.initialEquation --> L0.String <R SYSDYN.Expression.equation : L0.FunctionalRelation
+
+SYSDYN.LookupExpression <T SYSDYN.Expression
+    >-- SYSDYN.LookupExpression.lookup --> L0.String <R SYSDYN.Expression.equation : L0.FunctionalRelation
+
+SYSDYN.WithLookupExpression <T SYSDYN.Expression
+    >-- SYSDYN.WithLookupExpression.expression --> L0.String <R SYSDYN.Expression.equation : L0.FunctionalRelation
+    >-- SYSDYN.WithLookupExpression.lookup --> L0.String <R SYSDYN.Expression.equation : L0.FunctionalRelation
+    >-- SYSDYN.WithLookupExpression.minX --> L0.Double <R L0.IsRelatedTo : L0.TotalFunction
+    >-- SYSDYN.WithLookupExpression.maxX --> L0.Double <R L0.IsRelatedTo : L0.TotalFunction
+    >-- SYSDYN.WithLookupExpression.minY --> L0.Double <R L0.IsRelatedTo : L0.TotalFunction
+    >-- SYSDYN.WithLookupExpression.maxY --> L0.Double <R L0.IsRelatedTo : L0.TotalFunction
+
+//#####################################################################
+// Enumerations
+//#####################################################################
+    
+SYSDYN.ArrayIndexes <T L0.OrderedSet <R L0.HasNext
+
+SYSDYN.EnumerationIndexes <T L0.OrderedSet <R L0.HasNext
+
+SYSDYN.EnumerationIndex <T L0.Entity
+    @L0.singleProperty L0.HasName
+    >-- SYSDYN.EnumerationIndex.showEnumerationIndexInCharts --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.EnumerationIndex.showEnumerationIndexInCharts true
+    
+//#####################################################################
+// Redeclarations
+//#####################################################################
+        
+SYSDYN.Redeclaration <T L0.Entity
+    >-- SYSDYN.Redeclaration.replacedEnumeration --> SYSDYN.Enumeration <R L0.IsRelatedTo : L0.TotalFunction
+        L0.InverseOf SYSDYN.Redeclaration.replacedEnumeration.Inverse <R L0.DependsOn : L0.FunctionalRelation 
+    >-- SYSDYN.Redeclaration.replacingEnumeration --> SYSDYN.Enumeration <R L0.IsRelatedTo : L0.TotalFunction    
+        L0.InverseOf SYSDYN.Redeclaration.replacingEnumeration.Inverse <R L0.DependsOn : L0.FunctionalRelation 
+            
+//#####################################################################
+// Functions
+//#####################################################################    
+
+SYSDYN.SysdynModelicaFunction <T L0.Entity
+    @L0.singleProperty L0.HasName
+    >-- SYSDYN.SysdynModelicaFunction.modelicaFunctionCode --> L0.String <R L0.HasProperty : L0.TotalFunction
+    >-- SYSDYN.SysdynModelicaFunction.modelicaFunctionInterface --> L0.String <R L0.HasProperty : L0.TotalFunction
+    >-- SYSDYN.SysdynModelicaFunction.inputs --> L0.List <R L0.IsComposedOf : L0.FunctionalRelation
+    >-- SYSDYN.SysdynModelicaFunction.outputs --> L0.List <R L0.IsComposedOf : L0.FunctionalRelation
+
+SYSDYN.ExternalFunctionFile <T L0.Entity
+    @L0.singleProperty L0.HasName
+    >-- SYSDYN.ExternalFunctionFile.externalFile --> L0.ByteArray <R L0.HasProperty
+
+SYSDYN.SysdynModelicaFunctionLibrary <T L0.Library  
+    @L0.singleProperty L0.HasName  
+        
+SYSDYN.SysdynModelicaFunction.InterfaceVariable <T L0.Entity
+    @L0.singleProperty L0.HasName
+    >-- SYSDYN.SysdynModelicaFunction.definition --> L0.String <R L0.HasProperty
+    >-- SYSDYN.SysdynModelicaFunction.unit --> L0.String <R L0.HasProperty
+
+SYSDYN.SysdynModelicaFunction.Input <T SYSDYN.SysdynModelicaFunction.InterfaceVariable
+    >-- SYSDYN.SysdynModelicaFunction.optional --> L0.Boolean <R L0.HasProperty : L0.FunctionalRelation
+
+SYSDYN.SysdynModelicaFunction.VariableLengthInput <T SYSDYN.SysdynModelicaFunction.Input
+    >-- SYSDYN.SysdynModelicaFunction.VariableLengthInput.shownLabels --> L0.List <R L0.IsComposedOf
+    
+SYSDYN.SysdynModelicaFunction.Output <T SYSDYN.SysdynModelicaFunction.InterfaceVariable
+    
+//#####################################################################
+// Experiments
+//#####################################################################
+
+SYSDYN.Experiment <T SIMU.Experiment
+    >-- SYSDYN.Experiment.result --> SYSDYN.Result <R L0.IsComposedOf
+    >-- SYSDYN.Experiment.resultSet --> SYSDYN.ResultSet <R L0.IsComposedOf
+    >-- SYSDYN.Experiment.ic --> SYSDYN.InitialCondition <R L0.DependsOn : L0.FunctionalRelation
+    
+SYSDYN.BasicExperiment <T SYSDYN.Experiment
+
+SYSDYN.GameExperiment <T SYSDYN.Experiment
+    >-- SYSDYN.GameExperiment.stepDuration --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.GameExperiment.stepLength --> L0.Double <R L0.HasProperty : L0.FunctionalRelation    
+    @L0.assert SYSDYN.GameExperiment.stepDuration 1.0
+    @L0.assert SYSDYN.GameExperiment.stepLength 0.1
+
+
+FUNCTIONS.runChildren : L0.ExternalValue
+SYSDYN.Experiment.Run <T SIMU.Run
+    @L0.assert L0.domainChildren FUNCTIONS.runChildren
+    >-- SYSDYN.Experiment.Run.time <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Experiment.Run.time 
+        _ : L0.Value    
+            L0.domainProperties FUNCTIONS.runProperties : L0.ExternalValue
+            L0.valueAccessor FUNCTIONS.valuePropertyValue : L0.ExternalValue    
+
+SYSDYN.SimulateOnChangeExperiment <T SYSDYN.Experiment
+
+SYSDYN.PlaybackExperiment <T SYSDYN.Experiment
+    
+SYSDYN.SensitivityAnalysisExperiment <T SYSDYN.Experiment
+    >-- SYSDYN.SensitivityAnalysisExperiment.parameterList --> L0.List <R L0.IsComposedOf : L0.FunctionalRelation
+    >-- SYSDYN.SensitivityAnalysisExperiment.randomSeed --> L0.Integer <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SensitivityAnalysisExperiment.method --> SYSDYN.ValueGeneratorMethod <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SensitivityAnalysisExperiment.resultRefreshRate --> L0.Integer <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SensitivityAnalysisExperiment.numberOfValues --> L0.Integer <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.SensitivityAnalysisExperiment.randomSeed 123
+    @L0.assert SYSDYN.SensitivityAnalysisExperiment.numberOfValues 10
+
+SYSDYN.SensitivityAnalysisExperiment.Parameter <T L0.Entity
+    >-- SYSDYN.SensitivityAnalysisExperiment.Parameter.propabilityDistribution --> SYSDYN.ProbabilityDistribution <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SensitivityAnalysisExperiment.Parameter.variable --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.SensitivityAnalysisExperiment.Parameter.indexes --> L0.StringArray <R L0.HasProperty : L0.FunctionalRelation
+        
+SYSDYN.ProbabilityDistribution <T L0.Entity
+SYSDYN.UniformDistribution <T SYSDYN.ProbabilityDistribution
+    >-- SYSDYN.UniformDistribution.minValue --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.UniformDistribution.maxValue --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.UniformDistribution.minValue 0.0
+    @L0.assert SYSDYN.UniformDistribution.maxValue 10.0
+    
+SYSDYN.NormalDistribution <T SYSDYN.ProbabilityDistribution
+    >-- SYSDYN.NormalDistribution.minValue --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.NormalDistribution.maxValue --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.NormalDistribution.mean --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.NormalDistribution.stdDeviation --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.NormalDistribution.mean 5.0
+    @L0.assert SYSDYN.NormalDistribution.stdDeviation 1.0
+        
+SYSDYN.Interval <T SYSDYN.ProbabilityDistribution
+    >-- SYSDYN.Interval.minValue --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.Interval.maxValue --> L0.Double <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.Interval.minValue 0.0
+    @L0.assert SYSDYN.Interval.maxValue 10.0    
+
+SYSDYN.ValueGeneratorMethod <T L0.Entity
+SYSDYN.RandomGenerator <T SYSDYN.ValueGeneratorMethod
+SYSDYN.HaltonSequenceGenerator <T SYSDYN.ValueGeneratorMethod
+
+//#####################################################################
+// Results and history datasets
+//#####################################################################
+
+SYSDYN.Result <T L0.Entity
+    @L0.singleProperty L0.HasName
+    >-- SYSDYN.Result.parameterFile --> L0.String <R L0.HasProperty
+    >-- SYSDYN.Result.resultFile --> L0.String <R L0.HasProperty
+    >-- SYSDYN.Result.showResult --> SYSDYN.Result <R L0.IsRelatedTo : L0.Tag
+        @L0.symmetric
+    >-- SYSDYN.Result.time --> L0.Long <R L0.HasProperty : L0.FunctionalRelation
+        
+SYSDYN.HistoryDataset <T SYSDYN.Result
+    @L0.singleProperty L0.HasName
+    @L0.singleProperty L0.HasLabel
+    >-- SYSDYN.HistoryDataset.start --> L0.String <R L0.HasProperty     // Start of the history data table (e.g. B3)
+    >-- SYSDYN.HistoryDataset.end --> L0.String <R L0.HasProperty       // End of the history data table (e.g. D56)
+    >-- SYSDYN.HistoryDataset.timeName --> L0.String <R L0.HasProperty  // Name of the time variable. Will be saved as "time"
+    >-- SYSDYN.HistoryDataset.columns --> L0.Boolean <R L0.HasProperty  // Is the data in columns. If false, data is in rows
+    >-- SYSDYN.HistoryDataset.sheet --> SHEET.Spreadsheet <R L0.IsRelatedTo : L0.FunctionalRelation
+    
+SYSDYN.ResultSet <T L0.Entity
+    >-- SYSDYN.Experiment.result --> SYSDYN.Result <R L0.IsComposedOf
+
+SYSDYN.InitialCondition <T SIMU.State
+    >-- SYSDYN.InitialCondition.HasInitialValues --> MOD.PartialIC <R L0.HasProperty : L0.FunctionalRelation
+
+
+//#####################################################################
+//#####################################################################
+//################              DIAGRAM               #################
+//#####################################################################
+//#####################################################################    
+
+//#####################################################################
+// Defaults
+//#####################################################################
+          //G2D.HasFont _ : G2D.Font
+SYSDYN.DefaultFont : G2D.Font          
+  G2D.HasFontFamily "Tahoma"
+  G2D.HasFontSize 12
+  G2D.HasFontStyle G2D.FontStyle.normal_font_style
+  
+SYSDYN.SysdynSymbol <T DIA.FontProvider <T DIA.ColorProvider
+    @L0.assert G2D.HasFont SYSDYN.DefaultFont
+
+    
+//#####################################################################
+// Component types
+//#####################################################################
+
+SYSDYN.IsHeadOfTerminal
+    L0.InverseOf SYSDYN.HasHeadTerminal
+    @MOD.terminalRelation SYSDYN.Variable.isHeadOf
+SYSDYN.IsTailOfTerminal
+    L0.InverseOf SYSDYN.HasTailTerminal
+    @MOD.terminalRelation SYSDYN.Variable.isTailOf
+
+SYSDYN.SysdynTerminal <T DIA.Terminal
+    @L0.assert DIA.Terminal.AllowedDirections 0
+
+//#####################################################################
+SYSDYN.Valve
+    @MOD.connection SYSDYN.Variable.isTailOf
+    @MOD.connection SYSDYN.Variable.isHeadOf
+    
+SYSDYN.Orientation <T L0.Entity    
+SYSDYN.Horizontal <T SYSDYN.Orientation
+SYSDYN.Vertical <T SYSDYN.Orientation   
+
+SYSDYN.Location <T L0.Entity
+SYSDYN.Left <T SYSDYN.Location
+SYSDYN.Right <T SYSDYN.Location
+SYSDYN.Top <T SYSDYN.Location
+SYSDYN.Bottom <T SYSDYN.Location
+SYSDYN.Center <T SYSDYN.Location
+
+SYSDYN.ValveSymbol <T SYSDYN.SysdynSymbol
+    @MOD.defSymbol "Valve" SYSDYN.Valve
+    L0.HasDescription "(Shift+V)"
+    >-- SYSDYN.ValveSymbol.orientation --> SYSDYN.Orientation <R L0.IsWeaklyRelatedTo : L0.FunctionalRelation
+    @L0.assert SYSDYN.ValveSymbol.orientation SYSDYN.Horizontal
+    >-- SYSDYN.ValveSymbol.textLocation --> SYSDYN.Location <R L0.IsWeaklyRelatedTo : L0.FunctionalRelation
+    L0.IsDependencyOf BasicSymbols
+    STR.IsDefinedBy _ : DIA.Composite <R L0.HasNext 
+        @L0.orderedSet 
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.ValveSymbol SYSDYN.IsHeadOfTerminal
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.ValveSymbol SYSDYN.IsTailOfTerminal
+
+//#####################################################################
+SYSDYN.Auxiliary
+    @MOD.connection SYSDYN.Variable.isTailOf
+    @MOD.connection SYSDYN.Variable.isHeadOf
+
+SYSDYN.AuxiliarySymbol <T SYSDYN.SysdynSymbol
+    @MOD.defSymbol "Auxiliary" SYSDYN.Auxiliary
+    L0.HasDescription "(Shift+A)"
+    L0.IsDependencyOf BasicSymbols
+    STR.IsDefinedBy _ : DIA.Composite <R L0.HasNext 
+        @L0.orderedSet 
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.AuxiliarySymbol SYSDYN.IsHeadOfTerminal
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.AuxiliarySymbol SYSDYN.IsTailOfTerminal
+
+//#####################################################################
+SYSDYN.Cloud
+    @MOD.connection SYSDYN.Variable.isTailOf
+    @MOD.connection SYSDYN.Variable.isHeadOf
+
+SYSDYN.CloudSymbol <T SYSDYN.SysdynSymbol
+    @MOD.defSymbol "Cloud" SYSDYN.Cloud
+    L0.HasDescription "(Shift+C)"
+    L0.IsDependencyOf BasicSymbols
+    STR.IsDefinedBy _ : DIA.Composite <R L0.HasNext 
+        @L0.orderedSet 
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.CloudSymbol SYSDYN.IsHeadOfTerminal
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.CloudSymbol SYSDYN.IsTailOfTerminal
+
+//#####################################################################
+SYSDYN.Input
+    @MOD.connection SYSDYN.Variable.isTailOf
+    @MOD.connection SYSDYN.Variable.isHeadOf
+
+SYSDYN.InputSymbol <T SYSDYN.SysdynSymbol
+    @MOD.defSymbol "Input" SYSDYN.Input
+    L0.HasDescription "(Shift+I)"
+    L0.IsDependencyOf BasicSymbols
+    STR.IsDefinedBy _ : DIA.Composite <R L0.HasNext 
+        @L0.orderedSet
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.InputSymbol SYSDYN.IsHeadOfTerminal
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.InputSymbol SYSDYN.IsTailOfTerminal    
+
+//#####################################################################
+SYSDYN.Stock <T STR.Component
+    @MOD.connection SYSDYN.Variable.isTailOf
+    @MOD.connection SYSDYN.Variable.isHeadOf
+
+SYSDYN.StockSymbol <T SYSDYN.SysdynSymbol
+    @MOD.defSymbol "Stock" SYSDYN.Stock
+    L0.HasDescription "(Shift+S)"
+    L0.IsDependencyOf BasicSymbols
+    STR.IsDefinedBy _ : DIA.Composite <R L0.HasNext 
+        @L0.orderedSet 
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.StockSymbol SYSDYN.IsHeadOfTerminal
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.StockSymbol SYSDYN.IsTailOfTerminal    
+
+//#####################################################################
+SYSDYN.Shadow
+    @MOD.connection SYSDYN.Variable.isTailOf
+    @MOD.connection SYSDYN.Variable.isHeadOf
+
+SYSDYN.ShadowSymbol <T SYSDYN.SysdynSymbol
+    @MOD.defSymbol "Shadow" SYSDYN.Shadow
+    L0.HasDescription "(Shift+G)"
+    L0.IsDependencyOf BasicSymbols
+    STR.IsDefinedBy _ : DIA.Composite <R L0.HasNext 
+        @L0.orderedSet 
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.ShadowSymbol SYSDYN.IsHeadOfTerminal
+            _ : SYSDYN.SysdynTerminal
+                @MOD.terminal SYSDYN.ShadowSymbol SYSDYN.IsTailOfTerminal
+
+
+
+//#####################################################################
+// Diagram connection types
+//#####################################################################
+
+SYSDYN.FlowConnection <T DIA.RouteGraphConnection <T DIA.FontProvider <T DIA.ColorProvider
+    MOD.DiagramConnectionTypeToConnectionType
+        SYSDYN.Flow  
+    >-- SYSDYN.FlowConnection.width --> L0.Float <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.FlowConnection.width 
+        1.0 : L0.Float
+    @L0.assert G2D.HasFont SYSDYN.DefaultFont     
+
+SYSDYN.DependencyConnection <T DIA.Connection <T DIA.FontProvider <T DIA.ColorProvider
+    @L0.singleProperty SYSDYN.Dependency.angle
+    >-- SYSDYN.DependencyConnection.polarity --> L0.String <R L0.HasProperty : L0.FunctionalRelation
+    >-- SYSDYN.DependencyConnection.polarityLocation --> L0.String <R L0.HasProperty : L0.FunctionalRelation    
+    >-- SYSDYN.DependencyConnection.hideArrow --> SYSDYN.DependencyConnection <R L0.HasProperty : L0.Tag
+        @L0.symmetric
+    >-- SYSDYN.DependencyConnection.delayMark --> SYSDYN.DependencyConnection <R L0.HasProperty : L0.Tag
+        @L0.symmetric
+    >-- SYSDYN.DependencyConnection.strokeWidth --> L0.Float <R L0.HasProperty : L0.FunctionalRelation
+    @L0.assert SYSDYN.DependencyConnection.strokeWidth 
+        0.3 : L0.Float
+    @L0.assert SYSDYN.Dependency.angle 0.3
+    MOD.DiagramConnectionTypeToConnectionType
+        SYSDYN.Dependency
+    @L0.assert G2D.HasFont SYSDYN.DefaultFont
+
+// TODO: Browser URIs
+
+SYSDYN.Browser <R L0.Entity
+SYSDYN.ModelBrowser <R L0.Entity
+SYSDYN.SysdynOperationBrowser <R L0.Entity
+SYSDYN.AvailableSharedFunctionLibraries <R L0.Entity
+SYSDYN.AvailableVariableIndexes <R L0.Entity
+SYSDYN.EnumerationReplacement <R L0.Entity
+SYSDYN.ExternalFiles <R L0.Entity
+SYSDYN.SelectedSharedFunctionLibraries <R L0.Entity
+SYSDYN.UsedVariableIndexes <R L0.Entity
+SYSDYN.FunctionTree <R L0.Entity
+SYSDYN.ImportModuleTree <R L0.Entity
+SYSDYN.ExportModuleTree <R L0.Entity         
+        
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/SysdynFunctions.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/SysdynFunctions.pgraph
new file mode 100644 (file)
index 0000000..6fdcc89
--- /dev/null
@@ -0,0 +1,221 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+\r
+FL = <http://www.simantics.org/Sysdyn-1.1/Built-in Functions> : SYSDYN.SysdynModelicaFunctionLibrary\r
+\r
+\r
+\r
+FL.minmax : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """minmax(expression, minimum, maximum)\r
+\r
+Limits the result of an equation to between the given minimum and maximum values."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            FL.minmax.expression : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            FL.minmax.minimum : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            FL.minmax.maximum : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            FL.minmax.result : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real expression;\r
+    input Real minimum;\r
+    input Real maximum;\r
+    output Real result;\r
+algorithm\r
+    result := min(maximum, max(minimum, expression));"""\r
+\r
+\r
+\r
+FL.xidz : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """xidz(divident, divisor, x)\r
+\r
+x if divided by zero, divident/divisor otherwise"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            FL.xidz.divident : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            FL.xidz.divisor : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'q"\r
+            FL.xidz.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p/'q"\r
+                SYSDYN.SysdynModelicaFunction.definition "Result if divisor = 0"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            FL.xidz.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p/'q"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real divident;\r
+    input Real divisor;\r
+    input Real x;\r
+    output Real z;\r
+algorithm\r
+    if divisor > 0.0 or divisor < 0.0 then\r
+        z := divident / divisor;\r
+    else\r
+        z := x;\r
+    end if;"""\r
+\r
+\r
+\r
+FL.zidz : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription "zidz(divident, divisor)\r
+\r
+Zero if divided by zero, divident/divisor otherwise"\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            FL.zidz.divident : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            FL.zidz.divisor : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'q"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            FL.zidz.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p/'q"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real divident;\r
+    input Real divisor;\r
+    output Real z;\r
+algorithm\r
+    z := xidz(divident,divisor,0.0);"""\r
+\r
+\r
+\r
+FL.interpolate : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """interpolate(u, table)\r
+\r
+Interpolate function for two-dimensional table"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            FL.interpolate.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+                SYSDYN.SysdynModelicaFunction.definition "input value (first column of table)"\r
+            FL.interpolate.table : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+                SYSDYN.SysdynModelicaFunction.definition "table to be interpolated"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            FL.interpolate.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real u "input value (first column of table)";\r
+    input Real table[:, :] "table to be interpolated";\r
+    output Real y "interpolated input value (icol column of table)";\r
+algorithm\r
+    y := interpolateFull(u, table, 2);"""\r
+    \r
+    \r
+    \r
+FL.interpolateFull : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """interpolateFull(u, table, icol)\r
+\r
+The full interpolate function"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            FL.interpolateFull.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+                SYSDYN.SysdynModelicaFunction.definition "input value (first column of table)"\r
+            FL.interpolateFull.table : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+                SYSDYN.SysdynModelicaFunction.definition "table to be interpolated"\r
+            FL.interpolateFull.icol : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Integer"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+                SYSDYN.SysdynModelicaFunction.definition "column of table to be interpolated"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            FL.interpolateFull.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real u "input value (first column of table)";\r
+    input Real table[:, :] "table to be interpolated";\r
+    input Integer icol "column of table to be interpolated";\r
+    output Real y "interpolated input value (icol column of table)";\r
+protected \r
+    Integer i;\r
+    Integer n "number of rows of table";\r
+    Real u1;\r
+    Real u2;\r
+    Real y1;\r
+    Real y2;\r
+algorithm \r
+    n := size(table, 1);\r
+    if n <= 1 then\r
+        y := table[1, icol];\r
+    else\r
+        /* Search interval */\r
+        if u <= table[1, 1] then\r
+            i := 1;\r
+        else\r
+            i := 2;\r
+            while i < n and u > table[i, 1] loop\r
+                i := i + 1;\r
+            end while;\r
+            i := i - 1;\r
+        end if;\r
+\r
+        /* Get interpolation data */\r
+        u1 := table[i, 1];\r
+        u2 := table[i + 1, 1];\r
+        y1 := table[i, icol];\r
+        y2 := table[i + 1, icol];\r
+        /* Interpolate */\r
+        if u1 >= u2 then\r
+            y := y1;\r
+            /* since not possible to throw error */\r
+        else\r
+            y := y1 + (y2 - y1)*(u - u1)/(u2 - u1);\r
+        end if;\r
+    end if;"""\r
+    \r
+    \r
+    \r
+FL.unitCast : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """unitCast(u)\r
+\r
+Casts the expression to ANY unit."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            FL.unitCast.u : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+                SYSDYN.SysdynModelicaFunction.definition "the expression to be casted"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            FL.unitCast.y : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real u "the expression to be casted";\r
+    output Real y "the expression with unit ANY";\r
+algorithm\r
+    y := u;"""\r
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/SysdynModelingViewpoint.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/SysdynModelingViewpoint.pgraph
new file mode 100644 (file)
index 0000000..8267cfa
--- /dev/null
@@ -0,0 +1,248 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+VP = <http://www.simantics.org/Viewpoint-1.2>\r
+SIMU = <http://www.simantics.org/Simulation-1.1>\r
+PROJECT = <http://www.simantics.org/Project-1.2>\r
+IMAGE = <http://www.simantics.org/Image2-1.2>\r
+ACT = <http://www.simantics.org/Action-1.1>\r
+MOD = <http://www.simantics.org/Modeling-1.2>\r
+STR = <http://www.simantics.org/Structural-1.2>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+SILK = <http://www.simantics.org/Silk-1.1>\r
+SHEET = <http://www.simantics.org/Spreadsheet-1.2>\r
+JFREE = <http://www.simantics.org/JFreeChart-1.0>\r
+\r
+\r
+SBC = SYSDYN.ModelingBrowseContext : VP.BrowseContext\r
+SAC = SYSDYN.ModelingActionContext : VP.BrowseContext\r
+    VP.BrowseContext.IsIncludedIn PROJECT.ProjectActionContext\r
+\r
+SBC.VariableNodeType <T VP.NodeType\r
+    @L0.assert VP.HasContentType "Variable"\r
+    \r
+\r
+////////////////////////////////\r
+// From Project Viewpoint\r
+////////////////////////////////\r
+SBC\r
+    @VP.relationChildRule           PROJECT.Project     L0.ConsistsOf   SYSDYN.SysdynModel\r
+\r
+SBC\r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType L0.Entity\r
+        VP.VisualsContribution.HasRule VP.ResourceLabelLabelRule\r
+        VP.VisualsContribution.HasRule VP.ResourceNameModifierRule\r
+\r
+SBC\r
+    @VP.constantImageRule           SYSDYN.SysdynModel                  SILK.chart_organisation\r
+\r
+\r
+////////////////////////////////\r
+// From Modeling Viewpoint\r
+////////////////////////////////\r
+MBC = MOD.ModelingBrowseContext\r
+\r
+SBC\r
+    @VP.relationChildRule           SYSDYN.SysdynModel      SIMU.HasConfiguration   MBC.Configuration\r
+\r
+SBC\r
+    @VP.constantLabelRule           MBC.Configuration       "Configuration"\r
+    \r
+SBC\r
+    @VP.constantImageRule           MBC.Configuration       SILK.bricks\r
+    @VP.constantImageRule           STR.Component           SILK.brick\r
+    @VP.constantImageRule           STR.Composite           SILK.bricks\r
+\r
+\r
+////////////////////////////////\r
+// Sysdyn-specific Viewpoint\r
+////////////////////////////////\r
+\r
+SBC.ModuleSymbolNodeType <T VP.NodeType\r
+SBC.ModuleSymbol : SBC.ModuleSymbolNodeType\r
+\r
+BuiltinFunctions = <http://www.simantics.org/Sysdyn-1.1/Built-in Functions>\r
+SBC.BuiltinFunctions : VP.ResourceNodeType\r
+SBC.ModuleTypeChildRule : VP.ChildRule\r
+SBC.ModuleContentChildRule : VP.ChildRule\r
+SBC.VariableChildRule : VP.ChildRule\r
+SBC.ExperimentsFolder : VP.ResourceNodeType\r
+SBC.FunctionsFolder : VP.ResourceNodeType\r
+SBC.SharedFunctionsFolder : VP.ResourceNodeType\r
+SBC.Variable : SBC.VariableNodeType\r
+\r
+SBC\r
+    @VP.relationChildRuleWithFolder SYSDYN.SysdynModel  L0.ConsistsOf             SYSDYN.Experiment\r
+        SBC.ExperimentsFolder\r
+    @VP.relationChildRule           SYSDYN.Experiment   SYSDYN.Experiment.result  SYSDYN.Result\r
+\r
+    @VP.customChildRule     MBC.Configuration SBC.VariableChildRule\r
+        SBC.Variable\r
+    @VP.customChildRule     SBC.Variable SBC.VariableChildRule\r
+        SBC.Variable\r
+\r
+    @VP.relationChildRule    MBC.Configuration    L0.ConsistsOf   SHEET.Book\r
+    @VP.relationChildRule    SHEET.Book           L0.ConsistsOf   SHEET.Spreadsheet\r
+\r
+\r
+    // Function libraries  \r
+    // Functions folder  \r
+    @VP.relationChildRuleWithFolder SYSDYN.SysdynModel  L0.ConsistsOf    SYSDYN.SysdynModelicaFunction\r
+        SBC.FunctionsFolder \r
+    @VP.relationChildRule           SBC.FunctionsFolder L0.ConsistsOf    SYSDYN.SysdynModelicaFunctionLibrary\r
+\r
+    // Function libraries\r
+    @VP.relationChildRule      SYSDYN.SysdynModelicaFunctionLibrary      L0.ConsistsOf      SYSDYN.SysdynModelicaFunctionLibrary    \r
+    @VP.relationChildRule      SYSDYN.SysdynModelicaFunctionLibrary      L0.ConsistsOf      SYSDYN.SysdynModelicaFunction\r
+    @VP.relationChildRule      SYSDYN.SharedFunctionOntology             L0.ConsistsOf      SYSDYN.SysdynModelicaFunctionLibrary    \r
+    @VP.relationChildRule      SYSDYN.SharedFunctionOntology             L0.ConsistsOf      SYSDYN.SysdynModelicaFunction    \r
+\r
+    // Built-in functions\r
+    VP.BrowseContext.HasChildContribution _ : VP.ChildContribution\r
+        VP.ChildContribution.HasParentNodeType SBC.FunctionsFolder\r
+        VP.ChildContribution.HasChildNodeType SBC.BuiltinFunctions\r
+        VP.ChildContribution.HasRule _ : VP.ConstantChildRule\r
+            VP.ConstantChildRule.HasChild BuiltinFunctions    \r
+    @VP.relationChildRule      SBC.BuiltinFunctions      L0.ConsistsOf      SYSDYN.SysdynModelicaFunctionLibrary\r
+    @VP.relationChildRule      SBC.BuiltinFunctions      L0.ConsistsOf      SYSDYN.SysdynModelicaFunction\r
+\r
+    // Shared functions linked to a model    \r
+    @VP.relationChildRuleWithFolder SBC.FunctionsFolder   L0.IsLinkedTo  SYSDYN.SharedFunctionOntology \r
+        SBC.SharedFunctionsFolder\r
+\r
+\r
+    // Modules  \r
+    @VP.equalContentChildRule  MOD.StructuralModel\r
+        SBC.ModulesFolder : VP.ResourceNodeType \r
+    @VP.customChildRule SBC.ModulesFolder SBC.ModuleTypeChildRule\r
+        SBC.ModuleSymbol\r
+    @VP.customChildRule SBC.ModuleSymbol SBC.ModuleContentChildRule STR.Component     \r
+    \r
+    // Charts\r
+    @VP.relationChildRuleWithFolder MOD.StructuralModel L0.ConsistsOf JFREE.Chart\r
+        SBC.ChartsFolder : VP.ResourceNodeType        \r
+       \r
+// Labels  \r
+SBC.VariableNameLabelRule : VP.LabelRule\r
+SBC.ModuleTypeLabelRule : VP.LabelRule\r
+      \r
+SBC\r
+    @VP.constantLabelRule           SBC.ExperimentsFolder         "Experiments"\r
+    @VP.constantLabelRule           SBC.FunctionsFolder           "Functions"\r
+    @VP.constantLabelRule           SBC.ChartsFolder              "Charts"\r
+    @VP.constantLabelRule           SBC.ModulesFolder             "Modules"\r
+    @VP.constantLabelRule           SBC.SharedFunctionsFolder     "Shared Functions"    \r
+    @VP.constantLabelRule           SHEET.Book                    "Spreadsheets"\r
+    \r
+    @VP.customLabelRule             SIMU.Run                      PROJECT.ProjectBrowseContext.RunLabelRule\r
+    @VP.customLabelRule             SBC.BuiltinFunctions          VP.ResourceNameLabelRule\r
+    @VP.customLabelRule             SBC.ModuleSymbol              SBC.ModuleTypeLabelRule\r
+    @VP.customLabelRule             SBC.Variable                  SBC.VariableNameLabelRule\r
+    @VP.customLabelRule             SHEET.Spreadsheet             VP.ResourceNameLabelRule    \r
+    @VP.customLabelRule             SYSDYN.HistoryDataset         VP.ResourceLabelLabelRule    \r
+    @VP.customLabelRule             JFREE.Chart                   VP.ResourceLabelLabelRule        \r
+    \r
+// Modifiers\r
+SBC\r
+    @VP.customLabelRule             SYSDYN.SysdynModelicaFunction   VP.ResourceNameModifierRule     \r
+    @VP.customLabelRule             SYSDYN.HistoryDataset           VP.ResourceLabelModifierRule   \r
+    @VP.customLabelRule             JFREE.Chart                     VP.ResourceLabelModifierRule  \r
+    @VP.customLabelRule             SBC.FunctionsFolder             VP.NoModifierRule   \r
+    \r
+        \r
+// Decorations\r
+SBC.ActiveLabelDecorationRule : VP.ConstantLabelDecorationRule\r
+    VP.ConstantLabelDecorationRule.HasFormat "%s [ACTIVE]"\r
+    VP.ConstantLabelDecorationRule.HasStyle "B"    \r
+    \r
+        \r
+// Images\r
+SBC.VariableImageRule   : VP.ImageRule\r
+SBC.ChartImageRule      : VP.ImageRule\r
+SBC.ResultImageRule     : VP.ImageRule\r
+\r
+SBC\r
+    @VP.customImageRule             SBC.Variable                    SBC.VariableImageRule\r
+    @VP.customImageRule             JFREE.Chart                     SBC.ChartImageRule\r
+    @VP.customImageRule             SYSDYN.Result                   SBC.ResultImageRule \r
+    \r
+\r
+    @VP.constantImageRule           SBC.ExperimentsFolder           SILK.folder\r
+    @VP.constantImageRule           SBC.FunctionsFolder             SILK.folder\r
+    @VP.constantImageRule           SBC.SharedFunctionsFolder       SILK.folder_link   \r
+    @VP.constantImageRule           SYSDYN.SysdynModelicaFunctionLibrary SILK.folder   \r
+    @VP.constantImageRule           SYSDYN.SysdynModelicaFunction   SILK.brick\r
+    @VP.constantImageRule           SBC.ModulesFolder               SILK.folder   \r
+    @VP.constantImageRule           SBC.ModuleSymbol                SILK.bricks\r
+    @VP.constantImageRule           SBC.BuiltinFunctions            SILK.folder_link\r
+    @VP.constantImageRule           SYSDYN.SharedFunctionOntology   SILK.folder_link\r
+    @VP.constantImageRule           SHEET.Book                      SILK.table_multiple\r
+    @VP.constantImageRule           SHEET.Spreadsheet               SILK.table    \r
+    @VP.constantImageRule           SYSDYN.BasicExperiment          SILK.time    \r
+    @VP.constantImageRule           SYSDYN.PlaybackExperiment       SILK.timeline_marker    \r
+    @VP.constantImageRule           SBC.ChartsFolder                SILK.folder   \r
+    @VP.constantImageRule           SYSDYN.HistoryDataset           SILK.table \r
+\r
+SBC \r
+    // Active experiment \r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType SYSDYN.Experiment\r
+        VP.VisualsContribution.HasCondition _ : VP.HasStatementTest\r
+            VP.HasStatementTest.HasRelation SIMU.IsActive\r
+        VP.VisualsContribution.HasRule SBC.ActiveLabelDecorationRule    \r
+     \r
+    // Show result in charts   \r
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
+        VP.VisualsContribution.HasNodeType SYSDYN.Result\r
+        VP.VisualsContribution.HasCondition _ : VP.HasStatementTest\r
+            VP.HasStatementTest.HasRelation SYSDYN.Result.showResult\r
+        VP.VisualsContribution.HasRule SBC.ActiveLabelDecorationRule            \r
+    \r
+    \r
+// Actions \r
+ACTIONS = SAC.Actions : L0.Library   \r
+    \r
+// NEW -Actions    \r
+ACTIONS.NewModuleType                   : ACT.Action\r
+ACTIONS.NewEnumeration                  : ACT.Action\r
+ACTIONS.NewFunction                     : ACT.Action\r
+ACTIONS.NewFunctionLibrary              : ACT.Action\r
+ACTIONS.NewSharedFunctionLibrary        : ACT.Action\r
+ACTIONS.NewExperiment                   : ACT.Action\r
+ACTIONS.NewSimulationPlaybackExperiment : ACT.Action\r
+ACTIONS.NewLineChart                    : ACT.Action\r
+ACTIONS.NewBarChart                     : ACT.Action\r
+ACTIONS.NewPieChart                     : ACT.Action\r
+ACTIONS.NewSheet                        : ACT.Action\r
+ACTIONS.NewHistoryData                  : ACT.Action\r
+    \r
+SAC\r
+    @VP.actionContribution "Module" SBC.ModulesFolder SILK.bricks VP.NewActionCategory ACTIONS.NewModuleType\r
+    @VP.actionContribution "Enumeration" MBC.Configuration SILK.brick VP.NewActionCategory ACTIONS.NewEnumeration\r
+    @VP.actionContribution "Enumeration" SBC.ModuleSymbol SILK.brick VP.NewActionCategory ACTIONS.NewEnumeration\r
+    @VP.actionContribution "Function" SBC.FunctionsFolder SILK.brick VP.NewActionCategory ACTIONS.NewFunction\r
+    @VP.actionContribution "Function" SYSDYN.SysdynModelicaFunctionLibrary SILK.brick VP.NewActionCategory ACTIONS.NewFunction\r
+    @VP.actionContribution "Function" SYSDYN.SharedFunctionOntology SILK.brick VP.NewActionCategory ACTIONS.NewFunction\r
+    @VP.actionContribution "Function Library" SBC.FunctionsFolder SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary\r
+    @VP.actionContribution "Function Library" SYSDYN.SysdynModelicaFunctionLibrary SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary\r
+    @VP.actionContribution "Function Library" SYSDYN.SharedFunctionOntology SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary    \r
+    @VP.actionContribution "Shared Function Library" SBC.SharedFunctionsFolder SILK.folder VP.NewActionCategory ACTIONS.NewSharedFunctionLibrary \r
+    @VP.actionContribution "Experiment" SBC.ExperimentsFolder SILK.time VP.NewActionCategory ACTIONS.NewExperiment\r
+    @VP.actionContribution "Simulation Playback Experiment" SBC.ExperimentsFolder SILK.timeline_marker VP.NewActionCategory ACTIONS.NewSimulationPlaybackExperiment\r
+    @VP.actionContribution "Line Chart" SBC.ChartsFolder SILK.chart_line VP.NewActionCategory ACTIONS.NewLineChart\r
+    @VP.actionContribution "Pie Chart" SBC.ChartsFolder SILK.chart_pie VP.NewActionCategory ACTIONS.NewPieChart\r
+    @VP.actionContribution "Bar Chart" SBC.ChartsFolder SILK.chart_bar VP.NewActionCategory ACTIONS.NewBarChart\r
+    @VP.actionContribution "Sheet" SHEET.Book SILK.table VP.NewActionCategory ACTIONS.NewSheet    \r
+    @VP.actionContribution "History Data" SYSDYN.Experiment SILK.table VP.NewActionCategory ACTIONS.NewHistoryData        \r
+\r
+\r
+// Drop actions\r
+ACTIONS.FunctionDropAction : ACT.DropAction\r
+ACTIONS.ChartDropAction : ACT.DropAction\r
+\r
+SBC\r
+    @VP.dropActionContribution SBC.FunctionsFolder ACTIONS.FunctionDropAction 1.0\r
+    @VP.dropActionContribution SYSDYN.SysdynModelicaFunction ACTIONS.FunctionDropAction 1.0\r
+    @VP.dropActionContribution SYSDYN.SysdynModelicaFunctionLibrary ACTIONS.FunctionDropAction 1.0\r
+    @VP.dropActionContribution SYSDYN.SharedFunctionOntology ACTIONS.FunctionDropAction 1.0    \r
+    @VP.dropActionContribution JFREE.Chart ACTIONS.ChartDropAction 1.0        \r
+\r
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/Validation.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/Validation.pgraph
new file mode 100644 (file)
index 0000000..cfa53e0
--- /dev/null
@@ -0,0 +1,206 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+L0X = <http://www.simantics.org/Layer0X-1.1>\r
+ISSUE = <http://www.simantics.org/Issue-1.2>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+STR = <http://www.simantics.org/Structural-1.2>\r
+\r
+VALIDATIONS = SYSDYN.Validations : L0.Library\r
+\r
+VALIDATIONS.Issue <T ISSUE.Sources.DependencyTracker.Issue\r
+    >-- VALIDATIONS.Issue.stringContexts --> L0.List <R L0.DependsOn  \r
+    \r
+// BASEFUNCTION\r
+VALIDATIONS.Functions : L0.Library\r
+VALIDATIONS.Functions.baseRealizationFunction : L0.Function\r
+VALIDATIONS.Functions.path : L0.Function\r
+   L0.HasValueType "String"  \r
+\r
+// DEPENDENCIES\r
+VALIDATIONS.Dependencies : L0.Library\r
+VALIDATIONS.Dependencies.dependencyValidator : L0.Function\r
+VALIDATIONS.Dependencies.missingDependencyValidator : L0.Function\r
+  \r
+// EXPRESSIONS  \r
+VALIDATIONS.Expressions : L0.Library\r
+VALIDATIONS.Expressions.expressionValidator : L0.Function\r
+\r
+// ENUMERATIONS\r
+VALIDATIONS.Enumerations : L0.Library\r
+VALIDATIONS.Enumerations.enumerationIndexValidator : L0.Function\r
+\r
+// UNITS\r
+VALIDATIONS.Units : L0.Library\r
+VALIDATIONS.Units.unitValidator : L0.Function\r
+VALIDATIONS.Units.moduleInterfaceExtension : L0.Function\r
+\r
+\r
+SYSDYN.Variable\r
+    @VALIDATIONS.constraint\r
+        VALIDATIONS.ExpressionConstraint\r
+        VALIDATIONS.Expressions.ExpressionIssueSource\r
+            @L0.assert L0.HasName "ExpressionIssueSource" \r
+        VALIDATIONS.Expressions.expressionValidator \r
+        VALIDATIONS.Functions.baseRealizationFunction \r
+        \r
+SYSDYN.Variable\r
+    @VALIDATIONS.constraint\r
+        VALIDATIONS.DependencyConstraint\r
+        VALIDATIONS.Dependencies.DependencyConnectionsIssueSource\r
+            @L0.assert L0.HasName "DependencyConnectionsIssueSource"\r
+        VALIDATIONS.Dependencies.dependencyValidator \r
+        VALIDATIONS.Functions.baseRealizationFunction \r
+        \r
+SYSDYN.Enumeration\r
+    @VALIDATIONS.constraint\r
+        VALIDATIONS.EnumerationConstraint\r
+        VALIDATIONS.Enumerations.EnumerationIssueSource\r
+            @L0.assert L0.HasName "EnumerationIssueSource" \r
+        VALIDATIONS.Enumerations.enumerationIndexValidator \r
+        VALIDATIONS.Functions.baseRealizationFunction         \r
+\r
+SYSDYN.Variable\r
+    @VALIDATIONS.listeningConstraint\r
+        VALIDATIONS.MissingDependencyConstraint\r
+        VALIDATIONS.Dependencies.MissingDependencyConnectionsIssueSource\r
+            @L0.assert L0.HasName "MissingDependencyConnectionsIssueSource"\r
+        VALIDATIONS.Dependencies.missingDependencyValidator  \r
+        VALIDATIONS.Functions.baseRealizationFunction \r
+\r
+VALIDATIONS.Units.UnitIssueSource\r
+    >-- VALIDATIONS.Units.UnitIssueSource.allowEquivalents >-- L0.Boolean <R L0.HasProperty : L0.FunctionalRelation\r
+\r
+SYSDYN.Component\r
+    @VALIDATIONS.listeningConstraint\r
+        VALIDATIONS.UnitConstraint\r
+        VALIDATIONS.Units.UnitIssueSource\r
+            @L0.assert L0.HasName "UnitIssueSource"\r
+            @L0.assert VALIDATIONS.Units.UnitIssueSource.allowEquivalents L0.True\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Sources.DependencyTracker.HasExtension\r
+                L0.HasObject VALIDATIONS.Units.moduleInterfaceExtension\r
+        VALIDATIONS.Units.unitValidator  \r
+        VALIDATIONS.Functions.baseRealizationFunction\r
+\r
+VALIDATIONS.ExpressionIssue\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Error\r
+        VALIDATIONS.Expressions.expressionIssueDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path\r
+        \r
+VALIDATIONS.MissingLinkIssue\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Warning\r
+        VALIDATIONS.Dependencies.missingLinkIssueDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path\r
+                        \r
+VALIDATIONS.UnusedDependencyIssue\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Warning\r
+        VALIDATIONS.Dependencies.unusedDependencyIssueDescription : L0.Function   \r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path\r
+        \r
+VALIDATIONS.NoSuchVariableIssue\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Error\r
+        VALIDATIONS.Dependencies.noSuchVariableIssueDescription : L0.Function     \r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path\r
+\r
+VALIDATIONS.RangeIssue\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Error\r
+        VALIDATIONS.Dependencies.rangeIssueDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path        \r
+        \r
+VALIDATIONS.RangeWarning\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Warning\r
+        VALIDATIONS.Dependencies.rangeWarningDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path                   \r
+        \r
+VALIDATIONS.InvalidSheetReferenceIssue\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Error\r
+        VALIDATIONS.Dependencies.invalidSheetReferenceIssueDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path \r
+                    \r
+VALIDATIONS.EmptyEnumerationIssue\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Error\r
+        VALIDATIONS.Enumerations.emptyEnumerationIssueDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path     \r
+        \r
+VALIDATIONS.UnitWarning\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Warning\r
+        VALIDATIONS.Units.unitWarningDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path        \r
+\r
+VALIDATIONS.ModuleInputUnitWarning\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Warning\r
+        VALIDATIONS.Units.moduleInputUnitWarningDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path   \r
+        \r
+VALIDATIONS.ModuleOutputUnitWarning\r
+    @VALIDATIONS.issue\r
+        ISSUE.Severity.Warning\r
+        VALIDATIONS.Units.moduleOutputUnitWarningDescription : L0.Function\r
+            L0.HasValueType "String"\r
+        VALIDATIONS.Functions.path   \r
+        \r
+// IssueSource template\r
+VALIDATIONS.constraint : L0.Template\r
+    @template %type %constraint %source %validator %baseFunction\r
+        %type\r
+            L0.HasConstraint %constraint : L0.Constraint\r
+                L0.Constraint.Validator %validator\r
+        %source <T ISSUE.Sources.DependencyTracker\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Sources.DependencyTracker.HasType\r
+                L0.HasObject %type\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Sources.DependencyTracker.HasConstraint\r
+                L0.HasObject %constraint     \r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Sources.DependencyTracker.HasBaseFunction\r
+                L0.HasObject %baseFunction                          \r
+\r
+VALIDATIONS.listeningConstraint : L0.Template\r
+    @template %type %constraint %source %validator %baseFunction\r
+        %type\r
+            L0.HasConstraint %constraint : L0.Constraint\r
+                L0.Constraint.Validator %validator\r
+        %source <T ISSUE.Sources.ListeningDependencyTracker\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Sources.DependencyTracker.HasType\r
+                L0.HasObject %type\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Sources.DependencyTracker.HasConstraint\r
+                L0.HasObject %constraint\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Sources.DependencyTracker.HasBaseFunction\r
+                L0.HasObject %baseFunction                \r
+\r
+// Issue template\r
+VALIDATIONS.issue : L0.Template\r
+    @template %issue %severity %description %path\r
+        %issue <T SYSDYN.Validations.Issue\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Issue.HasSeverity\r
+                L0.HasObject %severity\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate L0.HasDescription\r
+                L0.HasObject %description\r
+            L0.Asserts _ : L0.Assertion\r
+                L0.HasPredicate ISSUE.Issue.path\r
+                L0.HasObject %path                
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/VensimFunctions.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/VensimFunctions.pgraph
new file mode 100644 (file)
index 0000000..fdee797
--- /dev/null
@@ -0,0 +1,537 @@
+\r
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+\r
+VF = <http://www.simantics.org/Sysdyn-1.1/Built-in Functions/Vensim Functions> : SYSDYN.SysdynModelicaFunctionLibrary\r
+\r
+/*\r
+VF.DELAYFIXED : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """DELAY FIXED( inputVar , dtime , init )\r
+    -> delay(inputVar, dtime)\r
+    init -value is ignored."""\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real inputVar;\r
+    input Real dtime;\r
+    input Real init;\r
+    input Real t = time;\r
+    output Real z;\r
+protected\r
+    parameter Real parameterDTime = dtime; \r
+algorithm\r
+    z := if time < parameterDTime then init else delay(inputVar, parameterDTime);"""\r
+*/\r
+    \r
+    \r
+    \r
+VF.IFTHENELSE : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """IFTHENELSE( cond , ontrue , onfalse )\r
+\r
+Returns ontrue if cond, otherwise onfalse"""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.IFTHENELSE.cond : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+            VF.IFTHENELSE.ontrue : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            VF.IFTHENELSE.onfalse : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.IFTHENELSE.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Boolean cond;\r
+    input Real ontrue;\r
+    input Real onfalse;\r
+    output Real z;\r
+algorithm\r
+    z := if cond then ontrue else onfalse;"""    \r
+    \r
+    \r
+    \r
+VF.MAX : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """MAX(a, b) \r
+\r
+Returns the larger of a and b."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.MAX.a : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            VF.MAX.b : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.MAX.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real a;\r
+    input Real b;\r
+    output Real z;\r
+algorithm\r
+    z := if a > b then a else b;"""       \r
+    \r
+    \r
+    \r
+VF.MIN : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """MIN(a, b) \r
+\r
+Returns the smaller of a and b."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.MIN.a : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            VF.MIN.b : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.MIN.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real a;\r
+    input Real b;\r
+    output Real z;\r
+algorithm\r
+    z := if a < b then a else b;"""        \r
+    \r
+    \r
+    \r
+VF.XIDZ : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """XIDZ(a, b, x)\r
+\r
+x if divided by zero, a/b otherwise."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.XIDZ.a : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            VF.XIDZ.b : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'q"\r
+            VF.XIDZ.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p/'q"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.XIDZ.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p/'q"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real a;\r
+    input Real b;\r
+    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := xidz(a, b, x);"""     \r
+    \r
+    \r
+    \r
+VF.ZIDZ : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """ZIDZ(a, b)\r
+\r
+Zero if divided by zero, a/b otherwise."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.ZIDZ.a : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            VF.ZIDZ.b : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'q"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.ZIDZ.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p/'q"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real a;\r
+    input Real b;\r
+    output Real z;\r
+algorithm\r
+    z := zidz(a, b);"""       \r
+    \r
+    \r
+    \r
+VF.ABS : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """ABS(x)\r
+\r
+Returns the absolute value of x."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.ABS.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.ABS.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := abs(x);"""      \r
+    \r
+    \r
+    \r
+VF.SQRT : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """SQRT(x)\r
+\r
+Returns the square root of x."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.SQRT.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.SQRT.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := sqrt(x);"""   \r
+        \r
+        \r
+        \r
+VF.MODULO : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """MODULO(a, b)\r
+\r
+Returns the remainder when a is divided by b. """\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.MODULO.a : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            VF.MODULO.b : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.MODULO.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real a;\r
+    input Real b;\r
+    output Real z;\r
+algorithm\r
+    z := mod(a, b);"""       \r
+    \r
+    \r
+    \r
+VF.PULSE : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """PULSE(start, width)\r
+\r
+Returns 1.0 starting at time start and lasting for interval width. 0.0 is returned at other times."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.PULSE.start : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+            VF.PULSE.width : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.PULSE.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real start;\r
+    input Real width;\r
+    input Real t = time;\r
+    output Real z;    \r
+algorithm\r
+    z := if t >= start and (t - start) <= width then 1.0 else 0.0;"""    \r
+    \r
+    \r
+    \r
+VF.RAMP : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """RAMP(slope, startTime, endTime) \r
+\r
+Returns 0 until the start time and then slopes upward until end time and then holds constant."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.RAMP.slope : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            VF.RAMP.startTime : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+            VF.RAMP.endTime : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.RAMP.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real slope;\r
+    input Real startTime;\r
+    input Real endTime;\r
+    input Real t = time;\r
+    output Real z;    \r
+algorithm\r
+    z := \r
+    if t > startTime then\r
+        if t < endTime then \r
+            slope * (t - startTime) \r
+        else\r
+            slope * (endTime - startTime)\r
+    else\r
+        0;"""        \r
+    \r
+    \r
+    \r
+VF.STEP : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """STEP(height, stepTime)\r
+\r
+Returns 0.0 until the step time and then returns height."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.STEP.height : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+            VF.STEP.stepTime : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "TIME"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.STEP.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real height;\r
+    input Real stepTime;\r
+    input Real t = time;\r
+    output Real z;\r
+algorithm\r
+    z := if t >= stepTime then height else 0.0;""" \r
+    \r
+    \r
+    \r
+/* Continuous built-in common mathematical functions */\r
+\r
+VF.EXP : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """EXP(x)\r
+\r
+Exponential, base e."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.EXP.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.EXP.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := exp(x);"""\r
+    \r
+    \r
+    \r
+VF.SIN : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """SIN(x)\r
+\r
+Returns the sine of x."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.SIN.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.SIN.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := sin(x);"""  \r
+          \r
+          \r
+            \r
+VF.SINH : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """SINH(x)\r
+\r
+Returns the hyperbolic sine of x."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.SINH.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.SINH.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := sinh(x);"""  \r
+\r
+\r
+\r
+VF.COS : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """COS(x)\r
+\r
+Returns the cosine of x."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.COS.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.COS.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := cos(x);"""  \r
+    \r
+    \r
+    \r
+VF.COSH : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """COSH(x)\r
+\r
+Returns the hyperbolic cosine of x."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.COSH.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.COSH.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := cosh(x);"""  \r
+    \r
+    \r
+    \r
+VF.TAN : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """TAN(x)\r
+\r
+Returns the tangent of x."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.TAN.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.TAN.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := tan(x);"""  \r
+    \r
+    \r
+    \r
+VF.TANH : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """TANH(x)\r
+\r
+Returns the hyperbolic tangent of x."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.TANH.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.TANH.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := tanh(x);"""  \r
+    \r
+    \r
+    \r
+VF.LN : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """LN(x)\r
+\r
+Returns the natural logarithm of x. \r
+\r
+In modelica log(x) is the natural logarighm and log10(x) is base 10 logarighm."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.LN.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "ANY"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.LN.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "1"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := log(x);"""  \r
+         \r
+         \r
+         \r
+VF.GAME : SYSDYN.SysdynModelicaFunction\r
+    L0.HasDescription """GAME(x)\r
+\r
+Returns x during normal simulation with x being any expression.\r
+\r
+In Vensim, this function allows modifying the variable in game mode. However, this behavior is not implemented yet."""\r
+    SYSDYN.SysdynModelicaFunction.inputs _ : L0.List\r
+        @L0.list\r
+            VF.GAME.x : SYSDYN.SysdynModelicaFunction.Input\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.optional false\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.outputs _ : L0.List\r
+        @L0.list\r
+            VF.GAME.z : SYSDYN.SysdynModelicaFunction.Output\r
+                SYSDYN.Variable.type "Real"\r
+                SYSDYN.SysdynModelicaFunction.unit "'p"\r
+    SYSDYN.SysdynModelicaFunction.modelicaFunctionCode """    input Real x;\r
+    output Real z;\r
+algorithm\r
+    z := x;""" 
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/WorkModel.pgraph b/1.8/org.simantics.sysdyn.ontology/graph/WorkModel.pgraph
new file mode 100644 (file)
index 0000000..de9d0ea
--- /dev/null
@@ -0,0 +1,751 @@
+L0 = <http://www.simantics.org/Layer0-1.1>\r
+L0X = <http://www.simantics.org/Layer0X-1.1>\r
+G2D = <http://www.simantics.org/G2D-1.1>\r
+STR = <http://www.simantics.org/Structural-1.2>\r
+DIA = <http://www.simantics.org/Diagram-2.2>\r
+SIMU = <http://www.simantics.org/Simulation-1.1>\r
+MOD = <http://www.simantics.org/Modeling-1.2>\r
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
+PROJ = <http://www.simantics.org/Project-1.2>\r
+\r
+//######################################################################\r
+//# Example work model with two modules\r
+//######################################################################\r
+\r
+/*\r
+WM = <http://Projects/Development Project> : PROJ.Project\r
+    @L0.new\r
+*/\r
+    \r
+/*    \r
+WM = <http://Projects/Work Model Project> : PROJ.Project\r
+    @L0.new\r
+\r
+\r
+TAGS = WM.Tags : L0.Library\r
+   \r
+    \r
+WM.dependency : L0.Template\r
+    @template %type %head %tail %angle\r
+        %type \r
+            @L0.tag TAGS.AdminIsVisible\r
+            @L0.tag TAGS.AdminIsFocusable\r
+            STR.HasConnectionType SYSDYN.SysdynConnectionType\r
+            SYSDYN.Dependency.angle %angle \r
+            DIA.HasArrowConnector _ : DIA.Connector\r
+                SYSDYN.HasHeadTerminal %head\r
+                DIA.AreConnected _ : DIA.Connector \r
+                  SYSDYN.HasTailTerminal %tail\r
+                  DIA.IsPlainConnectorOf %type\r
+                           \r
+WM.flow : L0.Template\r
+    @template %type %head %tail\r
+        %type \r
+            @L0.tag TAGS.AdminIsVisible\r
+            @L0.tag TAGS.AdminIsFocusable\r
+            STR.HasConnectionType SYSDYN.SysdynConnectionType\r
+            DIA.HasArrowConnector _ : DIA.Connector\r
+                SYSDYN.HasHeadTerminal %head\r
+                DIA.AreConnected _ : DIA.Connector \r
+                  SYSDYN.HasTailTerminal %tail\r
+                  DIA.IsPlainConnectorOf %type              \r
+\r
+WM.conf_dependency : L0.Template\r
+    @template %type %head %tail\r
+        %type \r
+            @L0.tag MOD.Mapped\r
+            SYSDYN.HasHead %head\r
+            SYSDYN.HasTail %tail\r
+                                \r
+WM.conf_dependency_ref : L0.Template\r
+    @template %type %head %tail %ref\r
+        %type \r
+            @L0.tag MOD.Mapped\r
+            SYSDYN.HasHead %head\r
+            SYSDYN.HasTail %tail\r
+            SYSDYN.Dependency.refersTo %ref                      \r
+\r
+\r
+\r
+WM.WorkSymbol <T SYSDYN.ModuleSymbol\r
+  MOD.SymbolToComponentType WM.WorkModel.WorkModule\r
+  STR.IsDefinedBy _ : DIA.Composite <R L0.HasNext\r
+      @L0.orderedSet \r
+          _ : SYSDYN.SysdynTerminal\r
+            @MOD.terminal SYSDYN.ModuleSymbol SYSDYN.IsHeadOfTerminal\r
+          _ : SYSDYN.SysdynTerminal\r
+            @MOD.terminal SYSDYN.ModuleSymbol SYSDYN.IsTailOfTerminal\r
+\r
+WM.WorkforceSymbol <T SYSDYN.ModuleSymbol\r
+  MOD.SymbolToComponentType WM.WorkModel.WorkforceModule\r
+  STR.IsDefinedBy _ : DIA.Composite <R L0.HasNext\r
+      @L0.orderedSet \r
+          _ : SYSDYN.SysdynTerminal\r
+            @MOD.terminal SYSDYN.ModuleSymbol SYSDYN.IsHeadOfTerminal\r
+          _ : SYSDYN.SysdynTerminal\r
+            @MOD.terminal SYSDYN.ModuleSymbol SYSDYN.IsTailOfTerminal\r
+\r
+WM.WorkModel : SYSDYN.SysdynModel\r
+    L0.HasLabel "Work Model" \r
+    SIMU.HasConfiguration WC\r
+    SYSDYN.SysdynModel.startTime 0.0 \r
+    SYSDYN.SysdynModel.stopTime 24.0 \r
+    L0.IsLinkedTo SYSDYN\r
+    L0.IsLinkedTo L0\r
+    \r
+WM.WorkModel.Experiment : SYSDYN.Experiment\r
+    L0.HasLabel "Experiment" \r
+\r
+WC = WM.WorkModel.WorkModelConfiguration : SYSDYN.Configuration\r
+  L0.HasLabel "WorkModelConfiguration" \r
+\r
+  \r
+// Modules\r
+WC.Workforce : WM.WorkModel.WorkforceModule\r
+    @L0.tag MOD.Mapped\r
+    L0.HasLabel "Workforce" \r
+WC.Work1 : WM.WorkModel.WorkModule\r
+    @L0.tag MOD.Mapped\r
+    L0.HasLabel "Work1"    \r
+WC.Work2 : WM.WorkModel.WorkModule\r
+    @L0.tag MOD.Mapped\r
+    L0.HasLabel "Work2"        \r
+      \r
+// Parameters\r
+WC.Work1CompletionTime : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.ParameterExpression\r
+                SYSDYN.Expression.equation "15"      \r
+WC.Work2CompletionTime : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped    \r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.ParameterExpression\r
+                SYSDYN.Expression.equation "11"     \r
+WC.Work2Amount : SYSDYN.Auxiliary\r
+      @L0.tag MOD.Mapped    \r
+      SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.ParameterExpression\r
+                SYSDYN.Expression.equation "700"     \r
+        \r
+// Enumeration Test\r
+WC.EnumerationTest : SYSDYN.Enumeration\r
+    SYSDYN.Enumeration.enumerationIndexes _ : SYSDYN.EnumerationIndexes\r
+        @L0.orderedSet\r
+            _ : SYSDYN.EnumerationIndex\r
+                L0.HasName "Moro" : L0.String\r
+            _ : SYSDYN.EnumerationIndex\r
+                L0.HasName "Tere" : L0.String            \r
+     \r
+// Inputs\r
+WC.TotalPossibleWorkingSpeedInput : SYSDYN.Input\r
+    @L0.tag MOD.Mapped\r
+WC.RequiredWorkingSpeed1 : SYSDYN.Input\r
+    @L0.tag MOD.Mapped\r
+WC.RequiredWorkingSpeed2 : SYSDYN.Input\r
+    @L0.tag MOD.Mapped     \r
+WC.Work1WorkDone : SYSDYN.Input\r
+    @L0.tag MOD.Mapped     \r
+WC.Work2WorkDone : SYSDYN.Input\r
+    @L0.tag MOD.Mapped                 \r
+      \r
+// Auxiliaries    \r
+WC.RequiredWorkingSpeedTotal : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "RequiredWorkingSpeed1+RequiredWorkingSpeed2"                            \r
+          \r
+WC.d1  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.TotalPossibleWorkingSpeedInput WC.Workforce WFC.PossibleWorkingSpeed        \r
+WC.d2  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work1 WC.TotalPossibleWorkingSpeedInput WMC.PossibleWorkingSpeedInput       \r
+WC.d3  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work1 WC.Work1CompletionTime WMC.WorkCompletionTimeInput\r
+WC.d4  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work1 WC.RequiredWorkingSpeedTotal WMC.RequiredWorkingSpeedTotalInput       \r
+WC.d5  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.RequiredWorkingSpeed1 WC.Work1 WMC.RequiredWorkingSpeed       \r
+WC.d6  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work2 WC.TotalPossibleWorkingSpeedInput WMC.PossibleWorkingSpeedInput       \r
+WC.d7  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work2 WC.Work2CompletionTime WMC.WorkCompletionTimeInput       \r
+WC.d8  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work2 WC.RequiredWorkingSpeedTotal WMC.RequiredWorkingSpeedTotalInput       \r
+WC.d9  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.RequiredWorkingSpeed2 WC.Work2 WMC.RequiredWorkingSpeed       \r
+WC.d10  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Workforce WC.RequiredWorkingSpeedTotal WFC.RequiredWorkingSpeedInput    \r
+WC.d11  : SYSDYN.Dependency\r
+    @WM.conf_dependency WC.RequiredWorkingSpeedTotal WC.RequiredWorkingSpeed1\r
+WC.d12  : SYSDYN.Dependency\r
+    @WM.conf_dependency WC.RequiredWorkingSpeedTotal WC.RequiredWorkingSpeed2\r
+WC.d13  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work1WorkDone WC.Work1 WMC.WorkDone\r
+WC.d14  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work2WorkDone WC.Work2 WMC.WorkDone   \r
+WC.d15  : SYSDYN.Dependency\r
+    @WM.conf_dependency_ref WC.Work2 WC.Work2Amount WMC.ProjectWorkAmount        \r
+               \r
+             \r
+WorkModelConfigurationDiagram : SYSDYN.ConfigurationDiagram <R L0.HasNext\r
+    MOD.DiagramToComposite WC\r
+    DIA.HasLayer WM.Admin : DIA.Layer\r
+        DIA.IsActive true \r
+        DIA.HasFocusableTag TAGS.AdminIsFocusable <R DIA.IsFocusable\r
+            @L0.symmetric\r
+        DIA.HasVisibleTag TAGS.AdminIsVisible <R DIA.IsVisible\r
+            @L0.symmetric\r
+    L0X.HasTrigger _ : SYSDYN.DiagramToCompositeMapping\r
+// DIA.NavigationEnabled "false" \r
+    @L0.orderedSet\r
+        WorkforceElement : WM.WorkforceSymbol\r
+            MOD.ElementToComponent WC.Workforce\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 101.0, 50.0] : G2D.Transform\r
+        Work1Element : WM.WorkSymbol\r
+            MOD.ElementToComponent WC.Work1\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 114.0, 87.0] : G2D.Transform\r
+        Work2Element : WM.WorkSymbol\r
+            MOD.ElementToComponent WC.Work2\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 108.0, 161.0] : G2D.Transform        \r
+        Work1CompletionTimeElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WC.Work1CompletionTime\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 165.0, 99.0] : G2D.Transform        \r
+        Work2CompletionTimeElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WC.Work2CompletionTime\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 165.0, 153.0] : G2D.Transform   \r
+        Work2AmountElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WC.Work2Amount\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 75.0, 160.0] : G2D.Transform   \r
+        RequiredWorkingSpeedTotalElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WC.RequiredWorkingSpeedTotal\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 32.0, 76.0] : G2D.Transform           \r
+        TotalPossibleWorkingSpeedInputElement : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WC.TotalPossibleWorkingSpeedInput\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 141.0, 60.0] : G2D.Transform\r
+        RequiredWorkingSpeed1Element : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WC.RequiredWorkingSpeed1\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 65.0, 125.0] : G2D.Transform\r
+        RequiredWorkingSpeed2Element : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WC.RequiredWorkingSpeed2\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 100.0, 122.0] : G2D.Transform\r
+        Work1WorkDoneElement : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WC.Work1WorkDone\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 155.0, 110.0] : G2D.Transform\r
+        Work2WorkDoneElement : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WC.Work2WorkDone\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 155.0, 130.0] : G2D.Transform                \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d1 \r
+            @WM.dependency TotalPossibleWorkingSpeedInputElement WorkforceElement -0.1        \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d2\r
+            @WM.dependency Work1Element TotalPossibleWorkingSpeedInputElement  -0.1      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d3 \r
+            @WM.dependency Work1Element  Work1CompletionTimeElement -0.1      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d4 \r
+            @WM.dependency Work1Element  RequiredWorkingSpeedTotalElement -0.1        \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d5 \r
+            @WM.dependency RequiredWorkingSpeed1Element  Work1Element -0.1      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d6\r
+            @WM.dependency Work2Element  TotalPossibleWorkingSpeedInputElement  -0.1      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d7 \r
+            @WM.dependency Work2Element  Work2CompletionTimeElement -0.1        \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d8 \r
+            @WM.dependency Work2Element  RequiredWorkingSpeedTotalElement -0.1      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d9\r
+            @WM.dependency RequiredWorkingSpeed2Element  Work2Element -0.1      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d10\r
+            @WM.dependency WorkforceElement RequiredWorkingSpeedTotalElement -0.1      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d11\r
+            @WM.dependency RequiredWorkingSpeedTotalElement RequiredWorkingSpeed1Element -0.1      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d12\r
+            @WM.dependency RequiredWorkingSpeedTotalElement RequiredWorkingSpeed2Element -0.1                      \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d13\r
+            @WM.dependency Work1WorkDoneElement Work1Element  -0.1    \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d14\r
+            @WM.dependency Work2WorkDoneElement Work2Element  -0.1    \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WC.d15\r
+            @WM.dependency Work2Element Work2AmountElement  -0.1            \r
+     \r
+WM.WorkModel.WorkModule <T SYSDYN.Module\r
+  STR.IsDefinedBy WMC\r
+\r
+WMC = WM.WorkModel.WorkModuleConfiguration : SYSDYN.Configuration  \r
+// Parameters\r
+WMC.MaximumWorkingSpeed : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.ParameterExpression\r
+                SYSDYN.Expression.equation "500"      \r
+WMC.WorkQuality : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.ParameterExpression\r
+                SYSDYN.Expression.equation "0.9"  \r
+                                     \r
+// Valves\r
+WMC.WorkingSpeed : SYSDYN.Valve\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "if ProjectIsReady  < 1 then WorkAllocation else 0" \r
+WMC.ErrorsGenerated : SYSDYN.Valve\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "(1-WorkQuality)*WorkingSpeed"                                                          \r
+WMC.ErrorsFoundRate : SYSDYN.Valve\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "Errors/ErrorsFoundTime"    \r
+WMC.ProjectReadyness : SYSDYN.Valve\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "(xidz(WorkDone, ProjectWorkAmount, 0.0) - ProjectIsReady) / 0.08"                       \r
+        \r
+\r
+        \r
+// Stocks\r
+WMC.WorkToDo : SYSDYN.Stock\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.StockExpression\r
+                SYSDYN.StockExpression.initialEquation "ProjectWorkAmount"      \r
+WMC.WorkDone : SYSDYN.Stock\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.StockExpression\r
+                SYSDYN.StockExpression.initialEquation "0"     \r
+      @L0.tag SYSDYN.IsOutput\r
+WMC.Errors : SYSDYN.Stock\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.StockExpression\r
+                SYSDYN.StockExpression.initialEquation "0"           \r
+WMC.ProjectIsReady : SYSDYN.Stock\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.StockExpression\r
+                SYSDYN.StockExpression.initialEquation "0"                 \r
+        \r
+// Auxiliaries    \r
+WMC.TimeToDeadline : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "max(0, WorkCompletionTimeInput-time)"      \r
+WMC.RequiredWorkingSpeed : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped\r
+    @L0.tag SYSDYN.IsOutput\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "if ProjectIsReady < 1 then xidz(WorkToDo, TimeToDeadline, MaximumWorkingSpeed) else 0"      \r
+WMC.WorkAllocation : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "xidz(RequiredWorkingSpeed, RequiredWorkingSpeedTotalInput, 0.0) * PossibleWorkingSpeedInput"      \r
+WMC.ErrorsFoundTime : SYSDYN.Auxiliary\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.WithLookupExpression\r
+                SYSDYN.Expression.equation "xidz(WorkDone, ProjectWorkAmount, 0.0)"    \r
+                SYSDYN.WithLookupExpression.lookup "{{0,5},{0.5,3},{1,0.5},{2,0.5}}"    \r
+                SYSDYN.WithLookupExpression.minX 0.0\r
+                SYSDYN.WithLookupExpression.maxX 5.0\r
+                SYSDYN.WithLookupExpression.minY 0.0\r
+                SYSDYN.WithLookupExpression.maxY 5.0\r
+\r
+// Inputs\r
+WMC.WorkCompletionTimeInput : SYSDYN.Input\r
+    @L0.tag MOD.Mapped\r
+WMC.PossibleWorkingSpeedInput : SYSDYN.Input\r
+    @L0.tag MOD.Mapped   \r
+WMC.RequiredWorkingSpeedTotalInput : SYSDYN.Input\r
+    @L0.tag MOD.Mapped       \r
+WMC.ProjectWorkAmount : SYSDYN.Input\r
+    @L0.tag MOD.Mapped\r
+    SYSDYN.Input.defaultInputValue 1000.0                                \r
+   \r
+WMC.c31 : SYSDYN.Cloud\r
+WMC.c33 : SYSDYN.Cloud\r
+   \r
+WMC.d31  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.TimeToDeadline WMC.WorkCompletionTimeInput     \r
+WMC.d32  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.RequiredWorkingSpeed WMC.MaximumWorkingSpeed     \r
+WMC.d33  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.RequiredWorkingSpeed WMC.TimeToDeadline     \r
+WMC.d34  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.RequiredWorkingSpeed WMC.ProjectIsReady     \r
+WMC.d35  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.RequiredWorkingSpeed WMC.WorkToDo     \r
+WMC.d36  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.WorkAllocation WMC.RequiredWorkingSpeedTotalInput     \r
+WMC.d37  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.WorkAllocation WMC.PossibleWorkingSpeedInput     \r
+WMC.d38  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.WorkAllocation WMC.RequiredWorkingSpeed       \r
+WMC.d40  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.ProjectReadyness WMC.WorkDone     \r
+WMC.d41  : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.ProjectReadyness WMC.ProjectWorkAmount     \r
+WMC.d42 : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.WorkingSpeed WMC.WorkAllocation     \r
+WMC.d43 : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.WorkingSpeed WMC.ProjectIsReady     \r
+WMC.d44 : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.ErrorsGenerated WMC.WorkingSpeed     \r
+WMC.d45 : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.ErrorsGenerated WMC.WorkQuality     \r
+WMC.d46 : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.ErrorsFoundRate WMC.Errors     \r
+WMC.d47 : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.ErrorsFoundRate WMC.ErrorsFoundTime     \r
+WMC.d48 : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.ErrorsFoundTime WMC.ProjectWorkAmount     \r
+WMC.d49 : SYSDYN.Dependency\r
+      @WM.conf_dependency WMC.ErrorsFoundTime WMC.WorkDone       \r
+     \r
+                     \r
+WMC.f31  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.WorkingSpeed WMC.WorkToDo   \r
+WMC.f32  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.WorkDone WMC.WorkingSpeed   \r
+WMC.f33  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.ErrorsGenerated WMC.c31   \r
+WMC.f34  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.Errors WMC.ErrorsGenerated   \r
+WMC.f35  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.ErrorsFoundRate WMC.Errors   \r
+WMC.f36  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.ErrorsFoundRate WMC.WorkDone   \r
+WMC.f37  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.WorkToDo WMC.ErrorsFoundRate   \r
+WMC.f40  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.ProjectIsReady WMC.ProjectReadyness   \r
+WMC.f41  : SYSDYN.Flow\r
+      @WM.conf_dependency WMC.ProjectReadyness WMC.c33   \r
+       \r
+WorkModuleConfigurationDiagram : SYSDYN.ConfigurationDiagram <R L0.HasNext\r
+    MOD.DiagramToComposite WMC\r
+    DIA.HasLayer WM.Admin\r
+\r
+    L0X.HasTrigger _ : SYSDYN.DiagramToCompositeMapping\r
+    @L0.orderedSet\r
+        WorkCompletionTimeInputElement : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WMC.WorkCompletionTimeInput\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 60.0, 55.0] : G2D.Transform           \r
+        PossibleWorkingSpeedInputElement : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WMC.PossibleWorkingSpeedInput\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 190.0, 60.0] : G2D.Transform           \r
+        RequiredWorkingSpeedTotalInputElement : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WMC.RequiredWorkingSpeedTotalInput\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 165.0, 45.0] : G2D.Transform     \r
+        ProjectWorkAmountElement : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WMC.ProjectWorkAmount\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 210.0, 120.0] : G2D.Transform                 \r
+      \r
+        WorkingSpeedElement : SYSDYN.ValveSymbol\r
+            MOD.ElementToComponent WMC.WorkingSpeed\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 125.0, 100.0] : G2D.Transform    \r
+        ErrorsGeneratedElement : SYSDYN.ValveSymbol\r
+            MOD.ElementToComponent WMC.ErrorsGenerated\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 135.0, 110.0] : G2D.Transform    \r
+        ErrorsFoundRateElement : SYSDYN.ValveSymbol\r
+            MOD.ElementToComponent WMC.ErrorsFoundRate\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 140.0, 140.0] : G2D.Transform   \r
+        ProjectReadynessElement : SYSDYN.ValveSymbol\r
+            MOD.ElementToComponent WMC.ProjectReadyness\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 215.0, 85.0] : G2D.Transform    \r
+        \r
+        WorkToDoElement : SYSDYN.StockSymbol\r
+            MOD.ElementToComponent WMC.WorkToDo\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 85.0, 100.0] : G2D.Transform          \r
+        WorkDoneElement : SYSDYN.StockSymbol\r
+            MOD.ElementToComponent WMC.WorkDone\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 160.0, 100.0] : G2D.Transform   \r
+        ErrorsElement : SYSDYN.StockSymbol\r
+            MOD.ElementToComponent WMC.Errors\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 153.0, 110.0] : G2D.Transform   \r
+        ProjectIsReadyElement : SYSDYN.StockSymbol\r
+            MOD.ElementToComponent WMC.ProjectIsReady\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 180.0, 85.0] : G2D.Transform                   \r
+          \r
+        MaximumWorkingSpeedElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WMC.MaximumWorkingSpeed\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 45.0, 70.0] : G2D.Transform   \r
+        WorkQualityElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WMC.WorkQuality\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 120.0, 130.0] : G2D.Transform   \r
+        TimeToDeadlineElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WMC.TimeToDeadline\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 80.0, 75.0] : G2D.Transform   \r
+        RequiredWorkingSpeedElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WMC.RequiredWorkingSpeed\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 90.0, 90.0] : G2D.Transform   \r
+        WorkAllocationElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WMC.WorkAllocation\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 140.0, 75.0] : G2D.Transform   \r
+        ErrorsFoundTimeElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WMC.ErrorsFoundTime\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 180.0, 140.0] : G2D.Transform   \r
+\r
+        c31Element : SYSDYN.CloudSymbol\r
+            MOD.ElementToComponent WMC.c31\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 110.0, 110.0] : G2D.Transform    \r
+        c33Element : SYSDYN.CloudSymbol\r
+            MOD.ElementToComponent WMC.c33\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 230.0, 85.0] : G2D.Transform           \r
+                  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d31\r
+            @WM.dependency TimeToDeadlineElement WorkCompletionTimeInputElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d32\r
+            @WM.dependency RequiredWorkingSpeedElement MaximumWorkingSpeedElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d33\r
+            @WM.dependency RequiredWorkingSpeedElement TimeToDeadlineElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d34\r
+            @WM.dependency RequiredWorkingSpeedElement ProjectIsReadyElement   -0.1  \r
+          _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d36\r
+            @WM.dependency WorkAllocationElement RequiredWorkingSpeedTotalInputElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d35\r
+            @WM.dependency RequiredWorkingSpeedElement WorkToDoElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d37\r
+            @WM.dependency WorkAllocationElement PossibleWorkingSpeedInputElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d38\r
+            @WM.dependency WorkAllocationElement RequiredWorkingSpeedElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d40\r
+            @WM.dependency ProjectReadynessElement WorkDoneElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d41\r
+            @WM.dependency ProjectReadynessElement ProjectWorkAmountElement   -0.1            \r
+        _ : SYSDYN.DependencyConnection            \r
+            MOD.DiagramConnectionToConnection WMC.d42\r
+            @WM.dependency WorkingSpeedElement WorkAllocationElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d43\r
+            @WM.dependency WorkingSpeedElement ProjectIsReadyElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d44\r
+            @WM.dependency ErrorsGeneratedElement WorkingSpeedElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d45\r
+            @WM.dependency ErrorsGeneratedElement WorkQualityElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d46\r
+            @WM.dependency ErrorsFoundRateElement ErrorsElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d47\r
+            @WM.dependency ErrorsFoundRateElement ErrorsFoundTimeElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d48\r
+            @WM.dependency ErrorsFoundTimeElement ProjectWorkAmountElement   -0.1  \r
+        _ : SYSDYN.DependencyConnection\r
+            MOD.DiagramConnectionToConnection WMC.d49\r
+            @WM.dependency ErrorsFoundTimeElement WorkDoneElement   -0.1              \r
+      \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f31\r
+              @WM.flow WorkingSpeedElement WorkToDoElement   \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f32\r
+              @WM.flow WorkDoneElement WorkingSpeedElement   \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f33\r
+              @WM.flow ErrorsGeneratedElement c31Element   \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f34\r
+              @WM.flow ErrorsElement ErrorsGeneratedElement   \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f35\r
+              @WM.flow ErrorsFoundRateElement ErrorsElement   \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f36\r
+              @WM.flow ErrorsFoundRateElement WorkDoneElement   \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f37\r
+              @WM.flow WorkToDoElement ErrorsFoundRateElement   \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f40\r
+              @WM.flow ProjectIsReadyElement ProjectReadynessElement   \r
+        _ : SYSDYN.FlowConnection\r
+              MOD.DiagramConnectionToConnection WMC.f41\r
+              @WM.flow ProjectReadynessElement c33Element   \r
+                      \r
+      \r
+WM.WorkModel.WorkforceModule <T SYSDYN.Module\r
+  STR.IsDefinedBy WM.WorkModel.WorkforceModuleConfiguration\r
+\r
+WFC = WM.WorkModel.WorkforceModuleConfiguration : SYSDYN.Configuration\r
+// Parameters\r
+WFC.TimeToAllocateResources : SYSDYN.Auxiliary\r
+      @L0.tag MOD.Mapped\r
+      SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.ParameterExpression\r
+                SYSDYN.Expression.equation "2"     \r
+WFC.Productivity : SYSDYN.Auxiliary\r
+      @L0.tag MOD.Mapped      \r
+      SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.ParameterExpression\r
+                SYSDYN.Expression.equation "1"       \r
+    \r
+// SYSDYN.Valve\r
+WFC.NetResources : SYSDYN.Valve\r
+      @L0.tag MOD.Mapped\r
+      SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "(WorkForceRequired-WorkforceStock)/TimeToAllocateResources"       \r
+\r
+// Stock\r
+WFC.WorkforceStock : SYSDYN.Stock\r
+      @L0.tag MOD.Mapped\r
+      SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.StockExpression\r
+                SYSDYN.StockExpression.initialEquation "0"         \r
+    \r
+// Auxiliaries    \r
+WFC.WorkForceRequired : SYSDYN.Auxiliary\r
+      @L0.tag MOD.Mapped\r
+      SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "RequiredWorkingSpeedInput/Productivity"      \r
+WFC.PossibleWorkingSpeed : SYSDYN.Auxiliary\r
+      @L0.tag MOD.Mapped\r
+      @L0.tag SYSDYN.IsOutput\r
+      SYSDYN.Variable.expressions _ : SYSDYN.Expressions\r
+        @L0.orderedSet\r
+            _ : SYSDYN.NormalExpression\r
+                SYSDYN.Expression.equation "WorkforceStock*Productivity"      \r
+                \r
+// Inputs\r
+WFC.RequiredWorkingSpeedInput : SYSDYN.Input\r
+      @L0.tag MOD.Mapped     \r
+      \r
+WFC.c21 : SYSDYN.Cloud\r
+      \r
+WFC.d21  : SYSDYN.Dependency\r
+      @WM.conf_dependency WFC.NetResources WFC.TimeToAllocateResources     \r
+WFC.d22  : SYSDYN.Dependency\r
+      @WM.conf_dependency WFC.NetResources WFC.WorkforceStock  \r
+WFC.d23  : SYSDYN.Dependency\r
+      @WM.conf_dependency WFC.NetResources WFC.WorkForceRequired  \r
+WFC.d24  : SYSDYN.Dependency\r
+      @WM.conf_dependency WFC.WorkForceRequired WFC.Productivity  \r
+WFC.d25  : SYSDYN.Dependency\r
+      @WM.conf_dependency WFC.WorkForceRequired WFC.RequiredWorkingSpeedInput   \r
+WFC.d26  : SYSDYN.Dependency\r
+      @WM.conf_dependency WFC.PossibleWorkingSpeed WFC.WorkforceStock  \r
+WFC.d27  : SYSDYN.Dependency\r
+      @WM.conf_dependency WFC.PossibleWorkingSpeed WFC.Productivity\r
+WFC.f21  : SYSDYN.Flow\r
+      @WM.conf_dependency WFC.WorkforceStock WFC.NetResources     \r
+WFC.f22  : SYSDYN.Flow\r
+      @WM.conf_dependency WFC.NetResources WFC.c21  \r
+   \r
+WorkforceModuleConfigurationDiagram : SYSDYN.ConfigurationDiagram <R L0.HasNext\r
+    MOD.DiagramToComposite WFC\r
+    DIA.HasLayer WM.Admin \r
+\r
+    L0X.HasTrigger _ : SYSDYN.DiagramToCompositeMapping\r
+  \r
+    @L0.orderedSet\r
+        TimeToAllocateResourcesElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WFC.TimeToAllocateResources\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 45.0, 75.0] : G2D.Transform   \r
+        ProductivityElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WFC.Productivity\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 120.0, 115.0] : G2D.Transform\r
+        NetResourcesElement : SYSDYN.ValveSymbol\r
+            MOD.ElementToComponent WFC.NetResources\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 60.0, 84.0] : G2D.Transform    \r
+        WorkforceStockElement : SYSDYN.StockSymbol\r
+            MOD.ElementToComponent WFC.WorkforceStock\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 93.0, 84.0] : G2D.Transform               \r
+        WorkForceRequiredElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WFC.WorkForceRequired\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 82.0, 117.0] : G2D.Transform\r
+        PossibleWorkingSpeedElement : SYSDYN.AuxiliarySymbol\r
+            MOD.ElementToComponent WFC.PossibleWorkingSpeed\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 115.0, 102.0] : G2D.Transform    \r
+        RequiredWorkingSpeedInputElement : SYSDYN.InputSymbol\r
+            MOD.ElementToComponent WFC.RequiredWorkingSpeedInput\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 45.0, 127.0] : G2D.Transform     \r
+        c21Element : SYSDYN.CloudSymbol\r
+            MOD.ElementToComponent WFC.c21\r
+            DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 45.0, 85.0] : G2D.Transform       \r
+        _ : SYSDYN.DependencyConnection\r
+          MOD.DiagramConnectionToConnection WFC.d21\r
+          @WM.dependency NetResourcesElement TimeToAllocateResourcesElement  -0.1\r
+        _ : SYSDYN.DependencyConnection\r
+          MOD.DiagramConnectionToConnection WFC.d22\r
+          @WM.dependency NetResourcesElement WorkforceStockElement  -0.1\r
+        _ : SYSDYN.DependencyConnection\r
+          MOD.DiagramConnectionToConnection WFC.d23\r
+          @WM.dependency NetResourcesElement WorkForceRequiredElement  -0.1\r
+        _ : SYSDYN.DependencyConnection\r
+          MOD.DiagramConnectionToConnection WFC.d24\r
+          @WM.dependency WorkForceRequiredElement ProductivityElement  -0.1\r
+        _ : SYSDYN.DependencyConnection\r
+          MOD.DiagramConnectionToConnection WFC.d25\r
+          @WM.dependency WorkForceRequiredElement RequiredWorkingSpeedInputElement  -0.1\r
+        _ : SYSDYN.DependencyConnection\r
+          MOD.DiagramConnectionToConnection WFC.d26\r
+          @WM.dependency PossibleWorkingSpeedElement WorkforceStockElement  -0.1\r
+        _ : SYSDYN.DependencyConnection\r
+          MOD.DiagramConnectionToConnection WFC.d27\r
+          @WM.dependency PossibleWorkingSpeedElement ProductivityElement  -0.1        \r
+        _ : SYSDYN.FlowConnection\r
+            MOD.DiagramConnectionToConnection WFC.f21\r
+            @WM.flow WorkforceStockElement NetResourcesElement               \r
+        _ : SYSDYN.FlowConnection\r
+            MOD.DiagramConnectionToConnection WFC.f22\r
+            @WM.flow c21Element NetResourcesElement        \r
+*/\r
diff --git a/1.8/org.simantics.sysdyn.ontology/graph/svg/loop.svg b/1.8/org.simantics.sysdyn.ontology/graph/svg/loop.svg
new file mode 100644 (file)
index 0000000..aaa11b1
--- /dev/null
@@ -0,0 +1,176 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   width="11.567822"
+   height="9.8627777"
+   id="svg1901"
+   sodipodi:version="0.32"
+   inkscape:version="0.48.4 r9939"
+   sodipodi:docname="loop.svg"
+   version="1.1">
+  <defs
+     id="defs1903">
+    <marker
+       inkscape:stockid="TriangleInL"
+       orient="auto"
+       refY="0"
+       refX="0"
+       id="TriangleInL"
+       style="overflow:visible">
+      <path
+         id="path4265"
+         d="m 5.77,0 -8.65,5 0,-10 8.65,5 z"
+         style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt"
+         transform="scale(-0.8,-0.8)"
+         inkscape:connector-curvature="0" />
+    </marker>
+    <marker
+       inkscape:stockid="Arrow2Lend"
+       orient="auto"
+       refY="0"
+       refX="0"
+       id="Arrow2Lend"
+       style="overflow:visible">
+      <path
+         id="path4153"
+         style="fill-rule:evenodd;stroke-width:0.625;stroke-linejoin:round"
+         d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
+         transform="matrix(-1.1,0,0,-1.1,-1.1,0)"
+         inkscape:connector-curvature="0" />
+    </marker>
+    <marker
+       inkscape:stockid="Arrow2Lstart"
+       orient="auto"
+       refY="0"
+       refX="0"
+       id="Arrow2Lstart"
+       style="overflow:visible">
+      <path
+         id="path4150"
+         style="fill-rule:evenodd;stroke-width:0.625;stroke-linejoin:round"
+         d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
+         transform="matrix(1.1,0,0,1.1,1.1,0)"
+         inkscape:connector-curvature="0" />
+    </marker>
+    <marker
+       inkscape:stockid="Arrow1Lstart"
+       orient="auto"
+       refY="0"
+       refX="0"
+       id="Arrow1Lstart"
+       style="overflow:visible">
+      <path
+         id="path4132"
+         d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
+         style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt"
+         transform="matrix(0.8,0,0,0.8,10,0)"
+         inkscape:connector-curvature="0" />
+    </marker>
+    <marker
+       inkscape:stockid="Arrow1Mstart"
+       orient="auto"
+       refY="0"
+       refX="0"
+       id="Arrow1Mstart"
+       style="overflow:visible">
+      <path
+         id="path4138"
+         d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
+         style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt"
+         transform="matrix(0.4,0,0,0.4,4,0)"
+         inkscape:connector-curvature="0" />
+    </marker>
+    <marker
+       inkscape:stockid="Arrow1Lend"
+       orient="auto"
+       refY="0"
+       refX="0"
+       id="Arrow1Lend"
+       style="overflow:visible">
+      <path
+         id="path4135"
+         d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
+         style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt"
+         transform="matrix(-0.8,0,0,-0.8,-10,0)"
+         inkscape:connector-curvature="0" />
+    </marker>
+  </defs>
+  <sodipodi:namedview
+     id="base"
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1.0"
+     inkscape:pageopacity="0.0"
+     inkscape:pageshadow="2"
+     inkscape:zoom="32"
+     inkscape:cx="-1.9642866"
+     inkscape:cy="-2.7672376"
+     inkscape:document-units="px"
+     inkscape:current-layer="layer1"
+     inkscape:window-width="1006"
+     inkscape:window-height="739"
+     inkscape:window-x="1428"
+     inkscape:window-y="52"
+     showgrid="false"
+     inkscape:window-maximized="0"
+     fit-margin-top="0"
+     fit-margin-left="0"
+     fit-margin-right="0"
+     fit-margin-bottom="0" />
+  <metadata
+     id="metadata1906">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+        <dc:title />
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <g
+     inkscape:label="Taso 1"
+     inkscape:groupmode="layer"
+     id="layer1"
+     transform="translate(-0.13537823,-1042.2366)">
+    <path
+       sodipodi:type="star"
+       style="fill:#000000;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       id="path2982"
+       sodipodi:sides="3"
+       sodipodi:cx="322.85715"
+       sodipodi:cy="309.50504"
+       sodipodi:r1="177.90733"
+       sodipodi:r2="88.953667"
+       sodipodi:arg1="2.9394727"
+       sodipodi:arg2="3.9866703"
+       inkscape:flatsided="true"
+       inkscape:rounded="0"
+       inkscape:randomized="0"
+       d="m 148.57144,345.21932 230.49908,-204.50728 61.85896,301.8717 z"
+       inkscape:transform-center-y="-0.37884722"
+       transform="matrix(0.00747689,-0.00472065,0.00249533,0.01414476,2.177026,1048.1856)" />
+    <path
+       sodipodi:type="arc"
+       style="fill:none;stroke:#000000;stroke-width:0.88339353;stroke-linecap:butt;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;marker-start:none;marker-mid:none;marker-end:none"
+       id="path2996"
+       sodipodi:cx="38.035713"
+       sodipodi:cy="1014.4158"
+       sodipodi:rx="21.785715"
+       sodipodi:ry="13.121153"
+       d="m 59.821428,1014.4158 a 21.785715,13.121153 0 1 1 -22.182754,-13.119"
+       transform="matrix(0.23486318,0,0,0.36599586,-8.614148,680.86439)"
+       sodipodi:start="0"
+       sodipodi:end="4.6941632"
+       sodipodi:open="true" />
+  </g>
+</svg>
diff --git a/1.8/org.simantics.sysdyn.ontology/mdl2pgraph.pl b/1.8/org.simantics.sysdyn.ontology/mdl2pgraph.pl
new file mode 100755 (executable)
index 0000000..b8e1a1c
--- /dev/null
@@ -0,0 +1,660 @@
+#!/usr/bin/perl
+#
+# Script for converting Vensim .mdl files into Simantics .pgraph files
+#
+
+use strict;
+use warnings;
+use Data::Dumper;
+
+die("Usage:\n\tparser.pl [filetoparse] [targetfile]") if($#ARGV < 1);
+
+sub trim($) {
+    my $string = shift;
+    $string =~ s/^\s+//;
+    $string =~ s/\s+$//;
+    return $string;
+}
+
+# Equation parser
+# See http://www.perlmonks.org/?node_id=678119
+
+my @token_def = (
+    [Whitespace => qr{\s+},      1],
+    [Comment    => qr{#.*\n?$}m, 1],
+    [AddOp      => qr{[+-]}     ],   
+    [MulOp      => qr{[*/]}     ],
+    [Number     => qr{(\d\.)+}      ],
+    [Equals     => qr{=}      ],
+    [Lt         => qr{<}      ],
+    [Gt         => qr{>}      ],
+    [OpenParen  => qr{\(}       ],
+    [CloseParen => qr{\)}       ],
+    [Comma       => qr{,}       ],
+    [If          => qr{IFTHENELSE}      ],
+    [Xls         => qr{GETXLSCONSTANTS} ],
+    [XlsData     => qr{GETXLSDATA} ],
+    [TimeShift   => qr{TIMESHIFT} ],
+    [VectorMap   => qr{VECTORELMMAP} ],
+    [Sum         => qr{SUM} ],
+    [Integ       => qr{INTEG} ],
+    [Str         => qr{'[^']+'}       ],
+    [Array       => qr{[0-9\w]+\[[^\]]+\]} ],
+    [Variable    => qr{[0-9\w]+}           ],
+);
+
+sub parseEquation($) {
+       my $input = shift;
+       my @tokens;
+       pos($input) = 0;
+
+       while(pos($input) < length $input){
+           my $matched = 0;
+           for my $t (@token_def){
+               my ($name, $re, $ignore_flag) = @$t;
+               if ($input =~ m/\G($re)/gc){
+                   $matched = 1;
+                   next if $ignore_flag;
+                   push @tokens, [$name, $1];
+                   next;
+               }
+           }
+            unless($matched) {
+              print "Syntax error at position " . pos($input).": $input\n";
+              return;
+            }
+       }
+       return token2str(\@tokens);
+}
+
+sub match {
+    my $tokens = shift;
+    my $expected_token = shift;
+    if ($tokens->[0][0] eq $expected_token){
+        my $current = shift @$tokens;
+        return $current->[1];
+    } else {
+        print "Syntax error: expected $expected_token, got $tokens->[0][0]\n";
+    }
+}
+
+sub lookahead {
+    my $tokens = shift;
+    my @expected = @_;
+    no warnings 'uninitialized';
+    for (0 .. $#expected){
+        return 0 if $tokens->[$_][0] ne $expected[$_];
+    }
+    return 1;
+}
+
+#
+# Parse vensim equations and convert to modelica equations
+# NOTE: This is not a bullet proof solution, but does parse correctly formed Vensim equations
+# FIXME: Find corresponding modelica version for the functions that are currently not transformed
+#
+sub token2str {
+    my $tokens = shift;
+    my $rval = "";
+
+    if (lookahead($tokens, 'Integ')){
+        # Stock.
+        match($tokens, 'Integ');
+        match($tokens, 'OpenParen');
+        my $a = token2str($tokens);
+        match($tokens, 'Comma');
+        my $b = token2str($tokens);
+        match($tokens, 'CloseParen');
+#      $rval = "INTEG($a, $b)";  # Integ function will be replaced with stock component, and it has only initial value ?
+        $rval = $b; # FIXME!
+    } elsif (lookahead($tokens, 'If')){
+        match($tokens, 'If');
+        match($tokens, 'OpenParen');
+        my $check = token2str($tokens);
+        match($tokens, 'Comma');
+        my $then = token2str($tokens);
+        match($tokens, 'Comma');
+        my $else = "";
+        if (lookahead($tokens, 'If')){
+            match($tokens, 'If');
+            match($tokens, 'OpenParen');
+            my $subcheck = token2str($tokens);
+            match($tokens, 'Comma');
+            my $subthen = token2str($tokens);
+            match($tokens, 'Comma');
+            my $subelse = token2str($tokens); # TODO doesn't support elseif yet..
+            match($tokens, 'CloseParen');
+            $else = "elseif $subcheck then $subthen else $subelse";
+        } else {
+            $else = "else ".token2str($tokens)."";
+        }
+        match($tokens, 'CloseParen');
+        $rval = "if $check then $then ".$else.""; # Apparently, end if is not used inside equations..
+    } elsif (lookahead($tokens, 'Xls')){
+        match($tokens, 'Xls');
+        match($tokens, 'OpenParen');
+        my $a = match($tokens, 'Str');
+        match($tokens, 'Comma');
+        my $b = match($tokens, 'Str');
+        match($tokens, 'Comma');
+        my $c = match($tokens, 'Str');
+        match($tokens, 'CloseParen');
+        $rval = "XLS_CONSTANT($a, $b, $c)";
+    } elsif (lookahead($tokens, 'XlsData')){
+        match($tokens, 'XlsData');
+        match($tokens, 'OpenParen');
+        my $a = match($tokens, 'Str');
+        match($tokens, 'Comma');
+        my $b = match($tokens, 'Str');
+        match($tokens, 'Comma');
+        my $c = match($tokens, 'Str');
+        match($tokens, 'Comma');
+        my $d = match($tokens, 'Str');
+        match($tokens, 'CloseParen');
+        $rval = "XLS_DATA($a, $b, $c, $d)";
+    } elsif (lookahead($tokens, 'VectorMap')){
+        match($tokens, 'VectorMap');
+        match($tokens, 'OpenParen');
+        my $a = token2str($tokens); # Should be a variable, but we can use token2str to parse it anyway
+        match($tokens, 'Comma');
+        my $b = token2str($tokens); # Should be a number, but we can use token2str to parse it anyway
+        match($tokens, 'CloseParen');
+        $rval = "VECTOR_MAP($a, $b)"; #  
+    } elsif (lookahead($tokens, 'TimeShift')){
+        match($tokens, 'TimeShift');
+        match($tokens, 'OpenParen');
+        my $var = token2str($tokens); # Should be a variable, but we can use token2str to parse it anyway
+        match($tokens, 'Comma');
+        my $num = token2str($tokens); # Should be a number, but we can use token2str to parse it anyway
+        match($tokens, 'CloseParen');
+        $rval = "delay($var, $num)"; # FIXME: Not sure if this is correct..
+    } elsif (lookahead($tokens, 'Sum')){
+        match($tokens, 'Sum');
+        match($tokens, 'OpenParen');
+        my $var = token2str($tokens); # Should be a variable, but we can use token2str to parse it anyway
+        match($tokens, 'CloseParen');
+        $rval = "sum($var)";
+    } elsif (lookahead($tokens, 'Array')){
+        my $var = match($tokens, 'Array');
+        $rval = $var;
+    } elsif (lookahead($tokens, 'Variable')){
+        my $var = match($tokens, 'Variable');
+        $rval = $var;
+    } elsif (lookahead($tokens, 'AddOp')){
+        my $op = match($tokens, 'AddOp');
+        $rval = $op;
+    } elsif (lookahead($tokens, 'MulOp')){
+        my $op = match($tokens, 'MulOp');
+        $rval = $op;
+    } elsif (lookahead($tokens, 'Number')){
+        my $n = match($tokens, 'Number');
+        $rval = $n;
+    } elsif (lookahead($tokens, 'Equals')){
+        my $n = match($tokens, 'Equals');
+        $rval = $n.$n; # In modelica we must use two times = (This should be used only in if statements..)
+    } elsif (lookahead($tokens, 'Lt')){
+        my $n = match($tokens, 'Lt');
+        $rval = $n;
+    } elsif (lookahead($tokens, 'Gt')){
+        my $n = match($tokens, 'Gt');
+        $rval = $n;
+    } elsif (lookahead($tokens, 'OpenParen')){
+        match($tokens, 'OpenParen');
+        my $inner = token2str($tokens);
+        match($tokens, 'CloseParen');
+        $rval = "($inner)";
+    } else {
+        return "";
+    }
+    my $next = token2str($tokens);
+    return $rval.$next;
+}
+
+# And finally the actual program
+
+my $sourcefile = $ARGV[0];
+my $targetfile = $ARGV[1];
+
+open(DAT, $sourcefile) || die("Could not open source file for reading!");
+my @raw_data=<DAT>;
+close(DAT);
+
+my $elements = {};
+
+# 1. Parse equations
+
+my $text = join("\n", @raw_data);
+while($text =~ m/(.*)(:=|=|:)([^~]*)~([^~]*)~([^\|]*)/mg) {
+       my $var      = trim($1);
+       my $op       = $2;
+       my $equation = trim($3);
+       my $unit     = trim($4);
+       my $comment  = trim($5); # May include also "~       :SUPPLEMENTARY"
+
+    $var =~ s/\[.*//g; # Remove the array part from the end ( foo[bar] => foo )
+
+       $equation =~ s/[\n\s\\]//g; # Remove white spaces, line breaks and backslashes (backslash seems to be used to break equation into two lines).
+    my $type = "";
+    # FIXME: No idea what is the exact difference of these:
+#    if($op =~ m/^:=$/) {
+#        $type = "VARIABLE";
+#    } elsif($op =~ m/^:$/) { 
+#        $type = "CONSTANT";
+#    } else {
+#        $type = "EQUATION";
+#    }
+    $type = "auxiliary";
+    if($equation =~ m/^\s*INTEG\(/) { # If equation is integral, the element type is stock.
+        $type = "stock";
+    }
+    # TODO: is there any way to detect valve? 
+    
+    # Convert equation to modelica format
+    my $modelica_equation = parseEquation($equation);
+    if($modelica_equation =~ m/^\+if/) {  # FIXME: Not sure why "+ IF THEN ELSE" is used in Vensim..
+        $modelica_equation =~ s/^\+//g;
+    }
+    $modelica_equation =~ s/\+-/-/g; # For some reason there is +- ... which means same as -
+       if($elements->{$var}) {
+        push(@{$elements->{$var}->{'equations'}}, $modelica_equation);
+    } else {
+        my @eq = ($modelica_equation);
+        $elements->{$var} = {name => $var,
+                                type => $type,
+                                equations => \@eq,
+                                unit => $unit,
+                                comment => $comment};
+    }
+}
+
+my $diagrams = {};
+my $connections = {};
+my $ghost_symbols = {};
+my $types = {};
+
+# 2. Parse diagram layout
+# i.e., the part after this:
+#  \\\---/// Sketch information - do not modify anything except names
+#  V300  Do not put anything below this section - it will be ignored
+#
+
+my $diagram;
+foreach my $row (@raw_data) {
+    # Lines starting with * indicates new diagram configuration..
+    if($row =~ m/^\*\w/) {
+        $diagram = trim($row);
+        $diagram =~ s/^(\*)//;
+    }
+    if($diagram) {
+        if($row =~ m/^1\d*,/) {
+           my @data = split(/,/, $row);
+            my $type = $data[0];
+            my $id   = $data[1];
+           if($type == 1) {
+                # Connection
+                # 1,6,1,5,1,0,0,0,0,64,0,-1--1--1,,1|(729,352)|
+                # 1,546,138,3,0,0,0,0,0,64,1,-1--1--1,,1|(-1642,-250)|   <- this connection is not visible in vensim?
+                       # Flow
+                       # 1,33,35,8,4,0,0,22,0,0,0,-1--1--1,,1|(456,528)|
+
+                my $target = $data[2];
+                my $source = $data[3];
+                my $foo    = $data[4]; # If this is 100, the flow direction must be changed (Yeah, wtf?)
+                my $t = $data[9] == 64 ? "dependency" : "flow";
+                my $hidden = $data[10] == 1 ? 1 : 0; # TODO: Not sure if this is correct
+                if($t eq "flow" && $foo == 100) {
+                    my $tmp = $target;
+                    $target = $source;
+                    $source = $tmp;
+                }
+
+                $connections->{$diagram} = {} unless($connections->{$diagram});
+                $connections->{$diagram}->{$id} = {source => $source, target => $target, type => $t, hidden => $hidden};
+           } elsif($type == 10) {
+                # Element
+                # 10,1,TotalPopulation,417,269,47,65,3,131,0,0,0,0,0,0      <- not sure, might be stock (but actually is auxiliary9
+                # 10,11,TotalPopulationT1,417,610,47,65,3,131,0,0,0,0,0,0   <- what is this?
+                # 10,274,LungCsIVNoD,-1050,1269,40,20,3,3,0,0,0,0,0,0       <- level aka stock?
+                # 10,2,LungCs01,-1109,-650,79,18,3,131,0,0,0,0,0,0          <- stock
+                # 10,786,LungCSmokersPercentageOfPopulation,-700,-835,147,21,8,131,0,0,0,0,0,0  <- input?
+                # 10,63,LungCProgress0102Rate,-1248,-541,91,9,8,3,0,0,0,0,0,0   <- aux ?
+                # 10,125,LungCModelPopCorrectionRate,1582,65,105,9,8,3,0,0,0,0,0,0 <- constant  (FIXME: seems to be identical with aux)
+                # 10,152,LungCTreated1PopCorr,287,269,102,9,40,3,1,0,-1,0,0,0   <- valve
+
+                my $name   = $data[2];
+                my $x      = $data[3];
+                my $y      = $data[4];
+                my $width  = $data[5];
+                my $height = $data[6];
+                my $foo    = $data[7];
+                my $bar    = $data[8]; # 131 for stock, 3 for aux
+                my $t      = "unknown"; #$data[11] == -1 ? "valve" : "stock"; # -1 for valve, 0 for stock ?
+                my $ghost  = 0;
+                if($#data > 15) { # Ghost symbols contains more parameters..
+                    # 10,505,LungCs01Diagnosis, -808,-633, 64,9,40,3,0,0,-1,0,0,0
+                    # 10,590,LungCs01Diagnosis, 2614,1033, 73,9,8, 2,0,3,-1,0,0,0,128-128-128,0-0-0,|12||128-128-128
+                    $ghost = 1;
+                }
+
+                       if($foo == 3 && $bar == 3) {
+                    $t = "stock";
+                } elsif($foo == 3 && $bar == 131) {
+                    $t = "auxiliary"; # FIXME:
+                } elsif($foo == 8 && $bar == 131) {
+                    $t = "auxiliary";
+                } elsif($foo == 40 && $bar == 3) {
+                    $t = "valve";
+                       } elsif($bar == 3) {
+                    $t = "auxiliary";
+                       } else {
+                    $t = "valve";
+                }
+                if(!$ghost) {
+                    $types->{$name} = $t;
+                }
+
+                $diagrams->{$diagram} = {} unless($diagrams->{$diagram});
+                $diagrams->{$diagram}->{$id} = {
+                                            id => $id,
+                                            name => $name,
+                                                               x => $x,
+                                                               y => $y,
+                                                               width => $width,
+                                                               height => $height,
+                                            type => $t,
+                                            ghost => $ghost
+                                           };
+                       if($t eq "valve" && $ghost_symbols->{$id}) {
+                   $diagrams->{$diagram}->{($ghost_symbols->{$id})} = $diagrams->{$diagram}->{$id};
+                       }
+           } elsif($type == 11) {
+                # Valve
+                # 11,48,48,-1348,-887,6,8,34,3,0,0,1,0,0,0
+                my $x = $data[3];
+                my $y = $data[4];
+
+                # This data is very much related to the valve symbol on the next line .. 
+                       $ghost_symbols->{$id+1} = $id;
+           } elsif($type == 12) {
+                # Textbox (can be ignored, the string is on the next line)
+                # 12,2,0,430,56,114,34,8,132,0,0,-1,0,0,0
+                # Cloud
+                # 12,45,48,-1553,-888,10,8,0,3,0,0,-1,0,0,0
+
+                my $x      = $data[3];
+                my $y      = $data[4];
+                my $foo    = $data[7];
+                my $bar    = $data[8]; # 132 for textbox, 3 for cloud
+                if($bar == 3) {
+                    $diagrams->{$diagram} = {} unless($diagrams->{$diagram});
+                    $diagrams->{$diagram}->{$id} = {
+                                            id => $id,
+                                            name => "Cloud".$id, # Cloud does not have name, but we can generate one
+                                            x => $x,
+                                            y => $y,
+                                            type => 'cloud',
+                                            ghost => 0};
+                    $types->{"Cloud".$id} = 'cloud';
+                }
+           }
+        } else {
+            # Comment or something...
+        }
+    }
+}
+
+# 3. Generate .pgraph file
+my $generated_elements = {};
+my $generated_symbols = {};
+
+# Create combined configuration
+my $output = "";
+foreach my $key (keys (%$diagrams)) {
+    my $d = $key;
+    $d =~ s/\s+//g;
+    my $WC = "CMC";
+
+    my $tmp = $diagrams->{$key};
+    foreach my $id (keys (%$tmp)) {
+        my $n = $tmp->{$id}->{'name'};
+        if($tmp->{$id}->{'ghost'} == 1) { # Ghost does not contain correct element type
+           next;
+       }
+       my $type = $tmp->{$id}->{'type'};
+        no warnings 'uninitialized';
+       $type = "stock" if($elements->{$n}->{'type'} eq "stock");
+
+       if($type eq "cloud") {
+           # Cloud is not a real element, thus it is not present in elements array..
+            $output .= $WC.".".$tmp->{$id}->{'name'}." : SYSDYN.Cloud\n";
+            $output .= "\n";
+        } elsif($elements->{$n} && $elements->{$n}->{'name'} && !$generated_elements->{$elements->{$n}->{'name'}}) {
+            if($type eq "valve") {
+                   $output .= $WC.".".$elements->{$n}->{'name'}." : SYSDYN.Valve\n";
+                   $output .= "    \@L0.tag MOD.Mapped\n";
+                   $output .= "    SYSDYN.HasExpressions _ : SYSDYN.Expressions\n";
+                   $output .= "        \@L0.orderedSet\n";
+                my $equations = $elements->{$n}->{'equations'};
+                foreach my $equation (@$equations) {
+                       $output .= "            _ : SYSDYN.NormalExpression\n";
+                       $output .= "                SYSDYN.HasEquation \"".$equation."\" \n";
+                }
+            } elsif($type eq "stock") {
+                   $output .= $WC.".".$elements->{$n}->{'name'}." : SYSDYN.Stock\n";
+                   $output .= "    \@L0.tag MOD.Mapped\n";
+                   $output .= "    SYSDYN.HasExpressions _ : SYSDYN.Expressions\n";
+                   $output .= "        \@L0.orderedSet\n";
+                my $equations = $elements->{$n}->{'equations'};
+                foreach my $equation (@$equations) {
+                       $output .= "            _ : SYSDYN.StockExpression\n";
+                       $output .= "                SYSDYN.HasInitialEquation \"".$equation."\" \n";
+                }
+                $output .= "\n";
+            } elsif($type eq "auxiliary") {
+                   $output .= $WC.".".$elements->{$n}->{'name'}." : SYSDYN.Auxiliary\n";
+                   $output .= "    \@L0.tag MOD.Mapped\n";
+                   $output .= "    SYSDYN.HasExpressions _ : SYSDYN.Expressions\n";
+                   $output .= "        \@L0.orderedSet\n";
+                my $equations = $elements->{$n}->{'equations'};
+                foreach my $equation (@$equations) {
+                       $output .= "            _ : SYSDYN.NormalExpression\n";
+                       $output .= "                SYSDYN.HasEquation \"".$equation."\" \n";
+                }
+                $output .= "\n";
+            } else {
+                print("Unknown element type: $type\n");
+            }
+        }
+        $generated_elements->{$elements->{$n}->{'name'}} = 1;
+    }
+
+    my $c = $connections->{$key};
+    foreach my $id (keys (%$c)) {
+       my $source = $tmp->{$c->{$id}->{'source'}}->{'name'};
+       my $target = $tmp->{$c->{$id}->{'target'}}->{'name'};
+        if($source && $target) {
+           if($c->{$id}->{'type'} eq "flow") {
+                       $output .= $WC.".f".$id."  : SYSDYN.Flow\n";
+                       $output .= "    \@WM.conf_dependency ".$WC.".".$source." ".$WC.".".$target."\n";
+           } elsif($c->{$id}->{'type'} eq "dependency") {
+                       $output .= $WC.".d".$id."  : SYSDYN.Dependency\n";
+                       $output .= "    \@WM.conf_dependency ".$WC.".".$source." ".$WC.".".$target."\n";
+           } else {
+               print("Unknown connection type ".$c->{$id}->{'type'}."\n");
+           }
+        } else {
+            print("WARNING: ");
+            print("No source element for connection #".$c->{$id}->{'source'}." -> $target\n") if($target);
+            print("No target element for connection $source -> #".$c->{$id}->{'target'}."\n") if($source);
+        }
+    }
+    $output .= "\n";
+}
+
+# Create combined diagram
+my $max_x = 0; # FIXME: Assumes that there are positive locations..
+foreach my $key (keys (%$diagrams)) {
+    my $d = $key;
+    $d =~ s/\s+//g;
+
+    my $WC = "CMC";
+    my $tmp = $diagrams->{$key};
+    unless($key eq "Population") {
+        $output .= $d."ConfigurationDiagram : SYSDYN.ConfigurationDiagram <R L0.HasNext\n";
+        $output .= "    MOD.DiagramToComposite ".$WC."\n";
+        $output .= "    DIA.HasLayer WM.Admin : DIA.Layer\n";
+        $output .= "        DIA.IsActive true\n";
+        $output .= "        DIA.HasFocusableTag TAGS.AdminIsFocusable <R DIA.IsFocusable\n";
+        $output .= "            \@L0.symmetric\n";
+        $output .= "        DIA.HasVisibleTag TAGS.AdminIsVisible <R DIA.IsVisible\n";
+        $output .= "            \@L0.symmetric\n";
+        $output .= "    L0.HasTrigger _ : SYSDYN.DiagramToCompositeMapping\n";
+        $output .= "    \@L0.orderedSet\n";
+    }
+    my $offset_x = $max_x;
+    no warnings 'uninitialized';
+    foreach my $id (keys (%$tmp)) {
+        my $n = $tmp->{$id}->{'name'};
+        my $suffix = "Element".$tmp->{$id}->{'id'};  # id field in hash might be different than $id (see parsing of type 11 and type 10 elements)
+
+        if(!$generated_symbols->{$n.$suffix}) {
+            my $x = sprintf("%.1f", $tmp->{$id}->{'x'} / 5 + $offset_x); # Scale
+            my $y = sprintf("%.1f", $tmp->{$id}->{'y'} / 5); # Scale
+            $max_x = $x if(($tmp->{$id}->{'x'} / 5 + $offset_x) > $max_x) ;
+            my $type = $types->{$n}; # Type lookup contains correct type (ghosts does not..)
+            $type = "stock" if($elements->{$n}->{'type'} eq "stock");
+
+            if($type eq "stock") {
+                $output .= "      ".$n.$suffix." : SYSDYN.StockSymbol\n";
+                $output .= "          MOD.ElementToComponent ".$WC.".$n\n";
+                $output .= "          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, ".$x.", ".$y."] : G2D.Transform\n";
+            } elsif($type eq "auxiliary") {
+                $output .= "      ".$n.$suffix." : SYSDYN.AuxiliarySymbol\n";
+                $output .= "          MOD.ElementToComponent ".$WC.".$n\n";
+                $output .= "          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, ".$x.", ".$y."] : G2D.Transform\n";
+            } elsif($type eq "valve") {
+                $output .= "      ".$n.$suffix." : SYSDYN.ValveSymbol\n";
+                $output .= "          MOD.ElementToComponent ".$WC.".$n\n";
+                $output .= "          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, ".$x.", ".$y."] : G2D.Transform\n";
+            } elsif($type eq "input") {
+                $output .= "      ".$n.$suffix." : SYSDYN.InputSymbol\n";
+                $output .= "          MOD.ElementToComponent ".$WC.".$n\n";
+                $output .= "          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, ".$x.", ".$y."] : G2D.Transform\n";
+            } elsif($type eq "cloud") {
+                $output .= "      ".$n.$suffix." : SYSDYN.CloudSymbol\n";
+                $output .= "          MOD.ElementToComponent ".$WC.".$n\n";
+                $output .= "          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, ".$x.", ".$y."] : G2D.Transform\n";
+            } else {
+                print("Unknown element type $type\n");
+            }
+        }
+        $generated_symbols->{$n.$suffix} = 1;
+    }
+
+    my $c = $connections->{$key};
+    foreach my $id (keys (%$c)) {
+        my $source = $tmp->{$c->{$id}->{'source'}}->{'name'};
+        my $target = $tmp->{$c->{$id}->{'target'}}->{'name'};
+        if($source && $target) {
+            my $source_suffix = "Element".$tmp->{$c->{$id}->{'source'}}->{'id'};
+            my $target_suffix = "Element".$tmp->{$c->{$id}->{'target'}}->{'id'};
+
+            if($c->{$id}->{'hidden'} == 0) {
+                if($c->{$id}->{'type'} eq "flow") {
+                           $output .= "      _ : SYSDYN.FlowConnection\n";
+                           $output .= "          MOD.DiagramConnectionToConnection ".$WC.".f".$id."\n";
+                           $output .= "          \@WM.flow ".$source.$source_suffix." ".$target.$target_suffix."\n";
+                } elsif($c->{$id}->{'type'} eq "dependency") {
+                           $output .= "      _ : SYSDYN.DependencyConnection\n";
+                           $output .= "          MOD.DiagramConnectionToConnection ".$WC.".d".$id."\n";
+                           $output .= "          \@WM.dependency ".$source.$source_suffix." ".$target.$target_suffix."   -0.1\n";
+                } else {
+                    print("Unknown element type ".$c->{$id}->{'type'}."\n");
+                }
+            }
+        }
+    }
+    $output .= "\n";
+}
+
+my $header = <<END;
+L0 = <http://www.simantics.org/Layer0-1.0>
+G2D = <http://www.simantics.org/G2D-1.0>
+STR = <http://www.simantics.org/Structural-1.0>
+DIA = <http://www.simantics.org/Diagram-2.1>
+SIMU = <http://www.simantics.org/Simulation-1.0>
+MOD = <http://www.simantics.org/Modeling-1.1>
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>
+PROJ = <http://www.simantics.org/Project-1.1>
+
+//######################################################################
+//# Example work model with two modules
+//######################################################################
+
+WM = <http://www.simantics.org/Sysdyn-1.1/DevelopmentProject> : PROJ.Project
+    PROJ.HasFeature _ : PROJ.FeatureSpec
+        PROJ.HasGroupId "org.simantics.sysdyn.feature.group"
+    L0.PartOf <http://Projects>
+
+TAGS = WM.Tags : L0.Library
+
+WM.dependency : L0.Template
+    \@template %type %head %tail %angle
+        %type 
+            \@L0.tag TAGS.AdminIsVisible
+            \@L0.tag TAGS.AdminIsFocusable
+            STR.HasConnectionType SYSDYN.SysdynConnectionType
+            SYSDYN.angle %angle 
+            DIA.HasArrowConnector _ : DIA.Connector
+                SYSDYN.HasHeadTerminal %head
+                DIA.AreConnected _ : DIA.Connector 
+                  SYSDYN.HasTailTerminal %tail
+                  DIA.IsPlainConnectorOf %type
+
+WM.flow : L0.Template
+    \@template %type %head %tail
+        %type 
+            \@L0.tag TAGS.AdminIsVisible
+            \@L0.tag TAGS.AdminIsFocusable
+            STR.HasConnectionType SYSDYN.SysdynConnectionType
+            DIA.HasArrowConnector _ : DIA.Connector
+                SYSDYN.HasHeadTerminal %head
+                DIA.AreConnected _ : DIA.Connector 
+                  SYSDYN.HasTailTerminal %tail
+                  DIA.IsPlainConnectorOf %type              
+
+WM.conf_dependency : L0.Template
+    \@template %type %head %tail
+        %type 
+            \@L0.tag MOD.Mapped
+            SYSDYN.HasHead %head
+            SYSDYN.HasTail %tail
+
+WM.conf_dependency_ref : L0.Template
+    \@template %type %head %tail %ref
+        %type 
+            \@L0.tag MOD.Mapped
+            SYSDYN.HasHead %head
+            SYSDYN.HasTail %tail
+            SYSDYN.RefersTo %ref                      
+
+WM.CancerModel : SYSDYN.SysdynModel
+    L0.HasLabel "Cancer Model"
+    SIMU.HasConfiguration CMC
+    SYSDYN.HasStartTime 0.0
+    SYSDYN.HasStopTime 24.0
+
+WM.CancerModel.Experiment : SYSDYN.Experiment
+    L0.HasLabel "Experiment"
+
+CMC = WM.CancerModel.CancerModelConfiguration : SYSDYN.Configuration
+  L0.HasLabel "CancerModelConfiguration"
+
+END
+
+open(OUTPUT, ">$targetfile") || die("Could not open target file for writing!");
+print OUTPUT $header;
+print OUTPUT $output;
+close(OUTPUT);
+
+print("Simantics graph configuration saved successfully to file $targetfile\n");
diff --git a/1.8/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java b/1.8/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java
new file mode 100644 (file)
index 0000000..ef6f571
--- /dev/null
@@ -0,0 +1,2401 @@
+package org.simantics.sysdyn;\r
+\r
+import org.simantics.db.RequestProcessor;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.service.QueryControl;\r
+\r
+public class SysdynResource {\r
+    \r
+    public final Resource AdditionalSymbols;\r
+    public final Resource AdditionalSymbols_MultilineText;\r
+    public final Resource AllElementsGroup;\r
+    public final Resource ArrayIndexes;\r
+    public final Resource ArrayIndexes_Inverse;\r
+    public final Resource Auxiliary;\r
+    public final Resource AuxiliarySymbol;\r
+    public final Resource AvailableSharedFunctionLibraries;\r
+    public final Resource AvailableVariableIndexes;\r
+    public final Resource BasicExperiment;\r
+    public final Resource Bottom;\r
+    public final Resource Browser;\r
+    public final Resource Built$in_Functions;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_array;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_array_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_array_A_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_array_A_B;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_array_A_C;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_array_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cat;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cat_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cat_A_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cat_A_B;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cat_A_C;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cat_k;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cat_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cross;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cross_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cross_x;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_cross_y;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_diagonal;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_diagonal_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_diagonal_v;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_fill;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_fill_n;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_fill_n_n1;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_fill_n_n2;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_fill_n_n3;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_fill_o;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_fill_s;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_identity;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_identity_n;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_identity_outArray;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_linspace;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_linspace_n;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_linspace_v;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_linspace_x1;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_linspace_x2;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_matrix;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_matrix_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_matrix_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_max;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_max_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_max_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_min;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_min_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_min_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ndims;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ndims_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ndims_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ones;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ones_n;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ones_n_n1;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ones_n_n2;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ones_n_n3;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_ones_o;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_product;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_product_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_product_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_scalar;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_scalar_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_scalar_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_size;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_size_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_size_i;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_size_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_skew;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_skew_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_skew_x;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_sum;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_sum_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_sum_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_transpose;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_transpose_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_transpose_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_vector;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_vector_A;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_vector_result;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_zeros;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_zeros_n;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_zeros_n_n1;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_zeros_n_n2;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_zeros_n_n3;\r
+    public final Resource Built$in_Functions_Modelica_Array_Functions_zeros_o;\r
+    public final Resource Built$in_Functions_Modelica_Functions;\r
+    public final Resource Built$in_Functions_Modelica_Functions_abs;\r
+    public final Resource Built$in_Functions_Modelica_Functions_abs_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_abs_v;\r
+    public final Resource Built$in_Functions_Modelica_Functions_acos;\r
+    public final Resource Built$in_Functions_Modelica_Functions_acos_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_acos_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_asin;\r
+    public final Resource Built$in_Functions_Modelica_Functions_asin_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_asin_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_atan;\r
+    public final Resource Built$in_Functions_Modelica_Functions_atan2;\r
+    public final Resource Built$in_Functions_Modelica_Functions_atan2_u1;\r
+    public final Resource Built$in_Functions_Modelica_Functions_atan2_u2;\r
+    public final Resource Built$in_Functions_Modelica_Functions_atan2_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_atan_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_atan_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_ceil;\r
+    public final Resource Built$in_Functions_Modelica_Functions_ceil_x;\r
+    public final Resource Built$in_Functions_Modelica_Functions_ceil_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_cos;\r
+    public final Resource Built$in_Functions_Modelica_Functions_cos_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_cos_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_cosh;\r
+    public final Resource Built$in_Functions_Modelica_Functions_cosh_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_cosh_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_delay;\r
+    public final Resource Built$in_Functions_Modelica_Functions_delay_delayMax;\r
+    public final Resource Built$in_Functions_Modelica_Functions_delay_delayTime;\r
+    public final Resource Built$in_Functions_Modelica_Functions_delay_expr;\r
+    public final Resource Built$in_Functions_Modelica_Functions_delay_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_der;\r
+    public final Resource Built$in_Functions_Modelica_Functions_der_dexpr;\r
+    public final Resource Built$in_Functions_Modelica_Functions_der_expr;\r
+    public final Resource Built$in_Functions_Modelica_Functions_div;\r
+    public final Resource Built$in_Functions_Modelica_Functions_div_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_div_x;\r
+    public final Resource Built$in_Functions_Modelica_Functions_div_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_edge;\r
+    public final Resource Built$in_Functions_Modelica_Functions_edge_b;\r
+    public final Resource Built$in_Functions_Modelica_Functions_edge_edgeEvent;\r
+    public final Resource Built$in_Functions_Modelica_Functions_exp;\r
+    public final Resource Built$in_Functions_Modelica_Functions_exp_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_exp_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_floor;\r
+    public final Resource Built$in_Functions_Modelica_Functions_floor_x;\r
+    public final Resource Built$in_Functions_Modelica_Functions_floor_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_initial;\r
+    public final Resource Built$in_Functions_Modelica_Functions_initial_isInitial;\r
+    public final Resource Built$in_Functions_Modelica_Functions_log;\r
+    public final Resource Built$in_Functions_Modelica_Functions_log10;\r
+    public final Resource Built$in_Functions_Modelica_Functions_log10_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_log10_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_log_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_log_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_max;\r
+    public final Resource Built$in_Functions_Modelica_Functions_max_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_max_x;\r
+    public final Resource Built$in_Functions_Modelica_Functions_max_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_min;\r
+    public final Resource Built$in_Functions_Modelica_Functions_min_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_min_x;\r
+    public final Resource Built$in_Functions_Modelica_Functions_min_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_mod;\r
+    public final Resource Built$in_Functions_Modelica_Functions_mod_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_mod_x;\r
+    public final Resource Built$in_Functions_Modelica_Functions_mod_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_noEvent;\r
+    public final Resource Built$in_Functions_Modelica_Functions_noEvent_expr;\r
+    public final Resource Built$in_Functions_Modelica_Functions_noEvent_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_pre;\r
+    public final Resource Built$in_Functions_Modelica_Functions_pre_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_pre_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_rem;\r
+    public final Resource Built$in_Functions_Modelica_Functions_rem_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_rem_x;\r
+    public final Resource Built$in_Functions_Modelica_Functions_rem_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sample;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sample_interval;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sample_isSample;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sample_start;\r
+    public final Resource Built$in_Functions_Modelica_Functions_semiLinear;\r
+    public final Resource Built$in_Functions_Modelica_Functions_semiLinear_negativeSlope;\r
+    public final Resource Built$in_Functions_Modelica_Functions_semiLinear_positiveSlope;\r
+    public final Resource Built$in_Functions_Modelica_Functions_semiLinear_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_semiLinear_x;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sign;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sign_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sign_v;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sin;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sin_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sin_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sinh;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sinh_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sinh_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_smooth;\r
+    public final Resource Built$in_Functions_Modelica_Functions_smooth_expr;\r
+    public final Resource Built$in_Functions_Modelica_Functions_smooth_p;\r
+    public final Resource Built$in_Functions_Modelica_Functions_smooth_result;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sqrt;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sqrt_v;\r
+    public final Resource Built$in_Functions_Modelica_Functions_sqrt_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_tan;\r
+    public final Resource Built$in_Functions_Modelica_Functions_tan_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_tan_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_tanh;\r
+    public final Resource Built$in_Functions_Modelica_Functions_tanh_u;\r
+    public final Resource Built$in_Functions_Modelica_Functions_tanh_y;\r
+    public final Resource Built$in_Functions_Modelica_Functions_terminal;\r
+    public final Resource Built$in_Functions_Modelica_Functions_terminal_isTerminal;\r
+    public final Resource Built$in_Functions_Vensim_Functions;\r
+    public final Resource Built$in_Functions_Vensim_Functions_ABS;\r
+    public final Resource Built$in_Functions_Vensim_Functions_ABS_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_ABS_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_COS;\r
+    public final Resource Built$in_Functions_Vensim_Functions_COSH;\r
+    public final Resource Built$in_Functions_Vensim_Functions_COSH_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_COSH_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_COS_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_COS_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_EXP;\r
+    public final Resource Built$in_Functions_Vensim_Functions_EXP_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_EXP_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_GAME;\r
+    public final Resource Built$in_Functions_Vensim_Functions_GAME_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_GAME_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_IFTHENELSE;\r
+    public final Resource Built$in_Functions_Vensim_Functions_IFTHENELSE_cond;\r
+    public final Resource Built$in_Functions_Vensim_Functions_IFTHENELSE_onfalse;\r
+    public final Resource Built$in_Functions_Vensim_Functions_IFTHENELSE_ontrue;\r
+    public final Resource Built$in_Functions_Vensim_Functions_IFTHENELSE_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_LN;\r
+    public final Resource Built$in_Functions_Vensim_Functions_LN_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_LN_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MAX;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MAX_a;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MAX_b;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MAX_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MIN;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MIN_a;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MIN_b;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MIN_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MODULO;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MODULO_a;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MODULO_b;\r
+    public final Resource Built$in_Functions_Vensim_Functions_MODULO_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_PULSE;\r
+    public final Resource Built$in_Functions_Vensim_Functions_PULSE_start;\r
+    public final Resource Built$in_Functions_Vensim_Functions_PULSE_width;\r
+    public final Resource Built$in_Functions_Vensim_Functions_PULSE_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_RAMP;\r
+    public final Resource Built$in_Functions_Vensim_Functions_RAMP_endTime;\r
+    public final Resource Built$in_Functions_Vensim_Functions_RAMP_slope;\r
+    public final Resource Built$in_Functions_Vensim_Functions_RAMP_startTime;\r
+    public final Resource Built$in_Functions_Vensim_Functions_RAMP_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SIN;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SINH;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SINH_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SINH_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SIN_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SIN_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SQRT;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SQRT_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_SQRT_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_STEP;\r
+    public final Resource Built$in_Functions_Vensim_Functions_STEP_height;\r
+    public final Resource Built$in_Functions_Vensim_Functions_STEP_stepTime;\r
+    public final Resource Built$in_Functions_Vensim_Functions_STEP_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_TAN;\r
+    public final Resource Built$in_Functions_Vensim_Functions_TANH;\r
+    public final Resource Built$in_Functions_Vensim_Functions_TANH_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_TANH_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_TAN_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_TAN_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_XIDZ;\r
+    public final Resource Built$in_Functions_Vensim_Functions_XIDZ_a;\r
+    public final Resource Built$in_Functions_Vensim_Functions_XIDZ_b;\r
+    public final Resource Built$in_Functions_Vensim_Functions_XIDZ_x;\r
+    public final Resource Built$in_Functions_Vensim_Functions_XIDZ_z;\r
+    public final Resource Built$in_Functions_Vensim_Functions_ZIDZ;\r
+    public final Resource Built$in_Functions_Vensim_Functions_ZIDZ_a;\r
+    public final Resource Built$in_Functions_Vensim_Functions_ZIDZ_b;\r
+    public final Resource Built$in_Functions_Vensim_Functions_ZIDZ_z;\r
+    public final Resource Built$in_Functions_interpolate;\r
+    public final Resource Built$in_Functions_interpolateFull;\r
+    public final Resource Built$in_Functions_interpolateFull_icol;\r
+    public final Resource Built$in_Functions_interpolateFull_table;\r
+    public final Resource Built$in_Functions_interpolateFull_u;\r
+    public final Resource Built$in_Functions_interpolateFull_y;\r
+    public final Resource Built$in_Functions_interpolate_table;\r
+    public final Resource Built$in_Functions_interpolate_u;\r
+    public final Resource Built$in_Functions_interpolate_y;\r
+    public final Resource Built$in_Functions_minmax;\r
+    public final Resource Built$in_Functions_minmax_expression;\r
+    public final Resource Built$in_Functions_minmax_maximum;\r
+    public final Resource Built$in_Functions_minmax_minimum;\r
+    public final Resource Built$in_Functions_minmax_result;\r
+    public final Resource Built$in_Functions_unitCast;\r
+    public final Resource Built$in_Functions_unitCast_u;\r
+    public final Resource Built$in_Functions_unitCast_y;\r
+    public final Resource Built$in_Functions_xidz;\r
+    public final Resource Built$in_Functions_xidz_divident;\r
+    public final Resource Built$in_Functions_xidz_divisor;\r
+    public final Resource Built$in_Functions_xidz_x;\r
+    public final Resource Built$in_Functions_xidz_z;\r
+    public final Resource Built$in_Functions_zidz;\r
+    public final Resource Built$in_Functions_zidz_divident;\r
+    public final Resource Built$in_Functions_zidz_divisor;\r
+    public final Resource Built$in_Functions_zidz_z;\r
+    public final Resource Center;\r
+    public final Resource Charts;\r
+    public final Resource Charts_SensitivityDataset;\r
+    public final Resource Charts_SensitivityDataset_ConfidenceBound;\r
+    public final Resource Charts_SensitivityDataset_ConfidenceBound_color;\r
+    public final Resource Charts_SensitivityDataset_ConfidenceBound_color_Inverse;\r
+    public final Resource Charts_SensitivityDataset_ConfidenceBound_percent;\r
+    public final Resource Charts_SensitivityDataset_ConfidenceBound_percent_Inverse;\r
+    public final Resource Charts_SensitivityDataset_confidenceBounds;\r
+    public final Resource Charts_SensitivityDataset_confidenceBounds_Inverse;\r
+    public final Resource Charts_SensitivityDataset_median;\r
+    public final Resource Charts_SensitivityDataset_median_Inverse;\r
+    public final Resource Charts_SensitivityPlot;\r
+    public final Resource Cloud;\r
+    public final Resource CloudSymbol;\r
+    public final Resource Component;\r
+    public final Resource Configuration;\r
+    public final Resource ConfigurationDiagram;\r
+    public final Resource ConfigurationDiagramTemplate;\r
+    public final Resource ConfigurationDiagram_selection;\r
+    public final Resource ConfigurationDiagram_selection_Inverse;\r
+    public final Resource ConstantExpression;\r
+    public final Resource DefaultFont;\r
+    public final Resource DefaultProfile;\r
+    public final Resource DefaultRealization;\r
+    public final Resource DelayExpression;\r
+    public final Resource DelayExpression_delayTime;\r
+    public final Resource DelayExpression_delayTime_Inverse;\r
+    public final Resource DelayExpression_expression;\r
+    public final Resource DelayExpression_expression_Inverse;\r
+    public final Resource DelayExpression_initialValue;\r
+    public final Resource DelayExpression_initialValue_Inverse;\r
+    public final Resource DelayExpression_isInformationDelay;\r
+    public final Resource DelayExpression_order;\r
+    public final Resource DelayExpression_order_Inverse;\r
+    public final Resource Dependency;\r
+    public final Resource DependencyConnection;\r
+    public final Resource DependencyConnection_delayMark;\r
+    public final Resource DependencyConnection_hideArrow;\r
+    public final Resource DependencyConnection_polarity;\r
+    public final Resource DependencyConnection_polarityLocation;\r
+    public final Resource DependencyConnection_polarityLocation_Inverse;\r
+    public final Resource DependencyConnection_polarity_Inverse;\r
+    public final Resource DependencyConnection_strokeWidth;\r
+    public final Resource DependencyConnection_strokeWidth_Inverse;\r
+    public final Resource Dependency_angle;\r
+    public final Resource Dependency_angle_Inverse;\r
+    public final Resource Dependency_refersTo;\r
+    public final Resource DiagramToCompositeMapping;\r
+    public final Resource Enumeration;\r
+    public final Resource EnumerationIndex;\r
+    public final Resource EnumerationIndex_showEnumerationIndexInCharts;\r
+    public final Resource EnumerationIndex_showEnumerationIndexInCharts_Inverse;\r
+    public final Resource EnumerationIndexes;\r
+    public final Resource EnumerationIndexes_Inverse;\r
+    public final Resource EnumerationReplacement;\r
+    public final Resource Enumeration_enumerationIndexList;\r
+    public final Resource Enumeration_enumerationIndexList_Inverse;\r
+    public final Resource Enumeration_enumerationIndexes;\r
+    public final Resource Enumeration_enumerationIndexes_Inverse;\r
+    public final Resource Enumeration_isReplaceable;\r
+    public final Resource Enumeration_isReplaceable_Inverse;\r
+    public final Resource Experiment;\r
+    public final Resource Experiment_Run;\r
+    public final Resource Experiment_Run_time;\r
+    public final Resource Experiment_Run_time_Inverse;\r
+    public final Resource Experiment_ic;\r
+    public final Resource Experiment_ic_Inverse;\r
+    public final Resource Experiment_result;\r
+    public final Resource Experiment_resultSet;\r
+    public final Resource Experiment_resultSet_Inverse;\r
+    public final Resource Experiment_result_Inverse;\r
+    public final Resource ExportModuleTree;\r
+    public final Resource Expression;\r
+    public final Resource Expression_arrayRange;\r
+    public final Resource Expression_arrayRange_Inverse;\r
+    public final Resource Expression_equation;\r
+    public final Resource Expression_equation_Inverse;\r
+    public final Resource Expressions;\r
+    public final Resource Expressions_Inverse;\r
+    public final Resource ExternalFiles;\r
+    public final Resource ExternalFunctionFile;\r
+    public final Resource ExternalFunctionFile_externalFile;\r
+    public final Resource ExternalFunctionFile_externalFile_Inverse;\r
+    public final Resource Flow;\r
+    public final Resource FlowConnection;\r
+    public final Resource FlowConnection_width;\r
+    public final Resource FlowConnection_width_Inverse;\r
+    public final Resource FunctionTree;\r
+    public final Resource Functions;\r
+    public final Resource Functions_equationPropertyValue;\r
+    public final Resource Functions_runChildren;\r
+    public final Resource Functions_runProperties;\r
+    public final Resource Functions_valuePropertyProperties;\r
+    public final Resource Functions_valuePropertyValue;\r
+    public final Resource GameExperiment;\r
+    public final Resource GameExperiment_stepDuration;\r
+    public final Resource GameExperiment_stepDuration_Inverse;\r
+    public final Resource GameExperiment_stepLength;\r
+    public final Resource GameExperiment_stepLength_Inverse;\r
+    public final Resource HaltonSequenceGenerator;\r
+    public final Resource HasEquationOrEmpty;\r
+    public final Resource HasEquationOrEmpty_Inverse;\r
+    public final Resource HasHeadTerminal;\r
+    public final Resource HasRangeEnd;\r
+    public final Resource HasRangeEnd_Inverse;\r
+    public final Resource HasRangeStart;\r
+    public final Resource HasRangeStart_Inverse;\r
+    public final Resource HasRangeStep;\r
+    public final Resource HasRangeStep_Inverse;\r
+    public final Resource HasTailTerminal;\r
+    public final Resource HistoryDataset;\r
+    public final Resource HistoryDataset_FoundVariableNameNode;\r
+    public final Resource HistoryDataset_HistoryDatasetVariablesBrowseContext;\r
+    public final Resource HistoryDataset_HistoryDatasetVariablesBrowseContext_StringNodeType;\r
+    public final Resource HistoryDataset_HistoryDatasetVariablesBrowseContext_VariableChildRule;\r
+    public final Resource HistoryDataset_HistoryDatasetVariablesBrowseContext_VariableLabelRule;\r
+    public final Resource HistoryDataset_columns;\r
+    public final Resource HistoryDataset_columns_Inverse;\r
+    public final Resource HistoryDataset_end;\r
+    public final Resource HistoryDataset_end_Inverse;\r
+    public final Resource HistoryDataset_sheet;\r
+    public final Resource HistoryDataset_start;\r
+    public final Resource HistoryDataset_start_Inverse;\r
+    public final Resource HistoryDataset_timeName;\r
+    public final Resource HistoryDataset_timeName_Inverse;\r
+    public final Resource HistoryRealization;\r
+    public final Resource Horizontal;\r
+    public final Resource ImportModuleTree;\r
+    public final Resource ImportedOntologies;\r
+    public final Resource IndependentVariable;\r
+    public final Resource IndependentVariable_activeExpression;\r
+    public final Resource IndependentVariable_isUninitialized;\r
+    public final Resource IndependentVariable_isUninitialized_Inverse;\r
+    public final Resource IndependentVariable_rangeEnd;\r
+    public final Resource IndependentVariable_rangeEnd_Inverse;\r
+    public final Resource IndependentVariable_rangeStart;\r
+    public final Resource IndependentVariable_rangeStart_Inverse;\r
+    public final Resource IndependentVariable_rangeStep;\r
+    public final Resource IndependentVariable_rangeStep_Inverse;\r
+    public final Resource IndependentVariable_unit;\r
+    public final Resource IndependentVariable_unit_Inverse;\r
+    public final Resource InitialCondition;\r
+    public final Resource InitialCondition_HasInitialValues;\r
+    public final Resource InitialCondition_HasInitialValues_Inverse;\r
+    public final Resource Input;\r
+    public final Resource InputSymbol;\r
+    public final Resource Input_defaultInputValue;\r
+    public final Resource Input_defaultInputValue_Inverse;\r
+    public final Resource Interval;\r
+    public final Resource Interval_maxValue;\r
+    public final Resource Interval_maxValue_Inverse;\r
+    public final Resource Interval_minValue;\r
+    public final Resource Interval_minValue_Inverse;\r
+    public final Resource IsHeadOfTerminal;\r
+    public final Resource IsOutput;\r
+    public final Resource IsTailOfTerminal;\r
+    public final Resource IssueStyle;\r
+    public final Resource Left;\r
+    public final Resource Location;\r
+    public final Resource LookupExpression;\r
+    public final Resource LookupExpression_lookup;\r
+    public final Resource LookupExpression_lookup_Inverse;\r
+    public final Resource Loop;\r
+    public final Resource LoopSymbol;\r
+    public final Resource LoopSymbol_Clockwise;\r
+    public final Resource LoopSymbol_Clockwise_Inverse;\r
+    public final Resource Loop_Comment;\r
+    public final Resource Loop_Comment_Inverse;\r
+    public final Resource Loop_Items;\r
+    public final Resource Loop_Items_Inverse;\r
+    public final Resource Migration;\r
+    public final Resource Migration_from1$6to1$7;\r
+    public final Resource Migration_from1$6to1$7_Custom;\r
+    public final Resource Migration_from1$6to1$7_Ontologies;\r
+    public final Resource Migration_from1$6to1$7_OrderedSetsToLists;\r
+    public final Resource Migration_from1$6to1$7_Spreadsheets;\r
+    public final Resource Migration_from1$6to1$7_SysdynChanges;\r
+    public final Resource Migration_fromFunctionLibrary1;\r
+    public final Resource Migration_fromModel1;\r
+    public final Resource Migration_fromModule1;\r
+    public final Resource ModelBrowser;\r
+    public final Resource ModelingActionContext;\r
+    public final Resource ModelingActionContext_Actions;\r
+    public final Resource ModelingActionContext_Actions_ChartDropAction;\r
+    public final Resource ModelingActionContext_Actions_FunctionDropAction;\r
+    public final Resource ModelingActionContext_Actions_NewBarChart;\r
+    public final Resource ModelingActionContext_Actions_NewEnumeration;\r
+    public final Resource ModelingActionContext_Actions_NewExperiment;\r
+    public final Resource ModelingActionContext_Actions_NewFunction;\r
+    public final Resource ModelingActionContext_Actions_NewFunctionLibrary;\r
+    public final Resource ModelingActionContext_Actions_NewHistoryData;\r
+    public final Resource ModelingActionContext_Actions_NewLineChart;\r
+    public final Resource ModelingActionContext_Actions_NewModuleType;\r
+    public final Resource ModelingActionContext_Actions_NewPieChart;\r
+    public final Resource ModelingActionContext_Actions_NewSharedFunctionLibrary;\r
+    public final Resource ModelingActionContext_Actions_NewSheet;\r
+    public final Resource ModelingActionContext_Actions_NewSimulationPlaybackExperiment;\r
+    public final Resource ModelingBrowseContext;\r
+    public final Resource ModelingBrowseContext_ActiveLabelDecorationRule;\r
+    public final Resource ModelingBrowseContext_BuiltinFunctions;\r
+    public final Resource ModelingBrowseContext_ChartImageRule;\r
+    public final Resource ModelingBrowseContext_ChartsFolder;\r
+    public final Resource ModelingBrowseContext_ExperimentsFolder;\r
+    public final Resource ModelingBrowseContext_FunctionsFolder;\r
+    public final Resource ModelingBrowseContext_ModuleContentChildRule;\r
+    public final Resource ModelingBrowseContext_ModuleSymbol;\r
+    public final Resource ModelingBrowseContext_ModuleSymbolNodeType;\r
+    public final Resource ModelingBrowseContext_ModuleTypeChildRule;\r
+    public final Resource ModelingBrowseContext_ModuleTypeLabelRule;\r
+    public final Resource ModelingBrowseContext_ModulesFolder;\r
+    public final Resource ModelingBrowseContext_ResultImageRule;\r
+    public final Resource ModelingBrowseContext_SharedFunctionsFolder;\r
+    public final Resource ModelingBrowseContext_Variable;\r
+    public final Resource ModelingBrowseContext_VariableChildRule;\r
+    public final Resource ModelingBrowseContext_VariableImageRule;\r
+    public final Resource ModelingBrowseContext_VariableNameLabelRule;\r
+    public final Resource ModelingBrowseContext_VariableNodeType;\r
+    public final Resource Module;\r
+    public final Resource ModuleSymbol;\r
+    public final Resource Module_ParameterOverride;\r
+    public final Resource Module_ParameterOverrideBrowseContext;\r
+    public final Resource Module_ParameterOverrideBrowseContext_Node;\r
+    public final Resource Module_ParameterOverrideBrowseContext_NodeType;\r
+    public final Resource Module_ParameterOverrideBrowseContext_ParameterChildRule;\r
+    public final Resource Module_ParameterOverrideBrowseContext_ParameterLabelDecorationRule;\r
+    public final Resource Module_ParameterOverrideBrowseContext_ParameterLabelRule;\r
+    public final Resource Module_ParameterOverrideBrowseContext_ParameterModifierRule;\r
+    public final Resource Module_ParameterOverrideBrowseContext_ParameterSorterRule;\r
+    public final Resource Module_ParameterOverride_overriddenParameter;\r
+    public final Resource Module_ParameterOverride_overrideExpression;\r
+    public final Resource Module_ParameterOverride_overrideExpression_Inverse;\r
+    public final Resource Module_parameterOverride;\r
+    public final Resource Module_parameterOverride_Inverse;\r
+    public final Resource Module_redeclaration;\r
+    public final Resource Module_redeclaration_Inverse;\r
+    public final Resource ModulesSearchFunction;\r
+    public final Resource NormalDistribution;\r
+    public final Resource NormalDistribution_maxValue;\r
+    public final Resource NormalDistribution_maxValue_Inverse;\r
+    public final Resource NormalDistribution_mean;\r
+    public final Resource NormalDistribution_mean_Inverse;\r
+    public final Resource NormalDistribution_minValue;\r
+    public final Resource NormalDistribution_minValue_Inverse;\r
+    public final Resource NormalDistribution_stdDeviation;\r
+    public final Resource NormalDistribution_stdDeviation_Inverse;\r
+    public final Resource NormalExpression;\r
+    public final Resource Orientation;\r
+    public final Resource ParameterExpression;\r
+    public final Resource PlaybackExperiment;\r
+    public final Resource ProbabilityDistribution;\r
+    public final Resource Profiles;\r
+    public final Resource Profiles_IssueWarnings;\r
+    public final Resource Profiles_ShadowVisualizations;\r
+    public final Resource Profiles_SimulationPlaybackColours;\r
+    public final Resource RandomGenerator;\r
+    public final Resource Redeclaration;\r
+    public final Resource Redeclaration_replacedEnumeration;\r
+    public final Resource Redeclaration_replacedEnumeration_Inverse;\r
+    public final Resource Redeclaration_replacingEnumeration;\r
+    public final Resource Redeclaration_replacingEnumeration_Inverse;\r
+    public final Resource Result;\r
+    public final Resource ResultSet;\r
+    public final Resource Result_parameterFile;\r
+    public final Resource Result_parameterFile_Inverse;\r
+    public final Resource Result_resultFile;\r
+    public final Resource Result_resultFile_Inverse;\r
+    public final Resource Result_showResult;\r
+    public final Resource Result_time;\r
+    public final Resource Result_time_Inverse;\r
+    public final Resource Right;\r
+    public final Resource SearchContribution;\r
+    public final Resource SelectedSharedFunctionLibraries;\r
+    public final Resource SensitivityAnalysisExperiment;\r
+    public final Resource SensitivityAnalysisExperiment_Parameter;\r
+    public final Resource SensitivityAnalysisExperiment_ParameterActionContext;\r
+    public final Resource SensitivityAnalysisExperiment_ParameterActionContext_Actions;\r
+    public final Resource SensitivityAnalysisExperiment_ParameterBrowseContext;\r
+    public final Resource SensitivityAnalysisExperiment_ParameterBrowseContext_ParameterChildRule;\r
+    public final Resource SensitivityAnalysisExperiment_ParameterBrowseContext_ParameterLabelRule;\r
+    public final Resource SensitivityAnalysisExperiment_Parameter_indexes;\r
+    public final Resource SensitivityAnalysisExperiment_Parameter_indexes_Inverse;\r
+    public final Resource SensitivityAnalysisExperiment_Parameter_propabilityDistribution;\r
+    public final Resource SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse;\r
+    public final Resource SensitivityAnalysisExperiment_Parameter_variable;\r
+    public final Resource SensitivityAnalysisExperiment_Parameter_variable_Inverse;\r
+    public final Resource SensitivityAnalysisExperiment_method;\r
+    public final Resource SensitivityAnalysisExperiment_method_Inverse;\r
+    public final Resource SensitivityAnalysisExperiment_numberOfValues;\r
+    public final Resource SensitivityAnalysisExperiment_numberOfValues_Inverse;\r
+    public final Resource SensitivityAnalysisExperiment_parameterList;\r
+    public final Resource SensitivityAnalysisExperiment_parameterList_Inverse;\r
+    public final Resource SensitivityAnalysisExperiment_randomSeed;\r
+    public final Resource SensitivityAnalysisExperiment_randomSeed_Inverse;\r
+    public final Resource SensitivityAnalysisExperiment_resultRefreshRate;\r
+    public final Resource SensitivityAnalysisExperiment_resultRefreshRate_Inverse;\r
+    public final Resource Shadow;\r
+    public final Resource ShadowStyle;\r
+    public final Resource ShadowSymbol;\r
+    public final Resource Shadow_original;\r
+    public final Resource Shadow_original_Inverse;\r
+    public final Resource SharedFunctionOntology;\r
+    public final Resource SharedModuleOntology;\r
+    public final Resource SimulateOnChangeExperiment;\r
+    public final Resource SimulationPlaybackProfile;\r
+    public final Resource SimulationPlaybackStyle;\r
+    public final Resource Stock;\r
+    public final Resource StockExpression;\r
+    public final Resource StockExpression_initialEquation;\r
+    public final Resource StockExpression_initialEquation_Inverse;\r
+    public final Resource StockExpression_integralEquation;\r
+    public final Resource StockExpression_integralEquation_Inverse;\r
+    public final Resource StockExpression_useCustomIntegral;\r
+    public final Resource StockSymbol;\r
+    public final Resource SymbolReferences;\r
+    public final Resource SymbolReferences_BasicSymbols;\r
+    public final Resource SymbolReferences_CommentSymbols;\r
+    public final Resource Symbols;\r
+    public final Resource SysdynConnectionType;\r
+    public final Resource SysdynDiagramModelingRules;\r
+    public final Resource SysdynModel;\r
+    public final Resource SysdynModel_fmuFile;\r
+    public final Resource SysdynModel_fmuFile_Inverse;\r
+    public final Resource SysdynModel_lastExportFileName;\r
+    public final Resource SysdynModel_lastExportFileName_Inverse;\r
+    public final Resource SysdynModel_lastExportFilePath;\r
+    public final Resource SysdynModel_lastExportFilePath_Inverse;\r
+    public final Resource SysdynModel_outputInterval;\r
+    public final Resource SysdynModel_outputInterval_Inverse;\r
+    public final Resource SysdynModel_simulationStepLength;\r
+    public final Resource SysdynModel_simulationStepLength_Inverse;\r
+    public final Resource SysdynModel_solver;\r
+    public final Resource SysdynModel_solver_Inverse;\r
+    public final Resource SysdynModel_startTime;\r
+    public final Resource SysdynModel_startTime_Inverse;\r
+    public final Resource SysdynModel_stopTime;\r
+    public final Resource SysdynModel_stopTime_Inverse;\r
+    public final Resource SysdynModel_timeUnit;\r
+    public final Resource SysdynModel_timeUnit_Inverse;\r
+    public final Resource SysdynModel_tolerance;\r
+    public final Resource SysdynModel_tolerance_Inverse;\r
+    public final Resource SysdynModel_variableFilter;\r
+    public final Resource SysdynModel_variableFilter_Inverse;\r
+    public final Resource SysdynModelicaFunction;\r
+    public final Resource SysdynModelicaFunctionLibrary;\r
+    public final Resource SysdynModelicaFunction_Input;\r
+    public final Resource SysdynModelicaFunction_InterfaceVariable;\r
+    public final Resource SysdynModelicaFunction_Output;\r
+    public final Resource SysdynModelicaFunction_VariableLengthInput;\r
+    public final Resource SysdynModelicaFunction_VariableLengthInput_shownLabels;\r
+    public final Resource SysdynModelicaFunction_VariableLengthInput_shownLabels_Inverse;\r
+    public final Resource SysdynModelicaFunction_definition;\r
+    public final Resource SysdynModelicaFunction_definition_Inverse;\r
+    public final Resource SysdynModelicaFunction_inputs;\r
+    public final Resource SysdynModelicaFunction_inputs_Inverse;\r
+    public final Resource SysdynModelicaFunction_modelicaFunctionCode;\r
+    public final Resource SysdynModelicaFunction_modelicaFunctionCode_Inverse;\r
+    public final Resource SysdynModelicaFunction_modelicaFunctionInterface;\r
+    public final Resource SysdynModelicaFunction_modelicaFunctionInterface_Inverse;\r
+    public final Resource SysdynModelicaFunction_optional;\r
+    public final Resource SysdynModelicaFunction_optional_Inverse;\r
+    public final Resource SysdynModelicaFunction_outputs;\r
+    public final Resource SysdynModelicaFunction_outputs_Inverse;\r
+    public final Resource SysdynModelicaFunction_unit;\r
+    public final Resource SysdynModelicaFunction_unit_Inverse;\r
+    public final Resource SysdynModuleLibrary;\r
+    public final Resource SysdynOperationBrowser;\r
+    public final Resource SysdynSymbol;\r
+    public final Resource SysdynTerminal;\r
+    public final Resource Top;\r
+    public final Resource UniformDistribution;\r
+    public final Resource UniformDistribution_maxValue;\r
+    public final Resource UniformDistribution_maxValue_Inverse;\r
+    public final Resource UniformDistribution_minValue;\r
+    public final Resource UniformDistribution_minValue_Inverse;\r
+    public final Resource UsedVariableIndexes;\r
+    public final Resource Validations;\r
+    public final Resource Validations_Dependencies;\r
+    public final Resource Validations_Dependencies_DependencyConnectionsIssueSource;\r
+    public final Resource Validations_Dependencies_MissingDependencyConnectionsIssueSource;\r
+    public final Resource Validations_Dependencies_dependencyValidator;\r
+    public final Resource Validations_Dependencies_invalidSheetReferenceIssueDescription;\r
+    public final Resource Validations_Dependencies_missingDependencyValidator;\r
+    public final Resource Validations_Dependencies_missingLinkIssueDescription;\r
+    public final Resource Validations_Dependencies_noSuchVariableIssueDescription;\r
+    public final Resource Validations_Dependencies_rangeIssueDescription;\r
+    public final Resource Validations_Dependencies_rangeWarningDescription;\r
+    public final Resource Validations_Dependencies_unusedDependencyIssueDescription;\r
+    public final Resource Validations_DependencyConstraint;\r
+    public final Resource Validations_EmptyEnumerationIssue;\r
+    public final Resource Validations_EnumerationConstraint;\r
+    public final Resource Validations_Enumerations;\r
+    public final Resource Validations_Enumerations_EnumerationIssueSource;\r
+    public final Resource Validations_Enumerations_emptyEnumerationIssueDescription;\r
+    public final Resource Validations_Enumerations_enumerationIndexValidator;\r
+    public final Resource Validations_ExpressionConstraint;\r
+    public final Resource Validations_ExpressionIssue;\r
+    public final Resource Validations_Expressions;\r
+    public final Resource Validations_Expressions_ExpressionIssueSource;\r
+    public final Resource Validations_Expressions_expressionIssueDescription;\r
+    public final Resource Validations_Expressions_expressionValidator;\r
+    public final Resource Validations_Functions;\r
+    public final Resource Validations_Functions_baseRealizationFunction;\r
+    public final Resource Validations_Functions_path;\r
+    public final Resource Validations_InvalidSheetReferenceIssue;\r
+    public final Resource Validations_Issue;\r
+    public final Resource Validations_Issue_stringContexts;\r
+    public final Resource Validations_Issue_stringContexts_Inverse;\r
+    public final Resource Validations_MissingDependencyConstraint;\r
+    public final Resource Validations_MissingLinkIssue;\r
+    public final Resource Validations_ModuleInputUnitWarning;\r
+    public final Resource Validations_ModuleOutputUnitWarning;\r
+    public final Resource Validations_NoSuchVariableIssue;\r
+    public final Resource Validations_RangeIssue;\r
+    public final Resource Validations_RangeWarning;\r
+    public final Resource Validations_UnitConstraint;\r
+    public final Resource Validations_UnitWarning;\r
+    public final Resource Validations_Units;\r
+    public final Resource Validations_Units_UnitIssueSource;\r
+    public final Resource Validations_Units_UnitIssueSource_allowEquivalents;\r
+    public final Resource Validations_Units_UnitIssueSource_allowEquivalents_Inverse;\r
+    public final Resource Validations_Units_moduleInputUnitWarningDescription;\r
+    public final Resource Validations_Units_moduleInterfaceExtension;\r
+    public final Resource Validations_Units_moduleOutputUnitWarningDescription;\r
+    public final Resource Validations_Units_unitValidator;\r
+    public final Resource Validations_Units_unitWarningDescription;\r
+    public final Resource Validations_UnusedDependencyIssue;\r
+    public final Resource Validations_constraint;\r
+    public final Resource Validations_issue;\r
+    public final Resource Validations_listeningConstraint;\r
+    public final Resource ValueGeneratorMethod;\r
+    public final Resource Valve;\r
+    public final Resource ValveSymbol;\r
+    public final Resource ValveSymbol_orientation;\r
+    public final Resource ValveSymbol_textLocation;\r
+    public final Resource Variable;\r
+    public final Resource Variable_HasHead;\r
+    public final Resource Variable_HasTail;\r
+    public final Resource Variable_activeDatasets;\r
+    public final Resource Variable_activeDatasets_Inverse;\r
+    public final Resource Variable_arrayIndexes;\r
+    public final Resource Variable_arrayIndexesList;\r
+    public final Resource Variable_arrayIndexesList_Inverse;\r
+    public final Resource Variable_arrayIndexes_Inverse;\r
+    public final Resource Variable_equation;\r
+    public final Resource Variable_equation_Inverse;\r
+    public final Resource Variable_expressionList;\r
+    public final Resource Variable_expressionList_Inverse;\r
+    public final Resource Variable_expressions;\r
+    public final Resource Variable_expressions_Inverse;\r
+    public final Resource Variable_isHeadOf;\r
+    public final Resource Variable_isTailOf;\r
+    public final Resource Variable_names;\r
+    public final Resource Variable_names_Inverse;\r
+    public final Resource Variable_time;\r
+    public final Resource Variable_time_Inverse;\r
+    public final Resource Variable_times;\r
+    public final Resource Variable_times_Inverse;\r
+    public final Resource Variable_type;\r
+    public final Resource Variable_type_Inverse;\r
+    public final Resource Variable_unit;\r
+    public final Resource Variable_unit_Inverse;\r
+    public final Resource Variable_value;\r
+    public final Resource Variable_value_Inverse;\r
+    public final Resource Variable_values;\r
+    public final Resource Variable_values_Inverse;\r
+    public final Resource Variable_variability;\r
+    public final Resource Variable_variability_Inverse;\r
+    public final Resource Vertical;\r
+    public final Resource WithLookupExpression;\r
+    public final Resource WithLookupExpression_expression;\r
+    public final Resource WithLookupExpression_expression_Inverse;\r
+    public final Resource WithLookupExpression_lookup;\r
+    public final Resource WithLookupExpression_lookup_Inverse;\r
+    public final Resource WithLookupExpression_maxX;\r
+    public final Resource WithLookupExpression_maxY;\r
+    public final Resource WithLookupExpression_minX;\r
+    public final Resource WithLookupExpression_minY;\r
+        \r
+    public static class URIs {\r
+        public static final String AdditionalSymbols = "http://www.simantics.org/Sysdyn-1.1/AdditionalSymbols";\r
+        public static final String AdditionalSymbols_MultilineText = "http://www.simantics.org/Sysdyn-1.1/AdditionalSymbols/MultilineText";\r
+        public static final String AllElementsGroup = "http://www.simantics.org/Sysdyn-1.1/AllElementsGroup";\r
+        public static final String ArrayIndexes = "http://www.simantics.org/Sysdyn-1.1/ArrayIndexes";\r
+        public static final String ArrayIndexes_Inverse = "http://www.simantics.org/Sysdyn-1.1/ArrayIndexes/Inverse";\r
+        public static final String Auxiliary = "http://www.simantics.org/Sysdyn-1.1/Auxiliary";\r
+        public static final String AuxiliarySymbol = "http://www.simantics.org/Sysdyn-1.1/AuxiliarySymbol";\r
+        public static final String AvailableSharedFunctionLibraries = "http://www.simantics.org/Sysdyn-1.1/AvailableSharedFunctionLibraries";\r
+        public static final String AvailableVariableIndexes = "http://www.simantics.org/Sysdyn-1.1/AvailableVariableIndexes";\r
+        public static final String BasicExperiment = "http://www.simantics.org/Sysdyn-1.1/BasicExperiment";\r
+        public static final String Bottom = "http://www.simantics.org/Sysdyn-1.1/Bottom";\r
+        public static final String Browser = "http://www.simantics.org/Sysdyn-1.1/Browser";\r
+        public static final String Built$in_Functions = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_array = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/array";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_array_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/array/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_array_A_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/array/A/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_array_A_B = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/array/A/B";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_array_A_C = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/array/A/C";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_array_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/array/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cat = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cat";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cat_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cat/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cat_A_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cat/A/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cat_A_B = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cat/A/B";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cat_A_C = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cat/A/C";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cat_k = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cat/k";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cat_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cat/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cross = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cross";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cross_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cross/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cross_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cross/x";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_cross_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/cross/y";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_diagonal = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/diagonal";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_diagonal_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/diagonal/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_diagonal_v = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/diagonal/v";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_fill = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/fill";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_fill_n = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/fill/n";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_fill_n_n1 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/fill/n/n1";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_fill_n_n2 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/fill/n/n2";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_fill_n_n3 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/fill/n/n3";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_fill_o = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/fill/o";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_fill_s = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/fill/s";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_identity = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/identity";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_identity_n = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/identity/n";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_identity_outArray = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/identity/outArray";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_linspace = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/linspace";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_linspace_n = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/linspace/n";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_linspace_v = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/linspace/v";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_linspace_x1 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/linspace/x1";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_linspace_x2 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/linspace/x2";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_matrix = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/matrix";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_matrix_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/matrix/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_matrix_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/matrix/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_max = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/max";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_max_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/max/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_max_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/max/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_min = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/min";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_min_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/min/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_min_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/min/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ndims = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ndims";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ndims_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ndims/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ndims_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ndims/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ones = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ones";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ones_n = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ones/n";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ones_n_n1 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ones/n/n1";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ones_n_n2 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ones/n/n2";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ones_n_n3 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ones/n/n3";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_ones_o = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/ones/o";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_product = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/product";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_product_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/product/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_product_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/product/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_scalar = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/scalar";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_scalar_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/scalar/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_scalar_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/scalar/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_size = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/size";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_size_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/size/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_size_i = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/size/i";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_size_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/size/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_skew = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/skew";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_skew_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/skew/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_skew_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/skew/x";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_sum = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/sum";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_sum_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/sum/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_sum_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/sum/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_transpose = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/transpose";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_transpose_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/transpose/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_transpose_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/transpose/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_vector = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/vector";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_vector_A = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/vector/A";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_vector_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/vector/result";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_zeros = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/zeros";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_zeros_n = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/zeros/n";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_zeros_n_n1 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/zeros/n/n1";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_zeros_n_n2 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/zeros/n/n2";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_zeros_n_n3 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/zeros/n/n3";\r
+        public static final String Built$in_Functions_Modelica_Array_Functions_zeros_o = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Array%20Functions/zeros/o";\r
+        public static final String Built$in_Functions_Modelica_Functions = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions";\r
+        public static final String Built$in_Functions_Modelica_Functions_abs = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/abs";\r
+        public static final String Built$in_Functions_Modelica_Functions_abs_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/abs/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_abs_v = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/abs/v";\r
+        public static final String Built$in_Functions_Modelica_Functions_acos = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/acos";\r
+        public static final String Built$in_Functions_Modelica_Functions_acos_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/acos/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_acos_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/acos/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_asin = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/asin";\r
+        public static final String Built$in_Functions_Modelica_Functions_asin_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/asin/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_asin_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/asin/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_atan = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/atan";\r
+        public static final String Built$in_Functions_Modelica_Functions_atan2 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/atan2";\r
+        public static final String Built$in_Functions_Modelica_Functions_atan2_u1 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/atan2/u1";\r
+        public static final String Built$in_Functions_Modelica_Functions_atan2_u2 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/atan2/u2";\r
+        public static final String Built$in_Functions_Modelica_Functions_atan2_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/atan2/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_atan_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/atan/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_atan_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/atan/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_ceil = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/ceil";\r
+        public static final String Built$in_Functions_Modelica_Functions_ceil_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/ceil/x";\r
+        public static final String Built$in_Functions_Modelica_Functions_ceil_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/ceil/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_cos = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/cos";\r
+        public static final String Built$in_Functions_Modelica_Functions_cos_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/cos/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_cos_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/cos/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_cosh = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/cosh";\r
+        public static final String Built$in_Functions_Modelica_Functions_cosh_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/cosh/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_cosh_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/cosh/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_delay = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/delay";\r
+        public static final String Built$in_Functions_Modelica_Functions_delay_delayMax = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/delay/delayMax";\r
+        public static final String Built$in_Functions_Modelica_Functions_delay_delayTime = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/delay/delayTime";\r
+        public static final String Built$in_Functions_Modelica_Functions_delay_expr = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/delay/expr";\r
+        public static final String Built$in_Functions_Modelica_Functions_delay_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/delay/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_der = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/der";\r
+        public static final String Built$in_Functions_Modelica_Functions_der_dexpr = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/der/dexpr";\r
+        public static final String Built$in_Functions_Modelica_Functions_der_expr = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/der/expr";\r
+        public static final String Built$in_Functions_Modelica_Functions_div = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/div";\r
+        public static final String Built$in_Functions_Modelica_Functions_div_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/div/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_div_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/div/x";\r
+        public static final String Built$in_Functions_Modelica_Functions_div_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/div/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_edge = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/edge";\r
+        public static final String Built$in_Functions_Modelica_Functions_edge_b = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/edge/b";\r
+        public static final String Built$in_Functions_Modelica_Functions_edge_edgeEvent = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/edge/edgeEvent";\r
+        public static final String Built$in_Functions_Modelica_Functions_exp = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/exp";\r
+        public static final String Built$in_Functions_Modelica_Functions_exp_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/exp/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_exp_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/exp/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_floor = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/floor";\r
+        public static final String Built$in_Functions_Modelica_Functions_floor_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/floor/x";\r
+        public static final String Built$in_Functions_Modelica_Functions_floor_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/floor/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_initial = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/initial";\r
+        public static final String Built$in_Functions_Modelica_Functions_initial_isInitial = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/initial/isInitial";\r
+        public static final String Built$in_Functions_Modelica_Functions_log = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/log";\r
+        public static final String Built$in_Functions_Modelica_Functions_log10 = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/log10";\r
+        public static final String Built$in_Functions_Modelica_Functions_log10_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/log10/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_log10_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/log10/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_log_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/log/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_log_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/log/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_max = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/max";\r
+        public static final String Built$in_Functions_Modelica_Functions_max_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/max/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_max_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/max/x";\r
+        public static final String Built$in_Functions_Modelica_Functions_max_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/max/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_min = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/min";\r
+        public static final String Built$in_Functions_Modelica_Functions_min_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/min/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_min_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/min/x";\r
+        public static final String Built$in_Functions_Modelica_Functions_min_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/min/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_mod = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/mod";\r
+        public static final String Built$in_Functions_Modelica_Functions_mod_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/mod/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_mod_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/mod/x";\r
+        public static final String Built$in_Functions_Modelica_Functions_mod_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/mod/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_noEvent = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/noEvent";\r
+        public static final String Built$in_Functions_Modelica_Functions_noEvent_expr = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/noEvent/expr";\r
+        public static final String Built$in_Functions_Modelica_Functions_noEvent_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/noEvent/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_pre = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/pre";\r
+        public static final String Built$in_Functions_Modelica_Functions_pre_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/pre/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_pre_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/pre/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_rem = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/rem";\r
+        public static final String Built$in_Functions_Modelica_Functions_rem_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/rem/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_rem_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/rem/x";\r
+        public static final String Built$in_Functions_Modelica_Functions_rem_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/rem/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_sample = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sample";\r
+        public static final String Built$in_Functions_Modelica_Functions_sample_interval = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sample/interval";\r
+        public static final String Built$in_Functions_Modelica_Functions_sample_isSample = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sample/isSample";\r
+        public static final String Built$in_Functions_Modelica_Functions_sample_start = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sample/start";\r
+        public static final String Built$in_Functions_Modelica_Functions_semiLinear = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/semiLinear";\r
+        public static final String Built$in_Functions_Modelica_Functions_semiLinear_negativeSlope = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/semiLinear/negativeSlope";\r
+        public static final String Built$in_Functions_Modelica_Functions_semiLinear_positiveSlope = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/semiLinear/positiveSlope";\r
+        public static final String Built$in_Functions_Modelica_Functions_semiLinear_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/semiLinear/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_semiLinear_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/semiLinear/x";\r
+        public static final String Built$in_Functions_Modelica_Functions_sign = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sign";\r
+        public static final String Built$in_Functions_Modelica_Functions_sign_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sign/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_sign_v = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sign/v";\r
+        public static final String Built$in_Functions_Modelica_Functions_sin = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sin";\r
+        public static final String Built$in_Functions_Modelica_Functions_sin_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sin/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_sin_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sin/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_sinh = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sinh";\r
+        public static final String Built$in_Functions_Modelica_Functions_sinh_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sinh/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_sinh_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sinh/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_smooth = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/smooth";\r
+        public static final String Built$in_Functions_Modelica_Functions_smooth_expr = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/smooth/expr";\r
+        public static final String Built$in_Functions_Modelica_Functions_smooth_p = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/smooth/p";\r
+        public static final String Built$in_Functions_Modelica_Functions_smooth_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/smooth/result";\r
+        public static final String Built$in_Functions_Modelica_Functions_sqrt = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sqrt";\r
+        public static final String Built$in_Functions_Modelica_Functions_sqrt_v = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sqrt/v";\r
+        public static final String Built$in_Functions_Modelica_Functions_sqrt_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/sqrt/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_tan = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/tan";\r
+        public static final String Built$in_Functions_Modelica_Functions_tan_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/tan/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_tan_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/tan/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_tanh = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/tanh";\r
+        public static final String Built$in_Functions_Modelica_Functions_tanh_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/tanh/u";\r
+        public static final String Built$in_Functions_Modelica_Functions_tanh_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/tanh/y";\r
+        public static final String Built$in_Functions_Modelica_Functions_terminal = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/terminal";\r
+        public static final String Built$in_Functions_Modelica_Functions_terminal_isTerminal = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Modelica%20Functions/terminal/isTerminal";\r
+        public static final String Built$in_Functions_Vensim_Functions = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions";\r
+        public static final String Built$in_Functions_Vensim_Functions_ABS = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ABS";\r
+        public static final String Built$in_Functions_Vensim_Functions_ABS_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ABS/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_ABS_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ABS/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_COS = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/COS";\r
+        public static final String Built$in_Functions_Vensim_Functions_COSH = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/COSH";\r
+        public static final String Built$in_Functions_Vensim_Functions_COSH_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/COSH/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_COSH_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/COSH/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_COS_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/COS/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_COS_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/COS/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_EXP = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/EXP";\r
+        public static final String Built$in_Functions_Vensim_Functions_EXP_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/EXP/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_EXP_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/EXP/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_GAME = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/GAME";\r
+        public static final String Built$in_Functions_Vensim_Functions_GAME_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/GAME/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_GAME_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/GAME/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_IFTHENELSE = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/IFTHENELSE";\r
+        public static final String Built$in_Functions_Vensim_Functions_IFTHENELSE_cond = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/IFTHENELSE/cond";\r
+        public static final String Built$in_Functions_Vensim_Functions_IFTHENELSE_onfalse = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/IFTHENELSE/onfalse";\r
+        public static final String Built$in_Functions_Vensim_Functions_IFTHENELSE_ontrue = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/IFTHENELSE/ontrue";\r
+        public static final String Built$in_Functions_Vensim_Functions_IFTHENELSE_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/IFTHENELSE/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_LN = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/LN";\r
+        public static final String Built$in_Functions_Vensim_Functions_LN_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/LN/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_LN_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/LN/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_MAX = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MAX";\r
+        public static final String Built$in_Functions_Vensim_Functions_MAX_a = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MAX/a";\r
+        public static final String Built$in_Functions_Vensim_Functions_MAX_b = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MAX/b";\r
+        public static final String Built$in_Functions_Vensim_Functions_MAX_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MAX/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_MIN = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MIN";\r
+        public static final String Built$in_Functions_Vensim_Functions_MIN_a = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MIN/a";\r
+        public static final String Built$in_Functions_Vensim_Functions_MIN_b = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MIN/b";\r
+        public static final String Built$in_Functions_Vensim_Functions_MIN_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MIN/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_MODULO = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MODULO";\r
+        public static final String Built$in_Functions_Vensim_Functions_MODULO_a = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MODULO/a";\r
+        public static final String Built$in_Functions_Vensim_Functions_MODULO_b = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MODULO/b";\r
+        public static final String Built$in_Functions_Vensim_Functions_MODULO_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/MODULO/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_PULSE = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/PULSE";\r
+        public static final String Built$in_Functions_Vensim_Functions_PULSE_start = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/PULSE/start";\r
+        public static final String Built$in_Functions_Vensim_Functions_PULSE_width = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/PULSE/width";\r
+        public static final String Built$in_Functions_Vensim_Functions_PULSE_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/PULSE/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_RAMP = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/RAMP";\r
+        public static final String Built$in_Functions_Vensim_Functions_RAMP_endTime = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/RAMP/endTime";\r
+        public static final String Built$in_Functions_Vensim_Functions_RAMP_slope = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/RAMP/slope";\r
+        public static final String Built$in_Functions_Vensim_Functions_RAMP_startTime = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/RAMP/startTime";\r
+        public static final String Built$in_Functions_Vensim_Functions_RAMP_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/RAMP/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_SIN = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SIN";\r
+        public static final String Built$in_Functions_Vensim_Functions_SINH = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SINH";\r
+        public static final String Built$in_Functions_Vensim_Functions_SINH_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SINH/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_SINH_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SINH/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_SIN_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SIN/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_SIN_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SIN/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_SQRT = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SQRT";\r
+        public static final String Built$in_Functions_Vensim_Functions_SQRT_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SQRT/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_SQRT_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/SQRT/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_STEP = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/STEP";\r
+        public static final String Built$in_Functions_Vensim_Functions_STEP_height = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/STEP/height";\r
+        public static final String Built$in_Functions_Vensim_Functions_STEP_stepTime = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/STEP/stepTime";\r
+        public static final String Built$in_Functions_Vensim_Functions_STEP_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/STEP/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_TAN = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/TAN";\r
+        public static final String Built$in_Functions_Vensim_Functions_TANH = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/TANH";\r
+        public static final String Built$in_Functions_Vensim_Functions_TANH_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/TANH/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_TANH_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/TANH/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_TAN_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/TAN/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_TAN_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/TAN/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_XIDZ = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/XIDZ";\r
+        public static final String Built$in_Functions_Vensim_Functions_XIDZ_a = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/XIDZ/a";\r
+        public static final String Built$in_Functions_Vensim_Functions_XIDZ_b = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/XIDZ/b";\r
+        public static final String Built$in_Functions_Vensim_Functions_XIDZ_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/XIDZ/x";\r
+        public static final String Built$in_Functions_Vensim_Functions_XIDZ_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/XIDZ/z";\r
+        public static final String Built$in_Functions_Vensim_Functions_ZIDZ = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ZIDZ";\r
+        public static final String Built$in_Functions_Vensim_Functions_ZIDZ_a = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ZIDZ/a";\r
+        public static final String Built$in_Functions_Vensim_Functions_ZIDZ_b = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ZIDZ/b";\r
+        public static final String Built$in_Functions_Vensim_Functions_ZIDZ_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/Vensim%20Functions/ZIDZ/z";\r
+        public static final String Built$in_Functions_interpolate = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolate";\r
+        public static final String Built$in_Functions_interpolateFull = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolateFull";\r
+        public static final String Built$in_Functions_interpolateFull_icol = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolateFull/icol";\r
+        public static final String Built$in_Functions_interpolateFull_table = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolateFull/table";\r
+        public static final String Built$in_Functions_interpolateFull_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolateFull/u";\r
+        public static final String Built$in_Functions_interpolateFull_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolateFull/y";\r
+        public static final String Built$in_Functions_interpolate_table = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolate/table";\r
+        public static final String Built$in_Functions_interpolate_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolate/u";\r
+        public static final String Built$in_Functions_interpolate_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/interpolate/y";\r
+        public static final String Built$in_Functions_minmax = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/minmax";\r
+        public static final String Built$in_Functions_minmax_expression = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/minmax/expression";\r
+        public static final String Built$in_Functions_minmax_maximum = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/minmax/maximum";\r
+        public static final String Built$in_Functions_minmax_minimum = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/minmax/minimum";\r
+        public static final String Built$in_Functions_minmax_result = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/minmax/result";\r
+        public static final String Built$in_Functions_unitCast = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/unitCast";\r
+        public static final String Built$in_Functions_unitCast_u = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/unitCast/u";\r
+        public static final String Built$in_Functions_unitCast_y = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/unitCast/y";\r
+        public static final String Built$in_Functions_xidz = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/xidz";\r
+        public static final String Built$in_Functions_xidz_divident = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/xidz/divident";\r
+        public static final String Built$in_Functions_xidz_divisor = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/xidz/divisor";\r
+        public static final String Built$in_Functions_xidz_x = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/xidz/x";\r
+        public static final String Built$in_Functions_xidz_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/xidz/z";\r
+        public static final String Built$in_Functions_zidz = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/zidz";\r
+        public static final String Built$in_Functions_zidz_divident = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/zidz/divident";\r
+        public static final String Built$in_Functions_zidz_divisor = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/zidz/divisor";\r
+        public static final String Built$in_Functions_zidz_z = "http://www.simantics.org/Sysdyn-1.1/Built-in%20Functions/zidz/z";\r
+        public static final String Center = "http://www.simantics.org/Sysdyn-1.1/Center";\r
+        public static final String Charts = "http://www.simantics.org/Sysdyn-1.1/Charts";\r
+        public static final String Charts_SensitivityDataset = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset";\r
+        public static final String Charts_SensitivityDataset_ConfidenceBound = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/ConfidenceBound";\r
+        public static final String Charts_SensitivityDataset_ConfidenceBound_color = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/ConfidenceBound/color";\r
+        public static final String Charts_SensitivityDataset_ConfidenceBound_color_Inverse = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/ConfidenceBound/color/Inverse";\r
+        public static final String Charts_SensitivityDataset_ConfidenceBound_percent = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/ConfidenceBound/percent";\r
+        public static final String Charts_SensitivityDataset_ConfidenceBound_percent_Inverse = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/ConfidenceBound/percent/Inverse";\r
+        public static final String Charts_SensitivityDataset_confidenceBounds = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/confidenceBounds";\r
+        public static final String Charts_SensitivityDataset_confidenceBounds_Inverse = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/confidenceBounds/Inverse";\r
+        public static final String Charts_SensitivityDataset_median = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/median";\r
+        public static final String Charts_SensitivityDataset_median_Inverse = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityDataset/median/Inverse";\r
+        public static final String Charts_SensitivityPlot = "http://www.simantics.org/Sysdyn-1.1/Charts/SensitivityPlot";\r
+        public static final String Cloud = "http://www.simantics.org/Sysdyn-1.1/Cloud";\r
+        public static final String CloudSymbol = "http://www.simantics.org/Sysdyn-1.1/CloudSymbol";\r
+        public static final String Component = "http://www.simantics.org/Sysdyn-1.1/Component";\r
+        public static final String Configuration = "http://www.simantics.org/Sysdyn-1.1/Configuration";\r
+        public static final String ConfigurationDiagram = "http://www.simantics.org/Sysdyn-1.1/ConfigurationDiagram";\r
+        public static final String ConfigurationDiagramTemplate = "http://www.simantics.org/Sysdyn-1.1/ConfigurationDiagramTemplate";\r
+        public static final String ConfigurationDiagram_selection = "http://www.simantics.org/Sysdyn-1.1/ConfigurationDiagram/selection";\r
+        public static final String ConfigurationDiagram_selection_Inverse = "http://www.simantics.org/Sysdyn-1.1/ConfigurationDiagram/selection/Inverse";\r
+        public static final String ConstantExpression = "http://www.simantics.org/Sysdyn-1.1/ConstantExpression";\r
+        public static final String DefaultFont = "http://www.simantics.org/Sysdyn-1.1/DefaultFont";\r
+        public static final String DefaultProfile = "http://www.simantics.org/Sysdyn-1.1/DefaultProfile";\r
+        public static final String DefaultRealization = "http://www.simantics.org/Sysdyn-1.1/DefaultRealization";\r
+        public static final String DelayExpression = "http://www.simantics.org/Sysdyn-1.1/DelayExpression";\r
+        public static final String DelayExpression_delayTime = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/delayTime";\r
+        public static final String DelayExpression_delayTime_Inverse = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/delayTime/Inverse";\r
+        public static final String DelayExpression_expression = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/expression";\r
+        public static final String DelayExpression_expression_Inverse = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/expression/Inverse";\r
+        public static final String DelayExpression_initialValue = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/initialValue";\r
+        public static final String DelayExpression_initialValue_Inverse = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/initialValue/Inverse";\r
+        public static final String DelayExpression_isInformationDelay = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/isInformationDelay";\r
+        public static final String DelayExpression_order = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/order";\r
+        public static final String DelayExpression_order_Inverse = "http://www.simantics.org/Sysdyn-1.1/DelayExpression/order/Inverse";\r
+        public static final String Dependency = "http://www.simantics.org/Sysdyn-1.1/Dependency";\r
+        public static final String DependencyConnection = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection";\r
+        public static final String DependencyConnection_delayMark = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection/delayMark";\r
+        public static final String DependencyConnection_hideArrow = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection/hideArrow";\r
+        public static final String DependencyConnection_polarity = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection/polarity";\r
+        public static final String DependencyConnection_polarityLocation = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection/polarityLocation";\r
+        public static final String DependencyConnection_polarityLocation_Inverse = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection/polarityLocation/Inverse";\r
+        public static final String DependencyConnection_polarity_Inverse = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection/polarity/Inverse";\r
+        public static final String DependencyConnection_strokeWidth = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection/strokeWidth";\r
+        public static final String DependencyConnection_strokeWidth_Inverse = "http://www.simantics.org/Sysdyn-1.1/DependencyConnection/strokeWidth/Inverse";\r
+        public static final String Dependency_angle = "http://www.simantics.org/Sysdyn-1.1/Dependency/angle";\r
+        public static final String Dependency_angle_Inverse = "http://www.simantics.org/Sysdyn-1.1/Dependency/angle/Inverse";\r
+        public static final String Dependency_refersTo = "http://www.simantics.org/Sysdyn-1.1/Dependency/refersTo";\r
+        public static final String DiagramToCompositeMapping = "http://www.simantics.org/Sysdyn-1.1/DiagramToCompositeMapping";\r
+        public static final String Enumeration = "http://www.simantics.org/Sysdyn-1.1/Enumeration";\r
+        public static final String EnumerationIndex = "http://www.simantics.org/Sysdyn-1.1/EnumerationIndex";\r
+        public static final String EnumerationIndex_showEnumerationIndexInCharts = "http://www.simantics.org/Sysdyn-1.1/EnumerationIndex/showEnumerationIndexInCharts";\r
+        public static final String EnumerationIndex_showEnumerationIndexInCharts_Inverse = "http://www.simantics.org/Sysdyn-1.1/EnumerationIndex/showEnumerationIndexInCharts/Inverse";\r
+        public static final String EnumerationIndexes = "http://www.simantics.org/Sysdyn-1.1/EnumerationIndexes";\r
+        public static final String EnumerationIndexes_Inverse = "http://www.simantics.org/Sysdyn-1.1/EnumerationIndexes/Inverse";\r
+        public static final String EnumerationReplacement = "http://www.simantics.org/Sysdyn-1.1/EnumerationReplacement";\r
+        public static final String Enumeration_enumerationIndexList = "http://www.simantics.org/Sysdyn-1.1/Enumeration/enumerationIndexList";\r
+        public static final String Enumeration_enumerationIndexList_Inverse = "http://www.simantics.org/Sysdyn-1.1/Enumeration/enumerationIndexList/Inverse";\r
+        public static final String Enumeration_enumerationIndexes = "http://www.simantics.org/Sysdyn-1.1/Enumeration/enumerationIndexes";\r
+        public static final String Enumeration_enumerationIndexes_Inverse = "http://www.simantics.org/Sysdyn-1.1/Enumeration/enumerationIndexes/Inverse";\r
+        public static final String Enumeration_isReplaceable = "http://www.simantics.org/Sysdyn-1.1/Enumeration/isReplaceable";\r
+        public static final String Enumeration_isReplaceable_Inverse = "http://www.simantics.org/Sysdyn-1.1/Enumeration/isReplaceable/Inverse";\r
+        public static final String Experiment = "http://www.simantics.org/Sysdyn-1.1/Experiment";\r
+        public static final String Experiment_Run = "http://www.simantics.org/Sysdyn-1.1/Experiment/Run";\r
+        public static final String Experiment_Run_time = "http://www.simantics.org/Sysdyn-1.1/Experiment/Run/time";\r
+        public static final String Experiment_Run_time_Inverse = "http://www.simantics.org/Sysdyn-1.1/Experiment/Run/time/Inverse";\r
+        public static final String Experiment_ic = "http://www.simantics.org/Sysdyn-1.1/Experiment/ic";\r
+        public static final String Experiment_ic_Inverse = "http://www.simantics.org/Sysdyn-1.1/Experiment/ic/Inverse";\r
+        public static final String Experiment_result = "http://www.simantics.org/Sysdyn-1.1/Experiment/result";\r
+        public static final String Experiment_resultSet = "http://www.simantics.org/Sysdyn-1.1/Experiment/resultSet";\r
+        public static final String Experiment_resultSet_Inverse = "http://www.simantics.org/Sysdyn-1.1/Experiment/resultSet/Inverse";\r
+        public static final String Experiment_result_Inverse = "http://www.simantics.org/Sysdyn-1.1/Experiment/result/Inverse";\r
+        public static final String ExportModuleTree = "http://www.simantics.org/Sysdyn-1.1/ExportModuleTree";\r
+        public static final String Expression = "http://www.simantics.org/Sysdyn-1.1/Expression";\r
+        public static final String Expression_arrayRange = "http://www.simantics.org/Sysdyn-1.1/Expression/arrayRange";\r
+        public static final String Expression_arrayRange_Inverse = "http://www.simantics.org/Sysdyn-1.1/Expression/arrayRange/Inverse";\r
+        public static final String Expression_equation = "http://www.simantics.org/Sysdyn-1.1/Expression/equation";\r
+        public static final String Expression_equation_Inverse = "http://www.simantics.org/Sysdyn-1.1/Expression/equation/Inverse";\r
+        public static final String Expressions = "http://www.simantics.org/Sysdyn-1.1/Expressions";\r
+        public static final String Expressions_Inverse = "http://www.simantics.org/Sysdyn-1.1/Expressions/Inverse";\r
+        public static final String ExternalFiles = "http://www.simantics.org/Sysdyn-1.1/ExternalFiles";\r
+        public static final String ExternalFunctionFile = "http://www.simantics.org/Sysdyn-1.1/ExternalFunctionFile";\r
+        public static final String ExternalFunctionFile_externalFile = "http://www.simantics.org/Sysdyn-1.1/ExternalFunctionFile/externalFile";\r
+        public static final String ExternalFunctionFile_externalFile_Inverse = "http://www.simantics.org/Sysdyn-1.1/ExternalFunctionFile/externalFile/Inverse";\r
+        public static final String Flow = "http://www.simantics.org/Sysdyn-1.1/Flow";\r
+        public static final String FlowConnection = "http://www.simantics.org/Sysdyn-1.1/FlowConnection";\r
+        public static final String FlowConnection_width = "http://www.simantics.org/Sysdyn-1.1/FlowConnection/width";\r
+        public static final String FlowConnection_width_Inverse = "http://www.simantics.org/Sysdyn-1.1/FlowConnection/width/Inverse";\r
+        public static final String FunctionTree = "http://www.simantics.org/Sysdyn-1.1/FunctionTree";\r
+        public static final String Functions = "http://www.simantics.org/Sysdyn-1.1/Functions";\r
+        public static final String Functions_equationPropertyValue = "http://www.simantics.org/Sysdyn-1.1/Functions/equationPropertyValue";\r
+        public static final String Functions_runChildren = "http://www.simantics.org/Sysdyn-1.1/Functions/runChildren";\r
+        public static final String Functions_runProperties = "http://www.simantics.org/Sysdyn-1.1/Functions/runProperties";\r
+        public static final String Functions_valuePropertyProperties = "http://www.simantics.org/Sysdyn-1.1/Functions/valuePropertyProperties";\r
+        public static final String Functions_valuePropertyValue = "http://www.simantics.org/Sysdyn-1.1/Functions/valuePropertyValue";\r
+        public static final String GameExperiment = "http://www.simantics.org/Sysdyn-1.1/GameExperiment";\r
+        public static final String GameExperiment_stepDuration = "http://www.simantics.org/Sysdyn-1.1/GameExperiment/stepDuration";\r
+        public static final String GameExperiment_stepDuration_Inverse = "http://www.simantics.org/Sysdyn-1.1/GameExperiment/stepDuration/Inverse";\r
+        public static final String GameExperiment_stepLength = "http://www.simantics.org/Sysdyn-1.1/GameExperiment/stepLength";\r
+        public static final String GameExperiment_stepLength_Inverse = "http://www.simantics.org/Sysdyn-1.1/GameExperiment/stepLength/Inverse";\r
+        public static final String HaltonSequenceGenerator = "http://www.simantics.org/Sysdyn-1.1/HaltonSequenceGenerator";\r
+        public static final String HasEquationOrEmpty = "http://www.simantics.org/Sysdyn-1.1/HasEquationOrEmpty";\r
+        public static final String HasEquationOrEmpty_Inverse = "http://www.simantics.org/Sysdyn-1.1/HasEquationOrEmpty/Inverse";\r
+        public static final String HasHeadTerminal = "http://www.simantics.org/Sysdyn-1.1/HasHeadTerminal";\r
+        public static final String HasRangeEnd = "http://www.simantics.org/Sysdyn-1.1/HasRangeEnd";\r
+        public static final String HasRangeEnd_Inverse = "http://www.simantics.org/Sysdyn-1.1/HasRangeEnd/Inverse";\r
+        public static final String HasRangeStart = "http://www.simantics.org/Sysdyn-1.1/HasRangeStart";\r
+        public static final String HasRangeStart_Inverse = "http://www.simantics.org/Sysdyn-1.1/HasRangeStart/Inverse";\r
+        public static final String HasRangeStep = "http://www.simantics.org/Sysdyn-1.1/HasRangeStep";\r
+        public static final String HasRangeStep_Inverse = "http://www.simantics.org/Sysdyn-1.1/HasRangeStep/Inverse";\r
+        public static final String HasTailTerminal = "http://www.simantics.org/Sysdyn-1.1/HasTailTerminal";\r
+        public static final String HistoryDataset = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset";\r
+        public static final String HistoryDataset_FoundVariableNameNode = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/FoundVariableNameNode";\r
+        public static final String HistoryDataset_HistoryDatasetVariablesBrowseContext = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/HistoryDatasetVariablesBrowseContext";\r
+        public static final String HistoryDataset_HistoryDatasetVariablesBrowseContext_StringNodeType = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/HistoryDatasetVariablesBrowseContext/StringNodeType";\r
+        public static final String HistoryDataset_HistoryDatasetVariablesBrowseContext_VariableChildRule = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/HistoryDatasetVariablesBrowseContext/VariableChildRule";\r
+        public static final String HistoryDataset_HistoryDatasetVariablesBrowseContext_VariableLabelRule = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/HistoryDatasetVariablesBrowseContext/VariableLabelRule";\r
+        public static final String HistoryDataset_columns = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/columns";\r
+        public static final String HistoryDataset_columns_Inverse = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/columns/Inverse";\r
+        public static final String HistoryDataset_end = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/end";\r
+        public static final String HistoryDataset_end_Inverse = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/end/Inverse";\r
+        public static final String HistoryDataset_sheet = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/sheet";\r
+        public static final String HistoryDataset_start = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/start";\r
+        public static final String HistoryDataset_start_Inverse = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/start/Inverse";\r
+        public static final String HistoryDataset_timeName = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/timeName";\r
+        public static final String HistoryDataset_timeName_Inverse = "http://www.simantics.org/Sysdyn-1.1/HistoryDataset/timeName/Inverse";\r
+        public static final String HistoryRealization = "http://www.simantics.org/Sysdyn-1.1/HistoryRealization";\r
+        public static final String Horizontal = "http://www.simantics.org/Sysdyn-1.1/Horizontal";\r
+        public static final String ImportModuleTree = "http://www.simantics.org/Sysdyn-1.1/ImportModuleTree";\r
+        public static final String ImportedOntologies = "http://www.simantics.org/Sysdyn-1.1/ImportedOntologies";\r
+        public static final String IndependentVariable = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable";\r
+        public static final String IndependentVariable_activeExpression = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/activeExpression";\r
+        public static final String IndependentVariable_isUninitialized = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/isUninitialized";\r
+        public static final String IndependentVariable_isUninitialized_Inverse = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/isUninitialized/Inverse";\r
+        public static final String IndependentVariable_rangeEnd = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/rangeEnd";\r
+        public static final String IndependentVariable_rangeEnd_Inverse = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/rangeEnd/Inverse";\r
+        public static final String IndependentVariable_rangeStart = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/rangeStart";\r
+        public static final String IndependentVariable_rangeStart_Inverse = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/rangeStart/Inverse";\r
+        public static final String IndependentVariable_rangeStep = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/rangeStep";\r
+        public static final String IndependentVariable_rangeStep_Inverse = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/rangeStep/Inverse";\r
+        public static final String IndependentVariable_unit = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/unit";\r
+        public static final String IndependentVariable_unit_Inverse = "http://www.simantics.org/Sysdyn-1.1/IndependentVariable/unit/Inverse";\r
+        public static final String InitialCondition = "http://www.simantics.org/Sysdyn-1.1/InitialCondition";\r
+        public static final String InitialCondition_HasInitialValues = "http://www.simantics.org/Sysdyn-1.1/InitialCondition/HasInitialValues";\r
+        public static final String InitialCondition_HasInitialValues_Inverse = "http://www.simantics.org/Sysdyn-1.1/InitialCondition/HasInitialValues/Inverse";\r
+        public static final String Input = "http://www.simantics.org/Sysdyn-1.1/Input";\r
+        public static final String InputSymbol = "http://www.simantics.org/Sysdyn-1.1/InputSymbol";\r
+        public static final String Input_defaultInputValue = "http://www.simantics.org/Sysdyn-1.1/Input/defaultInputValue";\r
+        public static final String Input_defaultInputValue_Inverse = "http://www.simantics.org/Sysdyn-1.1/Input/defaultInputValue/Inverse";\r
+        public static final String Interval = "http://www.simantics.org/Sysdyn-1.1/Interval";\r
+        public static final String Interval_maxValue = "http://www.simantics.org/Sysdyn-1.1/Interval/maxValue";\r
+        public static final String Interval_maxValue_Inverse = "http://www.simantics.org/Sysdyn-1.1/Interval/maxValue/Inverse";\r
+        public static final String Interval_minValue = "http://www.simantics.org/Sysdyn-1.1/Interval/minValue";\r
+        public static final String Interval_minValue_Inverse = "http://www.simantics.org/Sysdyn-1.1/Interval/minValue/Inverse";\r
+        public static final String IsHeadOfTerminal = "http://www.simantics.org/Sysdyn-1.1/IsHeadOfTerminal";\r
+        public static final String IsOutput = "http://www.simantics.org/Sysdyn-1.1/IsOutput";\r
+        public static final String IsTailOfTerminal = "http://www.simantics.org/Sysdyn-1.1/IsTailOfTerminal";\r
+        public static final String IssueStyle = "http://www.simantics.org/Sysdyn-1.1/IssueStyle";\r
+        public static final String Left = "http://www.simantics.org/Sysdyn-1.1/Left";\r
+        public static final String Location = "http://www.simantics.org/Sysdyn-1.1/Location";\r
+        public static final String LookupExpression = "http://www.simantics.org/Sysdyn-1.1/LookupExpression";\r
+        public static final String LookupExpression_lookup = "http://www.simantics.org/Sysdyn-1.1/LookupExpression/lookup";\r
+        public static final String LookupExpression_lookup_Inverse = "http://www.simantics.org/Sysdyn-1.1/LookupExpression/lookup/Inverse";\r
+        public static final String Loop = "http://www.simantics.org/Sysdyn-1.1/Loop";\r
+        public static final String LoopSymbol = "http://www.simantics.org/Sysdyn-1.1/LoopSymbol";\r
+        public static final String LoopSymbol_Clockwise = "http://www.simantics.org/Sysdyn-1.1/LoopSymbol/Clockwise";\r
+        public static final String LoopSymbol_Clockwise_Inverse = "http://www.simantics.org/Sysdyn-1.1/LoopSymbol/Clockwise/Inverse";\r
+        public static final String Loop_Comment = "http://www.simantics.org/Sysdyn-1.1/Loop/Comment";\r
+        public static final String Loop_Comment_Inverse = "http://www.simantics.org/Sysdyn-1.1/Loop/Comment/Inverse";\r
+        public static final String Loop_Items = "http://www.simantics.org/Sysdyn-1.1/Loop/Items";\r
+        public static final String Loop_Items_Inverse = "http://www.simantics.org/Sysdyn-1.1/Loop/Items/Inverse";\r
+        public static final String Migration = "http://www.simantics.org/Sysdyn-1.1/Migration";\r
+        public static final String Migration_from1$6to1$7 = "http://www.simantics.org/Sysdyn-1.1/Migration/from1.6to1.7";\r
+        public static final String Migration_from1$6to1$7_Custom = "http://www.simantics.org/Sysdyn-1.1/Migration/from1.6to1.7/Custom";\r
+        public static final String Migration_from1$6to1$7_Ontologies = "http://www.simantics.org/Sysdyn-1.1/Migration/from1.6to1.7/Ontologies";\r
+        public static final String Migration_from1$6to1$7_OrderedSetsToLists = "http://www.simantics.org/Sysdyn-1.1/Migration/from1.6to1.7/OrderedSetsToLists";\r
+        public static final String Migration_from1$6to1$7_Spreadsheets = "http://www.simantics.org/Sysdyn-1.1/Migration/from1.6to1.7/Spreadsheets";\r
+        public static final String Migration_from1$6to1$7_SysdynChanges = "http://www.simantics.org/Sysdyn-1.1/Migration/from1.6to1.7/SysdynChanges";\r
+        public static final String Migration_fromFunctionLibrary1 = "http://www.simantics.org/Sysdyn-1.1/Migration/fromFunctionLibrary1";\r
+        public static final String Migration_fromModel1 = "http://www.simantics.org/Sysdyn-1.1/Migration/fromModel1";\r
+        public static final String Migration_fromModule1 = "http://www.simantics.org/Sysdyn-1.1/Migration/fromModule1";\r
+        public static final String ModelBrowser = "http://www.simantics.org/Sysdyn-1.1/ModelBrowser";\r
+        public static final String ModelingActionContext = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext";\r
+        public static final String ModelingActionContext_Actions = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions";\r
+        public static final String ModelingActionContext_Actions_ChartDropAction = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/ChartDropAction";\r
+        public static final String ModelingActionContext_Actions_FunctionDropAction = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/FunctionDropAction";\r
+        public static final String ModelingActionContext_Actions_NewBarChart = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewBarChart";\r
+        public static final String ModelingActionContext_Actions_NewEnumeration = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewEnumeration";\r
+        public static final String ModelingActionContext_Actions_NewExperiment = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewExperiment";\r
+        public static final String ModelingActionContext_Actions_NewFunction = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewFunction";\r
+        public static final String ModelingActionContext_Actions_NewFunctionLibrary = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewFunctionLibrary";\r
+        public static final String ModelingActionContext_Actions_NewHistoryData = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewHistoryData";\r
+        public static final String ModelingActionContext_Actions_NewLineChart = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewLineChart";\r
+        public static final String ModelingActionContext_Actions_NewModuleType = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewModuleType";\r
+        public static final String ModelingActionContext_Actions_NewPieChart = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewPieChart";\r
+        public static final String ModelingActionContext_Actions_NewSharedFunctionLibrary = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewSharedFunctionLibrary";\r
+        public static final String ModelingActionContext_Actions_NewSheet = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewSheet";\r
+        public static final String ModelingActionContext_Actions_NewSimulationPlaybackExperiment = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewSimulationPlaybackExperiment";\r
+        public static final String ModelingBrowseContext = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext";\r
+        public static final String ModelingBrowseContext_ActiveLabelDecorationRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ActiveLabelDecorationRule";\r
+        public static final String ModelingBrowseContext_BuiltinFunctions = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/BuiltinFunctions";\r
+        public static final String ModelingBrowseContext_ChartImageRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ChartImageRule";\r
+        public static final String ModelingBrowseContext_ChartsFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ChartsFolder";\r
+        public static final String ModelingBrowseContext_ExperimentsFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ExperimentsFolder";\r
+        public static final String ModelingBrowseContext_FunctionsFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/FunctionsFolder";\r
+        public static final String ModelingBrowseContext_ModuleContentChildRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModuleContentChildRule";\r
+        public static final String ModelingBrowseContext_ModuleSymbol = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModuleSymbol";\r
+        public static final String ModelingBrowseContext_ModuleSymbolNodeType = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModuleSymbolNodeType";\r
+        public static final String ModelingBrowseContext_ModuleTypeChildRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModuleTypeChildRule";\r
+        public static final String ModelingBrowseContext_ModuleTypeLabelRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModuleTypeLabelRule";\r
+        public static final String ModelingBrowseContext_ModulesFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModulesFolder";\r
+        public static final String ModelingBrowseContext_ResultImageRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ResultImageRule";\r
+        public static final String ModelingBrowseContext_SharedFunctionsFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/SharedFunctionsFolder";\r
+        public static final String ModelingBrowseContext_Variable = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/Variable";\r
+        public static final String ModelingBrowseContext_VariableChildRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/VariableChildRule";\r
+        public static final String ModelingBrowseContext_VariableImageRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/VariableImageRule";\r
+        public static final String ModelingBrowseContext_VariableNameLabelRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/VariableNameLabelRule";\r
+        public static final String ModelingBrowseContext_VariableNodeType = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/VariableNodeType";\r
+        public static final String Module = "http://www.simantics.org/Sysdyn-1.1/Module";\r
+        public static final String ModuleSymbol = "http://www.simantics.org/Sysdyn-1.1/ModuleSymbol";\r
+        public static final String Module_ParameterOverride = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverride";\r
+        public static final String Module_ParameterOverrideBrowseContext = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverrideBrowseContext";\r
+        public static final String Module_ParameterOverrideBrowseContext_Node = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverrideBrowseContext/Node";\r
+        public static final String Module_ParameterOverrideBrowseContext_NodeType = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverrideBrowseContext/NodeType";\r
+        public static final String Module_ParameterOverrideBrowseContext_ParameterChildRule = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverrideBrowseContext/ParameterChildRule";\r
+        public static final String Module_ParameterOverrideBrowseContext_ParameterLabelDecorationRule = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverrideBrowseContext/ParameterLabelDecorationRule";\r
+        public static final String Module_ParameterOverrideBrowseContext_ParameterLabelRule = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverrideBrowseContext/ParameterLabelRule";\r
+        public static final String Module_ParameterOverrideBrowseContext_ParameterModifierRule = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverrideBrowseContext/ParameterModifierRule";\r
+        public static final String Module_ParameterOverrideBrowseContext_ParameterSorterRule = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverrideBrowseContext/ParameterSorterRule";\r
+        public static final String Module_ParameterOverride_overriddenParameter = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverride/overriddenParameter";\r
+        public static final String Module_ParameterOverride_overrideExpression = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverride/overrideExpression";\r
+        public static final String Module_ParameterOverride_overrideExpression_Inverse = "http://www.simantics.org/Sysdyn-1.1/Module/ParameterOverride/overrideExpression/Inverse";\r
+        public static final String Module_parameterOverride = "http://www.simantics.org/Sysdyn-1.1/Module/parameterOverride";\r
+        public static final String Module_parameterOverride_Inverse = "http://www.simantics.org/Sysdyn-1.1/Module/parameterOverride/Inverse";\r
+        public static final String Module_redeclaration = "http://www.simantics.org/Sysdyn-1.1/Module/redeclaration";\r
+        public static final String Module_redeclaration_Inverse = "http://www.simantics.org/Sysdyn-1.1/Module/redeclaration/Inverse";\r
+        public static final String ModulesSearchFunction = "http://www.simantics.org/Sysdyn-1.1/ModulesSearchFunction";\r
+        public static final String NormalDistribution = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution";\r
+        public static final String NormalDistribution_maxValue = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution/maxValue";\r
+        public static final String NormalDistribution_maxValue_Inverse = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution/maxValue/Inverse";\r
+        public static final String NormalDistribution_mean = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution/mean";\r
+        public static final String NormalDistribution_mean_Inverse = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution/mean/Inverse";\r
+        public static final String NormalDistribution_minValue = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution/minValue";\r
+        public static final String NormalDistribution_minValue_Inverse = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution/minValue/Inverse";\r
+        public static final String NormalDistribution_stdDeviation = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution/stdDeviation";\r
+        public static final String NormalDistribution_stdDeviation_Inverse = "http://www.simantics.org/Sysdyn-1.1/NormalDistribution/stdDeviation/Inverse";\r
+        public static final String NormalExpression = "http://www.simantics.org/Sysdyn-1.1/NormalExpression";\r
+        public static final String Orientation = "http://www.simantics.org/Sysdyn-1.1/Orientation";\r
+        public static final String ParameterExpression = "http://www.simantics.org/Sysdyn-1.1/ParameterExpression";\r
+        public static final String PlaybackExperiment = "http://www.simantics.org/Sysdyn-1.1/PlaybackExperiment";\r
+        public static final String ProbabilityDistribution = "http://www.simantics.org/Sysdyn-1.1/ProbabilityDistribution";\r
+        public static final String Profiles = "http://www.simantics.org/Sysdyn-1.1/Profiles";\r
+        public static final String Profiles_IssueWarnings = "http://www.simantics.org/Sysdyn-1.1/Profiles/IssueWarnings";\r
+        public static final String Profiles_ShadowVisualizations = "http://www.simantics.org/Sysdyn-1.1/Profiles/ShadowVisualizations";\r
+        public static final String Profiles_SimulationPlaybackColours = "http://www.simantics.org/Sysdyn-1.1/Profiles/SimulationPlaybackColours";\r
+        public static final String RandomGenerator = "http://www.simantics.org/Sysdyn-1.1/RandomGenerator";\r
+        public static final String Redeclaration = "http://www.simantics.org/Sysdyn-1.1/Redeclaration";\r
+        public static final String Redeclaration_replacedEnumeration = "http://www.simantics.org/Sysdyn-1.1/Redeclaration/replacedEnumeration";\r
+        public static final String Redeclaration_replacedEnumeration_Inverse = "http://www.simantics.org/Sysdyn-1.1/Redeclaration/replacedEnumeration/Inverse";\r
+        public static final String Redeclaration_replacingEnumeration = "http://www.simantics.org/Sysdyn-1.1/Redeclaration/replacingEnumeration";\r
+        public static final String Redeclaration_replacingEnumeration_Inverse = "http://www.simantics.org/Sysdyn-1.1/Redeclaration/replacingEnumeration/Inverse";\r
+        public static final String Result = "http://www.simantics.org/Sysdyn-1.1/Result";\r
+        public static final String ResultSet = "http://www.simantics.org/Sysdyn-1.1/ResultSet";\r
+        public static final String Result_parameterFile = "http://www.simantics.org/Sysdyn-1.1/Result/parameterFile";\r
+        public static final String Result_parameterFile_Inverse = "http://www.simantics.org/Sysdyn-1.1/Result/parameterFile/Inverse";\r
+        public static final String Result_resultFile = "http://www.simantics.org/Sysdyn-1.1/Result/resultFile";\r
+        public static final String Result_resultFile_Inverse = "http://www.simantics.org/Sysdyn-1.1/Result/resultFile/Inverse";\r
+        public static final String Result_showResult = "http://www.simantics.org/Sysdyn-1.1/Result/showResult";\r
+        public static final String Result_time = "http://www.simantics.org/Sysdyn-1.1/Result/time";\r
+        public static final String Result_time_Inverse = "http://www.simantics.org/Sysdyn-1.1/Result/time/Inverse";\r
+        public static final String Right = "http://www.simantics.org/Sysdyn-1.1/Right";\r
+        public static final String SearchContribution = "http://www.simantics.org/Sysdyn-1.1/SearchContribution";\r
+        public static final String SelectedSharedFunctionLibraries = "http://www.simantics.org/Sysdyn-1.1/SelectedSharedFunctionLibraries";\r
+        public static final String SensitivityAnalysisExperiment = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment";\r
+        public static final String SensitivityAnalysisExperiment_Parameter = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/Parameter";\r
+        public static final String SensitivityAnalysisExperiment_ParameterActionContext = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/ParameterActionContext";\r
+        public static final String SensitivityAnalysisExperiment_ParameterActionContext_Actions = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/ParameterActionContext/Actions";\r
+        public static final String SensitivityAnalysisExperiment_ParameterBrowseContext = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/ParameterBrowseContext";\r
+        public static final String SensitivityAnalysisExperiment_ParameterBrowseContext_ParameterChildRule = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/ParameterBrowseContext/ParameterChildRule";\r
+        public static final String SensitivityAnalysisExperiment_ParameterBrowseContext_ParameterLabelRule = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/ParameterBrowseContext/ParameterLabelRule";\r
+        public static final String SensitivityAnalysisExperiment_Parameter_indexes = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/Parameter/indexes";\r
+        public static final String SensitivityAnalysisExperiment_Parameter_indexes_Inverse = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/Parameter/indexes/Inverse";\r
+        public static final String SensitivityAnalysisExperiment_Parameter_propabilityDistribution = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/Parameter/propabilityDistribution";\r
+        public static final String SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/Parameter/propabilityDistribution/Inverse";\r
+        public static final String SensitivityAnalysisExperiment_Parameter_variable = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/Parameter/variable";\r
+        public static final String SensitivityAnalysisExperiment_Parameter_variable_Inverse = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/Parameter/variable/Inverse";\r
+        public static final String SensitivityAnalysisExperiment_method = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/method";\r
+        public static final String SensitivityAnalysisExperiment_method_Inverse = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/method/Inverse";\r
+        public static final String SensitivityAnalysisExperiment_numberOfValues = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/numberOfValues";\r
+        public static final String SensitivityAnalysisExperiment_numberOfValues_Inverse = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/numberOfValues/Inverse";\r
+        public static final String SensitivityAnalysisExperiment_parameterList = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/parameterList";\r
+        public static final String SensitivityAnalysisExperiment_parameterList_Inverse = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/parameterList/Inverse";\r
+        public static final String SensitivityAnalysisExperiment_randomSeed = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/randomSeed";\r
+        public static final String SensitivityAnalysisExperiment_randomSeed_Inverse = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/randomSeed/Inverse";\r
+        public static final String SensitivityAnalysisExperiment_resultRefreshRate = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/resultRefreshRate";\r
+        public static final String SensitivityAnalysisExperiment_resultRefreshRate_Inverse = "http://www.simantics.org/Sysdyn-1.1/SensitivityAnalysisExperiment/resultRefreshRate/Inverse";\r
+        public static final String Shadow = "http://www.simantics.org/Sysdyn-1.1/Shadow";\r
+        public static final String ShadowStyle = "http://www.simantics.org/Sysdyn-1.1/ShadowStyle";\r
+        public static final String ShadowSymbol = "http://www.simantics.org/Sysdyn-1.1/ShadowSymbol";\r
+        public static final String Shadow_original = "http://www.simantics.org/Sysdyn-1.1/Shadow/original";\r
+        public static final String Shadow_original_Inverse = "http://www.simantics.org/Sysdyn-1.1/Shadow/original/Inverse";\r
+        public static final String SharedFunctionOntology = "http://www.simantics.org/Sysdyn-1.1/SharedFunctionOntology";\r
+        public static final String SharedModuleOntology = "http://www.simantics.org/Sysdyn-1.1/SharedModuleOntology";\r
+        public static final String SimulateOnChangeExperiment = "http://www.simantics.org/Sysdyn-1.1/SimulateOnChangeExperiment";\r
+        public static final String SimulationPlaybackProfile = "http://www.simantics.org/Sysdyn-1.1/SimulationPlaybackProfile";\r
+        public static final String SimulationPlaybackStyle = "http://www.simantics.org/Sysdyn-1.1/SimulationPlaybackStyle";\r
+        public static final String Stock = "http://www.simantics.org/Sysdyn-1.1/Stock";\r
+        public static final String StockExpression = "http://www.simantics.org/Sysdyn-1.1/StockExpression";\r
+        public static final String StockExpression_initialEquation = "http://www.simantics.org/Sysdyn-1.1/StockExpression/initialEquation";\r
+        public static final String StockExpression_initialEquation_Inverse = "http://www.simantics.org/Sysdyn-1.1/StockExpression/initialEquation/Inverse";\r
+        public static final String StockExpression_integralEquation = "http://www.simantics.org/Sysdyn-1.1/StockExpression/integralEquation";\r
+        public static final String StockExpression_integralEquation_Inverse = "http://www.simantics.org/Sysdyn-1.1/StockExpression/integralEquation/Inverse";\r
+        public static final String StockExpression_useCustomIntegral = "http://www.simantics.org/Sysdyn-1.1/StockExpression/useCustomIntegral";\r
+        public static final String StockSymbol = "http://www.simantics.org/Sysdyn-1.1/StockSymbol";\r
+        public static final String SymbolReferences = "http://www.simantics.org/Sysdyn-1.1/SymbolReferences";\r
+        public static final String SymbolReferences_BasicSymbols = "http://www.simantics.org/Sysdyn-1.1/SymbolReferences/BasicSymbols";\r
+        public static final String SymbolReferences_CommentSymbols = "http://www.simantics.org/Sysdyn-1.1/SymbolReferences/CommentSymbols";\r
+        public static final String Symbols = "http://www.simantics.org/Sysdyn-1.1/Symbols";\r
+        public static final String SysdynConnectionType = "http://www.simantics.org/Sysdyn-1.1/SysdynConnectionType";\r
+        public static final String SysdynDiagramModelingRules = "http://www.simantics.org/Sysdyn-1.1/SysdynDiagramModelingRules";\r
+        public static final String SysdynModel = "http://www.simantics.org/Sysdyn-1.1/SysdynModel";\r
+        public static final String SysdynModel_fmuFile = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/fmuFile";\r
+        public static final String SysdynModel_fmuFile_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/fmuFile/Inverse";\r
+        public static final String SysdynModel_lastExportFileName = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/lastExportFileName";\r
+        public static final String SysdynModel_lastExportFileName_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/lastExportFileName/Inverse";\r
+        public static final String SysdynModel_lastExportFilePath = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/lastExportFilePath";\r
+        public static final String SysdynModel_lastExportFilePath_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/lastExportFilePath/Inverse";\r
+        public static final String SysdynModel_outputInterval = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/outputInterval";\r
+        public static final String SysdynModel_outputInterval_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/outputInterval/Inverse";\r
+        public static final String SysdynModel_simulationStepLength = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/simulationStepLength";\r
+        public static final String SysdynModel_simulationStepLength_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/simulationStepLength/Inverse";\r
+        public static final String SysdynModel_solver = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/solver";\r
+        public static final String SysdynModel_solver_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/solver/Inverse";\r
+        public static final String SysdynModel_startTime = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/startTime";\r
+        public static final String SysdynModel_startTime_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/startTime/Inverse";\r
+        public static final String SysdynModel_stopTime = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/stopTime";\r
+        public static final String SysdynModel_stopTime_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/stopTime/Inverse";\r
+        public static final String SysdynModel_timeUnit = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/timeUnit";\r
+        public static final String SysdynModel_timeUnit_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/timeUnit/Inverse";\r
+        public static final String SysdynModel_tolerance = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/tolerance";\r
+        public static final String SysdynModel_tolerance_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/tolerance/Inverse";\r
+        public static final String SysdynModel_variableFilter = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/variableFilter";\r
+        public static final String SysdynModel_variableFilter_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModel/variableFilter/Inverse";\r
+        public static final String SysdynModelicaFunction = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction";\r
+        public static final String SysdynModelicaFunctionLibrary = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunctionLibrary";\r
+        public static final String SysdynModelicaFunction_Input = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/Input";\r
+        public static final String SysdynModelicaFunction_InterfaceVariable = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/InterfaceVariable";\r
+        public static final String SysdynModelicaFunction_Output = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/Output";\r
+        public static final String SysdynModelicaFunction_VariableLengthInput = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/VariableLengthInput";\r
+        public static final String SysdynModelicaFunction_VariableLengthInput_shownLabels = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/VariableLengthInput/shownLabels";\r
+        public static final String SysdynModelicaFunction_VariableLengthInput_shownLabels_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/VariableLengthInput/shownLabels/Inverse";\r
+        public static final String SysdynModelicaFunction_definition = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/definition";\r
+        public static final String SysdynModelicaFunction_definition_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/definition/Inverse";\r
+        public static final String SysdynModelicaFunction_inputs = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/inputs";\r
+        public static final String SysdynModelicaFunction_inputs_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/inputs/Inverse";\r
+        public static final String SysdynModelicaFunction_modelicaFunctionCode = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/modelicaFunctionCode";\r
+        public static final String SysdynModelicaFunction_modelicaFunctionCode_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/modelicaFunctionCode/Inverse";\r
+        public static final String SysdynModelicaFunction_modelicaFunctionInterface = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/modelicaFunctionInterface";\r
+        public static final String SysdynModelicaFunction_modelicaFunctionInterface_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/modelicaFunctionInterface/Inverse";\r
+        public static final String SysdynModelicaFunction_optional = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/optional";\r
+        public static final String SysdynModelicaFunction_optional_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/optional/Inverse";\r
+        public static final String SysdynModelicaFunction_outputs = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/outputs";\r
+        public static final String SysdynModelicaFunction_outputs_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/outputs/Inverse";\r
+        public static final String SysdynModelicaFunction_unit = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/unit";\r
+        public static final String SysdynModelicaFunction_unit_Inverse = "http://www.simantics.org/Sysdyn-1.1/SysdynModelicaFunction/unit/Inverse";\r
+        public static final String SysdynModuleLibrary = "http://www.simantics.org/Sysdyn-1.1/SysdynModuleLibrary";\r
+        public static final String SysdynOperationBrowser = "http://www.simantics.org/Sysdyn-1.1/SysdynOperationBrowser";\r
+        public static final String SysdynSymbol = "http://www.simantics.org/Sysdyn-1.1/SysdynSymbol";\r
+        public static final String SysdynTerminal = "http://www.simantics.org/Sysdyn-1.1/SysdynTerminal";\r
+        public static final String Top = "http://www.simantics.org/Sysdyn-1.1/Top";\r
+        public static final String UniformDistribution = "http://www.simantics.org/Sysdyn-1.1/UniformDistribution";\r
+        public static final String UniformDistribution_maxValue = "http://www.simantics.org/Sysdyn-1.1/UniformDistribution/maxValue";\r
+        public static final String UniformDistribution_maxValue_Inverse = "http://www.simantics.org/Sysdyn-1.1/UniformDistribution/maxValue/Inverse";\r
+        public static final String UniformDistribution_minValue = "http://www.simantics.org/Sysdyn-1.1/UniformDistribution/minValue";\r
+        public static final String UniformDistribution_minValue_Inverse = "http://www.simantics.org/Sysdyn-1.1/UniformDistribution/minValue/Inverse";\r
+        public static final String UsedVariableIndexes = "http://www.simantics.org/Sysdyn-1.1/UsedVariableIndexes";\r
+        public static final String Validations = "http://www.simantics.org/Sysdyn-1.1/Validations";\r
+        public static final String Validations_Dependencies = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies";\r
+        public static final String Validations_Dependencies_DependencyConnectionsIssueSource = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/DependencyConnectionsIssueSource";\r
+        public static final String Validations_Dependencies_MissingDependencyConnectionsIssueSource = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/MissingDependencyConnectionsIssueSource";\r
+        public static final String Validations_Dependencies_dependencyValidator = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/dependencyValidator";\r
+        public static final String Validations_Dependencies_invalidSheetReferenceIssueDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/invalidSheetReferenceIssueDescription";\r
+        public static final String Validations_Dependencies_missingDependencyValidator = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/missingDependencyValidator";\r
+        public static final String Validations_Dependencies_missingLinkIssueDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/missingLinkIssueDescription";\r
+        public static final String Validations_Dependencies_noSuchVariableIssueDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/noSuchVariableIssueDescription";\r
+        public static final String Validations_Dependencies_rangeIssueDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/rangeIssueDescription";\r
+        public static final String Validations_Dependencies_rangeWarningDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/rangeWarningDescription";\r
+        public static final String Validations_Dependencies_unusedDependencyIssueDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Dependencies/unusedDependencyIssueDescription";\r
+        public static final String Validations_DependencyConstraint = "http://www.simantics.org/Sysdyn-1.1/Validations/DependencyConstraint";\r
+        public static final String Validations_EmptyEnumerationIssue = "http://www.simantics.org/Sysdyn-1.1/Validations/EmptyEnumerationIssue";\r
+        public static final String Validations_EnumerationConstraint = "http://www.simantics.org/Sysdyn-1.1/Validations/EnumerationConstraint";\r
+        public static final String Validations_Enumerations = "http://www.simantics.org/Sysdyn-1.1/Validations/Enumerations";\r
+        public static final String Validations_Enumerations_EnumerationIssueSource = "http://www.simantics.org/Sysdyn-1.1/Validations/Enumerations/EnumerationIssueSource";\r
+        public static final String Validations_Enumerations_emptyEnumerationIssueDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Enumerations/emptyEnumerationIssueDescription";\r
+        public static final String Validations_Enumerations_enumerationIndexValidator = "http://www.simantics.org/Sysdyn-1.1/Validations/Enumerations/enumerationIndexValidator";\r
+        public static final String Validations_ExpressionConstraint = "http://www.simantics.org/Sysdyn-1.1/Validations/ExpressionConstraint";\r
+        public static final String Validations_ExpressionIssue = "http://www.simantics.org/Sysdyn-1.1/Validations/ExpressionIssue";\r
+        public static final String Validations_Expressions = "http://www.simantics.org/Sysdyn-1.1/Validations/Expressions";\r
+        public static final String Validations_Expressions_ExpressionIssueSource = "http://www.simantics.org/Sysdyn-1.1/Validations/Expressions/ExpressionIssueSource";\r
+        public static final String Validations_Expressions_expressionIssueDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Expressions/expressionIssueDescription";\r
+        public static final String Validations_Expressions_expressionValidator = "http://www.simantics.org/Sysdyn-1.1/Validations/Expressions/expressionValidator";\r
+        public static final String Validations_Functions = "http://www.simantics.org/Sysdyn-1.1/Validations/Functions";\r
+        public static final String Validations_Functions_baseRealizationFunction = "http://www.simantics.org/Sysdyn-1.1/Validations/Functions/baseRealizationFunction";\r
+        public static final String Validations_Functions_path = "http://www.simantics.org/Sysdyn-1.1/Validations/Functions/path";\r
+        public static final String Validations_InvalidSheetReferenceIssue = "http://www.simantics.org/Sysdyn-1.1/Validations/InvalidSheetReferenceIssue";\r
+        public static final String Validations_Issue = "http://www.simantics.org/Sysdyn-1.1/Validations/Issue";\r
+        public static final String Validations_Issue_stringContexts = "http://www.simantics.org/Sysdyn-1.1/Validations/Issue/stringContexts";\r
+        public static final String Validations_Issue_stringContexts_Inverse = "http://www.simantics.org/Sysdyn-1.1/Validations/Issue/stringContexts/Inverse";\r
+        public static final String Validations_MissingDependencyConstraint = "http://www.simantics.org/Sysdyn-1.1/Validations/MissingDependencyConstraint";\r
+        public static final String Validations_MissingLinkIssue = "http://www.simantics.org/Sysdyn-1.1/Validations/MissingLinkIssue";\r
+        public static final String Validations_ModuleInputUnitWarning = "http://www.simantics.org/Sysdyn-1.1/Validations/ModuleInputUnitWarning";\r
+        public static final String Validations_ModuleOutputUnitWarning = "http://www.simantics.org/Sysdyn-1.1/Validations/ModuleOutputUnitWarning";\r
+        public static final String Validations_NoSuchVariableIssue = "http://www.simantics.org/Sysdyn-1.1/Validations/NoSuchVariableIssue";\r
+        public static final String Validations_RangeIssue = "http://www.simantics.org/Sysdyn-1.1/Validations/RangeIssue";\r
+        public static final String Validations_RangeWarning = "http://www.simantics.org/Sysdyn-1.1/Validations/RangeWarning";\r
+        public static final String Validations_UnitConstraint = "http://www.simantics.org/Sysdyn-1.1/Validations/UnitConstraint";\r
+        public static final String Validations_UnitWarning = "http://www.simantics.org/Sysdyn-1.1/Validations/UnitWarning";\r
+        public static final String Validations_Units = "http://www.simantics.org/Sysdyn-1.1/Validations/Units";\r
+        public static final String Validations_Units_UnitIssueSource = "http://www.simantics.org/Sysdyn-1.1/Validations/Units/UnitIssueSource";\r
+        public static final String Validations_Units_UnitIssueSource_allowEquivalents = "http://www.simantics.org/Sysdyn-1.1/Validations/Units/UnitIssueSource/allowEquivalents";\r
+        public static final String Validations_Units_UnitIssueSource_allowEquivalents_Inverse = "http://www.simantics.org/Sysdyn-1.1/Validations/Units/UnitIssueSource/allowEquivalents/Inverse";\r
+        public static final String Validations_Units_moduleInputUnitWarningDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Units/moduleInputUnitWarningDescription";\r
+        public static final String Validations_Units_moduleInterfaceExtension = "http://www.simantics.org/Sysdyn-1.1/Validations/Units/moduleInterfaceExtension";\r
+        public static final String Validations_Units_moduleOutputUnitWarningDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Units/moduleOutputUnitWarningDescription";\r
+        public static final String Validations_Units_unitValidator = "http://www.simantics.org/Sysdyn-1.1/Validations/Units/unitValidator";\r
+        public static final String Validations_Units_unitWarningDescription = "http://www.simantics.org/Sysdyn-1.1/Validations/Units/unitWarningDescription";\r
+        public static final String Validations_UnusedDependencyIssue = "http://www.simantics.org/Sysdyn-1.1/Validations/UnusedDependencyIssue";\r
+        public static final String Validations_constraint = "http://www.simantics.org/Sysdyn-1.1/Validations/constraint";\r
+        public static final String Validations_issue = "http://www.simantics.org/Sysdyn-1.1/Validations/issue";\r
+        public static final String Validations_listeningConstraint = "http://www.simantics.org/Sysdyn-1.1/Validations/listeningConstraint";\r
+        public static final String ValueGeneratorMethod = "http://www.simantics.org/Sysdyn-1.1/ValueGeneratorMethod";\r
+        public static final String Valve = "http://www.simantics.org/Sysdyn-1.1/Valve";\r
+        public static final String ValveSymbol = "http://www.simantics.org/Sysdyn-1.1/ValveSymbol";\r
+        public static final String ValveSymbol_orientation = "http://www.simantics.org/Sysdyn-1.1/ValveSymbol/orientation";\r
+        public static final String ValveSymbol_textLocation = "http://www.simantics.org/Sysdyn-1.1/ValveSymbol/textLocation";\r
+        public static final String Variable = "http://www.simantics.org/Sysdyn-1.1/Variable";\r
+        public static final String Variable_HasHead = "http://www.simantics.org/Sysdyn-1.1/Variable/HasHead";\r
+        public static final String Variable_HasTail = "http://www.simantics.org/Sysdyn-1.1/Variable/HasTail";\r
+        public static final String Variable_activeDatasets = "http://www.simantics.org/Sysdyn-1.1/Variable/activeDatasets";\r
+        public static final String Variable_activeDatasets_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/activeDatasets/Inverse";\r
+        public static final String Variable_arrayIndexes = "http://www.simantics.org/Sysdyn-1.1/Variable/arrayIndexes";\r
+        public static final String Variable_arrayIndexesList = "http://www.simantics.org/Sysdyn-1.1/Variable/arrayIndexesList";\r
+        public static final String Variable_arrayIndexesList_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/arrayIndexesList/Inverse";\r
+        public static final String Variable_arrayIndexes_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/arrayIndexes/Inverse";\r
+        public static final String Variable_equation = "http://www.simantics.org/Sysdyn-1.1/Variable/equation";\r
+        public static final String Variable_equation_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/equation/Inverse";\r
+        public static final String Variable_expressionList = "http://www.simantics.org/Sysdyn-1.1/Variable/expressionList";\r
+        public static final String Variable_expressionList_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/expressionList/Inverse";\r
+        public static final String Variable_expressions = "http://www.simantics.org/Sysdyn-1.1/Variable/expressions";\r
+        public static final String Variable_expressions_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/expressions/Inverse";\r
+        public static final String Variable_isHeadOf = "http://www.simantics.org/Sysdyn-1.1/Variable/isHeadOf";\r
+        public static final String Variable_isTailOf = "http://www.simantics.org/Sysdyn-1.1/Variable/isTailOf";\r
+        public static final String Variable_names = "http://www.simantics.org/Sysdyn-1.1/Variable/names";\r
+        public static final String Variable_names_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/names/Inverse";\r
+        public static final String Variable_time = "http://www.simantics.org/Sysdyn-1.1/Variable/time";\r
+        public static final String Variable_time_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/time/Inverse";\r
+        public static final String Variable_times = "http://www.simantics.org/Sysdyn-1.1/Variable/times";\r
+        public static final String Variable_times_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/times/Inverse";\r
+        public static final String Variable_type = "http://www.simantics.org/Sysdyn-1.1/Variable/type";\r
+        public static final String Variable_type_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/type/Inverse";\r
+        public static final String Variable_unit = "http://www.simantics.org/Sysdyn-1.1/Variable/unit";\r
+        public static final String Variable_unit_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/unit/Inverse";\r
+        public static final String Variable_value = "http://www.simantics.org/Sysdyn-1.1/Variable/value";\r
+        public static final String Variable_value_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/value/Inverse";\r
+        public static final String Variable_values = "http://www.simantics.org/Sysdyn-1.1/Variable/values";\r
+        public static final String Variable_values_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/values/Inverse";\r
+        public static final String Variable_variability = "http://www.simantics.org/Sysdyn-1.1/Variable/variability";\r
+        public static final String Variable_variability_Inverse = "http://www.simantics.org/Sysdyn-1.1/Variable/variability/Inverse";\r
+        public static final String Vertical = "http://www.simantics.org/Sysdyn-1.1/Vertical";\r
+        public static final String WithLookupExpression = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression";\r
+        public static final String WithLookupExpression_expression = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression/expression";\r
+        public static final String WithLookupExpression_expression_Inverse = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression/expression/Inverse";\r
+        public static final String WithLookupExpression_lookup = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression/lookup";\r
+        public static final String WithLookupExpression_lookup_Inverse = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression/lookup/Inverse";\r
+        public static final String WithLookupExpression_maxX = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression/maxX";\r
+        public static final String WithLookupExpression_maxY = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression/maxY";\r
+        public static final String WithLookupExpression_minX = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression/minX";\r
+        public static final String WithLookupExpression_minY = "http://www.simantics.org/Sysdyn-1.1/WithLookupExpression/minY";\r
+    }\r
+    \r
+    public static Resource getResourceOrNull(ReadGraph graph, String uri) {\r
+        try {\r
+            return graph.getResource(uri);\r
+        } catch(DatabaseException e) {\r
+            System.err.println(e.getMessage());\r
+            return null;\r
+        }\r
+    }\r
+    \r
+    public SysdynResource(ReadGraph graph) {\r
+        AdditionalSymbols = getResourceOrNull(graph, URIs.AdditionalSymbols);\r
+        AdditionalSymbols_MultilineText = getResourceOrNull(graph, URIs.AdditionalSymbols_MultilineText);\r
+        AllElementsGroup = getResourceOrNull(graph, URIs.AllElementsGroup);\r
+        ArrayIndexes = getResourceOrNull(graph, URIs.ArrayIndexes);\r
+        ArrayIndexes_Inverse = getResourceOrNull(graph, URIs.ArrayIndexes_Inverse);\r
+        Auxiliary = getResourceOrNull(graph, URIs.Auxiliary);\r
+        AuxiliarySymbol = getResourceOrNull(graph, URIs.AuxiliarySymbol);\r
+        AvailableSharedFunctionLibraries = getResourceOrNull(graph, URIs.AvailableSharedFunctionLibraries);\r
+        AvailableVariableIndexes = getResourceOrNull(graph, URIs.AvailableVariableIndexes);\r
+        BasicExperiment = getResourceOrNull(graph, URIs.BasicExperiment);\r
+        Bottom = getResourceOrNull(graph, URIs.Bottom);\r
+        Browser = getResourceOrNull(graph, URIs.Browser);\r
+        Built$in_Functions = getResourceOrNull(graph, URIs.Built$in_Functions);\r
+        Built$in_Functions_Modelica_Array_Functions = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions);\r
+        Built$in_Functions_Modelica_Array_Functions_array = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_array);\r
+        Built$in_Functions_Modelica_Array_Functions_array_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_array_A);\r
+        Built$in_Functions_Modelica_Array_Functions_array_A_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_array_A_A);\r
+        Built$in_Functions_Modelica_Array_Functions_array_A_B = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_array_A_B);\r
+        Built$in_Functions_Modelica_Array_Functions_array_A_C = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_array_A_C);\r
+        Built$in_Functions_Modelica_Array_Functions_array_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_array_result);\r
+        Built$in_Functions_Modelica_Array_Functions_cat = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cat);\r
+        Built$in_Functions_Modelica_Array_Functions_cat_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cat_A);\r
+        Built$in_Functions_Modelica_Array_Functions_cat_A_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cat_A_A);\r
+        Built$in_Functions_Modelica_Array_Functions_cat_A_B = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cat_A_B);\r
+        Built$in_Functions_Modelica_Array_Functions_cat_A_C = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cat_A_C);\r
+        Built$in_Functions_Modelica_Array_Functions_cat_k = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cat_k);\r
+        Built$in_Functions_Modelica_Array_Functions_cat_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cat_result);\r
+        Built$in_Functions_Modelica_Array_Functions_cross = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cross);\r
+        Built$in_Functions_Modelica_Array_Functions_cross_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cross_result);\r
+        Built$in_Functions_Modelica_Array_Functions_cross_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cross_x);\r
+        Built$in_Functions_Modelica_Array_Functions_cross_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_cross_y);\r
+        Built$in_Functions_Modelica_Array_Functions_diagonal = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_diagonal);\r
+        Built$in_Functions_Modelica_Array_Functions_diagonal_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_diagonal_result);\r
+        Built$in_Functions_Modelica_Array_Functions_diagonal_v = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_diagonal_v);\r
+        Built$in_Functions_Modelica_Array_Functions_fill = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_fill);\r
+        Built$in_Functions_Modelica_Array_Functions_fill_n = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_fill_n);\r
+        Built$in_Functions_Modelica_Array_Functions_fill_n_n1 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_fill_n_n1);\r
+        Built$in_Functions_Modelica_Array_Functions_fill_n_n2 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_fill_n_n2);\r
+        Built$in_Functions_Modelica_Array_Functions_fill_n_n3 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_fill_n_n3);\r
+        Built$in_Functions_Modelica_Array_Functions_fill_o = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_fill_o);\r
+        Built$in_Functions_Modelica_Array_Functions_fill_s = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_fill_s);\r
+        Built$in_Functions_Modelica_Array_Functions_identity = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_identity);\r
+        Built$in_Functions_Modelica_Array_Functions_identity_n = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_identity_n);\r
+        Built$in_Functions_Modelica_Array_Functions_identity_outArray = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_identity_outArray);\r
+        Built$in_Functions_Modelica_Array_Functions_linspace = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_linspace);\r
+        Built$in_Functions_Modelica_Array_Functions_linspace_n = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_linspace_n);\r
+        Built$in_Functions_Modelica_Array_Functions_linspace_v = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_linspace_v);\r
+        Built$in_Functions_Modelica_Array_Functions_linspace_x1 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_linspace_x1);\r
+        Built$in_Functions_Modelica_Array_Functions_linspace_x2 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_linspace_x2);\r
+        Built$in_Functions_Modelica_Array_Functions_matrix = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_matrix);\r
+        Built$in_Functions_Modelica_Array_Functions_matrix_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_matrix_A);\r
+        Built$in_Functions_Modelica_Array_Functions_matrix_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_matrix_result);\r
+        Built$in_Functions_Modelica_Array_Functions_max = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_max);\r
+        Built$in_Functions_Modelica_Array_Functions_max_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_max_A);\r
+        Built$in_Functions_Modelica_Array_Functions_max_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_max_result);\r
+        Built$in_Functions_Modelica_Array_Functions_min = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_min);\r
+        Built$in_Functions_Modelica_Array_Functions_min_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_min_A);\r
+        Built$in_Functions_Modelica_Array_Functions_min_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_min_result);\r
+        Built$in_Functions_Modelica_Array_Functions_ndims = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ndims);\r
+        Built$in_Functions_Modelica_Array_Functions_ndims_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ndims_A);\r
+        Built$in_Functions_Modelica_Array_Functions_ndims_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ndims_result);\r
+        Built$in_Functions_Modelica_Array_Functions_ones = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ones);\r
+        Built$in_Functions_Modelica_Array_Functions_ones_n = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ones_n);\r
+        Built$in_Functions_Modelica_Array_Functions_ones_n_n1 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ones_n_n1);\r
+        Built$in_Functions_Modelica_Array_Functions_ones_n_n2 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ones_n_n2);\r
+        Built$in_Functions_Modelica_Array_Functions_ones_n_n3 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ones_n_n3);\r
+        Built$in_Functions_Modelica_Array_Functions_ones_o = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_ones_o);\r
+        Built$in_Functions_Modelica_Array_Functions_product = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_product);\r
+        Built$in_Functions_Modelica_Array_Functions_product_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_product_A);\r
+        Built$in_Functions_Modelica_Array_Functions_product_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_product_result);\r
+        Built$in_Functions_Modelica_Array_Functions_scalar = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_scalar);\r
+        Built$in_Functions_Modelica_Array_Functions_scalar_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_scalar_A);\r
+        Built$in_Functions_Modelica_Array_Functions_scalar_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_scalar_result);\r
+        Built$in_Functions_Modelica_Array_Functions_size = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_size);\r
+        Built$in_Functions_Modelica_Array_Functions_size_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_size_A);\r
+        Built$in_Functions_Modelica_Array_Functions_size_i = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_size_i);\r
+        Built$in_Functions_Modelica_Array_Functions_size_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_size_result);\r
+        Built$in_Functions_Modelica_Array_Functions_skew = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_skew);\r
+        Built$in_Functions_Modelica_Array_Functions_skew_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_skew_result);\r
+        Built$in_Functions_Modelica_Array_Functions_skew_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_skew_x);\r
+        Built$in_Functions_Modelica_Array_Functions_sum = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_sum);\r
+        Built$in_Functions_Modelica_Array_Functions_sum_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_sum_A);\r
+        Built$in_Functions_Modelica_Array_Functions_sum_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_sum_result);\r
+        Built$in_Functions_Modelica_Array_Functions_transpose = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_transpose);\r
+        Built$in_Functions_Modelica_Array_Functions_transpose_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_transpose_A);\r
+        Built$in_Functions_Modelica_Array_Functions_transpose_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_transpose_result);\r
+        Built$in_Functions_Modelica_Array_Functions_vector = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_vector);\r
+        Built$in_Functions_Modelica_Array_Functions_vector_A = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_vector_A);\r
+        Built$in_Functions_Modelica_Array_Functions_vector_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_vector_result);\r
+        Built$in_Functions_Modelica_Array_Functions_zeros = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_zeros);\r
+        Built$in_Functions_Modelica_Array_Functions_zeros_n = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_zeros_n);\r
+        Built$in_Functions_Modelica_Array_Functions_zeros_n_n1 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_zeros_n_n1);\r
+        Built$in_Functions_Modelica_Array_Functions_zeros_n_n2 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_zeros_n_n2);\r
+        Built$in_Functions_Modelica_Array_Functions_zeros_n_n3 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_zeros_n_n3);\r
+        Built$in_Functions_Modelica_Array_Functions_zeros_o = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Array_Functions_zeros_o);\r
+        Built$in_Functions_Modelica_Functions = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions);\r
+        Built$in_Functions_Modelica_Functions_abs = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_abs);\r
+        Built$in_Functions_Modelica_Functions_abs_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_abs_result);\r
+        Built$in_Functions_Modelica_Functions_abs_v = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_abs_v);\r
+        Built$in_Functions_Modelica_Functions_acos = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_acos);\r
+        Built$in_Functions_Modelica_Functions_acos_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_acos_u);\r
+        Built$in_Functions_Modelica_Functions_acos_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_acos_y);\r
+        Built$in_Functions_Modelica_Functions_asin = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_asin);\r
+        Built$in_Functions_Modelica_Functions_asin_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_asin_u);\r
+        Built$in_Functions_Modelica_Functions_asin_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_asin_y);\r
+        Built$in_Functions_Modelica_Functions_atan = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_atan);\r
+        Built$in_Functions_Modelica_Functions_atan2 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_atan2);\r
+        Built$in_Functions_Modelica_Functions_atan2_u1 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_atan2_u1);\r
+        Built$in_Functions_Modelica_Functions_atan2_u2 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_atan2_u2);\r
+        Built$in_Functions_Modelica_Functions_atan2_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_atan2_y);\r
+        Built$in_Functions_Modelica_Functions_atan_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_atan_u);\r
+        Built$in_Functions_Modelica_Functions_atan_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_atan_y);\r
+        Built$in_Functions_Modelica_Functions_ceil = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_ceil);\r
+        Built$in_Functions_Modelica_Functions_ceil_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_ceil_x);\r
+        Built$in_Functions_Modelica_Functions_ceil_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_ceil_y);\r
+        Built$in_Functions_Modelica_Functions_cos = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_cos);\r
+        Built$in_Functions_Modelica_Functions_cos_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_cos_u);\r
+        Built$in_Functions_Modelica_Functions_cos_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_cos_y);\r
+        Built$in_Functions_Modelica_Functions_cosh = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_cosh);\r
+        Built$in_Functions_Modelica_Functions_cosh_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_cosh_u);\r
+        Built$in_Functions_Modelica_Functions_cosh_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_cosh_y);\r
+        Built$in_Functions_Modelica_Functions_delay = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_delay);\r
+        Built$in_Functions_Modelica_Functions_delay_delayMax = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_delay_delayMax);\r
+        Built$in_Functions_Modelica_Functions_delay_delayTime = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_delay_delayTime);\r
+        Built$in_Functions_Modelica_Functions_delay_expr = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_delay_expr);\r
+        Built$in_Functions_Modelica_Functions_delay_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_delay_result);\r
+        Built$in_Functions_Modelica_Functions_der = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_der);\r
+        Built$in_Functions_Modelica_Functions_der_dexpr = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_der_dexpr);\r
+        Built$in_Functions_Modelica_Functions_der_expr = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_der_expr);\r
+        Built$in_Functions_Modelica_Functions_div = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_div);\r
+        Built$in_Functions_Modelica_Functions_div_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_div_result);\r
+        Built$in_Functions_Modelica_Functions_div_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_div_x);\r
+        Built$in_Functions_Modelica_Functions_div_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_div_y);\r
+        Built$in_Functions_Modelica_Functions_edge = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_edge);\r
+        Built$in_Functions_Modelica_Functions_edge_b = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_edge_b);\r
+        Built$in_Functions_Modelica_Functions_edge_edgeEvent = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_edge_edgeEvent);\r
+        Built$in_Functions_Modelica_Functions_exp = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_exp);\r
+        Built$in_Functions_Modelica_Functions_exp_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_exp_u);\r
+        Built$in_Functions_Modelica_Functions_exp_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_exp_y);\r
+        Built$in_Functions_Modelica_Functions_floor = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_floor);\r
+        Built$in_Functions_Modelica_Functions_floor_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_floor_x);\r
+        Built$in_Functions_Modelica_Functions_floor_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_floor_y);\r
+        Built$in_Functions_Modelica_Functions_initial = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_initial);\r
+        Built$in_Functions_Modelica_Functions_initial_isInitial = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_initial_isInitial);\r
+        Built$in_Functions_Modelica_Functions_log = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_log);\r
+        Built$in_Functions_Modelica_Functions_log10 = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_log10);\r
+        Built$in_Functions_Modelica_Functions_log10_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_log10_u);\r
+        Built$in_Functions_Modelica_Functions_log10_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_log10_y);\r
+        Built$in_Functions_Modelica_Functions_log_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_log_u);\r
+        Built$in_Functions_Modelica_Functions_log_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_log_y);\r
+        Built$in_Functions_Modelica_Functions_max = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_max);\r
+        Built$in_Functions_Modelica_Functions_max_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_max_result);\r
+        Built$in_Functions_Modelica_Functions_max_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_max_x);\r
+        Built$in_Functions_Modelica_Functions_max_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_max_y);\r
+        Built$in_Functions_Modelica_Functions_min = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_min);\r
+        Built$in_Functions_Modelica_Functions_min_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_min_result);\r
+        Built$in_Functions_Modelica_Functions_min_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_min_x);\r
+        Built$in_Functions_Modelica_Functions_min_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_min_y);\r
+        Built$in_Functions_Modelica_Functions_mod = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_mod);\r
+        Built$in_Functions_Modelica_Functions_mod_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_mod_result);\r
+        Built$in_Functions_Modelica_Functions_mod_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_mod_x);\r
+        Built$in_Functions_Modelica_Functions_mod_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_mod_y);\r
+        Built$in_Functions_Modelica_Functions_noEvent = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_noEvent);\r
+        Built$in_Functions_Modelica_Functions_noEvent_expr = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_noEvent_expr);\r
+        Built$in_Functions_Modelica_Functions_noEvent_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_noEvent_result);\r
+        Built$in_Functions_Modelica_Functions_pre = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_pre);\r
+        Built$in_Functions_Modelica_Functions_pre_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_pre_result);\r
+        Built$in_Functions_Modelica_Functions_pre_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_pre_y);\r
+        Built$in_Functions_Modelica_Functions_rem = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_rem);\r
+        Built$in_Functions_Modelica_Functions_rem_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_rem_result);\r
+        Built$in_Functions_Modelica_Functions_rem_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_rem_x);\r
+        Built$in_Functions_Modelica_Functions_rem_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_rem_y);\r
+        Built$in_Functions_Modelica_Functions_sample = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sample);\r
+        Built$in_Functions_Modelica_Functions_sample_interval = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sample_interval);\r
+        Built$in_Functions_Modelica_Functions_sample_isSample = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sample_isSample);\r
+        Built$in_Functions_Modelica_Functions_sample_start = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sample_start);\r
+        Built$in_Functions_Modelica_Functions_semiLinear = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_semiLinear);\r
+        Built$in_Functions_Modelica_Functions_semiLinear_negativeSlope = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_semiLinear_negativeSlope);\r
+        Built$in_Functions_Modelica_Functions_semiLinear_positiveSlope = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_semiLinear_positiveSlope);\r
+        Built$in_Functions_Modelica_Functions_semiLinear_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_semiLinear_result);\r
+        Built$in_Functions_Modelica_Functions_semiLinear_x = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_semiLinear_x);\r
+        Built$in_Functions_Modelica_Functions_sign = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sign);\r
+        Built$in_Functions_Modelica_Functions_sign_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sign_result);\r
+        Built$in_Functions_Modelica_Functions_sign_v = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sign_v);\r
+        Built$in_Functions_Modelica_Functions_sin = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sin);\r
+        Built$in_Functions_Modelica_Functions_sin_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sin_u);\r
+        Built$in_Functions_Modelica_Functions_sin_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sin_y);\r
+        Built$in_Functions_Modelica_Functions_sinh = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sinh);\r
+        Built$in_Functions_Modelica_Functions_sinh_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sinh_u);\r
+        Built$in_Functions_Modelica_Functions_sinh_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sinh_y);\r
+        Built$in_Functions_Modelica_Functions_smooth = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_smooth);\r
+        Built$in_Functions_Modelica_Functions_smooth_expr = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_smooth_expr);\r
+        Built$in_Functions_Modelica_Functions_smooth_p = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_smooth_p);\r
+        Built$in_Functions_Modelica_Functions_smooth_result = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_smooth_result);\r
+        Built$in_Functions_Modelica_Functions_sqrt = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sqrt);\r
+        Built$in_Functions_Modelica_Functions_sqrt_v = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sqrt_v);\r
+        Built$in_Functions_Modelica_Functions_sqrt_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_sqrt_y);\r
+        Built$in_Functions_Modelica_Functions_tan = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_tan);\r
+        Built$in_Functions_Modelica_Functions_tan_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_tan_u);\r
+        Built$in_Functions_Modelica_Functions_tan_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_tan_y);\r
+        Built$in_Functions_Modelica_Functions_tanh = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_tanh);\r
+        Built$in_Functions_Modelica_Functions_tanh_u = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_tanh_u);\r
+        Built$in_Functions_Modelica_Functions_tanh_y = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_tanh_y);\r
+        Built$in_Functions_Modelica_Functions_terminal = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_terminal);\r
+        Built$in_Functions_Modelica_Functions_terminal_isTerminal = getResourceOrNull(graph, URIs.Built$in_Functions_Modelica_Functions_terminal_isTerminal);\r
+        Built$in_Functions_Vensim_Functions = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions);\r
+        Built$in_Functions_Vensim_Functions_ABS = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ABS);\r
+        Built$in_Functions_Vensim_Functions_ABS_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ABS_x);\r
+        Built$in_Functions_Vensim_Functions_ABS_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ABS_z);\r
+        Built$in_Functions_Vensim_Functions_COS = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_COS);\r
+        Built$in_Functions_Vensim_Functions_COSH = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_COSH);\r
+        Built$in_Functions_Vensim_Functions_COSH_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_COSH_x);\r
+        Built$in_Functions_Vensim_Functions_COSH_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_COSH_z);\r
+        Built$in_Functions_Vensim_Functions_COS_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_COS_x);\r
+        Built$in_Functions_Vensim_Functions_COS_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_COS_z);\r
+        Built$in_Functions_Vensim_Functions_EXP = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_EXP);\r
+        Built$in_Functions_Vensim_Functions_EXP_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_EXP_x);\r
+        Built$in_Functions_Vensim_Functions_EXP_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_EXP_z);\r
+        Built$in_Functions_Vensim_Functions_GAME = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_GAME);\r
+        Built$in_Functions_Vensim_Functions_GAME_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_GAME_x);\r
+        Built$in_Functions_Vensim_Functions_GAME_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_GAME_z);\r
+        Built$in_Functions_Vensim_Functions_IFTHENELSE = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_IFTHENELSE);\r
+        Built$in_Functions_Vensim_Functions_IFTHENELSE_cond = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_IFTHENELSE_cond);\r
+        Built$in_Functions_Vensim_Functions_IFTHENELSE_onfalse = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_IFTHENELSE_onfalse);\r
+        Built$in_Functions_Vensim_Functions_IFTHENELSE_ontrue = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_IFTHENELSE_ontrue);\r
+        Built$in_Functions_Vensim_Functions_IFTHENELSE_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_IFTHENELSE_z);\r
+        Built$in_Functions_Vensim_Functions_LN = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_LN);\r
+        Built$in_Functions_Vensim_Functions_LN_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_LN_x);\r
+        Built$in_Functions_Vensim_Functions_LN_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_LN_z);\r
+        Built$in_Functions_Vensim_Functions_MAX = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MAX);\r
+        Built$in_Functions_Vensim_Functions_MAX_a = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MAX_a);\r
+        Built$in_Functions_Vensim_Functions_MAX_b = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MAX_b);\r
+        Built$in_Functions_Vensim_Functions_MAX_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MAX_z);\r
+        Built$in_Functions_Vensim_Functions_MIN = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MIN);\r
+        Built$in_Functions_Vensim_Functions_MIN_a = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MIN_a);\r
+        Built$in_Functions_Vensim_Functions_MIN_b = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MIN_b);\r
+        Built$in_Functions_Vensim_Functions_MIN_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MIN_z);\r
+        Built$in_Functions_Vensim_Functions_MODULO = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MODULO);\r
+        Built$in_Functions_Vensim_Functions_MODULO_a = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MODULO_a);\r
+        Built$in_Functions_Vensim_Functions_MODULO_b = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MODULO_b);\r
+        Built$in_Functions_Vensim_Functions_MODULO_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_MODULO_z);\r
+        Built$in_Functions_Vensim_Functions_PULSE = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_PULSE);\r
+        Built$in_Functions_Vensim_Functions_PULSE_start = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_PULSE_start);\r
+        Built$in_Functions_Vensim_Functions_PULSE_width = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_PULSE_width);\r
+        Built$in_Functions_Vensim_Functions_PULSE_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_PULSE_z);\r
+        Built$in_Functions_Vensim_Functions_RAMP = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_RAMP);\r
+        Built$in_Functions_Vensim_Functions_RAMP_endTime = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_RAMP_endTime);\r
+        Built$in_Functions_Vensim_Functions_RAMP_slope = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_RAMP_slope);\r
+        Built$in_Functions_Vensim_Functions_RAMP_startTime = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_RAMP_startTime);\r
+        Built$in_Functions_Vensim_Functions_RAMP_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_RAMP_z);\r
+        Built$in_Functions_Vensim_Functions_SIN = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SIN);\r
+        Built$in_Functions_Vensim_Functions_SINH = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SINH);\r
+        Built$in_Functions_Vensim_Functions_SINH_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SINH_x);\r
+        Built$in_Functions_Vensim_Functions_SINH_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SINH_z);\r
+        Built$in_Functions_Vensim_Functions_SIN_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SIN_x);\r
+        Built$in_Functions_Vensim_Functions_SIN_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SIN_z);\r
+        Built$in_Functions_Vensim_Functions_SQRT = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SQRT);\r
+        Built$in_Functions_Vensim_Functions_SQRT_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SQRT_x);\r
+        Built$in_Functions_Vensim_Functions_SQRT_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_SQRT_z);\r
+        Built$in_Functions_Vensim_Functions_STEP = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_STEP);\r
+        Built$in_Functions_Vensim_Functions_STEP_height = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_STEP_height);\r
+        Built$in_Functions_Vensim_Functions_STEP_stepTime = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_STEP_stepTime);\r
+        Built$in_Functions_Vensim_Functions_STEP_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_STEP_z);\r
+        Built$in_Functions_Vensim_Functions_TAN = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_TAN);\r
+        Built$in_Functions_Vensim_Functions_TANH = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_TANH);\r
+        Built$in_Functions_Vensim_Functions_TANH_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_TANH_x);\r
+        Built$in_Functions_Vensim_Functions_TANH_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_TANH_z);\r
+        Built$in_Functions_Vensim_Functions_TAN_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_TAN_x);\r
+        Built$in_Functions_Vensim_Functions_TAN_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_TAN_z);\r
+        Built$in_Functions_Vensim_Functions_XIDZ = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_XIDZ);\r
+        Built$in_Functions_Vensim_Functions_XIDZ_a = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_XIDZ_a);\r
+        Built$in_Functions_Vensim_Functions_XIDZ_b = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_XIDZ_b);\r
+        Built$in_Functions_Vensim_Functions_XIDZ_x = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_XIDZ_x);\r
+        Built$in_Functions_Vensim_Functions_XIDZ_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_XIDZ_z);\r
+        Built$in_Functions_Vensim_Functions_ZIDZ = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ZIDZ);\r
+        Built$in_Functions_Vensim_Functions_ZIDZ_a = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ZIDZ_a);\r
+        Built$in_Functions_Vensim_Functions_ZIDZ_b = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ZIDZ_b);\r
+        Built$in_Functions_Vensim_Functions_ZIDZ_z = getResourceOrNull(graph, URIs.Built$in_Functions_Vensim_Functions_ZIDZ_z);\r
+        Built$in_Functions_interpolate = getResourceOrNull(graph, URIs.Built$in_Functions_interpolate);\r
+        Built$in_Functions_interpolateFull = getResourceOrNull(graph, URIs.Built$in_Functions_interpolateFull);\r
+        Built$in_Functions_interpolateFull_icol = getResourceOrNull(graph, URIs.Built$in_Functions_interpolateFull_icol);\r
+        Built$in_Functions_interpolateFull_table = getResourceOrNull(graph, URIs.Built$in_Functions_interpolateFull_table);\r
+        Built$in_Functions_interpolateFull_u = getResourceOrNull(graph, URIs.Built$in_Functions_interpolateFull_u);\r
+        Built$in_Functions_interpolateFull_y = getResourceOrNull(graph, URIs.Built$in_Functions_interpolateFull_y);\r
+        Built$in_Functions_interpolate_table = getResourceOrNull(graph, URIs.Built$in_Functions_interpolate_table);\r
+        Built$in_Functions_interpolate_u = getResourceOrNull(graph, URIs.Built$in_Functions_interpolate_u);\r
+        Built$in_Functions_interpolate_y = getResourceOrNull(graph, URIs.Built$in_Functions_interpolate_y);\r
+        Built$in_Functions_minmax = getResourceOrNull(graph, URIs.Built$in_Functions_minmax);\r
+        Built$in_Functions_minmax_expression = getResourceOrNull(graph, URIs.Built$in_Functions_minmax_expression);\r
+        Built$in_Functions_minmax_maximum = getResourceOrNull(graph, URIs.Built$in_Functions_minmax_maximum);\r
+        Built$in_Functions_minmax_minimum = getResourceOrNull(graph, URIs.Built$in_Functions_minmax_minimum);\r
+        Built$in_Functions_minmax_result = getResourceOrNull(graph, URIs.Built$in_Functions_minmax_result);\r
+        Built$in_Functions_unitCast = getResourceOrNull(graph, URIs.Built$in_Functions_unitCast);\r
+        Built$in_Functions_unitCast_u = getResourceOrNull(graph, URIs.Built$in_Functions_unitCast_u);\r
+        Built$in_Functions_unitCast_y = getResourceOrNull(graph, URIs.Built$in_Functions_unitCast_y);\r
+        Built$in_Functions_xidz = getResourceOrNull(graph, URIs.Built$in_Functions_xidz);\r
+        Built$in_Functions_xidz_divident = getResourceOrNull(graph, URIs.Built$in_Functions_xidz_divident);\r
+        Built$in_Functions_xidz_divisor = getResourceOrNull(graph, URIs.Built$in_Functions_xidz_divisor);\r
+        Built$in_Functions_xidz_x = getResourceOrNull(graph, URIs.Built$in_Functions_xidz_x);\r
+        Built$in_Functions_xidz_z = getResourceOrNull(graph, URIs.Built$in_Functions_xidz_z);\r
+        Built$in_Functions_zidz = getResourceOrNull(graph, URIs.Built$in_Functions_zidz);\r
+        Built$in_Functions_zidz_divident = getResourceOrNull(graph, URIs.Built$in_Functions_zidz_divident);\r
+        Built$in_Functions_zidz_divisor = getResourceOrNull(graph, URIs.Built$in_Functions_zidz_divisor);\r
+        Built$in_Functions_zidz_z = getResourceOrNull(graph, URIs.Built$in_Functions_zidz_z);\r
+        Center = getResourceOrNull(graph, URIs.Center);\r
+        Charts = getResourceOrNull(graph, URIs.Charts);\r
+        Charts_SensitivityDataset = getResourceOrNull(graph, URIs.Charts_SensitivityDataset);\r
+        Charts_SensitivityDataset_ConfidenceBound = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_ConfidenceBound);\r
+        Charts_SensitivityDataset_ConfidenceBound_color = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_ConfidenceBound_color);\r
+        Charts_SensitivityDataset_ConfidenceBound_color_Inverse = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_ConfidenceBound_color_Inverse);\r
+        Charts_SensitivityDataset_ConfidenceBound_percent = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_ConfidenceBound_percent);\r
+        Charts_SensitivityDataset_ConfidenceBound_percent_Inverse = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_ConfidenceBound_percent_Inverse);\r
+        Charts_SensitivityDataset_confidenceBounds = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_confidenceBounds);\r
+        Charts_SensitivityDataset_confidenceBounds_Inverse = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_confidenceBounds_Inverse);\r
+        Charts_SensitivityDataset_median = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_median);\r
+        Charts_SensitivityDataset_median_Inverse = getResourceOrNull(graph, URIs.Charts_SensitivityDataset_median_Inverse);\r
+        Charts_SensitivityPlot = getResourceOrNull(graph, URIs.Charts_SensitivityPlot);\r
+        Cloud = getResourceOrNull(graph, URIs.Cloud);\r
+        CloudSymbol = getResourceOrNull(graph, URIs.CloudSymbol);\r
+        Component = getResourceOrNull(graph, URIs.Component);\r
+        Configuration = getResourceOrNull(graph, URIs.Configuration);\r
+        ConfigurationDiagram = getResourceOrNull(graph, URIs.ConfigurationDiagram);\r
+        ConfigurationDiagramTemplate = getResourceOrNull(graph, URIs.ConfigurationDiagramTemplate);\r
+        ConfigurationDiagram_selection = getResourceOrNull(graph, URIs.ConfigurationDiagram_selection);\r
+        ConfigurationDiagram_selection_Inverse = getResourceOrNull(graph, URIs.ConfigurationDiagram_selection_Inverse);\r
+        ConstantExpression = getResourceOrNull(graph, URIs.ConstantExpression);\r
+        DefaultFont = getResourceOrNull(graph, URIs.DefaultFont);\r
+        DefaultProfile = getResourceOrNull(graph, URIs.DefaultProfile);\r
+        DefaultRealization = getResourceOrNull(graph, URIs.DefaultRealization);\r
+        DelayExpression = getResourceOrNull(graph, URIs.DelayExpression);\r
+        DelayExpression_delayTime = getResourceOrNull(graph, URIs.DelayExpression_delayTime);\r
+        DelayExpression_delayTime_Inverse = getResourceOrNull(graph, URIs.DelayExpression_delayTime_Inverse);\r
+        DelayExpression_expression = getResourceOrNull(graph, URIs.DelayExpression_expression);\r
+        DelayExpression_expression_Inverse = getResourceOrNull(graph, URIs.DelayExpression_expression_Inverse);\r
+        DelayExpression_initialValue = getResourceOrNull(graph, URIs.DelayExpression_initialValue);\r
+        DelayExpression_initialValue_Inverse = getResourceOrNull(graph, URIs.DelayExpression_initialValue_Inverse);\r
+        DelayExpression_isInformationDelay = getResourceOrNull(graph, URIs.DelayExpression_isInformationDelay);\r
+        DelayExpression_order = getResourceOrNull(graph, URIs.DelayExpression_order);\r
+        DelayExpression_order_Inverse = getResourceOrNull(graph, URIs.DelayExpression_order_Inverse);\r
+        Dependency = getResourceOrNull(graph, URIs.Dependency);\r
+        DependencyConnection = getResourceOrNull(graph, URIs.DependencyConnection);\r
+        DependencyConnection_delayMark = getResourceOrNull(graph, URIs.DependencyConnection_delayMark);\r
+        DependencyConnection_hideArrow = getResourceOrNull(graph, URIs.DependencyConnection_hideArrow);\r
+        DependencyConnection_polarity = getResourceOrNull(graph, URIs.DependencyConnection_polarity);\r
+        DependencyConnection_polarityLocation = getResourceOrNull(graph, URIs.DependencyConnection_polarityLocation);\r
+        DependencyConnection_polarityLocation_Inverse = getResourceOrNull(graph, URIs.DependencyConnection_polarityLocation_Inverse);\r
+        DependencyConnection_polarity_Inverse = getResourceOrNull(graph, URIs.DependencyConnection_polarity_Inverse);\r
+        DependencyConnection_strokeWidth = getResourceOrNull(graph, URIs.DependencyConnection_strokeWidth);\r
+        DependencyConnection_strokeWidth_Inverse = getResourceOrNull(graph, URIs.DependencyConnection_strokeWidth_Inverse);\r
+        Dependency_angle = getResourceOrNull(graph, URIs.Dependency_angle);\r
+        Dependency_angle_Inverse = getResourceOrNull(graph, URIs.Dependency_angle_Inverse);\r
+        Dependency_refersTo = getResourceOrNull(graph, URIs.Dependency_refersTo);\r
+        DiagramToCompositeMapping = getResourceOrNull(graph, URIs.DiagramToCompositeMapping);\r
+        Enumeration = getResourceOrNull(graph, URIs.Enumeration);\r
+        EnumerationIndex = getResourceOrNull(graph, URIs.EnumerationIndex);\r
+        EnumerationIndex_showEnumerationIndexInCharts = getResourceOrNull(graph, URIs.EnumerationIndex_showEnumerationIndexInCharts);\r
+        EnumerationIndex_showEnumerationIndexInCharts_Inverse = getResourceOrNull(graph, URIs.EnumerationIndex_showEnumerationIndexInCharts_Inverse);\r
+        EnumerationIndexes = getResourceOrNull(graph, URIs.EnumerationIndexes);\r
+        EnumerationIndexes_Inverse = getResourceOrNull(graph, URIs.EnumerationIndexes_Inverse);\r
+        EnumerationReplacement = getResourceOrNull(graph, URIs.EnumerationReplacement);\r
+        Enumeration_enumerationIndexList = getResourceOrNull(graph, URIs.Enumeration_enumerationIndexList);\r
+        Enumeration_enumerationIndexList_Inverse = getResourceOrNull(graph, URIs.Enumeration_enumerationIndexList_Inverse);\r
+        Enumeration_enumerationIndexes = getResourceOrNull(graph, URIs.Enumeration_enumerationIndexes);\r
+        Enumeration_enumerationIndexes_Inverse = getResourceOrNull(graph, URIs.Enumeration_enumerationIndexes_Inverse);\r
+        Enumeration_isReplaceable = getResourceOrNull(graph, URIs.Enumeration_isReplaceable);\r
+        Enumeration_isReplaceable_Inverse = getResourceOrNull(graph, URIs.Enumeration_isReplaceable_Inverse);\r
+        Experiment = getResourceOrNull(graph, URIs.Experiment);\r
+        Experiment_Run = getResourceOrNull(graph, URIs.Experiment_Run);\r
+        Experiment_Run_time = getResourceOrNull(graph, URIs.Experiment_Run_time);\r
+        Experiment_Run_time_Inverse = getResourceOrNull(graph, URIs.Experiment_Run_time_Inverse);\r
+        Experiment_ic = getResourceOrNull(graph, URIs.Experiment_ic);\r
+        Experiment_ic_Inverse = getResourceOrNull(graph, URIs.Experiment_ic_Inverse);\r
+        Experiment_result = getResourceOrNull(graph, URIs.Experiment_result);\r
+        Experiment_resultSet = getResourceOrNull(graph, URIs.Experiment_resultSet);\r
+        Experiment_resultSet_Inverse = getResourceOrNull(graph, URIs.Experiment_resultSet_Inverse);\r
+        Experiment_result_Inverse = getResourceOrNull(graph, URIs.Experiment_result_Inverse);\r
+        ExportModuleTree = getResourceOrNull(graph, URIs.ExportModuleTree);\r
+        Expression = getResourceOrNull(graph, URIs.Expression);\r
+        Expression_arrayRange = getResourceOrNull(graph, URIs.Expression_arrayRange);\r
+        Expression_arrayRange_Inverse = getResourceOrNull(graph, URIs.Expression_arrayRange_Inverse);\r
+        Expression_equation = getResourceOrNull(graph, URIs.Expression_equation);\r
+        Expression_equation_Inverse = getResourceOrNull(graph, URIs.Expression_equation_Inverse);\r
+        Expressions = getResourceOrNull(graph, URIs.Expressions);\r
+        Expressions_Inverse = getResourceOrNull(graph, URIs.Expressions_Inverse);\r
+        ExternalFiles = getResourceOrNull(graph, URIs.ExternalFiles);\r
+        ExternalFunctionFile = getResourceOrNull(graph, URIs.ExternalFunctionFile);\r
+        ExternalFunctionFile_externalFile = getResourceOrNull(graph, URIs.ExternalFunctionFile_externalFile);\r
+        ExternalFunctionFile_externalFile_Inverse = getResourceOrNull(graph, URIs.ExternalFunctionFile_externalFile_Inverse);\r
+        Flow = getResourceOrNull(graph, URIs.Flow);\r
+        FlowConnection = getResourceOrNull(graph, URIs.FlowConnection);\r
+        FlowConnection_width = getResourceOrNull(graph, URIs.FlowConnection_width);\r
+        FlowConnection_width_Inverse = getResourceOrNull(graph, URIs.FlowConnection_width_Inverse);\r
+        FunctionTree = getResourceOrNull(graph, URIs.FunctionTree);\r
+        Functions = getResourceOrNull(graph, URIs.Functions);\r
+        Functions_equationPropertyValue = getResourceOrNull(graph, URIs.Functions_equationPropertyValue);\r
+        Functions_runChildren = getResourceOrNull(graph, URIs.Functions_runChildren);\r
+        Functions_runProperties = getResourceOrNull(graph, URIs.Functions_runProperties);\r
+        Functions_valuePropertyProperties = getResourceOrNull(graph, URIs.Functions_valuePropertyProperties);\r
+        Functions_valuePropertyValue = getResourceOrNull(graph, URIs.Functions_valuePropertyValue);\r
+        GameExperiment = getResourceOrNull(graph, URIs.GameExperiment);\r
+        GameExperiment_stepDuration = getResourceOrNull(graph, URIs.GameExperiment_stepDuration);\r
+        GameExperiment_stepDuration_Inverse = getResourceOrNull(graph, URIs.GameExperiment_stepDuration_Inverse);\r
+        GameExperiment_stepLength = getResourceOrNull(graph, URIs.GameExperiment_stepLength);\r
+        GameExperiment_stepLength_Inverse = getResourceOrNull(graph, URIs.GameExperiment_stepLength_Inverse);\r
+        HaltonSequenceGenerator = getResourceOrNull(graph, URIs.HaltonSequenceGenerator);\r
+        HasEquationOrEmpty = getResourceOrNull(graph, URIs.HasEquationOrEmpty);\r
+        HasEquationOrEmpty_Inverse = getResourceOrNull(graph, URIs.HasEquationOrEmpty_Inverse);\r
+        HasHeadTerminal = getResourceOrNull(graph, URIs.HasHeadTerminal);\r
+        HasRangeEnd = getResourceOrNull(graph, URIs.HasRangeEnd);\r
+        HasRangeEnd_Inverse = getResourceOrNull(graph, URIs.HasRangeEnd_Inverse);\r
+        HasRangeStart = getResourceOrNull(graph, URIs.HasRangeStart);\r
+        HasRangeStart_Inverse = getResourceOrNull(graph, URIs.HasRangeStart_Inverse);\r
+        HasRangeStep = getResourceOrNull(graph, URIs.HasRangeStep);\r
+        HasRangeStep_Inverse = getResourceOrNull(graph, URIs.HasRangeStep_Inverse);\r
+        HasTailTerminal = getResourceOrNull(graph, URIs.HasTailTerminal);\r
+        HistoryDataset = getResourceOrNull(graph, URIs.HistoryDataset);\r
+        HistoryDataset_FoundVariableNameNode = getResourceOrNull(graph, URIs.HistoryDataset_FoundVariableNameNode);\r
+        HistoryDataset_HistoryDatasetVariablesBrowseContext = getResourceOrNull(graph, URIs.HistoryDataset_HistoryDatasetVariablesBrowseContext);\r
+        HistoryDataset_HistoryDatasetVariablesBrowseContext_StringNodeType = getResourceOrNull(graph, URIs.HistoryDataset_HistoryDatasetVariablesBrowseContext_StringNodeType);\r
+        HistoryDataset_HistoryDatasetVariablesBrowseContext_VariableChildRule = getResourceOrNull(graph, URIs.HistoryDataset_HistoryDatasetVariablesBrowseContext_VariableChildRule);\r
+        HistoryDataset_HistoryDatasetVariablesBrowseContext_VariableLabelRule = getResourceOrNull(graph, URIs.HistoryDataset_HistoryDatasetVariablesBrowseContext_VariableLabelRule);\r
+        HistoryDataset_columns = getResourceOrNull(graph, URIs.HistoryDataset_columns);\r
+        HistoryDataset_columns_Inverse = getResourceOrNull(graph, URIs.HistoryDataset_columns_Inverse);\r
+        HistoryDataset_end = getResourceOrNull(graph, URIs.HistoryDataset_end);\r
+        HistoryDataset_end_Inverse = getResourceOrNull(graph, URIs.HistoryDataset_end_Inverse);\r
+        HistoryDataset_sheet = getResourceOrNull(graph, URIs.HistoryDataset_sheet);\r
+        HistoryDataset_start = getResourceOrNull(graph, URIs.HistoryDataset_start);\r
+        HistoryDataset_start_Inverse = getResourceOrNull(graph, URIs.HistoryDataset_start_Inverse);\r
+        HistoryDataset_timeName = getResourceOrNull(graph, URIs.HistoryDataset_timeName);\r
+        HistoryDataset_timeName_Inverse = getResourceOrNull(graph, URIs.HistoryDataset_timeName_Inverse);\r
+        HistoryRealization = getResourceOrNull(graph, URIs.HistoryRealization);\r
+        Horizontal = getResourceOrNull(graph, URIs.Horizontal);\r
+        ImportModuleTree = getResourceOrNull(graph, URIs.ImportModuleTree);\r
+        ImportedOntologies = getResourceOrNull(graph, URIs.ImportedOntologies);\r
+        IndependentVariable = getResourceOrNull(graph, URIs.IndependentVariable);\r
+        IndependentVariable_activeExpression = getResourceOrNull(graph, URIs.IndependentVariable_activeExpression);\r
+        IndependentVariable_isUninitialized = getResourceOrNull(graph, URIs.IndependentVariable_isUninitialized);\r
+        IndependentVariable_isUninitialized_Inverse = getResourceOrNull(graph, URIs.IndependentVariable_isUninitialized_Inverse);\r
+        IndependentVariable_rangeEnd = getResourceOrNull(graph, URIs.IndependentVariable_rangeEnd);\r
+        IndependentVariable_rangeEnd_Inverse = getResourceOrNull(graph, URIs.IndependentVariable_rangeEnd_Inverse);\r
+        IndependentVariable_rangeStart = getResourceOrNull(graph, URIs.IndependentVariable_rangeStart);\r
+        IndependentVariable_rangeStart_Inverse = getResourceOrNull(graph, URIs.IndependentVariable_rangeStart_Inverse);\r
+        IndependentVariable_rangeStep = getResourceOrNull(graph, URIs.IndependentVariable_rangeStep);\r
+        IndependentVariable_rangeStep_Inverse = getResourceOrNull(graph, URIs.IndependentVariable_rangeStep_Inverse);\r
+        IndependentVariable_unit = getResourceOrNull(graph, URIs.IndependentVariable_unit);\r
+        IndependentVariable_unit_Inverse = getResourceOrNull(graph, URIs.IndependentVariable_unit_Inverse);\r
+        InitialCondition = getResourceOrNull(graph, URIs.InitialCondition);\r
+        InitialCondition_HasInitialValues = getResourceOrNull(graph, URIs.InitialCondition_HasInitialValues);\r
+        InitialCondition_HasInitialValues_Inverse = getResourceOrNull(graph, URIs.InitialCondition_HasInitialValues_Inverse);\r
+        Input = getResourceOrNull(graph, URIs.Input);\r
+        InputSymbol = getResourceOrNull(graph, URIs.InputSymbol);\r
+        Input_defaultInputValue = getResourceOrNull(graph, URIs.Input_defaultInputValue);\r
+        Input_defaultInputValue_Inverse = getResourceOrNull(graph, URIs.Input_defaultInputValue_Inverse);\r
+        Interval = getResourceOrNull(graph, URIs.Interval);\r
+        Interval_maxValue = getResourceOrNull(graph, URIs.Interval_maxValue);\r
+        Interval_maxValue_Inverse = getResourceOrNull(graph, URIs.Interval_maxValue_Inverse);\r
+        Interval_minValue = getResourceOrNull(graph, URIs.Interval_minValue);\r
+        Interval_minValue_Inverse = getResourceOrNull(graph, URIs.Interval_minValue_Inverse);\r
+        IsHeadOfTerminal = getResourceOrNull(graph, URIs.IsHeadOfTerminal);\r
+        IsOutput = getResourceOrNull(graph, URIs.IsOutput);\r
+        IsTailOfTerminal = getResourceOrNull(graph, URIs.IsTailOfTerminal);\r
+        IssueStyle = getResourceOrNull(graph, URIs.IssueStyle);\r
+        Left = getResourceOrNull(graph, URIs.Left);\r
+        Location = getResourceOrNull(graph, URIs.Location);\r
+        LookupExpression = getResourceOrNull(graph, URIs.LookupExpression);\r
+        LookupExpression_lookup = getResourceOrNull(graph, URIs.LookupExpression_lookup);\r
+        LookupExpression_lookup_Inverse = getResourceOrNull(graph, URIs.LookupExpression_lookup_Inverse);\r
+        Loop = getResourceOrNull(graph, URIs.Loop);\r
+        LoopSymbol = getResourceOrNull(graph, URIs.LoopSymbol);\r
+        LoopSymbol_Clockwise = getResourceOrNull(graph, URIs.LoopSymbol_Clockwise);\r
+        LoopSymbol_Clockwise_Inverse = getResourceOrNull(graph, URIs.LoopSymbol_Clockwise_Inverse);\r
+        Loop_Comment = getResourceOrNull(graph, URIs.Loop_Comment);\r
+        Loop_Comment_Inverse = getResourceOrNull(graph, URIs.Loop_Comment_Inverse);\r
+        Loop_Items = getResourceOrNull(graph, URIs.Loop_Items);\r
+        Loop_Items_Inverse = getResourceOrNull(graph, URIs.Loop_Items_Inverse);\r
+        Migration = getResourceOrNull(graph, URIs.Migration);\r
+        Migration_from1$6to1$7 = getResourceOrNull(graph, URIs.Migration_from1$6to1$7);\r
+        Migration_from1$6to1$7_Custom = getResourceOrNull(graph, URIs.Migration_from1$6to1$7_Custom);\r
+        Migration_from1$6to1$7_Ontologies = getResourceOrNull(graph, URIs.Migration_from1$6to1$7_Ontologies);\r
+        Migration_from1$6to1$7_OrderedSetsToLists = getResourceOrNull(graph, URIs.Migration_from1$6to1$7_OrderedSetsToLists);\r
+        Migration_from1$6to1$7_Spreadsheets = getResourceOrNull(graph, URIs.Migration_from1$6to1$7_Spreadsheets);\r
+        Migration_from1$6to1$7_SysdynChanges = getResourceOrNull(graph, URIs.Migration_from1$6to1$7_SysdynChanges);\r
+        Migration_fromFunctionLibrary1 = getResourceOrNull(graph, URIs.Migration_fromFunctionLibrary1);\r
+        Migration_fromModel1 = getResourceOrNull(graph, URIs.Migration_fromModel1);\r
+        Migration_fromModule1 = getResourceOrNull(graph, URIs.Migration_fromModule1);\r
+        ModelBrowser = getResourceOrNull(graph, URIs.ModelBrowser);\r
+        ModelingActionContext = getResourceOrNull(graph, URIs.ModelingActionContext);\r
+        ModelingActionContext_Actions = getResourceOrNull(graph, URIs.ModelingActionContext_Actions);\r
+        ModelingActionContext_Actions_ChartDropAction = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_ChartDropAction);\r
+        ModelingActionContext_Actions_FunctionDropAction = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_FunctionDropAction);\r
+        ModelingActionContext_Actions_NewBarChart = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewBarChart);\r
+        ModelingActionContext_Actions_NewEnumeration = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewEnumeration);\r
+        ModelingActionContext_Actions_NewExperiment = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewExperiment);\r
+        ModelingActionContext_Actions_NewFunction = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewFunction);\r
+        ModelingActionContext_Actions_NewFunctionLibrary = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewFunctionLibrary);\r
+        ModelingActionContext_Actions_NewHistoryData = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewHistoryData);\r
+        ModelingActionContext_Actions_NewLineChart = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewLineChart);\r
+        ModelingActionContext_Actions_NewModuleType = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewModuleType);\r
+        ModelingActionContext_Actions_NewPieChart = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewPieChart);\r
+        ModelingActionContext_Actions_NewSharedFunctionLibrary = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewSharedFunctionLibrary);\r
+        ModelingActionContext_Actions_NewSheet = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewSheet);\r
+        ModelingActionContext_Actions_NewSimulationPlaybackExperiment = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewSimulationPlaybackExperiment);\r
+        ModelingBrowseContext = getResourceOrNull(graph, URIs.ModelingBrowseContext);\r
+        ModelingBrowseContext_ActiveLabelDecorationRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_ActiveLabelDecorationRule);\r
+        ModelingBrowseContext_BuiltinFunctions = getResourceOrNull(graph, URIs.ModelingBrowseContext_BuiltinFunctions);\r
+        ModelingBrowseContext_ChartImageRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_ChartImageRule);\r
+        ModelingBrowseContext_ChartsFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_ChartsFolder);\r
+        ModelingBrowseContext_ExperimentsFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_ExperimentsFolder);\r
+        ModelingBrowseContext_FunctionsFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_FunctionsFolder);\r
+        ModelingBrowseContext_ModuleContentChildRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModuleContentChildRule);\r
+        ModelingBrowseContext_ModuleSymbol = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModuleSymbol);\r
+        ModelingBrowseContext_ModuleSymbolNodeType = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModuleSymbolNodeType);\r
+        ModelingBrowseContext_ModuleTypeChildRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModuleTypeChildRule);\r
+        ModelingBrowseContext_ModuleTypeLabelRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModuleTypeLabelRule);\r
+        ModelingBrowseContext_ModulesFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModulesFolder);\r
+        ModelingBrowseContext_ResultImageRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_ResultImageRule);\r
+        ModelingBrowseContext_SharedFunctionsFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_SharedFunctionsFolder);\r
+        ModelingBrowseContext_Variable = getResourceOrNull(graph, URIs.ModelingBrowseContext_Variable);\r
+        ModelingBrowseContext_VariableChildRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_VariableChildRule);\r
+        ModelingBrowseContext_VariableImageRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_VariableImageRule);\r
+        ModelingBrowseContext_VariableNameLabelRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_VariableNameLabelRule);\r
+        ModelingBrowseContext_VariableNodeType = getResourceOrNull(graph, URIs.ModelingBrowseContext_VariableNodeType);\r
+        Module = getResourceOrNull(graph, URIs.Module);\r
+        ModuleSymbol = getResourceOrNull(graph, URIs.ModuleSymbol);\r
+        Module_ParameterOverride = getResourceOrNull(graph, URIs.Module_ParameterOverride);\r
+        Module_ParameterOverrideBrowseContext = getResourceOrNull(graph, URIs.Module_ParameterOverrideBrowseContext);\r
+        Module_ParameterOverrideBrowseContext_Node = getResourceOrNull(graph, URIs.Module_ParameterOverrideBrowseContext_Node);\r
+        Module_ParameterOverrideBrowseContext_NodeType = getResourceOrNull(graph, URIs.Module_ParameterOverrideBrowseContext_NodeType);\r
+        Module_ParameterOverrideBrowseContext_ParameterChildRule = getResourceOrNull(graph, URIs.Module_ParameterOverrideBrowseContext_ParameterChildRule);\r
+        Module_ParameterOverrideBrowseContext_ParameterLabelDecorationRule = getResourceOrNull(graph, URIs.Module_ParameterOverrideBrowseContext_ParameterLabelDecorationRule);\r
+        Module_ParameterOverrideBrowseContext_ParameterLabelRule = getResourceOrNull(graph, URIs.Module_ParameterOverrideBrowseContext_ParameterLabelRule);\r
+        Module_ParameterOverrideBrowseContext_ParameterModifierRule = getResourceOrNull(graph, URIs.Module_ParameterOverrideBrowseContext_ParameterModifierRule);\r
+        Module_ParameterOverrideBrowseContext_ParameterSorterRule = getResourceOrNull(graph, URIs.Module_ParameterOverrideBrowseContext_ParameterSorterRule);\r
+        Module_ParameterOverride_overriddenParameter = getResourceOrNull(graph, URIs.Module_ParameterOverride_overriddenParameter);\r
+        Module_ParameterOverride_overrideExpression = getResourceOrNull(graph, URIs.Module_ParameterOverride_overrideExpression);\r
+        Module_ParameterOverride_overrideExpression_Inverse = getResourceOrNull(graph, URIs.Module_ParameterOverride_overrideExpression_Inverse);\r
+        Module_parameterOverride = getResourceOrNull(graph, URIs.Module_parameterOverride);\r
+        Module_parameterOverride_Inverse = getResourceOrNull(graph, URIs.Module_parameterOverride_Inverse);\r
+        Module_redeclaration = getResourceOrNull(graph, URIs.Module_redeclaration);\r
+        Module_redeclaration_Inverse = getResourceOrNull(graph, URIs.Module_redeclaration_Inverse);\r
+        ModulesSearchFunction = getResourceOrNull(graph, URIs.ModulesSearchFunction);\r
+        NormalDistribution = getResourceOrNull(graph, URIs.NormalDistribution);\r
+        NormalDistribution_maxValue = getResourceOrNull(graph, URIs.NormalDistribution_maxValue);\r
+        NormalDistribution_maxValue_Inverse = getResourceOrNull(graph, URIs.NormalDistribution_maxValue_Inverse);\r
+        NormalDistribution_mean = getResourceOrNull(graph, URIs.NormalDistribution_mean);\r
+        NormalDistribution_mean_Inverse = getResourceOrNull(graph, URIs.NormalDistribution_mean_Inverse);\r
+        NormalDistribution_minValue = getResourceOrNull(graph, URIs.NormalDistribution_minValue);\r
+        NormalDistribution_minValue_Inverse = getResourceOrNull(graph, URIs.NormalDistribution_minValue_Inverse);\r
+        NormalDistribution_stdDeviation = getResourceOrNull(graph, URIs.NormalDistribution_stdDeviation);\r
+        NormalDistribution_stdDeviation_Inverse = getResourceOrNull(graph, URIs.NormalDistribution_stdDeviation_Inverse);\r
+        NormalExpression = getResourceOrNull(graph, URIs.NormalExpression);\r
+        Orientation = getResourceOrNull(graph, URIs.Orientation);\r
+        ParameterExpression = getResourceOrNull(graph, URIs.ParameterExpression);\r
+        PlaybackExperiment = getResourceOrNull(graph, URIs.PlaybackExperiment);\r
+        ProbabilityDistribution = getResourceOrNull(graph, URIs.ProbabilityDistribution);\r
+        Profiles = getResourceOrNull(graph, URIs.Profiles);\r
+        Profiles_IssueWarnings = getResourceOrNull(graph, URIs.Profiles_IssueWarnings);\r
+        Profiles_ShadowVisualizations = getResourceOrNull(graph, URIs.Profiles_ShadowVisualizations);\r
+        Profiles_SimulationPlaybackColours = getResourceOrNull(graph, URIs.Profiles_SimulationPlaybackColours);\r
+        RandomGenerator = getResourceOrNull(graph, URIs.RandomGenerator);\r
+        Redeclaration = getResourceOrNull(graph, URIs.Redeclaration);\r
+        Redeclaration_replacedEnumeration = getResourceOrNull(graph, URIs.Redeclaration_replacedEnumeration);\r
+        Redeclaration_replacedEnumeration_Inverse = getResourceOrNull(graph, URIs.Redeclaration_replacedEnumeration_Inverse);\r
+        Redeclaration_replacingEnumeration = getResourceOrNull(graph, URIs.Redeclaration_replacingEnumeration);\r
+        Redeclaration_replacingEnumeration_Inverse = getResourceOrNull(graph, URIs.Redeclaration_replacingEnumeration_Inverse);\r
+        Result = getResourceOrNull(graph, URIs.Result);\r
+        ResultSet = getResourceOrNull(graph, URIs.ResultSet);\r
+        Result_parameterFile = getResourceOrNull(graph, URIs.Result_parameterFile);\r
+        Result_parameterFile_Inverse = getResourceOrNull(graph, URIs.Result_parameterFile_Inverse);\r
+        Result_resultFile = getResourceOrNull(graph, URIs.Result_resultFile);\r
+        Result_resultFile_Inverse = getResourceOrNull(graph, URIs.Result_resultFile_Inverse);\r
+        Result_showResult = getResourceOrNull(graph, URIs.Result_showResult);\r
+        Result_time = getResourceOrNull(graph, URIs.Result_time);\r
+        Result_time_Inverse = getResourceOrNull(graph, URIs.Result_time_Inverse);\r
+        Right = getResourceOrNull(graph, URIs.Right);\r
+        SearchContribution = getResourceOrNull(graph, URIs.SearchContribution);\r
+        SelectedSharedFunctionLibraries = getResourceOrNull(graph, URIs.SelectedSharedFunctionLibraries);\r
+        SensitivityAnalysisExperiment = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment);\r
+        SensitivityAnalysisExperiment_Parameter = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_Parameter);\r
+        SensitivityAnalysisExperiment_ParameterActionContext = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_ParameterActionContext);\r
+        SensitivityAnalysisExperiment_ParameterActionContext_Actions = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_ParameterActionContext_Actions);\r
+        SensitivityAnalysisExperiment_ParameterBrowseContext = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_ParameterBrowseContext);\r
+        SensitivityAnalysisExperiment_ParameterBrowseContext_ParameterChildRule = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_ParameterBrowseContext_ParameterChildRule);\r
+        SensitivityAnalysisExperiment_ParameterBrowseContext_ParameterLabelRule = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_ParameterBrowseContext_ParameterLabelRule);\r
+        SensitivityAnalysisExperiment_Parameter_indexes = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_Parameter_indexes);\r
+        SensitivityAnalysisExperiment_Parameter_indexes_Inverse = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_Parameter_indexes_Inverse);\r
+        SensitivityAnalysisExperiment_Parameter_propabilityDistribution = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_Parameter_propabilityDistribution);\r
+        SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse);\r
+        SensitivityAnalysisExperiment_Parameter_variable = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_Parameter_variable);\r
+        SensitivityAnalysisExperiment_Parameter_variable_Inverse = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_Parameter_variable_Inverse);\r
+        SensitivityAnalysisExperiment_method = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_method);\r
+        SensitivityAnalysisExperiment_method_Inverse = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_method_Inverse);\r
+        SensitivityAnalysisExperiment_numberOfValues = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_numberOfValues);\r
+        SensitivityAnalysisExperiment_numberOfValues_Inverse = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_numberOfValues_Inverse);\r
+        SensitivityAnalysisExperiment_parameterList = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_parameterList);\r
+        SensitivityAnalysisExperiment_parameterList_Inverse = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_parameterList_Inverse);\r
+        SensitivityAnalysisExperiment_randomSeed = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_randomSeed);\r
+        SensitivityAnalysisExperiment_randomSeed_Inverse = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_randomSeed_Inverse);\r
+        SensitivityAnalysisExperiment_resultRefreshRate = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_resultRefreshRate);\r
+        SensitivityAnalysisExperiment_resultRefreshRate_Inverse = getResourceOrNull(graph, URIs.SensitivityAnalysisExperiment_resultRefreshRate_Inverse);\r
+        Shadow = getResourceOrNull(graph, URIs.Shadow);\r
+        ShadowStyle = getResourceOrNull(graph, URIs.ShadowStyle);\r
+        ShadowSymbol = getResourceOrNull(graph, URIs.ShadowSymbol);\r
+        Shadow_original = getResourceOrNull(graph, URIs.Shadow_original);\r
+        Shadow_original_Inverse = getResourceOrNull(graph, URIs.Shadow_original_Inverse);\r
+        SharedFunctionOntology = getResourceOrNull(graph, URIs.SharedFunctionOntology);\r
+        SharedModuleOntology = getResourceOrNull(graph, URIs.SharedModuleOntology);\r
+        SimulateOnChangeExperiment = getResourceOrNull(graph, URIs.SimulateOnChangeExperiment);\r
+        SimulationPlaybackProfile = getResourceOrNull(graph, URIs.SimulationPlaybackProfile);\r
+        SimulationPlaybackStyle = getResourceOrNull(graph, URIs.SimulationPlaybackStyle);\r
+        Stock = getResourceOrNull(graph, URIs.Stock);\r
+        StockExpression = getResourceOrNull(graph, URIs.StockExpression);\r
+        StockExpression_initialEquation = getResourceOrNull(graph, URIs.StockExpression_initialEquation);\r
+        StockExpression_initialEquation_Inverse = getResourceOrNull(graph, URIs.StockExpression_initialEquation_Inverse);\r
+        StockExpression_integralEquation = getResourceOrNull(graph, URIs.StockExpression_integralEquation);\r
+        StockExpression_integralEquation_Inverse = getResourceOrNull(graph, URIs.StockExpression_integralEquation_Inverse);\r
+        StockExpression_useCustomIntegral = getResourceOrNull(graph, URIs.StockExpression_useCustomIntegral);\r
+        StockSymbol = getResourceOrNull(graph, URIs.StockSymbol);\r
+        SymbolReferences = getResourceOrNull(graph, URIs.SymbolReferences);\r
+        SymbolReferences_BasicSymbols = getResourceOrNull(graph, URIs.SymbolReferences_BasicSymbols);\r
+        SymbolReferences_CommentSymbols = getResourceOrNull(graph, URIs.SymbolReferences_CommentSymbols);\r
+        Symbols = getResourceOrNull(graph, URIs.Symbols);\r
+        SysdynConnectionType = getResourceOrNull(graph, URIs.SysdynConnectionType);\r
+        SysdynDiagramModelingRules = getResourceOrNull(graph, URIs.SysdynDiagramModelingRules);\r
+        SysdynModel = getResourceOrNull(graph, URIs.SysdynModel);\r
+        SysdynModel_fmuFile = getResourceOrNull(graph, URIs.SysdynModel_fmuFile);\r
+        SysdynModel_fmuFile_Inverse = getResourceOrNull(graph, URIs.SysdynModel_fmuFile_Inverse);\r
+        SysdynModel_lastExportFileName = getResourceOrNull(graph, URIs.SysdynModel_lastExportFileName);\r
+        SysdynModel_lastExportFileName_Inverse = getResourceOrNull(graph, URIs.SysdynModel_lastExportFileName_Inverse);\r
+        SysdynModel_lastExportFilePath = getResourceOrNull(graph, URIs.SysdynModel_lastExportFilePath);\r
+        SysdynModel_lastExportFilePath_Inverse = getResourceOrNull(graph, URIs.SysdynModel_lastExportFilePath_Inverse);\r
+        SysdynModel_outputInterval = getResourceOrNull(graph, URIs.SysdynModel_outputInterval);\r
+        SysdynModel_outputInterval_Inverse = getResourceOrNull(graph, URIs.SysdynModel_outputInterval_Inverse);\r
+        SysdynModel_simulationStepLength = getResourceOrNull(graph, URIs.SysdynModel_simulationStepLength);\r
+        SysdynModel_simulationStepLength_Inverse = getResourceOrNull(graph, URIs.SysdynModel_simulationStepLength_Inverse);\r
+        SysdynModel_solver = getResourceOrNull(graph, URIs.SysdynModel_solver);\r
+        SysdynModel_solver_Inverse = getResourceOrNull(graph, URIs.SysdynModel_solver_Inverse);\r
+        SysdynModel_startTime = getResourceOrNull(graph, URIs.SysdynModel_startTime);\r
+        SysdynModel_startTime_Inverse = getResourceOrNull(graph, URIs.SysdynModel_startTime_Inverse);\r
+        SysdynModel_stopTime = getResourceOrNull(graph, URIs.SysdynModel_stopTime);\r
+        SysdynModel_stopTime_Inverse = getResourceOrNull(graph, URIs.SysdynModel_stopTime_Inverse);\r
+        SysdynModel_timeUnit = getResourceOrNull(graph, URIs.SysdynModel_timeUnit);\r
+        SysdynModel_timeUnit_Inverse = getResourceOrNull(graph, URIs.SysdynModel_timeUnit_Inverse);\r
+        SysdynModel_tolerance = getResourceOrNull(graph, URIs.SysdynModel_tolerance);\r
+        SysdynModel_tolerance_Inverse = getResourceOrNull(graph, URIs.SysdynModel_tolerance_Inverse);\r
+        SysdynModel_variableFilter = getResourceOrNull(graph, URIs.SysdynModel_variableFilter);\r
+        SysdynModel_variableFilter_Inverse = getResourceOrNull(graph, URIs.SysdynModel_variableFilter_Inverse);\r
+        SysdynModelicaFunction = getResourceOrNull(graph, URIs.SysdynModelicaFunction);\r
+        SysdynModelicaFunctionLibrary = getResourceOrNull(graph, URIs.SysdynModelicaFunctionLibrary);\r
+        SysdynModelicaFunction_Input = getResourceOrNull(graph, URIs.SysdynModelicaFunction_Input);\r
+        SysdynModelicaFunction_InterfaceVariable = getResourceOrNull(graph, URIs.SysdynModelicaFunction_InterfaceVariable);\r
+        SysdynModelicaFunction_Output = getResourceOrNull(graph, URIs.SysdynModelicaFunction_Output);\r
+        SysdynModelicaFunction_VariableLengthInput = getResourceOrNull(graph, URIs.SysdynModelicaFunction_VariableLengthInput);\r
+        SysdynModelicaFunction_VariableLengthInput_shownLabels = getResourceOrNull(graph, URIs.SysdynModelicaFunction_VariableLengthInput_shownLabels);\r
+        SysdynModelicaFunction_VariableLengthInput_shownLabels_Inverse = getResourceOrNull(graph, URIs.SysdynModelicaFunction_VariableLengthInput_shownLabels_Inverse);\r
+        SysdynModelicaFunction_definition = getResourceOrNull(graph, URIs.SysdynModelicaFunction_definition);\r
+        SysdynModelicaFunction_definition_Inverse = getResourceOrNull(graph, URIs.SysdynModelicaFunction_definition_Inverse);\r
+        SysdynModelicaFunction_inputs = getResourceOrNull(graph, URIs.SysdynModelicaFunction_inputs);\r
+        SysdynModelicaFunction_inputs_Inverse = getResourceOrNull(graph, URIs.SysdynModelicaFunction_inputs_Inverse);\r
+        SysdynModelicaFunction_modelicaFunctionCode = getResourceOrNull(graph, URIs.SysdynModelicaFunction_modelicaFunctionCode);\r
+        SysdynModelicaFunction_modelicaFunctionCode_Inverse = getResourceOrNull(graph, URIs.SysdynModelicaFunction_modelicaFunctionCode_Inverse);\r
+        SysdynModelicaFunction_modelicaFunctionInterface = getResourceOrNull(graph, URIs.SysdynModelicaFunction_modelicaFunctionInterface);\r
+        SysdynModelicaFunction_modelicaFunctionInterface_Inverse = getResourceOrNull(graph, URIs.SysdynModelicaFunction_modelicaFunctionInterface_Inverse);\r
+        SysdynModelicaFunction_optional = getResourceOrNull(graph, URIs.SysdynModelicaFunction_optional);\r
+        SysdynModelicaFunction_optional_Inverse = getResourceOrNull(graph, URIs.SysdynModelicaFunction_optional_Inverse);\r
+        SysdynModelicaFunction_outputs = getResourceOrNull(graph, URIs.SysdynModelicaFunction_outputs);\r
+        SysdynModelicaFunction_outputs_Inverse = getResourceOrNull(graph, URIs.SysdynModelicaFunction_outputs_Inverse);\r
+        SysdynModelicaFunction_unit = getResourceOrNull(graph, URIs.SysdynModelicaFunction_unit);\r
+        SysdynModelicaFunction_unit_Inverse = getResourceOrNull(graph, URIs.SysdynModelicaFunction_unit_Inverse);\r
+        SysdynModuleLibrary = getResourceOrNull(graph, URIs.SysdynModuleLibrary);\r
+        SysdynOperationBrowser = getResourceOrNull(graph, URIs.SysdynOperationBrowser);\r
+        SysdynSymbol = getResourceOrNull(graph, URIs.SysdynSymbol);\r
+        SysdynTerminal = getResourceOrNull(graph, URIs.SysdynTerminal);\r
+        Top = getResourceOrNull(graph, URIs.Top);\r
+        UniformDistribution = getResourceOrNull(graph, URIs.UniformDistribution);\r
+        UniformDistribution_maxValue = getResourceOrNull(graph, URIs.UniformDistribution_maxValue);\r
+        UniformDistribution_maxValue_Inverse = getResourceOrNull(graph, URIs.UniformDistribution_maxValue_Inverse);\r
+        UniformDistribution_minValue = getResourceOrNull(graph, URIs.UniformDistribution_minValue);\r
+        UniformDistribution_minValue_Inverse = getResourceOrNull(graph, URIs.UniformDistribution_minValue_Inverse);\r
+        UsedVariableIndexes = getResourceOrNull(graph, URIs.UsedVariableIndexes);\r
+        Validations = getResourceOrNull(graph, URIs.Validations);\r
+        Validations_Dependencies = getResourceOrNull(graph, URIs.Validations_Dependencies);\r
+        Validations_Dependencies_DependencyConnectionsIssueSource = getResourceOrNull(graph, URIs.Validations_Dependencies_DependencyConnectionsIssueSource);\r
+        Validations_Dependencies_MissingDependencyConnectionsIssueSource = getResourceOrNull(graph, URIs.Validations_Dependencies_MissingDependencyConnectionsIssueSource);\r
+        Validations_Dependencies_dependencyValidator = getResourceOrNull(graph, URIs.Validations_Dependencies_dependencyValidator);\r
+        Validations_Dependencies_invalidSheetReferenceIssueDescription = getResourceOrNull(graph, URIs.Validations_Dependencies_invalidSheetReferenceIssueDescription);\r
+        Validations_Dependencies_missingDependencyValidator = getResourceOrNull(graph, URIs.Validations_Dependencies_missingDependencyValidator);\r
+        Validations_Dependencies_missingLinkIssueDescription = getResourceOrNull(graph, URIs.Validations_Dependencies_missingLinkIssueDescription);\r
+        Validations_Dependencies_noSuchVariableIssueDescription = getResourceOrNull(graph, URIs.Validations_Dependencies_noSuchVariableIssueDescription);\r
+        Validations_Dependencies_rangeIssueDescription = getResourceOrNull(graph, URIs.Validations_Dependencies_rangeIssueDescription);\r
+        Validations_Dependencies_rangeWarningDescription = getResourceOrNull(graph, URIs.Validations_Dependencies_rangeWarningDescription);\r
+        Validations_Dependencies_unusedDependencyIssueDescription = getResourceOrNull(graph, URIs.Validations_Dependencies_unusedDependencyIssueDescription);\r
+        Validations_DependencyConstraint = getResourceOrNull(graph, URIs.Validations_DependencyConstraint);\r
+        Validations_EmptyEnumerationIssue = getResourceOrNull(graph, URIs.Validations_EmptyEnumerationIssue);\r
+        Validations_EnumerationConstraint = getResourceOrNull(graph, URIs.Validations_EnumerationConstraint);\r
+        Validations_Enumerations = getResourceOrNull(graph, URIs.Validations_Enumerations);\r
+        Validations_Enumerations_EnumerationIssueSource = getResourceOrNull(graph, URIs.Validations_Enumerations_EnumerationIssueSource);\r
+        Validations_Enumerations_emptyEnumerationIssueDescription = getResourceOrNull(graph, URIs.Validations_Enumerations_emptyEnumerationIssueDescription);\r
+        Validations_Enumerations_enumerationIndexValidator = getResourceOrNull(graph, URIs.Validations_Enumerations_enumerationIndexValidator);\r
+        Validations_ExpressionConstraint = getResourceOrNull(graph, URIs.Validations_ExpressionConstraint);\r
+        Validations_ExpressionIssue = getResourceOrNull(graph, URIs.Validations_ExpressionIssue);\r
+        Validations_Expressions = getResourceOrNull(graph, URIs.Validations_Expressions);\r
+        Validations_Expressions_ExpressionIssueSource = getResourceOrNull(graph, URIs.Validations_Expressions_ExpressionIssueSource);\r
+        Validations_Expressions_expressionIssueDescription = getResourceOrNull(graph, URIs.Validations_Expressions_expressionIssueDescription);\r
+        Validations_Expressions_expressionValidator = getResourceOrNull(graph, URIs.Validations_Expressions_expressionValidator);\r
+        Validations_Functions = getResourceOrNull(graph, URIs.Validations_Functions);\r
+        Validations_Functions_baseRealizationFunction = getResourceOrNull(graph, URIs.Validations_Functions_baseRealizationFunction);\r
+        Validations_Functions_path = getResourceOrNull(graph, URIs.Validations_Functions_path);\r
+        Validations_InvalidSheetReferenceIssue = getResourceOrNull(graph, URIs.Validations_InvalidSheetReferenceIssue);\r
+        Validations_Issue = getResourceOrNull(graph, URIs.Validations_Issue);\r
+        Validations_Issue_stringContexts = getResourceOrNull(graph, URIs.Validations_Issue_stringContexts);\r
+        Validations_Issue_stringContexts_Inverse = getResourceOrNull(graph, URIs.Validations_Issue_stringContexts_Inverse);\r
+        Validations_MissingDependencyConstraint = getResourceOrNull(graph, URIs.Validations_MissingDependencyConstraint);\r
+        Validations_MissingLinkIssue = getResourceOrNull(graph, URIs.Validations_MissingLinkIssue);\r
+        Validations_ModuleInputUnitWarning = getResourceOrNull(graph, URIs.Validations_ModuleInputUnitWarning);\r
+        Validations_ModuleOutputUnitWarning = getResourceOrNull(graph, URIs.Validations_ModuleOutputUnitWarning);\r
+        Validations_NoSuchVariableIssue = getResourceOrNull(graph, URIs.Validations_NoSuchVariableIssue);\r
+        Validations_RangeIssue = getResourceOrNull(graph, URIs.Validations_RangeIssue);\r
+        Validations_RangeWarning = getResourceOrNull(graph, URIs.Validations_RangeWarning);\r
+        Validations_UnitConstraint = getResourceOrNull(graph, URIs.Validations_UnitConstraint);\r
+        Validations_UnitWarning = getResourceOrNull(graph, URIs.Validations_UnitWarning);\r
+        Validations_Units = getResourceOrNull(graph, URIs.Validations_Units);\r
+        Validations_Units_UnitIssueSource = getResourceOrNull(graph, URIs.Validations_Units_UnitIssueSource);\r
+        Validations_Units_UnitIssueSource_allowEquivalents = getResourceOrNull(graph, URIs.Validations_Units_UnitIssueSource_allowEquivalents);\r
+        Validations_Units_UnitIssueSource_allowEquivalents_Inverse = getResourceOrNull(graph, URIs.Validations_Units_UnitIssueSource_allowEquivalents_Inverse);\r
+        Validations_Units_moduleInputUnitWarningDescription = getResourceOrNull(graph, URIs.Validations_Units_moduleInputUnitWarningDescription);\r
+        Validations_Units_moduleInterfaceExtension = getResourceOrNull(graph, URIs.Validations_Units_moduleInterfaceExtension);\r
+        Validations_Units_moduleOutputUnitWarningDescription = getResourceOrNull(graph, URIs.Validations_Units_moduleOutputUnitWarningDescription);\r
+        Validations_Units_unitValidator = getResourceOrNull(graph, URIs.Validations_Units_unitValidator);\r
+        Validations_Units_unitWarningDescription = getResourceOrNull(graph, URIs.Validations_Units_unitWarningDescription);\r
+        Validations_UnusedDependencyIssue = getResourceOrNull(graph, URIs.Validations_UnusedDependencyIssue);\r
+        Validations_constraint = getResourceOrNull(graph, URIs.Validations_constraint);\r
+        Validations_issue = getResourceOrNull(graph, URIs.Validations_issue);\r
+        Validations_listeningConstraint = getResourceOrNull(graph, URIs.Validations_listeningConstraint);\r
+        ValueGeneratorMethod = getResourceOrNull(graph, URIs.ValueGeneratorMethod);\r
+        Valve = getResourceOrNull(graph, URIs.Valve);\r
+        ValveSymbol = getResourceOrNull(graph, URIs.ValveSymbol);\r
+        ValveSymbol_orientation = getResourceOrNull(graph, URIs.ValveSymbol_orientation);\r
+        ValveSymbol_textLocation = getResourceOrNull(graph, URIs.ValveSymbol_textLocation);\r
+        Variable = getResourceOrNull(graph, URIs.Variable);\r
+        Variable_HasHead = getResourceOrNull(graph, URIs.Variable_HasHead);\r
+        Variable_HasTail = getResourceOrNull(graph, URIs.Variable_HasTail);\r
+        Variable_activeDatasets = getResourceOrNull(graph, URIs.Variable_activeDatasets);\r
+        Variable_activeDatasets_Inverse = getResourceOrNull(graph, URIs.Variable_activeDatasets_Inverse);\r
+        Variable_arrayIndexes = getResourceOrNull(graph, URIs.Variable_arrayIndexes);\r
+        Variable_arrayIndexesList = getResourceOrNull(graph, URIs.Variable_arrayIndexesList);\r
+        Variable_arrayIndexesList_Inverse = getResourceOrNull(graph, URIs.Variable_arrayIndexesList_Inverse);\r
+        Variable_arrayIndexes_Inverse = getResourceOrNull(graph, URIs.Variable_arrayIndexes_Inverse);\r
+        Variable_equation = getResourceOrNull(graph, URIs.Variable_equation);\r
+        Variable_equation_Inverse = getResourceOrNull(graph, URIs.Variable_equation_Inverse);\r
+        Variable_expressionList = getResourceOrNull(graph, URIs.Variable_expressionList);\r
+        Variable_expressionList_Inverse = getResourceOrNull(graph, URIs.Variable_expressionList_Inverse);\r
+        Variable_expressions = getResourceOrNull(graph, URIs.Variable_expressions);\r
+        Variable_expressions_Inverse = getResourceOrNull(graph, URIs.Variable_expressions_Inverse);\r
+        Variable_isHeadOf = getResourceOrNull(graph, URIs.Variable_isHeadOf);\r
+        Variable_isTailOf = getResourceOrNull(graph, URIs.Variable_isTailOf);\r
+        Variable_names = getResourceOrNull(graph, URIs.Variable_names);\r
+        Variable_names_Inverse = getResourceOrNull(graph, URIs.Variable_names_Inverse);\r
+        Variable_time = getResourceOrNull(graph, URIs.Variable_time);\r
+        Variable_time_Inverse = getResourceOrNull(graph, URIs.Variable_time_Inverse);\r
+        Variable_times = getResourceOrNull(graph, URIs.Variable_times);\r
+        Variable_times_Inverse = getResourceOrNull(graph, URIs.Variable_times_Inverse);\r
+        Variable_type = getResourceOrNull(graph, URIs.Variable_type);\r
+        Variable_type_Inverse = getResourceOrNull(graph, URIs.Variable_type_Inverse);\r
+        Variable_unit = getResourceOrNull(graph, URIs.Variable_unit);\r
+        Variable_unit_Inverse = getResourceOrNull(graph, URIs.Variable_unit_Inverse);\r
+        Variable_value = getResourceOrNull(graph, URIs.Variable_value);\r
+        Variable_value_Inverse = getResourceOrNull(graph, URIs.Variable_value_Inverse);\r
+        Variable_values = getResourceOrNull(graph, URIs.Variable_values);\r
+        Variable_values_Inverse = getResourceOrNull(graph, URIs.Variable_values_Inverse);\r
+        Variable_variability = getResourceOrNull(graph, URIs.Variable_variability);\r
+        Variable_variability_Inverse = getResourceOrNull(graph, URIs.Variable_variability_Inverse);\r
+        Vertical = getResourceOrNull(graph, URIs.Vertical);\r
+        WithLookupExpression = getResourceOrNull(graph, URIs.WithLookupExpression);\r
+        WithLookupExpression_expression = getResourceOrNull(graph, URIs.WithLookupExpression_expression);\r
+        WithLookupExpression_expression_Inverse = getResourceOrNull(graph, URIs.WithLookupExpression_expression_Inverse);\r
+        WithLookupExpression_lookup = getResourceOrNull(graph, URIs.WithLookupExpression_lookup);\r
+        WithLookupExpression_lookup_Inverse = getResourceOrNull(graph, URIs.WithLookupExpression_lookup_Inverse);\r
+        WithLookupExpression_maxX = getResourceOrNull(graph, URIs.WithLookupExpression_maxX);\r
+        WithLookupExpression_maxY = getResourceOrNull(graph, URIs.WithLookupExpression_maxY);\r
+        WithLookupExpression_minX = getResourceOrNull(graph, URIs.WithLookupExpression_minX);\r
+        WithLookupExpression_minY = getResourceOrNull(graph, URIs.WithLookupExpression_minY);\r
+    }\r
+    \r
+    public static SysdynResource getInstance(ReadGraph graph) {\r
+        Session session = graph.getSession();\r
+        SysdynResource ret = session.peekService(SysdynResource.class);\r
+        if(ret == null) {\r
+            QueryControl qc = graph.getService(QueryControl.class);\r
+            ret = new SysdynResource(qc.getIndependentGraph(graph));\r
+            session.registerService(SysdynResource.class, ret);\r
+        }\r
+        return ret;\r
+    }\r
+    \r
+    public static SysdynResource getInstance(RequestProcessor session) throws DatabaseException {\r
+        SysdynResource ret = session.peekService(SysdynResource.class);\r
+        if(ret == null) {\r
+            ret = session.syncRequest(new Read<SysdynResource>() {\r
+                public SysdynResource perform(ReadGraph graph) throws DatabaseException {\r
+                    QueryControl qc = graph.getService(QueryControl.class);\r
+                    return new SysdynResource(qc.getIndependentGraph(graph));\r
+                }\r
+            });\r
+            session.registerService(SysdynResource.class, ret);\r
+        }\r
+        return ret;\r
+    }\r
+    \r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ontology/testGraph.tg b/1.8/org.simantics.sysdyn.ontology/testGraph.tg
new file mode 100644 (file)
index 0000000..f419f04
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ontology/testGraph.tg differ
diff --git a/1.8/org.simantics.sysdyn.ontology/testGraph/Cancer.pgraph.keep b/1.8/org.simantics.sysdyn.ontology/testGraph/Cancer.pgraph.keep
new file mode 100644 (file)
index 0000000..42efd79
--- /dev/null
@@ -0,0 +1,6820 @@
+L0 = <http://www.simantics.org/Layer0-1.0>
+G2D = <http://www.simantics.org/G2D-1.0>
+STR = <http://www.simantics.org/Structural-1.0>
+DIA = <http://www.simantics.org/Diagram-2.1>
+SIMU = <http://www.simantics.org/Simulation-1.0>
+MOD = <http://www.simantics.org/Modeling-1.1>
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>
+PROJ = <http://www.simantics.org/Project-1.1>
+
+//######################################################################
+//# Example work model with two modules
+//######################################################################
+
+WM = <http://www.simantics.org/Sysdyn-1.1/DevelopmentProject> : PROJ.Project
+    PROJ.HasFeature _ : PROJ.FeatureSpec
+        PROJ.HasGroupId "org.simantics.sysdyn.feature.group"
+    L0.PartOf <http://Projects>
+
+TAGS = WM.Tags : L0.Library
+
+//WM.dependency : L0.Template
+//    @template %type %head %tail %angle
+//        %type 
+//            @L0.tag TAGS.AdminIsVisible
+//            @L0.tag TAGS.AdminIsFocusable
+//            STR.HasConnectionType SYSDYN.SysdynConnectionType
+//            SYSDYN.angle %angle 
+//            DIA.HasArrowConnector _ : DIA.Connector
+//                SYSDYN.HasHeadTerminal %head
+//                DIA.AreConnected _ : DIA.Connector 
+//                  SYSDYN.HasTailTerminal %tail
+//                  DIA.IsPlainConnectorOf %type
+//
+//WM.flow : L0.Template
+//    @template %type %head %tail
+//        %type 
+//            @L0.tag TAGS.AdminIsVisible
+//            @L0.tag TAGS.AdminIsFocusable
+//            STR.HasConnectionType SYSDYN.SysdynConnectionType
+//            DIA.HasArrowConnector _ : DIA.Connector
+//                SYSDYN.HasHeadTerminal %head
+//                DIA.AreConnected _ : DIA.Connector 
+//                  SYSDYN.HasTailTerminal %tail
+//                  DIA.IsPlainConnectorOf %type              
+//
+//WM.conf_dependency : L0.Template
+//    @template %type %head %tail
+//        %type 
+//            @L0.tag MOD.Mapped
+//            SYSDYN.HasHead %head
+//            SYSDYN.HasTail %tail
+//
+//WM.conf_dependency_ref : L0.Template
+//    @template %type %head %tail %ref
+//        %type 
+//            @L0.tag MOD.Mapped
+//            SYSDYN.HasHead %head
+//            SYSDYN.HasTail %tail
+//            SYSDYN.RefersTo %ref                      
+
+WM.CancerModel : SYSDYN.SysdynModel
+    L0.HasLabel "Cancer Model"
+    SIMU.HasConfiguration CMC
+    SYSDYN.HasStartTime 0.0
+    SYSDYN.HasStopTime 24.0
+
+WM.CancerModel.Experiment : SYSDYN.Experiment
+    L0.HasLabel "Experiment"
+
+CMC = WM.CancerModel.CancerModelConfiguration : SYSDYN.Configuration
+  L0.HasLabel "CancerModelConfiguration"
+
+CMC.LungCProgressIAIVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIVNos')" 
+
+CMC.LungCT1Progresses : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCNotProgressing1[Type,Stage,Gender,Age]*LungCT1ProgressesRate[Type,Stage,Age,Gender]" 
+CMC.LungCProgressIAIB : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIAIBRate[Type,Age,Gender]*LungCsIANoD[Type,Gender,Age]" 
+CMC.LungCT1Death : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCT1Disabling[Type,Stage,Gender,Age]*LungCT1DeathRate[Type,Stage,Age,Gender]" 
+CMC.LungCHealthyPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCHealthy[Gender,Age]*LungCModelPopCorrectionFactor[Gender,Age]" 
+CMC.LungCsIADiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIANos')" 
+
+CMC.LungCProgress03IV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgress03IVRate[Type,Age,Gender]*LungCs03[Type,Gender,Age]" 
+CMC.LungCsIIIBNoDAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCsIIIBNoD[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCsIIIBNoD[Type,Gender,Age], -1) else -LungCsIIIBNoD[Type,Gender,Age]+VECTOR_MAP(LungCsIIIBNoD[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCProgressIBIVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIBIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIBIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIBIVNos')" 
+
+CMC.LungCOutputs02NosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs02Diagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCProgressIIAIV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIIAIVRate[Type,Age,Gender]*LungCsIIANoD[Type,Gender,Age]" 
+CMC.LungCTherapy1Mortality : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCFirstTreatmentRate*(LungCD[Type,Stage,Gender,Age]*LungCTherapy1Ratio[Type,Stage,Age,Gender])*LungCTherapy1MortalityRatio/100" 
+CMC.LungCCured1PopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCCured1[Type,Stage,Gender,Age]" 
+CMC.LungCProgress01IV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgress01IVRate[Type,Age,Gender]*LungCs01[Type,Gender,Age]" 
+CMC.LungCs03Diagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCs03DiagnosisRate[Type,Age,Gender]*LungCs03[Type,Gender,Age]" 
+CMC.LungCs03PopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCs03[Type,Gender,Age]" 
+CMC.LungCProgressIAIIA : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIAIIARate[Type,Age,Gender]*LungCsIANoD[Type,Gender,Age]" 
+CMC.LungCDPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCD[Type,Stage,Gender,Age]" 
+CMC.LungCsIIIADiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIIANos')" 
+
+CMC.LungCOutputsIANsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIANoD[NonSmall,Gender!,Age!])" 
+
+CMC.LungCOutputTherapy1 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCTherapy1[Type!,Stage!,Gender!,Age!])+sum(LungCTherapyCure1[Type!,Stage!,Gender!,Age!])+sum(LungCTherapy1Mortality[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCT2ProgressesRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Re03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2ReIVNos')" 
+
+CMC.LungCOutputTherapy2Cure : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCTherapyCure2[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCT2Progresses : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCNotProgressing2[Type,Stage,Gender,Age]*LungCT2ProgressesRate[Type,Stage,Age,Gender]" 
+CMC.LungCT1ProgToDisablingRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Di03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1DiIVNos')" 
+
+CMC.LungCProgressIIBIIIB : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIIBIIIBRate[Type,Age,Gender]*LungCsIIBNoD[Type,Gender,Age]" 
+CMC.LungCsIIIANoDAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCsIIIANoD[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCsIIIANoD[Type,Gender,Age], -1) else -LungCsIIIANoD[Type,Gender,Age]+VECTOR_MAP(LungCsIIIANoD[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCOutputsIBNsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIBDiagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCOutputRelapse : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCT1Progresses[Type!,Stage!,Gender!,Age!])+sum(LungCT2Progresses[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCT1Deceased : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "0" 
+
+CMC.LungCT1DisablingPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCT1Disabling[Type,Stage,Gender,Age]" 
+CMC.LungCOutputsIAScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIADiagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCProgressIBIV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIBIVRate[Type,Age,Gender]*LungCsIBNoD[Type,Gender,Age]" 
+CMC.LungCsIVDiagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIVDiagnosisRate[Type,Age,Gender]*LungCsIVNoD[Type,Gender,Age]" 
+CMC.LungCOutputsIIIBScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIBDiagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCsIIADiagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIIADiagnosisRate[Type,Age,Gender]*LungCsIIANoD[Type,Gender,Age]" 
+CMC.LungCTherapy1Ratio : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Ra03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1RaIVNos')" 
+
+CMC.LungCsIBNoDPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCsIBNoD[Type,Gender,Age]" 
+CMC.LungCsIANoDAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCsIANoD[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCsIANoD[Type,Gender,Age], -1) else -LungCsIANoD[Type,Gender,Age]+VECTOR_MAP(LungCsIANoD[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCCured1Ageing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCCured1[Type,Stage,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCCured1[Type,Stage,Gender,Age], -1) else -LungCCured1[Type,Stage,Gender,Age]+VECTOR_MAP(LungCCured1[Type,Stage,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCProgress03IARate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P03IASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P03IANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P03IANos')" 
+
+CMC.LungCT1Disabling : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCT1DisablingIniVal[Type,Stage,Age,Gender]" 
+
+CMC.LungCCured2PopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCCured2[Type,Stage,Gender,Age]" 
+CMC.LungCTreated2IniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2TrIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Tr03Nos')" 
+
+CMC.LungCsIIBDiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIBNos')" 
+
+CMC.LungCOutputNoDSc : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCOutputs01ScNoD+LungCOutputs02ScNoD+LungCOutputs03ScNoD+LungCOutputsIAScNoD+LungCOutputsIBScNoD+LungCOutputsIIAScNoD+LungCOutputsIIBScNoD+LungCOutputsIIIAScNoD+LungCOutputsIIIBScNoD+LungCOutputsIVScNoD" 
+
+CMC.LungCOutputsIANsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIADiagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCTherapy2Failed : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCFirstTreatmentRate*(LungCD[Type,Stage,Gender,Age]*LungCTherapy2Ratio[Type,Stage,Age,Gender])*LungCTherapy2FailRatio/100" 
+CMC.LungCProgressIIBIIIARate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIIIANos')" 
+
+CMC.LungCProgressIBIIB : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIBIIBRate[Type,Age,Gender]*LungCsIBNoD[Type,Gender,Age]" 
+CMC.LungCsIIIBNoD : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCsIIIBNoDIniVal[Type,Age,Gender]" 
+
+CMC.LungCDAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCD[Type,Stage,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCD[Type,Stage,Gender,Age], -1) else -LungCD[Type,Stage,Gender,Age]+VECTOR_MAP(LungCD[Type,Stage,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCOutputProgressing2 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCT2Progressing[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCT1ProgressingAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCT1Progressing[Type,Stage,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCT1Progressing[Type,Stage,Gender,Age], -1) else -LungCT1Progressing[Type,Stage,Gender,Age]+VECTOR_MAP(LungCT1Progressing[Type,Stage,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCT1ProgToDisabling : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCT1Progressing[Type,Stage,Gender,Age]*LungCT1ProgToDisablingRate[Type,Stage,Age,Gender]" 
+CMC.LungCT2ProgressingPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCT2Progressing[Type,Stage,Gender,Age]" 
+CMC.LungCInception : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCHealthy[Gender,Age]*LungCSmokersPercentageOfPopulation[Age,Gender]/100*LungCInceptionRate[Small,Age,Gender]" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCHealthy[Gender,Age]*LungCSmokersPercentageOfPopulation[Age,Gender]/100*LungCInceptionRate[NonSmall,Age,Gender]" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCHealthy[Gender,Age]*LungCInceptionRate[NotSmoker,Age,Gender]*LungCInceptionRateChanges[Gender]" 
+CMC.LungCTherapyCure2 : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCFirstTreatmentRate*(LungCD[Type,Stage,Gender,Age]*LungCTherapy2Ratio[Type,Stage,Age,Gender]*LungCTherapy2CureRatio[Type,Stage,Age,Gender])*(1-LungCTherapy2FailRatio/100)" 
+CMC.LungCCured1 : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCCured1IniVal[Type,Stage,Age,Gender]" 
+
+CMC.LungCBirth : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "TotalPopulationBirth[Gender]" 
+CMC.LungCT2ProgressingAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCT2Progressing[Type,Stage,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCT2Progressing[Type,Stage,Gender,Age], -1) else -LungCT2Progressing[Type,Stage,Gender,Age]+VECTOR_MAP(LungCT2Progressing[Type,Stage,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCTherapy1 : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCFirstTreatmentRate*(LungCD[Type,Stage,Gender,Age]*LungCTherapy1Ratio[Type,Stage,Age,Gender]*(1-LungCTherapy1CureRatio[Type,Stage,Age,Gender]))*(1-LungCTherapy1MortalityRatio/100)" 
+CMC.LungCOutputNoDNs : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCOutputs01NsNoD+LungCOutputs02NsNoD+LungCOutputs03NsNoD+LungCOutputsIANsNoD+LungCOutputsIBNsNoD+LungCOutputsIIANsNoD+LungCOutputsIIBNsNoD+LungCOutputsIIIANsNoD+LungCOutputsIIIBNsNoD+LungCOutputsIVNsNoD" 
+
+CMC.LungCProgressIIAIIIA : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIIAIIIARate[Type,Age,Gender]*LungCsIIANoD[Type,Gender,Age]" 
+CMC.LungCs01PopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCs01[Type,Gender,Age]" 
+CMC.LungCOutputsIIBNosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIBDiagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCModelPop : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "0.1+LungCHealthy[Gender,Age]+LungCNoDSum[Gender,Age]+sum(LungCD[Type!,Stage!,Gender,Age])+sum(LungCCured1[Type!,Stage!,Gender,Age])+sum(LungCNotProgressing1[Type!,Stage!,Gender,Age])+sum(LungCT1Progressing[Type!,Stage!,Gender,Age])+sum(LungCT1Disabling[Type!,Stage!,Gender,Age])+sum(LungCCured2[Type!,Stage!,Gender,Age])+sum(LungCNotProgressing2[Type!,Stage!,Gender,Age])+sum(LungCT2Progressing[Type!,Stage!,Gender,Age])+sum(LungCT2Disabling[Type!,Stage!,Gender,Age])" 
+
+CMC.LungCProgressIIIAIIIBRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIAIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIAIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIAIIIBNos')" 
+
+CMC.LungCProgress0203 : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgress0203Rate[Type,Age,Gender]*LungCs02[Type,Gender,Age]" 
+CMC.LungCOutputsIIBNosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIBNoD[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCsIIBDiagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIIBDiagnosisRate[Type,Age,Gender]*LungCsIIBNoD[Type,Gender,Age]" 
+CMC.LungCOutputs03ScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs03[Small,Gender!,Age!])" 
+
+CMC.LungCsIIIBNoDPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCsIIIBNoD[Type,Gender,Age]" 
+CMC.LungCsIIANoDIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIANos')" 
+
+CMC.LungCProgress02IVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P02IVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P02IVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P02IVNos')" 
+
+CMC.LungCOutputs01ScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01Diagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCT2Progressing : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCT2ProgressingIniVal[Type,Stage,Age,Gender]" 
+
+CMC.LungCT2Death : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCT2Disabling[Type,Stage,Gender,Age]*LungCT2DeathRate[Type,Stage,Age,Gender]" 
+CMC.LungCOutputsIIAScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIADiagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCsIBNoD : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCsIBNoDIniVal[Type,Age,Gender]" 
+
+CMC.LungCT1DisablingIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1DiIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Di03Nos')" 
+
+CMC.LungCNotProgressing1 : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCTreated1IniVal[Type,Stage,Age,Gender]" 
+
+CMC.LungCOutputsIBScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIBDiagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCOutputProgressing1 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCT1Progressing[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCProgressIIIAIV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIIIAIVRate[Type,Age,Gender]*LungCsIIIANoD[Type,Gender,Age]" 
+CMC.LungCProgressIAIV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIAIVRate[Type,Age,Gender]*LungCsIANoD[Type,Gender,Age]" 
+CMC.LungCsIADiagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIADiagnosisRate[Type,Age,Gender]*LungCsIANoD[Type,Gender,Age]" 
+CMC.LungCOutputsIVNsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIVDiagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCOutputsIIIBNsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIBDiagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCProgress01IVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P01IVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P01IVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P01IVNos')" 
+
+CMC.LungCProgressIIAIIB : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIIAIIBRate[Type,Age,Gender]*LungCsIIANoD[Type,Gender,Age]" 
+CMC.LungCOutputNotProgressing1 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCNotProgressing1[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCsIIANoDPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCsIIANoD[Type,Gender,Age]" 
+CMC.LungCOutputsIIBNsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIBNoD[NonSmall,Gender!,Age!])" 
+
+CMC.LungCProgressIIAIIBRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIIBNos')" 
+
+CMC.LungCProgress0203Rate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P0203Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P0203Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P0203Nos')" 
+
+CMC.LungCsIIBNoDPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCsIIBNoD[Type,Gender,Age]" 
+CMC.LungCSmokersPercentageOfPopulation : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_DATA('LCancer.xls', 'LungC_Risk', 'PSmokingMenT', 'PSmokingMen')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_DATA('LCancer.xls', 'LungC_Risk', 'PSmokingWomenT', 'PSmokingWomen')" 
+
+CMC.LungCOutputsIVScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIVDiagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCs01Ageing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCs01[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCs01[Type,Gender,Age], -1) else -LungCs01[Type,Gender,Age]+VECTOR_MAP(LungCs01[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCOutputsIBNosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIBNoD[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCs02 : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCs02IniVal[Type,Age,Gender]" 
+
+CMC.LungCCausedDeath : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCT1Death[Type!,Stage!,Gender,Age])+sum(LungCT2Death[Type!,Stage!,Gender,Age])+sum(LungCTherapy1Mortality[Type!,Stage!,Gender,Age])" 
+
+CMC.LungCsIBDiagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIBNoD[Type,Gender,Age]*LungCsIBDiagnosisRate[Type,Age,Gender]" 
+CMC.LungCProgressIIBIV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIIBIVRate[Type,Age,Gender]*LungCsIIBNoD[Type,Gender,Age]" 
+CMC.LungCOutputCured2 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCCured2[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCsIBDiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIBNos')" 
+
+CMC.LungCTherapy1MortalityRatio : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mor')" 
+
+CMC.LungCTreated1PopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCNotProgressing1[Type,Stage,Gender,Age]" 
+CMC.LungCOutputTherapy2 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCTherapy2[Type!,Stage!,Gender!,Age!])+sum(LungCTherapyCure2[Type!,Stage!,Gender!,Age!])+sum(LungCTherapy2Failed[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCsIIBNoDIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIBNos')" 
+
+CMC.LungCs03DiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD03Nos')" 
+
+CMC.LungCsIIIANoDIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIIANos')" 
+
+CMC.LungCTreated1Ageing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCNotProgressing1[Type,Stage,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCNotProgressing1[Type,Stage,Gender,Age], -1) else -LungCNotProgressing1[Type,Stage,Gender,Age]+VECTOR_MAP(LungCNotProgressing1[Type,Stage,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCT2DisablingPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCT2Disabling[Type,Stage,Gender,Age]" 
+CMC.LungCOutputs03ScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs03Diagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCProgressIIIBIV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIIIBIVRate[Type,Age,Gender]*LungCsIIIBNoD[Type,Gender,Age]" 
+CMC.LungCProgressIIIBIVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIBIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIBIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIBIVNos')" 
+
+CMC.LungCProgressIIIAIVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIAIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIAIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIIAIVNos')" 
+
+CMC.LungCT2ProgToDisabling : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCT2Progressing[Type,Stage,Gender,Age]*LungCT2ProgToDisablingRate[Type,Stage,Age,Gender]" 
+CMC.LungCProgress03IVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P03IVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P03IVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P03IVNos')" 
+
+CMC.LungCOutputs03NosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs03[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCOutputsIIIAScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIADiagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCOutputsIIBScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIBNoD[Small,Gender!,Age!])" 
+
+CMC.LungCOutputsIIIBNosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIBDiagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.Cloud45 : SYSDYN.Cloud
+
+CMC.LungCOutputs03NosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs03Diagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCOutputs03NsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs03Diagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCOutputsIBNosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIBDiagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCOutputsIIIANsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIANoD[NonSmall,Gender!,Age!])" 
+
+CMC.LungCHealthy : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCHealthyIniVal[Age,Gender]" 
+
+CMC.LungCs01DiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD01Nos')" 
+
+CMC.LungCTreated1IniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1TrIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Tr03Nos')" 
+
+CMC.LungCProgressIBIIBRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIBIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIBIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIBIIBNos')" 
+
+CMC.LungCsIIBNoDAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCsIIBNoD[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCsIIBNoD[Type,Gender,Age], -1) else -LungCsIIBNoD[Type,Gender,Age]+VECTOR_MAP(LungCsIIBNoD[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCProgressIIIAIIIB : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIIIANoD[Type,Gender,Age]*LungCProgressIIIAIIIBRate[Type,Age,Gender]" 
+CMC.LungCOutputsIVNsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIVNoD[NonSmall,Gender!,Age!])" 
+
+CMC.LungCT1ProgressingIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1PrIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Pr03Nos')" 
+
+CMC.LungCs02Ageing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCs02[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCs02[Type,Gender,Age], -1) else -LungCs02[Type,Gender,Age]+VECTOR_MAP(LungCs02[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCOutputDisabling1 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCT1Disabling[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCOutputsIIIANsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIADiagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCsIIANoDAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCsIIANoD[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCsIIANoD[Type,Gender,Age], -1) else -LungCsIIANoD[Type,Gender,Age]+VECTOR_MAP(LungCsIIANoD[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCOutputsIIIANosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIANoD[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCProgress03IA : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgress03IARate[Type,Age,Gender]*LungCs03[Type,Gender,Age]" 
+CMC.LungCOutputsIIIANosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIADiagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCTreated2PopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCNotProgressing2[Type,Stage,Gender,Age]" 
+CMC.LungCsIIIBDiagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIIIBDiagnosisRate[Type,Age,Gender]*LungCsIIIBNoD[Type,Gender,Age]" 
+CMC.LungCInceptionRateChanges : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_DATA('LCancer.xls', 'LungC_Risk', 'B', 'C147')" 
+
+CMC.LungCNotProgressing2 : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCTreated2IniVal[Type,Stage,Age,Gender]" 
+
+CMC.LungCProgressIIBIVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIVNos')" 
+
+CMC.LungCs02Diagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCs02DiagnosisRate[Type,Age,Gender]*LungCs02[Type,Gender,Age]" 
+CMC.LungCFirstTreatmentRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "10" 
+
+CMC.LungCCured2 : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCCured2IniVal[Type,Stage,Age,Gender]" 
+
+CMC.LungCOutputs02NosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs02[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCOutputs02ScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs02[Small,Gender!,Age!])" 
+
+CMC.LungCProgressIIBIIIA : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgressIIBIIIARate[Type,Age,Gender]*LungCsIIBNoD[Type,Gender,Age]" 
+CMC.LungCs03Ageing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCs03[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCs03[Type,Gender,Age], -1) else -LungCs03[Type,Gender,Age]+VECTOR_MAP(LungCs03[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCOutputNsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01Diagnosis[NonSmall,Gender!,Age!])+sum(LungCs02Diagnosis[NonSmall,Gender!,Age!])+sum(LungCs03Diagnosis[NonSmall,Gender!,Age!])+sum(LungCsIADiagnosis[NonSmall,Gender!,Age!])+sum(LungCsIBDiagnosis[NonSmall,Gender!,Age!])+sum(LungCsIIADiagnosis[NonSmall,Gender!,Age!])+sum(LungCsIIBDiagnosis[NonSmall,Gender!,Age!])+sum(LungCsIIIADiagnosis[NonSmall,Gender!,Age!])+sum(LungCsIIIBDiagnosis[NonSmall,Gender!,Age!])+sum(LungCsIVDiagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCTherapyCure1 : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCFirstTreatmentRate*(LungCD[Type,Stage,Gender,Age]*LungCTherapy1Ratio[Type,Stage,Age,Gender]*LungCTherapy1CureRatio[Type,Stage,Age,Gender])*(1-LungCTherapy1MortalityRatio/100)" 
+CMC.LungCT2DisablingIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2DiIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Di03Nos')" 
+
+CMC.LungCsIBNoDIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIBNos')" 
+
+CMC.LungCOutputModelPopExcludingHealthy : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPop[Gender,Age]-LungCHealthy[Gender,Age]" 
+
+CMC.LungCsIIADiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIANos')" 
+
+CMC.LungCProgress0102 : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgress0102Rate[Type,Age,Gender]*LungCs01[Type,Gender,Age]" 
+CMC.LungCsIVNoDAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCsIVNoD[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCsIVNoD[Type,Gender,Age], -1) else -LungCsIVNoD[Type,Gender,Age]+VECTOR_MAP(LungCsIVNoD[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCModelPopCorrectionRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "0.9" 
+
+CMC.LungCTherapy2 : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCFirstTreatmentRate*(LungCD[Type,Stage,Gender,Age]*LungCTherapy2Ratio[Type,Stage,Age,Gender]*(1-LungCTherapy2CureRatio[Type,Stage,Age,Gender]))*(1-LungCTherapy2FailRatio/100)" 
+CMC.LungCsIIANoD : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCsIIANoDIniVal[Type,Age,Gender]" 
+
+CMC.LungCsIIIANoD : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCsIIIANoDIniVal[Type,Age,Gender]" 
+
+CMC.LungCOutputsIVNosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIVDiagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCTherapy2Ratio : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Ra03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2RaIVNos')" 
+
+CMC.LungCOutputs01NosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCCured2Ageing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCCured2[Type,Stage,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCCured2[Type,Stage,Gender,Age], -1) else -LungCCured2[Type,Stage,Gender,Age]+VECTOR_MAP(LungCCured2[Type,Stage,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCs03 : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCs03IniVal[Type,Age,Gender]" 
+
+CMC.LungCOutputs03NsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs03[NonSmall,Gender!,Age!])" 
+
+CMC.LungCOutputsIIANosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIANoD[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCsIIIANoDPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCsIIIANoD[Type,Gender,Age]" 
+CMC.LungCs01Diagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCs01DiagnosisRate[Type,Age,Gender]*LungCs01[Type,Gender,Age]" 
+CMC.LungCOutputs02NsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs02Diagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCOutputsIANosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIADiagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCProgress02IV : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCProgress02IVRate[Type,Age,Gender]*LungCs02[Type,Gender,Age]" 
+CMC.LungCT1Progressing : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCT1ProgressingIniVal[Type,Stage,Age,Gender]" 
+
+CMC.LungCOutputTherapy1Cure : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCTherapyCure1[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCsIANoDIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIANos')" 
+
+CMC.LungCOutputsIANosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIANoD[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCOutputTherapy1MortalityInTherapy : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCTherapy1Mortality[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCTreated2Ageing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCNotProgressing2[Type,Stage,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCNotProgressing2[Type,Stage,Gender,Age], -1) else -LungCNotProgressing2[Type,Stage,Gender,Age]+VECTOR_MAP(LungCNotProgressing2[Type,Stage,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCs01IniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd01Nos')" 
+
+CMC.LungCOutputDisabling2 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCT2Disabling[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCT1ProgressesRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Re03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1ReIVNos')" 
+
+CMC.LungCs02PopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCs02[Type,Gender,Age]" 
+CMC.LungCOutputsIIAScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIANoD[Small,Gender!,Age!])" 
+
+CMC.LungCsIVNoDPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIVNoD[Type,Gender,Age]*LungCModelPopCorrectionFactor[Gender,Age]" 
+CMC.LungCoutputNoDNos : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCOutputs01NosNoD+LungCOutputs02NosNoD+LungCOutputs03NosNoD+LungCOutputsIANosNoD+LungCOutputsIBNosNoD+LungCOutputsIIANosNoD+LungCOutputsIIBNosNoD+LungCOutputsIIIANosNoD+LungCOutputsIIIBNosNoD+LungCOutputsIVNosNoD" 
+
+CMC.LungCOutputsIIANosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIADiagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCs01 : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCs01IniVal[Type,Age,Gender]" 
+
+CMC.LungCOutputCured1 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCCured1[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCTherapy1CureRatio : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Cr03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1CrIVNos')" 
+
+CMC.LungCsIIIBDiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIIIBNos')" 
+
+CMC.LungCsIVDiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PDIVNos')" 
+
+CMC.LungCOutputsIIBNsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIBDiagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCOutputModelPop : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCModelPop[Gender!,Age!])" 
+
+CMC.LungCsIANoDPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCsIANoD[Type,Gender,Age]" 
+CMC.LungCCured2IniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2CrIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Cr03Nos')" 
+
+CMC.LungCModelPopCorrectionFactor : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionRate*(TotalPopulation[Gender,Age]/LungCModelPop[Gender,Age]-1)-(TotalPopulationDeath[Gender,Age]-LungCCausedDeath[Gender,Age])/LungCModelPop[Gender,Age]" 
+
+CMC.LungCTherapy2FailRatio : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Fail')" 
+
+CMC.LungCsIBNoDAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age0 then -LungCsIBNoD[Type,Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCsIBNoD[Type,Gender,Age], -1) else -LungCsIBNoD[Type,Gender,Age]+VECTOR_MAP(LungCsIBNoD[Type,Gender,Age], -1)*DummyRateForUnitsConversion" 
+CMC.LungCOutputNosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01Diagnosis[NotSmoker,Gender!,Age!])+sum(LungCs02Diagnosis[NotSmoker,Gender!,Age!])+sum(LungCs03Diagnosis[NotSmoker,Gender!,Age!])+sum(LungCsIADiagnosis[NotSmoker,Gender!,Age!])+sum(LungCsIBDiagnosis[NotSmoker,Gender!,Age!])+sum(LungCsIIADiagnosis[NotSmoker,Gender!,Age!])+sum(LungCsIIBDiagnosis[NotSmoker,Gender!,Age!])+sum(LungCsIIIADiagnosis[NotSmoker,Gender!,Age!])+sum(LungCsIIIBDiagnosis[NotSmoker,Gender!,Age!])+sum(LungCsIVDiagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCOutputNotProgressing2 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCNotProgressing2[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCOutputsIIIBNosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIBNoD[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCProgressIIBIIIBRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIBIIIBNos')" 
+
+CMC.LungCOutputT1Mortality : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCT1Death[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCOutputsIIIBNsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIBNoD[NonSmall,Gender!,Age!])" 
+
+CMC.LungCDIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDiaIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IDia03Nos')" 
+
+CMC.LungCOutputsIIANsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIANoD[NonSmall,Gender!,Age!])" 
+
+CMC.LungCProgressIIAIVRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIVNos')" 
+
+CMC.LungCOutputs01ScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01[Small,Gender!,Age!])" 
+
+CMC.LungCOutputNoDSum : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCNoDSum[Gender!,Age!])" 
+
+CMC.LungCsIVNoDIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIVNos')" 
+
+CMC.LungCT1ProgressingPopCorr : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCModelPopCorrectionFactor[Gender,Age]*LungCT1Progressing[Type,Stage,Gender,Age]" 
+CMC.LungCOutputTherapy1NoCure : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCTherapy1[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCOutputsIVScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIVNoD[Small,Gender!,Age!])" 
+
+CMC.LungCProgress0102Rate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P0102Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P0102Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'P0102Nos')" 
+
+CMC.LungCOutputDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01Diagnosis[Type!,Gender!,Age!])+sum(LungCs02Diagnosis[Type!,Gender!,Age!])+sum(LungCs03Diagnosis[Type!,Gender!,Age!])+sum(LungCsIADiagnosis[Type!,Gender!,Age!])+sum(LungCsIBDiagnosis[Type!,Gender!,Age!])+sum(LungCsIIADiagnosis[Type!,Gender!,Age!])+sum(LungCsIIBDiagnosis[Type!,Gender!,Age!])+sum(LungCsIIIADiagnosis[Type!,Gender!,Age!])+sum(LungCsIIIBDiagnosis[Type!,Gender!,Age!])+sum(LungCsIVDiagnosis[Type!,Gender!,Age!])" 
+
+CMC.LungCOutputHealthyAndTreated : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCHealthy[Gender!,Age!])+sum(LungCNotProgressing2[Type!,Stage!,Gender!,Age!])+sum(LungCNotProgressing1[Type!,Stage!,Gender!,Age!])+sum(LungCCured1[Type!,Stage!,Gender!,Age!])+sum(LungCCured2[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCOutputsIIANsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIADiagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCT2DeathRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Mo03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2MoIVNos')" 
+
+CMC.LungCProgressIAIBRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIBNos')" 
+
+CMC.LungCT2Deceased : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "0" 
+
+CMC.LungCs03IniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd03Nos')" 
+
+CMC.LungCOutputs01NsDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01Diagnosis[NonSmall,Gender!,Age!])" 
+
+CMC.LungCOutputs02NsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs02[NonSmall,Gender!,Age!])" 
+
+CMC.LungCsIIIADiagnosis : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "LungCsIIIADiagnosisRate[Type,Age,Gender]*LungCsIIIANoD[Type,Gender,Age]" 
+CMC.LungCTherapy2CureRatio : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Cr03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2CrIVNos')" 
+
+CMC.LungCHealthyIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IHe')" 
+
+CMC.LungCOutputMortality : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCCausedDeath[Gender!,Age!])" 
+
+CMC.LungCs02IniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INd02Nos')" 
+
+CMC.LungCOutputScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01Diagnosis[Small,Gender!,Age!])+sum(LungCs02Diagnosis[Small,Gender!,Age!])+sum(LungCs03Diagnosis[Small,Gender!,Age!])+sum(LungCsIADiagnosis[Small,Gender!,Age!])+sum(LungCsIBDiagnosis[Small,Gender!,Age!])+sum(LungCsIIADiagnosis[Small,Gender!,Age!])+sum(LungCsIIBDiagnosis[Small,Gender!,Age!])+sum(LungCsIIIADiagnosis[Small,Gender!,Age!])+sum(LungCsIIIBDiagnosis[Small,Gender!,Age!])+sum(LungCsIVDiagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCOutputs01NsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01[NonSmall,Gender!,Age!])" 
+
+CMC.LungCT1DeathRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1Mo03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT1MoIVNos')" 
+
+CMC.LungCProgressIAIIARate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIAIIANos')" 
+
+CMC.LungCsIIIBNoDIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'INdIIIBNos')" 
+
+CMC.LungCOutputs01NosDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01Diagnosis[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCInceptionRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIncSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIncNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIncNos')" 
+
+CMC.LungCs02DiagnosisRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PD02Nos')" 
+
+CMC.LungCNoDSum : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs01[Type!,Gender,Age])+sum(LungCs02[Type!,Gender,Age])+sum(LungCs03[Type!,Gender,Age])+sum(LungCsIANoD[Type!,Gender,Age])+sum(LungCsIBNoD[Type!,Gender,Age])+sum(LungCsIIANoD[Type!,Gender,Age])+sum(LungCsIIBNoD[Type!,Gender,Age])+sum(LungCsIIIANoD[Type!,Gender,Age])+sum(LungCsIIIBNoD[Type!,Gender,Age])+sum(LungCsIVNoD[Type!,Gender,Age])" 
+
+CMC.LungCOutputsIIIAScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIANoD[Small,Gender!,Age!])" 
+
+CMC.LungCHealthyAgeing : SYSDYN.Valve
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "(if Age==Age0 then -LungCHealthy[Gender,Age] elseif Age==Age100 then +VECTOR_MAP(LungCHealthy[Gender,Age], -1) else -LungCHealthy[Gender,Age]+VECTOR_MAP(LungCHealthy[Gender,Age], -1))*DummyRateForUnitsConversion" 
+CMC.LungCsIVNoD : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCsIVNoDIniVal[Type,Age,Gender]" 
+
+CMC.LungCOutputsIIIBScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIIBNoD[Small,Gender!,Age!])" 
+
+CMC.LungCOutputs02ScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCs02Diagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCOutputsIBNsNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIBNoD[NonSmall,Gender!,Age!])" 
+
+CMC.LungCT2ProgToDisablingRate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2Di03Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PT2DiIVNos')" 
+
+CMC.LungCOutputsIAScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIANoD[Small,Gender!,Age!])" 
+
+CMC.LungCCured1IniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1CrIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT1Cr03Nos')" 
+
+CMC.LungCOutputT2Mortality : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCT2Death[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCOutputTherapy2NoCure : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCTherapy2[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCOutputsIBScNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIBNoD[Small,Gender!,Age!])" 
+
+CMC.LungCOutputsIIBScDiagnosis : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIIBDiagnosis[Small,Gender!,Age!])" 
+
+CMC.LungCsIIBNoD : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCsIIBNoDIniVal[Type,Age,Gender]" 
+
+CMC.LungCT2ProgressingIniVal : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIIBSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIVSm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr01Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr02Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr03Sm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIIBNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIVNs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr01Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr02Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr03Ns')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIIANos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIIIBNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2PrIVNos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr01Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr02Nos')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'IT2Pr03Nos')" 
+
+CMC.LungCOutputTherapy2Failed : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCTherapy2Failed[Type!,Stage!,Gender!,Age!])" 
+
+CMC.LungCOutputsIVNosNoD : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(LungCsIVNoD[NotSmoker,Gender!,Age!])" 
+
+CMC.LungCsIANoD : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCsIANoDIniVal[Type,Age,Gender]" 
+
+CMC.LungCT2Disabling : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCT2DisablingIniVal[Type,Stage,Age,Gender]" 
+
+CMC.LungCProgressIIAIIIARate : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIIIASm')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIIIANs')" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_CONSTANT('LCancer.xls', 'LungC_In', 'PIIAIIIANos')" 
+
+CMC.LungCD : SYSDYN.Stock
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,sIA,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,sIB,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,sIIA,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,sIIB,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,sIIIA,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,sIIIB,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,sIV,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,s03,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,s02,Age,Gender]" 
+            _ : SYSDYN.StockExpression
+                SYSDYN.HasInitialEquation "LungCDIniVal[Type,s01,Age,Gender]" 
+
+CMC.d127  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCD
+CMC.d882  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputs01NosNoD
+CMC.d331  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIANoDAgeing CMC.DummyRateForUnitsConversion
+CMC.d737  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCs02Diagnosis
+CMC.f580  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgressIIIBIV
+CMC.f805  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCTherapyCure1 CMC.LungCD
+CMC.d84  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1Progresses CMC.LungCNotProgressing1
+CMC.d463  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCNotProgressing2
+CMC.f517  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgress03IV
+CMC.d458  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCsIIIBNoD
+CMC.d451  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCs02
+CMC.d220  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1ProgressingPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d454  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCsIBNoD
+CMC.d846  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy1 CMC.LungCTherapyCure1
+CMC.d722  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCsIVDiagnosis
+CMC.d578  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIIBIV CMC.LungCsIIIBNoD
+CMC.d695  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs03NsDiagnosis CMC.LungCs03Diagnosis
+CMC.d728  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCsIIADiagnosis
+CMC.d742  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCsIIBDiagnosis
+CMC.d378  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIBDiagnosis CMC.LungCsIBNoD
+CMC.d325  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIANoDPopCorr CMC.LungCsIIANoD
+CMC.f29  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Progressing CMC.LungCT1Progresses
+CMC.d889  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputsIIIANosNoD
+CMC.d572  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIAIV CMC.LungCsIIANoD
+CMC.f540  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIIBIV CMC.LungCsIIIBNoD
+CMC.d58  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCInception CMC.LungCHealthy
+CMC.d211  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1Death CMC.LungCT1DeathRate
+CMC.f15  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs02 CMC.LungCProgress0102
+CMC.d861  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputs01NsNoD
+CMC.f337  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIBNoD CMC.LungCsIIBNoDAgeing
+CMC.d101  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTreated1Ageing CMC.DummyRateForUnitsConversion
+CMC.d340  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIBNoDAgeing CMC.LungCsIIBNoD
+CMC.f76  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCNotProgressing1 CMC.LungCTreated1Ageing
+CMC.d62  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs01Ageing CMC.LungCs01
+CMC.d833  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured2Ageing CMC.DummyRateForUnitsConversion
+CMC.d571  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIAIV CMC.LungCProgressIIAIVRate
+CMC.f139  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs01 CMC.LungCs01PopCorr
+CMC.d129  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPopCorrectionFactor CMC.TotalPopulationDeath
+CMC.d917  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure2 CMC.LungCTherapy2FailRatio
+CMC.d926  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy2Failed CMC.LungCTherapy2Failed
+CMC.d548  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIANoD CMC.LungCsIIANoDIniVal
+CMC.f495  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCs02Diagnosis
+CMC.d739  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCsIADiagnosis
+CMC.d876  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputsIBScNoD
+CMC.d662  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs02ScNoD CMC.LungCs02
+CMC.d783  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIANosDiagnosis CMC.LungCsIIIADiagnosis
+CMC.d758  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs03NosNoD CMC.LungCs03
+CMC.f236  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIANoD CMC.LungCProgress03IA
+CMC.d706  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIAScDiagnosis CMC.LungCsIIIADiagnosis
+CMC.f348  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIANoD CMC.LungCsIIIANoDAgeing
+CMC.f145  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIANoD CMC.LungCsIANoDPopCorr
+CMC.d627  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputProgressing2 CMC.LungCT2Progressing
+CMC.d715  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCs03Diagnosis
+CMC.f23  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCNotProgressing1 CMC.LungCTherapy1
+CMC.f364  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCsIVNoDAgeing
+CMC.d96  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2 CMC.LungCFirstTreatmentRate
+CMC.d486  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNotProgressing1 CMC.LungCTreated1IniVal
+CMC.f509  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgress01IV
+CMC.d160  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTreated2PopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d569  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIBIV CMC.LungCProgressIBIVRate
+CMC.d367  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIVNoDAgeing CMC.LungCsIVNoD
+CMC.d716  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCsIADiagnosis
+CMC.d391  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIBDiagnosis CMC.LungCsIIBDiagnosisRate
+CMC.d778  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs03NosDiagnosis CMC.LungCs03Diagnosis
+CMC.d743  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCsIIIADiagnosis
+CMC.d720  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCsIIIADiagnosis
+CMC.d723  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCs01Diagnosis
+CMC.d453  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCsIANoD
+CMC.d180  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2ProgressingAgeing CMC.DummyRateForUnitsConversion
+CMC.d244  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress0203 CMC.LungCs02
+CMC.d351  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIANoDAgeing CMC.DummyRateForUnitsConversion
+CMC.f246  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs02 CMC.LungCs02PopCorr
+CMC.d488  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1Disabling CMC.LungCT1DisablingIniVal
+CMC.d835  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured2PopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d415  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIAIB CMC.LungCProgressIAIBRate
+CMC.d452  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCs03
+CMC.f342  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIANoD CMC.LungCsIIIANoDPopCorr
+CMC.d862  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputs02NsNoD
+CMC.f579  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgressIIIAIV
+CMC.f295  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIBIIIA CMC.LungCsIIBNoD
+CMC.d341  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIBNoDAgeing CMC.DummyRateForUnitsConversion
+CMC.d87  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1Progresses CMC.LungCT1ProgressesRate
+CMC.d508  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs01Diagnosis CMC.LungCs01DiagnosisRate
+CMC.d221  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1ProgressingPopCorr CMC.LungCT1Progressing
+CMC.d64  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress0102 CMC.LungCProgress0102Rate
+CMC.d417  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIBIIB CMC.LungCProgressIBIIBRate
+CMC.f12  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCInception CMC.LungCHealthy
+CMC.d881  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputsIVScNoD
+CMC.d765  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIVNosNoD CMC.LungCsIVNoD
+CMC.d784  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIBNosDiagnosis CMC.LungCsIIIBDiagnosis
+CMC.d507  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs01Diagnosis CMC.LungCs01
+CMC.d405  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIADiagnosis CMC.LungCsIIANoD
+CMC.d573  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIBIV CMC.LungCProgressIIBIVRate
+CMC.f237  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgress03IA CMC.LungCs03
+CMC.f370  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCsIVNoDPopCorr
+CMC.f309  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIBNoD CMC.LungCsIBNoDPopCorr
+CMC.d762  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIBNosNoD CMC.LungCsIIBNoD
+CMC.d734  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCInception CMC.LungCInceptionRateChanges
+CMC.d875  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputsIAScNoD
+CMC.d567  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress03IV CMC.LungCs03
+CMC.d116  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCausedDeath CMC.LungCT2Death
+CMC.d144  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs01PopCorr CMC.LungCs01
+CMC.d914  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2Failed CMC.LungCFirstTreatmentRate
+CMC.d380  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIBDiagnosis CMC.LungCsIBDiagnosisRate
+CMC.d100  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs01Ageing CMC.DummyRateForUnitsConversion
+CMC.f824  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCCured2 CMC.LungCCured2PopCorr
+CMC.d661  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs01ScNoD CMC.LungCs01
+CMC.f286  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIBNoD CMC.LungCProgressIIAIIB
+CMC.d800  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured1PopCorr CMC.LungCCured1
+CMC.f381  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIADiagnosis CMC.LungCsIIANoD
+CMC.d581  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCsIVNoDIniVal
+CMC.d308  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIIAIIIB CMC.LungCsIIIANoD
+CMC.f392  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIADiagnosis CMC.LungCsIIIANoD
+CMC.f177  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Progressing CMC.LungCT2ProgressingAgeing
+CMC.f496  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs02Diagnosis CMC.LungCs02
+CMC.d605  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCsIBDiagnosis
+CMC.d373  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIVNoDPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d607  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCsIIBDiagnosis
+CMC.d813  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCCured1
+CMC.f42  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Death CMC.LungCT2Disabling
+CMC.f205  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Death CMC.LungCT1Disabling
+CMC.d759  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIANosNoD CMC.LungCsIANoD
+CMC.d644  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIANsNoD CMC.LungCsIANoD
+CMC.d851  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy2Cure CMC.LungCTherapyCure2
+CMC.d927  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCausedDeath CMC.LungCTherapy1Mortality
+CMC.d694  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs02ScDiagnosis CMC.LungCs02Diagnosis
+CMC.d213  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1Death CMC.LungCT1Disabling
+CMC.d51  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCBirth CMC.TotalPopulationBirth
+CMC.d456  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCsIIBNoD
+CMC.d568  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIAIV CMC.LungCsIANoD
+CMC.d874  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputs03ScNoD
+CMC.d171  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2ProgressingPopCorr CMC.LungCT2Progressing
+CMC.d916  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2Failed CMC.LungCTherapy2FailRatio
+CMC.f386  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIBDiagnosis CMC.LungCsIIBNoD
+CMC.d796  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured1Ageing CMC.LungCCured1
+CMC.f200  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Disabling CMC.LungCT1ProgToDisabling
+CMC.f525  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgressIBIV
+CMC.d787  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCInception CMC.LungCSmokersPercentageOfPopulation
+CMC.d161  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTreated2PopCorr CMC.LungCNotProgressing2
+CMC.d919  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2Failed CMC.LungCTherapy2Ratio
+CMC.f534  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIBIV CMC.LungCsIIBNoD
+CMC.d744  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCsIIIBDiagnosis
+CMC.f20  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIADiagnosis CMC.LungCsIANoD
+CMC.d888  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputsIIBNosNoD
+CMC.d557  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress02IV CMC.LungCs02
+CMC.d718  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCsIIADiagnosis
+CMC.d468  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCNoDSum
+CMC.d700  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIBScDiagnosis CMC.LungCsIBDiagnosis
+CMC.f287  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIAIIB CMC.LungCsIIANoD
+CMC.f475  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCTherapy2 CMC.LungCD
+CMC.d868  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputsIIIANsNoD
+CMC.f294  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIANoD CMC.LungCProgressIIBIIIA
+CMC.d413  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIIAIIIB CMC.LungCProgressIIIAIIIBRate
+CMC.d932  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputRelapse CMC.LungCT2Progresses
+CMC.d764  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIBNosNoD CMC.LungCsIIIBNoD
+CMC.f275  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIBNoD CMC.LungCProgressIAIB
+CMC.d803  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured1PopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d606  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCsIIADiagnosis
+CMC.d724  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCs02Diagnosis
+CMC.d691  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs01NsDiagnosis CMC.LungCs01Diagnosis
+CMC.d666  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIAScNoD CMC.LungCsIIANoD
+CMC.d432  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIVDiagnosis CMC.LungCsIVDiagnosisRate
+CMC.d346  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIANoDPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.f911  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCTherapy2Failed CMC.LungCD
+CMC.d907  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy1 CMC.LungCTherapy1Mortality
+CMC.d708  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIBScDiagnosis CMC.LungCsIIIBDiagnosis
+CMC.d650  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIVNsNoD CMC.LungCsIVNoD
+CMC.d710  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIVScDiagnosis CMC.LungCsIVDiagnosis
+CMC.f895  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Deceased CMC.LungCTherapy1Mortality
+CMC.d856  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputHealthyAndTreated CMC.LungCCured1
+CMC.d69  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIANoDAgeing CMC.LungCsIANoD
+CMC.d664  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIAScNoD CMC.LungCsIANoD
+CMC.d545  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs03 CMC.LungCs03IniVal
+CMC.f191  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIANoD CMC.LungCProgressIAIIA
+CMC.f224  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Disabling CMC.LungCT1DisablingPopCorr
+CMC.d187  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputModelPop CMC.LungCModelPop
+CMC.d646  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIANsNoD CMC.LungCsIIANoD
+CMC.d262  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs03PopCorr CMC.LungCs03
+CMC.d79  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTreated1Ageing CMC.LungCNotProgressing1
+CMC.d212  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1ProgToDisabling CMC.LungCT1Progressing
+CMC.d352  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIANoDAgeing CMC.LungCsIIIANoD
+CMC.d126  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCHealthy
+CMC.d251  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs02PopCorr CMC.LungCs02
+CMC.f426  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCsIIIBDiagnosis
+CMC.f279  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIBIIB CMC.LungCsIBNoD
+CMC.d176  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2DisablingPopCorr CMC.LungCT2Disabling
+CMC.d256  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs02Ageing CMC.DummyRateForUnitsConversion
+CMC.d810  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1 CMC.LungCTherapy1CureRatio
+CMC.d574  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIBIV CMC.LungCsIIBNoD
+CMC.d170  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2ProgressingPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.f33  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Progressing CMC.LungCT2Progresses
+CMC.d920  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2Failed CMC.LungCD
+CMC.f428  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCsIVDiagnosis
+CMC.d887  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputsIIANosNoD
+CMC.d227  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1DisablingPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.f26  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCNotProgressing2 CMC.LungCTherapy2
+CMC.d99  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCHealthyAgeing CMC.DummyRateForUnitsConversion
+CMC.d566  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIAIV CMC.LungCProgressIAIVRate
+CMC.f526  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIBIV CMC.LungCsIBNoD
+CMC.d72  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIADiagnosis CMC.LungCsIADiagnosisRate
+CMC.d869  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputsIIIANsNoD
+CMC.d806  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure1 CMC.LungCFirstTreatmentRate
+CMC.d255  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs02Ageing CMC.LungCs02
+CMC.d500  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs02Diagnosis CMC.LungCs02DiagnosisRate
+CMC.f790  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCCured1 CMC.LungCTherapyCure1
+CMC.f533  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgressIIBIV
+CMC.d918  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2 CMC.LungCTherapy2FailRatio
+CMC.d604  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCsIADiagnosis
+CMC.d556  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress02IV CMC.LungCProgress02IVRate
+CMC.d717  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCsIBDiagnosis
+CMC.f232  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs03 CMC.LungCProgress0203
+CMC.d462  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCNotProgressing1
+CMC.d843  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCCured2
+CMC.d815  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputCured1 CMC.LungCCured1
+CMC.d330  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIANoDAgeing CMC.LungCsIIANoD
+CMC.f263  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs03 CMC.LungCs03Ageing
+CMC.f167  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Progressing CMC.LungCT2ProgressingPopCorr
+CMC.d360  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIBNoDPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d692  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs01ScDiagnosis CMC.LungCs01Diagnosis
+CMC.d610  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCsIVDiagnosis
+CMC.f514  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgress02IV CMC.LungCs02
+CMC.d931  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputRelapse CMC.LungCT1Progresses
+CMC.d725  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCs03Diagnosis
+CMC.d663  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs03ScNoD CMC.LungCs03
+CMC.f513  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgress02IV
+CMC.d854  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy1NoCure CMC.LungCTherapy1
+CMC.f797  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCCured1 CMC.LungCCured1PopCorr
+CMC.f510  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgress01IV CMC.LungCs01
+CMC.d549  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIBNoD CMC.LungCsIIBNoDIniVal
+CMC.d877  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputsIIAScNoD
+CMC.d645  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIBNsNoD CMC.LungCsIBNoD
+CMC.f322  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIANoD CMC.LungCsIIANoDPopCorr
+CMC.f469  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCDAgeing
+CMC.f353  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIBNoD CMC.LungCsIIIBNoDPopCorr
+CMC.d575  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIIAIV CMC.LungCProgressIIIAIVRate
+CMC.f375  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIBDiagnosis CMC.LungCsIBNoD
+CMC.d709  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIVNsDiagnosis CMC.LungCsIVDiagnosis
+CMC.d128  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPopCorrectionFactor CMC.LungCCausedDeath
+CMC.d589  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNotProgressing2 CMC.LungCNotProgressing2
+CMC.d250  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs02PopCorr CMC.LungCModelPopCorrectionFactor
+CMC.f192  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIAIIA CMC.LungCsIANoD
+CMC.d303  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIBIIB CMC.LungCsIBNoD
+CMC.d614  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy2 CMC.LungCTherapy2
+CMC.d699  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIBNsDiagnosis CMC.LungCsIBDiagnosis
+CMC.d501  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs02Diagnosis CMC.LungCs02
+CMC.f278  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIBNoD CMC.LungCProgressIBIIB
+CMC.d490  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNotProgressing2 CMC.LungCTreated2IniVal
+CMC.f150  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCNotProgressing1 CMC.LungCTreated1PopCorr
+CMC.d155  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTreated1PopCorr CMC.LungCNotProgressing1
+CMC.d130  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPopCorrectionFactor CMC.TotalPopulation
+CMC.d245  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress03IA CMC.LungCs03
+CMC.d626  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDisabling1 CMC.LungCT1Disabling
+CMC.d543  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs01 CMC.LungCs01IniVal
+CMC.d583  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2 CMC.LungCTherapy2Ratio
+CMC.f257  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs03 CMC.LungCs03PopCorr
+CMC.d782  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIBNosDiagnosis CMC.LungCsIIBDiagnosis
+CMC.d85  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2Progresses CMC.LungCNotProgressing2
+CMC.d809  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure1 CMC.LungCTherapy1CureRatio
+CMC.f332  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIBNoD CMC.LungCsIIBNoDPopCorr
+CMC.f425  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCsIIIADiagnosis
+CMC.d745  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCsIVDiagnosis
+CMC.f34  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Progresses CMC.LungCNotProgressing2
+CMC.d832  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure2 CMC.LungCFirstTreatmentRate
+CMC.d736  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCs01Diagnosis
+CMC.d781  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIANosDiagnosis CMC.LungCsIIADiagnosis
+CMC.d603  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCs03Diagnosis
+CMC.d828  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure2 CMC.LungCTherapy2Ratio
+CMC.d90  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2ProgToDisabling CMC.LungCT2Progressing
+CMC.d102  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTreated2Ageing CMC.DummyRateForUnitsConversion
+CMC.d565  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress03IV CMC.LungCProgress03IVRate
+CMC.d620  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputT2Mortality CMC.LungCT2Death
+CMC.d850  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy2NoCure CMC.LungCTherapy2
+CMC.d891  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputsIVNosNoD
+CMC.f16  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgress0102 CMC.LungCs01
+CMC.d730  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCsIIIADiagnosis
+CMC.d921  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCD CMC.LungCDIniVal
+CMC.d55  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCHealthyAgeing CMC.LungCHealthy
+CMC.f233  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgress0203 CMC.LungCs02
+CMC.d57  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCInception CMC.LungCInceptionRate
+CMC.d368  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIVNoDAgeing CMC.DummyRateForUnitsConversion
+CMC.f424  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCsIIADiagnosis
+CMC.d872  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputs01ScNoD
+CMC.d316  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIBNoDPopCorr CMC.LungCsIBNoD
+CMC.d89  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2ProgToDisabling CMC.LungCT2ProgToDisablingRate
+CMC.d175  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2DisablingPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.f11  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs01 CMC.LungCInception
+CMC.d492  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2Progressing CMC.LungCT2ProgressingIniVal
+CMC.d347  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIANoDPopCorr CMC.LungCsIIIANoD
+CMC.d842  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputCured2 CMC.LungCCured2
+CMC.d665  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIBScNoD CMC.LungCsIBNoD
+CMC.f434  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCs03Diagnosis
+CMC.d93  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2Death CMC.LungCT2DeathRate
+CMC.d899  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1Mortality CMC.LungCFirstTreatmentRate
+CMC.d865  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputsIBNsNoD
+CMC.f291  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIBIIIB CMC.LungCsIIBNoD
+CMC.d374  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIVNoDPopCorr CMC.LungCsIVNoD
+CMC.d904  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1 CMC.LungCTherapy1MortalityRatio
+CMC.f429  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVDiagnosis CMC.LungCsIVNoD
+CMC.d649  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIBNsNoD CMC.LungCsIIIBNoD
+CMC.d409  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIAIIIA CMC.LungCProgressIIAIIIARate
+CMC.d642  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs02NsNoD CMC.LungCs02
+CMC.d648  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIANsNoD CMC.LungCsIIIANoD
+CMC.d886  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputsIBNosNoD
+CMC.d585  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2Progresses CMC.LungCT2ProgressesRate
+CMC.f327  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIANoD CMC.LungCsIIANoDAgeing
+CMC.d727  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCsIBDiagnosis
+CMC.d320  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIBNoDAgeing CMC.LungCsIBNoD
+CMC.d732  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCsIVDiagnosis
+CMC.d811  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured1 CMC.LungCCured1IniVal
+CMC.d361  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIBNoDPopCorr CMC.LungCsIIIBNoD
+CMC.d465  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCT1Disabling
+CMC.d184  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputHealthyAndTreated CMC.LungCNotProgressing1
+CMC.d776  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs01NosDiagnosis CMC.LungCs01Diagnosis
+CMC.d894  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputModelPopExcludingHealthy CMC.LungCHealthy
+CMC.d131  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPopCorrectionFactor CMC.LungCModelPopCorrectionRate
+CMC.d181  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2ProgressingAgeing CMC.LungCT2Progressing
+CMC.d385  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIADiagnosis CMC.LungCsIIADiagnosisRate
+CMC.f502  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCs01Diagnosis
+CMC.d307  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIBIIIA CMC.LungCsIIBNoD
+CMC.d801  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured1Ageing CMC.DummyRateForUnitsConversion
+CMC.d154  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTreated1PopCorr CMC.LungCModelPopCorrectionFactor
+CMC.f830  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCTherapyCure2 CMC.LungCD
+CMC.d553  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress01IV CMC.LungCProgress01IVRate
+CMC.d747  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs01NosNoD CMC.LungCs01
+CMC.d847  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy2 CMC.LungCTherapyCure2
+CMC.d704  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIBScDiagnosis CMC.LungCsIIBDiagnosis
+CMC.d326  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIANoDPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.f47  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCBirth CMC.Cloud45
+CMC.d619  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputT1Mortality CMC.LungCT1Death
+CMC.f37  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Disabling CMC.LungCT2ProgToDisabling
+CMC.d335  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIBNoDPopCorr CMC.LungCsIIBNoD
+CMC.d855  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy1Cure CMC.LungCTherapyCure1
+CMC.d195  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIAIIA CMC.LungCsIANoD
+CMC.d698  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIAScDiagnosis CMC.LungCsIADiagnosis
+CMC.d554  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress01IV CMC.LungCs01
+CMC.d831  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure2 CMC.LungCD
+CMC.f521  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgressIAIV
+CMC.f162  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCDPopCorr
+CMC.d433  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIVDiagnosis CMC.LungCsIVNoD
+CMC.d780  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIBNosDiagnosis CMC.LungCsIBDiagnosis
+CMC.d880  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputsIIIBScNoD
+CMC.d647  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIBNsNoD CMC.LungCsIIBNoD
+CMC.d74  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2 CMC.LungCD
+CMC.d440  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs03Diagnosis CMC.LungCs03
+CMC.d890  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputsIIIBNosNoD
+CMC.d740  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCsIBDiagnosis
+CMC.f299  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIIAIIIB CMC.LungCsIIIANoD
+CMC.d103  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIANoDAgeing CMC.DummyRateForUnitsConversion
+CMC.d922  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2Disabling CMC.LungCT2DisablingIniVal
+CMC.f201  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1ProgToDisabling CMC.LungCT1Progressing
+CMC.d602  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCs02Diagnosis
+CMC.d871  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputsIVNsNoD
+CMC.f423  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCsIIBDiagnosis
+CMC.d719  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCsIIBDiagnosis
+CMC.d902  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1Mortality CMC.LungCTherapy1MortalityRatio
+CMC.d827  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured2PopCorr CMC.LungCCured2
+CMC.d91  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT2Death CMC.LungCT2Disabling
+CMC.d266  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs03Ageing CMC.LungCs03
+CMC.d467  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCT2Disabling
+CMC.d701  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIANsDiagnosis CMC.LungCsIIADiagnosis
+CMC.f474  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCTherapy1 CMC.LungCD
+CMC.f820  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCCured2 CMC.LungCCured2Ageing
+CMC.d867  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputsIIBNsNoD
+CMC.f214  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Progressing CMC.LungCT1ProgressingPopCorr
+CMC.f422  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCsIBDiagnosis
+CMC.f817  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCCured2 CMC.LungCTherapyCure2
+CMC.d905  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1Mortality CMC.LungCD
+CMC.d97  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1 CMC.LungCTherapy1Ratio
+CMC.f41  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Deceased CMC.LungCT2Death
+CMC.d731  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCsIIIBDiagnosis
+CMC.d668  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIAScNoD CMC.LungCsIIIANoD
+CMC.f52  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCHealthy CMC.LungCHealthyAgeing
+CMC.d302  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIAIB CMC.LungCsIANoD
+CMC.d229  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCausedDeath CMC.LungCT1Death
+CMC.d866  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputsIIANsNoD
+CMC.f910  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Progressing CMC.LungCTherapy2Failed
+CMC.d693  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs02NsDiagnosis CMC.LungCs02Diagnosis
+CMC.f503  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs01Diagnosis CMC.LungCs01
+CMC.d315  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIBNoDPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d402  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIBDiagnosis CMC.LungCsIIIBNoD
+CMC.d641  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs01NsNoD CMC.LungCs01
+CMC.d893  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputModelPopExcludingHealthy CMC.LungCModelPop
+CMC.d576  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIIAIV CMC.LungCsIIIANoD
+CMC.d761  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIANosNoD CMC.LungCsIIANoD
+CMC.d838  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure2 CMC.LungCTherapy2CureRatio
+CMC.d222  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1ProgressingAgeing CMC.LungCT1Progressing
+CMC.d616  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputMortality CMC.LungCCausedDeath
+CMC.d738  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCs03Diagnosis
+CMC.d83  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTreated2Ageing CMC.LungCNotProgressing2
+CMC.d804  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure1 CMC.LungCTherapy1Ratio
+CMC.d870  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputsIIIBNsNoD
+CMC.d305  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIAIIB CMC.LungCsIIANoD
+CMC.f896  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCTherapy1Mortality CMC.LungCD
+CMC.d544  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs02 CMC.LungCs02IniVal
+CMC.f217  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Progressing CMC.LungCT1ProgressingAgeing
+CMC.d122  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCHealthyPopCorr CMC.LungCHealthy
+CMC.d777  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs02NosDiagnosis CMC.LungCs02Diagnosis
+CMC.d143  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs01PopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d269  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs03Ageing CMC.DummyRateForUnitsConversion
+CMC.d464  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCT1Progressing
+CMC.d628  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDisabling2 CMC.LungCT2Disabling
+CMC.d878  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputsIIBScNoD
+CMC.d363  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIBNoDAgeing CMC.DummyRateForUnitsConversion
+CMC.f46  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCHealthy CMC.LungCBirth
+CMC.d630  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSum CMC.LungCNoDSum
+CMC.d183  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputHealthyAndTreated CMC.LungCHealthy
+CMC.f518  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgress03IV CMC.LungCs03
+CMC.d472  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCDAgeing CMC.LungCD
+CMC.d362  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIBNoDAgeing CMC.LungCsIIIBNoD
+CMC.d439  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs03Diagnosis CMC.LungCs03DiagnosisRate
+CMC.f317  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIBNoD CMC.LungCsIBNoDAgeing
+CMC.d608  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCsIIIADiagnosis
+CMC.d132  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPopCorrectionFactor CMC.LungCModelPop
+CMC.d411  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIAIIB CMC.LungCProgressIIAIIBRate
+CMC.d705  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIANsDiagnosis CMC.LungCsIIIADiagnosis
+CMC.f398  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIBDiagnosis CMC.LungCsIIIBNoD
+CMC.d836  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured2 CMC.LungCCured2IniVal
+CMC.d546  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIANoD CMC.LungCsIANoDIniVal
+CMC.d407  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIAIIA CMC.LungCProgressIAIIARate
+CMC.f537  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIIAIV CMC.LungCsIIIANoD
+CMC.f522  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIAIV CMC.LungCsIANoD
+CMC.d785  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIVNosDiagnosis CMC.LungCsIVDiagnosis
+CMC.d587  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNotProgressing1 CMC.LungCNotProgressing1
+CMC.d609  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCsIIIBDiagnosis
+CMC.d667  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIBScNoD CMC.LungCsIIBNoD
+CMC.d741  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNosDiagnosis CMC.LungCsIIADiagnosis
+CMC.f298  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIBNoD CMC.LungCProgressIIIAIIIB
+CMC.d95  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1 CMC.LungCFirstTreatmentRate
+CMC.d714  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCs02Diagnosis
+CMC.d601  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputDiagnosis CMC.LungCs01Diagnosis
+CMC.d243  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress03IA CMC.LungCProgress03IARate
+CMC.d779  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIANosDiagnosis CMC.LungCsIADiagnosis
+CMC.d551  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIBNoD CMC.LungCsIIIBNoDIniVal
+CMC.f529  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIVNoD CMC.LungCProgressIIAIV
+CMC.d697  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIANsDiagnosis CMC.LungCsIADiagnosis
+CMC.d726  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCsIADiagnosis
+CMC.d397  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIADiagnosis CMC.LungCsIIIANoD
+CMC.d857  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputHealthyAndTreated CMC.LungCCured2
+CMC.d707  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIBNsDiagnosis CMC.LungCsIIIBDiagnosis
+CMC.d65  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress0102 CMC.LungCs01
+CMC.d261  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCs03PopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d459  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCsIVNoD
+CMC.d321  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIBNoDAgeing CMC.DummyRateForUnitsConversion
+CMC.d823  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCCured2Ageing CMC.LungCCured2
+CMC.d903  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure1 CMC.LungCTherapy1MortalityRatio
+CMC.f204  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Deceased CMC.LungCT1Death
+CMC.d165  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCDPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d729  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputScDiagnosis CMC.LungCsIIBDiagnosis
+CMC.f435  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs03Diagnosis CMC.LungCs03
+CMC.d924  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy2 CMC.LungCTherapy2Failed
+CMC.d885  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputsIANosNoD
+CMC.d884  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputs03NosNoD
+CMC.d228  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1DisablingPopCorr CMC.LungCT1Disabling
+CMC.d760  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIBNosNoD CMC.LungCsIBNoD
+CMC.d863  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputs03NsNoD
+CMC.d749  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs02NosNoD CMC.LungCs02
+CMC.d268  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIANoDPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.f172  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2Disabling CMC.LungCT2DisablingPopCorr
+CMC.f404  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIAIB CMC.LungCsIANoD
+CMC.d223  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1ProgressingAgeing CMC.DummyRateForUnitsConversion
+CMC.d613  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy1 CMC.LungCTherapy1
+CMC.d721  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCsIIIBDiagnosis
+CMC.f282  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIANoD CMC.LungCProgressIIAIIIA
+CMC.d669  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIBScNoD CMC.LungCsIIIBNoD
+CMC.d121  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCHealthyPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d702  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIAScDiagnosis CMC.LungCsIIADiagnosis
+CMC.d487  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1Progressing CMC.LungCT1ProgressingIniVal
+CMC.d873  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputs02ScNoD
+CMC.d577  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIIBIV CMC.LungCProgressIIIBIVRate
+CMC.d209  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCT1ProgToDisabling CMC.LungCT1ProgToDisablingRate
+CMC.f117  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCHealthy CMC.LungCHealthyPopCorr
+CMC.d643  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs03NsNoD CMC.LungCs03
+CMC.d455  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCsIIANoD
+CMC.f80  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCNotProgressing2 CMC.LungCTreated2Ageing
+CMC.d336  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIBNoDPopCorr CMC.LungCModelPopCorrectionFactor
+CMC.d457  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCsIIIANoD
+CMC.d696  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputs03ScDiagnosis CMC.LungCs03Diagnosis
+CMC.d713  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNsDiagnosis CMC.LungCs01Diagnosis
+CMC.d879  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDSc CMC.LungCOutputsIIIAScNoD
+CMC.d550  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIANoD CMC.LungCsIIIANoDIniVal
+CMC.d670  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIVScNoD CMC.LungCsIVNoD
+CMC.d419  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIBIIIA CMC.LungCProgressIIBIIIARate
+CMC.f290  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIBNoD CMC.LungCProgressIIBIIIB
+CMC.d149  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIANoDPopCorr CMC.LungCsIANoD
+CMC.d625  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputProgressing1 CMC.LungCT1Progressing
+CMC.d304  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIAIIIA CMC.LungCsIIANoD
+CMC.d547  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIBNoD CMC.LungCsIBNoDIniVal
+CMC.d396  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIADiagnosis CMC.LungCsIIIADiagnosisRate
+CMC.f530  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIAIV CMC.LungCsIIANoD
+CMC.f66  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIANoD CMC.LungCsIANoDAgeing
+CMC.f19  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCD CMC.LungCsIADiagnosis
+CMC.d306  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIBIIIB CMC.LungCsIIBNoD
+CMC.d763  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIIANosNoD CMC.LungCsIIIANoD
+CMC.d70  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIADiagnosis CMC.LungCsIANoD
+CMC.d839  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy2 CMC.LungCTherapy2CureRatio
+CMC.f793  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCCured1 CMC.LungCCured1Ageing
+CMC.d166  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCDPopCorr CMC.LungCD
+CMC.f30  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT1Progresses CMC.LungCNotProgressing1
+CMC.d570  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIBIV CMC.LungCsIBNoD
+CMC.d909  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputTherapy1MortalityInTherapy CMC.LungCTherapy1Mortality
+CMC.d403  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIIBDiagnosis CMC.LungCsIIIBDiagnosisRate
+CMC.d466  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCModelPop CMC.LungCT2Progressing
+CMC.f252  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs02 CMC.LungCs02Ageing
+CMC.d883  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCoutputNoDNos CMC.LungCOutputs02NosNoD
+CMC.f283  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCProgressIIAIIIA CMC.LungCsIIANoD
+CMC.d134  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCHealthy CMC.LungCHealthyIniVal
+CMC.d75  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1 CMC.LungCD
+CMC.f156  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCNotProgressing2 CMC.LungCTreated2PopCorr
+CMC.d421  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgressIIBIIIB CMC.LungCProgressIIBIIIBRate
+CMC.f59  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCs01 CMC.LungCs01Ageing
+CMC.d450  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCNoDSum CMC.LungCs01
+CMC.d703  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputsIIBNsDiagnosis CMC.LungCsIIBDiagnosis
+CMC.d864  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputNoDNs CMC.LungCOutputsIANsNoD
+CMC.d900  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapy1Mortality CMC.LungCTherapy1Ratio
+CMC.d473  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCDAgeing CMC.DummyRateForUnitsConversion
+CMC.d185  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCOutputHealthyAndTreated CMC.LungCNotProgressing2
+CMC.d390  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCsIIBDiagnosis CMC.LungCsIIBNoD
+CMC.f356  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCsIIIBNoD CMC.LungCsIIIBNoDAgeing
+CMC.f38  : SYSDYN.Flow
+    @WM.conf_dependency CMC.LungCT2ProgToDisabling CMC.LungCT2Progressing
+CMC.d807  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCTherapyCure1 CMC.LungCD
+CMC.d242  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.LungCProgress0203 CMC.LungCProgress0203Rate
+
+CMC.TotalPopulationT1 : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "delay(TotalPopulation[Gender,Age], 1)" 
+
+CMC.TotalPopulationBirth : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "DummyRateForUnitsConversion*TotalPopulationT1[Gender,Age0]" 
+
+CMC.TotalPopulationMen : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_DATA('LCancer.xls', 'Population_In', '7', 'C113')" 
+
+CMC.OutputDataTotalPopulationMenSum : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(TotalPopulationMen[Age!])" 
+
+CMC.TotalPopulationWomen : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "XLS_DATA('LCancer.xls', 'Population_In', '7', 'C9')" 
+
+CMC.TotalPopulation : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "TotalPopulationMen[Age]" 
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "TotalPopulationWomen[Age]" 
+
+CMC.OutputDataTotalPopulationWomenSum : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "sum(TotalPopulationWomen[Age!])" 
+
+CMC.DummyRateForUnitsConversion : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "1" 
+
+CMC.TotalPopulationDeath : SYSDYN.Auxiliary
+    @L0.tag MOD.Mapped
+    SYSDYN.HasExpressions _ : SYSDYN.Expressions
+        @L0.orderedSet
+            _ : SYSDYN.NormalExpression
+                SYSDYN.HasEquation "if Age==Age99 then (TotalPopulation[Gender,Age99]+TotalPopulation[Gender,Age100]-TotalPopulationT1[Gender,Age100])/4 elseif Age==Age100 then (TotalPopulation[Gender,Age99]+TotalPopulation[Gender,Age100]-TotalPopulationT1[Gender,Age100])*3/4 else VECTOR_MAP(TotalPopulation[Gender,Age], 0)-VECTOR_MAP(TotalPopulationT1[Gender,Age], 1)*DummyRateForUnitsConversion" 
+
+CMC.d6  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.TotalPopulationDeath CMC.TotalPopulation
+CMC.d21  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.TotalPopulationDeath CMC.DummyRateForUnitsConversion
+CMC.d9  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.TotalPopulation CMC.TotalPopulationMen
+CMC.d17  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.OutputDataTotalPopulationMenSum CMC.TotalPopulationMen
+CMC.d12  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.TotalPopulationDeath CMC.TotalPopulationT1
+CMC.d20  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.TotalPopulationBirth CMC.DummyRateForUnitsConversion
+CMC.d14  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.TotalPopulationT1 CMC.TotalPopulation
+CMC.d18  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.OutputDataTotalPopulationWomenSum CMC.TotalPopulationWomen
+CMC.d10  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.TotalPopulation CMC.TotalPopulationWomen
+CMC.d13  : SYSDYN.Dependency
+    @WM.conf_dependency CMC.TotalPopulationBirth CMC.TotalPopulationT1
+
+LungCancerConfigurationDiagram : SYSDYN.ConfigurationDiagram <R L0.HasNext
+    MOD.DiagramToComposite CMC
+    DIA.HasLayer WM.Admin : DIA.Layer
+        DIA.IsActive true
+        DIA.HasFocusableTag TAGS.AdminIsFocusable <R DIA.IsFocusable
+            @L0.symmetric
+        DIA.HasVisibleTag TAGS.AdminIsVisible <R DIA.IsVisible
+            @L0.symmetric
+    L0.HasTrigger _ : SYSDYN.DiagramToCompositeMapping
+    @L0.orderedSet
+      LungCProgressIAIVRateElement559 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIAIVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -343.2, -21.0] : G2D.Transform
+      LungCT1ProgressesElement32 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT1Progresses
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 76.2, 40.8] : G2D.Transform
+      LungCProgressIAIBElement277 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIAIB
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -211.0, 16.2] : G2D.Transform
+      LungCsIBNoDElement443 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIBNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 516.4, -10.6] : G2D.Transform
+      LungCT1DeathElement207 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT1Death
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 247.2, 41.4] : G2D.Transform
+      LungCHealthyPopCorrElement119 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCHealthyPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -208.0, -203.6] : G2D.Transform
+      LungCsIADiagnosisRateElement71 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIADiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -187.2, -16.2] : G2D.Transform
+      LungCProgress03IVElement520 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgress03IV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -325.6, -52.2] : G2D.Transform
+      LungCsIIIBNoDAgeingElement358 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIIBNoDAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -158.4, 200.8] : G2D.Transform
+      LungCProgressIBIVRateElement560 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIBIVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -348.0, 29.8] : G2D.Transform
+      LungCOutputs02NosDiagnosisElement767 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs02NosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 476.2, 233.2] : G2D.Transform
+      LungCProgressIIAIVElement532 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIAIV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -333.2, 82.2] : G2D.Transform
+      LungCTherapy1MortalityElement898 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapy1Mortality
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 57.8, -26.6] : G2D.Transform
+      LungCCured1PopCorrElement799 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCCured1PopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 26.4, -28.8] : G2D.Transform
+      LungCProgress01IVElement512 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgress01IV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -319.8, -128.8] : G2D.Transform
+      LungCs03DiagnosisElement437 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs03Diagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -163.4, -48.4] : G2D.Transform
+      LungCs03PopCorrElement259 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs03PopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -203.6, -68.2] : G2D.Transform
+      LungCProgressIAIIAElement194 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIAIIA
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -260.4, 1.4] : G2D.Transform
+      LungCDPopCorrElement164 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCDPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -62.4, 191.0] : G2D.Transform
+      LungCsIIIADiagnosisRateElement395 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIIIADiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -210.2, 187.0] : G2D.Transform
+      LungCOutputsIANsNoDElement634 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIANsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 556.8, -25.2] : G2D.Transform
+      LungCOutputTherapy1Element611 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputTherapy1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 589.4, 161.0] : G2D.Transform
+      LungCT2ProgressesRateElement584 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT2ProgressesRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 71.8, 96.0] : G2D.Transform
+      LungCOutputTherapy2CureElement849 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputTherapy2Cure
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 450.0, 186.8] : G2D.Transform
+      LungCT2ProgressesElement36 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT2Progresses
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 76.2, 109.6] : G2D.Transform
+      LungCT1ProgToDisablingRateElement208 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT1ProgToDisablingRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 161.0, 24.4] : G2D.Transform
+      LungCProgressIIBIIIBElement293 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIBIIIB
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -168.6, 144.4] : G2D.Transform
+      LungCsIIIANoDAgeingElement350 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIIANoDAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -274.4, 154.6] : G2D.Transform
+      LungCOutputsIBNsDiagnosisElement675 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIBNsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 275.0] : G2D.Transform
+      LungCOutputRelapseElement930 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputRelapse
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 262.4, 220.8] : G2D.Transform
+      LungCs03Element442 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCs03
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 516.4, -41.2] : G2D.Transform
+      LungCT1DeceasedElement199 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT1Deceased
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 286.8, 37.6] : G2D.Transform
+      TotalPopulationDeathElement114 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulationDeath
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 389.4, 57.6] : G2D.Transform
+      LungCT1DisablingPopCorrElement226 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT1DisablingPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 226.8, 54.4] : G2D.Transform
+      LungCOutputsIAScDiagnosisElement684 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIAScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 473.0, 260.6] : G2D.Transform
+      LungCModelPopCorrectionFactorElement153 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 121.8, 66.8] : G2D.Transform
+      LungCProgressIBIVElement528 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIBIV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -330.2, 37.8] : G2D.Transform
+      LungCsIVDiagnosisElement431 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIVDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -163.6, 257.2] : G2D.Transform
+      LungCOutputsIIIBScDiagnosisElement689 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIBScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 347.0] : G2D.Transform
+      LungCsIIADiagnosisElement383 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIADiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -213.6, 85.8] : G2D.Transform
+      LungCTherapy1RatioElement73 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCTherapy1Ratio
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -16.4, 20.4] : G2D.Transform
+      LungCsIBNoDPopCorrElement311 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIBNoDPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -173.0, 19.0] : G2D.Transform
+      LungCsIANoDAgeingElement68 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIANoDAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -200.0, -22.4] : G2D.Transform
+      LungCCured1Element812 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCCured1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 517.4, 91.8] : G2D.Transform
+      LungCCured1AgeingElement795 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCCured1Ageing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 38.2, -19.2] : G2D.Transform
+      LungCProgress03IARateElement241 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgress03IARate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -263.4, -44.8] : G2D.Transform
+      LungCT1DisablingElement198 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT1Disabling
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 208.8, 37.2] : G2D.Transform
+      LungCCured2PopCorrElement826 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCCured2PopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 33.6, 165.8] : G2D.Transform
+      LungCTreated2IniValElement489 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCTreated2IniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -429.8, 46.2] : G2D.Transform
+      LungCsIIBDiagnosisRateElement389 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIIBDiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -141.4, 136.6] : G2D.Transform
+      LungCOutputNoDScElement859 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputNoDSc
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 659.0, -9.6] : G2D.Transform
+      LungCOutputsIANsDiagnosisElement674 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIANsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 256.2] : G2D.Transform
+      LungCTherapy2FailedElement913 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapy2Failed
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 59.6, 183.0] : G2D.Transform
+      LungCProgressIIBIIIARateElement418 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIBIIIARate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -212.2, 147.6] : G2D.Transform
+      LungCProgressIBIIBElement281 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIBIIB
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -175.4, 55.8] : G2D.Transform
+      LungCsIIIBNoDElement273 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIIIBNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -183.4, 213.0] : G2D.Transform
+      LungCDAgeingElement471 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCDAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -65.4, 210.6] : G2D.Transform
+      LungCOutputProgressing2Element622 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputProgressing2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 623.8, 132.2] : G2D.Transform
+      LungCModelPopCorrectionFactorElement249 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -189.8, -115.4] : G2D.Transform
+      LungCT1ProgressingAgeingElement219 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT1ProgressingAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 140.8, 51.2] : G2D.Transform
+      LungCT1ProgToDisablingElement203 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT1ProgToDisabling
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 157.4, 41.4] : G2D.Transform
+      LungCT2ProgressingPopCorrElement169 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT2ProgressingPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 131.4, 123.8] : G2D.Transform
+      LungCInceptionElement14 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCInception
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -211.2, -155.0] : G2D.Transform
+      LungCTherapyCure2Element819 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapyCure2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -24.0, 152.0] : G2D.Transform
+      LungCCured1Element789 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCCured1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 13.0, -6.4] : G2D.Transform
+      LungCBirthElement49 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCBirth
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -269.6, -173.6] : G2D.Transform
+      LungCModelPopCorrectionFactorElement834 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 42.0, 179.6] : G2D.Transform
+      LungCT2ProgressingAgeingElement179 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT2ProgressingAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 139.6, 118.6] : G2D.Transform
+      LungCTherapy1Element25 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapy1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -25.8, 39.6] : G2D.Transform
+      LungCOutputNoDNsElement858 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputNoDNs
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 657.4, -27.6] : G2D.Transform
+      LungCProgressIIAIIIAElement285 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIAIIIA
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -265.6, 97.8] : G2D.Transform
+      LungCs01PopCorrElement141 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs01PopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -200.8, -148.6] : G2D.Transform
+      LungCOutputsIIBNosDiagnosisElement772 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIBNosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 476.6, 318.6] : G2D.Transform
+      LungCDElement124 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 507.2, 69.6] : G2D.Transform
+      LungCModelPopElement104 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPop
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 394.8, 15.4] : G2D.Transform
+      LungCProgressIIIAIIIBRateElement412 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIIAIIIBRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -273.8, 194.8] : G2D.Transform
+      LungCProgress0203Element235 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgress0203
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -239.8, -76.6] : G2D.Transform
+      LungCsIBDiagnosisElement594 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIBDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 273.8] : G2D.Transform
+      LungCModelPopCorrectionFactorElement314 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -279.6, 41.4] : G2D.Transform
+      LungCOutputsIIBNosNoDElement754 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIBNosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 557.0, 24.0] : G2D.Transform
+      LungCsIIBDiagnosisElement388 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIBDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -147.8, 128.6] : G2D.Transform
+      LungCOutputs03ScNoDElement653 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs03ScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 565.0, -37.6] : G2D.Transform
+      LungCsIIIBNoDPopCorrElement355 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIIBNoDPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -162.6, 194.6] : G2D.Transform
+      LungCsIIANoDIniValElement479 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIIANoDIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -429.4, -74.4] : G2D.Transform
+      LungCModelPopCorrectionFactorElement159 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 123.6, 134.2] : G2D.Transform
+      LungCProgress02IVRateElement555 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgress02IVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -327.0, -102.4] : G2D.Transform
+      LungCOutputs01ScDiagnosisElement681 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs01ScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 210.2] : G2D.Transform
+      LungCT2ProgressingElement8 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT2Progressing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 116.2, 105.6] : G2D.Transform
+      DummyRateForUnitsConversionElement98 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.DummyRateForUnitsConversion
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 70.0, -141.0] : G2D.Transform
+      LungCT2DeathElement44 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT2Death
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 247.2, 108.6] : G2D.Transform
+      LungCOutputsIIAScDiagnosisElement686 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIAScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 296.6] : G2D.Transform
+      LungCsIBNoDElement270 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIBNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -187.6, 40.4] : G2D.Transform
+      LungCT1DisablingIniValElement485 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT1DisablingIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -426.2, 26.6] : G2D.Transform
+      LungCNotProgressing1Element5 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCNotProgressing1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 30.0, 35.8] : G2D.Transform
+      LungCOutputsIBScDiagnosisElement685 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIBScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 279.4] : G2D.Transform
+      LungCOutputProgressing1Element621 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputProgressing1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 623.8, 114.6] : G2D.Transform
+      LungCProgressIIIAIVElement539 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIIAIV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -338.8, 170.0] : G2D.Transform
+      LungCProgressIAIVElement524 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIAIV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -328.0, -10.4] : G2D.Transform
+      LungCsIADiagnosisElement22 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIADiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -195.6, -5.4] : G2D.Transform
+      LungCOutputsIVNsDiagnosisElement680 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIVNsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 359.8] : G2D.Transform
+      LungCOutputsIIIBNsDiagnosisElement679 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIBNsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 343.6] : G2D.Transform
+      LungCProgress01IVRateElement552 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgress01IVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -314.0, -143.8] : G2D.Transform
+      LungCProgressIIAIIBElement289 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIAIIB
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -225.8, 101.6] : G2D.Transform
+      LungCT1ProgressingElement460 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT1Progressing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 516.2, 114.6] : G2D.Transform
+      LungCOutputNotProgressing1Element586 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputNotProgressing1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 630.0, 88.0] : G2D.Transform
+      LungCsIIANoDPopCorrElement324 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIANoDPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -268.8, 46.2] : G2D.Transform
+      LungCsIIIBDiagnosisElement598 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIIBDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 342.8] : G2D.Transform
+      LungCOutputsIIBNsNoDElement637 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIBNsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 556.0, 17.0] : G2D.Transform
+      LungCProgressIIAIIBRateElement410 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIAIIBRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -213.4, 94.2] : G2D.Transform
+      LungCsIIADiagnosisElement595 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIADiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 291.2] : G2D.Transform
+      LungCProgress0203RateElement240 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgress0203Rate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -258.6, -82.8] : G2D.Transform
+      LungCsIIBNoDPopCorrElement334 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIBNoDPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -166.4, 99.8] : G2D.Transform
+      LungCSmokersPercentageOfPopulationElement786 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCSmokersPercentageOfPopulation
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -140.0, -167.0] : G2D.Transform
+      LungCOutputsIVScDiagnosisElement690 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIVScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 364.0] : G2D.Transform
+      LungCs01AgeingElement61 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs01Ageing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -193.8, -143.0] : G2D.Transform
+      LungCOutputsIBNosNoDElement752 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIBNosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 562.8, -4.0] : G2D.Transform
+      LungCs02Element230 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCs02
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -221.8, -89.4] : G2D.Transform
+      LungCCausedDeathElement115 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCCausedDeath
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 357.4, 65.0] : G2D.Transform
+      LungCsIBDiagnosisElement377 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIBDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -148.8, 44.6] : G2D.Transform
+      LungCsIIBNoDElement447 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIIBNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 514.6, 17.0] : G2D.Transform
+      LungCProgressIIBIVElement536 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIBIV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -335.6, 122.4] : G2D.Transform
+      LungCOutputCured2Element841 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputCured2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 628.0, 106.8] : G2D.Transform
+      LungCsIBDiagnosisRateElement379 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIBDiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -136.2, 56.0] : G2D.Transform
+      LungCTherapy1MortalityRatioElement901 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCTherapy1MortalityRatio
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 32.4, 11.0] : G2D.Transform
+      TotalPopulationElement113 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulation
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 350.8, 10.2] : G2D.Transform
+      LungCTreated1PopCorrElement152 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTreated1PopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 57.4, 53.8] : G2D.Transform
+      LungCTherapy2Element189 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapy2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 518.6, 182.6] : G2D.Transform
+      LungCOutputTherapy2Element612 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputTherapy2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 590.2, 182.4] : G2D.Transform
+      LungCsIIBNoDIniValElement480 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIIBNoDIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -429.4, -66.6] : G2D.Transform
+      LungCs03DiagnosisRateElement438 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCs03DiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -154.2, -60.8] : G2D.Transform
+      LungCsIIIANoDIniValElement481 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIIIANoDIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -429.2, -58.6] : G2D.Transform
+      LungCTreated1AgeingElement78 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTreated1Ageing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 62.8, 48.6] : G2D.Transform
+      LungCT2DisablingPopCorrElement174 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT2DisablingPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 227.4, 122.4] : G2D.Transform
+      LungCOutputs03ScDiagnosisElement683 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs03ScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 244.0] : G2D.Transform
+      LungCsIIANoDElement444 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIIANoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 514.6, 1.8] : G2D.Transform
+      LungCProgressIIIBIVElement542 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIIBIV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -341.2, 210.8] : G2D.Transform
+      LungCProgressIIIBIVRateElement564 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIIBIVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -351.6, 197.6] : G2D.Transform
+      LungCProgressIIIAIVRateElement563 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIIAIVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -351.0, 160.6] : G2D.Transform
+      LungCT2ProgToDisablingElement40 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT2ProgToDisabling
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 159.6, 110.2] : G2D.Transform
+      LungCProgress03IVRateElement558 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgress03IVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -333.0, -63.6] : G2D.Transform
+      LungCOutputs03NosNoDElement750 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs03NosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 560.2, -33.2] : G2D.Transform
+      LungCOutputsIIIAScDiagnosisElement688 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIAScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 328.8] : G2D.Transform
+      LungCOutputsIIBScNoDElement657 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIBScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 563.2, 20.8] : G2D.Transform
+      LungCModelPopCorrectionFactorElement312 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -164.8, 8.8] : G2D.Transform
+      LungCOutputsIIIBNosDiagnosisElement774 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIBNosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 474.4, 351.2] : G2D.Transform
+      Cloud45Element45 : SYSDYN.CloudSymbol
+          MOD.ElementToComponent CMC.Cloud45
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -310.6, -177.6] : G2D.Transform
+      LungCModelPopCorrectionFactorElement260 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -189.4, -74.4] : G2D.Transform
+      LungCOutputs03NosDiagnosisElement768 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs03NosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 477.0, 248.0] : G2D.Transform
+      LungCOutputs03NsDiagnosisElement673 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs03NsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 240.2] : G2D.Transform
+      LungCOutputsIBNosDiagnosisElement770 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIBNosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 475.4, 283.8] : G2D.Transform
+      LungCsIADiagnosisElement593 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIADiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 255.4] : G2D.Transform
+      LungCTherapy1Element188 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapy1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 517.6, 159.2] : G2D.Transform
+      LungCOutputsIIIANsNoDElement638 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIANsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 555.8, 30.6] : G2D.Transform
+      LungCHealthyElement1 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCHealthy
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -222.4, -177.6] : G2D.Transform
+      LungCs01DiagnosisRateElement506 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCs01DiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -153.8, -140.2] : G2D.Transform
+      LungCTreated1IniValElement136 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCTreated1IniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -429.2, 10.0] : G2D.Transform
+      LungCProgressIBIIBRateElement416 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIBIIBRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -154.6, 62.4] : G2D.Transform
+      LungCsIIBNoDAgeingElement339 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIBNoDAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -163.6, 106.2] : G2D.Transform
+      LungCProgressIIIAIIIBElement301 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIIAIIIB
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -270.8, 183.8] : G2D.Transform
+      LungCOutputsIVNsNoDElement640 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIVNsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 556.8, 60.4] : G2D.Transform
+      LungCModelPopCorrectionFactorElement120 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -182.6, -209.0] : G2D.Transform
+      LungCT1ProgressingIniValElement484 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT1ProgressingIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -425.0, 17.6] : G2D.Transform
+      LungCT1ProgressesElement928 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT1Progresses
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 206.4, 211.6] : G2D.Transform
+      LungCTherapy1MortalityElement906 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapy1Mortality
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 517.6, 154.2] : G2D.Transform
+      LungCs02AgeingElement254 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs02Ageing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -199.6, -102.4] : G2D.Transform
+      LungCOutputDisabling1Element623 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputDisabling1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 623.8, 121.0] : G2D.Transform
+      LungCOutputsIIIANsDiagnosisElement678 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIANsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 325.2] : G2D.Transform
+      LungCsIIANoDAgeingElement329 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIANoDAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -276.0, 72.2] : G2D.Transform
+      LungCOutputsIIIANosNoDElement755 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIANosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 553.6, 38.4] : G2D.Transform
+      LungCProgress03IAElement239 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgress03IA
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -239.2, -37.4] : G2D.Transform
+      LungCOutputsIIIANosDiagnosisElement773 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIANosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 474.4, 332.8] : G2D.Transform
+      LungCTreated2PopCorrElement158 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTreated2PopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 44.8, 123.2] : G2D.Transform
+      LungCsIIIBDiagnosisElement400 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIIBDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -146.6, 216.4] : G2D.Transform
+      LungCInceptionRateChangesElement733 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCInceptionRateChanges
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -164.6, -180.8] : G2D.Transform
+      LungCNotProgressing2Element6 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCNotProgressing2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 30.2, 105.8] : G2D.Transform
+      LungCProgressIIBIVRateElement562 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIBIVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -348.8, 115.8] : G2D.Transform
+      LungCs02DiagnosisElement498 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs02Diagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -163.2, -86.0] : G2D.Transform
+      LungCFirstTreatmentRateElement94 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCFirstTreatmentRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 3.2, 73.4] : G2D.Transform
+      LungCCured2Element816 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCCured2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 22.8, 148.4] : G2D.Transform
+      LungCOutputs02NosNoDElement748 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs02NosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 562.2, -48.0] : G2D.Transform
+      LungCOutputs02ScNoDElement652 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs02ScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 564.2, -52.2] : G2D.Transform
+      LungCProgressIIBIIIAElement297 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgressIIBIIIA
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -209.6, 139.8] : G2D.Transform
+      LungCs03AgeingElement265 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs03Ageing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -200.2, -63.8] : G2D.Transform
+      LungCOutputNsDiagnosisElement711 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputNsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 598.2, 260.0] : G2D.Transform
+      LungCTherapyCure1Element792 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapyCure1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -32.8, -2.6] : G2D.Transform
+      LungCT2DisablingIniValElement493 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT2DisablingIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -427.2, 61.4] : G2D.Transform
+      LungCsIBNoDIniValElement478 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIBNoDIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -430.0, -83.0] : G2D.Transform
+      LungCOutputModelPopExcludingHealthyElement892 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputModelPopExcludingHealthy
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 408.8, -56.4] : G2D.Transform
+      LungCsIIADiagnosisRateElement384 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIIADiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -219.2, 75.2] : G2D.Transform
+      LungCsIIIBNoDElement445 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIIIBNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 514.6, 44.4] : G2D.Transform
+      LungCProgress0102Element18 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgress0102
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -239.6, -117.0] : G2D.Transform
+      LungCsIVNoDAgeingElement366 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIVNoDAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -190.8, 266.8] : G2D.Transform
+      LungCTherapyCure1Element844 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapyCure1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 517.6, 164.6] : G2D.Transform
+      LungCModelPopCorrectionRateElement125 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 316.4, 13.0] : G2D.Transform
+      LungCsIVDiagnosisElement599 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIVDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 359.8] : G2D.Transform
+      LungCTherapy2Element28 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapy2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -24.8, 109.8] : G2D.Transform
+      LungCsIIANoDElement190 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIIANoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -250.0, 83.2] : G2D.Transform
+      LungCsIIIANoDElement272 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIIIANoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -249.2, 169.0] : G2D.Transform
+      LungCOutputsIVNosDiagnosisElement775 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIVNosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 475.8, 368.8] : G2D.Transform
+      LungCTherapy2RatioElement582 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCTherapy2Ratio
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 19.6, 128.8] : G2D.Transform
+      LungCOutputs01NosNoDElement746 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs01NosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 561.4, -61.8] : G2D.Transform
+      LungCTherapy2FailedElement923 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapy2Failed
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 518.0, 176.8] : G2D.Transform
+      LungCCured2AgeingElement822 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCCured2Ageing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 39.4, 161.2] : G2D.Transform
+      LungCModelPopCorrectionFactorElement313 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -161.8, 93.4] : G2D.Transform
+      LungCNotProgressing2Element109 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCNotProgressing2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 518.6, 101.8] : G2D.Transform
+      LungCs03Element231 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCs03
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -222.4, -51.8] : G2D.Transform
+      LungCOutputs03NsNoDElement633 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs03NsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 557.8, -41.2] : G2D.Transform
+      LungCModelPopCorrectionFactorElement148 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -37.0, 181.0] : G2D.Transform
+      LungCOutputsIIANosNoDElement753 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIANosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 562.4, 9.6] : G2D.Transform
+      LungCsIIIANoDPopCorrElement344 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIIANoDPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -272.2, 147.0] : G2D.Transform
+      LungCs01DiagnosisElement505 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs01Diagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -161.6, -126.6] : G2D.Transform
+      LungCs02Element441 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCs02
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 515.0, -54.8] : G2D.Transform
+      LungCOutputs02NsDiagnosisElement672 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs02NsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 223.8] : G2D.Transform
+      LungCOutputsIANosDiagnosisElement769 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIANosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 477.6, 265.6] : G2D.Transform
+      LungCs01Element106 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCs01
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 514.6, -68.2] : G2D.Transform
+      LungCProgress02IVElement516 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCProgress02IV
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -323.4, -89.0] : G2D.Transform
+      LungCT1ProgressingElement197 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT1Progressing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 115.0, 36.2] : G2D.Transform
+      LungCOutputTherapy1CureElement853 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputTherapy1Cure
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 460.0, 162.4] : G2D.Transform
+      LungCsIANoDIniValElement138 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIANoDIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -430.0, -90.2] : G2D.Transform
+      LungCOutputsIANosNoDElement751 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIANosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 563.0, -17.8] : G2D.Transform
+      LungCOutputTherapy1MortalityInTherapyElement908 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputTherapy1MortalityInTherapy
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 456.4, 150.8] : G2D.Transform
+      LungCTreated2AgeingElement82 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTreated2Ageing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 49.8, 118.6] : G2D.Transform
+      LungCs01IniValElement137 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCs01IniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -427.8, -114.0] : G2D.Transform
+      LungCOutputDisabling2Element624 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputDisabling2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 628.8, 137.6] : G2D.Transform
+      LungCT1ProgressesRateElement86 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT1ProgressesRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 70.0, 26.8] : G2D.Transform
+      LungCs02PopCorrElement248 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs02PopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -202.0, -107.4] : G2D.Transform
+      LungCOutputsIIAScNoDElement656 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIAScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 563.2, 5.8] : G2D.Transform
+      LungCsIVNoDPopCorrElement372 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIVNoDPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -194.6, 272.0] : G2D.Transform
+      LungCoutputNoDNosElement860 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCoutputNoDNos
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 659.6, 9.6] : G2D.Transform
+      LungCOutputsIIANosDiagnosisElement771 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIANosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 477.4, 301.2] : G2D.Transform
+      LungCs01Element2 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCs01
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -221.8, -130.0] : G2D.Transform
+      LungCOutputCured1Element814 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputCured1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 631.2, 92.0] : G2D.Transform
+      LungCTherapy1CureRatioElement808 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCTherapy1CureRatio
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -53.0, 19.4] : G2D.Transform
+      LungCsIIIBDiagnosisRateElement401 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIIIBDiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -144.0, 223.4] : G2D.Transform
+      LungCsIVDiagnosisRateElement427 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIVDiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -153.0, 266.6] : G2D.Transform
+      LungCTherapyCure2Element845 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCTherapyCure2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 519.2, 188.6] : G2D.Transform
+      LungCOutputsIIBNsDiagnosisElement677 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIBNsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 310.2] : G2D.Transform
+      LungCOutputModelPopElement186 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputModelPop
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 384.6, -0.2] : G2D.Transform
+      LungCT2ProgressingElement110 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT2Progressing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 517.0, 131.8] : G2D.Transform
+      LungCsIANoDPopCorrElement147 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIANoDPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -202.4, -30.2] : G2D.Transform
+      LungCs01DiagnosisElement590 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs01Diagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 206.6] : G2D.Transform
+      LungCCured2IniValElement829 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCCured2IniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -428.4, 69.8] : G2D.Transform
+      LungCModelPopCorrectionFactorElement112 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 359.0, 33.2] : G2D.Transform
+      LungCModelPopCorrectionFactorElement345 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -274.2, 139.2] : G2D.Transform
+      LungCTherapy2FailRatioElement915 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCTherapy2FailRatio
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -2.4, 165.8] : G2D.Transform
+      LungCsIIBDiagnosisElement596 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIBDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 309.2] : G2D.Transform
+      LungCsIBNoDAgeingElement319 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIBNoDAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -167.0, 25.8] : G2D.Transform
+      LungCOutputNosDiagnosisElement735 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputNosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 604.2, 325.2] : G2D.Transform
+      LungCOutputNotProgressing2Element588 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputNotProgressing2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 628.6, 102.0] : G2D.Transform
+      LungCOutputsIIIBNosNoDElement756 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIBNosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 559.6, 53.8] : G2D.Transform
+      LungCsIIIANoDElement446 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIIIANoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 514.4, 30.6] : G2D.Transform
+      LungCProgressIIBIIIBRateElement420 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIBIIIBRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -160.2, 152.0] : G2D.Transform
+      LungCOutputT1MortalityElement617 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputT1Mortality
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 250.0, 57.8] : G2D.Transform
+      LungCOutputsIIIBNsNoDElement639 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIBNsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 556.0, 45.2] : G2D.Transform
+      LungCDIniValElement494 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCDIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -429.0, -9.4] : G2D.Transform
+      LungCOutputsIIANsNoDElement636 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIANsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 556.0, 2.4] : G2D.Transform
+      LungCModelPopCorrectionFactorElement369 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -198.8, 278.6] : G2D.Transform
+      LungCProgressIIAIVRateElement561 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIAIVRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -349.4, 72.4] : G2D.Transform
+      LungCOutputs01ScNoDElement651 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs01ScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 563.2, -65.6] : G2D.Transform
+      LungCsIVNoDElement448 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIVNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 515.4, 59.8] : G2D.Transform
+      LungCOutputNoDSumElement629 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputNoDSum
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 20.6] : G2D.Transform
+      LungCsIVNoDIniValElement483 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIVNoDIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -429.8, -42.6] : G2D.Transform
+      LungCT1ProgressingPopCorrElement216 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT1ProgressingPopCorr
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 133.2, 55.8] : G2D.Transform
+      LungCOutputTherapy1NoCureElement852 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputTherapy1NoCure
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 457.2, 156.6] : G2D.Transform
+      LungCOutputsIVScNoDElement660 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIVScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 564.0, 65.0] : G2D.Transform
+      LungCProgress0102RateElement63 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgress0102Rate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -249.6, -108.2] : G2D.Transform
+      LungCOutputDiagnosisElement600 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 603.8, 229.6] : G2D.Transform
+      LungCModelPopCorrectionFactorElement359 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -155.6, 186.2] : G2D.Transform
+      LungCOutputHealthyAndTreatedElement182 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputHealthyAndTreated
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 654.6, -70.8] : G2D.Transform
+      LungCOutputsIIANsDiagnosisElement676 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIANsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 292.2] : G2D.Transform
+      LungCNotProgressing1Element108 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCNotProgressing1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 516.8, 87.4] : G2D.Transform
+      LungCT2DeathRateElement92 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT2DeathRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 243.8, 89.6] : G2D.Transform
+      LungCProgressIAIBRateElement414 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIAIBRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -195.4, 4.6] : G2D.Transform
+      LungCT2DeceasedElement10 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT2Deceased
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 292.6, 103.8] : G2D.Transform
+      LungCs03IniValElement477 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCs03IniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -428.0, -100.0] : G2D.Transform
+      LungCOutputs01NsDiagnosisElement671 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs01NsDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 459.4, 206.0] : G2D.Transform
+      LungCModelPopCorrectionFactorElement142 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -149.8, -148.8] : G2D.Transform
+      LungCOutputs02NsNoDElement632 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs02NsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 556.4, -55.4] : G2D.Transform
+      LungCsIIIADiagnosisElement394 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIIADiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -213.0, 176.2] : G2D.Transform
+      LungCT2ProgressesElement929 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCT2Progresses
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 205.2, 229.0] : G2D.Transform
+      LungCTherapy2CureRatioElement837 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCTherapy2CureRatio
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -47.8, 128.6] : G2D.Transform
+      LungCHealthyIniValElement133 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCHealthyIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -424.2, -127.4] : G2D.Transform
+      LungCOutputMortalityElement615 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputMortality
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 387.8, 76.4] : G2D.Transform
+      LungCs03DiagnosisElement592 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs03Diagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 239.4] : G2D.Transform
+      LungCsIANoDElement123 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIANoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 515.4, -25.6] : G2D.Transform
+      TotalPopulationBirthElement50 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulationBirth
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -296.2, -187.4] : G2D.Transform
+      LungCs02IniValElement476 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCs02IniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -428.0, -107.4] : G2D.Transform
+      LungCOutputScDiagnosisElement712 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 601.0, 290.2] : G2D.Transform
+      LungCOutputs01NsNoDElement631 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs01NsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 556.0, -68.6] : G2D.Transform
+      LungCT1DeathRateElement210 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT1DeathRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 239.2, 25.4] : G2D.Transform
+      LungCProgressIAIIARateElement406 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIAIIARate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -265.8, 9.4] : G2D.Transform
+      LungCsIIIBNoDIniValElement482 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCsIIIBNoDIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -428.8, -50.8] : G2D.Transform
+      LungCOutputs01NosDiagnosisElement766 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs01NosDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 476.0, 215.2] : G2D.Transform
+      LungCInceptionRateElement56 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCInceptionRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -160.4, -155.2] : G2D.Transform
+      LungCs02DiagnosisRateElement499 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCs02DiagnosisRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -158.8, -101.0] : G2D.Transform
+      LungCNoDSumElement449 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCNoDSum
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 462.0, 1.0] : G2D.Transform
+      LungCOutputsIIIAScNoDElement658 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIAScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 563.0, 34.8] : G2D.Transform
+      LungCHealthyAgeingElement54 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCHealthyAgeing
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -197.6, -197.2] : G2D.Transform
+      LungCsIVNoDElement274 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIVNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -210.0, 253.8] : G2D.Transform
+      LungCOutputsIIIBScNoDElement659 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIIBScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 563.2, 49.4] : G2D.Transform
+      LungCOutputs02ScDiagnosisElement682 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputs02ScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 228.4] : G2D.Transform
+      LungCOutputsIBNsNoDElement635 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIBNsNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 557.8, -10.8] : G2D.Transform
+      LungCT2ProgToDisablingRateElement88 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT2ProgToDisablingRate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 161.0, 95.2] : G2D.Transform
+      LungCOutputsIAScNoDElement654 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIAScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 564.0, -21.4] : G2D.Transform
+      LungCCured1IniValElement788 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCCured1IniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -431.0, 32.2] : G2D.Transform
+      LungCOutputT2MortalityElement618 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputT2Mortality
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 258.4, 126.0] : G2D.Transform
+      LungCOutputTherapy2NoCureElement848 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputTherapy2NoCure
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 448.6, 181.8] : G2D.Transform
+      LungCOutputsIBScNoDElement655 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIBScNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 565.0, -7.0] : G2D.Transform
+      LungCOutputsIIBScDiagnosisElement687 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIIBScDiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 470.8, 314.2] : G2D.Transform
+      LungCsIIBNoDElement271 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIIBNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -185.6, 125.2] : G2D.Transform
+      LungCModelPopCorrectionFactorElement267 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -189.4, -36.6] : G2D.Transform
+      LungCT2ProgressingIniValElement491 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCT2ProgressingIniVal
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -425.8, 53.4] : G2D.Transform
+      LungCT1DisablingElement461 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT1Disabling
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 517.8, 120.0] : G2D.Transform
+      LungCHealthyElement105 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCHealthy
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 515.8, -82.8] : G2D.Transform
+      LungCOutputTherapy2FailedElement925 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputTherapy2Failed
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 452.4, 176.2] : G2D.Transform
+      LungCOutputsIVNosNoDElement757 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCOutputsIVNosNoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 561.4, 69.4] : G2D.Transform
+      LungCCured2Element840 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCCured2
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 518.8, 106.6] : G2D.Transform
+      LungCsIANoDElement3 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCsIANoD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -223.4, -8.6] : G2D.Transform
+      LungCsIIIADiagnosisElement597 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCsIIIADiagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 324.6] : G2D.Transform
+      LungCT2DisablingElement9 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT2Disabling
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 210.0, 104.4] : G2D.Transform
+      LungCT2DisablingElement111 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCT2Disabling
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 517.4, 136.2] : G2D.Transform
+      LungCModelPopCorrectionFactorElement802 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCModelPopCorrectionFactor
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 45.8, -41.2] : G2D.Transform
+      LungCProgressIIAIIIARateElement408 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.LungCProgressIIAIIIARate
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -287.0, 89.2] : G2D.Transform
+      LungCs02DiagnosisElement591 : SYSDYN.ValveSymbol
+          MOD.ElementToComponent CMC.LungCs02Diagnosis
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 522.8, 224.0] : G2D.Transform
+      LungCDElement4 : SYSDYN.StockSymbol
+          MOD.ElementToComponent CMC.LungCD
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, -107.6, 73.2] : G2D.Transform
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d127
+          @WM.dependency LungCModelPopElement104 LungCDElement124   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d882
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputs01NosNoDElement746   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d331
+          @WM.dependency LungCsIIANoDAgeingElement329 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d737
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCs02DiagnosisElement591   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f580
+          @WM.flow LungCsIVNoDElement274 LungCProgressIIIBIVElement542
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f805
+          @WM.flow LungCTherapyCure1Element792 LungCDElement4
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d84
+          @WM.dependency LungCT1ProgressesElement32 LungCNotProgressing1Element5   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d463
+          @WM.dependency LungCModelPopElement104 LungCNotProgressing2Element109   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f517
+          @WM.flow LungCsIVNoDElement274 LungCProgress03IVElement520
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d458
+          @WM.dependency LungCNoDSumElement449 LungCsIIIBNoDElement445   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d451
+          @WM.dependency LungCNoDSumElement449 LungCs02Element441   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d220
+          @WM.dependency LungCT1ProgressingPopCorrElement216 LungCModelPopCorrectionFactorElement153   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d454
+          @WM.dependency LungCNoDSumElement449 LungCsIBNoDElement443   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d846
+          @WM.dependency LungCOutputTherapy1Element611 LungCTherapyCure1Element844   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d722
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCsIVDiagnosisElement599   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d578
+          @WM.dependency LungCProgressIIIBIVElement542 LungCsIIIBNoDElement273   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d695
+          @WM.dependency LungCOutputs03NsDiagnosisElement673 LungCs03DiagnosisElement592   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d728
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCsIIADiagnosisElement595   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d742
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCsIIBDiagnosisElement596   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d378
+          @WM.dependency LungCsIBDiagnosisElement377 LungCsIBNoDElement270   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d325
+          @WM.dependency LungCsIIANoDPopCorrElement324 LungCsIIANoDElement190   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f29
+          @WM.flow LungCT1ProgressingElement197 LungCT1ProgressesElement32
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d889
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputsIIIANosNoDElement755   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d572
+          @WM.dependency LungCProgressIIAIVElement532 LungCsIIANoDElement190   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f540
+          @WM.flow LungCProgressIIIBIVElement542 LungCsIIIBNoDElement273
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d58
+          @WM.dependency LungCInceptionElement14 LungCHealthyElement1   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d211
+          @WM.dependency LungCT1DeathElement207 LungCT1DeathRateElement210   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f15
+          @WM.flow LungCs02Element230 LungCProgress0102Element18
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d861
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputs01NsNoDElement631   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f337
+          @WM.flow LungCsIIBNoDElement271 LungCsIIBNoDAgeingElement339
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d101
+          @WM.dependency LungCTreated1AgeingElement78 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d340
+          @WM.dependency LungCsIIBNoDAgeingElement339 LungCsIIBNoDElement271   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f76
+          @WM.flow LungCNotProgressing1Element5 LungCTreated1AgeingElement78
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d62
+          @WM.dependency LungCs01AgeingElement61 LungCs01Element2   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d833
+          @WM.dependency LungCCured2AgeingElement822 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d571
+          @WM.dependency LungCProgressIIAIVElement532 LungCProgressIIAIVRateElement561   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f139
+          @WM.flow LungCs01Element2 LungCs01PopCorrElement141
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d129
+          @WM.dependency LungCModelPopCorrectionFactorElement112 TotalPopulationDeathElement114   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d917
+          @WM.dependency LungCTherapyCure2Element819 LungCTherapy2FailRatioElement915   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d926
+          @WM.dependency LungCOutputTherapy2FailedElement925 LungCTherapy2FailedElement923   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f495
+          @WM.flow LungCDElement4 LungCs02DiagnosisElement498
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d739
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCsIADiagnosisElement593   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d876
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputsIBScNoDElement655   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d662
+          @WM.dependency LungCOutputs02ScNoDElement652 LungCs02Element441   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d783
+          @WM.dependency LungCOutputsIIIANosDiagnosisElement773 LungCsIIIADiagnosisElement597   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d758
+          @WM.dependency LungCOutputs03NosNoDElement750 LungCs03Element442   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f236
+          @WM.flow LungCsIANoDElement3 LungCProgress03IAElement239
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d706
+          @WM.dependency LungCOutputsIIIAScDiagnosisElement688 LungCsIIIADiagnosisElement597   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f348
+          @WM.flow LungCsIIIANoDElement272 LungCsIIIANoDAgeingElement350
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f145
+          @WM.flow LungCsIANoDElement3 LungCsIANoDPopCorrElement147
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d627
+          @WM.dependency LungCOutputProgressing2Element622 LungCT2ProgressingElement110   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d715
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCs03DiagnosisElement592   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f23
+          @WM.flow LungCNotProgressing1Element5 LungCTherapy1Element25
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f364
+          @WM.flow LungCsIVNoDElement274 LungCsIVNoDAgeingElement366
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d96
+          @WM.dependency LungCTherapy2Element28 LungCFirstTreatmentRateElement94   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f509
+          @WM.flow LungCsIVNoDElement274 LungCProgress01IVElement512
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d160
+          @WM.dependency LungCTreated2PopCorrElement158 LungCModelPopCorrectionFactorElement159   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d569
+          @WM.dependency LungCProgressIBIVElement528 LungCProgressIBIVRateElement560   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d367
+          @WM.dependency LungCsIVNoDAgeingElement366 LungCsIVNoDElement274   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d716
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCsIADiagnosisElement593   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d391
+          @WM.dependency LungCsIIBDiagnosisElement388 LungCsIIBDiagnosisRateElement389   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d778
+          @WM.dependency LungCOutputs03NosDiagnosisElement768 LungCs03DiagnosisElement592   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d743
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCsIIIADiagnosisElement597   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d720
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCsIIIADiagnosisElement597   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d723
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCs01DiagnosisElement590   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d453
+          @WM.dependency LungCNoDSumElement449 LungCsIANoDElement123   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d180
+          @WM.dependency LungCT2ProgressingAgeingElement179 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d244
+          @WM.dependency LungCProgress0203Element235 LungCs02Element230   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d351
+          @WM.dependency LungCsIIIANoDAgeingElement350 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f246
+          @WM.flow LungCs02Element230 LungCs02PopCorrElement248
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d835
+          @WM.dependency LungCCured2PopCorrElement826 LungCModelPopCorrectionFactorElement834   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d415
+          @WM.dependency LungCProgressIAIBElement277 LungCProgressIAIBRateElement414   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d452
+          @WM.dependency LungCNoDSumElement449 LungCs03Element442   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f342
+          @WM.flow LungCsIIIANoDElement272 LungCsIIIANoDPopCorrElement344
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d862
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputs02NsNoDElement632   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f579
+          @WM.flow LungCsIVNoDElement274 LungCProgressIIIAIVElement539
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f295
+          @WM.flow LungCProgressIIBIIIAElement297 LungCsIIBNoDElement271
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d341
+          @WM.dependency LungCsIIBNoDAgeingElement339 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d87
+          @WM.dependency LungCT1ProgressesElement32 LungCT1ProgressesRateElement86   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d508
+          @WM.dependency LungCs01DiagnosisElement505 LungCs01DiagnosisRateElement506   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d221
+          @WM.dependency LungCT1ProgressingPopCorrElement216 LungCT1ProgressingElement197   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d64
+          @WM.dependency LungCProgress0102Element18 LungCProgress0102RateElement63   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d417
+          @WM.dependency LungCProgressIBIIBElement281 LungCProgressIBIIBRateElement416   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f12
+          @WM.flow LungCInceptionElement14 LungCHealthyElement1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d881
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputsIVScNoDElement660   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d765
+          @WM.dependency LungCOutputsIVNosNoDElement757 LungCsIVNoDElement448   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d784
+          @WM.dependency LungCOutputsIIIBNosDiagnosisElement774 LungCsIIIBDiagnosisElement598   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d507
+          @WM.dependency LungCs01DiagnosisElement505 LungCs01Element2   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d405
+          @WM.dependency LungCsIIADiagnosisElement383 LungCsIIANoDElement190   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d573
+          @WM.dependency LungCProgressIIBIVElement536 LungCProgressIIBIVRateElement562   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f237
+          @WM.flow LungCProgress03IAElement239 LungCs03Element231
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f370
+          @WM.flow LungCsIVNoDElement274 LungCsIVNoDPopCorrElement372
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f309
+          @WM.flow LungCsIBNoDElement270 LungCsIBNoDPopCorrElement311
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d762
+          @WM.dependency LungCOutputsIIBNosNoDElement754 LungCsIIBNoDElement447   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d734
+          @WM.dependency LungCInceptionElement14 LungCInceptionRateChangesElement733   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d875
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputsIAScNoDElement654   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d567
+          @WM.dependency LungCProgress03IVElement520 LungCs03Element231   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d116
+          @WM.dependency LungCCausedDeathElement115 LungCT2DeathElement44   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d144
+          @WM.dependency LungCs01PopCorrElement141 LungCs01Element2   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d914
+          @WM.dependency LungCTherapy2FailedElement913 LungCFirstTreatmentRateElement94   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d380
+          @WM.dependency LungCsIBDiagnosisElement377 LungCsIBDiagnosisRateElement379   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d100
+          @WM.dependency LungCs01AgeingElement61 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f824
+          @WM.flow LungCCured2Element816 LungCCured2PopCorrElement826
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d661
+          @WM.dependency LungCOutputs01ScNoDElement651 LungCs01Element106   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f286
+          @WM.flow LungCsIIBNoDElement271 LungCProgressIIAIIBElement289
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d800
+          @WM.dependency LungCCured1PopCorrElement799 LungCCured1Element789   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f381
+          @WM.flow LungCsIIADiagnosisElement383 LungCsIIANoDElement190
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d308
+          @WM.dependency LungCProgressIIIAIIIBElement301 LungCsIIIANoDElement272   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f392
+          @WM.flow LungCsIIIADiagnosisElement394 LungCsIIIANoDElement272
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f177
+          @WM.flow LungCT2ProgressingElement8 LungCT2ProgressingAgeingElement179
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f496
+          @WM.flow LungCs02DiagnosisElement498 LungCs02Element230
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d605
+          @WM.dependency LungCOutputDiagnosisElement600 LungCsIBDiagnosisElement594   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d373
+          @WM.dependency LungCsIVNoDPopCorrElement372 LungCModelPopCorrectionFactorElement369   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d607
+          @WM.dependency LungCOutputDiagnosisElement600 LungCsIIBDiagnosisElement596   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d813
+          @WM.dependency LungCModelPopElement104 LungCCured1Element812   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f42
+          @WM.flow LungCT2DeathElement44 LungCT2DisablingElement9
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f205
+          @WM.flow LungCT1DeathElement207 LungCT1DisablingElement198
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d759
+          @WM.dependency LungCOutputsIANosNoDElement751 LungCsIANoDElement123   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d644
+          @WM.dependency LungCOutputsIANsNoDElement634 LungCsIANoDElement123   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d851
+          @WM.dependency LungCOutputTherapy2CureElement849 LungCTherapyCure2Element845   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d927
+          @WM.dependency LungCCausedDeathElement115 LungCTherapy1MortalityElement898   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d694
+          @WM.dependency LungCOutputs02ScDiagnosisElement682 LungCs02DiagnosisElement591   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d213
+          @WM.dependency LungCT1DeathElement207 LungCT1DisablingElement198   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d51
+          @WM.dependency LungCBirthElement49 TotalPopulationBirthElement50   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d456
+          @WM.dependency LungCNoDSumElement449 LungCsIIBNoDElement447   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d568
+          @WM.dependency LungCProgressIAIVElement524 LungCsIANoDElement3   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d874
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputs03ScNoDElement653   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d171
+          @WM.dependency LungCT2ProgressingPopCorrElement169 LungCT2ProgressingElement8   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d916
+          @WM.dependency LungCTherapy2FailedElement913 LungCTherapy2FailRatioElement915   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f386
+          @WM.flow LungCsIIBDiagnosisElement388 LungCsIIBNoDElement271
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d796
+          @WM.dependency LungCCured1AgeingElement795 LungCCured1Element789   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f200
+          @WM.flow LungCT1DisablingElement198 LungCT1ProgToDisablingElement203
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f525
+          @WM.flow LungCsIVNoDElement274 LungCProgressIBIVElement528
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d787
+          @WM.dependency LungCInceptionElement14 LungCSmokersPercentageOfPopulationElement786   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d161
+          @WM.dependency LungCTreated2PopCorrElement158 LungCNotProgressing2Element6   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d919
+          @WM.dependency LungCTherapy2FailedElement913 LungCTherapy2RatioElement582   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f534
+          @WM.flow LungCProgressIIBIVElement536 LungCsIIBNoDElement271
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d744
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCsIIIBDiagnosisElement598   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f20
+          @WM.flow LungCsIADiagnosisElement22 LungCsIANoDElement3
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d888
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputsIIBNosNoDElement754   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d557
+          @WM.dependency LungCProgress02IVElement516 LungCs02Element230   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d718
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCsIIADiagnosisElement595   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d468
+          @WM.dependency LungCModelPopElement104 LungCNoDSumElement449   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d700
+          @WM.dependency LungCOutputsIBScDiagnosisElement685 LungCsIBDiagnosisElement594   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f287
+          @WM.flow LungCProgressIIAIIBElement289 LungCsIIANoDElement190
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f475
+          @WM.flow LungCTherapy2Element28 LungCDElement4
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d868
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputsIIIANsNoDElement638   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f294
+          @WM.flow LungCsIIIANoDElement272 LungCProgressIIBIIIAElement297
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d413
+          @WM.dependency LungCProgressIIIAIIIBElement301 LungCProgressIIIAIIIBRateElement412   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d932
+          @WM.dependency LungCOutputRelapseElement930 LungCT2ProgressesElement929   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d764
+          @WM.dependency LungCOutputsIIIBNosNoDElement756 LungCsIIIBNoDElement445   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f275
+          @WM.flow LungCsIBNoDElement270 LungCProgressIAIBElement277
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d803
+          @WM.dependency LungCCured1PopCorrElement799 LungCModelPopCorrectionFactorElement802   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d606
+          @WM.dependency LungCOutputDiagnosisElement600 LungCsIIADiagnosisElement595   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d724
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCs02DiagnosisElement591   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d691
+          @WM.dependency LungCOutputs01NsDiagnosisElement671 LungCs01DiagnosisElement590   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d666
+          @WM.dependency LungCOutputsIIAScNoDElement656 LungCsIIANoDElement444   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d432
+          @WM.dependency LungCsIVDiagnosisElement431 LungCsIVDiagnosisRateElement427   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d346
+          @WM.dependency LungCsIIIANoDPopCorrElement344 LungCModelPopCorrectionFactorElement345   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f911
+          @WM.flow LungCTherapy2FailedElement913 LungCDElement4
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d907
+          @WM.dependency LungCOutputTherapy1Element611 LungCTherapy1MortalityElement906   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d708
+          @WM.dependency LungCOutputsIIIBScDiagnosisElement689 LungCsIIIBDiagnosisElement598   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d650
+          @WM.dependency LungCOutputsIVNsNoDElement640 LungCsIVNoDElement448   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d710
+          @WM.dependency LungCOutputsIVScDiagnosisElement690 LungCsIVDiagnosisElement599   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f895
+          @WM.flow LungCT1DeceasedElement199 LungCTherapy1MortalityElement898
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d856
+          @WM.dependency LungCOutputHealthyAndTreatedElement182 LungCCured1Element812   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d69
+          @WM.dependency LungCsIANoDAgeingElement68 LungCsIANoDElement3   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d664
+          @WM.dependency LungCOutputsIAScNoDElement654 LungCsIANoDElement123   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f191
+          @WM.flow LungCsIIANoDElement190 LungCProgressIAIIAElement194
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f224
+          @WM.flow LungCT1DisablingElement198 LungCT1DisablingPopCorrElement226
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d187
+          @WM.dependency LungCOutputModelPopElement186 LungCModelPopElement104   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d646
+          @WM.dependency LungCOutputsIIANsNoDElement636 LungCsIIANoDElement444   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d262
+          @WM.dependency LungCs03PopCorrElement259 LungCs03Element231   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d79
+          @WM.dependency LungCTreated1AgeingElement78 LungCNotProgressing1Element5   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d212
+          @WM.dependency LungCT1ProgToDisablingElement203 LungCT1ProgressingElement197   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d352
+          @WM.dependency LungCsIIIANoDAgeingElement350 LungCsIIIANoDElement272   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d126
+          @WM.dependency LungCModelPopElement104 LungCHealthyElement105   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d251
+          @WM.dependency LungCs02PopCorrElement248 LungCs02Element230   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f426
+          @WM.flow LungCDElement4 LungCsIIIBDiagnosisElement400
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f279
+          @WM.flow LungCProgressIBIIBElement281 LungCsIBNoDElement270
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d176
+          @WM.dependency LungCT2DisablingPopCorrElement174 LungCT2DisablingElement9   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d256
+          @WM.dependency LungCs02AgeingElement254 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d810
+          @WM.dependency LungCTherapy1Element25 LungCTherapy1CureRatioElement808   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d574
+          @WM.dependency LungCProgressIIBIVElement536 LungCsIIBNoDElement271   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d170
+          @WM.dependency LungCT2ProgressingPopCorrElement169 LungCModelPopCorrectionFactorElement159   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f33
+          @WM.flow LungCT2ProgressingElement8 LungCT2ProgressesElement36
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d920
+          @WM.dependency LungCTherapy2FailedElement913 LungCDElement4   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f428
+          @WM.flow LungCDElement4 LungCsIVDiagnosisElement431
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d887
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputsIIANosNoDElement753   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d227
+          @WM.dependency LungCT1DisablingPopCorrElement226 LungCModelPopCorrectionFactorElement153   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f26
+          @WM.flow LungCNotProgressing2Element6 LungCTherapy2Element28
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d99
+          @WM.dependency LungCHealthyAgeingElement54 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d566
+          @WM.dependency LungCProgressIAIVElement524 LungCProgressIAIVRateElement559   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f526
+          @WM.flow LungCProgressIBIVElement528 LungCsIBNoDElement270
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d72
+          @WM.dependency LungCsIADiagnosisElement22 LungCsIADiagnosisRateElement71   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d869
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputsIIIANsNoDElement638   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d806
+          @WM.dependency LungCTherapyCure1Element792 LungCFirstTreatmentRateElement94   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d255
+          @WM.dependency LungCs02AgeingElement254 LungCs02Element230   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d500
+          @WM.dependency LungCs02DiagnosisElement498 LungCs02DiagnosisRateElement499   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f790
+          @WM.flow LungCCured1Element789 LungCTherapyCure1Element792
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f533
+          @WM.flow LungCsIVNoDElement274 LungCProgressIIBIVElement536
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d918
+          @WM.dependency LungCTherapy2Element28 LungCTherapy2FailRatioElement915   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d604
+          @WM.dependency LungCOutputDiagnosisElement600 LungCsIADiagnosisElement593   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d556
+          @WM.dependency LungCProgress02IVElement516 LungCProgress02IVRateElement555   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d717
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCsIBDiagnosisElement594   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f232
+          @WM.flow LungCs03Element231 LungCProgress0203Element235
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d462
+          @WM.dependency LungCModelPopElement104 LungCNotProgressing1Element108   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d843
+          @WM.dependency LungCModelPopElement104 LungCCured2Element840   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d815
+          @WM.dependency LungCOutputCured1Element814 LungCCured1Element812   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d330
+          @WM.dependency LungCsIIANoDAgeingElement329 LungCsIIANoDElement190   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f263
+          @WM.flow LungCs03Element231 LungCs03AgeingElement265
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f167
+          @WM.flow LungCT2ProgressingElement8 LungCT2ProgressingPopCorrElement169
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d360
+          @WM.dependency LungCsIIIBNoDPopCorrElement355 LungCModelPopCorrectionFactorElement359   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d692
+          @WM.dependency LungCOutputs01ScDiagnosisElement681 LungCs01DiagnosisElement590   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d610
+          @WM.dependency LungCOutputDiagnosisElement600 LungCsIVDiagnosisElement599   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f514
+          @WM.flow LungCProgress02IVElement516 LungCs02Element230
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d931
+          @WM.dependency LungCOutputRelapseElement930 LungCT1ProgressesElement928   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d725
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCs03DiagnosisElement592   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d663
+          @WM.dependency LungCOutputs03ScNoDElement653 LungCs03Element442   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f513
+          @WM.flow LungCsIVNoDElement274 LungCProgress02IVElement516
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d854
+          @WM.dependency LungCOutputTherapy1NoCureElement852 LungCTherapy1Element188   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f797
+          @WM.flow LungCCured1Element789 LungCCured1PopCorrElement799
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f510
+          @WM.flow LungCProgress01IVElement512 LungCs01Element2
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d877
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputsIIAScNoDElement656   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d645
+          @WM.dependency LungCOutputsIBNsNoDElement635 LungCsIBNoDElement443   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f322
+          @WM.flow LungCsIIANoDElement190 LungCsIIANoDPopCorrElement324
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f469
+          @WM.flow LungCDElement4 LungCDAgeingElement471
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f353
+          @WM.flow LungCsIIIBNoDElement273 LungCsIIIBNoDPopCorrElement355
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d575
+          @WM.dependency LungCProgressIIIAIVElement539 LungCProgressIIIAIVRateElement563   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f375
+          @WM.flow LungCsIBDiagnosisElement377 LungCsIBNoDElement270
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d709
+          @WM.dependency LungCOutputsIVNsDiagnosisElement680 LungCsIVDiagnosisElement599   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d128
+          @WM.dependency LungCModelPopCorrectionFactorElement112 LungCCausedDeathElement115   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d589
+          @WM.dependency LungCOutputNotProgressing2Element588 LungCNotProgressing2Element109   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d250
+          @WM.dependency LungCs02PopCorrElement248 LungCModelPopCorrectionFactorElement249   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f192
+          @WM.flow LungCProgressIAIIAElement194 LungCsIANoDElement3
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d303
+          @WM.dependency LungCProgressIBIIBElement281 LungCsIBNoDElement270   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d614
+          @WM.dependency LungCOutputTherapy2Element612 LungCTherapy2Element189   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d699
+          @WM.dependency LungCOutputsIBNsDiagnosisElement675 LungCsIBDiagnosisElement594   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d501
+          @WM.dependency LungCs02DiagnosisElement498 LungCs02Element230   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f278
+          @WM.flow LungCsIIBNoDElement271 LungCProgressIBIIBElement281
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f150
+          @WM.flow LungCNotProgressing1Element5 LungCTreated1PopCorrElement152
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d155
+          @WM.dependency LungCTreated1PopCorrElement152 LungCNotProgressing1Element5   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d130
+          @WM.dependency LungCModelPopCorrectionFactorElement112 TotalPopulationElement113   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d245
+          @WM.dependency LungCProgress03IAElement239 LungCs03Element231   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d626
+          @WM.dependency LungCOutputDisabling1Element623 LungCT1DisablingElement461   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d583
+          @WM.dependency LungCTherapy2Element28 LungCTherapy2RatioElement582   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f257
+          @WM.flow LungCs03Element231 LungCs03PopCorrElement259
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d782
+          @WM.dependency LungCOutputsIIBNosDiagnosisElement772 LungCsIIBDiagnosisElement596   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d85
+          @WM.dependency LungCT2ProgressesElement36 LungCNotProgressing2Element6   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d809
+          @WM.dependency LungCTherapyCure1Element792 LungCTherapy1CureRatioElement808   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f332
+          @WM.flow LungCsIIBNoDElement271 LungCsIIBNoDPopCorrElement334
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f425
+          @WM.flow LungCDElement4 LungCsIIIADiagnosisElement394
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d745
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCsIVDiagnosisElement599   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f34
+          @WM.flow LungCT2ProgressesElement36 LungCNotProgressing2Element6
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d832
+          @WM.dependency LungCTherapyCure2Element819 LungCFirstTreatmentRateElement94   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d736
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCs01DiagnosisElement590   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d781
+          @WM.dependency LungCOutputsIIANosDiagnosisElement771 LungCsIIADiagnosisElement595   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d603
+          @WM.dependency LungCOutputDiagnosisElement600 LungCs03DiagnosisElement592   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d828
+          @WM.dependency LungCTherapyCure2Element819 LungCTherapy2RatioElement582   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d90
+          @WM.dependency LungCT2ProgToDisablingElement40 LungCT2ProgressingElement8   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d102
+          @WM.dependency LungCTreated2AgeingElement82 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d565
+          @WM.dependency LungCProgress03IVElement520 LungCProgress03IVRateElement558   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d620
+          @WM.dependency LungCOutputT2MortalityElement618 LungCT2DeathElement44   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d850
+          @WM.dependency LungCOutputTherapy2NoCureElement848 LungCTherapy2Element189   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d891
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputsIVNosNoDElement757   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f16
+          @WM.flow LungCProgress0102Element18 LungCs01Element2
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d730
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCsIIIADiagnosisElement597   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d55
+          @WM.dependency LungCHealthyAgeingElement54 LungCHealthyElement1   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f233
+          @WM.flow LungCProgress0203Element235 LungCs02Element230
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d57
+          @WM.dependency LungCInceptionElement14 LungCInceptionRateElement56   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d368
+          @WM.dependency LungCsIVNoDAgeingElement366 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f424
+          @WM.flow LungCDElement4 LungCsIIADiagnosisElement383
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d872
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputs01ScNoDElement651   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d316
+          @WM.dependency LungCsIBNoDPopCorrElement311 LungCsIBNoDElement270   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d89
+          @WM.dependency LungCT2ProgToDisablingElement40 LungCT2ProgToDisablingRateElement88   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d175
+          @WM.dependency LungCT2DisablingPopCorrElement174 LungCModelPopCorrectionFactorElement159   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f11
+          @WM.flow LungCs01Element2 LungCInceptionElement14
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d347
+          @WM.dependency LungCsIIIANoDPopCorrElement344 LungCsIIIANoDElement272   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d842
+          @WM.dependency LungCOutputCured2Element841 LungCCured2Element840   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d665
+          @WM.dependency LungCOutputsIBScNoDElement655 LungCsIBNoDElement443   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f434
+          @WM.flow LungCDElement4 LungCs03DiagnosisElement437
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d93
+          @WM.dependency LungCT2DeathElement44 LungCT2DeathRateElement92   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d899
+          @WM.dependency LungCTherapy1MortalityElement898 LungCFirstTreatmentRateElement94   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d865
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputsIBNsNoDElement635   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f291
+          @WM.flow LungCProgressIIBIIIBElement293 LungCsIIBNoDElement271
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d374
+          @WM.dependency LungCsIVNoDPopCorrElement372 LungCsIVNoDElement274   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d904
+          @WM.dependency LungCTherapy1Element25 LungCTherapy1MortalityRatioElement901   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f429
+          @WM.flow LungCsIVDiagnosisElement431 LungCsIVNoDElement274
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d649
+          @WM.dependency LungCOutputsIIIBNsNoDElement639 LungCsIIIBNoDElement445   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d409
+          @WM.dependency LungCProgressIIAIIIAElement285 LungCProgressIIAIIIARateElement408   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d642
+          @WM.dependency LungCOutputs02NsNoDElement632 LungCs02Element441   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d648
+          @WM.dependency LungCOutputsIIIANsNoDElement638 LungCsIIIANoDElement446   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d886
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputsIBNosNoDElement752   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d585
+          @WM.dependency LungCT2ProgressesElement36 LungCT2ProgressesRateElement584   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f327
+          @WM.flow LungCsIIANoDElement190 LungCsIIANoDAgeingElement329
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d727
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCsIBDiagnosisElement594   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d320
+          @WM.dependency LungCsIBNoDAgeingElement319 LungCsIBNoDElement270   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d732
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCsIVDiagnosisElement599   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d361
+          @WM.dependency LungCsIIIBNoDPopCorrElement355 LungCsIIIBNoDElement273   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d465
+          @WM.dependency LungCModelPopElement104 LungCT1DisablingElement461   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d184
+          @WM.dependency LungCOutputHealthyAndTreatedElement182 LungCNotProgressing1Element108   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d776
+          @WM.dependency LungCOutputs01NosDiagnosisElement766 LungCs01DiagnosisElement590   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d894
+          @WM.dependency LungCOutputModelPopExcludingHealthyElement892 LungCHealthyElement105   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d131
+          @WM.dependency LungCModelPopCorrectionFactorElement112 LungCModelPopCorrectionRateElement125   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d181
+          @WM.dependency LungCT2ProgressingAgeingElement179 LungCT2ProgressingElement8   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d385
+          @WM.dependency LungCsIIADiagnosisElement383 LungCsIIADiagnosisRateElement384   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f502
+          @WM.flow LungCDElement4 LungCs01DiagnosisElement505
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d307
+          @WM.dependency LungCProgressIIBIIIAElement297 LungCsIIBNoDElement271   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d801
+          @WM.dependency LungCCured1AgeingElement795 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d154
+          @WM.dependency LungCTreated1PopCorrElement152 LungCModelPopCorrectionFactorElement153   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f830
+          @WM.flow LungCTherapyCure2Element819 LungCDElement4
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d553
+          @WM.dependency LungCProgress01IVElement512 LungCProgress01IVRateElement552   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d747
+          @WM.dependency LungCOutputs01NosNoDElement746 LungCs01Element106   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d847
+          @WM.dependency LungCOutputTherapy2Element612 LungCTherapyCure2Element845   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d704
+          @WM.dependency LungCOutputsIIBScDiagnosisElement687 LungCsIIBDiagnosisElement596   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d326
+          @WM.dependency LungCsIIANoDPopCorrElement324 LungCModelPopCorrectionFactorElement314   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f47
+          @WM.flow LungCBirthElement49 Cloud45Element45
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d619
+          @WM.dependency LungCOutputT1MortalityElement617 LungCT1DeathElement207   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f37
+          @WM.flow LungCT2DisablingElement9 LungCT2ProgToDisablingElement40
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d335
+          @WM.dependency LungCsIIBNoDPopCorrElement334 LungCsIIBNoDElement271   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d855
+          @WM.dependency LungCOutputTherapy1CureElement853 LungCTherapyCure1Element844   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d195
+          @WM.dependency LungCProgressIAIIAElement194 LungCsIANoDElement3   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d698
+          @WM.dependency LungCOutputsIAScDiagnosisElement684 LungCsIADiagnosisElement593   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d554
+          @WM.dependency LungCProgress01IVElement512 LungCs01Element2   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d831
+          @WM.dependency LungCTherapyCure2Element819 LungCDElement4   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f521
+          @WM.flow LungCsIVNoDElement274 LungCProgressIAIVElement524
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f162
+          @WM.flow LungCDElement4 LungCDPopCorrElement164
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d433
+          @WM.dependency LungCsIVDiagnosisElement431 LungCsIVNoDElement274   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d780
+          @WM.dependency LungCOutputsIBNosDiagnosisElement770 LungCsIBDiagnosisElement594   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d880
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputsIIIBScNoDElement659   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d647
+          @WM.dependency LungCOutputsIIBNsNoDElement637 LungCsIIBNoDElement447   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d74
+          @WM.dependency LungCTherapy2Element28 LungCDElement4   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d440
+          @WM.dependency LungCs03DiagnosisElement437 LungCs03Element231   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d890
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputsIIIBNosNoDElement756   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d740
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCsIBDiagnosisElement594   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f299
+          @WM.flow LungCProgressIIIAIIIBElement301 LungCsIIIANoDElement272
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d103
+          @WM.dependency LungCsIANoDAgeingElement68 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f201
+          @WM.flow LungCT1ProgToDisablingElement203 LungCT1ProgressingElement197
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d602
+          @WM.dependency LungCOutputDiagnosisElement600 LungCs02DiagnosisElement591   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d871
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputsIVNsNoDElement640   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f423
+          @WM.flow LungCDElement4 LungCsIIBDiagnosisElement388
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d719
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCsIIBDiagnosisElement596   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d902
+          @WM.dependency LungCTherapy1MortalityElement898 LungCTherapy1MortalityRatioElement901   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d827
+          @WM.dependency LungCCured2PopCorrElement826 LungCCured2Element816   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d91
+          @WM.dependency LungCT2DeathElement44 LungCT2DisablingElement9   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d266
+          @WM.dependency LungCs03AgeingElement265 LungCs03Element231   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d467
+          @WM.dependency LungCModelPopElement104 LungCT2DisablingElement111   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d701
+          @WM.dependency LungCOutputsIIANsDiagnosisElement676 LungCsIIADiagnosisElement595   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f474
+          @WM.flow LungCTherapy1Element25 LungCDElement4
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f820
+          @WM.flow LungCCured2Element816 LungCCured2AgeingElement822
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d867
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputsIIBNsNoDElement637   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f214
+          @WM.flow LungCT1ProgressingElement197 LungCT1ProgressingPopCorrElement216
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f422
+          @WM.flow LungCDElement4 LungCsIBDiagnosisElement377
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f817
+          @WM.flow LungCCured2Element816 LungCTherapyCure2Element819
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d905
+          @WM.dependency LungCTherapy1MortalityElement898 LungCDElement4   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d97
+          @WM.dependency LungCTherapy1Element25 LungCTherapy1RatioElement73   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f41
+          @WM.flow LungCT2DeceasedElement10 LungCT2DeathElement44
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d731
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCsIIIBDiagnosisElement598   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d668
+          @WM.dependency LungCOutputsIIIAScNoDElement658 LungCsIIIANoDElement446   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f52
+          @WM.flow LungCHealthyElement1 LungCHealthyAgeingElement54
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d302
+          @WM.dependency LungCProgressIAIBElement277 LungCsIANoDElement3   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d229
+          @WM.dependency LungCCausedDeathElement115 LungCT1DeathElement207   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d866
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputsIIANsNoDElement636   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f910
+          @WM.flow LungCT2ProgressingElement8 LungCTherapy2FailedElement913
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d693
+          @WM.dependency LungCOutputs02NsDiagnosisElement672 LungCs02DiagnosisElement591   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f503
+          @WM.flow LungCs01DiagnosisElement505 LungCs01Element2
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d315
+          @WM.dependency LungCsIBNoDPopCorrElement311 LungCModelPopCorrectionFactorElement312   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d402
+          @WM.dependency LungCsIIIBDiagnosisElement400 LungCsIIIBNoDElement273   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d641
+          @WM.dependency LungCOutputs01NsNoDElement631 LungCs01Element106   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d893
+          @WM.dependency LungCOutputModelPopExcludingHealthyElement892 LungCModelPopElement104   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d576
+          @WM.dependency LungCProgressIIIAIVElement539 LungCsIIIANoDElement272   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d761
+          @WM.dependency LungCOutputsIIANosNoDElement753 LungCsIIANoDElement444   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d838
+          @WM.dependency LungCTherapyCure2Element819 LungCTherapy2CureRatioElement837   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d222
+          @WM.dependency LungCT1ProgressingAgeingElement219 LungCT1ProgressingElement197   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d616
+          @WM.dependency LungCOutputMortalityElement615 LungCCausedDeathElement115   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d738
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCs03DiagnosisElement592   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d83
+          @WM.dependency LungCTreated2AgeingElement82 LungCNotProgressing2Element6   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d804
+          @WM.dependency LungCTherapyCure1Element792 LungCTherapy1RatioElement73   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d870
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputsIIIBNsNoDElement639   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d305
+          @WM.dependency LungCProgressIIAIIBElement289 LungCsIIANoDElement190   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f896
+          @WM.flow LungCTherapy1MortalityElement898 LungCDElement4
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f217
+          @WM.flow LungCT1ProgressingElement197 LungCT1ProgressingAgeingElement219
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d122
+          @WM.dependency LungCHealthyPopCorrElement119 LungCHealthyElement1   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d777
+          @WM.dependency LungCOutputs02NosDiagnosisElement767 LungCs02DiagnosisElement591   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d143
+          @WM.dependency LungCs01PopCorrElement141 LungCModelPopCorrectionFactorElement142   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d269
+          @WM.dependency LungCs03AgeingElement265 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d464
+          @WM.dependency LungCModelPopElement104 LungCT1ProgressingElement460   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d628
+          @WM.dependency LungCOutputDisabling2Element624 LungCT2DisablingElement111   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d878
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputsIIBScNoDElement657   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d363
+          @WM.dependency LungCsIIIBNoDAgeingElement358 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f46
+          @WM.flow LungCHealthyElement1 LungCBirthElement49
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d630
+          @WM.dependency LungCOutputNoDSumElement629 LungCNoDSumElement449   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d183
+          @WM.dependency LungCOutputHealthyAndTreatedElement182 LungCHealthyElement105   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f518
+          @WM.flow LungCProgress03IVElement520 LungCs03Element231
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d472
+          @WM.dependency LungCDAgeingElement471 LungCDElement4   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d362
+          @WM.dependency LungCsIIIBNoDAgeingElement358 LungCsIIIBNoDElement273   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d439
+          @WM.dependency LungCs03DiagnosisElement437 LungCs03DiagnosisRateElement438   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f317
+          @WM.flow LungCsIBNoDElement270 LungCsIBNoDAgeingElement319
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d608
+          @WM.dependency LungCOutputDiagnosisElement600 LungCsIIIADiagnosisElement597   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d132
+          @WM.dependency LungCModelPopCorrectionFactorElement112 LungCModelPopElement104   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d411
+          @WM.dependency LungCProgressIIAIIBElement289 LungCProgressIIAIIBRateElement410   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d705
+          @WM.dependency LungCOutputsIIIANsDiagnosisElement678 LungCsIIIADiagnosisElement597   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f398
+          @WM.flow LungCsIIIBDiagnosisElement400 LungCsIIIBNoDElement273
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d407
+          @WM.dependency LungCProgressIAIIAElement194 LungCProgressIAIIARateElement406   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f537
+          @WM.flow LungCProgressIIIAIVElement539 LungCsIIIANoDElement272
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f522
+          @WM.flow LungCProgressIAIVElement524 LungCsIANoDElement3
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d785
+          @WM.dependency LungCOutputsIVNosDiagnosisElement775 LungCsIVDiagnosisElement599   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d587
+          @WM.dependency LungCOutputNotProgressing1Element586 LungCNotProgressing1Element108   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d609
+          @WM.dependency LungCOutputDiagnosisElement600 LungCsIIIBDiagnosisElement598   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d667
+          @WM.dependency LungCOutputsIIBScNoDElement657 LungCsIIBNoDElement447   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d741
+          @WM.dependency LungCOutputNosDiagnosisElement735 LungCsIIADiagnosisElement595   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f298
+          @WM.flow LungCsIIIBNoDElement273 LungCProgressIIIAIIIBElement301
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d95
+          @WM.dependency LungCTherapy1Element25 LungCFirstTreatmentRateElement94   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d714
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCs02DiagnosisElement591   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d601
+          @WM.dependency LungCOutputDiagnosisElement600 LungCs01DiagnosisElement590   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d243
+          @WM.dependency LungCProgress03IAElement239 LungCProgress03IARateElement241   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d779
+          @WM.dependency LungCOutputsIANosDiagnosisElement769 LungCsIADiagnosisElement593   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f529
+          @WM.flow LungCsIVNoDElement274 LungCProgressIIAIVElement532
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d697
+          @WM.dependency LungCOutputsIANsDiagnosisElement674 LungCsIADiagnosisElement593   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d726
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCsIADiagnosisElement593   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d397
+          @WM.dependency LungCsIIIADiagnosisElement394 LungCsIIIANoDElement272   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d857
+          @WM.dependency LungCOutputHealthyAndTreatedElement182 LungCCured2Element840   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d707
+          @WM.dependency LungCOutputsIIIBNsDiagnosisElement679 LungCsIIIBDiagnosisElement598   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d65
+          @WM.dependency LungCProgress0102Element18 LungCs01Element2   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d261
+          @WM.dependency LungCs03PopCorrElement259 LungCModelPopCorrectionFactorElement260   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d459
+          @WM.dependency LungCNoDSumElement449 LungCsIVNoDElement448   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d321
+          @WM.dependency LungCsIBNoDAgeingElement319 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d823
+          @WM.dependency LungCCured2AgeingElement822 LungCCured2Element816   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d903
+          @WM.dependency LungCTherapyCure1Element792 LungCTherapy1MortalityRatioElement901   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f204
+          @WM.flow LungCT1DeceasedElement199 LungCT1DeathElement207
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d165
+          @WM.dependency LungCDPopCorrElement164 LungCModelPopCorrectionFactorElement148   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d729
+          @WM.dependency LungCOutputScDiagnosisElement712 LungCsIIBDiagnosisElement596   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f435
+          @WM.flow LungCs03DiagnosisElement437 LungCs03Element231
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d924
+          @WM.dependency LungCOutputTherapy2Element612 LungCTherapy2FailedElement923   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d885
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputsIANosNoDElement751   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d884
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputs03NosNoDElement750   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d228
+          @WM.dependency LungCT1DisablingPopCorrElement226 LungCT1DisablingElement198   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d760
+          @WM.dependency LungCOutputsIBNosNoDElement752 LungCsIBNoDElement443   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d863
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputs03NsNoDElement633   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d749
+          @WM.dependency LungCOutputs02NosNoDElement748 LungCs02Element441   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d268
+          @WM.dependency LungCsIANoDPopCorrElement147 LungCModelPopCorrectionFactorElement267   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f172
+          @WM.flow LungCT2DisablingElement9 LungCT2DisablingPopCorrElement174
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f404
+          @WM.flow LungCProgressIAIBElement277 LungCsIANoDElement3
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d223
+          @WM.dependency LungCT1ProgressingAgeingElement219 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d613
+          @WM.dependency LungCOutputTherapy1Element611 LungCTherapy1Element188   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d721
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCsIIIBDiagnosisElement598   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f282
+          @WM.flow LungCsIIIANoDElement272 LungCProgressIIAIIIAElement285
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d669
+          @WM.dependency LungCOutputsIIIBScNoDElement659 LungCsIIIBNoDElement445   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d121
+          @WM.dependency LungCHealthyPopCorrElement119 LungCModelPopCorrectionFactorElement120   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d702
+          @WM.dependency LungCOutputsIIAScDiagnosisElement686 LungCsIIADiagnosisElement595   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d873
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputs02ScNoDElement652   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d577
+          @WM.dependency LungCProgressIIIBIVElement542 LungCProgressIIIBIVRateElement564   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d209
+          @WM.dependency LungCT1ProgToDisablingElement203 LungCT1ProgToDisablingRateElement208   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f117
+          @WM.flow LungCHealthyElement1 LungCHealthyPopCorrElement119
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d643
+          @WM.dependency LungCOutputs03NsNoDElement633 LungCs03Element442   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d455
+          @WM.dependency LungCNoDSumElement449 LungCsIIANoDElement444   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f80
+          @WM.flow LungCNotProgressing2Element6 LungCTreated2AgeingElement82
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d336
+          @WM.dependency LungCsIIBNoDPopCorrElement334 LungCModelPopCorrectionFactorElement313   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d457
+          @WM.dependency LungCNoDSumElement449 LungCsIIIANoDElement446   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d696
+          @WM.dependency LungCOutputs03ScDiagnosisElement683 LungCs03DiagnosisElement592   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d713
+          @WM.dependency LungCOutputNsDiagnosisElement711 LungCs01DiagnosisElement590   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d879
+          @WM.dependency LungCOutputNoDScElement859 LungCOutputsIIIAScNoDElement658   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d670
+          @WM.dependency LungCOutputsIVScNoDElement660 LungCsIVNoDElement448   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d419
+          @WM.dependency LungCProgressIIBIIIAElement297 LungCProgressIIBIIIARateElement418   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f290
+          @WM.flow LungCsIIIBNoDElement273 LungCProgressIIBIIIBElement293
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d149
+          @WM.dependency LungCsIANoDPopCorrElement147 LungCsIANoDElement3   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d625
+          @WM.dependency LungCOutputProgressing1Element621 LungCT1ProgressingElement460   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d304
+          @WM.dependency LungCProgressIIAIIIAElement285 LungCsIIANoDElement190   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d396
+          @WM.dependency LungCsIIIADiagnosisElement394 LungCsIIIADiagnosisRateElement395   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f530
+          @WM.flow LungCProgressIIAIVElement532 LungCsIIANoDElement190
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f66
+          @WM.flow LungCsIANoDElement3 LungCsIANoDAgeingElement68
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f19
+          @WM.flow LungCDElement4 LungCsIADiagnosisElement22
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d306
+          @WM.dependency LungCProgressIIBIIIBElement293 LungCsIIBNoDElement271   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d763
+          @WM.dependency LungCOutputsIIIANosNoDElement755 LungCsIIIANoDElement446   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d70
+          @WM.dependency LungCsIADiagnosisElement22 LungCsIANoDElement3   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d839
+          @WM.dependency LungCTherapy2Element28 LungCTherapy2CureRatioElement837   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f793
+          @WM.flow LungCCured1Element789 LungCCured1AgeingElement795
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d166
+          @WM.dependency LungCDPopCorrElement164 LungCDElement4   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f30
+          @WM.flow LungCT1ProgressesElement32 LungCNotProgressing1Element5
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d570
+          @WM.dependency LungCProgressIBIVElement528 LungCsIBNoDElement270   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d909
+          @WM.dependency LungCOutputTherapy1MortalityInTherapyElement908 LungCTherapy1MortalityElement906   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d403
+          @WM.dependency LungCsIIIBDiagnosisElement400 LungCsIIIBDiagnosisRateElement401   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d466
+          @WM.dependency LungCModelPopElement104 LungCT2ProgressingElement110   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f252
+          @WM.flow LungCs02Element230 LungCs02AgeingElement254
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d883
+          @WM.dependency LungCoutputNoDNosElement860 LungCOutputs02NosNoDElement748   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f283
+          @WM.flow LungCProgressIIAIIIAElement285 LungCsIIANoDElement190
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d75
+          @WM.dependency LungCTherapy1Element25 LungCDElement4   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f156
+          @WM.flow LungCNotProgressing2Element6 LungCTreated2PopCorrElement158
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d421
+          @WM.dependency LungCProgressIIBIIIBElement293 LungCProgressIIBIIIBRateElement420   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f59
+          @WM.flow LungCs01Element2 LungCs01AgeingElement61
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d450
+          @WM.dependency LungCNoDSumElement449 LungCs01Element106   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d703
+          @WM.dependency LungCOutputsIIBNsDiagnosisElement677 LungCsIIBDiagnosisElement596   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d864
+          @WM.dependency LungCOutputNoDNsElement858 LungCOutputsIANsNoDElement634   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d900
+          @WM.dependency LungCTherapy1MortalityElement898 LungCTherapy1RatioElement73   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d473
+          @WM.dependency LungCDAgeingElement471 DummyRateForUnitsConversionElement98   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d185
+          @WM.dependency LungCOutputHealthyAndTreatedElement182 LungCNotProgressing2Element109   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d390
+          @WM.dependency LungCsIIBDiagnosisElement388 LungCsIIBNoDElement271   -0.1
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f356
+          @WM.flow LungCsIIIBNoDElement273 LungCsIIIBNoDAgeingElement358
+      _ : SYSDYN.FlowConnection
+          MOD.DiagramConnectionToConnection CMC.f38
+          @WM.flow LungCT2ProgToDisablingElement40 LungCT2ProgressingElement8
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d807
+          @WM.dependency LungCTherapyCure1Element792 LungCDElement4   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d242
+          @WM.dependency LungCProgress0203Element235 LungCProgress0203RateElement240   -0.1
+
+      TotalPopulationT1Element11 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulationT1
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 743.0, 122.0] : G2D.Transform
+      TotalPopulationBirthElement3 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulationBirth
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 708.0, 85.0] : G2D.Transform
+      TotalPopulationMenElement7 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulationMen
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 709.4, 24.0] : G2D.Transform
+      OutputDataTotalPopulationMenSumElement15 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.OutputDataTotalPopulationMenSum
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 679.6, 38.6] : G2D.Transform
+      TotalPopulationWomenElement8 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulationWomen
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 775.0, 25.2] : G2D.Transform
+      TotalPopulationElement1 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulation
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 743.0, 53.8] : G2D.Transform
+      OutputDataTotalPopulationWomenSumElement16 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.OutputDataTotalPopulationWomenSum
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 800.8, 41.4] : G2D.Transform
+      DummyRateForUnitsConversionElement19 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.DummyRateForUnitsConversion
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 735.8, 149.0] : G2D.Transform
+      TotalPopulationDeathElement5 : SYSDYN.AuxiliarySymbol
+          MOD.ElementToComponent CMC.TotalPopulationDeath
+          DIA.HasTransform [1.0, 0.0, 0.0, 1.0, 832.8, 85.0] : G2D.Transform
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d6
+          @WM.dependency TotalPopulationDeathElement5 TotalPopulationElement1   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d21
+          @WM.dependency TotalPopulationDeathElement5 DummyRateForUnitsConversionElement19   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d9
+          @WM.dependency TotalPopulationElement1 TotalPopulationMenElement7   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d17
+          @WM.dependency OutputDataTotalPopulationMenSumElement15 TotalPopulationMenElement7   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d12
+          @WM.dependency TotalPopulationDeathElement5 TotalPopulationT1Element11   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d20
+          @WM.dependency TotalPopulationBirthElement3 DummyRateForUnitsConversionElement19   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d14
+          @WM.dependency TotalPopulationT1Element11 TotalPopulationElement1   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d18
+          @WM.dependency OutputDataTotalPopulationWomenSumElement16 TotalPopulationWomenElement8   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d10
+          @WM.dependency TotalPopulationElement1 TotalPopulationWomenElement8   -0.1
+      _ : SYSDYN.DependencyConnection
+          MOD.DiagramConnectionToConnection CMC.d13
+          @WM.dependency TotalPopulationBirthElement3 TotalPopulationT1Element11   -0.1
+
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/.credentials.properties b/1.8/org.simantics.sysdyn.product.site.feature/.credentials.properties
new file mode 100644 (file)
index 0000000..859dca4
--- /dev/null
@@ -0,0 +1,2 @@
+simantics.user=anonymous\r
+simantics.password=
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/.project b/1.8/org.simantics.sysdyn.product.site.feature/.project
new file mode 100644 (file)
index 0000000..83aae40
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.sysdyn.product.site.feature</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.FeatureBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.FeatureNature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/Resources.rmap b/1.8/org.simantics.sysdyn.product.site.feature/Resources.rmap
new file mode 100644 (file)
index 0000000..78c416f
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<rmap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.eclipse.org/buckminster/RMap-1.0"\r
+       xmlns:bc="http://www.eclipse.org/buckminster/Common-1.0" xmlns:pv="http://www.eclipse.org/buckminster/Provider-1.0">\r
+\r
+       <redirect href="http://www.simantics.org/download/head/rmap/Sysdyn.rmap" />\r
+\r
+</rmap>
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/buckminster.cspex b/1.8/org.simantics.sysdyn.product.site.feature/buckminster.cspex
new file mode 100644 (file)
index 0000000..46e472e
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<cspecExtension xmlns:com="http://www.eclipse.org/buckminster/Common-1.0"\r
+                    xmlns="http://www.eclipse.org/buckminster/CSpec-1.0">\r
+    <actions>\r
+        <public name="create.product" actor="ant">\r
+            <actorProperties>\r
+                <property key="buildFile" value="build/product.ant" />\r
+                <property key="targets" value="create.product" />\r
+            </actorProperties>\r
+            <properties>\r
+                <property key="profile" value="${p2.profileName}" />\r
+                <property key="iu" value="${p2.rootId}" />\r
+            </properties>\r
+            <prerequisites alias="repository">\r
+                <attribute name="site.p2" />\r
+            </prerequisites>\r
+            <products alias="destination" base="${buckminster.output}">\r
+                <path path="${build.label}.${target.ws}.${target.os}.${target.arch}/" />\r
+            </products>\r
+        </public>\r
+        <public name="create.product.zip" actor="ant">\r
+            <actorProperties>\r
+                <property key="buildFileId" value="buckminster.pdetasks" />\r
+                <property key="targets" value="create.zip" />\r
+            </actorProperties>\r
+            <prerequisites alias="action.requirements">\r
+                <attribute name="create.product" />\r
+            </prerequisites>\r
+            <products alias="action.output" base="${buckminster.output}">\r
+                <path path="${build.label}.${target.ws}.${target.os}.${target.arch}.zip" />\r
+            </products>\r
+        </public>\r
+    </actions>\r
+</cspecExtension>
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/buckminster.properties b/1.8/org.simantics.sysdyn.product.site.feature/buckminster.properties
new file mode 100644 (file)
index 0000000..f310dee
--- /dev/null
@@ -0,0 +1,22 @@
+#buckminster.output.root=c:/simantics-build/site
+#buckminster.temp.root=c:/simantics-build/temp
+
+# How .qualifier in versions should be replaced
+qualifier.replacement.*=generator:lastRevision
+generator.lastRevision.format=r{0,number,000000}
+
+# Pack200 compression
+#site.pack200=true
+#site.retain.unpack=true
+
+# JAR Signing
+#site.signing=true
+#signing.type=local
+#local.sign=true
+
+# Generate source bundles
+cbi.include.source=false
+
+target.os=win32
+target.ws=win32
+target.arch=*
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/build.properties b/1.8/org.simantics.sysdyn.product.site.feature/build.properties
new file mode 100644 (file)
index 0000000..82ab19c
--- /dev/null
@@ -0,0 +1 @@
+bin.includes = feature.xml\r
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/build/product.ant b/1.8/org.simantics.sysdyn.product.site.feature/build/product.ant
new file mode 100644 (file)
index 0000000..9dd09c8
--- /dev/null
@@ -0,0 +1,49 @@
+<project>\r
+        <pathconvert property="equinox.launcher.jar">\r
+          <first count="1">\r
+            <sort>\r
+              <fileset dir="${eclipse.home}/plugins" includes="**/org.eclipse.equinox.launcher_*.jar"/>\r
+              <reverse xmlns="antlib:org.apache.tools.ant.types.resources.comparators">\r
+                <date/>\r
+              </reverse>\r
+            </sort>\r
+          </first>\r
+        </pathconvert>\r
+\r
+       <target name="create.product">\r
+               <property name="destination" location="${sp:destination}"/>\r
+               <delete dir="${destination}"></delete>\r
+               <makeurl property="repository" file="${sp:repository}"/>\r
+               <mkdir dir="${destination}"/>\r
+               <echoproperties ></echoproperties>\r
+               <echo message="${equinox.launcher.jar}"/>\r
+               <echo message="${repository}"/>\r
+               <echo message="${destination}"/>\r
+               <java jar="${equinox.launcher.jar}" fork="true" failonerror="true" >\r
+                       <arg value="-application"/>\r
+                       <arg value="org.eclipse.equinox.p2.director"/>\r
+                       <arg value="-artifactRepository"/>\r
+                       <arg value="${repository}"/>\r
+                       <arg value="-metadataRepository"/>\r
+                       <arg value="${repository}"/>\r
+                       <arg value="-destination"/>\r
+                       <arg value="${destination}"/>\r
+                       <arg value="-bundlepool"/>\r
+                       <arg value="${destination}"/>\r
+                       <arg value="-roaming"/>\r
+                       <arg value="-profile"/>\r
+                       <arg value="${profile}"/>\r
+                       <arg value="-profileProperties" />\r
+                       <arg value="org.eclipse.update.install.features=true" />\r
+                       <arg value="-installIU"/>\r
+                       <arg value="${iu}"/>\r
+                       <arg value="-p2.os" />\r
+                       <arg value="${target.os}" />\r
+                       <arg value="-p2.ws" />\r
+                       <arg value="${target.ws}" />\r
+                       <arg value="-p2.arch" />\r
+                       <arg value="${target.arch}" />\r
+                       <arg value="-consoleLog"/>\r
+               </java>\r
+       </target>\r
+</project>
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/feature.xml b/1.8/org.simantics.sysdyn.product.site.feature/feature.xml
new file mode 100644 (file)
index 0000000..8612af1
--- /dev/null
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<feature\r
+      id="org.simantics.sysdyn.product.site"\r
+      label="Sysdyn Product Site"\r
+      version="1.5.1.qualifier"\r
+      provider-name="VTT Technical Research Centre of Finland">\r
+\r
+   <description url="http://www.example.com/description">\r
+      [Enter Feature Description here.]\r
+   </description>\r
+\r
+   <copyright url="http://www.example.com/copyright">\r
+      [Enter Copyright Description here.]\r
+   </copyright>\r
+\r
+   <license url="http://www.example.com/license">\r
+      [Enter License Description here.]\r
+   </license>\r
+\r
+   <includes\r
+         id="org.simantics.sysdyn"\r
+         version="0.0.0"/>\r
+\r
+</feature>\r
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/jenkins.buckminster.script b/1.8/org.simantics.sysdyn.product.site.feature/jenkins.buckminster.script
new file mode 100644 (file)
index 0000000..f739863
--- /dev/null
@@ -0,0 +1,6 @@
+importtargetdefinition -A 'd:/target/3.7.1/target-win.target'\r
+import 'site.cquery'\r
+build\r
+perform -D target.os=* -D target.ws=* -D target.arch=* org.simantics.sysdyn.product.site#site.p2\r
+perform -D target.os=win32 -D target.ws=win32 -D target.arch=x86 -D p2.profileName=SysdynProfile -D p2.rootId=org.simantics.sysdyn.product.Sysdyn -D build.label=SimanticsSysdyn-b${BUILD_NUMBER}-r${SVN_REVISION} org.simantics.sysdyn.product.site#create.product.zip\r
+perform -D target.os=win32 -D target.ws=win32 -D target.arch=x86_64 -D p2.profileName=SysdynProfile -D p2.rootId=org.simantics.sysdyn.product.Sysdyn -D build.label=SimanticsSysdyn-b${BUILD_NUMBER}-r${SVN_REVISION} org.simantics.sysdyn.product.site#create.product.zip\r
diff --git a/1.8/org.simantics.sysdyn.product.site.feature/site.cquery b/1.8/org.simantics.sysdyn.product.site.feature/site.cquery
new file mode 100644 (file)
index 0000000..678b963
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<cq:componentQuery xmlns:cq="http://www.eclipse.org/buckminster/CQuery-1.0" resourceMap="Resources.rmap" properties=".credentials.properties">\r
+    <cq:rootRequest name="org.simantics.sysdyn.product.site" componentType="eclipse.feature"/>\r
+    <cq:property key="target.arch" value="*"/>\r
+    <cq:property key="target.os" value="*"/>\r
+    <cq:property key="target.ws" value="*"/>\r
+    <cq:advisorNode namePattern=".*\.source$" componentType="osgi.bundle" skipComponent="true"/>\r
+    <cq:advisorNode namePattern=".*\.source$" componentType="eclipse.feature" skipComponent="true"/>\r
+    <cq:advisorNode namePattern=".*" branchTagPath="main"/>\r
+</cq:componentQuery>\r
diff --git a/1.8/org.simantics.sysdyn.tests/.classpath b/1.8/org.simantics.sysdyn.tests/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.sysdyn.tests/.project b/1.8/org.simantics.sysdyn.tests/.project
new file mode 100644 (file)
index 0000000..0736802
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.sysdyn.tests</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.sysdyn.tests/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.sysdyn.tests/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..f287d53
--- /dev/null
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.sysdyn.tests/META-INF/MANIFEST.MF b/1.8/org.simantics.sysdyn.tests/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..ff6e3bc
--- /dev/null
@@ -0,0 +1,12 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Sysdyn Tests
+Bundle-SymbolicName: org.simantics.sysdyn.tests
+Bundle-Version: 1.0.0.qualifier
+Bundle-Activator: org.simantics.sysdyn.tests.Activator
+Require-Bundle: org.simantics.modelica;bundle-version="1.0.0",
+ org.junit;bundle-version="4.8.2",
+ org.simantics.db.testing;bundle-version="1.0.0"
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Import-Package: org.osgi.framework
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFMU.fmu b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFMU.fmu
new file mode 100644 (file)
index 0000000..722d10f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFMU.fmu differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFile.fmu b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFile.fmu
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFile.txt b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/DummyFile.txt
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTest.mo b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTest.mo
new file mode 100644 (file)
index 0000000..078b6c6
--- /dev/null
@@ -0,0 +1,31 @@
+model FMUAllTypesOfVariablesTestModel\r
+       parameter Boolean b = true;\r
+       parameter Integer i = 1;\r
+       parameter Real r = 1.0;\r
+       \r
+       Boolean discreteBoolean;\r
+       Integer discreteInteger;\r
+       Real continuousReal;    \r
+       \r
+       Real valveBoolean;\r
+       Real valveInteger;\r
+       Real valveReal;\r
+       \r
+       Real stockBoolean(start=0.0,fixed=true);\r
+       Real stockInteger(start=0.0,fixed=true);\r
+       Real stockReal(start=0.0,fixed=true);\r
+       \r
+       parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+equation\r
+       discreteBoolean = if initial() or b or not b then (b) else pre(discreteBoolean);\r
+       discreteInteger = if initial() or i < 0 or i >= 0 then (i) else pre(discreteInteger);\r
+       continuousReal = if initial() or r < 0 or r >= 0 then (r) else pre(continuousReal);     \r
+       \r
+       valveBoolean = if initial() or b or not b then (if b then 1 else -1) else pre(valveBoolean);\r
+       valveInteger = if initial() or i < 0 or i >= 0 then (i) else pre(valveInteger);\r
+       valveReal = if initial() or r < 0 or r >= 0 then (r) else pre(valveReal);\r
+       \r
+       der(stockBoolean) = valveBoolean;\r
+       der(stockInteger) = valveInteger;\r
+       der(stockReal) = valveReal;\r
+end FMUAllTypesOfVariablesTestModel;
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTest.mos b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTest.mos
new file mode 100644 (file)
index 0000000..bb9dde3
--- /dev/null
@@ -0,0 +1,2 @@
+loadFile("FMUAllTypesOfVariablesTest.mo");\r
+translateModelFMU(FMUAllTypesOfVariablesTestModel)
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.c
new file mode 100644 (file)
index 0000000..2903352
--- /dev/null
@@ -0,0 +1,530 @@
+/* Simulation code for FMUAllTypesOfVariablesTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "simulation_runtime.h"\r
+#include "omc_error.h"\r
+\r
+#include <assert.h>\r
+#include <string.h>\r
+\r
+#include "FMUAllTypesOfVariablesTestModel_functions.h"\r
+\r
+#include "_FMUAllTypesOfVariablesTestModel.h"\r
+#include "FMUAllTypesOfVariablesTestModel_functions.c"\r
+/* dummy VARINFO and FILEINFO */\r
+const FILE_INFO dummyFILE_INFO = {"",-1,-1,-1,-1,1};\r
+const VAR_INFO dummyVAR_INFO = {-1,"","",(FILE_INFO){"",-1,-1,-1,-1,1}};\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef _OMC_MEASURE_TIME\r
+int measure_time_flag = 1;\r
+#else\r
+int measure_time_flag = 0;\r
+#endif\r
+\r
+void setupDataStruc(DATA *data)\r
+{\r
+  ASSERT(data,"Error while initialize Data");\r
+  data->modelData.modelName = "FMUAllTypesOfVariablesTestModel";\r
+  data->modelData.modelFilePrefix = "FMUAllTypesOfVariablesTestModel";\r
+  data->modelData.modelDir = "";\r
+  data->modelData.modelGUID = "{e473ffda-4cfa-4ca5-b49b-0c9abe90687b}";\r
+  \r
+  data->modelData.nStates = 3;\r
+  data->modelData.nVariablesReal = 2*3+4;\r
+  data->modelData.nVariablesInteger = 1;\r
+  data->modelData.nVariablesBoolean = 1;\r
+  data->modelData.nVariablesString = 0;\r
+  data->modelData.nParametersReal = 2;\r
+  data->modelData.nParametersInteger = 1;\r
+  data->modelData.nParametersBoolean = 1;\r
+  data->modelData.nParametersString = 0;\r
+  data->modelData.nInputVars = 0;\r
+  data->modelData.nOutputVars = 0;\r
+  data->modelData.nJacobians = 4;\r
+  data->modelData.nHelpVars = 0;\r
+  \r
+  data->modelData.nAliasReal = 0;\r
+  data->modelData.nAliasInteger = 0;\r
+  data->modelData.nAliasBoolean = 0;\r
+  data->modelData.nAliasString = 0;\r
+  \r
+  data->modelData.nZeroCrossings = 0;\r
+  data->modelData.nSamples = 0;\r
+  data->modelData.nInitEquations = 0;\r
+  data->modelData.nResiduals = 3;\r
+  data->modelData.nExtObjs = 0;\r
+  data->modelData.nFunctions = 0;\r
+  data->modelData.nEquations = 18;\r
+  \r
+  data->modelData.nDelayExpressions = 0;\r
+  \r
+}\r
+\r
+void setupDataStruc2(DATA *data)\r
+{\r
+  const struct FUNCTION_INFO funcInfo[1] = {{-1,"",omc_dummyFileInfo}};\r
+  memcpy(data->modelData.functionNames, &funcInfo, data->modelData.nFunctions*sizeof(FUNCTION_INFO));\r
+  \r
+  const VAR_INFO** equationInfo_cref1 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref1[0] = &$PvalveReal__varInfo;\r
+  const VAR_INFO** equationInfo_cref3 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref3[0] = &$P$DER$PstockReal__varInfo;\r
+  const VAR_INFO** equationInfo_cref5 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref5[0] = &$PvalveInteger__varInfo;\r
+  const VAR_INFO** equationInfo_cref7 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref7[0] = &$P$DER$PstockInteger__varInfo;\r
+  const VAR_INFO** equationInfo_cref9 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref9[0] = &$PvalveBoolean__varInfo;\r
+  const VAR_INFO** equationInfo_cref11 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref11[0] = &$P$DER$PstockBoolean__varInfo;\r
+  const VAR_INFO** equationInfo_cref13 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref13[0] = &$PcontinuousReal__varInfo;\r
+  const VAR_INFO** equationInfo_cref15 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref15[0] = &$PdiscreteInteger__varInfo;\r
+  const VAR_INFO** equationInfo_cref17 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref17[0] = &$PdiscreteBoolean__varInfo;\r
+  const struct EQUATION_INFO equationInfo[18] = {\r
+    {1012,"SES_ALGORITHM 0", 0, NULL},\r
+    {1013,"SES_SIMPLE_ASSIGN 1",1,equationInfo_cref1},\r
+    {1014,"SES_ALGORITHM 2", 0, NULL},\r
+    {1015,"SES_SIMPLE_ASSIGN 3",1,equationInfo_cref3},\r
+    {1016,"SES_ALGORITHM 4", 0, NULL},\r
+    {1017,"SES_SIMPLE_ASSIGN 5",1,equationInfo_cref5},\r
+    {1018,"SES_ALGORITHM 6", 0, NULL},\r
+    {1019,"SES_SIMPLE_ASSIGN 7",1,equationInfo_cref7},\r
+    {1020,"SES_ALGORITHM 8", 0, NULL},\r
+    {1021,"SES_SIMPLE_ASSIGN 9",1,equationInfo_cref9},\r
+    {1022,"SES_ALGORITHM 10", 0, NULL},\r
+    {1023,"SES_SIMPLE_ASSIGN 11",1,equationInfo_cref11},\r
+    {1024,"SES_ALGORITHM 12", 0, NULL},\r
+    {1025,"SES_SIMPLE_ASSIGN 13",1,equationInfo_cref13},\r
+    {1026,"SES_ALGORITHM 14", 0, NULL},\r
+    {1027,"SES_SIMPLE_ASSIGN 15",1,equationInfo_cref15},\r
+    {1028,"SES_ALGORITHM 16", 0, NULL},\r
+    {1029,"SES_SIMPLE_ASSIGN 17",1,equationInfo_cref17}\r
+  };\r
+  const int n_omc_equationInfo_reverse_prof_index = 0;\r
+  const int omc_equationInfo_reverse_prof_index[] = {\r
+    \r
+  };\r
+  memcpy(data->modelData.equationInfo, &equationInfo, data->modelData.nEquations*sizeof(EQUATION_INFO));\r
+  \r
+  data->modelData.nProfileBlocks = n_omc_equationInfo_reverse_prof_index;\r
+  data->modelData.equationInfo_reverse_prof_index = (int*) malloc(data->modelData.nProfileBlocks*sizeof(int));\r
+  memcpy(data->modelData.equationInfo_reverse_prof_index, omc_equationInfo_reverse_prof_index, data->modelData.nProfileBlocks*sizeof(int));\r
+}\r
+\r
+/* Has to be performed after _init.xml file has been read */\r
+void callExternalObjectConstructors(DATA *data)\r
+{\r
+  state mem_state;\r
+  mem_state = get_memory_state();\r
+  /* data->simulationInfo.extObjs = NULL; */\r
+}\r
+\r
+void callExternalObjectDestructors(DATA *data)\r
+{\r
+  if (data->simulationInfo.extObjs) {\r
+    free(data->simulationInfo.extObjs);\r
+    data->simulationInfo.extObjs = 0;\r
+  }\r
+}\r
+\r
+\r
+int input_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+int output_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* Initializes the raw time events of the simulation using the now\r
+   calcualted parameters. */\r
+void function_sampleInit(DATA *data)\r
+{\r
+}\r
+\r
+int function_updateSample(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_storeDelayed(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundStartValues(DATA *data)\r
+{\r
+\r
+  \r
+  DEBUG_INFO(LOG_INIT, "updating start-values:");\r
+  \r
+  return 0;\r
+}\r
+\r
+int initial_residual(DATA *data, double $P$_lambda, double* initialResiduals)\r
+{\r
+  int i = 0;\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  DEBUG_INFO(LOG_RES_INIT, "updating initial_residuals:");\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($PstockReal - $P$START$PstockReal));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stockReal - $_start(stockReal)) = %f", i, initialResiduals[i-1]);\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($PstockInteger - $P$START$PstockInteger));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stockInteger - $_start(stockInteger)) = %f", i, initialResiduals[i-1]);\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($PstockBoolean - $P$START$PstockBoolean));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stockBoolean - $_start(stockBoolean)) = %f", i, initialResiduals[i-1]);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundParameters(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_0(DATA *data) {\r
+  modelica_boolean tmp0;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:24:2-24:93]*/\r
+  tmp0 = initial();\r
+  $PvalveBoolean = (((tmp0 || $Pb) || (!$Pb))?($Pb?1.0:-1.0):$P$PRE$PvalveBoolean); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_1(DATA *data) {\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:28:2-28:34]*/\r
+  $P$DER$PstockBoolean = $PvalveBoolean; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_2(DATA *data) {\r
+  modelica_boolean tmp1;\r
+  modelica_boolean tmp2;\r
+  modelica_boolean tmp3;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:25:2-25:80]*/\r
+  tmp1 = initial();\r
+  RELATIONTOZC(tmp2, (modelica_integer)$Pi, (modelica_integer) 0, -1,Less,<);\r
+  RELATIONTOZC(tmp3, (modelica_integer)$Pi, (modelica_integer) 0, -1,GreaterEq,>=);\r
+  $PvalveInteger = (((tmp1 || tmp2) || tmp3)?((modelica_real)(modelica_integer)$Pi):$P$PRE$PvalveInteger); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_3(DATA *data) {\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:29:2-29:34]*/\r
+  $P$DER$PstockInteger = $PvalveInteger; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_4(DATA *data) {\r
+  modelica_boolean tmp4;\r
+  modelica_boolean tmp5;\r
+  modelica_boolean tmp6;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:26:2-26:74]*/\r
+  tmp4 = initial();\r
+  RELATIONTOZC(tmp5, $Pr, 0.0, -1,Less,<);\r
+  RELATIONTOZC(tmp6, $Pr, 0.0, -1,GreaterEq,>=);\r
+  $PvalveReal = (((tmp4 || tmp5) || tmp6)?$Pr:$P$PRE$PvalveReal); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_5(DATA *data) {\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:30:2-30:28]*/\r
+  $P$DER$PstockReal = $PvalveReal; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+static void functionODE_system0(DATA *data,int omc_thread_number)\r
+{\r
+  eqFunction_0(data);\r
+  eqFunction_1(data);\r
+  eqFunction_2(data);\r
+  eqFunction_3(data);\r
+  eqFunction_4(data);\r
+  eqFunction_5(data);\r
+}\r
+static void (*functionODE_systems[1])(DATA *, int) = {\r
+  functionODE_system0\r
+};\r
+\r
+void function_initMemoryState()\r
+{\r
+  push_memory_states(1);\r
+}\r
+\r
+int functionODE(DATA *data)\r
+{\r
+  int id,th_id;\r
+  state mem_state; /* We need to have separate memory pools for separate systems... */\r
+  mem_state = get_memory_state();\r
+  for (id=0; id<1; id++) {\r
+    th_id = omp_get_thread_num();\r
+    functionODE_systems[id](data,th_id);\r
+  }\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+#include <simulation_inline_solver.h>\r
+const char *_omc_force_solver=_OMC_FORCE_SOLVER;\r
+const int inline_work_states_ndims=_OMC_SOLVER_WORK_STATES_NDIMS;\r
+int functionODE_inline(DATA* data, double stepSize)\r
+{\r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_6(DATA *data) {\r
+  modelica_boolean tmp10;\r
+  modelica_boolean tmp11;\r
+  modelica_boolean tmp12;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:22:2-22:84]*/\r
+  tmp10 = initial();\r
+  RELATIONTOZC(tmp11, $Pr, 0.0, -1,Less,<);\r
+  RELATIONTOZC(tmp12, $Pr, 0.0, -1,GreaterEq,>=);\r
+  $PcontinuousReal = (((tmp10 || tmp11) || tmp12)?$Pr:$P$PRE$PcontinuousReal); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+/* for continuous time variables */\r
+int functionAlgebraics(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  eqFunction_6(data);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_7(DATA *data) {\r
+  modelica_boolean tmp13;\r
+  modelica_boolean tmp14;\r
+  modelica_boolean tmp15;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:26:2-26:74]*/\r
+  tmp13 = initial();\r
+  SAVEZEROCROSS(tmp14, $Pr, 0.0, -1,Less,<);\r
+  SAVEZEROCROSS(tmp15, $Pr, 0.0, -1,GreaterEq,>=);\r
+  $PvalveReal = (((tmp13 || tmp14) || tmp15)?$Pr:$P$PRE$PvalveReal); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_8(DATA *data) {\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:30:2-30:28]*/\r
+  $P$DER$PstockReal = $PvalveReal; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_9(DATA *data) {\r
+  modelica_boolean tmp16;\r
+  modelica_boolean tmp17;\r
+  modelica_boolean tmp18;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:25:2-25:80]*/\r
+  tmp16 = initial();\r
+  SAVEZEROCROSS(tmp17, (modelica_integer)$Pi, (modelica_integer) 0, -1,Less,<);\r
+  SAVEZEROCROSS(tmp18, (modelica_integer)$Pi, (modelica_integer) 0, -1,GreaterEq,>=);\r
+  $PvalveInteger = (((tmp16 || tmp17) || tmp18)?((modelica_real)(modelica_integer)$Pi):$P$PRE$PvalveInteger); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_10(DATA *data) {\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:29:2-29:34]*/\r
+  $P$DER$PstockInteger = $PvalveInteger; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_11(DATA *data) {\r
+  modelica_boolean tmp19;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:24:2-24:93]*/\r
+  tmp19 = initial();\r
+  $PvalveBoolean = (((tmp19 || $Pb) || (!$Pb))?($Pb?1.0:-1.0):$P$PRE$PvalveBoolean); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_12(DATA *data) {\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:28:2-28:34]*/\r
+  $P$DER$PstockBoolean = $PvalveBoolean; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_13(DATA *data) {\r
+  modelica_boolean tmp20;\r
+  modelica_boolean tmp21;\r
+  modelica_boolean tmp22;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:22:2-22:84]*/\r
+  tmp20 = initial();\r
+  SAVEZEROCROSS(tmp21, $Pr, 0.0, -1,Less,<);\r
+  SAVEZEROCROSS(tmp22, $Pr, 0.0, -1,GreaterEq,>=);\r
+  $PcontinuousReal = (((tmp20 || tmp21) || tmp22)?$Pr:$P$PRE$PcontinuousReal); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_14(DATA *data) {\r
+  modelica_boolean tmp23;\r
+  modelica_boolean tmp24;\r
+  modelica_boolean tmp25;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:21:2-21:86]*/\r
+  tmp23 = initial();\r
+  SAVEZEROCROSS(tmp24, (modelica_integer)$Pi, (modelica_integer) 0, -1,Less,<);\r
+  SAVEZEROCROSS(tmp25, (modelica_integer)$Pi, (modelica_integer) 0, -1,GreaterEq,>=);\r
+  $PdiscreteInteger = (((tmp23 || tmp24) || tmp25)?(modelica_integer)$Pi:$P$PRE$PdiscreteInteger); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_15(DATA *data) {\r
+  modelica_boolean tmp26;\r
+  /*#modelicaLine [FMUAllTypesOfVariablesTest.mo:20:2-20:81]*/\r
+  tmp26 = initial();\r
+  $PdiscreteBoolean = (((tmp26 || $Pb) || (!$Pb))?$Pb:$P$PRE$PdiscreteBoolean); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+int functionDAE(DATA *data, int *needToIterate)\r
+{\r
+  state mem_state;\r
+  *needToIterate = 0;\r
+  \r
+  mem_state = get_memory_state();\r
+  eqFunction_7(data);\r
+  eqFunction_8(data);\r
+  eqFunction_9(data);\r
+  eqFunction_10(data);\r
+  eqFunction_11(data);\r
+  eqFunction_12(data);\r
+  eqFunction_13(data);\r
+  eqFunction_14(data);\r
+  eqFunction_15(data);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_onlyZeroCrossings(DATA *data, double *gout,double *t)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int checkForDiscreteChanges(DATA *data)\r
+{\r
+  int needToIterate = 0;\r
+\r
+  if ($PdiscreteBoolean != $P$PRE$PdiscreteBoolean) { DEBUG_INFO2(LOG_EVENTS,"Discrete Var discreteBoolean : %d to %d", $P$PRE$PdiscreteBoolean, $PdiscreteBoolean);  needToIterate=1; }\r
+  if ($PdiscreteInteger != $P$PRE$PdiscreteInteger) { DEBUG_INFO2(LOG_EVENTS,"Discrete Var discreteInteger : %ld to %ld", $P$PRE$PdiscreteInteger, $PdiscreteInteger);  needToIterate=1; }\r
+  \r
+  return needToIterate;\r
+}\r
+\r
+/* function to check assert after a step is done */\r
+int checkForAsserts(DATA *data)\r
+{\r
+\r
+  \r
+  return 0;\r
+}\r
+\r
+ int initialAnalyticJacobianA(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianB(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianC(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianD(DATA* data){\r
+    return 1;\r
+ }\r
+ int functionJacA(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacB(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacC(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacD(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+const char *linear_model_frame =\r
+  "model linear_FMUAllTypesOfVariablesTestModel\n  parameter Integer n = 3; // states \n  parameter Integer k = 0; // top-level inputs \n  parameter Integer l = 0; // top-level outputs \n"\r
+  "  parameter Real x0[3] = {%s};\n"\r
+  "  parameter Real u0[0] = {%s};\n"\r
+  "  parameter Real A[3,3] = [%s];\n"\r
+  "  parameter Real B[3,0] = zeros(3,0);%s\n"\r
+  "  parameter Real C[0,3] = zeros(0,3);%s\n"\r
+  "  parameter Real D[0,0] = zeros(0,0);%s\n"\r
+  "  Real x[3](start=x0);\n"\r
+  "  input Real u[0];\n"\r
+  "  output Real y[0];\n"\r
+  "\n  Real x_PstockBoolean = x[1];\n  Real x_PstockInteger = x[2];\n  Real x_PstockReal = x[3];\n      \n"\r
+  "equation\n  der(x) = A * x + B * u;\n  y = C * x + D * u;\nend linear_FMUAllTypesOfVariablesTestModel;\n"\r
+;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+/* forward the main in the simulation runtime */\r
+extern int _main_SimulationRuntime(int argc, char**argv, DATA *data);\r
+\r
+/* call the simulation runtime main from our main! */\r
+int main(int argc, char**argv)\r
+{\r
+  DATA data;\r
+  setupDataStruc(&data);\r
+  return _main_SimulationRuntime(argc, argv, &data);\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.dll b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.dll
new file mode 100644 (file)
index 0000000..09daf82
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.dll differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.fmu b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.fmu
new file mode 100644 (file)
index 0000000..330c53a
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.fmu differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.lib b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.lib
new file mode 100644 (file)
index 0000000..293de43
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel.lib differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_FMU.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_FMU.c
new file mode 100644 (file)
index 0000000..0199232
--- /dev/null
@@ -0,0 +1,202 @@
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER FMUAllTypesOfVariablesTestModel\r
+#define MODEL_GUID "{e473ffda-4cfa-4ca5-b49b-0c9abe90687b}"\r
+\r
+// include fmu header files, typedefs and macros\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "omc_error.h"\r
+#include "fmiModelTypes.h"\r
+#include "fmiModelFunctions.h"\r
+#include "FMUAllTypesOfVariablesTestModel_functions.h"\r
+#include "initialization.h"\r
+#include "events.h"\r
+#include "fmu_model_interface.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+void setStartValues(ModelInstance *comp);\r
+void setDefaultStartValues(ModelInstance *comp);\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo);\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value);\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value);\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value);\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value);\r
+\r
+// define model size\r
+#define NUMBER_OF_STATES 3\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+#define NUMBER_OF_REALS 12\r
+#define NUMBER_OF_INTEGERS 2\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_BOOLEANS 2\r
+#define NUMBER_OF_EXTERNALFUNCTIONS 0\r
+\r
+// define variable data for model\r
+#define $PstockBoolean_ 0 \r
+#define $PstockInteger_ 1 \r
+#define $PstockReal_ 2 \r
+#define $P$DER$PstockBoolean_ 3 \r
+#define $P$DER$PstockInteger_ 4 \r
+#define $P$DER$PstockReal_ 5 \r
+#define $PcontinuousReal_ 6 \r
+#define $PvalveBoolean_ 7 \r
+#define $PvalveInteger_ 8 \r
+#define $PvalveReal_ 9 \r
+#define $Pr_ 10 \r
+#define time_ 11 \r
+#define $PdiscreteInteger_ 0 \r
+#define $Pi_ 1 \r
+#define $PdiscreteBoolean_ 0 \r
+#define $Pb_ 1 \r
+\r
+\r
+// define initial state vector as vector of value references\r
+#define STATES { $PstockBoolean_, $PstockInteger_, $PstockReal_ }\r
+#define STATESDERIVATIVES { $P$DER$PstockBoolean_, $P$DER$PstockInteger_, $P$DER$PstockReal_ }\r
+\r
+\r
+// implementation of the Model Exchange functions\r
+#include "fmu_model_interface.c"\r
+\r
+// Set values for all variables that define a start value\r
+void setDefaultStartValues(ModelInstance *comp) {\r
+\r
+comp->fmuData->modelData.realVarsData[0].attribute.start = 0.0;\r
+comp->fmuData->modelData.realVarsData[1].attribute.start = 0.0;\r
+comp->fmuData->modelData.realVarsData[2].attribute.start = 0.0;\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = 1.0;\r
+comp->fmuData->modelData.realParameterData[1].attribute.start = 0.0;\r
+comp->fmuData->modelData.integerParameterData[0].attribute.start = 1;\r
+comp->fmuData->modelData.booleanParameterData[0].attribute.start = 1;\r
+}\r
+// Set values for all variables that define a start value\r
+void setStartValues(ModelInstance *comp) {\r
+\r
+  comp->fmuData->modelData.realVarsData[0].attribute.start =  comp->fmuData->localData[0]->realVars[0];\r
+  comp->fmuData->modelData.realVarsData[1].attribute.start =  comp->fmuData->localData[0]->realVars[1];\r
+  comp->fmuData->modelData.realVarsData[2].attribute.start =  comp->fmuData->localData[0]->realVars[2];\r
+  comp->fmuData->modelData.realVarsData[3].attribute.start =  comp->fmuData->localData[0]->realVars[3];\r
+  comp->fmuData->modelData.realVarsData[4].attribute.start =  comp->fmuData->localData[0]->realVars[4];\r
+  comp->fmuData->modelData.realVarsData[5].attribute.start =  comp->fmuData->localData[0]->realVars[5];\r
+  comp->fmuData->modelData.realVarsData[6].attribute.start =  comp->fmuData->localData[0]->realVars[6];\r
+  comp->fmuData->modelData.realVarsData[7].attribute.start =  comp->fmuData->localData[0]->realVars[7];\r
+  comp->fmuData->modelData.realVarsData[8].attribute.start =  comp->fmuData->localData[0]->realVars[8];\r
+  comp->fmuData->modelData.realVarsData[9].attribute.start =  comp->fmuData->localData[0]->realVars[9];\r
+  comp->fmuData->modelData.integerVarsData[0].attribute.start =  comp->fmuData->localData[0]->integerVars[0];\r
+  comp->fmuData->modelData.booleanVarsData[0].attribute.start =  comp->fmuData->localData[0]->booleanVars[0];\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = comp->fmuData->simulationInfo.realParameter[0];\r
+comp->fmuData->modelData.realParameterData[1].attribute.start = comp->fmuData->simulationInfo.realParameter[1];\r
+comp->fmuData->modelData.integerParameterData[0].attribute.start = comp->fmuData->simulationInfo.integerParameter[0];\r
+comp->fmuData->modelData.booleanParameterData[0].attribute.start = comp->fmuData->simulationInfo.booleanParameter[0];\r
+}\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $PstockBoolean_ : return comp->fmuData->localData[0]->realVars[0]; break;\r
+      case $PstockInteger_ : return comp->fmuData->localData[0]->realVars[1]; break;\r
+      case $PstockReal_ : return comp->fmuData->localData[0]->realVars[2]; break;\r
+      case $P$DER$PstockBoolean_ : return comp->fmuData->localData[0]->realVars[3]; break;\r
+      case $P$DER$PstockInteger_ : return comp->fmuData->localData[0]->realVars[4]; break;\r
+      case $P$DER$PstockReal_ : return comp->fmuData->localData[0]->realVars[5]; break;\r
+      case $PcontinuousReal_ : return comp->fmuData->localData[0]->realVars[6]; break;\r
+      case $PvalveBoolean_ : return comp->fmuData->localData[0]->realVars[7]; break;\r
+      case $PvalveInteger_ : return comp->fmuData->localData[0]->realVars[8]; break;\r
+      case $PvalveReal_ : return comp->fmuData->localData[0]->realVars[9]; break;\r
+      case $Pr_ : return comp->fmuData->simulationInfo.realParameter[0]; break;\r
+      case time_ : return comp->fmuData->simulationInfo.realParameter[1]; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+}\r
+\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value) {\r
+  switch (vr) {\r
+      case $PstockBoolean_ : comp->fmuData->localData[0]->realVars[0]=value; break;\r
+      case $PstockInteger_ : comp->fmuData->localData[0]->realVars[1]=value; break;\r
+      case $PstockReal_ : comp->fmuData->localData[0]->realVars[2]=value; break;\r
+      case $P$DER$PstockBoolean_ : comp->fmuData->localData[0]->realVars[3]=value; break;\r
+      case $P$DER$PstockInteger_ : comp->fmuData->localData[0]->realVars[4]=value; break;\r
+      case $P$DER$PstockReal_ : comp->fmuData->localData[0]->realVars[5]=value; break;\r
+      case $PcontinuousReal_ : comp->fmuData->localData[0]->realVars[6]=value; break;\r
+      case $PvalveBoolean_ : comp->fmuData->localData[0]->realVars[7]=value; break;\r
+      case $PvalveInteger_ : comp->fmuData->localData[0]->realVars[8]=value; break;\r
+      case $PvalveReal_ : comp->fmuData->localData[0]->realVars[9]=value; break;\r
+      case $Pr_ : comp->fmuData->simulationInfo.realParameter[0]=value; break;\r
+      case time_ : comp->fmuData->simulationInfo.realParameter[1]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $PdiscreteInteger_ : return comp->fmuData->localData[0]->integerVars[0]; break;\r
+      case $Pi_ : return comp->fmuData->simulationInfo.integerParameter[0]; break;\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value) {\r
+  switch (vr) {\r
+      case $PdiscreteInteger_ : comp->fmuData->localData[0]->integerVars[0]=value; break;\r
+      case $Pi_ : comp->fmuData->simulationInfo.integerParameter[0]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $PdiscreteBoolean_ : return comp->fmuData->localData[0]->booleanVars[0]; break;\r
+      case $Pb_ : return comp->fmuData->simulationInfo.booleanParameter[0]; break;\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value) {\r
+  switch (vr) {\r
+      case $PdiscreteBoolean_ : comp->fmuData->localData[0]->booleanVars[0]=value; break;\r
+      case $Pb_ : comp->fmuData->simulationInfo.booleanParameter[0]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value){\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_functions.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_functions.c
new file mode 100644 (file)
index 0000000..005d469
--- /dev/null
@@ -0,0 +1,16 @@
+#include "FMUAllTypesOfVariablesTestModel_functions.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#define _OMC_LIT0_data "'p"\r
+static const size_t _OMC_LIT0_strlen = 2;\r
+static const char _OMC_LIT0[3] = _OMC_LIT0_data;\r
+#define _OMC_LIT1_data "'p/s"\r
+static const size_t _OMC_LIT1_strlen = 4;\r
+static const char _OMC_LIT1[5] = _OMC_LIT1_data;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_functions.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_functions.h
new file mode 100644 (file)
index 0000000..cf5bf6b
--- /dev/null
@@ -0,0 +1,17 @@
+#ifndef FMUAllTypesOfVariablesTestModel__H\r
+#define FMUAllTypesOfVariablesTestModel__H\r
+#define omp_get_thread_num() 0\r
+#include "modelica.h"\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <errno.h>\r
+#include "simulation_runtime.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_records.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/FMUAllTypesOfVariablesTestModel_records.c
new file mode 100644 (file)
index 0000000..f4e92f3
--- /dev/null
@@ -0,0 +1,3 @@
+/* Additional record code for FMUAllTypesOfVariablesTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#include "meta_modelica.h"\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/_FMUAllTypesOfVariablesTestModel.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/_FMUAllTypesOfVariablesTestModel.h
new file mode 100644 (file)
index 0000000..7cbac25
--- /dev/null
@@ -0,0 +1,88 @@
+/* Simulation code for FMUAllTypesOfVariablesTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#define time data->localData[0]->timeValue\r
+\r
+/* States */\r
+#define _$PstockBoolean(i) data->localData[i]->realVars[0]\r
+#define $PstockBoolean _$PstockBoolean(0)\r
+#define $P$PRE$PstockBoolean data->simulationInfo.realVarsPre[0]\r
+#define $P$START$PstockBoolean data->modelData.realVarsData[0].attribute.start\r
+#define $PstockBoolean__varInfo data->modelData.realVarsData[0].info\r
+#define _$PstockInteger(i) data->localData[i]->realVars[1]\r
+#define $PstockInteger _$PstockInteger(0)\r
+#define $P$PRE$PstockInteger data->simulationInfo.realVarsPre[1]\r
+#define $P$START$PstockInteger data->modelData.realVarsData[1].attribute.start\r
+#define $PstockInteger__varInfo data->modelData.realVarsData[1].info\r
+#define _$PstockReal(i) data->localData[i]->realVars[2]\r
+#define $PstockReal _$PstockReal(0)\r
+#define $P$PRE$PstockReal data->simulationInfo.realVarsPre[2]\r
+#define $P$START$PstockReal data->modelData.realVarsData[2].attribute.start\r
+#define $PstockReal__varInfo data->modelData.realVarsData[2].info\r
+/* StatesDerivatives */\r
+#define _$P$DER$PstockBoolean(i) data->localData[i]->realVars[3]\r
+#define $P$DER$PstockBoolean _$P$DER$PstockBoolean(0)\r
+#define $P$PRE$P$DER$PstockBoolean data->simulationInfo.realVarsPre[3]\r
+#define $P$START$P$DER$PstockBoolean data->modelData.realVarsData[3].attribute.start\r
+#define $P$DER$PstockBoolean__varInfo data->modelData.realVarsData[3].info\r
+#define _$P$DER$PstockInteger(i) data->localData[i]->realVars[4]\r
+#define $P$DER$PstockInteger _$P$DER$PstockInteger(0)\r
+#define $P$PRE$P$DER$PstockInteger data->simulationInfo.realVarsPre[4]\r
+#define $P$START$P$DER$PstockInteger data->modelData.realVarsData[4].attribute.start\r
+#define $P$DER$PstockInteger__varInfo data->modelData.realVarsData[4].info\r
+#define _$P$DER$PstockReal(i) data->localData[i]->realVars[5]\r
+#define $P$DER$PstockReal _$P$DER$PstockReal(0)\r
+#define $P$PRE$P$DER$PstockReal data->simulationInfo.realVarsPre[5]\r
+#define $P$START$P$DER$PstockReal data->modelData.realVarsData[5].attribute.start\r
+#define $P$DER$PstockReal__varInfo data->modelData.realVarsData[5].info\r
+/* Algebraic Vars */\r
+#define _$PcontinuousReal(i) data->localData[i]->realVars[6]\r
+#define $PcontinuousReal _$PcontinuousReal(0)\r
+#define $P$PRE$PcontinuousReal data->simulationInfo.realVarsPre[6]\r
+#define $P$START$PcontinuousReal data->modelData.realVarsData[6].attribute.start\r
+#define $PcontinuousReal__varInfo data->modelData.realVarsData[6].info\r
+#define _$PvalveBoolean(i) data->localData[i]->realVars[7]\r
+#define $PvalveBoolean _$PvalveBoolean(0)\r
+#define $P$PRE$PvalveBoolean data->simulationInfo.realVarsPre[7]\r
+#define $P$START$PvalveBoolean data->modelData.realVarsData[7].attribute.start\r
+#define $PvalveBoolean__varInfo data->modelData.realVarsData[7].info\r
+#define _$PvalveInteger(i) data->localData[i]->realVars[8]\r
+#define $PvalveInteger _$PvalveInteger(0)\r
+#define $P$PRE$PvalveInteger data->simulationInfo.realVarsPre[8]\r
+#define $P$START$PvalveInteger data->modelData.realVarsData[8].attribute.start\r
+#define $PvalveInteger__varInfo data->modelData.realVarsData[8].info\r
+#define _$PvalveReal(i) data->localData[i]->realVars[9]\r
+#define $PvalveReal _$PvalveReal(0)\r
+#define $P$PRE$PvalveReal data->simulationInfo.realVarsPre[9]\r
+#define $P$START$PvalveReal data->modelData.realVarsData[9].attribute.start\r
+#define $PvalveReal__varInfo data->modelData.realVarsData[9].info\r
+/* Algebraic Parameter */\r
+#define $Pr data->simulationInfo.realParameter[0]\r
+#define $P$START$Pr data->modelData.realParameterData[0].attribute.start\r
+#define $Pr__varInfo data->modelData.realParameterData[0].info\r
+#define time data->simulationInfo.realParameter[1]\r
+#define $P$STARTtime data->modelData.realParameterData[1].attribute.start\r
+#define time__varInfo data->modelData.realParameterData[1].info\r
+/* External Objects */\r
+/* Algebraic Integer Vars */\r
+#define _$PdiscreteInteger(i) data->localData[i]->integerVars[0]\r
+#define $PdiscreteInteger _$PdiscreteInteger(0)\r
+#define $P$PRE$PdiscreteInteger data->simulationInfo.integerVarsPre[0]\r
+#define $P$START$PdiscreteInteger data->modelData.integerVarsData[0].attribute.start\r
+#define $PdiscreteInteger__varInfo data->modelData.integerVarsData[0].info\r
+/* Algebraic Integer Parameter */\r
+#define $Pi data->simulationInfo.integerParameter[0]\r
+#define $P$START$Pi data->modelData.integerParameterData[0].attribute.start\r
+#define $Pi__varInfo data->modelData.integerParameterData[0].info\r
+/* Algebraic Boolean Vars */\r
+#define _$PdiscreteBoolean(i) data->localData[i]->booleanVars[0]\r
+#define $PdiscreteBoolean _$PdiscreteBoolean(0)\r
+#define $P$PRE$PdiscreteBoolean data->simulationInfo.booleanVarsPre[0]\r
+#define $P$START$PdiscreteBoolean data->modelData.booleanVarsData[0].attribute.start\r
+#define $PdiscreteBoolean__varInfo data->modelData.booleanVarsData[0].info\r
+/* Algebraic Boolean Parameters */\r
+#define $Pb data->simulationInfo.booleanParameter[0]\r
+#define $P$START$Pb data->modelData.booleanParameterData[0].attribute.start\r
+#define $Pb__varInfo data->modelData.booleanParameterData[0].info\r
+/* Algebraic String Variables */\r
+/* Algebraic String Parameter */\r
+/* Jacobian Variables */\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/modelDescription.xml b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUAllTypesOfVariablesTest/modelDescription.xml
new file mode 100644 (file)
index 0000000..8dd28af
--- /dev/null
@@ -0,0 +1,143 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="FMUAllTypesOfVariablesTestModel"\r
+  modelIdentifier="FMUAllTypesOfVariablesTestModel"\r
+  guid="{e473ffda-4cfa-4ca5-b49b-0c9abe90687b}"\r
+  generationTool="OpenModelica Compiler 1.8.1+ (r11690)"\r
+  generationDateAndTime="2012-05-10T14:47:53Z"\r
+  variableNamingConvention="structured"\r
+  numberOfContinuousStates="3"\r
+  numberOfEventIndicators="0">\r
+  <ModelVariables>\r
+  <ScalarVariable\r
+    name="stockBoolean"\r
+    valueReference="0"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="stockInteger"\r
+    valueReference="1"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="stockReal"\r
+    valueReference="2"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stockBoolean)"\r
+    valueReference="3"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stockInteger)"\r
+    valueReference="4"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stockReal)"\r
+    valueReference="5"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="continuousReal"\r
+    valueReference="6"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valveBoolean"\r
+    valueReference="7"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valveInteger"\r
+    valueReference="8"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valveReal"\r
+    valueReference="9"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="r"\r
+    valueReference="10"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="1.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="time"\r
+    valueReference="11"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="discreteInteger"\r
+    valueReference="0"\r
+    variability="discrete"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Integer/>\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="i"\r
+    valueReference="1"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Integer/>\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="discreteBoolean"\r
+    valueReference="0"\r
+    variability="discrete"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Boolean/>\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="b"\r
+    valueReference="1"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Boolean/>\r
+  </ScalarVariable>\r
+  </ModelVariables>\r
+</fmiModelDescription>\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTest.mo b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTest.mo
new file mode 100644 (file)
index 0000000..b988538
--- /dev/null
@@ -0,0 +1,9 @@
+model FMUBooleanTestModel\r
+       parameter Boolean b = true;\r
+       Real valve;\r
+       Real stock(start=0.0,fixed=true);\r
+       parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+equation\r
+       valve = if initial() or b or not b then (if b then 1 else -1) else pre(valve);\r
+       der(stock) = valve;\r
+end FMUBooleanTestModel;
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTest.mos b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTest.mos
new file mode 100644 (file)
index 0000000..cd93a4b
--- /dev/null
@@ -0,0 +1,2 @@
+loadFile("FMUBooleanTest.mo");\r
+translateModelFMU(FMUBooleanTestModel)
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.c
new file mode 100644 (file)
index 0000000..0825610
--- /dev/null
@@ -0,0 +1,356 @@
+/* Simulation code for FMUBooleanTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "simulation_runtime.h"\r
+#include "omc_error.h"\r
+\r
+#include <assert.h>\r
+#include <string.h>\r
+\r
+#include "FMUBooleanTestModel_functions.h"\r
+\r
+#include "_FMUBooleanTestModel.h"\r
+#include "FMUBooleanTestModel_functions.c"\r
+/* dummy VARINFO and FILEINFO */\r
+const FILE_INFO dummyFILE_INFO = {"",-1,-1,-1,-1,1};\r
+const VAR_INFO dummyVAR_INFO = {-1,"","",(FILE_INFO){"",-1,-1,-1,-1,1}};\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef _OMC_MEASURE_TIME\r
+int measure_time_flag = 1;\r
+#else\r
+int measure_time_flag = 0;\r
+#endif\r
+\r
+void setupDataStruc(DATA *data)\r
+{\r
+  ASSERT(data,"Error while initialize Data");\r
+  data->modelData.modelName = "FMUBooleanTestModel";\r
+  data->modelData.modelFilePrefix = "FMUBooleanTestModel";\r
+  data->modelData.modelDir = "";\r
+  data->modelData.modelGUID = "{3286e2d9-75aa-4917-9a7e-69e4959910a6}";\r
+  \r
+  data->modelData.nStates = 1;\r
+  data->modelData.nVariablesReal = 2*1+1;\r
+  data->modelData.nVariablesInteger = 0;\r
+  data->modelData.nVariablesBoolean = 0;\r
+  data->modelData.nVariablesString = 0;\r
+  data->modelData.nParametersReal = 1;\r
+  data->modelData.nParametersInteger = 0;\r
+  data->modelData.nParametersBoolean = 1;\r
+  data->modelData.nParametersString = 0;\r
+  data->modelData.nInputVars = 0;\r
+  data->modelData.nOutputVars = 0;\r
+  data->modelData.nJacobians = 4;\r
+  data->modelData.nHelpVars = 0;\r
+  \r
+  data->modelData.nAliasReal = 0;\r
+  data->modelData.nAliasInteger = 0;\r
+  data->modelData.nAliasBoolean = 0;\r
+  data->modelData.nAliasString = 0;\r
+  \r
+  data->modelData.nZeroCrossings = 0;\r
+  data->modelData.nSamples = 0;\r
+  data->modelData.nInitEquations = 0;\r
+  data->modelData.nResiduals = 1;\r
+  data->modelData.nExtObjs = 0;\r
+  data->modelData.nFunctions = 0;\r
+  data->modelData.nEquations = 4;\r
+  \r
+  data->modelData.nDelayExpressions = 0;\r
+  \r
+}\r
+\r
+void setupDataStruc2(DATA *data)\r
+{\r
+  const struct FUNCTION_INFO funcInfo[1] = {{-1,"",omc_dummyFileInfo}};\r
+  memcpy(data->modelData.functionNames, &funcInfo, data->modelData.nFunctions*sizeof(FUNCTION_INFO));\r
+  \r
+  const VAR_INFO** equationInfo_cref1 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref1[0] = &$Pvalve__varInfo;\r
+  const VAR_INFO** equationInfo_cref3 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref3[0] = &$P$DER$Pstock__varInfo;\r
+  const struct EQUATION_INFO equationInfo[4] = {\r
+    {1003,"SES_ALGORITHM 0", 0, NULL},\r
+    {1004,"SES_SIMPLE_ASSIGN 1",1,equationInfo_cref1},\r
+    {1005,"SES_ALGORITHM 2", 0, NULL},\r
+    {1006,"SES_SIMPLE_ASSIGN 3",1,equationInfo_cref3}\r
+  };\r
+  const int n_omc_equationInfo_reverse_prof_index = 0;\r
+  const int omc_equationInfo_reverse_prof_index[] = {\r
+    \r
+  };\r
+  memcpy(data->modelData.equationInfo, &equationInfo, data->modelData.nEquations*sizeof(EQUATION_INFO));\r
+  \r
+  data->modelData.nProfileBlocks = n_omc_equationInfo_reverse_prof_index;\r
+  data->modelData.equationInfo_reverse_prof_index = (int*) malloc(data->modelData.nProfileBlocks*sizeof(int));\r
+  memcpy(data->modelData.equationInfo_reverse_prof_index, omc_equationInfo_reverse_prof_index, data->modelData.nProfileBlocks*sizeof(int));\r
+}\r
+\r
+/* Has to be performed after _init.xml file has been read */\r
+void callExternalObjectConstructors(DATA *data)\r
+{\r
+  state mem_state;\r
+  mem_state = get_memory_state();\r
+  /* data->simulationInfo.extObjs = NULL; */\r
+}\r
+\r
+void callExternalObjectDestructors(DATA *data)\r
+{\r
+  if (data->simulationInfo.extObjs) {\r
+    free(data->simulationInfo.extObjs);\r
+    data->simulationInfo.extObjs = 0;\r
+  }\r
+}\r
+\r
+\r
+int input_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+int output_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* Initializes the raw time events of the simulation using the now\r
+   calcualted parameters. */\r
+void function_sampleInit(DATA *data)\r
+{\r
+}\r
+\r
+int function_updateSample(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_storeDelayed(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundStartValues(DATA *data)\r
+{\r
+\r
+  \r
+  DEBUG_INFO(LOG_INIT, "updating start-values:");\r
+  \r
+  return 0;\r
+}\r
+\r
+int initial_residual(DATA *data, double $P$_lambda, double* initialResiduals)\r
+{\r
+  int i = 0;\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  DEBUG_INFO(LOG_RES_INIT, "updating initial_residuals:");\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($Pstock - $P$START$Pstock));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stock - $_start(stock)) = %f", i, initialResiduals[i-1]);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundParameters(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_0(DATA *data) {\r
+  modelica_boolean tmp0;\r
+  /*#modelicaLine [FMUBooleanTest.mo:7:2-7:79]*/\r
+  tmp0 = initial();\r
+  $Pvalve = (((tmp0 || $Pb) || (!$Pb))?($Pb?1.0:-1.0):$P$PRE$Pvalve); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_1(DATA *data) {\r
+  /*#modelicaLine [FMUBooleanTest.mo:8:2-8:20]*/\r
+  $P$DER$Pstock = $Pvalve; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+static void functionODE_system0(DATA *data,int omc_thread_number)\r
+{\r
+  eqFunction_0(data);\r
+  eqFunction_1(data);\r
+}\r
+static void (*functionODE_systems[1])(DATA *, int) = {\r
+  functionODE_system0\r
+};\r
+\r
+void function_initMemoryState()\r
+{\r
+  push_memory_states(1);\r
+}\r
+\r
+int functionODE(DATA *data)\r
+{\r
+  int id,th_id;\r
+  state mem_state; /* We need to have separate memory pools for separate systems... */\r
+  mem_state = get_memory_state();\r
+  for (id=0; id<1; id++) {\r
+    th_id = omp_get_thread_num();\r
+    functionODE_systems[id](data,th_id);\r
+  }\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+#include <simulation_inline_solver.h>\r
+const char *_omc_force_solver=_OMC_FORCE_SOLVER;\r
+const int inline_work_states_ndims=_OMC_SOLVER_WORK_STATES_NDIMS;\r
+int functionODE_inline(DATA* data, double stepSize)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* for continuous time variables */\r
+int functionAlgebraics(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_2(DATA *data) {\r
+  modelica_boolean tmp2;\r
+  /*#modelicaLine [FMUBooleanTest.mo:7:2-7:79]*/\r
+  tmp2 = initial();\r
+  $Pvalve = (((tmp2 || $Pb) || (!$Pb))?($Pb?1.0:-1.0):$P$PRE$Pvalve); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_3(DATA *data) {\r
+  /*#modelicaLine [FMUBooleanTest.mo:8:2-8:20]*/\r
+  $P$DER$Pstock = $Pvalve; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+int functionDAE(DATA *data, int *needToIterate)\r
+{\r
+  state mem_state;\r
+  *needToIterate = 0;\r
+  \r
+  mem_state = get_memory_state();\r
+  eqFunction_2(data);\r
+  eqFunction_3(data);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_onlyZeroCrossings(DATA *data, double *gout,double *t)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int checkForDiscreteChanges(DATA *data)\r
+{\r
+  int needToIterate = 0;\r
+\r
+  \r
+  return needToIterate;\r
+}\r
+\r
+/* function to check assert after a step is done */\r
+int checkForAsserts(DATA *data)\r
+{\r
+\r
+  \r
+  return 0;\r
+}\r
+\r
+ int initialAnalyticJacobianA(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianB(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianC(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianD(DATA* data){\r
+    return 1;\r
+ }\r
+ int functionJacA(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacB(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacC(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacD(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+const char *linear_model_frame =\r
+  "model linear_FMUBooleanTestModel\n  parameter Integer n = 1; // states \n  parameter Integer k = 0; // top-level inputs \n  parameter Integer l = 0; // top-level outputs \n"\r
+  "  parameter Real x0[1] = {%s};\n"\r
+  "  parameter Real u0[0] = {%s};\n"\r
+  "  parameter Real A[1,1] = [%s];\n"\r
+  "  parameter Real B[1,0] = zeros(1,0);%s\n"\r
+  "  parameter Real C[0,1] = zeros(0,1);%s\n"\r
+  "  parameter Real D[0,0] = zeros(0,0);%s\n"\r
+  "  Real x[1](start=x0);\n"\r
+  "  input Real u[0];\n"\r
+  "  output Real y[0];\n"\r
+  "\n  Real x_Pstock = x[1];\n      \n"\r
+  "equation\n  der(x) = A * x + B * u;\n  y = C * x + D * u;\nend linear_FMUBooleanTestModel;\n"\r
+;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+/* forward the main in the simulation runtime */\r
+extern int _main_SimulationRuntime(int argc, char**argv, DATA *data);\r
+\r
+/* call the simulation runtime main from our main! */\r
+int main(int argc, char**argv)\r
+{\r
+  DATA data;\r
+  setupDataStruc(&data);\r
+  return _main_SimulationRuntime(argc, argv, &data);\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.dll b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.dll
new file mode 100644 (file)
index 0000000..1376771
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.dll differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.fmu b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.fmu
new file mode 100644 (file)
index 0000000..4da6ff8
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.fmu differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.lib b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.lib
new file mode 100644 (file)
index 0000000..734ec89
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel.lib differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_FMU.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_FMU.c
new file mode 100644 (file)
index 0000000..0cc1a91
--- /dev/null
@@ -0,0 +1,154 @@
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER FMUBooleanTestModel\r
+#define MODEL_GUID "{3286e2d9-75aa-4917-9a7e-69e4959910a6}"\r
+\r
+// include fmu header files, typedefs and macros\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "omc_error.h"\r
+#include "fmiModelTypes.h"\r
+#include "fmiModelFunctions.h"\r
+#include "FMUBooleanTestModel_functions.h"\r
+#include "initialization.h"\r
+#include "events.h"\r
+#include "fmu_model_interface.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+void setStartValues(ModelInstance *comp);\r
+void setDefaultStartValues(ModelInstance *comp);\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo);\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value);\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value);\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value);\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value);\r
+\r
+// define model size\r
+#define NUMBER_OF_STATES 1\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+#define NUMBER_OF_REALS 4\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_BOOLEANS 1\r
+#define NUMBER_OF_EXTERNALFUNCTIONS 0\r
+\r
+// define variable data for model\r
+#define $Pstock_ 0 \r
+#define $P$DER$Pstock_ 1 \r
+#define $Pvalve_ 2 \r
+#define time_ 3 \r
+#define $Pb_ 0 \r
+\r
+\r
+// define initial state vector as vector of value references\r
+#define STATES { $Pstock_ }\r
+#define STATESDERIVATIVES { $P$DER$Pstock_ }\r
+\r
+\r
+// implementation of the Model Exchange functions\r
+#include "fmu_model_interface.c"\r
+\r
+// Set values for all variables that define a start value\r
+void setDefaultStartValues(ModelInstance *comp) {\r
+\r
+comp->fmuData->modelData.realVarsData[0].attribute.start = 0.0;\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = 0.0;\r
+comp->fmuData->modelData.booleanParameterData[0].attribute.start = 1;\r
+}\r
+// Set values for all variables that define a start value\r
+void setStartValues(ModelInstance *comp) {\r
+\r
+  comp->fmuData->modelData.realVarsData[0].attribute.start =  comp->fmuData->localData[0]->realVars[0];\r
+  comp->fmuData->modelData.realVarsData[1].attribute.start =  comp->fmuData->localData[0]->realVars[1];\r
+  comp->fmuData->modelData.realVarsData[2].attribute.start =  comp->fmuData->localData[0]->realVars[2];\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = comp->fmuData->simulationInfo.realParameter[0];\r
+comp->fmuData->modelData.booleanParameterData[0].attribute.start = comp->fmuData->simulationInfo.booleanParameter[0];\r
+}\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $Pstock_ : return comp->fmuData->localData[0]->realVars[0]; break;\r
+      case $P$DER$Pstock_ : return comp->fmuData->localData[0]->realVars[1]; break;\r
+      case $Pvalve_ : return comp->fmuData->localData[0]->realVars[2]; break;\r
+      case time_ : return comp->fmuData->simulationInfo.realParameter[0]; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+}\r
+\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value) {\r
+  switch (vr) {\r
+      case $Pstock_ : comp->fmuData->localData[0]->realVars[0]=value; break;\r
+      case $P$DER$Pstock_ : comp->fmuData->localData[0]->realVars[1]=value; break;\r
+      case $Pvalve_ : comp->fmuData->localData[0]->realVars[2]=value; break;\r
+      case time_ : comp->fmuData->simulationInfo.realParameter[0]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value) {\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $Pb_ : return comp->fmuData->simulationInfo.booleanParameter[0]; break;\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value) {\r
+  switch (vr) {\r
+      case $Pb_ : comp->fmuData->simulationInfo.booleanParameter[0]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value){\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_functions.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_functions.c
new file mode 100644 (file)
index 0000000..c36052e
--- /dev/null
@@ -0,0 +1,16 @@
+#include "FMUBooleanTestModel_functions.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#define _OMC_LIT0_data "'p"\r
+static const size_t _OMC_LIT0_strlen = 2;\r
+static const char _OMC_LIT0[3] = _OMC_LIT0_data;\r
+#define _OMC_LIT1_data "'p/s"\r
+static const size_t _OMC_LIT1_strlen = 4;\r
+static const char _OMC_LIT1[5] = _OMC_LIT1_data;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_functions.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_functions.h
new file mode 100644 (file)
index 0000000..3f2c297
--- /dev/null
@@ -0,0 +1,17 @@
+#ifndef FMUBooleanTestModel__H\r
+#define FMUBooleanTestModel__H\r
+#define omp_get_thread_num() 0\r
+#include "modelica.h"\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <errno.h>\r
+#include "simulation_runtime.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_records.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/FMUBooleanTestModel_records.c
new file mode 100644 (file)
index 0000000..291900d
--- /dev/null
@@ -0,0 +1,3 @@
+/* Additional record code for FMUBooleanTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#include "meta_modelica.h"\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/_FMUBooleanTestModel.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/_FMUBooleanTestModel.h
new file mode 100644 (file)
index 0000000..4c999f6
--- /dev/null
@@ -0,0 +1,37 @@
+/* Simulation code for FMUBooleanTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#define time data->localData[0]->timeValue\r
+\r
+/* States */\r
+#define _$Pstock(i) data->localData[i]->realVars[0]\r
+#define $Pstock _$Pstock(0)\r
+#define $P$PRE$Pstock data->simulationInfo.realVarsPre[0]\r
+#define $P$START$Pstock data->modelData.realVarsData[0].attribute.start\r
+#define $Pstock__varInfo data->modelData.realVarsData[0].info\r
+/* StatesDerivatives */\r
+#define _$P$DER$Pstock(i) data->localData[i]->realVars[1]\r
+#define $P$DER$Pstock _$P$DER$Pstock(0)\r
+#define $P$PRE$P$DER$Pstock data->simulationInfo.realVarsPre[1]\r
+#define $P$START$P$DER$Pstock data->modelData.realVarsData[1].attribute.start\r
+#define $P$DER$Pstock__varInfo data->modelData.realVarsData[1].info\r
+/* Algebraic Vars */\r
+#define _$Pvalve(i) data->localData[i]->realVars[2]\r
+#define $Pvalve _$Pvalve(0)\r
+#define $P$PRE$Pvalve data->simulationInfo.realVarsPre[2]\r
+#define $P$START$Pvalve data->modelData.realVarsData[2].attribute.start\r
+#define $Pvalve__varInfo data->modelData.realVarsData[2].info\r
+/* Algebraic Parameter */\r
+#define time data->simulationInfo.realParameter[0]\r
+#define $P$STARTtime data->modelData.realParameterData[0].attribute.start\r
+#define time__varInfo data->modelData.realParameterData[0].info\r
+/* External Objects */\r
+/* Algebraic Integer Vars */\r
+/* Algebraic Integer Parameter */\r
+/* Algebraic Boolean Vars */\r
+/* Algebraic Boolean Parameters */\r
+#define $Pb data->simulationInfo.booleanParameter[0]\r
+#define $P$START$Pb data->modelData.booleanParameterData[0].attribute.start\r
+#define $Pb__varInfo data->modelData.booleanParameterData[0].info\r
+/* Algebraic String Variables */\r
+/* Algebraic String Parameter */\r
+/* Jacobian Variables */\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/modelDescription.xml b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUBooleanTest/modelDescription.xml
new file mode 100644 (file)
index 0000000..75163cb
--- /dev/null
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="FMUBooleanTestModel"\r
+  modelIdentifier="FMUBooleanTestModel"\r
+  guid="{3286e2d9-75aa-4917-9a7e-69e4959910a6}"\r
+  generationTool="OpenModelica Compiler 1.8.1+ (r11690)"\r
+  generationDateAndTime="2012-05-10T10:13:28Z"\r
+  variableNamingConvention="structured"\r
+  numberOfContinuousStates="1"\r
+  numberOfEventIndicators="0">\r
+  <ModelVariables>\r
+  <ScalarVariable\r
+    name="stock"\r
+    valueReference="0"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stock)"\r
+    valueReference="1"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valve"\r
+    valueReference="2"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="time"\r
+    valueReference="3"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="b"\r
+    valueReference="0"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Boolean/>\r
+  </ScalarVariable>\r
+  </ModelVariables>\r
+</fmiModelDescription>\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTest.mo b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTest.mo
new file mode 100644 (file)
index 0000000..3a19817
--- /dev/null
@@ -0,0 +1,19 @@
+model FMUCallBeforeInitializationTestModel\r
+       parameter Boolean b = true;\r
+       parameter Integer i = 1;\r
+       parameter Real r = 1.0;\r
+       Real valveBoolean;\r
+       Real stockBoolean(start=0.0,fixed=true);\r
+       Real valveInteger;\r
+       Real stockInteger(start=0.0,fixed=true);\r
+       Real valveReal;\r
+       Real stockReal(start=0.0,fixed=true);   \r
+       parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+equation\r
+       valveBoolean = if initial() or b or not b then (if b then 1 else -1) else pre(valveBoolean);\r
+       valveInteger = if initial() or i < 0 or i >= 0 then (i) else pre(valveInteger);\r
+       valveReal = if initial() or r < 0 or r >= 0 then (r) else pre(valveReal);       \r
+       der(stockBoolean) = valveBoolean;\r
+       der(stockInteger) = valveInteger;\r
+       der(stockReal) = valveReal;\r
+end FMUCallBeforeInitializationTestModel;
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTest.mos b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTest.mos
new file mode 100644 (file)
index 0000000..0a20aa7
--- /dev/null
@@ -0,0 +1,2 @@
+loadFile("FMUCallBeforeInitializationTest.mo");\r
+translateModelFMU(FMUCallBeforeInitializationTestModel)
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.c
new file mode 100644 (file)
index 0000000..d27de66
--- /dev/null
@@ -0,0 +1,464 @@
+/* Simulation code for FMUCallBeforeInitializationTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "simulation_runtime.h"\r
+#include "omc_error.h"\r
+\r
+#include <assert.h>\r
+#include <string.h>\r
+\r
+#include "FMUCallBeforeInitializationTestModel_functions.h"\r
+\r
+#include "_FMUCallBeforeInitializationTestModel.h"\r
+#include "FMUCallBeforeInitializationTestModel_functions.c"\r
+/* dummy VARINFO and FILEINFO */\r
+const FILE_INFO dummyFILE_INFO = {"",-1,-1,-1,-1,1};\r
+const VAR_INFO dummyVAR_INFO = {-1,"","",(FILE_INFO){"",-1,-1,-1,-1,1}};\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef _OMC_MEASURE_TIME\r
+int measure_time_flag = 1;\r
+#else\r
+int measure_time_flag = 0;\r
+#endif\r
+\r
+void setupDataStruc(DATA *data)\r
+{\r
+  ASSERT(data,"Error while initialize Data");\r
+  data->modelData.modelName = "FMUCallBeforeInitializationTestModel";\r
+  data->modelData.modelFilePrefix = "FMUCallBeforeInitializationTestModel";\r
+  data->modelData.modelDir = "";\r
+  data->modelData.modelGUID = "{f4c1919a-ebce-4a1a-baca-8e57e23985cf}";\r
+  \r
+  data->modelData.nStates = 3;\r
+  data->modelData.nVariablesReal = 2*3+3;\r
+  data->modelData.nVariablesInteger = 0;\r
+  data->modelData.nVariablesBoolean = 0;\r
+  data->modelData.nVariablesString = 0;\r
+  data->modelData.nParametersReal = 2;\r
+  data->modelData.nParametersInteger = 1;\r
+  data->modelData.nParametersBoolean = 1;\r
+  data->modelData.nParametersString = 0;\r
+  data->modelData.nInputVars = 0;\r
+  data->modelData.nOutputVars = 0;\r
+  data->modelData.nJacobians = 4;\r
+  data->modelData.nHelpVars = 0;\r
+  \r
+  data->modelData.nAliasReal = 0;\r
+  data->modelData.nAliasInteger = 0;\r
+  data->modelData.nAliasBoolean = 0;\r
+  data->modelData.nAliasString = 0;\r
+  \r
+  data->modelData.nZeroCrossings = 0;\r
+  data->modelData.nSamples = 0;\r
+  data->modelData.nInitEquations = 0;\r
+  data->modelData.nResiduals = 3;\r
+  data->modelData.nExtObjs = 0;\r
+  data->modelData.nFunctions = 0;\r
+  data->modelData.nEquations = 12;\r
+  \r
+  data->modelData.nDelayExpressions = 0;\r
+  \r
+}\r
+\r
+void setupDataStruc2(DATA *data)\r
+{\r
+  const struct FUNCTION_INFO funcInfo[1] = {{-1,"",omc_dummyFileInfo}};\r
+  memcpy(data->modelData.functionNames, &funcInfo, data->modelData.nFunctions*sizeof(FUNCTION_INFO));\r
+  \r
+  const VAR_INFO** equationInfo_cref1 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref1[0] = &$PvalveReal__varInfo;\r
+  const VAR_INFO** equationInfo_cref3 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref3[0] = &$P$DER$PstockReal__varInfo;\r
+  const VAR_INFO** equationInfo_cref5 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref5[0] = &$PvalveInteger__varInfo;\r
+  const VAR_INFO** equationInfo_cref7 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref7[0] = &$P$DER$PstockInteger__varInfo;\r
+  const VAR_INFO** equationInfo_cref9 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref9[0] = &$PvalveBoolean__varInfo;\r
+  const VAR_INFO** equationInfo_cref11 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref11[0] = &$P$DER$PstockBoolean__varInfo;\r
+  const struct EQUATION_INFO equationInfo[12] = {\r
+    {1009,"SES_ALGORITHM 0", 0, NULL},\r
+    {1010,"SES_SIMPLE_ASSIGN 1",1,equationInfo_cref1},\r
+    {1011,"SES_ALGORITHM 2", 0, NULL},\r
+    {1012,"SES_SIMPLE_ASSIGN 3",1,equationInfo_cref3},\r
+    {1013,"SES_ALGORITHM 4", 0, NULL},\r
+    {1014,"SES_SIMPLE_ASSIGN 5",1,equationInfo_cref5},\r
+    {1015,"SES_ALGORITHM 6", 0, NULL},\r
+    {1016,"SES_SIMPLE_ASSIGN 7",1,equationInfo_cref7},\r
+    {1017,"SES_ALGORITHM 8", 0, NULL},\r
+    {1018,"SES_SIMPLE_ASSIGN 9",1,equationInfo_cref9},\r
+    {1019,"SES_ALGORITHM 10", 0, NULL},\r
+    {1020,"SES_SIMPLE_ASSIGN 11",1,equationInfo_cref11}\r
+  };\r
+  const int n_omc_equationInfo_reverse_prof_index = 0;\r
+  const int omc_equationInfo_reverse_prof_index[] = {\r
+    \r
+  };\r
+  memcpy(data->modelData.equationInfo, &equationInfo, data->modelData.nEquations*sizeof(EQUATION_INFO));\r
+  \r
+  data->modelData.nProfileBlocks = n_omc_equationInfo_reverse_prof_index;\r
+  data->modelData.equationInfo_reverse_prof_index = (int*) malloc(data->modelData.nProfileBlocks*sizeof(int));\r
+  memcpy(data->modelData.equationInfo_reverse_prof_index, omc_equationInfo_reverse_prof_index, data->modelData.nProfileBlocks*sizeof(int));\r
+}\r
+\r
+/* Has to be performed after _init.xml file has been read */\r
+void callExternalObjectConstructors(DATA *data)\r
+{\r
+  state mem_state;\r
+  mem_state = get_memory_state();\r
+  /* data->simulationInfo.extObjs = NULL; */\r
+}\r
+\r
+void callExternalObjectDestructors(DATA *data)\r
+{\r
+  if (data->simulationInfo.extObjs) {\r
+    free(data->simulationInfo.extObjs);\r
+    data->simulationInfo.extObjs = 0;\r
+  }\r
+}\r
+\r
+\r
+int input_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+int output_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* Initializes the raw time events of the simulation using the now\r
+   calcualted parameters. */\r
+void function_sampleInit(DATA *data)\r
+{\r
+}\r
+\r
+int function_updateSample(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_storeDelayed(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundStartValues(DATA *data)\r
+{\r
+\r
+  \r
+  DEBUG_INFO(LOG_INIT, "updating start-values:");\r
+  \r
+  return 0;\r
+}\r
+\r
+int initial_residual(DATA *data, double $P$_lambda, double* initialResiduals)\r
+{\r
+  int i = 0;\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  DEBUG_INFO(LOG_RES_INIT, "updating initial_residuals:");\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($PstockReal - $P$START$PstockReal));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stockReal - $_start(stockReal)) = %f", i, initialResiduals[i-1]);\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($PstockInteger - $P$START$PstockInteger));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stockInteger - $_start(stockInteger)) = %f", i, initialResiduals[i-1]);\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($PstockBoolean - $P$START$PstockBoolean));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stockBoolean - $_start(stockBoolean)) = %f", i, initialResiduals[i-1]);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundParameters(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_0(DATA *data) {\r
+  modelica_boolean tmp0;\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:13:2-13:93]*/\r
+  tmp0 = initial();\r
+  $PvalveBoolean = (((tmp0 || $Pb) || (!$Pb))?($Pb?1.0:-1.0):$P$PRE$PvalveBoolean); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_1(DATA *data) {\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:16:2-16:34]*/\r
+  $P$DER$PstockBoolean = $PvalveBoolean; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_2(DATA *data) {\r
+  modelica_boolean tmp1;\r
+  modelica_boolean tmp2;\r
+  modelica_boolean tmp3;\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:14:2-14:80]*/\r
+  tmp1 = initial();\r
+  RELATIONTOZC(tmp2, (modelica_integer)$Pi, (modelica_integer) 0, -1,Less,<);\r
+  RELATIONTOZC(tmp3, (modelica_integer)$Pi, (modelica_integer) 0, -1,GreaterEq,>=);\r
+  $PvalveInteger = (((tmp1 || tmp2) || tmp3)?((modelica_real)(modelica_integer)$Pi):$P$PRE$PvalveInteger); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_3(DATA *data) {\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:17:2-17:34]*/\r
+  $P$DER$PstockInteger = $PvalveInteger; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_4(DATA *data) {\r
+  modelica_boolean tmp4;\r
+  modelica_boolean tmp5;\r
+  modelica_boolean tmp6;\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:15:2-15:74]*/\r
+  tmp4 = initial();\r
+  RELATIONTOZC(tmp5, $Pr, 0.0, -1,Less,<);\r
+  RELATIONTOZC(tmp6, $Pr, 0.0, -1,GreaterEq,>=);\r
+  $PvalveReal = (((tmp4 || tmp5) || tmp6)?$Pr:$P$PRE$PvalveReal); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_5(DATA *data) {\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:18:2-18:28]*/\r
+  $P$DER$PstockReal = $PvalveReal; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+static void functionODE_system0(DATA *data,int omc_thread_number)\r
+{\r
+  eqFunction_0(data);\r
+  eqFunction_1(data);\r
+  eqFunction_2(data);\r
+  eqFunction_3(data);\r
+  eqFunction_4(data);\r
+  eqFunction_5(data);\r
+}\r
+static void (*functionODE_systems[1])(DATA *, int) = {\r
+  functionODE_system0\r
+};\r
+\r
+void function_initMemoryState()\r
+{\r
+  push_memory_states(1);\r
+}\r
+\r
+int functionODE(DATA *data)\r
+{\r
+  int id,th_id;\r
+  state mem_state; /* We need to have separate memory pools for separate systems... */\r
+  mem_state = get_memory_state();\r
+  for (id=0; id<1; id++) {\r
+    th_id = omp_get_thread_num();\r
+    functionODE_systems[id](data,th_id);\r
+  }\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+#include <simulation_inline_solver.h>\r
+const char *_omc_force_solver=_OMC_FORCE_SOLVER;\r
+const int inline_work_states_ndims=_OMC_SOLVER_WORK_STATES_NDIMS;\r
+int functionODE_inline(DATA* data, double stepSize)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* for continuous time variables */\r
+int functionAlgebraics(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_6(DATA *data) {\r
+  modelica_boolean tmp10;\r
+  modelica_boolean tmp11;\r
+  modelica_boolean tmp12;\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:15:2-15:74]*/\r
+  tmp10 = initial();\r
+  SAVEZEROCROSS(tmp11, $Pr, 0.0, -1,Less,<);\r
+  SAVEZEROCROSS(tmp12, $Pr, 0.0, -1,GreaterEq,>=);\r
+  $PvalveReal = (((tmp10 || tmp11) || tmp12)?$Pr:$P$PRE$PvalveReal); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_7(DATA *data) {\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:18:2-18:28]*/\r
+  $P$DER$PstockReal = $PvalveReal; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_8(DATA *data) {\r
+  modelica_boolean tmp13;\r
+  modelica_boolean tmp14;\r
+  modelica_boolean tmp15;\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:14:2-14:80]*/\r
+  tmp13 = initial();\r
+  SAVEZEROCROSS(tmp14, (modelica_integer)$Pi, (modelica_integer) 0, -1,Less,<);\r
+  SAVEZEROCROSS(tmp15, (modelica_integer)$Pi, (modelica_integer) 0, -1,GreaterEq,>=);\r
+  $PvalveInteger = (((tmp13 || tmp14) || tmp15)?((modelica_real)(modelica_integer)$Pi):$P$PRE$PvalveInteger); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_9(DATA *data) {\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:17:2-17:34]*/\r
+  $P$DER$PstockInteger = $PvalveInteger; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_10(DATA *data) {\r
+  modelica_boolean tmp16;\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:13:2-13:93]*/\r
+  tmp16 = initial();\r
+  $PvalveBoolean = (((tmp16 || $Pb) || (!$Pb))?($Pb?1.0:-1.0):$P$PRE$PvalveBoolean); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_11(DATA *data) {\r
+  /*#modelicaLine [FMUCallBeforeInitializationTest.mo:16:2-16:34]*/\r
+  $P$DER$PstockBoolean = $PvalveBoolean; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+int functionDAE(DATA *data, int *needToIterate)\r
+{\r
+  state mem_state;\r
+  *needToIterate = 0;\r
+  \r
+  mem_state = get_memory_state();\r
+  eqFunction_6(data);\r
+  eqFunction_7(data);\r
+  eqFunction_8(data);\r
+  eqFunction_9(data);\r
+  eqFunction_10(data);\r
+  eqFunction_11(data);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_onlyZeroCrossings(DATA *data, double *gout,double *t)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int checkForDiscreteChanges(DATA *data)\r
+{\r
+  int needToIterate = 0;\r
+\r
+  \r
+  return needToIterate;\r
+}\r
+\r
+/* function to check assert after a step is done */\r
+int checkForAsserts(DATA *data)\r
+{\r
+\r
+  \r
+  return 0;\r
+}\r
+\r
+ int initialAnalyticJacobianA(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianB(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianC(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianD(DATA* data){\r
+    return 1;\r
+ }\r
+ int functionJacA(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacB(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacC(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacD(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+const char *linear_model_frame =\r
+  "model linear_FMUCallBeforeInitializationTestModel\n  parameter Integer n = 3; // states \n  parameter Integer k = 0; // top-level inputs \n  parameter Integer l = 0; // top-level outputs \n"\r
+  "  parameter Real x0[3] = {%s};\n"\r
+  "  parameter Real u0[0] = {%s};\n"\r
+  "  parameter Real A[3,3] = [%s];\n"\r
+  "  parameter Real B[3,0] = zeros(3,0);%s\n"\r
+  "  parameter Real C[0,3] = zeros(0,3);%s\n"\r
+  "  parameter Real D[0,0] = zeros(0,0);%s\n"\r
+  "  Real x[3](start=x0);\n"\r
+  "  input Real u[0];\n"\r
+  "  output Real y[0];\n"\r
+  "\n  Real x_PstockBoolean = x[1];\n  Real x_PstockInteger = x[2];\n  Real x_PstockReal = x[3];\n      \n"\r
+  "equation\n  der(x) = A * x + B * u;\n  y = C * x + D * u;\nend linear_FMUCallBeforeInitializationTestModel;\n"\r
+;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+/* forward the main in the simulation runtime */\r
+extern int _main_SimulationRuntime(int argc, char**argv, DATA *data);\r
+\r
+/* call the simulation runtime main from our main! */\r
+int main(int argc, char**argv)\r
+{\r
+  DATA data;\r
+  setupDataStruc(&data);\r
+  return _main_SimulationRuntime(argc, argv, &data);\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.dll b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.dll
new file mode 100644 (file)
index 0000000..d296450
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.dll differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.fmu b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.fmu
new file mode 100644 (file)
index 0000000..0a901a5
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.fmu differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.lib b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.lib
new file mode 100644 (file)
index 0000000..da146e3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel.lib differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_FMU.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_FMU.c
new file mode 100644 (file)
index 0000000..3c57e87
--- /dev/null
@@ -0,0 +1,190 @@
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER FMUCallBeforeInitializationTestModel\r
+#define MODEL_GUID "{f4c1919a-ebce-4a1a-baca-8e57e23985cf}"\r
+\r
+// include fmu header files, typedefs and macros\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "omc_error.h"\r
+#include "fmiModelTypes.h"\r
+#include "fmiModelFunctions.h"\r
+#include "FMUCallBeforeInitializationTestModel_functions.h"\r
+#include "initialization.h"\r
+#include "events.h"\r
+#include "fmu_model_interface.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+void setStartValues(ModelInstance *comp);\r
+void setDefaultStartValues(ModelInstance *comp);\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo);\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value);\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value);\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value);\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value);\r
+\r
+// define model size\r
+#define NUMBER_OF_STATES 3\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+#define NUMBER_OF_REALS 11\r
+#define NUMBER_OF_INTEGERS 1\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_BOOLEANS 1\r
+#define NUMBER_OF_EXTERNALFUNCTIONS 0\r
+\r
+// define variable data for model\r
+#define $PstockBoolean_ 0 \r
+#define $PstockInteger_ 1 \r
+#define $PstockReal_ 2 \r
+#define $P$DER$PstockBoolean_ 3 \r
+#define $P$DER$PstockInteger_ 4 \r
+#define $P$DER$PstockReal_ 5 \r
+#define $PvalveBoolean_ 6 \r
+#define $PvalveInteger_ 7 \r
+#define $PvalveReal_ 8 \r
+#define $Pr_ 9 \r
+#define time_ 10 \r
+#define $Pi_ 0 \r
+#define $Pb_ 0 \r
+\r
+\r
+// define initial state vector as vector of value references\r
+#define STATES { $PstockBoolean_, $PstockInteger_, $PstockReal_ }\r
+#define STATESDERIVATIVES { $P$DER$PstockBoolean_, $P$DER$PstockInteger_, $P$DER$PstockReal_ }\r
+\r
+\r
+// implementation of the Model Exchange functions\r
+#include "fmu_model_interface.c"\r
+\r
+// Set values for all variables that define a start value\r
+void setDefaultStartValues(ModelInstance *comp) {\r
+\r
+comp->fmuData->modelData.realVarsData[0].attribute.start = 0.0;\r
+comp->fmuData->modelData.realVarsData[1].attribute.start = 0.0;\r
+comp->fmuData->modelData.realVarsData[2].attribute.start = 0.0;\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = 1.0;\r
+comp->fmuData->modelData.realParameterData[1].attribute.start = 0.0;\r
+comp->fmuData->modelData.integerParameterData[0].attribute.start = 1;\r
+comp->fmuData->modelData.booleanParameterData[0].attribute.start = 1;\r
+}\r
+// Set values for all variables that define a start value\r
+void setStartValues(ModelInstance *comp) {\r
+\r
+  comp->fmuData->modelData.realVarsData[0].attribute.start =  comp->fmuData->localData[0]->realVars[0];\r
+  comp->fmuData->modelData.realVarsData[1].attribute.start =  comp->fmuData->localData[0]->realVars[1];\r
+  comp->fmuData->modelData.realVarsData[2].attribute.start =  comp->fmuData->localData[0]->realVars[2];\r
+  comp->fmuData->modelData.realVarsData[3].attribute.start =  comp->fmuData->localData[0]->realVars[3];\r
+  comp->fmuData->modelData.realVarsData[4].attribute.start =  comp->fmuData->localData[0]->realVars[4];\r
+  comp->fmuData->modelData.realVarsData[5].attribute.start =  comp->fmuData->localData[0]->realVars[5];\r
+  comp->fmuData->modelData.realVarsData[6].attribute.start =  comp->fmuData->localData[0]->realVars[6];\r
+  comp->fmuData->modelData.realVarsData[7].attribute.start =  comp->fmuData->localData[0]->realVars[7];\r
+  comp->fmuData->modelData.realVarsData[8].attribute.start =  comp->fmuData->localData[0]->realVars[8];\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = comp->fmuData->simulationInfo.realParameter[0];\r
+comp->fmuData->modelData.realParameterData[1].attribute.start = comp->fmuData->simulationInfo.realParameter[1];\r
+comp->fmuData->modelData.integerParameterData[0].attribute.start = comp->fmuData->simulationInfo.integerParameter[0];\r
+comp->fmuData->modelData.booleanParameterData[0].attribute.start = comp->fmuData->simulationInfo.booleanParameter[0];\r
+}\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $PstockBoolean_ : return comp->fmuData->localData[0]->realVars[0]; break;\r
+      case $PstockInteger_ : return comp->fmuData->localData[0]->realVars[1]; break;\r
+      case $PstockReal_ : return comp->fmuData->localData[0]->realVars[2]; break;\r
+      case $P$DER$PstockBoolean_ : return comp->fmuData->localData[0]->realVars[3]; break;\r
+      case $P$DER$PstockInteger_ : return comp->fmuData->localData[0]->realVars[4]; break;\r
+      case $P$DER$PstockReal_ : return comp->fmuData->localData[0]->realVars[5]; break;\r
+      case $PvalveBoolean_ : return comp->fmuData->localData[0]->realVars[6]; break;\r
+      case $PvalveInteger_ : return comp->fmuData->localData[0]->realVars[7]; break;\r
+      case $PvalveReal_ : return comp->fmuData->localData[0]->realVars[8]; break;\r
+      case $Pr_ : return comp->fmuData->simulationInfo.realParameter[0]; break;\r
+      case time_ : return comp->fmuData->simulationInfo.realParameter[1]; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+}\r
+\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value) {\r
+  switch (vr) {\r
+      case $PstockBoolean_ : comp->fmuData->localData[0]->realVars[0]=value; break;\r
+      case $PstockInteger_ : comp->fmuData->localData[0]->realVars[1]=value; break;\r
+      case $PstockReal_ : comp->fmuData->localData[0]->realVars[2]=value; break;\r
+      case $P$DER$PstockBoolean_ : comp->fmuData->localData[0]->realVars[3]=value; break;\r
+      case $P$DER$PstockInteger_ : comp->fmuData->localData[0]->realVars[4]=value; break;\r
+      case $P$DER$PstockReal_ : comp->fmuData->localData[0]->realVars[5]=value; break;\r
+      case $PvalveBoolean_ : comp->fmuData->localData[0]->realVars[6]=value; break;\r
+      case $PvalveInteger_ : comp->fmuData->localData[0]->realVars[7]=value; break;\r
+      case $PvalveReal_ : comp->fmuData->localData[0]->realVars[8]=value; break;\r
+      case $Pr_ : comp->fmuData->simulationInfo.realParameter[0]=value; break;\r
+      case time_ : comp->fmuData->simulationInfo.realParameter[1]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $Pi_ : return comp->fmuData->simulationInfo.integerParameter[0]; break;\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value) {\r
+  switch (vr) {\r
+      case $Pi_ : comp->fmuData->simulationInfo.integerParameter[0]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $Pb_ : return comp->fmuData->simulationInfo.booleanParameter[0]; break;\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value) {\r
+  switch (vr) {\r
+      case $Pb_ : comp->fmuData->simulationInfo.booleanParameter[0]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value){\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_functions.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_functions.c
new file mode 100644 (file)
index 0000000..621cd41
--- /dev/null
@@ -0,0 +1,16 @@
+#include "FMUCallBeforeInitializationTestModel_functions.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#define _OMC_LIT0_data "'p"\r
+static const size_t _OMC_LIT0_strlen = 2;\r
+static const char _OMC_LIT0[3] = _OMC_LIT0_data;\r
+#define _OMC_LIT1_data "'p/s"\r
+static const size_t _OMC_LIT1_strlen = 4;\r
+static const char _OMC_LIT1[5] = _OMC_LIT1_data;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_functions.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_functions.h
new file mode 100644 (file)
index 0000000..a350862
--- /dev/null
@@ -0,0 +1,17 @@
+#ifndef FMUCallBeforeInitializationTestModel__H\r
+#define FMUCallBeforeInitializationTestModel__H\r
+#define omp_get_thread_num() 0\r
+#include "modelica.h"\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <errno.h>\r
+#include "simulation_runtime.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_records.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/FMUCallBeforeInitializationTestModel_records.c
new file mode 100644 (file)
index 0000000..ed3c84c
--- /dev/null
@@ -0,0 +1,3 @@
+/* Additional record code for FMUCallBeforeInitializationTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#include "meta_modelica.h"\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/_FMUCallBeforeInitializationTestModel.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/_FMUCallBeforeInitializationTestModel.h
new file mode 100644 (file)
index 0000000..57ae682
--- /dev/null
@@ -0,0 +1,73 @@
+/* Simulation code for FMUCallBeforeInitializationTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#define time data->localData[0]->timeValue\r
+\r
+/* States */\r
+#define _$PstockBoolean(i) data->localData[i]->realVars[0]\r
+#define $PstockBoolean _$PstockBoolean(0)\r
+#define $P$PRE$PstockBoolean data->simulationInfo.realVarsPre[0]\r
+#define $P$START$PstockBoolean data->modelData.realVarsData[0].attribute.start\r
+#define $PstockBoolean__varInfo data->modelData.realVarsData[0].info\r
+#define _$PstockInteger(i) data->localData[i]->realVars[1]\r
+#define $PstockInteger _$PstockInteger(0)\r
+#define $P$PRE$PstockInteger data->simulationInfo.realVarsPre[1]\r
+#define $P$START$PstockInteger data->modelData.realVarsData[1].attribute.start\r
+#define $PstockInteger__varInfo data->modelData.realVarsData[1].info\r
+#define _$PstockReal(i) data->localData[i]->realVars[2]\r
+#define $PstockReal _$PstockReal(0)\r
+#define $P$PRE$PstockReal data->simulationInfo.realVarsPre[2]\r
+#define $P$START$PstockReal data->modelData.realVarsData[2].attribute.start\r
+#define $PstockReal__varInfo data->modelData.realVarsData[2].info\r
+/* StatesDerivatives */\r
+#define _$P$DER$PstockBoolean(i) data->localData[i]->realVars[3]\r
+#define $P$DER$PstockBoolean _$P$DER$PstockBoolean(0)\r
+#define $P$PRE$P$DER$PstockBoolean data->simulationInfo.realVarsPre[3]\r
+#define $P$START$P$DER$PstockBoolean data->modelData.realVarsData[3].attribute.start\r
+#define $P$DER$PstockBoolean__varInfo data->modelData.realVarsData[3].info\r
+#define _$P$DER$PstockInteger(i) data->localData[i]->realVars[4]\r
+#define $P$DER$PstockInteger _$P$DER$PstockInteger(0)\r
+#define $P$PRE$P$DER$PstockInteger data->simulationInfo.realVarsPre[4]\r
+#define $P$START$P$DER$PstockInteger data->modelData.realVarsData[4].attribute.start\r
+#define $P$DER$PstockInteger__varInfo data->modelData.realVarsData[4].info\r
+#define _$P$DER$PstockReal(i) data->localData[i]->realVars[5]\r
+#define $P$DER$PstockReal _$P$DER$PstockReal(0)\r
+#define $P$PRE$P$DER$PstockReal data->simulationInfo.realVarsPre[5]\r
+#define $P$START$P$DER$PstockReal data->modelData.realVarsData[5].attribute.start\r
+#define $P$DER$PstockReal__varInfo data->modelData.realVarsData[5].info\r
+/* Algebraic Vars */\r
+#define _$PvalveBoolean(i) data->localData[i]->realVars[6]\r
+#define $PvalveBoolean _$PvalveBoolean(0)\r
+#define $P$PRE$PvalveBoolean data->simulationInfo.realVarsPre[6]\r
+#define $P$START$PvalveBoolean data->modelData.realVarsData[6].attribute.start\r
+#define $PvalveBoolean__varInfo data->modelData.realVarsData[6].info\r
+#define _$PvalveInteger(i) data->localData[i]->realVars[7]\r
+#define $PvalveInteger _$PvalveInteger(0)\r
+#define $P$PRE$PvalveInteger data->simulationInfo.realVarsPre[7]\r
+#define $P$START$PvalveInteger data->modelData.realVarsData[7].attribute.start\r
+#define $PvalveInteger__varInfo data->modelData.realVarsData[7].info\r
+#define _$PvalveReal(i) data->localData[i]->realVars[8]\r
+#define $PvalveReal _$PvalveReal(0)\r
+#define $P$PRE$PvalveReal data->simulationInfo.realVarsPre[8]\r
+#define $P$START$PvalveReal data->modelData.realVarsData[8].attribute.start\r
+#define $PvalveReal__varInfo data->modelData.realVarsData[8].info\r
+/* Algebraic Parameter */\r
+#define $Pr data->simulationInfo.realParameter[0]\r
+#define $P$START$Pr data->modelData.realParameterData[0].attribute.start\r
+#define $Pr__varInfo data->modelData.realParameterData[0].info\r
+#define time data->simulationInfo.realParameter[1]\r
+#define $P$STARTtime data->modelData.realParameterData[1].attribute.start\r
+#define time__varInfo data->modelData.realParameterData[1].info\r
+/* External Objects */\r
+/* Algebraic Integer Vars */\r
+/* Algebraic Integer Parameter */\r
+#define $Pi data->simulationInfo.integerParameter[0]\r
+#define $P$START$Pi data->modelData.integerParameterData[0].attribute.start\r
+#define $Pi__varInfo data->modelData.integerParameterData[0].info\r
+/* Algebraic Boolean Vars */\r
+/* Algebraic Boolean Parameters */\r
+#define $Pb data->simulationInfo.booleanParameter[0]\r
+#define $P$START$Pb data->modelData.booleanParameterData[0].attribute.start\r
+#define $Pb__varInfo data->modelData.booleanParameterData[0].info\r
+/* Algebraic String Variables */\r
+/* Algebraic String Parameter */\r
+/* Jacobian Variables */\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/modelDescription.xml b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUCallBeforeInitializationTest/modelDescription.xml
new file mode 100644 (file)
index 0000000..102788e
--- /dev/null
@@ -0,0 +1,119 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="FMUCallBeforeInitializationTestModel"\r
+  modelIdentifier="FMUCallBeforeInitializationTestModel"\r
+  guid="{f4c1919a-ebce-4a1a-baca-8e57e23985cf}"\r
+  generationTool="OpenModelica Compiler 1.8.1+ (r11690)"\r
+  generationDateAndTime="2012-05-10T11:40:43Z"\r
+  variableNamingConvention="structured"\r
+  numberOfContinuousStates="3"\r
+  numberOfEventIndicators="0">\r
+  <ModelVariables>\r
+  <ScalarVariable\r
+    name="stockBoolean"\r
+    valueReference="0"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="stockInteger"\r
+    valueReference="1"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="stockReal"\r
+    valueReference="2"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stockBoolean)"\r
+    valueReference="3"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stockInteger)"\r
+    valueReference="4"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stockReal)"\r
+    valueReference="5"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valveBoolean"\r
+    valueReference="6"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valveInteger"\r
+    valueReference="7"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valveReal"\r
+    valueReference="8"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="r"\r
+    valueReference="9"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="1.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="time"\r
+    valueReference="10"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="i"\r
+    valueReference="0"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Integer/>\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="b"\r
+    valueReference="0"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Boolean/>\r
+  </ScalarVariable>\r
+  </ModelVariables>\r
+</fmiModelDescription>\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTest.mo b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTest.mo
new file mode 100644 (file)
index 0000000..fd9af84
--- /dev/null
@@ -0,0 +1,10 @@
+model FMUIntegerTestModel\r
+       parameter Integer i1 = 1;\r
+       parameter Integer i2 = 1;\r
+       Real valve;\r
+       Real stock(start=0.0,fixed=true);\r
+       parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+equation\r
+       valve = if initial() or i1 < 0 or i1 >= 0 then (i1 + i2) else pre(valve);\r
+       der(stock) = valve;\r
+end FMUIntegerTestModel;
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTest.mos b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTest.mos
new file mode 100644 (file)
index 0000000..ee7b2b1
--- /dev/null
@@ -0,0 +1,2 @@
+loadFile("FMUIntegerTest.mo");\r
+translateModelFMU(FMUIntegerTestModel)
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.c
new file mode 100644 (file)
index 0000000..ed54ffb
--- /dev/null
@@ -0,0 +1,364 @@
+/* Simulation code for FMUIntegerTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "simulation_runtime.h"\r
+#include "omc_error.h"\r
+\r
+#include <assert.h>\r
+#include <string.h>\r
+\r
+#include "FMUIntegerTestModel_functions.h"\r
+\r
+#include "_FMUIntegerTestModel.h"\r
+#include "FMUIntegerTestModel_functions.c"\r
+/* dummy VARINFO and FILEINFO */\r
+const FILE_INFO dummyFILE_INFO = {"",-1,-1,-1,-1,1};\r
+const VAR_INFO dummyVAR_INFO = {-1,"","",(FILE_INFO){"",-1,-1,-1,-1,1}};\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef _OMC_MEASURE_TIME\r
+int measure_time_flag = 1;\r
+#else\r
+int measure_time_flag = 0;\r
+#endif\r
+\r
+void setupDataStruc(DATA *data)\r
+{\r
+  ASSERT(data,"Error while initialize Data");\r
+  data->modelData.modelName = "FMUIntegerTestModel";\r
+  data->modelData.modelFilePrefix = "FMUIntegerTestModel";\r
+  data->modelData.modelDir = "";\r
+  data->modelData.modelGUID = "{2d294e78-8670-49d1-89de-38199246249e}";\r
+  \r
+  data->modelData.nStates = 1;\r
+  data->modelData.nVariablesReal = 2*1+1;\r
+  data->modelData.nVariablesInteger = 0;\r
+  data->modelData.nVariablesBoolean = 0;\r
+  data->modelData.nVariablesString = 0;\r
+  data->modelData.nParametersReal = 1;\r
+  data->modelData.nParametersInteger = 2;\r
+  data->modelData.nParametersBoolean = 0;\r
+  data->modelData.nParametersString = 0;\r
+  data->modelData.nInputVars = 0;\r
+  data->modelData.nOutputVars = 0;\r
+  data->modelData.nJacobians = 4;\r
+  data->modelData.nHelpVars = 0;\r
+  \r
+  data->modelData.nAliasReal = 0;\r
+  data->modelData.nAliasInteger = 0;\r
+  data->modelData.nAliasBoolean = 0;\r
+  data->modelData.nAliasString = 0;\r
+  \r
+  data->modelData.nZeroCrossings = 0;\r
+  data->modelData.nSamples = 0;\r
+  data->modelData.nInitEquations = 0;\r
+  data->modelData.nResiduals = 1;\r
+  data->modelData.nExtObjs = 0;\r
+  data->modelData.nFunctions = 0;\r
+  data->modelData.nEquations = 4;\r
+  \r
+  data->modelData.nDelayExpressions = 0;\r
+  \r
+}\r
+\r
+void setupDataStruc2(DATA *data)\r
+{\r
+  const struct FUNCTION_INFO funcInfo[1] = {{-1,"",omc_dummyFileInfo}};\r
+  memcpy(data->modelData.functionNames, &funcInfo, data->modelData.nFunctions*sizeof(FUNCTION_INFO));\r
+  \r
+  const VAR_INFO** equationInfo_cref1 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref1[0] = &$Pvalve__varInfo;\r
+  const VAR_INFO** equationInfo_cref3 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref3[0] = &$P$DER$Pstock__varInfo;\r
+  const struct EQUATION_INFO equationInfo[4] = {\r
+    {1003,"SES_ALGORITHM 0", 0, NULL},\r
+    {1004,"SES_SIMPLE_ASSIGN 1",1,equationInfo_cref1},\r
+    {1005,"SES_ALGORITHM 2", 0, NULL},\r
+    {1006,"SES_SIMPLE_ASSIGN 3",1,equationInfo_cref3}\r
+  };\r
+  const int n_omc_equationInfo_reverse_prof_index = 0;\r
+  const int omc_equationInfo_reverse_prof_index[] = {\r
+    \r
+  };\r
+  memcpy(data->modelData.equationInfo, &equationInfo, data->modelData.nEquations*sizeof(EQUATION_INFO));\r
+  \r
+  data->modelData.nProfileBlocks = n_omc_equationInfo_reverse_prof_index;\r
+  data->modelData.equationInfo_reverse_prof_index = (int*) malloc(data->modelData.nProfileBlocks*sizeof(int));\r
+  memcpy(data->modelData.equationInfo_reverse_prof_index, omc_equationInfo_reverse_prof_index, data->modelData.nProfileBlocks*sizeof(int));\r
+}\r
+\r
+/* Has to be performed after _init.xml file has been read */\r
+void callExternalObjectConstructors(DATA *data)\r
+{\r
+  state mem_state;\r
+  mem_state = get_memory_state();\r
+  /* data->simulationInfo.extObjs = NULL; */\r
+}\r
+\r
+void callExternalObjectDestructors(DATA *data)\r
+{\r
+  if (data->simulationInfo.extObjs) {\r
+    free(data->simulationInfo.extObjs);\r
+    data->simulationInfo.extObjs = 0;\r
+  }\r
+}\r
+\r
+\r
+int input_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+int output_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* Initializes the raw time events of the simulation using the now\r
+   calcualted parameters. */\r
+void function_sampleInit(DATA *data)\r
+{\r
+}\r
+\r
+int function_updateSample(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_storeDelayed(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundStartValues(DATA *data)\r
+{\r
+\r
+  \r
+  DEBUG_INFO(LOG_INIT, "updating start-values:");\r
+  \r
+  return 0;\r
+}\r
+\r
+int initial_residual(DATA *data, double $P$_lambda, double* initialResiduals)\r
+{\r
+  int i = 0;\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  DEBUG_INFO(LOG_RES_INIT, "updating initial_residuals:");\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($Pstock - $P$START$Pstock));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stock - $_start(stock)) = %f", i, initialResiduals[i-1]);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundParameters(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_0(DATA *data) {\r
+  modelica_boolean tmp0;\r
+  modelica_boolean tmp1;\r
+  modelica_boolean tmp2;\r
+  /*#modelicaLine [FMUIntegerTest.mo:8:2-8:74]*/\r
+  tmp0 = initial();\r
+  RELATIONTOZC(tmp1, (modelica_integer)$Pi1, (modelica_integer) 0, -1,Less,<);\r
+  RELATIONTOZC(tmp2, (modelica_integer)$Pi1, (modelica_integer) 0, -1,GreaterEq,>=);\r
+  $Pvalve = (((tmp0 || tmp1) || tmp2)?((modelica_real)((modelica_integer)$Pi1 + (modelica_integer)$Pi2)):$P$PRE$Pvalve); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_1(DATA *data) {\r
+  /*#modelicaLine [FMUIntegerTest.mo:9:2-9:20]*/\r
+  $P$DER$Pstock = $Pvalve; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+static void functionODE_system0(DATA *data,int omc_thread_number)\r
+{\r
+  eqFunction_0(data);\r
+  eqFunction_1(data);\r
+}\r
+static void (*functionODE_systems[1])(DATA *, int) = {\r
+  functionODE_system0\r
+};\r
+\r
+void function_initMemoryState()\r
+{\r
+  push_memory_states(1);\r
+}\r
+\r
+int functionODE(DATA *data)\r
+{\r
+  int id,th_id;\r
+  state mem_state; /* We need to have separate memory pools for separate systems... */\r
+  mem_state = get_memory_state();\r
+  for (id=0; id<1; id++) {\r
+    th_id = omp_get_thread_num();\r
+    functionODE_systems[id](data,th_id);\r
+  }\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+#include <simulation_inline_solver.h>\r
+const char *_omc_force_solver=_OMC_FORCE_SOLVER;\r
+const int inline_work_states_ndims=_OMC_SOLVER_WORK_STATES_NDIMS;\r
+int functionODE_inline(DATA* data, double stepSize)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* for continuous time variables */\r
+int functionAlgebraics(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_2(DATA *data) {\r
+  modelica_boolean tmp4;\r
+  modelica_boolean tmp5;\r
+  modelica_boolean tmp6;\r
+  /*#modelicaLine [FMUIntegerTest.mo:8:2-8:74]*/\r
+  tmp4 = initial();\r
+  SAVEZEROCROSS(tmp5, (modelica_integer)$Pi1, (modelica_integer) 0, -1,Less,<);\r
+  SAVEZEROCROSS(tmp6, (modelica_integer)$Pi1, (modelica_integer) 0, -1,GreaterEq,>=);\r
+  $Pvalve = (((tmp4 || tmp5) || tmp6)?((modelica_real)((modelica_integer)$Pi1 + (modelica_integer)$Pi2)):$P$PRE$Pvalve); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_3(DATA *data) {\r
+  /*#modelicaLine [FMUIntegerTest.mo:9:2-9:20]*/\r
+  $P$DER$Pstock = $Pvalve; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+int functionDAE(DATA *data, int *needToIterate)\r
+{\r
+  state mem_state;\r
+  *needToIterate = 0;\r
+  \r
+  mem_state = get_memory_state();\r
+  eqFunction_2(data);\r
+  eqFunction_3(data);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_onlyZeroCrossings(DATA *data, double *gout,double *t)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int checkForDiscreteChanges(DATA *data)\r
+{\r
+  int needToIterate = 0;\r
+\r
+  \r
+  return needToIterate;\r
+}\r
+\r
+/* function to check assert after a step is done */\r
+int checkForAsserts(DATA *data)\r
+{\r
+\r
+  \r
+  return 0;\r
+}\r
+\r
+ int initialAnalyticJacobianA(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianB(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianC(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianD(DATA* data){\r
+    return 1;\r
+ }\r
+ int functionJacA(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacB(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacC(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacD(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+const char *linear_model_frame =\r
+  "model linear_FMUIntegerTestModel\n  parameter Integer n = 1; // states \n  parameter Integer k = 0; // top-level inputs \n  parameter Integer l = 0; // top-level outputs \n"\r
+  "  parameter Real x0[1] = {%s};\n"\r
+  "  parameter Real u0[0] = {%s};\n"\r
+  "  parameter Real A[1,1] = [%s];\n"\r
+  "  parameter Real B[1,0] = zeros(1,0);%s\n"\r
+  "  parameter Real C[0,1] = zeros(0,1);%s\n"\r
+  "  parameter Real D[0,0] = zeros(0,0);%s\n"\r
+  "  Real x[1](start=x0);\n"\r
+  "  input Real u[0];\n"\r
+  "  output Real y[0];\n"\r
+  "\n  Real x_Pstock = x[1];\n      \n"\r
+  "equation\n  der(x) = A * x + B * u;\n  y = C * x + D * u;\nend linear_FMUIntegerTestModel;\n"\r
+;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+/* forward the main in the simulation runtime */\r
+extern int _main_SimulationRuntime(int argc, char**argv, DATA *data);\r
+\r
+/* call the simulation runtime main from our main! */\r
+int main(int argc, char**argv)\r
+{\r
+  DATA data;\r
+  setupDataStruc(&data);\r
+  return _main_SimulationRuntime(argc, argv, &data);\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.dll b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.dll
new file mode 100644 (file)
index 0000000..ae281fc
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.dll differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.fmu b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.fmu
new file mode 100644 (file)
index 0000000..3e0d419
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.fmu differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.lib b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.lib
new file mode 100644 (file)
index 0000000..a9ef1e5
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel.lib differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_FMU.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_FMU.c
new file mode 100644 (file)
index 0000000..d211cc7
--- /dev/null
@@ -0,0 +1,159 @@
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER FMUIntegerTestModel\r
+#define MODEL_GUID "{2d294e78-8670-49d1-89de-38199246249e}"\r
+\r
+// include fmu header files, typedefs and macros\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "omc_error.h"\r
+#include "fmiModelTypes.h"\r
+#include "fmiModelFunctions.h"\r
+#include "FMUIntegerTestModel_functions.h"\r
+#include "initialization.h"\r
+#include "events.h"\r
+#include "fmu_model_interface.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+void setStartValues(ModelInstance *comp);\r
+void setDefaultStartValues(ModelInstance *comp);\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo);\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value);\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value);\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value);\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value);\r
+\r
+// define model size\r
+#define NUMBER_OF_STATES 1\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+#define NUMBER_OF_REALS 4\r
+#define NUMBER_OF_INTEGERS 2\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_EXTERNALFUNCTIONS 0\r
+\r
+// define variable data for model\r
+#define $Pstock_ 0 \r
+#define $P$DER$Pstock_ 1 \r
+#define $Pvalve_ 2 \r
+#define time_ 3 \r
+#define $Pi1_ 0 \r
+#define $Pi2_ 1 \r
+\r
+\r
+// define initial state vector as vector of value references\r
+#define STATES { $Pstock_ }\r
+#define STATESDERIVATIVES { $P$DER$Pstock_ }\r
+\r
+\r
+// implementation of the Model Exchange functions\r
+#include "fmu_model_interface.c"\r
+\r
+// Set values for all variables that define a start value\r
+void setDefaultStartValues(ModelInstance *comp) {\r
+\r
+comp->fmuData->modelData.realVarsData[0].attribute.start = 0.0;\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = 0.0;\r
+comp->fmuData->modelData.integerParameterData[0].attribute.start = 1;\r
+comp->fmuData->modelData.integerParameterData[1].attribute.start = 1;\r
+}\r
+// Set values for all variables that define a start value\r
+void setStartValues(ModelInstance *comp) {\r
+\r
+  comp->fmuData->modelData.realVarsData[0].attribute.start =  comp->fmuData->localData[0]->realVars[0];\r
+  comp->fmuData->modelData.realVarsData[1].attribute.start =  comp->fmuData->localData[0]->realVars[1];\r
+  comp->fmuData->modelData.realVarsData[2].attribute.start =  comp->fmuData->localData[0]->realVars[2];\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = comp->fmuData->simulationInfo.realParameter[0];\r
+comp->fmuData->modelData.integerParameterData[0].attribute.start = comp->fmuData->simulationInfo.integerParameter[0];\r
+comp->fmuData->modelData.integerParameterData[1].attribute.start = comp->fmuData->simulationInfo.integerParameter[1];\r
+}\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $Pstock_ : return comp->fmuData->localData[0]->realVars[0]; break;\r
+      case $P$DER$Pstock_ : return comp->fmuData->localData[0]->realVars[1]; break;\r
+      case $Pvalve_ : return comp->fmuData->localData[0]->realVars[2]; break;\r
+      case time_ : return comp->fmuData->simulationInfo.realParameter[0]; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+}\r
+\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value) {\r
+  switch (vr) {\r
+      case $Pstock_ : comp->fmuData->localData[0]->realVars[0]=value; break;\r
+      case $P$DER$Pstock_ : comp->fmuData->localData[0]->realVars[1]=value; break;\r
+      case $Pvalve_ : comp->fmuData->localData[0]->realVars[2]=value; break;\r
+      case time_ : comp->fmuData->simulationInfo.realParameter[0]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $Pi1_ : return comp->fmuData->simulationInfo.integerParameter[0]; break;\r
+      case $Pi2_ : return comp->fmuData->simulationInfo.integerParameter[1]; break;\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value) {\r
+  switch (vr) {\r
+      case $Pi1_ : comp->fmuData->simulationInfo.integerParameter[0]=value; break;\r
+      case $Pi2_ : comp->fmuData->simulationInfo.integerParameter[1]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value) {\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value){\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_functions.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_functions.c
new file mode 100644 (file)
index 0000000..c03781f
--- /dev/null
@@ -0,0 +1,16 @@
+#include "FMUIntegerTestModel_functions.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#define _OMC_LIT0_data "'p"\r
+static const size_t _OMC_LIT0_strlen = 2;\r
+static const char _OMC_LIT0[3] = _OMC_LIT0_data;\r
+#define _OMC_LIT1_data "'p/s"\r
+static const size_t _OMC_LIT1_strlen = 4;\r
+static const char _OMC_LIT1[5] = _OMC_LIT1_data;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_functions.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_functions.h
new file mode 100644 (file)
index 0000000..c0eb9cd
--- /dev/null
@@ -0,0 +1,17 @@
+#ifndef FMUIntegerTestModel__H\r
+#define FMUIntegerTestModel__H\r
+#define omp_get_thread_num() 0\r
+#include "modelica.h"\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <errno.h>\r
+#include "simulation_runtime.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_records.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/FMUIntegerTestModel_records.c
new file mode 100644 (file)
index 0000000..10585d8
--- /dev/null
@@ -0,0 +1,3 @@
+/* Additional record code for FMUIntegerTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#include "meta_modelica.h"\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/_FMUIntegerTestModel.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/_FMUIntegerTestModel.h
new file mode 100644 (file)
index 0000000..1048818
--- /dev/null
@@ -0,0 +1,40 @@
+/* Simulation code for FMUIntegerTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#define time data->localData[0]->timeValue\r
+\r
+/* States */\r
+#define _$Pstock(i) data->localData[i]->realVars[0]\r
+#define $Pstock _$Pstock(0)\r
+#define $P$PRE$Pstock data->simulationInfo.realVarsPre[0]\r
+#define $P$START$Pstock data->modelData.realVarsData[0].attribute.start\r
+#define $Pstock__varInfo data->modelData.realVarsData[0].info\r
+/* StatesDerivatives */\r
+#define _$P$DER$Pstock(i) data->localData[i]->realVars[1]\r
+#define $P$DER$Pstock _$P$DER$Pstock(0)\r
+#define $P$PRE$P$DER$Pstock data->simulationInfo.realVarsPre[1]\r
+#define $P$START$P$DER$Pstock data->modelData.realVarsData[1].attribute.start\r
+#define $P$DER$Pstock__varInfo data->modelData.realVarsData[1].info\r
+/* Algebraic Vars */\r
+#define _$Pvalve(i) data->localData[i]->realVars[2]\r
+#define $Pvalve _$Pvalve(0)\r
+#define $P$PRE$Pvalve data->simulationInfo.realVarsPre[2]\r
+#define $P$START$Pvalve data->modelData.realVarsData[2].attribute.start\r
+#define $Pvalve__varInfo data->modelData.realVarsData[2].info\r
+/* Algebraic Parameter */\r
+#define time data->simulationInfo.realParameter[0]\r
+#define $P$STARTtime data->modelData.realParameterData[0].attribute.start\r
+#define time__varInfo data->modelData.realParameterData[0].info\r
+/* External Objects */\r
+/* Algebraic Integer Vars */\r
+/* Algebraic Integer Parameter */\r
+#define $Pi1 data->simulationInfo.integerParameter[0]\r
+#define $P$START$Pi1 data->modelData.integerParameterData[0].attribute.start\r
+#define $Pi1__varInfo data->modelData.integerParameterData[0].info\r
+#define $Pi2 data->simulationInfo.integerParameter[1]\r
+#define $P$START$Pi2 data->modelData.integerParameterData[1].attribute.start\r
+#define $Pi2__varInfo data->modelData.integerParameterData[1].info\r
+/* Algebraic Boolean Vars */\r
+/* Algebraic Boolean Parameters */\r
+/* Algebraic String Variables */\r
+/* Algebraic String Parameter */\r
+/* Jacobian Variables */\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/modelDescription.xml b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUIntegerTest/modelDescription.xml
new file mode 100644 (file)
index 0000000..60ef85d
--- /dev/null
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="FMUIntegerTestModel"\r
+  modelIdentifier="FMUIntegerTestModel"\r
+  guid="{2d294e78-8670-49d1-89de-38199246249e}"\r
+  generationTool="OpenModelica Compiler 1.8.1+ (r11690)"\r
+  generationDateAndTime="2012-05-10T10:10:54Z"\r
+  variableNamingConvention="structured"\r
+  numberOfContinuousStates="1"\r
+  numberOfEventIndicators="0">\r
+  <ModelVariables>\r
+  <ScalarVariable\r
+    name="stock"\r
+    valueReference="0"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stock)"\r
+    valueReference="1"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valve"\r
+    valueReference="2"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="time"\r
+    valueReference="3"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="i1"\r
+    valueReference="0"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Integer/>\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="i2"\r
+    valueReference="1"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Integer/>\r
+  </ScalarVariable>\r
+  </ModelVariables>\r
+</fmiModelDescription>\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTest.mo b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTest.mo
new file mode 100644 (file)
index 0000000..986ef25
--- /dev/null
@@ -0,0 +1,10 @@
+model FMURealTestModel\r
+       parameter Real r1 = 1.0;\r
+       parameter Real r2 = 1.0;\r
+       Real valve;\r
+       Real stock(start=0.0,fixed=true);\r
+       parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+equation\r
+       valve = if initial() or r1 < 0 or r1 >= 0 then (r1 + r2) else pre(valve);\r
+       der(stock) = valve;\r
+end FMURealTestModel;
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTest.mos b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTest.mos
new file mode 100644 (file)
index 0000000..e76e578
--- /dev/null
@@ -0,0 +1,2 @@
+loadFile("FMURealTest.mo");\r
+translateModelFMU(FMURealTestModel)
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.c
new file mode 100644 (file)
index 0000000..7c90624
--- /dev/null
@@ -0,0 +1,364 @@
+/* Simulation code for FMURealTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "simulation_runtime.h"\r
+#include "omc_error.h"\r
+\r
+#include <assert.h>\r
+#include <string.h>\r
+\r
+#include "FMURealTestModel_functions.h"\r
+\r
+#include "_FMURealTestModel.h"\r
+#include "FMURealTestModel_functions.c"\r
+/* dummy VARINFO and FILEINFO */\r
+const FILE_INFO dummyFILE_INFO = {"",-1,-1,-1,-1,1};\r
+const VAR_INFO dummyVAR_INFO = {-1,"","",(FILE_INFO){"",-1,-1,-1,-1,1}};\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef _OMC_MEASURE_TIME\r
+int measure_time_flag = 1;\r
+#else\r
+int measure_time_flag = 0;\r
+#endif\r
+\r
+void setupDataStruc(DATA *data)\r
+{\r
+  ASSERT(data,"Error while initialize Data");\r
+  data->modelData.modelName = "FMURealTestModel";\r
+  data->modelData.modelFilePrefix = "FMURealTestModel";\r
+  data->modelData.modelDir = "";\r
+  data->modelData.modelGUID = "{7cae105e-c592-4723-8ae7-041b2a1231d7}";\r
+  \r
+  data->modelData.nStates = 1;\r
+  data->modelData.nVariablesReal = 2*1+1;\r
+  data->modelData.nVariablesInteger = 0;\r
+  data->modelData.nVariablesBoolean = 0;\r
+  data->modelData.nVariablesString = 0;\r
+  data->modelData.nParametersReal = 3;\r
+  data->modelData.nParametersInteger = 0;\r
+  data->modelData.nParametersBoolean = 0;\r
+  data->modelData.nParametersString = 0;\r
+  data->modelData.nInputVars = 0;\r
+  data->modelData.nOutputVars = 0;\r
+  data->modelData.nJacobians = 4;\r
+  data->modelData.nHelpVars = 0;\r
+  \r
+  data->modelData.nAliasReal = 0;\r
+  data->modelData.nAliasInteger = 0;\r
+  data->modelData.nAliasBoolean = 0;\r
+  data->modelData.nAliasString = 0;\r
+  \r
+  data->modelData.nZeroCrossings = 0;\r
+  data->modelData.nSamples = 0;\r
+  data->modelData.nInitEquations = 0;\r
+  data->modelData.nResiduals = 1;\r
+  data->modelData.nExtObjs = 0;\r
+  data->modelData.nFunctions = 0;\r
+  data->modelData.nEquations = 4;\r
+  \r
+  data->modelData.nDelayExpressions = 0;\r
+  \r
+}\r
+\r
+void setupDataStruc2(DATA *data)\r
+{\r
+  const struct FUNCTION_INFO funcInfo[1] = {{-1,"",omc_dummyFileInfo}};\r
+  memcpy(data->modelData.functionNames, &funcInfo, data->modelData.nFunctions*sizeof(FUNCTION_INFO));\r
+  \r
+  const VAR_INFO** equationInfo_cref1 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref1[0] = &$Pvalve__varInfo;\r
+  const VAR_INFO** equationInfo_cref3 = (const VAR_INFO**)calloc(1,sizeof(VAR_INFO*));\r
+  equationInfo_cref3[0] = &$P$DER$Pstock__varInfo;\r
+  const struct EQUATION_INFO equationInfo[4] = {\r
+    {1003,"SES_ALGORITHM 0", 0, NULL},\r
+    {1004,"SES_SIMPLE_ASSIGN 1",1,equationInfo_cref1},\r
+    {1005,"SES_ALGORITHM 2", 0, NULL},\r
+    {1006,"SES_SIMPLE_ASSIGN 3",1,equationInfo_cref3}\r
+  };\r
+  const int n_omc_equationInfo_reverse_prof_index = 0;\r
+  const int omc_equationInfo_reverse_prof_index[] = {\r
+    \r
+  };\r
+  memcpy(data->modelData.equationInfo, &equationInfo, data->modelData.nEquations*sizeof(EQUATION_INFO));\r
+  \r
+  data->modelData.nProfileBlocks = n_omc_equationInfo_reverse_prof_index;\r
+  data->modelData.equationInfo_reverse_prof_index = (int*) malloc(data->modelData.nProfileBlocks*sizeof(int));\r
+  memcpy(data->modelData.equationInfo_reverse_prof_index, omc_equationInfo_reverse_prof_index, data->modelData.nProfileBlocks*sizeof(int));\r
+}\r
+\r
+/* Has to be performed after _init.xml file has been read */\r
+void callExternalObjectConstructors(DATA *data)\r
+{\r
+  state mem_state;\r
+  mem_state = get_memory_state();\r
+  /* data->simulationInfo.extObjs = NULL; */\r
+}\r
+\r
+void callExternalObjectDestructors(DATA *data)\r
+{\r
+  if (data->simulationInfo.extObjs) {\r
+    free(data->simulationInfo.extObjs);\r
+    data->simulationInfo.extObjs = 0;\r
+  }\r
+}\r
+\r
+\r
+int input_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+int output_function(DATA *data)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* Initializes the raw time events of the simulation using the now\r
+   calcualted parameters. */\r
+void function_sampleInit(DATA *data)\r
+{\r
+}\r
+\r
+int function_updateSample(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_storeDelayed(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundStartValues(DATA *data)\r
+{\r
+\r
+  \r
+  DEBUG_INFO(LOG_INIT, "updating start-values:");\r
+  \r
+  return 0;\r
+}\r
+\r
+int initial_residual(DATA *data, double $P$_lambda, double* initialResiduals)\r
+{\r
+  int i = 0;\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  DEBUG_INFO(LOG_RES_INIT, "updating initial_residuals:");\r
+  initialResiduals[i++] = ((1.0 - $P$_lambda) * ($Pstock - $P$START$Pstock));\r
+  DEBUG_INFO_AL2(LOG_RES_INIT, "   residual[%d] : (1.0 - $_lambda) * (stock - $_start(stock)) = %f", i, initialResiduals[i-1]);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int updateBoundParameters(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_0(DATA *data) {\r
+  modelica_boolean tmp0;\r
+  modelica_boolean tmp1;\r
+  modelica_boolean tmp2;\r
+  /*#modelicaLine [FMURealTest.mo:8:2-8:74]*/\r
+  tmp0 = initial();\r
+  RELATIONTOZC(tmp1, $Pr1, 0.0, -1,Less,<);\r
+  RELATIONTOZC(tmp2, $Pr1, 0.0, -1,GreaterEq,>=);\r
+  $Pvalve = (((tmp0 || tmp1) || tmp2)?($Pr1 + $Pr2):$P$PRE$Pvalve); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_1(DATA *data) {\r
+  /*#modelicaLine [FMURealTest.mo:9:2-9:20]*/\r
+  $P$DER$Pstock = $Pvalve; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+static void functionODE_system0(DATA *data,int omc_thread_number)\r
+{\r
+  eqFunction_0(data);\r
+  eqFunction_1(data);\r
+}\r
+static void (*functionODE_systems[1])(DATA *, int) = {\r
+  functionODE_system0\r
+};\r
+\r
+void function_initMemoryState()\r
+{\r
+  push_memory_states(1);\r
+}\r
+\r
+int functionODE(DATA *data)\r
+{\r
+  int id,th_id;\r
+  state mem_state; /* We need to have separate memory pools for separate systems... */\r
+  mem_state = get_memory_state();\r
+  for (id=0; id<1; id++) {\r
+    th_id = omp_get_thread_num();\r
+    functionODE_systems[id](data,th_id);\r
+  }\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+#include <simulation_inline_solver.h>\r
+const char *_omc_force_solver=_OMC_FORCE_SOLVER;\r
+const int inline_work_states_ndims=_OMC_SOLVER_WORK_STATES_NDIMS;\r
+int functionODE_inline(DATA* data, double stepSize)\r
+{\r
+  return 0;\r
+}\r
+\r
+/* for continuous time variables */\r
+int functionAlgebraics(DATA *data)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+\r
+void eqFunction_2(DATA *data) {\r
+  modelica_boolean tmp4;\r
+  modelica_boolean tmp5;\r
+  modelica_boolean tmp6;\r
+  /*#modelicaLine [FMURealTest.mo:8:2-8:74]*/\r
+  tmp4 = initial();\r
+  SAVEZEROCROSS(tmp5, $Pr1, 0.0, -1,Less,<);\r
+  SAVEZEROCROSS(tmp6, $Pr1, 0.0, -1,GreaterEq,>=);\r
+  $Pvalve = (((tmp4 || tmp5) || tmp6)?($Pr1 + $Pr2):$P$PRE$Pvalve); \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+\r
+void eqFunction_3(DATA *data) {\r
+  /*#modelicaLine [FMURealTest.mo:9:2-9:20]*/\r
+  $P$DER$Pstock = $Pvalve; \r
+  /*#endModelicaLine*/\r
+}\r
+\r
+int functionDAE(DATA *data, int *needToIterate)\r
+{\r
+  state mem_state;\r
+  *needToIterate = 0;\r
+  \r
+  mem_state = get_memory_state();\r
+  eqFunction_2(data);\r
+  eqFunction_3(data);\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int function_onlyZeroCrossings(DATA *data, double *gout,double *t)\r
+{\r
+  state mem_state;\r
+  \r
+  mem_state = get_memory_state();\r
+  restore_memory_state(mem_state);\r
+  \r
+  return 0;\r
+}\r
+\r
+int checkForDiscreteChanges(DATA *data)\r
+{\r
+  int needToIterate = 0;\r
+\r
+  \r
+  return needToIterate;\r
+}\r
+\r
+/* function to check assert after a step is done */\r
+int checkForAsserts(DATA *data)\r
+{\r
+\r
+  \r
+  return 0;\r
+}\r
+\r
+ int initialAnalyticJacobianA(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianB(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianC(DATA* data){\r
+    return 1;\r
+ }\r
+\r
+ int initialAnalyticJacobianD(DATA* data){\r
+    return 1;\r
+ }\r
+ int functionJacA(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacB(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacC(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+ int functionJacD(DATA* data, double* jac){\r
+    return 0;\r
+ }\r
+\r
+const char *linear_model_frame =\r
+  "model linear_FMURealTestModel\n  parameter Integer n = 1; // states \n  parameter Integer k = 0; // top-level inputs \n  parameter Integer l = 0; // top-level outputs \n"\r
+  "  parameter Real x0[1] = {%s};\n"\r
+  "  parameter Real u0[0] = {%s};\n"\r
+  "  parameter Real A[1,1] = [%s];\n"\r
+  "  parameter Real B[1,0] = zeros(1,0);%s\n"\r
+  "  parameter Real C[0,1] = zeros(0,1);%s\n"\r
+  "  parameter Real D[0,0] = zeros(0,0);%s\n"\r
+  "  Real x[1](start=x0);\n"\r
+  "  input Real u[0];\n"\r
+  "  output Real y[0];\n"\r
+  "\n  Real x_Pstock = x[1];\n      \n"\r
+  "equation\n  der(x) = A * x + B * u;\n  y = C * x + D * u;\nend linear_FMURealTestModel;\n"\r
+;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+/* forward the main in the simulation runtime */\r
+extern int _main_SimulationRuntime(int argc, char**argv, DATA *data);\r
+\r
+/* call the simulation runtime main from our main! */\r
+int main(int argc, char**argv)\r
+{\r
+  DATA data;\r
+  setupDataStruc(&data);\r
+  return _main_SimulationRuntime(argc, argv, &data);\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.dll b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.dll
new file mode 100644 (file)
index 0000000..26fbfce
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.dll differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.fmu b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.fmu
new file mode 100644 (file)
index 0000000..097ed6c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.fmu differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.lib b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.lib
new file mode 100644 (file)
index 0000000..ae85129
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel.lib differ
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_FMU.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_FMU.c
new file mode 100644 (file)
index 0000000..facd7f6
--- /dev/null
@@ -0,0 +1,159 @@
+\r
+// define class name and unique id\r
+#define MODEL_IDENTIFIER FMURealTestModel\r
+#define MODEL_GUID "{7cae105e-c592-4723-8ae7-041b2a1231d7}"\r
+\r
+// include fmu header files, typedefs and macros\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+#include "openmodelica.h"\r
+#include "openmodelica_func.h"\r
+#include "simulation_data.h"\r
+#include "omc_error.h"\r
+#include "fmiModelTypes.h"\r
+#include "fmiModelFunctions.h"\r
+#include "FMURealTestModel_functions.h"\r
+#include "initialization.h"\r
+#include "events.h"\r
+#include "fmu_model_interface.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+void setStartValues(ModelInstance *comp);\r
+void setDefaultStartValues(ModelInstance *comp);\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo);\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value);\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value);\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value);\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr);\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value);\r
+\r
+// define model size\r
+#define NUMBER_OF_STATES 1\r
+#define NUMBER_OF_EVENT_INDICATORS 0\r
+#define NUMBER_OF_REALS 6\r
+#define NUMBER_OF_INTEGERS 0\r
+#define NUMBER_OF_STRINGS 0\r
+#define NUMBER_OF_BOOLEANS 0\r
+#define NUMBER_OF_EXTERNALFUNCTIONS 0\r
+\r
+// define variable data for model\r
+#define $Pstock_ 0 \r
+#define $P$DER$Pstock_ 1 \r
+#define $Pvalve_ 2 \r
+#define $Pr1_ 3 \r
+#define $Pr2_ 4 \r
+#define time_ 5 \r
+\r
+\r
+// define initial state vector as vector of value references\r
+#define STATES { $Pstock_ }\r
+#define STATESDERIVATIVES { $P$DER$Pstock_ }\r
+\r
+\r
+// implementation of the Model Exchange functions\r
+#include "fmu_model_interface.c"\r
+\r
+// Set values for all variables that define a start value\r
+void setDefaultStartValues(ModelInstance *comp) {\r
+\r
+comp->fmuData->modelData.realVarsData[0].attribute.start = 0.0;\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = 1.0;\r
+comp->fmuData->modelData.realParameterData[1].attribute.start = 1.0;\r
+comp->fmuData->modelData.realParameterData[2].attribute.start = 0.0;\r
+}\r
+// Set values for all variables that define a start value\r
+void setStartValues(ModelInstance *comp) {\r
+\r
+  comp->fmuData->modelData.realVarsData[0].attribute.start =  comp->fmuData->localData[0]->realVars[0];\r
+  comp->fmuData->modelData.realVarsData[1].attribute.start =  comp->fmuData->localData[0]->realVars[1];\r
+  comp->fmuData->modelData.realVarsData[2].attribute.start =  comp->fmuData->localData[0]->realVars[2];\r
+comp->fmuData->modelData.realParameterData[0].attribute.start = comp->fmuData->simulationInfo.realParameter[0];\r
+comp->fmuData->modelData.realParameterData[1].attribute.start = comp->fmuData->simulationInfo.realParameter[1];\r
+comp->fmuData->modelData.realParameterData[2].attribute.start = comp->fmuData->simulationInfo.realParameter[2];\r
+}\r
+// Used to set the next time event, if any.\r
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {\r
+}\r
+\r
+fmiReal getReal(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      case $Pstock_ : return comp->fmuData->localData[0]->realVars[0]; break;\r
+      case $P$DER$Pstock_ : return comp->fmuData->localData[0]->realVars[1]; break;\r
+      case $Pvalve_ : return comp->fmuData->localData[0]->realVars[2]; break;\r
+      case $Pr1_ : return comp->fmuData->simulationInfo.realParameter[0]; break;\r
+      case $Pr2_ : return comp->fmuData->simulationInfo.realParameter[1]; break;\r
+      case time_ : return comp->fmuData->simulationInfo.realParameter[2]; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+}\r
+\r
+fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value) {\r
+  switch (vr) {\r
+      case $Pstock_ : comp->fmuData->localData[0]->realVars[0]=value; break;\r
+      case $P$DER$Pstock_ : comp->fmuData->localData[0]->realVars[1]=value; break;\r
+      case $Pvalve_ : comp->fmuData->localData[0]->realVars[2]=value; break;\r
+      case $Pr1_ : comp->fmuData->simulationInfo.realParameter[0]=value; break;\r
+      case $Pr2_ : comp->fmuData->simulationInfo.realParameter[1]=value; break;\r
+      case time_ : comp->fmuData->simulationInfo.realParameter[2]=value; break;\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value) {\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value) {\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+fmiString getString(ModelInstance* comp, const fmiValueReference vr) {\r
+  switch (vr) {\r
+      default:\r
+          return 0;\r
+  }\r
+}\r
+\r
+fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value){\r
+  switch (vr) {\r
+      default:\r
+          return fmiError;\r
+  }\r
+  return fmiOK;\r
+}\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_functions.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_functions.c
new file mode 100644 (file)
index 0000000..3f150b1
--- /dev/null
@@ -0,0 +1,16 @@
+#include "FMURealTestModel_functions.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+#define _OMC_LIT0_data "'p"\r
+static const size_t _OMC_LIT0_strlen = 2;\r
+static const char _OMC_LIT0[3] = _OMC_LIT0_data;\r
+#define _OMC_LIT1_data "'p/s"\r
+static const size_t _OMC_LIT1_strlen = 4;\r
+static const char _OMC_LIT1[5] = _OMC_LIT1_data;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_functions.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_functions.h
new file mode 100644 (file)
index 0000000..1dedb2a
--- /dev/null
@@ -0,0 +1,17 @@
+#ifndef FMURealTestModel__H\r
+#define FMURealTestModel__H\r
+#define omp_get_thread_num() 0\r
+#include "modelica.h"\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <errno.h>\r
+#include "simulation_runtime.h"\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_records.c b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/FMURealTestModel_records.c
new file mode 100644 (file)
index 0000000..8cfdfcf
--- /dev/null
@@ -0,0 +1,3 @@
+/* Additional record code for FMURealTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#include "meta_modelica.h"\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/_FMURealTestModel.h b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/_FMURealTestModel.h
new file mode 100644 (file)
index 0000000..ede4615
--- /dev/null
@@ -0,0 +1,40 @@
+/* Simulation code for FMURealTestModel generated by the OpenModelica Compiler 1.8.1+ (r11690). */\r
+#define time data->localData[0]->timeValue\r
+\r
+/* States */\r
+#define _$Pstock(i) data->localData[i]->realVars[0]\r
+#define $Pstock _$Pstock(0)\r
+#define $P$PRE$Pstock data->simulationInfo.realVarsPre[0]\r
+#define $P$START$Pstock data->modelData.realVarsData[0].attribute.start\r
+#define $Pstock__varInfo data->modelData.realVarsData[0].info\r
+/* StatesDerivatives */\r
+#define _$P$DER$Pstock(i) data->localData[i]->realVars[1]\r
+#define $P$DER$Pstock _$P$DER$Pstock(0)\r
+#define $P$PRE$P$DER$Pstock data->simulationInfo.realVarsPre[1]\r
+#define $P$START$P$DER$Pstock data->modelData.realVarsData[1].attribute.start\r
+#define $P$DER$Pstock__varInfo data->modelData.realVarsData[1].info\r
+/* Algebraic Vars */\r
+#define _$Pvalve(i) data->localData[i]->realVars[2]\r
+#define $Pvalve _$Pvalve(0)\r
+#define $P$PRE$Pvalve data->simulationInfo.realVarsPre[2]\r
+#define $P$START$Pvalve data->modelData.realVarsData[2].attribute.start\r
+#define $Pvalve__varInfo data->modelData.realVarsData[2].info\r
+/* Algebraic Parameter */\r
+#define $Pr1 data->simulationInfo.realParameter[0]\r
+#define $P$START$Pr1 data->modelData.realParameterData[0].attribute.start\r
+#define $Pr1__varInfo data->modelData.realParameterData[0].info\r
+#define $Pr2 data->simulationInfo.realParameter[1]\r
+#define $P$START$Pr2 data->modelData.realParameterData[1].attribute.start\r
+#define $Pr2__varInfo data->modelData.realParameterData[1].info\r
+#define time data->simulationInfo.realParameter[2]\r
+#define $P$STARTtime data->modelData.realParameterData[2].attribute.start\r
+#define time__varInfo data->modelData.realParameterData[2].info\r
+/* External Objects */\r
+/* Algebraic Integer Vars */\r
+/* Algebraic Integer Parameter */\r
+/* Algebraic Boolean Vars */\r
+/* Algebraic Boolean Parameters */\r
+/* Algebraic String Variables */\r
+/* Algebraic String Parameter */\r
+/* Jacobian Variables */\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/modelDescription.xml b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMURealTest/modelDescription.xml
new file mode 100644 (file)
index 0000000..93a288c
--- /dev/null
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<fmiModelDescription\r
+  fmiVersion="1.0"\r
+  modelName="FMURealTestModel"\r
+  modelIdentifier="FMURealTestModel"\r
+  guid="{7cae105e-c592-4723-8ae7-041b2a1231d7}"\r
+  generationTool="OpenModelica Compiler 1.8.1+ (r11690)"\r
+  generationDateAndTime="2012-05-10T10:57:43Z"\r
+  variableNamingConvention="structured"\r
+  numberOfContinuousStates="1"\r
+  numberOfEventIndicators="0">\r
+  <ModelVariables>\r
+  <ScalarVariable\r
+    name="stock"\r
+    valueReference="0"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="der(stock)"\r
+    valueReference="1"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="valve"\r
+    valueReference="2"\r
+    variability="continuous"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real   />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="r1"\r
+    valueReference="3"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="1.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="r2"\r
+    valueReference="4"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="1.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  <ScalarVariable\r
+    name="time"\r
+    valueReference="5"\r
+    variability="parameter"\r
+    causality="internal"\r
+    alias="noAlias">\r
+    <Real start="0.0" fixed="true"  />\r
+  </ScalarVariable>\r
+  </ModelVariables>\r
+</fmiModelDescription>\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUUnitTestModel.fmu b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUUnitTestModel.fmu
new file mode 100644 (file)
index 0000000..2b91065
Binary files /dev/null and b/1.8/org.simantics.sysdyn.tests/Models/FMUTests/FMUUnitTestModel.fmu differ
diff --git a/1.8/org.simantics.sysdyn.tests/SCLTests.launch b/1.8/org.simantics.sysdyn.tests/SCLTests.launch
new file mode 100644 (file)
index 0000000..993ac42
--- /dev/null
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>\r
+<launchConfiguration type="org.eclipse.pde.ui.JunitLaunchConfig">\r
+<booleanAttribute key="append.args" value="true"/>\r
+<stringAttribute key="application" value="org.eclipse.pde.junit.runtime.coretestapplication"/>\r
+<booleanAttribute key="askclear" value="true"/>\r
+<booleanAttribute key="automaticAdd" value="true"/>\r
+<booleanAttribute key="automaticValidate" value="false"/>\r
+<stringAttribute key="bad_container_name" value="\org.simantics.sysdyn.tests\SCLTests.launch"/>\r
+<stringAttribute key="bootstrap" value=""/>\r
+<stringAttribute key="checked" value="[NONE]"/>\r
+<booleanAttribute key="clearConfig" value="true"/>\r
+<booleanAttribute key="clearws" value="true"/>\r
+<booleanAttribute key="clearwslog" value="false"/>\r
+<stringAttribute key="configLocation" value="${workspace_loc}/.metadata/.plugins/org.eclipse.pde.core/pde-junit"/>\r
+<booleanAttribute key="default" value="true"/>\r
+<booleanAttribute key="includeOptional" value="true"/>\r
+<stringAttribute key="location" value="${workspace_loc}/../junit-workspace"/>\r
+<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">\r
+<listEntry value="/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scl/SCLTests.java"/>\r
+</listAttribute>\r
+<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">\r
+<listEntry value="1"/>\r
+</listAttribute>\r
+<stringAttribute key="org.eclipse.jdt.junit.CONTAINER" value=""/>\r
+<booleanAttribute key="org.eclipse.jdt.junit.KEEPRUNNING_ATTR" value="true"/>\r
+<stringAttribute key="org.eclipse.jdt.junit.TESTNAME" value=""/>\r
+<stringAttribute key="org.eclipse.jdt.junit.TEST_KIND" value="org.eclipse.jdt.junit.loader.junit4"/>\r
+<stringAttribute key="org.eclipse.jdt.launching.JRE_CONTAINER" value="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.simantics.sysdyn.tests.scl.SCLTests"/>\r
+<stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl} -consoleLog"/>\r
+<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="org.simantics.sysdyn.tests"/>\r
+<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.pde.ui.workbenchClasspathProvider"/>\r
+<stringAttribute key="pde.version" value="3.3"/>\r
+<stringAttribute key="product" value="org.simantics.sysdyn.ui.product"/>\r
+<booleanAttribute key="run_in_ui_thread" value="true"/>\r
+<booleanAttribute key="show_selected_only" value="false"/>\r
+<booleanAttribute key="tracing" value="false"/>\r
+<booleanAttribute key="useCustomFeatures" value="false"/>\r
+<booleanAttribute key="useDefaultConfig" value="true"/>\r
+<booleanAttribute key="useDefaultConfigArea" value="false"/>\r
+<booleanAttribute key="useProduct" value="false"/>\r
+</launchConfiguration>\r
diff --git a/1.8/org.simantics.sysdyn.tests/build.properties b/1.8/org.simantics.sysdyn.tests/build.properties
new file mode 100644 (file)
index 0000000..098add7
--- /dev/null
@@ -0,0 +1,5 @@
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               Models/\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/Activator.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/Activator.java
new file mode 100644 (file)
index 0000000..aadaff3
--- /dev/null
@@ -0,0 +1,30 @@
+package org.simantics.sysdyn.tests;\r
+\r
+import org.osgi.framework.BundleActivator;\r
+import org.osgi.framework.BundleContext;\r
+\r
+public class Activator implements BundleActivator {\r
+\r
+       private static BundleContext context;\r
+\r
+       static BundleContext getContext() {\r
+               return context;\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)\r
+        */\r
+       public void start(BundleContext bundleContext) throws Exception {\r
+               Activator.context = bundleContext;\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)\r
+        */\r
+       public void stop(BundleContext bundleContext) throws Exception {\r
+               Activator.context = null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/CallFMUBeforeInitializationTests.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/CallFMUBeforeInitializationTests.java
new file mode 100644 (file)
index 0000000..c3974d9
--- /dev/null
@@ -0,0 +1,229 @@
+package org.simantics.sysdyn.tests.fmi;\r
+\r
+import static org.junit.Assert.fail;\r
+import junit.framework.Assert;\r
+\r
+import org.junit.Test;\r
+import org.simantics.modelica.fmi.FMUControlJNI;\r
+import org.simantics.modelica.fmi.FMUJNIException;\r
+\r
+/**\r
+ * Tests calls to fmu control before model has been loaded or initialized.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class CallFMUBeforeInitializationTests {\r
+       \r
+       /**\r
+        * Try fmu jni methods without loading an fmu.\r
+        * All but unload should throw an exception.\r
+        */\r
+       @Test\r
+       public void testBeforeLoad() {\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               try {\r
+                       control.initializeSimulation();\r
+                       fail("Initialized a simulation before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: Tried to initialize simulation before loading it\r
+               }\r
+               \r
+               try {\r
+                       control.getAllVariables();\r
+                       fail("getAllVariables returned something before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There is no model to get the variables from\r
+               }\r
+               \r
+               try {\r
+                       control.filterVariables(".*");\r
+                       fail("filterVariables returned something before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There is no model to get the variables from\r
+               }\r
+               \r
+               try {\r
+                       double d = control.getRealValue("dummy");\r
+                       fail("Got a Real value before loading fmu: " + d);\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There are no variables\r
+               }\r
+               \r
+               try {\r
+                       control.getSubscribedResults(new double[0]);\r
+                       fail("Got subscribed results before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There is no model or subscription\r
+               }\r
+               \r
+               try {\r
+                       control.setBooleanValue("dummy", true);\r
+                       fail("Set a boolean value  before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There are no variables\r
+               }\r
+               \r
+               try {\r
+                       control.setRealValue("dummy", 1.0);\r
+                       fail("Set a real value  before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There are no variables\r
+               }\r
+               \r
+               try {\r
+                       control.setIntegerValue("dummy", 1);\r
+                       fail("Set an integer value  before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There are no variables\r
+               }\r
+               \r
+               try {\r
+                       control.setStepLength(0.1);\r
+                       fail("Set step length before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There is no model for which to set the step length\r
+               }\r
+               \r
+               try {\r
+                       control.simulateStep();\r
+                       fail("Simulated a step before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There is no model to simulate\r
+               }\r
+               \r
+               try {\r
+                       control.subscribe(new String[] {"dummy"});\r
+                       fail("Subscribed variables before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There is no model to subscribe from\r
+               }\r
+               \r
+               \r
+               // succeeds\r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       // control should NOT throw this exception: Unload only unloads if something has been loaded\r
+                       fail(e.getMessage());\r
+               }\r
+               \r
+       }\r
+       \r
+       /*\r
+        * Test:\r
+        * Load a valid fmu, but do not initialize it. Test that all\r
+        * methods work as they are supposed to. Some throw exceptions while\r
+        * others work.\r
+        */\r
+       @Test\r
+       public void testBeforeInitialization() {\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMUAllTypesOfVariablesTest\\FMUAllTypesOfVariablesTestModel.fmu";\r
+\r
+               // Initialize a model\r
+               try {\r
+\r
+                       control.loadFMUFile(path);\r
+               } catch (FMUJNIException e) {\r
+                       fail("FMU loading failed");\r
+               }\r
+               \r
+               // Fails\r
+               \r
+               try {\r
+                       double d = control.getRealValue("dummy");\r
+                       fail("Got a Real value before loading fmu: " + d);\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There are no variables\r
+               }\r
+               \r
+               try {\r
+                       control.setBooleanValue("dummy", true);\r
+                       fail("Set a boolean value  before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There are no variables\r
+               }\r
+               \r
+               try {\r
+                       control.setRealValue("dummy", 1.0);\r
+                       fail("Set a real value  before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There are no variables\r
+               }\r
+               \r
+               try {\r
+                       control.setIntegerValue("dummy", 1);\r
+                       fail("Set an integer value  before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There are no variables\r
+               }\r
+               \r
+               try {\r
+                       control.simulateStep();\r
+                       fail("Simulated a step before loading fmu");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: There is no model to simulate\r
+               }\r
+               \r
+\r
+               \r
+               // Succeeds\r
+               try {\r
+                       control.setStepLength(0.1);\r
+               } catch (FMUJNIException e) {\r
+                       // control should NOT throw this exception: simulation step length can be set\r
+                       // beforehand for future simulations\r
+                       fail(e.getMessage());\r
+               }\r
+               \r
+               try {\r
+                       control.getAllVariables();\r
+               } catch (FMUJNIException e) {\r
+                       // control should NOT throw this exception: Variables are found in loadFMU\r
+                       fail(e.getMessage());\r
+               }\r
+               \r
+               try {\r
+                       control.filterVariables(".*");\r
+               } catch (FMUJNIException e) {\r
+                       // control should NOT throw this exception: Variables are found in loadFMU\r
+                       fail(e.getMessage());\r
+               }\r
+               \r
+               \r
+               try {\r
+                       double[] array = new double[0];\r
+                       control.getSubscribedResults(array);\r
+                       Assert.assertTrue("Returned a wrong kind of array", array.length == 0);\r
+               } catch (FMUJNIException e) {\r
+                       // control should NOT throw this exception: Should return the given double\r
+                       // array filled with subscribed values or 0.0 if there was some problem\r
+                       fail(e.getMessage());\r
+               }\r
+               \r
+               try {\r
+                       control.subscribe(new String[] {"dummy"});\r
+               } catch (FMUJNIException e) {\r
+                       // control should NOT throw this exception: users can subscribe before initialization\r
+                       fail(e.getMessage());\r
+               }\r
+               \r
+               \r
+               try {\r
+                       control.initializeSimulation();\r
+               } catch (FMUJNIException e) {\r
+                       fail(e.getMessage());\r
+                       // control should NOT throw this exception\r
+               }\r
+               \r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       // control should NOT throw this exception\r
+                       fail(e.getMessage());\r
+               }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUBooleanTest.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUBooleanTest.java
new file mode 100644 (file)
index 0000000..1ba9423
--- /dev/null
@@ -0,0 +1,194 @@
+package org.simantics.sysdyn.tests.fmi;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+\r
+import junit.framework.Assert;\r
+\r
+import org.junit.Test;\r
+import org.simantics.modelica.fmi.FMUControlJNI;\r
+import org.simantics.modelica.fmi.FMUJNIException;\r
+\r
+/**\r
+ * Tests that a boolean value can be changed, erroneous values and variables are detected\r
+ * and the change is propagated to the rest of the model.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FMUBooleanTest {\r
+       \r
+       @Test\r
+       public void testSetBoolean() {\r
+               \r
+               /*\r
+               Below is the model used for testing. \r
+               Model is located in Models\FMUTests\FMUBooleanTest \r
+               \r
+               model FMUBooleanTestModel\r
+                       parameter Boolean b = true;\r
+                       Real valve;\r
+                       Real stock(start=0.0,fixed=true);\r
+                       parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+               equation\r
+                       valve = if initial() or b or not b then (if b then 1 else -1) else pre(valve);\r
+                       der(stock) = valve;\r
+               end FMUBooleanTestModel;\r
+               \r
+               \r
+               The condition for valve is automatically generated in sysdyn. It is a hack for getting \r
+               valve to notice a change in b. \r
+                */\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMUBooleanTest\\FMUBooleanTestModel.fmu";\r
+\r
+\r
+               try {\r
+\r
+                       control.loadFMUFile(path);\r
+\r
+                       control.setStepLength(0.1);\r
+\r
+                       control.initializeSimulation();\r
+\r
+\r
+                       String[] s = control.getAllVariables();\r
+                       List<String> nameList = Arrays.asList(s);\r
+                       int valve = nameList.indexOf("valve");\r
+                       int stock = nameList.indexOf("stock");\r
+                       control.subscribe(s);\r
+\r
+                       /*\r
+                        * Simulate the model for time 0 - 3 with b == true\r
+                        *     => stock == 3 when time == 3\r
+                        *     \r
+                        * Change b to false and simulate to time == 6\r
+                        *     => stock == 0 when time == 6 \r
+                        */\r
+                       double value;\r
+                       double[] results = new double[s.length];\r
+                       for(int i = 0; i < 60; i++) {\r
+                               results = control.getSubscribedResults(results);\r
+\r
+                               if(i == 30) {\r
+                                       value = results[stock];\r
+                                       Assert.assertFalse("stock != 3 when time == 3. (stock == " + value + ")",  value < 2.999 || value > 3.001);\r
+                                       control.setBooleanValue("b", false);\r
+                               }\r
+                               \r
+                               value = results[valve];\r
+                               if(i > 30) {\r
+                                       Assert.assertFalse("valve != -1 after time == 3. (valve == " + value + ")",  value > -0.999 || value < -1.001);\r
+                               } else {\r
+                                       Assert.assertFalse("valve != 1 before time == 3. (valve == " + value + ")",  value < 0.999 || value > 1.001);\r
+\r
+                               }\r
+                               control.simulateStep();\r
+                       }\r
+                       \r
+                       results = control.getSubscribedResults(results);\r
+                       value = results[stock];\r
+                       Assert.assertFalse("stock != 0 when time == 6. (stock == " + value + ")",  value < -0.001 || value > 0.001);\r
+                       \r
+                       \r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+               \r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+       \r
+       @Test\r
+       public void testSetBooleanErrors() {\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMUAllTypesOfVariablesTest\\FMUAllTypesOfVariablesTestModel.fmu";\r
+\r
+               // Initialize a model\r
+               try {\r
+\r
+                       control.loadFMUFile(path);\r
+\r
+                       control.loadFMUFile(path);\r
+                       \r
+                       control.setStepLength(0.1);\r
+\r
+                       control.initializeSimulation();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+               \r
+               // Try to set value to a dummy variable\r
+               try {\r
+                       control.setBooleanValue("dummy", true);\r
+                       Assert.fail("Succeeded in setting a Boolean value to a dummy variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown: no such variable\r
+               }\r
+               \r
+               // Try to set value to a Real variable\r
+               try {\r
+                       control.setBooleanValue("r", true);\r
+                       Assert.fail("Succeeded in setting a Boolean value to a Real variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown\r
+               }\r
+               \r
+               // Try to set value to an Integer variable\r
+               try {\r
+                       control.setBooleanValue("i", true);\r
+                       Assert.fail("Succeeded in setting a Boolean value to an Integer variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown\r
+               }\r
+               \r
+               // Try to set value to a continuous Real variable\r
+               try {\r
+                       control.setBooleanValue("continuousReal", true);\r
+                       Assert.fail("Succeeded in setting a Boolean value to a continuous Real variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown\r
+               }\r
+               \r
+               // Try to set value to a discrete Integer variable\r
+               try {\r
+                       control.setBooleanValue("discreteInteger", true);\r
+                       Assert.fail("Succeeded in setting a Boolean value to a discrete Integer variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown\r
+               }               \r
+               \r
+               \r
+               /*** SUCCEEDS ***/\r
+               // For reference, set a boolean value\r
+               try {\r
+                       control.setBooleanValue("b", true);\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Could not set a boolean value to boolean variable");\r
+               }\r
+               \r
+               // Set a value to a variable that is not a parameter. This is possible, but should no affect the simulation\r
+               try {\r
+                       control.setBooleanValue("discreteBoolean", true);\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Could not set a boolean value to discrete boolean variable");\r
+               }\r
+               \r
+               // Unload model\r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUControlTestSuite.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUControlTestSuite.java
new file mode 100644 (file)
index 0000000..89b1e1c
--- /dev/null
@@ -0,0 +1,25 @@
+package org.simantics.sysdyn.tests.fmi;\r
+\r
+import org.junit.runner.RunWith;\r
+import org.junit.runners.Suite;\r
+import org.junit.runners.Suite.SuiteClasses;\r
+\r
+/**\r
+ * Test suite for testing fmu functionalities.\r
+ * \r
+ * Tests are independent.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@RunWith(Suite.class)\r
+@SuiteClasses({ \r
+       LoadFMUFileFailTests.class, \r
+       CallFMUBeforeInitializationTests.class, \r
+       FMUIntegerTest.class, \r
+       FMUBooleanTest.class, \r
+       FMURealTest.class,\r
+       FMUResultFilterTest.class})\r
+public class FMUControlTestSuite {\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUIntegerTest.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUIntegerTest.java
new file mode 100644 (file)
index 0000000..70bad9f
--- /dev/null
@@ -0,0 +1,198 @@
+package org.simantics.sysdyn.tests.fmi;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+\r
+import junit.framework.Assert;\r
+\r
+import org.junit.Test;\r
+import org.simantics.modelica.fmi.FMUControlJNI;\r
+import org.simantics.modelica.fmi.FMUJNIException;\r
+\r
+/**\r
+ * Tests that an integer value can be changed and the change is propagated \r
+ * to the rest of the model.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FMUIntegerTest {\r
+\r
+\r
+\r
+       @Test\r
+       public void test() {\r
+               \r
+               /*\r
+               Below is the model used for testing. \r
+               Model is located in Models\FMUTests\FMUIntegerTest \r
+               \r
+               model FMUIntegerTestModel\r
+                       parameter Integer i1 = 1;\r
+                       parameter Integer i2 = 1;\r
+                       Real valve;\r
+                       Real stock(start=0.0,fixed=true);\r
+                       parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+               equation\r
+                       valve = if initial() or i1 < 0 or i1 >= 0 then (i1 + i2) else pre(valve);\r
+                       der(stock) = valve;\r
+               end FMUIntegerTestModel;\r
+               \r
+               \r
+               The condition for valve is automatically generated in sysdyn. It is a hack for getting \r
+               valve to notice a change in i1 and i2. \r
+                */\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMUIntegerTest\\FMUIntegerTestModel.fmu";\r
+\r
+\r
+               try {\r
+\r
+                       control.loadFMUFile(path);\r
+\r
+                       control.setStepLength(0.1);\r
+\r
+                       control.initializeSimulation();\r
+\r
+\r
+                       String[] s = control.getAllVariables();\r
+                       List<String> nameList = Arrays.asList(s);\r
+                       int valve = nameList.indexOf("valve");\r
+                       int stock = nameList.indexOf("stock");\r
+                       control.subscribe(s);\r
+\r
+                       /*\r
+                        * Simulate the model for time 0 - 3 with i1==1 and i2==1\r
+                        *     => stock == 6 when time == 3\r
+                        *     \r
+                        * Change i1 to 3 and simulate to time == 6\r
+                        *     => stock == 18 when time == 6 \r
+                        */\r
+                       double value;\r
+                       double[] results = new double[s.length];\r
+                       for(int i = 0; i < 60; i++) {\r
+                               results = control.getSubscribedResults(results);\r
+\r
+                               if(i == 30) {\r
+                                       value = results[stock];\r
+                                       Assert.assertFalse("stock != 6 when time == 3. (stock == " + value + ")",  value < 5.999 || value > 6.001);\r
+                                       control.setIntegerValue("i1", 3);\r
+                               }\r
+                               \r
+                               value = results[valve];\r
+                               if(i > 30) {\r
+                                       Assert.assertFalse("valve != 4 after time == 3. (valve == " + value + ")",  value < 3.999 || value > 4.001);\r
+                               } else {\r
+                                       Assert.assertFalse("valve != 2 before time == 3. (valve == " + value + ")",  value < 1.999 || value > 2.001);\r
+\r
+                               }\r
+                               control.simulateStep();\r
+                       }\r
+                       \r
+                       results = control.getSubscribedResults(results);\r
+                       value = results[stock];\r
+                       Assert.assertFalse("stock != 18 when time == 6. (stock == " + value + ")",  value < 17.999 || value > 18.001);\r
+                       \r
+                       \r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+               \r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+       @Test\r
+       public void testSetIntegerErrors() {\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMUAllTypesOfVariablesTest\\FMUAllTypesOfVariablesTestModel.fmu";\r
+\r
+               // Initialize a model\r
+               try {\r
+\r
+                       control.loadFMUFile(path);\r
+\r
+                       control.setStepLength(0.1);\r
+\r
+                       control.initializeSimulation();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+               \r
+               // Try to set value to a dummy variable\r
+               try {\r
+                       control.setIntegerValue("dummy", 1);\r
+                       Assert.fail("Succeeded in setting an Integer value to a dummy variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown: no such variable\r
+               }\r
+               \r
+               // Try to set a Boolean value to an Integer variable \r
+               try {\r
+                       control.setIntegerValue("b", 1);\r
+                       Assert.fail("Succeeded in setting an Integer value to an Integer variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown\r
+               }\r
+               \r
+               // Try to set a Boolean value to a discrete Integer variable \r
+               try {\r
+                       control.setIntegerValue("discreteBoolean", 1);\r
+                       Assert.fail("Succeeded in setting an Integer value to a discrete Integer variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown\r
+               }\r
+               \r
+               // Try to set value to a Real variable\r
+               try {\r
+                       control.setIntegerValue("r", 1);\r
+                       Assert.fail("Succeeded in setting an Integer value to a Real variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown\r
+               }\r
+               \r
+\r
+               \r
+               // Try to set value to a continuous Real variable\r
+               try {\r
+                       control.setIntegerValue("continuousReal", 1);\r
+                       Assert.fail("Succeeded in setting a Boolean value to a continuous Real variable");\r
+               } catch (FMUJNIException e) {\r
+                       // Exception should be thrown\r
+               }\r
+               \r
+\r
+               \r
+               \r
+               /*** SUCCEEDS ***/\r
+               \r
+               // For reference, set an integer value\r
+               try {\r
+                       control.setIntegerValue("i", 1);\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Could not set an integer value to integer variable");\r
+               }\r
+               \r
+               // Set a value to a variable that is not a parameter. This is possible, but should no affect the simulation\r
+               try {\r
+                       control.setIntegerValue("discreteInteger", 1);\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Could not set an integer value to discrete integer variable");\r
+               }               \r
+               \r
+               // Unload model\r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMURealTest.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMURealTest.java
new file mode 100644 (file)
index 0000000..f996b7a
--- /dev/null
@@ -0,0 +1,109 @@
+package org.simantics.sysdyn.tests.fmi;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+\r
+import junit.framework.Assert;\r
+\r
+import org.junit.Test;\r
+import org.simantics.modelica.fmi.FMUControlJNI;\r
+import org.simantics.modelica.fmi.FMUJNIException;\r
+\r
+/**\r
+ * Tests that a real value can be changed and the change is propagated \r
+ * to the rest of the model.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FMURealTest {\r
+       \r
+       /*\r
+       Below is the model used for testing. \r
+       Model is located in Models\FMUTests\FMURealTest \r
+       \r
+       model FMURealTestModel\r
+               parameter Real r1 = 1.0;\r
+               parameter Real r2 = 1.0;\r
+               Real valve;\r
+               Real stock(start=0.0,fixed=true);\r
+               parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+       equation\r
+               if initial() or r1 < 0 or r1 >= 0 then (r1 + r2) else pre(valve);\r
+               der(stock) = valve;\r
+       end FMURealTestModel;\r
+       \r
+       \r
+       The condition for valve is automatically generated in sysdyn. It is a hack for getting \r
+       valve to notice a change in i1 and i2. \r
+        */\r
+\r
+       @Test\r
+       public void test() {\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMURealTest\\FMURealTestModel.fmu";\r
+\r
+\r
+               try {\r
+\r
+                       control.loadFMUFile(path);\r
+\r
+                       control.setStepLength(0.1);\r
+\r
+                       control.initializeSimulation();\r
+\r
+\r
+                       String[] s = control.getAllVariables();\r
+                       List<String> nameList = Arrays.asList(s);\r
+                       int valve = nameList.indexOf("valve");\r
+                       int stock = nameList.indexOf("stock");\r
+                       control.subscribe(s);\r
+\r
+                       /*\r
+                        * Simulate the model for time 0 - 3 with r1==1 and r2==1\r
+                        *     => stock == 6 when time == 3\r
+                        *     \r
+                        * Change r1 to 3 and simulate to time == 6\r
+                        *     => stock == 18 when time == 6 \r
+                        */\r
+                       double value;\r
+                       double[] results = new double[s.length];\r
+                       for(int i = 0; i < 60; i++) {\r
+                               results = control.getSubscribedResults(results);\r
+\r
+                               if(i == 30) {\r
+                                       value = results[stock];\r
+                                       Assert.assertFalse("stock != 6 when time == 3. (stock == " + value + ")",  value < 5.999 || value > 6.001);\r
+                                       control.setRealValue("r1", 3);\r
+                               }\r
+                               \r
+                               value = results[valve];\r
+                               if(i > 30) {\r
+                                       Assert.assertFalse("valve != 4 after time == 3. (valve == " + value + ")",  value < 3.999 || value > 4.001);\r
+                               } else {\r
+                                       Assert.assertFalse("valve != 2 before time == 3. (valve == " + value + ")",  value < 1.999 || value > 2.001);\r
+\r
+                               }\r
+                               control.simulateStep();\r
+                       }\r
+                       \r
+                       results = control.getSubscribedResults(results);\r
+                       value = results[stock];\r
+                       Assert.assertFalse("stock != 18 when time == 6. (stock == " + value + ")",  value < 17.999 || value > 18.001);\r
+                       \r
+                       \r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+               \r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUResultFilterTest.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/FMUResultFilterTest.java
new file mode 100644 (file)
index 0000000..0cbb9f5
--- /dev/null
@@ -0,0 +1,142 @@
+package org.simantics.sysdyn.tests.fmi;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+\r
+import junit.framework.Assert;\r
+\r
+import org.junit.Test;\r
+import org.simantics.modelica.fmi.FMUControlJNI;\r
+import org.simantics.modelica.fmi.FMUJNIException;\r
+\r
+\r
+/**\r
+ * Tests result filtering\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FMUResultFilterTest {\r
+       \r
+       /*\r
+       Below is the model used for testing. \r
+       Model is located in Models\FMUTests\FMURealTest \r
+       \r
+       model FMURealTestModel\r
+               parameter Real r1 = 1.0;\r
+               parameter Real r2 = 1.0;\r
+               Real valve;\r
+               Real stock(start=0.0,fixed=true);\r
+               parameter Real time = 0; // Time parameter is set at each time step by simulator\r
+       equation\r
+               if initial() or r1 < 0 or r1 >= 0 then (r1 + r2) else pre(valve);\r
+               der(stock) = valve;\r
+       end FMURealTestModel;\r
+       \r
+       \r
+       The condition for valve is automatically generated in sysdyn. It is a hack for getting \r
+       valve to notice a change in i1 and i2. \r
+       \r
+       Results always contain "time" for each modelica class, hence result size is +1\r
+        */\r
+\r
+       @Test\r
+       public void testReturn3() {\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMURealTest\\FMURealTestModel.fmu";\r
+\r
+\r
+               try {\r
+                       \r
+               \r
+\r
+                       control.loadFMUFile(path);\r
+\r
+                       String[] bothRealParameters = control.filterVariables("r(.*)");\r
+                       Assert.assertEquals("Filter \"r(.*)\" returned " + bothRealParameters.length + " results. Should have returned 3", bothRealParameters.length, 3);\r
+                       List<String> result = Arrays.asList(bothRealParameters);\r
+                       Assert.assertTrue("Result did not contain r1", result.contains("r1"));\r
+                       Assert.assertTrue("Result did not contain r2", result.contains("r2"));\r
+                       Assert.assertTrue("Result did not contain time", result.contains("time"));\r
+\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+       @Test\r
+       public void testReturn2() {\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMURealTest\\FMURealTestModel.fmu";\r
+\r
+\r
+               try {\r
+\r
+                       control.loadFMUFile(path);\r
+\r
+                       String[] stock = control.filterVariables("stock");\r
+                       Assert.assertEquals("Filter \"stock\" returned " + stock.length + " results. Should have returned 2", stock.length, 2);\r
+                       List<String> result = Arrays.asList(stock);\r
+                       Assert.assertTrue("Result did not contain stock", result.contains("stock"));\r
+                       Assert.assertTrue("Result did not contain time", result.contains("time"));\r
+                       \r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+       @Test\r
+       public void testReturn1() {\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMURealTest\\FMURealTestModel.fmu";\r
+\r
+\r
+               try {\r
+                       control.loadFMUFile(path);\r
+                       \r
+                       String[] empty = control.filterVariables("empty");\r
+                       Assert.assertEquals("Filter \"empty\" returned " + empty.length + " results. Should have returned 1", empty.length, 1);\r
+                       \r
+                       List<String> result = Arrays.asList(empty);\r
+                       Assert.assertTrue("Result did not contain time", result.contains("time"));\r
+                       \r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+       @Test\r
+       public void testReturn1WhenNullFilter() {\r
+\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\FMURealTest\\FMURealTestModel.fmu";\r
+\r
+\r
+               try {\r
+                       control.loadFMUFile(path);\r
+                       \r
+                       String[] NULL = control.filterVariables(null);\r
+                       Assert.assertEquals("Filter null returned " + NULL.length + " results. Should have returned 1", NULL.length, 1);\r
+                       \r
+                       List<String> result = Arrays.asList(NULL);\r
+                       Assert.assertTrue("Result did not contain time", result.contains("time"));\r
+                       \r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+       }\r
+       \r
+\r
+       \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/LoadFMUFileFailTests.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/LoadFMUFileFailTests.java
new file mode 100644 (file)
index 0000000..c6f9b6c
--- /dev/null
@@ -0,0 +1,82 @@
+package org.simantics.sysdyn.tests.fmi;\r
+\r
+import static org.junit.Assert.*;\r
+\r
+\r
+import org.junit.Test;\r
+import org.simantics.modelica.fmi.FMUControlJNI;\r
+import org.simantics.modelica.fmi.FMUJNIException;\r
+\r
+/**\r
+ * Test possible error situations in loading an fmu file to the control\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class LoadFMUFileFailTests {\r
+       \r
+       \r
+       @Test\r
+       public void testLoadNonExistingFile() {\r
+               FMUControlJNI control = new FMUControlJNI();\r
+               \r
+               String path = ".\\Models\\FMUTests\\Non-Existing.fmu";\r
+\r
+               try {\r
+                       control.loadFMUFile(path);\r
+                       fail("Loaded a non-existing file without throwing an exception");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: Tried to load a non-existing file\r
+                       System.out.println(e.getMessage());\r
+               }\r
+               \r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       fail("Unload failed");\r
+               }\r
+       }\r
+       \r
+       @Test\r
+       public void testLoadNonFMUFile() {\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\DummyFile.txt";\r
+\r
+               try {\r
+                       control.loadFMUFile(path);\r
+                       fail("Loaded a non-FMU file without throwing an exception");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: Tried to load an incorrect file\r
+                       System.out.println(e.getMessage());\r
+               }\r
+               \r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       fail("Unload failed");\r
+               }\r
+       }\r
+       \r
+       @Test\r
+       public void testLoadNonFMUFile2() {\r
+               FMUControlJNI control = new FMUControlJNI();\r
+\r
+               String path = ".\\Models\\FMUTests\\DummyFile.fmu"; // <- an empty text file with fmu-extension. not a valid fmu file\r
+\r
+               try {\r
+                       control.loadFMUFile(path);\r
+                       fail("Loaded a non-FMU file without throwing an exception");\r
+               } catch (FMUJNIException e) {\r
+                       // control should throw this exception: Tried to load an incorrect file\r
+               }\r
+               \r
+               try {\r
+                       control.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       fail("Unload failed");\r
+               }\r
+       }\r
+       \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/MultipleSimultaneousFMUSimulationsTest.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/fmi/MultipleSimultaneousFMUSimulationsTest.java
new file mode 100644 (file)
index 0000000..6a4d7af
--- /dev/null
@@ -0,0 +1,159 @@
+package org.simantics.sysdyn.tests.fmi;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+\r
+import junit.framework.Assert;\r
+\r
+import org.junit.Test;\r
+import org.simantics.modelica.fmi.FMUControlJNI;\r
+import org.simantics.modelica.fmi.FMUJNIException;\r
+\r
+public class MultipleSimultaneousFMUSimulationsTest {\r
+\r
+\r
+       /**\r
+        * This test runs simultaneously {@link FMURealTest}, {@link FMUIntegerTest} and {@link FMUBooleanTest} to\r
+        * see that they do not conflict with each other.\r
+        */\r
+\r
+       @Test\r
+       public void testMultipleSimulations() {\r
+\r
+               FMUControlJNI control1 = new FMUControlJNI();\r
+               FMUControlJNI control2 = new FMUControlJNI();\r
+               FMUControlJNI control3 = new FMUControlJNI();\r
+\r
+               String path1 = ".\\Models\\FMUTests\\FMURealTest\\FMURealTestModel.fmu";\r
+               String path2 = ".\\Models\\FMUTests\\FMUIntegerTest\\FMUIntegerTestModel.fmu";\r
+               String path3 = ".\\Models\\FMUTests\\FMUBooleanTest\\FMUBooleanTestModel.fmu";  \r
+\r
+               try {\r
+                       control1.loadFMUFile(path1);\r
+                       control2.loadFMUFile(path2);\r
+                       control3.loadFMUFile(path3);\r
+\r
+                       control1.setStepLength(0.1);\r
+                       control2.setStepLength(0.1);\r
+                       control3.setStepLength(0.1);\r
+\r
+                       control1.initializeSimulation();\r
+                       control2.initializeSimulation();\r
+                       control3.initializeSimulation();\r
+\r
+\r
+                       String[] s1 = control1.getAllVariables();\r
+                       String[] s2 = control2.getAllVariables();\r
+                       String[] s3 = control3.getAllVariables();\r
+\r
+\r
+                       List<String> nameList1 = Arrays.asList(s1);\r
+                       List<String> nameList2 = Arrays.asList(s2);\r
+                       List<String> nameList3 = Arrays.asList(s3);\r
+                       int valve1 = nameList1.indexOf("valve");\r
+                       int valve2 = nameList2.indexOf("valve");\r
+                       int valve3 = nameList3.indexOf("valve");\r
+\r
+                       int stock1 = nameList1.indexOf("stock");\r
+                       int stock2 = nameList2.indexOf("stock");\r
+                       int stock3 = nameList3.indexOf("stock");\r
+\r
+                       control1.subscribe(s1);\r
+                       control2.subscribe(s2);\r
+                       control3.subscribe(s3);\r
+\r
+\r
+                       double value;\r
+                       double[] results1 = new double[s1.length];\r
+                       double[] results2 = new double[s2.length];\r
+                       double[] results3 = new double[s3.length];\r
+\r
+                       for(int i = 0; i < 60; i++) {\r
+\r
+                               // Real\r
+                               results1 = control1.getSubscribedResults(results1);\r
+\r
+                               if(i == 30) {\r
+                                       value = results1[stock1];\r
+                                       Assert.assertFalse("stock != 6 when time == 3. (stock == " + value + ")",  value < 5.999 || value > 6.001);\r
+                                       control1.setRealValue("r1", 3);\r
+                               }\r
+\r
+                               value = results1[valve1];\r
+                               if(i > 30) {\r
+                                       Assert.assertFalse("valve != 4 after time == 3. (valve == " + value + ")",  value < 3.999 || value > 4.001);\r
+                               } else {\r
+                                       Assert.assertFalse("valve != 2 before time == 3. (valve == " + value + ")",  value < 1.999 || value > 2.001);\r
+\r
+                               }\r
+                               control1.simulateStep();\r
+\r
+                               // Integer\r
+                               results2 = control2.getSubscribedResults(results2);\r
+\r
+                               if(i == 30) {\r
+                                       value = results2[stock2];\r
+                                       Assert.assertFalse("stock != 6 when time == 3. (stock == " + value + ")",  value < 5.999 || value > 6.001);\r
+                                       control2.setIntegerValue("i1", 3);\r
+                               }\r
+\r
+                               value = results2[valve2];\r
+                               if(i > 30) {\r
+                                       Assert.assertFalse("valve != 4 after time == 3. (valve == " + value + ")",  value < 3.999 || value > 4.001);\r
+                               } else {\r
+                                       Assert.assertFalse("valve != 2 before time == 3. (valve == " + value + ")",  value < 1.999 || value > 2.001);\r
+\r
+                               }\r
+                               control2.simulateStep();\r
+\r
+                               // Boolean\r
+                               results3 = control3.getSubscribedResults(results3);\r
+\r
+                               if(i == 30) {\r
+                                       value = results3[stock3];\r
+                                       Assert.assertFalse("stock != 3 when time == 3. (stock == " + value + ")",  value < 2.999 || value > 3.001);\r
+                                       control3.setBooleanValue("b", false);\r
+                               }\r
+\r
+                               value = results3[valve3];\r
+                               if(i > 30) {\r
+                                       Assert.assertFalse("valve != -1 after time == 3. (valve == " + value + ")",  value > -0.999 || value < -1.001);\r
+                               } else {\r
+                                       Assert.assertFalse("valve != 1 before time == 3. (valve == " + value + ")",  value < 0.999 || value > 1.001);\r
+\r
+                               }\r
+                               control3.simulateStep();\r
+\r
+                       }\r
+\r
+                       // Real\r
+                       results1 = control1.getSubscribedResults(results1);\r
+                       value = results1[stock1];\r
+                       Assert.assertFalse("stock != 18 when time == 6. (stock == " + value + ")",  value < 17.999 || value > 18.001);\r
+\r
+                       // Integer\r
+                       results2 = control2.getSubscribedResults(results2);\r
+                       value = results2[stock2];\r
+                       Assert.assertFalse("stock != 18 when time == 6. (stock == " + value + ")",  value < 17.999 || value > 18.001);\r
+\r
+                       // Boolean\r
+                       results3 = control3.getSubscribedResults(results3);\r
+                       value = results3[stock3];\r
+                       Assert.assertFalse("stock != 0 when time == 6. (stock == " + value + ")",  value < -0.001 || value > 0.001);\r
+\r
+\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+\r
+               try {\r
+                       control1.unloadFMU();\r
+                       control2.unloadFMU();\r
+                       control3.unloadFMU();\r
+               } catch (FMUJNIException e) {\r
+                       Assert.fail("Exception in native fmu code: " + e.getMessage());\r
+               }\r
+\r
+       }\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scl/SCLTestScripts.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scl/SCLTestScripts.java
new file mode 100644 (file)
index 0000000..40755c9
--- /dev/null
@@ -0,0 +1,21 @@
+package org.simantics.sysdyn.tests.scl;\r
+\r
+import junit.runner.Version;\r
+\r
+import org.junit.Test;\r
+import org.simantics.db.testing.base.ScriptTestBase;\r
+\r
+public class SCLTestScripts extends ScriptTestBase {\r
+\r
+       public SCLTestScripts() {\r
+               super("../scripts");\r
+       System.out.println("JUnit version is: " + Version.id());\r
+       }\r
+\r
+    @Test public void ImportModel_DiscoveryAndExploitationOfResources() { test(300); }\r
+    @Test public void ImportModel_GlobalCarbonCycle() { test(300); }\r
+    @Test public void ImportModel_PredatorAndLimitedPrey() { test(300); }\r
+    @Test public void ImportModel_ResourceExploitationUseRecycling() { test(300); }\r
+    @Test public void ImportModel_TouristsEnvironmentsAndHotelFacilities() { test(300); }\r
+    \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scl/SCLTests.java b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scl/SCLTests.java
new file mode 100644 (file)
index 0000000..db9b75c
--- /dev/null
@@ -0,0 +1,24 @@
+package org.simantics.sysdyn.tests.scl;\r
+\r
+import org.junit.BeforeClass;\r
+import org.junit.Test;\r
+import org.junit.runner.RunWith;\r
+import org.junit.runners.Suite.SuiteClasses;\r
+import org.simantics.db.testing.common.RegressionSuiteRunner;\r
+\r
+@RunWith(RegressionSuiteRunner.class)\r
+@SuiteClasses({SCLTestScripts.class})\r
+\r
+public class SCLTests {\r
+\r
+       @BeforeClass\r
+    public static void setUp() {\r
+\r
+    }\r
+       \r
+       @Test\r
+       public static void asd() {\r
+               System.out.println("asd");\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_DiscoveryAndExploitationOfResources.sts b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_DiscoveryAndExploitationOfResources.sts
new file mode 100644 (file)
index 0000000..d2b35a7
--- /dev/null
@@ -0,0 +1,10 @@
+>import "File"\r
+>import "Simantics/Misc"\r
+>import "Simantics/Testing"\r
+>import "Simantics/Sysdyn"\r
+>m = importModel $ (getSystemProperty "scl.test.path")  + "/../../../../../../../org.simantics.sysdyn.feature/rootFiles/sampleModels/Discovery And Exploitation Of Resources.sysdyn"\r
+>exp = fromJust $ possibleResourceChild m "Experiment"\r
+>id = activateExperiment exp\r
+>run id\r
+>withinEpsilon (lastValue exp id "/Available Resources") 6.127e-6 0.001\r
+True
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_GlobalCarbonCycle.sts b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_GlobalCarbonCycle.sts
new file mode 100644 (file)
index 0000000..d731bc9
--- /dev/null
@@ -0,0 +1,10 @@
+>import "File"\r
+>import "Simantics/Misc"\r
+>import "Simantics/Testing"\r
+>import "Simantics/Sysdyn"\r
+>m = importModel $ (getSystemProperty "scl.test.path")  + "/../../../../../../../org.simantics.sysdyn.feature/rootFiles/sampleModels/Global Carbon Cycle.sysdyn"\r
+>exp = fromJust $ possibleResourceChild m "Experiment"\r
+>id = activateExperiment exp\r
+>run id\r
+>withinEpsilon (lastValue exp id "/Carbon In Biosphere") 2710.604 0.001\r
+True
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_PredatorAndLimitedPrey.sts b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_PredatorAndLimitedPrey.sts
new file mode 100644 (file)
index 0000000..3d04aaa
--- /dev/null
@@ -0,0 +1,10 @@
+>import "File"\r
+>import "Simantics/Misc"\r
+>import "Simantics/Testing"\r
+>import "Simantics/Sysdyn"\r
+>m = importModel $ (getSystemProperty "scl.test.path")  + "/../../../../../../../org.simantics.sysdyn.feature/rootFiles/sampleModels/Predator And Limited Prey.sysdyn"\r
+>exp = fromJust $ possibleResourceChild m "Experiment"\r
+>id = activateExperiment exp\r
+>run id\r
+>withinEpsilon (lastValue exp id "/prey") 0.996 0.001\r
+True
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_ResourceExploitationUseRecycling.sts b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_ResourceExploitationUseRecycling.sts
new file mode 100644 (file)
index 0000000..9dc029b
--- /dev/null
@@ -0,0 +1,10 @@
+>import "File"\r
+>import "Simantics/Misc"\r
+>import "Simantics/Testing"\r
+>import "Simantics/Sysdyn"\r
+>m = importModel $ (getSystemProperty "scl.test.path")  + "/../../../../../../../org.simantics.sysdyn.feature/rootFiles/sampleModels/Resource Exploitation Use Recycling.sysdyn"\r
+>exp = fromJust $ possibleResourceChild m "Experiment"\r
+>id = activateExperiment exp\r
+>run id\r
+>withinEpsilon (lastValue exp id "/Resource Demand") 9.243 0.001\r
+True
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_TouristsEnvironmentsAndHotelFacilities.sts b/1.8/org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts/ImportModel_TouristsEnvironmentsAndHotelFacilities.sts
new file mode 100644 (file)
index 0000000..2db9bd4
--- /dev/null
@@ -0,0 +1,10 @@
+>import "File"\r
+>import "Simantics/Misc"\r
+>import "Simantics/Testing"\r
+>import "Simantics/Sysdyn"\r
+>m = importModel $ (getSystemProperty "scl.test.path")  + "/../../../../../../../org.simantics.sysdyn.feature/rootFiles/sampleModels/Tourists Environments And Hotel Facilities.sysdyn"\r
+>exp = fromJust $ possibleResourceChild m "Experiment"\r
+>id = activateExperiment exp\r
+>run id\r
+>withinEpsilon (lastValue exp id "/Tourists") 2642.086 0.001\r
+True
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui.old/.classpath b/1.8/org.simantics.sysdyn.ui.old/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/.project b/1.8/org.simantics.sysdyn.ui.old/.project
new file mode 100644 (file)
index 0000000..2ebd569
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.sysdyn.ui</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.sysdyn.ui.old/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..6d81695
--- /dev/null
@@ -0,0 +1,8 @@
+#Thu Nov 05 12:45:23 EET 2009\r
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/META-INF/MANIFEST.MF b/1.8/org.simantics.sysdyn.ui.old/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..33131ca
--- /dev/null
@@ -0,0 +1,18 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Ui
+Bundle-SymbolicName: org.simantics.sysdyn.ui;singleton:=true
+Bundle-Version: 1.0.0.qualifier
+Bundle-Activator: org.simantics.sysdyn.ui.Activator
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ org.simantics.ui;bundle-version="1.0.0",
+ org.simantics.diagram;bundle-version="1.0.0",
+ org.simantics.db;bundle-version="0.6.2",
+ org.simantics.db.common;bundle-version="0.6.2",
+ org.simantics.db.layer0;bundle-version="0.7.0",
+ org.simantics.g2d;bundle-version="1.0.0",
+ org.simantics.scenegraph;bundle-version="1.0.0",
+ org.simantics.layer0.utils;bundle-version="0.6.2"
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/1.8/org.simantics.sysdyn.ui.old/adapters.xml b/1.8/org.simantics.sysdyn.ui.old/adapters.xml
new file mode 100644 (file)
index 0000000..86c2aa3
--- /dev/null
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<adapters>\r
+<!-- \r
+       <target interface="org.simantics.project.features.IProjectFeature">\r
+               <type\r
+                       uri="http://www.simantics.org/Ontology/ProConf/1.0#SymbolManagerFeature"\r
+                       class="org.simantics.diagram.symbollibrary.SymbolManagerFeature">\r
+               </type>\r
+       </target>\r
+\r
+       <target interface="org.simantics.g2d.diagram.DiagramClass">\r
+               <baseType uri="http://www.simantics.org/Simantics/Diagram/2.0#Composite" />\r
+               <adapter uri="http://www.simantics.org/Simantics/Diagram/2.0#Composite"\r
+                       adapterClass="org.simantics.diagram.adapter.DiagramClassAdapter" />\r
+       </target>\r
+ -->\r
+       <target interface="org.simantics.diagram.adapter.GraphElementClassFactory">\r
+               <resource uri="http://www.simantics.org/Sysdyn#VariableElement"\r
+                       class="org.simantics.sysdyn.ui.adapters.VariableClassFactory" />\r
+       </target>\r
+\r
+       <target interface="org.simantics.diagram.adapter.GraphElementFactory">\r
+               <type uri="http://www.simantics.org/Sysdyn#VariableElement"\r
+                       class="org.simantics.sysdyn.ui.adapters.VariableClassFactory" />\r
+       </target>\r
+\r
+       <target interface="org.simantics.diagram.synchronization.graph.ElementWriter">\r
+               <type uri="http://www.simantics.org/Sysdyn#VariableElement"\r
+                       class="org.simantics.sysdyn.ui.adapters.VariableElementWriter" />\r
+       </target>\r
+\r
+</adapters>
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui.old/build.properties b/1.8/org.simantics.sysdyn.ui.old/build.properties
new file mode 100644 (file)
index 0000000..6f20375
--- /dev/null
@@ -0,0 +1,5 @@
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               plugin.xml\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/plugin.xml b/1.8/org.simantics.sysdyn.ui.old/plugin.xml
new file mode 100644 (file)
index 0000000..cac6482
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<?eclipse version="3.4"?>\r
+<plugin>\r
+   <extension\r
+         point="org.eclipse.ui.editors">\r
+      <editor\r
+            class="org.simantics.sysdyn.ui.diagram.SysdynDiagramEditor"\r
+            default="false"\r
+            id="org.simantics.sysdyn.ui.diagramEditor"\r
+            name="Sysdyn diagram editor">\r
+      </editor>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.ui.resourceEditorAdapter">\r
+      <adapter\r
+            editorId="org.simantics.sysdyn.ui.diagramEditor"\r
+            priority="3"\r
+            type_uris="http://www.vtt.fi/Simantics/Layer0/1.0/Types#Entity">\r
+      </adapter>\r
+   </extension>\r
+\r
+</plugin>\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/Activator.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/Activator.java
new file mode 100644 (file)
index 0000000..2134237
--- /dev/null
@@ -0,0 +1,50 @@
+package org.simantics.sysdyn.ui;\r
+\r
+import org.eclipse.ui.plugin.AbstractUIPlugin;\r
+import org.osgi.framework.BundleContext;\r
+\r
+/**\r
+ * The activator class controls the plug-in life cycle\r
+ */\r
+public class Activator extends AbstractUIPlugin {\r
+\r
+       // The plug-in ID\r
+       public static final String PLUGIN_ID = "org.simantics.sysdyn.ui";\r
+\r
+       // The shared instance\r
+       private static Activator plugin;\r
+       \r
+       /**\r
+        * The constructor\r
+        */\r
+       public Activator() {\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)\r
+        */\r
+       public void start(BundleContext context) throws Exception {\r
+               super.start(context);\r
+               plugin = this;\r
+       }\r
+\r
+       /*\r
+        * (non-Javadoc)\r
+        * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)\r
+        */\r
+       public void stop(BundleContext context) throws Exception {\r
+               plugin = null;\r
+               super.stop(context);\r
+       }\r
+\r
+       /**\r
+        * Returns the shared instance\r
+        *\r
+        * @return the shared instance\r
+        */\r
+       public static Activator getDefault() {\r
+               return plugin;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/SysdynResource.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/SysdynResource.java
new file mode 100644 (file)
index 0000000..426b322
--- /dev/null
@@ -0,0 +1,72 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007- VTT Technical Research Centre of Finland.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui;\r
+\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public class SysdynResource {\r
+    \r
+    public final Resource HasX;\r
+    public final Resource HasY;\r
+    public final Resource SysdynModel;\r
+    public final Resource SysdynModelManager;\r
+    public final Resource SysdynModellingDomain;\r
+    public final Resource TestDiagram;\r
+    public final Resource Variable;\r
+    public final Resource VariableElement;\r
+    \r
+    public static class URIs {\r
+        public static final String HasX = "http://www.simantics.org/Sysdyn#HasX";\r
+        public static final String HasY = "http://www.simantics.org/Sysdyn#HasY";\r
+        public static final String SysdynModel = "http://www.simantics.org/Sysdyn#SysdynModel";\r
+        public static final String SysdynModelManager = "http://www.simantics.org/Sysdyn#SysdynModelManager";\r
+        public static final String SysdynModellingDomain = "http://www.simantics.org/Sysdyn#SysdynModellingDomain";\r
+        public static final String TestDiagram = "http://www.simantics.org/Sysdyn#TestDiagram";\r
+        public static final String Variable = "http://www.simantics.org/Sysdyn#Variable";\r
+        public static final String VariableElement = "http://www.simantics.org/Sysdyn#VariableElement";\r
+    }\r
+    \r
+    public static Resource getResourceOrNull(ReadGraph graph, String uri) {\r
+        try {\r
+            return graph.getResourceByURI(uri);\r
+        } catch(DatabaseException e) {\r
+            System.err.println(e.getMessage());\r
+            return null;\r
+        }\r
+    }\r
+    \r
+    public SysdynResource(ReadGraph graph) {\r
+        HasX = getResourceOrNull(graph, URIs.HasX);\r
+        HasY = getResourceOrNull(graph, URIs.HasY);\r
+        SysdynModel = getResourceOrNull(graph, URIs.SysdynModel);\r
+        SysdynModelManager = getResourceOrNull(graph, URIs.SysdynModelManager);\r
+        SysdynModellingDomain = getResourceOrNull(graph, URIs.SysdynModellingDomain);\r
+        TestDiagram = getResourceOrNull(graph, URIs.TestDiagram);\r
+        Variable = getResourceOrNull(graph, URIs.Variable);\r
+        VariableElement = getResourceOrNull(graph, URIs.VariableElement);\r
+    }\r
+    \r
+    public static SysdynResource getInstance(ReadGraph graph) {\r
+        Session session = graph.getSession();\r
+        SysdynResource ret = session.getService(SysdynResource.class);\r
+        if(ret == null) {\r
+            ret = new SysdynResource(graph);\r
+            session.registerService(SysdynResource.class, ret);\r
+        }\r
+        return ret;\r
+    }\r
+    \r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/adapters/VariableClassFactory.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/adapters/VariableClassFactory.java
new file mode 100644 (file)
index 0000000..e45047f
--- /dev/null
@@ -0,0 +1,46 @@
+package org.simantics.sysdyn.ui.adapters;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.adapter.ElementQuerySupport;\r
+import org.simantics.diagram.adapter.GraphElementClassFactory;\r
+import org.simantics.diagram.adapter.GraphElementFactory;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.impl.Element;\r
+import org.simantics.sysdyn.ui.SysdynResource;\r
+import org.simantics.sysdyn.ui.diagram.DrawableElementClass;\r
+import org.simantics.sysdyn.ui.elements.TestDrawable;\r
+\r
+public class VariableClassFactory implements GraphElementFactory, GraphElementClassFactory {\r
+\r
+       @Override\r
+       public IElement spawn(ReadGraph g, Resource resource,\r
+                       ElementQuerySupport support, IDiagram diagram)\r
+                       throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+               \r
+               ElementClass elementClass = \r
+                       DrawableElementClass.createElementClass(sr.VariableElement);\r
+               IElement element = Element.spawnNew(elementClass);\r
+                       \r
+               TestDrawable drawable = new TestDrawable();\r
+               drawable.moveTo(\r
+                               (Double)g.getRelatedValue(resource, sr.HasX),\r
+                               (Double)g.getRelatedValue(resource, sr.HasY)\r
+                               );\r
+               element.setHint(DrawableElementClass.KEY_CONTENT, drawable);\r
+               \r
+               //diagram.addElement(element);\r
+               return element;\r
+       }\r
+\r
+       @Override\r
+       public ElementClass create(ReadGraph g, Resource elementType,\r
+                       ElementQuerySupport support) throws DatabaseException {\r
+               return DrawableElementClass.createElementClass(elementType);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/adapters/VariableElementWriter.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/adapters/VariableElementWriter.java
new file mode 100644 (file)
index 0000000..a671b6b
--- /dev/null
@@ -0,0 +1,23 @@
+package org.simantics.sysdyn.ui.adapters;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.synchronization.graph.ElementWriter;\r
+import org.simantics.g2d.element.IElement;\r
+\r
+public class VariableElementWriter implements ElementWriter {\r
+\r
+       @Override\r
+       public void addToGraph(WriteGraph graph, IElement element,\r
+                       Resource elementResource) throws DatabaseException {\r
+               System.out.println("addToGraph");               \r
+       }\r
+\r
+       @Override\r
+       public void removeFromGraph(WriteGraph graph, Resource elementResource)\r
+                       throws DatabaseException {\r
+               System.out.println("removeFromGraph");          \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/DiagramEditorFacade.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/DiagramEditorFacade.java
new file mode 100644 (file)
index 0000000..daf3582
--- /dev/null
@@ -0,0 +1,124 @@
+package org.simantics.sysdyn.ui.diagram;\r
+\r
+import java.awt.Color;\r
+\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;\r
+import org.simantics.diagram.adapter.IDiagramLoader;\r
+import org.simantics.diagram.participant.SGFocusParticipant;\r
+import org.simantics.g2d.canvas.Hints;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.canvas.impl.CanvasContext;\r
+import org.simantics.g2d.chassis.SWTChassis;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.diagram.participant.CanvasBoundsParticipant;\r
+import org.simantics.g2d.diagram.participant.DiagramParticipant;\r
+import org.simantics.g2d.diagram.participant.ElementInteractor;\r
+import org.simantics.g2d.diagram.participant.ElementPainter;\r
+import org.simantics.g2d.diagram.participant.Selection;\r
+import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;\r
+import org.simantics.g2d.element.ElementClassProviders;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.impl.Element;\r
+import org.simantics.g2d.participant.CanvasGrab;\r
+import org.simantics.g2d.participant.KeyUtil;\r
+import org.simantics.g2d.participant.MousePanZoomInteractor;\r
+import org.simantics.g2d.participant.MouseUtil;\r
+import org.simantics.g2d.participant.Notifications;\r
+import org.simantics.g2d.participant.PanZoomRotateHandler;\r
+import org.simantics.g2d.participant.PointerPainter;\r
+import org.simantics.g2d.participant.RulerPainter;\r
+import org.simantics.g2d.participant.SGTransformUtil;\r
+import org.simantics.g2d.snap.GridSnapAdvisor;\r
+import org.simantics.layer0.utils.ResourceArray;\r
+import org.simantics.sysdyn.ui.elements.IDrawable;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.workbench.ResourceEditorPart;\r
+import org.simantics.utils.datastructures.hints.IHintContext;\r
+import org.simantics.utils.threads.AWTThread;\r
+\r
+public abstract class DiagramEditorFacade extends ResourceEditorPart {\r
+\r
+       SWTChassis chassis;\r
+       IDiagram diagram;\r
+       IDiagramLoader loader;\r
+       \r
+       public DiagramEditorFacade() {\r
+               super();                \r
+       }\r
+       \r
+       @Override\r
+       public void reload(ReadGraph g) throws DatabaseException {\r
+               // TODO Auto-generated method stub              \r
+       }\r
+               \r
+       @Override\r
+       public void createPartControl(Composite parent) {\r
+               chassis = new SWTChassis(parent, SWT.NONE);\r
+               chassis.syncPopulate(); \r
+               \r
+               final ICanvasContext context = new CanvasContext(\r
+                               AWTThread.getThreadAccess());\r
+               chassis.setCanvasContext(context);\r
+\r
+               context.add(new SGTransformUtil());\r
+               context.add(new MouseUtil());\r
+               context.add(new KeyUtil());\r
+               context.add(new PanZoomRotateHandler());\r
+               context.add(new MousePanZoomInteractor());\r
+               context.add(new RulerPainter());\r
+               context.add(new CanvasGrab());\r
+               context.add(new CanvasBoundsParticipant());\r
+               context.add(new Notifications());\r
+               context.add(new SGFocusParticipant(chassis));   \r
+               context.add(new DiagramParticipant());\r
+               context.add(new ElementPainter());\r
+               context.add(new PointerInteractor(true, true, true, false, true, false, null));\r
+               context.add(new ElementInteractor());\r
+               context.add(new Selection());        \r
+               \r
+               IHintContext h = context.getDefaultHintContext();               \r
+               h.setHint(PointerPainter.KEY_PAINT_POINTER, true);              \r
+               \r
+               h.setHint(ElementPainter.KEY_SELECTION_FRAME_COLOR, Color.MAGENTA);\r
+        h.setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);\r
+\r
+        h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 100000.0);\r
+        h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 10.0);\r
+\r
+        h.setHint(DiagramHints.SNAP_ADVISOR,\r
+                       new GridSnapAdvisor(10.0));\r
+        \r
+        try {\r
+                       SimanticsUI.getSession().syncRequest(new ReadRequest() {\r
+                               \r
+                               @Override\r
+                               public void run(ReadGraph graph) throws DatabaseException {\r
+                                       loader = new GraphToDiagramSynchronizer(graph, context, \r
+                                                       ElementClassProviders.staticProvider(null));\r
+                                       \r
+                                       diagram = loader.loadDiagram(graph,\r
+                                                       getResourceInput().getResource(),\r
+                                                       ResourceArray.EMPTY, \r
+                                                       null);                                  \r
+                               }\r
+                               \r
+                       });\r
+                       h.setHint(DiagramHints.KEY_DIAGRAM, diagram);\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }               \r
+               \r
+       }\r
+       \r
+       @Override\r
+       public void setFocus() {\r
+               chassis.setFocus();             \r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/DrawableElementClass.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/DrawableElementClass.java
new file mode 100644 (file)
index 0000000..2851dcc
--- /dev/null
@@ -0,0 +1,137 @@
+package org.simantics.sysdyn.ui.diagram;\r
+\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.diagram.adapter.handler.ResourceAdapter;\r
+import org.simantics.g2d.diagram.handler.PickRequest.PickPolicy;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.Move;\r
+import org.simantics.g2d.element.handler.Outline;\r
+import org.simantics.g2d.element.handler.Pick2;\r
+import org.simantics.g2d.element.handler.SceneGraph;\r
+import org.simantics.g2d.element.handler.Transform;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.sysdyn.ui.elements.IDrawable;\r
+import org.simantics.sysdyn.ui.elements.ITransformable;\r
+import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;\r
+\r
+public class DrawableElementClass {\r
+       private DrawableElementClass() {}\r
+       \r
+       public static KeyOf KEY_CONTENT = new KeyOf(IDrawable.class, "CONTENT");\r
+       public static AffineTransform IDENTITY_TRANSFORM = new AffineTransform();\r
+               \r
+       public static WidgetHandler WIDGET_HANDLER_INSTANCE = new WidgetHandler();\r
+       \r
+       private static class WidgetHandler implements Transform, SceneGraph, InternalSize, Move, Outline, Pick2 {\r
+\r
+               private static final long serialVersionUID = 1722978969083481038L;\r
+               \r
+               @Override\r
+               public void setTransform(IElement e, AffineTransform at) {\r
+                       IDrawable drawable = (IDrawable)e.getHint(KEY_CONTENT);\r
+                       if(drawable instanceof ITransformable) {\r
+                               drawable = ((ITransformable)drawable).setTransform(at);\r
+                               e.setHint(KEY_CONTENT, drawable);\r
+                               drawable.updateSG();\r
+                       }\r
+               }\r
+               \r
+               @Override\r
+               public AffineTransform getTransform(IElement e) {\r
+                       IDrawable drawable = (IDrawable)e.getHint(KEY_CONTENT);\r
+                       if(drawable instanceof ITransformable)\r
+                               return ((ITransformable)drawable).getTransform();       \r
+                       else\r
+                               return IDENTITY_TRANSFORM;\r
+               }\r
+               \r
+               @Override\r
+               public void cleanup(IElement e) {\r
+                       ((IDrawable)e.getHint(KEY_CONTENT)).cleanupSG();        \r
+               }\r
+\r
+               @Override\r
+               public void init(IElement e, G2DParentNode parent) {\r
+                       ((IDrawable)e.getHint(KEY_CONTENT)).initSG(parent);\r
+               }\r
+               \r
+               @Override\r
+               public Rectangle2D getBounds(IElement e, Rectangle2D size) {\r
+                       if(size == null)\r
+                               size = new Rectangle2D.Double();\r
+                       ((IDrawable)e.getHint(KEY_CONTENT)).getBounds(size);\r
+                       return size;\r
+               }\r
+\r
+               @Override\r
+               public Point2D getPosition(IElement e) {\r
+                       IDrawable drawable = (IDrawable)e.getHint(KEY_CONTENT);\r
+                       if(drawable instanceof ITransformable)\r
+                               return ((ITransformable)drawable).getPosition();        \r
+                       else\r
+                               return new Point2D.Double(0.0, 0.0);\r
+               }\r
+\r
+               @Override\r
+               public void moveTo(IElement e, double x, double y) {\r
+                       IDrawable drawable = (IDrawable)e.getHint(KEY_CONTENT);\r
+                       if(drawable instanceof ITransformable) {\r
+                               drawable = ((ITransformable)drawable).moveTo(x, y);\r
+                               e.setHint(KEY_CONTENT, drawable);\r
+                               drawable.updateSG();\r
+                       }\r
+               }\r
+\r
+               @Override\r
+               public Shape getElementShape(IElement e) {\r
+                       return getBounds(e, null);\r
+               }\r
+               \r
+               @Override\r
+               public int pick(IElement e, Shape s, PickPolicy policy,\r
+                               Collection<IElement> result) {\r
+                       if(pickTest(e, s, policy)) {\r
+                               result.add(e);\r
+                               return 1;\r
+                       }\r
+                       else\r
+                               return 0;                       \r
+               }\r
+\r
+               @Override\r
+               public boolean pickTest(IElement e, Shape s, PickPolicy policy) {\r
+                       IDrawable drawable = (IDrawable)e.getHint(KEY_CONTENT);\r
+                       switch(policy) {\r
+                       case PICK_CONTAINED_OBJECTS:\r
+                               return drawable.pickContained(s);\r
+                       case PICK_INTERSECTING_OBJECTS:\r
+                               return drawable.pickIntersecting(s);\r
+                       default:\r
+                               return false;\r
+                       }                       \r
+               }\r
+               \r
+       }\r
+\r
+       public static ElementClass createElementClass(final Resource resource) { \r
+               return ElementClass.compile(\r
+                       WIDGET_HANDLER_INSTANCE,\r
+                       new ResourceAdapter() {\r
+\r
+                               @Override\r
+                               public Resource getResource() {\r
+                                       return resource;\r
+                               }\r
+                               \r
+                       }\r
+               );\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/SysdynDiagramEditor.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/diagram/SysdynDiagramEditor.java
new file mode 100644 (file)
index 0000000..614a437
--- /dev/null
@@ -0,0 +1,12 @@
+package org.simantics.sysdyn.ui.diagram;\r
+\r
+import org.simantics.sysdyn.ui.elements.TestDrawable;\r
+\r
+\r
+public class SysdynDiagramEditor extends DiagramEditorFacade {\r
+\r
+       public SysdynDiagramEditor() {\r
+               super();\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/Drawable.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/Drawable.java
new file mode 100644 (file)
index 0000000..90ab9cd
--- /dev/null
@@ -0,0 +1,34 @@
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+\r
+public abstract class Drawable implements IDrawable {\r
+\r
+       public static final AffineTransform IDENTITY = new AffineTransform();\r
+               \r
+       @Override\r
+       public void initSG(G2DParentNode parent) {\r
+       }\r
+       \r
+       @Override\r
+       public void cleanupSG() {\r
+       }\r
+\r
+       @Override\r
+       public void updateSG() {                \r
+       }\r
+\r
+       @Override\r
+       public boolean pickContained(Shape s) {\r
+               return false;\r
+       }\r
+\r
+       @Override\r
+       public boolean pickIntersecting(Shape s) {\r
+               return false;\r
+       }       \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/IDrawable.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/IDrawable.java
new file mode 100644 (file)
index 0000000..d48a3c9
--- /dev/null
@@ -0,0 +1,15 @@
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.Shape;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+\r
+public interface IDrawable {\r
+       void getBounds(Rectangle2D size);\r
+       void initSG(G2DParentNode parent);\r
+       void updateSG();\r
+       void cleanupSG();\r
+       boolean pickIntersecting(Shape s);\r
+       boolean pickContained(Shape s);\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/ITransformable.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/ITransformable.java
new file mode 100644 (file)
index 0000000..266b8b5
--- /dev/null
@@ -0,0 +1,11 @@
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Point2D;\r
+\r
+public interface ITransformable extends IDrawable {\r
+       ITransformable setTransform(AffineTransform at);\r
+       AffineTransform getTransform(); \r
+       public ITransformable moveTo(double x, double y);\r
+       Point2D getPosition();\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/PositionableDrawable.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/PositionableDrawable.java
new file mode 100644 (file)
index 0000000..58d697e
--- /dev/null
@@ -0,0 +1,40 @@
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Point2D;\r
+\r
+public abstract class PositionableDrawable extends Drawable implements ITransformable, Cloneable {\r
+       protected double posX;\r
+       protected double posY;\r
+       \r
+       @Override\r
+       public Point2D getPosition() {\r
+               return new Point2D.Double(posX, posY);\r
+       }\r
+       @Override\r
+       public AffineTransform getTransform() {\r
+               return new AffineTransform(1.0, 0.0, 0.0, 1.0, posX, posY);\r
+       }\r
+       @Override\r
+       public ITransformable moveTo(double x, double y) {\r
+               try {\r
+                       PositionableDrawable d = (PositionableDrawable)clone();\r
+                       d.posX = x;\r
+                       d.posY = y;\r
+                       return d;\r
+               } catch(CloneNotSupportedException e) {                 \r
+                       throw new Error(e);\r
+               }\r
+       }\r
+       @Override\r
+       public ITransformable setTransform(AffineTransform at) {\r
+               try {\r
+                       PositionableDrawable d = (PositionableDrawable)clone();\r
+                       d.posX = at.getTranslateX();\r
+                       d.posY = at.getTranslateY();\r
+                       return d;\r
+               } catch(CloneNotSupportedException e) {                 \r
+                       throw new Error(e);\r
+               }               \r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/TestDrawable.java b/1.8/org.simantics.sysdyn.ui.old/src/org/simantics/sysdyn/ui/elements/TestDrawable.java
new file mode 100644 (file)
index 0000000..5d35c5e
--- /dev/null
@@ -0,0 +1,36 @@
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+\r
+\r
+public class TestDrawable extends PositionableDrawable {\r
+\r
+       @Override\r
+       public void getBounds(Rectangle2D size) {\r
+               size.setFrame(-10.0, -10.0, 20.0, 20.0);\r
+       }\r
+       \r
+       ShapeNode node;\r
+       \r
+       @Override\r
+       public void initSG(G2DParentNode parent) {\r
+               node = parent.addNode(ShapeNode.class);\r
+               node.setShape(new Rectangle2D.Double(-10.0, -10.0, 20.0, 20.0));\r
+       }               \r
+       \r
+       @Override\r
+       public boolean pickContained(Shape s) {\r
+               return s.contains(-10.0, -10.0, 20.0, 20.0);\r
+       }\r
+       \r
+       @Override\r
+       public boolean pickIntersecting(Shape s) {\r
+               return s.intersects(-10.0, -10.0, 20.0, 20.0);\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/.classpath b/1.8/org.simantics.sysdyn.ui/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.sysdyn.ui/.hgignore b/1.8/org.simantics.sysdyn.ui/.hgignore
new file mode 100644 (file)
index 0000000..73df90f
--- /dev/null
@@ -0,0 +1,5 @@
+syntax: regexp\r
+^bin/\r
+\r
+syntax: glob\r
+*.svn/*
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/.project b/1.8/org.simantics.sysdyn.ui/.project
new file mode 100644 (file)
index 0000000..2ebd569
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.sysdyn.ui</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.sysdyn.ui/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.sysdyn.ui/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..f287d53
--- /dev/null
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF b/1.8/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..790eeb2
--- /dev/null
@@ -0,0 +1,72 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Simantics System Dynamics UI
+Bundle-SymbolicName: org.simantics.sysdyn.ui;singleton:=true
+Bundle-Version: 1.8.0.qualifier
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: org.simantics.layer0.utils;bundle-version="0.6.2",
+ org.simantics.scenegraph;bundle-version="0.9.0",
+ org.junit4;bundle-version="4.5.0";resolution:=optional,
+ org.simantics.ui;bundle-version="1.0.0",
+ org.eclipse.ui;bundle-version="3.5.0",
+ org.eclipse.core.runtime;bundle-version="3.5.0",
+ org.simantics.objmap;bundle-version="0.1.0",
+ org.simantics.sysdyn;bundle-version="1.0.0",
+ org.simantics.project;bundle-version="1.0.0",
+ org.eclipse.jface.text;bundle-version="3.5.0",
+ org.eclipse.ui.editors;bundle-version="3.5.0",
+ org.jfree.jcommon;bundle-version="1.0.16",
+ org.jfree.jchart;bundle-version="1.0.13",
+ org.simantics.modelica;bundle-version="1.0.0",
+ org.apache.log4j;bundle-version="1.2.15",
+ org.eclipse.ui.console;bundle-version="3.4.0",
+ org.simantics.browsing.ui.graph;bundle-version="1.1.0",
+ org.simantics.browsing.ui.swt;bundle-version="1.1.0",
+ org.simantics.modeling.ui;bundle-version="1.0.0",
+ org.eclipse.ui.cheatsheets,
+ org.simantics.graphviz.ui;bundle-version="1.0.0",
+ org.simantics.graphviz;bundle-version="1.0.0",
+ org.simantics.diagram;bundle-version="0.9.4",
+ org.simantics.modeling;bundle-version="1.0.0",
+ org.simantics.mapping;bundle-version="1.0.0",
+ org.simantics.structural.ontology;bundle-version="1.0.0",
+ gnu.trove2;bundle-version="2.0.4",
+ org.simantics.simulation;bundle-version="1.0.0",
+ org.simantics.message;bundle-version="0.9.0",
+ org.simantics.structural2;bundle-version="1.0.0",
+ org.simantics.layer0;bundle-version="1.0.0",
+ org.simantics.diagram.ontology;bundle-version="1.0.0",
+ org.simantics.graph;bundle-version="1.0.2",
+ org.simantics.graph.db;bundle-version="1.0.0",
+ org.simantics.structural.ui;bundle-version="1.1.1",
+ org.simantics.browsing.ui.model;bundle-version="1.0.0",
+ org.simantics.spreadsheet.ui;bundle-version="1.1.0",
+ org.simantics.views.swt;bundle-version="1.0.0",
+ org.simantics.selectionview;bundle-version="1.0.0",
+ org.simantics.issues;bundle-version="1.1.0",
+ org.simantics.issues.ui;bundle-version="1.1.0",
+ org.simantics.issues.common;bundle-version="1.1.0",
+ org.simantics.scenegraph.profile;bundle-version="1.0.0",
+ org.simantics.trend;bundle-version="1.0.0",
+ org.simantics.history;bundle-version="1.0.0",
+ org.simantics.utils.thread.swt;bundle-version="1.1.0",
+ org.simantics.jfreechart.ontology;bundle-version="0.1.0",
+ org.eclipse.ui.forms;bundle-version="3.5.2",
+ org.simantics.scenegraph.swing;bundle-version="1.0.0",
+ org.eclipse.nebula.widgets.tablecombo;bundle-version="1.0.0",
+ org.simantics.fmu;bundle-version="1.0.0",
+ org.simantics.jfreechart;bundle-version="1.0.0",
+ org.simantics.db.indexing;bundle-version="1.1.0",
+ org.simantics.workbench,
+ org.simantics.annotation.ui;bundle-version="1.0.0",
+ org.simantics.annotation.ontology;bundle-version="1.0.0",
+ org.simantics.spreadsheet.common;bundle-version="1.1.0"
+Bundle-Activator: org.simantics.sysdyn.ui.Activator
+Bundle-ActivationPolicy: lazy
+Export-Package: org.simantics.sysdyn.ui.browser.nodes
+Bundle-Vendor: VTT Technical Reserarch Centre of Finland
+Bundle-Localization: plugin
+Import-Package: freemarker.template,
+ org.simantics.workbench,
+ org.simantics.workbench.ontology,
+ org.simantics.workbench.search
diff --git a/1.8/org.simantics.sysdyn.ui/Splash.xcf b/1.8/org.simantics.sysdyn.ui/Splash.xcf
new file mode 100644 (file)
index 0000000..388267f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/Splash.xcf differ
diff --git a/1.8/org.simantics.sysdyn.ui/adapters.xml b/1.8/org.simantics.sysdyn.ui/adapters.xml
new file mode 100644 (file)
index 0000000..517bc7e
--- /dev/null
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>\r<!--\r
+    Copyright (c) 2010 Association for Decentralized Information Management in\r
+    Industry THTH ry.\r
+    All rights reserved. This program and the accompanying materials\r
+    are made available under the terms of the Eclipse Public License v1.0\r
+    which accompanies this distribution, and is available at\r
+    http://www.eclipse.org/legal/epl-v10.html\r
+   \r
+    Contributors:\r
+        VTT Technical Research Centre of Finland - initial API and implementation\r
+ -->\r
+
+<adapters>\r\r   <target interface="org.simantics.db.layer0.adapter.Realization">\r               <type uri="http://www.simantics.org/Sysdyn-0.0/Module"\r                 class="org.simantics.structural2.realization.StructuralRealization">\r                   <this />\r               </type>\r        </target>\r\r     <target interface="org.simantics.layer0.utils.triggers.ITrigger">\r      <type uri = "http://www.simantics.org/Sysdyn-0.0/DiagramToCompositeMapping"\r          class = "org.simantics.sysdyn.ui.editor.DiagramToCompositeMapping3">\r         <graph/>\r           <this />\r       </type>\r        </target>\r      \r       <target interface="org.simantics.structural.ui.modelBrowser.nodes.AbstractNode">\r               <type uri="http://www.simantics.org/Sysdyn-0.0/SysdynModel"\r                    class="org.simantics.structural.ui.modelBrowser.nodes.ModelNode">\r                      <this />\r               </type>\r        </target>               \r               \r\r      <target\r                interface="org.simantics.browsing.ui.common.node.AbstractNode">\r                <type\r                  uri="http://www.simantics.org/Sysdyn-0.0/SysdynModel"\r                  class="org.simantics.sysdyn.ui.browser.nodes.ModelNode">\r                       <this />\r               </type>\r\r               <resource\r                      uri="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r                 class="org.simantics.sysdyn.ui.browser.nodes.SymbolNode">\r                      <this />\r               </resource>\r\r           <type\r                  uri="http://www.simantics.org/Simulation-0.0/Experiment"\r                       class="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode">\r                  <this />\r               </type>\r                \r               <type\r                  uri="http://www.simantics.org/Sysdyn-0.0/Result"\r                       class="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode">\r                    <this />\r               </type>\r                \r       </target>\r\r     <!-- Inject default connection routing algorithm for sysdyn diagrams -->\r       <target interface="org.simantics.g2d.diagram.DiagramClass">\r            <adapter uri="http://www.simantics.org/Sysdyn-0.0/ConfigurationDiagram"\r                        adapterClass="org.simantics.sysdyn.ui.elements.ConfigurationDiagramClassAdapter" />\r    </target>\r\r     <!-- Sysdyn symbols -->\r        <target interface="org.simantics.diagram.adapter.ElementFactory">\r              <resource uri="http://www.simantics.org/Sysdyn-0.0/StockSymbol"\r                        class="org.simantics.sysdyn.ui.elements.StockFactory" />\r               <resource uri="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r                       class="org.simantics.sysdyn.ui.elements.ModuleFactory" />\r              <resource uri="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"\r                        class="org.simantics.sysdyn.ui.elements.ValveFactory" />\r               <resource uri="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"\r                    class="org.simantics.sysdyn.ui.elements.AuxiliaryFactory" />\r           <resource uri="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"\r                        class="org.simantics.sysdyn.ui.elements.CloudFactory" />\r               <resource uri="http://www.simantics.org/Sysdyn-0.0/InputSymbol"\r                        class="org.simantics.sysdyn.ui.elements.InputFactory" />\r               <resource uri="http://www.simantics.org/Sysdyn-0.0/ShadowSymbol"\r                       class="org.simantics.sysdyn.ui.elements.ShadowFactory" />                       \r               <resource uri="http://www.simantics.org/Sysdyn-0.0/LoopSymbol"\r                 class="org.simantics.sysdyn.ui.elements.LoopFactory" />                 \r\r              <type uri="http://www.simantics.org/Sysdyn-0.0/StockSymbol"\r                    class="org.simantics.sysdyn.ui.elements.StockFactory" />\r               <type uri="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r                   class="org.simantics.sysdyn.ui.elements.ModuleFactory" />\r              <type uri="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"\r                    class="org.simantics.sysdyn.ui.elements.ValveFactory" />\r               <type uri="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"\r                        class="org.simantics.sysdyn.ui.elements.AuxiliaryFactory" />\r           <type uri="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"\r                    class="org.simantics.sysdyn.ui.elements.CloudFactory" />\r               <type uri="http://www.simantics.org/Sysdyn-0.0/InputSymbol"\r                    class="org.simantics.sysdyn.ui.elements.InputFactory" />        \r               <type uri="http://www.simantics.org/Sysdyn-0.0/ShadowSymbol"\r                   class="org.simantics.sysdyn.ui.elements.ShadowFactory" />       \r               <type uri="http://www.simantics.org/Sysdyn-0.0/LoopSymbol"\r                     class="org.simantics.sysdyn.ui.elements.LoopFactory" /> \r       </target>\r      \r       <!-- Additional symbols -->\r    <target interface="org.simantics.diagram.adapter.ElementFactory">\r          <resource uri="http://www.simantics.org/Sysdyn-0.0/AdditionalSymbols/MultilineText"\r            class="org.simantics.sysdyn.ui.elements.MultilineTextElementFactory" />\r        <type uri="http://www.simantics.org/Sysdyn-0.0/AdditionalSymbols/MultilineText"\r            class="org.simantics.sysdyn.ui.elements.MultilineTextElementFactory" />         \r    </target>                  \r       \r       <!-- Sysdyn connections -->\r    <target interface="org.simantics.diagram.adapter.ElementFactory">\r              <!-- Edges -->       \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/FlowConnection"\r            class="org.simantics.sysdyn.ui.elements.connections.RouteFlowEdgeFactory" />\r        <type uri="http://www.simantics.org/Sysdyn-0.0/FlowConnection"\r            class="org.simantics.sysdyn.ui.elements.connections.RouteFlowEdgeFactory" />            \r        <type uri="http://www.simantics.org/Sysdyn-0.0/FlowConnection"\r            class="org.simantics.sysdyn.ui.elements.connections.RouteFlowConnectionFactory">\r            <graph/>\r        </type>                          \r                       \r               <resource uri="http://www.simantics.org/Sysdyn-0.0/DependencyConnection"\r                       class="org.simantics.sysdyn.ui.elements.connections.DependencyEdgeFactory" />\r          <type uri="http://www.simantics.org/Sysdyn-0.0/DependencyConnection"\r                   class="org.simantics.sysdyn.ui.elements.connections.DependencyEdgeFactory" />\r          <type uri="http://www.simantics.org/Sysdyn-0.0/DependencyConnection"\r                   class="org.simantics.sysdyn.ui.elements.connections.DependencyConnectionFactory" />\r    </target>\r      \r       <target interface="org.simantics.g2d.connection.EdgeVisualsConfigurer">\r          <baseType uri="http://www.simantics.org/Diagram-0.0/HasConnector" />\r   <resource uri="http://www.simantics.org/Diagram-0.0/HasPlainConnector"\r          class="org.simantics.diagram.content.ArrowConfigurer">\r         <string>none 0</string>\r       </resource>\r    <resource uri="http://www.simantics.org/Diagram-0.0/HasArrowConnector"\r          class="org.simantics.diagram.content.ArrowConfigurer">\r         <string>fill 1</string>\r       </resource>\r  </target>\r      \r       <!-- ModelBrowser2 -->\r \r       <target interface="org.simantics.browsing.ui.model.children.ChildRule">\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/ModuleTypeChildRule"\r            class="org.simantics.sysdyn.ui.browser.childrules.ModuleTypeChildRule"/>\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/ModuleContentChildRule"\r            class="org.simantics.sysdyn.ui.browser.childrules.ModuleContentChildRule"/>              \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/VariableChildRule"\r            class="org.simantics.sysdyn.ui.browser.childrules.VariableChildRule"/>                  \r                  \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/HistoryDataset/HistoryDatasetVariablesBrowseContext/VariableChildRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.historyDataset.VariableChildRule"/>     \r        <resource uri=" http://www.simantics.org/Sysdyn-0.0/Module/ParameterOverrideBrowseContext/ParameterChildRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.modules.ParameterChildRule"/>              \r            \r            \r       <!-- Sensitivity analysis -->\r      <resource uri="http://www.simantics.org/Sysdyn-0.0/SensitivityAnalysisExperiment/ParameterBrowseContext/ParameterChildRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.sensitivity.ParameterChildRule"/>         \r    </target>\r    \r    <target interface="org.simantics.browsing.ui.model.visuals.VisualsRule">\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/ModuleTypeLabelRule"\r            class="org.simantics.sysdyn.ui.browser.labelrules.ModuleTypeLabelRule"/>\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/VariableNameLabelRule"\r            class="org.simantics.sysdyn.ui.browser.labelrules.VariableNameLabelRule"/>\r\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/VariableImageRule"\r            class="org.simantics.sysdyn.ui.browser.imagerules.VariableImageRule"/>   \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/ChartImageRule"\r            class="org.simantics.sysdyn.ui.browser.imagerules.ChartImageRule"/>      \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/ResultImageRule"\r            class="org.simantics.sysdyn.ui.browser.imagerules.ResultImageRule"/>                        \r            \r  \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/HistoryDataset/HistoryDatasetVariablesBrowseContext/VariableLabelRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.historyDataset.VariableLabelRule"/>                \r\r            \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/Module/ParameterOverrideBrowseContext/ParameterLabelRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.modules.ParameterLabelRule"/>    \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/Module/ParameterOverrideBrowseContext/ParameterLabelDecorationRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.modules.ParameterLabelDecorationRule"/>               \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/Module/ParameterOverrideBrowseContext/ParameterModifierRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.modules.ParameterModifierRule"/>    \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/Module/ParameterOverrideBrowseContext/ParameterSorterRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.modules.ParameterSorterRule"/>      \r            \r    <!-- Sensitivity analysis -->\r      <resource uri="http://www.simantics.org/Sysdyn-0.0/SensitivityAnalysisExperiment/ParameterBrowseContext/ParameterLabelRule"\r            class="org.simantics.sysdyn.ui.properties.widgets.sensitivity.ParameterLabelRule"/>\r\r    </target>    \r    \r    <target interface="org.simantics.db.layer0.adapter.ActionFactory">\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewModuleType"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewModuleTypeAction" />\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewEnumeration"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewEnumerationAction" />\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewFunction"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewFunctionAction" />\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewFunctionLibrary"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewFunctionLibraryAction" />\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewSharedFunctionLibrary"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewSharedFunctionLibraryAction" />   \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewExperiment"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewExperimentAction" />   \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewSimulationPlaybackExperiment"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewSimulationPlaybackExperimentAction" />    \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewLineChart"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewLineChartAction" /> \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewBarChart"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewBarChartAction" /> \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewPieChart"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewPieChartAction" />        \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewSheet"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewSheetAction" />       \r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewHistoryData"\r            class="org.simantics.sysdyn.ui.browser.actions.newActions.NewHistoryDataAction" />                                                                                              \r    </target>         \r    \r   <target interface="org.simantics.db.layer0.adapter.DropActionFactory">\r        <resource\r            uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/FunctionDropAction"\r            class="org.simantics.sysdyn.ui.browser.actions.drop.FunctionDropAction" />\r        <resource\r            uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/ChartDropAction"\r            class="org.simantics.sysdyn.ui.browser.actions.drop.ChartDropAction" />            \r   \r                    \r    </target>     \r  \r    <target interface="org.simantics.db.layer0.adapter.Remover">\r        <type uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/ModuleSymbol"\r            class="org.simantics.sysdyn.ui.browser.actions.remove.ModuleTypeRemover">\r            <graph />\r            <this />\r        </type>\r        <type uri="http://www.simantics.org/Sysdyn-0.0/Variable"\r            class="org.simantics.sysdyn.ui.actions.SysdynVariableRemover">\r            <this />\r        </type>\r    </target>\r    \r    \r    <target interface="org.simantics.browsing.ui.model.nodetypes.NodeType">\r        <baseType uri="http://www.simantics.org/Layer0-0.0/Entity" />\r        <type\r            uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/ModuleSymbolNodeType"\r            class="org.simantics.sysdyn.ui.browser.nodeTypes.ModuleSymbolNodeType"\r            constructor="create">\r            <this/>\r        </type>        \r     </target>\r    \r  <!-- PROFILES -->\r    <target interface="org.simantics.scenegraph.profile.Style">\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/SimulationPlaybackStyle"\r            class="org.simantics.sysdyn.ui.elements.profiles.SimulationPlaybackStyle">\r        </resource>\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/IssueStyle"\r            class="org.simantics.sysdyn.ui.elements.profiles.IssueDecorationStyle">\r        </resource>\r        <resource uri="http://www.simantics.org/Sysdyn-0.0/ShadowStyle"\r            class="org.simantics.sysdyn.ui.elements.profiles.ShadowStyle">\r        </resource>        \r    </target>\r    \r \r    <!--  TODO: currently maps jfree concepts directly to Sysdyn implementations. Sysdyn needs tool specific types for the datasets. -->\r    <!--  TODO: AllVariablesOfModel query is run on random Resources; listing all possible types explicitly is cumbersome, we need a better implementation. -->\r    <target interface="org.simantics.jfreechart.chart.properties.IAllVariablesOfModel">  \r        <type uri="http://www.simantics.org/Sysdyn-1.1/SysdynModel"\r            class="org.simantics.sysdyn.ui.trend.AllVariablesOfModel">\r            <this />\r        </type>  \r        <type uri="http://www.simantics.org/JFreeChart-1.0/NumberAxis"\r            class="org.simantics.sysdyn.ui.trend.AllVariablesOfModel">\r            <this />\r        </type>   \r        <type uri="http://www.simantics.org/JFreeChart-1.0/Series"\r            class="org.simantics.sysdyn.ui.trend.AllVariablesOfModel">\r            <this />\r        </type>      \r        <type uri="http://www.simantics.org/Sysdyn-0.0/SensitivityAnalysisExperiment/Parameter"\r            class="org.simantics.sysdyn.ui.trend.AllParametersOfModel">\r            <this />\r        </type>\r    </target> \r       \r    <target interface="org.simantics.jfreechart.chart.properties.RangeHandlerFactory">  \r        <type uri="http://www.simantics.org/JFreeChart-1.0/Series"\r            class="org.simantics.sysdyn.ui.trend.SysdynRangeHandlerFactory">\r        </type>    \r        <type uri="http://www.simantics.org/Sysdyn-0.0/SensitivityAnalysisExperiment/Parameter"\r            class="org.simantics.sysdyn.ui.properties.widgets.sensitivity.SensitivityRangeHandlerFactory">\r        </type>\r    </target> \r    \r    <!--  TODO: currently maps jfree concepts directly to Sysdyn implementations. Sysdyn needs tool specific types for the datasets. -->\r     <target interface="org.simantics.jfreechart.chart.IDataset">\r        <type uri="http://www.simantics.org/JFreeChart-0.0/XYDataset"\r            class="org.simantics.sysdyn.ui.trend.XYDataset">\r            <graph />\r            <this />\r        </type>\r        <type uri="http://www.simantics.org/JFreeChart-0.0/CategoryDataset"\r            class="org.simantics.sysdyn.ui.trend.CategoryDataset">\r            <graph />\r            <this />\r        </type>        \r        <type uri="http://www.simantics.org/JFreeChart-0.0/PieDataset"\r            class="org.simantics.sysdyn.ui.trend.PieDataset">\r            <graph />\r            <this />\r        </type>   \r        <type uri="http://www.simantics.org/Sysdyn-0.0/Charts/SensitivityDataset"\r            class="org.simantics.sysdyn.ui.trend.SensitivityDataset">\r            <graph />\r            <this />\r        </type>\r    </target>\r    \r       <!-- Sensitivity analysis -->\r   <target\r        interface="org.simantics.sysdyn.ui.properties.widgets.sensitivity.IDistributionProperties">\r        <type\r            uri="http://www.simantics.org/Sysdyn-0.0/NormalDistribution"\r            class="org.simantics.sysdyn.ui.properties.widgets.sensitivity.NormalDistributionProperties">\r            <this />\r        </type>       \r        <type\r            uri="http://www.simantics.org/Sysdyn-0.0/UniformDistribution"\r            class="org.simantics.sysdyn.ui.properties.widgets.sensitivity.UniformDistributionProperties">\r            <this />\r        </type> \r        <type\r            uri="http://www.simantics.org/Sysdyn-0.0/Interval"\r            class="org.simantics.sysdyn.ui.properties.widgets.sensitivity.IntervalProperties">\r            <this />\r        </type>\r    </target>\r    \r    <!-- Search -->\r       <target interface="org.simantics.scl.runtime.function.Function">\r               <resource uri="http://www.simantics.org/Sysdyn-0.0/ModulesSearchFunction"\r                      class="org.simantics.sysdyn.ui.function.ModulesSearchFunction">\r                </resource>\r    </target>\r    \r
+</adapters>
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/build.properties b/1.8/org.simantics.sysdyn.ui/build.properties
new file mode 100644 (file)
index 0000000..258de40
--- /dev/null
@@ -0,0 +1,21 @@
+###############################################################################\r
+# Copyright (c) 2010 Association for Decentralized Information Management in\r
+# Industry THTH ry.\r
+# All rights reserved. This program and the accompanying materials\r
+# are made available under the terms of the Eclipse Public License v1.0\r
+# which accompanies this distribution, and is available at\r
+# http://www.eclipse.org/legal/epl-v10.html\r
+#\r
+# Contributors:\r
+#     VTT Technical Research Centre of Finland - initial API and implementation\r
+###############################################################################\r
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               plugin.xml,\\r
+               adapters.xml,\\r
+               icons/,\\r
+               splash.bmp,\\r
+               plugin.properties,\\r
+               plugin_customization.ini\r
diff --git a/1.8/org.simantics.sysdyn.ui/icons/box.png b/1.8/org.simantics.sysdyn.ui/icons/box.png
new file mode 100644 (file)
index 0000000..8443c23
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/box.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/brick.png b/1.8/org.simantics.sysdyn.ui/icons/brick.png
new file mode 100644 (file)
index 0000000..7851cf3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/brick.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/brick_link.png b/1.8/org.simantics.sysdyn.ui/icons/brick_link.png
new file mode 100644 (file)
index 0000000..9ebf013
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/brick_link.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/bricks.png b/1.8/org.simantics.sysdyn.ui/icons/bricks.png
new file mode 100644 (file)
index 0000000..0905f93
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/bricks.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/bullet_gray.png b/1.8/org.simantics.sysdyn.ui/icons/bullet_gray.png
new file mode 100644 (file)
index 0000000..6f58b93
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/bullet_gray.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/bullet_green.png b/1.8/org.simantics.sysdyn.ui/icons/bullet_green.png
new file mode 100644 (file)
index 0000000..1b5409f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/bullet_green.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_bar.png b/1.8/org.simantics.sysdyn.ui/icons/chart_bar.png
new file mode 100644 (file)
index 0000000..9051fbc
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_bar.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_bar_3.png b/1.8/org.simantics.sysdyn.ui/icons/chart_bar_3.png
new file mode 100644 (file)
index 0000000..15b7cae
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_bar_3.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_bar_3_blackAndWhite.png b/1.8/org.simantics.sysdyn.ui/icons/chart_bar_3_blackAndWhite.png
new file mode 100644 (file)
index 0000000..0e23ab3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_bar_3_blackAndWhite.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_bar_blackAndWhite.png b/1.8/org.simantics.sysdyn.ui/icons/chart_bar_blackAndWhite.png
new file mode 100644 (file)
index 0000000..087f88c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_bar_blackAndWhite.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_bar_light.png b/1.8/org.simantics.sysdyn.ui/icons/chart_bar_light.png
new file mode 100644 (file)
index 0000000..6069b5c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_bar_light.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_line.png b/1.8/org.simantics.sysdyn.ui/icons/chart_line.png
new file mode 100644 (file)
index 0000000..85020f3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_line.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_line_light.png b/1.8/org.simantics.sysdyn.ui/icons/chart_line_light.png
new file mode 100644 (file)
index 0000000..2a77b24
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_line_light.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_organisation.png b/1.8/org.simantics.sysdyn.ui/icons/chart_organisation.png
new file mode 100644 (file)
index 0000000..c32d25c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_organisation.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_pie.png b/1.8/org.simantics.sysdyn.ui/icons/chart_pie.png
new file mode 100644 (file)
index 0000000..fe00fa0
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_pie.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/chart_pie_light.png b/1.8/org.simantics.sysdyn.ui/icons/chart_pie_light.png
new file mode 100644 (file)
index 0000000..fa553c2
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/chart_pie_light.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/close.gif b/1.8/org.simantics.sysdyn.ui/icons/close.gif
new file mode 100644 (file)
index 0000000..1aca259
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/close.gif differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/control_fastforward.png b/1.8/org.simantics.sysdyn.ui/icons/control_fastforward.png
new file mode 100644 (file)
index 0000000..31f7fd3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/control_fastforward.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/control_fastforward_blue.png b/1.8/org.simantics.sysdyn.ui/icons/control_fastforward_blue.png
new file mode 100644 (file)
index 0000000..4a2f9d4
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/control_fastforward_blue.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/control_pause.png b/1.8/org.simantics.sysdyn.ui/icons/control_pause.png
new file mode 100644 (file)
index 0000000..2d9ce9c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/control_pause.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/control_pause_blue.png b/1.8/org.simantics.sysdyn.ui/icons/control_pause_blue.png
new file mode 100644 (file)
index 0000000..ec61099
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/control_pause_blue.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/control_play.png b/1.8/org.simantics.sysdyn.ui/icons/control_play.png
new file mode 100644 (file)
index 0000000..0846555
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/control_play.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/control_play_blue.png b/1.8/org.simantics.sysdyn.ui/icons/control_play_blue.png
new file mode 100644 (file)
index 0000000..f8c8ec6
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/control_play_blue.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/control_step.png b/1.8/org.simantics.sysdyn.ui/icons/control_step.png
new file mode 100644 (file)
index 0000000..820b020
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/control_step.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/control_step_blue.png b/1.8/org.simantics.sysdyn.ui/icons/control_step_blue.png
new file mode 100644 (file)
index 0000000..98071cc
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/control_step_blue.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/cursor.png b/1.8/org.simantics.sysdyn.ui/icons/cursor.png
new file mode 100644 (file)
index 0000000..532f532
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/cursor.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/dependency.png b/1.8/org.simantics.sysdyn.ui/icons/dependency.png
new file mode 100644 (file)
index 0000000..768b55f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/dependency.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/dependency_old.png b/1.8/org.simantics.sysdyn.ui/icons/dependency_old.png
new file mode 100644 (file)
index 0000000..6a604a3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/dependency_old.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/equalizer.png b/1.8/org.simantics.sysdyn.ui/icons/equalizer.png
new file mode 100644 (file)
index 0000000..e496cf4
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/equalizer.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/error.svg b/1.8/org.simantics.sysdyn.ui/icons/error.svg
new file mode 100644 (file)
index 0000000..e4eb0ab
--- /dev/null
@@ -0,0 +1,151 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   version="1.0"
+   width="744.09448"
+   height="1052.3622"
+   id="svg2"
+   sodipodi:version="0.32"
+   inkscape:version="0.46"
+   sodipodi:docname="error.svg"
+   inkscape:output_extension="org.inkscape.output.svg.inkscape">
+  <metadata
+     id="metadata29">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <sodipodi:namedview
+     inkscape:window-height="841"
+     inkscape:window-width="1212"
+     inkscape:pageshadow="2"
+     inkscape:pageopacity="0.0"
+     guidetolerance="10.0"
+     gridtolerance="10.0"
+     objecttolerance="10.0"
+     borderopacity="1.0"
+     bordercolor="#666666"
+     pagecolor="#ffffff"
+     id="base"
+     showgrid="false"
+     inkscape:zoom="7.0241977"
+     inkscape:cx="-17.826432"
+     inkscape:cy="1037.7942"
+     inkscape:window-x="270"
+     inkscape:window-y="71"
+     inkscape:current-layer="svg2"
+     inkscape:window-maximized="0" />
+  <defs
+     id="defs4">
+    <inkscape:perspective
+       sodipodi:type="inkscape:persp3d"
+       inkscape:vp_x="0 : 526.18109 : 1"
+       inkscape:vp_y="0 : 1000 : 0"
+       inkscape:vp_z="744.09448 : 526.18109 : 1"
+       inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
+       id="perspective31" />
+    <linearGradient
+       id="linearGradient3488">
+      <stop
+         id="stop3490"
+         style="stop-color:#000000;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3492"
+         style="stop-color:#000000;stop-opacity:0"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       id="linearGradient3420">
+      <stop
+         id="stop3422"
+         style="stop-color:#ff1e1e;stop-opacity:1;"
+         offset="0" />
+      <stop
+         id="stop3424"
+         style="stop-color:#dc2828;stop-opacity:1;"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="315.71429"
+       y1="502.36218"
+       x2="472.85712"
+       y2="502.36218"
+       id="linearGradient3426"
+       xlink:href="#linearGradient3420"
+       gradientUnits="userSpaceOnUse" />
+    <linearGradient
+       x1="315.71429"
+       y1="502.36218"
+       x2="472.85712"
+       y2="502.36218"
+       id="linearGradient3494"
+       xlink:href="#linearGradient3488"
+       gradientUnits="userSpaceOnUse" />
+    <linearGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3420"
+       id="linearGradient2411"
+       gradientUnits="userSpaceOnUse"
+       x1="315.71429"
+       y1="502.36218"
+       x2="472.85712"
+       y2="502.36218"
+       gradientTransform="matrix(0,-2.7617189e-2,2.7612784e-2,0,-11.701736,14.171172)" />
+    <linearGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3488"
+       id="linearGradient2413"
+       gradientUnits="userSpaceOnUse"
+       x1="315.71429"
+       y1="502.36218"
+       x2="472.85712"
+       y2="502.36218"
+       gradientTransform="matrix(0,-2.7617189e-2,2.7612784e-2,0,-11.701736,14.171172)" />
+  </defs>
+  <path
+     style="fill:url(#linearGradient2411);fill-opacity:1;fill-rule:evenodd;stroke:url(#linearGradient2413);stroke-width:0;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+     id="path2383"
+     d="M 2.1698824,1.1121873 C 3.3682412,1.1119962 4.3398041,2.0835591 4.3398041,3.2821091 C 4.3398041,4.4806589 3.3682412,5.4522219 2.1698824,5.4520308 C 0.97152351,5.4522219 -3.9437272e-05,4.4806589 -3.9437272e-05,3.2821091 C -3.9437272e-05,2.0835591 0.97152351,1.1119962 2.1698824,1.1121873 L 2.1698824,1.1121873 z" />
+  <g
+     style="fill:#ffffff;fill-opacity:1;stroke:none"
+     id="g3164"
+     transform="matrix(9.4934061e-2,0,0,1.3562015e-2,-34.990031,-2.4459735)">
+    <rect
+       style="opacity:0.8;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:12.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+       id="rect3166"
+       y="472.36218"
+       x="388.57144"
+       height="40"
+       width="5.7142859" />
+  </g>
+  <path
+     style="opacity:0.8;fill:none;fill-rule:evenodd;stroke:#ffffff;stroke-width:0.35824198;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+     id="path2385"
+     d="M 3.8894553,3.2821081 C 3.8894553,4.2317955 3.1195813,5.0016695 2.1698938,5.0016695 C 1.2202064,5.0016695 0.45033238,4.2317955 0.45033238,3.2821081 C 0.45033238,2.3324207 1.2202064,1.5625466 2.1698938,1.5625466 C 3.1195813,1.5625466 3.8894553,2.3324207 3.8894553,3.2821081 z" />
+  <g
+     style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-opacity:1"
+     id="g3159"
+     transform="matrix(9.4934061e-2,0,0,4.0686044e-2,-34.990031,-17.157021)">
+    <rect
+       style="opacity:0.8;fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:12.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+       id="rect3157"
+       y="472.36218"
+       x="388.57144"
+       height="40"
+       width="5.7142859" />
+  </g>
+</svg>
diff --git a/1.8/org.simantics.sysdyn.ui/icons/error_decoration.png b/1.8/org.simantics.sysdyn.ui/icons/error_decoration.png
new file mode 100644 (file)
index 0000000..688ad22
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/error_decoration.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/fatal.svg b/1.8/org.simantics.sysdyn.ui/icons/fatal.svg
new file mode 100644 (file)
index 0000000..5ee4816
--- /dev/null
@@ -0,0 +1,612 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
+<svg
+   xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   version="1.0"
+   width="744.09448"
+   height="1052.3622"
+   id="svg2">
+  <metadata
+     id="metadata29">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+        <dc:title></dc:title>
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <defs
+     id="defs4">
+    <linearGradient
+       id="linearGradient3488">
+      <stop
+         id="stop3490"
+         style="stop-color:#000000;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3492"
+         style="stop-color:#000000;stop-opacity:0"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       id="linearGradient3420">
+      <stop
+         id="stop3422"
+         style="stop-color:#ff1e1e;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3424"
+         style="stop-color:#dc2828;stop-opacity:1"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="315.71429"
+       y1="502.36218"
+       x2="472.85712"
+       y2="502.36218"
+       id="linearGradient3426"
+       xlink:href="#linearGradient3420"
+       gradientUnits="userSpaceOnUse" />
+    <linearGradient
+       x1="315.71429"
+       y1="502.36218"
+       x2="472.85712"
+       y2="502.36218"
+       id="linearGradient3494"
+       xlink:href="#linearGradient3488"
+       gradientUnits="userSpaceOnUse" />
+    <linearGradient
+       x1="111.7876"
+       y1="230.2852"
+       x2="111.7876"
+       y2="142.84979"
+       id="linearGradient3407"
+       xlink:href="#XMLID_3_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="111.7876"
+       y1="230.2852"
+       x2="111.7876"
+       y2="142.84979"
+       id="XMLID_3_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3166"
+         style="stop-color:#ffffff;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3167"
+         style="stop-color:#fafafa;stop-opacity:1"
+         offset="0.1019" />
+      <stop
+         id="stop3168"
+         style="stop-color:#ebebeb;stop-opacity:1"
+         offset="0.2256" />
+      <stop
+         id="stop3169"
+         style="stop-color:#d2d2d2;stop-opacity:1"
+         offset="0.36059999" />
+      <stop
+         id="stop3170"
+         style="stop-color:#b0b0b0;stop-opacity:1"
+         offset="0.50370002" />
+      <stop
+         id="stop3171"
+         style="stop-color:#848484;stop-opacity:1"
+         offset="0.65319997" />
+      <stop
+         id="stop3172"
+         style="stop-color:#4e4e4e;stop-opacity:1"
+         offset="0.80809999" />
+      <stop
+         id="stop3173"
+         style="stop-color:#0f0f0f;stop-opacity:1"
+         offset="0.96460003" />
+      <stop
+         id="stop3174"
+         style="stop-color:#000000;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3175"
+         style="stop-color:#FFFFFF"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3176"
+         style="stop-color:#FFFFFF"
+         offset="0.6667" />
+      <a:midPointStop
+         id="midPointStop3177"
+         style="stop-color:#000000"
+         offset="1" />
+    </linearGradient>
+    <radialGradient
+       cx="223.2383"
+       cy="994.02441"
+       r="45.424"
+       fx="223.2383"
+       fy="994.02441"
+       id="radialGradient3409"
+       xlink:href="#XMLID_4_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(1.273125,-0.583125,0.4891875,1.0680937,-219.67181,-763.6707)" />
+    <radialGradient
+       cx="223.2383"
+       cy="994.02441"
+       r="45.424"
+       fx="223.2383"
+       fy="994.02441"
+       id="XMLID_4_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(1.358,-0.622,0.5218,1.1393,-739.9166,-885.3684)">
+      <stop
+         id="stop3180"
+         style="stop-color:#ffffff;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3181"
+         style="stop-color:#000000;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3182"
+         style="stop-color:#FFFFFF"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3183"
+         style="stop-color:#FFFFFF"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3184"
+         style="stop-color:#000000"
+         offset="1" />
+    </radialGradient>
+    <linearGradient
+       x1="131.50101"
+       y1="96.0942"
+       x2="141.1622"
+       y2="105.7555"
+       id="linearGradient3411"
+       xlink:href="#XMLID_5_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="131.50101"
+       y1="96.0942"
+       x2="141.1622"
+       y2="105.7555"
+       id="XMLID_5_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3188"
+         style="stop-color:#ffffff;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3189"
+         style="stop-color:#000000;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3190"
+         style="stop-color:#FFFFFF"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3191"
+         style="stop-color:#FFFFFF"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3192"
+         style="stop-color:#000000"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="139.91209"
+       y1="98.640602"
+       x2="154.45309"
+       y2="98.640602"
+       id="linearGradient3413"
+       xlink:href="#XMLID_6_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="139.91209"
+       y1="98.640602"
+       x2="154.45309"
+       y2="98.640602"
+       id="XMLID_6_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3196"
+         style="stop-color:#bbbbbb;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3197"
+         style="stop-color:#888888;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3198"
+         style="stop-color:#BBBBBB"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3199"
+         style="stop-color:#BBBBBB"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3200"
+         style="stop-color:#888888"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="145.959"
+       y1="93.064499"
+       x2="166.4863"
+       y2="93.064499"
+       id="linearGradient3415"
+       xlink:href="#XMLID_7_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="145.959"
+       y1="93.064499"
+       x2="166.4863"
+       y2="93.064499"
+       id="XMLID_7_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3203"
+         style="stop-color:#ff9200;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3204"
+         style="stop-color:#ff0000;stop-opacity:1"
+         offset="0.264" />
+      <stop
+         id="stop3205"
+         style="stop-color:#fa0000;stop-opacity:1"
+         offset="0.37470001" />
+      <stop
+         id="stop3206"
+         style="stop-color:#eb0000;stop-opacity:1"
+         offset="0.50889999" />
+      <stop
+         id="stop3207"
+         style="stop-color:#d20000;stop-opacity:1"
+         offset="0.65539998" />
+      <stop
+         id="stop3208"
+         style="stop-color:#b00000;stop-opacity:1"
+         offset="0.81059998" />
+      <stop
+         id="stop3209"
+         style="stop-color:#850000;stop-opacity:1"
+         offset="0.97109997" />
+      <stop
+         id="stop3210"
+         style="stop-color:#7c0000;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3211"
+         style="stop-color:#FF9200"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3212"
+         style="stop-color:#FF9200"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3213"
+         style="stop-color:#FF0000"
+         offset="0.264" />
+      <a:midPointStop
+         id="midPointStop3214"
+         style="stop-color:#FF0000"
+         offset="0.6667" />
+      <a:midPointStop
+         id="midPointStop3215"
+         style="stop-color:#7C0000"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="158.666"
+       y1="69.667"
+       x2="171.85741"
+       y2="69.667"
+       id="linearGradient3417"
+       xlink:href="#XMLID_8_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="158.666"
+       y1="69.667"
+       x2="171.85741"
+       y2="69.667"
+       id="XMLID_8_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3218"
+         style="stop-color:#ff6d00;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3219"
+         style="stop-color:#ff3300;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3220"
+         style="stop-color:#FF6D00"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3221"
+         style="stop-color:#FF6D00"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3222"
+         style="stop-color:#FF3300"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="160.666"
+       y1="69.8423"
+       x2="168.79691"
+       y2="69.8423"
+       id="linearGradient3419"
+       xlink:href="#XMLID_9_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="160.666"
+       y1="69.8423"
+       x2="168.79691"
+       y2="69.8423"
+       id="XMLID_9_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3225"
+         style="stop-color:#ffae00;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3226"
+         style="stop-color:#fff030;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3227"
+         style="stop-color:#FFAE00"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3228"
+         style="stop-color:#FFAE00"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3229"
+         style="stop-color:#FFF030"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="169.2207"
+       y1="81.175797"
+       x2="193.29491"
+       y2="81.175797"
+       id="linearGradient3421"
+       xlink:href="#XMLID_10_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="169.2207"
+       y1="81.175797"
+       x2="193.29491"
+       y2="81.175797"
+       id="XMLID_10_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3232"
+         style="stop-color:#ff6d00;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3233"
+         style="stop-color:#ff3300;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3234"
+         style="stop-color:#FF6D00"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3235"
+         style="stop-color:#FF6D00"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3236"
+         style="stop-color:#FF3300"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="171.38091"
+       y1="80.176804"
+       x2="189.1348"
+       y2="80.176804"
+       id="linearGradient3423"
+       xlink:href="#XMLID_11_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="171.38091"
+       y1="80.176804"
+       x2="189.1348"
+       y2="80.176804"
+       id="XMLID_11_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3239"
+         style="stop-color:#ffae00;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3240"
+         style="stop-color:#fff030;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3241"
+         style="stop-color:#FFAE00"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3242"
+         style="stop-color:#FFAE00"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3243"
+         style="stop-color:#FFF030"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="170.4492"
+       y1="100.71"
+       x2="194.9375"
+       y2="100.71"
+       id="linearGradient3425"
+       xlink:href="#XMLID_12_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="170.4492"
+       y1="100.71"
+       x2="194.9375"
+       y2="100.71"
+       id="XMLID_12_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3246"
+         style="stop-color:#ff6d00;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3247"
+         style="stop-color:#ff3300;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3248"
+         style="stop-color:#FF6D00"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3249"
+         style="stop-color:#FF6D00"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3250"
+         style="stop-color:#FF3300"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="172.3457"
+       y1="99.710899"
+       x2="191.03909"
+       y2="99.710899"
+       id="linearGradient3427"
+       xlink:href="#XMLID_13_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+    <linearGradient
+       x1="172.3457"
+       y1="99.710899"
+       x2="191.03909"
+       y2="99.710899"
+       id="XMLID_13_"
+       gradientUnits="userSpaceOnUse">
+      <stop
+         id="stop3253"
+         style="stop-color:#ffae00;stop-opacity:1"
+         offset="0" />
+      <stop
+         id="stop3254"
+         style="stop-color:#fff030;stop-opacity:1"
+         offset="1" />
+      <a:midPointStop
+         id="midPointStop3255"
+         style="stop-color:#FFAE00"
+         offset="0" />
+      <a:midPointStop
+         id="midPointStop3256"
+         style="stop-color:#FFAE00"
+         offset="0.5" />
+      <a:midPointStop
+         id="midPointStop3257"
+         style="stop-color:#FFF030"
+         offset="1" />
+    </linearGradient>
+    <linearGradient
+       x1="172.3457"
+       y1="99.710899"
+       x2="191.03909"
+       y2="99.710899"
+       id="linearGradient3175"
+       xlink:href="#XMLID_13_"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.9375,0,0,0.9375,474,66.36218)" />
+  </defs>
+  <g
+     transform="matrix(0.0330998,0,0,0.0330998,-17.583388,-2.9032996)"
+     id="g3390">
+    <path
+       d="m 616.36125,173.18655 c 1.50375,-1.15031 3.06188,-2.51625 4.66781,-4.12125 -0.007,-0.0553 -0.0131,-0.10593 -0.0197,-0.15937 0.21751,-0.11344 0.42657,-0.24938 0.60938,-0.43406 2.15906,-2.15719 -0.615,-6.8625 -4.32281,-10.56844 -3.70406,-3.70406 -8.41219,-6.47813 -10.56657,-4.32281 -0.18656,0.18656 -0.32249,0.3975 -0.43781,0.61875 -0.0534,-0.009 -0.10218,-0.0187 -0.15562,-0.0272 -2.56125,2.56125 -4.515,5.00437 -5.94938,7.28531 -5.8725,-2.595 -12.36281,-4.04625 -19.19437,-4.04625 -26.26313,0 -47.55563,21.29344 -47.55563,47.55469 0,26.26687 21.2925,47.55469 47.55563,47.55469 26.26406,0 47.55375,-21.28782 47.55375,-47.55469 -9.4e-4,-12.2175 -4.61156,-23.35594 -12.18469,-31.77938 z"
+       id="path3163"
+       style="opacity:0.2;stroke:none" />
+    <path
+       d="m 531.24656,202.77499 c 0,26.26688 21.29157,47.55469 47.55469,47.55469 26.26406,0 47.55375,-21.28781 47.55375,-47.55469 0,-26.26125 -21.28969,-47.55281 -47.55375,-47.55281 -26.26312,0 -47.55469,21.29156 -47.55469,47.55281 z"
+       id="path3164"
+       style="stroke:none" />
+    <path
+       d="m 533.96344,202.77499 c 0,24.72469 20.11594,44.83875 44.83687,44.83875 24.72469,0 44.83688,-20.11406 44.83688,-44.83875 0,-24.72281 -20.11219,-44.835 -44.83688,-44.835 -24.72093,0 -44.83687,20.11219 -44.83687,44.835 z"
+       id="path3178"
+       style="opacity:0.6;fill:url(#linearGradient3407);stroke:none" />
+    <path
+       d="m 541.89094,197.46687 c 5.15437,11.25937 20.20875,15.39937 33.62719,9.25406 13.41937,-6.14531 20.11593,-20.25188 14.96062,-31.50656 -5.15719,-11.25563 -20.21062,-15.40313 -33.63,-9.25594 -13.41844,6.14437 -20.115,20.25094 -14.95781,31.50844 z"
+       id="path3185"
+       style="fill:url(#radialGradient3409);stroke:none" />
+    <path
+       d="m 603.94594,151.98124 c -10.05,10.05094 -10.80657,18.28875 -7.10063,21.99469 3.70406,3.70406 11.94375,2.94937 21.99281,-7.09875 -1.03031,-8.7675 -2.1975,-12.69656 -14.89218,-14.89594 z"
+       id="path3186"
+       style="stroke:none" />
+    <path
+       d="m 596.1825,168.56937 c 0,1.90406 0.59156,3.41812 1.62375,4.44562 3.06844,3.07031 10.47937,2.23594 19.59563,-6.65062 -0.97032,-7.86657 -2.22282,-10.90969 -12.98626,-12.89625 -5.87625,6.04031 -8.23312,11.33437 -8.23312,15.10125 z"
+       id="path3193"
+       style="fill:url(#linearGradient3411);stroke:none" />
+    <path
+       d="m 604.5375,151.39155 c -2.15531,2.15532 0.61875,6.86063 4.32469,10.56844 3.70406,3.70594 8.41218,6.48 10.56562,4.32281 2.16094,-2.15906 -0.615,-6.8625 -4.32281,-10.56843 -3.70406,-3.70407 -8.41031,-6.48 -10.5675,-4.32282 z"
+       id="path3194"
+       style="stroke:none" />
+    <path
+       d="m 605.49937,152.35343 c -1.19343,1.19156 0.74344,5.06437 4.32282,8.64656 3.58125,3.58125 7.45218,5.51719 8.64468,4.32281 1.19532,-1.19531 -0.73781,-5.06437 -4.32281,-8.64656 -3.58031,-3.57937 -7.44937,-5.51719 -8.64469,-4.32281 z"
+       id="path3201"
+       style="fill:url(#linearGradient3413);stroke:none" />
+    <path
+       d="m 630.08062,149.90843 c -0.0234,-0.49031 -0.0422,-0.99094 -0.0572,-1.48875 -13.10344,1.08 -17.64,6.04031 -19.18782,8.95406 0.29157,0.46313 0.56626,0.94125 0.83719,1.42594 l 0.63938,-0.28406 c 1.59281,-2.83407 5.97281,-7.34719 17.76843,-8.60719 z"
+       id="path3216"
+       style="fill:url(#linearGradient3415);stroke:none" />
+    <path
+       d="m 628.42219,120.20562 6.69469,1.79625 -5.67282,21.14343 -6.69469,-1.79625 5.67282,-21.14343 z"
+       id="path3223"
+       style="fill:url(#linearGradient3417);stroke:none" />
+    <path
+       d="m 624.62437,140.67968 c 1.15969,0.31125 1.52438,0.41062 2.68313,0.72187 0.89062,-3.31312 4.05,-15.09187 4.93969,-18.405 -1.15875,-0.31125 -1.52438,-0.40875 -2.68313,-0.71906 -0.88969,3.31125 -4.05093,15.09188 -4.93969,18.40219 z"
+       id="path3230"
+       style="fill:url(#linearGradient3419);stroke:none" />
+    <path
+       d="m 651.94031,134.23999 3.27375,6.11063 -19.29562,10.33781 -3.27375,-6.11063 19.29562,-10.33781 z"
+       id="path3237"
+       style="fill:url(#linearGradient3421);stroke:none" />
+    <path
+       d="m 634.66969,144.53655 c 0.52218,0.97407 0.68437,1.27969 1.20656,2.25188 2.77781,-1.48875 12.65813,-6.78188 15.43781,-8.27063 -0.52219,-0.97218 -0.68437,-1.27781 -1.20656,-2.25 -2.77969,1.48782 -12.65812,6.78 -15.43781,8.26875 z"
+       id="path3244"
+       style="fill:url(#linearGradient3423);stroke:none" />
+    <path
+       d="m 656.75437,160.52843 -1.95,6.6525 -21.0075,-6.15281 1.94813,-6.65438 21.00937,6.15469 z"
+       id="path3251"
+       style="fill:url(#linearGradient3425);stroke:none" />
+    <path
+       d="m 635.57438,158.60468 c 3.02718,0.88594 13.78218,4.03781 16.8075,4.92375 0.31124,-1.06031 0.40874,-1.39125 0.71812,-2.44969 -3.02531,-0.88781 -13.78031,-4.03781 -16.8075,-4.92375 -0.31031,1.0575 -0.40688,1.39125 -0.71812,2.44969 z"
+       id="path3258"
+       style="fill:url(#linearGradient3175);stroke:none" />
+  </g>
+</svg>
diff --git a/1.8/org.simantics.sysdyn.ui/icons/fatal_decoration.png b/1.8/org.simantics.sysdyn.ui/icons/fatal_decoration.png
new file mode 100644 (file)
index 0000000..f2e1f4c
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/fatal_decoration.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/flow.png b/1.8/org.simantics.sysdyn.ui/icons/flow.png
new file mode 100644 (file)
index 0000000..e90b3d2
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/flow.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/flow_old.png b/1.8/org.simantics.sysdyn.ui/icons/flow_old.png
new file mode 100644 (file)
index 0000000..b1a1819
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/flow_old.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/folder.png b/1.8/org.simantics.sysdyn.ui/icons/folder.png
new file mode 100644 (file)
index 0000000..784e8fa
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/folder.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/folder_link.png b/1.8/org.simantics.sysdyn.ui/icons/folder_link.png
new file mode 100644 (file)
index 0000000..b9b75f6
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/folder_link.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/function.png b/1.8/org.simantics.sysdyn.ui/icons/function.png
new file mode 100644 (file)
index 0000000..d677847
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/function.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/functionLink.png b/1.8/org.simantics.sysdyn.ui/icons/functionLink.png
new file mode 100644 (file)
index 0000000..70ae679
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/functionLink.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/maximize.gif b/1.8/org.simantics.sysdyn.ui/icons/maximize.gif
new file mode 100644 (file)
index 0000000..5e5999b
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/maximize.gif differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/minimize.gif b/1.8/org.simantics.sysdyn.ui/icons/minimize.gif
new file mode 100644 (file)
index 0000000..7402dc9
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/minimize.gif differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/modelicaArrayFunction.png b/1.8/org.simantics.sysdyn.ui/icons/modelicaArrayFunction.png
new file mode 100644 (file)
index 0000000..878469f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/modelicaArrayFunction.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/modelicaFunction.png b/1.8/org.simantics.sysdyn.ui/icons/modelicaFunction.png
new file mode 100644 (file)
index 0000000..30ee96f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/modelicaFunction.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/page_white_text.png b/1.8/org.simantics.sysdyn.ui/icons/page_white_text.png
new file mode 100644 (file)
index 0000000..813f712
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/page_white_text.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/page_white_text_width.png b/1.8/org.simantics.sysdyn.ui/icons/page_white_text_width.png
new file mode 100644 (file)
index 0000000..d9cf132
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/page_white_text_width.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/rainbow.png b/1.8/org.simantics.sysdyn.ui/icons/rainbow.png
new file mode 100644 (file)
index 0000000..5ede989
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/rainbow.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/save_as.png b/1.8/org.simantics.sysdyn.ui/icons/save_as.png
new file mode 100644 (file)
index 0000000..033bd35
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/save_as.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.png b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.png
new file mode 100644 (file)
index 0000000..e65f010
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.xcf b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.xcf
new file mode 100644 (file)
index 0000000..49879df
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.xcf differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn16.png b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn16.png
new file mode 100644 (file)
index 0000000..138465f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn16.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn32.png b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn32.png
new file mode 100644 (file)
index 0000000..b77a76a
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn32.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn48.png b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn48.png
new file mode 100644 (file)
index 0000000..142afd3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn48.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn64.png b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn64.png
new file mode 100644 (file)
index 0000000..1d4d73f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/simantics_sysdyn64.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/sysdyn.png b/1.8/org.simantics.sysdyn.ui/icons/sysdyn.png
new file mode 100644 (file)
index 0000000..2c801ef
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/sysdyn.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/sysdyn32.png b/1.8/org.simantics.sysdyn.ui/icons/sysdyn32.png
new file mode 100644 (file)
index 0000000..01398b2
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/sysdyn32.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/sysdynFunction.png b/1.8/org.simantics.sysdyn.ui/icons/sysdynFunction.png
new file mode 100644 (file)
index 0000000..ddc929d
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/sysdynFunction.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/table.png b/1.8/org.simantics.sysdyn.ui/icons/table.png
new file mode 100644 (file)
index 0000000..abcd936
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/table.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/table_multiple.png b/1.8/org.simantics.sysdyn.ui/icons/table_multiple.png
new file mode 100644 (file)
index 0000000..d76448e
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/table_multiple.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/table_multiple_pinned.png b/1.8/org.simantics.sysdyn.ui/icons/table_multiple_pinned.png
new file mode 100644 (file)
index 0000000..5f4e487
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/table_multiple_pinned.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/time.png b/1.8/org.simantics.sysdyn.ui/icons/time.png
new file mode 100644 (file)
index 0000000..911da3f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/time.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/time_go.png b/1.8/org.simantics.sysdyn.ui/icons/time_go.png
new file mode 100644 (file)
index 0000000..d451ee0
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/time_go.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/time_rainbow.png b/1.8/org.simantics.sysdyn.ui/icons/time_rainbow.png
new file mode 100644 (file)
index 0000000..579887f
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/time_rainbow.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/timeline_marker.png b/1.8/org.simantics.sysdyn.ui/icons/timeline_marker.png
new file mode 100644 (file)
index 0000000..a3fbddf
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/timeline_marker.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/variable.png b/1.8/org.simantics.sysdyn.ui/icons/variable.png
new file mode 100644 (file)
index 0000000..0299de3
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/variable.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/variableGray.png b/1.8/org.simantics.sysdyn.ui/icons/variableGray.png
new file mode 100644 (file)
index 0000000..a3ed59b
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/variableGray.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/vensimFunction.png b/1.8/org.simantics.sysdyn.ui/icons/vensimFunction.png
new file mode 100644 (file)
index 0000000..f007096
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/vensimFunction.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/icons/warning.svg b/1.8/org.simantics.sysdyn.ui/icons/warning.svg
new file mode 100644 (file)
index 0000000..1dd13ec
--- /dev/null
@@ -0,0 +1,173 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   version="1.0"
+   width="600"
+   height="500"
+   id="svg2904"
+   inkscape:version="0.48.0 r9654"
+   sodipodi:docname="Nuvola_apps_important_yellow.svg">
+  <sodipodi:namedview
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1"
+     objecttolerance="10"
+     gridtolerance="10"
+     guidetolerance="10"
+     inkscape:pageopacity="0"
+     inkscape:pageshadow="2"
+     inkscape:window-width="1356"
+     inkscape:window-height="874"
+     id="namedview28"
+     showgrid="false"
+     inkscape:zoom="64"
+     inkscape:cx="1.4002934"
+     inkscape:cy="497.30748"
+     inkscape:window-x="0"
+     inkscape:window-y="0"
+     inkscape:window-maximized="0"
+     inkscape:current-layer="svg2904" />
+  <metadata
+     id="metadata2950">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+        <dc:title></dc:title>
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <defs
+     id="defs2906">
+    <linearGradient
+       id="Grad1"
+       x1="41.1948738"
+       y1="616.477173"
+       x2="118.931351"
+       y2="527.555115"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.03733917,0,0,-0.03535839,0.20475678,22.530063)">
+      <stop
+         offset="0"
+         id="stop2909"
+         style="stop-color:#f2b600;stop-opacity:1;" />
+      <stop
+         offset="1"
+         id="stop2911"
+         style="stop-color:#f29600;stop-opacity:1;" />
+    </linearGradient>
+    <linearGradient
+       id="Grad2"
+       x1="530.809509"
+       y1="486.631012"
+       x2="174.805481"
+       y2="211.22995"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.00786651,0,0,0.00786651,-0.00679244,0.00631797)">
+      <stop
+         offset="0"
+         id="stop2914"
+         style="stop-color:#d88500;stop-opacity:1;" />
+      <stop
+         offset="1"
+         id="stop2916"
+         style="stop-color:#fc3;stop-opacity:1;" />
+    </linearGradient>
+    <linearGradient
+       id="Grad3"
+       x1="187.873566"
+       y1="224.598923"
+       x2="581.837463"
+       y2="483.100006"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.00786651,0,0,0.00786651,-0.00679244,0.00631791)">
+      <stop
+         offset="0"
+         id="stop2919"
+         style="stop-color:#ffd657;stop-opacity:1;" />
+      <stop
+         offset="1"
+         id="stop2921"
+         style="stop-color:#f2b600;stop-opacity:1;" />
+    </linearGradient>
+    <linearGradient
+       id="Grad4"
+       x1="250.398453"
+       y1="101.536331"
+       x2="412.094299"
+       y2="264.54187"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.00786651,0,0,0.00786651,-0.00679244,0.00631797)">
+      <stop
+         offset="0"
+         id="stop2924"
+         style="stop-color:#fff1c5;stop-opacity:1;" />
+      <stop
+         offset="1"
+         id="stop2926"
+         style="stop-color:#fc3;stop-opacity:1;" />
+    </linearGradient>
+    <radialGradient
+       id="Grad5"
+       cx="295.471252"
+       cy="186.096344"
+       r="179.550003"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0,0.01254747,-0.00718228,-1.7748438e-7,3.6893627,-2.0814894)">
+      <stop
+         offset="0"
+         stop-color="#ffffff"
+         id="stop2929" />
+      <stop
+         offset="0.5"
+         stop-color="#ffffff"
+         id="stop2931" />
+      <stop
+         offset="1"
+         stop-color="#d5d5d5"
+         id="stop2933" />
+    </radialGradient>
+  </defs>
+  <path
+     d="m 2.2495975,0.17755318 c 0,0 -2.13182401,3.50059672 -2.13182401,3.50059672 -0.04090583,0.066865 -0.04090583,0.1494635 0,0.2163294 0.0401193,0.066078 0.11563773,0.1077713 0.19744941,0.1077713 l 4.2636484,0 c 0.081025,0 0.1565435,-0.041693 0.197449,-0.1077713 0.040119,-0.066866 0.040119,-0.1494637 0,-0.2163294 L 2.6444965,0.17755318 C 2.6035909,0.11068789 2.528072,0.06899551 2.4470466,0.06899551 c -0.081025,0 -0.1565435,0.04169235 -0.1974491,0.10855767 z"
+     style="fill-opacity:0.17857098"
+     id="path2935"
+     inkscape:connector-curvature="0" />
+  <path
+     d="m 2.1557113,0.11487581 c 0,0 -2.13182443,3.50059629 -2.13182443,3.50059629 -0.04090583,0.066865 -0.04090583,0.1494646 0,0.2163294 0.04011931,0.066079 0.11563774,0.1077714 0.1974494,0.1077714 l 4.26364803,0 c 0.081026,0 0.1565435,-0.041692 0.1974498,-0.1077714 0.040119,-0.066864 0.040119,-0.1494636 0,-0.2163294 L 2.5506094,0.11487581 C 2.5097038,0.04801053 2.4341857,0.006318 2.3531605,0.006318 c -0.081026,0 -0.1565436,0.04169253 -0.1974492,0.10855781 z"
+     style="fill:url(#Grad1)"
+     id="path2937"
+     inkscape:connector-curvature="0" />
+  <path
+     d="m 2.3531605,0.1864611 c -0.013374,0 -0.025959,0.007079 -0.033039,0.018093 L 1.2542088,1.9548528 0.1882969,3.7051507 c -0.007081,0.011014 -0.007081,0.025173 0,0.036186 0.007081,0.011014 0.0196662,0.018093 0.0330394,0.018093 l 4.26364802,0 c 0.013374,0 0.025959,-0.00708 0.03304,-0.018093 0.00708,-0.011014 0.00708,-0.025173 0,-0.036186 L 2.3861996,0.20455409 c -0.00708,-0.0110133 -0.019666,-0.018093 -0.033039,-0.018093 z"
+     style="fill:url(#Grad2)"
+     id="path2939"
+     inkscape:connector-curvature="0" />
+  <path
+     d="m 2.3528655,0.1864611 c -0.013374,0 -0.02596,0.007079 -0.03304,0.018093 L 1.2539138,1.9548528 0.18800176,3.7051507 c -0.007081,0.011014 -0.007081,0.025173 0,0.036186 0.007081,0.011014 0.0196662,0.018093 0.0330394,0.018093 l 4.26364814,0 c 0.013374,0 0.025959,-0.00708 0.033039,-0.018093 0.00708,-0.011014 0.00708,-0.025173 0,-0.036186 L 2.3859045,0.20455409 c -0.00708,-0.0110133 -0.019666,-0.018093 -0.033039,-0.018093 z"
+     style="fill:none;stroke:url(#Grad3);stroke-width:0.09439755;stroke-linejoin:round"
+     id="path2941"
+     inkscape:connector-curvature="0" />
+  <path
+     d="m 2.3537257,0.24950271 c -0.012666,6.1991e-4 -0.024472,0.007694 -0.03122,0.0181914 L 1.2565934,2.0179925 1.1081131,2.2618546 c 0.3616458,0.2170897 0.7847846,0.3421927 1.2370087,0.3421927 0.458646,0 0.8874945,-0.128465 1.2524958,-0.3512883 L 2.3886332,0.26769413 c -0.00708,-0.0110133 -0.019568,-0.0181914 -0.032941,-0.0181914 -6.199e-4,0 -0.00135,-3.07e-5 -0.00197,0 z"
+     style="fill:url(#Grad4);stroke-width:10;stroke-linejoin:round"
+     id="path2943"
+     inkscape:connector-curvature="0" />
+  <path
+     d="m 2.2446032,1.1202159 -1.28774827,2.113732 c -0.0220263,0.036973 -0.0220263,0.082598 0,0.1187843 0.0220272,0.036972 0.0637188,0.059786 0.10855797,0.059786 l 2.57471,0 c 0.044839,0 0.086531,-0.022814 0.1085579,-0.059786 0.022026,-0.036972 0.022026,-0.081811 0,-0.1187843 L 2.4617192,1.1202159 c -0.022026,-0.036972 -0.063719,-0.059785 -0.108558,-0.059785 -0.044839,0 -0.086532,0.022813 -0.108558,0.059785 z"
+     style="fill:url(#Grad5)"
+     id="path2945"
+     inkscape:connector-curvature="0" />
+  <path
+     d="M 2.2852663,3.337518 C 2.2114878,3.3021821 2.1553008,3.2172169 2.1553008,3.1409868 c 0,-0.1419381 0.148319,-0.248858 0.2886484,-0.2080803 0.094669,0.027511 0.1590123,0.1129419 0.1582241,0.2100805 -6.804e-4,0.082516 -0.036387,0.1433023 -0.1092874,0.1860081 -0.055802,0.032689 -0.1491636,0.03652 -0.2076196,0.00852 z M 2.3020353,2.7770489 C 2.2928126,2.7719848 2.2710912,2.7543341 2.2537687,2.737834 2.1932418,2.6801841 2.1933171,2.6806913 2.1538627,2.0638401 2.1187897,1.5155034 2.1184996,1.506983 2.1335493,1.4675949 2.1674053,1.3789769 2.2428431,1.3401722 2.3684515,1.346762 c 0.079842,0.00419 0.1413326,0.032228 0.1813017,0.082674 0.03414,0.043088 0.041563,0.067446 0.041532,0.1362832 -3.36e-5,0.074803 -0.047818,0.9921396 -0.054611,1.0483554 -0.00889,0.073626 -0.05188,0.133375 -0.1148864,0.1596827 -0.036004,0.015035 -0.095413,0.016668 -0.119753,0.00329 z"
+     id="path2947"
+     inkscape:connector-curvature="0" />
+</svg>
diff --git a/1.8/org.simantics.sysdyn.ui/icons/warning_decoration.png b/1.8/org.simantics.sysdyn.ui/icons/warning_decoration.png
new file mode 100644 (file)
index 0000000..c80f14d
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/icons/warning_decoration.png differ
diff --git a/1.8/org.simantics.sysdyn.ui/plugin.properties b/1.8/org.simantics.sysdyn.ui/plugin.properties
new file mode 100644 (file)
index 0000000..a6b3f78
--- /dev/null
@@ -0,0 +1,9 @@
+about.text = Simantics System Dynamics\n\\r
+\n\\r
+Version 1.8.0\n\\r
+\n\\r
+Copyright (c) 2014 Association for Decentralized Information Management in Industry THTH ry.\n\\r
+\n\\r
+Contributors:\n\\r
+VTT Technical Research Centre of Finland\n\\r
+Semantum Oy
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/plugin.xml b/1.8/org.simantics.sysdyn.ui/plugin.xml
new file mode 100644 (file)
index 0000000..ee0afef
--- /dev/null
@@ -0,0 +1,3320 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<?eclipse version="3.4"?>\r
+<!--\r
+    Copyright (c) 2010 Association for Decentralized Information Management in\r
+    Industry THTH ry.\r
+    All rights reserved. This program and the accompanying materials\r
+    are made available under the terms of the Eclipse Public License v1.0\r
+    which accompanies this distribution, and is available at\r
+    http://www.eclipse.org/legal/epl-v10.html\r
+   \r
+    Contributors:\r
+        VTT Technical Research Centre of Finland - initial API and implementation\r
+ -->\r
+\r
+<plugin>\r
+   <extension\r
+         point="org.eclipse.ui.editors">\r
+      <editor\r
+            class="org.simantics.modeling.ui.diagramEditor.DiagramEditor:viewer=org.simantics.sysdyn.ui.editor.DiagramViewer"\r
+            contributorClass="org.simantics.ui.toolbar.ToolbarContributor:toolbar=org.simantics.sysdyn.ui.diagramToolbar"\r
+            default="false"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/plugin.png"\r
+            id="org.simantics.sysdyn.ui.diagramViewer"\r
+            matchingStrategy="org.simantics.ui.workbench.editor.input.ResourceEditorInputMatchingStrategy"\r
+            name="System Dynamic Diagram Viewer">\r
+      </editor>\r
+      <editor\r
+            class="org.simantics.sysdyn.ui.modelica.SysdynModelicaEditor"\r
+            contributorClass="org.simantics.sysdyn.ui.modelica.TextEditorActionBarContributor"\r
+            default="false"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/page_white_text.png"\r
+            id="org.simantics.sysdyn.ui.modelicaEditor"\r
+            name="Modelica Code Viewer">\r
+      </editor>\r
+      <editor\r
+            class="org.simantics.sysdyn.ui.trend.TrendEditor"\r
+            default="false"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"\r
+            id="org.simantics.sysdyn.ui.jfreeChartEditor"\r
+            name="Chart Viewer">\r
+      </editor>\r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.ui.views">\r
+      <category\r
+            id="org.simantics.sysdyn.ui.category"\r
+            name="System Dynamics">\r
+      </category>\r
+      <view\r
+            allowMultiple="true"\r
+            category="org.simantics.sysdyn.ui.category"\r
+            class="org.simantics.sysdyn.ui.trend.TrendView"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"\r
+            id="org.simantics.sysdyn.ui.trend.view"\r
+            name="Trend"\r
+            restorable="true">\r
+      </view>\r
+      <view\r
+            category="org.simantics.sysdyn.ui.category"\r
+            class="org.simantics.sysdyn.ui.browser.SysdynBrowser"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
+            id="org.simantics.sysdyn.ui.browser"\r
+            name="Model Browser"\r
+            restorable="true">\r
+      </view>\r
+      <view\r
+            allowMultiple="false"\r
+            category="org.simantics.sysdyn.ui.category"\r
+            class="org.simantics.sysdyn.ui.structure.StructureView"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/arrow_switch.png"\r
+            id="org.simantics.sysdyn.ui.structure.view"\r
+            name="Structure"\r
+            restorable="true">\r
+      </view>\r
+      <view\r
+            allowMultiple="false"\r
+            category="org.simantics.sysdyn.ui.category"\r
+            class="org.simantics.sysdyn.ui.values.ValueView"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/page_white_database.png"\r
+            id="org.simantics.sysdyn.ui.values.view"\r
+            name="Values"\r
+            restorable="true">\r
+      </view>\r
+      <view\r
+            category="org.simantics.sysdyn.ui.category"\r
+            class="org.simantics.sysdyn.ui.browser.SysdynModelBrowser"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
+            id="org.simantics.sysdyn.ui.modelBrowser"\r
+            name="Model Browser"\r
+            restorable="true">\r
+         <description>\r
+            Structural model browser view for Sysdyn.\r
+         </description>\r
+      </view>\r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.ui.perspectives">\r
+      <perspective\r
+            class="org.simantics.sysdyn.ui.project.SysdynPerspectiveFactory"\r
+            icon="icons/sysdyn.png"\r
+            id="org.simantics.sysdyn.ui.perspective"\r
+            name="System Dynamics">\r
+      </perspective>\r
+      <perspective\r
+            class="org.simantics.sysdyn.ui.project.SysdynEquationPerspectiveFactory"\r
+            icon="icons/function.png"\r
+            id="org.simantics.sysdyn.ui.perspective.equation"\r
+            name="Equation">\r
+      </perspective>\r
+      <perspective\r
+            class="org.simantics.sysdyn.ui.project.SysdynTrendPerspectiveFactory"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_curve.png"\r
+            id="org.simantics.sysdyn.ui.perspective.trend"\r
+            name="Trend">\r
+      </perspective>\r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.ui.perspectiveExtensions">\r
+      <perspectiveExtension\r
+            targetID="org.simantics.sysdyn.ui.perspective">\r
+         <view\r
+               id="org.simantics.browsing.ui.graph.propertyView"\r
+               ratio="0.65f"\r
+               relationship="bottom"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.eclipse.ui.console.ConsoleView"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.trend.view"\r
+               ratio="0.4f"\r
+               relationship="left"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.structure.view"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.trend.view">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.browser"\r
+               ratio="0.25f"\r
+               relationship="left"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.simantics.diagram.symbollibrary"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.browser">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.values.view"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.trend.view">\r
+         </view>\r
+         <view\r
+               id="org.simantics.issues.ui.issueview2"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.diagram.profile"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.jfreechart.chartPanel"\r
+               minimized="true"\r
+               ratio="0.5"\r
+               relationship="right"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.simantics.workbench.search.browser"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.browser">\r
+         </view>\r
+         <!--\r
+         <view\r
+               id="org.simantics.document.workbench.documentViewer"\r
+               minimized="true"\r
+               relationship="stack"\r
+               relative="org.simantics.jfreechart.chartPanel">\r
+         </view>\r
+         -->\r
+      </perspectiveExtension>\r
+      <perspectiveExtension\r
+            targetID="org.simantics.sysdyn.ui.perspective.equation">\r
+         <view\r
+               id="org.simantics.browsing.ui.graph.propertyView"\r
+               minimized="false"\r
+               ratio="0.65f"\r
+               relationship="right"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.eclipse.ui.console.ConsoleView"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.trend.view"\r
+               minimized="true"\r
+               ratio="0.4f"\r
+               relationship="left"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.structure.view"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.trend.view">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.browser"\r
+               minimized="true"\r
+               ratio="0.25f"\r
+               relationship="left"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.simantics.diagram.symbollibrary"\r
+               minimized="true"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.browser">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.values.view"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.trend.view">\r
+         </view>\r
+         <view\r
+               id="org.simantics.issues.ui.issueview2"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.diagram.profile"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.jfreechart.chartPanel"\r
+               minimized="true"\r
+               ratio="0.5"\r
+               relationship="right"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.simantics.workbench.search.browser"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.browser">\r
+         </view>\r
+      </perspectiveExtension>\r
+      <perspectiveExtension\r
+            targetID="org.simantics.sysdyn.ui.perspective.trend">\r
+         <view\r
+               id="org.simantics.browsing.ui.graph.propertyView"\r
+               minimized="true"\r
+               ratio="0.6f"\r
+               relationship="bottom"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.eclipse.ui.console.ConsoleView"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.trend.view"\r
+               ratio="0.4f"\r
+               relationship="bottom"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.structure.view"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.trend.view">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.browser"\r
+               minimized="true"\r
+               ratio="0.25f"\r
+               relationship="left"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.simantics.diagram.symbollibrary"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.browser">\r
+         </view>\r
+         <view\r
+               id="org.simantics.sysdyn.ui.values.view"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.trend.view">\r
+         </view>\r
+         <view\r
+               id="org.simantics.issues.ui.issueview2"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.diagram.profile"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.browsing.ui.graph.propertyView">\r
+         </view>\r
+         <view\r
+               id="org.simantics.jfreechart.chartPanel"\r
+               minimized="false"\r
+               ratio="0.4"\r
+               relationship="right"\r
+               relative="org.eclipse.ui.editorss">\r
+         </view>\r
+         <view\r
+               id="org.simantics.workbench.search.browser"\r
+               minimized="false"\r
+               relationship="stack"\r
+               relative="org.simantics.sysdyn.ui.browser">\r
+         </view>\r
+      </perspectiveExtension>\r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.ui.contexts">\r
+      <context\r
+            id="org.simantics.sysdyn.ui.basicExperiment"\r
+            name="Basic Experiment">\r
+      </context>\r
+      <context\r
+            id="org.simantics.sysdyn.ui.playbackExperiment"\r
+            name="Playback Experiment">\r
+      </context>\r
+      <context\r
+            id="org.simantics.sysdyn.ui.gameExperiment"\r
+            name="Game Experiment">\r
+      </context>\r
+      <context\r
+            id="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment"\r
+            name="Sensitivity Analysis Experiment">\r
+      </context>\r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.ui.menus">\r
+      <menuContribution\r
+            locationURI="menu:sFile?after=import.ext">\r
+         <command commandId="org.eclipse.ui.file.import" />\r
+         <command commandId="org.eclipse.ui.file.export" />\r
+      </menuContribution>\r
+      <menuContribution\r
+            locationURI="toolbar:org.eclipse.ui.main.toolbar">\r
+         <toolbar\r
+               id="org.simantics.sysdyn.ui.modelToolbar">\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.exportModelButton"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/disk.png"\r
+                  id="org.simantics.sysdyn.ui.export.button"\r
+                  tooltip="Save model">\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.exportModelAsButton"\r
+                  icon="icons/save_as.png"\r
+                  id="org.simantics.sysdyn.ui.exportAs.button"\r
+                  tooltip="Save model as...">\r
+            </command>\r
+         </toolbar>\r
+         <toolbar\r
+               id="org.simantics.sysdyn.ui.diagramToolbar">\r
+         </toolbar>\r
+         <toolbar\r
+               id="org.simantics.sysdyn.ui.experimentControlToolbar">\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.run"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
+                  id="org.simantics.sysdyn.ui.run.button"\r
+                  label="Simulate"\r
+                  style="push">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.basicExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.toggleSimulation"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"\r
+                  label="Simulate On Change"\r
+                  style="toggle"\r
+                  tooltip="Simulate On Change">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.basicExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.dispose"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"\r
+                  id="org.simantics.sysdyn.ui.dispose.button"\r
+                  label="Quit Experiment"\r
+                  tooltip="Quit Experiment">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.basicExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.saveResults"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"\r
+                  id="org.simantics.sysdyn.ui.save.button"\r
+                  label="Save Results">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.basicExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.saveIC"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"\r
+                  id="org.simantics.sysdyn.ui.saveic.button"\r
+                  label="Save Initial Condition">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.gameExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.saveHistory"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"\r
+                  id="org.simantics.sysdyn.ui.savehistory.button"\r
+                  label="Save History">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.gameExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.synthesisSimulation"\r
+                  hoverIcon="icons/equalizer.png"\r
+                  icon="icons/equalizer.png"\r
+                  label="Sliders and Trends"\r
+                  style="toggle"\r
+                  tooltip="Sliders and Trends">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.basicExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                     <and>\r
+                        <count\r
+                              value="0">\r
+                        </count>\r
+                     </and>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+         </toolbar>\r
+         <toolbar\r
+               id="org.simantics.sysdyn.ui.playbackControlToolbar">\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.playbackReset"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_start_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_start.png"\r
+                  id="org.simantics.sysdyn.ui.playbackReset.button"\r
+                  label="Reset"\r
+                  style="push"\r
+                  tooltip="Reset">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.playbackExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.playback"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
+                  id="org.simantics.sysdyn.ui.playback.button"\r
+                  label="Start Playback"\r
+                  style="pulldown"\r
+                  tooltip="Start playback">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.playbackExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <dynamic\r
+                  class="org.simantics.sysdyn.ui.menu.PlaybackSliderContribution"\r
+                  id="org.simantics.sysdyn.ui.playbackSlider">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.playbackExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </dynamic>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.playbackReload"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"\r
+                  label="Reload"\r
+                  style="push"\r
+                  tooltip="Reload">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.playbackExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.dispose"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"\r
+                  id="org.simantics.sysdyn.ui.dispose.button"\r
+                  label="Quit Experiment"\r
+                  tooltip="Quit Experiment">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.playbackExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+         </toolbar>\r
+         <toolbar\r
+               id="org.simantics.sysdyn.ui.gameControlToolbar">\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.reloadGame"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
+                  id="org.simantics.sysdyn.ui.reload.game.button"\r
+                  label="Reload Game"\r
+                  style="push">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.gameExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <dynamic\r
+                  class="org.simantics.sysdyn.ui.menu.GameStepDurationContribution"\r
+                  id="org.simantics.sysdyn.ui.gameStepDuration">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.gameExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </dynamic>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.step"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_end_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_end.png"\r
+                  id="org.simantics.sysdyn.ui.step.button"\r
+                  label="Step"\r
+                  style="push">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.gameExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.dispose"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"\r
+                  id="org.simantics.sysdyn.ui.dispose.button"\r
+                  label="Quit Experiment"\r
+                  tooltip="Quit Experiment">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.gameExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+         </toolbar>\r
+         <toolbar\r
+               id="org.simantics.sysdyn.ui.sensitivityAnalysisControlToolbar">\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.runSensitivityAnalysis"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
+                  id="org.simantics.sysdyn.ui.runSensitivityAnalysis.button"\r
+                  label="Simulate"\r
+                  style="push">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"\r
+                  label="Simulate On Change"\r
+                  style="toggle"\r
+                  tooltip="Simulate On Change">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.dispose"\r
+                  hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"\r
+                  id="org.simantics.sysdyn.ui.dispose.button"\r
+                  label="Quit Experiment"\r
+                  tooltip="Quit Experiment">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.saveSensitivityAnalysisResults"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"\r
+                  id="org.simantics.sysdyn.ui.saveSensitivityAnalysis.button"\r
+                  label="Save Sensitivity Analysis Results">\r
+               <visibleWhen>\r
+                  <with\r
+                        variable="activeContexts">\r
+                     <iterate\r
+                           ifEmpty="false"\r
+                           operator="or">\r
+                        <equals\r
+                              value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">\r
+                        </equals>\r
+                     </iterate>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+         </toolbar>\r
+      </menuContribution>\r
+      <menuContribution\r
+            locationURI="toolbar:org.simantics.sysdyn.ui.trend.view">\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.trend.view.pin"\r
+               icon="icons/table_multiple_pinned.png"\r
+               label="Pin Trend"\r
+               style="toggle"\r
+               tooltip="Pins the trend so that it does not react to selection changes">\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.trend.view.png"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/images.png"\r
+               label="Export to PNG"\r
+               style="push"\r
+               tooltip="Exports the trend to PNG file">\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.trend.view.svg"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/map.png"\r
+               label="Export to SVG"\r
+               style="push"\r
+               tooltip="Exports the trend to SVG file">\r
+         </command>\r
+      </menuContribution>\r
+      <menuContribution\r
+            locationURI="popup:#SysdynBrowserPopup?after=wbStart">\r
+         <menu id="org.simantics.new"\r
+               label="New">\r
+               <!--\r
+            <command\r
+                  commandId="org.simantics.modeling.ui.newModel"\r
+                  id="org.simantics.sysdyn.ui.browser.newModel"\r
+                  label="Model"\r
+                  style="push">\r
+            </command>\r
+            -->\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newSCLModule"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/script.png"\r
+                  id="org.simantics.sysdyn.ui.newSCLModule"\r
+                  label="SCL Module"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newAnnotationType"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/note.png"\r
+                  id="org.simantics.sysdyn.ui.newAnnotationType"\r
+                  label="Annotation Type"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                        <test\r
+                              args="http://www.simantics.org/Layer0-0.0/Library"\r
+                              property="org.simantics.graph.resourceType"\r
+                              value="true">\r
+                        </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newAnnotationValue"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/note.png"\r
+                  id="org.simantics.sysdyn.ui.newAnnotationValue"\r
+                  label="Annotation Value"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                        <test\r
+                              args="http://www.simantics.org/Layer0-0.0/Entity"\r
+                              property="org.simantics.graph.resourceType"\r
+                              value="true">\r
+                        </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newLibrary"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/folder.png"\r
+                  id="org.simantics.sysdyn.ui.newLibrary"\r
+                  label="Library"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <or>\r
+                        <test\r
+                              args="http://www.simantics.org/Layer0-0.0/Library"\r
+                              property="org.simantics.graph.resourceType"\r
+                              value="true">\r
+                        </test>\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                     </or>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newModuleNode"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newModule"\r
+                  label="Module type"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ModulesNode"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newExperiment"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/time.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newExperiment"\r
+                  label="Experiment"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newPlaybackExperiment"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/timeline_marker.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newPlaybackExperiment"\r
+                  label="Playback Experiment"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newGameExperiment"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/time_go.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newGameExperiment"\r
+                  label="Game Experiment"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"\r
+                  icon="icons/time_rainbow.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newSensitivityAnalysisExperiment"\r
+                  label="Sensitivity Analysis Experiment"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newEnumeration"\r
+                  id="org.simantics.sysdyn.ui.browser.newEnumeration"\r
+                  label="Enumeration"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newFunction"\r
+                  id="org.simantics.sysdyn.ui.browser.newFunction"\r
+                  label="Function"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <or>\r
+                        <test\r
+                              args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"\r
+                              property="org.simantics.sysdyn.ui.nodeClass">\r
+                        </test>\r
+                        <test\r
+                              args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
+                              property="org.simantics.sysdyn.ui.nodeClass">\r
+                        </test>\r
+                        <test\r
+                              args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"\r
+                              property="org.simantics.sysdyn.ui.nodeClass">\r
+                        </test>\r
+                     </or>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newFunctionLibrary"\r
+                  label="Function Library"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <or>\r
+                        <test\r
+                              args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"\r
+                              property="org.simantics.sysdyn.ui.nodeClass">\r
+                        </test>\r
+                        <test\r
+                              args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
+                              property="org.simantics.sysdyn.ui.nodeClass">\r
+                        </test>\r
+                     </or>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newSharedFunctionLibrary"\r
+                  label="Shared Function Library"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newSpreadSheet"\r
+                  label="Sheet"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.BookNode"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newXYLineChart"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newXYLineChart"\r
+                  label="Line Chart"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newSensitivityChart"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/rainbow.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newSensitivityChart"\r
+                  label="Sensitivity Chart"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newBarChart"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/chart_bar.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newBarChart"\r
+                  label="Bar Chart"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newPieChart"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/chart_pie.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newPieChart"\r
+                  label="Pie Chart"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newHistoryData"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/table.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newHistoryData"\r
+                  label="History Data"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.newModel"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newModel"\r
+                  label="Model"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            <!--\r
+            <command\r
+                  commandId="org.simantics.documentation.workbench.newDocumentation"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/script.png"\r
+                  id="org.simantics.sysdyn.ui.browser.newDocumentation"\r
+                  label="Document"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.document.workbench.browser_old.DocumentationFolder"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            -->\r
+         </menu>\r
+         <dynamic\r
+               class="org.simantics.ui.contribution.OpenWithMenuContribution"\r
+               id="org.simantics.sysdyn.ui.browser.openWithMenu">\r
+         </dynamic>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.activateResult"\r
+               id="org.simantics.sysdyn.ui.browser.activateResult"\r
+               label="Show in charts"\r
+               style="push">\r
+            <visibleWhen\r
+                  checkEnabled="true">\r
+               <with\r
+                     variable="selection">\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </with>\r
+            </visibleWhen>\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.activateResultSet"\r
+               id="org.simantics.sysdyn.ui.browser.activateResultSet"\r
+               label="Show in charts"\r
+               style="push">\r
+            <visibleWhen\r
+                  checkEnabled="true">\r
+               <with\r
+                     variable="selection">\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </with>\r
+            </visibleWhen>\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.renameNode"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/textfield_rename.png"\r
+               id="org.simantics.sysdyn.ui.browser.rename"\r
+               label="Rename"\r
+               style="push">\r
+            <visibleWhen checkEnabled="true">\r
+            </visibleWhen>\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.removeNode"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/cross.png"\r
+               id="org.simantics.sysdyn.ui.browser.remove"\r
+               label="Remove"\r
+               style="push">\r
+            <visibleWhen checkEnabled="true">\r
+            </visibleWhen>\r
+         </command>\r
+         <menu\r
+               id="org.simantics.import"\r
+               label="Import">\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.importModel"\r
+                  label="Model"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.importSharedLibrary"\r
+                  label="Shared Library"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            <!--\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.importMdl"\r
+                  label="Vensim model"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            -->\r
+            <command\r
+                  commandId="org.simantics.image.ui.importImage"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/image_add.png"\r
+                  label="Image"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <test\r
+                           args="org.simantics.image.ui.modelBrowser.ImagesNode"\r
+                           property="org.simantics.modeling.ui.nodeClass">\r
+                     </test>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.importFunctionLibrary"\r
+                  label="Function library"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.importModule"\r
+                  label="Module"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.importMdl"\r
+                  label="Vensim Model (.mdl)"\r
+                  style="push">\r
+            </command>\r
+         </menu>\r
+         <menu\r
+               id="org.simantics.export"\r
+               label="Export">\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.exportSharedOntology"\r
+                  icon="platform:/plugin/com.famfamfam.silk/icons/folder.png"\r
+                  id="org.simantics.sysdyn.ui.exportSharedOntology"\r
+                  label="Shared Library"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+                  <with\r
+                        variable="selection">\r
+                     <or>\r
+                        <test\r
+                              args="org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode"\r
+                              property="org.simantics.sysdyn.ui.nodeClass">\r
+                        </test>\r
+                     </or>\r
+                  </with>\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.exportModel"\r
+                  label="Model"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.exportFunctionLibrary"\r
+                  label="Function library"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+            <command\r
+                  commandId="org.simantics.sysdyn.ui.exportModule"\r
+                  label="Module"\r
+                  style="push">\r
+               <visibleWhen\r
+                     checkEnabled="true">\r
+               </visibleWhen>\r
+            </command>\r
+         </menu>\r
+         <command\r
+               commandId="org.eclipse.ui.edit.findReplace"\r
+               label="Find"\r
+               style="push">\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.activateExperiment"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
+               id="org.simantics.sysdyn.ui.browser.activateExperiment"\r
+               label="Activate Experiment"\r
+               style="push">\r
+            <visibleWhen\r
+                  checkEnabled="true">\r
+               <with\r
+                     variable="selection">\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </with>\r
+            </visibleWhen>\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.assignIC"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
+               id="org.simantics.sysdyn.ui.browser.assignIC"\r
+               label="Assign IC"\r
+               style="push">\r
+            <visibleWhen\r
+                  checkEnabled="true">\r
+               <with\r
+                     variable="selection">\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </with>\r
+            </visibleWhen>\r
+         </command>\r
+      </menuContribution>\r
+      <menuContribution\r
+            locationURI="popup:#SysdynDiagramPopup?after=wbStart">\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.showModule"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/palette.png"\r
+               label="Show Module"\r
+               style="push">\r
+            <visibleWhen>\r
+               <with\r
+                     variable="selection">\r
+                  <test\r
+                        args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
+                        property="org.simantics.graph.resourceType">\r
+                  </test>\r
+               </with>\r
+            </visibleWhen>\r
+         </command>\r
+         <dynamic\r
+               class="org.simantics.sysdyn.ui.menu.FontContextMenuContribution"\r
+               id="org.simantics.sysdyn.ui.fontContextMenu">\r
+            <visibleWhen\r
+                  checkEnabled="true">\r
+               <with\r
+                     variable="selection">\r
+                  <or>\r
+                     <test\r
+                           args="http://www.simantics.org/Diagram-0.0/FontProvider"\r
+                           property="org.simantics.graph.resourceTypes"\r
+                           value="true">\r
+                     </test>\r
+                  </or>\r
+               </with>\r
+            </visibleWhen>\r
+         </dynamic>\r
+         <command\r
+               commandId="org.eclipse.ui.edit.copy"\r
+               label="Copy"\r
+               style="push">\r
+            <visibleWhen\r
+                  checkEnabled="true">\r
+               <with\r
+                     variable="selection">\r
+                  <or>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                  </or>\r
+               </with>\r
+            </visibleWhen>\r
+         </command>\r
+         <command\r
+               commandId="org.eclipse.ui.edit.paste"\r
+               label="Paste"\r
+               style="push">\r
+         </command>\r
+         <command\r
+               commandId="org.eclipse.ui.edit.findReplace"\r
+               label="Find"\r
+               style="push">\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.pasteSpecial"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/paste_plain.png"\r
+               label="Paste special"\r
+               style="push">\r
+         </command>         \r
+         <command\r
+               commandId="org.eclipse.ui.edit.cut"\r
+               label="Cut"\r
+               style="push">\r
+            <visibleWhen>\r
+               <with\r
+                     variable="selection">\r
+                  <or>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Layer0-0.0/SCLModule"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                  </or>\r
+               </with>\r
+            </visibleWhen>\r
+         </command>\r
+         <command\r
+               commandId="org.eclipse.ui.edit.rename"\r
+               label="Rename"\r
+               style="push">\r
+            <visibleWhen>\r
+               <with\r
+                     variable="selection">\r
+                  <or>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                     <test\r
+                           args="http://www.simantics.org/Layer0-0.0/SCLModule"\r
+                           property="org.simantics.graph.resourceType"\r
+                           value="true">\r
+                     </test>\r
+                  </or>\r
+               </with>\r
+            </visibleWhen>\r
+         </command>\r
+      </menuContribution>\r
+      <menuContribution\r
+            locationURI="popup:#ExternalFunctionFileBrowser?after=wbStart">\r
+      </menuContribution>\r
+      <menuContribution\r
+            allPopups="false"\r
+            locationURI="menu:sFile?after=#FileNewMenu">\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.importModel"\r
+               label="Import Model"\r
+               style="push">\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.importSharedLibrary"\r
+               label="Import Shared Library"\r
+               style="push">\r
+         </command>\r
+      </menuContribution>\r
+      <menuContribution\r
+            allPopups="false"\r
+            locationURI="menu:#FileNewMenu">\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.newModel"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation_add.png"\r
+               label="SD Model"\r
+               style="push">\r
+         </command>\r
+      </menuContribution>\r
+      <menuContribution\r
+            allPopups="false"\r
+            locationURI="menu:org.simantics.sysdyn.ui.playback.button">\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.playbackSlow"\r
+               icon="icons/control_step.png"\r
+               label="Slow"\r
+               style="push">\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.playbackNormal"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
+               label="Normal"\r
+               style="push">\r
+         </command>\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.playbackFast"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/control_fastforward.png"\r
+               label="Fast"\r
+               style="push">\r
+         </command>\r
+      </menuContribution>\r
+      <menuContribution\r
+            locationURI="toolbar:org.simantics.sysdyn.ui.chartPanel">\r
+         <command\r
+               commandId="org.simantics.sysdyn.ui.chartPanelOrientation"\r
+               icon="platform:/plugin/com.famfamfam.silk/icons/page_white_text_width.png"\r
+               label="Change Orientation"\r
+               style="push"\r
+               tooltip="Change orientation">\r
+         </command>\r
+      </menuContribution>\r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.ui.commands">\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newSCLModule"\r
+            name="New SCL Module">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newAnnotationType"\r
+            name="New Annotation Type">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newAnnotationValue"\r
+            name="New Annotation Value">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newLibrary"\r
+            name="New Library">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.exportSharedOntology"\r
+            name="Export Shared Library">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.trend.view.pin"\r
+            name="Pin Trend">\r
+         <state\r
+               class="org.eclipse.jface.commands.ToggleState"\r
+               id="org.simantics.sysdyn.ui.trend.view.pin.state">\r
+         </state>\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.trend.view.png"\r
+            name="Export To PNG">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.trend.view.svg"\r
+            name="Export To SVG">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.showModule"\r
+            name="Show Module">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.pasteSpecial"\r
+            name="Paste Special">\r
+      </command>      \r
+      <command\r
+            id="org.simantics.sysdyn.ui.removeNode"\r
+            name="Remove Node">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.renameNode"\r
+            name="Rename Node">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleSimulation"\r
+            id="org.simantics.sysdyn.ui.toggleSimulation"\r
+            name="Toggle Simulate">\r
+         <state\r
+               class="org.eclipse.jface.commands.ToggleState"\r
+               id="org.simantics.sysdyn.ui.toggleSimulation.state">\r
+         </state>\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.SynthesisSimulation"\r
+            id="org.simantics.sysdyn.ui.synthesisSimulation"\r
+            name="Slider and Trends">\r
+         <state\r
+               class="org.eclipse.jface.commands.ToggleState"\r
+               id="org.simantics.sysdyn.ui.synthesisSimulation.state">\r
+         </state>\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewModuleNodeHandler"\r
+            id="org.simantics.sysdyn.ui.newModuleNode"\r
+            name="New Module">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.activateExperiment"\r
+            name="Activate Experiment">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.assignIC"\r
+            name="Assign IC">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.RunBasicExperiment"\r
+            id="org.simantics.sysdyn.ui.run"\r
+            name="Run Basic Simulation">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.DisposeExperiment"\r
+            id="org.simantics.sysdyn.ui.dispose"\r
+            name="Quit Experiment">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.SaveResultsHandler"\r
+            id="org.simantics.sysdyn.ui.saveResults"\r
+            name="Save Results">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.SaveICHandler"\r
+            id="org.simantics.sysdyn.ui.saveIC"\r
+            name="Save Initial Condition">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.SaveHistoryHandler"\r
+            id="org.simantics.sysdyn.ui.saveHistory"\r
+            name="Save History">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleResultActivation"\r
+            id="org.simantics.sysdyn.ui.activateResult"\r
+            name="Show In Charts">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleResultSetActivation"\r
+            id="org.simantics.sysdyn.ui.activateResultSet"\r
+            name="Show In Charts">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewExperimentNodeHandler"\r
+            id="org.simantics.sysdyn.ui.newExperiment"\r
+            name="New Experiment">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.exportModel"\r
+            name="Export Model">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.importModel"\r
+            name="Import Model">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.importSharedLibrary"\r
+            name="Import Shared Library">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newEnumeration"\r
+            name="New Enumeration">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.importMdl"\r
+            name="Import .mdl">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewFunctionHandler"\r
+            id="org.simantics.sysdyn.ui.newFunction"\r
+            name="NewFunction">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.importExternalFunctionFile"\r
+            name="ImportExternalFunctionFile">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.exportExternalFunctionFile"\r
+            name="ExportExternalFunctionFile">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newFunctionLibrary"\r
+            name="New Function Library">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newSharedFunctionLibrary"\r
+            name="New Shared Function Library">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.importFunctionLibrary"\r
+            name="Import Function Library">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.exportFunctionLibrary"\r
+            name="Export Function Library">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.importModule"\r
+            name="Import Module">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.exportModule"\r
+            name="Export Module">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newSpreadSheet"\r
+            name="New SpreadSheet">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newModel"\r
+            name="New System Dynamics Model">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newPlaybackExperiment"\r
+            name="New Playback Experiment">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newGameExperiment"\r
+            name="New Game Experiment">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"\r
+            name="New Sensitivity Analysis Experiment">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackExperimentHandler"\r
+            id="org.simantics.sysdyn.ui.playback"\r
+            name="Playback experiment">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.SlowSpeedHandler"\r
+            id="org.simantics.sysdyn.ui.playbackSlow"\r
+            name="Slow Playback">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.NormalSpeedHandler"\r
+            id="org.simantics.sysdyn.ui.playbackNormal"\r
+            name="Normal Playback">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.FastSpeedHandler"\r
+            id="org.simantics.sysdyn.ui.playbackFast"\r
+            name="Fast Playback">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackResetHandler"\r
+            id="org.simantics.sysdyn.ui.playbackReset"\r
+            name="Reset Playback">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackReloadHandler"\r
+            id="org.simantics.sysdyn.ui.playbackReload"\r
+            name="Reload Playback">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.ChartPanelOrientationHandler"\r
+            id="org.simantics.sysdyn.ui.chartPanelOrientation"\r
+            name="Chart Panel Orientation">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewXYLineChartHandler"\r
+            id="org.simantics.sysdyn.ui.newXYLineChart"\r
+            name="New XY Line Chart">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewBarChartHandler"\r
+            id="org.simantics.sysdyn.ui.newBarChart"\r
+            name="New Bar Chart">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewPieChartHandler"\r
+            id="org.simantics.sysdyn.ui.newPieChart"\r
+            name="New Pie Chart">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewSensitivityChartHandler"\r
+            id="org.simantics.sysdyn.ui.newSensitivityChart"\r
+            name="New XY Line Chart">\r
+      </command>      \r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewHistoryDataHandler"\r
+            id="org.simantics.sysdyn.ui.newHistoryData"\r
+            name="New History Data">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.game.StepHandler"\r
+            id="org.simantics.sysdyn.ui.step"\r
+            name="Step">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.game.ReloadGameExperimentHandler"\r
+            id="org.simantics.sysdyn.ui.reloadGame"\r
+            name="Reload Game">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"\r
+            name="New Game Experiment">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.RunSensitivityAnalysisExperiment"\r
+            id="org.simantics.sysdyn.ui.runSensitivityAnalysis"\r
+            name="Run Basic Simulation">\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.ToggleSimulation"\r
+            id="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation"\r
+            name="Toggle Simulate">\r
+         <state\r
+               class="org.eclipse.jface.commands.ToggleState"\r
+               id="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation.state">\r
+         </state>\r
+      </command>\r
+      <command\r
+            defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.SaveResultsHandler"\r
+            id="org.simantics.sysdyn.ui.saveSensitivityAnalysisResults"\r
+            name="Save Results">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.exportModelButton"\r
+            name="Export Model">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.exportModelAsButton"\r
+            name="Export Model As...">\r
+      </command>\r
+      <command\r
+            id="org.simantics.sysdyn.ui.diagramTool"\r
+            name="Diagram Tool">\r
+         <state\r
+               id="org.eclipse.ui.commands.radioState">\r
+            <class\r
+                  class="org.eclipse.ui.handlers.RadioState">\r
+               <parameter\r
+                     name="default"\r
+                     value="pointer">\r
+               </parameter>\r
+               <parameter\r
+                     name="persisted"\r
+                     value="false">\r
+               </parameter>\r
+            </class>\r
+         </state>\r
+      </command>\r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.ui.handlers">\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.trend.PinTrend"\r
+            commandId="org.simantics.sysdyn.ui.trend.view.pin">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.trend.TrendToPng"\r
+            commandId="org.simantics.sysdyn.ui.trend.view.png">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.trend.TrendToSvg"\r
+            commandId="org.simantics.sysdyn.ui.trend.view.svg">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.NewSCLModuleHandler"\r
+            commandId="org.simantics.sysdyn.ui.newSCLModule">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.NewAnnotationTypeHandler"\r
+            commandId="org.simantics.sysdyn.ui.newAnnotationType">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                 <test\r
+                       args="http://www.simantics.org/Layer0-0.0/Library"\r
+                       property="org.simantics.graph.resourceType"\r
+                       value="true">\r
+                 </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.NewAnnotationValueHandler"\r
+            commandId="org.simantics.sysdyn.ui.newAnnotationValue">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                 <test\r
+                       args="http://www.simantics.org/Layer0-0.0/Entity"\r
+                       property="org.simantics.graph.resourceType"\r
+                       value="true">\r
+                 </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.NewLibraryHandler"\r
+            commandId="org.simantics.sysdyn.ui.newLibrary">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                        <test\r
+                              args="http://www.simantics.org/Layer0-0.0/Library"\r
+                              property="org.simantics.graph.resourceType"\r
+                              value="true">\r
+                        </test>\r
+                     <test\r
+                           args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
+                           property="org.simantics.sysdyn.ui.nodeClass">\r
+                     </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.ShowModuleHandler"\r
+            commandId="org.simantics.sysdyn.ui.showModule">\r
+         <enabledWhen>\r
+            <and>\r
+               <with\r
+                     variable="selection">\r
+                  <and>\r
+                     <test\r
+                           args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
+                           property="org.simantics.graph.resourceType">\r
+                     </test>\r
+                  </and>\r
+               </with>\r
+            </and>\r
+         </enabledWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.PasteSpecialHandler"\r
+            commandId="org.simantics.sysdyn.ui.pasteSpecial">\r
+      </handler>      \r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.UnlinkNodeHandler2"\r
+            commandId="org.simantics.sysdyn.ui.removeNode">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.image.ui.modelBrowser.ImageNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.operating.ui.modelBrowser.CompositeNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SheetNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.AbstractChartNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SCLModule"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <!--\r
+                  <test\r
+                        args="org.simantics.document.workbench.browser_old.DocumentationNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  -->\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.RenameNodeHandler"\r
+            commandId="org.simantics.sysdyn.ui.renameNode">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SheetNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.BarChartNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModuleNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SCLModule"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <!--\r
+                  <test\r
+                        args="org.simantics.document.workbench.browser_old.DocumentationNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  -->\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.imports.ImportModelHandler"\r
+            commandId="org.simantics.sysdyn.ui.importModel">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.imports.ImportSharedLibraryHandler"\r
+            commandId="org.simantics.sysdyn.ui.importSharedLibrary">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.exports.ExportModelHandler"\r
+            commandId="org.simantics.sysdyn.ui.exportModel">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.imports.ImportMdlHandler"\r
+            commandId="org.simantics.sysdyn.ui.importMdl">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.newComponents.NewEnumerationNodeHandler"\r
+            commandId="org.simantics.sysdyn.ui.newEnumeration">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.imports.ImportExternalFunctionFilesHandler"\r
+            commandId="org.simantics.sysdyn.ui.importExternalFunctionFile">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.exports.ExportExternalFunctionFilesHandler"\r
+            commandId="org.simantics.sysdyn.ui.exportExternalFunctionFile">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.newComponents.NewFunctionLibraryHandler"\r
+            commandId="org.simantics.sysdyn.ui.newFunctionLibrary">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.newComponents.NewSharedFunctionLibraryHandler"\r
+            commandId="org.simantics.sysdyn.ui.newSharedFunctionLibrary">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.exports.ExportFunctionLibrary"\r
+            commandId="org.simantics.sysdyn.ui.exportFunctionLibrary">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.imports.ImportFunctionLibrary"\r
+            commandId="org.simantics.sysdyn.ui.importFunctionLibrary">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.imports.ImportModuleHandler"\r
+            commandId="org.simantics.sysdyn.ui.importModule">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModulesNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.exports.ExportModuleHandler"\r
+            commandId="org.simantics.sysdyn.ui.exportModule">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.modeling.ui.modelBrowser.handlers.StandardCopyHandler"\r
+            commandId="org.eclipse.ui.edit.copy">\r
+         <enabledWhen>\r
+            <not>\r
+               <count\r
+                     value="0">\r
+               </count>\r
+            </not>\r
+         </enabledWhen>\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <test\r
+                     args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"\r
+                     property="org.simantics.sysdyn.ui.nodeClass">\r
+               </test>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.modeling.ui.modelBrowser.handlers.StandardPasteHandler"\r
+            commandId="org.eclipse.ui.edit.paste">\r
+         <enabledWhen>\r
+            <not>\r
+               <count\r
+                     value="0">\r
+               </count>\r
+            </not>\r
+         </enabledWhen>\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModuleNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.newComponents.NewSpreadSheetHandler"\r
+            commandId="org.simantics.sysdyn.ui.newSpreadSheet">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.newComponents.NewModelHandler"\r
+            commandId="org.simantics.sysdyn.ui.newModel">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.newComponents.NewPlaybackExperimentNodeHandler"\r
+            commandId="org.simantics.sysdyn.ui.newPlaybackExperiment">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.newComponents.NewGameExperimentNodeHandler"\r
+            commandId="org.simantics.sysdyn.ui.newGameExperiment">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.newComponents.NewSensitivityAnalysisExperimentNodeHandler"\r
+            commandId="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.FindReplaceHandler"\r
+            commandId="org.eclipse.ui.edit.findReplace">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.exports.ExportModelAsButtonHandler"\r
+            commandId="org.simantics.sysdyn.ui.exportModelAsButton">\r
+         <activeWhen>\r
+            <or>\r
+               <with\r
+                  variable="activePartId">\r
+                         <equals value="org.simantics.browsing.ui.graph.propertyView"/>\r
+               </with>\r
+               <with\r
+                  variable="selection">\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass2">\r
+                  </test>\r
+               </with>\r
+            </or>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.exports.ExportModelButtonHandler"\r
+            commandId="org.simantics.sysdyn.ui.exportModelButton">\r
+         <activeWhen>\r
+            <or>\r
+               <with\r
+                     variable="activePartId">\r
+                  <equals\r
+                        value="org.simantics.browsing.ui.graph.propertyView">\r
+                  </equals>\r
+               </with>\r
+               <with\r
+                     variable="selection">\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass2">\r
+                  </test>\r
+               </with>\r
+            </or>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.DiagramToolHandler"\r
+            commandId="org.simantics.sysdyn.ui.diagramTool">\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator"\r
+            commandId="org.simantics.sysdyn.ui.activateExperiment">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.AssignIC"\r
+            commandId="org.simantics.sysdyn.ui.assignIC">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>\r
+      <handler\r
+            class="org.simantics.sysdyn.ui.handlers.ExportSharedOntologyHandler"\r
+            commandId="org.simantics.sysdyn.ui.exportSharedOntology">\r
+         <activeWhen>\r
+            <with\r
+                  variable="selection">\r
+               <or>\r
+                  <test\r
+                        args="org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode"\r
+                        property="org.simantics.sysdyn.ui.nodeClass">\r
+                  </test>\r
+               </or>\r
+            </with>\r
+         </activeWhen>\r
+      </handler>      \r
+   </extension>\r
+   \r
+   <extension\r
+         point="org.eclipse.ui.importWizards">\r
+         \r
+      <category\r
+           id="org.simantics.sysdyn.import"\r
+           name="Sysdyn">\r
+      </category>\r
+<!--      <wizard\r
+            category="org.simantics.sysdyn.import"\r
+            class="org.simantics.sysdyn.ui.wizards.models.ImportWizardModel"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
+            id="org.simantics.sysdyn.ui.wizards.modelImport"\r
+            name="Import Sysdyn Model">\r
+      </wizard> -->\r
+      <wizard\r
+            category="org.simantics.sysdyn.import"\r
+            class="org.simantics.sysdyn.ui.wizards.model.SysdynModelImportWizard"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
+            id="org.simantics.sysdyn.import.model2"\r
+            name="Import Sysdyn Model">\r
+      </wizard>\r
+<!--      <wizard\r
+            category="org.simantics.sysdyn.import"\r
+            class="org.simantics.sysdyn.ui.wizards.modules.ImportWizardModule"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"\r
+            id="org.simantics.sysdyn.ui.wizards.moduleImport"\r
+            name="Import Sysdyn Module">\r
+      </wizard>\r
+      <wizard\r
+            category="org.simantics.sysdyn.import"\r
+            class="org.simantics.sysdyn.ui.wizards.functions.ImportWizardFunction"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/brick.png"\r
+            id="org.simantics.sysdyn.ui.wizards.functionImport"\r
+            name="Import Sysdyn Function Library">\r
+      </wizard>\r
+      <wizard\r
+            category="org.simantics.sysdyn.import"\r
+            class="org.simantics.sysdyn.ui.wizards.mdl.ImportWizardMdl"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
+            id="org.simantics.sysdyn.ui.wizards.mdlImport"\r
+            name="Import Vensim Model (.mdl)">\r
+      </wizard> -->\r
+   </extension>\r
+   \r
+   <extension\r
+         point="org.eclipse.ui.exportWizards">\r
+         \r
+      <category\r
+           id="org.simantics.sysdyn.export"\r
+           name="Sysdyn">\r
+      </category>\r
+<!--     <wizard\r
+            category="org.simantics.sysdyn.export"\r
+            class="org.simantics.sysdyn.ui.wizards.models.ExportWizardModel"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
+            id="org.simantics.sysdyn.export.model"\r
+            name="Export Sysdyn Model">\r
+      </wizard> -->\r
+        <wizard\r
+            category="org.simantics.sysdyn.export"\r
+            class="org.simantics.sysdyn.ui.wizards.model.SysdynModelExportWizard"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
+            id="org.simantics.sysdyn.export.model2"\r
+            name="Export Sysdyn Model">\r
+      </wizard>\r
+<!--      <wizard\r
+            category="org.simantics.sysdyn.export"\r
+            class="org.simantics.sysdyn.ui.wizards.modules.ExportWizardModule"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"\r
+            id="org.simantics.sysdyn.export.module"\r
+            name="Export Sysdyn Module">\r
+      </wizard> \r
+      <wizard\r
+            category="org.simantics.sysdyn.export"\r
+            class="org.simantics.sysdyn.ui.wizards.functions.ExportWizardFunction"\r
+            icon="platform:/plugin/com.famfamfam.silk/icons/brick.png"\r
+            id="org.simantics.sysdyn.export.function"\r
+            name="Export Sysdyn Function Library">\r
+      </wizard> -->\r
+   </extension>\r
+   \r
+   <extension\r
+         point="org.eclipse.core.expressions.propertyTesters">\r
+      <propertyTester\r
+            class="org.simantics.browsing.ui.swt.NodePropertyTester"\r
+            id="org.simantics.browsing.ui.nodePropertyTester"\r
+            namespace="org.simantics.sysdyn.ui"\r
+            properties="nodeClass"\r
+            type="org.eclipse.jface.viewers.IStructuredSelection">\r
+      </propertyTester>\r
+      <propertyTester\r
+            class="org.simantics.sysdyn.ui.browser.nodes.ExportTester"\r
+            id="org.simantics.sysdyn.ui.selectionPropertyTester"\r
+            namespace="org.simantics.sysdyn.ui"\r
+            properties="nodeClass2"\r
+            type="org.eclipse.jface.viewers.IStructuredSelection">\r
+      </propertyTester>\r
+   </extension>\r
+   <extension\r
+         id="product"\r
+         point="org.eclipse.core.runtime.products">\r
+      <product\r
+            application="org.simantics.workbench.application"\r
+            description="Simantics System Dynamic Modelling Environment"\r
+            name="Simantics System Dynamic Tool">\r
+         <property\r
+               name="appName"\r
+               value="Simantics System Dynamic Tool">\r
+         </property>\r
+         <property\r
+               name="preferenceCustomization"\r
+               value="plugin_customization.ini">\r
+         </property>\r
+         <property\r
+               name="windowImages"\r
+               value="icons/simantics_sysdyn16.png,icons/simantics_sysdyn32.png,icons/simantics_sysdyn48.png,icons/simantics_sysdyn64.png,icons/simantics_sysdyn128.png">\r
+         </property>\r
+         <property\r
+               name="aboutText"\r
+               value="%about.text">\r
+         </property>\r
+         <property\r
+               name="aboutImage"\r
+               value="icons/simantics_sysdyn128.png">\r
+         </property>\r
+      </product>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.browsing.ui.common.viewpointContributionBinding">\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ModuleType"\r
+               preference="1.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.Project"\r
+               preference="1.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.Modules"\r
+               preference="1.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.Model"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AnnotationContribution"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AnnotationContribution2"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.LibraryContribution"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.Experiment"\r
+               preference="1.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SimulationResult"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSet"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.Configuration"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraries"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.LibraryFunctions"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SharedFunctionLibraries"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.Book"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.Charts"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SCLModules"\r
+               preference="2">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.InitialConditions"\r
+               preference="2">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableVariableIndexes">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.AvailableEnumerations"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/UsedVariableIndexes">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.UsedEnumerations"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationIndexes"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationReplacement">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.ReplaceableEnumerations"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFiles"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ModelBrowser">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SysdynProject"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.functions.SharedFunctionLibraries"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.functions.SelectedSharedFunctionLibraries"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/FunctionTree">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModels"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeLibraries"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedLibraries"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSubLibraries"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ImportModuleTree">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModels"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ExportModuleTree">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModels"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModules"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+   </extension>\r
+\r
+   <extension\r
+         point="org.simantics.browsing.ui.common.comparableContextBinding">\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
+         <implementation\r
+               class="org.simantics.modeling.ui.modelBrowser2.contributions.LexicalComparableContributor"\r
+               preference="1.0">\r
+         </implementation>\r
+      </binding>\r
+   </extension>\r
+   \r
+   <extension\r
+         point="org.simantics.browsing.ui.common.labelerBinding">\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SharedOntologyLabeler"\r
+               preference="3.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ConfigurationLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.VariableLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ExperimentsLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ModelLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ModulesLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ExperimentLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ModuleLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.InputLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ModuleTypeLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.FunctionsLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SharedFunctionsLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.BookLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SheetLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ChartLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ChartsLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SCLModulesLabeler"\r
+               preference="2">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.InitialConditionsLabeler"\r
+               preference="2">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SCLModuleLabeler"\r
+               preference="2">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.InitialConditionLabeler"\r
+               preference="2">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AnnotationTypeLabeler"\r
+               preference="2">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AnnotationValueLabeler"\r
+               preference="2">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.LibraryLabeler"\r
+               preference="2">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableVariableIndexes">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationLabeler"\r
+               preference="1.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/UsedVariableIndexes">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.ConflictingEnumerationLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationIndexLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationReplacement">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.ReplaceableEnumerationsLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/FunctionTree">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeFunctionLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedLibraryLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedFolderLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ImportModuleTree">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ExportModuleTree">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModulesLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.browsing.ui.common.imagerBinding">\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SharedOntologyImager"\r
+               preference="3.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AnnotationTypeImager"\r
+               preference="3.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AnnotationValueImager"\r
+               preference="3.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.LibraryImager"\r
+               preference="3.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.browsing.ui.swt.ImageDescriptorProviderAdapter"\r
+               preference="1.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultImager"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetImager"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ChartImager"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ChartsImager"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileImager"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.browsing.ui.common.labelDecoratorBinding">\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultDecorator"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetDecorator"\r
+               preference="2.0">\r
+         </implementation>\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.browser.contributions.ExperimentLabelDecorator"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.browsing.ui.common.selectionProcessorBinding">\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Modeling-0.0/ModelingBrowseContext">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">\r
+         </implementation>\r
+      </binding>\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">\r
+         </implementation>\r
+      </binding>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.browsing.ui.common.checkedStateBinding">\r
+      <binding\r
+            browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">\r
+         <implementation\r
+               class="org.simantics.sysdyn.ui.properties.widgets.arrays.ShowInChartsCheckBox"\r
+               preference="2.0">\r
+         </implementation>\r
+      </binding>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.ui.resourceEditorAdapter">\r
+      <adapterClass\r
+            class="org.simantics.sysdyn.ui.editor.OpenDiagramFromConfigurationAdapter"\r
+            groupId="org.simantics.diagramEditor.group"\r
+            priority="100">\r
+      </adapterClass>\r
+      <adapterClass\r
+            class="org.simantics.sysdyn.ui.editor.OpenDiagramFromComponentAdapter"\r
+            priority="90">\r
+      </adapterClass>\r
+      <adapter\r
+            editorId="org.simantics.sysdyn.ui.modelicaEditor"\r
+            priority="2"\r
+            type_uris="http://www.simantics.org/Sysdyn-0.0/Configuration">\r
+      </adapter>\r
+      <adapter\r
+            editorId="org.simantics.sysdyn.ui.jfreeChartEditor"\r
+            priority="2"\r
+            type_uris="http://www.simantics.org/JFreeChart-0.0/Chart">\r
+      </adapter>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.ui.doubleClick">\r
+      <doubleClickAction\r
+            class="org.simantics.sysdyn.ui.actions.ActivateExperimentAction"\r
+            name="Activate Sysdyn Experiment"\r
+            priority="300.0">\r
+      </doubleClickAction>\r
+      <doubleClickAction\r
+            class="org.simantics.sysdyn.ui.browser.actions.ActivateResultDatasetAction"\r
+            name="Activate Result In Charts"\r
+            priority="250.0">\r
+      </doubleClickAction>  \r
+      <doubleClickAction\r
+            class="org.simantics.sysdyn.ui.browser.actions.ActivateResultSetDatasetAction"\r
+            name="Activate Result In Charts"\r
+            priority="240.0">\r
+      </doubleClickAction> \r
+      <doubleClickAction\r
+            class="org.simantics.sysdyn.ui.browser.actions.OpenSheetAction"\r
+            name="Open Spreadsheet"\r
+            priority="220.0">\r
+      </doubleClickAction>\r
+      <!--<doubleClickAction\r
+            class="org.simantics.sysdyn.ui.actions.ConsumeUnnecessaryEntersAction"\r
+            name="Consume unnecessary enters"\r
+            priority="200.0">\r
+      </doubleClickAction>-->\r
+      <doubleClickAction\r
+            class="org.simantics.sysdyn.ui.actions.ShowInstantiatedModuleAction"\r
+            name="Show Instantiated Module"\r
+            priority="100.0">\r
+      </doubleClickAction>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.ui.toolbarCommand">\r
+      <command\r
+            commandId="org.simantics.sysdyn.ui.diagramTool"\r
+            image="platform:/plugin/com.famfamfam.silk/icons/lock.png"\r
+            name="Lock Sketch"\r
+            toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
+            type="radio"\r
+            value="lock">\r
+      </command>\r
+      <command\r
+            commandId="org.simantics.sysdyn.ui.diagramTool"\r
+            image="icons/cursor.png"\r
+            name="Pointer"\r
+            toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
+            type="radio"\r
+            value="pointer">\r
+      </command>\r
+      <command\r
+            commandId="org.simantics.sysdyn.ui.diagramTool"\r
+            image="icons/dependency.png"\r
+            name="Create Dependency (Alt+Mouse1)"\r
+            toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
+            type="radio"\r
+            value="dependency">\r
+      </command>\r
+      <command\r
+            commandId="org.simantics.sysdyn.ui.diagramTool"\r
+            image="icons/flow.png"\r
+            name="Create Flow (Alt+Mouse2)"\r
+            toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
+            type="radio"\r
+            value="flow">\r
+      </command>\r
+      <command\r
+            commandId="org.simantics.sysdyn.ui.diagramTool"\r
+            image="platform:/plugin/com.famfamfam.silk/icons/textfield_add.png"\r
+            name="Create Auxiliary (Shift+A)"\r
+            toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
+            type="radio"\r
+            value="auxiliary">\r
+      </command>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.project.feature">\r
+      <feature\r
+            class="org.simantics.sysdyn.ui.project.SysdynProject"\r
+            description="System dynamics modelling project. Create system dynamics models and simulate them with OpenModelica."\r
+            id="org.simantics.sysdyn.project"\r
+            label="System Dynamics Project"\r
+            published="true">\r
+         <requires id="org.simantics.sysdyn.dependencies"/>\r
+         <requires id="org.simantics.simulation.experimentManager"/>\r
+         <installGroup id="org.simantics.sysdyn.feature.group" version="[1.0.0,2.0.0)"/>\r
+      </feature>\r
+      <feature\r
+            class="org.simantics.project.features.DependencyValidationFeature:http://www.simantics.org/Sysdyn-0.0/ImportedOntologies"\r
+            id="org.simantics.sysdyn.dependencies"\r
+            label="System Dynamics Ontology Dependencies">\r
+      </feature>\r
+   </extension>\r
+   \r
+   \r
+   <extension point="org.simantics.scl.reflection.binding">\r
+      <namespace path="http://www.simantics.org/Sysdyn-0.0/Validations">\r
+        <namespace path="Dependencies">\r
+            <externalClass className="org.simantics.db.Resource"/>\r
+            <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
+            <externalClass className="org.simantics.db.ReadGraph"/>\r
+            <externalClass className="org.simantics.db.WriteGraph"/>\r
+            <class className="org.simantics.sysdyn.ui.validation.DependencyFunction"/>\r
+        </namespace>\r
+        <namespace path="Expressions">\r
+            <externalClass className="org.simantics.db.Resource"/>\r
+            <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
+            <externalClass className="org.simantics.db.ReadGraph"/>\r
+            <externalClass className="org.simantics.db.WriteGraph"/>\r
+            <class className="org.simantics.sysdyn.ui.validation.ExpressionIssueFunction"/>\r
+        </namespace>\r
+        <namespace path="Functions">\r
+            <externalClass className="org.simantics.db.Resource"/>\r
+            <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
+            <externalClass className="org.simantics.db.ReadGraph"/>\r
+            <externalClass className="org.simantics.db.WriteGraph"/>\r
+            <class className="org.simantics.sysdyn.ui.validation.Functions"/>\r
+        </namespace>\r
+        <namespace path="Enumerations">\r
+            <externalClass className="org.simantics.db.Resource"/>\r
+            <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
+            <externalClass className="org.simantics.db.ReadGraph"/>\r
+            <externalClass className="org.simantics.db.WriteGraph"/>\r
+            <class className="org.simantics.sysdyn.ui.validation.EnumerationFunction"/>\r
+        </namespace>        \r
+        <namespace path="Units">\r
+            <externalClass className="org.simantics.db.Resource"/>\r
+            <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
+            <externalClass className="org.simantics.db.ReadGraph"/>\r
+            <externalClass className="org.simantics.db.WriteGraph"/>\r
+            <class className="org.simantics.sysdyn.ui.validation.UnitFunction"/>\r
+        </namespace>             \r
+      </namespace>\r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.ui.preferencePages">\r
+      <page\r
+            class="org.simantics.sysdyn.ui.preferences.SolverPreferencePage"\r
+            id="org.simantics.sysdyn.solver.preferences"\r
+            name="Solver">\r
+      </page>\r
+      <page\r
+            class="org.simantics.sysdyn.ui.preferences.ModelicaPreferencePage"\r
+            id="org.simantics.modelica.preferences"\r
+            name="Modelica">\r
+      </page>\r
+      <page\r
+            class="org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferencePage"\r
+            id="org.simantics.sysdyn.diagram.preferences"\r
+            name="Sysdyn Diagrams">\r
+      </page>      \r
+   </extension>\r
+   <extension\r
+         point="org.eclipse.core.runtime.preferences">\r
+      <initializer\r
+            class="org.simantics.modelica.preferences.ModelicaPreferenceInitializer">\r
+      </initializer>\r
+      <initializer\r
+            class="org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferencesInitializer">\r
+      </initializer>      \r
+   </extension>\r
+</plugin>\r
diff --git a/1.8/org.simantics.sysdyn.ui/plugin_customization.ini b/1.8/org.simantics.sysdyn.ui/plugin_customization.ini
new file mode 100644 (file)
index 0000000..92e8ed0
--- /dev/null
@@ -0,0 +1,2 @@
+org.eclipse.ui/SHOW_PROGRESS_ON_STARTUP = false\r
+org.eclipse.ui/DOCK_PERSPECTIVE_BAR=right
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/splash.bmp b/1.8/org.simantics.sysdyn.ui/splash.bmp
new file mode 100644 (file)
index 0000000..faea2d9
Binary files /dev/null and b/1.8/org.simantics.sysdyn.ui/splash.bmp differ
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/Activator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/Activator.java
new file mode 100644 (file)
index 0000000..5e1333d
--- /dev/null
@@ -0,0 +1,110 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui;\r
+\r
+import java.net.URL;\r
+\r
+import org.apache.log4j.BasicConfigurator;\r
+import org.apache.log4j.ConsoleAppender;\r
+import org.apache.log4j.Level;\r
+import org.apache.log4j.Logger;\r
+import org.apache.log4j.SimpleLayout;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.resource.ImageRegistry;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.jface.resource.ResourceManager;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.ui.plugin.AbstractUIPlugin;\r
+import org.osgi.framework.Bundle;\r
+import org.osgi.framework.BundleContext;\r
+import org.simantics.issues.Severity;\r
+import org.simantics.utils.FileUtils;\r
+\r
+public class Activator extends AbstractUIPlugin {\r
+\r
+    // The plug-in ID\r
+    public static final String PLUGIN_ID = "org.simantics.sysdyn.ui";\r
+    \r
+    // The shared instance\r
+    private static Activator plugin;\r
+    \r
+    private static LocalResourceManager resourceManager;\r
+    \r
+    public static String          FATAL_SVG_TEXT;\r
+    public static String          ERROR_SVG_TEXT;\r
+    public static String          WARNING_SVG_TEXT;\r
+    public static ImageDescriptor FATAL_DECORATION_ICON;\r
+    public static ImageDescriptor ERROR_DECORATION_ICON;\r
+    public static ImageDescriptor WARNING_DECORATION_ICON;\r
+\r
+    @Override\r
+    public void start(BundleContext context) throws Exception {\r
+        super.start(context);\r
+        ConsoleAppender appender =\r
+            new ConsoleAppender(new SimpleLayout());\r
+        BasicConfigurator.configure(appender);\r
+        Logger.getRootLogger().setLevel(Level.WARN);\r
+        plugin = this;\r
+        \r
+        \r
+        Bundle bundle = context.getBundle();\r
+\r
+        FATAL_SVG_TEXT = FileUtils.getContents(bundle.getResource("icons/fatal.svg"));\r
+        ERROR_SVG_TEXT = FileUtils.getContents(bundle.getResource("icons/error.svg"));\r
+        WARNING_SVG_TEXT = FileUtils.getContents(bundle.getResource("icons/warning.svg"));\r
+        FATAL_DECORATION_ICON = ImageDescriptor.createFromURL(bundle.getResource("icons/fatal_decoration.png"));\r
+        ERROR_DECORATION_ICON = ImageDescriptor.createFromURL(bundle.getResource("icons/error_decoration.png"));\r
+        WARNING_DECORATION_ICON = ImageDescriptor.createFromURL(bundle.getResource("icons/warning_decoration.png"));\r
+    }\r
+    \r
+    @Override\r
+    public void stop(BundleContext context) throws Exception {\r
+        plugin = null;\r
+        super.stop(context);\r
+    }\r
+\r
+    public static Activator getDefault() {\r
+        return plugin;\r
+    }\r
+    \r
+    @Override\r
+    protected ImageRegistry createImageRegistry() {\r
+        return super.createImageRegistry();\r
+    }\r
+\r
+    @Override\r
+    protected void initializeImageRegistry(ImageRegistry reg) {\r
+        reg.put(Severity.FATAL.toString(), FATAL_DECORATION_ICON);\r
+        reg.put(Severity.ERROR.toString(), ERROR_DECORATION_ICON);\r
+        reg.put(Severity.WARNING.toString(), WARNING_DECORATION_ICON);\r
+    }\r
+    \r
+    public static ResourceManager initializeResourceManager(Display display) {\r
+        if (resourceManager == null) {\r
+            resourceManager = new LocalResourceManager(JFaceResources.getResources(display));\r
+        }\r
+        return resourceManager;\r
+    }\r
+\r
+    public static ResourceManager getResources() {\r
+        if (resourceManager == null)\r
+            throw new IllegalStateException("ResourceManager of bundle '" + PLUGIN_ID + "' is not initialized.");\r
+        return resourceManager;\r
+    }\r
+    \r
+    public static URL getDefaultResource(String name) {\r
+        Activator plugin = getDefault();\r
+        if(plugin == null) throw new IllegalStateException("The plugin is not active.");\r
+        return plugin.getBundle().getResource(name);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ActivateExperimentAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ActivateExperimentAction.java
new file mode 100644 (file)
index 0000000..4e00ace
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.actions;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator;\r
+import org.simantics.ui.DoubleClickEvent;\r
+import org.simantics.ui.IDoubleClickAction;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.action.PriorityAction;\r
+\r
+public class ActivateExperimentAction implements IDoubleClickAction {\r
+\r
+       @Override\r
+       public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {\r
+        ReadGraph g = e.getGraph();\r
+        final Resource experiment = ResourceAdaptionUtils.toSingleResource(e.getResource());\r
+        if (experiment == null)\r
+            return;\r
+\r
+        if (g.isInstanceOf(experiment, SimulationResource.getInstance(g).Experiment)) {\r
+            final IProject project = SimanticsUI.getProject();\r
+            if (project == null)\r
+                return;\r
+\r
+            final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+            if (experimentManager == null) {\r
+                ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());\r
+                return;\r
+            }\r
+\r
+            e.add(new PriorityAction(PriorityAction.HIGH+20) {\r
+                @Override\r
+                public void run() {\r
+                       SysdynExperimentActivator.scheduleActivation(SimanticsUI.getSession(), project, experimentManager, experiment);\r
+                }\r
+            });\r
+            e.consume();\r
+        }\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ConsumeUnnecessaryEntersAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ConsumeUnnecessaryEntersAction.java
new file mode 100644 (file)
index 0000000..b5a284d
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.actions;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.DoubleClickEvent;\r
+import org.simantics.ui.IDoubleClickAction;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.action.PriorityAction;\r
+\r
+public class ConsumeUnnecessaryEntersAction implements IDoubleClickAction {\r
+\r
+       @Override\r
+       public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {\r
+        ReadGraph g = e.getGraph();\r
+        Layer0X L0X = Layer0X.getInstance(g);\r
+        final Resource resource = ResourceAdaptionUtils.toSingleResource(e.getResource());\r
+        if(resource == null)\r
+               return;\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+               \r
+               if(g.isInheritedFrom(resource, sr.SysdynModel) \r
+                               || (g.isInstanceOf(resource, sr.Variable)\r
+                                               && !g.isInstanceOf(resource, sr.IndependentVariable)\r
+                                               && !g.isInstanceOf(resource, sr.Input)\r
+                               )) {\r
+                       consume(e);\r
+               } else if(g.hasStatement(resource, L0X.Represents)){\r
+                       Resource represents = g.getSingleObject(resource, L0X.Represents);      \r
+                       if (g.isInstanceOf(represents, sr.Variable)\r
+                                       && !g.isInstanceOf(resource, sr.IndependentVariable)\r
+                                       && !g.isInstanceOf(resource, sr.Input)) {\r
+                               consume(e);\r
+                       }\r
+               }\r
+       }\r
+       \r
+       private void consume(DoubleClickEvent e) {\r
+        e.add(new PriorityAction(PriorityAction.HIGH) {\r
+            @Override\r
+            public void run() {\r
+               \r
+            }\r
+        });\r
+               e.consume();\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ShowInstantiatedModuleAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ShowInstantiatedModuleAction.java
new file mode 100644 (file)
index 0000000..830b2c5
--- /dev/null
@@ -0,0 +1,137 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.actions;\r
+\r
+import java.util.Set;\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.ui.PartInitException;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.BrowserSelection;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleNode;\r
+import org.simantics.sysdyn.ui.editor.SysdynEditorInput;\r
+import org.simantics.ui.DoubleClickEvent;\r
+import org.simantics.ui.IDoubleClickAction;\r
+import org.simantics.ui.workbench.ResourceEditorInput2;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+import org.simantics.utils.ui.action.PriorityAction;\r
+import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
+\r
+/**\r
+ * Open an editor for a module instance. \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ShowInstantiatedModuleAction implements IDoubleClickAction {\r
+\r
+    private static final String EDITOR_ID = "org.simantics.sysdyn.ui.diagramViewer";\r
+    \r
+       @Override\r
+       public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {\r
+               \r
+        ReadGraph g = e.getGraph();\r
+        Layer0 l0 = Layer0.getInstance(g);\r
+        StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
+\r
+        // Open instance for a module instance, if the resource is adaptable to variable\r
+        Variable variable = AdaptionUtils.adaptToSingle(e.getResource(), Variable.class);\r
+        if(variable != null) {\r
+            Resource represents = variable.getRepresents(g);\r
+            Resource instanceOf = g.getPossibleObject(represents, l0.InstanceOf);\r
+            Resource configuration = g.getPossibleObject(instanceOf, sr2.IsDefinedBy);\r
+            if(configuration != null) {\r
+                String rvi = Variables.getRVI(g, variable);\r
+                if(!rvi.isEmpty())\r
+                    rvi = rvi.substring(1);\r
+                Resource model = Variables.getModel(g, variable);\r
+                addShowModuleAction(e, getResourceEditorInput(g, model, configuration, rvi));\r
+                return;\r
+            }\r
+        }\r
+        \r
+        if(e.getResource() instanceof IStructuredSelection) {\r
+                       Set<BrowserSelection> bss = ISelectionUtils.filterSetSelection(e.getResource(), BrowserSelection.class);\r
+                       \r
+                       if(!bss.isEmpty()) {\r
+                        // Find varaible from BrowserSelection. (Will be replaced with the Variable adaption above)\r
+                               for(BrowserSelection bs : bss) {\r
+                                       Resource configuration = (Resource)bs.getAdapter(Resource.class);\r
+                                       Resource instanceOf = g.getSingleObject(configuration, l0.InstanceOf);\r
+                                       \r
+                                       SysdynResource sr = SysdynResource.getInstance(g);\r
+                                       if(g.isInheritedFrom(instanceOf, sr.Module)) {\r
+                                               configuration = g.getSingleObject(instanceOf, sr2.IsDefinedBy);\r
+                                               variable = (Variable) bs.getAdapter(Variable.class);\r
+                                               String rvi = Variables.getRVI(g, variable).substring(1);\r
+                                               Resource model = Variables.getModel(g, variable);\r
+                                               addShowModuleAction(e, getResourceEditorInput(g, model, configuration, rvi));\r
+                                       } \r
+                               }\r
+                       } else {\r
+                               ModuleNode moduleNode = ISelectionUtils.filterSingleSelection(e.getResource(), ModuleNode.class);\r
+                               if(moduleNode != null) {\r
+                                       Resource model;\r
+                                       String rvi;\r
+                                       if(moduleNode.getVariable() != null) {\r
+                                               model = Variables.getModel(g, moduleNode.getVariable());\r
+                                               Variable var = moduleNode.getVariable();\r
+                                               rvi = Variables.getRVI(g, var).substring(1);\r
+                                       } else {\r
+                                               rvi = (String)g.getRelatedValue(moduleNode.data, Layer0.getInstance(g).HasName);\r
+                                               model = g.getSingleObject(moduleNode.data, l0.PartOf);\r
+                                       }\r
+                                       \r
+                               Resource instanceOf = g.getSingleObject(moduleNode.data, l0.InstanceOf);\r
+                                       Resource conf = g.getSingleObject(instanceOf, sr2.IsDefinedBy);\r
+                                   \r
+                                       addShowModuleAction(e, getResourceEditorInput(g, model, conf, rvi));\r
+                       }\r
+                       }\r
+        } \r
+       }\r
+       \r
+       private ResourceEditorInput2 getResourceEditorInput(ReadGraph g, Resource model, Resource configuration, String rvi) throws DatabaseException {\r
+\r
+               if(model == null) {\r
+                       model = g.syncRequest(new PossibleModel(model));\r
+                       rvi = null;\r
+               }\r
+               \r
+               Resource diagram = g.getSingleObject(configuration, ModelingResources.getInstance(g).CompositeToDiagram);\r
+               return new SysdynEditorInput(EDITOR_ID, diagram, model, rvi == null ? "" : "/" + rvi);\r
+       }\r
+       \r
+       private void addShowModuleAction(DoubleClickEvent e, final ResourceEditorInput2 editorInput) {\r
+        e.add(new PriorityAction(PriorityAction.HIGH) {\r
+            @Override\r
+            public void run() {\r
+               try {\r
+                                       WorkbenchUtils.openEditor(EDITOR_ID, editorInput);\r
+                               } catch (PartInitException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+            }\r
+        });\r
+               e.consume();\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/SysdynVariableRemover.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/SysdynVariableRemover.java
new file mode 100644 (file)
index 0000000..107a172
--- /dev/null
@@ -0,0 +1,115 @@
+package org.simantics.sysdyn.ui.actions;\r
+\r
+import java.util.Map;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Statement;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithSupertype;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.Instances;\r
+import org.simantics.db.layer0.adapter.Remover;\r
+import org.simantics.db.layer0.adapter.impl.EntityRemover;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.project.ontology.ProjectResource;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Remover for sysdyn variables. The main purpose is to take care that input and output references\r
+ * are removed \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynVariableRemover implements Remover {\r
+    \r
+    private Resource resource;\r
+     \r
+    public SysdynVariableRemover(Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+\r
+    @Override\r
+    public String canRemove(ReadGraph graph, Map<Object, Object> aux) throws DatabaseException {\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void remove(WriteGraph graph) throws DatabaseException {\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        // Take care of inputs and outputs\r
+        if(graph.hasStatement(resource, SR.IsOutput) || graph.isInstanceOf(resource, SR.Input)) {\r
+            Layer0 L0 = Layer0.getInstance(graph);\r
+            ProjectResource PROJ = ProjectResource.getInstance(graph);\r
+            Resource configuration = graph.getPossibleObject(resource, L0.PartOf);\r
+            if(configuration != null) {\r
+                Resource moduleType =  graph.getPossibleObject(configuration, L0.PartOf);\r
+                if(graph.isInheritedFrom(moduleType, SR.Module)) {\r
+                    Resource project = moduleType;\r
+                    do {\r
+                        project = graph.getPossibleObject(project, L0.PartOf);\r
+                    } while (project != null && !graph.isInstanceOf(project, PROJ.Project));\r
+\r
+                    if(project != null) {\r
+                        for(Resource model : graph.syncRequest(new ObjectsWithType(project, L0.ConsistsOf, SR.SysdynModel))) {\r
+                            removeOutputReferencesFromModel(graph, model, resource, moduleType);\r
+                        }\r
+                    }\r
+\r
+                }\r
+            }\r
+        }\r
+\r
+        // Remove possible shadow variables\r
+        for(Resource shadow : graph.getObjects(resource, SR.Shadow_original_Inverse)) {\r
+            Resource element = graph.getPossibleObject(shadow, ModelingResources.getInstance(graph).ComponentToElement);\r
+            // TODO: not sure if this is correct, but without this the removal \r
+            // of a model with several shadow variables that have the same \r
+            // original variable fails in an assertion error\r
+            if (element != null)\r
+               RemoverUtil.remove(graph, element);\r
+        }\r
+        \r
+        EntityRemover.remove(graph, resource);\r
+\r
+    }\r
+\r
+    private void removeOutputReferencesFromModel(WriteGraph graph, Resource model, Resource reference, Resource moduleType) throws DatabaseException {\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        StructuralResource2 SR2 = StructuralResource2.getInstance(graph);\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        \r
+        Instances moduleInstanceFinder = graph.adapt(moduleType, Instances.class);\r
+        \r
+        denyReferences(graph, moduleInstanceFinder, graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration), reference);\r
+        \r
+        for(Resource type : graph.syncRequest(new ObjectsWithSupertype(model, L0.ConsistsOf, SR.Module))) {\r
+            Resource configuration = graph.getPossibleObject(type, SR2.IsDefinedBy);\r
+            denyReferences(graph, moduleInstanceFinder, configuration, reference);\r
+\r
+        }\r
+        \r
+    }\r
+    \r
+    private void denyReferences(WriteGraph graph, Instances moduleInstanceFinder, Resource indexRoot, Resource reference) throws DatabaseException {\r
+        StructuralResource2 SR2 = StructuralResource2.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+        for(Resource module : moduleInstanceFinder.find(graph, indexRoot)) {\r
+            for(Statement stm : graph.getStatements(module, SR2.IsConnectedTo)) {\r
+                Resource connection = stm.getObject();\r
+                Resource ref = graph.getPossibleObject(connection, SR.Dependency_refersTo);\r
+                if(ref != null && ref.equals(reference)) {\r
+                    graph.deny(connection, SR.Dependency_refersTo);\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/BrowserSelection.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/BrowserSelection.java
new file mode 100644 (file)
index 0000000..cfd31c8
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser;\r
+\r
+import org.eclipse.core.runtime.IAdaptable;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
+\r
+public class BrowserSelection implements IAdaptable, ISelection {\r
+       private Resource resource;\r
+       private Object originalInput;\r
+       private Variable variable;\r
+\r
+       public BrowserSelection(Object originalInput, VariableNode<Variable> vn) {\r
+               this.originalInput = originalInput;\r
+               this.resource = vn.data;\r
+               Variable variable = vn.getVariable();\r
+               if(variable != null) {\r
+                       this.variable = variable;\r
+               }\r
+       }\r
+\r
+       @SuppressWarnings("rawtypes")\r
+       @Override\r
+       public Object getAdapter(Class adapter) {\r
+               if (adapter == Resource.class)\r
+                       return resource;\r
+               if (adapter == Variable.class)\r
+                       return variable;\r
+               if (NodeContext.class.equals(adapter))\r
+            return originalInput;\r
+               if (originalInput instanceof IAdaptable) {\r
+                       IAdaptable input = (IAdaptable)originalInput;\r
+                       return input.getAdapter(adapter);\r
+               }\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public boolean isEmpty() {\r
+               if(originalInput == null)\r
+                       return true;\r
+               return false;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynBrowser.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynBrowser.java
new file mode 100644 (file)
index 0000000..8cda472
--- /dev/null
@@ -0,0 +1,178 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser;\r
+\r
+import java.util.Arrays;\r
+import java.util.Collections;\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.GraphExplorer;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.platform.GraphExplorerView;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.ContextMenuInitializer;\r
+import org.simantics.browsing.ui.swt.DefaultSelectionDataResolver;\r
+import org.simantics.browsing.ui.swt.GraphExplorerFactory;\r
+import org.simantics.browsing.ui.swt.IContextMenuInitializer;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ResourceRead;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.SelectionHints;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
+import org.simantics.sysdyn.ui.properties.SysdynPropertyPage;\r
+import org.simantics.ui.selection.AnyResource;\r
+import org.simantics.ui.selection.AnyVariable;\r
+import org.simantics.ui.selection.WorkbenchSelectionContentType;\r
+import org.simantics.ui.workbench.IPropertyPage;\r
+import org.simantics.utils.datastructures.BinaryFunction;\r
+import org.simantics.utils.datastructures.hints.IHintContext;\r
+\r
+\r
+public class SysdynBrowser extends GraphExplorerView {\r
+    \r
+    private static final Set<String> browseContexts  = new HashSet<String>(Arrays.asList(\r
+            "http://www.simantics.org/Sysdyn-1.1/Browser",  \r
+            "http://www.semantum.fi/SimupediaWorkbench-1.0/OldBrowser",\r
+            "http://www.simantics.org/Image-1.1/Browser"));    \r
+\r
+    private BinaryFunction<Object[], GraphExplorer, Object[]> selectionTransformation = new BinaryFunction<Object[], GraphExplorer, Object[]>() {\r
+\r
+        \r
+        /*\r
+        private Key[] KEYS = new Key[] { SelectionHints.KEY_MAIN };\r
+        \r
+        @Override\r
+        public Object[] call(GraphExplorer explorer, Object[] objects) {\r
+            Object[] result = new Object[objects.length];\r
+            for (int i = 0; i < objects.length; i++) {\r
+                SelectionElement context = new SelectionElement(KEYS, objects[i]);\r
+                context.setHint(SelectionHints.KEY_MAIN, objects[i]);\r
+                result[i] = context;\r
+            }\r
+            return result;\r
+        }\r
+        */\r
+        \r
+        class SelectionElement extends AdaptableHintContext {\r
+\r
+            private Variable variable;\r
+            private Resource resource;\r
+            \r
+            public SelectionElement(Variable variable, Resource resource, Key... keys) {\r
+                super(keys);\r
+                this.variable = variable;\r
+                this.resource = resource;\r
+            }\r
+\r
+            @SuppressWarnings("unchecked")\r
+            @Override\r
+            public <T> T getContent(WorkbenchSelectionContentType<T> contentType) {\r
+                if(contentType instanceof AnyResource) return (T)resource;\r
+                else if(contentType instanceof AnyVariable) {\r
+                    AnyVariable type = (AnyVariable)contentType;\r
+                    try {\r
+                        \r
+                        if(variable != null) return (T)variable;\r
+                        \r
+                        if(resource == null) return null;\r
+                        \r
+                        return (T) type.processor.sync(new ResourceRead<Variable>(resource) {\r
+                            @Override\r
+                            public Variable perform(ReadGraph graph) throws DatabaseException {\r
+                                return Variables.getPossibleVariable(graph, resource);\r
+                            }\r
+                            \r
+                        });\r
+                    } catch (DatabaseException e) {\r
+                        Logger.defaultLogError(e);\r
+                    }\r
+                } \r
+                return null;\r
+            }                        \r
+\r
+        }\r
+\r
+               @Override\r
+               public Object[] call(GraphExplorer explorer, Object[] objects) {\r
+               Object[] result = new Object[objects.length];\r
+               for (int i = 0; i < objects.length; i++) {\r
+                       \r
+                       NodeContext ctx = (NodeContext)objects[i];        \r
+                   @SuppressWarnings("unchecked")\r
+                               VariableNode<Variable> vn = (VariableNode<Variable>) ctx.getAdapter(VariableNode.class);\r
+                   IHintContext context;\r
+                   if(vn != null && vn.getVariable() != null) {\r
+                       context = new SelectionElement(vn.getVariable(),vn.data, SelectionHints.KEY_MAIN, SelectionHints.KEY_SELECTION_PROPERTY);\r
+                       context.setHint(SelectionHints.KEY_MAIN, new BrowserSelection(objects[i], vn));\r
+                       context.setHint(SelectionHints.KEY_SELECTION_PROPERTY, vn.getVariable());\r
+                   } else {\r
+                       Object resource = ctx.getAdapter(Resource.class);\r
+                       context = new SelectionElement(null, resource == null ? null : (Resource)resource, SelectionHints.KEY_MAIN);\r
+                       context.setHint(SelectionHints.KEY_MAIN, objects[i]);\r
+                   }\r
+                   result[i] = context;\r
+               }\r
+               return result;\r
+               }\r
+       \r
+    };\r
+    \r
+    protected GraphExplorer createExplorerControl(Composite parent) {\r
+        return GraphExplorerFactory.getInstance()\r
+        .selectionDataResolver(new DefaultSelectionDataResolver())\r
+        .selectionTransformation(selectionTransformation)\r
+        .create(parent, getStyle());\r
+    }\r
+    \r
+    @Override\r
+    protected IContextMenuInitializer getContextMenuInitializer() {\r
+        return new ContextMenuInitializer("#SysdynBrowserPopup");\r
+    }\r
+    \r
+    @Override\r
+    protected Set<String> getBrowseContexts() {\r
+        return browseContexts;\r
+    }\r
+    \r
+    @Override\r
+    protected void createControls(Composite parent) {\r
+        // Make sure the resource manager of this plug-in is initialized\r
+        // properly before using it in this browser.\r
+        Activator.initializeResourceManager(parent.getDisplay());\r
+\r
+        super.createControls(parent);\r
+        //IToolBarManager toolBar = getViewSite().getActionBars().getToolBarManager();\r
+        //toolBar.add(new HomeAction());\r
+    }\r
+    \r
+    @SuppressWarnings("rawtypes")\r
+       @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if (adapter == IPropertyPage.class)\r
+            return new SysdynPropertyPage(getSite(), Collections.singleton(SysdynResource.URIs.Browser));\r
+        return super.getAdapter(adapter);\r
+    }\r
+    \r
+    public SysdynBrowser() {\r
+       hideComparatorSelector = true;\r
+       hideViewpointSelector = true;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynModelBrowser.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynModelBrowser.java
new file mode 100644 (file)
index 0000000..b2e0e0e
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser;\r
+\r
+import java.util.Arrays;\r
+import java.util.Collections;\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.simantics.structural.ui.modelBrowser.ModelBrowser2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.SysdynPropertyPage;\r
+import org.simantics.ui.workbench.IPropertyPage;\r
+\r
+/**\r
+ * Model browser for sysdyn models. Content configured in SysdynModelingViewpoint.pgraph\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynModelBrowser extends ModelBrowser2 {\r
+\r
+    final private Set<String> browseContexts  = new HashSet<String>(Arrays.asList(SysdynResource.URIs.ModelingBrowseContext, "http://www.simantics.org/Operating-1.1/Browser", "http://www.simantics.org/Image-1.1/Browser"));\r
+\r
+    @Override\r
+    protected IPropertyPage getPropertyPage() {\r
+        return new SysdynPropertyPage(getSite(), Collections.singleton(SysdynResource.URIs.ModelingBrowseContext));\r
+    }\r
+\r
+    @Override\r
+    protected Set<String> getBrowseContexts() {\r
+        return browseContexts;\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ActivateResultDatasetAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ActivateResultDatasetAction.java
new file mode 100644 (file)
index 0000000..8c7e6fb
--- /dev/null
@@ -0,0 +1,60 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.DoubleClickEvent;\r
+import org.simantics.ui.IDoubleClickAction;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+/**\r
+ * Activates a result dataset to be shown in charts and other result visualizations\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ActivateResultDatasetAction implements IDoubleClickAction {\r
+\r
+    @Override\r
+    public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {\r
+        final Resource result = ResourceAdaptionUtils.toSingleResource(e.getResource());\r
+        if (result == null)\r
+            return;\r
+\r
+        ReadGraph graph = e.getGraph();\r
+\r
+        if(graph.isInstanceOf(result, SysdynResource.getInstance(graph).Result)) {\r
+\r
+            graph.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    if(graph.isInstanceOf(result, sr.Result)) {\r
+                        if (graph.hasStatement(result, sr.Result_showResult)) {\r
+                            graph.denyStatement(result, sr.Result_showResult, result);\r
+                        } else {\r
+                            graph.claim(result, sr.Result_showResult, result);\r
+                        }\r
+                    }                \r
+                }\r
+            });\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ActivateResultSetDatasetAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ActivateResultSetDatasetAction.java
new file mode 100644 (file)
index 0000000..3ad688e
--- /dev/null
@@ -0,0 +1,75 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions;\r
+\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.DoubleClickEvent;\r
+import org.simantics.ui.IDoubleClickAction;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+/**\r
+ * Activates the result datasets of a result set to be shown in charts and other result visualizations\r
+ * \r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ActivateResultSetDatasetAction implements IDoubleClickAction {\r
+\r
+    @Override\r
+    public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {\r
+        final Resource resultSet = ResourceAdaptionUtils.toSingleResource(e.getResource());\r
+        if (resultSet == null)\r
+            return;\r
+\r
+        ReadGraph graph = e.getGraph();\r
+\r
+        if(graph.isInstanceOf(resultSet, SysdynResource.getInstance(graph).ResultSet)) {\r
+\r
+            graph.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    if(graph.isInstanceOf(resultSet, sr.ResultSet)) {\r
+                       // If there is at least one result which shown, clear them all.\r
+                       // If not one result is shown, show them all.\r
+                       boolean resultShown = false;\r
+                       Collection<Resource> results = graph.getObjects(resultSet, sr.Experiment_result); \r
+                       for (Resource result : results) {\r
+                               if (graph.hasStatement(result, sr.Result_showResult)) {\r
+                                       resultShown = true;\r
+                                       break;\r
+                               }\r
+                       }\r
+                       for (Resource result : results) {\r
+                               if (resultShown) { \r
+                                       graph.denyStatement(result, sr.Result_showResult, result);\r
+                            } else {\r
+                                graph.claim(result, sr.Result_showResult, result);\r
+                            }\r
+                       }\r
+                    }                \r
+                }\r
+            });\r
+            e.consume();\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenSheetAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenSheetAction.java
new file mode 100644 (file)
index 0000000..91e560e
--- /dev/null
@@ -0,0 +1,69 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions;\r
+\r
+import org.eclipse.ui.PartInitException;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.RVI;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.ui.DoubleClickEvent;\r
+import org.simantics.ui.IDoubleClickAction;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.ui.workbench.ResourceEditorInput2;\r
+import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
+\r
+/**\r
+ * Opens the selected spreadsheet in a spreadsheet editor \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class OpenSheetAction implements IDoubleClickAction {\r
+\r
+    @Override\r
+    public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {\r
+        Resource result = ResourceAdaptionUtils.toSingleResource(e.getResource());\r
+        if (result == null)\r
+            return;\r
+        \r
+        ReadGraph graph = e.getGraph();\r
+        SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);\r
+\r
+        final Resource sheet = result;\r
+\r
+        if(graph.isInstanceOf(sheet, SHEET.Spreadsheet)) {\r
+               \r
+            Variable variable = graph.adapt(sheet, Variable.class);\r
+            final Resource model = Variables.getModel(graph, variable);\r
+            final RVI rvi = variable.getRVI(graph);\r
+            \r
+            PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+\r
+                private static final String EDITOR_ID = "org.simantics.spreadsheet.ui.editor2";\r
+\r
+                @Override\r
+                public void run() {\r
+                    try {\r
+                        WorkbenchUtils.openEditor(EDITOR_ID, new ResourceEditorInput2(EDITOR_ID, sheet, model, rvi));\r
+                    } catch (PartInitException e) {\r
+                        e.printStackTrace();\r
+                    }\r
+                }\r
+            });\r
+\r
+        }\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/ChartDropAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/ChartDropAction.java
new file mode 100644 (file)
index 0000000..27c0272
--- /dev/null
@@ -0,0 +1,180 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.drop;\r
+\r
+import java.util.Iterator;\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.SingleObjectWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.DropActionFactory;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Action for droppin variables to charts\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartDropAction implements DropActionFactory {\r
+\r
+    @Override\r
+    public Runnable create(ReadGraph g, Object target, Object source) throws DatabaseException {\r
+\r
+        final Resource targetChart = AdaptionUtils.adaptToSingle(target, Resource.class);\r
+        if(targetChart == null || source == null || !(source instanceof IStructuredSelection))\r
+            return null;\r
+        \r
+        final IStructuredSelection selection = (IStructuredSelection) source;\r
+\r
+        return new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        SysdynResource sr = SysdynResource.getInstance(graph);\r
+                        Layer0 L0 = Layer0.getInstance(graph);\r
+                        JFreeChartResource JFREE = JFreeChartResource.getInstance(graph);\r
+\r
+                        Iterator<?> iterator = selection.iterator();\r
+                        \r
+                        // Run through all selections and add all IndependentVariables and Inputs to the target chart\r
+                        while(iterator.hasNext()) {\r
+\r
+                            Variable variable = AdaptionUtils.adaptToSingle(iterator.next(), Variable.class);\r
+                            if(variable == null)\r
+                                continue;\r
+\r
+                            Resource represents = (Resource)variable.getPropertyValue(graph, Variables.REPRESENTS);\r
+                            if(represents == null || \r
+                                    !(graph.isInstanceOf(represents, sr.IndependentVariable) || \r
+                                            graph.isInstanceOf(represents, sr.Input)))\r
+                                continue;\r
+\r
+                            Resource plot = graph.syncRequest(new PossibleObjectWithType(targetChart, L0.ConsistsOf, JFREE.Plot));\r
+                            if(plot != null) {\r
+                                if(graph.isInstanceOf(plot, JFREE.XYPlot)) {\r
+                                    dropToLineChart(graph, targetChart, variable);\r
+                                } else if(graph.isInstanceOf(plot, JFREE.CategoryPlot)) {\r
+                                    dropToBarChart(graph, targetChart, variable);\r
+                                } else if(graph.isInstanceOf(plot, JFREE.PiePlot)) {\r
+                                    dropToPieChart(graph, targetChart, variable);\r
+                                }\r
+                            }\r
+                        }\r
+\r
+                    }\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+\r
+    /**\r
+     * Drop variable to a pie chart\r
+     * @param graph ReadGraph\r
+     * @param pieChart Pie chart resource\r
+     * @param variable Dropped variable\r
+     * @throws DatabaseException\r
+     */\r
+    private void dropToPieChart(WriteGraph graph, Resource pieChart, Variable variable) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+        Resource plot = graph.syncRequest(new SingleObjectWithType(pieChart, l0.ConsistsOf, jfree.Plot));\r
+        if(plot == null)\r
+            return;\r
+\r
+        Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+\r
+        if(dataset == null)\r
+            return;\r
+\r
+        // Create the series and attach it to the dataset\r
+        String rvi = Variables.getRVI(graph, variable);\r
+        Resource series = ChartUtils.createSeries(graph, dataset, rvi);\r
+        graph.claimLiteral(series, jfree.Series_exploded, false); \r
+    }\r
+\r
+    /**\r
+     * Drop variable to a bar chart\r
+     * @param graph ReadGraph\r
+     * @param barChart Bar chart resource\r
+     * @param variable Dropped variable\r
+     * @throws DatabaseException\r
+     */\r
+    private void dropToBarChart(WriteGraph graph, Resource barChart, Variable variable) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+        Resource plot = graph.syncRequest(new SingleObjectWithType(barChart, l0.ConsistsOf, jfree.Plot));\r
+        if(plot == null)\r
+            return;\r
+\r
+        Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+\r
+        if(dataset == null)\r
+            return;\r
+\r
+        // Create the series and attach it to the dataset\r
+        String rvi = Variables.getRVI(graph, variable);\r
+        ChartUtils.createSeries(graph, dataset, rvi);\r
+    }\r
+\r
+    /**\r
+     * Drop variable to a line chart\r
+     * @param graph ReadGraph\r
+     * @param lineChart Line chart resource\r
+     * @param variable Dropped variable\r
+     * @throws DatabaseException\r
+     */\r
+    private void dropToLineChart(WriteGraph graph, Resource lineChart, Variable variable) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+        Resource plot = graph.syncRequest(new SingleObjectWithType(lineChart, l0.ConsistsOf, jfree.Plot));\r
+        if(plot == null)\r
+            return;\r
+\r
+        Resource rangeAxis = null;\r
+        Resource dataset = null;\r
+        Resource rangeAxisList = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
+        if(rangeAxisList == null ||  ListUtils.toList(graph, rangeAxisList).isEmpty()) {\r
+            // No range axis -> Create a new one\r
+            rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);\r
+            Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
+            dataset = ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);\r
+        } else {\r
+            rangeAxis = ListUtils.toList(graph, rangeAxisList).get(0);\r
+            dataset = graph.getPossibleObject(rangeAxis, jfree.Dataset_mapToRangeAxis_Inverse);\r
+        }\r
+\r
+        // Create the series and attach it to the dataset\r
+        String rvi = Variables.getRVI(graph, variable);\r
+        ChartUtils.createSeries(graph, dataset, rvi);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/FunctionDropAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/FunctionDropAction.java
new file mode 100644 (file)
index 0000000..354f25b
--- /dev/null
@@ -0,0 +1,83 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.drop;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.DropActionFactory;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Action for moving functions and function libraries in model browser \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FunctionDropAction implements DropActionFactory {\r
+\r
+    @Override\r
+    public Runnable create(ReadGraph g, Object target, Object source) throws DatabaseException {\r
+        Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);\r
+        Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);\r
+\r
+        if(t == null || s == null)\r
+            return null;\r
+\r
+        SysdynResource sr = SysdynResource.getInstance(g);\r
+        Layer0 L0 = Layer0.getInstance(g);\r
+\r
+        // If target is a function, find functions parent to be the drop target\r
+        if(g.isInstanceOf(t, sr.SysdynModelicaFunction))\r
+            t = g.getSingleObject(t, L0.PartOf);\r
+\r
+        final Resource library = t;\r
+        final Resource tobemoved = s;\r
+\r
+        // Libraries and model accept drops\r
+        if(!(g.isInstanceOf(library, sr.SysdynModelicaFunctionLibrary) || \r
+                g.isInstanceOf(library, sr.SysdynModel) ||\r
+                g.isInstanceOf(library, sr.SharedFunctionOntology)))\r
+            return null;\r
+\r
+        // Functions and function libraries can be dropped\r
+        if(!(g.isInstanceOf(tobemoved, sr.SysdynModelicaFunction) || \r
+                g.isInstanceOf(tobemoved, sr.SysdynModelicaFunctionLibrary)))\r
+            return null;\r
+\r
+\r
+        return new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 L0 = Layer0.getInstance(graph);\r
+                        Resource oldLib = graph.getSingleObject(tobemoved, L0.PartOf);\r
+\r
+                        // Remove dragged entity from its parent and add it to the new parent\r
+                        graph.claim(tobemoved, L0.PartOf, library);\r
+                        graph.deny(tobemoved, L0.PartOf, oldLib);\r
+                    }\r
+\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewBarChartAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewBarChartAction.java
new file mode 100644 (file)
index 0000000..2e16bce
--- /dev/null
@@ -0,0 +1,111 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import java.util.Collections;\r
+import java.util.UUID;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new bar chart to a model\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewBarChartAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource model = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                        G2DResource g2d = G2DResource.getInstance(graph);\r
+\r
+                        // Chart\r
+                        Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,\r
+                                l0.HasName, "BarChart" + UUID.randomUUID().toString(),\r
+                                l0.HasLabel, NameUtils.findFreshLabel(graph, "Bar Chart", model),\r
+                                l0.PartOf, model,\r
+                                jfree.Chart_visibleBorder, true,\r
+                                jfree.Chart_borderWidth, 3,\r
+                                jfree.Chart_visibleLegend, false\r
+                                );\r
+                        \r
+                        // Border color\r
+                        graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
+\r
+                        // Title\r
+                        GraphUtils.create2(graph, jfree.TextTitle,\r
+                                l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
+                                l0.HasLabel, "Bar Chart Title",\r
+                                jfree.Title_position, jfree.Top,\r
+                                l0.PartOf, jfreechart);\r
+                        \r
+                        // X-axis\r
+                        Resource domainAxis = GraphUtils.create2(graph, jfree.CategoryAxis,\r
+                                l0.HasName, "CategoryAxis" + UUID.randomUUID().toString());\r
+                        \r
+                        // Y-axis\r
+                        Resource rangeAxis = GraphUtils.create2(graph, jfree.NumberAxis,\r
+                                l0.HasName, "NumberAxis" + UUID.randomUUID().toString());\r
+\r
+                        // Renderer\r
+                        Resource renderer = GraphUtils.create2(graph, jfree.BarRenderer);\r
+                        \r
+                        // Dataset \r
+                        Resource dataset = GraphUtils.create2(graph, jfree.CategoryDataset,\r
+                                l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),\r
+                                jfree.Dataset_mapToDomainAxis, domainAxis,\r
+                                jfree.Dataset_mapToRangeAxis, rangeAxis,\r
+                                jfree.Dataset_seriesList, ListUtils.create(graph, Collections.<Resource>emptyList()),\r
+                                jfree.Dataset_renderer, renderer);\r
+\r
+                        // Plot\r
+                        GraphUtils.create2(graph, jfree.CategoryPlot,\r
+                                l0.HasName, "Category plot" + UUID.randomUUID().toString(),\r
+                                l0.PartOf, jfreechart,\r
+                                jfree.Plot_domainAxis, domainAxis,\r
+                                jfree.Plot_rangeAxis, rangeAxis,\r
+                                jfree.Plot_rangeAxisList, ListUtils.create(graph, Collections.singletonList(rangeAxis)),\r
+                                l0.ConsistsOf, dataset,\r
+                                l0.ConsistsOf, domainAxis,\r
+                                l0.ConsistsOf, rangeAxis);\r
+                    }\r
+\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewEnumerationAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewEnumerationAction.java
new file mode 100644 (file)
index 0000000..ffc74ba
--- /dev/null
@@ -0,0 +1,88 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import java.util.Collections;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new enumeration to a model or module\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewEnumerationAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource resource = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+\r
+\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph g) throws DatabaseException {\r
+                        SysdynResource sr = SysdynResource.getInstance(g);\r
+                        Layer0 l0 = Layer0.getInstance(g);\r
+\r
+                        // Find the configuration from...\r
+                        Resource configuration = null;\r
+                        if(g.isInstanceOf(resource, sr.Configuration)) {\r
+                            configuration = resource;\r
+                        } else if(g.isInheritedFrom(resource, sr.ModuleSymbol)) {\r
+                            // Module symbol\r
+                            Resource module = g.getPossibleObject(resource,ModelingResources.getInstance(g).SymbolToComponentType);\r
+                            configuration = g.getPossibleObject(module, StructuralResource2.getInstance(g).IsDefinedBy);\r
+                        } else {\r
+                            // Module instance\r
+                            Resource instanceOf = g.getSingleObject(resource, l0.InstanceOf);\r
+                            if(g.isInheritedFrom(instanceOf, sr.Module)) {\r
+                                configuration = g.getPossibleObject(instanceOf, StructuralResource2.getInstance(g).IsDefinedBy);\r
+                            } else {\r
+                                return;\r
+                            }\r
+                        }\r
+\r
+                        // Find unique name\r
+                        String name = NameUtils.findFreshName(g, "Enum", configuration, l0.ConsistsOf, "%s%d");\r
+                        \r
+                        // Create enumeration\r
+                        GraphUtils.create2(g, \r
+                                sr.Enumeration,\r
+                                l0.HasName, name,\r
+                                sr.Enumeration_enumerationIndexList, ListUtils.create(g, Collections.<Resource>emptyList()),\r
+                                l0.PartOf, configuration);\r
+                    }\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewExperimentAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewExperimentAction.java
new file mode 100644 (file)
index 0000000..05f7914
--- /dev/null
@@ -0,0 +1,89 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new basic experiment\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewExperimentAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource model = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+\r
+\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        String name = NameUtils.findFreshName(graph, getNameSuggestion(), model, l0.ConsistsOf, "%s%d");\r
+\r
+                        Resource experiment = GraphUtils.create2(graph, getExperimentType(graph),\r
+                                l0.HasName, name,\r
+                                l0.HasLabel, name,\r
+                                l0.PartOf, model);\r
+                        \r
+                        configureExperiment(graph, experiment);\r
+                    }\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+    /**\r
+     * Override to do experiment-specific alterations\r
+     */\r
+    protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
+        \r
+    }\r
+    \r
+    /**\r
+     * Get the type of this experiment.\r
+     * \r
+     * @param g ReadGraph\r
+     * @return The type resource of this experiment\r
+     */\r
+    protected Resource getExperimentType(ReadGraph g) {\r
+        return SysdynResource.getInstance(g).BasicExperiment;\r
+    }\r
+    \r
+    /**\r
+     * Returns the suggested name for this experiment.\r
+     * If the name has already been taken, appropriate prefix needs to be added. \r
+     *  \r
+     * @return Suggested name for this experiment. \r
+     */\r
+    protected String getNameSuggestion() {\r
+        return "Experiment";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionAction.java
new file mode 100644 (file)
index 0000000..a76b5c1
--- /dev/null
@@ -0,0 +1,72 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new modelica function to a model, function library or shared function library.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewFunctionAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource resource = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph g) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(g);\r
+                        SysdynResource sr = SysdynResource.getInstance(g);\r
+\r
+                        Resource library = null;\r
+                        if(g.isInstanceOf(resource, sr.SysdynModel) || g.isInstanceOf(resource, l0.Library))\r
+                            library = resource;\r
+                        else if (g.isInstanceOf(resource, sr.SysdynModelicaFunction))\r
+                            library = g.getPossibleObject(resource, l0.PartOf);\r
+\r
+                        if(library == null)\r
+                            return;\r
+\r
+\r
+                        String name = NameUtils.findFreshName(g, "Function", library, l0.ConsistsOf, "%s%d");\r
+\r
+                        GraphUtils.create2(g, sr.SysdynModelicaFunction,\r
+                                l0.HasName, name,\r
+                                l0.HasDescription, "",\r
+                                sr.SysdynModelicaFunction_modelicaFunctionCode, "",\r
+                                l0.PartOf, library);\r
+                    }\r
+                });\r
+\r
+            }\r
+        };\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionLibraryAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionLibraryAction.java
new file mode 100644 (file)
index 0000000..031e37e
--- /dev/null
@@ -0,0 +1,100 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new function library\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewFunctionLibraryAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource resource = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+                createLibrary(resource, false);\r
+            }\r
+        };\r
+    }\r
+    \r
+    /**\r
+     * Create a new Library to the selected root or to SharedOntologies\r
+     * \r
+     * @param libraryLocation Resource of the model or other \r
+     * library where the new library will be added.\r
+     * @param shared is the library a shared library\r
+     */\r
+    protected static void createLibrary(final Resource libraryLocation, final boolean shared) {\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(g);\r
+                SysdynResource sr = SysdynResource.getInstance(g);\r
+\r
+                // Libraries can be created to model, function library and shared function library\r
+                if(!(g.isInstanceOf(libraryLocation, sr.SysdynModel) ||\r
+                        g.isInstanceOf(libraryLocation, sr.SysdynModelicaFunctionLibrary) ||\r
+                                g.isInstanceOf(libraryLocation, sr.SharedFunctionOntology)))\r
+                    return;\r
+\r
+                Resource root = libraryLocation;\r
+\r
+                String name = "FunctionLibrary";\r
+                Resource libraryType = sr.SysdynModelicaFunctionLibrary;\r
+                \r
+                if(shared) {\r
+                    \r
+                    try {\r
+                        root = g.getResource("http://SharedOntologies");\r
+                    } catch (ResourceNotFoundException e) {\r
+                        root = g.getResource("http:/");\r
+                        root = GraphUtils.create2(g, l0.Library, \r
+                                l0.HasName, "SharedOntologies",\r
+                                l0.PartOf, root);\r
+                    }\r
+                    \r
+                    name = "Shared" + name;\r
+                    libraryType = sr.SharedFunctionOntology;\r
+                }\r
+\r
+                name = NameUtils.findFreshName(g, name, root, l0.ConsistsOf, "%s%d");\r
+                \r
+                Resource functionLibrary = GraphUtils.create2(g, libraryType,\r
+                        l0.HasName, name,\r
+                        l0.HasDescription, "",\r
+                        l0.PartOf, root);\r
+                \r
+                if(shared)\r
+                    g.claim(libraryLocation, l0.IsLinkedTo, functionLibrary);\r
+            }\r
+        });\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewHistoryDataAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewHistoryDataAction.java
new file mode 100644 (file)
index 0000000..43f0ffa
--- /dev/null
@@ -0,0 +1,69 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import java.util.UUID;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Create a new history data\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewHistoryDataAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource experiment = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        SysdynResource sr = SysdynResource.getInstance(graph);\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        if(!graph.isInstanceOf(experiment, sr.Experiment))\r
+                            return; // Not called from an experiment\r
+\r
+                        Resource model = graph.getPossibleObject(experiment, l0.PartOf);\r
+                        // Create the history dataset\r
+                        GraphUtils.create2(graph, \r
+                                sr.HistoryDataset,\r
+                                l0.HasName, "HistoryDataset" + UUID.randomUUID().toString(),\r
+                                l0.HasLabel, NameUtils.findFreshLabel(graph, "History Dataset", experiment),\r
+                                sr.Experiment_result_Inverse, experiment, \r
+                                sr.HistoryDataset_columns, Boolean.TRUE,\r
+                                l0.PartOf, model);\r
+                    }\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewLineChartAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewLineChartAction.java
new file mode 100644 (file)
index 0000000..b21e7fc
--- /dev/null
@@ -0,0 +1,110 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.UUID;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new line chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewLineChartAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource model = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                        G2DResource g2d = G2DResource.getInstance(graph);\r
+\r
+                        // Chart\r
+                        Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,\r
+                                l0.HasName, "Chart" + UUID.randomUUID().toString(),\r
+                                l0.HasLabel, NameUtils.findFreshLabel(graph, "Chart", model),\r
+                                l0.PartOf, model,\r
+                                jfree.Chart_visibleBorder, true,\r
+                                jfree.Chart_borderWidth, 3);\r
+                        graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
+\r
+                        // Title\r
+                        GraphUtils.create2(graph, jfree.TextTitle,\r
+                                l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
+                                l0.HasLabel, "Chart Title",\r
+                                jfree.Title_position, jfree.Top,\r
+                                l0.PartOf, jfreechart);\r
+\r
+                        // X-axis\r
+                        Resource domainAxis = GraphUtils.create2(graph, jfree.NumberAxis,\r
+                                l0.HasName, "NumberAxis" + UUID.randomUUID().toString());\r
+                        \r
+                        // Y-axis\r
+                        Resource rangeAxis = GraphUtils.create2(graph, jfree.NumberAxis,\r
+                                l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
+                                l0.HasLabel, "Y-axis");\r
+                        \r
+                        // Renderer\r
+                        Resource renderer = GraphUtils.create2(graph, jfree.XYLineRenderer);\r
+\r
+                        // Dataset\r
+                        Resource dataset = GraphUtils.create2(graph, jfree.XYDataset,\r
+                                l0.HasName, "XYDataset" + UUID.randomUUID().toString(),\r
+                                jfree.Dataset_mapToDomainAxis, domainAxis,\r
+                                jfree.Dataset_mapToRangeAxis, rangeAxis,\r
+                                jfree.Dataset_seriesList, ListUtils.create(graph, new ArrayList<Resource>()),\r
+                                jfree.Dataset_renderer, renderer);\r
+\r
+                        // Plot\r
+                        GraphUtils.create2(graph, jfree.XYPlot,\r
+                                l0.HasName, "XYPlot" + UUID.randomUUID().toString(),\r
+                                l0.PartOf, jfreechart,\r
+                                jfree.Plot_domainAxis, domainAxis,\r
+                                jfree.Plot_rangeAxis, rangeAxis,\r
+                                jfree.Plot_rangeAxisList, ListUtils.create(graph, Collections.singletonList(rangeAxis)),\r
+                                l0.ConsistsOf, dataset,\r
+                                l0.ConsistsOf, domainAxis,\r
+                                l0.ConsistsOf, rangeAxis);\r
+                    }\r
+\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewModuleTypeAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewModuleTypeAction.java
new file mode 100644 (file)
index 0000000..1d503d0
--- /dev/null
@@ -0,0 +1,144 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.db.layer0.adapter.Template;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+\r
+/**\r
+ * Creates a new module type\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewModuleTypeAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource model = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph g) throws DatabaseException {\r
+                        SysdynResource sr = SysdynResource.getInstance(g);\r
+                        Layer0 l0 = Layer0.getInstance(g);\r
+                        Layer0X L0X = Layer0X.getInstance(g);\r
+                        ModelingResources mr = ModelingResources.getInstance(g);\r
+                        StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
+\r
+                        String name = NameUtils.findFreshName(g, "ModuleType", model, l0.ConsistsOf, "%s%d");\r
+\r
+                        Resource moduleType = g.newResource();\r
+                        g.claimLiteral(moduleType, l0.HasName, name);\r
+                        g.claim(moduleType, l0.Inherits, sr.Module);\r
+                        g.claim(moduleType, l0.PartOf, model);\r
+\r
+\r
+\r
+                        Resource configuration = GraphUtils.create2(g, \r
+                                sr.Configuration,\r
+                                l0.HasName, name + "Configuration",\r
+                                l0.PartOf, moduleType);\r
+\r
+                        g.claim(moduleType, sr2.IsDefinedBy , configuration);\r
+\r
+                        Resource diagram = g.newResource();\r
+                        g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,\r
+                                ArrayMap\r
+                                .keys("", "diagram", "name")\r
+                                .values(configuration, diagram, "Diagrammi")\r
+                                );\r
+\r
+\r
+                        // Remove default mapping and add sysdyn mapping\r
+                        for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {\r
+                            if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {\r
+                                g.deny(diagram, L0X.HasTrigger, trigger);\r
+                            }\r
+                        }\r
+\r
+                        Resource mapping = g.newResource();\r
+                        g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);\r
+                        g.claim(diagram, L0X.HasTrigger, mapping);\r
+\r
+                        Resource moduleSymbol = g.newResource();\r
+                        g.claimLiteral(moduleSymbol, l0.HasName, name + " Symbol");\r
+                        g.claimLiteral(moduleSymbol, l0.HasLabel, name + " Symbol");\r
+                        g.claim(moduleSymbol, l0.Inherits, sr.ModuleSymbol);\r
+                        g.claim(moduleSymbol, mr.SymbolToComponentType, moduleType);\r
+                        g.claim(moduleSymbol, l0.PartOf, moduleType);\r
+\r
+                        Resource terminal = g.newResource();\r
+                        g.claim(terminal, l0.InstanceOf, sr.SysdynTerminal);\r
+                        Resource relation = createTerminalRelation(g, moduleSymbol, sr.IsHeadOfTerminal, sr.Variable_isHeadOf);\r
+                        DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal, relation);               \r
+\r
+                        Resource terminal2 = g.newResource();\r
+                        g.claim(terminal2, l0.InstanceOf, sr.SysdynTerminal);\r
+                        relation = createTerminalRelation(g, moduleSymbol, sr.IsTailOfTerminal, sr.Variable_isTailOf);\r
+                        DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal2, relation);\r
+\r
+                        g.claim(moduleSymbol, sr2.IsDefinedBy, OrderedSetUtils.create(g, sr2.Composite, terminal, terminal2));\r
+\r
+\r
+\r
+                    }\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+    public static Resource createTerminalRelation(WriteGraph graph, Resource symbol, Resource connectionRelation, Resource configurationRelation) throws DatabaseException {\r
+        StructuralResource2 STR = StructuralResource2.getInstance(graph);\r
+        ModelingResources MOD = ModelingResources.getInstance(graph);\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+\r
+\r
+        Resource terminalRelation = null;\r
+        terminalRelation = GraphUtils.create(graph,\r
+                MOD.DiagramConnectionRelationToConnectionRelation, configurationRelation,\r
+                L0.PartOf, symbol,\r
+                L0.HasName, NameUtils.getSafeName(graph, connectionRelation)\r
+                );\r
+\r
+        graph.claim(terminalRelation, L0.SubrelationOf, null, connectionRelation);\r
+        Resource inverse = GraphUtils.create(graph,\r
+                L0.PartOf, terminalRelation, \r
+                L0.HasName, "Inverse");\r
+\r
+        graph.claim(inverse, L0.SubrelationOf, null, STR.Connects);\r
+        graph.claim(terminalRelation, L0.InverseOf, inverse);\r
+\r
+        return terminalRelation;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewPieChartAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewPieChartAction.java
new file mode 100644 (file)
index 0000000..1ae83a6
--- /dev/null
@@ -0,0 +1,90 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import java.util.Collections;\r
+import java.util.UUID;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new pie chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewPieChartAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource model = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                        G2DResource g2d = G2DResource.getInstance(graph);\r
+\r
+                        // Chart\r
+                        Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,\r
+                                l0.HasName, "PieChart" + UUID.randomUUID().toString(),\r
+                                l0.HasLabel, NameUtils.findFreshLabel(graph, "Pie Chart", model),\r
+                                l0.PartOf, model,\r
+                                jfree.Chart_visibleBorder, true,\r
+                                jfree.Chart_borderWidth, 3);\r
+                        graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
+\r
+                        // Title\r
+                        GraphUtils.create2(graph, jfree.TextTitle,\r
+                                l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
+                                l0.HasLabel, "Pie Chart Title",\r
+                                jfree.Title_position, jfree.Top,\r
+                                l0.PartOf, jfreechart);\r
+                        \r
+                        // Dataset\r
+                        Resource dataset = GraphUtils.create2(graph, jfree.PieDataset,\r
+                                l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),\r
+                                jfree.Dataset_seriesList, ListUtils.create(graph, Collections.<Resource>emptyList())\r
+                                );\r
+\r
+                        // Plot\r
+                        GraphUtils.create2(graph, jfree.PiePlot,\r
+                                l0.HasName, "PiePlot" + UUID.randomUUID().toString(),\r
+                                l0.PartOf, jfreechart,\r
+                                l0.ConsistsOf, dataset\r
+                                );\r
+                    }\r
+\r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSharedFunctionLibraryAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSharedFunctionLibraryAction.java
new file mode 100644 (file)
index 0000000..98efd11
--- /dev/null
@@ -0,0 +1,38 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Creates a new shared function library\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewSharedFunctionLibraryAction extends NewFunctionLibraryAction {\r
+    \r
+    \r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource resource = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+                createLibrary(resource, true);\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSheetAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSheetAction.java
new file mode 100644 (file)
index 0000000..e579df6
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.ActionFactory;\r
+import org.simantics.sysdyn.utils.SheetUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new spreadsheet to a book\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewSheetAction implements ActionFactory{\r
+\r
+    @Override\r
+    public Runnable create(Object target) {\r
+        if(!(target instanceof Resource))\r
+            return null;\r
+        final Resource book = (Resource)target;\r
+\r
+        return new Runnable() {\r
+            @Override\r
+            public void run() {\r
+\r
+                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        SheetUtils.createSheet(graph, book, null, new String[] {}, new int[] {50});\r
+                    }\r
+                    \r
+                });\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSimulationPlaybackExperimentAction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSimulationPlaybackExperimentAction.java
new file mode 100644 (file)
index 0000000..b0363b9
--- /dev/null
@@ -0,0 +1,55 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.newActions;\r
+\r
+import java.awt.Color;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Creates a new simulation playback experiment\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewSimulationPlaybackExperimentAction extends NewExperimentAction {\r
+    \r
+    protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
+        G2DResource g2d = G2DResource.getInstance(graph);\r
+        Resource defaultGradient = GraphUtils.create2(graph, g2d.ColorGradient);\r
+        graph.claim(experiment, g2d.HasColorGradient, defaultGradient);\r
+\r
+        Resource placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
+                g2d.HasGradientPosition, 0.0);\r
+        graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(0, 62, 133).getColorComponents(new float[4]));\r
+        graph.claim(defaultGradient, g2d.HasColorPlacement, placement);\r
+        \r
+        placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
+                g2d.HasGradientPosition, 1.0);\r
+        graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(255, 230, 0).getColorComponents(new float[4]));\r
+        graph.claim(defaultGradient, g2d.HasColorPlacement, placement);\r
+    }\r
+\r
+    protected Resource getExperimentType(ReadGraph g) {\r
+        return SysdynResource.getInstance(g).PlaybackExperiment;\r
+    }\r
+\r
+    protected String getNameSuggestion() {\r
+        return "Playback Experiment";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleTypeRemover.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleTypeRemover.java
new file mode 100644 (file)
index 0000000..e21bd81
--- /dev/null
@@ -0,0 +1,47 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.actions.remove;\r
+\r
+import java.util.Map;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.Remover;\r
+import org.simantics.modeling.ui.modelBrowser.handlers.DeleteNodeHandler;\r
+\r
+/**\r
+ * Remover for module type nodes. Not functioning - {@link DeleteNodeHandler} prevents deleting other than entityNodes\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ModuleTypeRemover implements Remover {\r
+\r
+    private Resource resource;\r
+    \r
+    public ModuleTypeRemover(ReadGraph graph, Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+    \r
+    @Override\r
+    public String canRemove(ReadGraph graph, Map<Object, Object> aux) throws DatabaseException {\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void remove(WriteGraph graph) throws DatabaseException {\r
+        System.out.println("Delete resource " + resource);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/ModuleContentChildRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/ModuleContentChildRule.java
new file mode 100644 (file)
index 0000000..df545e7
--- /dev/null
@@ -0,0 +1,75 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.childrules;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+\r
+/**\r
+ * Child rule for displaying children of module types in Modules folder\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ModuleContentChildRule implements ChildRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {\r
+        ArrayList<Resource> children = new ArrayList<Resource>();\r
+        \r
+        if(!(parent instanceof Resource)) {\r
+            return children;\r
+        }\r
+        \r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        StructuralResource2 str = StructuralResource2.getInstance(graph);\r
+\r
+        Resource symbol = (Resource)parent;\r
+        \r
+        // Find module component\r
+        Resource component = graph.getPossibleObject(symbol,ModelingResources.getInstance(graph).SymbolToComponentType);\r
+        \r
+        if(component == null)\r
+            return children;\r
+        \r
+        // Find component configuration\r
+        Resource configuration = graph.getSingleObject(component, str.IsDefinedBy);\r
+        \r
+        if(configuration == null)\r
+            return children;\r
+        \r
+        // Add all components \r
+        children.addAll(graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, str.Component)));\r
+        \r
+        return children;\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getParents(ReadGraph graph, Object child)\r
+            throws DatabaseException {\r
+        return new ArrayList<Resource>();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/ModuleTypeChildRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/ModuleTypeChildRule.java
new file mode 100644 (file)
index 0000000..111d12c
--- /dev/null
@@ -0,0 +1,73 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.childrules;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Child rule for finding module types defined in a model\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ModuleTypeChildRule implements ChildRule {\r
+\r
+       @Override\r
+       public boolean isCompatible(Class<?> contentType) {\r
+               return contentType.equals(Resource.class);\r
+       }\r
+\r
+       @Override\r
+       public Collection<?> getChildren(ReadGraph graph, Object parent)\r
+                       throws DatabaseException {\r
+\r
+       ArrayList<Resource> children = new ArrayList<Resource>();\r
+       \r
+               if(!(parent instanceof Resource)) {\r
+                       return children;\r
+               }\r
+               \r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               StructuralResource2 st = StructuralResource2.getInstance(graph);\r
+\r
+               Resource model = (Resource)parent;\r
+               if(!graph.isInstanceOf(model, SysdynResource.getInstance(graph).SysdynModel))\r
+                   return children;\r
+               \r
+               // Find all component types that are inherited from SYSDYN.Module\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(model, l0.ConsistsOf, st.ComponentType))) {\r
+               if(graph.isInheritedFrom(r, SysdynResource.getInstance(graph).Module)) {\r
+                       Resource symbol = graph.getPossibleObject(r,ModelingResources.getInstance(graph).ComponentTypeToSymbol);\r
+                       children.add(symbol);\r
+               }\r
+        }\r
+               \r
+               return children;\r
+       }\r
+\r
+       @Override\r
+       public Collection<?> getParents(ReadGraph graph, Object child)\r
+                       throws DatabaseException {\r
+               return new ArrayList<Resource>();\r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/VariableChildRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/childrules/VariableChildRule.java
new file mode 100644 (file)
index 0000000..270ad22
--- /dev/null
@@ -0,0 +1,86 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.childrules;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Child rule for building model configuration out of Variable nodes\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class VariableChildRule implements ChildRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Variable.class) || contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {\r
+        \r
+        ArrayList<Variable> result = new ArrayList<Variable>();\r
+        \r
+        if (parent == null) {\r
+            return result;\r
+        }\r
+        \r
+        Variable variable = null;\r
+        \r
+        if(parent instanceof Variable) {\r
+            variable = (Variable) parent;\r
+        } else if(parent instanceof Resource) {\r
+            variable = Variables.getVariable(graph, (Resource)parent);\r
+        }\r
+        \r
+        if(variable == null)\r
+            return result;\r
+        \r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+        ArrayList<Variable> variables = new ArrayList<Variable>();\r
+\r
+        for(Variable child : variable.getChildren(graph)) {\r
+            Resource represents = (Resource)child.getPropertyValue(graph, Variables.REPRESENTS);\r
+            if(graph.isInstanceOf(represents, sr.IndependentVariable)) {\r
+                variables.add(child);\r
+            } else if (graph.isInstanceOf(represents, sr.Input)) {\r
+                variables.add(child);\r
+            } else if (graph.isInstanceOf(represents, sr.Module)) {\r
+                variables.add(child);\r
+            } else if (graph.isInstanceOf(represents, sr.Enumeration)) {\r
+                variables.add(child);\r
+            }\r
+        }\r
+        \r
+        for (Variable v : variables) {\r
+            result.add(v);\r
+        }\r
+        \r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getParents(ReadGraph graph, Object child) throws DatabaseException {\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AbstractNodeImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AbstractNodeImager.java
new file mode 100644 (file)
index 0000000..2106ce5
--- /dev/null
@@ -0,0 +1,241 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.Collection;\r
+import java.util.HashSet;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.viewers.IDecoration;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.issues.Severity;\r
+import org.simantics.issues.common.MaxIssueSeverityRecursive;\r
+import org.simantics.issues.ontology.IssueResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.browser.nodes.BookNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.InitialCondition;\r
+import org.simantics.sysdyn.ui.browser.nodes.InitialConditionsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.InputNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModulesNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SCLModule;\r
+import org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.SheetNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
+import org.simantics.utils.ui.gfx.DecorationOverlayIcon;\r
+\r
+/**\r
+ * Imager for nodes in old sysdyn model browser\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class AbstractNodeImager extends ImagerContributor<AbstractNode<Resource>> {\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, AbstractNode<Resource> node) throws DatabaseException {\r
+\r
+        String image = null;\r
+        if (node instanceof SharedFunctionsFolder)\r
+            image = "icons/folder_link.png";\r
+        else if (node instanceof ExperimentsFolder || \r
+                node instanceof ModulesNode || \r
+                node instanceof FunctionsFolder ||\r
+                node instanceof FunctionLibraryNode ||\r
+                node instanceof SCLModulesFolder ||\r
+                node instanceof InitialConditionsFolder ||\r
+                node instanceof SharedFunctionLibraryNode)\r
+            image = "icons/folder.png";\r
+        else if (node instanceof ModuleTypeNode || node instanceof ModuleNode || node instanceof ConfigurationNode)\r
+            image = "icons/bricks.png";\r
+        else if (node instanceof SCLModule)\r
+            image = "icons/box.png";\r
+        else if (node instanceof InitialCondition)\r
+            image = "icons/table.png";\r
+        else if (node instanceof ExperimentNode) {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            if(graph.isInstanceOf(node.data, sr.PlaybackExperiment))\r
+                image = "icons/timeline_marker.png";\r
+            else if(graph.isInstanceOf(node.data, sr.GameExperiment))\r
+                image = "icons/time_go.png";\r
+            else if(graph.isInstanceOf(node.data, sr.SensitivityAnalysisExperiment))\r
+                image = "icons/time_rainbow.png";\r
+            else\r
+                image = "icons/time.png";\r
+        } else if (node instanceof InputNode)\r
+            image = "icons/brick_link.png";\r
+        else if (node instanceof ModelNode)\r
+            image = "icons/chart_organisation.png";\r
+        else if (node instanceof FunctionNode) {\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            if (graph.hasStatement(node.data, l0.PartOf, sr.Built$in_Functions)) {\r
+                // Sysdyn functions\r
+                image =  "icons/sysdynFunction.png";\r
+            } else if (graph.hasStatement(node.data, l0.PartOf, sr.Built$in_Functions_Modelica_Functions)) {\r
+                image =  "icons/modelicaFunction.png";\r
+            } else if (graph.hasStatement(node.data, l0.PartOf, sr.Built$in_Functions_Modelica_Array_Functions)) {\r
+                image =  "icons/modelicaArrayFunction.png";\r
+            } else if (graph.hasStatement(node.data, l0.PartOf, sr.Built$in_Functions_Vensim_Functions)) {\r
+                image =  "icons/vensimFunction.png";\r
+            } else {\r
+                Resource r = graph.getPossibleObject(node.data, l0.PartOf);\r
+                if (r != null) {\r
+                    boolean shared = false;\r
+                    do {\r
+                        shared = graph.isInstanceOf(r, sr.SharedFunctionOntology);\r
+                        r = graph.getPossibleObject(r, l0.PartOf);\r
+                    } while (!shared && (r != null));\r
+                    if (shared) {\r
+                        image =  "icons/functionLink.png";\r
+                    } else {\r
+                        image =  "icons/function.png";\r
+                    }\r
+                }\r
+            }\r
+        } else if (node instanceof VariableNode)\r
+            // Must be queried after FunctionNode\r
+            image =  "icons/brick.png";\r
+        else if (node instanceof BookNode)\r
+            image =  "icons/table_multiple.png";\r
+        else if (node instanceof SheetNode)\r
+            image =  "icons/table.png";\r
+\r
+        if (image != null) {\r
+\r
+            ImageDescriptor id = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource(image));\r
+\r
+            Severity maxSeverity = getMaxSeverity(graph, node);\r
+            \r
+            if (maxSeverity == null)\r
+                return id;\r
+            else\r
+                return getDecoration(id, maxSeverity);\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @param graph\r
+     * @param node\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    private Severity getMaxSeverity(ReadGraph graph, AbstractNode<Resource> node) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        IssueResource.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+        HashSet<Resource> issueTypes = new HashSet<Resource>();\r
+        issueTypes.add(SR.Variable);\r
+        issueTypes.add(SR.Configuration);\r
+        issueTypes.add(SR.Module);\r
+        \r
+        Resource data = node.data;\r
+        if(node instanceof ModuleTypeNode) {\r
+            Resource symbol = node.data;\r
+            Resource moduleType = graph.getPossibleObject(symbol, L0.PartOf);\r
+            data = graph.getPossibleObject(moduleType, StructuralResource2.getInstance(graph).IsDefinedBy);\r
+        } else if(node instanceof ModuleNode) {\r
+            Resource moduleType = graph.getPossibleObject(node.data, L0.InstanceOf);\r
+            data = graph.getPossibleObject(moduleType, StructuralResource2.getInstance(graph).IsDefinedBy);\r
+        } else if(node instanceof ModelNode) {\r
+            data = graph.getPossibleObject(node.data, SimulationResource.getInstance(graph).HasConfiguration);\r
+        }\r
+\r
+        Severity maxSeverity = getMaxSeverityStructural(graph, data, issueTypes, null);  \r
+        return maxSeverity;\r
+    }\r
+    \r
+    /**\r
+     * Recursive function for obtaining maximum severity of a configuration and its module\r
+     * children\r
+     * \r
+     * @param graph readGraph\r
+     * @param resource Resource from which issues are searched for. If the resource is configuraiton, issues are searched also from its module children.\r
+     * @param issueTypes Issue type resources\r
+     * @param severity Maximum current severity\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    private Severity getMaxSeverityStructural(ReadGraph graph, Resource resource, HashSet<Resource> issueTypes, Severity severity) throws DatabaseException {\r
+        if(resource == null)\r
+            return severity;\r
+        \r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        Resource data = resource;\r
+        Severity maxSeverity = graph.syncRequest(new MaxIssueSeverityRecursive(data, L0.ConsistsOf, issueTypes));\r
+\r
+        // Try structural\r
+        if(graph.isInstanceOf(data, SR.Configuration)) {\r
+            Collection<Resource> moduleChildren =  graph.syncRequest(new ModuleChildren(data));\r
+            for(Resource r : moduleChildren) {\r
+                Resource moduleType = graph.getPossibleObject(r, L0.InstanceOf);\r
+                Resource configuration = graph.getPossibleObject(moduleType, StructuralResource2.getInstance(graph).IsDefinedBy);\r
+                if(configuration != null)\r
+                    maxSeverity = getMaxSeverityStructural(graph, configuration, issueTypes, maxSeverity);\r
+            }\r
+        }\r
+\r
+        return Severity.moreSevere(maxSeverity, severity);\r
+    }\r
+\r
+    /**\r
+     * Request for obtaining all module children of a configuration\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class ModuleChildren implements Read<Collection<Resource>> {\r
+        \r
+        Resource configuration; \r
+        \r
+        public ModuleChildren(Resource configuration) {\r
+            this.configuration = configuration;\r
+        }\r
+\r
+        @Override\r
+        public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {\r
+            return graph.syncRequest(new ObjectsWithType(configuration, Layer0.getInstance(graph).ConsistsOf, SysdynResource.getInstance(graph).Module));\r
+        }\r
+    }\r
+\r
+    private ImageDescriptor getDecoration(ImageDescriptor original, Severity severity) {\r
+        ImageDescriptor img = Activator.getDefault().getImageRegistry().getDescriptor(severity.toString());\r
+        if (original == null || original.getImageData() == null) \r
+            return img;\r
+        else\r
+            return new DecorationOverlayIcon(original, img, IDecoration.BOTTOM_LEFT);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AbstractNodeLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AbstractNodeLabeler.java
new file mode 100644 (file)
index 0000000..6fd403f
--- /dev/null
@@ -0,0 +1,29 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public class AbstractNodeLabeler extends LabelerContributor<AbstractNode<Resource>> {\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, AbstractNode<Resource> node) throws DatabaseException {\r
+        if (!graph.hasStatement(node.data))\r
+            return "";\r
+        return graph.adapt(node.data, String.class);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution.java
new file mode 100644 (file)
index 0000000..19d9ce1
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.annotation.ontology.AnnotationResource;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.ISpecialFolder;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.AnnotationType;\r
+import org.simantics.sysdyn.ui.browser.nodes.AnnotationValue;\r
+\r
+public class AnnotationContribution  extends ViewpointContributor<AbstractNode<Resource>> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, AbstractNode<Resource> node) throws DatabaseException {\r
+       \r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        \r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        \r
+        if(node instanceof ISpecialFolder) return result;\r
+        \r
+       AnnotationResource ANNO = AnnotationResource.getInstance(graph);\r
+        if(graph.isInstanceOf(node.data, L0.Library)) {\r
+               for(Resource anno : graph.syncRequest(new ObjectsWithType(node.data, L0.ConsistsOf, ANNO.AnnotationType))) {\r
+                result.add(new AnnotationType(anno));\r
+               }\r
+        }\r
+       for(Resource anno : graph.syncRequest(new ObjectsWithType(node.data, L0.ConsistsOf, ANNO.Annotation))) {\r
+            result.add(new AnnotationValue(anno));\r
+       }\r
+        \r
+        return result;\r
+        \r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution2.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationContribution2.java
new file mode 100644 (file)
index 0000000..a29c1da
--- /dev/null
@@ -0,0 +1,55 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.annotation.ontology.AnnotationResource;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.AnnotationType;\r
+import org.simantics.sysdyn.ui.browser.nodes.AnnotationValue;\r
+\r
+public class AnnotationContribution2  extends ViewpointContributor<Resource> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, Resource res) throws DatabaseException {\r
+       \r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        \r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        \r
+       AnnotationResource ANNO = AnnotationResource.getInstance(graph);\r
+        if(graph.isInstanceOf(res, L0.Library)) {\r
+               for(Resource anno : graph.syncRequest(new ObjectsWithType(res, L0.ConsistsOf, ANNO.AnnotationType))) {\r
+                result.add(new AnnotationType(anno));\r
+               }\r
+        }\r
+       for(Resource anno : graph.syncRequest(new ObjectsWithType(res, L0.ConsistsOf, ANNO.Annotation))) {\r
+            result.add(new AnnotationValue(anno));\r
+       }\r
+        \r
+        return result;\r
+        \r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationTypeImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationTypeImager.java
new file mode 100644 (file)
index 0000000..660fd9d
--- /dev/null
@@ -0,0 +1,25 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.net.MalformedURLException;\r
+import java.net.URL;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.AnnotationType;\r
+\r
+public class AnnotationTypeImager extends ImagerContributor<AnnotationType> {\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, AnnotationType node) throws DatabaseException {\r
+       \r
+        try {\r
+               return ImageDescriptor.createFromURL(new URL("platform:/plugin/com.famfamfam.silk/icons/note.png"));\r
+        } catch (MalformedURLException e) {\r
+               e.printStackTrace();\r
+        }\r
+        return null;\r
+        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationTypeLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationTypeLabeler.java
new file mode 100644 (file)
index 0000000..96221a0
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.AnnotationType;\r
+\r
+public class AnnotationTypeLabeler extends LabelerContributor<AnnotationType>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, AnnotationType input) throws DatabaseException {\r
+       Layer0 L0 = Layer0.getInstance(graph);\r
+       Resource relation = graph.getSingleObject(input.data, L0.HasRange_Inverse);\r
+        return NameUtils.getSafeName(graph, relation);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationValueImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationValueImager.java
new file mode 100644 (file)
index 0000000..b6a88ab
--- /dev/null
@@ -0,0 +1,25 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.net.MalformedURLException;\r
+import java.net.URL;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.AnnotationValue;\r
+\r
+public class AnnotationValueImager extends ImagerContributor<AnnotationValue> {\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, AnnotationValue node) throws DatabaseException {\r
+       \r
+        try {\r
+               return ImageDescriptor.createFromURL(new URL("platform:/plugin/com.famfamfam.silk/icons/note.png"));\r
+        } catch (MalformedURLException e) {\r
+               e.printStackTrace();\r
+        }\r
+        return null;\r
+        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationValueLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/AnnotationValueLabeler.java
new file mode 100644 (file)
index 0000000..320b36b
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.AnnotationValue;\r
+\r
+public class AnnotationValueLabeler extends LabelerContributor<AnnotationValue>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, AnnotationValue input) throws DatabaseException {\r
+        return NameUtils.getSafeName(graph, input.data);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Book.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Book.java
new file mode 100644 (file)
index 0000000..8bd950f
--- /dev/null
@@ -0,0 +1,29 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.BookNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SheetNode;\r
+\r
+public class Book extends ViewpointContributor<BookNode> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, BookNode book) throws DatabaseException {\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(book.data, l0.ConsistsOf, SpreadsheetResource.getInstance(graph).Spreadsheet))) {\r
+            result.add(new SheetNode(r));\r
+        }\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/BookLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/BookLabeler.java
new file mode 100644 (file)
index 0000000..88d2850
--- /dev/null
@@ -0,0 +1,20 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.BookNode;\r
+\r
+public class BookLabeler  extends LabelerContributor<BookNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, BookNode input) throws DatabaseException {\r
+        return "SpreadSheets";\r
+    }\r
+    \r
+    @Override\r
+    public int getCategory(ReadGraph graph, BookNode input) throws DatabaseException {\r
+       return -1;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartImager.java
new file mode 100644 (file)
index 0000000..11bb85e
--- /dev/null
@@ -0,0 +1,47 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.browser.nodes.AbstractChartNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.BarChartNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.LineChartNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.PieChartNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SensitivityChartNode;\r
+\r
+/**\r
+ * Provides image for {@link LineChartNode} in model browser\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartImager extends ImagerContributor<AbstractChartNode<Resource>> {\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, AbstractChartNode<Resource> input) throws DatabaseException {\r
+        if(input instanceof SensitivityChartNode)\r
+            return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/rainbow.png"));\r
+        else if(input instanceof BarChartNode)\r
+            return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_bar.png"));\r
+        else if(input instanceof PieChartNode)\r
+            return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_pie.png"));\r
+        else\r
+            return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_line.png"));\r
+\r
+        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartLabeler.java
new file mode 100644 (file)
index 0000000..1301ab5
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.AbstractChartNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.LineChartNode;\r
+\r
+/**\r
+ * Provides label for {@link LineChartNode} in model browser\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartLabeler extends LabelerContributor<AbstractChartNode<Resource>> {\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, AbstractChartNode<Resource> chart) throws DatabaseException {\r
+        String name = graph.getPossibleRelatedValue(chart.data, Layer0.getInstance(graph).HasLabel);\r
+        return name == null ? "Chart (no label)" : name;\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Charts.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Charts.java
new file mode 100644 (file)
index 0000000..5abab1e
--- /dev/null
@@ -0,0 +1,67 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.BarChartNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.LineChartNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.PieChartNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SensitivityChartNode;\r
+\r
+/**\r
+ * Class for creating chart nodes for model browser\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class Charts extends ViewpointContributor<ChartsFolder> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, ChartsFolder folder) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        JFreeChartResource JFREE = JFreeChartResource.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        for(Resource chart : graph.syncRequest(\r
+                new ObjectsWithType(folder.data,\r
+                        L0.ConsistsOf, \r
+                        JFREE.Chart))) {\r
+            Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, L0.ConsistsOf, JFREE.Plot));\r
+            if(plot != null) {\r
+                if(graph.isInstanceOf(plot, SR.Charts_SensitivityPlot)) {\r
+                    result.add(new SensitivityChartNode(chart));\r
+                } else if(graph.isInstanceOf(plot, JFREE.XYPlot)) {\r
+                    result.add(new LineChartNode(chart));\r
+                } else if(graph.isInstanceOf(plot, JFREE.CategoryPlot)) {\r
+                    result.add(new BarChartNode(chart));\r
+                } else if(graph.isInstanceOf(plot, JFREE.PiePlot)) {\r
+                    result.add(new PieChartNode(chart));\r
+                }\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartsImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartsImager.java
new file mode 100644 (file)
index 0000000..e51b8e7
--- /dev/null
@@ -0,0 +1,33 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
+\r
+/**\r
+ * Provides image for {@link ChartsFolder} in model browser\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartsImager extends ImagerContributor<ChartsFolder> {\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, ChartsFolder chartNode) throws DatabaseException {\r
+        return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/folder.png"));\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartsLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ChartsLabeler.java
new file mode 100644 (file)
index 0000000..ff4dc7a
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
+\r
+/**\r
+ * Provides label for {@link ChartsFolder} in model browser\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartsLabeler extends LabelerContributor<ChartsFolder> {\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, ChartsFolder input) throws DatabaseException {\r
+        return "Charts";\r
+    }\r
+    \r
+    @Override\r
+    public int getCategory(ReadGraph graph, ChartsFolder input) throws DatabaseException {\r
+       return -3;\r
+    }    \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Configuration.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Configuration.java
new file mode 100644 (file)
index 0000000..fdb9ee0
--- /dev/null
@@ -0,0 +1,105 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.TreeMap;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.BookNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.EnumerationNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.InputNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
+\r
+public class Configuration extends ViewpointContributor<ConfigurationNode<Resource>> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, ConfigurationNode<Resource> configuration) throws DatabaseException {\r
+               ArrayList<Object> result = new ArrayList<Object>();\r
+               Variable variable = configuration.getVariable();\r
+               \r
+               if (variable == null) {\r
+                       return result;\r
+               }\r
+               \r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               TreeMap<String, Variable> variables = new TreeMap<String, Variable>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+               TreeMap<String, Variable> inputs = new TreeMap<String, Variable>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+               TreeMap<String, Variable> modules = new TreeMap<String, Variable>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+               TreeMap<String, Variable> enumerations = new TreeMap<String, Variable>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+\r
+\r
+               for(Variable child : variable.getChildren(graph)) {\r
+                       Resource represents = (Resource)child.getPropertyValue(graph, Variables.REPRESENTS);\r
+                       if(graph.isInstanceOf(represents, sr.IndependentVariable)) {\r
+                               variables.put(child.getName(graph), child);\r
+                       } else if (graph.isInstanceOf(represents, sr.Input)) {\r
+                               inputs.put(child.getName(graph), child);\r
+                       } else if (graph.isInstanceOf(represents, sr.Module)) {\r
+                               modules.put(child.getName(graph), child);\r
+                       } else if (graph.isInstanceOf(represents, sr.Enumeration)) {\r
+                               enumerations.put(child.getName(graph), child);\r
+                       }\r
+               }\r
+               \r
+               for (String s : variables.keySet()) {\r
+                       Variable v = variables.get(s);\r
+                       Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS);\r
+                       result.add(new VariableNode<Variable>(v, represents));\r
+               }\r
+               \r
+               for (String s : inputs.keySet()) {\r
+                       Variable v = inputs.get(s);\r
+                       Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS);\r
+                       result.add(new InputNode(v, represents));\r
+               }\r
+               \r
+               for (String s : modules.keySet()) {\r
+                       Variable v = modules.get(s);\r
+                       Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS);\r
+                       result.add(new ModuleNode(v, represents));\r
+               }\r
+               \r
+               for (String s : enumerations.keySet()) {\r
+                       Variable v = enumerations.get(s);\r
+                       Resource represents = (Resource)v.getPropertyValue(graph, Variables.REPRESENTS);\r
+                       result.add(new EnumerationNode(v, represents));\r
+               }\r
+               \r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(\r
+                       configuration.data,\r
+                       Layer0.getInstance(graph).ConsistsOf, \r
+                       SpreadsheetResource.getInstance(graph).Book))) {\r
+                   result.add(new BookNode(r));\r
+               }\r
+               \r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "Standard";\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ConfigurationLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ConfigurationLabeler.java
new file mode 100644 (file)
index 0000000..c3039e4
--- /dev/null
@@ -0,0 +1,32 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode;\r
+\r
+public class ConfigurationLabeler extends LabelerContributor<ConfigurationNode<Resource>>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, ConfigurationNode<Resource> conf) throws DatabaseException {\r
+        return "Configuration";\r
+    }\r
+\r
+    @Override\r
+    public int getCategory(ReadGraph graph, ConfigurationNode<Resource> input) throws DatabaseException {\r
+       return -7;\r
+    } \r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Experiment.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Experiment.java
new file mode 100644 (file)
index 0000000..9e7aff0
--- /dev/null
@@ -0,0 +1,49 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder;\r
+\r
+public class Experiment extends ViewpointContributor<ExperimentsFolder> {\r
+\r
+    @SuppressWarnings("unchecked")\r
+       @Override\r
+    public Collection<?> getContribution(ReadGraph graph, ExperimentsFolder experimentsFolder) throws DatabaseException {\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(experimentsFolder.data, l0.ConsistsOf, SimulationResource.getInstance(graph).Experiment))) {\r
+            try {\r
+                result.add(graph.adapt(r, AbstractNode.class));\r
+            } catch(DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentLabelDecorator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentLabelDecorator.java
new file mode 100644 (file)
index 0000000..d86672d
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.eclipse.jface.resource.FontDescriptor;\r
+import org.eclipse.swt.SWT;\r
+import org.simantics.browsing.ui.content.LabelDecorator;\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelDecoratorContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentNode;\r
+\r
+public class ExperimentLabelDecorator extends LabelDecoratorContributor<ExperimentNode> {\r
+\r
+    @Override\r
+    public LabelDecorator getDecorator(ReadGraph graph, ExperimentNode experimentNode) throws DatabaseException {\r
+        if (graph.hasStatement(experimentNode.data, SimulationResource.getInstance(graph).IsActive)) {\r
+            return new LabelDecorator.Stub() {\r
+                @Override\r
+                public String decorateLabel(String label, String column, int itemIndex) {\r
+                    return label + " [ACTIVE]";\r
+                }\r
+\r
+                @SuppressWarnings("unchecked")\r
+                @Override\r
+                public <F> F decorateFont(F font, String column, int itemIndex) {\r
+                    return (F) ((FontDescriptor) font).withStyle(SWT.BOLD);\r
+                }\r
+            };\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentLabeler.java
new file mode 100644 (file)
index 0000000..37c0295
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentNode;\r
+\r
+public class ExperimentLabeler extends LabelerContributor<ExperimentNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, ExperimentNode experiment) throws DatabaseException {\r
+       \r
+        String name = graph.getPossibleRelatedValue(experiment.data, Layer0.getInstance(graph).HasLabel);\r
+        \r
+        SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+                       \r
+        String icName = null;\r
+        Resource ic = graph.getPossibleObject(experiment.data, SYSDYN.Experiment_ic);\r
+        if(ic != null) {\r
+               icName = NameUtils.getSafeName(graph, ic);\r
+        }\r
+        \r
+        return (name == null ? "Experiment (no name)" : name) + (icName != null ? " (" + icName + ")" : "");\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentsLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ExperimentsLabeler.java
new file mode 100644 (file)
index 0000000..98f5f33
--- /dev/null
@@ -0,0 +1,32 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder;\r
+\r
+public class ExperimentsLabeler extends LabelerContributor<ExperimentsFolder> {\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, ExperimentsFolder experiments) throws DatabaseException {\r
+        return "Experiments";\r
+    }\r
+    \r
+    @Override\r
+    public int getCategory(ReadGraph graph, ExperimentsFolder input) throws DatabaseException {\r
+       return -6;\r
+    }     \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraries.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraries.java
new file mode 100644 (file)
index 0000000..5cd6bbe
--- /dev/null
@@ -0,0 +1,81 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.TreeMap;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
+\r
+public class FunctionLibraries  extends ViewpointContributor<FunctionsFolder> {\r
+\r
+       @Override\r
+    public Collection<?> getContribution(ReadGraph graph, FunctionsFolder functionsFolder)\r
+    throws DatabaseException {\r
+\r
+       Layer0 l0 = Layer0.getInstance(graph);\r
+       SysdynResource sr = SysdynResource.getInstance(graph);\r
+       \r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        \r
+               TreeMap<String, Resource> sortResult = new TreeMap<String, Resource>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+        // Find and sort model functions\r
+        for(Resource function : graph.syncRequest(new ObjectsWithType(functionsFolder.data, l0.ConsistsOf, sr.SysdynModelicaFunction))) {\r
+                       sortResult.put(NameUtils.getSafeName(graph, function), function);\r
+        }\r
+               for(Resource function : sortResult.values())\r
+                       result.add(new FunctionNode(function));\r
+        \r
+        // Find and sort model function libraries\r
+               sortResult.clear();\r
+        for(Resource functionLibrary : graph.syncRequest(new ObjectsWithType(functionsFolder.data, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) {\r
+                       sortResult.put(NameUtils.getSafeName(graph, functionLibrary), functionLibrary);\r
+               }\r
+               for(Resource functionLibrary : sortResult.values())\r
+                       result.add(new FunctionLibraryNode<Resource>(functionLibrary));\r
+               \r
+               // Find built-in functions\r
+        Resource sysdyn = graph.getPossibleResource("http://www.simantics.org/Sysdyn-1.1");\r
+        if(sysdyn != null) {\r
+               for(Resource library : graph.syncRequest(new ObjectsWithType(sysdyn, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) {\r
+                        result.add(new FunctionLibraryNode<Resource>(library));\r
+               }\r
+        }\r
+        \r
+        \r
+        result.add(new SharedFunctionsFolder(functionsFolder.data));\r
+        \r
+        return result;\r
+\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+    \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraryLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionLibraryLabeler.java
new file mode 100644 (file)
index 0000000..96ef1f9
--- /dev/null
@@ -0,0 +1,24 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
+\r
+public class FunctionLibraryLabeler extends LabelerContributor<FunctionLibraryNode<Resource>>{\r
+\r
+       @Override\r
+       public String getLabel(ReadGraph graph, FunctionLibraryNode<Resource> input)\r
+                       throws DatabaseException {\r
+               String name = NameUtils.getSafeName(graph, input.data);\r
+               return name;\r
+       }\r
+\r
+       @Override\r
+       public int getCategory(ReadGraph graph, FunctionLibraryNode<Resource> input) throws DatabaseException {\r
+               return -1;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionsLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/FunctionsLabeler.java
new file mode 100644 (file)
index 0000000..421c9e6
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
+\r
+public class FunctionsLabeler  extends LabelerContributor<FunctionsFolder>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, FunctionsFolder input) throws DatabaseException {\r
+        return "Functions";\r
+    }\r
+    \r
+    @Override\r
+    public int getCategory(ReadGraph graph, FunctionsFolder input) throws DatabaseException {\r
+       return -4;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditionLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditionLabeler.java
new file mode 100644 (file)
index 0000000..97a1a3a
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.InitialCondition;\r
+\r
+public class InitialConditionLabeler extends LabelerContributor<InitialCondition>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, InitialCondition input) throws DatabaseException {\r
+        return NameUtils.getSafeName(graph, input.data);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditions.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditions.java
new file mode 100644 (file)
index 0000000..138e890
--- /dev/null
@@ -0,0 +1,50 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.InitialCondition;\r
+import org.simantics.sysdyn.ui.browser.nodes.InitialConditionsFolder;\r
+\r
+public class InitialConditions extends ViewpointContributor<InitialConditionsFolder> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, InitialConditionsFolder model)\r
+    throws DatabaseException {\r
+\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+        \r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(model.data, l0.ConsistsOf, SYSDYN.InitialCondition))) {\r
+                result.add(new InitialCondition(r));\r
+        }\r
+        return result;\r
+\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditionsLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InitialConditionsLabeler.java
new file mode 100644 (file)
index 0000000..21d4541
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.InitialConditionsFolder;\r
+\r
+public class InitialConditionsLabeler  extends LabelerContributor<InitialConditionsFolder>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, InitialConditionsFolder input) throws DatabaseException {\r
+        return "Initial Conditions";\r
+    }\r
+    \r
+    @Override\r
+    public int getCategory(ReadGraph graph, InitialConditionsFolder input) throws DatabaseException {\r
+       return -2;\r
+    }\r
+    \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InputLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/InputLabeler.java
new file mode 100644 (file)
index 0000000..7d34ce2
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.ui.browser.nodes.InputNode;\r
+\r
+public class InputLabeler extends LabelerContributor<InputNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, InputNode var) throws DatabaseException {\r
+       Layer0 l0 = Layer0.getInstance(graph);\r
+       Layer0X L0X = Layer0X.getInstance(graph);\r
+        Resource varres = var.data;\r
+        StringBuilder sb = new StringBuilder();\r
+        for(Resource r : graph.getObjects(varres, l0.HasName))\r
+            sb.append(graph.getValue(r));\r
+               if(graph.isInstanceOf(varres, L0X.Realization)) {\r
+                       varres = graph.getPossibleObject(varres, L0X.Represents);\r
+                       if(varres == null) return sb.toString();\r
+               }\r
+               sb.append(" : ");\r
+               for(Resource t : graph.getObjects(varres, l0.InstanceOf))\r
+                       for(Resource r : graph.getObjects(t, l0.HasName))\r
+                               sb.append(graph.getValue(r));\r
+        return sb.toString();\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryContribution.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryContribution.java
new file mode 100644 (file)
index 0000000..9101dbf
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.Library;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+\r
+public class LibraryContribution  extends ViewpointContributor<AbstractNode<Resource>> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, AbstractNode<Resource> node) throws DatabaseException {\r
+       \r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        \r
+        if(!(node instanceof ModelNode || node instanceof Library)) return result;\r
+        \r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        if(!graph.isInstanceOf(node.data, L0.SharedOntology)) {\r
+               for(Resource lib : graph.syncRequest(new ObjectsWithType(node.data, L0.ConsistsOf, L0.Library))) {\r
+                result.add(new Library(lib));\r
+               }\r
+        }\r
+        \r
+        return result;\r
+        \r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryFunctions.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryFunctions.java
new file mode 100644 (file)
index 0000000..6e3a1a1
--- /dev/null
@@ -0,0 +1,64 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.TreeMap;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionNode;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
+\r
+public class LibraryFunctions extends ViewpointContributor<FunctionLibraryNode<Resource>> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph,\r
+                       FunctionLibraryNode<Resource> library) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+               \r
+               TreeMap<String, Resource> sortResult = new TreeMap<String, Resource>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+\r
+               // Find and sort functions in library\r
+               for(Resource function : graph.syncRequest(new ObjectsWithType(library.data, l0.ConsistsOf, SysdynResource.getInstance(graph).SysdynModelicaFunction))) {\r
+                       sortResult.put(NameUtils.getSafeName(graph, function), function);\r
+               }\r
+               for(Resource function : sortResult.values())\r
+                       result.add(new FunctionNode(function));\r
+\r
+               // Find and sort libraries in library\r
+               sortResult.clear();\r
+               for(Resource functionLibrary : graph.syncRequest(new ObjectsWithType(library.data, l0.ConsistsOf, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary))) {\r
+                       sortResult.put(NameUtils.getSafeName(graph, functionLibrary), functionLibrary);\r
+               }\r
+               for(Resource functionLibrary : sortResult.values())\r
+                       result.add(new FunctionLibraryNode<Resource>(functionLibrary));\r
+               \r
+               return result;\r
+\r
+    }\r
+       \r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryImager.java
new file mode 100644 (file)
index 0000000..b8c6df4
--- /dev/null
@@ -0,0 +1,25 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.net.MalformedURLException;\r
+import java.net.URL;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.Library;\r
+\r
+public class LibraryImager extends ImagerContributor<Library> {\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, Library node) throws DatabaseException {\r
+       \r
+        try {\r
+               return ImageDescriptor.createFromURL(new URL("platform:/plugin/com.famfamfam.silk/icons/folder.png"));\r
+        } catch (MalformedURLException e) {\r
+               e.printStackTrace();\r
+        }\r
+        return null;\r
+        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/LibraryLabeler.java
new file mode 100644 (file)
index 0000000..ce2daf2
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.Library;\r
+\r
+public class LibraryLabeler extends LabelerContributor<Library> {\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, Library input) throws DatabaseException {\r
+        return NameUtils.getSafeName(graph, input.data);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Model.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Model.java
new file mode 100644 (file)
index 0000000..ddcf935
--- /dev/null
@@ -0,0 +1,70 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.primitiverequest.PossibleObject;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.InitialConditionsFolder;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModulesNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder;\r
+\r
+/**\r
+ * Provides children for a model in model browser\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class Model  extends ViewpointContributor<ModelNode> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, ModelNode model)\r
+    throws DatabaseException {\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        \r
+        Layer0X L0X = Layer0X.getInstance(graph);\r
+        Resource baseRealization = graph.syncRequest(new PossibleObject(model.data, L0X.HasBaseRealization));\r
+        if (baseRealization != null) {\r
+               try {\r
+                       String URI = graph.getURI(baseRealization);\r
+               Variable variable = Variables.getVariable(graph, URI);\r
+                result.add(new ConfigurationNode<Resource>(variable, baseRealization));\r
+               } catch (DatabaseException e) {\r
+               }\r
+        }\r
+        result.add(new ExperimentsFolder(model.data));\r
+        result.add(new ModulesNode(model.data));\r
+        result.add(new FunctionsFolder(model.data));\r
+        result.add(new ChartsFolder(model.data));\r
+        result.add(new SCLModulesFolder(model.data));\r
+        result.add(new InitialConditionsFolder(model.data));\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModelLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModelLabeler.java
new file mode 100644 (file)
index 0000000..16798d8
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+\r
+public class ModelLabeler extends LabelerContributor<ModelNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, ModelNode model) throws DatabaseException {\r
+        String label = graph.getPossibleRelatedValue(model.data, Layer0.getInstance(graph).HasLabel);\r
+        return label == null ? "Model (no name)" : label;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleLabeler.java
new file mode 100644 (file)
index 0000000..6c26809
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleNode;\r
+\r
+public class ModuleLabeler  extends LabelerContributor<ModuleNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, ModuleNode module) throws DatabaseException {\r
+       Layer0 l0 = Layer0.getInstance(graph);\r
+       Layer0X L0X = Layer0X.getInstance(graph);\r
+        Resource resource = module.data;\r
+        StringBuilder sb = new StringBuilder();\r
+        for(Resource r : graph.getObjects(resource, l0.HasName))\r
+            sb.append(graph.getValue(r));\r
+               if(graph.isInstanceOf(resource, L0X.Realization)) {\r
+                       resource = graph.getPossibleObject(resource, L0X.Represents);\r
+                       if(resource == null) return sb.toString();\r
+               }\r
+               sb.append(" : ");\r
+               for(Resource t : graph.getObjects(resource, l0.InstanceOf))\r
+                       for(Resource r : graph.getObjects(t, l0.HasName))\r
+                               sb.append(graph.getValue(r));\r
+        return sb.toString();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleType.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleType.java
new file mode 100644 (file)
index 0000000..4ebe335
--- /dev/null
@@ -0,0 +1,91 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.TreeMap;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.EnumerationNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.InputNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
+\r
+public class ModuleType extends ViewpointContributor<ModuleTypeNode> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, ModuleTypeNode module) throws DatabaseException {\r
+               ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               StructuralResource2 str = StructuralResource2.getInstance(graph);\r
+               \r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               Resource instance =  graph.getPossibleObject(module.data, mr.SymbolToComponentType);\r
+\r
+               if(instance == null) return result;\r
+               Resource conf = graph.getSingleObject(instance, str.IsDefinedBy);\r
+               \r
+               // Independent variables\r
+               TreeMap<String, Resource> variables = new TreeMap<String, Resource>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.IndependentVariable))) {\r
+                       variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r);\r
+               }\r
+               for(String key : variables.keySet())\r
+                       result.add(new VariableNode<Resource>(variables.get(key)));\r
+               \r
+               // Inputs\r
+               variables.clear();\r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Input))) {\r
+                       variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r);\r
+               }\r
+               for(String key : variables.keySet())\r
+                       result.add(new InputNode(variables.get(key)));\r
+               \r
+               // Modules\r
+               variables.clear();\r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Module))) {\r
+                       variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r);\r
+               }\r
+               for(String key : variables.keySet())\r
+                       result.add(new ModuleNode(variables.get(key)));\r
+               \r
+               // Enumerations\r
+               variables.clear();\r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, sr.Enumeration))) {\r
+                       variables.put((String)graph.getPossibleRelatedValue(r, l0.HasName, Bindings.STRING), r);\r
+               }\r
+               for(String key : variables.keySet())\r
+                       result.add(new EnumerationNode(variables.get(key)));\r
+               \r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "Standard";\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleTypeLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModuleTypeLabeler.java
new file mode 100644 (file)
index 0000000..3265401
--- /dev/null
@@ -0,0 +1,34 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode;\r
+\r
+public class ModuleTypeLabeler extends LabelerContributor<ModuleTypeNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, ModuleTypeNode moduleType) throws DatabaseException {\r
+        ModelingResources mr = ModelingResources.getInstance(graph);\r
+        Resource typeResource =  graph.getPossibleObject(moduleType.data, mr.SymbolToComponentType);\r
+        String label = null;\r
+        if(typeResource != null)\r
+            label = graph.getPossibleRelatedValue(typeResource, Layer0.getInstance(graph).HasName);\r
+        return label == null ? "ModuleType (no name)" : label;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Modules.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Modules.java
new file mode 100644 (file)
index 0000000..41bf4e9
--- /dev/null
@@ -0,0 +1,54 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModulesNode;\r
+\r
+public class Modules extends ViewpointContributor<ModulesNode> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, ModulesNode model)\r
+    throws DatabaseException {\r
+\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        StructuralResource2 st = StructuralResource2.getInstance(graph);\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(model.data, l0.ConsistsOf, st.ComponentType))) {\r
+               if(graph.isInheritedFrom(r, SysdynResource.getInstance(graph).Module)) {\r
+                       Resource symbol = graph.getPossibleObject(r,ModelingResources.getInstance(graph).ComponentTypeToSymbol);\r
+                       result.add(new ModuleTypeNode(symbol));\r
+               }\r
+        }\r
+        return result;\r
+\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModulesLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/ModulesLabeler.java
new file mode 100644 (file)
index 0000000..36d64d0
--- /dev/null
@@ -0,0 +1,33 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModulesNode;\r
+\r
+public class ModulesLabeler extends LabelerContributor<ModulesNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, ModulesNode input) throws DatabaseException {\r
+        return "Modules";\r
+    }\r
+    \r
+    @Override\r
+    public int getCategory(ReadGraph graph, ModulesNode input) throws DatabaseException {\r
+       return -5;\r
+    }     \r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/OperatingInterfacesLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/OperatingInterfacesLabeler.java
new file mode 100644 (file)
index 0000000..8c7a8c6
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.OperatingInterfacesFolder;\r
+\r
+public class OperatingInterfacesLabeler extends LabelerContributor<OperatingInterfacesFolder> {\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, OperatingInterfacesFolder input) throws DatabaseException {\r
+        return "Operating interfaces";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Project.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/Project.java
new file mode 100644 (file)
index 0000000..73725cc
--- /dev/null
@@ -0,0 +1,62 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.project.ontology.ProjectResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode;\r
+\r
+public class Project extends ViewpointContributor<Resource> {\r
+\r
+    @SuppressWarnings("unchecked")\r
+       @Override\r
+    public Collection<?> getContribution(ReadGraph graph, Resource project)\r
+    throws DatabaseException {\r
+\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(project, l0.ConsistsOf, sr.SysdynModel))) {\r
+            try {\r
+                result.add(graph.adapt(r, AbstractNode.class));\r
+            } catch(DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+        \r
+        ProjectResource PROJ = ProjectResource.getInstance(graph);\r
+        if(!graph.isInstanceOf(project, PROJ.Project)) return Collections.emptyList();\r
+        Collection<Resource> ontologies = Simantics.applySCL("Simantics/SharedOntologies", "traverseSharedOntologies", graph, graph.getRootLibrary());\r
+        for(Resource o : ontologies) result.add(new SharedOntologyNode(o));\r
+\r
+        return result;\r
+\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModuleLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModuleLabeler.java
new file mode 100644 (file)
index 0000000..97cdb9b
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.SCLModule;\r
+\r
+public class SCLModuleLabeler extends LabelerContributor<SCLModule>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, SCLModule input) throws DatabaseException {\r
+        return NameUtils.getSafeName(graph, input.data);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModules.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModules.java
new file mode 100644 (file)
index 0000000..edd997f
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.SCLModule;\r
+import org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder;\r
+\r
+public class SCLModules extends ViewpointContributor<SCLModulesFolder> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, SCLModulesFolder model)\r
+    throws DatabaseException {\r
+\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        \r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(model.data, l0.ConsistsOf, L0.SCLModule))) {\r
+                result.add(new SCLModule(r));\r
+        }\r
+        return result;\r
+\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModulesLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SCLModulesLabeler.java
new file mode 100644 (file)
index 0000000..b291017
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder;\r
+\r
+public class SCLModulesLabeler  extends LabelerContributor<SCLModulesFolder>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, SCLModulesFolder input) throws DatabaseException {\r
+        return "SCL Modules";\r
+    }\r
+    \r
+    @Override\r
+    public int getCategory(ReadGraph graph, SCLModulesFolder input) throws DatabaseException {\r
+       return -2;\r
+    }\r
+    \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedFunctionLibraries.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedFunctionLibraries.java
new file mode 100644 (file)
index 0000000..7d5c736
--- /dev/null
@@ -0,0 +1,36 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder;\r
+\r
+public class SharedFunctionLibraries extends ViewpointContributor<SharedFunctionsFolder> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph,\r
+                       SharedFunctionsFolder sharedFunctionsFolder) throws DatabaseException {\r
+               \r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+\r
+        \r
+        for(Resource sharedLibrary : graph.syncRequest(new ObjectsWithType(\r
+                       sharedFunctionsFolder.data, \r
+                       Layer0.getInstance(graph).IsLinkedTo, \r
+                       SysdynResource.getInstance(graph).SharedFunctionOntology)))\r
+        {\r
+               result.add(new SharedFunctionLibraryNode(sharedLibrary));\r
+        }\r
+        \r
+               return result;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedFunctionsLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedFunctionsLabeler.java
new file mode 100644 (file)
index 0000000..c1c8c0a
--- /dev/null
@@ -0,0 +1,25 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder;\r
+\r
+public class SharedFunctionsLabeler extends LabelerContributor<SharedFunctionsFolder>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, SharedFunctionsFolder input) throws DatabaseException {\r
+        return "Shared Functions";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyImager.java
new file mode 100644 (file)
index 0000000..5c51a8f
--- /dev/null
@@ -0,0 +1,25 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.net.MalformedURLException;\r
+import java.net.URL;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode;\r
+\r
+public class SharedOntologyImager extends ImagerContributor<SharedOntologyNode> {\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, SharedOntologyNode node) throws DatabaseException {\r
+       \r
+        try {\r
+               return ImageDescriptor.createFromURL(new URL("platform:/plugin/com.famfamfam.silk/icons/folder.png"));\r
+        } catch (MalformedURLException e) {\r
+               e.printStackTrace();\r
+        }\r
+        return null;\r
+        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SharedOntologyLabeler.java
new file mode 100644 (file)
index 0000000..9ebfc57
--- /dev/null
@@ -0,0 +1,21 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.Versions;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode;\r
+\r
+public class SharedOntologyLabeler extends LabelerContributor<SharedOntologyNode> {\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, SharedOntologyNode node) throws DatabaseException {\r
+       return Versions.getStandardNameString(graph, node.data);\r
+    }\r
+    \r
+    @Override\r
+    public int getCategory(ReadGraph graph, SharedOntologyNode node) throws DatabaseException {\r
+       return -1;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SheetLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SheetLabeler.java
new file mode 100644 (file)
index 0000000..ff4bd59
--- /dev/null
@@ -0,0 +1,15 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.SheetNode;\r
+\r
+public class SheetLabeler  extends LabelerContributor<SheetNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, SheetNode sheet) throws DatabaseException {\r
+        return  graph.getPossibleRelatedValue(sheet.data, Layer0.getInstance(graph).HasName);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResult.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResult.java
new file mode 100644 (file)
index 0000000..f7bd86f
--- /dev/null
@@ -0,0 +1,74 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.io.File;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.HistoryDataNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode;\r
+\r
+public class SimulationResult  extends ViewpointContributor<AbstractNode<Resource>> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, AbstractNode<Resource> node) throws DatabaseException {\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        if (!(node instanceof ExperimentNode || node instanceof SimulationResultSetNode))\r
+               return result;\r
+        for(final Resource r : graph.syncRequest(new ObjectsWithType(node.data, sr.Experiment_result, sr.Result))) {\r
+            if(graph.isInstanceOf(r, sr.HistoryDataset)) {\r
+                result.add(new HistoryDataNode(r));\r
+            } else {\r
+                result.add(new SimulationResultNode<Resource>(r));\r
+\r
+                String resultPath = (String)graph.getPossibleRelatedValue(r, sr.Result_resultFile);\r
+                File file = new File(resultPath);\r
+                if(!file.exists()) {\r
+                    graph.asyncRequest(new WriteRequest() {\r
+\r
+                        @Override\r
+                        public void perform(WriteGraph graph) throws DatabaseException {\r
+                            String resultPath = (String)graph.getPossibleRelatedValue(r, SysdynResource.getInstance(graph).Result_resultFile);\r
+                            File file = new File(resultPath);\r
+                            if(!file.exists()) {\r
+                                Layer0 l0 = Layer0.getInstance(graph);\r
+                                graph.deny(r, l0.PartOf);\r
+                                graph.deny(r, graph.getInverse(SysdynResource.getInstance(graph).Experiment_result));\r
+                            }\r
+                        }\r
+                    });\r
+                }\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultDecorator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultDecorator.java
new file mode 100644 (file)
index 0000000..3676eba
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.eclipse.jface.resource.FontDescriptor;\r
+import org.eclipse.swt.SWT;\r
+import org.simantics.browsing.ui.content.LabelDecorator;\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelDecoratorContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode;\r
+\r
+public class SimulationResultDecorator extends LabelDecoratorContributor<SimulationResultNode<Resource>>{\r
+\r
+    @Override\r
+    public LabelDecorator getDecorator(ReadGraph graph, SimulationResultNode<Resource> result) throws DatabaseException {\r
+        if (graph.hasStatement(result.data, SysdynResource.getInstance(graph).Result_showResult)) {\r
+            return new LabelDecorator.Stub() {\r
+\r
+                @SuppressWarnings("unchecked")\r
+                @Override\r
+                public <F> F decorateFont(F font, String column, int itemIndex) {\r
+                    return (F) ((FontDescriptor) font).withStyle(SWT.BOLD);\r
+                }\r
+            };\r
+        }\r
+        return new LabelDecorator.Stub() {\r
+\r
+            @SuppressWarnings("unchecked")\r
+            @Override\r
+            public <F> F decorateFont(F font, String column, int itemIndex) {\r
+                return (F) ((FontDescriptor) font).withStyle(SWT.NORMAL);\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultImager.java
new file mode 100644 (file)
index 0000000..3dc688d
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode;\r
+\r
+public class SimulationResultImager extends ImagerContributor<SimulationResultNode<Resource>>{\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, SimulationResultNode<Resource> result) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        if(graph.isInstanceOf(result.data, sr.HistoryDataset))\r
+            return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/table.png"));\r
+        if(graph.hasStatement(result.data, sr.Result_showResult))\r
+            return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_bar.png"));\r
+        else\r
+            return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_bar_blackAndWhite.png"));\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultLabeler.java
new file mode 100644 (file)
index 0000000..f0e968e
--- /dev/null
@@ -0,0 +1,29 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode;\r
+\r
+public class SimulationResultLabeler extends LabelerContributor<SimulationResultNode<Resource>>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, SimulationResultNode<Resource> result) throws DatabaseException {\r
+        String name = graph.getPossibleRelatedValue(result.data, Layer0.getInstance(graph).HasLabel);\r
+        return name == null ? "Experiment (no name)" : name;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSet.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSet.java
new file mode 100644 (file)
index 0000000..dfbe881
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode;\r
+\r
+public class SimulationResultSet extends ViewpointContributor<ExperimentNode> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, ExperimentNode experiment) throws DatabaseException {\r
+        ArrayList<SimulationResultSetNode> results = new ArrayList<SimulationResultSetNode>();\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        for(final Resource r : graph.syncRequest(new ObjectsWithType(experiment.data, sr.Experiment_resultSet, sr.ResultSet))) {\r
+            results.add(new SimulationResultSetNode(r));\r
+        }\r
+        return results;\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetDecorator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetDecorator.java
new file mode 100644 (file)
index 0000000..2491ee5
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.eclipse.jface.resource.FontDescriptor;\r
+import org.eclipse.swt.SWT;\r
+import org.simantics.browsing.ui.content.LabelDecorator;\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelDecoratorContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode;\r
+\r
+public class SimulationResultSetDecorator extends LabelDecoratorContributor<SimulationResultSetNode>{\r
+\r
+    @Override\r
+    public LabelDecorator getDecorator(ReadGraph graph, SimulationResultSetNode resultSet) throws DatabaseException {\r
+       SysdynResource sr = SysdynResource.getInstance(graph);\r
+       for (Resource result : graph.getObjects(resultSet.data, sr.Experiment_result)) {\r
+               if (graph.hasStatement(result, sr.Result_showResult)) {\r
+                return new LabelDecorator.Stub() {\r
+\r
+                    @SuppressWarnings("unchecked")\r
+                    @Override\r
+                    public <F> F decorateFont(F font, String column, int itemIndex) {\r
+                        return (F) ((FontDescriptor) font).withStyle(SWT.BOLD);\r
+                    }\r
+                };\r
+               }\r
+       }\r
+        return new LabelDecorator.Stub() {\r
+\r
+            @SuppressWarnings("unchecked")\r
+            @Override\r
+            public <F> F decorateFont(F font, String column, int itemIndex) {\r
+                return (F) ((FontDescriptor) font).withStyle(SWT.NORMAL);\r
+            }\r
+        };\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetImager.java
new file mode 100644 (file)
index 0000000..88c7380
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode;\r
+\r
+public class SimulationResultSetImager extends ImagerContributor<SimulationResultSetNode>{\r
+\r
+    @Override\r
+    public ImageDescriptor getDescriptor(ReadGraph graph, SimulationResultSetNode resultSet) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+       for (Resource result : graph.getObjects(resultSet.data, sr.Experiment_result)) {\r
+               if (graph.hasStatement(result, sr.Result_showResult)) {\r
+                return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_bar_3.png"));\r
+               }\r
+       }\r
+        return ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_bar_3_blackAndWhite.png"));\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SimulationResultSetLabeler.java
new file mode 100644 (file)
index 0000000..16c4259
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode;\r
+\r
+public class SimulationResultSetLabeler extends LabelerContributor<SimulationResultSetNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, SimulationResultSetNode resultSet) throws DatabaseException {\r
+        String name = graph.getPossibleRelatedValue(resultSet.data, Layer0.getInstance(graph).HasLabel);\r
+        return name == null ? "Experiment (no name)" : name;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SysdynProject.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/SysdynProject.java
new file mode 100644 (file)
index 0000000..91c46b6
--- /dev/null
@@ -0,0 +1,39 @@
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.structural.ui.modelBrowser.nodes.AbstractNode;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class SysdynProject  extends ViewpointContributor<Resource> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, Resource project)\r
+    throws DatabaseException {\r
+\r
+        ArrayList<AbstractNode> result = new ArrayList<AbstractNode>();\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(project, L0.ConsistsOf, SysdynResource.getInstance(graph).SysdynModel))) {\r
+            try {\r
+                result.add(graph.adapt(r, AbstractNode.class));\r
+            } catch(DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+        return result;\r
+\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/VariableLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/contributions/VariableLabeler.java
new file mode 100644 (file)
index 0000000..6302ad0
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.contributions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
+\r
+public class VariableLabeler  extends LabelerContributor<VariableNode<Resource>>{\r
+\r
+       @Override\r
+       public String getLabel(ReadGraph graph, VariableNode<Resource> var) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               Layer0X L0X = Layer0X.getInstance(graph);\r
+               Resource varres = var.data;\r
+               StringBuilder sb = new StringBuilder();\r
+               for(Resource r : graph.getObjects(varres, l0.HasName))\r
+                       sb.append(graph.getValue(r));\r
+               if(graph.isInstanceOf(varres, L0X.Realization)) {\r
+                       varres = graph.getPossibleObject(varres, L0X.Represents);\r
+                       if(varres == null) return sb.toString();\r
+               }\r
+               sb.append(" : ");\r
+               for(Resource t : graph.getObjects(varres, l0.InstanceOf))\r
+                       for(Resource r : graph.getObjects(t, l0.HasName))\r
+                               sb.append(graph.getValue(r));\r
+               return sb.toString();\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/ChartImageRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/ChartImageRule.java
new file mode 100644 (file)
index 0000000..044d9bc
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.imagerules;\r
+\r
+import java.util.Collections;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.images.ImageRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+\r
+public class ChartImageRule implements ImageRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return Resource.class.equals(contentType);\r
+    }\r
+\r
+    @Override\r
+    public Map<String, ImageDescriptor> getImage(ReadGraph graph, Object content) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+        String image = "icons/chart_line.png";\r
+\r
+        Resource chart = (Resource) content;\r
+\r
+        Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));\r
+        if(plot != null) {\r
+            if(graph.isInstanceOf(plot, jfree.CategoryPlot)) {\r
+                image = "icons/chart_bar.png";\r
+            } else if(graph.isInstanceOf(plot, jfree.PiePlot)) {\r
+                image = "icons/chart_pie.png";\r
+            }\r
+        }\r
+\r
+        return Collections.singletonMap(ColumnKeys.SINGLE, \r
+                ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource(image))\r
+                );    \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/ResultImageRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/ResultImageRule.java
new file mode 100644 (file)
index 0000000..ed7024e
--- /dev/null
@@ -0,0 +1,46 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.imagerules;\r
+\r
+import java.util.Collections;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.images.ImageRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+\r
+public class ResultImageRule implements ImageRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return Resource.class.equals(contentType);\r
+    }\r
+\r
+    @Override\r
+    public Map<String, ImageDescriptor> getImage(ReadGraph graph, Object content) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Resource data = (Resource) content;\r
+        \r
+        String image = "icons/chart_bar_blackAndWhite.png";\r
+        if(graph.hasStatement(data, sr.Result_showResult))\r
+            image ="icons/chart_bar.png";\r
+        \r
+        return Collections.singletonMap(ColumnKeys.SINGLE, \r
+                ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource(image))\r
+                );   \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/VariableImageRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/imagerules/VariableImageRule.java
new file mode 100644 (file)
index 0000000..ba780a6
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.imagerules;\r
+\r
+import java.util.Collections;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.images.ImageRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class VariableImageRule implements ImageRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return Variable.class.equals(contentType);\r
+    }\r
+\r
+    @Override\r
+    public Map<String, ImageDescriptor> getImage(ReadGraph graph, Object content) throws DatabaseException {\r
+        Variable var = AdaptionUtils.adaptToSingle(content, Variable.class);\r
+\r
+        String image =  "icons/brick.png";\r
+        \r
+        Resource r =  (Resource)var.getPropertyValue(graph, Variables.REPRESENTS);\r
+        if(r != null) {\r
+            Layer0 L0 = Layer0.getInstance(graph);\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            Resource type = graph.getSingleObject(r, L0.InstanceOf);\r
+            if(graph.isInheritedFrom(type, sr.Module)) {\r
+                image = "icons/bricks.png";\r
+            }\r
+        }\r
+\r
+        return Collections.singletonMap(ColumnKeys.SINGLE, \r
+                ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource(image))\r
+                );\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/ModuleTypeLabelRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/ModuleTypeLabelRule.java
new file mode 100644 (file)
index 0000000..90d7234
--- /dev/null
@@ -0,0 +1,32 @@
+package org.simantics.sysdyn.ui.browser.labelrules;\r
+\r
+import java.util.Collections;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.labels.LabelRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.modeling.ModelingResources;\r
+\r
+public class ModuleTypeLabelRule implements LabelRule {\r
+    public static final ModuleTypeLabelRule INSTANCE = new ModuleTypeLabelRule();\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
+        Resource symbol = (Resource)content;\r
+        Resource component = graph.getSingleObject(symbol, ModelingResources.getInstance(graph).SymbolToComponentType);\r
+        \r
+        return Collections.singletonMap(ColumnKeys.SINGLE, \r
+                NameUtils.getSafeName(graph, component)\r
+                );\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/VariableNameLabelRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/VariableNameLabelRule.java
new file mode 100644 (file)
index 0000000..8e97b42
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.labelrules;\r
+\r
+import java.util.Collections;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.labels.LabelRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class VariableNameLabelRule  implements LabelRule {\r
+    public static final ModuleTypeLabelRule INSTANCE = new ModuleTypeLabelRule();\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Variable.class);\r
+    }\r
+\r
+    @Override\r
+    public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
+        Variable var = AdaptionUtils.adaptToSingle(content, Variable.class);\r
+        return Collections.singletonMap(ColumnKeys.SINGLE, \r
+                var != null ? var.getName(graph) : "No variable"\r
+                );\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodeTypes/ModuleSymbolNodeType.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodeTypes/ModuleSymbolNodeType.java
new file mode 100644 (file)
index 0000000..e4e8fde
--- /dev/null
@@ -0,0 +1,114 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodeTypes;\r
+\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.WeakHashMap;\r
+\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.common.NodeContextBuilder;\r
+import org.simantics.browsing.ui.model.nodetypes.NodeType;\r
+import org.simantics.browsing.ui.model.nodetypes.SpecialNodeType;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.ui.selection.WorkbenchSelectionElement;\r
+\r
+/**\r
+ * Experimental node type for Module symbols. Copied mostly from {@link SpecialNodeType}. \r
+ * Not necessary needed.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ModuleSymbolNodeType implements NodeType {\r
+    \r
+    private Resource resource;\r
+    private Class<?> contentType;\r
+    \r
+    private static final WeakHashMap<Resource, ModuleSymbolNodeType> nodeTypeCache =\r
+            new WeakHashMap<Resource, ModuleSymbolNodeType>();\r
+\r
+    public ModuleSymbolNodeType(Resource resource) {\r
+        this.resource = resource;\r
+        this.contentType = Resource.class;\r
+    }\r
+    \r
+    public static ModuleSymbolNodeType  create(Resource entityType) {\r
+        synchronized(nodeTypeCache) {\r
+            ModuleSymbolNodeType result = nodeTypeCache.get(entityType);\r
+            if(result == null) {\r
+                result = new ModuleSymbolNodeType(entityType);\r
+                nodeTypeCache.put(entityType, result);\r
+            }\r
+            return result;\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public NodeContext createNodeContext(ReadGraph graph, Object content)\r
+            throws DatabaseException {\r
+        if(contentType.isInstance(content))\r
+            return NodeContextBuilder.buildWithData(KEY_SEQUENCE,\r
+                    new Object[] {content, this}\r
+            );\r
+        else\r
+            return null;\r
+    }\r
+\r
+    @Override\r
+    public Class<?> getContentType() {\r
+        return contentType;\r
+    }\r
+\r
+    @Override\r
+    public int hashCode() {\r
+        return resource.hashCode();\r
+    }\r
+\r
+    @Override\r
+    public boolean equals(Object obj) {\r
+        if (this == obj)\r
+            return true;\r
+        if (obj == null)\r
+            return false;\r
+        if (getClass() != obj.getClass())\r
+            return false;\r
+        ModuleSymbolNodeType other = (ModuleSymbolNodeType) obj;\r
+        return resource.equals(other.resource);\r
+    }\r
+\r
+    @Override\r
+    public boolean inherits(ReadGraph graph, NodeType superType) {\r
+        // Special node type does not support inheritance\r
+        return equals(superType);\r
+    }\r
+\r
+    @Override\r
+    public Collection<NodeType> getSuper(ReadGraph g) {\r
+        return Collections.emptyList();\r
+    }\r
+    \r
+    @Override\r
+    public String toString(ReadGraph graph) throws DatabaseException {\r
+        return "(" + NameUtils.getSafeName(graph, resource) + ")";\r
+    }\r
+\r
+    @Override\r
+    public WorkbenchSelectionElement getWorkbenchSelectionElement(NodeContext context) {\r
+        return null;\r
+    }\r
+    \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AbstractChartNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AbstractChartNode.java
new file mode 100644 (file)
index 0000000..61eb185
--- /dev/null
@@ -0,0 +1,79 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import java.util.Iterator;\r
+\r
+import org.eclipse.core.runtime.IAdaptable;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public abstract class AbstractChartNode<T> extends AbstractNode<Resource> implements IDropTargetNode, IDeletableNode {\r
+\r
+    public AbstractChartNode(Resource data) {\r
+        super(data);\r
+    }\r
+\r
+\r
+    /**\r
+     * Add variable to this chart, if the dropped element(s) can be adapted to a {@link Variable} \r
+     */\r
+    @Override\r
+    public void drop(Object data) {\r
+        IStructuredSelection selection = (IStructuredSelection)data;\r
+        Iterator<?> iterator = selection.iterator();\r
+        while(iterator.hasNext()) {\r
+            Object o = iterator.next();\r
+            if(o instanceof IAdaptable) {\r
+                Variable v = (Variable) ((IAdaptable)o).getAdapter(Variable.class);\r
+                if(v != null) {\r
+                    addVariableToChart(v);\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * Adds a variable to this chart and map it to the first rangeAxis\r
+     * @param variable\r
+     */\r
+    protected abstract void addVariableToChart(final Variable variable);\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }    \r
+\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationType.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationType.java
new file mode 100644 (file)
index 0000000..d5f3b6b
--- /dev/null
@@ -0,0 +1,68 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.primitiverequest.PossibleObject;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class AnnotationType extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
+\r
+    public AnnotationType(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }    \r
+\r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        Session session = Simantics.getSession();\r
+        try {\r
+                       Resource relation =  session.syncRequest(new PossibleObject(data, session.getService(Layer0.class).HasRange_Inverse));\r
+                       if(relation != null)\r
+                               return new LabelModifier(session, relation, session.getService(Layer0.class).HasName);\r
+               } catch (Exception e) {\r
+                       Logger.defaultLogError(e);\r
+               }\r
+               return null;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationValue.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationValue.java
new file mode 100644 (file)
index 0000000..0f551ee
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class AnnotationValue extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
+\r
+    public AnnotationValue(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }    \r
+\r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+       Session session = Simantics.getSession();\r
+       return new LabelModifier(session, data, session.getService(Layer0.class).HasName);\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BarChartNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BarChartNode.java
new file mode 100644 (file)
index 0000000..9dff79b
--- /dev/null
@@ -0,0 +1,69 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.SingleObjectWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Bar chart node\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class BarChartNode extends AbstractChartNode<Resource> {\r
+\r
+    public BarChartNode(Resource data) {\r
+        super(data);\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Adds a variable to this chart\r
+     * @param variable\r
+     */\r
+    @Override\r
+    protected void addVariableToChart(final Variable variable) {\r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+                Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));\r
+                if(plot == null)\r
+                    return;\r
+\r
+                Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+                \r
+                if(dataset == null)\r
+                    return;\r
+                \r
+                // Create the series and attach it to the dataset\r
+                String rvi = Variables.getRVI(graph, variable);\r
+                ChartUtils.createSeries(graph, dataset, rvi);\r
+            }\r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BookNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BookNode.java
new file mode 100644 (file)
index 0000000..02f5bc5
--- /dev/null
@@ -0,0 +1,11 @@
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+\r
+public class BookNode extends AbstractNode<Resource> {\r
+\r
+    public BookNode(Resource data) {\r
+        super(data);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ChartsFolder.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ChartsFolder.java
new file mode 100644 (file)
index 0000000..d75b01b
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+\r
+/**\r
+ * Folder containing all sysdyn charts\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartsFolder extends AbstractNode<Resource> {\r
+\r
+    public ChartsFolder(Resource resource) {\r
+        super(resource);\r
+    }\r
+    \r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(clazz == adapter) // There is no resource for this node..\r
+            return null;\r
+        return super.getAdapter(adapter);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ConfigurationNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ConfigurationNode.java
new file mode 100644 (file)
index 0000000..4b61442
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.IDeletable;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.layer0.variable.Variable;\r
+\r
+public class ConfigurationNode<T> extends VariableNode<Resource> implements IDeletable {\r
+       \r
+       public ConfigurationNode(Resource resource) {\r
+               super(resource);\r
+       }\r
+       \r
+    public ConfigurationNode(Variable variable, Resource represents) {\r
+        super(variable, represents);\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/EnumerationNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/EnumerationNode.java
new file mode 100644 (file)
index 0000000..7d7ee9d
--- /dev/null
@@ -0,0 +1,108 @@
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class EnumerationNode extends VariableNode<Resource> implements IModifiableNode, IDeletableNode {\r
+\r
+       public EnumerationNode(Resource resource) {\r
+               super(resource);\r
+       }\r
+       \r
+       public EnumerationNode(Variable variable, Resource represents) {\r
+        super(variable, represents);\r
+       }\r
+    \r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        \r
+        final Session session = SimanticsUI.getSession();\r
+        LabelModifier modifier = new LabelModifier(session, data, session.getService(Layer0.class).HasName) {\r
+            @Override\r
+            public String isValid(String label) {\r
+                if (!new VariableNameValidator().isValid(data, label))\r
+                    return "Not valid";\r
+                else\r
+                    return null;\r
+            }\r
+            \r
+            @Override\r
+            public void modify(final String label) {\r
+                try {\r
+                                       session.syncRequest(new WriteRequest() {\r
+                                               @Override\r
+                                               public void perform(WriteGraph graph)\r
+                                                               throws DatabaseException {\r
+\r
+                                               String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);\r
+                                               if(!originalName.equals(label)) {\r
+                                                   Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);\r
+                                                   new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);\r
+                                                       graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);\r
+                                               }\r
+                                               }\r
+                                       });\r
+                               } catch (DatabaseException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+\r
+               super.modify(label);\r
+            }\r
+        };\r
+        return modifier;\r
+    }\r
+\r
+       @Override\r
+       public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    for(Resource redeclaration : graph.getObjects(data, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
+                       graph.deny(redeclaration, sr.Module_redeclaration_Inverse);\r
+                    }\r
+                    \r
+                    for(Resource redeclaration : graph.getObjects(data, sr.Redeclaration_replacingEnumeration_Inverse)) {\r
+                       graph.deny(redeclaration, sr.Module_redeclaration_Inverse);\r
+                    }\r
+                    \r
+                    Layer0 L0 = Layer0.getInstance(graph);\r
+                    Resource conf = graph.getPossibleObject(data, L0.PartOf);\r
+                    for(Resource var : graph.syncRequest(new ObjectsWithType(conf, L0.ConsistsOf, sr.Variable))) {\r
+                        Resource arrayIndexes = graph.getPossibleObject(var, sr.Variable_arrayIndexesList);\r
+                        if(arrayIndexes != null) {\r
+                            if(ListUtils.getNode(graph, arrayIndexes, data) != null) {\r
+                                ListUtils.removeElement(graph, arrayIndexes, data);\r
+                            }\r
+                        }\r
+                    }\r
+                    \r
+                    RemoverUtil.remove(graph, data);\r
+                    \r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentNode.java
new file mode 100644 (file)
index 0000000..deeb8dd
--- /dev/null
@@ -0,0 +1,92 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class ExperimentNode extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode{\r
+\r
+    public ExperimentNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @Override\r
+    public boolean handleDoubleClick() {\r
+        if (data == null)\r
+            return false;\r
+        IProject project = SimanticsUI.getProject();\r
+        IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        if (experimentManager == null) {\r
+            ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());\r
+            return false;\r
+        }\r
+        SysdynExperimentActivator.scheduleActivation(SimanticsUI.getSession(), project, experimentManager, data);\r
+        return true;\r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data) {\r
+            @Override\r
+            public String isValid(String label) {\r
+                if (label.isEmpty())\r
+                    return "Empty label not allowed";\r
+                return null;\r
+            }\r
+        };\r
+        return modifier;\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    Collection<Resource> results = graph.getObjects(data, SysdynResource.getInstance(graph).Experiment_result);\r
+                    if(results != null)\r
+                        for(Resource result : results) \r
+                            SimulationResultNode.unlinkResult(graph, result);\r
+                    Collection<Resource> resultSets = graph.getObjects(data, SysdynResource.getInstance(graph).Experiment_resultSet);\r
+                    if(resultSets != null)\r
+                        for(Resource resultSet : resultSets) \r
+                            SimulationResultSetNode.unlinkResultSet(graph, resultSet);\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentsFolder.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentsFolder.java
new file mode 100644 (file)
index 0000000..76be910
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+\r
+public class ExperimentsFolder extends AbstractNode<Resource> {\r
+\r
+    public ExperimentsFolder(Resource resource) {\r
+        super(resource);\r
+    }\r
+    \r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(clazz == adapter) // There is no resource for this node..\r
+            return null;\r
+        return super.getAdapter(adapter);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExportTester.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExportTester.java
new file mode 100644 (file)
index 0000000..dad1cd4
--- /dev/null
@@ -0,0 +1,92 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import java.util.Collection;\r
+\r
+import org.eclipse.core.expressions.PropertyTester;\r
+import org.eclipse.ui.IEditorPart;\r
+import org.eclipse.ui.IWorkbenchPage;\r
+import org.simantics.DatabaseJob;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * This class tests whether the export functionality is active\r
+ * \r
+ * @author Tuomas Miettinen\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class ExportTester extends PropertyTester {\r
+\r
+    @Override\r
+    public boolean test(Object receiver, final String property, final Object[] args, final Object expectedValue) {\r
+       // Find the resource from the receiver.\r
+        Resource inputResource = ResourceAdaptionUtils.toSingleResource(receiver);\r
+        if (inputResource == null) {\r
+               @SuppressWarnings("rawtypes")\r
+                       Collection<AbstractNode> a = AdaptionUtils.adaptToCollection(receiver, AbstractNode.class);\r
+               if (a.size() > 1) // Multiple selections.\r
+                       return false;\r
+               if (a.size() == 1)\r
+                       inputResource = (Resource)a.iterator().next().data;\r
+        }\r
+        if (inputResource == null) {\r
+               \r
+               IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();\r
+               IEditorPart editor = page.getActiveEditor();\r
+               if (editor instanceof DiagramEditor) {\r
+               inputResource = ((DiagramEditor)editor).getInputResource();\r
+               } else {\r
+                       return false;\r
+               }\r
+       }\r
+        final Resource resource = inputResource;\r
+\r
+        Session session = SimanticsUI.peekSession();\r
+        if (session == null)\r
+            return false;\r
+\r
+        if (DatabaseJob.inProgress())\r
+            return false;\r
+\r
+        // Check if we can get the model of the resource.\r
+        try {\r
+            return session.syncRequest(new Read<Boolean>() {\r
+                @Override\r
+                public Boolean perform(ReadGraph g) throws DatabaseException {\r
+                       if (g.sync(new PossibleModel(resource)) != null) {\r
+                               return true;\r
+                       }\r
+                       return false;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            // Purposefully not logging these exceptions, there might be way too\r
+            // many even under normal circumstances.\r
+            // TODO: add debug tracing options controlling the printing of these exceptions\r
+            return false;\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionLibraryNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionLibraryNode.java
new file mode 100644 (file)
index 0000000..00a3dcb
--- /dev/null
@@ -0,0 +1,93 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.FunctionLibraryNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+public class FunctionLibraryNode<T> extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode, IDropTargetNode {\r
+\r
+       \r
+    public FunctionLibraryNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+       @Override\r
+       public Modifier getModifier(String columnId) {\r
+               try {\r
+                       Resource hasName = Layer0.getInstance(SimanticsUI.getSession()).HasName;\r
+                       LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data, hasName) {\r
+                               @Override\r
+                   public String isValid(String label) {\r
+                       if (!new FunctionLibraryNameValidator().isValid(data, label))\r
+                           return "Not valid";\r
+                       else\r
+                           return null;\r
+                   }\r
+                       };\r
+                       return modifier;\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public void delete() throws DeleteException {\r
+           SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+               @Override\r
+               public void perform(WriteGraph graph) throws DatabaseException {\r
+                   RemoverUtil.remove(graph, data);\r
+               }\r
+           });\r
+       }\r
+\r
+       @Override\r
+       public void drop(Object data) {\r
+               final Resource[] resources = ResourceAdaptionUtils.toResources(data);\r
+               final Resource library = this.data;\r
+               if(resources.length > 0) {\r
+                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                               \r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       for(Resource tobeMoved : resources) {\r
+                                               if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||\r
+                                                               graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {\r
+                                                       graph.deny(tobeMoved, l0.PartOf);\r
+                                                       graph.claim(tobeMoved, l0.PartOf, library);\r
+                                               }\r
+                                       }\r
+                               }\r
+                       });\r
+               }\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionNode.java
new file mode 100644 (file)
index 0000000..2131251
--- /dev/null
@@ -0,0 +1,95 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.FunctionNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+public class FunctionNode extends VariableNode<Resource> implements IDeletableNode, IModifiableNode, IDropTargetNode {\r
+       \r
+    public FunctionNode(final Resource resource) {\r
+       super(resource);\r
+    }\r
+    \r
+       @Override\r
+       public Modifier getModifier(String columnId) {\r
+               try {\r
+                       Resource hasName = Layer0.getInstance(SimanticsUI.getSession()).HasName;\r
+                       LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data, hasName) {\r
+                @Override\r
+                public String isValid(String label) {\r
+                    if (!new FunctionNameValidator().isValid(data, label))\r
+                        return "Not valid";\r
+                    else\r
+                        return null;\r
+                }\r
+                       };\r
+                       return modifier;\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public void delete() throws DeleteException {\r
+           SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+               @Override\r
+               public void perform(WriteGraph graph) throws DatabaseException {\r
+                   RemoverUtil.remove(graph, data);\r
+               }\r
+           });\r
+       }\r
+       \r
+       @Override\r
+       public void drop(Object data) {\r
+               final Resource[] resources = ResourceAdaptionUtils.toResources(data);\r
+               final Resource thisFunction = this.data;\r
+               \r
+               if(resources.length > 0) {\r
+                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                               \r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       Resource library = null;\r
+                                       for(Resource tobeMoved : resources) {\r
+                                               if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||\r
+                                                               graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {\r
+                                                       if(library == null) {\r
+                                                               library = graph.getSingleObject(thisFunction, l0.PartOf);\r
+                                                       }\r
+                                                       graph.deny(tobeMoved, l0.PartOf);\r
+                                                       graph.claim(tobeMoved, l0.PartOf, library);\r
+                                               }\r
+                                       }\r
+                               }\r
+                       });\r
+               }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionsFolder.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionsFolder.java
new file mode 100644 (file)
index 0000000..5e4f874
--- /dev/null
@@ -0,0 +1,66 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+public class FunctionsFolder extends AbstractNode<Resource> implements IDropTargetNode{\r
+\r
+    public FunctionsFolder(Resource resource) {\r
+        super(resource);\r
+    }\r
+    \r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(clazz == adapter) // There is no resource for this node..\r
+            return null;\r
+        return super.getAdapter(adapter);\r
+    }\r
+    \r
+       @Override\r
+       public void drop(Object data) {\r
+               final Resource[] resources = ResourceAdaptionUtils.toResources(data);\r
+               final Resource library = this.data;\r
+               if(resources.length > 0) {\r
+                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                               \r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       for(Resource tobeMoved : resources) {\r
+                                               if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||\r
+                                                               graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {\r
+                                                       graph.deny(tobeMoved, l0.PartOf);\r
+                                                       graph.claim(tobeMoved, l0.PartOf, library);\r
+                                               }\r
+                                       }\r
+                               }\r
+                       });\r
+               }\r
+       }\r
+       \r
+\r
+
+       \r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/HistoryDataNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/HistoryDataNode.java
new file mode 100644 (file)
index 0000000..196a52e
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class HistoryDataNode extends SimulationResultNode<Resource> {\r
+\r
+    public HistoryDataNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }\r
+        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialCondition.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialCondition.java
new file mode 100644 (file)
index 0000000..dcd937a
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class InitialCondition extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
+\r
+    public InitialCondition(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }    \r
+\r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        Session session = SimanticsUI.getSession();\r
+        return new LabelModifier(session, data, session.getService(Layer0.class).HasName);\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialConditionsFolder.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialConditionsFolder.java
new file mode 100644 (file)
index 0000000..abf40d4
--- /dev/null
@@ -0,0 +1,32 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.ISpecialFolder;\r
+import org.simantics.db.Resource;\r
+\r
+public class InitialConditionsFolder extends AbstractNode<Resource> implements ISpecialFolder {\r
+    \r
+    public InitialConditionsFolder(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(clazz == adapter) // There is no resource for this node..\r
+            return null;\r
+        return super.getAdapter(adapter);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InputNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InputNode.java
new file mode 100644 (file)
index 0000000..ca731e9
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.layer0.variable.Variable;\r
+\r
+public class InputNode  extends VariableNode<Resource> {\r
+\r
+       public InputNode(Resource resource) {\r
+               super(resource);\r
+       }\r
+       \r
+    public InputNode(Variable variable, Resource represents) {\r
+        super(variable, represents);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/Library.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/Library.java
new file mode 100644 (file)
index 0000000..736081e
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class Library extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
+\r
+    public Library(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }    \r
+\r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+       Session session = Simantics.getSession();\r
+       return new LabelModifier(session, data, session.getService(Layer0.class).HasName);\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/LineChartNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/LineChartNode.java
new file mode 100644 (file)
index 0000000..ef2ec49
--- /dev/null
@@ -0,0 +1,76 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.SingleObjectWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Node representing a  line chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class LineChartNode extends AbstractChartNode<Resource> {\r
+\r
+    public LineChartNode(Resource data) {\r
+        super(data);\r
+    }\r
+\r
+    /**\r
+     * Adds a variable to this chart and map it to the first rangeAxis\r
+     * @param variable\r
+     */\r
+    @Override\r
+    protected void addVariableToChart(final Variable variable) {\r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+                Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));\r
+                if(plot == null)\r
+                    return;\r
+\r
+                Resource rangeAxis = null;\r
+                Resource dataset = null;\r
+                Resource rangeAxisList = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
+                if(rangeAxisList == null ||  ListUtils.toList(graph, rangeAxisList).isEmpty()) {\r
+                    // No range axis -> Create a new one\r
+                    rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);\r
+                    Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
+                    dataset = ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);\r
+                } else {\r
+                    rangeAxis = ListUtils.toList(graph, rangeAxisList).get(0);\r
+                    dataset = graph.getPossibleObject(rangeAxis, jfree.Dataset_mapToRangeAxis_Inverse);\r
+                }\r
+                \r
+                // Create the series and attach it to the dataset\r
+                String rvi = Variables.getRVI(graph, variable);\r
+                ChartUtils.createSeries(graph, dataset, rvi);\r
+            }\r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModelNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModelNode.java
new file mode 100644 (file)
index 0000000..660fe18
--- /dev/null
@@ -0,0 +1,139 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.request.Write;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.ModelNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class ModelNode extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {\r
+\r
+       Listener<String> configurationNameSynchronizer;\r
+       private boolean disposed = false;\r
+       \r
+    public ModelNode(Resource resource) {\r
+        super(resource);\r
+               \r
+        // Not the best solution for name sync\r
+        configurationNameSynchronizer = new Listener<String>() {\r
+\r
+               @Override\r
+                       public void execute(final String result) {\r
+                               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                                       \r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               SimulationResource sim = SimulationResource.getInstance(graph);\r
+                                               Resource configuration = graph.getPossibleObject(data, sim.HasConfiguration);\r
+                                               graph.claimLiteral(configuration, l0.HasLabel, result);\r
+                                       }\r
+                               });\r
+                       }\r
+\r
+                       @Override\r
+                       public void exception(Throwable t) {\r
+                               t.printStackTrace();\r
+                       }\r
+\r
+                       @Override\r
+                       public boolean isDisposed() {\r
+                               return disposed;\r
+                       }\r
+               };\r
+               \r
+        SimanticsUI.getSession().asyncRequest(new Read<String>() {\r
+\r
+                       @Override\r
+                       public String perform(ReadGraph graph) throws DatabaseException {\r
+                               return graph.getPossibleRelatedValue(data, Layer0.getInstance(graph).HasLabel);\r
+                       }\r
+               \r
+        }, configurationNameSynchronizer);\r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data) {\r
+            @Override\r
+            public String isValid(String label) {\r
+                if (!new ModelNameValidator().isValid(data, label))\r
+                    return "Not valid";\r
+                else\r
+                    return null;\r
+            }\r
+            \r
+            @Override\r
+            protected Write getWriteRequest(final String label) {\r
+                return new WriteRequest() {\r
+                    @Override\r
+                    public void perform(WriteGraph g) throws DatabaseException {\r
+                       Layer0 l0 = Layer0.getInstance(g);\r
+                        g.claimLiteral(data, l0.HasLabel, label);\r
+                        String safeName = NameUtils.findFreshName(g, label, g.getSingleObject(data, l0.PartOf), l0.ConsistsOf, "%s%d");\r
+                        g.claimLiteral(data, l0.HasName, safeName);\r
+                    }\r
+                };\r
+            }\r
+        };\r
+        return modifier;\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+       disposed = true;\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                       Layer0 l0 = Layer0.getInstance(graph);\r
+                       \r
+                    for(Resource r : graph.getObjects(data, l0.ConsistsOf))\r
+                        if(graph.isInstanceOf(r, SysdynResource.getInstance(graph).Result))\r
+                            SimulationResultNode.deleteResultFiles(graph, r);\r
+\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }\r
+        \r
+    }\r
+\r
+       @Override\r
+       public boolean handleDoubleClick() {\r
+               return false;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleNode.java
new file mode 100644 (file)
index 0000000..297124a
--- /dev/null
@@ -0,0 +1,114 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.PasteHandler;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ModuleNode extends ConfigurationNode<Resource> implements IModifiableNode {\r
+\r
+       Resource configuration;\r
+       \r
+       public ModuleNode(Resource resource) {\r
+               super(resource);\r
+               \r
+\r
+        SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                       Resource type =  graph.getPossibleObject(data, Layer0.getInstance(graph).InstanceOf);\r
+                       configuration = graph.getPossibleObject(type, StructuralResource2.getInstance(graph).IsDefinedBy);                              \r
+                       }\r
+               });\r
+       }\r
+       \r
+    public ModuleNode(Variable variable, Resource represents) {\r
+        super(variable, represents);\r
+        \r
+        SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                       Resource type =  graph.getPossibleObject(data, Layer0.getInstance(graph).InstanceOf);\r
+                       configuration = graph.getPossibleObject(type, StructuralResource2.getInstance(graph).IsDefinedBy);                              \r
+                       }\r
+               });\r
+    }\r
+    \r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(PasteHandler.class == adapter && configuration != null) \r
+            return new DefaultPasteHandler(configuration);\r
+        return super.getAdapter(adapter);\r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        try {\r
+            final Session session = SimanticsUI.getSession();\r
+            Resource hasName = Layer0.getInstance(session).HasName;\r
+            LabelModifier modifier = new LabelModifier(session, data, hasName) {\r
+                @Override\r
+                public String isValid(String label) {\r
+                    if (!new VariableNameValidator().isValid(data, label))\r
+                        return "Not valid";\r
+                    else\r
+                        return null;\r
+                }\r
+                \r
+                @Override\r
+                public void modify(final String label) {\r
+                    try {\r
+                                       session.syncRequest(new WriteRequest() {\r
+                                               @Override\r
+                                               public void perform(WriteGraph graph)\r
+                                                               throws DatabaseException {\r
+\r
+                                               String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);\r
+                                               if(!originalName.equals(label)) {\r
+                                                   Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);\r
+                                                   new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);\r
+                                                       graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);\r
+                                               }\r
+                                               }\r
+                                       });\r
+                               } catch (DatabaseException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+\r
+                       super.modify(label);\r
+                }\r
+            };\r
+            return modifier;\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return null;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleTypeNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleTypeNode.java
new file mode 100644 (file)
index 0000000..6d77344
--- /dev/null
@@ -0,0 +1,208 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import java.util.Collection;\r
+\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.layer0.adapter.PasteHandler;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.issues.ontology.IssueResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.ui.utils.ModuleTypeNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ModuleTypeNode extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
+\r
+       \r
+       Listener<String> configurationNameSynchronizer;\r
+       private boolean disposed = false;\r
+       private Resource configuration;\r
+       \r
+    public ModuleTypeNode(Resource resource) {\r
+        super(resource);\r
+\r
+        SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                       ModelingResources mr = ModelingResources.getInstance(graph);\r
+                       StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+                       Resource type =  graph.getPossibleObject(data, mr.SymbolToComponentType);\r
+                       configuration = graph.getPossibleObject(type, sr2.IsDefinedBy);                         \r
+                       }\r
+               });\r
+        \r
+        // Not the best solution for name sync\r
+        configurationNameSynchronizer = new Listener<String>() {\r
+\r
+               @Override\r
+                       public void execute(final String result) {\r
+                   if(result == null)\r
+                       return; \r
+                   \r
+                               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                                       \r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               if(configuration != null)\r
+                                                       graph.claimLiteral(configuration, Layer0.getInstance(graph).HasLabel, result);\r
+                                       }\r
+                               });\r
+                       }\r
+\r
+                       @Override\r
+                       public void exception(Throwable t) {\r
+                               t.printStackTrace();\r
+                       }\r
+\r
+                       @Override\r
+                       public boolean isDisposed() {\r
+                               return disposed;\r
+                       }\r
+               };\r
+               \r
+        SimanticsUI.getSession().asyncRequest(new Read<String>() {\r
+\r
+                       @Override\r
+                       public String perform(ReadGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                ModelingResources mr = ModelingResources.getInstance(graph);\r
+                Resource type =  graph.getPossibleObject(data, mr.SymbolToComponentType);\r
+                               return (String) (type != null ? graph.getRelatedValue(type, l0.HasName) : null);\r
+                       }\r
+               \r
+        }, configurationNameSynchronizer);\r
+        \r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        Modifier modifier = null;\r
+        try {\r
+            modifier = SimanticsUI.getSession().syncRequest(new Read<Modifier>() {\r
+\r
+                @Override\r
+                public Modifier perform(ReadGraph graph) throws ManyObjectsForFunctionalRelationException, ServiceException {\r
+                    ModelingResources mr = ModelingResources.getInstance(graph);\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    Resource type =  graph.getPossibleObject(data, mr.SymbolToComponentType);\r
+\r
+                    LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), type, l0.HasName) {\r
+                        @Override\r
+                        public String isValid(String label) {\r
+                            if (!new ModuleTypeNameValidator().isValid(data, label))\r
+                                return "Not valid";\r
+                            else\r
+                                return null;\r
+                        }\r
+                    };\r
+\r
+\r
+                    return modifier;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        return modifier;\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+       disposed = true;\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException{\r
+                       Layer0 l0 = Layer0.getInstance(graph);\r
+                    StructuralResource2 st = StructuralResource2.getInstance(graph);\r
+                    ModelingResources mr = ModelingResources.getInstance(graph);\r
+\r
+                    Resource type =  graph.getPossibleObject(data, mr.SymbolToComponentType);\r
+                    Resource model = graph.getSingleObject(type, l0.PartOf);\r
+                    Resource modelConfiguration = graph.getSingleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+                    if (!graph.syncRequest(new ObjectsWithType(modelConfiguration, l0.ConsistsOf, type)).isEmpty()) {\r
+                        throw new ModuleDeleteException("The module is used at the model configuration");\r
+                    }\r
+                    Collection<Resource> moduleTypes = graph.syncRequest(new ObjectsWithType(model, l0.ConsistsOf, st.ComponentType));\r
+                    for(Resource r : moduleTypes) {\r
+                        Resource configuration = graph.getPossibleObject(r, st.IsDefinedBy);\r
+                        if(configuration != null && !graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, type)).isEmpty()) {\r
+                            throw new ModuleDeleteException("The module is used at another module: " + graph.getRelatedValue(r, l0.HasName));\r
+                        }\r
+                    }\r
+                    \r
+                    IssueResource ISSUE = IssueResource.getInstance(graph);\r
+                    // Remove issues\r
+                    for(Resource issueSource : graph.syncRequest(new ObjectsWithType(type, l0.ConsistsOf, ISSUE.Sources_DependencyTracker))) {\r
+                        for(Resource issue : graph.syncRequest(new ObjectsWithType(issueSource, ISSUE.IssueSource_Manages, ISSUE.Issue))) {\r
+                            RemoverUtil.remove(graph, issue);\r
+                        }\r
+                    }\r
+                    RemoverUtil.remove(graph, type);\r
+                }\r
+            });\r
+        } catch (ModuleDeleteException e) {\r
+            Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
+            MessageDialog dialog = new MessageDialog(shell, "Unable to delete", null, e.message, SWT.ERROR,\r
+                    new String[] { "OK" }, 0);\r
+            dialog.create();\r
+            dialog.open();\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    private class ModuleDeleteException extends DatabaseException {\r
+        private static final long serialVersionUID = 4076002781765246919L;\r
+        String message;\r
+        \r
+        public ModuleDeleteException(String message) {\r
+            this.message = message;\r
+        }\r
+    }\r
+    \r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(PasteHandler.class == adapter && configuration != null) \r
+            return new DefaultPasteHandler(configuration);\r
+        return super.getAdapter(adapter);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModulesNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModulesNode.java
new file mode 100644 (file)
index 0000000..faf9fae
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+\r
+public class ModulesNode extends AbstractNode<Resource> {\r
+    \r
+    public ModulesNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(clazz == adapter) // There is no resource for this node..\r
+            return null;\r
+        return super.getAdapter(adapter);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/OperatingInterfacesFolder.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/OperatingInterfacesFolder.java
new file mode 100644 (file)
index 0000000..ce15295
--- /dev/null
@@ -0,0 +1,23 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+\r
+public class OperatingInterfacesFolder extends AbstractNode<Resource> {\r
+\r
+    public OperatingInterfacesFolder(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/PieChartNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/PieChartNode.java
new file mode 100644 (file)
index 0000000..776cbdb
--- /dev/null
@@ -0,0 +1,68 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.SingleObjectWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Node for pie charts\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PieChartNode extends AbstractChartNode<Resource> {\r
+\r
+    public PieChartNode(Resource data) {\r
+        super(data);\r
+    }\r
+\r
+    /**\r
+     * Adds a variable to this chart\r
+     * @param variable\r
+     */\r
+    @Override\r
+    protected void addVariableToChart(final Variable variable) {\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+                Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));\r
+                if(plot == null)\r
+                    return;\r
+\r
+                Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
+                \r
+                if(dataset == null)\r
+                    return;\r
+                \r
+                // Create the series and attach it to the dataset\r
+                String rvi = Variables.getRVI(graph, variable);\r
+                Resource series = ChartUtils.createSeries(graph, dataset, rvi);\r
+                graph.claimLiteral(series, jfree.Series_exploded, false);\r
+            }\r
+        });        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java
new file mode 100644 (file)
index 0000000..70815ee
--- /dev/null
@@ -0,0 +1,57 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class SCLModule extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
+\r
+    public SCLModule(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }    \r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        Session session = SimanticsUI.getSession();\r
+        return new LabelModifier(session, data, session.getService(Layer0.class).HasName);\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModulesFolder.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModulesFolder.java
new file mode 100644 (file)
index 0000000..425a602
--- /dev/null
@@ -0,0 +1,32 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.ISpecialFolder;\r
+import org.simantics.db.Resource;\r
+\r
+public class SCLModulesFolder extends AbstractNode<Resource> implements ISpecialFolder {\r
+    \r
+    public SCLModulesFolder(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(clazz == adapter) // There is no resource for this node..\r
+            return null;\r
+        return super.getAdapter(adapter);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SensitivityChartNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SensitivityChartNode.java
new file mode 100644 (file)
index 0000000..026330c
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.layer0.variable.Variable;\r
+\r
+public class SensitivityChartNode extends AbstractChartNode<Resource> {\r
+\r
+    public SensitivityChartNode(Resource data) {\r
+        super(data);\r
+    }\r
+\r
+    @Override\r
+    protected void addVariableToChart(Variable variable) {\r
+        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedFunctionLibraryNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedFunctionLibraryNode.java
new file mode 100644 (file)
index 0000000..e2269eb
--- /dev/null
@@ -0,0 +1,94 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.SharedFunctionLibraryNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+public class SharedFunctionLibraryNode extends FunctionLibraryNode<Resource> implements IDropTargetNode {\r
+\r
+    public SharedFunctionLibraryNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+       @Override\r
+       public void delete() throws DeleteException {\r
+               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               \r
+                               graph.deny(data, l0.PartOf);\r
+                               graph.deny(data, l0.IsLinkedTo_Inverse);\r
+\r
+                               // TODO: remove file\r
+                       }\r
+               });\r
+       }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        try {\r
+            Resource hasName = Layer0.getInstance(SimanticsUI.getSession()).HasName;\r
+            LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data, hasName) {\r
+                @Override\r
+                public String isValid(String label) {\r
+                    if (!new SharedFunctionLibraryNameValidator().isValid(data, label))\r
+                        return "Not valid";\r
+                    else\r
+                        return null;\r
+                }\r
+            };\r
+            return modifier;\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return null;\r
+    }\r
+       \r
+       @Override\r
+       public void drop(Object data) {\r
+               final Resource[] resources = ResourceAdaptionUtils.toResources(data);\r
+               final Resource library = this.data;\r
+               if(resources.length > 0) {\r
+                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                               \r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       for(Resource tobeMoved : resources) {\r
+                                               if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||\r
+                                                               graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {\r
+                                                       graph.deny(tobeMoved, l0.PartOf);\r
+                                                       graph.claim(tobeMoved, l0.PartOf, library);\r
+                                               }\r
+                                       }\r
+                                       \r
+                               }\r
+                       });\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedFunctionsFolder.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedFunctionsFolder.java
new file mode 100644 (file)
index 0000000..0531fd9
--- /dev/null
@@ -0,0 +1,30 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+\r
+public class SharedFunctionsFolder extends AbstractNode<Resource> {\r
+\r
+       public SharedFunctionsFolder(Resource data) {\r
+               super(data);\r
+       }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(clazz == adapter) // There is no resource for this node..\r
+            return null;\r
+        return super.getAdapter(adapter);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedOntologyNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SharedOntologyNode.java
new file mode 100644 (file)
index 0000000..6e6d595
--- /dev/null
@@ -0,0 +1,42 @@
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class SharedOntologyNode extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
+\r
+    public SharedOntologyNode(Resource data) {\r
+        super(data);\r
+    }\r
+    \r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    RemoverUtil.remove(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }    \r
+    }\r
+\r
+       @Override\r
+       public Modifier getModifier(String columnId) {\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SheetNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SheetNode.java
new file mode 100644 (file)
index 0000000..39fdb22
--- /dev/null
@@ -0,0 +1,83 @@
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.eclipse.ui.PartInitException;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.RVI;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.utils.SheetNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.workbench.ResourceEditorInput2;\r
+import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
+\r
+public class SheetNode extends AbstractNode<Resource> implements IModifiableNode, IDoubleClickableNode {\r
+\r
+    public SheetNode(Resource data) {\r
+        super(data);\r
+    }\r
+    \r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        \r
+        Session session = SimanticsUI.getSession();\r
+        LabelModifier modifier = new LabelModifier(session, data, session.getService(Layer0.class).HasName) {\r
+            @Override\r
+            public String isValid(String label) {\r
+                if (!new SheetNameValidator().isValid(data, label))\r
+                    return "Not valid";\r
+                else\r
+                    return null;\r
+            }\r
+        };\r
+        return modifier;\r
+    }\r
+\r
+    @Override\r
+    public boolean handleDoubleClick() {\r
+        \r
+        try {\r
+            \r
+            SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+\r
+                    Variable variable = graph.adapt(data, Variable.class);\r
+                    final Resource model = Variables.getModel(graph, variable);\r
+                    final RVI rvi = variable.getRVI(graph);\r
+\r
+                    PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+                        \r
+                        private static final String EDITOR_ID = "org.simantics.spreadsheet.ui.editor2";\r
+                        \r
+                        @Override\r
+                        public void run() {\r
+                            try {\r
+                                System.out.println("Activating sheet: model=" + model + " rvi=" + rvi);\r
+                                WorkbenchUtils.openEditor(EDITOR_ID, new ResourceEditorInput2(EDITOR_ID, data, model, rvi));\r
+                            } catch (PartInitException e) {\r
+                                e.printStackTrace();\r
+                            }\r
+                        }\r
+                    });\r
+                }\r
+            });\r
+        } catch (Exception e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        return true;\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultNode.java
new file mode 100644 (file)
index 0000000..bc9c4a3
--- /dev/null
@@ -0,0 +1,95 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import java.io.File;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.handlers.ToggleResultActivation;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class SimulationResultNode<T>  extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {\r
+\r
+    public SimulationResultNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+    \r
+    \r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data) {\r
+            @Override\r
+            public String isValid(String label) {\r
+                if (label.isEmpty())\r
+                    return "Empty label not allowed";\r
+                return null;\r
+            }\r
+        };\r
+        return modifier;\r
+    }\r
+\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    unlinkResult(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }\r
+        \r
+    }\r
+    \r
+    \r
+    public static void unlinkResult(WriteGraph graph, Resource result) throws DatabaseException  {\r
+        deleteResultFiles(graph, result);\r
+        RemoverUtil.remove(graph, result);\r
+    }\r
+    \r
+    public static void deleteResultFiles(WriteGraph graph, Resource result) throws DatabaseException  {\r
+        String path;\r
+        path = graph.getPossibleRelatedValue(result, SysdynResource.getInstance(graph).Result_resultFile);\r
+        if(path != null) {\r
+            File file = new File(path);\r
+            file.delete();\r
+            File parent = file.getParentFile();\r
+            if(parent.listFiles() != null && parent.listFiles().length == 0)\r
+                parent.delete();\r
+        }\r
+    }\r
+\r
+\r
+       @Override\r
+       public boolean handleDoubleClick() {\r
+               Resource[] resources = {data};\r
+               ToggleResultActivation.toggleActivation(resources);\r
+               return true;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultSetNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultSetNode.java
new file mode 100644 (file)
index 0000000..194e1c9
--- /dev/null
@@ -0,0 +1,84 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.handlers.ToggleResultSetActivation;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class SimulationResultSetNode  extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {\r
+\r
+    public SimulationResultSetNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+    \r
+    \r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data) {\r
+            @Override\r
+            public String isValid(String label) {\r
+                if (label.isEmpty())\r
+                    return "Empty label not allowed";\r
+                return null;\r
+            }\r
+        };\r
+        return modifier;\r
+    }\r
+\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                                       unlinkResultSet(graph, data);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }\r
+        \r
+    }\r
+    \r
+    \r
+    public static void unlinkResultSet(WriteGraph graph, Resource resultSet) throws DatabaseException  {\r
+       SysdynResource sr = SysdynResource.getInstance(graph);\r
+       for (Resource result : graph.syncRequest(new ObjectsWithType(resultSet, sr.Experiment_result, sr.Result))) {\r
+                       SimulationResultNode.unlinkResult(graph, result);\r
+       }\r
+        RemoverUtil.remove(graph, resultSet);\r
+    }\r
+\r
+       @Override\r
+       public boolean handleDoubleClick() {\r
+               Resource[] resources = {data};\r
+               ToggleResultSetActivation.toggleActivation(resources);\r
+               return true;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SymbolNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SymbolNode.java
new file mode 100644 (file)
index 0000000..4345615
--- /dev/null
@@ -0,0 +1,23 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.IDeletable;\r
+import org.simantics.db.Resource;\r
+\r
+public class SymbolNode extends AbstractNode<Resource> implements IDeletable {\r
+\r
+    public SymbolNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/VariableNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/VariableNode.java
new file mode 100644 (file)
index 0000000..fdfcb13
--- /dev/null
@@ -0,0 +1,88 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.browser.nodes;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class VariableNode<T> extends AbstractNode<Resource> implements IModifiableNode {\r
+\r
+       Variable variable;\r
+\r
+       public VariableNode(Resource resource) {\r
+               super(resource);\r
+       }\r
+\r
+       public VariableNode(Variable variable, Resource represents) {\r
+               super(represents);\r
+               this.variable = variable;\r
+       }\r
+\r
+       public Variable getVariable() {\r
+               return variable;\r
+       }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        try {\r
+            final Session session = SimanticsUI.getSession();\r
+            Resource hasName = Layer0.getInstance(session).HasName;\r
+            LabelModifier modifier = new LabelModifier(session, data, hasName) {\r
+                @Override\r
+                public String isValid(String label) {\r
+                    if (!new VariableNameValidator().isValid(data, label))\r
+                        return "Not valid";\r
+                    else\r
+                        return null;\r
+                }\r
+                \r
+                @Override\r
+                public void modify(final String label) {\r
+                    try {\r
+                                       session.syncRequest(new WriteRequest() {\r
+                                               @Override\r
+                                               public void perform(WriteGraph graph)\r
+                                                               throws DatabaseException {\r
+\r
+                                               String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);\r
+                                               if(!originalName.equals(label)) {\r
+                                                   Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);\r
+                                                   new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);\r
+                                                       graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);\r
+                                               }\r
+                                               }\r
+                                       });\r
+                               } catch (DatabaseException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+\r
+                       super.modify(label);\r
+                }\r
+            };\r
+            return modifier;\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return null;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/DiagramToCompositeMapping3.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/DiagramToCompositeMapping3.java
new file mode 100644 (file)
index 0000000..240874f
--- /dev/null
@@ -0,0 +1,129 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.utils.binaryPredicates.InversePredicate;\r
+import org.simantics.layer0.utils.binaryPredicates.OrderedSetElementsPredicate;\r
+import org.simantics.mapping.constraint.instructions.IInstruction;\r
+import org.simantics.mapping.constraint.instructions.TypedBracketInstruction.CreationInstruction;\r
+import org.simantics.mapping.rule.instructions.IRuleInstruction;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class DiagramToCompositeMapping3 extends org.simantics.modeling.mapping.DiagramToCompositeMapping3 {\r
+\r
+    private SysdynResource sdr;\r
+\r
+    public DiagramToCompositeMapping3(ReadGraph g, Resource mapping)\r
+    throws DatabaseException {\r
+        super(g, mapping);\r
+    }\r
+\r
+    @Override\r
+    protected void setup(ReadGraph graph) {\r
+        sdr = SysdynResource.getInstance(graph);\r
+    }\r
+\r
+    @Override\r
+    protected Resource getConfigurationConnectionType() {\r
+        return sdr.DependencyConnection;\r
+    }\r
+\r
+    @Override\r
+    public CreationInstruction componentCreationInstruction(int component, int componentType, int configuration) {\r
+        return new SysdynCreationInstruction(project, configurationRoot, component, componentType, configuration);\r
+    }\r
+\r
+    @Override\r
+    protected IRuleInstruction additiveRule() {\r
+        return \r
+        \r
+        if_(bf(OrderedSetElementsPredicate.INSTANCE, Diagram, Element),\r
+                query(\r
+                    if_(and(bf(L0.InstanceOf, Element, ElementType),\r
+                               bf(MOD.SymbolToComponentType, ElementType, ComponentType)\r
+                        ),\r
+                        // If element type of the element has a corresponding component type\r
+                        createComponentRule(),\r
+                    \r
+                        if_(and(b(DIA.Connection, Element), bf(L0.InstanceOf, Element, ElementType), bf(MOD.DiagramConnectionTypeToConnectionType, ElementType, ComponentType)),\r
+                                createNormalConnectionRule(),\r
+\r
+                                if_(b(DIA.Flag, Element),\r
+                                        createFlagRule()\r
+                                )\r
+                        )\r
+                    )\r
+                )\r
+            );\r
+    }\r
+\r
+    @Override\r
+    protected IRuleInstruction destructiveRule() {\r
+        return\r
+        if_(and(bf(L0.ConsistsOf, Configuration, Component),\r
+                b(mapped, Component) // handle only mapped components\r
+        ),\r
+        query(\r
+                if_(and(bf(MOD.ComponentToElement, Component, Element),\r
+                        bf(new InversePredicate(OrderedSetElementsPredicate.INSTANCE), Element, Diagram)\r
+                ),\r
+                // If component has a corresponding element in the diagram\r
+                if_(and(statement_bff(Component, ConnectionRelation, Connection, STR.IsConnectedTo),\r
+                        b(mapped, Connection)\r
+                ),\r
+                // If component has a mapped connection\r
+                unless(\r
+                        bf(MOD.ConnectionToDiagramConnection, Connection, DiagramConnectionRelation),\r
+                        // If the configuration connection does not have a correspondence in the diagram remove it\r
+                        and(deny(exists(Connection)))\r
+                )\r
+                ),\r
+\r
+                unless(\r
+                        bf(MOD.ConnectionToDiagramConnection, Component, Element),\r
+                        // If the configuration connection does not have a correspondence in the diagram remove it\r
+                        and(deny(exists(Component)))\r
+                )\r
+\r
+                )\r
+        )\r
+        );\r
+    }\r
+\r
+    @Override\r
+    protected IInstruction claimBasicConnection() {\r
+        return and(exists(\r
+                bf(MOD.DiagramConnectionToConnection, Element, Connection),\r
+                Connection\r
+        ),\r
+        bb(L0.InstanceOf, Connection, ComponentType),\r
+        bb(L0.PartOf, Connection, Configuration),\r
+        b(mapped, Connection)\r
+\r
+        );\r
+    }\r
+    \r
+//    @Override\r
+//    protected IInstruction claimBasicConnection() {\r
+//        return and(exists(\r
+//                bf(MOD.DiagramConnectionToConnection, Element, Connection),\r
+//                Connection\r
+//        ),\r
+//        bb(L0.InstanceOf, Connection, ComponentType),\r
+//        b(mapped, Connection),\r
+//        bb(L0.PartOf, Connection, Configuration)\r
+//        );\r
+//    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/DiagramViewer.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/DiagramViewer.java
new file mode 100644 (file)
index 0000000..c1bbf18
--- /dev/null
@@ -0,0 +1,208 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor;\r
+\r
+import java.awt.dnd.DnDConstants;\r
+import java.util.Collections;\r
+import java.util.Set;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchPartSite;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Session;\r
+import org.simantics.diagram.handler.DeleteHandler;\r
+import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;\r
+import org.simantics.diagram.synchronization.SynchronizationHints;\r
+import org.simantics.g2d.canvas.Hints;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.canvas.impl.CanvasContext;\r
+import org.simantics.g2d.connection.IConnectionAdvisor;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.handler.PickRequest;\r
+import org.simantics.g2d.diagram.participant.DiagramParticipant;\r
+import org.simantics.g2d.diagram.participant.ElementInteractor;\r
+import org.simantics.g2d.diagram.participant.ElementPainter;\r
+import org.simantics.g2d.diagram.participant.Selection;\r
+import org.simantics.g2d.diagram.participant.ZOrderHandler;\r
+import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementClasses;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.IElementClassProvider;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.participant.GridPainter;\r
+import org.simantics.g2d.participant.RulerPainter;\r
+import org.simantics.g2d.tooltip.TerminalTooltipParticipant;\r
+import org.simantics.jfreechart.chart.element.PopulateChartDropParticipant;\r
+import org.simantics.modeling.mapping.ElementCopyAdvisor;\r
+import org.simantics.modeling.mapping.MappedElementCopyAdvisor;\r
+import org.simantics.modeling.ui.diagramEditor.handlers.LinkBrowsingHandler;\r
+import org.simantics.structural2.modelingRules.IModelingRules;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.editor.participant.CreateVariablesShortcutParticipant;\r
+import org.simantics.sysdyn.ui.editor.participant.SelectionUpdaterParticipant;\r
+import org.simantics.sysdyn.ui.editor.participant.SysdynComponentCopyAdvisor;\r
+import org.simantics.sysdyn.ui.editor.participant.SysdynElementClassProviders;\r
+import org.simantics.sysdyn.ui.editor.participant.SysdynPopulateElementDropParticipant;\r
+import org.simantics.sysdyn.ui.elements.CloudFactory;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementClasses;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementFactory;\r
+import org.simantics.sysdyn.ui.elements.connections.ConnectionClasses;\r
+import org.simantics.sysdyn.ui.elements.connections.RouteFlowEdgeClass;\r
+import org.simantics.sysdyn.ui.elements.connections.SysdynConnectionClass;\r
+import org.simantics.sysdyn.ui.handlers.ExtendedCopyPasteHandler;\r
+import org.simantics.sysdyn.ui.properties.SysdynPropertyPage;\r
+import org.simantics.ui.workbench.IPropertyPage;\r
+import org.simantics.utils.datastructures.hints.IHintContext;\r
+import org.simantics.utils.threads.AWTThread;\r
+import org.simantics.utils.threads.ThreadUtils;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class DiagramViewer extends org.simantics.modeling.ui.diagramEditor.DiagramViewer {\r
+\r
+       protected String getPopupId() {\r
+               return "#SysdynDiagramPopup";\r
+       }\r
+\r
+       @Override\r
+       public void createPartControl(Composite parent) {\r
+               super.createPartControl(parent);\r
+       } \r
+\r
+       @Override\r
+       protected Set<String> getPropertyPageContexts() {\r
+               return Collections.singleton(SysdynResource.URIs.Browser);\r
+       }\r
+\r
+       @Override\r
+       protected IPropertyPage createPropertyPage(IWorkbenchPartSite site, Set<String> contexts) {\r
+               return new SysdynPropertyPage(site, contexts);\r
+       }\r
+\r
+       @Override\r
+       protected IElementClassProvider createElementClassProvider(ReadGraph graph) {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               ElementClass dependencyClass = SysdynConnectionClass.CLASS.newClassWith(new StaticObjectAdapter(sr.DependencyConnection));\r
+               ElementClass flowClass = RouteFlowEdgeClass.FLOW_CLASS.newClassWith(new StaticObjectAdapter(sr.FlowConnection));\r
+               return SysdynElementClassProviders.mappedProvider(\r
+                               ElementClasses.CONNECTION, dependencyClass,\r
+                               ElementClasses.FLAG, CloudFactory.createElementClass(sr.CloudSymbol, SysdynElementFactory.createTerminals(graph, sr.CloudSymbol)),\r
+                               ConnectionClasses.FLOW, flowClass,\r
+                               ConnectionClasses.DEPENDENCY, dependencyClass,\r
+                               SysdynElementClasses.VALVE,  CloudFactory.createElementClass(sr.ValveSymbol, SysdynElementFactory.createTerminals(graph, sr.ValveSymbol))\r
+               );\r
+\r
+\r
+       }\r
+       \r
+       @Override\r
+    public void initializeCanvasContext(CanvasContext ctx) {\r
+       super.initializeCanvasContext(ctx);\r
+       // GRID and RULER have to be set here. They cause deadlocks in Show Module if set in onCreated()\r
+               IHintContext h = ctx.getDefaultHintContext();\r
+               h.setHint(GridPainter.KEY_GRID_ENABLED, Boolean.FALSE);\r
+               h.setHint(RulerPainter.KEY_RULER_ENABLED, Boolean.FALSE);\r
+               h.setHint(Hints.KEY_DISPLAY_MARGINS, Boolean.FALSE);\r
+               h.setHint(Hints.KEY_DISPLAY_PAGE, Boolean.FALSE);\r
+    }\r
+\r
+       @Override\r
+       protected void onCreated() {\r
+           sourceDiagram.setHint(DiagramHints.KEY_ALLOW_ROUTE_POINTS, Boolean.FALSE);\r
+           sourceDiagram.setHint(SynchronizationHints.COPY_ADVISOR, new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new SysdynComponentCopyAdvisor()));\r
+\r
+           ThreadUtils.asyncExec(AWTThread.getThreadAccess(), new Runnable() { \r
+\r
+               @Override\r
+               public void run() {\r
+                   if (isDisposed())  {\r
+                       return; \r
+                   } else {\r
+                       if(canvasContext != null && sourceDiagram != null) {\r
+                           ElementPainter ep = canvasContext.getSingleItem(ElementPainter.class);\r
+                           for(IElement e : sourceDiagram.getElements()) {\r
+                               if(e.getElementClass().getId().contains("Connection")){\r
+                                   ep.update(e);\r
+                               }\r
+                           }\r
+                       }\r
+                   }\r
+               }\r
+           });\r
+       }\r
+\r
+       @Override\r
+       protected void addKeyBindingParticipants(CanvasContext ctx) {\r
+               ctx.add(new DeleteHandler(getEditorSite().getActionBars().getStatusLineManager()));\r
+               ctx.add(new CreateVariablesShortcutParticipant(synchronizer));\r
+               ctx.add(new ExtendedCopyPasteHandler(getEditorSite().getActionBars().getStatusLineManager()).setWorkbenchSite(getEditorSite()));\r
+       }\r
+\r
+       @Override\r
+       protected void initializeSynchronizationContext(ReadGraph graph, IModifiableSynchronizationContext context) {\r
+               super.initializeSynchronizationContext(graph, context);\r
+\r
+               // Make sure SysdynResource is available.\r
+               SysdynResource.getInstance(graph);\r
+       }\r
+\r
+       @Override\r
+       protected void addStructureParticipants(ICanvasContext ctx) {\r
+        addWorkbenchSelectionProvider(ctx);\r
+\r
+               // Add visual browsing capabilities for structural models\r
+\r
+               //        Remove double click handler, because it is not working properly\r
+               //        ctx.add(new StructuralBrowsingHandler(getSite(), sessionContext, getResourceInput2()));\r
+               ctx.add(new LinkBrowsingHandler(getSite(), this, sessionContext));\r
+\r
+       }\r
+       \r
+    protected void addDropParticipants(ICanvasContext ctx) {\r
+        ctx.getDefaultHintContext().setHint(Hints.KEY_ALLOWED_DRAG_ACTIONS, DnDConstants.ACTION_COPY);\r
+\r
+        ctx.add(new SysdynPopulateElementDropParticipant(synchronizer));\r
+        ctx.add(new PopulateChartDropParticipant(synchronizer));\r
+    }\r
+\r
+       @Override\r
+       protected void addOtherParticipants(CanvasContext ctx) {\r
+           ctx.add(new SelectionUpdaterParticipant());\r
+       }\r
+\r
+       @Override \r
+       protected PointerInteractor getPointerInteractor() {\r
+               return new org.simantics.sysdyn.ui.editor.participant.SysdynPointerInteractor(true, true, true, false, true, false, synchronizer.getElementClassProvider(), PickRequest.PickSorter.CONNECTIONS_FIRST);\r
+       }\r
+\r
+       @Override\r
+       protected IConnectionAdvisor getConnectionAdvisor(IModelingRules modelingRules, Session session) {\r
+               return new SysdynConnectionAdvisor(modelingRules, sessionContext.getSession());\r
+       }\r
+\r
+       @Override\r
+    protected void addDiagramParticipants(ICanvasContext ctx) {\r
+        ctx.add(new ZOrderHandler());\r
+        ctx.add(getPointerInteractor());\r
+        ctx.add(new ElementInteractor(PickRequest.PickSorter.CONNECTIONS_FIRST));\r
+        ctx.add(new Selection());\r
+        ctx.add(new DiagramParticipant());\r
+        ctx.add(new ElementPainter());\r
+        //ctx.add(new ElementHeartbeater());\r
+        //ctx.add(new ZoomTransitionParticipant(TransitionFunction.SIGMOID));\r
+        //ctx.add(new TooltipParticipant());\r
+        ctx.add(new TerminalTooltipParticipant());\r
+    }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromComponentAdapter.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromComponentAdapter.java
new file mode 100644 (file)
index 0000000..fb89ccc
--- /dev/null
@@ -0,0 +1,204 @@
+package org.simantics.sysdyn.ui.editor;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.ui.IEditorPart;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.db.layer0.variable.RVI;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.diagram.content.ConnectionUtil;\r
+import org.simantics.diagram.flag.FlagUtil;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ComponentUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.actions.NavigateToTarget;\r
+import org.simantics.modeling.ui.Activator;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.ui.workbench.editor.AbstractResourceEditorAdapter;\r
+import org.simantics.utils.datastructures.Callback;\r
+import org.simantics.utils.threads.SWTThread;\r
+import org.simantics.utils.threads.ThreadUtils;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class OpenDiagramFromComponentAdapter extends AbstractResourceEditorAdapter {\r
+\r
+    private static final String EDITOR_ID = "org.simantics.sysdyn.ui.diagramViewer";\r
+\r
+    public OpenDiagramFromComponentAdapter() {\r
+        super("Diagram Editor", Activator.COMPOSITE_ICON);\r
+    }\r
+\r
+    @Override\r
+    public boolean canHandle(ReadGraph graph, Object input) throws DatabaseException {\r
+        Resource r = tryGetResource(graph, input);\r
+        if (r == null)\r
+            return false;\r
+        Variable v = AdaptionUtils.adaptToSingle(input, Variable.class);\r
+        Collection<Runnable> rs = tryFindDiagram(graph, r, v);\r
+        return !rs.isEmpty();\r
+    }\r
+\r
+    private Resource tryGetResource(ReadGraph graph, Object input) throws DatabaseException {\r
+        Resource r = ResourceAdaptionUtils.toSingleResource(input);\r
+        if (r == null) {\r
+            Variable v = AdaptionUtils.adaptToSingle(input, Variable.class);\r
+            r = findResource(graph, v);\r
+        }\r
+        return r;\r
+    }\r
+\r
+    private Resource findResource(ReadGraph graph, Variable v) throws DatabaseException {\r
+        while (v != null) {\r
+            Resource r = v.getPossibleRepresents(graph);\r
+            if (r != null)\r
+                return r;\r
+            v = v.browsePossible(graph, ".");\r
+        }\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void openEditor(final Object input) throws Exception {\r
+        final Display d = Display.getCurrent();\r
+        if (d == null)\r
+            return;\r
+\r
+        SimanticsUI.getSession().syncRequest(new ReadRequest() {\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                Resource r = tryGetResource(graph, input);\r
+                if (r == null)\r
+                    return;\r
+\r
+                Variable v = AdaptionUtils.adaptToSingle(input, Variable.class);\r
+\r
+                final Collection<Runnable> rs = tryFindDiagram(graph, r, v);\r
+                if (rs.isEmpty())\r
+                    return;\r
+\r
+                SWTThread.getThreadAccess(d).asyncExec(new Runnable() {\r
+                    @Override\r
+                    public void run() {\r
+                        for (Runnable runnable : rs) {\r
+                            runnable.run();\r
+                        }\r
+                    }\r
+                });\r
+            }\r
+        });\r
+    }\r
+\r
+    private Collection<Runnable> tryFindDiagram(ReadGraph g, Resource module, Variable variable) throws DatabaseException {\r
+        try {\r
+            return findDiagram(g, module, variable);\r
+        } catch (DatabaseException e) {\r
+            return Collections.emptyList();\r
+        }\r
+    }\r
+\r
+    private Collection<Runnable> findDiagram(ReadGraph g, Resource module, Variable variable) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(g);\r
+        SysdynResource SYSDYN = SysdynResource.getInstance(g);\r
+\r
+        if (g.isInstanceOf(module, SYSDYN.IndependentVariable) || g.isInstanceOf(module, SYSDYN.Input) || g.isInstanceOf(module, SYSDYN.Module)) {\r
+            Collection<Runnable> result = new ArrayList<Runnable>(1);\r
+\r
+            Variable moduleVariable = Variables.getVariable(g, module);\r
+            RVI rvi = moduleVariable.getRVI(g);\r
+            \r
+            Resource composite = g.getSingleObject(module, l0.PartOf);\r
+            Resource model = g.syncRequest(new PossibleModel(composite));\r
+\r
+            final Resource diagram = ComponentUtils.getCompositeDiagram(g, composite);\r
+            \r
+//            final ResourceArray compositePath = StructuralVariables.getCompositeArray(g, composite);\r
+//            final ResourceArray variablePath = compositePath.removeFromBeginning(1);\r
+//\r
+//            Resource model = StructuralVariables.getModel(g, compositePath.head());\r
+//            if (model == null)\r
+//                return Collections.emptyList();\r
+//\r
+//            String rvi = StructuralVariables.getRVI(g, variablePath);\r
+//            if (rvi == null)\r
+//                return Collections.emptyList();\r
+\r
+            if (variable != null) {\r
+                // Get proper RVI from variable if it exists.\r
+                Variable context = Variables.getPossibleContext(g, variable);\r
+                if (context != null) {\r
+                    // We want the composite's RVI, not the component in it.\r
+                    Variable parent = variable.getParent(g);\r
+                    if (parent != null) {\r
+                       rvi = parent.getRVI(g);\r
+//                        String contextURI = context.getURI(g);\r
+//                        String parentURI = parent.getURI(g);\r
+//                        rvi = parentURI.replace(contextURI, "");\r
+                       model = Variables.getModel(g, context);\r
+                    }\r
+                }\r
+            }\r
+\r
+            final Collection<Object> selectedObjects = findElementObjects(g, module);\r
+\r
+            result.add(\r
+                    NavigateToTarget.editorActivator(EDITOR_ID, diagram, model, rvi, new Callback<IEditorPart>() {\r
+                        @Override\r
+                        public void run(IEditorPart part) {\r
+                            final ICanvasContext openedCanvas = (ICanvasContext) part.getAdapter(ICanvasContext.class);\r
+                            assert openedCanvas != null;\r
+                            // CanvasContext-wide denial of initial zoom-to-fit on diagram open.\r
+                            openedCanvas.getDefaultHintContext().setHint(DiagramHints.KEY_INITIAL_ZOOM_TO_FIT, Boolean.FALSE);\r
+                            ThreadUtils.asyncExec(openedCanvas.getThreadAccess(),\r
+                                    NavigateToTarget.elementSelectorZoomer(openedCanvas, selectedObjects, false));\r
+                        }\r
+                    }));\r
+            return result;\r
+        }\r
+\r
+        // Nothing to open\r
+        return Collections.emptyList();\r
+    }\r
+\r
+    public static Collection<Object> findElementObjects(ReadGraph g, Resource module) throws DatabaseException {\r
+        DiagramResource DIA = DiagramResource.getInstance(g);\r
+        ModelingResources MOD = ModelingResources.getInstance(g);\r
+        final Collection<Object> selectedObjects = new ArrayList<Object>();\r
+        for (Resource element : g.getObjects(module, MOD.ComponentToElement)) {\r
+            if (g.isInstanceOf(element, DIA.Flag) && FlagUtil.isExternal(g, element)) {\r
+                // Use external flag primarily if one exists in the correspondences\r
+                selectedObjects.clear();\r
+                selectedObjects.add(element);\r
+                break;\r
+            } else if (g.isInstanceOf(element, DIA.RouteGraphConnection)) {\r
+                selectedObjects.add(element);\r
+            } else if (g.isInstanceOf(element, DIA.Connection)) {\r
+                // Okay, we need to find a part of the connection\r
+                ConnectionUtil cu = new ConnectionUtil(g);\r
+                cu.gatherConnectionParts(element, selectedObjects);\r
+            } else {\r
+                selectedObjects.add(element);\r
+            }\r
+        }\r
+        for(Resource element : g.getObjects(module, MOD.HasParentComponent_Inverse)) {\r
+            selectedObjects.add(element);\r
+        }\r
+        return selectedObjects;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromConfigurationAdapter.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromConfigurationAdapter.java
new file mode 100644 (file)
index 0000000..8fe5d1d
--- /dev/null
@@ -0,0 +1,121 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor;\r
+\r
+import org.eclipse.ui.PartInitException;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.ResourceArray;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.modeling.ComponentUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.ui.Activator;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.structural2.StructuralVariables;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.workbench.ResourceEditorInput2;\r
+import org.simantics.ui.workbench.editor.AbstractResourceEditorAdapter;\r
+import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
+\r
+public class OpenDiagramFromConfigurationAdapter extends AbstractResourceEditorAdapter {\r
+\r
+       private static final String EDITOR_ID = "org.simantics.sysdyn.ui.diagramViewer";\r
+\r
+    public OpenDiagramFromConfigurationAdapter() {\r
+        super("Diagram Editor", Activator.COMPOSITE_ICON);\r
+    }\r
+\r
+    protected String getEditorId() {\r
+        return EDITOR_ID;\r
+    }\r
+\r
+    @Override\r
+    public boolean canHandle(ReadGraph g, Resource r) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+               if(g.isInheritedFrom(r, sr.ModuleSymbol)) {\r
+                       ModelingResources mr = ModelingResources.getInstance(g);\r
+                       StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
+                       Resource componentType = g.getSingleObject(r, mr.SymbolToComponentType);\r
+                       r = g.getSingleObject(componentType, sr2.IsDefinedBy);\r
+               }\r
+               Layer0X L0X = Layer0X.getInstance(g);\r
+               Resource represents = g.getPossibleObject(r, L0X.Represents);\r
+               if(represents != null){\r
+                       if(g.isInstanceOf(represents, sr.Configuration)) {\r
+                               r = represents;\r
+                       }\r
+               }\r
+               return ComponentUtils.compositeHasDiagram(g, r) /*|| ComponentUtils.componentHasDiagram(g, r)*/;\r
+    }\r
+\r
+    @Override\r
+    public void openEditor(final Resource r) throws Exception {\r
+\r
+        SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+\r
+            @Override\r
+            public void run(ReadGraph g) throws DatabaseException {\r
+               Resource cr = r;\r
+                               Layer0X L0X = Layer0X.getInstance(g);\r
+                               if(g.isInheritedFrom(r, SysdynResource.getInstance(g).ModuleSymbol)) {\r
+                                       ModelingResources mr = ModelingResources.getInstance(g);\r
+                                       StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
+                                       Resource componentType = g.getSingleObject(r, mr.SymbolToComponentType);\r
+                                       Resource configuration = g.getSingleObject(componentType, sr2.IsDefinedBy);\r
+                                       cr = configuration;\r
+                               } else {     \r
+                                       Resource represents = g.getPossibleObject(r, L0X.Represents);\r
+                                       if(represents != null && g.isInstanceOf(represents, SysdynResource.getInstance(g).Configuration)){\r
+                                               cr = represents;\r
+                                       } else {\r
+                                               cr = r;\r
+                                       }\r
+                               }\r
+\r
+               \r
+                final Resource diagram = ComponentUtils.getPossibleCompositeDiagram(g, cr);\r
+                if(diagram == null) return;\r
+                final ResourceArray compositePath = StructuralVariables.getCompositeArray(g, cr);\r
+                final ResourceArray variablePath = compositePath.removeFromBeginning(1);\r
+\r
+                final Resource model = StructuralVariables.getModel(g, compositePath.head());\r
+                if(model == null) return;\r
+\r
+                \r
+                \r
+                final String rvi = StructuralVariables.getRVI(g, variablePath);\r
+                if(rvi == null) return;\r
+\r
+                PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+                    @Override\r
+                    public void run() {\r
+                        try {\r
+                            String editorId = getEditorId();\r
+//                            System.out.println("Activating diagram: model=" + modelURI + " rvi='" + rvi + "'");\r
+                            WorkbenchUtils.openEditor(editorId, new ResourceEditorInput2(editorId, diagram, model, rvi));\r
+                        } catch (PartInitException e) {\r
+                            // TODO Auto-generated catch block\r
+                            e.printStackTrace();\r
+                        }\r
+                    }\r
+                });\r
+\r
+            }\r
+\r
+        });\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynConnectionAdvisor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynConnectionAdvisor.java
new file mode 100644 (file)
index 0000000..ffcfd38
--- /dev/null
@@ -0,0 +1,149 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.RequestProcessor;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.content.ConnectionUtil;\r
+import org.simantics.diagram.content.ResourceTerminal;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.g2d.connection.IConnectionAdvisor;\r
+import org.simantics.g2d.diagram.handler.Topology.Terminal;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.structural2.modelingRules.CPIgnore;\r
+import org.simantics.structural2.modelingRules.ConnectionJudgement;\r
+import org.simantics.structural2.modelingRules.ConnectionJudgementType;\r
+import org.simantics.structural2.modelingRules.IConnectionPoint;\r
+import org.simantics.structural2.modelingRules.IModelingRules;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.CloudFactory.CloudSceneGraph;\r
+\r
+public class SysdynConnectionAdvisor  implements IConnectionAdvisor {\r
+\r
+       IModelingRules modelingRules;\r
+       RequestProcessor processor;\r
+\r
+       public SysdynConnectionAdvisor(IModelingRules modelingRules,\r
+                       RequestProcessor processor) {\r
+               this.modelingRules = modelingRules;\r
+               this.processor = processor;\r
+       }\r
+\r
+       IConnectionPoint getConnectionPoint(ReadGraph g, IElement element, Terminal term) throws DatabaseException {\r
+               Object obj = null;\r
+               if (element != null)\r
+                       obj = ElementUtils.getObject(element);\r
+\r
+               if (obj instanceof Resource) {\r
+                       Resource elementResource = (Resource) obj;\r
+                       return ConnectionUtil.toConnectionPoint(g, elementResource, term);\r
+               }\r
+\r
+               // FIXME: this currently allows connections to begin from flags\r
+               // but is rather hackish.\r
+               if(element.getElementClass().containsClass(CloudSceneGraph.class)) {\r
+                       return CPIgnore.NULL_INSTANCE;\r
+               }\r
+\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public Object canBeConnected(Object backend,\r
+                       final IElement element1, final Terminal term1,\r
+                       final IElement element2, final Terminal term2) {\r
+               try {\r
+                       if(backend == null)\r
+                               backend = processor;\r
+                       return ((RequestProcessor)backend).syncRequest(new Read<Object>() {\r
+\r
+                               @Override\r
+                               public Object perform(ReadGraph g) throws DatabaseException {\r
+                                       if(element1 != null && term1 != null && element2 != null && term2 != null) {\r
+                                               StaticObjectAdapter soa = element1.getElementClass().getSingleItem(StaticObjectAdapter.class);\r
+                                               Resource startElementResource = soa.adapt(Resource.class);\r
+                                               Object r = ElementUtils.getObject(element2);\r
+                                               if(r == null || !(r instanceof Resource))\r
+                                                   return null;\r
+                                               Resource endElementResource = (Resource) r;\r
+                                               \r
+                                               DiagramResource dr = DiagramResource.getInstance(g);\r
+                                               Resource terminal2 = ((ResourceTerminal) term2).getResource();\r
+                                               SysdynResource sr = SysdynResource.getInstance(g);\r
+                                               \r
+                                               \r
+                                               // Chech that end terminal has IsHeadOfTerminal relation\r
+                                               Resource connectionPoint = g.getPossibleObject(terminal2, dr.HasConnectionPoint);\r
+                        if(connectionPoint == null || !g.isSubrelationOf(connectionPoint, sr.IsHeadOfTerminal)) {\r
+                            return null;\r
+                        }\r
+\r
+                                               \r
+                        // If end element is input symbol, allow only one connection and only from a module\r
+                                               if(g.isInstanceOf(endElementResource, sr.InputSymbol)) {\r
+                                                       if(!g.isInheritedFrom(startElementResource, sr.ModuleSymbol)) return null;\r
+                                                       if(g.getObjects(endElementResource, sr.IsHeadOfTerminal).size() > 0) return null;\r
+                                               }\r
+                                               \r
+                                       }\r
+\r
+                                       ArrayList<IConnectionPoint> cps = new ArrayList<IConnectionPoint>();\r
+                                       cps.add(getConnectionPoint(g, element1, term1));\r
+                                       if(element2 != null)\r
+                                               cps.add(getConnectionPoint(g, element2, term2));\r
+                                       ConnectionJudgement judgement = \r
+                                               modelingRules.judgeConnection(g, cps);                  \r
+\r
+                                       if(judgement.type == ConnectionJudgementType.LEGAL)\r
+                                               return judgement;\r
+                                       else\r
+                                               return null;\r
+                               }\r
+\r
+                       });\r
+               } catch(DatabaseException e) {\r
+                       e.printStackTrace();\r
+                       return null;\r
+               }\r
+       }\r
+\r
+       @Override\r
+       public boolean canBeginConnection(Object backend,\r
+                       final IElement element, final Terminal term) {\r
+               try {\r
+                       if(backend == null)\r
+                               backend = processor;\r
+                       return ((RequestProcessor)backend).syncRequest(new Read<Boolean>() {\r
+\r
+                               @Override\r
+                               public Boolean perform(ReadGraph g) throws DatabaseException {\r
+                                       return modelingRules.judgeConnection(g,\r
+                                                       Arrays.asList(getConnectionPoint(g, element, term)))\r
+                                                       .type != ConnectionJudgementType.ILLEGAL;\r
+                               }\r
+\r
+                       });\r
+               } catch(DatabaseException e) {\r
+                       e.printStackTrace();\r
+                       return false;\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynCreationInstruction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynCreationInstruction.java
new file mode 100644 (file)
index 0000000..6772154
--- /dev/null
@@ -0,0 +1,99 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor;\r
+\r
+import gnu.trove.TIntIntHashMap;\r
+\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.common.utils.URIStringUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.mapping.constraint.instructions.TypedBracketInstruction.CreationInstruction;\r
+import org.simantics.modeling.services.ComponentNamingUtil;\r
+import org.simantics.modeling.services.NamingException;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.project.IProject;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.ShadowVariableReferenceDialogRunnable;\r
+import org.simantics.utils.threads.SWTThread;\r
+\r
+public class SysdynCreationInstruction extends CreationInstruction {\r
+\r
+    IProject project;\r
+    Resource configurationRoot;\r
+    int lComponentType;\r
+    int lConfiguration;\r
+\r
+    public SysdynCreationInstruction(IProject project, Resource configurationRoot, int variableId, int componentType,\r
+            int configuration) {\r
+        super(variableId);\r
+        this.project = project;\r
+        this.configurationRoot = configurationRoot;\r
+        lComponentType = componentType;\r
+        lConfiguration = configuration;\r
+    }\r
+\r
+    @Override\r
+    public Resource create(WriteGraph g, Object[] bindings) throws DatabaseException {\r
+        Resource componentType = (Resource) bindings[lComponentType];\r
+        Resource configuration = (Resource) bindings[lConfiguration];\r
+\r
+        Layer0 l0 = Layer0.getInstance(g);\r
+        Layer0X L0X = Layer0X.getInstance(g);\r
+        \r
+        try {\r
+            \r
+            // Naming strategy\r
+            String proposition = URIStringUtils.escape(ComponentNamingUtil.findFreshInstanceName(g, project, configuration, configuration, componentType));\r
+            Resource result = GraphUtils.create(g,\r
+                    l0.HasName, proposition\r
+            );\r
+            g.claim(result, L0X.Represents, result);\r
+            \r
+            // Add uninitialized tag. The tag is used to start name editing \r
+            SysdynResource SR = SysdynResource.getInstance(g);\r
+            g.claim(result, SR.IndependentVariable_isUninitialized, result);\r
+            \r
+            // Async reference dialog for shadow variables\r
+            if(SR.Shadow.equals(componentType)) {\r
+                Layer0 L0 = Layer0.getInstance(g);\r
+                Collection<Resource> referrableVariables = g.syncRequest(new ObjectsWithType(configuration, L0.ConsistsOf, SR.IndependentVariable));\r
+                referrableVariables.addAll( g.syncRequest(new ObjectsWithType(configuration, L0.ConsistsOf, SR.Input)));\r
+                HashMap<String, Resource> names = new  HashMap<String, Resource>();\r
+                for(Resource var : referrableVariables) {\r
+                    String name = NameUtils.getSafeName(g, var);\r
+                    names.put(name, var);\r
+                }\r
+                SWTThread.getThreadAccess().asyncExec(new ShadowVariableReferenceDialogRunnable(result, names));\r
+            }\r
+            \r
+            return result;\r
+        } catch (NamingException e1) {\r
+            throw new DatabaseException(e1);\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void mapVariables(TIntIntHashMap map) {\r
+        super.mapVariables(map);\r
+        lComponentType = map.get(lComponentType);\r
+        lConfiguration = map.get(lConfiguration);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorInput.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorInput.java
new file mode 100644 (file)
index 0000000..7e317c6
--- /dev/null
@@ -0,0 +1,387 @@
+package org.simantics.sysdyn.ui.editor;\r
+\r
+import org.eclipse.core.runtime.IAdaptable;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.ui.IMemento;\r
+import org.eclipse.ui.IPersistableElement;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.RequestProcessor;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.common.ResourceArray;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.AdaptionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.service.LifecycleSupport;\r
+import org.simantics.db.service.SerialisationSupport;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.icons.ImageDescriptorProvider;\r
+import org.simantics.ui.workbench.ResourceEditorInput2;\r
+import org.simantics.ui.workbench.ResourceEditorInputFactory2;\r
+import org.simantics.ui.workbench.TitleRequest;\r
+import org.simantics.ui.workbench.ToolTipRequest;\r
+import org.simantics.utils.ObjectUtils;\r
+import org.simantics.utils.datastructures.cache.ProvisionException;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.workbench.StringMemento;\r
+\r
+/**\r
+ * TEMPORARY fix to support sysdyn\r
+ * \r
+ * @author tlteemu\r
+ *\r
+ */\r
+public class SysdynEditorInput extends ResourceEditorInput2 {\r
+    \r
+    private final static boolean      DEBUG_UPDATE    = false;\r
+\r
+    private static final String       NO_NAME         =  "(no name)";\r
+\r
+    private final String              editorID;\r
+\r
+    private String                    randomAccessResourceId;\r
+\r
+    private transient Resource        resource;\r
+\r
+    /**\r
+     * Gotten from the editor that needs to initialize this input. Currently\r
+     * needed for two things: {@link #exists()} and {@link #saveState(IMemento)}.\r
+     */\r
+    private transient Session         session;\r
+\r
+    private transient boolean         exists;\r
+\r
+    private transient String          name;\r
+\r
+    private transient String          tooltip;\r
+\r
+    private transient ImageDescriptor imageDesc;\r
+\r
+    /** Persistent memento for external data */\r
+    private final StringMemento       persistentStore = new StringMemento();\r
+\r
+    /**\r
+     * @param editorID\r
+     * @param r\r
+     */\r
+    public SysdynEditorInput(String editorID, Resource r, Resource model, String rvi) {\r
+        super(editorID, r, model, rvi);\r
+        if (editorID == null)\r
+            throw new IllegalArgumentException("null editor id");\r
+        if (r == null)\r
+            throw new IllegalArgumentException("null resource");\r
+\r
+        this.editorID = editorID;\r
+        this.randomAccessResourceId = "";\r
+        this.resource = r;\r
+        this.rvi = rvi;\r
+        this.session = SimanticsUI.getSession();\r
+\r
+        ensureRandomAccessId();\r
+        setNonExistant();\r
+    }\r
+\r
+    void ensureRandomAccessId() {\r
+        if (resource == null)\r
+            throw new IllegalStateException("resource is null, input is disposed");\r
+        // Make sure that the resource has a random access id\r
+        try {\r
+            SerialisationSupport support = session.getService(SerialisationSupport.class);\r
+            randomAccessResourceId = String.valueOf(support.getRandomAccessId(resource));\r
+        } catch (DatabaseException e) {\r
+            throw new RuntimeException(e);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void init(IAdaptable adapter) throws DatabaseException {\r
+        if (resource == null && randomAccessResourceId != null) {\r
+            getSession().syncRequest(new ReadRequest() {\r
+                @Override\r
+                public void run(ReadGraph g) throws DatabaseException {\r
+                    try {\r
+                        long id = Long.parseLong(randomAccessResourceId);\r
+                        resource = g.getService(SerialisationSupport.class).getResource(id);\r
+                        update(g);\r
+                    } catch (NumberFormatException e) {\r
+                        setNonExistant();\r
+                    } catch (DatabaseException e) {\r
+                        setNonExistant();\r
+                    }\r
+                }\r
+            });\r
+        } else {\r
+            if (resource != null) {\r
+                updateCaches(getSession(), true);\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        //System.out.println("dispose resource editor input: " + name);\r
+        // NOTE: this has to be done since Eclipse will cache these IEditorInput\r
+        // instances within EditorHistoryItem's that are stored in an EditorHistory\r
+        // instance. They are held by strong reference which means that the session\r
+        // cannot be collected if it is not nulled here.\r
+        session = null;\r
+        resource = null;\r
+    }\r
+\r
+    /**\r
+     * @return a graph instance if it exists and has not yet been disposed,\r
+     *         <code>null</code> otherwise\r
+     */\r
+    public Session getSession() {\r
+        // TODO: also throw an exception if the session is disposed\r
+        if (session == null)\r
+            throw new IllegalStateException("session is disposed");\r
+        return session;\r
+    }\r
+\r
+    @Override\r
+    public boolean exists() {\r
+        return exists;\r
+    }\r
+\r
+    @Override\r
+    public boolean exists(ReadGraph graph) throws DatabaseException {\r
+        try {\r
+            assertExists(graph);\r
+            return true;\r
+        } catch (ResourceNotFoundException e) {\r
+        } catch (Nonexistant e) {\r
+        }\r
+        return false;\r
+    }\r
+\r
+    @Override\r
+    public Resource getResource() {\r
+        return resource;\r
+    }\r
+\r
+    @Override\r
+    @Deprecated\r
+    public ResourceArray getResourceArray() {\r
+        return new ResourceArray(resource);\r
+    }\r
+\r
+    @Override\r
+    public String getRVI() {\r
+        return rvi;\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.eclipse.ui.IEditorInput#getImageDescriptor()\r
+     */\r
+    @Override\r
+    public ImageDescriptor getImageDescriptor() {\r
+        return imageDesc;\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.eclipse.ui.IEditorInput#getName()\r
+     */\r
+    @Override\r
+    public String getName() {\r
+        return name;\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.eclipse.ui.IEditorInput#getToolTipText()\r
+     */\r
+    @Override\r
+    public String getToolTipText() {\r
+        return tooltip;\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.eclipse.ui.IEditorInput#getPersistable()\r
+     */\r
+    @Override\r
+    public IPersistableElement getPersistable() {\r
+        // Don't allow persistability when it's not possible.\r
+        if (!isPersistable())\r
+            return null;\r
+        return this;\r
+    }\r
+\r
+    protected boolean isPersistable() {\r
+        if (session == null)\r
+            return false;\r
+        LifecycleSupport lc = session.peekService(LifecycleSupport.class);\r
+        if (lc == null)\r
+            return false;\r
+        if (lc.isClosed())\r
+            return false;\r
+        return true;\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.eclipse.ui.IPersistableElement#getFactoryId()\r
+     */\r
+    @Override\r
+    public String getFactoryId() {\r
+        return ResourceEditorInputFactory2.getFactoryId();\r
+    }\r
+\r
+    /**\r
+     * Saves the state of the given resource editor input into the given memento.\r
+     *\r
+     * @param memento the storage area for element state\r
+     * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento)\r
+     */\r
+    @Override\r
+    public void saveState(IMemento memento) {\r
+//        List<String> ids = randomAccessResourceId;\r
+        if (randomAccessResourceId == null) {\r
+            // Must create a new random access ID.\r
+            ensureRandomAccessId();\r
+        }\r
+        IMemento child = memento.createChild(ResourceEditorInputFactory2.TAG_RESOURCE_ID);\r
+        child.putTextData(randomAccessResourceId);\r
+        memento.putString(ResourceEditorInputFactory2.TAG_EDITOR_ID, editorID);\r
+//        memento.putString(ResourceEditorInputFactory2.TAG_MODEL_URI, modelURI);\r
+        memento.putString(ResourceEditorInputFactory2.TAG_MODEL_ID, modelId);\r
+        memento.putString(ResourceEditorInputFactory2.TAG_RVI, rvi);\r
+        memento.putString(ResourceEditorInputFactory2.TAG_EXTERNAL_MEMENTO_ID, persistentStore.toString());\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)\r
+     */\r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        //System.out.println("[ResourceEditorInput] getAdapter: " + adapter.getName());\r
+        return null;\r
+    }\r
+\r
+\r
+    @Override\r
+    public int hashCode() {\r
+        final int prime = 31;\r
+        int result = 1;\r
+        result = prime * result + editorID.hashCode();\r
+        result = prime * result + ObjectUtils.hashCode(modelId);\r
+        result = prime * result + ObjectUtils.hashCode(rvi);\r
+        result = prime * result + ObjectUtils.hashCode(randomAccessResourceId);\r
+        return result;\r
+    }\r
+\r
+    private void updateCaches(RequestProcessor processor, boolean sync) throws DatabaseException {\r
+        ReadRequest req = new ReadRequest() {\r
+            @Override\r
+            public void run(ReadGraph g) throws DatabaseException {\r
+                update(g);\r
+            }\r
+        };\r
+        if (sync) {\r
+            processor.syncRequest(req);\r
+        } else {\r
+            processor.asyncRequest(req);\r
+        }\r
+    }\r
+\r
+    static class Nonexistant extends DatabaseException {\r
+        private static final long serialVersionUID = -7964385375237203651L;\r
+\r
+        @Override\r
+        public synchronized Throwable fillInStackTrace() {\r
+            return this;\r
+        }\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.simantics.ui.workbench.IResourceEditorInput#update(org.simantics.db.Graph)\r
+     */\r
+    @Override\r
+    public void update(ReadGraph g) throws DatabaseException {\r
+        Resource r = getResource();\r
+        if (r == null)\r
+            return;\r
+\r
+        if (DEBUG_UPDATE)\r
+            System.out.println("update(" + this + ")");\r
+\r
+        try {\r
+            assertExists(g);\r
+\r
+            name = g.syncRequest(new TitleRequest(editorID, this));\r
+            if (name == null)\r
+                name = NO_NAME;\r
+\r
+            tooltip = g.syncRequest(new ToolTipRequest(editorID, this));\r
+            if (tooltip == null)\r
+                tooltip = NO_NAME;\r
+\r
+            try {\r
+                ImageDescriptorProvider idp = g.adapt(r, ImageDescriptorProvider.class);\r
+                imageDesc = idp.get();\r
+            } catch (AdaptionException e) {\r
+                imageDesc = ImageDescriptor.getMissingImageDescriptor();\r
+            } catch (ProvisionException e) {\r
+                imageDesc = ImageDescriptor.getMissingImageDescriptor();\r
+                ErrorLogger.defaultLogError(e);\r
+            }\r
+\r
+            if (DEBUG_UPDATE)\r
+                System.out.println("update(" + this + ") finished");\r
+        } catch (DatabaseException e) {\r
+            if (DEBUG_UPDATE)\r
+                e.printStackTrace();\r
+            setNonExistant();\r
+        }\r
+    }\r
+\r
+    private void assertExists(ReadGraph g) throws DatabaseException {\r
+        Resource r = getResource();\r
+        if (r == null)\r
+            throw new Nonexistant();\r
+\r
+        // 1. Check resource existence\r
+        boolean exists = g.hasStatement(r);\r
+        if (!exists)\r
+            throw new Nonexistant();\r
+\r
+        // 2. Validate modelURI\r
+        if (getModel(g) != null && g.getPossibleURI(getModel(g)) != null) {\r
+            Layer0X L0X = Layer0X.getInstance(g);\r
+            \r
+            // 3. Validate RVI\r
+            Resource model = getModel(g);\r
+            Resource baseRealization = g.getPossibleObject(model, L0X.HasBaseRealization);\r
+            Variable modelVariable = Variables.getVariable(g, g.getURI(baseRealization));\r
+            modelVariable.browse(g, getRVI());\r
+        }\r
+\r
+        // Touch the diagram title calculation within this existence\r
+        // checking request.\r
+        g.syncRequest(new TitleRequest(editorID, this));\r
+    }\r
+\r
+    private void setNonExistant() {\r
+        if (DEBUG_UPDATE)\r
+            System.out.println("setNonExistant(" + this + " @ " + System.identityHashCode(this) + ")");\r
+\r
+        exists = false;\r
+        tooltip = name = NO_NAME;\r
+        imageDesc = ImageDescriptor.getMissingImageDescriptor();\r
+    }\r
+\r
+    public IMemento getPersistentStore() {\r
+        return persistentStore;\r
+    }\r
+\r
+    @Override\r
+    public String toString() {\r
+        return getClass().getSimpleName() + " [name=" + getName() + ", resource=" + resource + "]";\r
+    }\r
+    \r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorNamingService.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorNamingService.java
new file mode 100644 (file)
index 0000000..98f825b
--- /dev/null
@@ -0,0 +1,74 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor;\r
+\r
+import org.eclipse.ui.IEditorInput;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.ui.features.EditorNamingService2;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.workbench.IResourceEditorInput2;\r
+\r
+/**\r
+ * SysdynEditorNamingService provides names for diagram viewers. \r
+ * If the viewer shows an instantiated module, the service provides a name of type: "instanceName : instanceOf".\r
+ * Otherwise works as standard EditorNamingService2.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynEditorNamingService extends EditorNamingService2 {\r
+\r
+       @Override\r
+       public String getName(ReadGraph g, String editorId, IEditorInput in) throws DatabaseException {\r
+               if(in instanceof IResourceEditorInput2) {\r
+                       IResourceEditorInput2 input = (IResourceEditorInput2) in;\r
+\r
+                       if(input.getRVI() != null && !input.getRVI().isEmpty()) {\r
+                               Resource model = input.getModel(g);\r
+                               if(model != null) {\r
+                                       Resource configuration = g.getPossibleObject(model, SimulationResource.getInstance(g).HasConfiguration);\r
+                                       String configurationName = NameUtils.getSafeName(g, configuration);\r
+                                       String uri = g.getURI(input.getModel(g)) + "/" + configurationName + input.getRVI();\r
+                                       Variable v = Variables.getPossibleVariable(g, uri);\r
+                                       if(v != null) {\r
+                                               String name = input.getRVI();\r
+                                               if(name.contains("/"))\r
+                                                       name = name.substring(name.lastIndexOf("/") + 1);\r
+\r
+                                               Resource instanceOf = g.getPossibleObject(v.getRepresents(g), Layer0.getInstance(g).InstanceOf);\r
+                                               return name + " : " + NameUtils.getSafeName(g, instanceOf);\r
+                                       }\r
+                               }\r
+                       } else {\r
+                               ModelingResources mr = ModelingResources.getInstance(g);\r
+                               SysdynResource sr = SysdynResource.getInstance(g);\r
+                               Resource composite = g.getPossibleObject(input.getResource(), mr.DiagramToComposite);\r
+                               if(composite != null) {\r
+                                       if(g.isInstanceOf(composite, sr.Configuration))\r
+                                               composite = g.getPossibleObject(composite, Layer0.getInstance(g).PartOf);\r
+                                       if(composite != null) \r
+                                               return NameUtils.getSafeName(g, composite);\r
+                               }\r
+                       }\r
+               }\r
+               return super.getName(g, editorId, in);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/CreateVariablesShortcutParticipant.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/CreateVariablesShortcutParticipant.java
new file mode 100644 (file)
index 0000000..96d6f93
--- /dev/null
@@ -0,0 +1,322 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Point2D;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.Queries;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.diagram.query.DiagramRequests;\r
+import org.simantics.g2d.canvas.SGDesignation;\r
+import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;\r
+import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.DiagramMutator;\r
+import org.simantics.g2d.diagram.DiagramUtils;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;\r
+import org.simantics.g2d.diagram.participant.ElementPainter;\r
+import org.simantics.g2d.diagram.participant.Selection;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.participant.MouseUtil;\r
+import org.simantics.g2d.participant.MouseUtil.MouseInfo;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;\r
+import org.simantics.scenegraph.g2d.events.KeyEvent;\r
+import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;\r
+import org.simantics.scenegraph.g2d.events.KeyEvent.KeyReleasedEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.AuxiliaryFactory;\r
+import org.simantics.sysdyn.ui.elements.CloudFactory;\r
+import org.simantics.sysdyn.ui.elements.InputFactory;\r
+import org.simantics.sysdyn.ui.elements.LoopFactory;\r
+import org.simantics.sysdyn.ui.elements.ShadowFactory;\r
+import org.simantics.sysdyn.ui.elements.StockFactory;\r
+import org.simantics.sysdyn.ui.elements.ValveFactory;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Callback;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class CreateVariablesShortcutParticipant extends AbstractDiagramParticipant {\r
+\r
+       private GraphToDiagramSynchronizer synchronizer;\r
+\r
+       private VariableInformation variableInformation;\r
+\r
+       @Dependency\r
+       MouseUtil mouseUtil;\r
+\r
+       @Dependency\r
+       Selection selection;\r
+\r
+       @Dependency\r
+       ElementPainter diagramPainter;\r
+\r
+       ShapeNode node;\r
+       G2DParentNode parent;\r
+\r
+       private boolean createVar;\r
+       private IDiagram createVarDiagram;\r
+\r
+       @SGInit(designation = SGDesignation.CANVAS)\r
+       public void init(G2DParentNode parent) {\r
+               this.parent = parent;\r
+       }\r
+\r
+       public void removeSG() {\r
+               node.remove();\r
+               node = null;\r
+               setDirty();\r
+       }\r
+\r
+       void updateSG() {\r
+\r
+               if (node == null) {\r
+                       node = variableInformation.node;\r
+               }\r
+\r
+               MouseInfo mi = mouseUtil.getMouseInfo(0);\r
+               if (mi == null)\r
+                       return;\r
+\r
+               Point2D newPos = mi.canvasPosition;\r
+               double x = newPos.getX();\r
+               double y = newPos.getY();\r
+\r
+               AffineTransform origAt = node.getTransform();\r
+               double oldX = origAt.getTranslateX();\r
+               double oldY = origAt.getTranslateY();\r
+               AffineTransform move = new AffineTransform();\r
+               move.setToTranslation(x - oldX, y - oldY);\r
+               AffineTransform at2 = new AffineTransform(origAt);\r
+               at2.preConcatenate(move);\r
+               node.setTransform(at2);\r
+               setDirty();\r
+       }\r
+\r
+       public CreateVariablesShortcutParticipant(GraphToDiagramSynchronizer synchronizer) {\r
+               this.synchronizer = synchronizer;\r
+       }\r
+\r
+       @EventHandler(priority = -10)\r
+       public boolean handleKeyboardEvent(KeyEvent ke) {\r
+\r
+               KeyPressedEvent kpe;\r
+               if (ke instanceof KeyPressedEvent) {\r
+                       \r
+                       kpe = (KeyPressedEvent) ke;\r
+                       \r
+                       if (!kpe.isShiftDown() || isEditing()) \r
+                               return false;\r
+                       \r
+                       if (kpe.keyCode == java.awt.event.KeyEvent.VK_A) {\r
+                               variableInformation = new VariableInformation(\r
+                               java.awt.event.KeyEvent.VK_A,\r
+                               SysdynResource.URIs.AuxiliarySymbol,\r
+                               (ShapeNode)AuxiliaryFactory.AUX_STATIC_IMAGE.init(parent)\r
+                               );\r
+                       } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_S) {\r
+                               variableInformation = new VariableInformation(\r
+                                               java.awt.event.KeyEvent.VK_S,\r
+                                               SysdynResource.URIs.StockSymbol,\r
+                                               (ShapeNode)StockFactory.STOCK_IMAGE.init(parent)\r
+                                               );\r
+                       } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_C) {\r
+                               variableInformation = new VariableInformation(\r
+                                               java.awt.event.KeyEvent.VK_C,\r
+                                               SysdynResource.URIs.CloudSymbol,\r
+                                               (ShapeNode)CloudFactory.CLOUD_IMAGE.init(parent)\r
+                                               );\r
+                       } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_V) {\r
+                               variableInformation = new VariableInformation(\r
+                                               java.awt.event.KeyEvent.VK_V,\r
+                                               SysdynResource.URIs.ValveSymbol,\r
+                                               (ShapeNode)ValveFactory.VALVE_STATIC_IMAGE.init(parent)\r
+                                               );\r
+                       } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_I) {\r
+                               variableInformation = new VariableInformation(\r
+                                               java.awt.event.KeyEvent.VK_I,\r
+                                               SysdynResource.URIs.InputSymbol,\r
+                                               (ShapeNode)InputFactory.INPUT_IMAGE.init(parent)\r
+                                               );\r
+                       } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_G) {\r
+                variableInformation = new VariableInformation(\r
+                        java.awt.event.KeyEvent.VK_G,\r
+                        SysdynResource.URIs.ShadowSymbol,\r
+                        (ShapeNode)ShadowFactory.GHOST_IMAGE.init(parent)\r
+                        );\r
+                       } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_L) {\r
+                variableInformation = new VariableInformation(\r
+                        java.awt.event.KeyEvent.VK_L,\r
+                        SysdynResource.URIs.LoopSymbol,\r
+                        (ShapeNode)LoopFactory.LOOP_STATIC_IMAGE.init(parent)\r
+                        );\r
+            }\r
+\r
+                       if (variableInformation != null) {\r
+                               updateSG();\r
+                               return true;\r
+                       }\r
+               }\r
+\r
+               KeyReleasedEvent kre;\r
+               if (ke instanceof KeyReleasedEvent) {\r
+                       kre = (KeyReleasedEvent) ke;\r
+                       \r
+                       if (variableInformation != null\r
+                                       && (kre.keyCode == variableInformation.shortcutKey || kre.keyCode == java.awt.event.KeyEvent.VK_SHIFT)) {\r
+                               if (node != null) {\r
+                                       // If there is a variable to be created, do it when a key is released.\r
+                                       if (createVar) {\r
+                                               createVar = false;\r
+                                               createVariableOnDiagram(createVarDiagram);\r
+                                       }\r
+                                       variableInformation = null;\r
+                                       removeSG();\r
+                                       return true;\r
+                               }\r
+                       }\r
+               }\r
+\r
+               return false;\r
+\r
+       }\r
+\r
+       @EventHandler(priority = -10)\r
+       public boolean handleMouse(MouseMovedEvent e) {\r
+\r
+               if (variableInformation != null ) {\r
+                       updateSG();\r
+               } else {\r
+                       if (node != null) {\r
+                               removeSG();\r
+                       }\r
+               }\r
+               return false;\r
+       }\r
+\r
+\r
+       @EventHandler(priority = 100)\r
+       public boolean handleMouseEvent(MouseEvent me) {\r
+\r
+\r
+               MouseEvent.MouseClickEvent mce;\r
+               if (me instanceof MouseEvent.MouseClickEvent) {\r
+                       mce = (MouseEvent.MouseClickEvent) me;\r
+               } else {\r
+                       return false;\r
+               }\r
+\r
+               if (!\r
+                               (\r
+                                               mce.button == MouseEvent.LEFT_BUTTON && \r
+                                               variableInformation != null && \r
+                                               mce.stateMask ==  MouseEvent.SHIFT_MASK\r
+                               )) \r
+               {\r
+                       return false;\r
+               }\r
+               \r
+               final IDiagram d = getHint(DiagramHints.KEY_DIAGRAM);\r
+               if (d == null)\r
+                       return false;\r
+               \r
+               // Need to create a new variable, save the diagram to do this later.\r
+               createVar = true;\r
+               createVarDiagram = d;\r
+\r
+               return true;\r
+       }\r
+\r
+\r
+       private void createVariableOnDiagram(IDiagram d) {\r
+               DiagramUtils.mutateDiagram(d, new Callback<DiagramMutator>() {\r
+                       @Override\r
+                       public void run(DiagramMutator m) {\r
+\r
+                               Resource r;\r
+                               try {\r
+                                       r = SimanticsUI\r
+                                       .getSession()\r
+                                       .syncRequest(\r
+                                                       Queries\r
+                                                       .resource(variableInformation.symbolURI));\r
+                                       ElementClass ec = SimanticsUI.getSession().syncRequest(\r
+                                                       DiagramRequests.getElementClass(r, diagram));\r
+\r
+                                       IElement element = m.newElement(ec);\r
+\r
+                                       // MouseUtil mutil = new MouseUtil();\r
+                                       MouseInfo minfo = mouseUtil.getMouseInfo(0);\r
+\r
+                                       //at least when using breakpoints this is possible\r
+                                       if(minfo == null) \r
+                                               return;\r
+\r
+                                       Point2D p = minfo.canvasPosition;\r
+                                       //FIXME - Arto element doesn't know its size at first. Hopefully temp fix.\r
+                                       p.setLocation(p.getX()-5.46, p.getY()+1);\r
+\r
+                                       ElementUtils.setPos(element, p);\r
+\r
+                               } catch (DatabaseException e) {\r
+                                       ExceptionUtils.logAndShowError(e);\r
+                               }\r
+\r
+                       }\r
+               });\r
+\r
+               synchronizer.getCanvasContext().getContentContext().setDirty();\r
+\r
+       }\r
+\r
+       private class VariableInformation {\r
+               public String symbolURI;\r
+               public ShapeNode node;\r
+               public int shortcutKey;\r
+\r
+               public VariableInformation(int shortcutKey, String symbolURI, ShapeNode node) {\r
+                       this.symbolURI = symbolURI;\r
+                       this.node = node;\r
+                       this.shortcutKey = shortcutKey;\r
+               }\r
+       }\r
+       \r
+       private boolean isEditing() {\r
+        int selectionId = 0;\r
+        Set<IElement> ss = selection.getSelection(selectionId);\r
+        if (ss.isEmpty()) {\r
+            return false;\r
+        }\r
+        for (IElement e : ss) {\r
+               for(Object o : e.getHints().values()) {\r
+                       if (o instanceof TextNode) {\r
+                               TextNode tn = (TextNode) o;\r
+                               if(tn.isEditMode())\r
+                                       return true;\r
+                       }\r
+               }\r
+        }\r
+               return false;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SelectionUpdaterParticipant.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SelectionUpdaterParticipant.java
new file mode 100644 (file)
index 0000000..023c78c
--- /dev/null
@@ -0,0 +1,96 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.VirtualGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.ui.DiagramModelHints;\r
+import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;\r
+import org.simantics.g2d.canvas.impl.HintReflection.HintListener;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;\r
+import org.simantics.g2d.diagram.participant.Selection;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintObservable;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+\r
+public class SelectionUpdaterParticipant extends AbstractDiagramParticipant {\r
+\r
+    @Dependency Selection selection;\r
+\r
+    @HintListener(Class = Selection.class, Field = "SELECTION0")\r
+    public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
+        IDiagram diagram = sender.getHint(DiagramHints.KEY_DIAGRAM);\r
+        Collection<IElement> elements = AdaptionUtils.adaptToCollection(newValue, IElement.class);\r
+        if(diagram != null) {\r
+            Session session = SimanticsUI.getSession();\r
+            session.asyncRequest(new ModifyDiagramSelection(session.getService(VirtualGraph.class), diagram, elements));\r
+        }\r
+    }\r
+    \r
+    @HintListener(Class = Selection.class, Field = "SELECTION0")\r
+    public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {\r
+        IDiagram diagram = sender.getHint(DiagramHints.KEY_DIAGRAM);\r
+        if(diagram != null) {\r
+            Session session = SimanticsUI.getSession();\r
+            session.asyncRequest(new ModifyDiagramSelection(session.getService(VirtualGraph.class), diagram, null));\r
+        }\r
+    }\r
+    \r
+    \r
+    private class ModifyDiagramSelection extends WriteRequest {\r
+        IDiagram diagram;\r
+        Collection<IElement> elements;\r
+        \r
+        public ModifyDiagramSelection(VirtualGraph provider, IDiagram diagram, Collection<IElement> elements) {\r
+            super(provider);\r
+            this.elements = elements;\r
+            this.diagram = diagram;\r
+        }\r
+        \r
+        @Override\r
+        public void perform(WriteGraph graph) throws DatabaseException {\r
+            Resource diagramRuntime = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RUNTIME_RESOURCE);\r
+            \r
+            if(diagramRuntime == null) {\r
+                return;\r
+            }\r
+            \r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+            DiagramResource DR = DiagramResource.getInstance(graph);\r
+\r
+            graph.deny(diagramRuntime, SR.ConfigurationDiagram_selection);\r
+\r
+            if(elements != null) {\r
+                for(IElement e : elements) {\r
+                    Resource object = e.getHint(ElementHints.KEY_OBJECT);\r
+                    if(object != null && graph.isInstanceOf(object, DR.Element)) {\r
+                        graph.claim(diagramRuntime, SR.ConfigurationDiagram_selection, object);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynComponentCopyAdvisor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynComponentCopyAdvisor.java
new file mode 100644 (file)
index 0000000..8e61586
--- /dev/null
@@ -0,0 +1,102 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import java.util.Map;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Statement;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.diagram.synchronization.ISynchronizationContext;\r
+import org.simantics.diagram.synchronization.StatementEvaluation;\r
+import org.simantics.diagram.synchronization.SynchronizationHints;\r
+import org.simantics.diagram.synchronization.graph.CopyAdvisorUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ComponentUtils;\r
+import org.simantics.modeling.mapping.ComponentCopyAdvisor;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.datastructures.BinaryFunction;\r
+\r
+public class SysdynComponentCopyAdvisor extends ComponentCopyAdvisor {\r
+\r
+    private Layer0 L0;\r
+    private StructuralResource2 STR;\r
+    private SysdynResource SYSDYN;\r
+\r
+    @Override\r
+    public Object copy(ISynchronizationContext context, WriteGraph graph, Resource source, Resource sourceContainer, Resource targetContainer, Map<Object, Object> map) throws DatabaseException {\r
+//        Object copy = super.copy(context, graph, source, sourceContainer, targetContainer, map);\r
+        \r
+      BinaryFunction<StatementEvaluation, ReadGraph, Statement> tester = new BinaryFunction<StatementEvaluation, ReadGraph, Statement>() {\r
+          @Override\r
+          public StatementEvaluation call(ReadGraph graph, Statement statement) {\r
+              try {\r
+                  if(statement.getPredicate().equals(L0.List_Next) ||\r
+                          statement.getPredicate().equals(L0.List_Previous)) {\r
+                      return StatementEvaluation.INCLUDE_AND_FOLLOW;\r
+                  } else if(statement.getPredicate().equals(L0.List_Element)){\r
+                      if(graph.isInstanceOf(statement.getObject(), SYSDYN.Enumeration))\r
+                          return StatementEvaluation.INCLUDE;\r
+                      else\r
+                          return StatementEvaluation.INCLUDE_AND_FOLLOW;\r
+                  } else if(statement.getPredicate().equals(SYSDYN.Shadow_original))\r
+                      return StatementEvaluation.INCLUDE;\r
+              } catch (ServiceException e) {\r
+                  e.printStackTrace();\r
+              }\r
+              return StatementEvaluation.USE_DEFAULT;\r
+          }\r
+          \r
+      };\r
+        \r
+      SYSDYN = SysdynResource.getInstance(graph);\r
+      L0 = Layer0.getInstance(graph);\r
+        STR = StructuralResource2.getInstance(graph);\r
+        Resource copy = null;\r
+        if (graph.isInstanceOf(source, STR.Connection)) {\r
+            // Configuration connections are not named, can't use TG copy for\r
+            // them at the moment.\r
+            copy = CopyAdvisorUtil.copy2(graph, source, null, map);\r
+        } else {\r
+//            Resource model = graph.syncRequest(new PossibleModel(targetContainer));\r
+//            copy = CopyAdvisorUtil.copy4(graph, source, model);\r
+            copy = CopyAdvisorUtil.copy2(graph, source, tester, map);\r
+        }\r
+\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        if (graph.hasStatement(sourceContainer, L0.ConsistsOf, source))\r
+            graph.claim(targetContainer, L0.ConsistsOf, copy);\r
+\r
+        if (context.get(SynchronizationHints.NO_RENAME) == null)\r
+//            renameComponent(context, graph, source, copy, sourceContainer, targetContainer);\r
+            rename(context, graph, source, (Resource)copy, sourceContainer, targetContainer);\r
+        \r
+        return copy;\r
+    }\r
+    \r
+\r
+    public String rename(ISynchronizationContext context, WriteGraph graph, Resource source,\r
+            Resource copy, Resource sourceContainer, Resource targetContainer) throws DatabaseException {\r
+       Layer0 l0 = Layer0.getInstance(graph);\r
+       String copyName = NameUtils.getSafeName(graph, copy);\r
+        Resource configurationRoot = ComponentUtils.getCompositeConfigurationRoot(graph, targetContainer);\r
+       String name =  NameUtils.findFreshName(graph, copyName, configurationRoot, l0.ConsistsOf, "%s%d");\r
+       graph.claimLiteral(copy, l0.HasName, name, Bindings.STRING);\r
+       return name;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectTool.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectTool.java
new file mode 100644 (file)
index 0000000..72de5cb
--- /dev/null
@@ -0,0 +1,472 @@
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.Deque;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.participant.ConnectTool2;\r
+import org.simantics.diagram.participant.ConnectionBuilder;\r
+import org.simantics.diagram.participant.ControlPoint;\r
+import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;\r
+import org.simantics.g2d.connection.IConnectionAdvisor;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.handler.Topology.Terminal;\r
+import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil;\r
+import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementClasses;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.impl.Element;\r
+import org.simantics.g2d.elementclass.BranchPointClass;\r
+import org.simantics.g2d.elementclass.FlagClass;\r
+import org.simantics.g2d.routing.Constants;\r
+import org.simantics.g2d.routing.IConnection;\r
+import org.simantics.g2d.routing.IRouter2;\r
+import org.simantics.g2d.routing.TrivialRouter2;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;\r
+import org.simantics.structural2.modelingRules.ConnectionJudgement;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.editor.routing.FlowRouter;\r
+import org.simantics.sysdyn.ui.elements.CloudFactory;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementHints;\r
+import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;\r
+import org.simantics.sysdyn.ui.elements.connections.ConnectionClasses;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Callback;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class SysdynConnectTool extends ConnectTool2 {\r
+\r
+       public SysdynConnectTool(TerminalInfo startTerminal, int mouseId,\r
+                       Point2D startCanvasPos) {\r
+               super(startTerminal, mouseId, startCanvasPos);\r
+       }\r
+\r
+       @Override\r
+       @SGInit\r
+       public void initSG(G2DParentNode parent) {\r
+               ghostNode = parent.addNode(G2DParentNode.class);\r
+               ghostNode.setZIndex(PAINT_PRIORITY);\r
+\r
+               ShapeNode pathNode = ghostNode.getOrCreateNode("path", ShapeNode.class);\r
+               pathNode.setColor(Color.BLACK);\r
+               pathNode.setStroke(new BasicStroke(1f));\r
+               pathNode.setScaleStroke(true);\r
+               pathNode.setZIndex(0);\r
+\r
+               G2DParentNode points = ghostNode.getOrCreateNode("points", G2DParentNode.class);\r
+               points.setZIndex(1);\r
+\r
+               updateSG();\r
+       }\r
+\r
+       @Override\r
+       protected TerminalInfo createFlag(EdgeEnd connectionEnd) {\r
+               ElementClass flagClass = elementClassProvider.get(ElementClasses.FLAG);\r
+               IElement e = Element.spawnNew(flagClass);\r
+\r
+               e.setHint(FlagClass.KEY_FLAG_TYPE, endToFlagType(connectionEnd));\r
+               e.setHint(FlagClass.KEY_FLAG_MODE, FlagClass.Mode.Internal);\r
+\r
+               TerminalInfo ti = new TerminalInfo();\r
+               ti.e = e;\r
+\r
+               // start: this part changed to support overlapping terminals\r
+               ArrayList<Terminal> terminals = new ArrayList<Terminal>();\r
+               ElementUtils.getTerminals(e, terminals, false);\r
+               ti.t = terminals.get(0);\r
+               // end\r
+\r
+               ti.posElem = TerminalUtil.getTerminalPosOnElement(e, ti.t);\r
+               ti.posDia = TerminalUtil.getTerminalPosOnDiagram(e, ti.t);\r
+\r
+               return ti;\r
+       }\r
+\r
+       static class Segment {\r
+               public final ControlPoint begin;\r
+               public final ControlPoint end;\r
+               public Path2D             path;\r
+\r
+               public Segment(ControlPoint begin, ControlPoint end) {\r
+                       this.begin = begin;\r
+                       this.end = end;\r
+               }\r
+\r
+               @Override\r
+               public String toString() {\r
+                       return "Segment[begin=" + begin + ", end=" + end + ", path=" + path + "]";\r
+               }\r
+       }\r
+\r
+       private List<Segment> toSegments(Deque<ControlPoint> points) {\r
+               if (points.isEmpty())\r
+                       return Collections.emptyList();\r
+\r
+               List<Segment> segments = new ArrayList<Segment>();\r
+\r
+               Iterator<ControlPoint> it = points.iterator();\r
+               ControlPoint prev = it.next();\r
+               while (it.hasNext()) {\r
+                       ControlPoint next = it.next();\r
+                       segments.add(new Segment(prev, next));\r
+                       prev = next;\r
+               }\r
+\r
+               return segments;\r
+       }\r
+\r
+       public interface SysdynConnection extends IConnection { }\r
+\r
+       @Override\r
+       protected void updateSG() {\r
+               if (controlPoints.isEmpty())\r
+                       return;\r
+\r
+               // Route connection segments separately\r
+               IRouter2 router = ElementUtils.getHintOrDefault(diagram, DiagramHints.ROUTE_ALGORITHM, TrivialRouter2.INSTANCE);\r
+               final List<Segment> segments = toSegments(controlPoints);\r
+               //System.out.println("controlpoints: " + controlPoints);\r
+               //System.out.println("segments: " + segments);\r
+               router.route(new SysdynConnection() {\r
+                       @Override\r
+                       public Collection<? extends Object> getSegments() {\r
+                               return segments;\r
+                       }\r
+\r
+                       @Override\r
+                       public Connector getBegin(Object seg) {\r
+                               return getConnector(((Segment) seg).begin);\r
+                       }\r
+\r
+                       @Override\r
+                       public Connector getEnd(Object seg) {\r
+                               return getConnector(((Segment) seg).end);\r
+                       }\r
+\r
+                       private Connector getConnector(ControlPoint cp) {\r
+                               Connector c = new Connector();\r
+                               c.x = cp.getPosition().getX();\r
+                               c.y = cp.getPosition().getY();\r
+\r
+                               c.allowedDirections = Constants.EAST_FLAG | Constants.WEST_FLAG\r
+                                               | Constants.NORTH_FLAG | Constants.SOUTH_FLAG;\r
+\r
+                               TerminalInfo ti = cp.getAttachedTerminal();\r
+                               if (ti != null && (ti != startFlag && ti != endFlag)) {\r
+                                       if(ti.e.getElementClass().containsClass(ValveSceneGraph.class)) {\r
+                                               Rectangle2D bounds = ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D();\r
+                                               c.parentObstacle = new Rectangle2D.Double(\r
+                                                               bounds.getCenterX() - FlowRouter.OFFSET,\r
+                                                               bounds.getCenterY() - FlowRouter.OFFSET, \r
+                                                               FlowRouter.OFFSET * 2,\r
+                                                               FlowRouter.OFFSET * 2);\r
+                                       } else {\r
+                                               c.parentObstacle =  ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D();\r
+                                       }\r
+                               } else if (ti != null && ti == startFlag) {\r
+                                       c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),\r
+                                                       ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D());\r
+                               } else if (isEndingInFlag() && ti.e != null) {\r
+                                       c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),\r
+                                                       CloudFactory.CLOUD_IMAGE.getBounds());\r
+                               } else {\r
+                                       c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),\r
+                                                       BranchPointClass.DEFAULT_IMAGE2.getBounds());\r
+                               }\r
+\r
+                               return c;\r
+                       }\r
+\r
+                       @Override\r
+                       public void setPath(Object seg, Path2D path) {\r
+                               ((Segment) seg).path = (Path2D) path.clone();\r
+                       }\r
+               });\r
+\r
+               // Combine the routed paths\r
+               Path2D path = new Path2D.Double();\r
+               for (Segment seg : segments) {\r
+                       //System.out.println("SEG: " + seg);\r
+                       if (seg.path != null)\r
+                               path.append(seg.path.getPathIterator(null), true);\r
+               }\r
+\r
+               // Create scene graph to visualize the connection.\r
+               ShapeNode pathNode = ghostNode.getOrCreateNode("path", ShapeNode.class);\r
+               pathNode.setShape(path);\r
+\r
+               /*\r
+                * Removed Points\r
+                */\r
+\r
+               setDirty();\r
+       }\r
+\r
+       @Override\r
+       protected Object canConnect(final IConnectionAdvisor advisor, final IElement endElement, final Terminal endTerminal) {\r
+               final IElement se = startTerminal != null ? startTerminal.e : startFlag.e;\r
+               final Terminal st = startTerminal != null ? startTerminal.t : null;\r
+\r
+               if(se.equals(endElement)) return null;\r
+               if(Boolean.FALSE.equals(diagram.getHint(DiagramHints.KEY_USE_CONNECTION_FLAGS)) && endElement == null) {\r
+                       return null;\r
+               }\r
+\r
+               if(endElement == null && endTerminal == null)\r
+                       return advisor.canBeConnected(null, se, st, endElement, endTerminal);\r
+\r
+               try {\r
+                       return SimanticsUI.getSession().syncRequest(new Read<Object>() {\r
+\r
+                               @Override\r
+                               public Object perform(ReadGraph g) throws DatabaseException {\r
+\r
+                                       // Checking if connection type can be connected to the intended endElement\r
+                                       SysdynResource sr = SysdynResource.getInstance(g);\r
+                                       StaticObjectAdapter soa = endElement.getElementClass().getSingleItem(StaticObjectAdapter.class);\r
+                                       Resource end = soa.adapt(Resource.class);\r
+                                       ElementClass dependency = elementClassProvider.get(ConnectionClasses.DEPENDENCY);\r
+                                       ElementClass flow = elementClassProvider.get(ConnectionClasses.FLOW);\r
+                                       ElementClass currentConnection = elementClassProvider.get(ElementClasses.CONNECTION);\r
+                                       if(currentConnection.equals(dependency)) {\r
+                                               if(end.equals(sr.CloudSymbol)) return null;\r
+                                               soa = se.getElementClass().getSingleItem(StaticObjectAdapter.class);\r
+                                               Resource start = soa.adapt(Resource.class);\r
+                                               if(g.isInheritedFrom(start, sr.ModuleSymbol) && !end.equals(sr.InputSymbol)) return null;\r
+                                               if(end.equals(sr.ShadowSymbol)) return null;\r
+                                       } else if (currentConnection.equals(flow)) {\r
+                                               if(!(end.equals(sr.StockSymbol) || end.equals(sr.ValveSymbol) || end.equals(sr.CloudSymbol))) return null;\r
+                                       } else {\r
+                                               return null;\r
+                                       }\r
+\r
+\r
+                                       if (advisor == null)\r
+                                               return Boolean.TRUE;     \r
+                                       return advisor.canBeConnected(g, se, st, endElement, endTerminal);\r
+                               }\r
+\r
+                       });\r
+               } catch(DatabaseException e) {\r
+                       e.printStackTrace();\r
+                       return null;\r
+               }\r
+\r
+       }\r
+\r
+       @Override\r
+       protected boolean processMouseMove(MouseMovedEvent me) {\r
+               mouseHasMoved = true;\r
+\r
+               Point2D mouseControlPos = me.controlPosition;\r
+               Point2D mouseCanvasPos = util.controlToCanvas(mouseControlPos, new Point2D.Double());\r
+\r
+               ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);\r
+               if (snapAdvisor != null)\r
+                       snapAdvisor.snap(mouseCanvasPos);\r
+\r
+               // Record last snapped canvas position of mouse.\r
+               this.lastMouseCanvasPos.setLocation(mouseCanvasPos);\r
+\r
+               if (isEndingInFlag()) {\r
+                       endFlagNode.setTransform(AffineTransform.getTranslateInstance(mouseCanvasPos.getX(), mouseCanvasPos.getY()));\r
+               }\r
+\r
+               List<TerminalInfo> tiList = ((SysdynPointerInteractor)pi).pickTerminals(me.controlPosition);\r
+               TerminalInfo ti = null;\r
+\r
+               IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);\r
+               for(TerminalInfo info : tiList) {\r
+                       if(advisor == null || info.e == null || info.t == null)\r
+                               continue;\r
+                       Object canConnect = canConnect(advisor, info.e, info.t);\r
+                       if (canConnect != null) {\r
+                               ti = info;\r
+                               break;\r
+                       }\r
+               }\r
+\r
+               if (ti != null && !isStartTerminal(ti.e, ti.t)) {\r
+                       Pair<ConnectionJudgement, TerminalInfo> canConnect = canConnect(ti.e, ti.t);\r
+                       if (canConnect != null) {\r
+                               connectionJudgment = canConnect.first;\r
+\r
+                               if (!isEndingInFlag() || !TerminalUtil.isSameTerminal(ti, endTerminal)) {\r
+                                       controlPoints.getLast()\r
+                                       .setPosition(ti.posDia)\r
+                                       .setAttachedToTerminal(ti);\r
+\r
+                                       endTerminal = ti;\r
+                               }\r
+\r
+                               // Make sure that we are ending with a flag if ALT is pressed\r
+                               // and no end terminal is defined. If we are in flow creation\r
+                               // mode, we want to show the terminal cloud (or flag) even when\r
+                               // alt is not pressed.\r
+                               if (inFlowMode() && flowInProgress() && !startTerminals.isEmpty())\r
+                                       endWithoutTerminal(lastMouseCanvasPos, true);\r
+                               else\r
+                                       endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));\r
+                               updateSG();\r
+                               return false;\r
+                       }\r
+               }\r
+\r
+               connectionJudgment = null;\r
+               if (isEndTerminalDefined()) {\r
+                       // CASE: Mouse was previously on top of a valid terminal to end\r
+                       // the connection. Now the mouse has been moved where there is\r
+                       // no longer a terminal to connect to.\r
+                       //\r
+                       // => Disconnect the last edge segment from the previous\r
+                       // terminal, mark endElement/endTerminal non-existent\r
+                       // and connect the disconnected edge to a new branch point.\r
+\r
+                       controlPoints.getLast()\r
+                       .setPosition(mouseCanvasPos)\r
+                       .setDirection(calculateCurrentBranchPointDirection())\r
+                       .setAttachedToTerminal(null);\r
+\r
+                       endTerminal = null;\r
+               } else {\r
+                       // CASE: Mouse was not previously on top of a valid ending\r
+                       // element terminal.\r
+                       //\r
+                       // => Move and re-orient last branch point.\r
+\r
+                       controlPoints.getLast()\r
+                       .setPosition(mouseCanvasPos)\r
+                       .setDirection(calculateCurrentBranchPointDirection());\r
+               }\r
+\r
+               // Make sure that we are ending with a flag if ALT is pressed and no end\r
+               // terminal is defined. If we are in flow creation mode, we want to show \r
+               // the terminal cloud (or flag) even when alt is not pressed.\r
+               if (inFlowMode() && flowInProgress() && !startTerminals.isEmpty())\r
+                       endWithoutTerminal(lastMouseCanvasPos, true);\r
+               else\r
+                       endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));\r
+               updateSG();\r
+               return false;\r
+       }\r
+\r
+       @Override\r
+       protected boolean processMouseButtonPress(MouseButtonPressedEvent e) {\r
+               MouseButtonEvent me = e;\r
+\r
+               // Do nothing before the mouse has moved at least a little.\r
+        // This prevents the user from ending the connection right where\r
+        // it started.\r
+               if (!mouseHasMoved)\r
+                       return true;\r
+\r
+               if (me.button == MouseEvent.LEFT_BUTTON || \r
+                               (me.button == MouseEvent.RIGHT_BUTTON && flowInProgress() && !inFlowMode())) {\r
+                       Point2D mouseControlPos = me.controlPosition;\r
+                       Point2D mouseCanvasPos = util.getInverseTransform().transform(mouseControlPos, new Point2D.Double());\r
+\r
+                       ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);\r
+                       if (snapAdvisor != null)\r
+                               snapAdvisor.snap(mouseCanvasPos);\r
+\r
+                       // Clicked on an allowed end terminal. End connection & end mode.\r
+                       if (isEndTerminalDefined()) {\r
+                               createConnection();\r
+                               remove();\r
+                               return true;\r
+                       } else {\r
+                               // Finish connection in thin air only if the\r
+                               // connection was started from a valid terminal.\r
+                               \r
+                               // If we are in flow creation mode, we want to be able to\r
+                               // create the terminal cloud (or flag) without having to \r
+                               // press alt.\r
+                               \r
+                               if (!startTerminals.isEmpty() && ((me.stateMask & MouseEvent.ALT_MASK) != 0 || \r
+                                               (inFlowMode() && flowInProgress()))) {\r
+                                       Pair<ConnectionJudgement, TerminalInfo> pair = canConnect(null, null);\r
+                                       if (pair != null) {\r
+                                               connectionJudgment = (ConnectionJudgement) pair.first;\r
+                                               selectedStartTerminal = pair.second;\r
+                                               createConnection();\r
+                                               setDirty();\r
+                                               remove();\r
+                                       } else {\r
+                                               // Inform the user why connection couldn't be created.\r
+                                               ErrorLogger.defaultLogWarning("Can't resolve connection type for new connection.", null);\r
+                                       }\r
+                                       return true;\r
+                               } else if (routePointsAllowed()\r
+                                               && (me.stateMask & (MouseEvent.ALT_MASK | MouseEvent.SHIFT_MASK | MouseEvent.CTRL_MASK)) == 0) {\r
+                                       // Add new connection control point.\r
+                                       controlPoints.add(newControlPointWithCalculatedDirection(mouseCanvasPos));\r
+                                       resetForcedBranchPointDirection();\r
+                                       updateSG();\r
+                               }\r
+                       }\r
+               }\r
+\r
+               return true;\r
+       }\r
+       \r
+       private boolean inFlowMode() {\r
+               return SysdynElementHints.FLOW_TOOL.equals(getHint(SysdynElementHints.SYSDYN_KEY_TOOL));\r
+       }\r
+       \r
+       private boolean flowInProgress() {\r
+               return elementClassProvider.get(ElementClasses.CONNECTION).equals(elementClassProvider.get(ConnectionClasses.FLOW));\r
+       }\r
+\r
+       @Override\r
+       protected void createConnection() {\r
+\r
+               if(this.connectionJudgment == null) return;\r
+\r
+               final ConnectionJudgement judgment = this.connectionJudgment;\r
+               // ConnectionBuilder changed to SysdynconnectionBuilder to support overlapping terminals and valve creation\r
+               final ConnectionBuilder builder = new SysdynConnectionBuilder(this.diagram);\r
+               final Deque<ControlPoint> controlPoints = this.controlPoints;\r
+               final TerminalInfo startTerminal = this.startTerminal;\r
+               final TerminalInfo endTerminal = this.endTerminal;\r
+\r
+               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               builder.create(graph, judgment, controlPoints, startTerminal, endTerminal);\r
+                       }\r
+               }, new Callback<DatabaseException>() {\r
+                       @Override\r
+                       public void run(DatabaseException parameter) {\r
+                               if (parameter != null)\r
+                                       ExceptionUtils.logAndShowError(parameter);\r
+                       }\r
+               });\r
+       }    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectionBuilder.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectionBuilder.java
new file mode 100644 (file)
index 0000000..159abc5
--- /dev/null
@@ -0,0 +1,252 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Point2D;\r
+import java.util.ArrayList;\r
+import java.util.Deque;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.content.ConnectionUtil;\r
+import org.simantics.diagram.participant.ConnectionBuilder;\r
+import org.simantics.diagram.participant.ControlPoint;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.diagram.synchronization.graph.AddElement;\r
+import org.simantics.diagram.ui.DiagramModelHints;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.diagram.handler.Topology.Terminal;\r
+import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil;\r
+import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementClasses;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;\r
+import org.simantics.g2d.element.impl.Element;\r
+import org.simantics.g2d.elementclass.FlagClass;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.structural2.modelingRules.ConnectionJudgement;\r
+import org.simantics.structural2.modelingRules.IModelingRules;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementClasses;\r
+import org.simantics.sysdyn.ui.elements.ValveFactory;\r
+import org.simantics.sysdyn.ui.elements.connections.ConnectionClasses;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class SysdynConnectionBuilder extends ConnectionBuilder{\r
+\r
+       public SysdynConnectionBuilder(IDiagram diagram) {\r
+               super(diagram);\r
+       }\r
+\r
+    /**\r
+     * @param graph\r
+     * @param judgment\r
+     * @param controlPoints\r
+     * @param startTerminal\r
+     * @param endTerminal\r
+     * @throws DatabaseException\r
+     */\r
+    public void create(WriteGraph graph, ConnectionJudgement judgment, Deque<ControlPoint> controlPoints,\r
+            TerminalInfo startTerminal, TerminalInfo endTerminal) throws DatabaseException {\r
+       // If needs a valve, we will create two separate connections\r
+        if(needsValve(startTerminal, endTerminal)) {\r
+               createValveAndConnections(graph, judgment, controlPoints, startTerminal, endTerminal);\r
+        } \r
+        // If no need for valve, just call createConnection with false on createValve parameter\r
+        else {\r
+               createConnection(graph, judgment, controlPoints, startTerminal, endTerminal, false);\r
+        }\r
+    }\r
+    /**\r
+     * @param graph\r
+     * @param judgment\r
+     * @param controlPoints\r
+     * @param startTerminal\r
+     * @param endTerminal\r
+     * @throws DatabaseException\r
+     */\r
+    public TerminalInfo createConnection(WriteGraph graph, ConnectionJudgement judgment, Deque<ControlPoint> controlPoints,\r
+            TerminalInfo startTerminal, TerminalInfo endTerminal, boolean createValve) throws DatabaseException {\r
+        TerminalInfo newValve = null;\r
+\r
+       this.cu = new ConnectionUtil(graph);\r
+\r
+        // 1. Get diagram connection to construct.\r
+        Resource connection = getOrCreateConnection(graph, startTerminal, endTerminal);\r
+        \r
+        // 1.1 Give running name to connection and increment the counter attached to the diagram.\r
+        AddElement.claimFreshElementName(graph, diagramResource, connection);\r
+\r
+        // 2. Add branch points\r
+        List<Pair<ControlPoint, Resource>> bps = createBranchPoints(graph, connection, controlPoints);\r
+        \r
+        // 3. Create edges between branch points.\r
+        Resource firstBranchPoint = null;\r
+        Resource lastBranchPoint = null;\r
+        if (!bps.isEmpty()) {\r
+            Iterator<Pair<ControlPoint, Resource>> it = bps.iterator();\r
+            Pair<ControlPoint, Resource> prev = it.next();\r
+            firstBranchPoint = prev.second;\r
+            while (it.hasNext()) {\r
+                Pair<ControlPoint, Resource> next = it.next();\r
+                cu.connect(prev.second, next.second);\r
+                prev = next;\r
+            }\r
+            lastBranchPoint = prev.second;\r
+        }\r
+\r
+        // 4. Connect start/end terminals if those exist.\r
+        // If first/lastBranchPoint != null, connect to those.\r
+        // Otherwise connect the start/end terminals together.\r
+        Connector startConnector = null;\r
+        Connector endConnector = null;\r
+        IElement startFlag = null;\r
+        IElement endFlag = null;\r
+\r
+        if (startTerminal != null) {\r
+            startConnector = createConnectorForNode(graph, connection, startTerminal, EdgeEnd.Begin, judgment);\r
+        } else if (createFlags) {\r
+            startFlag = createFlag(graph, connection, EdgeEnd.Begin, controlPoints.getFirst(), FlagClass.Type.In, "");\r
+                       ArrayList<Terminal> terminals = new ArrayList<Terminal>();\r
+                       ElementUtils.getTerminals(startFlag, terminals, false);\r
+                       Terminal st = terminals.get(1);\r
+            startConnector = createConnectorForNode(graph, connection, (Resource) ElementUtils.getObject(startFlag),\r
+                    st, EdgeEnd.Begin, judgment);\r
+        }\r
+\r
+        if (endTerminal != null) {\r
+            endConnector = createConnectorForNode(graph, connection, endTerminal, EdgeEnd.End, judgment);\r
+        } else if (createFlags) {\r
+               if(createValve)\r
+                endFlag = createValveElement(graph, connection, EdgeEnd.End, controlPoints.getLast());\r
+               else\r
+                       endFlag = createFlag(graph, connection, EdgeEnd.End, controlPoints.getLast(), FlagClass.Type.Out, "");\r
+                       ArrayList<Terminal> terminals = new ArrayList<Terminal>();\r
+                       ElementUtils.getTerminals(endFlag, terminals, false);\r
+                       Terminal et = terminals.get(0);\r
+            endConnector = createConnectorForNode(graph, connection, (Resource) ElementUtils.getObject(endFlag),\r
+                    et, EdgeEnd.End, judgment);\r
+            \r
+            if(createValve) {\r
+               newValve = new TerminalInfo();\r
+               newValve.e = endFlag;\r
+               newValve.t = terminals.get(1);\r
+               newValve.posElem = TerminalUtil.getTerminalPosOnElement(endFlag, newValve.t);\r
+               newValve.posDia = TerminalUtil.getTerminalPosOnDiagram(endFlag, newValve.t);\r
+            }\r
+        }\r
+\r
+        if (firstBranchPoint == null || lastBranchPoint == null) {\r
+            cu.connect(startConnector.getConnector(), endConnector.getConnector());\r
+        } else {\r
+            cu.connect(startConnector.getConnector(), firstBranchPoint);\r
+            cu.connect(lastBranchPoint, endConnector.getConnector());\r
+        }\r
+\r
+        // 5. Finally, set connection type according to modelling rules\r
+        IModelingRules modelingRules = diagram.getHint(DiagramModelHints.KEY_MODELING_RULES);\r
+        if (judgment.connectionType != null && modelingRules != null) {\r
+            modelingRules.setConnectionType(graph, connection, judgment.connectionType);\r
+        }\r
+\r
+        this.cu = null;\r
+        return newValve;\r
+    }\r
+    \r
+    \r
+    /**\r
+     * @param graph\r
+     * @param connection\r
+     * @param end\r
+     * @param cp\r
+     * @param type\r
+     * @return an element describing the new created flag resource\r
+     * @throws DatabaseException\r
+     */\r
+    public IElement createValveElement(WriteGraph graph, Resource connection, EdgeEnd end, ControlPoint cp) throws DatabaseException {\r
+        ElementClass valveClass = elementClassProvider.get(SysdynElementClasses.VALVE);\r
+        IElement valveElement = Element.spawnNew(valveClass);\r
+        Resource valveClassResource = ElementUtils.checkedAdapt(valveClass, Resource.class);\r
+\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        G2DResource G2D = G2DResource.getInstance(graph);\r
+        DiagramResource DIA = DiagramResource.getInstance(graph);\r
+\r
+        Resource valve = graph.newResource();\r
+        graph.claim(valve, L0.InstanceOf, null, valveClassResource);\r
+        graph.claim(valve, L0.PartOf, diagramResource);\r
+        AddElement.claimFreshElementName(graph, diagramResource, valve);\r
+        valveElement.setHint(ElementHints.KEY_OBJECT, valve);\r
+\r
+        OrderedSetUtils.add(graph, diagramResource, valve);\r
+\r
+        AffineTransform at = AffineTransform.getTranslateInstance(cp.getPosition().getX(), cp.getPosition().getY());\r
+        valveElement.setHint(ElementHints.KEY_TRANSFORM, at);\r
+        double[] matrix = new double[6];\r
+        at.getMatrix(matrix);\r
+        graph.claimLiteral(valve, DIA.HasTransform, G2D.Transform, matrix);\r
+\r
+        // Put the element on all the currently active layers if possible.\r
+        if (layerManager != null) {\r
+            layerManager.removeFromAllLayers(graph, valve);\r
+            layerManager.putElementOnVisibleLayers(diagram, graph, valve);\r
+        }\r
+\r
+        return valveElement;\r
+    }\r
+    \r
+    private boolean needsValve(TerminalInfo startTerminal, TerminalInfo endTerminal) {\r
+               if (!elementClassProvider.get(ElementClasses.CONNECTION)\r
+                               .equals(elementClassProvider.get(ConnectionClasses.FLOW))) \r
+                       return false;\r
+               if(startTerminal != null && startTerminal.e != null && startTerminal.e.getElementClass().getId().equals(ValveFactory.class.getSimpleName())) {\r
+                       return false;\r
+               } else if(endTerminal != null && endTerminal.e != null && endTerminal.e.getElementClass().getId().equals(ValveFactory.class.getSimpleName())) {\r
+                       return false;\r
+               }\r
+               return true;\r
+    }\r
+    \r
+    private void createValveAndConnections(WriteGraph graph, ConnectionJudgement judgment, Deque<ControlPoint> controlPoints,\r
+            TerminalInfo startTerminal, TerminalInfo endTerminal) throws DatabaseException {\r
+       \r
+               ControlPoint cpfirst = controlPoints.getFirst();\r
+               ControlPoint cplast = controlPoints.getLast();\r
+\r
+               // Set the position in the middle of the route\r
+               double startX = cpfirst.getPosition().getX();\r
+               double startY = cpfirst.getPosition().getY();\r
+               double x = cplast.getPosition().getX();\r
+               double y = cplast.getPosition().getY();\r
+               Point2D pos = new Point2D.Double(startX - (startX - x) / 2, startY - (startY - y) / 2);\r
+               \r
+               // Replace the last control point with the control point in the middle\r
+        controlPoints.getLast().setPosition(pos);\r
+\r
+        // Create a connection to a new valve and get the new valve\r
+        TerminalInfo newValve = createConnection(graph, judgment, controlPoints, startTerminal, null, true);\r
+        \r
+               // Replace the last control point with the original control point\r
+        controlPoints.getLast().setPosition(x, y);\r
+        \r
+        // Create a connection starting from the new valve\r
+               createConnection(graph, judgment, controlPoints, newValve, endTerminal, false);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynCopyPasteStrategy.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynCopyPasteStrategy.java
new file mode 100644 (file)
index 0000000..2c5c0dd
--- /dev/null
@@ -0,0 +1,237 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.handler.CopyPasteUtil;\r
+import org.simantics.diagram.handler.DefaultCopyPasteStrategy;\r
+import org.simantics.diagram.handler.ElementObjectAssortment;\r
+import org.simantics.diagram.handler.PasteOperation;\r
+import org.simantics.diagram.handler.Paster;\r
+import org.simantics.diagram.handler.Paster.NodeMap;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+\r
+/**\r
+ *  A copy-paste-strategy that changes variable names in the equations of copied variables.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SysdynCopyPasteStrategy extends DefaultCopyPasteStrategy {\r
+    \r
+    @Override\r
+    public void paste(final PasteOperation op) {\r
+        try {\r
+            Session session = Simantics.getSession();\r
+            if (op.sameDiagram()) {\r
+               if (op.cut) {\r
+                       CopyPasteUtil.localCutPaste(op);\r
+                       return;\r
+               }\r
+            } else {\r
+                if (CopyPasteUtil.onlyFlagsWithoutCorrespondence(session, op.ea)\r
+                        && CopyPasteUtil.checkFlagExternality(session, op.ea.flags, false)) {\r
+                    CopyPasteUtil.continueFlags(op);\r
+                    return;\r
+                } else {\r
+                       // Deny operation if copying shadow without original.\r
+                       if (copyingShadowWithoutOriginal(session, op.ea)) {\r
+                               PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+                                   public void run() {\r
+                                           Shell activeShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
+                                           MessageDialog.openError(\r
+                                                       activeShell, \r
+                                                       "Error in pasting variables", \r
+                                                       "Cannot paste a shadow variable to another diagram without the original variable. " +\r
+                                                       "Shadow variables referring to a variable in another diagram are not supported in " +\r
+                                                       "the current version.");\r
+                                       }\r
+                               });\r
+                               return;\r
+                       }\r
+                       if (op.cut) {\r
+                               // Deny cut if cutting variable which has shadow that is not in the same cut operation. \r
+                               if (cuttingOriginalWithoutAllShadows(session, op.ea)) {\r
+                               PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+                                   public void run() {\r
+                                           Shell activeShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
+                                           MessageDialog.openError(\r
+                                                       activeShell, \r
+                                                       "Error in pasting variables", \r
+                                                       "Cannot cut and paste a variable to another diagram without all of its shadows.");\r
+                                       }\r
+                               });\r
+                               return;\r
+                       }\r
+                       }\r
+                }\r
+            }\r
+            Paster paster = new Paster(session, op);\r
+            paster.perform();\r
+\r
+            // Change shadow originals for all shadows of which original is also copied.\r
+               replaceCopiedShadowOriginalsWithCreatedOnes(session, paster.getNodeMap());\r
+\r
+            renameVariablesInEquations(session, paster.getNodeMap());\r
+        } catch (DatabaseException e) {\r
+            ErrorLogger.defaultLogError(e);\r
+        }\r
+    }\r
+    \r
+    private static boolean cuttingOriginalWithoutAllShadows(Session session, final ElementObjectAssortment ea) throws DatabaseException {\r
+        return session.syncRequest(new Read<Boolean>() {\r
+               \r
+               @Override\r
+               public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                               for (Resource r : ea.nodeList) {\r
+                                       ModelingResources MOD = ModelingResources.getInstance(graph); \r
+                                       SysdynResource SR = SysdynResource.getInstance(graph); \r
+                                       if (graph.isInstanceOf(r, SR.StockSymbol)\r
+                                                       || graph.isInstanceOf(r, SR.AuxiliarySymbol)\r
+                                                       || graph.isInstanceOf(r, SR.ValveSymbol)\r
+                                                       || graph.isInstanceOf(r, SR.InputSymbol)) {\r
+                                               Resource component = graph.getPossibleObject(r, MOD.ElementToComponent);\r
+                                               Collection<Resource> shadows = graph.getObjects(component, SR.Shadow_original_Inverse);\r
+                                               for (Resource shadow : shadows) {\r
+                                                       Resource shadowElement = graph.getPossibleObject(shadow, MOD.ComponentToElement);\r
+                                                       if (!ea.nodes.contains(shadowElement))\r
+                                                               return true;\r
+                                               }\r
+                                               \r
+                                       }\r
+                           }\r
+                               return false;\r
+            }\r
+               });\r
+    }\r
+    \r
+    private static boolean copyingShadowWithoutOriginal(Session session, final ElementObjectAssortment ea) throws DatabaseException {\r
+        return session.syncRequest(new Read<Boolean>() {\r
+               \r
+               @Override\r
+               public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                               for (Resource r : ea.nodeList) {\r
+                                       ModelingResources MOD = ModelingResources.getInstance(graph); \r
+                                       SysdynResource SR = SysdynResource.getInstance(graph); \r
+                                       if (graph.isInstanceOf(r, SR.ShadowSymbol)) {\r
+                                               Resource component = graph.getPossibleObject(r, MOD.ElementToComponent);\r
+                                               Resource original = graph.getPossibleObject(component, SR.Shadow_original);\r
+                                               Resource originalElement = graph.getPossibleObject(original, MOD.ComponentToElement);\r
+                                               if (!ea.nodes.contains(originalElement))\r
+                                                       return true;\r
+                                       }\r
+                           }\r
+                               return false;\r
+            }\r
+               });\r
+    }\r
+    \r
+    private void replaceCopiedShadowOriginalsWithCreatedOnes(Session session, final NodeMap nodeMap) {\r
+       session.asyncRequest(new WriteRequest() {\r
+            \r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+               ModelingResources MOD = ModelingResources.getInstance(graph); \r
+                               SysdynResource SR = SysdynResource.getInstance(graph); \r
+                               if (nodeMap == null)\r
+                                       return;\r
+                               Set<Resource> allResources = nodeMap.allResources();\r
+               for (Resource r : allResources) {\r
+                       // Go through all shadows\r
+                       if (graph.isInstanceOf(r, SR.ShadowSymbol)) {\r
+                               // See if the original of the shadow is copied\r
+                               Resource shadowComponent = graph.getPossibleObject(r, MOD.ElementToComponent);\r
+                                               Resource original = graph.getPossibleObject(shadowComponent, SR.Shadow_original);\r
+                                               Resource originalElement = graph.getPossibleObject(original, MOD.ComponentToElement);\r
+                                               Resource copiedOriginal = nodeMap.getResource(originalElement);\r
+                                               \r
+                               // If original is copied, change the copy shadow original to point to the new variable.\r
+                                               if (copiedOriginal != null) {\r
+                                                       Resource copiedShadow = nodeMap.getResource(r);\r
+                                                       Resource copiedShadowComponent = graph.getPossibleObject(copiedShadow, MOD.ElementToComponent);\r
+                                                       graph.deny(copiedShadowComponent, SR.Shadow_original);\r
+                                                       Resource copiedOriginalComponent = graph.getPossibleObject(copiedOriginal, MOD.ElementToComponent);;\r
+                                                       graph.claim(copiedShadowComponent, SR.Shadow_original, copiedOriginalComponent);\r
+                                               }\r
+                       }\r
+               }\r
+            }\r
+        });\r
+    }\r
+\r
+    \r
+    /**\r
+     * Rename variables in equations that need to be renamed.\r
+     * \r
+     * 1. Find the original variables and their names that were copied\r
+     * 2. For each copied variables, modify its equations. If equation had a reference\r
+     * to another copied variable, it needs to be modified. \r
+     * @param session\r
+     * @param nodeMap\r
+     */\r
+    private void renameVariablesInEquations(Session session, final NodeMap nodeMap) {\r
+        session.asyncRequest(new WriteRequest() {\r
+            \r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                Set<Resource> copies = new HashSet<Resource>();\r
+                HashMap<String, String> names = new HashMap<String, String>();\r
+                \r
+                ModelingResources MOD = ModelingResources.getInstance(graph);\r
+                // Collect copied variables and their names\r
+                if (nodeMap == null)\r
+                       return;\r
+                for(Resource var : nodeMap.allResources()) {\r
+                    Resource comp = graph.getPossibleObject(var, MOD.ElementToComponent);\r
+                    \r
+                    Resource r = nodeMap.getResource(var);\r
+                    Resource copy = graph.getPossibleObject(r, MOD.ElementToComponent);\r
+\r
+                    if(comp != null && copy != null) {\r
+                        names.put(NameUtils.getSafeName(graph, comp), NameUtils.getSafeName(graph, copy));\r
+                        copies.add(copy);\r
+                    }\r
+                }\r
+                \r
+                // Change equations only from copied variables\r
+                for(Resource copy : copies) {\r
+                    // Check for each name individually\r
+                    for(String originalName : names.keySet()) {\r
+                        String newName = names.get(originalName);\r
+                        new VariableNameValidator().renameInEquations(graph, copy, originalName, newName);\r
+                    }\r
+                }\r
+            }\r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynElementClassProviders.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynElementClassProviders.java
new file mode 100644 (file)
index 0000000..93c5675
--- /dev/null
@@ -0,0 +1,69 @@
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementClassProviders;\r
+import org.simantics.g2d.element.IElementClassProvider;\r
+\r
+public class SysdynElementClassProviders extends ElementClassProviders {\r
+       \r
+    /**\r
+     * Create an element class provider that based on the specified map. The\r
+     * provider will directly access the map with the received keys. The\r
+     * argument map will be copied.\r
+     * \r
+     * @param map the map to use for element class provision\r
+     * @return <code>null</code> if there is no provider for the specified key\r
+     */\r
+    public static IElementClassProvider mappedProvider(Map<Object, ElementClass> map) {\r
+        // Copy the map as a safety measure\r
+        final Map<Object, ElementClass> copy = new HashMap<Object, ElementClass>(map);\r
+        return new ISysdynElementClassProvider() {\r
+            @Override\r
+            public ElementClass get(Object key) {\r
+                return copy.get(key);\r
+            }\r
+\r
+                       @Override\r
+                       public void put(Object key, ElementClass value) {\r
+                               copy.put(key, value);\r
+                       }\r
+\r
+        };\r
+    }\r
+    \r
+    /**\r
+     * Does the same as {@link #mappedProvider(Map)}, the map is simply provided\r
+     * differently. The specified array must contain\r
+     * <code>[key, ElementClass, key, ElementClass, ...]</code>.\r
+     * \r
+     * @param map the map to use for element class provision\r
+     * @return <code>null</code> if there is no provider for the specified key\r
+     */\r
+    public static IElementClassProvider mappedProvider(Object... keyClassPairs) {\r
+        if (keyClassPairs.length % 2 != 0)\r
+            throw new IllegalArgumentException();\r
+        Map<Object, ElementClass> map = new HashMap<Object, ElementClass>();\r
+        int n = keyClassPairs.length / 2;\r
+        for (int i = 0; i < n; ++i) {\r
+            Object key = keyClassPairs[i * 2];\r
+            Object elementClass = keyClassPairs[i*2+1];\r
+            if (!(elementClass instanceof ElementClass))\r
+                throw new IllegalArgumentException("not an ElementClass instance: "  + elementClass);\r
+            map.put(key, (ElementClass) elementClass);\r
+        }\r
+        return mappedProvider(map);\r
+    }\r
+\r
+\r
+       public interface ISysdynElementClassProvider extends IElementClassProvider {\r
+               \r
+               /**\r
+                * Update a value in an IElementClassProvider\r
+                */\r
+           void put(Object key, ElementClass value);\r
+           \r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynPointerInteractor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynPointerInteractor.java
new file mode 100644 (file)
index 0000000..ef74d7b
--- /dev/null
@@ -0,0 +1,186 @@
+package org.simantics.sysdyn.ui.editor.participant;\r
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+\r
+import java.awt.Shape;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.List;\r
+\r
+import org.simantics.g2d.canvas.Hints;\r
+import org.simantics.g2d.canvas.ICanvasParticipant;\r
+import org.simantics.g2d.canvas.IToolMode;\r
+import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;\r
+import org.simantics.g2d.canvas.impl.DependencyReflection.Reference;\r
+import org.simantics.g2d.connection.IConnectionAdvisor;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.handler.PickContext;\r
+import org.simantics.g2d.diagram.handler.PickRequest.PickSorter;\r
+import org.simantics.g2d.diagram.participant.Selection;\r
+import org.simantics.g2d.diagram.participant.TerminalPainter;\r
+import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;\r
+import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil;\r
+import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;\r
+import org.simantics.g2d.element.ElementClasses;\r
+import org.simantics.g2d.element.IElementClassProvider;\r
+import org.simantics.g2d.participant.KeyUtil;\r
+import org.simantics.g2d.participant.MouseUtil;\r
+import org.simantics.g2d.participant.TransformUtil;\r
+import org.simantics.g2d.utils.GeometryUtils;\r
+import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;\r
+import org.simantics.sysdyn.ui.editor.participant.SysdynElementClassProviders.ISysdynElementClassProvider;\r
+import org.simantics.sysdyn.ui.editor.routing.DependencyRouter;\r
+import org.simantics.sysdyn.ui.editor.routing.FlowRouter;\r
+import org.simantics.sysdyn.ui.elements.AuxiliaryFactory;\r
+import org.simantics.sysdyn.ui.elements.CloudFactory;\r
+import org.simantics.sysdyn.ui.elements.InputFactory;\r
+import org.simantics.sysdyn.ui.elements.ModuleFactory;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementHints;\r
+import org.simantics.sysdyn.ui.elements.connections.ConnectionClasses;\r
+\r
+/**\r
+ * Pointer tool does the following operations with mouse:\r
+ *   - Selections\r
+ *   - Scale\r
+ *   - Rotate\r
+ *   - Translate\r
+ *   - Draws connections\r
+ *\r
+ * Pointer tool is active only when KEY_TOOLMODE is PointerToolMode\r
+ *\r
+ * TODO Pick rectangle not a point\r
+ *\r
+ * @author Toni Kalajainen\r
+ */\r
+public class SysdynPointerInteractor extends PointerInteractor {\r
+\r
+       @Dependency Selection selection;\r
+       @Dependency KeyUtil keys;\r
+       @Dependency TransformUtil util;\r
+       @Dependency PickContext pickContext;\r
+       @Dependency MouseUtil mice;\r
+       @Reference TerminalPainter terminalPainter;\r
+\r
+       public SysdynPointerInteractor(boolean clickSelect, boolean boxSelect, boolean dragElement, boolean dndDragElement, boolean connect, boolean doubleClickEdit, IElementClassProvider newConnectionClassProvider, PickSorter pickSorter) {\r
+               super(clickSelect, boxSelect, dragElement, dndDragElement, connect, doubleClickEdit, newConnectionClassProvider, pickSorter);\r
+       }\r
+\r
+       @Override\r
+       @EventHandler(priority = TOOL_PRIORITY)\r
+       public boolean handlePress(MouseButtonPressedEvent me) {\r
+               if (!connects()) \r
+                       return false;\r
+               if (elementClassProvider == null)\r
+                       return false;\r
+               \r
+               // There should (maybe) be only one sysdynConnectTool associated with \r
+               // the canvas context at a time. If this is not the case, right-clicks\r
+               // are not always handled correctly mid-connection as they are instead \r
+               // treated as commands to create a new cloud and a new flow. There\r
+               // might be a more sensible way to fix this.\r
+               if (getContext().containsItemByClass(SysdynConnectTool.class)) {\r
+                       return false;\r
+               }\r
+               \r
+               IToolMode mode = getHint(Hints.KEY_TOOL);\r
+               if (!Hints.CONNECTTOOL.equals(mode))\r
+                       return false;\r
+               \r
+               IToolMode sysdynMode = getHint(SysdynElementHints.SYSDYN_KEY_TOOL);\r
+               \r
+               assertDependencies();\r
+               \r
+               TerminalInfo ti = pickTerminal(me.controlPosition);\r
+               Point2D curCanvasPos = util.controlToCanvas(me.controlPosition, null);\r
+               \r
+               ICanvasParticipant bsi = null;\r
+               \r
+               if (me.button == MouseEvent.LEFT_BUTTON) {\r
+                       if (SysdynElementHints.LOCK_TOOL.equals(sysdynMode))\r
+                               // Do nothing.\r
+                               return false;\r
+                       else if (SysdynElementHints.DEPENDENCY_TOOL.equals(sysdynMode))\r
+                               bsi = getDependencyConnectTool(ti, me.mouseId, curCanvasPos);\r
+                       else if (SysdynElementHints.FLOW_TOOL.equals(sysdynMode))\r
+                               bsi = getFlowConnectTool(ti, me.mouseId, curCanvasPos);\r
+                       else\r
+                               bsi = getDependencyConnectTool(ti, me.mouseId, curCanvasPos);\r
+               }\r
+               else if (me.button == MouseEvent.RIGHT_BUTTON) {\r
+                       if (SysdynElementHints.LOCK_TOOL.equals(sysdynMode) ||\r
+                                       SysdynElementHints.DEPENDENCY_TOOL.equals(sysdynMode) ||\r
+                                       SysdynElementHints.FLOW_TOOL.equals(sysdynMode))\r
+                               return false;\r
+                       else\r
+                               bsi = getFlowConnectTool(ti, me.mouseId, curCanvasPos);\r
+               }\r
+               \r
+               if (bsi != null) {\r
+                       getContext().add(bsi);\r
+                       return true;\r
+               }\r
+               \r
+               return false;\r
+       }\r
+       \r
+       private ICanvasParticipant getDependencyConnectTool(TerminalInfo ti, int mouseId, Point2D curCanvasPos) {\r
+               // can not have dependencies that start from thin air\r
+               if (ti == null)\r
+                       return null;\r
+               // can not have dependencies that start from clouds\r
+               if (ti.e.getElementClass().getId().equals(CloudFactory.class.getSimpleName())) \r
+                       return null;\r
+               \r
+               diagram.setHint(DiagramHints.ROUTE_ALGORITHM, new DependencyRouter());\r
+               diagram.setHint(DiagramHints.KEY_USE_CONNECTION_FLAGS, false);\r
+               ISysdynElementClassProvider secp = (ISysdynElementClassProvider)elementClassProvider;\r
+               secp.put(ElementClasses.CONNECTION, elementClassProvider.get(ConnectionClasses.DEPENDENCY));\r
+\r
+               // not sure if this is necessary\r
+               IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);\r
+               if (advisor == null || advisor.canBeginConnection(null, ti.e, ti.t)) {\r
+                       return new SysdynConnectTool(ti, mouseId, curCanvasPos);\r
+               }\r
+               \r
+               return null;\r
+       }\r
+       \r
+       private ICanvasParticipant getFlowConnectTool(TerminalInfo ti, int mouseId, Point2D curCanvasPos) {\r
+               // flows must not start from auxiliaries, inputs or modules\r
+               if (ti != null && (ti.e.getElementClass().getId().equals(AuxiliaryFactory.class.getSimpleName()) || \r
+                               ti.e.getElementClass().getId().equals(InputFactory.class.getSimpleName()) || \r
+                               ti.e.getElementClass().getId().equals(ModuleFactory.class.getSimpleName()))) \r
+                       return null;\r
+               \r
+               diagram.setHint(DiagramHints.ROUTE_ALGORITHM, new FlowRouter());\r
+               diagram.setHint(DiagramHints.KEY_USE_CONNECTION_FLAGS, true);\r
+               ISysdynElementClassProvider secp = (ISysdynElementClassProvider)elementClassProvider;\r
+               secp.put(ElementClasses.CONNECTION, elementClassProvider.get(ConnectionClasses.FLOW));\r
+               \r
+               // not sure if this is necessary\r
+               IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);\r
+               if (ti == null || advisor == null || advisor.canBeginConnection(null, ti.e, ti.t)) {\r
+                       return new SysdynConnectTool(ti, mouseId, curCanvasPos);\r
+               }\r
+               \r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public List<TerminalInfo> pickTerminals(Point2D controlPos) {\r
+               Rectangle2D controlPickRect = new Rectangle2D.Double(controlPos.getX()-SysdynPointerInteractor.PICK_DIST, controlPos.getY()-SysdynPointerInteractor.PICK_DIST, SysdynPointerInteractor.PICK_DIST*2+1, SysdynPointerInteractor.PICK_DIST*2+1);\r
+               Shape       canvasPickRect  = GeometryUtils.transformShape(controlPickRect, util.getInverseTransform());\r
+               return TerminalUtil.pickTerminals(diagram, canvasPickRect, false, true);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynPopulateElementDropParticipant.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynPopulateElementDropParticipant.java
new file mode 100644 (file)
index 0000000..f15307c
--- /dev/null
@@ -0,0 +1,82 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import java.awt.dnd.DropTargetDragEvent;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;\r
+import org.simantics.diagram.ui.DiagramModelHints;\r
+import org.simantics.g2d.dnd.ElementClassDragItem;\r
+import org.simantics.g2d.dnd.IDnDContext;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.ui.diagramEditor.PopulateElementDropParticipant;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class SysdynPopulateElementDropParticipant extends PopulateElementDropParticipant {\r
+\r
+       public SysdynPopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer) {\r
+               super(synchronizer);\r
+       }\r
+\r
+    @Override\r
+    public void dragEnter(DropTargetDragEvent dtde, IDnDContext dp) {\r
+        super.dragEnter(dtde, dp);\r
+        \r
+        // Check that user is not trying to populate a module to itself. \r
+        // This doesn't prevent infinite recursion if there is one module between two exactly the same modules.\r
+        // e.g. WorkModule -> WokrforceModule -> WorkModule creates an infinite recursion\r
+        final Collection<ElementClassDragItem> items = dp.getItemsByClass(ElementClassDragItem.class);\r
+        if(!items.isEmpty()) {\r
+                Collection<ElementClassDragItem> unvalidModules = null;\r
+               try {\r
+                       unvalidModules = synchronizer.getSession().syncRequest(new Read<Collection<ElementClassDragItem>>() {\r
+\r
+                                       @Override\r
+                                       public Collection<ElementClassDragItem> perform(ReadGraph graph)\r
+                                                       throws DatabaseException {\r
+                                                Collection<ElementClassDragItem> unvalidModules = new ArrayList<ElementClassDragItem>();\r
+                                               for(ElementClassDragItem item : items) {\r
+                                                       StaticObjectAdapter soa = item.getElementClass().getSingleItem(StaticObjectAdapter.class);\r
+                                                       Resource type = soa.adapt(Resource.class);\r
+                                                       \r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       if(graph.isInheritedFrom(type, sr.ModuleSymbol)) {\r
+                                               Resource module = graph.getSingleObject(type, ModelingResources.getInstance(graph).SymbolToComponentType);\r
+                                               Resource configuration = graph.getSingleObject(module, StructuralResource2.getInstance(graph).IsDefinedBy);\r
+                                               Resource dia = graph.getSingleObject(configuration, ModelingResources.getInstance(graph).CompositeToDiagram);\r
+                                               Resource editorDia = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);\r
+                                               if(dia.equals(editorDia))\r
+                                                       unvalidModules.add(item);\r
+                                       }\r
+                                               }\r
+                                               return unvalidModules;\r
+                                       }\r
+                               });\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+                       if(!unvalidModules.isEmpty()) {\r
+                               for(ElementClassDragItem item : unvalidModules) {\r
+                                       dp.remove(item);\r
+                               }\r
+                       }\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynSpecialComponentCopyAdvisor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynSpecialComponentCopyAdvisor.java
new file mode 100644 (file)
index 0000000..40c3835
--- /dev/null
@@ -0,0 +1,44 @@
+package org.simantics.sysdyn.ui.editor.participant;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.synchronization.ISynchronizationContext;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ComponentUtils;\r
+\r
+/**\r
+ * Copy advisor for copying sysdyn elements with custom prefix and/or suffix\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynSpecialComponentCopyAdvisor extends SysdynComponentCopyAdvisor {\r
+    \r
+    private String prefix = "";\r
+    private String suffix = "";\r
+    \r
+    public SysdynSpecialComponentCopyAdvisor(String prefix, String suffix) {\r
+        this.prefix = prefix;\r
+        this.suffix = suffix;\r
+    }\r
+    \r
+    @Override\r
+    public String rename(ISynchronizationContext context, WriteGraph graph, Resource source,\r
+            Resource copy, Resource sourceContainer, Resource targetContainer) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        String copyName = NameUtils.getSafeName(graph, copy);\r
+        Resource configurationRoot = ComponentUtils.getCompositeConfigurationRoot(graph, targetContainer);\r
+        \r
+        if(prefix == null)\r
+            prefix = "";\r
+        if(suffix == null)\r
+            suffix = "";\r
+        \r
+        String name =  NameUtils.findFreshName(graph, prefix + copyName + suffix, configurationRoot, l0.ConsistsOf, "%s%d");\r
+        graph.claimLiteral(copy, l0.HasName, name, Bindings.STRING);\r
+        return name;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/DependencyRouter.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/DependencyRouter.java
new file mode 100644 (file)
index 0000000..2cab67e
--- /dev/null
@@ -0,0 +1,189 @@
+package org.simantics.sysdyn.ui.editor.routing;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Shape;\r
+import java.awt.Stroke;\r
+import java.awt.geom.Arc2D;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.g2d.routing.IConnection;\r
+import org.simantics.g2d.routing.IConnection.Connector;\r
+import org.simantics.g2d.routing.IRouter2;\r
+import org.simantics.sysdyn.ui.elements.connections.Arcs;\r
+import org.simantics.sysdyn.ui.elements.connections.DependencyEdgeClass;\r
+import org.simantics.utils.datastructures.Triple;\r
+\r
+public class DependencyRouter implements IRouter2 {\r
+    \r
+    public static DependencyRouter INSTANCE = new DependencyRouter();\r
+\r
+       @Override\r
+       public void route(IConnection connection) {\r
+               if(connection.getSegments().isEmpty())\r
+                       return;\r
+               Object seg = connection.getSegments().iterator().next();\r
+        Connector begin = connection.getBegin(seg);\r
+        Connector end = connection.getEnd(seg);\r
+        \r
+        Triple<Arc2D, Path2D, Path2D> shapes = new Triple<Arc2D, Path2D, Path2D>(new Arc2D.Double(), new Path2D.Double(), new Path2D.Double());\r
+        createArrowShape(shapes,\r
+                       begin.parentObstacle,\r
+                       end.parentObstacle,\r
+                       0.3,\r
+                       null);\r
+        \r
+        Path2D path = new Path2D.Double();\r
+        path.append(shapes.first, false);\r
+        path.append(shapes.second, false);\r
+        connection.setPath(seg, path);\r
+       }\r
+\r
+       \r
+       /*\r
+        * Total length of the arrow is ARROW_LENGTH1 + ARROW_LENGTH2\r
+        */\r
+    public static double ARROW_LENGTH1 = 0.1;\r
+    public static double ARROW_LENGTH2 = 1.9;\r
+    public static double ARROW_WIDTH = 0.7;\r
+    public static double DELAYMARK_LENGTH = 6;\r
+    public static double DELAYMARK_GAP = 0.4;\r
+    \r
+\r
+       private static Path2D createArrow(Path2D shape, double x, double y, double dx, double dy) {\r
+               if(shape == null)\r
+                       shape = new Path2D.Double();\r
+               else\r
+                       shape.reset();\r
+               \r
+        shape.moveTo(x+ARROW_LENGTH1*dx, y+ARROW_LENGTH1*dy);\r
+        x -= ARROW_LENGTH2*dx;\r
+        y -= ARROW_LENGTH2*dy;\r
+        shape.lineTo(x-ARROW_WIDTH*dy, y+ARROW_WIDTH*dx);\r
+        shape.lineTo(x+ARROW_WIDTH*dy, y-ARROW_WIDTH*dx);\r
+        shape.closePath();\r
+        return shape;\r
+    }\r
+       \r
+       public static Arc2D createArc(Arc2D arc, Shape beginBounds, Shape endBounds, double angle) {\r
+               if (beginBounds == null || endBounds == null)\r
+                       return new Arc2D.Double();\r
+               double x0 = beginBounds.getBounds2D().getCenterX();\r
+        double y0 = beginBounds.getBounds2D().getCenterY();\r
+        double x1 = endBounds.getBounds2D().getCenterX();\r
+        double y1 = endBounds.getBounds2D().getCenterY();\r
+        \r
+//        System.out.println("createArrowShape " + x0 + " " + y0 + " " + x1 + " " + y1);\r
+        \r
+        double offset = \r
+            Math.abs(angle) < 1.0e-6\r
+            ? 1e3 * Math.signum(angle)\r
+            : Math.tan(Math.PI*0.5-angle)*0.5;\r
+            \r
+        double cx = 0.5*(x0+x1) + offset * (y1-y0);\r
+        double cy = 0.5*(y0+y1) + offset * (x0-x1);\r
+        double dx0 = x0 - cx;\r
+        double dy0 = y0 - cy;\r
+        double dx1 = x1 - cx;\r
+        double dy1 = y1 - cy;\r
+        \r
+        double r = Math.sqrt(dx0*dx0 + dy0*dy0);\r
+        \r
+//        Rectangle2D bounds = new Rectangle2D.Double();\r
+//        tail.getBounds(bounds);\r
+        double angle0 = Arcs.nextIntersectingAngle(cx, cy, r, \r
+            Math.atan2(-dy0, dx0), beginBounds, angle < 0.0);\r
+//        head.getBounds(bounds);\r
+        double angle1 = Arcs.nextIntersectingAngle(cx, cy, r, \r
+            Math.atan2(-dy1, dx1), endBounds, angle > 0.0);\r
+        double extent = angle1-angle0;\r
+        //double arcAngle = angle0;\r
+        if(angle < 0.0) {\r
+            double temp = angle0;            \r
+            angle0 = angle1;\r
+            angle1 = temp;\r
+            extent = -extent;\r
+        }                \r
+        if(extent < 0)\r
+            extent += Math.PI*2.0;\r
+        else if(extent >= 360.0)\r
+            extent -= Math.PI*2.0;\r
+        if(arc == null)\r
+               arc = new Arc2D.Double();\r
+        arc.setArc(cx-r, cy-r, 2*r, 2*r, \r
+            Math.toDegrees(angle0), \r
+            Math.toDegrees(extent), \r
+            Arc2D.OPEN);\r
+//        \r
+               return arc;\r
+       }\r
+       \r
+       public static Point2D computeCenter(Rectangle2D tail, Rectangle2D head, double angle) {\r
+\r
+               double x0 = tail.getCenterX();\r
+        double y0 = tail.getCenterY();\r
+        double x1 = head.getCenterX();\r
+        double y1 = head.getCenterY();\r
+        \r
+//        System.out.println("createArrowShape " + x0 + " " + y0 + " " + x1 + " " + y1);\r
+        \r
+        double offset = \r
+            Math.abs(angle) < 1.0e-6\r
+            ? 1e3 * Math.signum(angle)\r
+            : Math.tan(Math.PI*0.5-angle)*0.5;\r
+            \r
+        double cx = 0.5*(x0+x1) + offset * (y1-y0);\r
+        double cy = 0.5*(y0+y1) + offset * (x0-x1);\r
+        \r
+        return new Point2D.Double(cx, cy);\r
+               \r
+       }\r
+       \r
+\r
+       public static Path2D createDelayMark(Path2D shape, double x, double y, double angle, BasicStroke stroke) {\r
+               if(shape == null)\r
+                       shape = new Path2D.Double();\r
+               else\r
+                       shape.reset();\r
+               \r
+               float strokeWidth = stroke != null ? stroke.getLineWidth() : DependencyEdgeClass.DEFAULT_STROKE_WIDTH;\r
+               \r
+               double dx = Math.cos(angle) * (DELAYMARK_LENGTH + strokeWidth) / 2; \r
+               double dy = -Math.sin(angle) * (DELAYMARK_LENGTH + strokeWidth) / 2; \r
+               double dxGap = Math.cos(angle + Math.PI / 2) * (DELAYMARK_GAP / 2 + strokeWidth); \r
+               double dyGap = -Math.sin(angle + Math.PI / 2) * (DELAYMARK_GAP / 2 + strokeWidth);\r
+        shape.moveTo(x - dx - dxGap, y - dy - dyGap);\r
+        shape.lineTo(x + dx - dxGap, y + dy - dyGap);\r
+        shape.moveTo(x - dx + dxGap, y - dy + dyGap);\r
+        shape.lineTo(x + dx + dxGap, y + dy + dyGap);\r
+        return shape;\r
+       }\r
+       \r
+       public static Triple<Arc2D, Path2D, Path2D> createArrowShape(Triple<Arc2D, Path2D, Path2D> shapes, Shape beginBounds, Shape endBounds, double angle, Stroke stroke) {\r
+               if(shapes == null || shapes.first == null || shapes.second == null || shapes.third == null) {\r
+                       shapes = new Triple<Arc2D, Path2D, Path2D>(new Arc2D.Double(), new Path2D.Double(), new Path2D.Double());\r
+               }\r
+               createArc(shapes.first, beginBounds, endBounds, angle);\r
+               \r
+        double angle0 =  Math.toRadians(shapes.first.getAngleStart());\r
+        double angle1 = Math.toRadians(shapes.first.getAngleStart() + shapes.first.getAngleExtent());\r
+        double x = Math.cos(angle > 0.0 ? angle1 : angle0);\r
+        double y = -Math.sin(angle > 0.0 ? angle1 : angle0);\r
+        double r = shapes.first.getHeight() / 2;\r
+        \r
+        createArrow(shapes.second, shapes.first.getCenterX() + r*x, shapes.first.getCenterY() + r*y, \r
+            angle < 0.0 ? -y : y, \r
+            angle > 0.0 ? -x : x);\r
+\r
+        double angleCenter = Math.toRadians(shapes.first.getAngleStart() + (shapes.first.getAngleExtent() / 2));\r
+        double arcCenterX = shapes.first.getCenterX() + r * Math.cos(angleCenter);\r
+        double arcCenterY = shapes.first.getCenterY() - r * Math.sin(angleCenter);\r
+        createDelayMark(shapes.third, arcCenterX, arcCenterY, angleCenter, \r
+                       stroke instanceof BasicStroke ? (BasicStroke)stroke : null);\r
+        \r
+        return shapes;\r
+        \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/FlowRouter.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/FlowRouter.java
new file mode 100644 (file)
index 0000000..fc64625
--- /dev/null
@@ -0,0 +1,139 @@
+package org.simantics.sysdyn.ui.editor.routing;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.PathIterator;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.g2d.routing.Constants;\r
+import org.simantics.g2d.routing.IConnection;\r
+import org.simantics.g2d.routing.IConnection.Connector;\r
+import org.simantics.g2d.routing.IRouter2;\r
+import org.simantics.sysdyn.ui.elements.connections.Flows;\r
+\r
+public class FlowRouter implements IRouter2{\r
+\r
+       SysdynLocalRouter localRouter;\r
+       \r
+       public static final float OFFSET = 0.5f;\r
+\r
+    public FlowRouter() {\r
+        this(false);\r
+    }\r
+\r
+    public FlowRouter(boolean roundCorners) {\r
+        this.localRouter = new SysdynLocalRouter();\r
+    }\r
+\r
+    private Path2D route(double beginX, double beginY, int sDir, Rectangle2D beginObstacle,\r
+            double endX, double endY, int tDir, Rectangle2D endObstacle) {\r
+        localRouter.sx = beginX;\r
+        localRouter.sy = beginY;\r
+        if(beginObstacle == null) {\r
+            localRouter.aMinX = beginX;\r
+            localRouter.aMinY = beginY;\r
+            localRouter.aMaxX = beginX;\r
+            localRouter.aMaxY = beginY;\r
+        }\r
+        else {\r
+            localRouter.aMinX = beginObstacle.getMinX();\r
+            localRouter.aMinY = beginObstacle.getMinY();\r
+            localRouter.aMaxX = beginObstacle.getMaxX();\r
+            localRouter.aMaxY = beginObstacle.getMaxY();\r
+        }\r
+        localRouter.sourceDirection = sDir;\r
+\r
+        localRouter.tx = endX;\r
+        localRouter.ty = endY;\r
+        if(endObstacle == null) {\r
+            localRouter.bMinX = endX;\r
+            localRouter.bMinY = endY;\r
+            localRouter.bMaxX = endX;\r
+            localRouter.bMaxY = endY;\r
+        }\r
+        else {\r
+            localRouter.bMinX = endObstacle.getMinX();\r
+            localRouter.bMinY = endObstacle.getMinY();\r
+            localRouter.bMaxX = endObstacle.getMaxX();\r
+            localRouter.bMaxY = endObstacle.getMaxY();\r
+        }\r
+        localRouter.targetDirection = tDir;\r
+        \r
+        // adjust flows to start and stop within the obstacle\r
+        if(sDir == Constants.EAST || sDir == Constants.WEST) {\r
+               localRouter.aMinY = localRouter.aMinY + OFFSET;\r
+               localRouter.aMaxY = localRouter.aMaxY - OFFSET;\r
+        }\r
+        if(tDir == Constants.EAST || tDir == Constants.WEST) {\r
+               localRouter.bMinY = localRouter.bMinY + OFFSET;\r
+               localRouter.bMaxY = localRouter.bMaxY - OFFSET;\r
+        }\r
+        if(sDir == Constants.SOUTH || sDir == Constants.NORTH) {\r
+               localRouter.aMinX = localRouter.aMinX + OFFSET;\r
+               localRouter.aMaxX = localRouter.aMaxX - OFFSET;\r
+        }\r
+        if(tDir == Constants.SOUTH || tDir == Constants.NORTH) {\r
+               localRouter.bMinX = localRouter.bMinX + OFFSET;\r
+               localRouter.bMaxX = localRouter.bMaxX - OFFSET;\r
+        }\r
+\r
+        localRouter.route();\r
+        \r
+        Path2D completePath = new Path2D.Double();\r
+        \r
+        completePath = Flows.createOffsetPath(localRouter.path, OFFSET);\r
+        completePath.append(Flows.createOffsetPath(localRouter.path, -OFFSET), false);\r
+        \r
+        return completePath;\r
+    }\r
+    \r
+    @Override\r
+    public void route(IConnection connection) {\r
+        Collection<?> segments = connection.getSegments();\r
+        if(segments.size() == 1)\r
+            for(Object seg : segments) {\r
+                Connector begin = connection.getBegin(seg);\r
+                Connector end = connection.getEnd(seg);\r
+\r
+                double bestLength = Double.POSITIVE_INFINITY;\r
+                Path2D bestPath = null;\r
+                \r
+                for(int sDir : Constants.POSSIBLE_DIRECTIONS[begin.allowedDirections])\r
+                    for(int tDir : Constants.POSSIBLE_DIRECTIONS[end.allowedDirections]) {\r
+                        Path2D path = route(begin.x, begin.y, sDir, begin.parentObstacle,\r
+                                end.x, end.y, tDir, end.parentObstacle);\r
+\r
+                        double length = pathCost(path);\r
+                        if(length < bestLength) {\r
+                            bestLength = length;\r
+                            bestPath = path;\r
+                        }\r
+                    }\r
+\r
+                if(bestPath != null)\r
+                    connection.setPath(seg, bestPath);\r
+            }\r
+    }\r
+    \r
+\r
+    final static AffineTransform IDENTITY = new AffineTransform();\r
+\r
+    static double pathCost(Path2D path) {\r
+        double length = 0.0;\r
+        PathIterator it = path.getPathIterator(IDENTITY);\r
+        double[] temp = new double[6];\r
+        double x=0.0, y=0.0;\r
+        double bendCount = 0.0;\r
+        while(!it.isDone()) {\r
+            bendCount += 1.0;\r
+            if(it.currentSegment(temp) != PathIterator.SEG_MOVETO)\r
+                length += Math.abs(x - temp[0] + y - temp[1]);\r
+            x = temp[0];\r
+            y = temp[1];\r
+            it.next();\r
+        }\r
+        return bendCount - 1.0 / length;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/SysdynLocalRouter.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/routing/SysdynLocalRouter.java
new file mode 100644 (file)
index 0000000..253e6a1
--- /dev/null
@@ -0,0 +1,477 @@
+package org.simantics.sysdyn.ui.editor.routing;\r
+\r
+import java.awt.geom.Path2D;\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.g2d.routing.Constants;\r
+\r
+public class SysdynLocalRouter {\r
+\r
+       static final double OFFSET = 1.0;\r
+       \r
+       double aMinX;\r
+       double aMinY;\r
+       double aMaxX;\r
+       double aMaxY;\r
+\r
+       double bMinX;\r
+       double bMinY;\r
+       double bMaxX;\r
+       double bMaxY;\r
+\r
+       double sx;\r
+       double sy;\r
+\r
+       double tx;\r
+       double ty;\r
+\r
+       int sourceDirection;\r
+       int targetDirection;\r
+\r
+       ArrayList<Double> points;\r
+       Path2D path;\r
+\r
+       public SysdynLocalRouter() {\r
+       }\r
+\r
+       /**\r
+        * Case where both source and target connection directions are to east.\r
+        */\r
+       void routeEast() {\r
+               if (bMinX >= aMaxX || tx >= 0 && !(bMaxY < aMinY || aMaxY < bMinY)) {\r
+                       if (ty != 0.0) {\r
+                /*  ______           ______\r
+                 * |      |         |      |\r
+                 * |      |----\    |      |\r
+                 * |      |    \--->|      |\r
+                 * |______|         |______|\r
+                 */\r
+                               double mx = 0.5 * (aMaxX + bMinX);\r
+                               point(mx, 0.0);\r
+                               point(mx, ty);\r
+                       } else\r
+                               ; // Just a straight line\r
+               } else {\r
+                       double x0 = bMinX;\r
+                       double x1 = aMaxX;\r
+                       double my;\r
+            /*      ______\r
+             *     |      |\r
+             *     |      |\r
+             *  /->|      |\r
+             *  |  |______|\r
+             *  |\r
+             *  \-------------\\r
+             *        ______  |\r
+             *       |      | |\r
+             *       |      |-/\r
+             *       |      |\r
+             *       |______|\r
+             * \r
+             * If the elements are separated in Y-direction,\r
+             * route between the elements (this is always the shortest path).\r
+             */\r
+                       if (bMaxY < aMinY)\r
+                               my = 0.5 * (aMinY + bMaxY);\r
+                       else if (aMaxY < bMinY)\r
+                               my = 0.5 * (aMaxY + bMinY);\r
+                       else {\r
+                /*\r
+                 *  /------------------------\\r
+                 *  |   ______      ______   |\r
+                 *  |  |      |    |      |  |\r
+                 *  |  |      |    |      |--+\r
+                 *  +->|      |    |      |  |\r
+                 *  |  |______|    |______|  |\r
+                 *  |                        |\r
+                 *  \------------------------/\r
+                 * \r
+                 * or\r
+                 * \r
+                 *    /-----------\\r
+                 *    |   ______  |\r
+                 *    |  |      | |\r
+                 *    |  |      | |\r
+                 * /--+->|      | |\r
+                 * |  ___|______| |\r
+                 * | |      |     |\r
+                 * | |      |-+---/\r
+                 * | |      | |\r
+                 * | |______| |\r
+                 * |          |\r
+                 * \----------/\r
+                 * \r
+                 * We may choose either lower or upper path.\r
+                 */\r
+                               double upperX0 = bMinX;\r
+                               double upperX1 = aMaxX;\r
+                               double lowerX0 = bMinX;\r
+                               double lowerX1 = aMaxX;\r
+                               double upperY = Math.min(aMinY, bMinY);\r
+                               double lowerY = Math.max(aMaxY, bMaxY);\r
+\r
+                               if (aMinX < bMinX) {\r
+                                       if (ty < 0.5 * (aMinY + aMaxY))\r
+                                               lowerX0 = aMinX;\r
+                                       else\r
+                                               upperX0 = aMinX;\r
+                               }\r
+\r
+                               if (bMaxX > aMaxX) {\r
+                                       if (ty < 0.5 * (aMinY + aMaxY))\r
+                                               upperX1 = bMaxX;\r
+                                       else\r
+                                               lowerX1 = bMaxX;\r
+                               }\r
+\r
+                               double upperLength = upperX1 - upperY + (upperX1 - upperX0)\r
+                                               + (ty - upperY) + (tx - upperX0);\r
+                               double lowerLength = lowerX1 + lowerY + (lowerX1 - lowerX0)\r
+                                               + (lowerY - ty) + (tx - lowerX0);\r
+\r
+                               if (upperLength < lowerLength) {\r
+                                       x0 = upperX0;\r
+                                       x1 = upperX1;\r
+                                       my = upperY;\r
+                               } else {\r
+                                       x0 = lowerX0;\r
+                                       x1 = lowerX1;\r
+                                       my = lowerY;\r
+                               }\r
+                       }\r
+                       point(x1, 0.0);\r
+                       point(x1, my);\r
+                       point(x0, my);\r
+                       point(x0, ty);\r
+               }\r
+       }\r
+\r
+       void routeWest() {\r
+               if (tx >= 0.0) {\r
+                       double fx = Math.max(aMaxX, bMaxX);\r
+                       double mx = 0.5 * (aMaxX + bMinX);\r
+                       if (bMinY >= 0.0 || bMaxY <= 0.0 || mx < 0.0) {\r
+                /*                   ______\r
+                 *                  |      |\r
+                 *                  |      |\r
+                 *                  |      |<-\\r
+                 *  ______          |______|  |\r
+                 * |      |                   |\r
+                 * |      |-------------------/\r
+                 * |      |\r
+                 * |______|\r
+                 */\r
+                point(fx, 0.0);\r
+            }\r
+            else {\r
+                /*             /-------------\\r
+                 *             |    ______   |\r
+                 *             |   |      |  |\r
+                 *  ______     |   |      |  |\r
+                 * |      |    |   |      |<-+\r
+                 * |      |----+   |______|  |\r
+                 * |      |    |             |\r
+                 * |______|    \-------------/\r
+                 * \r
+                 * We may choose either upper or lower path\r
+                 * by the path length.\r
+                 */\r
+                               double my = Math.abs(bMinY) + Math.abs(ty - bMinY) < Math\r
+                                               .abs(bMaxY) + Math.abs(ty - bMaxY) ? bMinY : bMaxY;\r
+                               point(mx, 0.0);\r
+                               point(mx, my);\r
+                               point(fx, my);\r
+                       }\r
+                       point(fx, ty);\r
+               } else {\r
+                       double fx = Math.max(aMaxX, bMaxX);\r
+                       double mx = 0.5 * (aMinX + bMaxX);\r
+                       point(fx, 0.0);\r
+                       if (ty <= aMinY || ty >= aMaxY\r
+                                       || (tx >= mx && ty >= aMinY && ty <= aMaxY)) {\r
+                /*                   ______\r
+                 *                  |      |\r
+                 *                  |      |\r
+                 *                  |      |--\\r
+                 *  ______          |______|  |\r
+                 * |      |                   |\r
+                 * |      |<------------------/\r
+                 * |      |\r
+                 * |______|\r
+                 */\r
+                point(fx, ty);\r
+            }\r
+            else {\r
+                /*             /-------------\\r
+                 *             |    ______   |\r
+                 *             |   |      |  |\r
+                 *  ______     |   |      |  |\r
+                 * |      |    |   |      |--+\r
+                 * |      |<---+   |______|  |\r
+                 * |      |    |             |\r
+                 * |______|    \-------------/\r
+                 * \r
+                 * We may choose either upper or lower path\r
+                 * by the path length.\r
+                 */\r
+                               double my = Math.abs(aMinY) + Math.abs(ty - aMinY) < Math\r
+                                               .abs(aMaxY) + Math.abs(ty - aMaxY) ? aMinY : aMaxY;\r
+                               point(fx, my);\r
+                               point(mx, my);\r
+                               point(mx, ty);\r
+                       }\r
+               }\r
+       }\r
+\r
+       void routeSouth() {\r
+               if (tx > 0.0 && (bMinY >= 0.0 || (ty > 0.0 && bMinX <= aMaxX)))\r
+                       point(tx, 0.0);\r
+               else if (bMinX > aMaxX) {\r
+                       double mx = 0.5 * (aMaxX + bMinX);\r
+                       point(mx, 0.0);\r
+                       point(mx, bMinY);\r
+                       point(tx, bMinY);\r
+               } else {\r
+                       double fx = aMaxX;\r
+                       double my = 0.5 * (aMaxY + bMinY);\r
+                       if (my < aMaxY && (tx < aMinX || ty < aMinY)) {\r
+                               my = Math.min(aMinY, bMinY);\r
+                               if (bMaxX > aMaxX)\r
+                                       fx = bMaxX;\r
+                       }\r
+                       point(fx, 0.0);\r
+                       point(fx, my);\r
+                       point(tx, my);\r
+               }\r
+       }\r
+\r
+       double xx, xy, yx, yy;\r
+\r
+       void point(double x, double y) {\r
+               lineTo(x * xx + y * yx + sx, x * xy + y * yy + sy);\r
+       }\r
+\r
+       /*\r
+        * should draw only horizontal or vertical lines. Determine the offset and\r
+        * draw both lines.\r
+        */\r
+       void lineTo(double x, double y) {\r
+               double cx = path.getCurrentPoint().getX();\r
+               double cy = path.getCurrentPoint().getY();\r
+               \r
+               if (Math.abs(cx - x) < 1e-5) {\r
+                       // Vertical line\r
+                       if(points.size() % 2 == 0) {\r
+                               points.add(points.get(points.size()-2));\r
+                       }\r
+                       points.add(y);\r
+               } else if (Math.abs(cy - y) < 1e-5) {\r
+                       // Horizontal line\r
+                       if(points.size() % 2 != 0) {\r
+                               points.add(cy);\r
+                       }\r
+                       points.add(x);\r
+               }\r
+               path.lineTo(x, y);\r
+       }\r
+       void rotate() {\r
+               double temp;\r
+\r
+               temp = tx;\r
+               tx = ty;\r
+               ty = -temp;\r
+\r
+               temp = aMinX;\r
+               aMinX = aMinY;\r
+               aMinY = -aMaxX;\r
+               aMaxX = aMaxY;\r
+               aMaxY = -temp;\r
+\r
+               temp = bMinX;\r
+               bMinX = bMinY;\r
+               bMinY = -bMaxX;\r
+               bMaxX = bMaxY;\r
+               bMaxY = -temp;\r
+\r
+               temp = xx;\r
+               xx = -xy;\r
+               xy = temp;\r
+\r
+               temp = yx;\r
+               yx = -yy;\r
+               yy = temp;\r
+\r
+               --targetDirection;\r
+               if (targetDirection < 0)\r
+                       targetDirection += 4;\r
+               --sourceDirection;\r
+       }\r
+\r
+       void flip() {\r
+               double temp;\r
+\r
+               ty = -ty;\r
+\r
+               temp = aMinY;\r
+               aMinY = -aMaxY;\r
+               aMaxY = -temp;\r
+\r
+               temp = bMinY;\r
+               bMinY = -bMaxY;\r
+               bMaxY = -temp;\r
+\r
+               yx = -yx;\r
+               yy = -yy;\r
+\r
+               targetDirection = (targetDirection + 2) % 4;\r
+       }\r
+\r
+       /*\r
+        * Puts source terminal to origo and rotates the situation so that the\r
+        * connection leaves to east. Finally, the case where target direction is to\r
+        * south is eliminated by optionally flipping the situation.\r
+        */\r
+       void canonicalize() {\r
+               aMinX -= sx;\r
+               aMinY -= sy;\r
+               aMaxX -= sx;\r
+               aMaxY -= sy;\r
+               bMinX -= sx;\r
+               bMinY -= sy;\r
+               bMaxX -= sx;\r
+               bMaxY -= sy;\r
+               tx -= sx;\r
+               ty -= sy;\r
+               xx = yy = 1.0;\r
+               xy = yx = 0.0;\r
+               while (sourceDirection > 0)\r
+                       rotate();\r
+\r
+               if (targetDirection == Constants.SOUTH)\r
+                       flip();\r
+       }\r
+\r
+       public void route() {\r
+               /*\r
+                * Three cases: 1. Obstacles share X-axis at some point 2. Obstacles\r
+                * share Y-Axis at some point 3. Obstacles don't share axis => Have to\r
+                * make corners.\r
+                */             \r
+//             if (\r
+//                             aMinX > bMinX && aMinX < bMaxX ||\r
+//                             aMaxX > bMinX && aMaxX < bMaxX ||\r
+//                             aMinX < bMinX && aMaxX > bMaxX) {\r
+//                     // Obstacles share x-axis => no corner\r
+//                     double minX = aMinX > bMinX ? aMinX : bMinX;\r
+//                     double maxX = aMaxX < bMaxX ? aMaxX : bMaxX;\r
+//                     double middle = minX + (maxX - minX) / 2;\r
+//                     sx = middle;\r
+//                     tx = middle;\r
+//                     if (sy > ty) {\r
+//                             sy = aMinY;\r
+//                             ty = bMaxY;\r
+//                     } else {\r
+//                             sy = aMaxY;\r
+//                             ty = bMinY;\r
+//                     }\r
+//             } else if (\r
+//                             aMinY > bMinY && aMinY < bMaxY || \r
+//                             aMaxY > bMinY && aMaxY < bMaxY ||\r
+//                             aMinY < bMinY && aMaxY > bMaxY) {\r
+//                     // Obstacles share y-axis => no corner\r
+//                     double minY = aMinY > bMinY ? aMinY : bMinY;\r
+//                     double maxY = aMaxY < bMaxY ? aMaxY : bMaxY;\r
+//                     double middle = minY + (maxY - minY) / 2;\r
+//                     sy = middle;\r
+//                     ty = middle;\r
+//                     if (sx > tx) {\r
+//                             sx = aMinX;\r
+//                             tx = bMaxX;\r
+//                     } else {\r
+//                             sx = aMaxX;\r
+//                             tx = bMinX;\r
+//                     }\r
+//             } else {\r
+                       sx = aMinX + (aMaxX - aMinX) / 2;\r
+                       sy = aMinY + (aMaxY - aMinY) / 2;\r
+                       tx = bMinX + (bMaxX - bMinX) / 2;\r
+                       ty = bMinY + (bMaxY - bMinY) / 2;\r
+                       // Move starting point to the edge of the start element\r
+                       switch (sourceDirection) {\r
+                       case Constants.WEST:\r
+                               sx = aMinX;\r
+                               break;\r
+                       case Constants.EAST:\r
+                               sx = aMaxX;\r
+                               break;\r
+                       case Constants.NORTH:\r
+                               sy = aMinY;\r
+                               break;\r
+                       case Constants.SOUTH:\r
+                               sy = aMaxY;\r
+                               break;\r
+                       }\r
+\r
+                       // Move target point to the edge of the ending element\r
+                       switch (targetDirection) {\r
+                       case Constants.EAST:\r
+                               tx = bMaxX;\r
+                               break;\r
+                       case Constants.WEST:\r
+                               tx = bMinX;\r
+                               break;\r
+                       case Constants.NORTH:\r
+                               ty = bMinY;\r
+                               break;\r
+                       case Constants.SOUTH:\r
+                               ty = bMaxY;\r
+                               break;\r
+                       }\r
+//             }\r
+\r
+               path = new Path2D.Double();\r
+               points = new ArrayList<Double>();\r
+\r
+               path.moveTo(sx, sy);\r
+               points.add(sx);\r
+               points.add(sy);\r
+\r
+               // Vertical and horizontal cases\r
+               if ((Math.abs(sx - tx) < 1e-5 && isVertical())\r
+                       || (Math.abs(sy - ty) < 1e-5 && isHorizontal())) {\r
+                       lineTo(tx, ty);\r
+                       return;\r
+               }\r
+               \r
+\r
+               canonicalize();\r
+               switch (targetDirection) {\r
+               case Constants.EAST:\r
+                       routeWest();\r
+                       break;\r
+               case Constants.WEST:\r
+                       routeEast();\r
+                       break;\r
+               case Constants.NORTH:\r
+                       routeSouth();\r
+                       break;\r
+               }\r
+\r
+               point(tx, ty);\r
+\r
+       }\r
+       \r
+       private boolean isVertical() {\r
+               return\r
+               (sourceDirection == Constants.SOUTH && targetDirection == Constants.SOUTH)\r
+               ||\r
+               (sourceDirection == Constants.NORTH && targetDirection == Constants.NORTH);\r
+       }\r
+       \r
+       private boolean isHorizontal() {\r
+               return\r
+               (sourceDirection == Constants.EAST && targetDirection == Constants.EAST)\r
+               ||\r
+               (sourceDirection == Constants.WEST && targetDirection == Constants.WEST);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/AuxiliaryFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/AuxiliaryFactory.java
new file mode 100644 (file)
index 0000000..ab3bbd3
--- /dev/null
@@ -0,0 +1,63 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.geom.Ellipse2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.diagram.elements.ResizeRectangularSceneGraph;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.OutlinePick;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.g2d.utils.Alignment;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class AuxiliaryFactory extends SysdynElementFactory {\r
+\r
+    public static final Image AUX_STATIC_IMAGE = new ShapeImage(new Ellipse2D.Double(-5, -2, 10, 4), null, new BasicStroke(1), true);\r
+\r
+    @Override\r
+    protected ElementClass compileElementClass(Resource elementType, Collection<ObjectTerminal> terminals) {\r
+        return ElementClass.compile(\r
+                SimpleElementLayers.INSTANCE,\r
+                OutlinePick.INSTANCE,\r
+                TextImpl.INSTANCE,\r
+                TextColorImpl.BLACK,\r
+                TextFontImpl.DEFAULT,\r
+                DefaultTransform.INSTANCE,\r
+                new StaticObjectAdapter(elementType),\r
+                new StaticSymbolImpl(AUX_STATIC_IMAGE),\r
+                StaticSymbolImageInitializer.INSTANCE,\r
+                new SysdynTextElementHandler(0, 0, Alignment.CENTER, 0, 1.5, 1.5, true),\r
+                BoundsOutline.INSTANCE,\r
+                ResizeRectangularSceneGraph.INSTANCE,\r
+                RESIZE_PROPERTY_SETTER,   \r
+                new WholeElementTerminals(terminals)\r
+        ).setId(AuxiliaryFactory.class.getSimpleName());\r
+    }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/BorderSceneGraph.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/BorderSceneGraph.java
new file mode 100644 (file)
index 0000000..2126e9c
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.SceneGraphNodeKey;\r
+import org.simantics.g2d.element.handler.SceneGraph;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.utils.datastructures.Callback;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+\r
+public class BorderSceneGraph implements SceneGraph, Callback<RectangleNode> {\r
+\r
+    public static final BorderSceneGraph INSTANCE         = new BorderSceneGraph();\r
+\r
+    private static final long            serialVersionUID = 5544256245734478634L;\r
+\r
+    private static final Key             BORDER_NODE      = new SceneGraphNodeKey(RectangleNode.class, "BORDER_NODE");\r
+\r
+    @Override\r
+    public void init(IElement e, G2DParentNode parent) {\r
+        RectangleNode node = ElementUtils.getOrCreateNode(e, parent, BORDER_NODE, "border", RectangleNode.class, this);\r
+\r
+        // Calculate borders from text node bounds.\r
+        node.init(ElementUtils.getElementBounds(e));\r
+        AffineTransform transform = ElementUtils.getTransform(e);\r
+        if(transform != null)\r
+               node.setTransform(transform);\r
+    }\r
+\r
+    @Override\r
+    public void run(RectangleNode node) {\r
+        node.setZIndex(-10);\r
+    }\r
+\r
+    @Override\r
+    public void cleanup(IElement e) {\r
+        ElementUtils.removePossibleNode(e, BORDER_NODE);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/CloudFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/CloudFactory.java
new file mode 100644 (file)
index 0000000..6489501
--- /dev/null
@@ -0,0 +1,193 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.SceneGraphNodeKey;\r
+import org.simantics.g2d.element.handler.HandleMouseEvent;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.SceneGraph;\r
+import org.simantics.g2d.element.handler.impl.BorderColorImpl;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.HoverImpl;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.OutlinePick;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseEnterEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseExitEvent;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintListener;\r
+import org.simantics.utils.datastructures.hints.IHintObservable;\r
+\r
+public class CloudFactory extends SysdynElementFactory {\r
+\r
+    public static final double       CLOUD_SIZE_X  = 2.5;\r
+    public static final double       CLOUD_SIZE_Y  = 1.7;\r
+    public static final double       CLOUD_CURVES  = 7;\r
+\r
+    private static final BasicStroke    STROKE           = new BasicStroke(1f);\r
+    public static final Image       CLOUD_IMAGE = new ShapeImage(getCloudShape(), null, STROKE, true);\r
+\r
+    static Shape getCloudShape() {\r
+        Path2D path = new Path2D.Double();\r
+        double ox = CLOUD_SIZE_X;\r
+        double oy = 0.0;\r
+        double posX = 0;\r
+        double posY = 0;\r
+        path.moveTo(posX + ox, posY + oy);\r
+        for (int i = 1; i < CLOUD_CURVES + 1; ++i) {\r
+            double angle = (Math.PI * 2.0 / CLOUD_CURVES) * i;\r
+            double x = Math.cos(angle) * CLOUD_SIZE_X;\r
+            double y = Math.sin(angle) * CLOUD_SIZE_Y;\r
+            path.curveTo(\r
+                    posX + (2*ox + x)*0.5, posY + (2*oy + y)*0.5,\r
+                    posX + (ox + 2*x)*0.5, posY + (oy + 2*y)*0.5,\r
+                    posX + x, posY + y);\r
+            ox = x;\r
+            oy = y;\r
+        }\r
+        return path;\r
+    }\r
+    \r
+    public static ElementClass createElementClass(Resource elementType, Collection<ObjectTerminal> terminals) {\r
+        return ElementClass.compile(\r
+                SimpleElementLayers.INSTANCE,\r
+                OutlinePick.INSTANCE,\r
+                TextImpl.INSTANCE,\r
+                TextColorImpl.BLACK,\r
+                TextFontImpl.DEFAULT,\r
+                DefaultTransform.INSTANCE,\r
+                new StaticObjectAdapter(elementType),\r
+                new StaticSymbolImpl(CLOUD_IMAGE),\r
+                StaticSymbolImageInitializer.INSTANCE,\r
+                CloudSceneGraph.INSTANCE,\r
+                HoverImpl.INSTANCE,\r
+                BoundsOutline.INSTANCE,\r
+                new BorderColorImpl(Color.BLACK),\r
+                new WholeElementTerminals(terminals)\r
+        ).setId(CloudFactory.class.getSimpleName());\r
+    }\r
+    \r
+    @Override\r
+    public void load(ReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource element, IElement e)\r
+            throws DatabaseException {\r
+        super.load(graph, canvas, diagram, element, e);\r
+        e.setHint(ElementHints.KEY_BORDER_COLOR, e.getHint(ElementHints.KEY_TEXT_COLOR));\r
+    }\r
+\r
+    @Override\r
+    protected ElementClass compileElementClass(Resource elementType, Collection<ObjectTerminal> terminals) {\r
+        return createElementClass(elementType, terminals);\r
+    }\r
+\r
+    public static class CloudSceneGraph implements SceneGraph, InternalSize, HandleMouseEvent {\r
+\r
+        private static final long           serialVersionUID = 5544256245734478634L;\r
+\r
+        public static final CloudSceneGraph INSTANCE         = new CloudSceneGraph();\r
+\r
+        private static final Key            NODE             = new SceneGraphNodeKey(ShapeNode.class, "CLOUD_NODE");\r
+        \r
+        private IHintListener hoverHintListener;\r
+\r
+        @Override\r
+        public void init(IElement e, G2DParentNode parent) {\r
+            \r
+            HoverShapeNode node = ElementUtils.getOrCreateNode(e, parent, NODE, "cloud", HoverShapeNode.class);\r
+            \r
+            AffineTransform at = ElementUtils.getTransform(e);\r
+            \r
+            node.setStroke(STROKE);\r
+            node.setScaleStroke(true);\r
+            node.setColor(ElementUtils.getBorderColor(e, Color.BLACK));\r
+            node.setShape(getCloudShape());\r
+            \r
+            if(at != null)\r
+                node.setTransform(at);\r
+            \r
+            hoverHintListener = new IHintListener() {\r
+                \r
+                @Override\r
+                public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {\r
+                    \r
+                }\r
+                \r
+                @Override\r
+                public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
+                    IElement e = (IElement)sender;\r
+                    HoverShapeNode shape = (HoverShapeNode) e.getHint(NODE);\r
+                    if(shape == null) {\r
+                        return;\r
+                    }\r
+                    shape.setHover(ElementUtils.isHovering(e));\r
+                }\r
+            };\r
+            e.addHintListener(hoverHintListener);\r
+        }\r
+\r
+        @Override\r
+        public void cleanup(IElement e) {\r
+            e.removeHintListener(hoverHintListener);\r
+            ElementUtils.removePossibleNode(e, NODE);\r
+        }\r
+\r
+        @Override\r
+        public Rectangle2D getBounds(IElement e, Rectangle2D size) {\r
+            if (size == null)\r
+                size = new Rectangle2D.Double();\r
+            size.setFrame(CLOUD_IMAGE.getBounds());\r
+            return size;\r
+        }\r
+\r
+        @Override\r
+        public boolean handleMouseEvent(IElement e, ICanvasContext ctx, MouseEvent me) {\r
+            if (me instanceof MouseEnterEvent) {\r
+               e.setHint(ElementHints.KEY_HOVER, true);\r
+                return false;\r
+            } else if (me instanceof MouseExitEvent) {\r
+               e.setHint(ElementHints.KEY_HOVER, false);\r
+                return false;\r
+            }\r
+            return false;\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ComponentNameSynchronizer.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ComponentNameSynchronizer.java
new file mode 100644 (file)
index 0000000..0e47ca9
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.synchronization.IModificationQueue;\r
+import org.simantics.diagram.synchronization.ISynchronizationContext;\r
+import org.simantics.diagram.synchronization.graph.GraphSynchronizationHints;\r
+import org.simantics.diagram.synchronization.graph.RelatedPropertyModification;\r
+import org.simantics.diagram.synchronization.graph.ResourceSynchronizer;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintObservable;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class ComponentNameSynchronizer extends ResourceSynchronizer {\r
+\r
+    public static final ComponentNameSynchronizer INSTANCE = new ComponentNameSynchronizer();\r
+\r
+    private static final Key[] SYNCHRONIZED_HINTS = {\r
+        ElementHints.KEY_TEXT\r
+    };\r
+\r
+    @Override\r
+    public Key[] getSynchronizedHints() {\r
+        return SYNCHRONIZED_HINTS;\r
+    }\r
+\r
+    @Override\r
+    public boolean hintChanged(ISynchronizationContext context, IModificationQueue queue, Resource object, IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
+        if (ElementHints.KEY_TEXT.equals(key)) {\r
+            Session session = context.get(GraphSynchronizationHints.SESSION);\r
+            Layer0 l0;\r
+                       try {\r
+                               l0 = Layer0.getInstance(session);\r
+                   ModelingResources mr = session.getService(ModelingResources.class);\r
+                   return queue.offer(new RelatedPropertyModification(object, mr.ElementToComponent, l0.HasName, l0.String, newValue, Bindings.STRING), null);\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+        }\r
+        return false;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ConfigurationDiagramClassAdapter.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ConfigurationDiagramClassAdapter.java
new file mode 100644 (file)
index 0000000..e562ff3
--- /dev/null
@@ -0,0 +1,46 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.adaption.ResourceAdapter;\r
+import org.simantics.db.procedure.AsyncProcedure;\r
+import org.simantics.diagram.adapter.DiagramClassAdapter;\r
+import org.simantics.g2d.diagram.DiagramClass;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.diagram.handler.LifeCycle;\r
+import org.simantics.g2d.routing.RouterFactory;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class ConfigurationDiagramClassAdapter implements ResourceAdapter<DiagramClass> {\r
+\r
+    @Override\r
+    public void adapt(AsyncReadGraph g, Resource source, Resource r, AsyncProcedure<DiagramClass> procedure) {\r
+        procedure.execute(g, DiagramClassAdapter.INSTANCE.newClassWith(\r
+                Initializer.INSTANCE\r
+        ));\r
+    }\r
+\r
+    static class Initializer extends LifeCycle.Stub {\r
+        public static final Initializer INSTANCE = new Initializer();\r
+\r
+        @Override\r
+        public void onDiagramCreated(IDiagram diagram) {\r
+            diagram.setHint(DiagramHints.ROUTE_ALGORITHM, RouterFactory.create(false, false));\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/HoverShapeNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/HoverShapeNode.java
new file mode 100644 (file)
index 0000000..3cc5b2f
--- /dev/null
@@ -0,0 +1,77 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.AlphaComposite;\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Composite;\r
+import java.awt.Graphics2D;\r
+import java.awt.Shape;\r
+import java.awt.Stroke;\r
+\r
+import org.simantics.scenegraph.ISelectionPainterNode;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+\r
+public class HoverShapeNode extends ShapeNode implements ISelectionPainterNode {\r
+\r
+    private static final long serialVersionUID = -4580969977763722602L;\r
+\r
+    transient public boolean hover = false;\r
+    \r
+    @Override\r
+    protected void renderShape(Graphics2D g2d, Shape s) {\r
+        boolean fill = Boolean.TRUE.equals(dynamicFill) ? true : this.fill;\r
+        if (fill)\r
+            g2d.fill(s);\r
+        \r
+        Color oldColor = g2d.getColor();\r
+        BasicStroke oldStroke = (BasicStroke)g2d.getStroke();\r
+        Composite oldComposite = g2d.getComposite();\r
+        \r
+        boolean selected = NodeUtil.isSelected(this, 1);\r
+        if (selected) {\r
+            float lineWidth = oldStroke.getLineWidth() * 5;\r
+            g2d.setStroke(new BasicStroke(lineWidth < 1.0f ? lineWidth : 1.0f));\r
+               g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));\r
+               g2d.setColor(Color.RED);\r
+            g2d.draw(s);\r
+            g2d.setColor(oldColor);\r
+        }\r
+        \r
+        if(!selected && hover) {\r
+            g2d.setColor(Color.LIGHT_GRAY);\r
+            float lineWidth = oldStroke.getLineWidth() * 5;\r
+            g2d.setStroke(new BasicStroke(lineWidth < 1.0f ? lineWidth : 1.0f));\r
+            g2d.draw(s);\r
+\r
+        }\r
+\r
+        g2d.setColor(oldColor);\r
+        g2d.setStroke(oldStroke);\r
+        g2d.setComposite(oldComposite);\r
+        \r
+        Stroke stroke = dynamicStroke != null ? dynamicStroke : this.stroke;\r
+        if (stroke != null)\r
+            g2d.draw(s);\r
+        \r
+    }\r
+    \r
+    public void setHover(boolean hover) {\r
+        this.hover = hover;\r
+        repaint();\r
+    }\r
+\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Input.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Input.java
new file mode 100644 (file)
index 0000000..54f83d4
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.ElementHandler;\r
+\r
+public class Input implements ElementHandler {\r
+\r
+    private static final long serialVersionUID = -1526125969376635502L;\r
+    \r
+    public static final Input INSTANCE = new Input();\r
+    \r
+    public String getInputReference(IElement e) {\r
+        return e.getHint(SysdynElementHints.KEY_INPUT_REFERENCE);\r
+    }\r
+\r
+    \r
+    public void setInputReference(IElement e, String inputReference) {\r
+        if (inputReference != null)\r
+            e.setHint(SysdynElementHints.KEY_INPUT_REFERENCE, inputReference);\r
+        else\r
+            e.removeHint(SysdynElementHints.KEY_INPUT_REFERENCE);\r
+    }\r
+    \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/InputFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/InputFactory.java
new file mode 100644 (file)
index 0000000..b19f43d
--- /dev/null
@@ -0,0 +1,239 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.diagram.elements.ResizeRectangularSceneGraph;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.ui.DiagramModelHints;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.SceneGraphNodeKey;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.OutlinePick;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.g2d.utils.Alignment;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+\r
+public class InputFactory extends SysdynElementFactory {\r
+\r
+    private static final BasicStroke    STROKE          = new BasicStroke(1f);\r
+    public static final Image          INPUT_IMAGE     = new ShapeImage(getInputShape(), null, STROKE, true);\r
+\r
+    static Shape getInputShape() {\r
+        Path2D path = new Path2D.Double();\r
+        path.moveTo(-6, -1);\r
+        path.lineTo(-1, -1);\r
+        path.lineTo(-1, -2.5);\r
+        path.lineTo(1.5, 0);\r
+        path.curveTo(1.5, -2.5, 6.5, -2.5, 6.5, 0);\r
+        path.curveTo(6.5, 2.5, 1.5, 2.5, 1.5, 0);\r
+        path.lineTo(-1, 2.5);\r
+        path.lineTo(-1, 1);\r
+        path.lineTo(-6, 1);\r
+        path.closePath();\r
+        return path;\r
+    }\r
+\r
+    @Override\r
+    protected ElementClass compileElementClass(Resource elementType, Collection<ObjectTerminal> terminals) {\r
+        return ElementClass.compile(\r
+                SimpleElementLayers.INSTANCE,\r
+                OutlinePick.INSTANCE,\r
+                TextImpl.INSTANCE,\r
+                TextColorImpl.BLACK,\r
+                TextFontImpl.DEFAULT,\r
+                DefaultTransform.INSTANCE,\r
+                new StaticObjectAdapter(elementType),\r
+                new StaticSymbolImpl(INPUT_IMAGE),\r
+                StaticSymbolImageInitializer.INSTANCE,\r
+                Input.INSTANCE,\r
+                new InputSceneGraph(0, 0, Alignment.CENTER, 0, 1.5, 1.5, true),\r
+                BoundsOutline.INSTANCE,\r
+                ResizeRectangularSceneGraph.INSTANCE,\r
+                RESIZE_PROPERTY_SETTER,                    \r
+                new WholeElementTerminals(terminals)\r
+        ).setId(InputFactory.class.getSimpleName());\r
+    }\r
+\r
+    @Override\r
+    public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {\r
+        super.load(graph, canvas, diagram, element, e);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        ModelingResources mr = ModelingResources.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Resource component = null;\r
+        Resource dependency = null;\r
+        Resource refersTo = null;\r
+        Resource module = null;\r
+        String moduleName = "";\r
+        String referenceName = "";\r
+        component = graph.getPossibleObject(element, mr.ElementToComponent);\r
+        if(component != null) \r
+            dependency = graph.getPossibleObject(component, sr.Variable_isHeadOf);\r
+        if(dependency != null) {\r
+            refersTo = graph.getPossibleObject(dependency, sr.Dependency_refersTo);\r
+            if(refersTo != null) {\r
+                referenceName = (String) graph.getPossibleRelatedValue(refersTo, l0.HasName);\r
+                module = graph.getPossibleObject(dependency, sr.Variable_HasTail);\r
+                moduleName = (String) graph.getPossibleRelatedValue(module, l0.HasName);\r
+            }\r
+        } else {\r
+            Resource runtime = diagram.getHint((DiagramModelHints.KEY_DIAGRAM_RUNTIME_RESOURCE));\r
+            DiagramResource dr = DiagramResource.getInstance(graph);\r
+            String variable = (String)graph.getPossibleRelatedValue(runtime, dr.RuntimeDiagram_HasVariable);\r
+            if(variable == null)\r
+               return;\r
+            \r
+            \r
+            try {\r
+               Variable v = Variables.getVariable(graph, variable);\r
+               if(v != null) {\r
+                       module = v.getRepresents(graph);\r
+               }\r
+               if(module != null)\r
+                       for(Resource dep : graph.getObjects(module, sr.Variable_isHeadOf)) {\r
+                               Resource reference = graph.getPossibleObject(dep, sr.Dependency_refersTo);\r
+                               if(reference!= null && reference.equals(component)) {\r
+                                       refersTo = graph.getSingleObject(dep, sr.Variable_HasTail);\r
+                                       referenceName = (String) graph.getPossibleRelatedValue(refersTo, l0.HasName);\r
+                                       Variable parent = null;\r
+                                       parent = v.getParent(graph);\r
+                                       Resource represents = parent.getRepresents(graph);\r
+                                       if(parent != null && !graph.isInstanceOf(represents, sr.Configuration) && !graph.isInstanceOf(represents, sr.Experiment_Run)) {\r
+                                               moduleName = parent.getName(graph);\r
+                                       }\r
+                                       break;\r
+                               }\r
+                       }\r
+            } catch (MissingVariableException mve) {\r
+               // DO nothing.\r
+            }\r
+        }\r
+\r
+        String inputReference = null;\r
+        if (moduleName != null && refersTo != null) {\r
+            inputReference = moduleName + "." + referenceName;\r
+        }\r
+        if (inputReference == null) {\r
+            inputReference = "";\r
+        }\r
+\r
+        SysdynElementUtils.setInputReference(e, inputReference);\r
+\r
+        Font font = ElementUtils.getTextFont(e);\r
+        font = font.deriveFont(font.getStyle());\r
+        ElementUtils.setTextFont(e, font);\r
+    }\r
+\r
+\r
+    public static class InputSceneGraph extends SysdynTextElementNoBounds implements InternalSize {\r
+\r
+        private static final long   serialVersionUID = -3713275157729126409L;\r
+        public static final Key     INPUT_SG_NODE          = new SceneGraphNodeKey(TextNode.class, "INPUT_SG_NODE");\r
+\r
+        private final double originX;\r
+        private final Alignment horizontalAlignment;\r
+\r
+        public InputSceneGraph(double originX, double originY, Alignment horizontalAlignment, double borderWidth, double paddingX, double paddingY, boolean editable) {\r
+            super(originX, originY, horizontalAlignment, borderWidth, paddingX, paddingY, editable);\r
+            this.originX = originX;\r
+            this.horizontalAlignment = horizontalAlignment;\r
+        }\r
+\r
+        @Override\r
+        public void init(final IElement e, G2DParentNode parent) {\r
+            super.init(e, parent);\r
+            TextNode node = ElementUtils.getOrCreateNode(e, parent, INPUT_SG_NODE, "input", TextNode.class);\r
+            Font font = ElementUtils.getTextFont(e);\r
+            font = font.deriveFont((float) 10.0);\r
+//            font = font.deriveFont(Font.ITALIC);\r
+            Color color = new Color(150, 150, 150);\r
+            Color fillColor = ElementUtils.getFillColor(e);\r
+            Color borderColor = ElementUtils.getBorderColor(e, Color.BLACK);\r
+            String text = SysdynElementUtils.getInputReference(e);\r
+            double scale = 0.235;\r
+            AffineTransform at = ElementUtils.getTransform(e);\r
+            node.init(text, font, color, originX, originY, scale);\r
+            node.setBackgroundColor(fillColor);\r
+            node.setBorderColor(borderColor);\r
+            node.setHorizontalAlignment((byte) horizontalAlignment.ordinal());\r
+            node.setBorderWidth((float) 0);\r
+            node.setEditable(false);\r
+            node.setShowSelection(false);\r
+\r
+            if(at != null) {\r
+                node.setTransform(at);\r
+                // Use affinetransform to move the name of the valve below the valve symbol\r
+                AffineTransform at2 = (AffineTransform) at.clone();\r
+                at2.translate(0, font.getSize2D() * scale);\r
+                node.setTransform(at2);\r
+            }\r
+            \r
+            unflipText(e);\r
+        }\r
+\r
+        @Override\r
+        public Rectangle2D getBounds(IElement e, Rectangle2D size) {\r
+            TextNode name = (TextNode) e.getHint(SG_NODE);\r
+            TextNode reference = (TextNode) e.getHint(INPUT_SG_NODE);\r
+            if (size == null)\r
+                size = new Rectangle2D.Double();\r
+            if (name != null)\r
+                size.setRect(name.getBoundsInLocal());\r
+            \r
+            if(reference != null) {\r
+               /* Only the main text box as bounds\r
+                if (reference.getBoundsInLocal().getWidth() > size.getWidth())\r
+                    size.setRect(size.getX(), size.getY(), reference.getBoundsInLocal().getWidth(), size.getHeight());\r
+                */\r
+            }\r
+            else\r
+                size.setFrame(0, 0, 0, 0);\r
+            return size;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopClockwise.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopClockwise.java
new file mode 100644 (file)
index 0000000..19cf448
--- /dev/null
@@ -0,0 +1,35 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.ElementHandler;\r
+\r
+public class LoopClockwise implements ElementHandler {\r
+\r
+       private static final long serialVersionUID = -5104770127548577905L;\r
+       \r
+       public static final LoopClockwise INSTANCE = new LoopClockwise();\r
+    \r
+    public String getTextLocation(IElement e) {\r
+        return e.getHint(SysdynElementHints.KEY_LOOP_CLOCKWISE);\r
+    }\r
+\r
+    \r
+    public void setTextLocation(IElement e, Boolean clockwise) {\r
+        if (clockwise != null)\r
+            e.setHint(SysdynElementHints.KEY_LOOP_CLOCKWISE, clockwise);\r
+        else\r
+            e.removeHint(SysdynElementHints.KEY_LOOP_CLOCKWISE);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopFactory.java
new file mode 100644 (file)
index 0000000..473ee7a
--- /dev/null
@@ -0,0 +1,379 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Paint;\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Arc2D;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.RectangularShape;\r
+import java.util.Collection;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.elements.ITextListener;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.DiagramUtils;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.SceneGraphNodeKey;\r
+import org.simantics.g2d.element.handler.HandleMouseEvent;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.HoverImpl;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.OutlinePick;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.elementclass.ImageClass.StaticImageElementHandler;\r
+import org.simantics.g2d.image.DefaultImages;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.g2d.svg.SVGImage;\r
+import org.simantics.g2d.utils.Alignment;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.nodes.SVGNode;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.LoopTab;\r
+import org.simantics.sysdyn.utils.LoopUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Callback;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintListener;\r
+import org.simantics.utils.datastructures.hints.IHintObservable;\r
+\r
+/**\r
+ * Factory for loops.\r
+ * \r
+ * @author Tuomas Miettinen\r
+ */\r
+public class LoopFactory extends SysdynElementFactory {\r
+\r
+       public static final Image LOOP_STATIC_IMAGE = new ShapeImage(getLoopShape(), null, new BasicStroke(1), true);\r
+       private static Image image = null;\r
+\r
+       @Override\r
+       public ElementClass create(ReadGraph graph, ICanvasContext canvas,\r
+                       IDiagram diagram, Resource elementType) throws DatabaseException {\r
+\r
+               // Create the loop symbol svg image\r
+               G2DResource g2d = G2DResource.getInstance(graph);\r
+               String svgDoc = graph.getPossibleRelatedValue(elementType, g2d.HasSVGDocument);\r
+               String id = "TextElement: " + NameUtils.getSafeName(graph, elementType);\r
+               if (svgDoc != null)\r
+                       image = new SVGImage(id+".svg", svgDoc);\r
+               else\r
+                       image = DefaultImages.ERROR_DECORATOR.get();\r
+\r
+               return ElementClass.compile(\r
+                               SimpleElementLayers.INSTANCE,\r
+                               OutlinePick.INSTANCE,\r
+                               TextImpl.INSTANCE,\r
+                               TextColorImpl.BLACK,\r
+                               TextFontImpl.DEFAULT,\r
+                               DefaultTransform.INSTANCE,\r
+                               new StaticObjectAdapter(elementType),\r
+                               new StaticSymbolImpl(image),\r
+                               StaticSymbolImageInitializer.INSTANCE,\r
+                               LoopSceneGraph.INSTANCE,\r
+                               new LoopImageSceneGraph(image),\r
+                               HoverImpl.INSTANCE,\r
+                               BoundsOutline.INSTANCE,\r
+                               LoopClockwise.INSTANCE\r
+        ).setId(LoopFactory.class.getSimpleName());\r
+       }\r
+\r
+       static Shape getLoopShape() {\r
+               // Used in shortcut.\r
+               Path2D loop = new Path2D.Double();\r
+               loop.moveTo(1, 2);\r
+               loop.lineTo(0, 0);\r
+               loop.lineTo(-1, 2);\r
+               loop.closePath();\r
+\r
+               loop.append(new Arc2D.Double(-10, -3, 10, 10, 0, -270, Arc2D.OPEN), false);\r
+               return loop;\r
+       }\r
+\r
+       @Override\r
+       protected String getText(ReadGraph graph, Resource element) throws DatabaseException {\r
+               // Get loop comment instead of loop name.\r
+               SysdynResource sr = SysdynResource.getInstance(graph); \r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
+               String text = null;\r
+               if (component != null) {\r
+                       text = (String) graph.getPossibleRelatedValue(component, sr.Loop_Comment);\r
+               }\r
+               if (text == null)\r
+                       text = "";\r
+               else if (LoopTab.AUTO.equals(text)) {\r
+                       switch (LoopUtils.getLoopType(graph, component)) {\r
+                       case BALANCING:\r
+                               text = "B";\r
+                               break;\r
+                       case REINFORCING:\r
+                               text = "R";\r
+                               break;\r
+                       default:\r
+                               text = "";\r
+                       }\r
+               }\r
+               return text;\r
+       }\r
+\r
+       @Override\r
+       protected ElementClass compileElementClass(Resource elementType,\r
+                       Collection<ObjectTerminal> terminals) {\r
+               return null;\r
+       }\r
+       \r
+    @Override\r
+    public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {\r
+        super.load(graph, canvas, diagram, element, e);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Boolean clockwise = graph.getPossibleRelatedValue(element, sr.LoopSymbol_Clockwise, Bindings.BOOLEAN);\r
+        if(clockwise == null) {\r
+            clockwise = Boolean.TRUE;\r
+        }\r
+        SysdynElementUtils.setLoopClockwise(e, clockwise);\r
+    }\r
+    \r
+    \r
+\r
+       /**\r
+        * Handling for the loop image on diagram.\r
+        * @author Tuomas Miettinen\r
+        *\r
+        */\r
+       public static class LoopImageSceneGraph extends StaticImageElementHandler {\r
+\r
+               private static final long serialVersionUID = -185893525553743589L;\r
+               \r
+               private IHintListener hoverHintListener;\r
+               \r
+               private static final Key            NODE             = new SceneGraphNodeKey(LoopNode.class, "LOOP_NODE");\r
+\r
+               public LoopImageSceneGraph(Image i) {\r
+                       super(i);\r
+               }\r
+\r
+               @Override\r
+               public void init(IElement e, G2DParentNode parent) {\r
+                       super.init(e, parent);\r
+\r
+                       // Create new hover shape node for the loop image\r
+                       final LoopNode node = ElementUtils.getOrCreateNode(e, parent, NODE, "loopHover", LoopNode.class);\r
+                       \r
+                       // Mirror the image if clockwise is selected.\r
+                       Boolean clockwise = e.getHint(SysdynElementHints.KEY_LOOP_CLOCKWISE);\r
+                       SVGNode image = e.getHint(getNodeKey());\r
+                       if (clockwise != null && clockwise) {\r
+               Point2D imageParent = (Point2D) image.localToParent(new Point2D.Double(0.0,0.0)).clone();\r
+               AffineTransform at = new AffineTransform(-1.0, 0.0, 0.0, 1.0, imageParent.getX(), imageParent.getY());\r
+               image.setTransform(at);\r
+                       }\r
+                       \r
+                       // Set the shape of the shape node to match the shape of the image\r
+                       RectangularShape bounds = (RectangularShape)image.getBounds().clone();\r
+                       node.setShape(bounds);\r
+                                               \r
+                       // Set the shape node transparent\r
+                       Paint paint = new Color(0,0,0,0);\r
+                       node.setColor(paint);\r
+                       \r
+                       // Handle hover\r
+                       Boolean hover = e.getHint(ElementHints.KEY_HOVER); \r
+                       node.setHover(hover != null ? hover : false);\r
+                       hoverHintListener = new IHintListener() {\r
+\r
+                               @Override\r
+                               public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {\r
+                               }\r
+\r
+                               @Override\r
+                               public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
+                                       IElement e = (IElement)sender;\r
+                                       LoopNode shape = (LoopNode) e.getHint(NODE);\r
+                                       if(shape == null) {\r
+                                               return;\r
+                                       }\r
+                                       boolean hover = ElementUtils.isHovering(e);\r
+                                       shape.setHover(hover);\r
+                               }\r
+                       };\r
+                       e.addHintListener(hoverHintListener);\r
+               }\r
+\r
+               @Override\r
+               public void cleanup(IElement e) {\r
+                       super.cleanup(e);\r
+                       e.removeHintListener(hoverHintListener);\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Handling for the text box of loop in diagram.\r
+        * @author Tuomas Miettinen\r
+        *\r
+        */\r
+       public static class LoopSceneGraph extends SysdynTextElementNoBounds  implements HandleMouseEvent {\r
+\r
+               private static final long serialVersionUID = -5093461687773246286L;\r
+\r
+               public static final LoopSceneGraph INSTANCE         = new LoopSceneGraph();\r
+               \r
+               private static final Key            NODE             = new SceneGraphNodeKey(ShapeNode.class, "LOOP_COMMENT_NODE");\r
+        \r
+               public LoopSceneGraph() {\r
+                       super(0, 0, Alignment.CENTER, 0, 1, 1, true);\r
+               }\r
+               \r
+               @Override\r
+               public void init(IElement e, G2DParentNode parent) {\r
+                       super.init(e, parent);\r
+                       \r
+                       // Move the text box into (around) the middle of the loop image\r
+                       AffineTransform at = ElementUtils.getTransform(e);\r
+                       final LoopNode node = ElementUtils.getOrCreateNode(e, parent, NODE, "loopComment", LoopNode.class);\r
+\r
+                       // Unflip the text and image\r
+                       unflipText(e);\r
+\r
+                       if(at != null) {\r
+                               node.setTransform(at);\r
+\r
+                               TextNode name = (TextNode) e.getHint(SG_NODE);\r
+                               if(name != null) {\r
+                                       AffineTransform at2 = (AffineTransform) at.clone();\r
+                                       at2.translate(getXCoordShift(e), getYCoordShift(e));\r
+\r
+                                       Alignment alignment = Alignment.CENTER;\r
+\r
+                                       name.setTransform(at2);\r
+                                       if(alignment != null) {\r
+                                               name.setHorizontalAlignment((byte) alignment.ordinal());\r
+                                               name.setVerticalAlignment((byte) alignment.ordinal());\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+\r
+               private static double getXCoordShift(IElement e) {\r
+                       //String location = e.getHint(SysdynElementHints.KEY_LOCATION);\r
+                       return 0;\r
+               }\r
+\r
+               private static double getYCoordShift(IElement e) {\r
+                       //String location = e.getHint(SysdynElementHints.KEY_LOCATION);\r
+                       return 9.7;\r
+               }\r
+\r
+               @Override\r
+               protected <T extends SysdynTextNode> Callback<T> getCallback(final IElement e, G2DParentNode parent, Class<T> nodeClass) {\r
+                       return new Callback<T>() {\r
+                               @Override\r
+                               public void run(T node) {\r
+                                       node.setTextListener(new ITextListener() {\r
+\r
+                                               Resource component;\r
+\r
+                                               @Override\r
+                                               public void textChanged() {\r
+                                               }\r
+\r
+                                               @Override\r
+                                               public void textEditingStarted() {\r
+                                                       if(component != null) return;\r
+\r
+                                                       Object o = e.getHint(ElementHints.KEY_OBJECT);\r
+                                                       if(o != null && o instanceof Resource) {\r
+                                                               final Resource element = (Resource)o;\r
+                                                               SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+\r
+                                                                       @Override\r
+                                                                       public void run(ReadGraph graph) throws DatabaseException {\r
+                                                                               component = graph.getPossibleObject(element, ModelingResources.getInstance(graph).ElementToComponent);\r
+                                                                       }\r
+                                                               });\r
+                                                       }\r
+                                               }\r
+\r
+                                               @Override\r
+                                               public void textEditingCancelled() {\r
+                                                       TextNode node = (TextNode) e.getHint(SG_NODE);\r
+                                                       if (node != null) {\r
+                                                               endEdit(node);\r
+                                                       }\r
+                                               }\r
+\r
+                                               @Override\r
+                                               public void textEditingEnded() {\r
+                                                       TextNode node = (TextNode) e.getHint(SG_NODE);\r
+                                                       if (node == null)\r
+                                                               return;\r
+\r
+                                                       // Write the changed comment of the loop\r
+                                                       final String text = node.getText();\r
+                                                       try {\r
+                                                               SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                                                                       @Override\r
+                                                                       public void perform(WriteGraph graph)\r
+                                                                                       throws DatabaseException {\r
+                                                                               if (component != null) {\r
+                                                                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                                                                       graph.deny(component, sr.Loop_Comment);\r
+                                                                                       graph.claimLiteral(component, sr.Loop_Comment, text);\r
+                                                                               }\r
+                                                                       }\r
+\r
+                                                               });\r
+                                                       } catch (DatabaseException e1) {\r
+                                                               e1.printStackTrace();\r
+                                                       }\r
+\r
+                                                       IDiagram diagram = ElementUtils.getDiagram(e);\r
+                                                       DiagramUtils.synchronizeHintsToBackend(diagram, e);\r
+                                                       endEdit(node);\r
+                                               }\r
+                                       });\r
+                               }\r
+                       };\r
+               }\r
+\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopNode.java
new file mode 100644 (file)
index 0000000..865ddf6
--- /dev/null
@@ -0,0 +1,241 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.elements.DiagramNodeUtil;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.scenegraph.INode;\r
+import org.simantics.scenegraph.ParentNode;\r
+import org.simantics.scenegraph.g2d.IG2DNode;\r
+import org.simantics.scenegraph.g2d.nodes.ConnectionNode;\r
+import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Node for Sysdyn loop elements.\r
+ * \r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class LoopNode extends HoverShapeNode {\r
+\r
+       /**\r
+        * Interface for nodes that can be part of loops\r
+        * @author Tuomas Miettinen\r
+        *\r
+        */\r
+       public interface ILoopComponentNode {\r
+               \r
+               /**\r
+                * Sets or resets the loop selected status\r
+                * @param loop The loop which has been selected\r
+                * @param selected true iff the loop is selected\r
+                */\r
+               public void setLoopSelected(LoopNode loop, boolean selected);\r
+               \r
+       }\r
+       \r
+       public static Color HIGHLIGHT_COLOR = Color.decode("#ff5fbf");\r
+       \r
+       private boolean selected = false;\r
+       \r
+       private static final long serialVersionUID = 6173159124691715569L;\r
+       \r
+       @Override\r
+    public void render(Graphics2D g2d) {\r
+               super.render(g2d);\r
+               \r
+               // If the loop is selected, highlight also the elements that belong to the loop.\r
+               boolean selected = NodeUtil.isSelected(this, 1);\r
+               // Do nothing if the selection is and was off.\r
+               if (selected || this.selected != selected) {\r
+                       this.selected = selected; \r
+                       // Tell all items belonging to the loop that the loop is selected.\r
+                       setLoopItemsSelected();\r
+               }\r
+       }\r
+       \r
+       private void setLoopItemsSelected() {\r
+               // Get all variables and dependencies in the loop.\r
+               List<Resource> loopItems = getAllLoopItems();\r
+               \r
+               // Get the diagram where this loop is.\r
+               RTreeNode diagramNode = (RTreeNode)NodeUtil.getNearestParentOfType(this, RTreeNode.class);\r
+               if (diagramNode == null)\r
+                       return;\r
+               \r
+               // Go through all elements on the diagram where this loop is.\r
+               Collection<IG2DNode> children = diagramNode.getNodes();\r
+               Iterator<IG2DNode> it = children.iterator();\r
+               while (it.hasNext()) {\r
+                       IG2DNode n = it.next();\r
+                       \r
+                       // Get the respective node \r
+                       INode child = getNodeOfPossibleLoopComponentNode(n);\r
+                       if (child instanceof ILoopComponentNode) {\r
+                               ILoopComponentNode ln = (ILoopComponentNode)child;\r
+                               // Get the respective element \r
+                               IElement e = DiagramNodeUtil.getElement((IG2DNode)child.getParent());\r
+                               // Get the respective resource \r
+                               Resource r = e.getHint(ElementHints.KEY_OBJECT);\r
+                               // If the node belongs to the loop, tell it that whether the loop is selected or not.\r
+                               ln.setLoopSelected(this, NodeUtil.isSelected(this, 1) && loopItems.contains(r));\r
+                       }\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Get the ILoopComponentNode under the variable, dependency, or flow. \r
+        * @param n node under which the ILoopComponentNode is sought\r
+        * @return ILoopComponentNode or null, if there is not any.\r
+        */\r
+       private static INode getNodeOfPossibleLoopComponentNode(IG2DNode n) {\r
+               // Get all nodeIds of n's children.\r
+               Collection<String> nodeIds = ((ParentNode<?>)n).getNodeIds();\r
+\r
+               // Flows and SysdynTextNodes\r
+               for (String id : nodeIds) {\r
+                       if ("text".equals(id)\r
+                                       || id.startsWith("flow_")) \r
+                               return ((ParentNode<?>)n).getNode(id);\r
+               }\r
+\r
+               // Dependencies\r
+               if (n instanceof ConnectionNode) {\r
+                       // See the if a child of n has a DependencyNode as a child.\r
+                       Iterator<IG2DNode> it = ((ConnectionNode) n).getNodes().iterator();\r
+                       while (it.hasNext()) {\r
+                               n = it.next();\r
+                               if (n instanceof ParentNode<?>) {\r
+                                       nodeIds = ((ParentNode<?>)n).getNodeIds();\r
+                                       for (String id : nodeIds) {\r
+                                               if (id.startsWith("edge_"))\r
+                                                       return ((ParentNode<?>)n).getNode(id);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               return null; // n was no variable, dependency, or flow\r
+\r
+       }\r
+\r
+       /**\r
+        * Get all variables and dependencies in the loop.\r
+        * @return A list where the items are, in unspecified order.\r
+        */\r
+       private List<Resource> getAllLoopItems() {\r
+               IElement loopElement = DiagramNodeUtil.getElement(this);\r
+               final Resource loopSymbolResource = loopElement.getHint(ElementHints.KEY_OBJECT);\r
+               List<Resource> loopItems = Collections.emptyList();\r
+               \r
+               try {\r
+                       loopItems = SimanticsUI.getSession().syncRequest(new Read<List<Resource>>(){\r
+\r
+                               @Override\r
+                               public List<Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                                       ModelingResources mod = ModelingResources.getInstance(graph);\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Resource loopComponentResource = graph.getPossibleObject(loopSymbolResource, mod.ElementToComponent);\r
+                                       if (loopComponentResource == null)\r
+                                               return Collections.emptyList();\r
+                                       \r
+                                       Resource loopResource = graph.getPossibleObject(loopComponentResource, sr.Loop_Items);\r
+                                       if (loopResource == null)\r
+                                               return Collections.emptyList();\r
+                                       \r
+                                       List<Resource> loopItems = ListUtils.toPossibleList(graph, loopResource);\r
+                                       if (loopItems == null)\r
+                                               return Collections.emptyList();\r
+                                       \r
+                                       ArrayList<Resource> dependencyItems = new ArrayList<Resource>();\r
+                                       \r
+                                       // Add dependencies and flows.\r
+                                       for (int i = 0; i < loopItems.size(); ++i) {\r
+                                       boolean skipBackwardFlows = false;\r
+                                       \r
+                                       // Go through forward dependencies and flows\r
+                                       Collection<Resource> forwardDependencies = graph.getObjects(loopItems.get(i), sr.Variable_isTailOf);\r
+                                       \r
+                                       // And also through the forward dependencies of possible shadows.\r
+                                       Collection<Resource> shadows = graph.getObjects(loopItems.get(i), sr.Shadow_original_Inverse);\r
+                                       for (Resource shadow : shadows)\r
+                                               forwardDependencies.addAll(graph.getObjects(shadow, sr.Variable_isTailOf));\r
+                                               \r
+                                       for (Resource dependency : forwardDependencies) {\r
+                                               Resource dependingVariable = graph.getSingleObject(dependency, sr.Variable_HasHead);\r
+                                               if (dependingVariable.equals(loopItems.get((i + 1) % loopItems.size()))) {\r
+                                                       if (graph.isInstanceOf(dependency, sr.Flow)\r
+                                                                       && graph.isInstanceOf(loopItems.get(i), sr.Stock)) {\r
+                                                               // Flows from stocks don't count. \r
+                                                               continue;\r
+                                                       }\r
+                                                       skipBackwardFlows = true;\r
+                                                       dependencyItems.add(graph.getSingleObject(dependency, mod.ConnectionToDiagramConnection));\r
+                                                       break;\r
+                                               }\r
+                                       }\r
+                                       \r
+                                       if (skipBackwardFlows)\r
+                                               continue;\r
+                                       \r
+                                       // Backward flows from stocks.\r
+                                       Collection<Resource> backwardFlows = graph.getObjects(loopItems.get(i), sr.Variable_isHeadOf);\r
+                                               for (Resource flow : backwardFlows) {\r
+                                                       if (graph.isInstanceOf(flow, sr.Flow)) {\r
+                                                               Resource dependingVariable = graph.getSingleObject(flow, sr.Variable_HasTail);\r
+                                                               if (dependingVariable.equals(loopItems.get((i + 1) % loopItems.size()))\r
+                                                                               && graph.isInstanceOf(dependingVariable, sr.Stock)) {\r
+                                                                       dependencyItems.add(graph.getSingleObject(flow, mod.ConnectionToDiagramConnection));\r
+                                                                       break;\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                               }\r
+                                       \r
+                                       // Convert variables from component to element.\r
+                                       for (int i = 0; i < loopItems.size(); ++i) {\r
+                                               loopItems.set(i, graph.getPossibleObject(loopItems.get(i), mod.ComponentToElement));\r
+                                       }\r
+                                       // Merge the two lists.\r
+                                       loopItems.addAll(dependencyItems);\r
+                                       \r
+                                       return loopItems;\r
+                               }\r
+                               \r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       // TODO Auto-generated catch block\r
+                       e1.printStackTrace();\r
+               }\r
+               \r
+               return loopItems;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ModuleFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ModuleFactory.java
new file mode 100644 (file)
index 0000000..175a95d
--- /dev/null
@@ -0,0 +1,88 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.diagram.elements.ResizeRectangularSceneGraph;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.impl.BorderColorImpl;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.OutlinePick;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.g2d.utils.Alignment;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+\r
+public class ModuleFactory extends SysdynElementFactory {\r
+\r
+    private static final BasicStroke    STROKE           = new BasicStroke(2.0f);\r
+    private static final Image DEFAULT_IMAGE = new ShapeImage(new Rectangle2D.Double(-5, -2.5, 10, 5), null, STROKE, true);\r
+\r
+    @Override\r
+    protected ElementClass compileElementClass(Resource elementType, Collection<ObjectTerminal> terminals) {\r
+        return ElementClass.compile(\r
+                SimpleElementLayers.INSTANCE,\r
+                OutlinePick.INSTANCE,\r
+                TextImpl.INSTANCE,\r
+                TextColorImpl.BLACK,\r
+                new TextFontImpl(new Font("arial", Font.PLAIN, 25)),\r
+                DefaultTransform.INSTANCE,\r
+                new StaticObjectAdapter(elementType),\r
+                new StaticSymbolImpl(DEFAULT_IMAGE),\r
+                StaticSymbolImageInitializer.INSTANCE,\r
+                new ModuleSceneGraph(0, 0, Alignment.CENTER, 1f , 2, 3, true),\r
+                BoundsOutline.INSTANCE,\r
+                new BorderColorImpl(Color.BLACK),\r
+                ResizeRectangularSceneGraph.INSTANCE,\r
+                RESIZE_PROPERTY_SETTER,                   \r
+                new WholeElementTerminals(terminals)\r
+        ).setId(ModuleFactory.class.getSimpleName());\r
+    }\r
+    \r
+    \r
+    public static class ModuleSceneGraph extends SysdynTextElementHandler implements InternalSize {\r
+\r
+               private static final long       serialVersionUID = 2367230056477661273L;\r
+        \r
+               public ModuleSceneGraph(double originX, double originY, Alignment horizontalAlignment, double borderWidth,\r
+                   double paddingX, double paddingY, boolean editable) {\r
+               super(originX, originY, horizontalAlignment, borderWidth, paddingX, paddingY, editable);\r
+        }\r
+               \r
+               \r
+               \r
+               @Override\r
+               protected TextNode getOrCreateTextNode(IElement e, G2DParentNode parent) {\r
+            return ElementUtils.getOrCreateNode(e, parent, SG_NODE, "text", ModuleNode.class, getCallback(e, parent, ModuleNode.class));\r
+               }\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ModuleNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ModuleNode.java
new file mode 100644 (file)
index 0000000..f2431be
--- /dev/null
@@ -0,0 +1,92 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.AlphaComposite;\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Composite;\r
+import java.awt.Graphics2D;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.scenegraph.utils.GeometryUtils;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+\r
+public class ModuleNode extends SysdynTextNode {\r
+\r
+       private static final long serialVersionUID = 8535695797227320496L;\r
+    private static double              CORNER_LENGTH    = 2.0; \r
+    private static double              CORNER_PADDING   = 0.8; \r
+    \r
+    \r
+    @Override\r
+    public void render(Graphics2D g) {\r
+       super.render(g);\r
+       \r
+        BasicStroke oldStroke = (BasicStroke)g.getStroke();\r
+        Color oldColor = g.getColor();\r
+\r
+        Rectangle2D bounds = getBounds();\r
+\r
+        \r
+        Path2D path = new Path2D.Double();\r
+        // LEFT TOP\r
+        path.moveTo(bounds.getMinX() + CORNER_LENGTH, bounds.getMinY() - CORNER_PADDING);\r
+        path.lineTo(bounds.getMinX() - CORNER_PADDING, bounds.getMinY() - CORNER_PADDING);\r
+        path.lineTo(bounds.getMinX() - CORNER_PADDING, bounds.getMinY() + CORNER_LENGTH);\r
+        \r
+        // LEFT BOTTOM\r
+        path.moveTo(bounds.getMinX() + CORNER_LENGTH, bounds.getMaxY() + CORNER_PADDING);\r
+        path.lineTo(bounds.getMinX() - CORNER_PADDING, bounds.getMaxY() + CORNER_PADDING);\r
+        path.lineTo(bounds.getMinX() - CORNER_PADDING, bounds.getMaxY() - CORNER_LENGTH);\r
+        \r
+        // RIGHT TOP\r
+        path.moveTo(bounds.getMaxX() - CORNER_LENGTH, bounds.getMinY() - CORNER_PADDING);\r
+        path.lineTo(bounds.getMaxX() + CORNER_PADDING, bounds.getMinY() - CORNER_PADDING);\r
+        path.lineTo(bounds.getMaxX() + CORNER_PADDING, bounds.getMinY() + CORNER_LENGTH);\r
+        \r
+        // RIGHT BOTTOM\r
+        path.moveTo(bounds.getMaxX() - CORNER_LENGTH, bounds.getMaxY() + CORNER_PADDING);\r
+        path.lineTo(bounds.getMaxX() + CORNER_PADDING, bounds.getMaxY() + CORNER_PADDING);\r
+        path.lineTo(bounds.getMaxX() + CORNER_PADDING, bounds.getMaxY() - CORNER_LENGTH);\r
+        \r
+        g.setStroke(new BasicStroke((float) (/*scale**/scale*borderWidth)));       \r
+        g.setColor(borderColor);\r
+        g.draw(path);   \r
+        \r
+        \r
+        boolean selected = NodeUtil.isSelected(this, 1);\r
+        if (selected && showsSelection()) {\r
+            Composite oc = g.getComposite();\r
+            g.setComposite(AlphaComposite.SrcOver.derive(0.5f));\r
+\r
+            g.setColor(Color.RED);\r
+            float bw = borderWidth;\r
+            double s = GeometryUtils.getScale(g.getTransform());\r
+            if (bw <= 0f) {\r
+                bw = (float) (1f / s);\r
+            } else {\r
+                bw *= 3f * scale;\r
+            }\r
+            g.setStroke(new BasicStroke(bw));\r
+            g.draw(path);\r
+\r
+            g.setComposite(oc);\r
+        }\r
+\r
+        g.setColor(oldColor);\r
+        g.setStroke(oldStroke);\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/MultilineTextElementFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/MultilineTextElementFactory.java
new file mode 100644 (file)
index 0000000..d6b56d0
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.adapter.TextElementClassFactory;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.IElement;\r
+\r
+/**\r
+ * Multi-line text element used in comment in sysdyn diagrams\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class MultilineTextElementFactory extends TextElementClassFactory {\r
+\r
+    @Override\r
+    public void load(ReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource element, IElement e)\r
+            throws DatabaseException {\r
+        super.load(graph, canvas, diagram, element, e);\r
+        e.setHint(ElementHints.KEY_RESIZABLE, true);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Orientation.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Orientation.java
new file mode 100644 (file)
index 0000000..dbf3257
--- /dev/null
@@ -0,0 +1,35 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.ElementHandler;\r
+\r
+public class Orientation implements ElementHandler {\r
+\r
+    private static final long serialVersionUID = 958120463924210936L;\r
+    \r
+    public static final Orientation INSTANCE = new Orientation();\r
+    \r
+    public String getOrientation(IElement e) {\r
+        return e.getHint(SysdynElementHints.KEY_ORIENTATION);\r
+    }\r
+\r
+    \r
+    public void setOrientation(IElement e, String orientation) {\r
+        if (orientation != null)\r
+            e.setHint(SysdynElementHints.KEY_ORIENTATION, orientation);\r
+        else\r
+            e.removeHint(SysdynElementHints.KEY_ORIENTATION);\r
+    }\r
+}\r
+    \r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/RectangleNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/RectangleNode.java
new file mode 100644 (file)
index 0000000..1f05f54
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+import org.simantics.scenegraph.g2d.G2DNode;\r
+\r
+public class RectangleNode extends G2DNode {\r
+       \r
+       private static final long serialVersionUID = 654692698101485672L;\r
+\r
+    protected Rectangle2D bounds = null;\r
+\r
+    @SyncField("bounds")\r
+    public void init(Rectangle2D bounds) {\r
+        this.bounds = bounds;\r
+    }\r
+\r
+    @Override\r
+    public void render(Graphics2D g) {\r
+        if(bounds == null) return;\r
+        AffineTransform ot = g.getTransform();\r
+        \r
+        g.transform(transform);\r
+        g.setColor(Color.BLACK);\r
+        double scale = g.getTransform().getScaleX();\r
+        g.setStroke(new BasicStroke( (float)(1.0 / scale) ));\r
+\r
+        g.draw(bounds);\r
+        g.setTransform(ot);\r
+    }\r
+\r
+       @Override\r
+       public Rectangle2D getBoundsInLocal() {\r
+               return bounds;\r
+       }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowFactory.java
new file mode 100644 (file)
index 0000000..726cae6
--- /dev/null
@@ -0,0 +1,129 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Ellipse2D;\r
+import java.awt.geom.Path2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.elements.ResizeRectangularSceneGraph;\r
+import org.simantics.diagram.elements.TextElementHandler;\r
+import org.simantics.diagram.synchronization.SynchronizationHints;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.OutlinePick;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.g2d.utils.Alignment;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ShadowFactory extends SysdynElementFactory {\r
+\r
+    private static TextElementHandler shadowHandler = new TextElementHandler(0, 0, Alignment.LEADING, 0.0, 2.0, 2.0, false); \r
+    private static final TextColorImpl GRAY = new TextColorImpl(java.awt.Color.GRAY);\r
+    private static final BasicStroke    STROKE          = new BasicStroke(1f);\r
+    public static final Image          GHOST_IMAGE     = new ShapeImage(getGhostShape(), null, STROKE, true);\r
+\r
+    static Shape getGhostShape() {\r
+        \r
+        Path2D path = new Path2D.Double();\r
+        \r
+        // Body\r
+        path.moveTo(-3, 3);\r
+        path.quadTo(-3, -3, 0, -3);\r
+        path.quadTo(3, -3, 3, 3);\r
+        path.lineTo(2, 2);\r
+        path.lineTo(1, 3);\r
+        path.lineTo(0, 2);\r
+        path.lineTo(-1, 3);\r
+        path.lineTo(-2, 2);\r
+        path.closePath();\r
+        \r
+        // Eyes\r
+        path.append(new Ellipse2D.Double(-1.25, -1.25, 0.5, 0.5), false);\r
+        path.append(new Ellipse2D.Double(0.75, -1.25, 0.5, 0.5), false);\r
+        return path;\r
+    }\r
+\r
+\r
+    @Override\r
+    protected ElementClass compileElementClass(Resource elementType, Collection<ObjectTerminal> terminals) {\r
+        return ElementClass.compile(\r
+                SimpleElementLayers.INSTANCE,\r
+                OutlinePick.INSTANCE,\r
+                TextImpl.INSTANCE,\r
+                GRAY,\r
+                TextFontImpl.DEFAULT,\r
+                DefaultTransform.INSTANCE,\r
+                new StaticObjectAdapter(elementType),\r
+                new StaticSymbolImpl(GHOST_IMAGE),\r
+                StaticSymbolImageInitializer.INSTANCE,\r
+                shadowHandler,\r
+                BoundsOutline.INSTANCE,\r
+                ResizeRectangularSceneGraph.INSTANCE,\r
+                RESIZE_PROPERTY_SETTER,    \r
+                new WholeElementTerminals(terminals)\r
+        ).setId(ShadowFactory.class.getSimpleName());\r
+    }\r
+\r
+    @Override\r
+    public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        ModelingResources mr = ModelingResources.getInstance(graph);\r
+\r
+        Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
+        String text = null;\r
+        if (component != null) {\r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+            Resource original = graph.getPossibleObject(component, SR.Shadow_original);\r
+            if(original != null)\r
+                text = "< " + (String) graph.getPossibleRelatedValue(original, l0.HasName) + " >";\r
+        }\r
+        if (text == null)\r
+            text = "< --- >";\r
+\r
+        ElementUtils.setText(e, text);\r
+        \r
+        super.getVisualProperties(graph, element, e);\r
+\r
+        AffineTransform at = DiagramGraphUtil.getAffineTransform(graph, element);\r
+        ElementUtils.setTransform(e, at);\r
+\r
+        // This synchronizes only text and transformation (not font and color)\r
+        e.setHint(SynchronizationHints.HINT_SYNCHRONIZER, SYNCHRONIZER);\r
+        \r
+        e.setHint(ElementHints.KEY_HOVER, false);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceDialogRunnable.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceDialogRunnable.java
new file mode 100644 (file)
index 0000000..6e1f7de
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.viewers.LabelProvider;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.dialogs.ElementListSelectionDialog;\r
+import org.simantics.db.Resource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ShadowVariableReferenceDialogRunnable implements Runnable {\r
+\r
+    private Resource shadow;\r
+    private HashMap<String, Resource> possibleReferences;\r
\r
+    public ShadowVariableReferenceDialogRunnable(Resource shadow, HashMap<String, Resource> possibleReferences) {\r
+        this.shadow = shadow;\r
+        this.possibleReferences = possibleReferences;\r
+    }\r
+    \r
+    @Override\r
+    public void run() {\r
+        Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
+        \r
+        ElementListSelectionDialog dialog = \r
+                new ElementListSelectionDialog(shell, new LabelProvider());\r
+        dialog.setElements(possibleReferences.keySet().toArray(new String[possibleReferences.keySet().size()]));\r
+        dialog.setTitle("Select referred variable");\r
+        dialog.setMultipleSelection(false);\r
+        \r
+        dialog.open();\r
+        \r
+        Object[] result = dialog.getResult(); \r
+        \r
+        Resource resource = null;\r
+        if(result != null && result.length == 1)\r
+            resource = possibleReferences.get(result[0]);\r
+        \r
+        SimanticsUI.getSession().asyncRequest(new ShadowVariableReferenceRequest(shadow, resource));\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceRequest.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceRequest.java
new file mode 100644 (file)
index 0000000..7fb80e8
--- /dev/null
@@ -0,0 +1,45 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ShadowVariableReferenceRequest extends WriteRequest {\r
+    \r
+    Resource shadow;\r
+    Resource original;\r
+    \r
+    public ShadowVariableReferenceRequest(Resource shadow, Resource original) {\r
+        this.shadow = shadow;\r
+        this.original = original;\r
+    }\r
+\r
+    @Override\r
+    public void perform(WriteGraph graph) throws DatabaseException {\r
+        if(shadow == null)\r
+            return;\r
+        \r
+        if(shadow != null && original == null) {\r
+            Resource element = graph.getPossibleObject(shadow, ModelingResources.getInstance(graph).ComponentToElement);\r
+            RemoverUtil.remove(graph, element);\r
+        } else { \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        graph.claim(shadow, SR.Shadow_original, original);\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Size.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/Size.java
new file mode 100644 (file)
index 0000000..00b0d2f
--- /dev/null
@@ -0,0 +1,88 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.LifeCycle;\r
+\r
+/**\r
+ * Class for internal size and setting default bounds when element is created. \r
+ * Used especially with comment elements (resizeable text elements)\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class Size implements  InternalSize, LifeCycle {\r
+    private static final long serialVersionUID = -7459941323196171227L;\r
+    private Rectangle2D defaultBounds;\r
+    \r
+    public Size(Rectangle2D defaultSize) {\r
+        this.defaultBounds = defaultSize;\r
+    }\r
+    \r
+    /**\r
+     * Set default bounds for the created element\r
+     * @param e Element\r
+     */\r
+    @Override\r
+    public void onElementCreated(IElement e) {\r
+        e.setHint(ElementHints.KEY_BOUNDS, defaultBounds);\r
+    }\r
+    \r
+    /**\r
+     * Returns bounds of the element\r
+     */\r
+    @Override\r
+    public Rectangle2D getBounds(IElement e, Rectangle2D size) {\r
+        if (size==null) size = new Rectangle2D.Double();\r
+        size.setFrame((Rectangle2D)e.getHint(ElementHints.KEY_BOUNDS));\r
+        return size;\r
+    }\r
+\r
+    @Override\r
+    public void onElementDestroyed(IElement e) {}\r
+    @Override\r
+    public void onElementActivated(IDiagram d, IElement e) {}\r
+    @Override\r
+    public void onElementDeactivated(IDiagram d, IElement e) {}\r
+\r
+    @Override\r
+    public int hashCode() {\r
+        final int prime = 31;\r
+        int result = 1;\r
+        result = prime * result\r
+                + ((defaultBounds == null) ? 0 : defaultBounds.hashCode());\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public boolean equals(Object obj) {\r
+        if (this == obj)\r
+            return true;\r
+        if (obj == null)\r
+            return false;\r
+        if (getClass() != obj.getClass())\r
+            return false;\r
+        Size other = (Size) obj;\r
+        if (defaultBounds == null) {\r
+            if (other.defaultBounds != null)\r
+                return false;\r
+        } else if (!defaultBounds.equals(other.defaultBounds))\r
+            return false;\r
+        return true;\r
+    }    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/StockFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/StockFactory.java
new file mode 100644 (file)
index 0000000..96b6895
--- /dev/null
@@ -0,0 +1,76 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.elements.ResizeRectangularSceneGraph;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.impl.BorderColorImpl;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.OutlinePick;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.g2d.utils.Alignment;\r
+\r
+public class StockFactory extends SysdynElementFactory {\r
+\r
+    private static final BasicStroke    STROKE           = new BasicStroke(1f);\r
+    public static final Image STOCK_IMAGE = new ShapeImage(new Rectangle2D.Double(-5, -2.5, 10, 5), null, STROKE, true);\r
+\r
+    @Override\r
+    protected ElementClass compileElementClass(Resource elementType, Collection<ObjectTerminal> terminals) {\r
+        return ElementClass.compile(\r
+                SimpleElementLayers.INSTANCE,\r
+                OutlinePick.INSTANCE,\r
+                TextImpl.INSTANCE,\r
+                TextColorImpl.BLACK,\r
+                TextFontImpl.DEFAULT,\r
+                DefaultTransform.INSTANCE,\r
+                new StaticObjectAdapter(elementType),\r
+                new StaticSymbolImpl(STOCK_IMAGE),\r
+                StaticSymbolImageInitializer.INSTANCE,\r
+                new SysdynTextElementHandler(0, 0, Alignment.CENTER, 1f, 1.0, 1.0, true),\r
+                BoundsOutline.INSTANCE,\r
+                new BorderColorImpl(Color.BLACK),\r
+                ResizeRectangularSceneGraph.INSTANCE,\r
+                RESIZE_PROPERTY_SETTER,    \r
+                new WholeElementTerminals(terminals)\r
+        ).setId(StockFactory.class.getSimpleName());\r
+    }\r
+\r
+    @Override\r
+    public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {\r
+        super.load(graph, canvas, diagram, element, e);\r
+        e.setHint(ElementHints.KEY_BORDER_COLOR, e.getHint(ElementHints.KEY_TEXT_COLOR));\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementClasses.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementClasses.java
new file mode 100644 (file)
index 0000000..a2cb04a
--- /dev/null
@@ -0,0 +1,8 @@
+package org.simantics.sysdyn.ui.elements;\r
+\r
+public class SysdynElementClasses {\r
+\r
+    public static final Object VALVE = new Object() {\r
+        public String toString() { return "VALVE"; }\r
+    };\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementFactory.java
new file mode 100644 (file)
index 0000000..174ae57
--- /dev/null
@@ -0,0 +1,211 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.eclipse.jface.preference.PreferenceConverter;\r
+import org.eclipse.jface.resource.StringConverter;\r
+import org.eclipse.swt.graphics.FontData;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Statement;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.diagram.adapter.SyncElementFactory;\r
+import org.simantics.diagram.content.ResourceTerminal;\r
+import org.simantics.diagram.elements.ElementPropertySetter;\r
+import org.simantics.diagram.elements.ResizeRectangularSceneGraph;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.diagram.synchronization.CompositeHintSynchronizer;\r
+import org.simantics.diagram.synchronization.IHintSynchronizer;\r
+import org.simantics.diagram.synchronization.SynchronizationHints;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.diagram.synchronization.graph.TransformSynchronizer;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferences;\r
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPropertyExternalRead;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * An ElementFactory that gathers common functionality for system dynamics symbols.\r
+ * Just implement {@link #compileElementClass(Resource, Collection)} to add a symbol.\r
+ * \r
+ * @author Tuukka Lehtonen\r
+ */\r
+public abstract class SysdynElementFactory extends SyncElementFactory {\r
+\r
+    public static final IHintSynchronizer SYNCHRONIZER = new CompositeHintSynchronizer(\r
+            ComponentNameSynchronizer.INSTANCE,\r
+            TransformSynchronizer.INSTANCE);\r
+\r
+    public static final ElementPropertySetter RESIZE_PROPERTY_SETTER =\r
+            new ElementPropertySetter(ResizeRectangularSceneGraph.KEY_SG_NODE);\r
+    \r
+    protected String getText(ReadGraph graph, Resource element) throws DatabaseException {\r
+       Layer0 l0 = Layer0.getInstance(graph);\r
+        ModelingResources mr = ModelingResources.getInstance(graph);\r
+        Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
+        String text = null;\r
+        if (component != null) {\r
+            text = (String) graph.getPossibleRelatedValue(component, l0.HasName);\r
+        }\r
+        if (text == null)\r
+            text = "[empty]";\r
+               return text;\r
+    }\r
+    \r
+    @Override\r
+    public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {\r
+        e.setHint(ElementHints.KEY_RESIZABLE, true);\r
+       ElementUtils.setText(e, getText(graph, element));\r
+       // Just testing loop finding.\r
+       //ModelingResources mr = ModelingResources.getInstance(graph);\r
+        //Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
+        //ConfigurationUtils.getLoops(graph, component);\r
+        getVisualProperties(graph, element, e);\r
+\r
+        AffineTransform at = DiagramGraphUtil.getAffineTransform(graph, element);\r
+        ElementUtils.setTransform(e, at);\r
+\r
+        // This synchronizes only text and transformation (not font and color)\r
+        e.setHint(SynchronizationHints.HINT_SYNCHRONIZER, SYNCHRONIZER);\r
+        \r
+        e.setHint(ElementHints.KEY_HOVER, false);\r
+    }\r
+    \r
+    /**\r
+     * Reads a collection of visualization properties e.g. colour and font.\r
+     * @param graph ReadGraph\r
+     * @param element Element resource\r
+     * @param e Diagram element\r
+     * @throws DatabaseException\r
+     */\r
+    protected void getVisualProperties(ReadGraph graph, Resource element, IElement e) throws DatabaseException {\r
+        G2DResource g2d = G2DResource.getInstance(graph);\r
+        DiagramResource dr = DiagramResource.getInstance(graph);\r
+        ModelingResources mr = ModelingResources.getInstance(graph);\r
+        \r
+        if (graph.isInstanceOf(element, dr.FontProvider)) {\r
+            Statement fontStatement = graph.getPossibleStatement(element, g2d.HasFont);\r
+            if(fontStatement != null && !fontStatement.isAsserted(element)) {\r
+                ElementUtils.setTextFont(e, G2DUtils.getFont(graph, fontStatement.getObject()));\r
+            } else {\r
+                String fontdata = graph.syncRequest(new SysdynDiagramPropertyExternalRead(new Pair<Resource, String>(element, SysdynDiagramPreferences.getFontPreferenceName(graph, element))));\r
+                if(fontdata != null) {\r
+                    FontData[] fdArray = PreferenceConverter.basicGetFontData(fontdata);\r
+                    if(fdArray != null) {\r
+                        if(fdArray.length == 1) {\r
+                            FontData fd = fdArray[0];\r
+                            if(fd != null) {\r
+                                Font font = new Font(fd.getName(), fd.getStyle(), fd.getHeight());\r
+                                e.setHint(ElementHints.KEY_FONT, font);\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        if (graph.isInstanceOf(element, dr.ColorProvider)) {\r
+            Statement colorStatement = graph.getPossibleStatement(element, g2d.HasColor);\r
+            if(colorStatement != null && !colorStatement.isAsserted(element)) {\r
+                e.setHint(ElementHints.KEY_TEXT_COLOR, G2DUtils.getColor(graph, colorStatement.getObject()));\r
+            } else {\r
+                String color = graph.syncRequest(new SysdynDiagramPropertyExternalRead(new Pair<Resource, String>(element, SysdynDiagramPreferences.getColorPreferenceName(graph, element))));\r
+                if(color != null) {\r
+                    RGB rgb = StringConverter.asRGB(color, null);\r
+                    if(rgb != null) {\r
+                        Color c = new Color(rgb.red, rgb.green, rgb.blue);\r
+                        e.setHint(ElementHints.KEY_TEXT_COLOR, c);\r
+                        e.setHint(ElementHints.KEY_BORDER_COLOR, c);\r
+                    }\r
+                }\r
+\r
+            }\r
+        }\r
+\r
+        Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
+        if (component != null && graph.hasStatement(component, SysdynResource.getInstance(graph).IsOutput)) {\r
+            Font font = ElementUtils.getTextFont(e);\r
+            font = font.deriveFont(Font.BOLD);\r
+            ElementUtils.setTextFont(e, font);\r
+        }\r
+        \r
+        double bounds[] = DiagramGraphUtil.getPossibleRelatedDoubleArray(graph, element, G2DResource.getInstance(graph).HasBounds);\r
+        if (bounds != null) {\r
+            e.setHint(ElementHints.KEY_BOUNDS, new Rectangle2D.Double(bounds[0], bounds[1], bounds[2], bounds[3]));\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public ElementClass create(ReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType)\r
+    throws DatabaseException {\r
+        return compileElementClass(elementType, createTerminals(graph, elementType));\r
+    }\r
+    \r
+    public static Collection<ObjectTerminal> createTerminals(ReadGraph graph, Resource elementType) {\r
+\r
+               try {\r
+               StructuralResource2 sr = StructuralResource2.getInstance(graph);\r
+               DiagramResource dr = DiagramResource.getInstance(graph);\r
+\r
+               Resource definedByList = graph.getPossibleObject(elementType, sr.IsDefinedBy);\r
+               Collection<Resource> definedBy = Collections.emptyList();\r
+               if (definedByList != null)\r
+                   definedBy = OrderedSetUtils.toList(graph, definedByList);\r
+               Collection<ObjectTerminal> terminals = new ArrayList<ObjectTerminal>(definedBy.size());\r
+               for (Resource r : definedBy) {\r
+                   if (graph.isInstanceOf(r, dr.Terminal)) {\r
+                       terminals.add(new ResourceTerminal(r));\r
+                   }\r
+               }\r
+               return terminals;\r
+               } catch (ManyObjectsForFunctionalRelationException e) {\r
+                       e.printStackTrace();\r
+               } catch (ServiceException e) {\r
+                       e.printStackTrace();\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               return null;\r
+    }\r
+\r
+    /**\r
+     * @param elementType the type of the loaded element\r
+     * @param terminals the terminals of the element type being loaded\r
+     * @return an {@link ElementClass} representing the loaded element type\r
+     */\r
+    protected abstract ElementClass compileElementClass(Resource elementType, Collection<ObjectTerminal> terminals);\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementHints.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementHints.java
new file mode 100644 (file)
index 0000000..fdd74d4
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.g2d.canvas.IToolMode;\r
+import org.simantics.g2d.canvas.impl.ToolMode;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;\r
+\r
+public class SysdynElementHints {\r
+\r
+    public static final Key KEY_INPUT_REFERENCE = new KeyOf(String.class, "INPUT_REFERENCE");\r
+    public static final Key KEY_ORIENTATION = new KeyOf(String.class, "ORIENTATION");   \r
+    public static final Key KEY_LOCATION = new KeyOf(String.class, "LOCATION");     \r
+    public static final Key KEY_LOOP_CLOCKWISE = new KeyOf(Boolean.class, "LOOP_CLOCKWISE");     \r
+    \r
+    public static final Key       SYSDYN_KEY_TOOL = new KeyOf(ToolMode.class, "SysdynKeyTool");\r
+    public static final IToolMode DEPENDENCY_TOOL = new ToolMode("DependencyTool");\r
+    public static final IToolMode FLOW_TOOL       = new ToolMode("FlowTool");\r
+    public static final IToolMode LOCK_TOOL       = new ToolMode("LockTool");\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementUtils.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynElementUtils.java
new file mode 100644 (file)
index 0000000..f912495
--- /dev/null
@@ -0,0 +1,83 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.g2d.element.IElement;\r
+\r
+public class SysdynElementUtils {\r
+\r
+\r
+    public static void setInputReference(IElement e, String inputReference)\r
+    {\r
+        Input i = e.getElementClass().getSingleItem(Input.class);\r
+        if(i != null)\r
+            i.setInputReference(e, inputReference);\r
+    }\r
+\r
+    public static String getInputReference(IElement e)\r
+    {\r
+        Input i = e.getElementClass().getSingleItem(Input.class);\r
+        if(i != null)\r
+            return i.getInputReference(e);\r
+        else\r
+            return null;\r
+    }\r
+\r
+    public static void setOrientation(IElement e, String orientation)\r
+    {\r
+        Orientation o = e.getElementClass().getSingleItem(Orientation.class);\r
+        if(o != null)\r
+            o.setOrientation(e, orientation);\r
+    }\r
+\r
+    public static String getOrientation(IElement e)\r
+    {\r
+        Orientation o = e.getElementClass().getSingleItem(Orientation.class);\r
+        if(o != null)\r
+            return o.getOrientation(e);\r
+        else\r
+            return null;\r
+    }\r
+    \r
+    public static void setValveTextLocation(IElement e, String location)\r
+    {\r
+        ValveTextLocation v = e.getElementClass().getSingleItem(ValveTextLocation.class);\r
+        if(v != null)\r
+            v.setTextLocation(e, location);\r
+    }\r
+\r
+    public static String getValveTextLocation(IElement e)\r
+    {\r
+        ValveTextLocation v = e.getElementClass().getSingleItem(ValveTextLocation.class);\r
+        if(v != null)\r
+            return v.getTextLocation(e);\r
+        else\r
+            return null;\r
+    }\r
+\r
+       public static void setLoopClockwise(IElement e, Boolean clockwise) {\r
+        LoopClockwise l = e.getElementClass().getSingleItem(LoopClockwise.class);\r
+        if(l != null)\r
+            l.setTextLocation(e, clockwise);\r
+       }\r
+\r
+    public static String getLoopClockwise(IElement e)\r
+    {\r
+       LoopClockwise l = e.getElementClass().getSingleItem(LoopClockwise.class);\r
+        if(l != null)\r
+            return l.getTextLocation(e);\r
+        else\r
+            return null;\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementHandler.java
new file mode 100644 (file)
index 0000000..408ff09
--- /dev/null
@@ -0,0 +1,55 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT - initial API and implementation\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.diagram.elements.TextElementHandler;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.utils.Alignment;\r
+\r
+/**\r
+ * Version of {@link SysdynTextElementNoBounds} that supports InternalSize\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynTextElementHandler extends SysdynTextElementNoBounds implements InternalSize {\r
+    private static final long serialVersionUID = -1307413505370441178L;\r
+\r
+    public static SysdynTextElementHandler INSTANCE = new SysdynTextElementHandler();\r
+    \r
+    public SysdynTextElementHandler() {\r
+        super();\r
+    }\r
+\r
+    public SysdynTextElementHandler(double originX, double originY, Alignment horizontalAlignment) {\r
+        super(originX, originY, horizontalAlignment);\r
+    }\r
+\r
+    public SysdynTextElementHandler(double originX, double originY, Alignment horizontalAlignment, double borderWidth) {\r
+        super(originX, originY, horizontalAlignment, borderWidth);\r
+    }\r
+\r
+    public SysdynTextElementHandler(double originX, double originY, Alignment horizontalAlignment, double borderWidth,\r
+            double paddingX, double paddingY, boolean editable) {\r
+        super(originX, originY, horizontalAlignment, borderWidth, paddingX, paddingY, editable);\r
+    }\r
+    \r
+    @Override\r
+    public Rectangle2D getBounds(IElement e, Rectangle2D size) {\r
+        Rectangle2D bounds = TextElementHandler.calculateBounds(e, size, horizontalAlignment, SCALE, paddingX, paddingX);\r
+        return bounds;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementNoBounds.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementNoBounds.java
new file mode 100644 (file)
index 0000000..3d6eda9
--- /dev/null
@@ -0,0 +1,308 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT - initial API and implementation\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.Color;\r
+import java.awt.geom.AffineTransform;\r
+\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.ui.IWorkbenchPage;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.elements.DiagramNodeUtil;\r
+import org.simantics.diagram.elements.ITextListener;\r
+import org.simantics.diagram.elements.TextElementNoBounds;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.diagram.participant.SGFocusParticipant;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.chassis.SWTChassis;\r
+import org.simantics.g2d.diagram.DiagramUtils;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.utils.Alignment;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramViewer;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Callback;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;\r
+\r
+/**\r
+ * TextElement for variables in Siamntics System Dynamics\r
+ * \r
+ * The main differences for the basic TextElementNoBounds are:\r
+ * 1. Text is never mirrored\r
+ * 2. Edit mode is activated when the variable is created\r
+ *  \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynTextElementNoBounds extends TextElementNoBounds {\r
+\r
+    private static final long serialVersionUID = -148784588840819612L;\r
+    \r
+    public static final Key ELEMENT_INITIALIZED = new KeyOf(Boolean.class, "SYSDYN_TEXT_ELEMENT_INITIALIZED");\r
+\r
+    // Constructors \r
+    public SysdynTextElementNoBounds() {\r
+        super(0, 0, Alignment.LEADING, 0);\r
+    }\r
+\r
+    public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment) {\r
+        super(originX, originY, horizontalAlignment, 0);\r
+    }\r
+\r
+    public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment, double borderWidth) {\r
+        super(originX, originY, horizontalAlignment, borderWidth);\r
+    }\r
+\r
+    public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment, double borderWidth, double paddingX, double paddingY, boolean editable) {\r
+        super(originX, originY, horizontalAlignment, borderWidth, paddingX, paddingY, editable);\r
+    }\r
+\r
+    // End constructors\r
+\r
+    protected <T extends SysdynTextNode> Callback<T> getCallback(final IElement e, G2DParentNode parent, Class<T> nodeClass) {\r
+        return new Callback<T>() {\r
+            @Override\r
+            public void run(T node) {\r
+                node.setTextListener(new ITextListener() {\r
+\r
+                    String textBeforeEdit;\r
+                    Resource component;\r
+\r
+                    @Override\r
+                    public void textChanged() {\r
+                        TextNode node = (TextNode) e.getHint(SG_NODE);\r
+                        if(!new VariableNameValidator().isValid(component, node.getText(), false)) {\r
+                            node.setColor(Color.RED);\r
+                        } else {\r
+                            node.setColor(ElementUtils.getTextColor(e, Color.BLACK));\r
+                        }\r
+\r
+\r
+                    }\r
+\r
+                    @Override\r
+                    public void textEditingStarted() {\r
+                        TextNode node = (TextNode) e.getHint(SG_NODE);\r
+                        if (node == null)\r
+                               return;\r
+                        textBeforeEdit = node.getText();\r
+\r
+                        if(component != null) return;\r
+                        \r
+                        Object o = e.getHint(ElementHints.KEY_OBJECT);\r
+                        if(o != null && o instanceof Resource) {\r
+                            final Resource element = (Resource)o;\r
+                            SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+\r
+                                @Override\r
+                                public void run(ReadGraph graph) throws DatabaseException {\r
+                                    component = graph.getPossibleObject(element, ModelingResources.getInstance(graph).ElementToComponent);\r
+                                }\r
+                            });\r
+                        }\r
+                    }\r
+\r
+                    @Override\r
+                    public void textEditingCancelled() {\r
+                        TextNode node = (TextNode) e.getHint(SG_NODE);\r
+                        if (node != null) {\r
+                            if(new VariableNameValidator().isValid(component, node.getText(), false))\r
+                                node.setColor(ElementUtils.getTextColor(e, Color.BLACK));\r
+                            endEdit(node);\r
+                        }\r
+                    }\r
+\r
+                    @Override\r
+                    public void textEditingEnded() {\r
+                        TextNode node = (TextNode) e.getHint(SG_NODE);\r
+                        if (node == null)\r
+                            return;\r
+                        String text = node.getText();\r
+                        if(!new VariableNameValidator().isValid(component, text, false)) {\r
+                            text = textBeforeEdit;\r
+                            node.setText(text);\r
+                            if(new VariableNameValidator().isValid(component, text, false))\r
+                                node.setColor(ElementUtils.getTextColor(e, Color.BLACK));\r
+                        } else {\r
+                            Object o = e.getHint(ElementHints.KEY_OBJECT);\r
+                            final String textAfterEdit = text;\r
+                            if(o != null && o instanceof Resource) {\r
+                                SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                                    @Override\r
+                                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                                        Resource configuration = graph.getPossibleObject(component, Layer0.getInstance(graph).PartOf);\r
+                                        new VariableNameValidator().renameInAllEquations(graph, configuration, textBeforeEdit, textAfterEdit);\r
+                                    }\r
+                                });\r
+                            }\r
+                        }\r
+                        ElementUtils.setText(e, text);\r
+                        IDiagram diagram = ElementUtils.getDiagram(e);\r
+                        DiagramUtils.synchronizeHintsToBackend(diagram, e);\r
+                        endEdit(node);\r
+                    }\r
+                });\r
+            }\r
+        };\r
+    }\r
+    \r
+    /**\r
+     * Reverts any rotations that are assigned to the text element\r
+     * @param e\r
+     */\r
+    public static void unflipText(IElement e) {\r
+        Object o = e.getHint(SG_NODE);\r
+        if (o instanceof TextNode) {\r
+            TextNode text = (TextNode)o;\r
+            AffineTransform at = text.getTransform();\r
+            double x = at.getTranslateX();\r
+            double y = at.getTranslateY();\r
+            at.setToRotation(0);\r
+            at.setToTranslation(x, y);\r
+            at.setTransform(at);\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Activates edit mode for a newly created variable. \r
+     * \r
+     * Sets focus for diagram if the variable was created by dragging from model browser.\r
+     * \r
+     * @param e\r
+     */\r
+    protected void activateEdit(final IElement e) {\r
+        final SysdynTextNode node = e.getHint(SG_NODE);\r
+        if(node == null)\r
+            return;\r
+        \r
+        final ICanvasContext ctx = DiagramNodeUtil.getCanvasContext(node);\r
+        // FIXME: needed only because eventdelegator registrations are done before adding node to scene graph.\r
+        if (ctx == null)\r
+            return;\r
+        if (!node.isEditMode()) {\r
+            \r
+            // Get the active editor\r
+            IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();\r
+            final DiagramEditor editor = (DiagramEditor)page.getActiveEditor();\r
+            final ICanvasContext editorCtx = (ICanvasContext) editor.getViewer().getAdapter(ICanvasContext.class);\r
+\r
+            editor.getViewer().getComposite().getDisplay().asyncExec(new Runnable() {\r
+                    \r
+                @Override\r
+                public void run() {\r
+                    Control c = editor.getViewer().getComposite().getDisplay().getFocusControl();\r
+                    if (c == null || "BasicSymbols".equals(c.getParent().getToolTipText())) {\r
+                        // If the variable has been drag and dropped, set focus to diagram and then activate edit.\r
+                        \r
+                        editorCtx.add(new SGFocusParticipant((SWTChassis)editor.getViewer().getComposite(), DiagramViewer.DIAGRAMMING_CONTEXT) {\r
+                \r
+                            @Override\r
+                            public void focusGained(java.awt.event.FocusEvent event) {\r
+                                \r
+                                // When focus has been gained, acticate edit and destroy the listener.\r
+                                editor.getViewer().getComposite().getDisplay().asyncExec(new Runnable() {\r
+                                    \r
+                                    @Override\r
+                                    public void run() {\r
+                                        if (Boolean.TRUE.equals(node.setEditMode(true))) {\r
+                                            node.activateEdit(0, e, ctx, true);\r
+                                            node.repaint();\r
+                                        }\r
+                                    }\r
+                                });\r
+                                ctx.remove(this);\r
+                            }\r
+                            \r
+                            @Override\r
+                            public void focusLost(java.awt.event.FocusEvent e) {\r
+                            }\r
+                        });\r
+                    \r
+                        editor.setFocus();\r
+                    } else {\r
+                        // If the variable has been created with shortcut key, just activate the edit.\r
+                        if (Boolean.TRUE.equals(node.setEditMode(true))) {\r
+                            node.activateEdit(0, e, ctx, true);\r
+                            node.repaint();\r
+                        }\r
+                    }\r
+                }\r
+            }); \r
+        }\r
+    }\r
+    \r
+    @Override\r
+    protected TextNode getOrCreateTextNode(IElement e, G2DParentNode parent) {\r
+        return ElementUtils.getOrCreateNode(e, parent, SG_NODE, "text", SysdynTextNode.class, getCallback(e, parent, SysdynTextNode.class));\r
+    }\r
+    \r
+    @Override\r
+    public void init(final IElement e, G2DParentNode parent) {\r
+        super.init(e, parent);\r
+\r
+        \r
+        // Add handling for activating text edit for new variables\r
+     // Store initialization status to hints to prevent unnecessary graph queries\r
+        Boolean isInitialized = e.getHint(ELEMENT_INITIALIZED);  \r
+        Object o = e.getHint(ElementHints.KEY_OBJECT);\r
+        if (o instanceof Resource && !Boolean.TRUE.equals(isInitialized)) {\r
+            final Resource element = (Resource)o;\r
+            try {\r
+                SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+    \r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        SysdynResource SR = SysdynResource.getInstance(graph);\r
+                        ModelingResources MR = ModelingResources.getInstance(graph);\r
+                        Resource component = graph.getPossibleObject(element, MR.ElementToComponent);\r
+                        if (component == null)\r
+                            return;\r
+                        \r
+                        // See if the resource of the element has just been created. \r
+                        Resource r = graph.getPossibleObject(component, SR.IndependentVariable_isUninitialized);\r
+                        if (r == null){\r
+                            return;\r
+                        }\r
+                        \r
+                        // If the resource is just been created, activate editing its name.\r
+                        if (!graph.isInstanceOf(r, SR.Loop)) {\r
+                            activateEdit(e);\r
+                        }\r
+                        graph.deny(component, SR.IndependentVariable_isUninitialized, r);\r
+                    }\r
+                });\r
+            } catch (DatabaseException e1) {\r
+                e1.printStackTrace();\r
+            }\r
+            e.setHint(ELEMENT_INITIALIZED, Boolean.TRUE);\r
+        }\r
+        \r
+        unflipText(e);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextNode.java
new file mode 100644 (file)
index 0000000..1d593a3
--- /dev/null
@@ -0,0 +1,102 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT - initial API and implementation\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.diagram.elements.TextEditActivation;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.scenegraph.g2d.events.EventTypes;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseDragBegin;\r
+import org.simantics.sysdyn.ui.elements.LoopNode.ILoopComponentNode;\r
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
+\r
+/**\r
+ * Text node for Sysdyn elements.\r
+ * \r
+ *  Additions to the basic node:\r
+ *  1. Draw borders when hovering\r
+ *  2. Support Sysdyn's diagram locking\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SysdynTextNode extends TextNode implements ILoopComponentNode {\r
+\r
+    private static final long serialVersionUID = 5235077104121753251L;\r
+       private HashMap<LoopNode, Boolean> loopSelectionMap = new HashMap<LoopNode, Boolean>();\r
+\r
+       private boolean isLoopSelected() {\r
+               return loopSelectionMap.containsValue(true);\r
+       }\r
+\r
+    @Override\r
+    public int getEventMask(){\r
+        return EventTypes.FocusLostMask | super.getEventMask();\r
+    }\r
+    \r
+    @Override\r
+    protected boolean mouseDragged(MouseDragBegin e) {\r
+        // Disable dragging if LockSketch is ON\r
+        if (SysdynElementHints.LOCK_TOOL.equals(SysdynWorkbenchUtils.getSysdynToolMode())){\r
+            super.mouseDragged(e);\r
+            return true;}\r
+        else\r
+            return super.mouseDragged(e);\r
+    }\r
+    \r
+    \r
+    @Override\r
+    protected void renderSelectedHover(Graphics2D g, boolean isSelected, boolean isHovering) {\r
+        \r
+        if (!isSelected && isHovering) {\r
+            BasicStroke oldStroke = (BasicStroke)g.getStroke();\r
+            Color oldColor = g.getColor();\r
+            g.setColor(Color.LIGHT_GRAY);\r
+            g.setStroke(new BasicStroke((float)(2.0*scale)));\r
+            g.draw(getBoundsInLocal());\r
+            g.setColor(oldColor);\r
+            g.setStroke(oldStroke);\r
+            \r
+        } else if (isLoopSelected()) {\r
+            BasicStroke oldStroke = (BasicStroke)g.getStroke();\r
+            Color oldColor = g.getColor();\r
+            g.setColor(LoopNode.HIGHLIGHT_COLOR);\r
+            g.setStroke(new BasicStroke((float)(2.0*scale)));\r
+            g.draw(getBoundsInLocal());\r
+            g.setColor(oldColor);\r
+            g.setStroke(oldStroke);\r
+            \r
+        }\r
+    }\r
+    \r
+    public TextEditActivation activateEdit(int mouseId, IElement e, ICanvasContext ctx, boolean save) {\r
+        if (save)\r
+            return editActivation = super.activateEdit(mouseId, e, ctx);\r
+        return super.activateEdit(mouseId, e, ctx);\r
+    }\r
+    \r
+       @Override\r
+       public void setLoopSelected(LoopNode loop, boolean selected) {\r
+               Boolean loopSelected = loopSelectionMap.get(loop);\r
+               if (loopSelected == null || loopSelected != selected) {\r
+                       loopSelectionMap.put(loop, selected);\r
+                       repaint();\r
+               }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveFactory.java
new file mode 100644 (file)
index 0000000..200ce9e
--- /dev/null
@@ -0,0 +1,338 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.NoninvertibleTransformException;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.elements.ResizeNode.TranslateEdge;\r
+import org.simantics.diagram.elements.ResizeRectangularSceneGraph;\r
+import org.simantics.diagram.elements.TextElementNoBounds;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.SceneGraphNodeKey;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.SceneGraph;\r
+import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
+import org.simantics.g2d.element.handler.impl.HoverImpl;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.OutlinePick;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.image.Image;\r
+import org.simantics.g2d.image.impl.ShapeImage;\r
+import org.simantics.g2d.utils.Alignment;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;\r
+import org.simantics.utils.datastructures.hints.IHintListener;\r
+import org.simantics.utils.datastructures.hints.IHintObservable;\r
+\r
+\r
+public class ValveFactory extends SysdynElementFactory {\r
+\r
+    public static final Key             KEY_ROTATED        = new KeyOf(Boolean.class, "ROTATED");\r
+\r
+    public static final double          VALVE_SIZE         = 1.5;\r
+\r
+    private static final BasicStroke    STROKE             = new BasicStroke(1f);\r
+    public static final Image          VALVE_STATIC_IMAGE = new ShapeImage(createShape(VALVE_SIZE, false), null, STROKE, true);\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.simantics.sysdyn.ui.elements.SysdynElementFactory#compileElementClass(org.simantics.db.Resource, java.util.Collection)\r
+     */\r
+    @Override\r
+    protected ElementClass compileElementClass(Resource elementType, Collection<ObjectTerminal> terminals) {\r
+        return ElementClass.compile(\r
+                SimpleElementLayers.INSTANCE,\r
+                OutlinePick.INSTANCE,\r
+                TextImpl.INSTANCE,\r
+                TextColorImpl.BLACK,\r
+                TextFontImpl.DEFAULT,\r
+                DefaultTransform.INSTANCE,\r
+                new StaticObjectAdapter(elementType),\r
+                new StaticSymbolImpl(VALVE_STATIC_IMAGE),\r
+                StaticSymbolImageInitializer.INSTANCE,\r
+                HoverImpl.INSTANCE,\r
+                Orientation.INSTANCE,\r
+                ValveTextLocation.INSTANCE,\r
+                ValveSceneGraph.INSTANCE,\r
+                ValveText.INSTANCE,\r
+                new ResizeRectangularSceneGraph(TextElementNoBounds.SG_NODE),\r
+                RESIZE_PROPERTY_SETTER,          \r
+                ValveBounds.INSTANCE,\r
+                ValveOutline.INSTANCE,\r
+                new WholeElementTerminals(terminals)\r
+        ).setId(ValveFactory.class.getSimpleName());\r
+    }\r
+    \r
+    @Override\r
+    public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {\r
+        super.load(graph, canvas, diagram, element, e);\r
+        \r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+        Resource orientation = graph.getPossibleObject(element, sr.ValveSymbol_orientation);\r
+        \r
+        String orientationText;\r
+        if(orientation != null && sr.Vertical.equals(orientation)) {\r
+            orientationText = "Vertical";\r
+        } else {\r
+            orientationText = "Horizontal";\r
+        } \r
+        SysdynElementUtils.setOrientation(e, orientationText);\r
+\r
+        Resource location = graph.getPossibleObject(element, sr.ValveSymbol_textLocation);\r
+        String locationText;\r
+        if(location == null || sr.Bottom.equals(location)) {\r
+            locationText = "Bottom";\r
+        } else if(sr.Top.equals(location)) {\r
+            locationText = "Top";\r
+        } else if(sr.Left.equals(location)) {\r
+            locationText = "Left";\r
+        } else {\r
+            locationText = "Right";\r
+        }\r
+        SysdynElementUtils.setValveTextLocation(e, locationText);    \r
+        \r
+        \r
+        ResizeRectangularSceneGraph resize = e.getElementClass().getSingleItem(ResizeRectangularSceneGraph.class);\r
+        if(resize != null) {\r
+            \r
+            if(location == null || sr.Bottom.equals(location)) {\r
+                resize.setYTranslateEdge(TranslateEdge.NORTH);\r
+                resize.setXTranslateEdge(TranslateEdge.NONE);\r
+            } else if(sr.Top.equals(location)) {\r
+                resize.setYTranslateEdge(TranslateEdge.SOUTH);\r
+                resize.setXTranslateEdge(TranslateEdge.NONE);\r
+            } else if(sr.Left.equals(location)) {\r
+                resize.setYTranslateEdge(TranslateEdge.NONE);\r
+                resize.setXTranslateEdge(TranslateEdge.EAST);\r
+            } else {\r
+                resize.setYTranslateEdge(TranslateEdge.NONE);\r
+                resize.setXTranslateEdge(TranslateEdge.WEST);\r
+            }\r
+        }\r
+        \r
+    }\r
+    \r
+    /**\r
+     * @param valveSize\r
+     * @param rotated <code>true</code> for vertical valve, <code>false</code>\r
+     *        for horizontal\r
+     * @return\r
+     */\r
+    private static Path2D createShape(double valveSize, boolean rotated) {\r
+        Path2D path = new Path2D.Double();\r
+        path.moveTo(-valveSize, -valveSize);\r
+        if(rotated) {\r
+            path.lineTo(-valveSize, +valveSize);\r
+            path.lineTo(+valveSize, -valveSize);\r
+        } else {\r
+            path.lineTo(+valveSize, -valveSize);\r
+            path.lineTo(-valveSize, +valveSize);\r
+        }\r
+        path.lineTo(+valveSize, +valveSize);\r
+        path.closePath();\r
+        return path;\r
+    }\r
+    \r
+    public static class ValveText extends SysdynTextElementNoBounds {\r
+        private static final long serialVersionUID = -5354779831383095960L;\r
+     \r
+        public static ValveText INSTANCE = new ValveText();\r
+        \r
+        public ValveText() {\r
+            super(0, 0, Alignment.CENTER, 0, 1, 1, true);\r
+        }\r
+        \r
+        @Override\r
+        public void init(IElement e, G2DParentNode parent) {\r
+            super.init(e, parent);\r
+            \r
+            TextNode text = e.getHint(TextElementNoBounds.SG_NODE);\r
+            HoverShapeNode valve = e.getHint(ValveSceneGraph.VALVE_SG_NODE);\r
+            if(valve != null && text != null) {\r
+                Rectangle2D textBounds = text.getBoundsInLocal();\r
+                Rectangle2D valveBounds = valve.getBoundsInLocal();\r
+                AffineTransform at = (AffineTransform) text.getTransform().clone();\r
+                at.translate(\r
+                        getTextXTranslate(e, textBounds, valveBounds), \r
+                        getTextYTranslate(e, textBounds, valveBounds));\r
+                text.setTransform(at);\r
+            }\r
+            \r
+        }\r
+        \r
+        private static double getTextXTranslate(IElement e, Rectangle2D textBounds, Rectangle2D valveBounds) {\r
+            String location = e.getHint(SysdynElementHints.KEY_LOCATION);\r
+            if(location.equals("Bottom")) {\r
+                return -textBounds.getCenterX();\r
+            } else if(location.equals("Top")) {\r
+                return -textBounds.getCenterX();\r
+            } else if(location.equals("Left")) {\r
+                return -textBounds.getMaxX() - valveBounds.getWidth() / 2;\r
+            } else {\r
+                return valveBounds.getMaxX() - textBounds.getMinX();\r
+            }\r
+        }\r
+        \r
+        private static double getTextYTranslate(IElement e, Rectangle2D textBounds, Rectangle2D valveBounds) {\r
+            String location = e.getHint(SysdynElementHints.KEY_LOCATION);\r
+            if(location.equals("Bottom")) {\r
+                return valveBounds.getMaxY() - textBounds.getMinY();\r
+            } else if(location.equals("Top")) {\r
+                return valveBounds.getMinY() - textBounds.getMaxY();\r
+            } else if(location.equals("Left")) {\r
+                return -textBounds.getCenterY();\r
+            } else {\r
+                return -textBounds.getCenterY();\r
+            }\r
+        }\r
+    }\r
+    \r
+    public static class ValveBounds implements InternalSize {\r
+        private static final long serialVersionUID = -666692270776359301L;\r
+\r
+        public static final ValveBounds INSTANCE         = new ValveBounds();\r
+\r
+        @Override\r
+        public Rectangle2D getBounds(IElement e, Rectangle2D size) {\r
+            TextNode textNode = e.getHint(TextElementNoBounds.SG_NODE);\r
+            ValveSceneGraph valveSG = e.getElementClass().getSingleItem(ValveSceneGraph.class);\r
+\r
+            if(textNode != null && valveSG != null) {\r
+                try {\r
+                    AffineTransform elementTransform = ElementUtils.getTransform(e);\r
+                    AffineTransform nodeTransform = textNode.getTransform();\r
+\r
+                    AffineTransform elementTransformInverse = elementTransform.createInverse();\r
+                    elementTransformInverse.concatenate(nodeTransform);\r
+\r
+                    Rectangle2D text = textNode.getBoundsInLocal();\r
+                    Shape textShape = elementTransformInverse.createTransformedShape(text);\r
+\r
+                    Rectangle2D valve = valveSG.getValveBounds(e, new Rectangle2D.Double());\r
+\r
+                    size.setRect(textShape.getBounds2D());\r
+                    size.add(valve);\r
+                    return size;\r
+                } catch (NoninvertibleTransformException e1) {\r
+                    e1.printStackTrace();\r
+                }\r
+            }\r
+            // FallBack\r
+            Path2D path = createShape(VALVE_SIZE, Boolean.TRUE.equals(e.getHint(KEY_ROTATED)));\r
+            return path.getBounds2D();\r
+        }\r
+\r
+    }\r
+    \r
+    public static class ValveSceneGraph implements SceneGraph {\r
+        private static final long serialVersionUID = 7987939328158347639L;\r
+\r
+        public static final ValveSceneGraph INSTANCE         = new ValveSceneGraph();\r
+\r
+        private static final Key            VALVE_SG_NODE             = new SceneGraphNodeKey(ShapeNode.class, "VALVE_SHAPE_NODE");\r
+        \r
+        private IHintListener hoverHintListener;\r
+\r
+        @Override\r
+        public void init(IElement e, G2DParentNode parent) {\r
+            final HoverShapeNode node = ElementUtils.getOrCreateNode(e, parent, VALVE_SG_NODE, "valveShape", HoverShapeNode.class);\r
+\r
+            // Calculate borders from text node bounds.\r
+            node.setStroke(STROKE);\r
+            node.setScaleStroke(true);\r
+            Color color = e.getHint(ElementHints.KEY_TEXT_COLOR);\r
+            node.setColor(color != null ? color : Color.BLACK);\r
+            boolean rotated = false;\r
+            String orientation = SysdynElementUtils.getOrientation(e);\r
+            if(orientation != null && orientation.equals("Vertical"))\r
+                rotated = true;\r
+            node.setShape(createShape(VALVE_SIZE, Boolean.TRUE.equals(rotated)));\r
+            Boolean hover = e.getHint(ElementHints.KEY_HOVER); \r
+            node.setHover(hover != null ? hover : false);\r
+            \r
+            AffineTransform at = ElementUtils.getTransform(e);\r
+            if(at != null)\r
+                node.setTransform(at);\r
+            \r
+\r
+            hoverHintListener = new IHintListener() {\r
+                \r
+                @Override\r
+                public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {\r
+                    \r
+                }\r
+                \r
+                @Override\r
+                public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
+                    IElement e = (IElement)sender;\r
+                    HoverShapeNode shape = (HoverShapeNode) e.getHint(VALVE_SG_NODE);\r
+                    if(shape == null) {\r
+                        return;\r
+                    }\r
+                    boolean hover = ElementUtils.isHovering(e);\r
+                    shape.setHover(hover);\r
+                }\r
+            };\r
+            e.addHintListener(hoverHintListener);            \r
+        }\r
+\r
+        @Override\r
+        public void cleanup(IElement e) {\r
+            e.removeHintListener(hoverHintListener);\r
+            ElementUtils.removePossibleNode(e, VALVE_SG_NODE);            \r
+        }\r
+        \r
+        \r
+        public Rectangle2D getValveBounds(IElement e, Rectangle2D size) {\r
+            if (size == null)\r
+                size = new Rectangle2D.Double();\r
+            \r
+            HoverShapeNode node = e.getHint(VALVE_SG_NODE);\r
+            if(node != null) {\r
+                size.setFrame(node.getBoundsInLocal());\r
+            } else {\r
+                size.setFrame(createShape(VALVE_SIZE, Boolean.TRUE.equals(e.getHint(KEY_ROTATED))).getBounds2D());\r
+            }\r
+            \r
+            // Add some padding to the valve\r
+            double padding = 1;\r
+            size.setFrame(size.getX() - padding, size.getY() - padding, size.getWidth() + padding * 2, size.getHeight() + padding * 2);\r
+            return size;\r
+        }\r
+        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveOutline.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveOutline.java
new file mode 100644 (file)
index 0000000..afac8e4
--- /dev/null
@@ -0,0 +1,57 @@
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.NoninvertibleTransformException;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.simantics.diagram.elements.TextElementNoBounds;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
+import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;\r
+\r
+public class ValveOutline extends BoundsOutline {\r
+\r
+    public static final BoundsOutline INSTANCE         = new ValveOutline();\r
+\r
+    private static final long         serialVersionUID = 5544256245734478634L;\r
+\r
+    public ValveOutline() {\r
+        super();\r
+    }\r
+\r
+    @Override\r
+    public Shape getElementShape(IElement e) {\r
+        TextNode textNode = e.getHint(TextElementNoBounds.SG_NODE);\r
+        ValveSceneGraph valveSG = e.getElementClass().getSingleItem(ValveSceneGraph.class);\r
+\r
+        if(textNode != null && valveSG != null) {\r
+            try {\r
+                AffineTransform elementTransform = ElementUtils.getTransform(e);\r
+                AffineTransform nodeTransform = textNode.getTransform();\r
+\r
+                AffineTransform elementTransformInverse = elementTransform.createInverse();\r
+                elementTransformInverse.concatenate(nodeTransform);\r
+\r
+                Rectangle2D text = textNode.getBoundsInLocal();\r
+                Shape textShape = elementTransformInverse.createTransformedShape(text);\r
+\r
+                Rectangle2D valve = valveSG.getValveBounds(e, new Rectangle2D.Double());\r
+\r
+                Path2D path = new Path2D.Double(textShape);\r
+                path.append(valve, false);\r
+\r
+                return path;\r
+            } catch (NoninvertibleTransformException e1) {\r
+                e1.printStackTrace();\r
+            }\r
+        }\r
+\r
+        InternalSize b = e.getElementClass().getSingleItem(InternalSize.class);\r
+        return b.getBounds(e, new Rectangle2D.Double());\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveTextLocation.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ValveTextLocation.java
new file mode 100644 (file)
index 0000000..8957e43
--- /dev/null
@@ -0,0 +1,35 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.ElementHandler;\r
+\r
+public class ValveTextLocation implements ElementHandler {\r
+\r
+    private static final long serialVersionUID = 7123851901569461658L;\r
+    \r
+    public static final ValveTextLocation INSTANCE = new ValveTextLocation();\r
+    \r
+    public String getTextLocation(IElement e) {\r
+        return e.getHint(SysdynElementHints.KEY_LOCATION);\r
+    }\r
+\r
+    \r
+    public void setTextLocation(IElement e, String location) {\r
+        if (location != null)\r
+            e.setHint(SysdynElementHints.KEY_LOCATION, location);\r
+        else\r
+            e.removeHint(SysdynElementHints.KEY_LOCATION);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/WholeElementTerminals.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/WholeElementTerminals.java
new file mode 100644 (file)
index 0000000..ff409fe
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements;\r
+\r
+import java.awt.Shape;\r
+import java.util.Collection;\r
+\r
+import org.simantics.g2d.diagram.handler.Topology.Terminal;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
+import org.simantics.g2d.element.handler.impl.Terminals;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class WholeElementTerminals extends Terminals {\r
+\r
+    private static final long serialVersionUID = -8209833430671135001L;\r
+\r
+    public WholeElementTerminals(Collection<ObjectTerminal> ts) {\r
+        super(ts);\r
+    }\r
+\r
+    @Override\r
+    public Shape getTerminalShape(IElement node, Terminal t) {\r
+        // For each terminal, return the shape of the element.\r
+        return ElementUtils.getElementShapeOrBounds(node);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/Arcs.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/Arcs.java
new file mode 100644 (file)
index 0000000..c054d41
--- /dev/null
@@ -0,0 +1,232 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.Shape;\r
+\r
+public class Arcs {\r
+\r
+    public static final double PI2 = Math.PI*2.0;\r
+    \r
+    /**\r
+     * Returns angle + 2PI * n such that the\r
+     * result is between -PI and PI.\r
+     */\r
+    public static double normalizeAngle(double angle) {\r
+        return Math.IEEEremainder(angle, PI2);\r
+    }\r
+    \r
+    /**\r
+     * Returns true, if three normalized angles are clockwise oriented.\r
+     */\r
+    public static boolean areClockwiseOrdered(double angle1, double angle2, double angle3) {\r
+        //System.out.println(angle1 + " " + angle2 + " " + angle3);\r
+        return angle1 < angle2 \r
+            ? (angle2 < angle3 || angle3 < angle1)\r
+            : (angle2 < angle3 && angle3 < angle1)\r
+            ;\r
+    }\r
+    \r
+    /**\r
+     * Returns an angle in radians between straight line from (x0,y0) to (x2,y2)\r
+     * and an arc from (x0,y0) to (x2,y2) thru (x1,y1). The angle\r
+     * is measured at (x0,y0) and is between -PI and PI.\r
+     */\r
+    public static double angleOfArc(\r
+        double x0, double y0, \r
+        double x1, double y1,\r
+        double x2, double y2) {\r
+        double dx0 = x1-x0;\r
+        double dy0 = y1-y0;\r
+        double dx1 = x1-x2;\r
+        double dy1 = y1-y2;\r
+        double dx = x2-x0;\r
+        double dy = y2-y0;\r
+        // Length of cross product (p1-p0)x(p2-p0)\r
+        double dd = dx0*dy - dy0*dx; \r
+        \r
+        if(Math.abs(dd) < 1e-6) // Points are (almost) collinear\r
+            return 0.0;\r
+        else {            \r
+            // (p1-p0)*(p1-p2) / dd\r
+            double offset = (dx0*dx1 + dy0*dy1) / dd;\r
+            double angle = Math.PI*0.5 - Math.atan(offset);\r
+            if(dd > 0.0)\r
+                angle = angle-Math.PI;\r
+            return angle;\r
+            \r
+        }\r
+    }\r
+        \r
+    /**\r
+     * \r
+     * @param startX Start point x coord\r
+     * @param startY Start point y coord\r
+     * @param cx Center of the circle x coord\r
+     * @param cy Center of the circle y coord\r
+     * @param r Radius of the circle\r
+     * @param curAngle Start angle\r
+     * @param endBounds Shape\r
+     * @param dir direction to which is iterated\r
+     * @param move amount of which is iterated\r
+     * @param noOfIteration current number of itartion\r
+     * @param turn true iff we are increasing the angle\r
+     * @param crossed true if we have crossed the boundary we're targeting\r
+     * @return new angle\r
+     */\r
+    private static double iterateAngle(double startX, double startY, \r
+               double cx, double cy, double r,\r
+            double curAngle, Shape endBounds, boolean dir, double move,\r
+            int noOfIteration, boolean turn, boolean crossed) {\r
+       // Do this many steps\r
+       if (noOfIteration > 16)\r
+               return normalizeAngle(curAngle);\r
+       \r
+       if (crossed) // When we have crossed the boundary, start split half method\r
+               move *= 0.5;\r
+       double x_rad, y_rad;\r
+       if (dir != turn) { // The direction of iteration is based on dir and turn bits\r
+               x_rad = startX + (move * Math.sin(curAngle));\r
+               y_rad = startY + (move * Math.cos(curAngle));\r
+       } else {\r
+               x_rad = startX - (move * Math.sin(curAngle));\r
+               y_rad = startY - (move * Math.cos(curAngle));\r
+       }\r
+       curAngle = -Math.atan((y_rad-cy)/(x_rad-cx));\r
+               if (x_rad-cx < 0)\r
+                       curAngle += Math.PI;\r
+       curAngle = normalizeAngle(curAngle);\r
+               \r
+               if (endBounds.contains(x_rad, y_rad)) {\r
+                       return iterateAngle(x_rad, y_rad,\r
+                                       cx,cy,r,curAngle,endBounds,dir, move, noOfIteration+1, false, crossed);\r
+       }\r
+       else {\r
+               // Crossed is hereafter true\r
+               return iterateAngle(x_rad, y_rad,\r
+                                       cx,cy,r,curAngle,endBounds,dir, move, noOfIteration+1, true, true);\r
+       }\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @param cx x coord of the center point of the circle \r
+     * @param cy y coord of the center point of the circle\r
+     * @param r radius of the circle\r
+     * @param curAngle angle of the arc\r
+     * @param endBounds bounding shape\r
+     * @param dir direction of the arc\r
+     * @return\r
+     */\r
+    public static double nextIntersectingAngle(double cx, double cy, double r,\r
+        double curAngle, Shape endBounds, boolean dir) {\r
+       // Move this much per iteration till the border is crossed.\r
+       double move = 3.0;\r
+        return iterateAngle(endBounds.getBounds2D().getCenterX(),\r
+                                               endBounds.getBounds2D().getCenterY(),\r
+                                               cx,cy,r,curAngle,endBounds,dir,move, 0, false, false);\r
+    }\r
+    \r
+       public static boolean hitTest(Shape beginBounds, Shape endBounds, double angle, double x, double y, double tolerance) {\r
+               \r
+               boolean clockWise = angle > 0;\r
+               \r
+               double x0 = beginBounds.getBounds2D().getCenterX();\r
+        double y0 = beginBounds.getBounds2D().getCenterY();\r
+        double x1 = endBounds.getBounds2D().getCenterX();\r
+        double y1 = endBounds.getBounds2D().getCenterY();\r
+        \r
+        double offset = \r
+            Math.abs(angle) < 1.0e-6\r
+            ? 1e3 * Math.signum(angle)\r
+            : Math.tan(Math.PI*0.5-angle)*0.5;\r
+        double cx = 0.5*(x0+x1) + offset * (y1-y0);\r
+        double cy = 0.5*(y0+y1) + offset * (x0-x1);\r
+        double dx0 = x0 - cx;\r
+        double dy0 = y0 - cy;\r
+        double dx1 = x1 - cx;\r
+        double dy1 = y1 - cy;\r
+        double r = Math.sqrt(dx0*dx0 + dy0*dy0);\r
+        double angle0 = Arcs.nextIntersectingAngle(cx, cy, r, \r
+            Math.atan2(-dy0, dx0), beginBounds, angle < 0.0);\r
+        double angle1 = Arcs.nextIntersectingAngle(cx, cy, r, \r
+            Math.atan2(-dy1, dx1), endBounds, angle > 0.0);\r
+        \r
+        double dx = x-cx;\r
+        double dy = y-cy;\r
+        double dist = dx*dx + dy*dy;\r
+        \r
+        //System.out.println("HitTest: x0=" + x0 + " y0=" + y0 + " y=" + y + " x=" + x + " dist=" + dist + " r2=" + r*r);\r
+        \r
+        double tolerance2 = tolerance * tolerance;\r
+        if(dist < (r+tolerance2)*(r+tolerance2) &&\r
+            dist > (r-tolerance2)*(r-tolerance2)) {\r
+            double ang = Arcs.normalizeAngle(Math.atan2(-dy, dx));\r
+               //System.out.println("test " + angle0 + " " + ang + " " + angle1);\r
+            if(Arcs.areClockwiseOrdered(angle0, ang, angle1) == clockWise) {\r
+               //System.out.println("hit");\r
+                return true;\r
+            }\r
+        }\r
+        \r
+        return false;\r
+        \r
+       }\r
+\r
+       /**\r
+        * Calculates the radial distance between an arc and a point\r
+        * @param beginBounds Begin coordinate of the arc\r
+        * @param endBounds End coordinate of the arc\r
+        * @param angle The central angle of the arc\r
+        * @param x x coordinate of the measured point\r
+        * @param y x coordinate of the measured point \r
+        * @return The radial distance between the the arc and (x,y); Double.NaN if the\r
+        *  distance is not real.\r
+        */\r
+       public static double getRadialDistance(Shape beginBounds,\r
+                       Shape endBounds, double angle, double x, double y) {\r
+\r
+               boolean clockWise = angle > 0;\r
+               \r
+               double x0 = beginBounds.getBounds2D().getCenterX();\r
+        double y0 = beginBounds.getBounds2D().getCenterY();\r
+        double x1 = endBounds.getBounds2D().getCenterX();\r
+        double y1 = endBounds.getBounds2D().getCenterY();\r
+        \r
+        double offset = \r
+            Math.abs(angle) < 1.0e-6\r
+            ? 1e3 * Math.signum(angle)\r
+            : Math.tan(Math.PI*0.5-angle)*0.5;\r
+        double cx = 0.5*(x0+x1) + offset * (y1-y0);\r
+        double cy = 0.5*(y0+y1) + offset * (x0-x1);\r
+        double dx0 = x0 - cx;\r
+        double dy0 = y0 - cy;\r
+        double dx1 = x1 - cx;\r
+        double dy1 = y1 - cy;\r
+        double r = Math.sqrt(dx0*dx0 + dy0*dy0);\r
+        double angle0 = Arcs.nextIntersectingAngle(cx, cy, r, \r
+            Math.atan2(-dy0, dx0), beginBounds, angle < 0.0);\r
+        double angle1 = Arcs.nextIntersectingAngle(cx, cy, r, \r
+            Math.atan2(-dy1, dx1), endBounds, angle > 0.0);\r
+        \r
+        double dx = x-cx;\r
+        double dy = y-cy;\r
+        double dist2 = dx*dx + dy*dy;\r
+               \r
+           double ang = Arcs.normalizeAngle(Math.atan2(-dy, dx));\r
+               if(!Arcs.areClockwiseOrdered(angle0, ang, angle1) == clockWise) {\r
+               return Double.NaN;\r
+           }\r
+           return  Math.abs(Math.sqrt(dist2) - r);\r
+       }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/ConnectionClasses.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/ConnectionClasses.java
new file mode 100644 (file)
index 0000000..310c59f
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+public class ConnectionClasses {\r
+\r
+    public static final Object CONNECTION = new Object() {\r
+        public String toString() { return "CONNECTION"; }\r
+    };\r
+\r
+    public static final Object FLAG = new Object() {\r
+        public String toString() { return "FLAG"; }\r
+    };\r
+\r
+    public static final Object FLOW = new Object() {\r
+        public String toString() { return "FLOW"; }\r
+    };\r
+\r
+    public static final Object DEPENDENCY = new Object() {\r
+        public String toString() { return "DEPENDENCY"; }\r
+    };\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyConnectionFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyConnectionFactory.java
new file mode 100644 (file)
index 0000000..6316eec
--- /dev/null
@@ -0,0 +1,319 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.io.StringReader;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Set;\r
+import java.util.concurrent.ConcurrentSkipListMap;\r
+import java.util.concurrent.atomic.AtomicInteger;\r
+\r
+import org.eclipse.jface.preference.PreferenceConverter;\r
+import org.eclipse.jface.resource.StringConverter;\r
+import org.eclipse.swt.graphics.FontData;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Statement;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.AsyncMultiProcedure;\r
+import org.simantics.db.procedure.AsyncProcedure;\r
+import org.simantics.db.procedure.SyncProcedure;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.diagram.adapter.ElementFactoryAdapter;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.ui.editor.routing.DependencyRouter;\r
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferences;\r
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPropertyExternalRead;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * An element class for single connection entity elements. A connection entity\r
+ * consists of connection edge segments and branch points as its children.\r
+ * \r
+ * @author Tuukka Lehtonen\r
+ * @author Tuomas Miettinen\r
+ */\r
+public class DependencyConnectionFactory extends ElementFactoryAdapter {\r
+\r
+    public static final ElementClass CLASS = SysdynConnectionClass.CLASS;\r
+\r
+    @Override\r
+    public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType, final AsyncProcedure<ElementClass> procedure) {\r
+        procedure.execute(graph, SysdynConnectionClass.CLASS.newClassWith(false, new StaticObjectAdapter(elementType)));\r
+    }\r
+\r
+    @Override\r
+    protected Resource getElementClassBaseType(AsyncReadGraph graph) {\r
+        return graph.getService(DiagramResource.class).Connection;\r
+    }\r
+\r
+    @Override\r
+    public void load(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, final Resource elementResource,\r
+            final IElement element, final AsyncProcedure<IElement> procedure) {\r
+\r
+        final AtomicInteger ready = new AtomicInteger(1);\r
+        final ConcurrentSkipListMap<String, Pair<Resource, Object>> properties = new ConcurrentSkipListMap<String, Pair<Resource, Object>>();\r
+\r
+        element.setHint(DiagramHints.ROUTE_ALGORITHM, DependencyRouter.INSTANCE);\r
+\r
+        G2DResource G2D;\r
+        try {\r
+            G2D = G2DResource.getInstance(graph.getSession());\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+            return;\r
+        }\r
+\r
+        // Find possible font\r
+        graph.forPossibleStatement(elementResource, G2D.HasFont, new SyncProcedure<Statement>() {\r
+\r
+            @Override\r
+            public void execute(ReadGraph graph, Statement result) throws DatabaseException {\r
+                if(result != null && !result.isAsserted(elementResource)) {\r
+                    element.setHint(ElementHints.KEY_FONT, G2DUtils.getFont(graph, result.getObject()));\r
+                } else {\r
+                    String fontdata = graph.syncRequest(new SysdynDiagramPropertyExternalRead(new Pair<Resource, String>(elementResource, SysdynDiagramPreferences.ARROW_FONT)));\r
+                    if(fontdata != null) {\r
+                        FontData[] fdArray = PreferenceConverter.basicGetFontData(fontdata);\r
+                        if(fdArray != null) {\r
+                            if(fdArray.length == 1) {\r
+                                FontData fd = fdArray[0];\r
+                                if(fd != null) {\r
+                                    Font font = new Font(fd.getName(), fd.getStyle(), fd.getHeight());\r
+                                    element.setHint(ElementHints.KEY_FONT, font);\r
+                                }\r
+                            }\r
+                        }\r
+                    }\r
+\r
+                }\r
+            }\r
+\r
+            @Override\r
+            public void exception(ReadGraph graph, Throwable throwable) throws DatabaseException {\r
+                throwable.printStackTrace();\r
+            }\r
+        });\r
+\r
+        // Find possible color\r
+        graph.forPossibleStatement(elementResource, G2D.HasColor, new SyncProcedure<Statement>() {\r
+\r
+            @Override\r
+            public void execute(ReadGraph graph, Statement result) throws DatabaseException {\r
+                if(result != null && !result.isAsserted(elementResource)) {\r
+                    element.setHint(ElementHints.KEY_TEXT_COLOR, G2DUtils.getColor(graph, result.getObject()));\r
+                } else {\r
+                       String color;\r
+                       if (isForStockInitialOnly(graph, elementResource)) {\r
+                               color = graph.syncRequest(new SysdynDiagramPropertyExternalRead(new Pair<Resource, String>(elementResource, SysdynDiagramPreferences.ARROW_STOCK_INITIAL_COLOR)));\r
+                       } else {\r
+                               color = graph.syncRequest(new SysdynDiagramPropertyExternalRead(new Pair<Resource, String>(elementResource, SysdynDiagramPreferences.ARROW_COLOR)));\r
+                       }\r
+                       if(color != null) {\r
+                        RGB rgb = StringConverter.asRGB(color, null);\r
+                        if(rgb != null) {\r
+                            Color c = new Color(rgb.red, rgb.green, rgb.blue);\r
+                            element.setHint(ElementHints.KEY_TEXT_COLOR, c);\r
+                        }\r
+                    }\r
+\r
+                }\r
+            }\r
+\r
+            @Override\r
+            public void exception(ReadGraph graph, Throwable throwable) throws DatabaseException {\r
+                throwable.printStackTrace();\r
+            }\r
+        });\r
+\r
+\r
+        // A complicated-looking procedure for obtaining all HasProperties to properties map\r
+        graph.forEachPredicate(elementResource, new AsyncMultiProcedure<Resource>() {\r
+\r
+            @Override\r
+            public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                throwable.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public void execute(AsyncReadGraph graph, final Resource property) {\r
+\r
+                ready.incrementAndGet();\r
+                Layer0 l0;\r
+                try {\r
+                    l0 = Layer0.getInstance(graph.getSession());\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                    return;\r
+                }\r
+\r
+                graph.forIsSubrelationOf(property, l0.HasProperty, new AsyncProcedure<Boolean>() {\r
+\r
+                    @Override\r
+                    public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                        throwable.printStackTrace();\r
+                    }\r
+\r
+                    @Override\r
+                    public void execute(AsyncReadGraph graph, final Boolean isProperty) {\r
+\r
+                        if(isProperty) {\r
+\r
+                            graph.forPossibleRelatedValue(elementResource, property, new AsyncProcedure<Object>() {\r
+\r
+                                @Override\r
+                                public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                                    throwable.printStackTrace();\r
+                                }\r
+\r
+                                @Override\r
+                                public void execute(AsyncReadGraph graph, final Object value) {\r
+\r
+                                    Layer0 l0;\r
+                                    try {\r
+                                        l0 = Layer0.getInstance(graph.getSession());\r
+                                    } catch (DatabaseException e) {\r
+                                        e.printStackTrace();\r
+                                        return;\r
+                                    }\r
+\r
+                                    graph.forPossibleRelatedValue(property, l0.HasName, Bindings.STRING, new AsyncProcedure<String>() {\r
+\r
+                                        @Override\r
+                                        public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                                            throwable.printStackTrace();\r
+                                        }\r
+\r
+                                        @Override\r
+                                        public void execute(AsyncReadGraph graph, String name) {\r
+\r
+                                            properties.put(name, Pair.make(property, value));\r
+                                            if(ready.decrementAndGet() == 0) {\r
+                                                element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Pair<Resource, Object>>(properties));\r
+                                                procedure.execute(graph, element);\r
+                                            }\r
+\r
+                                        }\r
+\r
+                                    });\r
+\r
+                                }\r
+\r
+                            });\r
+\r
+\r
+                        } else {\r
+\r
+                            if(ready.decrementAndGet() == 0) {\r
+                                element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Pair<Resource, Object>>(properties));\r
+                                procedure.execute(graph, element);\r
+                            }\r
+\r
+                        }\r
+\r
+                    }\r
+\r
+                });\r
+            }\r
+\r
+            @Override\r
+            public void finished(AsyncReadGraph graph) {\r
+\r
+                if(ready.decrementAndGet() == 0) {\r
+                    element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Object>(properties));\r
+                    procedure.execute(graph, element);\r
+                }\r
+\r
+            }\r
+\r
+        });\r
+\r
+    }\r
+\r
+       protected static boolean isForStockInitialOnly(ReadGraph graph,\r
+                       Resource elementResource) throws DatabaseException {\r
+               SysdynResource SR = SysdynResource.getInstance(graph);\r
+       ModelingResources MO = ModelingResources.getInstance(graph);\r
+       Layer0 L0 = Layer0.getInstance(graph);\r
+       Resource connection = graph.getPossibleObject(elementResource, MO.DiagramConnectionToConnection);\r
+       Resource tail = graph.getPossibleObject(connection, SR.Variable_HasTail);\r
+       if (tail == null)\r
+               return false;\r
+       \r
+       if (graph.isInstanceOf(tail, SR.Shadow))\r
+               tail = graph.getPossibleObject(tail, SR.Shadow_original);\r
+               \r
+       Resource head = graph.getPossibleObject(connection, SR.Variable_HasHead);\r
+       if (head == null || !graph.isInstanceOf(head, SR.Stock) || tail == null)\r
+               return false;\r
+       \r
+       Resource expressionListResource = graph.getPossibleObject(head, SR.Variable_expressionList);\r
+       List<Resource> expressionList = ListUtils.toPossibleList(graph, expressionListResource);\r
+       \r
+       // Keep track on whether at least one initial equation contains the variable\r
+       boolean initialContainsVariable = false;\r
+       // Go through all expressions\r
+       for (Resource expression : expressionList) {\r
+               if (!graph.isInstanceOf(expression, SR.StockExpression))\r
+                       return false;\r
+               \r
+               String tailStr = graph.getPossibleRelatedValue(tail, L0.HasName, Bindings.STRING);\r
+               String integral = graph.getPossibleRelatedValue(expression, SR.StockExpression_integralEquation, Bindings.STRING);\r
+               if (equationContainsVariable(graph, integral, tailStr))\r
+                       // At least one integral equation contains the variable\r
+                       return false;\r
+               String initial = graph.getPossibleRelatedValue(expression, SR.StockExpression_initialEquation, Bindings.STRING);\r
+               if (!initialContainsVariable && equationContainsVariable(graph, initial, tailStr))\r
+                       // At least one initial equation contains the variable\r
+                       initialContainsVariable = true;\r
+       }\r
+       \r
+       // No integral equation contains the variable.\r
+               return initialContainsVariable;\r
+       }\r
+\r
+       private static boolean equationContainsVariable(ReadGraph graph,\r
+                       String equation, String variable) {\r
+               ExpressionParser parser = new ExpressionParser(new StringReader(equation));\r
+               try {\r
+                       parser.expr();\r
+               } catch (Throwable t) {\r
+                       return false;\r
+               }\r
+               \r
+               // Collect references\r
+        Set<String> references = parser.getReferences().keySet();\r
+        \r
+        // See if the equation contains variable\r
+        return references.contains(variable);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyEdgeClass.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyEdgeClass.java
new file mode 100644 (file)
index 0000000..5b86bd9
--- /dev/null
@@ -0,0 +1,273 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.awt.Shape;\r
+import java.awt.Stroke;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Rectangle2D;\r
+import java.beans.PropertyChangeEvent;\r
+import java.beans.PropertyChangeListener;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.DiagramMutator;\r
+import org.simantics.g2d.diagram.DiagramUtils;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.diagram.handler.PickRequest.PickPolicy;\r
+import org.simantics.g2d.diagram.handler.Topology;\r
+import org.simantics.g2d.diagram.handler.Topology.Connection;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.SceneGraphNodeKey;\r
+import org.simantics.g2d.element.handler.EdgeVisuals;\r
+import org.simantics.g2d.element.handler.EdgeVisuals.ArrowType;\r
+import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;\r
+import org.simantics.g2d.element.handler.Pick;\r
+import org.simantics.g2d.element.handler.SceneGraph;\r
+import org.simantics.g2d.element.handler.TerminalLayout;\r
+import org.simantics.g2d.element.handler.Transform;\r
+import org.simantics.g2d.element.handler.impl.ConfigurableEdgeVisuals;\r
+import org.simantics.g2d.element.handler.impl.ConnectionSelectionOutline;\r
+import org.simantics.g2d.element.handler.impl.FillColorImpl;\r
+import org.simantics.g2d.element.handler.impl.ParentImpl;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.elementclass.connection.EdgeClass.EdgeHandler;\r
+import org.simantics.g2d.elementclass.connection.EdgeClass.FixedTransform;\r
+import org.simantics.g2d.utils.Alignment;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+import org.simantics.sysdyn.ui.editor.routing.DependencyRouter;\r
+import org.simantics.utils.datastructures.Callback;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+\r
+public class DependencyEdgeClass {\r
+       \r
+       public static final float DEFAULT_STROKE_WIDTH = 0.3f;\r
+\r
+       private static class NodePick implements Pick {\r
+\r
+           private static final long serialVersionUID = 1L;\r
+           \r
+           public static NodePick INSTANCE = new NodePick();\r
+\r
+           @Override\r
+           public boolean pickTest(IElement e, Shape s, PickPolicy policy) {\r
+               Rectangle2D pickRect = null;\r
+               if (s instanceof Rectangle2D)\r
+                   pickRect = (Rectangle2D) s;\r
+               else\r
+                   // FIXME: suboptimal, but works.\r
+                   pickRect = s.getBounds2D();\r
+\r
+            DependencyNode node = e.getHint(SysdynEdgeSceneGraph.KEY_SG_NODE);\r
+            if(node == null) {\r
+               return false;\r
+            }\r
+            return Arcs.hitTest(node.getBeginBounds(), node.getEndBounds(), node.getAngle(), pickRect.getCenterX(), pickRect.getCenterY(), 1.7);\r
+            \r
+           }\r
+\r
+       }\r
+       \r
+    public static final ElementClass CLASS =\r
+        ElementClass.compile(\r
+                SysdynEdgeSceneGraph.INSTANCE,\r
+                EdgeHandler.INSTANCE,\r
+                new ConfigurableEdgeVisuals(\r
+                        ArrowType.None, ArrowType.Fill, \r
+                        new BasicStroke(DEFAULT_STROKE_WIDTH,\r
+                                BasicStroke.CAP_BUTT,\r
+                                BasicStroke.JOIN_ROUND,\r
+                                10.0f, null, 0.0f)\r
+                        , 1.0, 1.0),\r
+                FillColorImpl.BLACK,\r
+                FixedTransform.INSTANCE,\r
+                TextImpl.INSTANCE,\r
+                TextColorImpl.BLACK,\r
+                TextFontImpl.DEFAULT,\r
+                NodePick.INSTANCE,\r
+                ConnectionSelectionOutline.INSTANCE,\r
+                SimpleElementLayers.INSTANCE,\r
+                ParentImpl.INSTANCE\r
+        ).setId("EdgeClass.STRAIGHT");\r
+\r
+    public static class SysdynEdgeSceneGraph implements SceneGraph {\r
+\r
+        private static final long serialVersionUID = 2914383071126238996L;\r
+\r
+        public static final SysdynEdgeSceneGraph INSTANCE = new SysdynEdgeSceneGraph();\r
+\r
+        public static final Stroke ARROW_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);\r
+\r
+        public static final Key KEY_SG_NODE = new SceneGraphNodeKey(DependencyNode.class, "EDGE_NODE");\r
+        \r
+        @Override\r
+        public void init(IElement e, G2DParentNode parent) {\r
+            DependencyNode node = ElementUtils.getOrCreateNode(e, parent, KEY_SG_NODE, "edge_" + e.hashCode(), DependencyNode.class);\r
+            \r
+            Font font = ElementUtils.getTextFont(e);\r
+            Color color = ElementUtils.getTextColor(e);\r
+            \r
+            HashMap<String, Object> properties = e.getHint(DiagramHints.PROPERTIES);\r
+            Pair<?, ?> polarityPair =  (Pair<?, ?>)properties.get("polarity");\r
+            Pair<?, ?> polarityLocationPair =  (Pair<?, ?>)properties.get("polarityLocation");\r
+            boolean delayMark = properties.containsKey("delayMark");\r
+            boolean arrowHead = !properties.containsKey("hideArrow");\r
+            \r
+            String location;\r
+            if(polarityLocationPair == null)\r
+                location = DependencyNode.INSIDE;\r
+            else\r
+                location = (String) polarityLocationPair.second;\r
+\r
+            String text = polarityPair != null ? (String)  polarityPair.second : "";\r
+            node.init(text, location, delayMark, arrowHead, font, color, 0, 0, 0.235);\r
+            \r
+            update(e);\r
+        }\r
+\r
+        @Override\r
+        public void cleanup(IElement e) {\r
+            ElementUtils.removePossibleNode(e, KEY_SG_NODE);\r
+        }\r
+        \r
+        public void update(final IElement e) {\r
+               \r
+            DependencyNode node = e.getHint(KEY_SG_NODE);\r
+            if(node == null) return;\r
+            final IDiagram diagram = ElementUtils.peekDiagram(e);\r
+            \r
+            node.setFieldListener(new PropertyChangeListener() {\r
+\r
+                @Override\r
+                public void propertyChange(final PropertyChangeEvent event) {\r
+                       \r
+                                       String field = event.getPropertyName();\r
+                           Map<String, Pair<Resource, Object>> properties = e.getHint(DiagramHints.PROPERTIES);\r
+                           if(properties == null) return;\r
+                           final Pair<Resource, Object> property = properties.get(field);\r
+                           if(property == null) return;\r
+\r
+                       DiagramUtils.mutateDiagram(diagram, new Callback<DiagramMutator>() {\r
+                                               \r
+                                               @Override\r
+                                               public void run(DiagramMutator mutator) {\r
+                                                       mutator.modifyProperty(e, property.first, event.getNewValue());\r
+                                               }\r
+                                               \r
+                                       });\r
+                       \r
+                }\r
+                \r
+                       });\r
+\r
+\r
+\r
+            Shape beginTerminalShape = null;\r
+            Shape endTerminalShape = null;\r
+            if (diagram != null) {\r
+                Topology topology = diagram.getDiagramClass().getAtMostOneItemOfClass(Topology.class);\r
+                if (topology != null) {\r
+                    Connection beginConnection = topology.getConnection(e, EdgeEnd.Begin);\r
+                    Connection endConnection = topology.getConnection(e, EdgeEnd.End);\r
+                    beginTerminalShape = getCanvasTerminalShape(beginConnection);\r
+                    endTerminalShape = getCanvasTerminalShape(endConnection);\r
+                }\r
+            }\r
+            \r
+            if(beginTerminalShape == null || endTerminalShape == null) return;\r
+            \r
+            EdgeVisuals vh = e.getElementClass().getSingleItem(EdgeVisuals.class);\r
+            Map<String, Pair<Resource, Object>> properties = e.getHint(DiagramHints.PROPERTIES);\r
+            Pair<Resource, Object> strokeWidthPair = properties.get("strokeWidth");\r
+            \r
+            float strokeWidth;\r
+            if(strokeWidthPair == null)\r
+               strokeWidth = DEFAULT_STROKE_WIDTH;\r
+            else\r
+               strokeWidth = (Float)strokeWidthPair.second;\r
+\r
+            vh.setStroke(e, new BasicStroke(strokeWidth,\r
+                                BasicStroke.CAP_BUTT,\r
+                                BasicStroke.JOIN_MITER,\r
+                                10.0f, null, 0.0f));\r
+            Stroke stroke = vh.getStroke(e);\r
+            Font font = ElementUtils.getTextFont(e);\r
+            Color color = ElementUtils.getTextColor(e);\r
+//            Color fillColor = ElementUtils.getFillColor(e);\r
+            Color borderColor = ElementUtils.getBorderColor(e, Color.BLACK);\r
+//            String text = ElementUtils.getText(e);\r
+            Alignment hAlign = ElementUtils.getHintOrDefault(e, ElementHints.KEY_HORIZONTAL_ALIGN, Alignment.CENTER);\r
+            node.setBackgroundColor(null);\r
+            node.setBorderColor(borderColor);\r
+            node.setHorizontalAlignment((byte) hAlign.ordinal());\r
+            node.setPadding(0, 0);\r
+            node.setBorderWidth((float) 0);\r
+            node.setEditable(false);\r
+            node.setFont(font);\r
+            \r
+            node.setBeginBounds(beginTerminalShape);\r
+            node.setEndBounds(endTerminalShape);\r
+            node.setStroke(stroke);\r
+            node.setColor(color);\r
+            node.setShapes(DependencyRouter.createArrowShape(node.getShapes(), node.getBeginBounds(), node.getEndBounds(), node.getAngle(), node.getStroke()));\r
+\r
+            if(properties != null) {\r
+                       for(Map.Entry<String, Pair<Resource, Object>> entry : properties.entrySet()) {\r
+                               NodeUtil.setPropertyIfSupported(entry.getKey(), entry.getValue().second, node);                         \r
+//                             node.setProperty(entry.getKey(), entry.getValue().second);\r
+//                             System.out.println("setProperty " + entry.getKey() + " => " + entry.getValue().second);\r
+                       }\r
+            }\r
+            EdgeHandler eh = e.getElementClass().getAtMostOneItemOfClass(EdgeHandler.class);\r
+            Path2D path = eh.getPath(e);\r
+            if(path == null)\r
+               path = new Path2D.Double();\r
+            else\r
+               path.reset();\r
+            path.append(node.getShapes().first, false);\r
+            eh.setPath(e, path);\r
+\r
+        }\r
+\r
+        private static Shape getCanvasTerminalShape(Connection connection) {\r
+            if (connection != null && connection.node != null && connection.terminal != null) {\r
+                TerminalLayout layout = connection.node.getElementClass().getAtMostOneItemOfClass(TerminalLayout.class);\r
+                if (layout != null) {\r
+                    //return layout.getTerminalShape(connection.node, connection.terminal);\r
+                    Shape shp = layout.getTerminalShape(connection.node, connection.terminal);\r
+                    Transform tr = connection.node.getElementClass().getAtMostOneItemOfClass(Transform.class);\r
+                    if (tr == null)\r
+                        return shp;\r
+\r
+                    return tr.getTransform(connection.node).createTransformedShape(shp);\r
+                    \r
+                }\r
+            }\r
+            return null;\r
+        }\r
+\r
+    }\r
+  \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyEdgeFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyEdgeFactory.java
new file mode 100644 (file)
index 0000000..e8f1b89
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.procedure.AsyncProcedure;\r
+import org.simantics.diagram.adapter.ElementFactoryAdapter;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+\r
+/**\r
+ * An element class factory for sysdyn dependency connection edge segments.\r
+ * \r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class DependencyEdgeFactory extends ElementFactoryAdapter {\r
+\r
+    private static final ElementClass CLASS = DependencyEdgeClass.CLASS;\r
+\r
+    @Override\r
+    public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType,\r
+            AsyncProcedure<ElementClass> procedure) {\r
+        procedure.execute(graph, CLASS);\r
+    }\r
+\r
+    @Override\r
+    public void getClass(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementResource,\r
+            AsyncProcedure<ElementClass> procedure) {\r
+        procedure.execute(graph, CLASS);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/DependencyNode.java
new file mode 100644 (file)
index 0000000..2bd3a51
--- /dev/null
@@ -0,0 +1,409 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.awt.Graphics2D;\r
+import java.awt.Shape;\r
+import java.awt.Stroke;\r
+import java.awt.geom.Arc2D;\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+import java.beans.PropertyChangeEvent;\r
+import java.beans.PropertyChangeListener;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.g2d.utils.Alignment;\r
+import org.simantics.scenegraph.ISelectionPainterNode;\r
+import org.simantics.scenegraph.g2d.IG2DNode;\r
+import org.simantics.scenegraph.g2d.events.EventTypes;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonReleasedEvent;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseDragBegin;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;\r
+import org.simantics.scenegraph.g2d.nodes.ConnectionNode;\r
+import org.simantics.scenegraph.g2d.nodes.SingleElementNode;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+import org.simantics.sysdyn.ui.editor.routing.DependencyRouter;\r
+import org.simantics.sysdyn.ui.elements.LoopNode.ILoopComponentNode;\r
+import org.simantics.sysdyn.ui.elements.LoopNode;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementHints;\r
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
+import org.simantics.utils.datastructures.Triple;\r
+\r
+/**\r
+ * Node for dependency arrows and polarity text\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class DependencyNode extends TextNode implements ISelectionPainterNode, ILoopComponentNode {\r
+\r
+    public static final String INSIDE = "Inside";\r
+    public static final String OUTSIDE = "Outside";\r
+\r
+    public static final double HITMARGIN = 1.7;\r
+    \r
+    private static final long serialVersionUID = 1294351381209071074L;\r
+\r
+    private Color color;\r
+    private Stroke stroke;\r
+    private Shape beginBounds;\r
+    private Shape endBounds;\r
+    private double angle = 0.3;\r
+    private String side;\r
+    private boolean delayMark = false;\r
+    private boolean arrowHead = true;\r
+    private transient Triple<Arc2D, Path2D, Path2D> shapes = new Triple<Arc2D, Path2D, Path2D>(new Arc2D.Double(), new Path2D.Double(), new Path2D.Double());\r
+\r
+    transient public boolean hover = false;\r
+    private boolean dragging = false;\r
+\r
+    private transient PropertyChangeListener fieldListener = null;\r
+       \r
+    @Override\r
+    public void init() {\r
+        super.init();\r
+        addEventHandler(this);\r
+\r
+    }\r
+\r
+\r
+    /**\r
+     * Inits the dependency node with a text\r
+     * @param text Polarity\r
+     * @param side Polarity Location\r
+     * @param font Font\r
+     * @param color Color\r
+     * @param x Text initial location x\r
+     * @param y Text initial location y\r
+     * @param scale Scale\r
+     */\r
+    public void init(String text, String side, boolean delayMark, boolean arrowHead, Font font, Color color, double x, double y, double scale) {\r
+        super.init(text, font, color, x, y, scale);\r
+        this.side = side;\r
+        this.delayMark = delayMark;\r
+        this.arrowHead = arrowHead;\r
+        setHorizontalAlignment((byte) Alignment.CENTER.ordinal());\r
+        setVerticalAlignment((byte) Alignment.CENTER.ordinal());\r
+    }\r
+\r
+    @Override\r
+    public void cleanup() {\r
+        super.cleanup();\r
+    }\r
+\r
+    public void setFieldListener(PropertyChangeListener listener) {\r
+        this.fieldListener = listener;\r
+    }\r
+\r
+    @ServerSide\r
+    public void commitProperty(String field, Object value) {\r
+        if(fieldListener != null) {\r
+            fieldListener.propertyChange(new PropertyChangeEvent(this, field, null, value));\r
+        }\r
+    }\r
+\r
+    @PropertySetter("color")\r
+    @SyncField("color")\r
+    public void setColor(Color color) {\r
+        this.color = color;\r
+    }\r
+\r
+    @PropertySetter("stroke")\r
+    @SyncField("stroke")\r
+    public void setStroke(Stroke stroke) {\r
+        this.stroke = stroke;\r
+    }\r
+\r
+    @PropertySetter("beginBounds")\r
+    @SyncField("beginBounds")\r
+    public void setBeginBounds(Shape beginBounds) {\r
+        this.beginBounds = beginBounds;\r
+    }\r
+\r
+    @PropertySetter("endBounds")\r
+    @SyncField("endBounds")\r
+    public void setEndBounds(Shape endBounds) {\r
+        this.endBounds = endBounds;\r
+    }\r
+\r
+    @PropertySetter("angle")\r
+    @SyncField("angle")\r
+    public void setAngle(Double angle) {\r
+        this.angle = angle.doubleValue();\r
+        if(this.beginBounds != null && this.endBounds != null)\r
+            this.shapes = DependencyRouter.createArrowShape(this.shapes, this.beginBounds, this.endBounds, this.angle, this.stroke);\r
+    }\r
+\r
+    @PropertySetter("shapes")\r
+    @SyncField("shapes")\r
+    public void setShapes(Triple<Arc2D, Path2D, Path2D> shapes) {\r
+        this.shapes = shapes;\r
+    }\r
+\r
+    public Color getColor() {\r
+        return color;\r
+    }\r
+\r
+    public Stroke getStroke() {\r
+        return stroke;\r
+    }\r
+\r
+    public Shape getBeginBounds() {\r
+        return beginBounds;\r
+    }\r
+\r
+    public Shape getEndBounds() {\r
+        return endBounds;\r
+    }\r
+\r
+    public double getAngle() {\r
+        return angle;\r
+    }\r
+\r
+    public Triple<Arc2D, Path2D, Path2D> getShapes() {\r
+        return shapes;\r
+    }\r
+\r
+\r
+\r
+    @Override\r
+    public void render(Graphics2D g) {\r
+        if(beginBounds == null || endBounds == null) return;\r
+\r
+        // Removed to let the global control handle rendering quality issues.\r
+        //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\r
+\r
+        boolean selected = NodeUtil.isSelected(this, 2);\r
+        if(font != null) g.setFont(font);\r
+        if(selected) {\r
+            g.setColor(Color.PINK);\r
+            float strokeWidth = 1.4f + 2 * (stroke instanceof BasicStroke ? ((BasicStroke)stroke).getLineWidth() : DependencyEdgeClass.DEFAULT_STROKE_WIDTH); \r
+            g.setStroke(new BasicStroke(strokeWidth));\r
+            g.draw(shapes.first);\r
+            g.fill(shapes.second);\r
+            if(color != null) g.setColor(color);\r
+            g.setStroke(stroke);\r
+            g.draw(shapes.first);\r
+            if (arrowHead) {\r
+               g.draw(shapes.second);\r
+                g.fill(shapes.second);\r
+            }\r
+            if (delayMark) g.draw(shapes.third);\r
+        } else if (hover){\r
+            g.setColor(Color.LIGHT_GRAY);\r
+            float strokeWidth = 1.4f + 2 * (stroke instanceof BasicStroke ? ((BasicStroke)stroke).getLineWidth() : DependencyEdgeClass.DEFAULT_STROKE_WIDTH); \r
+            g.setStroke(new BasicStroke(strokeWidth));\r
+            g.draw(shapes.first);\r
+            g.fill(shapes.second);\r
+            if(color != null) g.setColor(color);\r
+            g.setStroke(stroke);\r
+            g.draw(shapes.first);\r
+            if (arrowHead) {\r
+               g.draw(shapes.second);\r
+                g.fill(shapes.second);\r
+            }\r
+            if (delayMark) g.draw(shapes.third);\r
+        } else if (isLoopSelected()) {\r
+            g.setColor(LoopNode.HIGHLIGHT_COLOR);\r
+            if(stroke != null) g.setStroke(stroke);\r
+            g.draw(shapes.first);\r
+            if (arrowHead) {\r
+               g.draw(shapes.second);\r
+                g.fill(shapes.second);\r
+            }\r
+            if (delayMark) g.draw(shapes.third);\r
+        } else {\r
+            if(color != null) g.setColor(color);\r
+            if(stroke != null) g.setStroke(stroke);\r
+            g.draw(shapes.first);\r
+            if (arrowHead) {\r
+               g.draw(shapes.second);\r
+                g.fill(shapes.second);\r
+            }\r
+            if (delayMark) g.draw(shapes.third);\r
+        }\r
+\r
+        double angleRad = angle > 0 ? \r
+                Math.toRadians(shapes.first.getAngleStart() + shapes.first.getAngleExtent()) : \r
+                    Math.toRadians(shapes.first.getAngleStart());\r
+                Point2D point = angle > 0 ? shapes.first.getEndPoint() : shapes.first.getStartPoint();\r
+\r
+                int angle1 = 220;\r
+                int angle2 = -40;\r
+                if(OUTSIDE.equals(side)) {\r
+                    angle1 *= -1;\r
+                    angle2 *= -1;\r
+                }\r
+                double a = Math.toRadians(angle < 0 ? angle1 : angle2);\r
+                double s = Math.sin(a) * 3;\r
+                double c = Math.cos(a) * 4;\r
+\r
+                g.translate(point.getX(), point.getY());\r
+                g.rotate(-angleRad);\r
+                g.translate(s, c);\r
+                g.rotate(angleRad);\r
+                super.render(g);\r
+                g.rotate(-angleRad);\r
+                g.translate(-s, -c);\r
+                g.rotate(angleRad);\r
+                g.translate(-point.getX(), -point.getY());\r
+\r
+    }\r
+\r
+    boolean pressHit = false;\r
+       private HashMap<LoopNode, Boolean> loopSelectionMap = new HashMap<LoopNode, Boolean>();\r
+\r
+       private boolean isLoopSelected() {\r
+               return loopSelectionMap.containsValue(true);\r
+       }\r
+       \r
+    protected boolean hitTest(org.simantics.scenegraph.g2d.events.MouseEvent event, double tolerance) {\r
+        if(beginBounds == null || endBounds == null) return false;\r
+        Point2D localPos = NodeUtil.worldToLocal(this, event.controlPosition, new Point2D.Double());\r
+        return Arcs.hitTest(beginBounds, endBounds, angle, localPos.getX(), localPos.getY(), tolerance);\r
+    }\r
+    \r
+    protected double getRadialDistanse(Point2D coord) {\r
+       if(beginBounds == null || endBounds == null) return Double.NaN;\r
+        Point2D localPos = NodeUtil.worldToLocal(this, coord, new Point2D.Double());\r
+        return Arcs.getRadialDistance(beginBounds, endBounds, angle, localPos.getX(), localPos.getY());\r
+    }\r
+\r
+    @Override\r
+    public Rectangle2D getBoundsInLocal() {\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public int getEventMask() {\r
+        return super.getEventMask() | EventTypes.MouseDragBeginMask\r
+                | EventTypes.MouseButtonPressedMask\r
+                | EventTypes.MouseButtonReleasedMask\r
+                ;\r
+    }\r
+    \r
+    @Override\r
+    protected boolean mouseMoved(MouseMovedEvent event) {\r
+        boolean hit = hitTest(event, HITMARGIN);\r
+        if(dragging) {\r
+            Point2D localPos = NodeUtil.worldToLocal(this, event.controlPosition, new Point2D.Double());\r
+            \r
+            setAngle(Arcs.angleOfArc(\r
+                    beginBounds.getBounds2D().getCenterX(), beginBounds.getBounds2D().getCenterY(),\r
+                    localPos.getX(), localPos.getY(),\r
+                    endBounds.getBounds2D().getCenterX(), endBounds.getBounds2D().getCenterY()));\r
+            repaint();\r
+        }\r
+        \r
+        if (hit != hover) {\r
+            hover = hit;\r
+            repaint();\r
+        }\r
+        return false;\r
+    }\r
+\r
+    private static boolean isEventDummy(MouseDragBegin e) {\r
+       if (e.controlPosition.distance(0, 0) == 0 \r
+                       && e.screenPosition.distance(0, 0) == 0\r
+                       && e.buttons == 0) {\r
+               return true;\r
+       } else {\r
+               return false;\r
+       }\r
+    }\r
+    \r
+    @Override\r
+    protected boolean mouseDragged(MouseDragBegin e) {\r
+       // Get rid of dummy events from dragGestureRecognized\r
+       if (isEventDummy(e)) {\r
+               return false;\r
+       }\r
+       \r
+       // Disable dragging if LockSketch is ON\r
+               if (SysdynElementHints.LOCK_TOOL.equals(SysdynWorkbenchUtils.getSysdynToolMode()))\r
+                       return false;\r
+               \r
+       //System.out.println(this.toString() + " event: " + e.toString());\r
+       boolean selected = NodeUtil.isSelected(this, 2);\r
+       double myRadialDistance = this.getRadialDistanse(e.controlPosition);\r
+       Collection<?> nodes = this.getParent().getParent().getParent().getNodes();\r
+       if (!selected) {\r
+               for (Object temp1 : nodes) {\r
+                       if (temp1 instanceof ConnectionNode) {\r
+                               for ( IG2DNode temp2 : ((ConnectionNode)temp1).getNodes()) {\r
+                                       if (temp2 instanceof SingleElementNode) {\r
+                                               for ( IG2DNode temp3 : ((SingleElementNode)temp2).getNodes()) {\r
+                                                       if (temp3 instanceof DependencyNode){\r
+                                                               DependencyNode otherDependencyNode = (DependencyNode)temp3;\r
+                                                               if (otherDependencyNode == this) {\r
+                                                                       continue;\r
+                                                               }\r
+                                                               double otherNodeDist = otherDependencyNode.getRadialDistanse(e.controlPosition);\r
+                                                               if (Double.isNaN(otherNodeDist)) {\r
+                                                                       continue;\r
+                                                               }\r
+                                                       if (otherDependencyNode.isDragging()) {\r
+                                                                       return true;\r
+                                                               } \r
+                                                               if (NodeUtil.isSelected(otherDependencyNode, 2) && (otherNodeDist < HITMARGIN)) {\r
+                                                                       return false;\r
+                                                               } \r
+                                                               if (otherNodeDist < myRadialDistance) {\r
+                                                                       return false;\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+               if ( (myRadialDistance < HITMARGIN) && !dragging) {\r
+               dragging = true;\r
+                       return true;\r
+               }\r
+        return false;\r
+    }\r
+\r
+    @Override\r
+    protected boolean mouseButtonPressed(MouseButtonPressedEvent e) {\r
+        return false;\r
+    }\r
+\r
+    protected boolean mouseButtonReleased(MouseButtonReleasedEvent e) {\r
+        if(dragging) {\r
+            commitProperty("angle", angle);\r
+            dragging = false;\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    protected boolean isDragging() {\r
+       return dragging;\r
+    }\r
+\r
+       @Override\r
+       public void setLoopSelected(LoopNode loop, boolean selected) {\r
+               Boolean loopSelected = loopSelectionMap.get(loop);\r
+               if (loopSelected == null || loopSelected != selected) {\r
+                       loopSelectionMap.put(loop, selected);\r
+                       repaint();\r
+               }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowArrowLineStyle.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowArrowLineStyle.java
new file mode 100644 (file)
index 0000000..a48e700
--- /dev/null
@@ -0,0 +1,142 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Path2D;\r
+import java.io.Serializable;\r
+import java.util.StringTokenizer;\r
+\r
+import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;\r
+\r
+\r
+/**\r
+ * Copied from ArrowLLineEndStyle\r
+ */\r
+public class FlowArrowLineStyle implements ILineEndStyle, Serializable {\r
+\r
+    private static final long serialVersionUID = 5348566089660986479L;\r
+\r
+    public static enum ArrowType { None, Stroke, Fill }\r
+\r
+    public static final double length = FlowConnectionStyle.DEFAULT_LINE_WIDTH * 4;\r
+    public static final double width = FlowConnectionStyle.DEFAULT_LINE_WIDTH * 2;\r
+    public static final double space = 0.0;\r
+\r
+    protected ArrowType type;\r
+    protected Path2D path;\r
+    protected double lineEndLength;\r
+    protected Color color;\r
+    \r
+    public FlowArrowLineStyle(String desc, Color color) {\r
+        this.type = ArrowType.None;\r
+        this.lineEndLength = 0.0;\r
+\r
+        double l = length;\r
+        double w = width;\r
+        double s = space;\r
+        \r
+        if(color != null)\r
+            this.color = color;\r
+        else\r
+            this.color = Color.BLACK;\r
+\r
+        StringTokenizer tokenizer = new StringTokenizer(desc);\r
+        if (tokenizer.hasMoreTokens()) {\r
+            String type = tokenizer.nextToken();\r
+            this.type = parseType(type);\r
+\r
+            if (tokenizer.hasMoreTokens()) {\r
+                String ls = tokenizer.nextToken();\r
+                l = parseSize(ls, length);\r
+\r
+                if (tokenizer.hasMoreTokens()) {\r
+                    String ws = tokenizer.nextToken();\r
+                    w = parseSize(ws, width);\r
+\r
+                    if (tokenizer.hasMoreTokens()) {\r
+                        String ss = tokenizer.nextToken();\r
+                        s = parseSize(ss, space);\r
+                    }\r
+                }\r
+            }\r
+            if (this.type != ArrowType.None) {\r
+                this.path = arrow(l, w, s);\r
+                lineEndLength = l+s;\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void render(Graphics2D g, double x, double y, int dir) {\r
+        if (type == ArrowType.None || path == null)\r
+            return;\r
+        AffineTransform old = g.getTransform();\r
+        g.translate(x, y);\r
+        g.rotate(dir*Math.PI*0.5);\r
+        g.setColor(color);\r
+\r
+        switch (type) {\r
+            case Fill:\r
+                g.fill(path);\r
+                break;\r
+            case Stroke:\r
+                g.draw(path);\r
+                break;\r
+                       default:\r
+                               break;\r
+        }\r
+\r
+        g.setTransform(old);\r
+    }\r
+\r
+    @Override\r
+    public double getLineEndLength(int direction) {\r
+        return lineEndLength;\r
+    }\r
+\r
+    private static Path2D arrow(double length, double width, double space) {\r
+        Path2D.Double path = new Path2D.Double();\r
+        path.moveTo(-space, 0);\r
+        path.lineTo(-length-space, -width);\r
+        path.lineTo(-length-space, +width);\r
+        path.closePath();\r
+        return path;\r
+    }\r
+\r
+    private double parseSize(String size, double defaultValue) {\r
+        try {\r
+            return Double.parseDouble(size);\r
+        } catch (NumberFormatException e) {\r
+            return defaultValue;\r
+        }\r
+    }\r
+\r
+    private ArrowType parseType(String type) {\r
+        String lower = type.toLowerCase();\r
+        if ("none".equals(lower))\r
+            return ArrowType.None;\r
+        if ("stroke".equals(lower))\r
+            return ArrowType.Stroke;\r
+        if ("fill".equals(lower))\r
+            return ArrowType.Fill;\r
+        throw new IllegalArgumentException("unrecognized arrow type: " + type);\r
+    }\r
+\r
+    @Override\r
+    public String toString() {\r
+        return getClass().getSimpleName() + "[" + type + ", " + path + "]";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowConnectionStyle.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowConnectionStyle.java
new file mode 100644 (file)
index 0000000..a7476de
--- /dev/null
@@ -0,0 +1,97 @@
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.Color;\r
+import java.awt.Graphics2D;\r
+import java.awt.Stroke;\r
+import java.awt.geom.Path2D;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.connection.rendering.BasicConnectionStyle;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.LoopNode;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class FlowConnectionStyle  extends BasicConnectionStyle {\r
+\r
+    private static final long serialVersionUID = 2777194644079591357L;\r
+\r
+    Color                     lineColor;\r
+    Stroke                    lineStroke;\r
+\r
+       private Resource resource;\r
+\r
+       // Is the default color overridden by the loop color\r
+       private boolean loopColorOverride = false;\r
+    \r
+    public static final float DEFAULT_LINE_WIDTH = 1.0f;\r
+\r
+    public FlowConnectionStyle(Color lineColor, Stroke lineStroke, Resource resource) {\r
+        super(lineColor, Color.BLACK, 0.5, lineStroke, lineStroke, 0.8);\r
+        this.lineColor = lineColor;\r
+        this.lineStroke = lineStroke;\r
+        this.resource = resource;\r
+    }\r
+    \r
+    @Override\r
+    public void drawBranchPoint(Graphics2D g, double x, double y) {\r
+    }\r
+\r
+    @Override\r
+    public void drawLine(Graphics2D g, double x1, double y1, double x2, double y2, boolean isTransient) {\r
+    }\r
+\r
+    @Override\r
+    public void drawPath(Graphics2D g, Path2D path, boolean isTransient) {\r
+        if (lineColor != null) // Highlight the flow if loop where the flow belongs to is selected.\r
+            g.setColor(loopColorOverride ? LoopNode.HIGHLIGHT_COLOR : lineColor);\r
+        if (lineStroke != null)\r
+            g.setStroke(lineStroke);\r
+\r
+        // Fetch the width of the flow\r
+        Float width = DEFAULT_LINE_WIDTH;\r
+        try {\r
+                       Float connectionWidth = SimanticsUI.getSession().syncRequest(new Read<Float>() {\r
+\r
+                               @Override\r
+                               public Float perform(ReadGraph graph)\r
+                                               throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       if (resource == null)\r
+                                               return null;\r
+                                       return graph.getPossibleRelatedValue(resource, sr.FlowConnection_width, Bindings.FLOAT);\r
+                               }\r
+                       });\r
+                       if (connectionWidth != null)\r
+                               width = connectionWidth; \r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+        Path2D p1 = Flows.createOffsetPath(path, width/2);\r
+        Path2D p2 = Flows.createOffsetPath(path, -width/2);\r
+        p1.append(p2, false);\r
+        g.draw(p1);\r
+    }\r
+\r
+    @Override\r
+    public void drawDegeneratedLine(Graphics2D g, double x, double y, boolean isHorizontal, boolean isTransient) {\r
+    }\r
+\r
+    @Override\r
+    public double getDegeneratedLineLength() {\r
+        return 0;\r
+    }\r
+\r
+    /**\r
+     * Set if the flow color should be overwritten with loop color\r
+     * @param loopColorOverride \r
+     */\r
+       public void setLoopColorOverride(boolean loopColorOverride) {\r
+               this.loopColorOverride  = loopColorOverride;\r
+       }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/Flows.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/Flows.java
new file mode 100644 (file)
index 0000000..a7c6bd9
--- /dev/null
@@ -0,0 +1,257 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.geom.Path2D;\r
+import java.awt.geom.PathIterator;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+public class Flows {\r
+       \r
+       public static double ARROW_LENGTH = 3.2;\r
+    public static double ARROW_WIDTH = 2;\r
+\r
+    static final double OFFSET = 1.0;\r
+    static final double ARROW_OFFSET = 3.2;\r
+\r
+    public static Path2D createArrow(Path2D arrow, Rectangle2D tail, Rectangle2D head) {   \r
+\r
+       double x = tail.getCenterX();\r
+        double y = tail.getCenterY();\r
+\r
+        double cx = head.getCenterX();\r
+        double minx = head.getMinX();\r
+        double maxx = head.getMaxX();\r
+        double miny = head.getMinY();\r
+        double maxy = head.getMaxY();\r
+\r
+        if(arrow == null)\r
+               arrow = new Path2D.Double();\r
+        else\r
+               arrow.reset();\r
+        \r
+        // approach from top\r
+        if (y < miny) {\r
+               arrow.moveTo(cx, miny);\r
+               arrow.lineTo(cx + ARROW_WIDTH, miny - ARROW_LENGTH);\r
+               arrow.lineTo(cx - ARROW_WIDTH, miny - ARROW_LENGTH);\r
+        } \r
+\r
+        // approach from beneath\r
+        else if (y > maxy) {\r
+               arrow.moveTo(cx, maxy);\r
+               arrow.lineTo(cx + ARROW_WIDTH, maxy + ARROW_LENGTH);\r
+               arrow.lineTo(cx - ARROW_WIDTH, maxy + ARROW_LENGTH);\r
+        }\r
+\r
+        // approach from left\r
+        else if (x < minx) {\r
+               arrow.moveTo(minx, y);\r
+               arrow.lineTo(minx - ARROW_LENGTH, y - ARROW_WIDTH);\r
+               arrow.lineTo(minx - ARROW_LENGTH, y + ARROW_WIDTH);\r
+        }\r
+\r
+        // approach from right\r
+        else if (x > maxx) {\r
+               arrow.moveTo(maxx, y);\r
+               arrow.lineTo(maxx + ARROW_LENGTH, y - ARROW_WIDTH);\r
+               arrow.lineTo(maxx + ARROW_LENGTH, y + ARROW_WIDTH);\r
+        }\r
+        else\r
+            return null; // FIXME (HN) This is just a quick bugfix, didn't understand the logic completely  \r
+\r
+        arrow.closePath();\r
+        \r
+        return arrow;\r
+        \r
+    }\r
+    \r
+    private static Path2D createLines(Path2D lines, boolean vertical, double ... coordinates) {\r
+       if(lines == null)\r
+               lines = new Path2D.Double();\r
+       else\r
+               lines.reset();\r
+       createOffsetLine(lines, vertical, OFFSET, coordinates);\r
+       createOffsetLine(lines, vertical, -OFFSET, coordinates);\r
+       return lines;\r
+    }\r
+\r
+    public static Path2D createLines(Path2D lines, boolean hasArrow, Rectangle2D valve, Rectangle2D node) {\r
+        double x0 = valve.getCenterX();\r
+        double y0 = valve.getCenterY();        \r
+        double x1 = node.getCenterX();\r
+        double y1 = node.getCenterY();\r
+        \r
+        double minY = hasArrow ? node.getMinY() - ARROW_OFFSET : node.getMinY();\r
+        double maxY = hasArrow ? node.getMaxY() + ARROW_OFFSET : node.getMaxY();\r
+        double minX = hasArrow ? node.getMinX() - ARROW_OFFSET : node.getMinX();\r
+        double maxX = hasArrow ? node.getMaxX() + ARROW_OFFSET : node.getMaxX();\r
+        \r
+        boolean rotated = false;\r
+        \r
+        if( rotated ) {\r
+            if(y1 > y0)\r
+                y0 += OFFSET;\r
+            else\r
+                y0 -= OFFSET;\r
+            if(node.getMinX() <= x0 && node.getMaxX() >= x0) {\r
+                if(y1 > y0)\r
+                    return createLines(lines, true, y0, x0, minY);\r
+                else\r
+                       return createLines(lines, true, y0, x0, maxY);\r
+            }\r
+            else {\r
+                if(x1 > x0)\r
+                       return createLines(lines, true, y0, x0, y1, minX);\r
+                else\r
+                       return createLines(lines, true, y0, x0, y1, maxX);\r
+            }\r
+        }\r
+        else {\r
+            if(x1 > x0)\r
+                x0 += OFFSET;\r
+            else\r
+                x0 -= OFFSET;\r
+            if(node.getMinY() <= y0 && node.getMaxY() >= y0) {\r
+                if(x1 > x0)\r
+                       return createLines(lines, false, x0, y0, minX);\r
+                else\r
+                       return createLines(lines, false, x0, y0, maxX);\r
+            }\r
+            else {\r
+                if(y1 > y0)\r
+                       return createLines(lines, false, x0, y0, x1, minY);\r
+                else\r
+                       return createLines(lines, false, x0, y0, x1, maxY);\r
+            }\r
+        }\r
+\r
+\r
+    }\r
+\r
+    public static Path2D createLine(Path2D path, boolean vertical, double ... coordinates) {\r
+        if(vertical)\r
+            path.moveTo(coordinates[1], coordinates[0]);\r
+        else\r
+            path.moveTo(coordinates[0], coordinates[1]);\r
+        for(int i=2;i<coordinates.length;++i, vertical = !vertical) {\r
+            if(vertical)\r
+                path.lineTo(coordinates[i-1], coordinates[i]);\r
+            else\r
+                path.lineTo(coordinates[i], coordinates[i-1]);\r
+        }\r
+        return path;\r
+    }\r
+    \r
+    public static Path2D createOffsetLine(Path2D path, boolean vertical, double offset, double ... coordinates) {\r
+        double[] newCoordinats = new double[coordinates.length];\r
+        newCoordinats[0] = coordinates[0];\r
+        newCoordinats[coordinates.length-1] = coordinates[coordinates.length-1];\r
+        for(int i=1;i<coordinates.length-1;++i) {\r
+            if(coordinates[i-1] < coordinates[i+1] ^ (i&1)==1)\r
+                newCoordinats[i] = coordinates[i]+offset;\r
+            else\r
+                newCoordinats[i] = coordinates[i]-offset;\r
+        }\r
+        return createLine(path, vertical, newCoordinats);\r
+    }\r
+    \r
+    \r
+    private static int x = 0;\r
+    private static int y = 1;\r
+    public static Path2D createOffsetPath(Path2D originalPath, float offset) {\r
+        PathIterator pi = originalPath.getPathIterator(null);\r
+        Path2D newPath = new Path2D.Double();\r
+        double[] previous = new double[6];\r
+        double[] current = new double[6];\r
+        double[] next = new double[6];\r
+        boolean vertical = false;\r
+        pi.currentSegment(current);\r
+        pi.next();\r
+        pi.currentSegment(next);\r
+        \r
+        Direction direction = getDirection(current, next);\r
+\r
+        int i = 0;\r
+        if(direction == Direction.SOUTH || direction == Direction.NORTH) {\r
+            // First line vertical\r
+            vertical = true;\r
+            current[x] += offset;\r
+            newPath.moveTo(current[x], current[y]);\r
+            \r
+            if(direction == Direction.SOUTH)\r
+                offset = -offset;\r
+        } else {\r
+            // First line horizontal\r
+            current[y] += offset;\r
+            i = 1;\r
+            newPath.moveTo(current[x], current[y]);\r
+            if(direction == Direction.WEST)\r
+                offset = -offset;\r
+        }\r
+        \r
+\r
+        previous[x] = current[x];\r
+        previous[y] = current[y];\r
+        current[x] = next[x];\r
+        current[y] = next[y];\r
+\r
+        while(!pi.isDone()) {\r
+            pi.next();\r
+            pi.currentSegment(next);\r
+            if(previous[i] < next[i] ^ (i&1)==1) {\r
+                if(vertical) {\r
+                    if(!pi.isDone()) current[y] += offset;\r
+                    newPath.lineTo(previous[x], current[y]);\r
+                } else {\r
+                    if(!pi.isDone()) current[x] += offset;\r
+                    newPath.lineTo(current[x], previous[y]);\r
+                }\r
+            } else {\r
+                if(vertical) {\r
+                    if(!pi.isDone()) current[y] -= offset;\r
+                    newPath.lineTo(previous[x], current[y]);\r
+                } else {\r
+                    if(!pi.isDone()) current[x] -= offset;\r
+                    newPath.lineTo(current[x], previous[y]);\r
+                }\r
+            }\r
+            \r
+            previous[x] = current[x];\r
+            previous[y] = current[y];\r
+            current[x] = next[x];\r
+            current[y] = next[y];\r
+            vertical = !vertical;\r
+            i = (i + 1) % 2;\r
+        }\r
+        return newPath;\r
+    }\r
+    \r
+    private static enum Direction {NORTH, SOUTH, EAST, WEST};\r
+\r
+    private static Direction getDirection(double[] current, double[] next) {\r
+        if(current[x] == next[x]) {\r
+            // move vertically\r
+            if(current[y] < next[y])\r
+                return Direction.SOUTH;\r
+            else\r
+                return Direction.NORTH;\r
+        } else {\r
+            //move horizontally\r
+            if(current[x] < next[x])\r
+                return Direction.EAST;\r
+            else\r
+                return Direction.WEST;\r
+        }\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowConnectionFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowConnectionFactory.java
new file mode 100644 (file)
index 0000000..6515eb0
--- /dev/null
@@ -0,0 +1,704 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Shape;\r
+import java.awt.Stroke;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import java.util.concurrent.ConcurrentSkipListMap;\r
+import java.util.concurrent.atomic.AtomicInteger;\r
+\r
+import org.eclipse.jface.resource.StringConverter;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.Statement;\r
+import org.simantics.db.common.procedure.adapter.TransientCacheListener;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.AsyncProcedure;\r
+import org.simantics.db.procedure.SyncMultiProcedure;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.diagram.adapter.SyncElementFactory;\r
+import org.simantics.diagram.connection.ConnectionVisuals;\r
+import org.simantics.diagram.connection.RouteGraph;\r
+import org.simantics.diagram.connection.RouteGraphConnectionClass;\r
+import org.simantics.diagram.connection.RouteLine;\r
+import org.simantics.diagram.connection.RouteNode;\r
+import org.simantics.diagram.connection.RouteTerminal;\r
+import org.simantics.diagram.connection.rendering.ConnectionStyle;\r
+import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;\r
+import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;\r
+import org.simantics.diagram.content.EdgeResource;\r
+import org.simantics.diagram.content.ResourceTerminal;\r
+import org.simantics.diagram.content.TerminalMap;\r
+import org.simantics.diagram.query.DiagramRequests;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.diagram.synchronization.graph.RouteGraphConnection;\r
+import org.simantics.diagram.ui.DiagramModelHints;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.connection.ConnectionEntity;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.diagram.handler.DataElementMap;\r
+import org.simantics.g2d.diagram.handler.Topology.Connection;\r
+import org.simantics.g2d.diagram.handler.Topology.Terminal;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;\r
+import org.simantics.g2d.element.handler.TerminalTopology;\r
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
+import org.simantics.g2d.routing.algorithm2.Router4;\r
+import org.simantics.g2d.utils.TopologicalSelectionExpander;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.scenegraph.g2d.nodes.connection.IRouteGraphListener;\r
+import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphChangeEvent;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.structural2.modelingRules.CPTerminal;\r
+import org.simantics.structural2.modelingRules.IAttachmentRelationMap;\r
+import org.simantics.structural2.modelingRules.IModelingRules;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;\r
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferences;\r
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPropertyExternalRead;\r
+import org.simantics.utils.datastructures.Pair;\r
+/**\r
+ * An element class for Sysdyn Flow elements.\r
+ * Copied from RouteGraphConnectionClassFactory and adapted to Flow needs\r
+ * \r
+ * @author Teemu Lempinen\r
+ * \r
+ */\r
+public class RouteFlowConnectionFactory extends SyncElementFactory {\r
+\r
+    public static final ElementClass CLASS = RouteFlowEdgeClass.FLOW_CLASS;\r
+\r
+    Layer0                             L0;\r
+    DiagramResource                    DIA;\r
+    StructuralResource2                STR;\r
+    ModelingResources                  MOD;\r
+\r
+    public RouteFlowConnectionFactory(ReadGraph graph) {\r
+        this.L0 = Layer0.getInstance(graph);\r
+        this.DIA = DiagramResource.getInstance(graph);\r
+        this.STR = StructuralResource2.getInstance(graph);\r
+        this.MOD = ModelingResources.getInstance(graph);\r
+    }\r
+\r
+    @Override\r
+    public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType, final AsyncProcedure<ElementClass> procedure) {\r
+        procedure.execute(graph, CLASS.newClassWith(false, new StaticObjectAdapter(elementType)));\r
+    }\r
+\r
+    @Override\r
+    protected Resource getElementClassBaseType(AsyncReadGraph graph) {\r
+        return graph.getService(SysdynResource.class).FlowConnection;\r
+    }\r
+\r
+    @Override\r
+    public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource connection,\r
+            final IElement element) throws DatabaseException {\r
+\r
+        // Do we need this?\r
+        element.setHint(DiagramHints.ROUTE_ALGORITHM, new Router4(false));\r
+\r
+        IModelingRules modelingRules = diagram.getHint(DiagramModelHints.KEY_MODELING_RULES);\r
+\r
+        IElement mappedElement = ElementUtils.getByData(diagram, connection);\r
+        if (mappedElement == null)\r
+            // FIXME: With undo this seems to happen, don't know why yet!\r
+            return;\r
+\r
+        Color color = null;\r
+        DiagramResource DR = DiagramResource.getInstance(graph);\r
+        G2DResource G2D = G2DResource.getInstance(graph);\r
+        if (graph.isInstanceOf(connection, DR.ColorProvider)) {\r
+            Statement colorStatement = graph.getPossibleStatement(connection, G2D.HasColor);\r
+            if(colorStatement != null && !colorStatement.isAsserted(connection)) {\r
+                element.setHint(ElementHints.KEY_TEXT_COLOR, G2DUtils.getColor(graph, colorStatement.getObject()));\r
+            } else {\r
+                String colorString = graph.syncRequest(new SysdynDiagramPropertyExternalRead(new Pair<Resource, String>(connection, SysdynDiagramPreferences.getColorPreferenceName(graph, connection))));\r
+                if(colorString != null) {\r
+                    RGB rgb = StringConverter.asRGB(colorString, null);\r
+                    if(rgb != null) {\r
+                        color = new Color(rgb.red, rgb.green, rgb.blue);\r
+                        element.setHint(ElementHints.KEY_TEXT_COLOR, color);\r
+                    }\r
+                }\r
+\r
+            }\r
+        }\r
+\r
+        RouteGraph rg = new RouteGraph();\r
+\r
+        Set<Resource> nodes = new HashSet<Resource>();\r
+        Set<EdgeResource> links = new HashSet<EdgeResource>();\r
+        Map<Object, RouteNode> nodeByData = new HashMap<Object, RouteNode>();\r
+\r
+        // Needed to support ConnectionEntity#getTerminalConnections\r
+        Set<BackendConnection> backendonnections = new HashSet<BackendConnection>();\r
+\r
+        // Load all route graph interior RouteNodes: route lines and points\r
+        for (Resource interiorNode : graph.getObjects(connection, DIA.HasInteriorRouteNode)) {\r
+            if (graph.isInstanceOf(interiorNode, DIA.RouteLine)) {\r
+                Boolean isHorizontal = graph.getRelatedValue(interiorNode, DIA.IsHorizontal, Bindings.BOOLEAN);\r
+                Double position = graph.getRelatedValue(interiorNode, DIA.HasPosition, Bindings.DOUBLE);\r
+                RouteLine line = rg.addLine(isHorizontal, position);\r
+                line.setData( RouteGraphConnection.serialize(graph, interiorNode) );\r
+\r
+                nodes.add( interiorNode );\r
+                nodeByData.put( interiorNode, line );\r
+\r
+                for (Resource connectedTo : graph.getObjects(interiorNode, DIA.AreConnected)) {\r
+                    links.add( new EdgeResource(interiorNode, connectedTo) );\r
+                }\r
+            } else if (graph.isInstanceOf(interiorNode, DIA.RoutePoint)) {\r
+                // Not supported yet. Ignore.\r
+            }\r
+        }\r
+\r
+        Rectangle2D bounds = new Rectangle2D.Double();\r
+\r
+        // Load all node terminal connections as RouteTerminals\r
+        for (Statement toConnector : graph.getStatements(connection, DIA.HasConnector)) {\r
+            Resource connector = toConnector.getObject();\r
+            Resource attachmentRelation = toConnector.getPredicate();\r
+\r
+            Statement terminalStm = findTerminalStatement(graph, STR, connection, connector);\r
+            if (terminalStm == null)\r
+                // Ignore broken connector: attached to the connection but not to any terminal.\r
+                continue;\r
+\r
+            Resource terminalElement = terminalStm.getObject();\r
+            Resource terminalElementType = graph.getPossibleType(terminalElement, DIA.Element);\r
+            if (terminalElementType == null)\r
+                // Ignore non-element terminal elements\r
+                continue;\r
+\r
+            Resource connectionRelation = graph.getInverse(terminalStm.getPredicate());\r
+\r
+            // Discover node and terminal this connector is connected to.\r
+            TerminalMap terminals = graph.syncRequest(DiagramRequests.elementTypeTerminals(terminalElementType),\r
+                    TransientCacheListener.<TerminalMap> instance());\r
+            Resource terminal = terminals.getTerminal(connectionRelation);\r
+            if (terminal == null) {\r
+                System.err.println(getClass().getSimpleName()\r
+                        + ": Could not find terminal for connection point "\r
+                        + NameUtils.getSafeName(graph, connectionRelation, true)\r
+                        + " in element "\r
+                        + NameUtils.getSafeName(graph, terminalElement, true)); \r
+                continue;\r
+            }\r
+\r
+            double[] position = graph.getRelatedValue(connector, DIA.HasRelativeLocation, Bindings.DOUBLE_ARRAY);\r
+            if (position.length != 2)\r
+                position = new double[] { 0, 0 };\r
+\r
+            //System.out.println("terminalStm: " + NameUtils.toString(graph, terminalStm));\r
+            AffineTransform terminalElementTr = getWorldTransform(graph, terminalElement);\r
+\r
+            double x = terminalElementTr.getTranslateX();\r
+            double y = terminalElementTr.getTranslateY();\r
+            double minx = x-1, miny = y-1, maxx = x+1, maxy = y+1;\r
+            int direction = 0x0;\r
+\r
+            // Use modelingRules to ascertain the proper attachmentRelation\r
+            // for this terminal connection, if available.\r
+            if (modelingRules != null) {\r
+                // Get attachmentRelation from modelingRules if possible.\r
+                IAttachmentRelationMap map = modelingRules.getAttachmentRelations(graph, connection);\r
+                Resource att = map.get(graph, new CPTerminal(terminalElement, terminal));\r
+                if (att != null) {\r
+                    //System.out.println("modeling rules attachment: " + NameUtils.getSafeLabel(graph, att));\r
+                    attachmentRelation = att;\r
+                }\r
+            }\r
+            //System.out.println("attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));\r
+\r
+            // Get element bounds to decide allowed terminal direction(s)\r
+            IElement te = graph.syncRequest(DiagramRequests.getElement(canvas, diagram, terminalElement, null));\r
+  \r
+            // Fetch the flow width\r
+            float lw = FlowConnectionStyle.DEFAULT_LINE_WIDTH;\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Float width = graph.getPossibleRelatedValue(connection, sr.FlowConnection_width, Bindings.FLOAT);\r
+               if (width != null)\r
+                       lw = width;\r
+            \r
+               if(te.getElementClass().containsClass(ValveSceneGraph.class)) {\r
+                // Valve behaves differently. The flow must start inside the valve bounds\r
+                ValveSceneGraph vs = te.getElementClass().getSingleItem(ValveSceneGraph.class);\r
+                Rectangle2D size = new Rectangle2D.Double();\r
+                vs.getValveBounds(te, size);\r
+                Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(size, terminalElementTr);\r
+                size = (Rectangle2D) shp;\r
+                bounds.setFrame(new Rectangle2D.Double(size.getCenterX() - (lw/2), size.getCenterY() - (lw/2), lw, lw));\r
+            } else {\r
+                // Basic bounds\r
+                bounds = ElementUtils.getElementShape(te).getBounds2D();\r
+                Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(bounds, terminalElementTr);\r
+                bounds.setFrame(shp.getBounds2D());\r
+            }\r
+            \r
+            x = bounds.getCenterX();\r
+            y = bounds.getCenterY();\r
+\r
+            // Expand bounds by 4mm to make the connections enter the terminals\r
+            // at a straight angle and from a distance instead of coming in\r
+            // "horizontally".\r
+            //GeometryUtils.expandRectangle(bounds, 4);\r
+\r
+            minx = bounds.getMinX();\r
+            miny = bounds.getMinY();\r
+            maxx = bounds.getMaxX();\r
+            maxy = bounds.getMaxY();\r
+\r
+            Integer allowedDirections = graph.getPossibleRelatedValue(terminal, DIA.Terminal_AllowedDirections, Bindings.INTEGER);\r
+\r
+            // Valve behaves differently. Allowed directions depend on the orientation of the valve\r
+            if(te.getElementClass().containsClass(ValveSceneGraph.class)) {\r
+                if(graph.hasStatement(terminalElement, sr.ValveSymbol_orientation, sr.Vertical)) {\r
+                    allowedDirections = 10; // Directions up and down (1010)\r
+                } else {\r
+                    allowedDirections = 5; // Directions left and right (0101)\r
+                }\r
+            }\r
+            if (allowedDirections != null) {\r
+                direction |= allowedDirections;\r
+            } else {\r
+                direction |= RouteGraphConnectionClass.shortestDirectionOutOfBounds(x, y, bounds);\r
+            }\r
+\r
+            backendonnections.add(\r
+                    new BackendConnection(\r
+                            toEdgeEnd(graph, attachmentRelation, EdgeEnd.Begin),\r
+                            terminalElement,\r
+                            terminal)\r
+                    );\r
+\r
+            if (direction == 0)\r
+                // Accept any horizontal/vertical direction if nothing is defined\r
+                direction = 0xf;\r
+\r
+            //System.out.println("load line style: " + NameUtils.getSafeLabel(graph, attachmentRelation));\r
+            ILineEndStyle endStyle = loadLineEndStyle(graph, te, attachmentRelation, color, lw);\r
+\r
+            RouteTerminal routeTerminal = rg.addBigTerminal(/*x, y,*/ minx, miny, maxx, maxy, /*direction,*/ endStyle);\r
+            routeTerminal.setData( RouteGraphConnection.serialize(graph, connector) );\r
+\r
+            nodes.add( connector );\r
+            nodeByData.put( connector, routeTerminal );\r
+\r
+            for (Resource connectedTo : graph.getObjects(connector, DIA.AreConnected)) {\r
+                links.add( new EdgeResource(connectedTo, connector) );\r
+            }\r
+        }\r
+\r
+        // Finish route graph loading by Linking route nodes together\r
+        for (EdgeResource link : links) {\r
+            RouteNode n1 = nodeByData.get(link.first());\r
+            RouteNode n2 = nodeByData.get(link.second());\r
+            if (n1 == null || n2 == null) {\r
+                System.err.println("Stray connection link found: " + link.toString(graph));\r
+                continue;\r
+            }\r
+            rg.link(n1, n2);\r
+        }\r
+\r
+        // Load connection line style\r
+        ConnectionStyle style = readConnectionStyle(graph, modelingRules, connection, element);\r
+        StyledRouteGraphRenderer renderer = new StyledRouteGraphRenderer(style);\r
+\r
+        // Finish element load\r
+        element.setHint(RouteGraphConnectionClass.KEY_ROUTEGRAPH, rg);\r
+        element.setHint(RouteGraphConnectionClass.KEY_RENDERER, renderer);\r
+        element.setHint(RouteGraphConnectionClass.KEY_PICK_TOLERANCE, 0.5);\r
+\r
+        // Initialize ConnectionEntity in element\r
+        // NOTE: MUST use the mapped element with class CE, not the connection (element) were loading into.\r
+        // GDS will synchronize element into mappedElement in a controlled manner.\r
+        element.setHint(ElementHints.KEY_CONNECTION_ENTITY, new CE(connection, mappedElement, backendonnections));\r
+\r
+        // Setup graph writeback support for route graph modifications\r
+        final Session session = graph.getSession();\r
+        element.setHint(RouteGraphConnectionClass.KEY_RG_LISTENER, new IRouteGraphListener() {\r
+            @Override\r
+            public void routeGraphChanged(RouteGraphChangeEvent event) {\r
+                scheduleSynchronize(session, connection, event);\r
+            }\r
+        });\r
+        \r
+     // A complicated-looking procedure for obtaining all HasProperties to properties map\r
+        final AtomicInteger ready = new AtomicInteger(1);\r
+        final ConcurrentSkipListMap<String, Pair<Resource, Object>> properties = new ConcurrentSkipListMap<String, Pair<Resource, Object>>();\r
+        graph.forEachPredicate(connection, new SyncMultiProcedure<Resource>() {\r
+\r
+            @Override\r
+            public void exception(ReadGraph graph, Throwable throwable) {\r
+                throwable.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public void execute(ReadGraph graph, final Resource property) {\r
+\r
+                ready.incrementAndGet();\r
+                Layer0 l0;\r
+                try {\r
+                    l0 = Layer0.getInstance(graph.getSession());\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                    return;\r
+                }\r
+\r
+                graph.forIsSubrelationOf(property, l0.HasProperty, new AsyncProcedure<Boolean>() {\r
+\r
+                    @Override\r
+                    public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                        throwable.printStackTrace();\r
+                    }\r
+\r
+                    @Override\r
+                    public void execute(AsyncReadGraph graph, final Boolean isProperty) {\r
+\r
+                        if(isProperty) {\r
+\r
+                            graph.forPossibleRelatedValue(connection, property, new AsyncProcedure<Object>() {\r
+\r
+                                @Override\r
+                                public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                                    throwable.printStackTrace();\r
+                                }\r
+\r
+                                @Override\r
+                                public void execute(AsyncReadGraph graph, final Object value) {\r
+\r
+                                    Layer0 l0;\r
+                                    try {\r
+                                        l0 = Layer0.getInstance(graph.getSession());\r
+                                    } catch (DatabaseException e) {\r
+                                        e.printStackTrace();\r
+                                        return;\r
+                                    }\r
+\r
+                                    graph.forPossibleRelatedValue(property, l0.HasName, Bindings.STRING, new AsyncProcedure<String>() {\r
+\r
+                                        @Override\r
+                                        public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                                            throwable.printStackTrace();\r
+                                        }\r
+\r
+                                        @Override\r
+                                        public void execute(AsyncReadGraph graph, String name) {\r
+\r
+                                            properties.put(name, Pair.make(property, value));\r
+                                            if(ready.decrementAndGet() == 0) {\r
+                                                element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Pair<Resource, Object>>(properties));\r
+                                            }\r
+\r
+                                        }\r
+\r
+                                    });\r
+\r
+                                }\r
+\r
+                            });\r
+\r
+\r
+                        } else {\r
+\r
+                            if(ready.decrementAndGet() == 0) {\r
+                                element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Pair<Resource, Object>>(properties));\r
+                            }\r
+\r
+                        }\r
+\r
+                    }\r
+\r
+                });\r
+            }\r
+\r
+            @Override\r
+            public void finished(ReadGraph graph) {\r
+\r
+                if(ready.decrementAndGet() == 0) {\r
+                    element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Object>(properties));\r
+                }\r
+\r
+            }\r
+\r
+        });\r
+\r
+    }\r
+\r
+    private EdgeEnd toEdgeEnd(ReadGraph graph, Resource attachmentRelation, EdgeEnd defaultValue)\r
+            throws DatabaseException {\r
+        if (graph.isSubrelationOf(attachmentRelation, DIA.IsTailConnectorOf))\r
+            return EdgeEnd.Begin;\r
+        if (graph.isSubrelationOf(attachmentRelation, DIA.IsHeadConnectorOf))\r
+            return EdgeEnd.End;\r
+        return defaultValue;\r
+    }\r
+\r
+    private ConnectionStyle readConnectionStyle(ReadGraph graph, IModelingRules modelingRules, Resource connection,\r
+            IElement element) throws DatabaseException {\r
+        Resource connectionType = null;\r
+        if (modelingRules != null)\r
+            connectionType = modelingRules.getConnectionType(graph, connection);\r
+        if (connectionType == null)\r
+            connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);\r
+\r
+        ConnectionVisuals cv = null;\r
+        if (connectionType != null)\r
+            cv = graph.syncRequest(DiagramRequests.getConnectionVisuals(connectionType),\r
+                    TransientCacheListener.<ConnectionVisuals> instance());\r
+\r
+\r
+        Color lineColor = element.getHint(ElementHints.KEY_TEXT_COLOR);\r
+        if (lineColor == null)\r
+            lineColor = (cv != null && cv.toColor() != null) ? cv.toColor() : Color.DARK_GRAY;\r
+\r
+            Stroke lineStroke = cv != null ? cv.stroke : null;\r
+            if (lineStroke == null)\r
+                lineStroke = new BasicStroke(0.1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, null, 0);\r
+\r
+            return new FlowConnectionStyle(\r
+                    lineColor,\r
+                    lineStroke,\r
+                    connection);\r
+    }\r
+\r
+    /**\r
+     * @param graph\r
+     * @param STR\r
+     * @param connection\r
+     * @param connector\r
+     * @return connection relation statement from diagram connection connector\r
+     *         to a node\r
+     * @throws DatabaseException\r
+     */\r
+    private static Statement findTerminalStatement(ReadGraph graph, StructuralResource2 STR, Resource connection,\r
+            Resource connector) throws DatabaseException {\r
+        for (Statement stm : graph.getStatements(connector, STR.Connects)) {\r
+            if (connection.equals(stm.getObject()))\r
+                continue;\r
+            return stm;\r
+        }\r
+        return null;\r
+    }\r
+\r
+    public ILineEndStyle loadLineEndStyle(ReadGraph graph, IElement te, Resource attachmentRelation, Color color, float lineWidth)\r
+            throws DatabaseException {\r
+        ILineEndStyle style;\r
+        // TODO: change bounds according to terminal type: Very small rectangle for Valves, Text box size for Stocks and Clouds\r
+        if(te.getElementClass().containsClass(ValveSceneGraph.class)) {\r
+            style =  new FlowArrowLineStyle("none 0 0 0", color);\r
+        } else {\r
+            if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector)) {\r
+                float arrowSize = lineWidth * 1.3f;\r
+                style = new FlowArrowLineStyle("fill " + arrowSize + " " + arrowSize + " 0", color);\r
+            } else {\r
+                style =  new FlowArrowLineStyle("none 0 0 0", color);\r
+            }\r
+        }\r
+        return style;\r
+    }\r
+\r
+    /**\r
+     * @param graph\r
+     * @param element\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    private static AffineTransform getWorldTransform(ReadGraph graph, Resource element) throws DatabaseException {\r
+        ModelingResources MOD = ModelingResources.getInstance(graph);\r
+        AffineTransform result = DiagramGraphUtil.getAffineTransform(graph, element);\r
+        while (true) {\r
+            Resource parentComponent = graph.getPossibleObject(element, MOD.HasParentComponent);\r
+            if (parentComponent == null)\r
+                return result;\r
+            element = graph.getPossibleObject(parentComponent, MOD.ComponentToElement);\r
+            if (element == null)\r
+                return result;\r
+            AffineTransform tr = DiagramGraphUtil.getAffineTransform(graph, element);\r
+            tr.setToTranslation(tr.getTranslateX(), tr.getTranslateY());\r
+            result.preConcatenate(tr);\r
+        }\r
+    }\r
+\r
+\r
+    protected void scheduleSynchronize(Session session, Resource connection, RouteGraphChangeEvent event) {\r
+        session.asyncRequest(RouteGraphConnection.synchronizer(connection, event));\r
+    }\r
+\r
+    /**\r
+     * Must have this in order for {@link TopologicalSelectionExpander} to work.\r
+     * Otherwise this is pretty useless and should be deprecated altogether.\r
+     * \r
+     * @see ElementHints#KEY_CONNECTION_ENTITY\r
+     */\r
+    static class CE implements ConnectionEntity {\r
+\r
+        /**\r
+         * The connection instance resource in the graph backend.\r
+         */\r
+        final Resource               connection;\r
+\r
+        /**\r
+         * The connection entity element which is a part of the diagram.\r
+         */\r
+        final IElement               connectionElement;\r
+\r
+        /**\r
+         * @see #getTerminalConnections(Collection)\r
+         */\r
+        final Set<BackendConnection> backendConnections;\r
+\r
+        /**\r
+         * Cache.\r
+         */\r
+        Set<Connection>              terminalConnections;\r
+\r
+        CE(Resource connection, IElement connectionElement, Set<BackendConnection> backendConnections) {\r
+            this.connection = connection;\r
+            this.connectionElement = connectionElement;\r
+            this.backendConnections = backendConnections;\r
+        }\r
+\r
+        @Override\r
+        public IElement getConnection() {\r
+            return connectionElement;\r
+        }\r
+\r
+        public Object getConnectionObject() {\r
+            return connection;\r
+        }\r
+\r
+        public IElement getConnectionElement() {\r
+            return connectionElement;\r
+        }\r
+\r
+        @Override\r
+        public Collection<IElement> getBranchPoints(Collection<IElement> result) {\r
+            return result != null ? result : Collections.<IElement> emptyList();\r
+        }\r
+\r
+        @Override\r
+        public Collection<IElement> getSegments(Collection<IElement> result) {\r
+            return result != null ? result : Collections.<IElement> emptyList();\r
+        }\r
+\r
+        @Override\r
+        public Collection<Connection> getTerminalConnections(Collection<Connection> result) {\r
+            if (terminalConnections == null)\r
+                terminalConnections = calculateTerminalConnections();\r
+            if (result == null)\r
+                result = new ArrayList<Connection>(terminalConnections);\r
+            else\r
+                result.addAll(terminalConnections);\r
+            return terminalConnections;\r
+        }\r
+\r
+        private Set<Connection> calculateTerminalConnections() {\r
+            IDiagram diagram = connectionElement.getDiagram();\r
+            DataElementMap dem = diagram.getDiagramClass().getSingleItem(DataElementMap.class);\r
+            Set<Connection> result = new HashSet<Connection>();\r
+            ArrayList<Terminal> ts = new ArrayList<Terminal>();\r
+            for (BackendConnection bc : backendConnections) {\r
+                IElement e = dem.getElement(diagram, bc.node);\r
+                if (e == null)\r
+                    continue;\r
+                TerminalTopology tt = e.getElementClass().getSingleItem(TerminalTopology.class);\r
+                tt.getTerminals(e, ts);\r
+                for (Terminal t : ts) {\r
+                    if (t instanceof ResourceTerminal) {\r
+                        ResourceTerminal rt = (ResourceTerminal) t;\r
+                        if (bc.terminal.equals(rt.getResource())) {\r
+                            result.add(new Connection(connectionElement, bc.end, e, t));\r
+                            break;\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            return result;\r
+        }\r
+\r
+        @Override\r
+        public void setListener(ConnectionListener listener) {\r
+            throw new UnsupportedOperationException();\r
+        }\r
+\r
+        @Override\r
+        public String toString() {\r
+            return getClass().getSimpleName() + "[resource=" + connection + ", connectionElement=" + connectionElement\r
+                    + "]";\r
+        }\r
+\r
+    }\r
+\r
+    public static class BackendConnection {\r
+        public final Resource node;\r
+        public final Resource terminal;\r
+        public final EdgeEnd  end;\r
+        public BackendConnection(EdgeEnd end, Resource node, Resource terminal) {\r
+            assert end != null;\r
+            assert node != null;\r
+            assert terminal != null;\r
+            this.end = end;\r
+            this.node = node;\r
+            this.terminal = terminal;\r
+        }\r
+        @Override\r
+        public boolean equals(Object obj) {\r
+            if (this == obj)\r
+                return true;\r
+            if (!(obj instanceof Connection))\r
+                return false;\r
+            Connection other = (Connection) obj;\r
+            return other.terminal == terminal\r
+                    && other.node == node\r
+                    && other.end == end;\r
+        }\r
+        @Override\r
+        public int hashCode() {\r
+            final int prime = 31;\r
+            int result = 1;\r
+            result = prime * result + end.hashCode();\r
+            result = prime * result + ((node == null) ? 0 : node.hashCode());\r
+            result = prime * result + ((terminal == null) ? 0 : terminal.hashCode());\r
+            return result;\r
+        }\r
+        @Override\r
+        public String toString() {\r
+            return "BackendConnection[node=" + node + ", terminal=" + terminal + ", end=" + end + "]";\r
+        }\r
+    }\r
+\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowEdgeClass.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowEdgeClass.java
new file mode 100644 (file)
index 0000000..5061e73
--- /dev/null
@@ -0,0 +1,82 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.simantics.diagram.connection.RouteGraph;\r
+import org.simantics.diagram.connection.RouteGraphConnectionClass;\r
+import org.simantics.diagram.connection.rendering.IRouteGraphRenderer;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.ElementHandler;\r
+import org.simantics.g2d.element.handler.SceneGraph;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.nodes.connection.IRouteGraphListener;\r
+\r
+\r
+public class RouteFlowEdgeClass extends RouteGraphConnectionClass {\r
+    \r
+    public static final ElementClass FLOW_CLASS = getElementClass();\r
+\r
+            \r
+    public static final ElementClass getElementClass() {\r
+        List<ElementHandler> oldList = CLASS.getAll();\r
+        ArrayList<ElementHandler> list = new ArrayList<ElementHandler>();\r
+        list.add(FlowConnectionSceneGraph.INSTANCE);\r
+        for(ElementHandler eh : oldList) {\r
+            if(!(eh instanceof SceneGraph)) {\r
+                list.add(eh);\r
+            }\r
+        }\r
+        return  ElementClass.compile(list);\r
+    }\r
+    \r
+    \r
+    static final class FlowConnectionSceneGraph implements SceneGraph {\r
+\r
+        public static final FlowConnectionSceneGraph INSTANCE = new FlowConnectionSceneGraph();\r
+\r
+        private static final long serialVersionUID = 1865920472882420644L;\r
+\r
+        @Override\r
+        public void init(IElement connection, G2DParentNode parent) {\r
+            RouteGraph rg = connection.getHint(KEY_ROUTEGRAPH);\r
+            IRouteGraphRenderer renderer = connection.getHint(KEY_RENDERER);\r
+            if (rg == null || renderer == null) {\r
+                cleanup(connection);\r
+            } else {\r
+               RouteFlowNode rgn = ElementUtils.getOrCreateNode(connection, parent, KEY_RG_NODE, "flow_" + connection.hashCode(), RouteFlowNode.class);\r
+                rgn.setRouteGraph(rg);\r
+                rgn.setRenderer(renderer);\r
+\r
+                IRouteGraphListener listener = connection.getHint(KEY_RG_LISTENER);\r
+                rgn.setRouteGraphListener(listener);\r
+\r
+                Double tolerance = connection.getHint(KEY_PICK_TOLERANCE);\r
+                if (tolerance != null)\r
+                    rgn.setPickTolerance(tolerance);\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void cleanup(IElement connection) {\r
+            ElementUtils.removePossibleNode(connection, KEY_RG_NODE);\r
+            connection.removeHint(KEY_RG_NODE);\r
+        }\r
+    }\r
+\r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowEdgeFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowEdgeFactory.java
new file mode 100644 (file)
index 0000000..97bb845
--- /dev/null
@@ -0,0 +1,38 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.procedure.AsyncProcedure;\r
+import org.simantics.diagram.adapter.ElementFactoryAdapter;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.g2d.element.ElementClass;\r
+\r
+public class RouteFlowEdgeFactory extends ElementFactoryAdapter {\r
+\r
+    private static final ElementClass CLASS = RouteFlowEdgeClass.FLOW_CLASS;\r
+\r
+    @Override\r
+    public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType,\r
+            AsyncProcedure<ElementClass> procedure) {\r
+        procedure.execute(graph, CLASS);\r
+    }\r
+\r
+    @Override\r
+    public void getClass(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementResource,\r
+            AsyncProcedure<ElementClass> procedure) {\r
+        procedure.execute(graph, CLASS);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowNode.java
new file mode 100644 (file)
index 0000000..4a75f08
--- /dev/null
@@ -0,0 +1,72 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.simantics.diagram.connection.rendering.ConnectionStyle;\r
+import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;\r
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseDragBegin;\r
+import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;\r
+import org.simantics.sysdyn.ui.elements.LoopNode;\r
+import org.simantics.sysdyn.ui.elements.LoopNode.ILoopComponentNode;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementHints;\r
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
+\r
+/**\r
+ * Node for flow arrows.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class RouteFlowNode extends RouteGraphNode implements ILoopComponentNode {\r
+\r
+       private static final long serialVersionUID = 2576929364910319487L;\r
+       boolean isLock = false;\r
+       private HashMap<LoopNode, Boolean> loopSelectionMap = new HashMap<LoopNode, Boolean>();\r
+\r
+       private boolean isLoopSelected() {\r
+               return loopSelectionMap.containsValue(true);\r
+       }\r
+       \r
+       @Override\r
+    protected boolean mouseDragged(MouseDragBegin e) {\r
+               // Disable dragging if LockSketch is ON\r
+               if (SysdynElementHints.LOCK_TOOL.equals(SysdynWorkbenchUtils.getSysdynToolMode()))\r
+                       return false;\r
+               else\r
+                       return super.mouseDragged(e);\r
+       }\r
+\r
+       @Override\r
+       public void setLoopSelected(LoopNode loop, boolean selected) {\r
+               Boolean loopSelected = loopSelectionMap.get(loop);\r
+               if (loopSelected == null || loopSelected != selected) {\r
+                       loopSelectionMap.put(loop, selected);\r
+                       \r
+                       // Here the FlowConnectionStyle takes care of drawing the flow, so\r
+                       // find it and tell it to change the color accordingly\r
+                       if (!(renderer instanceof StyledRouteGraphRenderer))\r
+                               return;\r
+               \r
+                       StyledRouteGraphRenderer renderer = (StyledRouteGraphRenderer)this.renderer;\r
+                       ConnectionStyle style = renderer.getStyle();\r
+                       if (!(style instanceof FlowConnectionStyle))\r
+                               return;\r
+                       \r
+                       FlowConnectionStyle fcs = (FlowConnectionStyle)style;\r
+                       \r
+                       fcs.setLoopColorOverride(isLoopSelected());\r
+                       repaint();\r
+               }\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/SysdynConnectionClass.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/SysdynConnectionClass.java
new file mode 100644 (file)
index 0000000..e9fc970
--- /dev/null
@@ -0,0 +1,572 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.connections;\r
+\r
+import java.awt.Color;\r
+import java.awt.Composite;\r
+import java.awt.Font;\r
+import java.awt.Shape;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Area;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.g2d.connection.ConnectionEntity;\r
+import org.simantics.g2d.connection.ConnectionEntity.ConnectionEvent;\r
+import org.simantics.g2d.connection.ConnectionEntity.ConnectionListener;\r
+import org.simantics.g2d.connection.handler.ConnectionHandler;\r
+import org.simantics.g2d.diagram.DiagramHints;\r
+import org.simantics.g2d.diagram.handler.PickRequest.PickPolicy;\r
+import org.simantics.g2d.diagram.handler.Topology.Connection;\r
+import org.simantics.g2d.element.ElementClass;\r
+import org.simantics.g2d.element.ElementHints;\r
+import org.simantics.g2d.element.ElementUtils;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.g2d.element.handler.Children;\r
+import org.simantics.g2d.element.handler.InternalSize;\r
+import org.simantics.g2d.element.handler.Outline;\r
+import org.simantics.g2d.element.handler.Pick;\r
+import org.simantics.g2d.element.handler.Pick2;\r
+import org.simantics.g2d.element.handler.SceneGraph;\r
+import org.simantics.g2d.element.handler.SelectionOutline;\r
+import org.simantics.g2d.element.handler.Transform;\r
+import org.simantics.g2d.element.handler.impl.ConnectionSelectionOutline;\r
+import org.simantics.g2d.element.handler.impl.ParentImpl;\r
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
+import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
+import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
+import org.simantics.g2d.element.handler.impl.TextImpl;\r
+import org.simantics.g2d.elementclass.connection.EdgeClass.FixedTransform;\r
+import org.simantics.g2d.utils.GeometryUtils;\r
+import org.simantics.scenegraph.g2d.G2DParentNode;\r
+import org.simantics.scenegraph.g2d.IG2DNode;\r
+import org.simantics.scenegraph.g2d.nodes.SingleElementNode;\r
+import org.simantics.utils.datastructures.ListenerList;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
+import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;\r
+\r
+/**\r
+ * An element class for single connection entity elements. A sysdyn connection\r
+ * entity consists of a single edge. Sysdyn connections can't be branched.\r
+ * \r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class SysdynConnectionClass {\r
+\r
+    public static final ElementClass CLASS =\r
+        ElementClass.compile(\r
+                TextImpl.INSTANCE,\r
+                TextFontImpl.DEFAULT,\r
+                TextColorImpl.BLACK,\r
+                FixedTransform.INSTANCE,\r
+                ConnectionPick.INSTANCE,\r
+                ConnectionBounds.INSTANCE,\r
+                ConnectionSelectionOutline.INSTANCE,\r
+                ConnectionHandlerImpl.INSTANCE,\r
+                ConnectionChildren.INSTANCE,\r
+                ParentImpl.INSTANCE,\r
+                ConnectionSceneGraph.INSTANCE,\r
+                SimpleElementLayers.INSTANCE\r
+        ).setId(SysdynConnectionClass.class.getSimpleName());\r
+\r
+    private static class ThreadLocalList extends ThreadLocal<List<IElement>> {\r
+        @Override\r
+        protected java.util.List<IElement> initialValue() {\r
+            return new ArrayList<IElement>();\r
+        }\r
+    };\r
+\r
+    private static final ThreadLocal<List<IElement>> perThreadSceneGraphList = new ThreadLocalList();\r
+    private static final ThreadLocal<List<IElement>> perThreadBoundsList = new ThreadLocalList();\r
+    private static final ThreadLocal<List<IElement>> perThreadShapeList = new ThreadLocalList();\r
+    private static final ThreadLocal<List<IElement>> perThreadPickList = new ThreadLocalList();\r
+\r
+    static class ConnectionHandlerImpl implements ConnectionHandler {\r
+\r
+        public static final ConnectionHandlerImpl INSTANCE = new ConnectionHandlerImpl();\r
+\r
+        private static final long serialVersionUID = 3267139233182458330L;\r
+\r
+        @Override\r
+        public Collection<IElement> getBranchPoints(IElement connection, Collection<IElement> result) {\r
+            ConnectionEntity entity = connection.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (entity == null)\r
+                return Collections.emptySet();\r
+            return entity.getBranchPoints(result);\r
+        }\r
+\r
+        @Override\r
+        public Collection<IElement> getChildren(IElement connection, Collection<IElement> result) {\r
+            ConnectionEntity entity = connection.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (entity == null)\r
+                return Collections.emptySet();\r
+            result = entity.getSegments(result);\r
+            return entity.getBranchPoints(result);\r
+        }\r
+\r
+        @Override\r
+        public Collection<IElement> getSegments(IElement connection, Collection<IElement> result) {\r
+            ConnectionEntity entity = connection.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (entity == null)\r
+                return Collections.emptySet();\r
+            return entity.getSegments(result);\r
+        }\r
+\r
+        @Override\r
+        public Collection<Connection> getTerminalConnections(IElement connection, Collection<Connection> result) {\r
+            ConnectionEntity entity = connection.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (entity == null)\r
+                return Collections.emptySet();\r
+            return entity.getTerminalConnections(result);\r
+        }\r
+    }\r
+\r
+    static final class ConnectionSceneGraph implements SceneGraph {\r
+\r
+        public static final ConnectionSceneGraph INSTANCE = new ConnectionSceneGraph();\r
+\r
+        private static final long serialVersionUID = 4232871859964883266L;\r
+\r
+        @Override\r
+        public void init(IElement connection, G2DParentNode parent) {\r
+            ConnectionEntity ce = connection.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (ce == null)\r
+                return;\r
+\r
+            // Painting is single-threaded, it is OK to use a single thread-local collection here.\r
+            List<IElement> children = perThreadSceneGraphList.get();\r
+            children.clear();\r
+            ce.getSegments(children);\r
+            ce.getBranchPoints(children);\r
+            //new Exception("painting connection entity " + ce.hashCode() + " with " + children.size() + " segments and branch points").printStackTrace();\r
+            if (children.isEmpty())\r
+                return;\r
+\r
+            Set<SingleElementNode> tmp = new HashSet<SingleElementNode>();\r
+\r
+               Map<String, Pair<Resource, Object>> properties = connection.getHint(DiagramHints.PROPERTIES);\r
+               \r
+               Font font = connection.getHint(ElementHints.KEY_FONT);\r
+               Color color = connection.getHint(ElementHints.KEY_TEXT_COLOR);\r
+            \r
+            int zIndex = 0;\r
+            for (IElement child : children) {\r
+               \r
+                ElementClass ec = child.getElementClass();\r
+\r
+                Transform transform = child.getElementClass().getSingleItem(Transform.class);\r
+                assert (transform != null);\r
+                AffineTransform at2 = transform.getTransform(child);\r
+                if (at2 == null)\r
+                    continue;\r
+\r
+                if(properties != null)\r
+                       child.setHint(DiagramHints.PROPERTIES, properties);\r
+                \r
+                if(font != null)\r
+                    child.setHint(ElementHints.KEY_FONT, font);\r
+                \r
+                if(color != null)\r
+                    child.setHint(ElementHints.KEY_TEXT_COLOR, color);\r
+                \r
+                SingleElementNode holder = child.getHint(ElementHints.KEY_SG_NODE);\r
+                if (holder == null) {\r
+                    holder = parent.addNode(ElementUtils.generateNodeId(child), SingleElementNode.class);\r
+                    child.setHint(ElementHints.KEY_SG_NODE, holder);\r
+                }\r
+                holder.setZIndex(++zIndex);\r
+\r
+                Composite composite = child.getHint(ElementHints.KEY_COMPOSITE);\r
+\r
+                holder.setTransform((AffineTransform) at2.clone());\r
+                holder.setComposite(composite);\r
+                holder.setVisible(true);\r
+\r
+                // New node handler\r
+                for (SceneGraph n : ec.getItemsByClass(SceneGraph.class)) {\r
+                    n.init(child, holder);\r
+                }\r
+                tmp.add(holder);\r
+            }\r
+\r
+            // Hide unaccessed nodes (but don't remove)\r
+            for (IG2DNode node : parent.getNodes()) {\r
+                if (node instanceof SingleElementNode) {\r
+                    if (!tmp.contains(node)) {\r
+                        ((SingleElementNode)node).setVisible(false);\r
+                    }\r
+                } else {\r
+                    //System.out.println("WHAT IS THIS: ");\r
+                    //NodeDebug.printSceneGraph(((Node) node));\r
+                }\r
+            }\r
+\r
+            // Don't leave dangling references behind.\r
+            children.clear();\r
+        }\r
+\r
+        @Override\r
+        public void cleanup(IElement e) {\r
+        }\r
+    }\r
+\r
+    static final class ConnectionBounds implements InternalSize, Outline {\r
+\r
+        public static final ConnectionBounds INSTANCE = new ConnectionBounds();\r
+\r
+        private static final long serialVersionUID = 4232871859964883266L;\r
+\r
+        @Override\r
+        public Rectangle2D getBounds(IElement e, Rectangle2D size) {\r
+            ConnectionEntity ce = e.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (ce == null)\r
+                return size;\r
+\r
+            Collection<IElement> parts = perThreadBoundsList.get();\r
+            parts.clear();\r
+            parts = ce.getSegments(parts);\r
+            if (parts.isEmpty())\r
+                return size;\r
+\r
+            parts = ce.getBranchPoints(parts);\r
+\r
+            Rectangle2D temp = null;\r
+            for (IElement part : parts) {\r
+                if (ElementUtils.isHidden(part))\r
+                    continue;\r
+\r
+                // Using on-diagram coordinates because neither connections nor\r
+                // edges have a non-identity transform which means that\r
+                // coordinates are always absolute. Therefore branch point\r
+                // bounds also need to be calculated in absolute coordinates.\r
+                Rectangle2D bounds = ElementUtils.getElementBoundsOnDiagram(part, size);\r
+                if (bounds == null)\r
+                    continue;\r
+\r
+//                System.out.println("InternalSize BOUNDS: " + size + " for part " + part + " " + part.getElementClass());\r
+                if (temp == null) {\r
+                    temp = new Rectangle2D.Double();\r
+                    temp.setRect(bounds);\r
+                } else\r
+                    Rectangle2D.union(temp, bounds, temp);\r
+                //System.out.println("InternalSize Combined BOUNDS: " + temp);\r
+            }\r
+            if (temp != null) {\r
+                if (size == null)\r
+                    size = temp;\r
+                else\r
+                    size.setRect(temp);\r
+            }\r
+\r
+            // Don't leave dangling references behind.\r
+            parts.clear();\r
+\r
+            return size;\r
+        }\r
+\r
+        private Shape getSelectionShape(IElement forPart) {\r
+            for (SelectionOutline so : forPart.getElementClass().getItemsByClass(SelectionOutline.class)) {\r
+                Shape shape = so.getSelectionShape(forPart);\r
+                if (shape != null)\r
+                    return shape;\r
+            }\r
+            // Using on-diagram coordinates because neither connections nor\r
+            // edges have a non-identity transform which means that\r
+            // coordinates are always absolute. Therefore branch point\r
+            // shape also needs to be calculated in absolute coordinates.\r
+            Shape shape = ElementUtils.getElementShapeOrBoundsOnDiagram(forPart);\r
+            return shape;\r
+            //return shape.getBounds2D();\r
+        }\r
+\r
+        @Override\r
+        public Shape getElementShape(IElement e) {\r
+            ConnectionEntity ce = e.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (ce == null)\r
+                return new Rectangle2D.Double();\r
+\r
+            Collection<IElement> parts = perThreadShapeList.get();\r
+            parts.clear();\r
+            parts = ce.getSegments(parts);\r
+            if (parts.isEmpty())\r
+                return new Rectangle2D.Double();\r
+            parts = ce.getBranchPoints(parts);\r
+\r
+            if (parts.size() == 1) {\r
+                Shape shape = getSelectionShape(parts.iterator().next());\r
+                //System.out.println("Outline SHAPE: " + shape);\r
+                //System.out.println("Outline BOUNDS: " + shape.getBounds2D());\r
+                return shape;\r
+            }\r
+\r
+            //System.out.println("Outline: " + e);\r
+            Area area = new Area();\r
+            for (IElement part : parts) {\r
+                //System.out.println(part);\r
+\r
+                Shape shape = getSelectionShape(part);\r
+\r
+                Rectangle2D bounds = shape.getBounds2D();\r
+//                System.out.println("    shape: " + shape);\r
+//                System.out.println("    bounds: " + bounds);\r
+\r
+                if (bounds.isEmpty()) {\r
+                    double w = bounds.getWidth();\r
+                    double h = bounds.getHeight();\r
+                    if (w <= 0.0 && h <= 0.0)\r
+                        continue;\r
+\r
+                    // Need to expand shape in either width or height to make it visible.\r
+                    final double exp = 0.1;\r
+                    if (w <= 0.0)\r
+                        shape = org.simantics.scenegraph.utils.GeometryUtils.expandRectangle(bounds, 0, 0, exp, exp);\r
+                    else if (h <= 0.0)\r
+                        shape = org.simantics.scenegraph.utils.GeometryUtils.expandRectangle(bounds, exp, exp, 0, 0);\r
+                }\r
+\r
+                //System.out.println("    final shape: " + shape);\r
+                //shape =  bounds;\r
+\r
+                Area a = null;\r
+                if (shape instanceof Area)\r
+                    a = (Area) shape;\r
+                else\r
+                    a = new Area(shape);\r
+                area.add(a);\r
+            }\r
+\r
+            // Don't leave dangling references behind.\r
+            parts.clear();\r
+\r
+            //System.out.println("    connection area outline: " + area);\r
+            //System.out.println("    connection area outline bounds: " + area.getBounds2D());\r
+            return area;\r
+        }\r
+    }\r
+\r
+    public static class ConnectionPick implements Pick2 {\r
+\r
+        public final static ConnectionPick INSTANCE = new ConnectionPick();\r
+\r
+        private static final long serialVersionUID = 1L;\r
+\r
+        @Override\r
+        public boolean pickTest(IElement e, Shape s, PickPolicy policy) {\r
+            ConnectionEntity ce = e.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (ce == null)\r
+                return false;\r
+\r
+            // Primarily pick branch points and then edges.\r
+            Collection<IElement> parts = perThreadPickList.get();\r
+            parts.clear();\r
+            parts = ce.getBranchPoints(parts);\r
+            parts = ce.getSegments(parts);\r
+            if (parts.isEmpty())\r
+                return false;\r
+\r
+            for (IElement part : parts) {\r
+                for (Pick pick : part.getElementClass().getItemsByClass(Pick.class)) {\r
+//                    System.out.println("TESTING: " + part + " : " + s + " : " + policy);\r
+                    if (pick.pickTest(part, s, policy)) {\r
+                        //System.out.println("  HIT!");\r
+                        return true;\r
+                    }\r
+                }\r
+            }\r
+\r
+            parts.clear();\r
+\r
+            return false;\r
+        }\r
+\r
+        @Override\r
+        public int pick(IElement e, Shape s, PickPolicy policy, Collection<IElement> result) {\r
+            int oldResultSize = result.size();\r
+\r
+//            new Exception("SysdynConnectionClass.pick: " + e + " : " + s + " : " + policy).printStackTrace();\r
+            \r
+            ConnectionEntity ce = e.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (ce == null)\r
+                return 0;\r
+\r
+            // Primarily pick branch points and then edges.\r
+            List<IElement> parts = perThreadPickList.get();\r
+            parts.clear();\r
+\r
+            ce.getSegments(parts);\r
+            int edges = parts.size();\r
+            ce.getBranchPoints(parts);\r
+            int branchPoints = parts.size() - edges;\r
+\r
+            boolean singleEdge = branchPoints == 0 && edges == 1;\r
+\r
+            if (parts.isEmpty())\r
+                return 0;\r
+\r
+            // See whether the whole connection is to be picked..\r
+            boolean pickConnection = false;\r
+            wholeConnectionPick:\r
+                for (Outline outline : e.getElementClass().getItemsByClass(Outline.class)) {\r
+                    Shape elementShape = outline.getElementShape(e);\r
+                    if (elementShape == null)\r
+                        continue;\r
+\r
+                    switch (policy) {\r
+                        case PICK_CONTAINED_OBJECTS:\r
+                            if (GeometryUtils.contains(s, elementShape)) {\r
+                                pickConnection = true;\r
+                                break wholeConnectionPick;\r
+                            }\r
+                            break;\r
+                        case PICK_INTERSECTING_OBJECTS:\r
+                            if (GeometryUtils.intersects(s, elementShape)) {\r
+                                pickConnection = true;\r
+                                break wholeConnectionPick;\r
+                            }\r
+                            break;\r
+                    }\r
+                }\r
+\r
+            ArrayList<IElement> picks = null;\r
+\r
+            // Pick connection segments\r
+            for (int i = 0; i < edges; ++i) {\r
+                IElement part = parts.get(i);\r
+                for (Pick pick : part.getElementClass().getItemsByClass(Pick.class)) {\r
+//                    System.out.println("TESTING SEGMENT: " + part + " : " + s + " : " + policy);\r
+                    if (pick.pickTest(part, s, policy)) {\r
+//                        System.out.println("  HIT!");\r
+                        if (picks == null)\r
+                            picks = new ArrayList<IElement>(4);\r
+                        picks.add(e);\r
+                        break;\r
+                    }\r
+                }\r
+            }\r
+\r
+            // Pick the whole connection ?\r
+            if (pickConnection) {\r
+                if (picks == null)\r
+                    picks = new ArrayList<IElement>(4);\r
+                picks.add(e);\r
+            }\r
+\r
+            // Pick branch/route points\r
+            for (int i = edges; i < parts.size(); ++i) {\r
+                IElement part = parts.get(i);\r
+                for (Pick pick : part.getElementClass().getItemsByClass(Pick.class)) {\r
+                    //System.out.println("TESTING BRANCHPOINT: " + part + " : " + s + " : " + policy);\r
+                    if (pick.pickTest(part, s, policy)) {\r
+                        //System.out.println("  HIT!");\r
+                        if (picks == null)\r
+                            picks = new ArrayList<IElement>(4);\r
+                        picks.add(part);\r
+                        break;\r
+                    }\r
+                }\r
+            }\r
+\r
+            if (picks != null) {\r
+                // Add the discovered pickable children to the result after the\r
+                // parent to make the parent the primary pickable.\r
+                // Skip the children if there is only one child.\r
+                if (!singleEdge) {\r
+                    result.addAll(picks);\r
+                } else {\r
+                    result.add(e);\r
+                }\r
+            }\r
+\r
+            parts.clear();\r
+\r
+//            System.out.println("pick result size = " + result.size());\r
+\r
+            return result.size() - oldResultSize;\r
+        }\r
+    }\r
+\r
+    private static final Key CHILD_LISTENERS = new KeyOf(ListenerList.class, "CHILD_LISTENERS");\r
+\r
+    public static class ConnectionChildren implements Children, ConnectionListener {\r
+\r
+        public final static ConnectionChildren INSTANCE = new ConnectionChildren();\r
+\r
+        private static final long serialVersionUID = 1L;\r
+\r
+        @Override\r
+        public Collection<IElement> getChildren(IElement element, Collection<IElement> result) {\r
+            ConnectionEntity ce = element.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+            if (ce == null) {\r
+                if (result == null)\r
+                    result = new ArrayList<IElement>(0);\r
+                return result;\r
+            }\r
+            result = ce.getSegments(result);\r
+            result = ce.getBranchPoints(result);\r
+            return result;\r
+        }\r
+\r
+        @Override\r
+        public void addChildListener(IElement element, ChildListener listener) {\r
+            ListenerList<ChildListener> ll = null;\r
+            synchronized (element) {\r
+                ll = element.getHint(CHILD_LISTENERS);\r
+                if (ll == null) {\r
+                    ll = new ListenerList<ChildListener>(ChildListener.class);\r
+                    element.setHint(CHILD_LISTENERS, ll);\r
+                    ConnectionEntity entity = element.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+                    entity.setListener(this);\r
+                }\r
+            }\r
+            ll.add(listener);\r
+        }\r
+\r
+        @Override\r
+        public void removeChildListener(IElement element, ChildListener listener) {\r
+            synchronized (element) {\r
+                ListenerList<ChildListener> ll = element.getHint(CHILD_LISTENERS);\r
+                if (ll == null)\r
+                    return;\r
+                ll.remove(listener);\r
+                if (ll.isEmpty()) {\r
+                    ConnectionEntity entity = element.getHint(ElementHints.KEY_CONNECTION_ENTITY);\r
+                    entity.setListener(null);\r
+                }\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void connectionChanged(ConnectionEvent event) {\r
+            fireChildrenChanged(event);\r
+        }\r
+\r
+        private void fireChildrenChanged(ConnectionEvent event) {\r
+            ListenerList<ChildListener> ll = event.connection.getHint(CHILD_LISTENERS);\r
+            if (ll == null)\r
+                return;\r
+            ChildEvent ce = new ChildEvent(event.connection, event.removedParts, event.addedParts);\r
+            for (ChildListener cl : ll.getListeners()) {\r
+                cl.elementChildrenChanged(ce);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/IssueDecorationStyle.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/IssueDecorationStyle.java
new file mode 100644 (file)
index 0000000..e3db689
--- /dev/null
@@ -0,0 +1,190 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.profiles;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collections;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.PossibleTypedParent;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.diagram.profile.StyleBase;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.issues.common.ErrorIssues;\r
+import org.simantics.issues.common.FatalIssues;\r
+import org.simantics.issues.common.WarningIssues;\r
+import org.simantics.issues.ontology.IssueResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.scenegraph.INode;\r
+import org.simantics.scenegraph.g2d.nodes.SVGNode;\r
+import org.simantics.scenegraph.profile.EvaluationContext;\r
+import org.simantics.scenegraph.profile.common.ProfileVariables;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.utils.datastructures.map.Tuple;\r
+\r
+/**\r
+ * Issue Decorations. Display an issue icon on \r
+ * a diagram element depending on the type of the issue\r
+ * .\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class IssueDecorationStyle extends StyleBase<IssueResult> {\r
+\r
+    private static final String DECORATION_NODE_NAME = "issueDecorations";\r
+\r
+    @Override\r
+    public IssueResult calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        ModelingResources MOD = ModelingResources.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        // Find a component for the element \r
+        Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);\r
+        \r
+        // If component is shadow, find the original component\r
+        if (component != null && graph.isInstanceOf(component, SR.Shadow)) {\r
+            component = graph.getPossibleObject(component, SR.Shadow_original);\r
+        }\r
+\r
+        if (component == null)\r
+            return null;\r
+        \r
+        // Get the current transform of the element to be able to move the decoration with the element\r
+        AffineTransform transform = DiagramGraphUtil.getAffineTransform(graph, element);\r
+\r
+        // Find the model of the component\r
+        Resource model = graph.syncRequest(new PossibleTypedParent(component, SimulationResource.getInstance(graph).Model));\r
+        if (model == null)\r
+            return null;\r
+\r
+        // Project\r
+        Resource project = graph.getPossibleObject(model, L0.PartOf);\r
+        if (project == null)\r
+            return null;\r
+\r
+        IssueResult result = null;\r
+        \r
+        /*\r
+         * Search for issues. Start from fatal and move to\r
+         * less important issues. This way the most important \r
+         * issue will be displayed.\r
+         * \r
+         * The issue is returned immediately after it is found.\r
+         */\r
+        \r
+        Set<Variable> fatals = graph.syncRequest(new FatalIssues(project, true));\r
+        result = getIssue(graph, IssueResult.Severity.FATAL, fatals, component, transform);\r
+        if(result != null) return result;\r
+        \r
+        Set<Variable> errors = graph.syncRequest(new ErrorIssues(project, true));\r
+        result = getIssue(graph, IssueResult.Severity.ERROR, errors, component, transform);\r
+        if(result != null) return result;\r
+\r
+        Set<Variable> warnings = graph.syncRequest(new WarningIssues(project, true));\r
+        result = getIssue(graph, IssueResult.Severity.WARNING, warnings, component, transform);\r
+        if(result != null) return result;\r
+\r
+        // No issue was found\r
+        return null;\r
+    }\r
+    \r
+    /**\r
+     * See if a set of issue variables concern this component\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param severity IssueResult.Severity of the issue\r
+     * @param issues Collection of issues of type severity\r
+     * @param component The component that is evaluated for issues\r
+     * @param transform AffineTransform of the diagram element\r
+     * @return IssueResult containing the severity and transform of the issue or null if no issue concerned component\r
+     * @throws DatabaseException\r
+     */\r
+    private IssueResult getIssue(ReadGraph graph, IssueResult.Severity severity, Set<Variable> issues, Resource component, AffineTransform transform) throws DatabaseException {\r
+        IssueResource ISSUE = IssueResource.getInstance(graph);\r
+        Resource list, issueResource;\r
+        for(Variable issue : issues) {\r
+            issueResource = issue.getRepresents(graph);\r
+            list = graph.getPossibleObject(issueResource, ISSUE.Issue_HasContexts);\r
+            List<Resource> contexts = ListUtils.toList(graph, list);\r
+            if(!contexts.isEmpty()) {\r
+                if(ListUtils.toList(graph, list).subList(0, 1).contains(component)) {\r
+                    return new IssueResult(severity, transform);\r
+                }\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void applyStyleForNode(EvaluationContext observer, INode node, IssueResult result) {\r
+        \r
+        // If result == null, remove possible issue decoration\r
+        if (result == null) {\r
+            ProfileVariables.denyChild(node, "", DECORATION_NODE_NAME);\r
+            return;\r
+        }\r
+\r
+        // Create issue decoration node\r
+        SVGNode svgNode = ProfileVariables.claimChild(node, "", DECORATION_NODE_NAME, SVGNode.class, observer);\r
+\r
+        // Move the decoration to the upper right corner of the element\r
+        Rectangle2D bounds = NodeUtil.getLocalBounds(node, Collections.<INode>singleton(svgNode));\r
+        double tx = bounds.getMaxX();\r
+        double ty = bounds.getY();\r
+        svgNode.setZIndex( Integer.MAX_VALUE );\r
+        svgNode.setTransform( AffineTransform.getTranslateInstance(tx-1, ty-1)); \r
+        svgNode.getTransform().scale(0.5, 0.5);\r
+        \r
+\r
+        // Apply the corresponding svg graphics to the node\r
+        IssueResult.Severity sev = result.getSeverity();\r
+        if (IssueResult.Severity.FATAL.equals(sev))\r
+            svgNode.setData(Activator.FATAL_SVG_TEXT);\r
+        else if (IssueResult.Severity.ERROR.equals(sev))\r
+            svgNode.setData(Activator.ERROR_SVG_TEXT);\r
+        else if (IssueResult.Severity.WARNING.equals(sev))\r
+            svgNode.setData(Activator.WARNING_SVG_TEXT);\r
+    }\r
+\r
+    @Override\r
+    protected void cleanupStyleForNode(INode node) {\r
+        ProfileVariables.denyChild(node, "", DECORATION_NODE_NAME);\r
+    }\r
+\r
+}\r
+\r
+/**\r
+ * This is needed to keep the issue decoration up-to-date when its parent\r
+ * element moves.\r
+ */\r
+class IssueResult extends Tuple {\r
+    \r
+    public enum Severity{FATAL, ERROR, WARNING};\r
+    \r
+    public IssueResult(Severity severity, AffineTransform transform) {\r
+        super(severity, transform);\r
+    }\r
+    public Severity getSeverity() {\r
+        return (Severity) getField(0);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/ShadowStyle.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/ShadowStyle.java
new file mode 100644 (file)
index 0000000..5e5f981
--- /dev/null
@@ -0,0 +1,161 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.profiles;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Stroke;\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.diagram.profile.StyleBase;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.scenegraph.INode;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+import org.simantics.scenegraph.g2d.nodes.SingleElementNode;\r
+import org.simantics.scenegraph.profile.EvaluationContext;\r
+import org.simantics.scenegraph.profile.common.ProfileVariables;\r
+import org.simantics.scenegraph.utils.GeometryUtils;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.profiles.ShadowResult.Style;\r
+import org.simantics.utils.datastructures.map.Tuple;\r
+\r
+public class ShadowStyle extends StyleBase<ShadowResult> {\r
+    \r
+    private static String SHADOW_DECORATION_NODE = "SHADOW_DECORATION_NODE";  \r
+    private static Stroke SHADOW_DECORATION_STROKE = new BasicStroke(0.2f);\r
+    \r
+    @Override\r
+    public ShadowResult calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration) throws DatabaseException {\r
+        ModelingResources MOD = ModelingResources.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        AffineTransform transform = DiagramGraphUtil.getAffineTransform(graph, element);\r
+        \r
+        Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);\r
+\r
+        Resource original = graph.getPossibleObject(component, SR.Shadow_original);\r
+        Collection<Resource> shadows = graph.getObjects(component, SR.Shadow_original_Inverse);\r
+        \r
+        for(Resource r : graph.getObjects(runtimeDiagram, SR.ConfigurationDiagram_selection)) {\r
+            Resource selection = graph.getPossibleObject(r, MOD.ElementToComponent);\r
+            if(original != null) {\r
+                Collection<Resource> otherShadows = graph.getObjects(original, SR.Shadow_original_Inverse);\r
+                otherShadows.remove(component);\r
+                if(selection.equals(original) || otherShadows.contains(selection)) {\r
+                    return new ShadowResult(Style.SHADOW, transform);\r
+                }\r
+            }\r
+\r
+            if(shadows.contains(selection)) {\r
+                return new ShadowResult(Style.ORIGINAL, transform);\r
+            }\r
+        }\r
+        \r
+        return new ShadowResult(Style.NONE, transform);\r
+    }\r
+    \r
+    public void applyStyleForNode(EvaluationContext observer, INode _node, ShadowResult result) {\r
+        \r
+        if(result == null || result.getStyle() == Style.NONE) {\r
+            cleanupStyleForNode(_node);\r
+            return;\r
+        }\r
+        // Create a node that will show the style effect\r
+        A node = ProfileVariables.claimChild(_node, "", SHADOW_DECORATION_NODE, A.class, observer);\r
+        if (node == null)\r
+            return;\r
+        \r
+        AffineTransform at = result.getTransform();\r
+\r
+        // Create a node for the style\r
+        INode n = NodeUtil.getNearestChildByClass((SingleElementNode)_node, TextNode.class);\r
+        Rectangle2D expandedElementBounds = GeometryUtils.expandRectangle( NodeUtil.getLocalElementBounds(n), 0.0);\r
+        node.setFill(false);\r
+        node.setColor(result.getStyle() == Style.SHADOW ? Color.BLUE : Color.MAGENTA);\r
+        node.setStroke(SHADOW_DECORATION_STROKE);\r
+        node.setValue("shape", expandedElementBounds);\r
+        node.setTransform(at);\r
+\r
+        // Find z-index for the TextNode associated with the element and place the style node just below that text node \r
+        int zIndex = -1;\r
+        if(n != null) {\r
+            at = ((TextNode)n).getTransform();\r
+            zIndex = ((TextNode)n).getZIndex() - 1;\r
+        } else {\r
+            n = _node;\r
+        }\r
+        node.setZIndex(zIndex);\r
+\r
+    }\r
+\r
+    @Override\r
+    protected void cleanupStyleForNode(INode node) {\r
+        ProfileVariables.denyChild(node, "", SHADOW_DECORATION_NODE);\r
+    }\r
+    \r
+    /**\r
+     * Dummy class for displaying the style\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    public static class A extends ShapeNode {\r
+\r
+        private static final long serialVersionUID = -5273246617906214956L;\r
+\r
+        @Override\r
+        public Rectangle2D getBoundsInLocal() {\r
+            return null;\r
+        }\r
+\r
+        @Override\r
+        public Rectangle2D getBoundsInLocal(boolean b) {\r
+            return null;\r
+        }\r
+\r
+        @Override\r
+        public Rectangle2D getBounds() {\r
+            return null;\r
+        }\r
+\r
+    }\r
+    \r
+}\r
+\r
+/**\r
+ * This is needed to keep the issue decoration up-to-date when its parent\r
+ * element moves.\r
+ */\r
+class ShadowResult extends Tuple {\r
+    \r
+    public enum Style{NONE, ORIGINAL, SHADOW};\r
+    \r
+    public ShadowResult(Style style, AffineTransform transform) {\r
+        super(style, transform);\r
+    }\r
+    public Style getStyle() {\r
+        return (Style) getField(0);\r
+    }\r
+    \r
+    public AffineTransform getTransform() {\r
+        return (AffineTransform) getField(1);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/SimulationPlaybackStyle.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/SimulationPlaybackStyle.java
new file mode 100644 (file)
index 0000000..35516ae
--- /dev/null
@@ -0,0 +1,316 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.elements.profiles;\r
+\r
+import java.awt.geom.AffineTransform;\r
+import java.awt.geom.Rectangle2D;\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.diagram.profile.StyleBase;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.project.IProject;\r
+import org.simantics.scenegraph.INode;\r
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
+import org.simantics.scenegraph.g2d.nodes.SingleElementNode;\r
+import org.simantics.scenegraph.profile.EvaluationContext;\r
+import org.simantics.scenegraph.profile.Observer;\r
+import org.simantics.scenegraph.profile.common.ProfileVariables;\r
+import org.simantics.scenegraph.utils.GeometryUtils;\r
+import org.simantics.scenegraph.utils.NodeUtil;\r
+import org.simantics.scl.runtime.tuple.Tuple2;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.Functions;\r
+import org.simantics.sysdyn.adapter.VariableRVIUtils;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Triple;\r
+import org.simantics.utils.ui.color.Color;\r
+import org.simantics.utils.ui.color.ColorGradient;\r
+import org.simantics.utils.ui.color.ColorValue;\r
+\r
+/**\r
+ * Profile style definition for simulation playback mode. Works only with SimulationPlaybackExperiment\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SimulationPlaybackStyle extends StyleBase<Triple<AffineTransform, Double, ColorGradient>> {\r
+\r
+    Resource gradientResource;\r
+    ColorGradient cg;\r
+    byte[] gradient;\r
+\r
+    /**\r
+     * Determine if style needs to be redrawn and return objects that are needed to redraw the style.\r
+     * \r
+     * @return All necessary components that are needed to draw this style\r
+     */\r
+    @Override\r
+    public Triple<AffineTransform, Double, ColorGradient> calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration) throws DatabaseException {\r
+\r
+        // Find SimulationPlaybackExperiment\r
+        IProject project = SimanticsUI.getProject();\r
+        IExperimentManager em = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = em.getActiveExperiment();\r
+        if(!(experiment instanceof SysdynPlaybackExperiment))\r
+            return null;\r
+\r
+        ModelingResources mr = ModelingResources.getInstance(graph);\r
+        DiagramResource dr = DiagramResource.getInstance(graph);\r
+\r
+        ColorGradient cg = null;\r
+\r
+        Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
+        if (component == null)\r
+            return null;\r
+\r
+        try {\r
+\r
+            // Find Variable for this component\r
+            String dv = graph.getPossibleRelatedValue(runtimeDiagram, dr.RuntimeDiagram_HasVariable);\r
+            Variable rootVariable = graph.getPossibleAdapter(graph.getRootLibrary(), Variable.class);\r
+            if (rootVariable == null) \r
+                return null;\r
+            Variable diagramVariable = rootVariable.browsePossible(graph, dv.substring(6));\r
+            if(diagramVariable == null) \r
+                return null;\r
+\r
+            Variable var = diagramVariable.browsePossible(graph, component);\r
+            if(var == null)\r
+                return null;\r
+\r
+            // Get simulation result values for this component\r
+            // Get values\r
+            Variable dsVariable = var.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
+            Object object = null;\r
+            if(dsVariable != null)\r
+                object = dsVariable.getValue(graph);\r
+            if(object == null || !(object instanceof ArrayList<?>))\r
+                return null;\r
+\r
+            ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
+\r
+            for(Object o : (ArrayList<?>)object) {\r
+                if(o instanceof SysdynDataSet)\r
+                    datasets.add((SysdynDataSet)o);\r
+            }\r
+\r
+            if(datasets.size() == 0)\r
+                return null;\r
+\r
+            if(datasets.size() > 1) {\r
+                String range = datasets.get(0).name.substring(\r
+                        datasets.get(0).name.indexOf('[') + 1,\r
+                        datasets.get(0).name.indexOf(']'));\r
+                int size = range.split(",").length;\r
+                String[] filter = new String[size];\r
+                for(int i = 0; i < size; i++)\r
+                    filter[i] = "Sum";\r
+\r
+                ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);\r
+                if(result2 != null) {\r
+                    datasets = result2;\r
+                }\r
+\r
+            }\r
+\r
+            // The datasets list should always be size == 1\r
+            SysdynDataSet dataset = datasets.get(0);\r
+            \r
+            // Get values (or sum of values)\r
+            double[] va = dataset.values;\r
+            if(va.length < 2)\r
+                return null;\r
+\r
+            // Get simulation timesteps for this component\r
+            double[] ta = dataset.times;\r
+            if(ta == null || ta.length < 2)\r
+                return null;\r
+\r
+            if(va.length == 0 || va.length == 2)\r
+                return null;\r
+\r
+            // Get playback time from the experiment run\r
+            Double time = null;\r
+            if(diagramVariable != null) {\r
+                Variable timeVar = diagramVariable.browsePossible(graph, "#" + Functions.TIME + "#");\r
+                if(timeVar != null)\r
+                    time = timeVar.getValue(graph, Bindings.DOUBLE);\r
+            }\r
+\r
+            if(time == null)\r
+                return null;\r
+\r
+            // Find minimum and maximum values for this variable\r
+            double min = va[0], max = va[0];\r
+            for(double d : va) {\r
+                if(d < min) \r
+                    min = d;\r
+                if(d > max)\r
+                    max = d;\r
+            }\r
+\r
+            // Find the index in time and value arrays for this time \r
+            // (time steps may vary, we need to loop to find the correct time) \r
+            int index = 0;\r
+            if(ta[ta.length - 1] - time > ta[ta.length / 2] ) {\r
+                index = ta.length - 1;\r
+                while(ta[index] > time && index > 0)\r
+                    index--;\r
+            } else {\r
+                while(ta[index] < time && index < ta.length - 1)\r
+                    index++;\r
+            }\r
+\r
+            double value = va[index];\r
+\r
+            // Calculate where the value is located between min and max values [0..1].   \r
+            double multiplier = (value - min) / (max - min);\r
+\r
+\r
+            // Get the transform of this element\r
+            AffineTransform at = (AffineTransform) DiagramGraphUtil.getAffineTransform(graph, element,  G2DResource.getInstance(graph).HasTransform, true).clone();\r
+\r
+            // Find the gradient used to draw this style\r
+            G2DResource g2d = G2DResource.getInstance(graph);\r
+            Resource gradient = graph.getPossibleObject(experiment.getResource(), g2d.HasColorGradient);\r
+            if(this.gradientResource == null || !this.gradientResource.equals(gradient)) {\r
+                ArrayList<ColorValue> colorValues = new ArrayList<ColorValue>();\r
+                for(Resource placement : graph.syncRequest(new ObjectsWithType(gradient, g2d.HasColorPlacement, g2d.ColorPlacement))) {\r
+                    Double position = graph.getPossibleRelatedValue(placement, g2d.HasGradientPosition, Bindings.DOUBLE);\r
+                    Resource rColor = graph.getPossibleObject(placement, g2d.HasColor);\r
+                    if (rColor != null) {\r
+                        colorValues.add(new ColorValue(new Color((java.awt.Color) G2DUtils.getObject(graph, rColor)), position));\r
+                    }\r
+                }\r
+                cg = new ColorGradient(colorValues, ColorGradient.HSV);\r
+            } else {\r
+                cg = this.cg;\r
+            }\r
+\r
+            return new Triple<AffineTransform, Double, ColorGradient>(at, multiplier, cg);\r
+\r
+        } catch(Exception ignore) {\r
+            ignore.printStackTrace();\r
+        }\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void styleResultChanged(Observer observer, Resource runtimeDiagram, Resource element, Triple<AffineTransform, Double, ColorGradient> result) {\r
+        if (result != null)\r
+            values.put(new Tuple2(runtimeDiagram, element), result);\r
+        else\r
+            values.remove(new Tuple2(runtimeDiagram, element));\r
+        observer.update();\r
+    }\r
+\r
+    /**\r
+     * Apply style\r
+     */\r
+    @Override\r
+    public void applyStyleForNode(EvaluationContext observer, INode _node, Triple<AffineTransform, Double, ColorGradient> result) {\r
+        Double multiplier;\r
+        if (result != null && (multiplier = result.second) != null && !multiplier.isNaN()) {\r
+\r
+            // Create a node that will show the style effect\r
+            A node = ProfileVariables.claimChild(_node, "", "playbackColour", A.class, observer);\r
+            if (node == null)\r
+                return;\r
+\r
+            AffineTransform at = result.first;\r
+\r
+            if(this.cg == null || !this.cg.equals(result.third)) {\r
+                this.cg = result.third;\r
+                this.gradient = cg.getGradientArray(101);\r
+            }\r
+\r
+            // Get integer values for red, green and blue\r
+            int i = (int)(multiplier * 100);\r
+            int r = (int)(gradient[i * 3 + 0]  & 0xff);\r
+            int g = (int)(gradient[i * 3 + 1]  & 0xff);\r
+            int b = (int)(gradient[i * 3 + 2]  & 0xff);\r
+            // Get color with r, g and b\r
+            java.awt.Color c = new java.awt.Color(r, g, b, 200);\r
+\r
+            // Create a node for the style\r
+            INode n = NodeUtil.getNearestChildByClass((SingleElementNode)_node, TextNode.class);\r
+            Rectangle2D expandedElementBounds = GeometryUtils.expandRectangle( NodeUtil.getLocalElementBounds(n), 0.0);\r
+            node.setFill(true);\r
+            node.setColor(c);\r
+            node.setStroke(null);\r
+            node.setValue("shape", expandedElementBounds);\r
+            node.setTransform(at);\r
+\r
+            // Find z-index for the TextNode associated with the element and place the style node just below that text node \r
+            int zIndex = -1;\r
+            if(n != null) {\r
+                at = ((TextNode)n).getTransform();\r
+                zIndex = ((TextNode)n).getZIndex() - 1;\r
+            } else {\r
+                n = _node;\r
+            }\r
+            node.setZIndex(zIndex);\r
+\r
+\r
+        } else {\r
+            cleanupStyleForNode(_node);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    protected void cleanupStyleForNode(INode node) {\r
+        ProfileVariables.denyChild(node, "", "playbackColour");\r
+    }\r
+\r
+\r
+    /**\r
+     * Dummy class for displaying the style\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    public static class A extends ShapeNode {\r
+\r
+        private static final long serialVersionUID = -5273246617906214956L;\r
+\r
+        @Override\r
+        public Rectangle2D getBoundsInLocal() {\r
+            return null;\r
+        }\r
+\r
+        @Override\r
+        public Rectangle2D getBoundsInLocal(boolean b) {\r
+            return null;\r
+        }\r
+\r
+        @Override\r
+        public Rectangle2D getBounds() {\r
+            return null;\r
+        }\r
+\r
+    }\r
+}\r
+
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/function/ModulesSearchFunction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/function/ModulesSearchFunction.java
new file mode 100644 (file)
index 0000000..2ef01ae
--- /dev/null
@@ -0,0 +1,158 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.function;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashSet;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.ui.IWorkbenchPage;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.layer0.genericrelation.Dependencies;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.scl.runtime.function.FunctionImpl5;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.handlers.FindSearchTrim;\r
+import org.simantics.sysdyn.ui.handlers.FindSearchTrim.Scope;\r
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
+import org.simantics.workbench.search.NameAndTypeRow;\r
+import org.simantics.workbench.search.NamedResource;\r
+import org.simantics.workbench.search.SearchQuery;\r
+import org.simantics.workbench.search.SearchResult;\r
+import org.simantics.workbench.search.Searching;\r
+\r
+/**\r
+ * modulesSearchFunction:\r
+ *      (IProgressMonitor, ReadGraph, model : Resource, query : String, maxResults : Integer) -> QueryResult\r
+ * \r
+ * @author Tuukka Lehtonen\r
+ * @author Tuomas Miettinen\r
+ */\r
+public class ModulesSearchFunction extends FunctionImpl5<IProgressMonitor, ReadGraph, Resource, SearchQuery, Integer, SearchResult> {\r
+\r
+       private final int MAX_RESULTS = 50000;\r
+       \r
+    @Override\r
+    public SearchResult apply(IProgressMonitor monitor, ReadGraph graph, Resource model, SearchQuery query, Integer maxResults) {\r
+        try {\r
+               String origQuery = query.getOriginalQuery();\r
+               SearchQuery wildcardedQuery;\r
+               if (!origQuery.isEmpty()) // Add asterisks for performSearch \r
+                       wildcardedQuery = query.withOriginalQuery("*" + origQuery + "*");\r
+               else\r
+                       wildcardedQuery = query.withOriginalQuery("*");\r
+               \r
+               String filteredQuery = wildcardedQuery.escaped(false).getQuery("Name","Types");\r
+               Collection<Map<String, Object>> results = Searching.performSearch(graph, \r
+                               Layer0X.getInstance(graph).Dependencies, \r
+                               model, \r
+                               filteredQuery, \r
+                               MAX_RESULTS);\r
+\r
+               // Check whether only currently open diagram is searched\r
+               if (!query.getSearchParams().contains(FindSearchTrim.CURRENT_DIAGRAM_OPTION))\r
+               return generateSearchResults(graph, results, Scope.ALL_MODELS);\r
+               else\r
+                       return generateSearchResults(graph, results, Scope.CURRENT_DIAGRAM);\r
+        } catch (DatabaseException e) {\r
+            Logger.defaultLogError(e);\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    private static boolean resourceFoundInCurrentDiagram(ReadGraph graph, Resource diagram) throws ManyObjectsForFunctionalRelationException, ServiceException {\r
+\r
+       IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();\r
+       DiagramEditor editor = (DiagramEditor)page.getActiveEditor();\r
+       if (editor != null) {\r
+               Resource inputResource = editor.getInputResource();\r
+               ModelingResources MOD = ModelingResources.getInstance(graph);\r
+               Resource editorResource = graph.getPossibleObject(inputResource, MOD.DiagramToComposite);\r
+               if (diagram.equalsResource(editorResource)) \r
+                       return true;\r
+        }\r
+        return false;\r
+    }\r
+\r
+    private static final SearchResult generateSearchResults(ReadGraph graph,\r
+            Collection<Map<String, Object>> results, Scope scope) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        DiagramResource DIA = DiagramResource.getInstance(graph);\r
+        SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+\r
+        SearchResult result = new SearchResult(NameAndTypeRow.columns);\r
+        Set<Resource> processed = new HashSet<Resource>();\r
+\r
+        for (Map<String, Object> r : results) {\r
+            Resource resource = (Resource) r.get(Dependencies.FIELD_RESOURCE);\r
+\r
+            // Only Auxiliary, Stock, Valve, Input, and Module \r
+            if (!(graph.isInstanceOf(resource, SYSDYN.IndependentVariable)\r
+                       || graph.isInstanceOf(resource, SYSDYN.Input)\r
+                       || graph.isInstanceOf(resource, SYSDYN.Module)))\r
+                continue;\r
+\r
+            // Prevent index corruption from producing duplicate results.\r
+            if (!processed.add(resource))\r
+                continue;\r
+\r
+            // Prevent diagram elements from being collected into the results.\r
+            Collection<Resource> typeResources = graph.getTypes(resource);\r
+            if (typeResources.contains(DIA.Element))\r
+                continue;\r
+\r
+            // Check if the result is found in the open diagram.  \r
+            Resource parent = (Resource) r.get(Dependencies.FIELD_PARENT);\r
+            if (scope == Scope.CURRENT_DIAGRAM &&\r
+                       !resourceFoundInCurrentDiagram(graph, parent))\r
+               continue;\r
+            \r
+            String name = (String) r.get(Dependencies.FIELD_NAME);\r
+            NameAndTypeRow rst = new NameAndTypeRow();\r
+            rst.resource = NamedResource.of(graph, resource, name);\r
+            rst.parent = NamedResource.of(graph, parent);\r
+\r
+            Collection<Resource> principalTypeResources = graph.getPrincipalTypes(resource);\r
+            if (!typeResources.isEmpty()) {\r
+                rst.types = new ArrayList<NamedResource>(typeResources.size());\r
+                rst.principalTypes = new ArrayList<NamedResource>(principalTypeResources.size());\r
+                for (Resource t : typeResources) {\r
+                    String typeName = graph.getPossibleRelatedValue(t, L0.HasName, Bindings.STRING);\r
+                    if (typeName == null)\r
+                        typeName = NameUtils.getSafeLabel(graph, t);\r
+                    NamedResource nr = NamedResource.of(graph, t, typeName);\r
+                    rst.types.add(nr);\r
+                    if (principalTypeResources.contains(t))\r
+                        rst.principalTypes.add(nr);\r
+                }\r
+            }\r
+  \r
+            result.addRow(rst);\r
+        }\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/AssignIC.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/AssignIC.java
new file mode 100644 (file)
index 0000000..a84ec55
--- /dev/null
@@ -0,0 +1,120 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.dialogs.IDialogSettings;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.window.Window;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.ResourceRead;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.Activator;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.ui.workbench.dialogs.ResourceSelectionDialog3;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class AssignIC extends AbstractHandler {\r
+\r
+       private Resource query(Resource experiment) throws DatabaseException {\r
+\r
+        Map<Resource, Pair<String, ImageDescriptor>> map = Simantics.getSession().syncRequest(new ResourceRead<Map<Resource, Pair<String, ImageDescriptor>>>(experiment) {\r
+\r
+                       @Override\r
+                       public Map<Resource, Pair<String, ImageDescriptor>> perform(ReadGraph graph) throws DatabaseException {\r
+                               Map<Resource, Pair<String, ImageDescriptor>> result = new HashMap<Resource, Pair<String, ImageDescriptor>>();\r
+                               Layer0 L0 = Layer0.getInstance(graph);\r
+                       SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+                               Resource model = graph.syncRequest(new PossibleModel(resource));\r
+                               for(Resource r : graph.syncRequest(new ObjectsWithType(model, L0.ConsistsOf, SYSDYN.InitialCondition))) {\r
+                                       String name = NameUtils.getSafeName(graph, r);\r
+                                       result.put(r, new Pair<String, ImageDescriptor>(name, null));\r
+                               }\r
+                               return result;\r
+                       }\r
+               \r
+        });\r
+        \r
+        Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
+        ResourceSelectionDialog3<Resource> dialog = new ResourceSelectionDialog3<Resource>(shell, map, "Select connection point type") {\r
+               @Override\r
+               protected IDialogSettings getBaseDialogSettings() {\r
+                       return Activator.getDefault().getDialogSettings();\r
+               }\r
+        };\r
+        if (dialog.open() == Window.OK) {\r
+               Object[] result = dialog.getResult();\r
+               if (result != null && result.length == 1) {\r
+                       final Resource res = (Resource)result[0];\r
+                       return res;\r
+               }\r
+        }\r
+        \r
+        return null;\r
+\r
+       }\r
+       \r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+       \r
+               ISelection selection = HandlerUtil.getCurrentSelection(event);\r
+        final Resource experiment = ResourceAdaptionUtils.toSingleResource(selection);\r
+        if (experiment == null)\r
+            return null;\r
+\r
+        try {\r
+\r
+               final Resource ic = query(experiment);\r
+               if(ic == null)\r
+                       return null;\r
+\r
+               Simantics.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+\r
+                               SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+\r
+                               graph.deny(experiment, SYSDYN.Experiment_ic);\r
+                               graph.claim(experiment, SYSDYN.Experiment_ic, ic);\r
+\r
+                       }\r
+\r
+               });\r
+\r
+        } catch (DatabaseException e) {\r
+\r
+        }\r
+\r
+        return null;\r
+        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ChartPanelOrientationHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ChartPanelOrientationHandler.java
new file mode 100644 (file)
index 0000000..2d32ce8
--- /dev/null
@@ -0,0 +1,100 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.dialogs.IDialogSettings;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.ui.IWorkbenchPart;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.commands.ICommandService;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.jfreechart.ChartPanel;\r
+import org.simantics.sysdyn.ui.Activator;\r
+\r
+/**\r
+ * This handler changes the orientation of a {@link ChartPanel}\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ChartPanelOrientationHandler extends AbstractHandler implements IElementUpdater {\r
+\r
+    private static String COMMAND = "org.simantics.sysdyn.ui.chartPanelOrientation";\r
+    \r
+    /**\r
+     * Read chart panel settings from IDialogSettings and change the orientation accordingly.\r
+     * Finally order the element to update its appearance.\r
+     */\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        IWorkbenchPart part = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getActivePart();\r
+        if(part instanceof ChartPanel) {\r
+            IDialogSettings settings = Activator.getDefault().getDialogSettings().getSection(ChartPanel.CHART_PANEL_SETTINGS);\r
+            if (settings == null) {\r
+                settings = Activator.getDefault().getDialogSettings().addNewSection(ChartPanel.CHART_PANEL_SETTINGS);\r
+            }\r
+            \r
+            String orientation = settings.get(ChartPanel.CHART_PANEL_ORIENTATION);\r
+            if(orientation == null)\r
+                settings.put(ChartPanel.CHART_PANEL_ORIENTATION, ChartPanel.CHART_PANEL_HORIZONTAL);\r
+            \r
+            if(ChartPanel.CHART_PANEL_VERTICAL.equals(orientation))\r
+                orientation = ChartPanel.CHART_PANEL_HORIZONTAL;\r
+            else\r
+                orientation = ChartPanel.CHART_PANEL_VERTICAL;\r
+            \r
+            settings.put(ChartPanel.CHART_PANEL_ORIENTATION, orientation);\r
+            ((ChartPanel)part).setOrientation(orientation);\r
+            \r
+            ICommandService commandService =\r
+                    (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+            commandService.refreshElements(COMMAND, null);\r
+        }\r
+\r
+        return null;\r
+    }\r
+\r
+    /**\r
+     * Update the icon of the element. The new icon and text are always opposite to the current situation.\r
+     */\r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public void updateElement(UIElement element, Map parameters) {\r
+        if(parameters == null)\r
+            return;\r
+        \r
+        IDialogSettings settings = Activator.getDefault().getDialogSettings().getSection(ChartPanel.CHART_PANEL_SETTINGS);\r
+        if(settings == null)\r
+            return;\r
+        \r
+        String orientation = settings.get(ChartPanel.CHART_PANEL_ORIENTATION);\r
+        if(orientation == null)\r
+            return;\r
+        \r
+        // Show the opposite icon and text to indicate change when the button is pressed\r
+        if(ChartPanel.CHART_PANEL_HORIZONTAL.equals(orientation)) {\r
+            element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/page_white_text.png")));\r
+            element.setTooltip("Vertical Orientation");\r
+        } else if (ChartPanel.CHART_PANEL_VERTICAL.equals(orientation)) {\r
+            element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/page_white_text_width.png")));\r
+            element.setTooltip("Horizontal Orientation");\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DiagramToolHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DiagramToolHandler.java
new file mode 100644 (file)
index 0000000..7f4a251
--- /dev/null
@@ -0,0 +1,67 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.eclipse.ui.handlers.RadioState;\r
+import org.simantics.g2d.canvas.Hints;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.canvas.IToolMode;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementHints;\r
+import org.simantics.utils.threads.ThreadUtils;\r
+\r
+public class DiagramToolHandler extends AbstractHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+               final ICanvasContext context = (ICanvasContext)HandlerUtil.getActiveEditor(event).getAdapter(ICanvasContext.class);\r
+               if (context == null) {\r
+                       throw new ExecutionException("Could not get context from editor");\r
+               }\r
+\r
+               String value = (String)event.getCommand().getState(RadioState.STATE_ID).getValue();\r
+               \r
+               final IToolMode mode;\r
+               if ("pointer".equals(value)) {\r
+                       mode = Hints.POINTERTOOL;\r
+               }\r
+               else if ("dependency".equals(value)) {\r
+                       mode = SysdynElementHints.DEPENDENCY_TOOL;\r
+               }\r
+               else if ("flow".equals(value)) {\r
+                       mode = SysdynElementHints.FLOW_TOOL;\r
+               }\r
+               else if ("lock".equals(value)) {\r
+                       mode = SysdynElementHints.LOCK_TOOL;\r
+               }\r
+               else {\r
+                       return null;\r
+               }\r
+               \r
+               ThreadUtils.syncExec(context.getThreadAccess(), new Runnable() {\r
+                       @Override\r
+                       public void run() {\r
+                               if (mode.equals(SysdynElementHints.DEPENDENCY_TOOL) \r
+                                               || mode.equals(SysdynElementHints.FLOW_TOOL)) {\r
+                                       // if one of the connection modes is selected, use the\r
+                                       // default connection tool as the base and indicate the\r
+                                       // desired connection type in another hint (this is done\r
+                                       // to make sure all features of the connection tool work\r
+                                       // as expected)\r
+                                       context.getDefaultHintContext().setHint(Hints.KEY_TOOL, Hints.CONNECTTOOL);\r
+                                       context.getDefaultHintContext().setHint(SysdynElementHints.SYSDYN_KEY_TOOL, mode);\r
+                               } else if (mode.equals(SysdynElementHints.LOCK_TOOL)) {\r
+                                       context.getDefaultHintContext().setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);\r
+                                       context.getDefaultHintContext().setHint(SysdynElementHints.SYSDYN_KEY_TOOL, mode);\r
+                               } else {\r
+                                       context.getDefaultHintContext().setHint(Hints.KEY_TOOL, mode);\r
+                                       context.getDefaultHintContext().removeHint(SysdynElementHints.SYSDYN_KEY_TOOL);\r
+                               }\r
+                       }\r
+               });\r
+               \r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DisposeExperiment.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DisposeExperiment.java
new file mode 100644 (file)
index 0000000..45c3ef9
--- /dev/null
@@ -0,0 +1,38 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class DisposeExperiment extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+        \r
+        IProject project = SimanticsUI.getProject();\r
+        IExperimentManager manager = \r
+            project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if (experiment != null)\r
+            experiment.shutdown(null);\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/EnumerationPasteHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/EnumerationPasteHandler.java
new file mode 100644 (file)
index 0000000..a37cb37
--- /dev/null
@@ -0,0 +1,29 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+\r
+public class EnumerationPasteHandler extends AbstractHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+               System.out.println("PASTE " + sel);\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExportSharedOntologyHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExportSharedOntologyHandler.java
new file mode 100644 (file)
index 0000000..5e29611
--- /dev/null
@@ -0,0 +1,32 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.modeling.ModelingUtils;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class ExportSharedOntologyHandler  extends AbstractHandler {\r
+\r
+    /**\r
+     * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource\r
+     */\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+               SharedOntologyNode node = AdaptionUtils.adaptToSingle(sel, SharedOntologyNode.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        ModelingUtils.exportSharedOntologyWithUI(node.data);\r
+\r
+        return null;\r
+        \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExtendedCopyPasteHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ExtendedCopyPasteHandler.java
new file mode 100644 (file)
index 0000000..1295e08
--- /dev/null
@@ -0,0 +1,97 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.Set;\r
+\r
+import org.eclipse.jface.action.IStatusLineManager;\r
+import org.simantics.diagram.elements.TextElementNoBounds;\r
+import org.simantics.diagram.elements.TextNode;\r
+import org.simantics.diagram.handler.CopyPasteHandler;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;\r
+import org.simantics.g2d.diagram.participant.Selection;\r
+import org.simantics.g2d.element.IElement;\r
+import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;\r
+import org.simantics.scenegraph.g2d.events.command.CommandEvent;\r
+import org.simantics.scenegraph.g2d.events.command.Commands;\r
+import org.simantics.sysdyn.ui.editor.participant.SysdynCopyPasteStrategy;\r
+\r
+/**\r
+ * ExtendedCopyPasteHandler is a canvas handler for Commands.CUT, Commands.COPY,\r
+ * Commands.PASTE, and Commands.RENAME commands for an IDiagram.\r
+ * \r
+ * <p>\r
+ * The handler attempts to copy/paste the current selection for pointer 0,\r
+ * meaning {@link Selection#SELECTION0}.\r
+ * </p>\r
+ * \r
+ * <p>\r
+ * The handler logic follows the specifications at <a\r
+ * href="http://www.simantics.org/wiki/index.php/UC:Copy_Item" >UC:Copy Item</a>\r
+ * and <a href="http://www.simantics.org/wiki/index.php/UC:Cut_Item" >UC:Cut\r
+ * Item</a>.\r
+ * </p>\r
+ * \r
+ * @see Selection current diagram selection source\r
+ * \r
+ * @author Tuomas Miettinen\r
+ * \r
+ */\r
+public class ExtendedCopyPasteHandler extends CopyPasteHandler {\r
+\r
+    @Dependency\r
+    private Selection sel;\r
+    \r
+    public ExtendedCopyPasteHandler(IStatusLineManager statusLine) {\r
+        super(new SysdynCopyPasteStrategy(), statusLine);\r
+    }\r
+       \r
+    @EventHandler(priority = 0)\r
+    public boolean handleCommand(CommandEvent e) {\r
+        if (e.command.equals( Commands.RENAME) ) {\r
+            initiateRename(e);\r
+            return true;\r
+        }\r
+        else return super.handleCommand(e);\r
+    }\r
+\r
+       private boolean initiateRename(CommandEvent e) {\r
+        int selectionId = 0;        \r
+        Set<IElement> ss = sel.getSelection(selectionId);\r
+\r
+        ICanvasContext ctx = getContext();\r
+        if (ctx == null)\r
+            return false;\r
+        IElement ie = null;\r
+        TextNode node = null;\r
+        \r
+        //If multiple selected, just pick one\r
+        for (IElement temp : ss){\r
+               if (temp != null) {\r
+                       node = (TextNode)temp.getHint(TextElementNoBounds.SG_NODE);\r
+                       if (node != null){\r
+                               ie = temp;\r
+                               break;\r
+                       }\r
+               }\r
+        }\r
+        if (ie != null) {\r
+                       if (node != null && Boolean.TRUE.equals(node.setEditMode(true))) {\r
+                node.activateEdit(0, ie, ctx);\r
+                node.repaint();\r
+                return true;\r
+                       }\r
+        }\r
+        return false;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindReplaceDialog.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindReplaceDialog.java
new file mode 100644 (file)
index 0000000..f467523
--- /dev/null
@@ -0,0 +1,107 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.jface.dialogs.Dialog;\r
+import org.eclipse.jface.dialogs.IDialogConstants;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.simantics.sysdyn.ui.handlers.FindSearchTrim.Scope;\r
+\r
+/**\r
+ * Find dialog for finding variables in diagrams.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class FindReplaceDialog extends Dialog {\r
+    \r
+    private FindSearchTrim search;\r
+    \r
+    private Button scopeButtonAllModels; \r
+    private Button scopeButtonCurrentDiagram; \r
+    private Scope scope;\r
+    private boolean diagramOpen;\r
+    \r
+    protected FindReplaceDialog(Shell parentShell, Scope scope, boolean diagramOpen) {\r
+        super(parentShell);\r
+               setBlockOnOpen(false);\r
+               this.scope = scope; \r
+               this.diagramOpen = diagramOpen;\r
+    }\r
+\r
+    @Override\r
+       protected boolean isResizable() {\r
+               return true;\r
+       }\r
+    \r
+    @Override\r
+    protected Control createDialogArea(Composite parent) {\r
+        Composite composite = ( Composite )super.createDialogArea(parent);\r
+        composite.getShell().setText("Find");\r
+        GridLayoutFactory.fillDefaults().margins(5, 5).numColumns(2).applyTo(composite);\r
+        \r
+        Label label = new Label(composite, SWT.NONE);\r
+        label.setText("Find: ");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).hint(40, SWT.DEFAULT).applyTo(label);\r
+\r
+        search = new FindSearchTrim(composite);\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(search);\r
+        \r
+        Group scopeGroup = new Group(composite, SWT.SHADOW_NONE);\r
+        scopeGroup.setText("Scope");\r
+        GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(scopeGroup);\r
+        GridLayoutFactory.fillDefaults().margins(5, 5).applyTo(scopeGroup);\r
+        \r
+        Composite scopeComposite = new Composite(scopeGroup, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(scopeComposite);\r
+        GridLayoutFactory.fillDefaults().applyTo(scopeComposite);\r
+        \r
+        scopeButtonCurrentDiagram = new Button(scopeComposite, SWT.RADIO);\r
+        scopeButtonCurrentDiagram.setText("Current Diagram");\r
+        scopeButtonCurrentDiagram.setSelection(scope == Scope.CURRENT_DIAGRAM);\r
+        scopeButtonCurrentDiagram.setEnabled(diagramOpen);\r
+        GridDataFactory.fillDefaults().applyTo(scopeButtonCurrentDiagram);\r
+        \r
+        scopeButtonAllModels = new Button(scopeComposite, SWT.RADIO);\r
+        scopeButtonAllModels.setText("All Models");\r
+        scopeButtonAllModels.setSelection(scope == Scope.ALL_MODELS);\r
+        GridDataFactory.fillDefaults().applyTo(scopeButtonAllModels);\r
+\r
+        return composite;\r
+    }\r
+    \r
+    @Override\r
+    protected void createButtonsForButtonBar(Composite parent) {\r
+        // Replace "OK" with "Find".\r
+               createButton(parent, IDialogConstants.OK_ID, "Find",\r
+                               true);\r
+               createButton(parent, IDialogConstants.CANCEL_ID,\r
+                               "Close", false);\r
+    }\r
+\r
+    @Override\r
+    protected void cancelPressed() {\r
+        setReturnCode(CANCEL);\r
+        close();\r
+    }\r
+\r
+    @Override\r
+    protected void okPressed() {\r
+        if (scopeButtonAllModels.getSelection())\r
+               scope = Scope.ALL_MODELS;\r
+        else if (scopeButtonCurrentDiagram.getSelection())\r
+               scope = Scope.CURRENT_DIAGRAM;\r
+        else\r
+               scope = Scope.ALL_MODELS;\r
+        search.findNameAndTypeQuery(scope);\r
+        setReturnCode(OK);\r
+        close();\r
+    }\r
+\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindReplaceHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindReplaceHandler.java
new file mode 100644 (file)
index 0000000..5239aec
--- /dev/null
@@ -0,0 +1,61 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.IEditorPart;\r
+import org.eclipse.ui.IWorkbenchPart;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.sysdyn.ui.browser.SysdynBrowser;\r
+import org.simantics.sysdyn.ui.editor.DiagramViewer;\r
+import org.simantics.sysdyn.ui.handlers.FindSearchTrim.Scope;\r
+\r
+/**\r
+ * Handler for Ctrl+F\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class FindReplaceHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        \r
+        IEditorPart editor = (IEditorPart)HandlerUtil.getActiveEditor(event);\r
+        IWorkbenchPart workbenchPart = (IWorkbenchPart)HandlerUtil.getActivePart(event); \r
+        \r
+        Shell shell = HandlerUtil.getActiveShell(event);\r
+        if(shell == null)\r
+            return null;\r
+        \r
+        // If there is something else in the diagram view, do not allow search in current diagram\r
+        if (!(editor instanceof DiagramEditor) || !(((DiagramEditor) editor).getViewer() instanceof DiagramViewer)) {\r
+            if (workbenchPart != null && workbenchPart instanceof SysdynBrowser) {\r
+               // If focus is on model browser, allow search in all models.\r
+                FindReplaceDialog dialog = new FindReplaceDialog(shell, Scope.ALL_MODELS, false);\r
+                dialog.open();\r
+            }\r
+            return null;\r
+        }\r
+        \r
+        final DiagramViewer viewer = (DiagramViewer) ((DiagramEditor) editor).getViewer();\r
+        if (viewer == null)\r
+            return null;\r
+        \r
+        Object d = viewer.getAdapter(IDiagram.class);\r
+        if (workbenchPart != null && workbenchPart instanceof SysdynBrowser) {\r
+               // If focus is on model browser, default search in all models, allow also current diagram.\r
+            FindReplaceDialog dialog = new FindReplaceDialog(shell, Scope.ALL_MODELS, true);\r
+            dialog.open();\r
+        } else if (d != null && d instanceof IDiagram && workbenchPart instanceof DiagramEditor) {\r
+               // If focus is on diagram editor, default search in current diagram, allow also all models.\r
+            FindReplaceDialog dialog = new FindReplaceDialog(shell, Scope.CURRENT_DIAGRAM, true);\r
+            dialog.open();\r
+        }\r
+\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindSearchTrim.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/FindSearchTrim.java
new file mode 100644 (file)
index 0000000..502410c
--- /dev/null
@@ -0,0 +1,49 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.workbench.internal.contributions.search.SearchTrim;\r
+import org.simantics.workbench.search.ISearchService;\r
+import org.simantics.workbench.search.SearchQuery;\r
+\r
+public class FindSearchTrim extends SearchTrim {\r
+       \r
+       public static enum Scope {\r
+               CURRENT_DIAGRAM,\r
+               ALL_MODELS\r
+       }\r
+       \r
+       public static final String CURRENT_DIAGRAM_OPTION = "@Current_diagram";\r
+       \r
+       public FindSearchTrim(Composite parent) {\r
+               super(parent);\r
+        GridDataFactory.fillDefaults().hint(160, SWT.DEFAULT).grab(true, true).applyTo(searchText);\r
+       }\r
+\r
+       public void findNameAndTypeQuery(Scope scope) {\r
+        \r
+           String originalQuery = searchText.getText();\r
+           String query = originalQuery;\r
+\r
+        // Don't allow empty queries\r
+        if (query.trim().isEmpty())\r
+            return;\r
+\r
+//        query = filter(query);\r
+//        query = "Name:" + query + " OR Types:" + query;\r
+        \r
+        // Add option for showing only findings in currently open diagram\r
+//        if (scope == Scope.CURRENT_DIAGRAM)\r
+//             query += " " + CURRENT_DIAGRAM_OPTION;\r
+//        SearchQuery searchQuery = new SearchQuery(originalQuery,query);\r
+        SearchQuery searchQuery = new SearchQuery(originalQuery);\r
+        searchQuery.setSearchFlag("Name", "on");\r
+        searchQuery.setSearchFlag("Types", "on");\r
+        if (scope == Scope.CURRENT_DIAGRAM)\r
+               searchQuery.setSearchParam(CURRENT_DIAGRAM_OPTION);\r
+        performQuery(searchQuery, ISearchService.ResultBrowser.VIEW);\r
+        \r
+       }       \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java
new file mode 100644 (file)
index 0000000..f77b693
--- /dev/null
@@ -0,0 +1,51 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.annotation.ui.AnnotationUtils;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class NewAnnotationTypeHandler  extends AbstractHandler {\r
+\r
+    /**\r
+     * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource\r
+     */\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+               Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
+        if(res == null) {\r
+               @SuppressWarnings("unchecked")\r
+                       AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
+               if (node == null)\r
+                       return null;\r
+               res = node.data;\r
+        }\r
+\r
+        final Resource parent = res;\r
+        \r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+               \r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                AnnotationUtils.newAnnotationType(graph, parent);\r
+            }\r
+            \r
+        });\r
+        \r
+        return null;\r
+        \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationValueHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationValueHandler.java
new file mode 100644 (file)
index 0000000..e8f757e
--- /dev/null
@@ -0,0 +1,45 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.Simantics;\r
+import org.simantics.annotation.ui.AnnotationUtils;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.PossibleIndexRoot;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class NewAnnotationValueHandler  extends AbstractHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+               Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
+        if(res == null) {\r
+               @SuppressWarnings("unchecked")\r
+                       AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
+               if (node == null)\r
+                       return null;\r
+               res = node.data;\r
+        }\r
+\r
+        final Resource parent = res;\r
+               try {\r
+                       Resource model = Simantics.getSession().syncRequest(new PossibleIndexRoot(parent));\r
+                       if(model == null) return null;\r
+               AnnotationUtils.newAnnotationInstance(parent, model);\r
+               } catch (DatabaseException e) {\r
+                       throw new ExecutionException(e.getMessage());\r
+               }\r
+        \r
+        return null;\r
+        \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java
new file mode 100644 (file)
index 0000000..0f20af7
--- /dev/null
@@ -0,0 +1,48 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.modeling.ui.actions.NewLibrary;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class NewLibraryHandler  extends AbstractHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+               Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
+        if(res == null) {\r
+               @SuppressWarnings("unchecked")\r
+                       AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
+               if (node == null)\r
+                       return null;\r
+               res = node.data;\r
+        }\r
+\r
+        final Resource parent = res;\r
+        \r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+               \r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                       NewLibrary.createLibrary(graph, parent);\r
+            }\r
+            \r
+        });\r
+        \r
+        return null;\r
+        \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewSCLModuleHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewSCLModuleHandler.java
new file mode 100644 (file)
index 0000000..a026c31
--- /dev/null
@@ -0,0 +1,47 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.modeling.ModelingUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class NewSCLModuleHandler  extends AbstractHandler {\r
+\r
+    /**\r
+     * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource\r
+     */\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+        @SuppressWarnings("unchecked")\r
+               AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        final Resource parent = node.data;\r
+        \r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+               \r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+               ModelingUtils.createSCLModuleDefault(graph, parent);\r
+            }\r
+            \r
+        });\r
+        \r
+        return null;\r
+        \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/PasteSpecialDialog.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/PasteSpecialDialog.java
new file mode 100644 (file)
index 0000000..a593b18
--- /dev/null
@@ -0,0 +1,85 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.jface.dialogs.Dialog;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+\r
+/**\r
+ * Paste special dialog for copying variables in diagram. Default method is to add a number to the end of the variable name.\r
+ * Special paste enables users to define their own prefix and/or suffix to the copied variable name(s). \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PasteSpecialDialog extends Dialog {\r
+\r
+    private Text prefixText, suffixText;\r
+    private String prefix, suffix;\r
+    \r
+    protected PasteSpecialDialog(Shell parentShell) {\r
+        super(parentShell);\r
+    }\r
+\r
+    @Override\r
+    protected Control createDialogArea(Composite parent) {\r
+        Composite composite = ( Composite )super.createDialogArea(parent);\r
+        composite.getShell().setText("Paste Special");\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
+        \r
+        Label label = new Label(composite, SWT.NONE);\r
+        label.setText("Prefix will be added to the beginning of\nthe copied variables, suffix to the end.");\r
+        GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(label);\r
+        \r
+\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Prefix: ");\r
+        label.setToolTipText("Text added to the beginning of a copied variable name");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+        \r
+        prefixText = new Text(composite, SWT.BORDER);\r
+        prefixText.setToolTipText("Text added to the beginning of a copied variable name");\r
+        GridDataFactory.fillDefaults().applyTo(prefixText);\r
+        \r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Suffix: ");\r
+        label.setToolTipText("Text added to the end of a copied variable name");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+        \r
+        suffixText = new Text(composite, SWT.BORDER);\r
+        suffixText.setToolTipText("Text added to the end of a copied variable name");\r
+        GridDataFactory.fillDefaults().applyTo(suffixText);\r
+        \r
+        return composite;\r
+    }\r
+    \r
+    public String getPrefix() {\r
+        return prefix;\r
+    }\r
+\r
+    public String getSuffix() {\r
+        return suffix;\r
+    }\r
+\r
+    @Override\r
+    protected void cancelPressed() {\r
+        prefix = "";\r
+        suffix = "";\r
+        setReturnCode(CANCEL);\r
+        close();\r
+    }\r
+\r
+    @Override\r
+    protected void okPressed() {\r
+        prefix = prefixText.getText();\r
+        suffix = suffixText.getText();\r
+        setReturnCode(OK);\r
+        close();\r
+    }\r
+\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/PasteSpecialHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/PasteSpecialHandler.java
new file mode 100644 (file)
index 0000000..9ed9bde
--- /dev/null
@@ -0,0 +1,86 @@
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.window.Window;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.IEditorPart;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.layer0.util.ClipboardUtils;\r
+import org.simantics.db.layer0.util.SimanticsClipboard.Representation;\r
+import org.simantics.diagram.handler.CopyPasteHandler;\r
+import org.simantics.diagram.handler.DiagramSelection;\r
+import org.simantics.diagram.handler.DiagramSelectionRepresentation;\r
+import org.simantics.diagram.synchronization.SynchronizationHints;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.diagram.IDiagram;\r
+import org.simantics.modeling.mapping.ElementCopyAdvisor;\r
+import org.simantics.modeling.mapping.MappedElementCopyAdvisor;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.scenegraph.g2d.events.command.Commands;\r
+import org.simantics.sysdyn.ui.editor.DiagramViewer;\r
+import org.simantics.sysdyn.ui.editor.participant.SysdynSpecialComponentCopyAdvisor;\r
+\r
+/**\r
+ * Handler for copying variables with custom prefix and/or suffix\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PasteSpecialHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        \r
+        IEditorPart editor = (IEditorPart)HandlerUtil.getActiveEditor(event);\r
+        if (!(editor instanceof DiagramEditor))\r
+            return null;\r
+        final DiagramViewer viewer = (DiagramViewer) ((DiagramEditor) editor).getViewer();\r
+        if (viewer == null)\r
+            return null;\r
+\r
+        Object d = viewer.getAdapter(IDiagram.class);\r
+        if(d != null && d instanceof IDiagram) {\r
+            IDiagram diagram = (IDiagram) d;\r
+            MappedElementCopyAdvisor standardCopyAdvisor = diagram.getHint(SynchronizationHints.COPY_ADVISOR);\r
+\r
+            Shell shell = viewer.getComposite().getShell();\r
+            if(shell == null)\r
+                return null;\r
+            \r
+            PasteSpecialDialog dialog = new PasteSpecialDialog(shell);\r
+            if(dialog.open() == Window.CANCEL)\r
+                return null;\r
+            \r
+            String prefix = dialog.getPrefix();\r
+            String suffix = dialog.getSuffix();\r
+            \r
+            diagram.setHint(SynchronizationHints.COPY_ADVISOR, new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new SysdynSpecialComponentCopyAdvisor(prefix, suffix)));\r
+\r
+            Object v = viewer.getAdapter(ICanvasContext.class);\r
+            if(v != null && v instanceof ICanvasContext) {\r
+                ICanvasContext ctx = (ICanvasContext) v;\r
+                CopyPasteHandler handler = ctx.getAtMostOneItemOfClass(CopyPasteHandler.class);\r
+                if(handler != null) {\r
+                    handler.paste(Commands.PASTE, getClipboardDiagramSelection());\r
+                }\r
+            }\r
+\r
+            diagram.setHint(SynchronizationHints.COPY_ADVISOR, standardCopyAdvisor);\r
+\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    public DiagramSelection getClipboardDiagramSelection() {\r
+        for (Set<Representation> content : Simantics.getClipboard().getContents()) {\r
+            DiagramSelection sel = ClipboardUtils.accept(content, DiagramSelectionRepresentation.KEY_DIAGRAM_SELECTION);\r
+            if (sel != null)\r
+                return sel;\r
+        }\r
+        return DiagramSelection.EMPTY;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RemoveNodeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RemoveNodeHandler.java
new file mode 100644 (file)
index 0000000..e2ee366
--- /dev/null
@@ -0,0 +1,67 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.CancelTransactionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class RemoveNodeHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        Resource[] resources = ResourceAdaptionUtils.toResources(sel);\r
+        if (resources.length == 0)\r
+            return null;\r
+\r
+        MessageDialog dialog = new MessageDialog(shell, "Remove Item", null, "Are you sure?", 0,\r
+                new String[] { "OK", "Cancel" }, 0);\r
+        dialog.create();\r
+        if (dialog.open() == 0)\r
+            deleteItem(resources);\r
+\r
+        return null;\r
+    }\r
+\r
+    public static void deleteItem(final Resource[] resources) {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
+                    for (Resource r : resources)\r
+                        RemoverUtil.remove(graph, r);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+        }\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RenameNodeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RenameNodeHandler.java
new file mode 100644 (file)
index 0000000..4cb78c8
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.IWorkbenchPart;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.browsing.ui.GraphExplorer;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+public class RenameNodeHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        NodeContext ctx = ISelectionUtils.filterSingleSelection(sel, NodeContext.class);\r
+        if (ctx == null)\r
+            return null;\r
+\r
+        IWorkbenchPart part = HandlerUtil.getActivePart(event);\r
+        if (part == null)\r
+            return null;\r
+\r
+        GraphExplorer graphExplorer = (GraphExplorer) part.getAdapter(GraphExplorer.class);\r
+        if (graphExplorer != null)\r
+            graphExplorer.startEditing(ctx, ColumnKeys.SINGLE);\r
+\r
+        return null;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java
new file mode 100644 (file)
index 0000000..1eba038
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IDynamicExperiment;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class RunBasicExperiment extends AbstractHandler implements IElementUpdater {\r
+    \r
+    public static final String COMMAND = "org.simantics.sysdyn.ui.run";\r
+    \r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+\r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof IDynamicExperiment)\r
+            ((IDynamicExperiment)experiment).simulate(true);\r
+        return null;\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+       @Override\r
+    public void updateElement(UIElement element, Map parameters) {\r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof SysdynExperiment) {\r
+               ExperimentState state = experiment.getState();\r
+               if(state == ExperimentState.RUNNING) {\r
+                       this.setBaseEnabled(false);\r
+               } else {\r
+                        this.setBaseEnabled(true);\r
+               }\r
+        }        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryDialog.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryDialog.java
new file mode 100644 (file)
index 0000000..44547c0
--- /dev/null
@@ -0,0 +1,292 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.jface.dialogs.IDialogSettings;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.annotation.ui.Activator;\r
+import org.simantics.modelica.data.DataSet;\r
+import org.simantics.spreadsheet.util.SpreadsheetUtils;\r
+import org.simantics.ui.workbench.dialogs.ResourceSelectionDialog3;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class SaveHistoryDialog extends ResourceSelectionDialog3<DataSet> {\r
+\r
+       private String sheetName;\r
+       private String sheetLocation;\r
+       \r
+       private GridData filterLayout;\r
+       \r
+       private boolean filterStart = false;\r
+       private boolean startValid = false;\r
+       private double start;\r
+       private boolean filterStep = false;\r
+       private boolean stepValid = false;\r
+       private int step;\r
+\r
+       public SaveHistoryDialog(Shell shell,\r
+                       Map<DataSet, Pair<String, ImageDescriptor>> parameter, String title) {\r
+               super(shell, parameter, title);\r
+               this.sheetName = "";\r
+               this.sheetLocation = "";\r
+       }\r
+\r
+       @Override\r
+       protected IDialogSettings getBaseDialogSettings() {\r
+               return Activator.getDefault().getDialogSettings();\r
+       }\r
+       \r
+       @Override\r
+       protected void setSelectionResult(Object[] newResult) {\r
+               super.setSelectionResult(newResult);\r
+               validatePage();\r
+       }\r
+\r
+       @Override\r
+       protected Control createExtendedContentArea(final Composite parent_) {\r
+\r
+               Composite parent = new Composite(parent_, SWT.NONE);\r
+               GridLayoutFactory.swtDefaults().numColumns(2).applyTo(parent);\r
+               GridDataFactory.fillDefaults().grab(true, false).applyTo(parent);\r
+\r
+               Label l = new Label(parent, SWT.NONE); \r
+               l.setText("Select a sheet:");\r
+               GridDataFactory.fillDefaults().grab(false, false).applyTo(l);\r
+               final Text t = new Text(parent,SWT.BORDER);\r
+               t.addModifyListener(new ModifyListener() {\r
+                       @Override\r
+                       public void modifyText(ModifyEvent e) {\r
+                               sheetName = t.getText();\r
+                               validatePage();\r
+                       }\r
+               });\r
+               GridDataFactory.fillDefaults().grab(true, false).applyTo(t);\r
+               Label l2 = new Label(parent, SWT.NONE); \r
+               l2.setText("Select cell in sheet:");\r
+               GridDataFactory.fillDefaults().grab(false, false).applyTo(l2);\r
+               final Text t2 = new Text(parent,SWT.BORDER);\r
+               t2.addModifyListener(new ModifyListener() {\r
+                       @Override\r
+                       public void modifyText(ModifyEvent e) {\r
+                               sheetLocation = t2.getText();\r
+                               validatePage();\r
+                       }\r
+               });\r
+               GridDataFactory.fillDefaults().grab(true, false).applyTo(t2);\r
+               \r
+               // filter options\r
+               Composite filterControls = new Composite(parent, SWT.NONE);\r
+               GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(filterControls);\r
+               GridLayoutFactory.fillDefaults().numColumns(2).applyTo(filterControls);\r
+               \r
+               Button filterButton = new Button(filterControls, SWT.ARROW | SWT.DOWN);\r
+               GridDataFactory.fillDefaults().applyTo(filterButton);\r
+               Label filterLabel = new Label(filterControls, SWT.NONE);\r
+               GridDataFactory.fillDefaults().applyTo(filterLabel);\r
+               \r
+               filterButton.addSelectionListener(new SelectionAdapter() {\r
+                       @Override\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               filterLayout.exclude = !filterLayout.exclude;\r
+                               parent_.layout();\r
+                       }\r
+               });\r
+               \r
+               filterLabel.setText("show filter options");\r
+               GridDataFactory.fillDefaults().applyTo(filterLabel);\r
+               \r
+               Composite filterOptions = new Composite(parent, SWT.NONE);\r
+               filterLayout = GridDataFactory.fillDefaults().span(2, 1).grab(true, false).exclude(true).create();\r
+               filterOptions.setLayoutData(filterLayout);\r
+               GridLayoutFactory.fillDefaults().numColumns(2).applyTo(filterOptions);\r
+               \r
+               final Button startButton = new Button(filterOptions, SWT.CHECK);\r
+               GridDataFactory.fillDefaults().applyTo(startButton);\r
+               startButton.setText("start time (in terms of simulation time)");\r
+               final Text startInput = new Text(filterOptions, SWT.BORDER);\r
+               GridDataFactory.fillDefaults().applyTo(startInput);\r
+               \r
+               startButton.addSelectionListener(new SelectionAdapter() {\r
+                       @Override\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               filterStart = startButton.getSelection();\r
+                               startInput.setEnabled(filterStart);\r
+                               startInput.setBackground(Display.getCurrent().getSystemColor(\r
+                                               !filterStart || startValid ? SWT.COLOR_WIDGET_BACKGROUND : SWT.COLOR_YELLOW));\r
+                               validatePage();\r
+                       }\r
+               });\r
+               \r
+               startInput.setEnabled(false);\r
+               startInput.addModifyListener(new ModifyListener() {\r
+                       @Override\r
+                       public void modifyText(ModifyEvent e) {\r
+                               try {\r
+                                       start = Double.parseDouble(startInput.getText());\r
+                                       startValid = true;\r
+                               }\r
+                               catch (Exception ex) {\r
+                                       startValid = false;\r
+                               }\r
+                               startInput.setBackground(Display.getCurrent().getSystemColor(\r
+                                               startValid ? SWT.COLOR_WIDGET_BACKGROUND : SWT.COLOR_YELLOW));\r
+                               validatePage();\r
+                       }\r
+               });\r
+               \r
+               final Button stepButton = new Button(filterOptions, SWT.CHECK);\r
+               GridDataFactory.fillDefaults().applyTo(stepButton);\r
+               stepButton.setText("sample rate (1 = every step, 2 = every other step...)");\r
+               final Text stepInput = new Text(filterOptions, SWT.BORDER);\r
+               GridDataFactory.fillDefaults().applyTo(stepInput);\r
+               \r
+               stepButton.addSelectionListener(new SelectionAdapter() {\r
+                       @Override\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               filterStep = stepButton.getSelection();\r
+                               stepInput.setEnabled(filterStep);\r
+                               stepInput.setBackground(Display.getCurrent().getSystemColor(\r
+                                               !filterStep || stepValid ? SWT.COLOR_WIDGET_BACKGROUND : SWT.COLOR_YELLOW));\r
+                               validatePage();\r
+                       }\r
+               });\r
+               \r
+               stepInput.setEnabled(false);\r
+               stepInput.addModifyListener(new ModifyListener() {\r
+                       @Override\r
+                       public void modifyText(ModifyEvent e) {\r
+                               try {\r
+                                       step = Integer.parseInt(stepInput.getText());\r
+                                       stepValid = true;\r
+                               }\r
+                               catch (Exception ex) {\r
+                                       stepValid = false;\r
+                               }\r
+                               stepInput.setBackground(Display.getCurrent().getSystemColor(\r
+                                               stepValid ? SWT.COLOR_WIDGET_BACKGROUND : SWT.COLOR_YELLOW));\r
+                               validatePage();\r
+                       }\r
+               });\r
+               \r
+               validatePage();\r
+               return super.createExtendedContentArea(parent);\r
+       }\r
+\r
+       @Override\r
+       protected void handleSelected(StructuredSelection selection) {\r
+               super.handleSelected(selection);\r
+               validatePage(); \r
+       }\r
+\r
+       protected void validatePage() {\r
+               \r
+               if(getSelectedItems().size() == 0) {\r
+                       updateStatus(new Status(Status.ERROR, PlatformUI.PLUGIN_ID, "Please select some variable(s)"));\r
+                       return;\r
+               }\r
+               \r
+               String error = validateSheet(sheetName);\r
+               if (error != null) {\r
+                       updateStatus(new Status(Status.ERROR, PlatformUI.PLUGIN_ID, error));\r
+                       return;\r
+               }\r
+\r
+               error = validateLocation(sheetLocation);\r
+               if (error != null) {\r
+                       updateStatus(new Status(Status.ERROR, PlatformUI.PLUGIN_ID, error));\r
+                       return;\r
+               }\r
+               \r
+               error = validateFilter();\r
+               if (error != null) {\r
+                       updateStatus(new Status(Status.ERROR, PlatformUI.PLUGIN_ID, error));\r
+                       return;\r
+               }\r
+               \r
+               updateStatus(new Status(Status.OK, Activator.PLUGIN_ID, ""));\r
+               \r
+       }\r
+\r
+       protected String validateSheet(String name) {\r
+               if (name.trim().isEmpty())\r
+                       return "Sheet name cannot be empty";\r
+               return null;\r
+       }\r
+\r
+       protected String validateLocation(String location) {\r
+               try {\r
+                       if(location.isEmpty())\r
+                               return "Empty location";\r
+                       SpreadsheetUtils.decodeCellAbsolute(location);\r
+                       return null;\r
+               } catch (Exception e) {\r
+                       return e.getMessage();\r
+               }\r
+       }\r
+       \r
+       protected String validateFilter() {\r
+               if (filterStart && !startValid) {\r
+                       return "Invalid start time in filter";\r
+               }\r
+               else if (filterStep && !stepValid) {\r
+                       return "Invalid sample rate in filter";\r
+               }\r
+               else {\r
+                       return null;\r
+               }\r
+       }\r
+\r
+       public String getSheetName() {\r
+               return sheetName;\r
+       }\r
+\r
+       public String getSheetLocation() {\r
+               return sheetLocation;\r
+       }\r
+       \r
+       public boolean filterStart() {\r
+               return filterStart;\r
+       }\r
+       \r
+       public double getStart() {\r
+               return start;\r
+       }\r
+       \r
+       public boolean filterStep() {\r
+               return filterStep;\r
+       }\r
+       \r
+       public int getStep() {\r
+               return step;\r
+       }\r
+       \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveHistoryHandler.java
new file mode 100644 (file)
index 0000000..f4a103c
--- /dev/null
@@ -0,0 +1,157 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.window.Window;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modelica.data.DataSet;\r
+import org.simantics.modelica.data.SimulationResult;\r
+import org.simantics.modeling.ModelingUtils;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.spreadsheet.Range;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.spreadsheet.util.SpreadsheetUtils;\r
+import org.simantics.sysdyn.manager.MemoryResult;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.manager.SysdynResult;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+       \r
+public class SaveHistoryHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+        \r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof SysdynGameExperimentBase) {\r
+            final SysdynGameExperimentBase exp = (SysdynGameExperimentBase)experiment;\r
+               try {\r
+                       \r
+                       Map<DataSet, Pair<String,ImageDescriptor>> map = new HashMap<DataSet, Pair<String,ImageDescriptor>>();\r
+\r
+                       SysdynResult r = exp.getCurrentResult(); \r
+                       if(r instanceof MemoryResult) {\r
+                               MemoryResult gr = (MemoryResult)r;\r
+                               SimulationResult sr = gr.getSimulationResult();\r
+                               for(DataSet ds : sr.getVariableDataSets()) {\r
+                                       map.put(ds, new Pair<String,ImageDescriptor>(ds.name, null));\r
+                               }\r
+                       }\r
+                       \r
+                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
+                SaveHistoryDialog dialog = new SaveHistoryDialog(shell, map, "Select variables");\r
+                if (dialog.open() == Window.OK) {\r
+                    final Object[] result = dialog.getResult();\r
+                    final String sheetName = dialog.getSheetName();\r
+                    final String sheetLocation = dialog.getSheetLocation();\r
+                    \r
+                    final boolean filterStart = dialog.filterStart();\r
+                    final double start = dialog.getStart();\r
+                    final boolean filterStep = dialog.filterStep();\r
+                    final int step = dialog.getStep();\r
+                    \r
+                    Simantics.getSession().syncRequest(new WriteRequest() {\r
+\r
+                       public void writeCell(WriteGraph graph, Variable sheet, String cellName, String value) throws DatabaseException {\r
+                               SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);\r
+                               Variable child = sheet.getPossibleChild(graph, cellName);\r
+                               if(child != null) {\r
+                                       child.setPropertyValue(graph, SHEET.Cell_content, Variant.ofInstance(value), Bindings.VARIANT);\r
+                               } else {\r
+                                       Layer0 L0 = Layer0.getInstance(graph);\r
+                                       Resource container = sheet.getRepresents(graph);\r
+                                       Resource cell = graph.newResource();\r
+                                       graph.claim(cell, L0.InstanceOf, null, SHEET.TextCell);\r
+                                       graph.addLiteral(cell, L0.HasName, L0.NameOf, L0.String, cellName, Bindings.STRING);\r
+                                       graph.addLiteral(cell, SHEET.Cell_content, SHEET.Cell_content_Inverse, L0.Variant, Variant.ofInstance(value), Bindings.VARIANT);\r
+                                       graph.claim(cell, L0.PartOf, container);\r
+                               }\r
+                       }\r
+                       \r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               \r
+                               SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);\r
+                               Resource modelResource = graph.syncRequest(new PossibleModel(exp.getResource()));\r
+                               if(modelResource == null) return;\r
+                               List<Resource> sheets = ModelingUtils.searchByTypeAndName(graph, modelResource, SHEET.Spreadsheet, sheetName);\r
+                               if(sheets.size() != 1) return;\r
+                               Variable sheet = Variables.getVariable(graph, sheets.get(0));\r
+                               \r
+                               Range base = SpreadsheetUtils.decodeCellAbsolute(sheetLocation);\r
+                               \r
+                               int row = base.startRow;\r
+                               DataSet first = (DataSet)result[0];\r
+                               writeCell(graph, sheet, SpreadsheetUtils.cellName(row++, base.startColumn), "time");\r
+                               for(int i=0;i<first.times.length;i++) {\r
+                                       if (filterStep && i % step != 0)\r
+                                               continue;\r
+                                       if (filterStart && first.times[i] < start)\r
+                                               continue;\r
+                                       String loc = SpreadsheetUtils.cellName(row++, base.startColumn);\r
+                                       writeCell(graph, sheet, loc, Double.toString(first.times[i]));\r
+                               }\r
+                               \r
+                               for(int j=0;j<result.length;j++) {\r
+                                       row = base.startRow;\r
+                                       first = (DataSet)result[j];\r
+                                       writeCell(graph, sheet, SpreadsheetUtils.cellName(row++, base.startColumn+1+j), first.name);\r
+                                       for(int i=0;i<first.values.length;i++) {\r
+                                               if (filterStep && i % step != 0)\r
+                                                       continue;\r
+                                               if (filterStart && first.times[i] < start)\r
+                                                       continue;\r
+                                               String loc = SpreadsheetUtils.cellName(row++, base.startColumn+1+j);\r
+                                               writeCell(graph, sheet, loc, Double.toString(first.values[i])); \r
+                                       }\r
+\r
+                               }\r
+                               \r
+                       }\r
+\r
+                    });\r
+                }\r
+                       \r
+                \r
+                       } catch (Throwable e) {\r
+                               e.printStackTrace();\r
+                       }\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveICHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveICHandler.java
new file mode 100644 (file)
index 0000000..de73834
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.manager.SysdynExperiments;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class SaveICHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+        \r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof SysdynExperiment) {\r
+            final SysdynExperiment exp = (SysdynExperiment)experiment;\r
+               try {\r
+                               Simantics.getSession().syncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               Variable v = Variables.getVariable(graph, exp.getResource());\r
+                                               SysdynExperiments.saveIC(graph, v, "IC");\r
+                                       }\r
+                                       \r
+                               });\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveResultsHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveResultsHandler.java
new file mode 100644 (file)
index 0000000..616f835
--- /dev/null
@@ -0,0 +1,38 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.simantics.simulation.experiment.IDynamicExperiment;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class SaveResultsHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+        \r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof IDynamicExperiment) {\r
+            ((IDynamicExperiment)experiment).saveState();\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ShowModuleHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ShowModuleHandler.java
new file mode 100644 (file)
index 0000000..0514909
--- /dev/null
@@ -0,0 +1,115 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.IEditorPart;\r
+import org.eclipse.ui.PartInitException;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.modeling.ComponentUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.editor.DiagramViewer;\r
+import org.simantics.sysdyn.ui.editor.SysdynEditorInput;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
+\r
+\r
+public class ShowModuleHandler extends AbstractHandler {\r
+\r
+    private static final String EDITOR_ID = "org.simantics.sysdyn.ui.diagramViewer";\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+               \r
+               ISelection s = HandlerUtil.getCurrentSelectionChecked(event);\r
+               final Resource resources[] = ResourceAdaptionUtils.toResources(s);\r
+               IEditorPart editor = (IEditorPart)HandlerUtil.getActiveEditor(event);\r
+               if (!(editor instanceof DiagramEditor))\r
+                       return null;\r
+               final DiagramViewer viewer = (DiagramViewer) ((DiagramEditor) editor).getViewer();\r
+               if (viewer == null)\r
+                       return null;\r
+               \r
+               SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+\r
+                DiagramResource dr = DiagramResource.getInstance(graph);\r
+                               Resource runtime = viewer.getRuntime();\r
+                               String uri = graph.getPossibleRelatedValue(runtime, dr.RuntimeDiagram_HasVariable, Bindings.STRING);\r
+                               Variable parent = Variables.getVariable(graph, uri);\r
+                               final Resource model = Variables.getModel(graph, parent);\r
+                               \r
+                               for(Resource element : resources) {\r
+\r
+                                       ModelingResources mr = ModelingResources.getInstance(graph);\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       StructuralResource2 st = StructuralResource2.getInstance(graph);\r
+                                       \r
+                                       final Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
+                                       final Resource componentType = graph.getPossibleType(component, sr.Module);\r
+                                       final Resource configuration = graph.getPossibleObject(componentType, st.IsDefinedBy);\r
+                                       final Resource diagram = ComponentUtils.getPossibleCompositeDiagram(graph, configuration);\r
+\r
+                                       Variable variable;\r
+                                       String rvi = "";\r
+                                       try {\r
+                                               variable = parent.browse(graph, component);\r
+                                               rvi = Variables.getRVI(graph, variable);\r
+                                       } catch (MissingVariableException e ) {\r
+                                               variable = Variables.getVariable(graph, graph.getURI(component));\r
+                                       }\r
+                                       final String finalRvi = rvi;\r
+                                       \r
+\r
+                                       \r
+                                       PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+\r
+                                               @Override\r
+                                               public void run() {\r
+                                                       try {\r
+                                                               String editorId = EDITOR_ID;\r
+                                                               WorkbenchUtils.openEditor(editorId, new SysdynEditorInput(editorId, diagram, model, finalRvi));\r
+                                                       } catch (PartInitException e) {\r
+                                                               e.printStackTrace();\r
+                                                       }\r
+                                               }\r
+                                       });\r
+                               \r
+                               }\r
+                               \r
+                       }\r
+               });\r
+               \r
+               return null;\r
+       }\r
+       \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SynthesisSimulation.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SynthesisSimulation.java
new file mode 100644 (file)
index 0000000..00f12bb
--- /dev/null
@@ -0,0 +1,87 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.Command;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.commands.State;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.commands.ICommandService;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * @author Tuomas Miettinen\r
+ */\r
+public class SynthesisSimulation extends AbstractHandler implements IElementUpdater {\r
+\r
+       public static final String COMMAND = "org.simantics.sysdyn.ui.synthesisSimulation";\r
+    public static final String STATE = "org.simantics.sysdyn.ui.synthesisSimulation.state";\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = service.getCommand(COMMAND);\r
+        State state = command.getState(STATE);\r
+        Boolean value = (Boolean) state.getValue();\r
+        value = !value;\r
+        state.setValue(value);\r
+        service.refreshElements(RunBasicExperiment.COMMAND, null);\r
+        \r
+        Command toggleCommand = service.getCommand(ToggleSimulation.COMMAND);\r
+        State toggleState = toggleCommand.getState(ToggleSimulation.STATE);\r
+        toggleState.setValue(value);\r
+        service.refreshElements(RunBasicExperiment.COMMAND, null);\r
+        \r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof SysdynExperiment) {\r
+            if(getState()) {\r
+                ((SysdynExperiment)experiment).toggleSimulation(true);\r
+            } else {\r
+                ((SysdynExperiment)experiment).toggleSimulation(false);\r
+            }\r
+        }\r
+            \r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+\r
+        return null;\r
+    }\r
+\r
+    public static Boolean getState() {\r
+        ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = service.getCommand(COMMAND);\r
+        State state = command.getState(STATE);\r
+        return (Boolean)state.getValue();\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+       @Override\r
+    public void updateElement(UIElement element, Map parameters) {\r
+        ICommandService commandService =\r
+            (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = commandService.getCommand(COMMAND);\r
+        boolean checked = (Boolean) command.getState(STATE).getValue();\r
+        element.setChecked(checked);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SysdynExperimentActivator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SysdynExperimentActivator.java
new file mode 100644 (file)
index 0000000..4b13c46
--- /dev/null
@@ -0,0 +1,194 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.concurrent.Semaphore;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.SubMonitor;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.RequestProcessor;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.AdaptionException;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.message.MessageService;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.model.ExperimentLoadingFailed;\r
+import org.simantics.simulation.project.IExperimentActivationListener;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.ui.listeners.SysdynExperimentManagerListener;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.DataContainer;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+import org.simantics.utils.ui.dialogs.ShowMessage;\r
+\r
+public class SysdynExperimentActivator extends AbstractHandler {\r
+    /**\r
+     * @param project\r
+     * @param experimentManager\r
+     * @param experiment\r
+     */\r
+    public static void scheduleActivation(RequestProcessor processor, final IProject project, final IExperimentManager experimentManager, final Resource experiment) {\r
+        String jobName = "Activate Experiment";\r
+        String experimentName = getName(processor, experiment);\r
+        if (experimentName != null)\r
+            jobName += " '" + experimentName + "'";\r
+        /*\r
+        // Shut down the previous active experiment\r
+        IExperiment activeExperiment = experimentManager.getActiveExperiment();\r
+        if (experiment != null)\r
+            activeExperiment.shutdown();\r
+         */\r
+        // Activate a new experiment\r
+        scheduleActivation(jobName, project, experimentManager, experiment);\r
+    }\r
+\r
+    /**\r
+     * @param project\r
+     * @param experimentManager\r
+     * @param experiment\r
+     */\r
+    public static void scheduleActivation(String jobName, final IProject project, final IExperimentManager experimentManager, final Resource experiment) {\r
+        new Job(jobName) {\r
+            @Override\r
+            protected IStatus run(final IProgressMonitor monitor) {\r
+                try {\r
+                    return SysdynExperimentActivator.activate(monitor, project, experimentManager, experiment);\r
+                } finally {\r
+                    monitor.done();\r
+                }\r
+            }\r
+        }.schedule();\r
+    }\r
+\r
+    public static IStatus activate(IProgressMonitor monitor, IProject project, IExperimentManager experimentManager, Resource experiment) {\r
+        return new SysdynExperimentActivator().activateExperiment(monitor, project, experimentManager, experiment);\r
+    }\r
+\r
+    private static String getName(RequestProcessor processor, final Resource resource) {\r
+        try {\r
+            return processor.syncRequest(new Read<String>() {\r
+                @Override\r
+                public String perform(ReadGraph graph) throws DatabaseException {\r
+                    try {\r
+                        return graph.adapt(resource, String.class);\r
+                    } catch (AdaptionException e) {\r
+                        return NameUtils.getSafeName(graph, resource);\r
+                    }\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            ErrorLogger.defaultLogWarning(e);\r
+            return null;\r
+        }\r
+    }\r
+\r
+    private IStatus activateExperiment(final IProgressMonitor monitor, final IProject project, final IExperimentManager manager, final Resource experimentResource) {\r
+        final SubMonitor mon = SubMonitor.convert(monitor, "Activating experiment", 100000);\r
+\r
+        SysdynExperimentManagerListener.listenManager(manager);\r
+        IExperiment[] experiments = manager.getExperiments();\r
+        SubMonitor shutdownMon = mon.newChild(10000);\r
+        int workPerExperiment;\r
+        if (experiments.length > 0)\r
+               workPerExperiment = 10000 / experiments.length;\r
+        else\r
+               workPerExperiment = 10000;\r
+        for(IExperiment e : experiments)\r
+            if(e.getState() != ExperimentState.DISPOSED)\r
+                e.shutdown(shutdownMon.newChild(workPerExperiment));\r
+        mon.setWorkRemaining(90000);\r
+\r
+        final Semaphore activated = new Semaphore(0);\r
+        final DataContainer<Throwable> problem = new DataContainer<Throwable>();\r
+        manager.startExperiment(experimentResource, new IExperimentActivationListener() {\r
+\r
+            @Override\r
+            public void onExperimentActivated(final IExperiment experiment) {\r
+                MessageService.defaultLog(new org.eclipse.core.runtime.Status(IStatus.INFO, "org.simantics.simulation.ui", 0, "Activated experiment " + experiment.getIdentifier() , null));\r
+                activated.release();\r
+            }\r
+            @Override\r
+            public void onFailure(Throwable e) {\r
+                problem.set(e);\r
+                activated.release();\r
+            }\r
+            @Override\r
+            public void onMessage(IStatus message) {\r
+                MessageService.getDefault().log(message);\r
+                /*ILogger logger = MessageService.getDefault();\r
+                    MultiStatus init = new MultiStatus(Activator.PLUGIN_ID, 0, "Activating experiment", null);\r
+                    for (String msg : messages) {\r
+                        init.add(new Status(IStatus.INFO, Activator.PLUGIN_ID, msg));\r
+                    }\r
+                    logger.log(init);*/\r
+            }\r
+            @Override\r
+            public IProgressMonitor getProgressMonitor() {\r
+                return mon;\r
+            }\r
+        }, true);\r
+        try {\r
+            activated.acquire();\r
+            Throwable t = problem.get();\r
+            if (t != null) {\r
+                if (t instanceof ExperimentLoadingFailed) {\r
+                    ErrorLogger.defaultLogError(t);\r
+                    ShowMessage.showError("Experiment Activation Failed", t.getMessage());\r
+                } else {\r
+                    ExceptionUtils.logAndShowError(t);\r
+                }\r
+            }\r
+\r
+            return Status.OK_STATUS;\r
+            //return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Experiment activation failed, see exception for details.", problem.get());\r
+        } catch (InterruptedException e) {\r
+            return Status.CANCEL_STATUS;\r
+        }\r
+    }\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+               ISelection selection = HandlerUtil.getCurrentSelection(event);\r
+        final Resource experiment = ResourceAdaptionUtils.toSingleResource(selection);\r
+        if (experiment == null)\r
+            return null;\r
+\r
+        final IProject project = SimanticsUI.getProject();\r
+        if (project == null)\r
+            return null;\r
+        \r
+        final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        if (experimentManager == null) {\r
+            ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());\r
+            return null;\r
+        }\r
+        \r
+        SysdynExperimentActivator.scheduleActivation(SimanticsUI.getSession(), project, experimentManager, experiment);\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultActivation.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultActivation.java
new file mode 100644 (file)
index 0000000..024c6cb
--- /dev/null
@@ -0,0 +1,64 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+public class ToggleResultActivation extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        Resource[] resources = ResourceAdaptionUtils.toResources(sel);\r
+        if (resources.length == 0)\r
+            return null;\r
+\r
+        toggleActivation(resources);\r
+\r
+        return null;\r
+    }\r
+\r
+    public static void toggleActivation(final Resource[] resources) {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    for(Resource r : resources) {\r
+                        if(graph.isInstanceOf(r, sr.Result)) {\r
+                            if (graph.hasStatement(r, sr.Result_showResult)) {\r
+                                graph.denyStatement(r, sr.Result_showResult, r);\r
+                            } else {\r
+                                graph.claim(r, sr.Result_showResult, r);\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultSetActivation.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultSetActivation.java
new file mode 100644 (file)
index 0000000..a667a8c
--- /dev/null
@@ -0,0 +1,76 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.Collection;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+public class ToggleResultSetActivation extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        Resource[] resources = ResourceAdaptionUtils.toResources(sel);\r
+        if (resources.length == 0)\r
+            return null;\r
+\r
+        toggleActivation(resources);\r
+\r
+        return null;\r
+    }\r
+\r
+    public static void toggleActivation(final Resource[] resources) {\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    for(Resource r : resources) {\r
+                       // If there is at least one result which shown, clear them all.\r
+                       // If not one result is shown, show them all.\r
+                       boolean resultShown = false;\r
+                       Collection<Resource> results = graph.getObjects(r, sr.Experiment_result); \r
+                       for (Resource result : results) {\r
+                               if (graph.hasStatement(result, sr.Result_showResult)) {\r
+                                       resultShown = true;\r
+                                       break;\r
+                               }\r
+                       }\r
+                       for (Resource result : results) {\r
+                               if (resultShown) { \r
+                                       graph.denyStatement(result, sr.Result_showResult, result);\r
+                            } else {\r
+                                graph.claim(result, sr.Result_showResult, result);\r
+                            }\r
+                       }\r
+                    }\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleSimulation.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleSimulation.java
new file mode 100644 (file)
index 0000000..351f9c4
--- /dev/null
@@ -0,0 +1,84 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.Command;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.commands.State;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.commands.ICommandService;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ToggleSimulation extends AbstractHandler implements IElementUpdater {\r
+\r
+    public static final String COMMAND = "org.simantics.sysdyn.ui.toggleSimulation";\r
+    public static final String STATE = "org.simantics.sysdyn.ui.toggleSimulation.state";\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = service.getCommand(COMMAND);\r
+        State state = command.getState(STATE);\r
+        Boolean value = (Boolean) state.getValue();\r
+        value = !value;\r
+        state.setValue(value);\r
+        service.refreshElements(RunBasicExperiment.COMMAND, null);\r
+        \r
+        Command synthesisCommand = service.getCommand(SynthesisSimulation.COMMAND);\r
+        State synthesisState = synthesisCommand.getState(SynthesisSimulation.STATE);\r
+        synthesisState.setValue(false);\r
+        service.refreshElements(RunBasicExperiment.COMMAND, null);\r
+        \r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof SysdynExperiment) {\r
+            if(getState()) {\r
+                ((SysdynExperiment)experiment).toggleSimulation(true);\r
+            } else {\r
+                ((SysdynExperiment)experiment).toggleSimulation(false);\r
+            }\r
+        }\r
+            \r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+\r
+        return null;\r
+    }\r
+\r
+    public static Boolean getState() {\r
+        ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = service.getCommand(COMMAND);\r
+        State state = command.getState(STATE);\r
+        return (Boolean)state.getValue();\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+       @Override\r
+    public void updateElement(UIElement element, Map parameters) {\r
+        ICommandService commandService =\r
+            (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = commandService.getCommand(COMMAND);\r
+        boolean checked = (Boolean) command.getState(STATE).getValue();\r
+        element.setChecked(checked);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/UnlinkNodeHandler2.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/UnlinkNodeHandler2.java
new file mode 100644 (file)
index 0000000..4689072
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers;\r
+\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.model.nodetypes.NodeType;\r
+import org.simantics.modeling.ui.modelBrowser.handlers.DeleteNodeHandler;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+public class UnlinkNodeHandler2 extends DeleteNodeHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+        Set<NodeContext> ctxs = ISelectionUtils.filterSetSelection(sel, NodeContext.class);\r
+\r
+        NodeType previousNodeType = null;\r
+        for (NodeContext ctx : ctxs) {\r
+            NodeType nodeType = ctx.getConstant(NodeType.TYPE);\r
+            if(previousNodeType == null) {\r
+                previousNodeType = nodeType;\r
+            } else if(!previousNodeType.equals(nodeType)) {\r
+                MessageDialog dialog = new MessageDialog(shell, "Unable to remove", null, "Only items of same type can be removed at the same time.", 0,\r
+                        new String[] { "OK" }, 0);\r
+                dialog.create();\r
+                dialog.open();\r
+                return null;\r
+            }\r
+        }\r
+\r
+        MessageDialog dialog = new MessageDialog(shell, "Remove Item", null, "Are you sure?", 0,\r
+                new String[] { "OK", "Cancel" }, 0);\r
+        dialog.create();\r
+        if (dialog.open() == 0) {\r
+            super.execute(event);\r
+        }\r
+        return null;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportExternalFunctionFilesHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportExternalFunctionFilesHandler.java
new file mode 100644 (file)
index 0000000..fe9d193
--- /dev/null
@@ -0,0 +1,97 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.exports;\r
+\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.widgets.DirectoryDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+/**\r
+ * Exports external function files from SysdynModelicaFunctions\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ExportExternalFunctionFilesHandler extends AbstractHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+           // Find shell and resources to be exported\r
+               Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+               ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+               final Resource[] resources = ResourceAdaptionUtils.toResources(sel);\r
+               if (resources.length < 1)\r
+                       return null;\r
+\r
+               return exportFiles(shell, resources);\r
+       }\r
+       \r
+       /**\r
+        * Exports selected file resources to files on disk. Assumes all resources are external files.\r
+        * \r
+        * @param shell SWT Shell\r
+        * @param resources External file resources\r
+        * @return null\r
+        */\r
+       public static Object exportFiles(Shell shell, final Resource[] resources) {\r
+           \r
+           // Select a path where to export the files\r
+               DirectoryDialog dd = new DirectoryDialog(shell);\r
+               dd.setFilterPath(Platform.getLocation().toOSString());\r
+               dd.setText("Export files to...");\r
+               dd.setMessage("Select a directory");\r
+               final String dir = dd.open();\r
+               if (dir == null) {\r
+                       return null;\r
+               }\r
+\r
+               SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+\r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               // Get byte arrays from each resource and write them to disk\r
+                               for(Resource r : resources) {\r
+                                       try {\r
+                                               String name = NameUtils.getSafeName(graph, r);\r
+                                               FileOutputStream fos = new FileOutputStream(dir + "\\" + name);\r
+                                               byte[] fileBArray = graph.getPossibleRelatedValue(r, sr.ExternalFunctionFile_externalFile, Bindings.BYTE_ARRAY);\r
+                                               fos.write(fileBArray);\r
+                                               fos.close();\r
+                                       } catch (IOException e) {\r
+                                               e.printStackTrace();\r
+                                       }\r
+                               }\r
+                               \r
+                       }\r
+               });\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportFunctionLibrary.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportFunctionLibrary.java
new file mode 100644 (file)
index 0000000..251ab7a
--- /dev/null
@@ -0,0 +1,115 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.exports;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
+import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.graph.db.TransferableGraphSource;\r
+import org.simantics.graph.db.TransferableGraphs;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+/**\r
+ * Exports a function library\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ExportFunctionLibrary  extends AbstractHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        final Resource functionLibrary = ResourceAdaptionUtils.toSingleResource(sel);\r
+        if(functionLibrary == null) return null;\r
+               \r
+               String name = null;\r
+               try {\r
+                       name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf))\r
+                                               return null;\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       String name = graph.syncRequest(new PossibleRelatedValue<String>(functionLibrary, l0.HasName, Bindings.STRING ));\r
+                                       return name;\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               // Do not export if the resource has no name\r
+               if(name == null) return null;\r
+               \r
+               // Find a location (and name) for the exported library using FileDialog\r
+               Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+               FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
+               fd.setText("Export Function Library");\r
+               fd.setFileName(name);\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH);\r
+               if(path.isEmpty() || !(new File(path).exists()))\r
+                       path = Platform.getLocation().toOSString();\r
+               fd.setFilterPath(path);\r
+               String[] filterExt = {"*.sysdynFunctions"};\r
+               fd.setFilterExtensions(filterExt);\r
+               fd.setOverwrite(true);\r
+               final String selected = fd.open();\r
+               if(selected == null) return null;\r
+               \r
+               // Save location to preference store\r
+               Activator.getDefault().getPreferenceStore().setValue(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH, (new File(selected)).getParent());\r
+\r
+               // Asynchronously create the file using transferable graph\r
+               SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+\r
+                   @Override\r
+                   public void run(ReadGraph graph) throws DatabaseException {\r
+                       TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, functionLibrary);\r
+                       TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));\r
+                       try {\r
+                           TransferableGraphs.writeTransferableGraph(graph, "sysdynFunctionLibrary", 1, s,new File(selected));\r
+                       } catch (Exception e) {\r
+                           e.printStackTrace();\r
+                       }\r
+                   }\r
+               });\r
+\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelAsButtonHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelAsButtonHandler.java
new file mode 100644 (file)
index 0000000..8e63184
--- /dev/null
@@ -0,0 +1,49 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.exports;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
+\r
+/**\r
+ * Exports a selected model asking the location.\r
+ * Model determination is based on any resource of the model.\r
+ * \r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ExportModelAsButtonHandler extends ExportModelButtonHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        \r
+               status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );\r
+        \r
+               final Resource model = determineModel(event);\r
+        if (model == null)\r
+               return null;\r
+        \r
+        String selected = getAbsolutePath(model, event, true);\r
+        \r
+        if (selected != null) {\r
+               createFile(model, selected);\r
+               setExportStatus(model, selected);\r
+        }\r
+        \r
+               return null;\r
+       }\r
+\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelButtonHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelButtonHandler.java
new file mode 100644 (file)
index 0000000..9954ae6
--- /dev/null
@@ -0,0 +1,122 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.exports;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.ui.IWorkbenchPage;\r
+import org.eclipse.ui.IWorkbenchPart;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.platform.PropertyPageView;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
+\r
+/**\r
+ * Exports a selected model without asking the location.\r
+ * Model determination is based on any resource of the model.\r
+ * \r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ExportModelButtonHandler extends ExportModelHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        \r
+               status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );\r
+        \r
+               final Resource model = determineModel(event);\r
+        if (model == null)\r
+               return null;\r
+\r
+        String selected = getAbsolutePath(model, event, false);\r
+        \r
+        if (selected != null) {\r
+               createFile(model, selected);\r
+               setExportStatus(model, selected);\r
+        }\r
+        \r
+        return null;\r
+       }\r
+\r
+       @Override\r
+       protected Resource determineModel(ExecutionEvent event) {\r
+               ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        if (sel == null) {\r
+               // No selection, this is true e.g. in PropertyPageView\r
+               IWorkbenchPart activePart = HandlerUtil.getActivePart(event);\r
+               // In such a case get the selection the PropertyPageView point to.\r
+               if (activePart instanceof PropertyPageView)\r
+                       sel = ((PropertyPageView)activePart).getLastSelection();\r
+        }\r
+        \r
+        // Get the Resource of the selection\r
+        Resource inputResource = ResourceAdaptionUtils.toSingleResource(sel);\r
+        if (inputResource == null) {\r
+               // Coner case for when export is called when some folder in model browser is selected.\r
+            if (sel instanceof IStructuredSelection) {\r
+                IStructuredSelection iss = (IStructuredSelection) sel;\r
+                if (iss.size() == 1) {\r
+                       Object element = iss.getFirstElement();\r
+                       AbstractNode<?> a = AdaptionUtils.adaptToSingle(element, AbstractNode.class);\r
+                       if (a != null)\r
+                               inputResource = (Resource)a.data;\r
+                }\r
+            }\r
+        }\r
+        \r
+        // When the selection doesn't have a resource, use the currently active diagram.\r
+        if (inputResource == null) {\r
+               IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();\r
+               DiagramEditor editor = (DiagramEditor)page.getActiveEditor();\r
+               if (editor != null && editor instanceof DiagramEditor) {\r
+               inputResource = editor.getInputResource();\r
+            } else {\r
+                       return null; \r
+            }\r
+       }\r
+        \r
+        // Now that we finally have determined which Resource is selected, we just need\r
+        // to get the model of that Resource.\r
+        Resource model;\r
+        final Resource resource = inputResource;\r
+               try {\r
+                       model = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                                       return graph.sync(new PossibleModel(resource));\r
+                               }\r
+                               \r
+                       });\r
+               if(model == null) return null;\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+                       return null;\r
+               }\r
+               return model;\r
+       }\r
+       \r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelHandler.java
new file mode 100644 (file)
index 0000000..78e893d
--- /dev/null
@@ -0,0 +1,291 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.exports;\r
+\r
+import java.io.File;\r
+import java.lang.reflect.InvocationTargetException;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.NullProgressMonitor;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.jface.action.IStatusLineManager;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelExport.SysdynModelExporter;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
+\r
+/**\r
+ * Exports a selected model\r
+ * Model determination is based on the very Resource of the model.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ExportModelHandler extends AbstractHandler {\r
+\r
+       protected static IStatusLineManager status;\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+               status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );\r
+        \r
+               final Resource model = determineModel(event);\r
+        if (model == null)\r
+               return null;\r
+        \r
+        String selected = getAbsolutePath(model, event, true);\r
+        \r
+        if (selected != null) {\r
+               createFile(model, selected);\r
+               setExportStatus(model, selected);\r
+        }\r
+\r
+        return null;\r
+       }\r
+       \r
+       /**\r
+        * Create the export file.\r
+        * @param model Model which is exported.\r
+        * @param fileName Full name of the file.\r
+        */\r
+       protected void setExportStatus(final Resource model, final String fileName) {\r
+               try {\r
+                       String modelName = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+       \r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
+                                               return null;\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       return graph.syncRequest(new PossibleRelatedValue<String>(model, l0.HasName, Bindings.STRING ));\r
+                               }\r
+                               \r
+                       });\r
+       \r
+                       if (modelName != null)\r
+                               setStatus("Saved model \"" + modelName + "\" to " + fileName);\r
+               \r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+       \r
+       /**\r
+        * Create the export file.\r
+        * @param model Model which is exported.\r
+        * @param fileName Full name of the file.\r
+        */\r
+       protected void createFile(final Resource model, final String fileName) {\r
+               File exportLocation = new File(fileName);\r
+               try {\r
+            SysdynModelExporter.exportModel(new NullProgressMonitor(), model, exportLocation, "", false);\r
+        } catch (InvocationTargetException e1) {\r
+            ExceptionUtils.logAndShowError("Model Export Failed", "Sysdyn model export failed, see exception for details", e1);\r
+        }\r
+\r
+//             // Asynchronously create the file using transferable graph\r
+//             SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+//\r
+//                 @Override\r
+//                 public void run(ReadGraph graph) throws DatabaseException {\r
+//                     HashMap<Resource, ExtentStatus> map = new HashMap<Resource, ExtentStatus>();\r
+//                     \r
+//                     Resource relation = graph.getPossibleResource("http://www.simantics.org/Documentation-1.1/createdBy");\r
+//                     if(relation != null) {\r
+//                         Resource createdBy = graph.getPossibleObject(model, relation);\r
+//                         if(createdBy != null)\r
+//                             map.put(createdBy, ExtentStatus.EXCLUDED);\r
+//                     }\r
+//                     \r
+//                     TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model);\r
+//                     conf.preStatus.putAll(map);\r
+//                     \r
+//                     TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));\r
+//                     try {\r
+//                         TransferableGraphs.writeTransferableGraph(graph, "sysdynModel", 1, s,new File(fileName));\r
+//                     } catch (Exception e) {\r
+//                         ExceptionUtils.logAndShowError("Model Export Failed", "Sysdyn model export failed, see exception for details", e);\r
+//                         \r
+//                         File modelFile = new File(fileName);\r
+//                         if (modelFile.exists())\r
+//                             modelFile.delete();\r
+//                     }\r
+//                     }\r
+//             });\r
+       }\r
+       \r
+       /**\r
+        * Get the model Resource based on the event.\r
+        * @param event\r
+        * @return model Resource which the event refers to.\r
+        */\r
+       protected Resource determineModel(ExecutionEvent event) {\r
+               // Just get the selected model.\r
+           ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+           final Resource model = ResourceAdaptionUtils.toSingleResource(sel);\r
+           return model;\r
+       }\r
+       \r
+       /**\r
+        * Get the absolute save path for the export file and save it to the database.\r
+        * @param model Model Resource which is exported.\r
+        * @param event\r
+        * @param saveAs true if save as... functionality is used; otherwise save \r
+        * functionality is used. \r
+        * @return The full path name of the exported model.\r
+        * @throws ExecutionException\r
+        */\r
+       protected String getAbsolutePath(final Resource model, ExecutionEvent event, boolean saveAs) throws ExecutionException {\r
+\r
+               // Determine the default path.\r
+               String path = null;\r
+               try {\r
+                       //If the model has been exported earlier, use that path.\r
+                       path = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
+                                               return null;\r
+                                       SysdynResource SR = SysdynResource.getInstance(graph);\r
+                                       String path = graph.syncRequest(new PossibleRelatedValue<String>(model, SR.SysdynModel_lastExportFilePath, Bindings.STRING ));\r
+                                       return path;\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               // If this is the initial save:\r
+               if (path == null) {\r
+                       if (saveAs == false) {\r
+                               // Save == Save as... when there has been no earlier save. \r
+                               return getAbsolutePath(model, event, true);\r
+                       }\r
+                       // Use import default path.\r
+                       path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);\r
+               }\r
+               if (saveAs == false && !(new File(path).exists())) {\r
+                       // Save == Save as... when the path doesn't exist. \r
+                       return getAbsolutePath(model, event, true);\r
+               }\r
+               if(path.isEmpty() || !(new File(path).exists()))\r
+                       path = Platform.getLocation().toOSString();\r
+                               \r
+        // Determine the default name\r
+               // FIXME: Model browser doesn't change its selection even if the selected object is removed,\r
+        // so you can try to export a removed model \r
+               String name = null;\r
+               try {\r
+                       name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
+                                               return null;\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       SysdynResource SR = SysdynResource.getInstance(graph);\r
+                                       // If the model has been exported earlier, use that name.\r
+                                       // When mere Save has progressed here, there is always be the name in the database.  \r
+                                       String name = graph.syncRequest(new PossibleRelatedValue<String>(model, SR.SysdynModel_lastExportFileName, Bindings.STRING ));\r
+                                       if (name == null) {\r
+                                               // If not, use the model name.\r
+                                               name = graph.syncRequest(new PossibleRelatedValue<String>(model, l0.HasName, Bindings.STRING ));\r
+                                       }\r
+                                       return name;\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               // Do not export if the resource has no name\r
+               if(name == null) return null;\r
+               \r
+               final String selected;\r
+               String fullPath = null;\r
+               if (saveAs == true) {\r
+               // Find a location (and name) for the exported library using FileDialog\r
+                       Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+                       FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
+                       fd.setText("Export Model");\r
+                       fd.setFileName(name);\r
+                       \r
+                       fd.setFilterPath(path);\r
+                       String[] filterExt = {"*.sysdyn"};\r
+                       fd.setFilterExtensions(filterExt);\r
+                       fd.setOverwrite(true);\r
+                       fullPath = fd.open();\r
+               }\r
+               else {\r
+                       // Save to the earlier location. \r
+                       fullPath = path;\r
+                       if (path.charAt(path.length() - 1) != '\\')\r
+                               fullPath += "\\"; // Saving to C:\ would otherwise add excess backslashes.\r
+                       fullPath += name;\r
+               }\r
+               selected = fullPath;\r
+               \r
+               if(selected == null) return null;\r
+\r
+               // Save location to preference store\r
+               try {\r
+                       SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       SysdynResource SR = SysdynResource.getInstance(graph);\r
+                                       graph.deny(model, SR.SysdynModel_lastExportFilePath);\r
+                                       graph.deny(model, SR.SysdynModel_lastExportFileName);\r
+                                       graph.addLiteral(model, SR.SysdynModel_lastExportFilePath, SR.SysdynModel_lastExportFilePath_Inverse, l0.String, new File(selected).getParent(), Bindings.STRING);\r
+                                       graph.addLiteral(model, SR.SysdynModel_lastExportFileName, SR.SysdynModel_lastExportFilePath_Inverse, l0.String, new File(selected).getName(), Bindings.STRING); \r
+                               }\r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               \r
+               return selected;\r
+\r
+       }\r
+       \r
+    protected static void setStatus(final String message) {\r
+       if (status != null)\r
+            status.setMessage(message);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModuleHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModuleHandler.java
new file mode 100644 (file)
index 0000000..6a0cc12
--- /dev/null
@@ -0,0 +1,276 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.exports;\r
+\r
+import java.io.File;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.MessageBox;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
+import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.graph.db.TransferableGraphSource;\r
+import org.simantics.graph.db.TransferableGraphs;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * Exports a selected module\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ExportModuleHandler extends AbstractHandler {\r
+\r
+       /**\r
+        * Temporary exception. At this phase, the system will not support exporting modules\r
+        * that depend on other modules. \r
+        * \r
+        * @author Teemu Lempinen\r
+        *\r
+        */\r
+       class ContainsDependenciesException extends DatabaseException {\r
+               private static final long serialVersionUID = -1533706136673146020L;\r
+               \r
+               private final Collection<String> dependencies;\r
+               \r
+               ContainsDependenciesException(Collection<String> dependencies) {\r
+                       this.dependencies = dependencies;\r
+               }\r
+               \r
+               public Collection<String> getDependencies() {\r
+                       return this.dependencies;\r
+               }\r
+               \r
+       }\r
+       \r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        final Resource modulesymbol = ResourceAdaptionUtils.toSingleResource(sel);\r
+        if(modulesymbol == null) return null;\r
+               \r
+               String name = null;\r
+               try {\r
+                       name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       ModelingResources mr = ModelingResources.getInstance(graph);\r
+                                       StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       \r
+                                       // Start checking for module dependencies\r
+                                       Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);\r
+                                       if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))\r
+                                               return null;\r
+                                       \r
+                                       Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
+                                       if (configuration == null)\r
+                                               return null;\r
+                                       \r
+                                       ArrayList<String> dependencies = null;\r
+                                       for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {\r
+                                               if(dependencies == null)\r
+                                                       dependencies = new ArrayList<String>();\r
+                                               String name = NameUtils.getSafeName(graph, r);\r
+                                               String instanceOf = NameUtils.getSafeName(graph, graph.getSingleObject(r, l0.InstanceOf));\r
+                                               dependencies.add(name + " : " + instanceOf);\r
+                                       }\r
+                                       if(dependencies != null && !dependencies.isEmpty())\r
+                                               throw new ContainsDependenciesException(dependencies);\r
+                                       // End checking for module dependencies. If dependencies were found, an exception was thrown\r
+                                       \r
+                                       String name = graph.getPossibleRelatedValue(component, l0.HasName, Bindings.STRING);\r
+                                       return name;\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+               } catch (ContainsDependenciesException e1) {\r
+                       Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+                       MessageBox mb = new MessageBox(shell, SWT.OK);\r
+                       StringBuilder sb = new StringBuilder();\r
+                       sb.append("This version does not support exporting modules with other module instances.\n\n");\r
+                       sb.append("Dependencies:\n");\r
+                       for(String s : e1.getDependencies())\r
+                               sb.append("    " + s + "\n");\r
+                       mb.setMessage(sb.toString());\r
+                       mb.setText("Module contains dependencies.");\r
+                       mb.open();\r
+                       return null;\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               \r
+        // Do not export if the resource has no name\r
+               if(name == null) return null;\r
+               \r
+        // Find a location (and name) for the exported library using FileDialog\r
+               Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+               FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
+               fd.setText("Export Module");\r
+               fd.setFileName(name);\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODULETPATH);\r
+               if(path.isEmpty() || !(new File(path).exists()))\r
+                       path = Platform.getLocation().toOSString();\r
+               fd.setFilterPath(path);\r
+               String[] filterExt = {"*.sysdynModule"};\r
+               fd.setFilterExtensions(filterExt);\r
+               fd.setOverwrite(true);\r
+               final String selected = fd.open();\r
+               if(selected == null) return null;\r
+               \r
+        // Save location to preference store\r
+               Activator.getDefault().getPreferenceStore().setValue(ImportUtilsUI.IMPORTMODULETPATH, (new File(selected)).getParent());\r
+               \r
+        // Asynchronously create the file using transferable graph\r
+               SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               ModelingResources mr = ModelingResources.getInstance(graph);\r
+\r
+                               final Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);\r
+                               if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))\r
+                                       return;\r
+                               String name = graph.syncRequest(new PossibleRelatedValue<String>(component, l0.HasName, Bindings.STRING ));\r
+                               final ArrayList<Pair<Resource, String>> roots = new ArrayList<Pair<Resource, String>>();\r
+                               roots.add(Pair.make(component, name));\r
+\r
+                               graph.asyncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+\r
+                                               Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
+                                               if (!graph.hasStatement(configuration, l0.PartOf, component)&& \r
+                                                               !graph.hasStatement(modulesymbol, l0.PartOf, component)) {\r
+                                                       // Make sure that configuration and symbol are included.\r
+                                                       // In old versions, they were attached to model, not to module.\r
+                                                       Resource previousPartof = graph.getSingleObject(configuration, l0.PartOf);\r
+\r
+                                                       graph.deny(configuration, l0.PartOf);\r
+                                                       graph.deny(modulesymbol, l0.PartOf);\r
+                                                       graph.claim(configuration, l0.PartOf, l0.ConsistsOf, component);\r
+                                                       graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, component);\r
+\r
+                                                       export(graph, selected, roots, component);\r
+\r
+                                                       graph.deny(configuration, l0.PartOf);\r
+                                                       graph.deny(modulesymbol, l0.PartOf);\r
+                                                       graph.claim(configuration, l0.PartOf, l0.ConsistsOf, previousPartof);\r
+                                                       graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, previousPartof);\r
+                                               } else {\r
+                                                       // Normal export\r
+                                                       export(graph, selected, roots, component);\r
+                                               }\r
+                                       }\r
+                               });\r
+\r
+                       }\r
+               });\r
+\r
+               return null;\r
+       }\r
+       \r
+       /**\r
+        * Export module (without dependencies to other modules) and write it to file. \r
+        * Disable existing enumeration replacement for during export.  \r
+        *  \r
+        * @param graph WriteGraph\r
+        * @param path Path for the exported file\r
+        * @param roots\r
+        * @param component Module\r
+        */\r
+       private void export(WriteGraph graph, final String path, ArrayList<Pair<Resource, String>> roots, final Resource component) {\r
+               \r
+               // FIXME: Enumeration replacement handling like this is not suitable.\r
+               try {\r
+                       Layer0 l0 = Layer0.getInstance(graph);\r
+                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                       StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+\r
+                       Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
+                       ArrayList<Pair<Resource, Resource>> replacements = new ArrayList<Pair<Resource, Resource>>();\r
+\r
+                       for(Resource enumeration : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {\r
+                               if(graph.hasStatement(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
+                                       for(Resource replacement : graph.getObjects(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
+                                               replacements.add(new Pair<Resource, Resource>(enumeration, replacement));\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       for(Pair<Resource,Resource> replacement : replacements)\r
+                               graph.deny(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);\r
+                       \r
+                       SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+\r
+                           @Override\r
+                           public void run(ReadGraph graph) throws DatabaseException {\r
+                               TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, component);\r
+                               TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));\r
+                               try {\r
+                                   TransferableGraphs.writeTransferableGraph(graph, "sysdynModule", 1, s,new File(path));\r
+                               } catch (Exception e) {\r
+                                   e.printStackTrace();\r
+                               }\r
+                           }\r
+                       });\r
+\r
+                       \r
+                       for(Pair<Resource,Resource> replacement : replacements)\r
+                               graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);\r
+\r
+               } catch (RuntimeBindingConstructionException e) {\r
+                       e.printStackTrace();\r
+//             } catch (IOException e) {\r
+//                     e.printStackTrace();\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/ReloadGameExperimentHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/ReloadGameExperimentHandler.java
new file mode 100644 (file)
index 0000000..218512c
--- /dev/null
@@ -0,0 +1,106 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.game;\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.ui.handlers.RunBasicExperiment;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Handler for initializing and reloading game experiments.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ReloadGameExperimentHandler extends RunBasicExperiment {\r
+       \r
+       private boolean started = false;\r
+       private boolean initialized = false;\r
+       \r
+       \r
+    public static final String COMMAND = "org.simantics.sysdyn.ui.reloadGame";\r
+    \r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+       SysdynGameExperimentBase game = getGameExperiment();\r
+        if(game != null)\r
+            game.simulate(true);\r
+        return null;\r
+    }\r
+       \r
+    /**\r
+     * Find currently active game experiment\r
+     * @return Currently active game experiment or null if game experiment not active\r
+     */\r
+    private SysdynGameExperimentBase getGameExperiment() {\r
+        // Find active experiment\r
+        IProject project = SimanticsUI.peekProject();\r
+        if (project == null)\r
+            return null;\r
+        \r
+        IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+\r
+        IExperiment active = manager.getActiveExperiment();\r
+        if (!(active instanceof SysdynGameExperimentBase))\r
+            return null;\r
+        \r
+        return (SysdynGameExperimentBase) active;\r
+    }\r
+       \r
+       @SuppressWarnings("rawtypes")\r
+       @Override\r
+       public void updateElement(UIElement element, Map parameters) {\r
+               // Disable button while initializign a model\r
+               super.updateElement(element, parameters);\r
+               \r
+               \r
+               // Change tooltip according to the current status\r
+               SysdynGameExperimentBase game = getGameExperiment();   \r
+\r
+        if(game == null) {\r
+                       started = false;\r
+                       initialized = false;\r
+                       return;\r
+        }\r
+        \r
+        ExperimentState state = game.getState();\r
+        \r
+               if(state==ExperimentState.INITIALIZING) {\r
+                       started = false;\r
+                       initialized = false;\r
+               } else if(state==ExperimentState.RUNNING) {\r
+                       started = true;\r
+                       initialized = false;\r
+               } else if(state==ExperimentState.STOPPED) {\r
+                       if(started && !initialized) {\r
+                               initialized = true;\r
+                       } \r
+               }\r
+               \r
+        \r
+        if(initialized) {\r
+            element.setTooltip("Reload Game");\r
+        } else {\r
+            element.setTooltip("Initialize Game");\r
+        }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/StepHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/StepHandler.java
new file mode 100644 (file)
index 0000000..ecb69ef
--- /dev/null
@@ -0,0 +1,108 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.game;\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Handler for stepping game simulations\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class StepHandler extends AbstractHandler implements IElementUpdater {\r
+       \r
+    public static String COMMAND = "org.simantics.sysdyn.ui.step";\r
+    \r
+       private boolean started = false;\r
+       private boolean initialized = false;\r
+       private boolean running = false;        \r
+    \r
+    private SysdynGameExperimentBase getGameExperiment() {\r
+        // Find active experiment\r
+        IProject project = SimanticsUI.peekProject();\r
+        if (project == null)\r
+            return null;\r
+        \r
+        IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+\r
+        IExperiment active = manager.getActiveExperiment();\r
+        if (!(active instanceof SysdynGameExperimentBase))\r
+            return null;\r
+        \r
+        return (SysdynGameExperimentBase) active;\r
+    }\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+        \r
+        SysdynGameExperimentBase game = getGameExperiment();\r
+        if(game != null)\r
+               game.simulateDuration(game.getStepDuration());\r
+       return null;\r
+    }\r
+\r
+       @SuppressWarnings("rawtypes")\r
+       @Override\r
+       public void updateElement(UIElement element, Map parameters) {\r
+               \r
+               // Disable button when model has not been initialized and change tooltip accordingly\r
+               SysdynGameExperimentBase game = getGameExperiment();   \r
+\r
+        if(game == null) {\r
+                       started = false;\r
+                       initialized = false;\r
+                       return;\r
+        }\r
+        \r
+        ExperimentState state = game.getState();\r
+        \r
+               if(state==ExperimentState.INITIALIZING) {\r
+                       started = false;\r
+                       initialized = false;\r
+                       running = false;\r
+               } else if(state==ExperimentState.RUNNING) {\r
+                       started = true;\r
+                       initialized = initialized == true ? true : false;\r
+                       running = true;\r
+               } else if(state==ExperimentState.STOPPED) {\r
+                       if(started && !initialized) {\r
+                               initialized = true;\r
+                       } \r
+                       running = false;\r
+               }\r
+        \r
+        if(initialized) {\r
+               if(!running)\r
+                       this.setBaseEnabled(true);\r
+               else\r
+                       this.setBaseEnabled(false);\r
+            element.setTooltip("Step");\r
+        } else {\r
+            this.setBaseEnabled(false);\r
+            element.setTooltip("Initialize Game First");\r
+        }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportExternalFunctionFilesHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportExternalFunctionFilesHandler.java
new file mode 100644 (file)
index 0000000..50277c1
--- /dev/null
@@ -0,0 +1,120 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.imports;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.IOException;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * Imports external functions to SysdynModelicaFunctions using FileDialog.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ImportExternalFunctionFilesHandler extends AbstractHandler {\r
+\r
+       public static final String[] C_EXTENSIONS = {"*.c","*.h","*.a","*.o"};\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+               Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+               Pair<String, String[]> selected = importFiles(shell, "Import...", C_EXTENSIONS);\r
+               if(selected.second == null || selected.second.length < 1) return null;\r
+\r
+               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                       \r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               // TODO: include files to database\r
+                       }\r
+               });\r
+               \r
+               return null;\r
+       }\r
+       \r
+       /**\r
+        * Opens a {@link FileDialog} to select the imported files.\r
+        *  \r
+        * @param shell SWT Shell\r
+        * @param text Header text for the FileDialog\r
+        * @param filter Filters for the FileDialog\r
+        * @return File names and paths for the files to be imported\r
+        */\r
+       public static Pair<String, String[]> importFiles(Shell shell, String text, String[] filter) {\r
+               FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
+               fd.setText(text);\r
+               fd.setFilterPath(Platform.getLocation().toOSString());\r
+               fd.setFilterExtensions(filter);\r
+               fd.open();\r
+               return new Pair<String, String[]>(fd.getFilterPath(), fd.getFileNames());\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Saves the given files as byte arrays to a function\r
+        * \r
+        * @param graph WriteGraph\r
+        * @param function Function where the files are to be added\r
+        * @param files Files to be added\r
+        * @throws DatabaseException\r
+        */\r
+       public static void addFilesToFunction(WriteGraph graph, Resource function, Pair<String, String[]> files) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               \r
+               if(!graph.isInstanceOf(function, sr.SysdynModelicaFunction))\r
+                       return;\r
+\r
+               for(String filename : files.second) {\r
+                       File file = new File(files.first, filename);\r
+                                       \r
+                       String name = file.getName();\r
+                       \r
+                       Resource externalFile = GraphUtils.create2(graph, \r
+                                       sr.ExternalFunctionFile,\r
+                                       l0.PartOf, function,\r
+                                       l0.HasName, name);\r
+                       \r
+                       try {\r
+                               byte[] fileBArray = new byte[(int)file.length()];\r
+                               FileInputStream fis = new FileInputStream(file);\r
+                               fis.read(fileBArray);\r
+                               graph.claimLiteral(externalFile, sr.ExternalFunctionFile_externalFile, fileBArray, Bindings.BYTE_ARRAY);\r
+                               fis.close();\r
+                       } catch (IOException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+\r
+               }\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportFunctionLibrary.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportFunctionLibrary.java
new file mode 100644 (file)
index 0000000..4e227e7
--- /dev/null
@@ -0,0 +1,88 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.imports;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.DatabaseJob;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Imports an exported function library (or shared function library) transferable graph. \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ImportFunctionLibrary  extends AbstractHandler {\r
+       \r
+       /**\r
+        * Called from a functions folder node\r
+        */\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        Resource r = ResourceAdaptionUtils.toSingleResource(sel);\r
+        if(r == null) {\r
+               FunctionsFolder mn = AdaptionUtils.adaptToSingle(sel, FunctionsFolder.class);\r
+               r = mn.data;\r
+        }\r
+        if(r == null) return null;\r
+        \r
+        final Resource functionLibrary = r;\r
+        \r
+        \r
+        // Get a transferable graph file\r
+               Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+               FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
+               fd.setText("Import Function Library");\r
+               \r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH);\r
+               if(path.isEmpty() || !(new File(path).exists()))\r
+                   path = Platform.getLocation().toOSString();\r
+               fd.setFilterPath(path);\r
+               String[] filterExt = {"*.sysdynFunctions; *.tg", "*.*"};\r
+               fd.setFilterExtensions(filterExt);\r
+               final String selected = fd.open();\r
+               if(selected == null) return null;\r
+\r
+               Job job = new DatabaseJob("Import function") {\r
+\r
+                   @Override\r
+                   protected IStatus run(IProgressMonitor monitor) {\r
+                       IStatus status = ImportUtilsUI.importFunctionLibrary(functionLibrary, selected, monitor);\r
+                       return status;\r
+                   }\r
+               };\r
+\r
+               job.setUser(true);\r
+               job.schedule();\r
+\r
+               return null;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportMdlHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportMdlHandler.java
new file mode 100644 (file)
index 0000000..8d35a4e
--- /dev/null
@@ -0,0 +1,88 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.imports;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.modelImport.MdlParser;\r
+import org.simantics.sysdyn.modelImport.model.Model;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Class for importing Vensim models (.mdl) to Simantics SysDyn using MdlParser \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ImportMdlHandler extends AbstractHandler {\r
+\r
+       public static String IMPORTMDLTPATH = "IMPORT_MDL_PATH";\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+               \r
+               final Resource project = SimanticsUI.getProject().get();\r
+               if(project == null) return null;\r
+\r
+               // Get the .mdl file\r
+               Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+               FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
+               fd.setText("Import .mdl");\r
+               String path = Activator.getDefault().getPreferenceStore().getString(IMPORTMDLTPATH);\r
+               if(path.isEmpty() || !(new File(path).exists()))\r
+                       path = Platform.getLocation().toOSString();\r
+               fd.setFilterPath(path);\r
+               String[] filterExt = {"*.mdl"};\r
+               fd.setFilterExtensions(filterExt);\r
+               String selected = fd.open();\r
+               if(selected == null) return null;\r
+\r
+               File file = new File(selected);\r
+               if(!file.isFile()) return null;\r
+               \r
+               Activator.getDefault().getPreferenceStore().setValue(IMPORTMDLTPATH, (new File(selected)).getParent());\r
+               \r
+               // Convert Vensim model to Simantics SysDyn format using MdlParser\r
+               final Model model;\r
+               try {\r
+                       model = MdlParser.parse(file);\r
+               }\r
+               catch (Exception e) {\r
+                       e.printStackTrace();\r
+                       return null;\r
+               }\r
+               \r
+               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               model.write(graph, project, new WriteContext());\r
+                       }\r
+               });\r
+               \r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModelHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModelHandler.java
new file mode 100644 (file)
index 0000000..2849101
--- /dev/null
@@ -0,0 +1,89 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.imports;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.DatabaseJob;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+/**\r
+ * Imports models from exported transferable graph files.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ImportModelHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        // Get imported transferable graph file using FileDialog\r
+        Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+        FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
+        fd.setText("Import Model");\r
+\r
+        String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);\r
+        if(path.isEmpty() || !(new File(path).exists())){\r
+               String execDir = System.getProperty("user.dir");\r
+               String slash = System.getProperty("file.separator");\r
+               path = execDir + slash + "sampleModels"; \r
+        }\r
+        \r
+        fd.setFilterPath(path);\r
+        String[] filterExt = {"*.sysdyn; *.tg", "*.*"};\r
+        fd.setFilterExtensions(filterExt);\r
+        final String selected = fd.open();\r
+        if(selected == null) return null;\r
+\r
+        Job job = new DatabaseJob("Import model") {\r
+\r
+            @Override\r
+            protected IStatus run(IProgressMonitor monitor) {\r
+               monitor.beginTask("Importing Model " + selected, 3);\r
+               IStatus status = null;\r
+               try {\r
+                       monitor.worked(1);\r
+                    status = ImportUtilsUI.importModelFile(selected, monitor);                         \r
+                    monitor.worked(2);\r
+               } catch (Exception e) {\r
+                       ExceptionUtils.logAndShowError("Model import failed, see exception for details",  e);\r
+                       ErrorLogger.defaultLogError("Model import failed, see exception for details", e);\r
+                       return Status.OK_STATUS;\r
+               } finally {\r
+                       monitor.done();\r
+               }\r
+\r
+                return status;\r
+            }\r
+        };\r
+        job.setUser(true);\r
+        job.schedule();\r
+\r
+        return null;\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModuleHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModuleHandler.java
new file mode 100644 (file)
index 0000000..19c4031
--- /dev/null
@@ -0,0 +1,83 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.imports;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.DatabaseJob;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Imports modules from exported transferable graph files.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ImportModuleHandler extends AbstractHandler {\r
+\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+               ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+\r
+               @SuppressWarnings("unchecked")\r
+               AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
+               if (node == null)\r
+                       return null;\r
+\r
+               final Resource model = node.data;\r
+\r
+               // Get imported transferable graph file using FileDialog\r
+               Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+               FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
+               fd.setText("Import Module");\r
+\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODULETPATH);\r
+               if(path.isEmpty() || !(new File(path).exists()))\r
+                       path = Platform.getLocation().toOSString();\r
+               fd.setFilterPath(path);\r
+               String[] filterExt = {"*.sysdynModule; *.tg", "*.*"};\r
+               fd.setFilterExtensions(filterExt);\r
+               final String selected = fd.open();\r
+               if(selected == null) return null;\r
+               \r
+               Job job = new DatabaseJob("Import module") {\r
+\r
+            @Override\r
+            protected IStatus run(IProgressMonitor monitor) {\r
+                IStatus status = ImportUtilsUI.importModuleFile(model, selected, monitor);\r
+                return status;\r
+            }\r
+        };\r
+        job.setUser(true);\r
+        job.schedule();\r
+\r
+               return null;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportSharedLibraryHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportSharedLibraryHandler.java
new file mode 100644 (file)
index 0000000..8165e54
--- /dev/null
@@ -0,0 +1,83 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.imports;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.DatabaseJob;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.graph.db.MissingDependencyException;\r
+import org.simantics.modeling.ModelingUtils;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class ImportSharedLibraryHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        // Get imported transferable graph file using FileDialog\r
+        Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+        FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
+        fd.setText("Import Shared Library");\r
+\r
+        String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);\r
+        if(path.isEmpty() || !(new File(path).exists())){\r
+               String execDir = System.getProperty("user.dir");\r
+               String slash = System.getProperty("file.separator");\r
+               path = execDir + slash + "sampleModels"; \r
+        }\r
+        \r
+        fd.setFilterPath(path);\r
+        String[] filterExt = {"*.sharedLibrary; *.tg", "*.*"};\r
+        fd.setFilterExtensions(filterExt);\r
+        final String selected = fd.open();\r
+        if(selected == null) return null;\r
+\r
+        Job job = new DatabaseJob("Import Shared Library") {\r
+\r
+            @Override\r
+            protected IStatus run(IProgressMonitor monitor) {\r
+               monitor.beginTask("Importing Shared Library " + selected, 3);\r
+               try {\r
+                       monitor.worked(1);\r
+                                       ModelingUtils.importSharedOntology(selected);\r
+                                       monitor.worked(2);\r
+               } catch (Exception e) {\r
+                       ExceptionUtils.logAndShowError(e);\r
+                       ErrorLogger.defaultLogError("Shared Library import failed, see exception for details.", e);\r
+               } finally {\r
+                                       monitor.done();\r
+                               }\r
+                return Status.OK_STATUS;\r
+            }\r
+        };\r
+        job.setUser(true);\r
+        job.schedule();\r
+\r
+        return null;\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewBarChartHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewBarChartHandler.java
new file mode 100644 (file)
index 0000000..88aa7eb
--- /dev/null
@@ -0,0 +1,110 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.util.Collections;\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Handler for creating a new Bar Chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewBarChartHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        \r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+\r
+        ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        final Resource model = node.data;        \r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(g);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
+                G2DResource g2d = G2DResource.getInstance(g);\r
+\r
+                Resource jfreechart = GraphUtils.create2(g, jfree.Chart,\r
+                        l0.HasName, "BarChart" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, NameUtils.findFreshLabel(g, "Bar Chart", model),\r
+                        l0.PartOf, model,\r
+                        jfree.Chart_visibleBorder, true,\r
+                        jfree.Chart_borderWidth, 3,\r
+                        jfree.Chart_visibleLegend, false\r
+                        );\r
+                \r
+                g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
+\r
+                GraphUtils.create2(g, jfree.TextTitle,\r
+                        l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, "Bar Chart Title",\r
+                        jfree.Title_position, jfree.Top,\r
+                        l0.PartOf, jfreechart);\r
+\r
+                Resource domainAxis = GraphUtils.create2(g, jfree.CategoryAxis,\r
+                        l0.HasName, "CategoryAxis" + UUID.randomUUID().toString());\r
+                \r
+                Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
+                        l0.HasName, "NumberAxis" + UUID.randomUUID().toString());\r
+\r
+                Resource renderer = GraphUtils.create2(g, jfree.BarRenderer);\r
+                \r
+                Resource dataset = GraphUtils.create2(g, jfree.CategoryDataset,\r
+                        l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),\r
+                        jfree.Dataset_mapToDomainAxis, domainAxis,\r
+                        jfree.Dataset_mapToRangeAxis, rangeAxis,\r
+                        jfree.Dataset_seriesList, ListUtils.create(g, Collections.<Resource>emptyList()),\r
+                        jfree.Dataset_renderer, renderer);\r
+\r
+                GraphUtils.create2(g, jfree.CategoryPlot,\r
+                        l0.HasName, "Category plot" + UUID.randomUUID().toString(),\r
+                        l0.PartOf, jfreechart,\r
+                        jfree.Plot_domainAxis, domainAxis,\r
+                        jfree.Plot_rangeAxis, rangeAxis,\r
+                        jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),\r
+                        l0.ConsistsOf, dataset,\r
+                        l0.ConsistsOf, domainAxis,\r
+                        l0.ConsistsOf, rangeAxis);\r
+            }\r
+\r
+        });\r
+        \r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewEnumerationNodeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewEnumerationNodeHandler.java
new file mode 100644 (file)
index 0000000..6801225
--- /dev/null
@@ -0,0 +1,87 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Creates a new Enumeration node to a configuration or module\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewEnumerationNodeHandler extends AbstractHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+               final Resource resource = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
+        \r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+               Layer0 l0 = Layer0.getInstance(g);\r
+               \r
+               // Find the actual configuration. Possible cases for resource are sr.Configuration, sr.ModuleSymbol or sr.Module.\r
+               Resource configuration = null;\r
+               if(g.isInstanceOf(resource, sr.Configuration)) {\r
+                       configuration = resource;\r
+               } else if(g.isInheritedFrom(resource, sr.ModuleSymbol)) {\r
+                       Resource module = g.getPossibleObject(resource,ModelingResources.getInstance(g).SymbolToComponentType);\r
+                       configuration = g.getPossibleObject(module, StructuralResource2.getInstance(g).IsDefinedBy);\r
+               } else {\r
+                       Resource instanceOf = g.getSingleObject(resource, l0.InstanceOf);\r
+                       if(g.isInheritedFrom(instanceOf, sr.Module)) {\r
+                               configuration = g.getPossibleObject(instanceOf, StructuralResource2.getInstance(g).IsDefinedBy);\r
+                       } else {\r
+                               return;\r
+                       }\r
+               }\r
+\r
+               // Create the enumeartion\r
+               \r
+               String name = NameUtils.findFreshName(g, "Enum", configuration, l0.ConsistsOf, "%s%d");\r
+               \r
+               GraphUtils.create2(g, \r
+                               sr.Enumeration,\r
+                               l0.HasName, name,\r
+                               sr.Enumeration_enumerationIndexList, ListUtils.create(g, new ArrayList<Resource>()),\r
+                               l0.PartOf, configuration);\r
+            }\r
+        });\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewExperimentNodeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewExperimentNodeHandler.java
new file mode 100644 (file)
index 0000000..0ddf1a3
--- /dev/null
@@ -0,0 +1,98 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Creates a new normal SysDyn experiment\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewExperimentNodeHandler extends AbstractHandler {\r
+\r
+    /**\r
+     * Assumes that it is called from a node that has a SysDyn model as its resource.\r
+     */\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+        ExperimentsFolder node = AdaptionUtils.adaptToSingle(sel, ExperimentsFolder.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        final Resource model = node.data;\r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(g);\r
+                String label = NameUtils.findFreshName(g, getNameSuggestion(), model, l0.ConsistsOf, l0.HasLabel, "%s%d");\r
+                Resource experiment = GraphUtils.create2(g, getExperimentType(g),\r
+                        l0.HasName, UUID.randomUUID().toString(),\r
+                        l0.HasLabel, label,\r
+                        l0.PartOf, model);\r
+                configureExperiment(g, experiment);\r
+            }\r
+        });\r
+        return null;\r
+    }\r
+    \r
+    /**\r
+     * Override to do experiment-specific alterations\r
+     */\r
+    protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
+        \r
+    }\r
+    \r
+    /**\r
+     * Get the type of this experiment.\r
+     * \r
+     * @param g ReadGraph\r
+     * @return The type resource of this experiment\r
+     */\r
+    protected Resource getExperimentType(ReadGraph g) {\r
+        return SysdynResource.getInstance(g).BasicExperiment;\r
+    }\r
+    \r
+    /**\r
+     * Returns the suggested name for this experiment.\r
+     * If the name has already been taken, appropriate prefix needs to be added. \r
+     *  \r
+     * @return Suggested name for this experiment. \r
+     */\r
+    protected String getNameSuggestion() {\r
+        return "Experiment";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionHandler.java
new file mode 100644 (file)
index 0000000..7acab21
--- /dev/null
@@ -0,0 +1,86 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Creates a new function to a SysdynModel or Library.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewFunctionHandler extends AbstractHandler {\r
+\r
+    /**\r
+     * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource\r
+     */\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+        @SuppressWarnings("unchecked")\r
+               AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        final Resource data = node.data;\r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(g);\r
+                SysdynResource sr = SysdynResource.getInstance(g);\r
+\r
+                // Library can be either SysdynModel or L0.Library. \r
+                Resource library = null;\r
+                if(g.isInstanceOf(data, sr.SysdynModel) || g.isInstanceOf(data, l0.Library))\r
+                       library = data;\r
+                else if (g.isInstanceOf(data, sr.SysdynModelicaFunction))\r
+                       library = g.getPossibleObject(data, l0.PartOf);\r
+                \r
+                if(library == null)\r
+                       return;\r
+                       \r
+                \r
+                String name = NameUtils.findFreshName(g, "Function", library, l0.ConsistsOf, "%s%d");\r
+\r
+                GraphUtils.create2(g, sr.SysdynModelicaFunction,\r
+                        l0.HasName, name,\r
+                        l0.HasDescription, "",\r
+                        sr.SysdynModelicaFunction_modelicaFunctionCode, "",\r
+                        l0.PartOf, library);\r
+            }\r
+        });\r
+        \r
+        return null;\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionLibraryHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionLibraryHandler.java
new file mode 100644 (file)
index 0000000..bf62f3e
--- /dev/null
@@ -0,0 +1,106 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Creates a new function library to a model or other library.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewFunctionLibraryHandler extends AbstractHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+        @SuppressWarnings("unchecked")\r
+               AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        createLibrary(node.data, false);\r
+        return null;\r
+       }\r
+       \r
+       /**\r
+        * Create function library. Shared libraries are created to root, local libraries to the model. \r
+        * Shared libraries can be used in other models in the project.\r
+        * \r
+        * @param model The initial location of the command\r
+        * @param shared Shared libraries are created to root, local libraries to the model.\r
+        */\r
+       protected void createLibrary(final Resource model, final boolean shared) {\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(g);\r
+                SysdynResource sr = SysdynResource.getInstance(g);\r
+\r
+                if(!(g.isInstanceOf(model, sr.SysdynModel) ||\r
+                               g.isInstanceOf(model, sr.SysdynModelicaFunctionLibrary) ||\r
+                                               g.isInstanceOf(model, sr.SharedFunctionOntology)))\r
+                       return;\r
+\r
+                Resource root = model;\r
+\r
+                String name = "FunctionLibrary";\r
+                Resource libraryType = sr.SysdynModelicaFunctionLibrary;\r
+                \r
+                if(shared) {\r
+                       \r
+                       try {\r
+                               root = g.getResource("http://SharedOntologies");\r
+                       } catch (ResourceNotFoundException e) {\r
+                               root = g.getResource("http:/");\r
+                               root = GraphUtils.create2(g, l0.Library, \r
+                                               l0.HasName, "SharedOntologies",\r
+                                               l0.PartOf, root);\r
+                       }\r
+                       \r
+                       name = "Shared" + name;\r
+                    libraryType = sr.SharedFunctionOntology;\r
+                }\r
+\r
+                name = NameUtils.findFreshName(g, name, root, l0.ConsistsOf, "%s%d");\r
+                \r
+                Resource functionLibrary = GraphUtils.create2(g, libraryType,\r
+                        l0.HasName, name,\r
+                        l0.HasDescription, "",\r
+                        l0.PartOf, root);\r
+                \r
+                if(shared)\r
+                       g.claim(model, l0.IsLinkedTo, functionLibrary);\r
+            }\r
+        });\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewGameExperimentNodeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewGameExperimentNodeHandler.java
new file mode 100644 (file)
index 0000000..601de37
--- /dev/null
@@ -0,0 +1,45 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+\r
+/**\r
+ * Handler for creating a new Game Experiment\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewGameExperimentNodeHandler extends NewExperimentNodeHandler  {\r
+\r
+    protected Resource getExperimentType(ReadGraph g) {\r
+        return SysdynResource.getInstance(g).GameExperiment;\r
+    }\r
+    \r
+    /**\r
+     * Override to do experiment-specific alterations\r
+     */\r
+    protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
+       SysdynResource sr = SysdynResource.getInstance(graph);\r
+        graph.claimLiteral(experiment, sr.GameExperiment_stepDuration, SysdynGameExperimentBase.DEFAULT_STEP_DURATION);\r
+        graph.claimLiteral(experiment, sr.GameExperiment_stepLength, SysdynGameExperimentBase.DEFAULT_STEP_LENGTH);\r
+    }\r
+\r
+    protected String getNameSuggestion() {\r
+        return "Game Experiment";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewHistoryDataHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewHistoryDataHandler.java
new file mode 100644 (file)
index 0000000..d97b684
--- /dev/null
@@ -0,0 +1,69 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Handler for creating new history dataset\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewHistoryDataHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+\r
+        final Resource experiment = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(g);\r
+                Layer0 l0 = Layer0.getInstance(g);\r
+                if(!g.isInstanceOf(experiment, sr.Experiment))\r
+                    return; // Not called from an experiment\r
+\r
+                Resource model = g.getPossibleObject(experiment, l0.PartOf);\r
+                // Create the history dataset\r
+                GraphUtils.create2(g, \r
+                        sr.HistoryDataset,\r
+                        l0.HasName, "HistoryDataset" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, NameUtils.findFreshLabel(g, "History Dataset", experiment),\r
+                        sr.Experiment_result_Inverse, experiment, \r
+                        sr.HistoryDataset_columns, Boolean.TRUE,\r
+                        l0.PartOf, model);\r
+            }\r
+        });\r
+        return null;\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModelHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModelHandler.java
new file mode 100644 (file)
index 0000000..6ed6858
--- /dev/null
@@ -0,0 +1,64 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.simantics.DatabaseJob;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.utils.ModelUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Creates a new SysDyn model.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewModelHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        \r
+        \r
+        Job job = new DatabaseJob("Creating System Dynamics Model") {\r
+            @Override\r
+            protected IStatus run(IProgressMonitor monitor) {\r
+                try {\r
+                    SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                        @Override\r
+                        public void perform(WriteGraph graph) throws DatabaseException {\r
+                            // Use ModelUtils to keep all model creations up-to-date\r
+                            ModelUtils.createModel(graph);\r
+                        }\r
+                    });\r
+                    return Status.OK_STATUS;\r
+                } catch (DatabaseException e) {\r
+                    return new Status(IStatus.ERROR, Activator.PLUGIN_ID, getName() + " failed.", e);\r
+                }\r
+            }\r
+        };\r
+//        job.setUser(true);\r
+        job.schedule();\r
+\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModuleNodeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModuleNodeHandler.java
new file mode 100644 (file)
index 0000000..60170f7
--- /dev/null
@@ -0,0 +1,132 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.Template;\r
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.actions.newActions.NewModuleTypeAction;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModulesNode;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+\r
+/**\r
+ * Creates a new module node for a model.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewModuleNodeHandler extends AbstractHandler {\r
+\r
+    /**\r
+     * Assumes to be called from a node that has a SysDyn model as its resource.\r
+     */\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        \r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+        ModulesNode node = AdaptionUtils.adaptToSingle(sel, ModulesNode.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        final Resource model = node.data;        \r
+        \r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+            \r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(g);\r
+                Layer0 l0 = Layer0.getInstance(g);\r
+                Layer0X L0X = Layer0X.getInstance(g);\r
+                ModelingResources mr = ModelingResources.getInstance(g);\r
+                StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
+                \r
+                String name = NameUtils.findFreshName(g, "ModuleType", model, l0.ConsistsOf, "%s%d");\r
+                \r
+                Resource moduleType = g.newResource();\r
+                g.claimLiteral(moduleType, l0.HasName, name);\r
+                g.claim(moduleType, l0.Inherits, sr.Module);\r
+                g.claim(moduleType, l0.PartOf, model);\r
+                \r
+                \r
+                \r
+                Resource configuration = GraphUtils.create2(g, \r
+                        sr.Configuration,\r
+                        l0.HasName, name + "Configuration",\r
+                        l0.PartOf, moduleType);\r
+                \r
+                g.claim(moduleType, sr2.IsDefinedBy , configuration);\r
+                \r
+                Resource diagram = g.newResource();\r
+                g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,\r
+                        ArrayMap\r
+                        .keys("", "diagram", "name")\r
+                        .values(configuration, diagram, "Diagrammi")\r
+                );\r
+                \r
+                \r
+                // Remove default mapping and add sysdyn mapping\r
+                for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {\r
+                       if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {\r
+                               g.deny(diagram, L0X.HasTrigger, trigger);\r
+                       }\r
+                }\r
+                \r
+                Resource mapping = g.newResource();\r
+                g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);\r
+                g.claim(diagram, L0X.HasTrigger, mapping);\r
+                \r
+                Resource moduleSymbol = g.newResource();\r
+                g.claimLiteral(moduleSymbol, l0.HasName, name + " Symbol");\r
+                g.claimLiteral(moduleSymbol, l0.HasLabel, name + " Symbol");\r
+                g.claim(moduleSymbol, l0.Inherits, sr.ModuleSymbol);\r
+                g.claim(moduleSymbol, mr.SymbolToComponentType, moduleType);\r
+                g.claim(moduleSymbol, l0.PartOf, moduleType);\r
+                \r
+                Resource terminal = g.newResource();\r
+                g.claim(terminal, l0.InstanceOf, sr.SysdynTerminal);\r
+                Resource relation = NewModuleTypeAction.createTerminalRelation(g, moduleSymbol, sr.IsHeadOfTerminal, sr.Variable_isHeadOf);\r
+                DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal, relation);               \r
+                \r
+                Resource terminal2 = g.newResource();\r
+                g.claim(terminal2, l0.InstanceOf, sr.SysdynTerminal);\r
+                relation = NewModuleTypeAction.createTerminalRelation(g, moduleSymbol, sr.IsTailOfTerminal, sr.Variable_isTailOf);\r
+                DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal2, relation);\r
+                                \r
+                g.claim(moduleSymbol, sr2.IsDefinedBy, OrderedSetUtils.create(g, sr2.Composite, terminal, terminal2));\r
+            \r
+                \r
+            }\r
+        });\r
+        return null;\r
+    }\r
+    \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPieChartHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPieChartHandler.java
new file mode 100644 (file)
index 0000000..3f17f99
--- /dev/null
@@ -0,0 +1,92 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.util.Collections;\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Handler for craeting a new Pie Chart\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewPieChartHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        \r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+\r
+        ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        final Resource model = node.data;        \r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(g);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
+                G2DResource g2d = G2DResource.getInstance(g);\r
+\r
+                Resource jfreechart = GraphUtils.create2(g, jfree.Chart,\r
+                        l0.HasName, "PieChart" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, NameUtils.findFreshLabel(g, "Pie Chart", model),\r
+                        l0.PartOf, model,\r
+                        jfree.Chart_visibleBorder, true,\r
+                        jfree.Chart_borderWidth, 3);\r
+                g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
+\r
+                GraphUtils.create2(g, jfree.TextTitle,\r
+                        l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, "Pie Chart Title",\r
+                        jfree.Title_position, jfree.Top,\r
+                        l0.PartOf, jfreechart);\r
+                \r
+                Resource dataset = GraphUtils.create2(g, jfree.PieDataset,\r
+                        l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),\r
+                        jfree.Dataset_seriesList, ListUtils.create(g, Collections.<Resource>emptyList())\r
+                        );\r
+\r
+                GraphUtils.create2(g, jfree.PiePlot,\r
+                        l0.HasName, "PiePlot" + UUID.randomUUID().toString(),\r
+                        l0.PartOf, jfreechart,\r
+                        l0.ConsistsOf, dataset\r
+                        );\r
+            }\r
+\r
+        });\r
+        \r
+        return null;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPlaybackExperimentNodeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPlaybackExperimentNodeHandler.java
new file mode 100644 (file)
index 0000000..a54ce36
--- /dev/null
@@ -0,0 +1,55 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.awt.Color;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Creates a new playback experiment.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewPlaybackExperimentNodeHandler  extends NewExperimentNodeHandler  {\r
+\r
+    protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
+        G2DResource g2d = G2DResource.getInstance(graph);\r
+        Resource defaultGradient = GraphUtils.create2(graph, g2d.ColorGradient);\r
+        graph.claim(experiment, g2d.HasColorGradient, defaultGradient);\r
+\r
+        Resource placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
+                g2d.HasGradientPosition, 0.0);\r
+        graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(0, 62, 133).getColorComponents(new float[4]));\r
+        graph.claim(defaultGradient, g2d.HasColorPlacement, placement);\r
+        \r
+        placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
+                g2d.HasGradientPosition, 1.0);\r
+        graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(255, 230, 0).getColorComponents(new float[4]));\r
+        graph.claim(defaultGradient, g2d.HasColorPlacement, placement);\r
+    }\r
+\r
+    protected Resource getExperimentType(ReadGraph g) {\r
+        return SysdynResource.getInstance(g).PlaybackExperiment;\r
+    }\r
+\r
+    protected String getNameSuggestion() {\r
+        return "Playback Experiment";\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityAnalysisExperimentNodeHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityAnalysisExperimentNodeHandler.java
new file mode 100644 (file)
index 0000000..1a8ae7a
--- /dev/null
@@ -0,0 +1,66 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Creates a new sensitivity analysis experiment.\r
+ * \r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class NewSensitivityAnalysisExperimentNodeHandler extends NewExperimentNodeHandler  {\r
+\r
+    @Override\r
+    protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        \r
+        Resource method = GraphUtils.create2(graph, sr.RandomGenerator);\r
+        graph.claim(experiment, sr.SensitivityAnalysisExperiment_method, method);\r
+\r
+        Resource distribution = GraphUtils.create2(graph, sr.UniformDistribution,\r
+                sr.UniformDistribution_minValue, 0.0,\r
+                sr.UniformDistribution_maxValue, 10.0);\r
+        \r
+        Resource parameter = GraphUtils.create2(graph, sr.SensitivityAnalysisExperiment_Parameter,\r
+                       sr.SensitivityAnalysisExperiment_Parameter_propabilityDistribution, distribution,\r
+                sr.SensitivityAnalysisExperiment_Parameter_variable, ChartUtils.emptyVariableName,\r
+                L0.PartOf, experiment);\r
+        \r
+        ArrayList<Resource> parameterList = new ArrayList<Resource>();\r
+        parameterList.add(parameter);\r
+        \r
+        graph.claim(experiment, sr.SensitivityAnalysisExperiment_parameterList, ListUtils.create(graph, parameterList));\r
+    }\r
+\r
+    @Override\r
+    protected Resource getExperimentType(ReadGraph g) {\r
+        return SysdynResource.getInstance(g).SensitivityAnalysisExperiment;\r
+    }\r
+\r
+    @Override\r
+    protected String getNameSuggestion() {\r
+        return "Sensitivity Experiment";\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityChartHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityChartHandler.java
new file mode 100644 (file)
index 0000000..013c560
--- /dev/null
@@ -0,0 +1,154 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.awt.Color;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class NewSensitivityChartHandler extends AbstractHandler {\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+\r
+        ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        final Resource model = node.data;        \r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(g);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
+                G2DResource g2d = G2DResource.getInstance(g);\r
+                SysdynResource SR = SysdynResource.getInstance(g);\r
+\r
+                Resource jfreechart = GraphUtils.create2(g, jfree.Chart,\r
+                        l0.HasName, "SensitivityChart" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, NameUtils.findFreshLabel(g, "SensitivityChart", model),\r
+                        l0.PartOf, model,\r
+                        jfree.Chart_visibleBorder, true,\r
+                        jfree.Chart_borderWidth, 3);\r
+                g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
+\r
+                GraphUtils.create2(g, jfree.TextTitle,\r
+                        l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, "Chart Title",\r
+                        jfree.Title_position, jfree.Top,\r
+                        l0.PartOf, jfreechart);\r
+\r
+                Resource domainAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
+                        l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
+                        jfree.variableRVI, "/time",\r
+                        l0.HasLabel, "Time");\r
+                Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
+                        l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, "");\r
+\r
+                Resource renderer = GraphUtils.create2(g, jfree.DeviationRenderer);\r
+                \r
+                Color[] colors = {\r
+                        new Color(255, 255, 64),\r
+                        new Color(0, 255, 0),\r
+                        new Color(0, 0, 255),\r
+                        new Color(128, 128, 128),\r
+                        new Color(192, 192, 192)\r
+                        };\r
+                \r
+                float[] colorContainer = new float[] {0, 0, 0, 1};\r
+\r
+                ArrayList<Resource> confidenceBounds = new ArrayList<Resource>();\r
+                confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,\r
+                        SR.Charts_SensitivityDataset_ConfidenceBound_percent, 25.0\r
+                        ));      \r
+                g.claimLiteral(confidenceBounds.get(0), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[0].getColorComponents(colorContainer));\r
+                \r
+                \r
+                confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,\r
+                        SR.Charts_SensitivityDataset_ConfidenceBound_percent, 50.0\r
+                        ));  \r
+                g.claimLiteral(confidenceBounds.get(1), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[1].getColorComponents(colorContainer));\r
+\r
+                confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,\r
+                        SR.Charts_SensitivityDataset_ConfidenceBound_percent, 75.0\r
+                        ));  \r
+                g.claimLiteral(confidenceBounds.get(2), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[2].getColorComponents(colorContainer));\r
+\r
+                confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,\r
+                        SR.Charts_SensitivityDataset_ConfidenceBound_percent, 100.0\r
+                        )); \r
+                g.claimLiteral(confidenceBounds.get(3), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[3].getColorComponents(colorContainer));\r
+\r
+                confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound\r
+                        ));  \r
+                g.claimLiteral(confidenceBounds.get(4), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[4].getColorComponents(colorContainer));\r
+\r
+                \r
+                Resource dataset = GraphUtils.create2(g, SR.Charts_SensitivityDataset,\r
+                        l0.HasName, "SensitivityDataset" + UUID.randomUUID().toString(),\r
+                        jfree.Dataset_mapToDomainAxis, domainAxis,\r
+                        jfree.Dataset_mapToRangeAxis, rangeAxis,\r
+                        jfree.Dataset_seriesList, ListUtils.create(g, new ArrayList<Resource>()),\r
+                        jfree.Dataset_renderer, renderer,\r
+                        SR.Charts_SensitivityDataset_confidenceBounds, ListUtils.create(g, confidenceBounds)\r
+                        );\r
+                \r
+                ChartUtils.createSeries(g, dataset, null);\r
+                \r
+\r
+\r
+\r
+                GraphUtils.create2(g, SR.Charts_SensitivityPlot,\r
+                        l0.HasName, "SensitivityPlot" + UUID.randomUUID().toString(),\r
+                        l0.PartOf, jfreechart,\r
+                        jfree.Plot_domainAxis, domainAxis,\r
+                        jfree.Plot_rangeAxis, rangeAxis,\r
+                        jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),\r
+                        l0.ConsistsOf, dataset,\r
+                        l0.ConsistsOf, domainAxis,\r
+                        l0.ConsistsOf, rangeAxis);\r
+            }\r
+\r
+        });\r
+\r
+\r
+\r
+        return null;\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSharedFunctionLibraryHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSharedFunctionLibraryHandler.java
new file mode 100644 (file)
index 0000000..ab79d1f
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Creates a new shared function library.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewSharedFunctionLibraryHandler extends NewFunctionLibraryHandler {\r
+\r
+       @Override\r
+       public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        \r
+        @SuppressWarnings("unchecked")\r
+               AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        createLibrary(node.data, true);\r
+        return null;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSpreadSheetHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSpreadSheetHandler.java
new file mode 100644 (file)
index 0000000..3a64607
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.utils.SheetUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+/**\r
+ * Creates a new spreadsheet sheet to a book.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NewSpreadSheetHandler extends AbstractHandler {\r
+\r
+    /**\r
+     * Called from a node that has a book as its resource.\r
+     */\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+        final Resource book = ResourceAdaptionUtils.toSingleResource(sel);\r
+        if(book == null) return null;\r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+            \r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                SheetUtils.createSheet(graph, book, null, new String[] {}, new int[] {50});\r
+            }\r
+        });      \r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewXYLineChartHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewXYLineChartHandler.java
new file mode 100644 (file)
index 0000000..2f06ce8
--- /dev/null
@@ -0,0 +1,114 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.newComponents;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Handler for creating a new XYLineChart in model browser\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class NewXYLineChartHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+\r
+\r
+        ISelection sel = HandlerUtil.getCurrentSelection(event);\r
+\r
+        ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);\r
+        if (node == null)\r
+            return null;\r
+\r
+        final Resource model = node.data;        \r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph g) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(g);\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
+                G2DResource g2d = G2DResource.getInstance(g);\r
+\r
+                Resource jfreechart = GraphUtils.create2(g, jfree.Chart,\r
+                        l0.HasName, "Chart" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, NameUtils.findFreshLabel(g, "Chart", model),\r
+                        l0.PartOf, model,\r
+                        jfree.Chart_visibleBorder, true,\r
+                        jfree.Chart_borderWidth, 3);\r
+                g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
+\r
+                GraphUtils.create2(g, jfree.TextTitle,\r
+                        l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, "Chart Title",\r
+                        jfree.Title_position, jfree.Top,\r
+                        l0.PartOf, jfreechart);\r
+\r
+                Resource domainAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
+                        l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
+                        jfree.variableRVI, "/time",\r
+                        l0.HasLabel, "Time");\r
+                Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
+                        l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
+                        l0.HasLabel, "Y-axis");\r
+                \r
+                Resource renderer = GraphUtils.create2(g, jfree.XYLineRenderer);\r
+\r
+                Resource dataset = GraphUtils.create2(g, jfree.XYDataset,\r
+                        l0.HasName, "XYDataset" + UUID.randomUUID().toString(),\r
+                        jfree.Dataset_mapToDomainAxis, domainAxis,\r
+                        jfree.Dataset_mapToRangeAxis, rangeAxis,\r
+                        jfree.Dataset_seriesList, ListUtils.create(g, new ArrayList<Resource>()),\r
+                        jfree.Dataset_renderer, renderer);\r
+\r
+                GraphUtils.create2(g, jfree.XYPlot,\r
+                        l0.HasName, "XYPlot" + UUID.randomUUID().toString(),\r
+                        l0.PartOf, jfreechart,\r
+                        jfree.Plot_domainAxis, domainAxis,\r
+                        jfree.Plot_rangeAxis, rangeAxis,\r
+                        jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),\r
+                        l0.ConsistsOf, dataset,\r
+                        l0.ConsistsOf, domainAxis,\r
+                        l0.ConsistsOf, rangeAxis);\r
+            }\r
+\r
+        });\r
+\r
+\r
+\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/RunSensitivityAnalysisExperiment.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/RunSensitivityAnalysisExperiment.java
new file mode 100644 (file)
index 0000000..a660276
--- /dev/null
@@ -0,0 +1,69 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.sensitivityAnalysis;\r
+\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IDynamicExperiment;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Handler for starting a sensitivity analysis simulation\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class RunSensitivityAnalysisExperiment extends AbstractHandler implements IElementUpdater {\r
+    \r
+    public static final String COMMAND = "org.simantics.sysdyn.ui.runSensitivityAnalysis";\r
+    \r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        // Current functionality is normal run experiment\r
+        \r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+        \r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof IDynamicExperiment)\r
+            ((IDynamicExperiment)experiment).simulate(true);\r
+        return null;\r
+    }\r
+\r
+    // What does this method do, is this needed?\r
+    @SuppressWarnings("rawtypes")\r
+       @Override\r
+    public void updateElement(UIElement element, Map parameters) {\r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof SysdynExperiment) {\r
+               ExperimentState state = experiment.getState();\r
+               if(state == ExperimentState.RUNNING) {\r
+                       this.setBaseEnabled(false);\r
+               } else {\r
+                        this.setBaseEnabled(true);\r
+               }\r
+        }        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/SaveResultsHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/SaveResultsHandler.java
new file mode 100644 (file)
index 0000000..dab71d2
--- /dev/null
@@ -0,0 +1,45 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.sensitivityAnalysis;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.simantics.simulation.experiment.IDynamicExperiment;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Save the results of a sensitivity analysis experiment\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SaveResultsHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        // Current functionality is normal run experiment\r
+        \r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+        \r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof IDynamicExperiment) {\r
+            ((IDynamicExperiment)experiment).saveState();\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/ToggleSimulation.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/ToggleSimulation.java
new file mode 100644 (file)
index 0000000..f90605c
--- /dev/null
@@ -0,0 +1,86 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.sensitivityAnalysis;\r
+\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.Command;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.commands.State;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.commands.ICommandService;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Handle for the Toggle Simulation button. When the button is down, the\r
+ * simulation is run every time the model is changed.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ToggleSimulation extends AbstractHandler implements IElementUpdater {\r
+\r
+    public static final String COMMAND = "org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation";\r
+    public static final String STATE = "org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation.state";\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        // Current functionality is normal run experiment\r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+\r
+        ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = service.getCommand(COMMAND);\r
+        State state = command.getState(STATE);\r
+        Boolean value = (Boolean) state.getValue();\r
+        value = !value;\r
+        state.setValue(value);\r
+        service.refreshElements(RunSensitivityAnalysisExperiment.COMMAND, null);\r
+        \r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment instanceof SysdynExperiment) {\r
+            if(getState()) {\r
+                ((SysdynExperiment)experiment).toggleSimulation(true);\r
+            } else {\r
+                ((SysdynExperiment)experiment).toggleSimulation(false);\r
+            }\r
+        }\r
+            \r
+        return null;\r
+    }\r
+\r
+    public static Boolean getState() {\r
+        ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = service.getCommand(COMMAND);\r
+        State state = command.getState(STATE);\r
+        return (Boolean)state.getValue();\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+       @Override\r
+    public void updateElement(UIElement element, Map parameters) {\r
+        ICommandService commandService =\r
+            (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = commandService.getCommand(COMMAND);\r
+        boolean checked = (Boolean) command.getState(STATE).getValue();\r
+        element.setChecked(checked);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/FastSpeedHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/FastSpeedHandler.java
new file mode 100644 (file)
index 0000000..d98a44e
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+\r
+public class FastSpeedHandler extends SpeedHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        setPlaybackSpeed(SysdynPlaybackExperiment.DURATION_FAST);\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/NormalSpeedHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/NormalSpeedHandler.java
new file mode 100644 (file)
index 0000000..b2ece4d
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+\r
+public class NormalSpeedHandler extends SpeedHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        setPlaybackSpeed(SysdynPlaybackExperiment.DURATION_NORMAL);\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackExperimentHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackExperimentHandler.java
new file mode 100644 (file)
index 0000000..72ae6ec
--- /dev/null
@@ -0,0 +1,82 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class PlaybackExperimentHandler extends AbstractHandler implements IElementUpdater {\r
+    \r
+    public static final String COMMAND = "org.simantics.sysdyn.ui.playback";\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
+            return null;\r
+        SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;\r
+        if(!spe.isPlaybackRunning())\r
+            spe.startPlayback();\r
+        else\r
+            spe.stopPlayback();\r
+        return null;\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public void updateElement(UIElement element, Map parameters) {\r
+        IExperimentManager manager = \r
+            SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
+            return;\r
+        SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;      \r
+        \r
+        ExperimentState state = experiment.getState();\r
+        if(state == ExperimentState.RUNNING && !spe.isPlaybackRunning()) {\r
+            // RUNNING == simulation, not playback\r
+            this.setBaseEnabled(false);\r
+        } else {\r
+            this.setBaseEnabled(true);\r
+        }\r
+\r
+        if(spe.isPlaybackRunning()) {\r
+            element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_pause.png")));\r
+            element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_pause_blue.png")));\r
+        } else {\r
+            long duration = spe.getPlaybackDuration();\r
+            if(duration == SysdynPlaybackExperiment.DURATION_SLOW) {\r
+                element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_step.png")));\r
+                element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_step_blue.png")));\r
+            } else if(duration == SysdynPlaybackExperiment.DURATION_FAST) {\r
+                element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_fastforward.png")));\r
+                element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_fastforward_blue.png")));\r
+            } else {\r
+                element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_play.png")));\r
+                element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_play_blue.png")));\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackReloadHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackReloadHandler.java
new file mode 100644 (file)
index 0000000..75cc05a
--- /dev/null
@@ -0,0 +1,27 @@
+package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class PlaybackReloadHandler extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        HandlerUtils.saveBeforeExperimentRun(event);\r
+        \r
+        IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
+            return null;\r
+        SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;\r
+        spe.simulate(true);\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackResetHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackResetHandler.java
new file mode 100644 (file)
index 0000000..e4155b6
--- /dev/null
@@ -0,0 +1,63 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.ui.commands.IElementUpdater;\r
+import org.eclipse.ui.menus.UIElement;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class PlaybackResetHandler extends AbstractHandler implements IElementUpdater {\r
+\r
+    public static final String COMMAND = "org.simantics.sysdyn.ui.playbackReset";\r
+\r
+    \r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
+            return null;\r
+        SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;\r
+        spe.resetPlayback();\r
+        return null;\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public void updateElement(UIElement element, Map parameters) {\r
+        IExperimentManager manager = \r
+                SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
+            return;\r
+        SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;      \r
+\r
+        ExperimentState state = experiment.getState();\r
+        if(state == ExperimentState.RUNNING && !spe.isPlaybackRunning()) {\r
+            // RUNNING == simulation, not playback\r
+            this.setBaseEnabled(false);\r
+        } else {\r
+            this.setBaseEnabled(true);\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SlowSpeedHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SlowSpeedHandler.java
new file mode 100644 (file)
index 0000000..6ebeba3
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+\r
+public class SlowSpeedHandler extends SpeedHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        setPlaybackSpeed(SysdynPlaybackExperiment.DURATION_SLOW);\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SpeedHandler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SpeedHandler.java
new file mode 100644 (file)
index 0000000..4fe9691
--- /dev/null
@@ -0,0 +1,50 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.commands.ICommandService;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+abstract class SpeedHandler extends AbstractHandler {\r
+    \r
+    protected void setPlaybackSpeed(long duration) {\r
+        \r
+        \r
+        IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
+            return;\r
+        final SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;\r
+        \r
+        if(spe.getPlaybackDuration() == duration)\r
+            return;\r
+        \r
+        \r
+        spe.setPlaybackDuration(duration);\r
+        \r
+        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                ICommandService commandService =\r
+                    (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+                commandService.refreshElements(PlaybackExperimentHandler.COMMAND, null);\r
+            }\r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynExperimentListener.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynExperimentListener.java
new file mode 100644 (file)
index 0000000..caea744
--- /dev/null
@@ -0,0 +1,66 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.listeners;\r
+\r
+import org.eclipse.core.commands.Command;\r
+import org.eclipse.core.commands.State;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.commands.ICommandService;\r
+import org.eclipse.ui.contexts.IContextActivation;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperimentListener;\r
+import org.simantics.sysdyn.ui.handlers.RunBasicExperiment;\r
+import org.simantics.sysdyn.ui.handlers.SynthesisSimulation;\r
+import org.simantics.sysdyn.ui.handlers.ToggleSimulation;\r
+import org.simantics.sysdyn.ui.handlers.game.ReloadGameExperimentHandler;\r
+import org.simantics.sysdyn.ui.handlers.game.StepHandler;\r
+import org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackExperimentHandler;\r
+import org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackResetHandler;\r
+\r
+public class SysdynExperimentListener  implements IExperimentListener {\r
+\r
+    IContextActivation contextActivation;\r
+\r
+    @Override\r
+    public void stateChanged(final ExperimentState state) {\r
+        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                ICommandService commandService =\r
+                    (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+                Command toggleCommand = commandService.getCommand(ToggleSimulation.COMMAND);\r
+                State toggleButtonState = toggleCommand.getState(ToggleSimulation.STATE);\r
+                Command synhesisCommand = commandService.getCommand(SynthesisSimulation.COMMAND);\r
+                State synthesisButtonState = synhesisCommand.getState(SynthesisSimulation.STATE);\r
+                                \r
+                switch(state) {\r
+                case DISPOSED:\r
+                       toggleButtonState.setValue(false); \r
+                       synthesisButtonState.setValue(false); \r
+                    break;\r
+                               default:\r
+                                       break;\r
+                }\r
+                commandService.refreshElements(toggleCommand.getId(), null); \r
+                commandService.refreshElements(synhesisCommand.getId(), null); \r
+                commandService.refreshElements(RunBasicExperiment.COMMAND, null);\r
+                commandService.refreshElements(PlaybackExperimentHandler.COMMAND, null);\r
+                commandService.refreshElements(PlaybackResetHandler.COMMAND, null);\r
+                commandService.refreshElements(StepHandler.COMMAND, null);\r
+                commandService.refreshElements(ReloadGameExperimentHandler.COMMAND, null);\r
+            }\r
+            \r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynExperimentManagerListener.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynExperimentManagerListener.java
new file mode 100644 (file)
index 0000000..09da1d4
--- /dev/null
@@ -0,0 +1,125 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.listeners;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.eclipse.ui.IWorkbench;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.contexts.IContextActivation;\r
+import org.eclipse.ui.contexts.IContextService;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.simulation.project.IExperimentManagerListener;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+import org.simantics.sysdyn.manager.SysdynSensitivityAnalysisExperiment;\r
+\r
+public class SysdynExperimentManagerListener implements IExperimentManagerListener{\r
+\r
+    public static final String BASIC_EXPERIMENT_CONTEXT = "org.simantics.sysdyn.ui.basicExperiment";\r
+    public static final String PLAYBACK_EXPERIMENT_CONTEXT = "org.simantics.sysdyn.ui.playbackExperiment";\r
+    public static final String GAME_EXPERIMENT_CONTEXT = "org.simantics.sysdyn.ui.gameExperiment";\r
+    public static final String SENSITIVITY_ANALYSIS_EXPERIMENT_CONTEXT = "org.simantics.sysdyn.ui.sensitivityAnalysisExperiment";\r
+    \r
+    static Set<IExperimentManager> managers = \r
+        new HashSet<IExperimentManager>();\r
+    \r
+    IExperimentManager manager;\r
+    \r
+    Collection<IContextActivation> contextActivations = \r
+        new ArrayList<IContextActivation>();\r
+        \r
+    public SysdynExperimentManagerListener(IExperimentManager manager) {\r
+        this.manager = manager;\r
+    }\r
+\r
+    public static void listenManager(IExperimentManager manager) {\r
+        synchronized(managers) {\r
+            if(managers.contains(manager))\r
+                return;\r
+            SysdynExperimentManagerListener listener = \r
+                new SysdynExperimentManagerListener(manager);\r
+            manager.addListener(listener);\r
+            managers.add(manager);\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void activeExperimentLoaded(final IExperiment experiment) {        \r
+        experiment.addListener(new SysdynExperimentListener());\r
+\r
+        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                IContextService contextService =\r
+                    (IContextService)PlatformUI.getWorkbench()\r
+                    .getActiveWorkbenchWindow().getService(IContextService.class);\r
+                synchronized(contextActivations) {\r
+                    if(experiment instanceof SysdynPlaybackExperiment) {\r
+                        contextActivations.add(contextService.activateContext(PLAYBACK_EXPERIMENT_CONTEXT));\r
+                        experiment.addListener(new SysdynPlaybackExperimentListener((SysdynPlaybackExperiment)experiment));\r
+                    } else if(experiment instanceof SysdynGameExperimentBase) {\r
+                        contextActivations.add(contextService.activateContext(GAME_EXPERIMENT_CONTEXT));\r
+                        // TODO: some listener?\r
+                    } else if(experiment instanceof SysdynSensitivityAnalysisExperiment) {\r
+                        contextActivations.add(contextService.activateContext(SENSITIVITY_ANALYSIS_EXPERIMENT_CONTEXT));\r
+                        // TODO: some listener?\r
+                    } else if(experiment instanceof SysdynExperiment) {\r
+                        contextActivations.add(contextService.activateContext(BASIC_EXPERIMENT_CONTEXT));\r
+                    }\r
+                }\r
+            }\r
+            \r
+        });\r
+    }\r
+\r
+    @Override\r
+    public void activeExperimentUnloaded() {\r
+        \r
+        synchronized(contextActivations) {\r
+            final Collection<IContextActivation> oldContextActivations = \r
+                contextActivations;\r
+            \r
+            contextActivations = new ArrayList<IContextActivation>();\r
+            \r
+            final IWorkbench workbench = PlatformUI.getWorkbench();\r
+            workbench.getDisplay().asyncExec(new Runnable() {\r
+    \r
+                @Override\r
+                public void run() {\r
+                    if (workbench.isClosing())\r
+                        return;\r
+                    \r
+                    IContextService contextService =\r
+                        (IContextService)workbench.getActiveWorkbenchWindow().getService(IContextService.class);\r
+                    contextService.deactivateContexts(oldContextActivations);                                \r
+                }\r
+                \r
+            });\r
+        }\r
+            \r
+    }\r
+\r
+    @Override\r
+    public void managerDisposed() {\r
+        synchronized(managers) {\r
+            managers.remove(manager);\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynPlaybackExperimentListener.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynPlaybackExperimentListener.java
new file mode 100644 (file)
index 0000000..70dc93d
--- /dev/null
@@ -0,0 +1,267 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.listeners;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.ui.IEditorPart;\r
+import org.eclipse.ui.IEditorReference;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.eclipse.ui.IWorkbenchPage;\r
+import org.eclipse.ui.IWorkbenchWindow;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.diagram.profile.Profiles;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.experiment.IExperimentListener;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+import org.simantics.sysdyn.ui.editor.DiagramViewer;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Listener for playback simulations. This listener activates and reverts the playback\r
+ * profile when a playback simlation is activated or disposed.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynPlaybackExperimentListener implements IExperimentListener {\r
+\r
+    private Resource model;\r
+    private Resource previousProfile;\r
+\r
+    public SysdynPlaybackExperimentListener(SysdynPlaybackExperiment experiment) {\r
+        this.model = experiment.getModel();\r
+        activatePlaybackProfile();\r
+    }\r
+\r
+    @Override\r
+    public void stateChanged(final ExperimentState state) {\r
+        switch(state) {\r
+            case DISPOSED:\r
+                revertPlaybackProfiles();\r
+            default:\r
+                break;\r
+        }\r
+    }\r
+\r
+    class DiagramInfo {\r
+        public Resource model = null;\r
+        public Resource previousProfile = null;\r
+    }\r
+\r
+    HashMap<Resource, DiagramInfo> previousRuntimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>(); \r
+\r
+    private void activatePlaybackProfile() {\r
+        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                previousRuntimeDiagramsAndModelUris.clear();\r
+                previousRuntimeDiagramsAndModelUris = getCurrentRuntimeDiagramInfos();\r
+                activatePlaybackProfileRequest(previousRuntimeDiagramsAndModelUris);\r
+            }\r
+        });\r
+    }\r
+    \r
+    private void revertPlaybackProfiles() {\r
+        \r
+        IProject project =  SimanticsUI.getProject();\r
+        if(project == null)\r
+            return;\r
+        IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment experiment = manager.getActiveExperiment();\r
+        \r
+        if(experiment != null && experiment instanceof SysdynPlaybackExperiment && this.model.equals(experiment.getModel()))\r
+                return;\r
+        \r
+        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                final HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = getCurrentRuntimeDiagramInfos();\r
+\r
+                VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);\r
+                Simantics.getSession().asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {\r
+                    \r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        \r
+                        Resource model = SysdynPlaybackExperimentListener.this.model;\r
+                        if(model == null)\r
+                            return;\r
+                        \r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        SysdynResource sr = SysdynResource.getInstance(graph);\r
+                        \r
+                        Resource defaultProfile = graph.syncRequest(new PossibleObjectWithType(model, l0.ConsistsOf, sr.DefaultProfile));\r
+                        if(defaultProfile == null)\r
+                            return;\r
+                        \r
+                        setProfileForModel(graph, model, previousProfile == null ? defaultProfile : previousProfile);\r
+                        \r
+                        HashMap<Resource, DiagramInfo> infos = getRuntimesForModel(graph, runtimeDiagramsAndModelUris, model);\r
+                        for(Resource runtimeDiagram : infos.keySet()) {\r
+                            Resource previous = null;\r
+                            if(previousRuntimeDiagramsAndModelUris.containsKey(runtimeDiagram)) {\r
+                                previous = previousRuntimeDiagramsAndModelUris.get(runtimeDiagram).previousProfile;\r
+                            }\r
+                            setProfileForDiagram(graph, runtimeDiagram, previous == null ? defaultProfile : previous);\r
+                        }\r
+                    }\r
+                });\r
+                \r
+            }\r
+        });\r
+    }\r
+    \r
+    /**\r
+     * Run in display thread.\r
+     * \r
+     * @return\r
+     */\r
+    private HashMap<Resource, DiagramInfo> getCurrentRuntimeDiagramInfos() {\r
+        HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>(); \r
+        IWorkbench workBench =  PlatformUI.getWorkbench();\r
+        IWorkbenchWindow window = workBench.getActiveWorkbenchWindow();\r
+        IWorkbenchPage[] pages = window.getPages();\r
+        for(IWorkbenchPage page : pages) {\r
+            for(IEditorReference reference : page.getEditorReferences()) {\r
+                IEditorPart iep = reference.getEditor(false);\r
+                if(iep instanceof DiagramEditor) {\r
+                    DiagramEditor editor = (DiagramEditor) iep;\r
+                    if (editor.getViewer() instanceof DiagramViewer) {\r
+                        DiagramViewer viewer = (DiagramViewer) editor.getViewer();\r
+                        Resource runtime = viewer.getRuntime();\r
+                        Resource model = viewer.getResourceInput2().getModel(null);\r
+                        DiagramInfo info = new DiagramInfo();\r
+                        info.model = model;\r
+                        runtimeDiagramsAndModelUris.put(runtime, info);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        return runtimeDiagramsAndModelUris;\r
+    }\r
+    \r
+    \r
+    private HashMap<Resource, DiagramInfo> getRuntimesForModel(WriteGraph graph, HashMap<Resource, DiagramInfo> allInfos, Resource model) throws DatabaseException {\r
+        HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>(); \r
+        for(Resource runtimeDiagram : allInfos.keySet()) {\r
+            DiagramInfo di = allInfos.get(runtimeDiagram);\r
+            if(di == null)\r
+                continue;\r
+            Resource m = di.model;\r
+            if(m == null || !model.equals(m))                    \r
+                continue;\r
+            \r
+            runtimeDiagramsAndModelUris.put(runtimeDiagram, di);\r
+        }\r
+        return runtimeDiagramsAndModelUris;\r
+    }\r
+    \r
+    private void activatePlaybackProfileRequest(final HashMap<Resource, DiagramInfo> allDiagramInfos) {\r
+        VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);\r
+        Simantics.getSession().asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {\r
+            \r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                \r
+                Resource model = SysdynPlaybackExperimentListener.this.model;\r
+                if(model == null)\r
+                    return;\r
+                \r
+                Resource profile = getSimulationPlaybackProfile(graph, model);\r
+                if(profile == null)\r
+                    return;\r
+                \r
+                DiagramResource DIA = DiagramResource.getInstance(graph);\r
+\r
+                Resource current = graph.getPossibleObject(model, DIA.HasActiveProfile);\r
+                previousProfile = current;\r
+\r
+                if(!profile.equals(current)) {\r
+                    setProfileForModel(graph, model, profile);\r
+                }\r
+                \r
+                HashMap<Resource, DiagramInfo> infos = getRuntimesForModel(graph, allDiagramInfos, model);\r
+                for(Resource runtimeDiagram : infos.keySet()) {\r
+                    DiagramInfo di = infos.get(runtimeDiagram);\r
+                    current = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile);\r
+                    di.previousProfile = current;\r
+                    if(profile.equals(current)) \r
+                        continue;\r
+                    setProfileForDiagram(graph, runtimeDiagram, profile);\r
+                }\r
+            }\r
+        });\r
+    }\r
+    \r
+    \r
+    private void setProfileForDiagram(WriteGraph graph, Resource runtimeDiagram, Resource profile) throws DatabaseException {\r
+        DiagramResource DIA = DiagramResource.getInstance(graph);\r
+\r
+        Resource current = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile);\r
+        if(profile.equals(current)) return;\r
+        \r
+        if(current != null)\r
+            graph.deny(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile, null, current);\r
+        graph.claim(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile, null, profile);\r
+\r
+        // Set this profile as the default profile for this diagram\r
+        Resource configuration = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasConfiguration);\r
+        graph.deny(configuration, DIA.HasActiveProfile);\r
+        graph.claim(configuration, DIA.HasActiveProfile, profile);\r
+    }\r
+    \r
+    private void setProfileForModel(WriteGraph graph, Resource model, Resource profile) throws DatabaseException {\r
+        DiagramResource DIA = DiagramResource.getInstance(graph);\r
+\r
+        // Set this profile as the default profile for this model\r
+        graph.deny(model, DIA.HasActiveProfile);\r
+        graph.claim(model, DIA.HasActiveProfile, profile);\r
+    }\r
+    \r
+    private Resource getSimulationPlaybackProfile(WriteGraph graph, Resource model) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        \r
+        Resource profile = graph.syncRequest(new PossibleObjectWithType(model, l0.ConsistsOf, sr.SimulationPlaybackProfile));\r
+        if(profile == null) {\r
+            profile = Profiles.createProfile(graph, "Simulation Playback", sr.Profiles_SimulationPlaybackColours);\r
+            graph.deny(profile, l0.InstanceOf);\r
+            graph.claim(profile, l0.InstanceOf, null, sr.SimulationPlaybackProfile);\r
+            graph.claim(model, l0.ConsistsOf, profile);\r
+        }\r
+\r
+        if(!graph.hasStatement(profile, SIMU.IsActive)) {\r
+            graph.claim(profile, SIMU.IsActive, sr.Profiles_SimulationPlaybackColours);\r
+        }\r
+        \r
+        return profile;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/FontContextMenuContribution.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/FontContextMenuContribution.java
new file mode 100644 (file)
index 0000000..9f69f7b
--- /dev/null
@@ -0,0 +1,196 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.menu;\r
+\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+\r
+import org.eclipse.jface.action.ContributionItem;\r
+import org.eclipse.jface.action.IContributionItem;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.widgets.Menu;\r
+import org.eclipse.swt.widgets.MenuItem;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.CustomFontDialog;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.contribution.DynamicMenuContribution;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+/**\r
+ * Context menu contribution for modifying fonts and font colors in diagram elements\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FontContextMenuContribution extends DynamicMenuContribution {\r
+\r
+       @Override\r
+       protected IContributionItem[] getContributionItems(final ReadGraph graph,\r
+                       Object[] selection) throws DatabaseException {\r
+               if (selection.length == 0)\r
+                       return new IContributionItem[0];\r
+\r
+               return new IContributionItem[] { new ContributionItem() {\r
+\r
+                       @Override\r
+                       public void fill(Menu menu, int index) {\r
+\r
+                               G2DResource G2D = G2DResource.getInstance(graph);\r
+\r
+                               Object[] selections = getSelectedObjects();\r
+\r
+                               Font font = null;\r
+                               Color color = null;\r
+\r
+                               /*\r
+                                *  Find a common font and color for the selected elements.\r
+                                *  \r
+                                *  If a common font or color is not found, the initial value in dialog is empty.\r
+                                */\r
+                               try {\r
+                                       for(Object o : selections) {\r
+                                               Resource element = ResourceAdaptionUtils\r
+                                                               .adaptToResource(o);\r
+                                               if(element != null) {\r
+                                                       Resource fontResource = graph.getPossibleObject(element, G2D.HasFont);\r
+                                                       if(fontResource != null) { \r
+                                                               Font newFont = G2DUtils.getFont(graph, fontResource);\r
+                                                               if(font == null) {\r
+                                                                       font = newFont;\r
+                                                               }\r
+\r
+                                                               if(font != null && !font.equals(newFont)) {\r
+                                                                       font = null;\r
+                                                                       break;\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                               } catch (DatabaseException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+\r
+                               try {\r
+                                       for(Object o : selections) {\r
+                                               Resource element = ResourceAdaptionUtils\r
+                                                               .adaptToResource(o);\r
+                                               if(element != null) {\r
+                                                   Resource colorResource = graph.getPossibleObject(element, G2D.HasColor);\r
+                                                   if(colorResource != null ) {\r
+                                                       Color newColor = G2DUtils.getColor(graph, colorResource);\r
+                                                       if(color == null)\r
+                                                           color = newColor;\r
+\r
+                                                       if(color != null && !color.equals(newColor))  {\r
+                                                           color = null;\r
+                                                           break;\r
+                                                       }\r
+                                                   }                    \r
+                                               }\r
+                                       }\r
+                               } catch (DatabaseException e) {\r
+                               }\r
+\r
+                               // Create the menu item with a selection listener\r
+                               MenuItem item;\r
+                               item = new MenuItem(menu, SWT.PUSH);\r
+\r
+                               item.setText("Font...");\r
+\r
+                               item.addSelectionListener(new FontSelectionListener(selections, font, color));\r
+                       }\r
+               } \r
+               };\r
+\r
+       }\r
+\r
+       /**\r
+        * Selection listener for font context menu action\r
+        * @author Teemu Lempinen\r
+        *\r
+        */\r
+       class FontSelectionListener implements SelectionListener {\r
+\r
+               private Font font;\r
+               private Color color;\r
+               private Object[] selections;\r
+\r
+               /**\r
+                * Font selection listener for context menu action in diagram\r
+                * \r
+                * @param selections Selected elements\r
+                * @param font Possible common font for the selected elements\r
+                * @param color Possible common color for the selected elements\r
+                */\r
+               public FontSelectionListener(Object[] selections, Font font, Color color) {\r
+                       this.selections = selections;\r
+                       this.font = font;\r
+                       this.color = color;\r
+               }\r
+\r
+               @Override\r
+               public void widgetSelected(SelectionEvent e) {\r
+                       // Create the dialog\r
+                       CustomFontDialog dialog = new CustomFontDialog(e.widget.getDisplay().getActiveShell(), "Sample");\r
+\r
+                       // Set possible font and color defaults\r
+                       if(font != null)\r
+                               dialog.setAWTFont(font);\r
+\r
+                       if(color != null)\r
+                               dialog.setColor(color);\r
+\r
+                       // Open dialog\r
+                       dialog.open();\r
+\r
+                       // Get results\r
+                       final Font resultFont = dialog.getAWTFont();\r
+                       final Color resultColor = dialog.getAWTColor();\r
+\r
+                       // Apply results to all selected elements\r
+                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       G2DResource G2D = G2DResource.getInstance(graph);\r
+\r
+                                       for(Object o : selections) {\r
+                                               Resource element = ResourceAdaptionUtils\r
+                                                               .adaptToResource(o);\r
+                                               if(resultFont != null) {\r
+                                                       graph.deny(element, G2D.HasFont);\r
+                                                       graph.claim(element, G2D.HasFont, G2DUtils.createFont(graph, resultFont));\r
+                                               }\r
+\r
+                                               if(resultColor != null) {\r
+                                                       graph.deny(element, G2D.HasColor);\r
+                                                       graph.claim(element, G2D.HasColor, G2DUtils.createColor(graph, resultColor));\r
+                                               }\r
+                                       }\r
+                               }\r
+                       });\r
+               }\r
+\r
+               @Override\r
+               public void widgetDefaultSelected(SelectionEvent e) {\r
+               }\r
+\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/GameStepDurationContribution.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/GameStepDurationContribution.java
new file mode 100644 (file)
index 0000000..fb1e41c
--- /dev/null
@@ -0,0 +1,106 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.menu;\r
+\r
+import org.eclipse.jface.action.IContributionItem;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.jface.resource.ResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.ToolBar;\r
+import org.eclipse.swt.widgets.ToolItem;\r
+import org.eclipse.ui.actions.CompoundContributionItem;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.validators.DoubleValidator;\r
+\r
+\r
+/**\r
+ * Contribution for adding a text field to menu bar. The text field is used \r
+ * to set the duration of one simulation step. This duration is different from\r
+ * the step length the simulator uses. Simulator steps as many steps that fit into\r
+ * the simulation duration determined in this field.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class GameStepDurationContribution extends CompoundContributionItem {\r
+\r
+       private TrackedText                             stepDuration;\r
+       private int                     width           = 40;\r
+    private ToolItem                           ti;\r
+    \r
+    public static String                       COMMAND         = "org.simantics.sysdyn.ui.gameStepDuration";\r
+\r
+    public GameStepDurationContribution() {\r
+        super(COMMAND);\r
+    }\r
+\r
+    @Override\r
+    protected IContributionItem[] getContributionItems() {\r
+        return new IContributionItem[0];\r
+    }\r
+\r
+    @Override\r
+    public void fill(final ToolBar parent, final int index) {\r
+        IProject project = SimanticsUI.peekProject();\r
+        if (project == null)\r
+            return;\r
+\r
+        // Find game experiment\r
+        IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+\r
+        IExperiment active = manager.getActiveExperiment();\r
+        if (!(active instanceof SysdynGameExperimentBase))\r
+            return;\r
+\r
+        final SysdynGameExperimentBase game = (SysdynGameExperimentBase) active;\r
+        \r
+        // Create the text\r
+        \r
+        ti = new ToolItem(parent, SWT.SEPARATOR, index);\r
+        ti.setText("Step Duration");\r
+        ti.setToolTipText("Step Duration");\r
+        \r
+        ISessionContext context = SimanticsUI.getSessionContext();\r
+        WidgetSupportImpl support = new WidgetSupportImpl(); // Dummy widget support for using tracked text\r
+\r
+        stepDuration = new TrackedText(parent, support, SWT.BORDER);\r
+        ResourceManager resourceManager = new LocalResourceManager(JFaceResources.getResources(), stepDuration.getWidget());\r
+        stepDuration.setColorProvider(new SysdynBasicColorProvider(resourceManager));\r
+        stepDuration.setInputValidator(new DoubleValidator());\r
+        stepDuration.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.GameExperiment_stepDuration));\r
+        stepDuration.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.GameExperiment_stepDuration));\r
+        \r
+        support.fireInput(context, game.getResource());\r
+        \r
+        ti.setWidth(width);\r
+        ti.setControl(stepDuration.getWidget());\r
+\r
+    }\r
+\r
+    @Override\r
+    public boolean isDynamic() {\r
+        return true;\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java
new file mode 100644 (file)
index 0000000..27e3b55
--- /dev/null
@@ -0,0 +1,171 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.menu;\r
+\r
+import java.text.DecimalFormat;\r
+import java.text.DecimalFormatSymbols;\r
+\r
+import org.eclipse.jface.action.ToolBarContributionItem;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Slider;\r
+import org.eclipse.swt.widgets.ToolBar;\r
+import org.eclipse.swt.widgets.ToolItem;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Contribution to the main toolbar. PlaybackSliderContribution contains a slider\r
+ * that can be used to control the time in a playback experiment\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PlaybackSliderContribution extends ToolBarContributionItem {\r
+\r
+    Runnable timeListener;\r
+    SysdynPlaybackExperiment spe;\r
+    Slider s;\r
+    Double startTime, endTime;\r
+    boolean ignoreChange = false;\r
+\r
+    @Override\r
+    public void fill(ToolBar parent, int index)\r
+    {\r
+        if (parent != null) {\r
+\r
+            IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+            IExperiment experiment = manager.getActiveExperiment();\r
+            if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
+                return;\r
+            spe = (SysdynPlaybackExperiment)experiment;\r
+\r
+            Double[] numbers = new Double[2];\r
+            try {\r
+                numbers = SimanticsUI.getSession().syncRequest(new Read<Double[]>() {\r
+                    @Override\r
+                    public Double[] perform(ReadGraph graph) throws DatabaseException {\r
+                        Double[] numbers = new Double[2];\r
+                        Resource model = spe.getModel();\r
+                        SysdynResource sr = SysdynResource.getInstance(graph);\r
+                        numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime);\r
+                        numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime);\r
+                        return numbers;\r
+                    }\r
+                });\r
+            } catch (DatabaseException e1) {\r
+                e1.printStackTrace();\r
+            }\r
+\r
+            // Separator ToolItem can contain a composite. Add a composite with a slider to this item\r
+            ToolItem ti = new ToolItem(parent, SWT.SEPARATOR);\r
+\r
+            Composite composite = new Composite(parent, SWT.NONE);\r
+            GridLayoutFactory.fillDefaults().margins(3, SWT.DEFAULT).numColumns(2).applyTo(composite);\r
+            GridDataFactory.fillDefaults().applyTo(composite);\r
+\r
+            s = new Slider(composite, SWT.NONE);\r
+            s.setMinimum(0);\r
+            s.setMaximum(100);\r
+            s.setIncrement(1);\r
+            s.setPageIncrement(1);\r
+            s.setThumb(1);\r
+\r
+            final Label label = new Label(composite, SWT.NONE);\r
+            GridDataFactory.fillDefaults().hint(70, SWT.DEFAULT).applyTo(label);\r
+            label.setText("0.0");\r
+\r
+            ti.setWidth(270);\r
+            ti.setControl(composite);\r
+\r
+            startTime = numbers[0];\r
+            endTime = numbers[1];\r
+            \r
+            // Create a DesimalFormat for rounding the time\r
+            final DecimalFormat format = new DecimalFormat();\r
+            format.setMinimumFractionDigits(0);\r
+            format.setMaximumFractionDigits(2);\r
+            DecimalFormatSymbols symbols = new DecimalFormatSymbols();\r
+            symbols.setDecimalSeparator('.');\r
+            symbols.setGroupingSeparator(' ');\r
+            format.setDecimalFormatSymbols(symbols);\r
+            \r
+            // Selection listener for the slider\r
+            s.addSelectionListener(new SelectionListener() {\r
+\r
+                @Override\r
+                public void widgetSelected(SelectionEvent e) {\r
+                    Slider s = (Slider)e.widget;\r
+                    Double time = s.getSelection() / 99.0 * (endTime - startTime) + startTime;\r
+                    spe.setTimeAndContinue(time);\r
+                    if(!label.isDisposed()) {\r
+                        label.setText(format.format(time));\r
+                    }\r
+                }\r
+\r
+                @Override\r
+                public void widgetDefaultSelected(SelectionEvent e) {\r
+                }\r
+            });\r
+\r
+            if(timeListener != null) {\r
+                spe.removeTimeListener(timeListener);\r
+            }\r
+\r
+            // Time listener for setting the time in the slider if the time is changed somewhere else\r
+            timeListener = new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+                    s.getDisplay().asyncExec(new Runnable() {\r
+\r
+                        @Override\r
+                        public void run() {\r
+                            if(!startTime.equals(spe.getStartTime()) || !endTime.equals(spe.getEndTime())) {\r
+                                startTime = spe.getStartTime();\r
+                                endTime = spe.getEndTime();\r
+                            }\r
+                            int value = (int) Math.round(((spe.getTime() - startTime) / (endTime - startTime) * 99));\r
+                            s.setSelection(value);\r
+                            label.setText(format.format(spe.getTime()));\r
+                        }\r
+                    });\r
+\r
+                }\r
+\r
+            };\r
+            spe.addTimeListener(timeListener);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        if(this.timeListener != null && spe != null) {\r
+            spe.removeTimeListener(timeListener);\r
+            this.timeListener = null;\r
+        }\r
+        super.dispose();\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/ModelicaSourceViewerConfiguration.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/ModelicaSourceViewerConfiguration.java
new file mode 100644 (file)
index 0000000..84c0055
--- /dev/null
@@ -0,0 +1,170 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.modelica;\r
+\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.eclipse.jface.text.IDocument;\r
+import org.eclipse.jface.text.TextAttribute;\r
+import org.eclipse.jface.text.presentation.IPresentationReconciler;\r
+import org.eclipse.jface.text.presentation.PresentationReconciler;\r
+import org.eclipse.jface.text.rules.DefaultDamagerRepairer;\r
+import org.eclipse.jface.text.rules.ICharacterScanner;\r
+import org.eclipse.jface.text.rules.IRule;\r
+import org.eclipse.jface.text.rules.IToken;\r
+import org.eclipse.jface.text.rules.RuleBasedScanner;\r
+import org.eclipse.jface.text.rules.Token;\r
+import org.eclipse.jface.text.source.ISourceViewer;\r
+import org.eclipse.jface.text.source.SourceViewerConfiguration;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.graphics.Color;\r
+\r
+public class ModelicaSourceViewerConfiguration extends SourceViewerConfiguration {\r
+\r
+       @Override\r
+    public IPresentationReconciler getPresentationReconciler(\r
+                       ISourceViewer sourceViewer) {\r
+               PresentationReconciler pr = new PresentationReconciler();\r
+               DefaultDamagerRepairer ddr = new DefaultDamagerRepairer(\r
+                               new RuleBasedScanner() {                                                                                                                \r
+                                       {\r
+                                               setRules(new IRule[] {new IRule() {\r
+\r
+                                                       @Override\r
+                                                       public IToken evaluate(ICharacterScanner scanner) {\r
+                                                               int ch;\r
+                                                               try {\r
+                                                                       scanner.unread();\r
+                                                                       ch = scanner.read();\r
+                                                               } catch (Throwable t) {\r
+                                                                       ch = -1;\r
+                                                               }\r
+                                                               if (ch <= 0 || !isIdentifierChar((char) ch)) {\r
+                                                                       ch = scanner.read();\r
+                                                                       if(isIdentifierChar((char)ch)) {\r
+                                                                               StringBuilder b = new StringBuilder();\r
+                                                                               do {\r
+                                                                                       b.append((char)ch);\r
+                                                                                       ch = scanner.read();\r
+                                                                               } while(isIdentifierChar((char) ch));\r
+                                                                               String str = b.toString();\r
+                                                                               if(keywords.contains(str))\r
+                                                                                       return getModelicaKeywordToken();\r
+                                                                       }\r
+                                                                       scanner.unread();\r
+                                                               }\r
+                                                               return Token.UNDEFINED;\r
+                                                       }                                                                       \r
+                                                       \r
+                                               }});\r
+                                       }                                                       \r
+                               }\r
+                       );\r
+               pr.setRepairer(ddr, IDocument.DEFAULT_CONTENT_TYPE);\r
+               pr.setDamager(ddr, IDocument.DEFAULT_CONTENT_TYPE);\r
+               return pr;\r
+       }\r
+       \r
+       static boolean isIdentifierChar(char c) {\r
+               return \r
+                       (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') \r
+                || (c >= '0' && c <= '9') || c == '_';\r
+       }\r
+       \r
+       // Includes also tokens that are strictly speaking not keywords\r
+       // but should be handled in (almost) a similar fashion.\r
+       public static final Set<String> keywords = new HashSet<String>();\r
+\r
+    static {\r
+        keywords.add("algorithm");\r
+        keywords.add("discrete");\r
+        keywords.add("false");\r
+        keywords.add("model");\r
+        keywords.add("redeclare");\r
+        keywords.add("and");\r
+        keywords.add("each");\r
+        keywords.add("final");\r
+        keywords.add("not");\r
+        keywords.add("replaceable");\r
+        keywords.add("annotation");\r
+        keywords.add("else");\r
+        keywords.add("flow");\r
+        keywords.add("operator");\r
+        keywords.add("return");\r
+        keywords.add("assert");\r
+        keywords.add("elseif");\r
+        keywords.add("for");\r
+        keywords.add("or");\r
+        keywords.add("stream");\r
+        keywords.add("block");\r
+        keywords.add("elsewhen");\r
+        keywords.add("function");\r
+        keywords.add("outer");\r
+        keywords.add("then");\r
+        keywords.add("break");\r
+        keywords.add("encapsulated");\r
+        keywords.add("if");\r
+        keywords.add("output");\r
+        keywords.add("true");\r
+        keywords.add("class");\r
+        keywords.add("end");\r
+        keywords.add("import");\r
+        keywords.add("package");\r
+        keywords.add("type");\r
+        keywords.add("connect");\r
+        keywords.add("enumeration");\r
+        keywords.add("in");\r
+        keywords.add("parameter");\r
+        keywords.add("when");\r
+        keywords.add("connector");\r
+        keywords.add("equation");\r
+        keywords.add("initial");\r
+        keywords.add("partial");\r
+        keywords.add("while");\r
+        keywords.add("constant");\r
+        keywords.add("expandable");\r
+        keywords.add("inner");\r
+        keywords.add("protected");\r
+        keywords.add("within");\r
+        keywords.add("constrainedby");\r
+        keywords.add("extends");\r
+        keywords.add("input");\r
+        keywords.add("public");\r
+        keywords.add("der");\r
+        keywords.add("external");\r
+        keywords.add("loop");\r
+        keywords.add("record");\r
+        keywords.add("time");\r
+        keywords.add("pure");\r
+        keywords.add("impure");\r
+        keywords.add("Real");\r
+        keywords.add("Boolean");\r
+        keywords.add("Integer");\r
+        keywords.add("String");\r
+    }\r
+\r
+       static IToken modelicaKeywordToken = null;\r
+       public IToken getModelicaKeywordToken() {\r
+               if(modelicaKeywordToken == null) {\r
+                       modelicaKeywordToken = \r
+                               new Token(\r
+                                               new TextAttribute(\r
+                                                               new Color(null, 127, 0, 85),\r
+                                                               new Color(null, 255, 255, 255),\r
+                                                               SWT.BOLD\r
+                                                               ));\r
+               }\r
+               return modelicaKeywordToken;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/SysdynModelicaEditor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/SysdynModelicaEditor.java
new file mode 100644 (file)
index 0000000..6d4757d
--- /dev/null
@@ -0,0 +1,154 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.modelica;\r
+\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.runtime.CoreException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.jface.operation.IRunnableContext;\r
+import org.eclipse.jface.text.Document;\r
+import org.eclipse.jface.text.IDocument;\r
+import org.eclipse.jface.text.PaintManager;\r
+import org.eclipse.jface.text.source.AnnotationModel;\r
+import org.eclipse.jface.text.source.AnnotationPainter;\r
+import org.eclipse.jface.text.source.DefaultCharacterPairMatcher;\r
+import org.eclipse.jface.text.source.IAnnotationModel;\r
+import org.eclipse.jface.text.source.MatchingCharacterPainter;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.ui.IEditorInput;\r
+import org.eclipse.ui.IEditorSite;\r
+import org.eclipse.ui.PartInitException;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.editors.text.TextEditor;\r
+import org.eclipse.ui.texteditor.AbstractDocumentProvider;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.modelica.ModelicaManager;\r
+import org.simantics.sysdyn.modelica.ModelicaWriter;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.LoadRepresentation;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.ModuleType;\r
+import org.simantics.sysdyn.representation.utils.RepresentationUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.workbench.ResourceEditorInput;\r
+\r
+/**\r
+ * Text editor for displaying Modelica code\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynModelicaEditor extends TextEditor {\r
+\r
+    AnnotationModel annotationModel = new AnnotationModel();\r
+    AnnotationPainter apainter;\r
+    \r
+    \r
+       public void init(final IEditorSite site, final IEditorInput input) throws PartInitException {\r
+               super.init(site, input);\r
+        try {\r
+                       Configuration configuration =\r
+                           LoadRepresentation.loadConfiguration(SimanticsUI.getSession(), ((ResourceEditorInput)input).getResource());\r
+                       setPartName(configuration.getLabel());\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+       }\r
+               \r
+    public SysdynModelicaEditor() {\r
+        super();\r
+        showOverviewRuler();\r
+        setDocumentProvider(new AbstractDocumentProvider() {\r
+\r
+            @Override\r
+            protected IAnnotationModel createAnnotationModel(Object element)\r
+                    throws CoreException {\r
+                return annotationModel;\r
+            }\r
+\r
+            @Override\r
+            protected IDocument createDocument(Object element)\r
+                    throws CoreException {\r
+                try {\r
+                    Configuration configuration =\r
+                        LoadRepresentation.loadConfiguration(SimanticsUI.getSession(), ((ResourceEditorInput)element).getResource());\r
+                    \r
+                    HashSet<Configuration> configurations = new HashSet<Configuration>();\r
+                    configurations.add(configuration);\r
+                    getConfigurations(configuration, configurations);\r
+                    \r
+                    String version = ModelicaManager.getDefaultOMVersion();\r
+                    return new Document(ModelicaWriter.write(configurations, configuration.getModel().getStartTime(), RepresentationUtils.isGameExperimentActive(), version));\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                    throw new CoreException(STATUS_ERROR);\r
+                }                \r
+            }\r
+\r
+            @Override\r
+            protected void doSaveDocument(IProgressMonitor monitor,\r
+                    Object element, IDocument document, boolean overwrite)\r
+                    throws CoreException {\r
+            }\r
+\r
+            @Override\r
+            protected IRunnableContext getOperationRunner(\r
+                    IProgressMonitor monitor) {\r
+                return PlatformUI.getWorkbench().getActiveWorkbenchWindow();\r
+            }\r
+            \r
+            @Override\r
+            public boolean isModifiable(Object element) {\r
+                return false;\r
+            }\r
+            \r
+            @Override\r
+            public boolean isReadOnly(Object element) {\r
+                return true;\r
+            }\r
+            \r
+        }); \r
+        \r
+        setSourceViewerConfiguration(new ModelicaSourceViewerConfiguration());\r
+                \r
+    }\r
+    \r
+    private void getConfigurations(Configuration configuration, Set<Configuration> configurations) {\r
+       for(IElement e : configuration.getElements()) {\r
+               if(e instanceof Module) {\r
+                       ModuleType mt = ((Module) e).getType();\r
+                       configurations.add(mt.getConfiguration());\r
+                       getConfigurations(mt.getConfiguration(), configurations);\r
+               }\r
+       }\r
+    }\r
+    \r
+    @Override\r
+    protected void createActions() {\r
+        super.createActions();\r
+        \r
+        PaintManager paintManager = new PaintManager(getSourceViewer());\r
+        MatchingCharacterPainter matchingCharacterPainter = new MatchingCharacterPainter(getSourceViewer(),\r
+                new DefaultCharacterPairMatcher( new char[] {'(', ')', '{', '}', '[', ']'} ));\r
+        matchingCharacterPainter.setColor(new Color(Display.getCurrent(), new RGB(160, 160, 160)));\r
+        paintManager.addPainter(matchingCharacterPainter);\r
+    }\r
+    \r
+    \r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/TextEditorActionBarContributor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/TextEditorActionBarContributor.java
new file mode 100644 (file)
index 0000000..555b13a
--- /dev/null
@@ -0,0 +1,22 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.modelica;\r
+\r
+import org.eclipse.ui.part.EditorActionBarContributor;\r
+\r
+public class TextEditorActionBarContributor extends EditorActionBarContributor {\r
+\r
+       public TextEditorActionBarContributor() {\r
+               // TODO Auto-generated constructor stub\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/ModelicaPreferencePage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/ModelicaPreferencePage.java
new file mode 100644 (file)
index 0000000..443c901
--- /dev/null
@@ -0,0 +1,157 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.preferences;\r
+\r
+import java.io.File;\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.eclipse.core.runtime.preferences.ConfigurationScope;\r
+import org.eclipse.core.runtime.preferences.IScopeContext;\r
+import org.eclipse.jface.preference.DirectoryFieldEditor;\r
+import org.eclipse.jface.preference.FieldEditorPreferencePage;\r
+import org.eclipse.jface.preference.RadioGroupFieldEditor;\r
+import org.eclipse.jface.preference.StringFieldEditor;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.eclipse.ui.IWorkbenchPreferencePage;\r
+import org.eclipse.ui.preferences.ScopedPreferenceStore;\r
+import org.osgi.service.prefs.Preferences;\r
+import org.simantics.modelica.Activator;\r
+import org.simantics.modelica.ModelicaManager;\r
+import org.simantics.modelica.preferences.OpenModelicaPreferences;\r
+\r
+public class ModelicaPreferencePage extends FieldEditorPreferencePage implements \r
+               IWorkbenchPreferencePage {\r
+\r
+       private static String CUSTOM_PATH = "Custom path";\r
+\r
+       private DirectoryFieldEditor path;\r
+       private RadioGroupFieldEditor rg;\r
+\r
+       public ModelicaPreferencePage() {\r
+               super(GRID);\r
+               setDescription("Modelica preferences");\r
+       }\r
+       \r
+       @Override\r
+       public void init(IWorkbench workbench) {\r
+               setPreferenceStore(new ScopedPreferenceStore(ConfigurationScope.INSTANCE, Activator.PLUGIN_ID));\r
+       }\r
+\r
+       @Override\r
+       public void createFieldEditors() {\r
+               final File installed = ModelicaManager.getInstalledOMHome();\r
+               final File builtIn = ModelicaManager.getBuiltinOMHome();\r
+\r
+               List<String[]> optionList = new ArrayList<String[]>();\r
+               optionList.add(new String[]{CUSTOM_PATH, CUSTOM_PATH});\r
+               if (installed != null) {\r
+                       optionList.add(new String[]{ "Local installation (" + ModelicaManager.getOMVersion(installed) + ")", installed.getAbsolutePath() });\r
+               }\r
+               if (builtIn != null) {\r
+                       optionList.add(new String[]{ "Built-in (" + ModelicaManager.getOMVersion(builtIn) + ")", builtIn.getAbsolutePath() });\r
+               }\r
+\r
+               String[][] options = optionList.toArray(new String[optionList.size()][]);\r
+\r
+               rg = new RadioGroupFieldEditor(OpenModelicaPreferences.OM_HOME,\r
+                               "&Choose the used OpenModelica version", 1,\r
+                               options, getFieldEditorParent()) {\r
+\r
+                       @Override\r
+                       protected void doStore() {\r
+                               // Do nothing. Path handles saving the value\r
+                       }\r
+\r
+                       @Override\r
+                       protected void fireValueChanged(String property, Object oldValue, Object newValue) {\r
+                               if((installed != null && newValue.equals(installed.getAbsolutePath())) || (builtIn != null && newValue.equals(builtIn.getAbsolutePath()))) {\r
+                                       path.setStringValue((String)newValue);\r
+                                       path.setEnabled(false, getFieldEditorParent());\r
+                               } else {\r
+                                       path.setEnabled(true, getFieldEditorParent());\r
+                               }   \r
+                       }\r
+\r
+                       @Override\r
+                       public void doLoadDefault() {\r
+                               System.err.println("LOAD DEFAULT");\r
+                               IScopeContext context = ConfigurationScope.INSTANCE;\r
+                               Preferences node = context.getNode(Activator.PLUGIN_ID);\r
+                               node.put(OpenModelicaPreferences.OM_HOME, ModelicaManager.getDefaultOMHome().getAbsolutePath());\r
+                               load();\r
+                       }\r
+               };\r
+\r
+               addField(rg);\r
+\r
+               path = new DirectoryFieldEditor(OpenModelicaPreferences.OM_HOME, \r
+                               "&Modelica Home:", getFieldEditorParent()) {\r
+\r
+                       @Override\r
+                       public void setValidateStrategy(int value) {\r
+                               super.setValidateStrategy(StringFieldEditor.VALIDATE_ON_KEY_STROKE);\r
+                       }\r
+\r
+                       @Override\r
+                       public void doStore() {\r
+                               super.doStore();\r
+                               IScopeContext context = ConfigurationScope.INSTANCE;\r
+                               Preferences node = context.getNode(Activator.PLUGIN_ID);\r
+                               node.put(OpenModelicaPreferences.OM_HOME, getStringValue());\r
+                       }\r
+\r
+                       @Override\r
+                       protected boolean doCheckState() {\r
+                               boolean valid = super.doCheckState();\r
+                               if(valid) {\r
+                                       // path is a valid directory\r
+                                       String path = getStringValue();\r
+                                       File dir = new File(path);\r
+                                       String version = ModelicaManager.getOMVersion(dir);\r
+                                       if(version == null || version.isEmpty()) {\r
+                                               return false;\r
+                                       }\r
+                               }\r
+\r
+                               return valid;\r
+                       }\r
+\r
+                       @Override\r
+                       public void doLoad() {\r
+                               super.doLoad();\r
+                               String value = getStringValue();\r
+                               updatePath(value);\r
+                       }\r
+\r
+                       @Override\r
+                       public void doLoadDefault() {\r
+                               updatePath(ModelicaManager.getDefaultOMHome().getAbsolutePath());\r
+                       }\r
+\r
+                       private void updatePath(String newValue) {\r
+                               if((installed != null && newValue.equals(installed.getAbsolutePath()) ||  newValue.equals(builtIn.getAbsolutePath()))) {\r
+                                       path.setStringValue(newValue);\r
+                                       path.setEnabled(false, getFieldEditorParent());\r
+                               } else {\r
+                                       path.setEnabled(true, getFieldEditorParent());\r
+                               }   \r
+                       }\r
+\r
+\r
+               };\r
+\r
+               path.setErrorMessage("Path must be a valid OpenModelica directory");\r
+               addField(path);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SolverPreferencePage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SolverPreferencePage.java
new file mode 100644 (file)
index 0000000..3cd3f05
--- /dev/null
@@ -0,0 +1,37 @@
+package org.simantics.sysdyn.ui.preferences;\r
+\r
+import org.eclipse.core.runtime.preferences.ConfigurationScope;\r
+import org.eclipse.jface.preference.FieldEditor;\r
+import org.eclipse.jface.preference.FieldEditorPreferencePage;\r
+import org.eclipse.jface.preference.RadioGroupFieldEditor;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.eclipse.ui.IWorkbenchPreferencePage;\r
+import org.eclipse.ui.preferences.ScopedPreferenceStore;\r
+import org.simantics.sysdyn.solver.SolverSettings;\r
+\r
+public class SolverPreferencePage extends FieldEditorPreferencePage implements\r
+               IWorkbenchPreferencePage {\r
+       \r
+       private FieldEditor solverEditor;\r
+       \r
+       public SolverPreferencePage() {\r
+               super(GRID);\r
+               setDescription("Solver preferences");\r
+       }\r
+\r
+       @Override\r
+       public void init(IWorkbench workbench) {\r
+               setPreferenceStore(new ScopedPreferenceStore(ConfigurationScope.INSTANCE, SolverSettings.QUALIFIER));\r
+       }\r
+\r
+       @Override\r
+       protected void createFieldEditors() {\r
+               solverEditor = new RadioGroupFieldEditor(SolverSettings.SOLVER_TYPE, "Solver type", 1,\r
+                               new String[][] { \r
+                                       { "Internal", SolverSettings.SOLVER_TYPE_INTERNAL },\r
+                                       { "OpenModelica", SolverSettings.SOLVER_TYPE_OPENMODELICA }\r
+                               }, getFieldEditorParent());\r
+               addField(solverEditor);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferencePage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferencePage.java
new file mode 100644 (file)
index 0000000..a61ae6b
--- /dev/null
@@ -0,0 +1,176 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+\r
+package org.simantics.sysdyn.ui.preferences;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.preference.BooleanFieldEditor;\r
+import org.eclipse.jface.preference.ColorFieldEditor;\r
+import org.eclipse.jface.preference.FieldEditor;\r
+import org.eclipse.jface.preference.FieldEditorPreferencePage;\r
+import org.eclipse.jface.preference.FontFieldEditor;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.eclipse.ui.IWorkbenchPreferencePage;\r
+import org.simantics.sysdyn.ui.Activator;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SysdynDiagramPreferencePage extends FieldEditorPreferencePage implements\r
+IWorkbenchPreferencePage {\r
+    \r
+    private HashMap<FieldEditor, Composite> fieldParents;\r
+    private Group colorEditors, fontEditors;\r
+\r
+    public SysdynDiagramPreferencePage() {\r
+        super(GRID);\r
+        setDescription("System dynamics diagram preferences");\r
+        fieldParents = new HashMap<FieldEditor, Composite>();\r
+    }\r
+\r
+    @Override\r
+    public void init(IWorkbench workbench) {\r
+        setPreferenceStore(Activator.getDefault().getPreferenceStore());\r
+    }\r
+\r
+    @Override\r
+    protected void createFieldEditors() {\r
+        Composite parent = new Composite(getFieldEditorParent(), SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().numColumns(1).applyTo(parent);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(parent);\r
+        \r
+        // DEFAULTS\r
+        Group defaults = new Group(parent, SWT.NONE);\r
+        defaults.setText("Default settings");\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(defaults);\r
+        addField(new ColorFieldEditor(SysdynDiagramPreferences.DEFAULT_COLOR, "Color", defaults));\r
+        addField(new CustomFontFieldEditor(SysdynDiagramPreferences.DEFAULT_FONT, "Font", defaults));\r
+        GridLayout layout = (GridLayout) defaults.getLayout();\r
+        layout.marginHeight = 3;\r
+        layout.marginWidth = 3;\r
+        defaults.setLayout(layout);\r
+        \r
+        // COLORS\r
+        colorEditors = new Group(parent, SWT.NONE);\r
+        colorEditors.setText("Colors");\r
+        GridDataFactory.fillDefaults().applyTo(colorEditors);\r
+        GridDataFactory.fillDefaults().applyTo(colorEditors);\r
+        Label label = new Label(colorEditors, SWT.NONE);\r
+        GridDataFactory.fillDefaults().span(3, 1).applyTo(label);\r
+        \r
+        label = new Label(colorEditors, SWT.NONE);\r
+        label.setText("Use default");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+        \r
+        addColorFieldEditor(SysdynDiagramPreferences.ARROW_COLOR, "&Dependency", SysdynDiagramPreferences.ARROW_USE_DEFAULT_COLOR);\r
+        addColorFieldEditor(SysdynDiagramPreferences.ARROW_STOCK_INITIAL_COLOR, "&Dependency to Stock Initial", SysdynDiagramPreferences.ARROW_STOCK_INITIAL_USE_DEFAULT_COLOR);\r
+        addColorFieldEditor(SysdynDiagramPreferences.FLOW_COLOR, "&Flow", SysdynDiagramPreferences.FLOW_USE_DEFAULT_COLOR);\r
+        addColorFieldEditor(SysdynDiagramPreferences.AUXILIARY_COLOR, "&Auxiliary", SysdynDiagramPreferences.AUXILIARY_USE_DEFAULT_COLOR);\r
+        addColorFieldEditor(SysdynDiagramPreferences.STOCK_COLOR, "&Stock", SysdynDiagramPreferences.STOCK_USE_DEFAULT_COLOR);\r
+        addColorFieldEditor(SysdynDiagramPreferences.VALVE_COLOR, "&Valve", SysdynDiagramPreferences.VALVE_USE_DEFAULT_COLOR);\r
+        addColorFieldEditor(SysdynDiagramPreferences.INPUT_COLOR, "&Input", SysdynDiagramPreferences.VALVE_USE_DEFAULT_COLOR);\r
+        addColorFieldEditor(SysdynDiagramPreferences.CLOUD_COLOR, "&Cloud", SysdynDiagramPreferences.CLOUD_USE_DEFAULT_COLOR);\r
+        addColorFieldEditor(SysdynDiagramPreferences.MODULE_COLOR, "&Module", SysdynDiagramPreferences.MODULE_USE_DEFAULT_COLOR);\r
+        \r
+        // FONTS\r
+        fontEditors = new Group(parent, SWT.NONE);\r
+        fontEditors.setText("Fonts");\r
+        GridDataFactory.fillDefaults().applyTo(fontEditors);\r
+        GridLayoutFactory.fillDefaults().applyTo(fontEditors);\r
+\r
+        label = new Label(fontEditors, SWT.NONE);\r
+        GridDataFactory.fillDefaults().span(3, 1).applyTo(label);\r
+        \r
+        label = new Label(fontEditors, SWT.NONE);\r
+        label.setText("Use default");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+\r
+        addFontFieldEditor(SysdynDiagramPreferences.ARROW_FONT, "Dependency", SysdynDiagramPreferences.ARROW_USE_DEFAULT_FONT);\r
+        addFontFieldEditor(SysdynDiagramPreferences.AUXILIARY_FONT, "Auxiliary", SysdynDiagramPreferences.AUXILIARY_USE_DEFAULT_FONT);\r
+        addFontFieldEditor(SysdynDiagramPreferences.STOCK_FONT, "Stock", SysdynDiagramPreferences.STOCK_USE_DEFAULT_FONT);\r
+        addFontFieldEditor(SysdynDiagramPreferences.VALVE_FONT, "Valve", SysdynDiagramPreferences.VALVE_USE_DEFAULT_FONT);\r
+        addFontFieldEditor(SysdynDiagramPreferences.INPUT_FONT, "Input", SysdynDiagramPreferences.INPUT_USE_DEFAULT_FONT);\r
+        addFontFieldEditor(SysdynDiagramPreferences.CLOUD_FONT, "Cloud", SysdynDiagramPreferences.CLOUD_USE_DEFAULT_FONT);\r
+        addFontFieldEditor(SysdynDiagramPreferences.MODULE_FONT, "Module", SysdynDiagramPreferences.MODULE_USE_DEFAULT_FONT);\r
+\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(4).applyTo(colorEditors);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(4).applyTo(fontEditors);\r
+    }\r
+    \r
+    \r
+    private void addColorFieldEditor(String property, String label, String defaultBoolean) {\r
+        ColorFieldEditor colorField = new ColorFieldEditor(property, label, colorEditors);\r
+        colorField.setEnabled(!getPreferenceStore().getBoolean(defaultBoolean), colorEditors);\r
+        Composite c = new Composite(colorEditors, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).applyTo(c);\r
+        GridLayoutFactory.fillDefaults().applyTo(c);\r
+        BooleanFieldEditor useDefault = new DefaultBooleanFiedEditor(colorField, defaultBoolean, c);\r
+        fieldParents.put(colorField, colorEditors);\r
+        addField(useDefault);\r
+        addField(colorField);\r
+    }\r
+    \r
+    private void addFontFieldEditor(String property, String label, String defaultBoolean) {\r
+        CustomFontFieldEditor fontField = new CustomFontFieldEditor(property, label, fontEditors);\r
+        fontField.setEnabled(!getPreferenceStore().getBoolean(defaultBoolean), fontEditors);\r
+        Composite c = new Composite(fontEditors, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).applyTo(c);\r
+        GridLayoutFactory.fillDefaults().applyTo(c);\r
+        BooleanFieldEditor useDefault = new DefaultBooleanFiedEditor(fontField, defaultBoolean, c);\r
+        \r
+        \r
+        \r
+        fieldParents.put(fontField, fontEditors);\r
+        addField(useDefault);\r
+        addField(fontField);\r
+    }\r
+    \r
+    private class DefaultBooleanFiedEditor extends BooleanFieldEditor {\r
+        private FieldEditor fieldEditor;\r
+        \r
+        public DefaultBooleanFiedEditor(FieldEditor fieldEditor, String name, Composite parent) {\r
+            super(name, "", parent);\r
+            this.fieldEditor = fieldEditor;\r
+        }\r
+        \r
+        @Override\r
+        protected void valueChanged(boolean oldValue, boolean newValue) {\r
+            super.valueChanged(oldValue, newValue);\r
+            fieldEditor.setEnabled(!newValue, fieldParents.get(fieldEditor));\r
+        }\r
+    }\r
+    \r
+    private class CustomFontFieldEditor extends FontFieldEditor {\r
+        \r
+        public CustomFontFieldEditor(String name, String labelText, Composite parent) {\r
+            super(name, labelText, parent);\r
+            \r
+            GridDataFactory.fillDefaults().applyTo(getChangeControl(parent));\r
+            setChangeButtonText("...");\r
+            getChangeControl(parent).setToolTipText("Change");\r
+            \r
+            \r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferences.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferences.java
new file mode 100644 (file)
index 0000000..1a8255f
--- /dev/null
@@ -0,0 +1,189 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.preferences;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.preference.IPreferenceStore;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SysdynDiagramPreferences {\r
+\r
+    public static String DEFAULT_COLOR = "Default color";\r
+    public static String DEFAULT_FONT = "Default font";\r
+    \r
+    public static String ARROW_COLOR = "Arrow color";\r
+    public static String ARROW_STOCK_INITIAL_COLOR = "Arrow stock initial color";\r
+    public static String FLOW_COLOR = "Flow color";\r
+    public static String AUXILIARY_COLOR = "Auxiliary color";\r
+    public static String CLOUD_COLOR = "Cloud color";\r
+    public static String STOCK_COLOR = "Stock color";\r
+    public static String VALVE_COLOR = "Valve color";\r
+    public static String INPUT_COLOR = "Input color";\r
+    public static String MODULE_COLOR = "Module color";\r
+    \r
+    public static HashMap<String, String> colorPreferenceNames;\r
+    \r
+    static {\r
+        colorPreferenceNames = new HashMap<String, String>();\r
+        colorPreferenceNames.put(SysdynResource.URIs.DependencyConnection, ARROW_COLOR);\r
+        colorPreferenceNames.put(SysdynResource.URIs.DependencyConnection + "_stockInitial", ARROW_STOCK_INITIAL_COLOR);\r
+        colorPreferenceNames.put(SysdynResource.URIs.FlowConnection, FLOW_COLOR);\r
+        colorPreferenceNames.put(SysdynResource.URIs.AuxiliarySymbol, AUXILIARY_COLOR);\r
+        colorPreferenceNames.put(SysdynResource.URIs.CloudSymbol, CLOUD_COLOR);\r
+        colorPreferenceNames.put(SysdynResource.URIs.StockSymbol, STOCK_COLOR);\r
+        colorPreferenceNames.put(SysdynResource.URIs.ValveSymbol, VALVE_COLOR);\r
+        colorPreferenceNames.put(SysdynResource.URIs.InputSymbol, INPUT_COLOR);\r
+        colorPreferenceNames.put(SysdynResource.URIs.ModuleSymbol, MODULE_COLOR);\r
+    }\r
+    \r
+    public static String getColorPreferenceName(ReadGraph graph, Resource resource) \r
+            throws DatabaseException {\r
+        String preference =  colorPreferenceNames.get(getSymbolUri(graph, resource));\r
+        return preference;\r
+    }\r
+    \r
+    public static String ARROW_USE_DEFAULT_COLOR = "Arrow use default color";\r
+    public static String ARROW_STOCK_INITIAL_USE_DEFAULT_COLOR = "Arrow stock initial use default color";\r
+    public static String FLOW_USE_DEFAULT_COLOR = "Flow use default color";\r
+    public static String AUXILIARY_USE_DEFAULT_COLOR = "Auxiliary use default color";\r
+    public static String CLOUD_USE_DEFAULT_COLOR = "Cloud use default color";\r
+    public static String STOCK_USE_DEFAULT_COLOR = "Stock use default color";\r
+    public static String VALVE_USE_DEFAULT_COLOR = "Valve use default color";\r
+    public static String INPUT_USE_DEFAULT_COLOR = "Input use default color";\r
+    public static String MODULE_USE_DEFAULT_COLOR = "Module use default color";\r
+    \r
+    public static HashMap<String, String> colorDefaults;\r
+    \r
+    static {\r
+        colorDefaults = new HashMap<String, String>();\r
+        colorDefaults.put(ARROW_COLOR, ARROW_USE_DEFAULT_COLOR);\r
+        colorDefaults.put(ARROW_STOCK_INITIAL_COLOR, ARROW_STOCK_INITIAL_USE_DEFAULT_COLOR);\r
+        colorDefaults.put(FLOW_COLOR, FLOW_USE_DEFAULT_COLOR);\r
+        colorDefaults.put(AUXILIARY_COLOR, AUXILIARY_USE_DEFAULT_COLOR);\r
+        colorDefaults.put(CLOUD_COLOR, CLOUD_USE_DEFAULT_COLOR);\r
+        colorDefaults.put(STOCK_COLOR, STOCK_USE_DEFAULT_COLOR);\r
+        colorDefaults.put(VALVE_COLOR, VALVE_USE_DEFAULT_COLOR);\r
+        colorDefaults.put(INPUT_COLOR, INPUT_USE_DEFAULT_COLOR);\r
+        colorDefaults.put(MODULE_COLOR, MODULE_USE_DEFAULT_COLOR);\r
+\r
+    }\r
+    \r
+    public static String ARROW_FONT = "Arrow font";\r
+    public static String AUXILIARY_FONT = "Auxiliary font";\r
+    public static String CLOUD_FONT = "Cloud font";\r
+    public static String STOCK_FONT = "Stock font";\r
+    public static String VALVE_FONT = "Valve font";\r
+    public static String INPUT_FONT = "Input font";\r
+    public static String MODULE_FONT = "Module font";\r
+    \r
+    public static HashMap<String, String> fontPreferenceNames;\r
+    \r
+    static {\r
+        fontPreferenceNames = new HashMap<String, String>();\r
+        fontPreferenceNames.put(SysdynResource.URIs.DependencyConnection, ARROW_FONT);\r
+        fontPreferenceNames.put(SysdynResource.URIs.AuxiliarySymbol, AUXILIARY_FONT);\r
+        fontPreferenceNames.put(SysdynResource.URIs.CloudSymbol, CLOUD_FONT);\r
+        fontPreferenceNames.put(SysdynResource.URIs.StockSymbol, STOCK_FONT);\r
+        fontPreferenceNames.put(SysdynResource.URIs.ValveSymbol, VALVE_FONT);\r
+        fontPreferenceNames.put(SysdynResource.URIs.InputSymbol, INPUT_FONT);\r
+        fontPreferenceNames.put(SysdynResource.URIs.ModuleSymbol, MODULE_FONT);\r
+    }\r
+    \r
+    public static String getFontPreferenceName(ReadGraph graph, Resource resource) \r
+            throws DatabaseException {\r
+        \r
+        String preference =  fontPreferenceNames.get(getSymbolUri(graph, resource));\r
+        return preference;\r
+    }\r
+    \r
+    public static String ARROW_USE_DEFAULT_FONT = "Arrow use default font";\r
+    public static String AUXILIARY_USE_DEFAULT_FONT = "Auxiliary use default font";\r
+    public static String CLOUD_USE_DEFAULT_FONT = "Cloud use default font";\r
+    public static String STOCK_USE_DEFAULT_FONT = "Stock use default font";\r
+    public static String VALVE_USE_DEFAULT_FONT = "Valve use default font";\r
+    public static String INPUT_USE_DEFAULT_FONT = "Input use default font";\r
+    public static String MODULE_USE_DEFAULT_FONT = "Module use default font";\r
+    \r
+    \r
+    public static HashMap<String, String> fontDefaults;\r
+    \r
+    static {\r
+        fontDefaults = new HashMap<String, String>();\r
+        fontDefaults.put(ARROW_FONT, ARROW_USE_DEFAULT_FONT);\r
+        fontDefaults.put(AUXILIARY_FONT, AUXILIARY_USE_DEFAULT_FONT);\r
+        fontDefaults.put(CLOUD_FONT, CLOUD_USE_DEFAULT_FONT);\r
+        fontDefaults.put(STOCK_FONT, STOCK_USE_DEFAULT_FONT);\r
+        fontDefaults.put(VALVE_FONT, VALVE_USE_DEFAULT_FONT);\r
+        fontDefaults.put(INPUT_FONT, INPUT_USE_DEFAULT_FONT);\r
+        fontDefaults.put(MODULE_FONT, MODULE_USE_DEFAULT_FONT);\r
+    }\r
+    \r
+\r
+    \r
+    private static String getSymbolUri(ReadGraph graph, Resource resource)\r
+            throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Resource symbol = graph.getSingleObject(resource, L0.InstanceOf);\r
+        \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        if(graph.isInheritedFrom(symbol, SR.ModuleSymbol))\r
+            symbol = SR.ModuleSymbol;\r
+        \r
+        return graph.getURI(symbol);\r
+    }\r
+\r
+    /**\r
+     * Get the name of the property that decides whether to use default value or not\r
+     * @param property\r
+     * @return\r
+     */\r
+    public static String getUseDefaultProperty(String property) {\r
+        String result = colorDefaults.get(property);\r
+        if(result == null)\r
+            result = fontDefaults.get(property);\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * Returns default property if USE DEFAULT is set, otherwise returns the \r
+     * same property as given as argument.\r
+     * @param property\r
+     * @return\r
+     */\r
+    public static String getPreferenceName(String property) {\r
+        String useDefault = fontDefaults.get(property);\r
+        IPreferenceStore store = Activator.getDefault().getPreferenceStore();\r
+        if(useDefault != null && store.getBoolean(useDefault)) {\r
+            return DEFAULT_FONT;\r
+        }\r
+        \r
+        useDefault = colorDefaults.get(property);\r
+        if(useDefault != null && store.getBoolean(useDefault)) {\r
+            return DEFAULT_COLOR;\r
+        }\r
+        \r
+        return property;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferencesInitializer.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPreferencesInitializer.java
new file mode 100644 (file)
index 0000000..1b1c455
--- /dev/null
@@ -0,0 +1,85 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.preferences;\r
+\r
+import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;\r
+import org.eclipse.jface.preference.IPreferenceStore;\r
+import org.eclipse.jface.preference.PreferenceConverter;\r
+import org.eclipse.swt.graphics.FontData;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.simantics.sysdyn.ui.Activator;\r
+\r
+import com.lowagie.text.Font;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SysdynDiagramPreferencesInitializer extends AbstractPreferenceInitializer {  \r
+\r
+    @Override  \r
+    public void initializeDefaultPreferences() {\r
+        RGB black = new RGB(0, 0, 0);\r
+        RGB arrow = new RGB(0,128,192);\r
+        RGB arrowToStockInitial = new RGB(128,128,128);\r
+        \r
+        IPreferenceStore store = Activator.getDefault().getPreferenceStore();\r
+        \r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.DEFAULT_COLOR, black);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.ARROW_STOCK_INITIAL_COLOR, arrowToStockInitial);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.ARROW_COLOR, arrow);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.FLOW_COLOR, black);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.AUXILIARY_COLOR, black);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.STOCK_COLOR, black);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.VALVE_COLOR, black);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.INPUT_COLOR, black);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.CLOUD_COLOR, black);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.MODULE_COLOR, black);\r
+        \r
+\r
+        store.setDefault(SysdynDiagramPreferences.ARROW_USE_DEFAULT_COLOR, false);\r
+        store.setDefault(SysdynDiagramPreferences.ARROW_STOCK_INITIAL_USE_DEFAULT_COLOR, false);\r
+        store.setDefault(SysdynDiagramPreferences.FLOW_USE_DEFAULT_COLOR, true);\r
+        store.setDefault(SysdynDiagramPreferences.AUXILIARY_USE_DEFAULT_COLOR, true);\r
+        store.setDefault(SysdynDiagramPreferences.STOCK_USE_DEFAULT_COLOR, true);\r
+        store.setDefault(SysdynDiagramPreferences.VALVE_USE_DEFAULT_COLOR, true);\r
+        store.setDefault(SysdynDiagramPreferences.INPUT_USE_DEFAULT_COLOR, true);\r
+        store.setDefault(SysdynDiagramPreferences.CLOUD_USE_DEFAULT_COLOR, true);\r
+        store.setDefault(SysdynDiagramPreferences.MODULE_USE_DEFAULT_COLOR, true);\r
+        \r
+        FontData[] basicFont = new FontData[] {new FontData("Tahoma", 12, Font.NORMAL)};\r
+        FontData[] italicFont = new FontData[] {new FontData("Tahoma", 12, Font.ITALIC)};\r
+        FontData[] moduleFont = new FontData[] {new FontData("Tahoma", 16, Font.NORMAL)};\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.DEFAULT_FONT, basicFont);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.ARROW_FONT, basicFont);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.AUXILIARY_FONT, basicFont);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.STOCK_FONT, basicFont);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.VALVE_FONT, basicFont);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.INPUT_FONT, italicFont);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.CLOUD_FONT, basicFont);\r
+        PreferenceConverter.setDefault(store, SysdynDiagramPreferences.MODULE_FONT, moduleFont);\r
+\r
+        store.setDefault(SysdynDiagramPreferences.ARROW_USE_DEFAULT_FONT, true);\r
+        store.setDefault(SysdynDiagramPreferences.AUXILIARY_USE_DEFAULT_FONT, true);\r
+        store.setDefault(SysdynDiagramPreferences.STOCK_USE_DEFAULT_FONT, true);\r
+        store.setDefault(SysdynDiagramPreferences.VALVE_USE_DEFAULT_FONT, true);\r
+        store.setDefault(SysdynDiagramPreferences.INPUT_USE_DEFAULT_FONT, false);\r
+        store.setDefault(SysdynDiagramPreferences.CLOUD_USE_DEFAULT_FONT, true);\r
+        store.setDefault(SysdynDiagramPreferences.MODULE_USE_DEFAULT_FONT, false);\r
+\r
+    }  \r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertyExternalRead.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertyExternalRead.java
new file mode 100644 (file)
index 0000000..6a95001
--- /dev/null
@@ -0,0 +1,54 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.preferences;\r
+\r
+import org.eclipse.jface.preference.IPreferenceStore;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ParametrizedPrimitiveRead;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynDiagramPropertyExternalRead extends ParametrizedPrimitiveRead<Pair<Resource, String>, String> {\r
+\r
+    private SysdynDiagramPropertySubscription subscription;\r
+\r
+    public SysdynDiagramPropertyExternalRead(Pair<Resource, String> input) {\r
+        super(input);\r
+    }\r
+\r
+    @Override\r
+    public void register(ReadGraph graph, Listener<String> procedure) {\r
+        subscription = new SysdynDiagramPropertySubscription(procedure, parameter.second);\r
+        SysdynDiagramPropertySupport.INSTANCE.register(subscription);\r
+        IPreferenceStore store = Activator.getDefault().getPreferenceStore();\r
+        if(store.contains(parameter.second)) {\r
+            String preference = SysdynDiagramPreferences.getPreferenceName(parameter.second);\r
+            procedure.execute(store.getString(preference));\r
+        } else\r
+            procedure.execute(null);\r
+    }\r
+    \r
+    @Override\r
+    public void unregistered() {\r
+        if(subscription != null) {\r
+            SysdynDiagramPropertySupport.INSTANCE.unregister(subscription);\r
+            subscription = null;\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertySubscription.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertySubscription.java
new file mode 100644 (file)
index 0000000..286572c
--- /dev/null
@@ -0,0 +1,38 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.preferences;\r
+\r
+import org.simantics.db.procedure.Listener;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynDiagramPropertySubscription {\r
+    \r
+    private Listener<String> listener;\r
+    private String propertyName;\r
+    \r
+    public SysdynDiagramPropertySubscription(Listener<String> listener, String propertyName) {\r
+        this.listener = listener;\r
+        this.propertyName = propertyName;\r
+    }\r
+\r
+    public Listener<String> getListener() {\r
+        return listener;\r
+    }\r
+    \r
+    public String getPropertyName() {\r
+        return propertyName;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertySupport.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/preferences/SysdynDiagramPropertySupport.java
new file mode 100644 (file)
index 0000000..441b7fe
--- /dev/null
@@ -0,0 +1,109 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.preferences;\r
+\r
+import gnu.trove.set.hash.THashSet;\r
+\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.eclipse.jface.preference.IPreferenceStore;\r
+import org.eclipse.jface.util.IPropertyChangeListener;\r
+import org.eclipse.jface.util.PropertyChangeEvent;\r
+import org.simantics.sysdyn.ui.Activator;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynDiagramPropertySupport {\r
+    \r
+    public static SysdynDiagramPropertySupport INSTANCE = new SysdynDiagramPropertySupport();\r
+    \r
+    private Set<String> diagramProperties;\r
+    private THashSet<SysdynDiagramPropertySubscription> subscriptions = new THashSet<SysdynDiagramPropertySubscription>();\r
+    private SysdynDiagramPropertySubscription[] subscriptionSnapshot = null;\r
+    \r
+    private void add(String property) {\r
+        diagramProperties.add(property);\r
+        String useDefault = SysdynDiagramPreferences.getUseDefaultProperty(property);\r
+        if(useDefault != null)\r
+            diagramProperties.add(useDefault);\r
+    }\r
+    \r
+    public SysdynDiagramPropertySupport() {\r
+        diagramProperties = new HashSet<String>();\r
+        for(String property : SysdynDiagramPreferences.colorPreferenceNames.values())\r
+            add(property);\r
+        \r
+        add(SysdynDiagramPreferences.DEFAULT_COLOR);\r
+        add(SysdynDiagramPreferences.DEFAULT_FONT);\r
+        \r
+        \r
+        for(String property : SysdynDiagramPreferences.fontPreferenceNames.values())\r
+            add(property);\r
+        \r
+        Activator.getDefault().getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() {\r
+            @Override\r
+            public void propertyChange(PropertyChangeEvent event) {\r
+                String propertyName = event.getProperty();\r
+                if(diagramProperties.contains(propertyName)){\r
+                    for(SysdynDiagramPropertySubscription subscription : getSubscriptionSnapshot()) {\r
+                        String p = subscription.getPropertyName();\r
+                        String p2 = SysdynDiagramPreferences.getPreferenceName(p);\r
+                        String dp = SysdynDiagramPreferences.getUseDefaultProperty(subscription.getPropertyName());\r
+                        if(propertyName.equals(p) ||\r
+                                propertyName.equals(p2) ||\r
+                                propertyName.equals(dp)) {\r
+                            IPreferenceStore store = Activator.getDefault().getPreferenceStore();\r
+                            String result = store.getString(p2);\r
+                            subscription.getListener().execute(result);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        });\r
+    }\r
+\r
+    public void register(SysdynDiagramPropertySubscription subscription) {\r
+        assert subscription != null;\r
+        synchronized (subscriptions) {\r
+            subscriptions.add(subscription);\r
+            subscriptionSnapshot = null;\r
+        }\r
+    }\r
+\r
+    public void unregister(SysdynDiagramPropertySubscription subscription) {\r
+        assert subscription != null;\r
+        synchronized (subscriptions) {\r
+            subscriptions.remove(subscription);\r
+            subscriptionSnapshot = null;\r
+        }\r
+\r
+    }\r
+    \r
+    public SysdynDiagramPropertySubscription[] getSubscriptionSnapshot() {\r
+        SysdynDiagramPropertySubscription[] snapshot = subscriptionSnapshot;\r
+        if (snapshot == null) {\r
+            synchronized (subscriptions) {\r
+                snapshot = subscriptionSnapshot;\r
+                if (snapshot == null) {\r
+                    snapshot = subscriptionSnapshot = \r
+                            subscriptions.toArray(new SysdynDiagramPropertySubscription[subscriptions.size()]);\r
+                }\r
+            }\r
+        }\r
+        return snapshot;\r
+    }    \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynEquationPerspectiveFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynEquationPerspectiveFactory.java
new file mode 100644 (file)
index 0000000..d1c2a24
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.project;\r
+\r
+import org.eclipse.ui.IPageLayout;\r
+import org.eclipse.ui.IPerspectiveFactory;\r
+\r
+public class SysdynEquationPerspectiveFactory implements IPerspectiveFactory {\r
+\r
+    @Override\r
+    public void createInitialLayout(IPageLayout layout) {\r
+        layout.setEditorAreaVisible(true);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynPerspectiveFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynPerspectiveFactory.java
new file mode 100644 (file)
index 0000000..096dfc5
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.project;\r
+\r
+import org.eclipse.ui.IPageLayout;\r
+import org.eclipse.ui.IPerspectiveFactory;\r
+\r
+public class SysdynPerspectiveFactory implements IPerspectiveFactory {\r
+\r
+    @Override\r
+    public void createInitialLayout(IPageLayout layout) {\r
+        layout.setEditorAreaVisible(true);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynProject.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynProject.java
new file mode 100644 (file)
index 0000000..96f4a89
--- /dev/null
@@ -0,0 +1,292 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.project;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.core.runtime.Platform;\r
+import org.simantics.databoard.accessor.Accessor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.RuntimeValuations;\r
+import org.simantics.db.layer0.adapter.TrendVariable;\r
+import org.simantics.db.layer0.service.ActivationManager;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.service.GraphChangeListenerSupport;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.fmu.FMUControlJNI;\r
+import org.simantics.issues.common.IssueUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingUtils;\r
+import org.simantics.modeling.services.CaseInsensitiveComponentNamingStrategy2;\r
+import org.simantics.modeling.services.ComponentNamingStrategy;\r
+import org.simantics.project.IProject;\r
+import org.simantics.project.ProjectKeys;\r
+import org.simantics.project.exception.ProjectException;\r
+import org.simantics.project.features.AbstractProjectFeature;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.simulation.project.ExperimentManagerKeys;\r
+import org.simantics.simulation.project.ExperimentManagerMode;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.editor.SysdynEditorNamingService;\r
+import org.simantics.ui.workbench.IEditorNamingService;\r
+import org.simantics.utils.FileUtils;\r
+import org.simantics.utils.ui.BundleUtils;\r
+\r
+public class SysdynProject extends AbstractProjectFeature {\r
+       private static final String DEFAULT_PERSPECTIVE = "org.simantics.sysdyn.ui.perspective";\r
+\r
+       @Override\r
+       public void configure() throws ProjectException {\r
+               final IProject project = getProject();\r
+               final Session session = getSession();\r
+\r
+               try {\r
+                       File base = BundleUtils.findFile("org.simantics.sysdyn.ui", "");\r
+                       File f = new File(base, "../org.simantics.sysdyn.tests/src/org/simantics/sysdyn/tests/scripts");\r
+                       if(f.exists()) {\r
+                               System.setProperty("scl.test.path", f.getAbsolutePath());\r
+                       }\r
+               } catch (Exception e) {\r
+                       \r
+               }\r
+               \r
+\r
+               getProjectElement().setHint(ProjectKeys.DEFAULT_PERSPECTIVE, DEFAULT_PERSPECTIVE);\r
+               \r
+               // Multi for simupedia use\r
+               getProjectElement().setHint(ExperimentManagerKeys.EXPERIMENT_MANAGER_MODE, ExperimentManagerMode.MULTI_EXPERIMENT);\r
+               // Single for normal workbench use\r
+//             getProjectElement().setHint(ExperimentManagerKeys.EXPERIMENT_MANAGER_MODE, ExperimentManagerMode.SINGLE_EXPERIMENT);\r
+               \r
+               getProjectElement().setHint(IEditorNamingService.KEY_EDITOR_NAMING_SERVICE, new SysdynEditorNamingService());\r
+\r
+               // Install naming strategy for model components.\r
+               GraphChangeListenerSupport changeSupport = session.peekService(GraphChangeListenerSupport.class);\r
+               if (changeSupport != null) {\r
+                       getProjectElement().setHint(ComponentNamingStrategy.PROJECT_KEY, new CaseInsensitiveComponentNamingStrategy2(changeSupport, "%s%d"));\r
+               }\r
+\r
+               try {\r
+\r
+                       Resource projectResource = project.get();\r
+\r
+                       session.registerService(RuntimeValuations.class, new RuntimeValuations() {\r
+\r
+                               @Override\r
+                               public boolean supports(String valuation) {\r
+\r
+                                       IExperimentManager expMan = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+                                       IExperiment experiment = expMan.getExperiment(valuation);\r
+\r
+                                       return experiment != null;\r
+\r
+                               }\r
+\r
+                               @Override\r
+                               public Accessor getAccessor(String variableIdentityPrefix, String valuation, String suffix) {\r
+                                       return null;\r
+                               }\r
+\r
+                               @Override\r
+                               public TrendVariable getVariable(String variableIdentityPrefix, String valuation, String suffix) {\r
+\r
+                                       return null;\r
+\r
+                               }\r
+\r
+                       });\r
+\r
+\r
+\r
+                       ActivationManager activationManager = session.getService(ActivationManager.class);\r
+                       if (activationManager != null) {\r
+                               activationManager.activate(session, projectResource);\r
+                       }\r
+\r
+\r
+                       final VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);\r
+\r
+                       support.getWorkspacePersistent("experiments");\r
+                       support.getWorkspacePersistent("profiles");\r
+            support.getWorkspacePersistent("preferences");\r
+                       support.getWorkspacePersistent("issues");\r
+\r
+               } catch (DatabaseException e) {\r
+\r
+                       throw new ProjectException(e);\r
+\r
+               }\r
+\r
+\r
+               cleanProjectFolder(session, project.get());\r
+\r
+               // Clean all temporary files possibly left by previous sysdyn instances\r
+               clearFMUTempDirectory();\r
+\r
+\r
+               // Issues\r
+               try {\r
+                       session.syncRequest(new ReadRequest() {\r
+                               @Override\r
+                               public void run(ReadGraph graph) throws DatabaseException {\r
+                                       onActivated(graph, getProject());\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       throw new ProjectException(e);\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Clears fmu temp directory. This directory hosts\r
+        * fmu files for game experiments. In normal situations\r
+        * experiments clean up their temp files, but for example\r
+        * a system crash may leave files to temp directory. \r
+        */\r
+       private void clearFMUTempDirectory() {\r
+               // Find commone "TEMP/fmu" directory\r
+               File commonDir = new File(FMUControlJNI.TEMP_FMU_COMMON_DIRECTORY);\r
+               if(commonDir != null && commonDir.isDirectory()) {\r
+\r
+                       // List all files and directories in "TEMP/fmu" \r
+                       for(File child : commonDir.listFiles()) {\r
+                               if(child.isDirectory()) {\r
+                                       // If directory is found, try to get the lock file in it\r
+                                       File lock = new File(child, FMUControlJNI.LOCK_FILE_NAME);\r
+                                       if(!lock.isFile() || lock.delete()) {\r
+                                               // If lock is not found, or the lock can be delted, the directory is not locked. -> Delete the rest of the directory\r
+                                               try {\r
+                                                       FileUtils.deleteAll(child);\r
+                                                       child.delete();\r
+                                               } catch (IOException e) {\r
+\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+\r
+       @Override\r
+       public void deconfigure() throws ProjectException {\r
+           \r
+        ModelingUtils.untrackDependencies(getSession());\r
+\r
+               getProjectElement().removeHint(ComponentNamingStrategy.PROJECT_KEY);\r
+       }\r
+\r
+       public void cleanProjectFolder(Session session, final Resource projectResource) throws ProjectException {\r
+               String projectName = null;\r
+               final HashMap<String, Resource> resultPaths = new HashMap<String, Resource>();\r
+               try {\r
+                       projectName = session.syncRequest(new Read<String>() {\r
+\r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       for(Resource model : graph.getObjects(projectResource, l0.ConsistsOf)) {\r
+                                               if(graph.isInstanceOf(model, sr.SysdynModel)){\r
+                                                       for(Resource experiment : graph.getObjects(model, l0.ConsistsOf)) {\r
+                                                               if(graph.isInstanceOf(experiment, SIMU.Experiment)) {\r
+                                                                       for(Resource result : graph.getObjects(experiment, sr.Experiment_result)) {\r
+                                                                               if(!graph.isInstanceOf(result, sr.HistoryDataset)) {\r
+                                                                                       String resultFile = (String)graph.getPossibleRelatedValue(result, sr.Result_resultFile);\r
+                                                                                       if(result != null) resultPaths.put(resultFile, result);\r
+                                                                               }\r
+                                                                       }\r
+                                                                       for(Resource resultSet : graph.getObjects(experiment, sr.Experiment_resultSet)) {\r
+                                                                               for(Resource result : graph.getObjects(resultSet, sr.Experiment_result)) {\r
+                                                                                       if(!graph.isInstanceOf(result, sr.HistoryDataset)) {\r
+                                                                                               String resultFile = (String)graph.getPossibleRelatedValue(result, sr.Result_resultFile);\r
+                                                                                               if(result != null) resultPaths.put(resultFile, result);\r
+                                                                                       }\r
+                                                                               }\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                                       return graph.getPossibleRelatedValue(projectResource, l0.HasName);\r
+\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       throw new ProjectException(e);\r
+               }\r
+\r
+               if(projectName != null) {\r
+                       File root = new File(Platform.getLocation().toOSString(), "www.simantics.org");\r
+                       if(!root.isDirectory()) return;\r
+                       File projectRoot = new File(root, projectName);\r
+                       if(!projectRoot.isDirectory()) return;\r
+                       File[] files = projectRoot.listFiles();\r
+\r
+                       for(File file : files) {\r
+                               if(resultPaths.get(file.getAbsolutePath()) == null) {\r
+                                       file.delete();\r
+                               } else {\r
+                                       resultPaths.remove(file.getAbsolutePath());\r
+                               }\r
+                       }\r
+\r
+                       if (!resultPaths.keySet().isEmpty()) {\r
+                               session.asyncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               for(String key : resultPaths.keySet()) {\r
+                                                       Resource result = resultPaths.get(key);\r
+                                                       graph.deny(result, l0.PartOf);\r
+                                                       graph.deny(result, graph.getInverse(SysdynResource.getInstance(graph).Experiment_result));\r
+                                               }\r
+                                       }\r
+                               }) ;\r
+                       }\r
+               }\r
+       }\r
+\r
+       public void onActivated(final ReadGraph graph, final IProject project) throws DatabaseException {\r
+\r
+//             GraphChangeListenerSupport changeSupport = graph.getService(GraphChangeListenerSupport.class);\r
+//             changeSupport.addMetadataListener(new GenericChangeListener<DependencyChangesRequest, DependencyChanges>() {\r
+//\r
+//                     @Override\r
+//                     public void onEvent(ReadGraph graph, DependencyChanges event) throws DatabaseException {\r
+//\r
+//                             WriteGraph w = (WriteGraph)graph;\r
+//                             w.addMetadata(event);\r
+//\r
+//                     }\r
+//\r
+//             });\r
+\r
+               IssueUtils.listenActiveProjectIssueSources(graph, project.get());\r
+               \r
+        ModelingUtils.trackDependencies(graph);\r
+\r
+\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynTrendPerspectiveFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/project/SysdynTrendPerspectiveFactory.java
new file mode 100644 (file)
index 0000000..cf2eb01
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.project;\r
+\r
+import org.eclipse.ui.IPageLayout;\r
+import org.eclipse.ui.IPerspectiveFactory;\r
+\r
+public class SysdynTrendPerspectiveFactory implements IPerspectiveFactory {\r
+\r
+    @Override\r
+    public void createInitialLayout(IPageLayout layout) {\r
+        layout.setEditorAreaVisible(true);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayDependencyTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayDependencyTab.java
new file mode 100644 (file)
index 0000000..bd1c1bf
--- /dev/null
@@ -0,0 +1,391 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.Scale;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.util.ObjectUtils;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.connections.DependencyEdgeClass;\r
+import org.simantics.sysdyn.ui.elements.connections.DependencyNode;\r
+import org.simantics.sysdyn.ui.properties.widgets.ArrowHeadWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.DelayMarkWidget;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.datastructures.Triple;\r
+\r
+/**\r
+ * Tab for multiple dependencies.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ArrayDependencyTab  extends AdjustableTab {\r
+\r
+    Button none, plus, minus, other, inside, outside;\r
+    TrackedText polarityText, polarityLocationText;\r
+    private DelayMarkWidget delayMark;\r
+    private ArrowHeadWidget arrowhead;\r
+       private Scale lineThicknessScale;\r
+       private Group hiddenDefaultbuttonGroup;\r
+       private Group polarityGroup;\r
+       private Group locationGroup;\r
+       private Composite misc;\r
+       private Group lineThicknessGroup;\r
+    \r
+    class LineThicknessSelectionListener extends SelectionListenerImpl<ArrayList<Resource>> {\r
+       Scale scale;\r
+               private int selection;\r
+\r
+        public LineThicknessSelectionListener(ISessionContext context, Scale scale) {\r
+               super(context);\r
+               this.scale = scale;\r
+        }\r
+        \r
+        @Override\r
+        public void beforeApply() {\r
+            this.selection = scale.getWidget().getSelection();\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, ArrayList<Resource> connectionElements) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            float width = ((float)selection) / 10.0f;\r
+            for (Resource r : connectionElements)\r
+               graph.claimLiteral(r, sr.DependencyConnection_strokeWidth, width);\r
+        }\r
+        \r
+    }\r
+    \r
+    class LineThicknessRadioSelectionFactory extends ReadFactoryImpl<ArrayList<Resource>, Integer> {\r
+\r
+        public LineThicknessRadioSelectionFactory() {\r
+        }\r
+\r
+        @Override\r
+        public Integer perform(ReadGraph graph, ArrayList<Resource> dependencyConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            if (dependencyConnection.size() > 0) {\r
+               Float width = graph.getPossibleRelatedValue(dependencyConnection.get(0), sr.DependencyConnection_strokeWidth, Bindings.FLOAT);  \r
+               if(width != null) {\r
+                       return (int)Math.round(width * 10);\r
+               }\r
+            }\r
+            return (int)Math.round(DependencyEdgeClass.DEFAULT_STROKE_WIDTH * 10);\r
+        }\r
+    }\r
+    \r
+    class OtherPolarityStringPropertyFactory extends ReadFactoryImpl<ArrayList<Resource>, String> {\r
+\r
+           private final String propertyURI;\r
+\r
+           public OtherPolarityStringPropertyFactory() {\r
+               this.propertyURI = SysdynResource.URIs.DependencyConnection_polarity;\r
+           }\r
+\r
+           @SuppressWarnings("unchecked")\r
+               @Override\r
+           public Object getIdentity(Object inputContents) {\r
+               return new Triple<ArrayList<Resource>, String, Object>((ArrayList<Resource>) inputContents, propertyURI, getClass());\r
+           }\r
+\r
+           @Override\r
+           public String perform(ReadGraph graph, ArrayList<Resource> resources) throws DatabaseException {\r
+               String value = graph.getPossibleRelatedValue(resources.get(0), graph.getResource(propertyURI));;\r
+               if (value == null)\r
+                       return "";\r
+               for (Resource r : resources) {\r
+                       String s = graph.getPossibleRelatedValue(r, graph.getResource(propertyURI));\r
+                       if (!value.equals(s))\r
+                               return "";\r
+               }\r
+               return value;\r
+           }           \r
+    }\r
+    \r
+    class OtherPolarityStringPropertyModifier extends TextModifyListenerImpl<ArrayList<Resource>> {\r
+\r
+       final private String propertyURI;\r
+       \r
+       public OtherPolarityStringPropertyModifier() {\r
+               this.propertyURI = SysdynResource.URIs.DependencyConnection_polarity;\r
+       }\r
+\r
+       @Override\r
+       public void applyText(WriteGraph graph, ArrayList<Resource> resources, String text) throws DatabaseException {\r
+               for (Resource r : resources)\r
+                       graph.claimLiteral(r, graph.getResource(propertyURI), text, Bindings.STRING);\r
+       }\r
+       \r
+    }\r
+\r
+    class PolarityLocationSelectionListener extends SelectionListenerImpl<ArrayList<Resource>> {\r
+        private String location;\r
+\r
+        public PolarityLocationSelectionListener(ISessionContext context, String location) {\r
+            super(context);\r
+            this.location = location;\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, ArrayList<Resource> connectionElements) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            for (Resource r : connectionElements)\r
+               graph.claimLiteral(r, sr.DependencyConnection_polarityLocation, location);\r
+        }\r
+        \r
+    }\r
+    \r
+    class PolarityLocationRadioSelectionFactory extends ReadFactoryImpl<ArrayList<Resource>, Boolean> {\r
+        private String location;\r
+\r
+        public PolarityLocationRadioSelectionFactory(String location) {\r
+            this.location = location;\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, location, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, ArrayList<Resource> dependencyConnections) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            for (Resource r : dependencyConnections) {\r
+               String location = graph.getPossibleRelatedValue(r, sr.DependencyConnection_polarityLocation, Bindings.STRING);  \r
+               if (DependencyNode.OUTSIDE.equals(this.location)) {\r
+                       if (ObjectUtils.objectEquals(this.location, location))\r
+                               continue;\r
+               } else {\r
+                       if (location == null) {\r
+                           continue;\r
+                       } else {\r
+                           if (ObjectUtils.objectEquals(this.location, location))\r
+                               continue;\r
+                       }\r
+               }\r
+               return false;\r
+            }\r
+            return true;\r
+        }\r
+    }\r
+    \r
+    class PolaritySelectionListener extends SelectionListenerImpl<ArrayList<Resource>> {\r
+        private String polarity;\r
+\r
+        public PolaritySelectionListener(ISessionContext context, String polarity) {\r
+            super(context);\r
+            this.polarity = polarity;\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, ArrayList<Resource> connectionElements) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            for (Resource r : connectionElements)\r
+               graph.claimLiteral(r, sr.DependencyConnection_polarity, polarity.trim());\r
+        }\r
+        \r
+    }\r
+    \r
+    class PolarityRadioSelectionFactory extends ReadFactoryImpl<ArrayList<Resource>, Boolean> {\r
+        private String polarity;\r
+\r
+        public PolarityRadioSelectionFactory(String polarity) {\r
+            this.polarity = polarity;\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, polarity, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, ArrayList<Resource> dependencyConnections) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            for (Resource r : dependencyConnections) {\r
+               String polarity = graph.getPossibleRelatedValue(r, sr.DependencyConnection_polarity, Bindings.STRING);     \r
+               if (polarity == null && this.polarity.equals(""))\r
+                       continue;\r
+               if (ObjectUtils.objectEquals(polarity, this.polarity))\r
+                       continue;\r
+               return false;\r
+            }\r
+            return true;\r
+        }\r
+    }\r
+    \r
+    class OtherPolaritySelectionFactory extends ReadFactoryImpl<ArrayList<Resource>, Boolean> {\r
+\r
+        String[] limits;\r
+        \r
+        public OtherPolaritySelectionFactory(String[] limits) {\r
+            this.limits = limits;\r
+        }\r
+        \r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Pair<Object, Class<?>>(inputContents, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, ArrayList<Resource> dependencyConnections) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            for (Resource r : dependencyConnections) {\r
+               String polarity = graph.getPossibleRelatedValue(r, sr.DependencyConnection_polarity, Bindings.STRING);\r
+                for(String s : limits) {\r
+                    if(ObjectUtils.objectEquals(polarity, s))\r
+                        return false;\r
+                }\r
+            }\r
+            return true;\r
+        }\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               composite = new Composite(body, SWT.NONE);\r
+        \r
+        /* Add a dummy button at the begin to suck in the nonsense selection events that\r
+         * the first radio button in the group of ALL the radio buttons receives when no\r
+         * radio is selected and then one is selected in other group than where the first \r
+         * radio button lies.  \r
+         */\r
+        hiddenDefaultbuttonGroup = new Group(composite, SWT.NONE);\r
+        new Button(hiddenDefaultbuttonGroup, support, SWT.RADIO);\r
+        \r
+        polarityGroup = new Group(composite, SWT.NONE);\r
+        polarityGroup.setText("Polarity");\r
+        \r
+        none = new Button(polarityGroup, support, SWT.RADIO);\r
+        none.setText("None");\r
+        none.setSelectionFactory(new PolarityRadioSelectionFactory(""));\r
+        none.addSelectionListener(new PolaritySelectionListener(context, ""));\r
+        \r
+        plus = new Button(polarityGroup, support, SWT.RADIO);\r
+        plus.setText("+");\r
+        plus.setSelectionFactory(new PolarityRadioSelectionFactory("+"));\r
+        plus.addSelectionListener(new PolaritySelectionListener(context, "+"));\r
+        \r
+        minus = new Button(polarityGroup, support, SWT.RADIO);\r
+        minus.setText("-");\r
+        minus.setSelectionFactory(new PolarityRadioSelectionFactory("-"));\r
+        minus.addSelectionListener(new PolaritySelectionListener(context, "-"));\r
+        \r
+        other = new Button(polarityGroup, support, SWT.RADIO);\r
+        other.setText("other");\r
+        other.setSelectionFactory(new OtherPolaritySelectionFactory(new String[] {null, "+", "-", ""}));\r
+        \r
+        polarityText = new TrackedText(polarityGroup, support, SWT.BORDER);\r
+        polarityText.setTextFactory(new OtherPolarityStringPropertyFactory());\r
+        polarityText.addModifyListener(new OtherPolarityStringPropertyModifier());\r
+        \r
+        locationGroup = new Group(composite, SWT.NONE);\r
+        locationGroup.setText("Location");\r
+        \r
+        inside = new Button(locationGroup, support, SWT.RADIO);\r
+        inside.setText("Inside");\r
+        inside.setSelectionFactory(new PolarityLocationRadioSelectionFactory(DependencyNode.INSIDE));\r
+        inside.addSelectionListener(new PolarityLocationSelectionListener(context, DependencyNode.INSIDE));\r
+        \r
+        outside = new Button(locationGroup, support, SWT.RADIO);\r
+        outside.setText("Outside");\r
+        outside.setSelectionFactory(new PolarityLocationRadioSelectionFactory(DependencyNode.OUTSIDE));\r
+        outside.addSelectionListener(new PolarityLocationSelectionListener(context, DependencyNode.OUTSIDE));\r
+\r
+        misc = new Composite(composite, SWT.NONE);\r
+        \r
+        arrowhead = new ArrowHeadWidget(misc, support, SWT.NULL);\r
+        delayMark = new DelayMarkWidget(misc, support, SWT.NULL);\r
+        \r
+        lineThicknessGroup = new Group(misc, SWT.NONE);\r
+        lineThicknessGroup.setText("Line thickness:");\r
+        lineThicknessScale = new Scale(lineThicknessGroup, support, SWT.HORIZONTAL);\r
+        lineThicknessScale.getWidget().setMinimum(1);\r
+        lineThicknessScale.getWidget().setMaximum(15);\r
+        lineThicknessScale.getWidget().setPageIncrement(1);\r
+        lineThicknessScale.getWidget().setIncrement(1);\r
+        lineThicknessScale.setSelectionFactory(new LineThicknessRadioSelectionFactory());\r
+        lineThicknessScale.addSelectionListener(new LineThicknessSelectionListener(context, lineThicknessScale));\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(composite);\r
+        \r
+        GridDataFactory.fillDefaults().exclude(true).applyTo(hiddenDefaultbuttonGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(hiddenDefaultbuttonGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityGroup);\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(polarityGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityText.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(locationGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(locationGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(misc);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(misc);\r
+\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).applyTo(arrowhead.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).applyTo(delayMark.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().span(2, 1).applyTo(lineThicknessGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(lineThicknessGroup);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
+        \r
+        GridDataFactory.fillDefaults().exclude(true).applyTo(hiddenDefaultbuttonGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(hiddenDefaultbuttonGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityGroup);\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(polarityGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityText.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(locationGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(locationGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(misc);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(misc);\r
+\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).applyTo(arrowhead.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).applyTo(delayMark.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().span(1, 1).applyTo(lineThicknessGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(lineThicknessGroup);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayFlowTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayFlowTab.java
new file mode 100644 (file)
index 0000000..ad02e9a
--- /dev/null
@@ -0,0 +1,106 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Scale;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.connections.FlowConnectionStyle;\r
+\r
+/**\r
+ * Tab for multiple dependencies.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ArrayFlowTab  extends LabelPropertyTabContributor {\r
+\r
+       private Scale lineThicknessScale;\r
+    \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(composite);\r
+        \r
+        Group lineThicknessGroup = new Group(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().applyTo(lineThicknessGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(lineThicknessGroup);\r
+        lineThicknessGroup.setText("Flow thickness:");\r
+        lineThicknessScale = new Scale(lineThicknessGroup, support, SWT.HORIZONTAL);\r
+        lineThicknessScale.getWidget().setMinimum(1);\r
+        lineThicknessScale.getWidget().setMaximum(9);\r
+        lineThicknessScale.getWidget().setPageIncrement(1);\r
+        lineThicknessScale.getWidget().setIncrement(1);\r
+        lineThicknessScale.setSelectionFactory(new LineThicknessRadioSelectionFactory());\r
+        lineThicknessScale.addSelectionListener(new LineThicknessSelectionListener(context, lineThicknessScale));\r
+    }\r
+    \r
+    class LineThicknessSelectionListener extends SelectionListenerImpl<ArrayList<Resource>> {\r
+       Scale scale;\r
+               private int selection;\r
+\r
+        public LineThicknessSelectionListener(ISessionContext context, Scale scale) {\r
+               super(context);\r
+               this.scale = scale;\r
+        }\r
+        \r
+        @Override\r
+        public void beforeApply() {\r
+            this.selection = scale.getWidget().getSelection();\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, ArrayList<Resource> connectionElements) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            float width = ((float)selection) / 3.0f;\r
+            for (Resource r : connectionElements)\r
+               graph.claimLiteral(r, sr.FlowConnection_width, width);\r
+        }\r
+        \r
+    }\r
+    \r
+    class LineThicknessRadioSelectionFactory extends ReadFactoryImpl<ArrayList<Resource>, Integer> {\r
+\r
+        public LineThicknessRadioSelectionFactory() {\r
+        }\r
+\r
+        @Override\r
+        public Integer perform(ReadGraph graph, ArrayList<Resource> flowConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            if (flowConnection.size() > 0) {\r
+               Float width = graph.getPossibleRelatedValue(flowConnection.get(0), sr.FlowConnection_width, Bindings.FLOAT);  \r
+               if(width != null) {\r
+                       return (int)Math.round(width * 3);\r
+               }\r
+            }\r
+            return (int)Math.round(FlowConnectionStyle.DEFAULT_LINE_WIDTH * 3);\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayIndexesTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayIndexesTab.java
new file mode 100644 (file)
index 0000000..e97de85
--- /dev/null
@@ -0,0 +1,410 @@
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.swt.widgets.TreeItem;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.ResourceArray;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+import org.simantics.utils.RunnableWithObject;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+\r
+public class ArrayIndexesTab extends LabelPropertyTabContributor implements Widget{\r
+\r
+       GraphExplorerComposite availableEnumerationsExplorer;\r
+       GraphExplorerComposite usedEnumerationsExplorer;\r
+       private WidgetSupportImpl buttonSupport;\r
+       private org.simantics.browsing.ui.swt.widgets.Label usedEnumerationsLabel;\r
+       \r
+       @Override\r
+       public void createControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               support.register(this);\r
+               \r
+               buttonSupport = new WidgetSupportImpl();\r
+               \r
+               GridLayoutFactory.fillDefaults().numColumns(4).applyTo(body);\r
+               \r
+               \r
+               Composite available = new Composite(body, SWT.NONE);\r
+               GridLayoutFactory.fillDefaults().applyTo(available);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(available);\r
+               Label label = new Label(available, SWT.None);\r
+               label.setText("Available Enumerations");\r
+               availableEnumerationsExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                               "displaySelectors", "displayFilter").values(false, false), site, available, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);\r
+               \r
+               availableEnumerationsExplorer\r
+               .setBrowseContexts(SysdynResource.URIs.AvailableVariableIndexes);\r
+               availableEnumerationsExplorer.setColumns(ColumnKeys.ENUMERATION_TABLE_COLUMNS);\r
+               availableEnumerationsExplorer.setInputSource(new SingleSelectionInputSource(\r
+                               ResourceArray.class));\r
+\r
+               availableEnumerationsExplorer.finish();\r
+\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                               availableEnumerationsExplorer);\r
+               \r
+               Control c = availableEnumerationsExplorer.getExplorerControl();\r
+               if (c instanceof Tree)\r
+                       ((Tree) c).setLinesVisible(true);\r
+               \r
+               \r
+               Button add = new Button(body, buttonSupport, SWT.NONE);\r
+               add.setText(" -> ");\r
+               \r
+               add.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {\r
+\r
+            List<Resource> enumerationResources;\r
+\r
+            @Override\r
+            public void beforeApply() {\r
+                enumerationResources = getSelectedResources(availableEnumerationsExplorer);\r
+            }\r
+\r
+                       @Override\r
+                       public void apply(WriteGraph graph, ResourceArray input)\r
+                                       throws DatabaseException {\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               for(Resource r : input.resources) {\r
+                                   Resource arrayIndexes = graph.getPossibleObject(r, sr.Variable_arrayIndexesList);\r
+                                   if(arrayIndexes == null) {\r
+                                       graph.claim(r, sr.Variable_arrayIndexesList, ListUtils.create(graph, enumerationResources));\r
+                                   } else {\r
+                                       ArrayList<Resource> filtered = new ArrayList<Resource>();\r
+                                       for(Resource enumeration : enumerationResources) {\r
+                                           if(ListUtils.getNode(graph, arrayIndexes, enumeration) == null)\r
+                                               filtered.add(enumeration);\r
+                                       }\r
+                                       ListUtils.insertBack(graph, arrayIndexes, filtered);\r
+                                   }\r
+                               }\r
+                       }\r
+               });\r
+               \r
+               Composite used = new Composite(body, SWT.NONE);\r
+               GridLayoutFactory.fillDefaults().applyTo(used);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(used);\r
+               usedEnumerationsLabel = new org.simantics.browsing.ui.swt.widgets.Label(used, buttonSupport, SWT.None);\r
+               usedEnumerationsLabel.setTextFactory(new ReadFactoryImpl<ResourceArray, String>() {\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph, ResourceArray input) throws DatabaseException {\r
+                if(input.size() < 2)\r
+                    return "Used Enumerations";\r
+                else {\r
+                    StringBuilder sb = new StringBuilder();\r
+                    sb.append("Enumerations in: ");\r
+                    boolean first = true;\r
+                    for(Resource r : input) {\r
+                        if(!first)\r
+                            sb.append(", ");\r
+                        first = false;\r
+                        \r
+                        String name = NameUtils.getSafeName(graph, r);\r
+                        sb.append(name);\r
+                    }\r
+                    return sb.toString();\r
+                }\r
+            }\r
+\r
+        });\r
+               \r
+               usedEnumerationsExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                               "displaySelectors", "displayFilter").values(false, false), site, used, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);\r
+               \r
+               usedEnumerationsExplorer\r
+               .setBrowseContexts(SysdynResource.URIs.UsedVariableIndexes);\r
+               usedEnumerationsExplorer.setColumns(ColumnKeys.ENUMERATION_TABLE_COLUMNS);\r
+               usedEnumerationsExplorer.setInputSource(new SingleSelectionInputSource(\r
+                               ResourceArray.class));\r
+\r
+               usedEnumerationsExplorer.finish();\r
+\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                               usedEnumerationsExplorer);\r
+               \r
+               Control c2 = usedEnumerationsExplorer.getExplorerControl();\r
+               if (c2 instanceof Tree)\r
+                       ((Tree) c2).setLinesVisible(true);\r
+               \r
+               Composite buttons = new Composite(body, SWT.None);\r
+               GridLayoutFactory.fillDefaults().applyTo(buttons);\r
+               \r
+               Button up = new Button(buttons, buttonSupport, SWT.NONE);\r
+               up.setText("Up");\r
+               up.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {\r
+\r
+            List<Integer> selectedIndexes;\r
+\r
+                   @Override\r
+                   public void beforeApply() {\r
+                selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);\r
+                   }\r
+\r
+                   @Override\r
+                   public void apply(WriteGraph graph, ResourceArray input)\r
+                           throws DatabaseException {\r
+                       \r
+                       Layer0 L0 = Layer0.getInstance(graph);\r
+                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                for(Resource variable : input) {\r
+                    Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
+                    if(arrayIndexes != null) {\r
+                        List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);\r
+                        List<Resource> toBeMoved = new ArrayList<Resource>();\r
+                        for(Integer index : selectedIndexes) {\r
+                            if(index < enumerations.size()) {\r
+                                Resource enumeration = enumerations.get(index);\r
+                                toBeMoved.add(enumeration);\r
+                            }\r
+\r
+                        }\r
+\r
+                        for(Resource enumeration : toBeMoved) {\r
+                            Resource node = ListUtils.getNode(graph, arrayIndexes, enumeration);\r
+                            Resource prev = graph.getSingleObject(node, L0.List_Previous);\r
+                            if(!arrayIndexes.equals(prev) && !toBeMoved.contains(graph.getPossibleObject(prev, L0.List_Element))) {\r
+                                ListUtils.swapWithPrevious(graph, arrayIndexes, enumeration);\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+                \r
+                // Move selection\r
+                usedEnumerationsExplorer.getDisplay().asyncExec(new RunnableWithObject(usedEnumerationsExplorer, selectedIndexes) {\r
+                    @Override\r
+                    public void run() {\r
+                        Control c = ((GraphExplorerComposite)object).getExplorerControl();\r
+                        if(c != null && c instanceof Tree && object2 instanceof List<?>) {\r
+                            Tree tree = (Tree) c;\r
+                            tree.deselectAll();\r
+                            \r
+                            @SuppressWarnings("unchecked")\r
+                            List<Integer> list = (List<Integer>) object2;\r
+                            Set<TreeItem> selection = new HashSet<TreeItem>();\r
+                            for(Integer i : list) {\r
+                                TreeItem item = null;\r
+                                if(i - 1 >= 0)\r
+                                    item = tree.getItem(i - 1);\r
+                                if(item == null || selection.contains(item))\r
+                                    item = tree.getItem(i);\r
+                                if(item != null && !selection.contains(item))\r
+                                    selection.add(item);\r
+                            }\r
+                            tree.setSelection(selection.toArray(new TreeItem[selection.size()]));\r
+                        }\r
+                    }\r
+                });\r
+                   }\r
+               });\r
+\r
+               Button down = new Button(buttons, buttonSupport, SWT.NONE);\r
+               down.setText("Down");\r
+               down.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {\r
+\r
+                   List<Integer> selectedIndexes;\r
+\r
+                   @Override\r
+                   public void beforeApply() {\r
+                       selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);\r
+                   }\r
+\r
+\r
+                   @Override\r
+                   public void apply(WriteGraph graph, ResourceArray input)\r
+                           throws DatabaseException {\r
+\r
+                       Layer0 L0 = Layer0.getInstance(graph);\r
+                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                       for(Resource variable : input) {\r
+                           Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
+                           if(arrayIndexes != null) {\r
+                               List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);\r
+                               List<Resource> toBeMoved = new ArrayList<Resource>();\r
+                               for(Integer index : selectedIndexes) {\r
+                                   if(index < enumerations.size()) {\r
+                                       Resource enumeration = enumerations.get(index);\r
+                                       toBeMoved.add(0, enumeration); // Make an inverted list. \r
+                                   }\r
+\r
+                               }\r
+\r
+                               for(Resource enumeration : toBeMoved) {\r
+                            Resource node = ListUtils.getNode(graph, arrayIndexes, enumeration);\r
+                            Resource next = graph.getSingleObject(node, L0.List_Next);\r
+                            if(!arrayIndexes.equals(next) && !toBeMoved.contains(graph.getPossibleObject(next, L0.List_Element))) {\r
+                                ListUtils.swapWithNext(graph, arrayIndexes, enumeration);\r
+                                   }\r
+                               }\r
+                           }\r
+                       }\r
+                       \r
+                       // Move selection\r
+                       usedEnumerationsExplorer.getDisplay().asyncExec(new RunnableWithObject(usedEnumerationsExplorer, selectedIndexes) {\r
+                    @Override\r
+                           public void run() {\r
+                               Control c = ((GraphExplorerComposite)object).getExplorerControl();\r
+                               if(c != null && c instanceof Tree && object2 instanceof List<?>) {\r
+                                   Tree tree = (Tree) c;\r
+                                   tree.deselectAll();\r
+                                   \r
+                                   @SuppressWarnings("unchecked")\r
+                            List<Integer> list = (List<Integer>) object2;\r
+                                   Set<TreeItem> selection = new HashSet<TreeItem>();\r
+                                   Collections.reverse(list);\r
+                            for(Integer i : list) {\r
+                                TreeItem item = null;\r
+                                if(i + 1 < tree.getItemCount())\r
+                                    item = tree.getItem(i + 1);\r
+                                if(item == null || selection.contains(item))\r
+                                    item = tree.getItem(i);\r
+                                if(item != null && !selection.contains(item))\r
+                                    selection.add(item);\r
+                            }\r
+                                   tree.setSelection(selection.toArray(new TreeItem[selection.size()]));\r
+                               }\r
+                           }\r
+                       });\r
+                   }\r
+               });\r
+\r
+               \r
+               Button remove = new Button(buttons, buttonSupport, SWT.NONE);\r
+               remove.setText("Remove");\r
+               remove.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {\r
+                   \r
+                   List<Integer> selectedIndexes;\r
+\r
+                   @Override\r
+                   public void beforeApply() {\r
+                       selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);\r
+                   }\r
+\r
+                   @Override\r
+                   public void apply(WriteGraph graph, ResourceArray input)\r
+                           throws DatabaseException {\r
+                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                       for(Resource variable : input) {\r
+                           Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
+                           if(arrayIndexes != null) {\r
+                               List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);\r
+                               List<Resource> toBeRemoved = new ArrayList<Resource>();\r
+                               for(Integer index : selectedIndexes) {\r
+                               if(index < enumerations.size()) {\r
+                                   Resource enumeration = enumerations.get(index);\r
+                                   toBeRemoved.add(enumeration);\r
+                               }\r
+\r
+                               }\r
+                               \r
+                               for(Resource enumeration : toBeRemoved)\r
+                                   ListUtils.removeElement(graph, arrayIndexes, enumeration);\r
+                           }\r
+                       }\r
+                   }\r
+               });\r
+       }\r
+\r
+       \r
+       private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {\r
+               List<Resource> result = new ArrayList<Resource>();\r
+               \r
+               ISelection selection = ((ISelectionProvider) explorer\r
+                               .getAdapter(ISelectionProvider.class)).getSelection();\r
+               if (selection == null)\r
+                       return result;\r
+               IStructuredSelection iss = (IStructuredSelection) selection;\r
+               @SuppressWarnings("unchecked")\r
+               List<AdaptableHintContext> selections = iss.toList();\r
+               for(AdaptableHintContext ahc : selections) {\r
+                       Resource resource = (Resource) ahc.getAdapter(Resource.class);\r
+                       result.add(resource);\r
+               }\r
+               return result;\r
+       }\r
+       \r
+          private List<Integer> getSelectedIndexes(final GraphExplorerComposite explorer) {\r
+               final List<Integer> result = new ArrayList<Integer>();\r
+\r
+               explorer.getDisplay().syncExec(new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+                    Control c = explorer.getExplorerControl();\r
+                    if (c instanceof Tree) {\r
+                        Tree tree = (Tree) c;\r
+                        TreeItem[] selection = tree.getSelection();\r
+                        \r
+                        for(TreeItem item : selection) {\r
+                            result.add(tree.indexOf(item));\r
+                        }\r
+                    }\r
+                }\r
+               });\r
+\r
+               return result;\r
+           }\r
+\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+           \r
+        if(input != null && input instanceof IStructuredSelection) {\r
+            Object first = ((IStructuredSelection)input).getFirstElement();\r
+            ResourceArray resourceArray = null;\r
+            if(first instanceof Resource)\r
+                resourceArray = new ResourceArray((Resource)first);\r
+            else if( first instanceof Collection<?>)\r
+                resourceArray = new ResourceArray(((Collection<?>)first).toArray(new Resource[((Collection<?>)first).size()]));\r
+            \r
+            if(resourceArray != null) {\r
+                StructuredSelection selection = new StructuredSelection(resourceArray);\r
+                availableEnumerationsExplorer.setInput(context, selection);\r
+                usedEnumerationsExplorer.setInput(context, selection);    \r
+                buttonSupport.fireInput(context, selection);\r
+            }\r
+        }\r
+        \r
+\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/CommentTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/CommentTab.java
new file mode 100644 (file)
index 0000000..0b6c00c
--- /dev/null
@@ -0,0 +1,66 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+\r
+/**\r
+ * Tab for editing diagram comments\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class CommentTab extends LabelPropertyTabContributor {\r
+\r
+       @Override\r
+       public String getPartName(ISelection forSelection) {\r
+               return "Comment";\r
+       }\r
+        \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        ScrolledComposite sc = new ScrolledComposite(body,  SWT.H_SCROLL | SWT.V_SCROLL);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+        \r
+        Composite composite = new Composite(sc, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+        \r
+        // FIXME: Currently needs Ctrl+Enter to accept changes. Change so that the syntax is common in all sysdyn\r
+        TrackedText text = new TrackedText(composite, support, SWT.BORDER | SWT.WRAP | SWT.MULTI);\r
+        text.setTextFactory(new StringPropertyFactory(DiagramResource.URIs.HasText));\r
+        text.addModifyListener(new StringPropertyModifier(context, DiagramResource.URIs.HasText));\r
+\r
+        GridDataFactory.fillDefaults().grab(true, true).hint(200, SWT.DEFAULT).applyTo(text.getWidget());\r
+\r
+        // Scrolled composite settings\r
+        sc.setContent(composite);\r
+        sc.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));\r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ConfigurationTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ConfigurationTab.java
new file mode 100644 (file)
index 0000000..33ad0ea
--- /dev/null
@@ -0,0 +1,381 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.dialogs.IInputValidator;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.issues.ontology.IssueResource;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.EquivalentUnitsWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.ComboStringPropertyModifier;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.ModelNameInputValidator;\r
+\r
+/**\r
+ * Tab displaying configuration properties. Displayed for model and configuration.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ConfigurationTab extends AdjustableTab {\r
+\r
+       private ScrolledComposite sc;\r
+       private Label nameLabel, startTimeLabel, stopTimeLabel, stepLengthLabel, \r
+               outputIntervalLabel, methodLabel, toleranceLabel, variableFilterLabel;\r
+       private TrackedText name, startTime, stopTime, stepLength, outputInterval, tolerance, variableFilter;\r
+       private TrackedCombo method, timeUnit;\r
+       private Button validateUnits;\r
+       private EquivalentUnitsWidget equivalentUnitsWidget;\r
+    /**\r
+     * Modifier for modifying model labels\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+       private class ModelLabelModifier extends TextModifyListenerImpl<Resource> {\r
+\r
+               public ModelLabelModifier(ISessionContext context, String propertyURI) {\r
+               }\r
+               \r
+       @Override\r
+       public void applyText(WriteGraph graph, Resource issue, String text) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+            graph.claimLiteral(issue, l0.HasLabel, text);\r
+            String safeName = NameUtils.findFreshName(graph, text, graph.getSingleObject(issue, l0.PartOf), l0.ConsistsOf, "%s%d");\r
+            graph.claimLiteral(issue, l0.HasName, safeName);\r
+       }\r
+               \r
+       }\r
+    \r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               sc = new ScrolledComposite(body,  SWT.H_SCROLL | SWT.V_SCROLL);\r
+               composite = new Composite(sc, SWT.NONE);\r
+        sc.setContent(composite);\r
+        \r
+        nameLabel = new Label(composite, SWT.NONE);\r
+        nameLabel.setText("Name");\r
+        \r
+        name = new TrackedText(composite, support, SWT.BORDER);\r
+        name.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));\r
+        name.addModifyListener(new ModelLabelModifier(context, Layer0.URIs.HasLabel));\r
+        name.setInputValidator(new ModelNameInputValidator(support));\r
+\r
+        startTimeLabel = new Label(composite, SWT.NONE);\r
+        startTimeLabel.setText("Start time");\r
+\r
+        startTime = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT);\r
+        startTime.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_startTime));\r
+        startTime.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_startTime));\r
+        startTime.setInputValidator(new DoubleValidator());\r
+\r
+        stopTimeLabel = new Label(composite, SWT.NONE);\r
+        stopTimeLabel.setText("Stop time");\r
+\r
+        stopTime = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT);\r
+        stopTime.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_stopTime));\r
+        stopTime.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_stopTime));\r
+        stopTime.setInputValidator(new DoubleValidator());\r
+\r
+        stepLengthLabel = new Label(composite, SWT.NONE);\r
+        stepLengthLabel.setText("Step length\n(empty = default)");\r
+\r
+        stepLength = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT);\r
+        stepLength.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_simulationStepLength));\r
+        stepLength.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_simulationStepLength));\r
+        stepLength.setInputValidator(new DoubleValidator());\r
+\r
+        outputIntervalLabel = new Label(composite, SWT.NONE);\r
+        outputIntervalLabel.setText("Output interval\n(empty = all steps)");\r
+        outputIntervalLabel.setAlignment(SWT.RIGHT);\r
+\r
+        outputInterval = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT);\r
+        outputInterval.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_outputInterval));\r
+        outputInterval.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_outputInterval));\r
+        outputInterval.setInputValidator(new DoubleValidator());\r
+\r
+        methodLabel = new Label(composite, SWT.NONE);\r
+        methodLabel.setText("Method");\r
+        \r
+        method = new TrackedCombo(composite, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
+        method.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+            @Override\r
+            public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+\r
+                Map<String, Object> map = new HashMap<String, Object>();\r
+                map.put("euler", "euler");\r
+                map.put("rungekutta", "rungekutta");\r
+                map.put("dassl", "dassl");\r
+                map.put("inline-euler", "inline-euler");\r
+                map.put("inline-rungekutta", "inline-rungekutta");\r
+                map.put("dasslwort", "dasslwort");\r
+                map.put("dasslSymJac", "dasslSymJac");\r
+                map.put("dasslNumJac", "dasslNumJac");\r
+                map.put("dasslColorSymJac", "dasslColorSymJac");\r
+                map.put("dasslInternalNumJac", "dasslInternalNumJac");\r
+                map.put("qss", "qss");\r
+                return map;\r
+            }\r
+        });\r
+        \r
+        method.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                String s = graph.getPossibleRelatedValue(input, SysdynResource.getInstance(graph).SysdynModel_solver);\r
+                return s != null ? s : "";\r
+            }\r
+        });\r
+        \r
+        method.addModifyListener(new ComboStringPropertyModifier<Resource>() {\r
+\r
+                       @Override\r
+                       public void applyText(WriteGraph graph, Resource input, String text)\r
+                                       throws DatabaseException {\r
+                               graph.claimLiteral(input, SysdynResource.getInstance(graph).SysdynModel_solver, text);\r
+                       }\r
+               });\r
+        \r
+        validateUnits = new Button(composite, support, SWT.CHECK);\r
+        validateUnits.setText("Validate units");\r
+        validateUnits.setSelectionFactory(new ReadFactoryImpl<Resource, Boolean>() {\r
+\r
+            @Override\r
+            public Boolean perform(ReadGraph graph, Resource model) throws DatabaseException {\r
+                Resource unitIssueSource = graph.syncRequest(\r
+                        new PossibleObjectWithType(model, \r
+                                Layer0X.getInstance(graph).Activates, \r
+                                SysdynResource.getInstance(graph).Validations_Units_UnitIssueSource));\r
+                if(unitIssueSource == null)\r
+                    return false;\r
+                \r
+                Boolean result = graph.getPossibleRelatedValue(unitIssueSource, IssueResource.getInstance(graph).IssueSource_active, Bindings.BOOLEAN);\r
+                return Boolean.TRUE.equals(result);\r
+            }\r
+        });\r
+        \r
+        validateUnits.addSelectionListener(new SelectionListenerImpl<Resource>(context){\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource model) throws DatabaseException {\r
+                Resource unitIssueSource = graph.syncRequest(\r
+                        new PossibleObjectWithType(model, \r
+                                Layer0X.getInstance(graph).Activates, \r
+                                SysdynResource.getInstance(graph).Validations_Units_UnitIssueSource));\r
+                IssueResource ISSUE = IssueResource.getInstance(graph);\r
+                Boolean result = graph.getPossibleRelatedValue(unitIssueSource, ISSUE.IssueSource_active, Bindings.BOOLEAN);\r
+                if(result == null)\r
+                    result = false;\r
+                graph.claimLiteral(unitIssueSource, ISSUE.IssueSource_active, Boolean.FALSE.equals(result));\r
+                \r
+                // Enable or disable the Unit Equivalents button based if\r
+                // unit validation is enabled or not.\r
+                final boolean enabled = !result;\r
+                if (!equivalentUnitsWidget.getWidget().isDisposed())\r
+                       equivalentUnitsWidget.getWidget().getDisplay().asyncExec(new Runnable() {\r
+                                               \r
+                                               @Override\r
+                                               public void run() {\r
+                                                       if(!equivalentUnitsWidget.getWidget().isDisposed())\r
+                                                               equivalentUnitsWidget.getWidget().setEnabled(enabled);\r
+                                               }\r
+                                       });\r
+\r
+            }\r
+            \r
+        });\r
+        \r
+        timeUnit = new TrackedCombo(composite, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
+        timeUnit.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+            @Override\r
+            public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+\r
+                Map<String, Object> map = new HashMap<String, Object>();\r
+                map.put("year", "year");\r
+                map.put("month", "month");\r
+                map.put("week", "week");\r
+                map.put("day", "day");\r
+                map.put("hour", "hour");\r
+                map.put("min", "min");\r
+                map.put("s", "s");\r
+                return map;\r
+            }\r
+        });\r
+        \r
+        timeUnit.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                String s = graph.getPossibleRelatedValue(input, SysdynResource.getInstance(graph).SysdynModel_timeUnit);\r
+                return s != null ? s : "month";\r
+            }\r
+        });\r
+        \r
+        timeUnit.addModifyListener(new ComboStringPropertyModifier<Resource>() {\r
+\r
+            @Override\r
+            public void applyText(WriteGraph graph, Resource input, String text)\r
+                    throws DatabaseException {\r
+                graph.claimLiteral(input, SysdynResource.getInstance(graph).SysdynModel_timeUnit, text);\r
+            }\r
+        });\r
+        \r
+        equivalentUnitsWidget = new EquivalentUnitsWidget(composite, support, SWT.NONE);\r
+        \r
+        toleranceLabel = new Label(composite, SWT.NONE);\r
+        toleranceLabel.setText("Tolerance");\r
+\r
+        tolerance = new TrackedText(composite, support, SWT.BORDER | SWT.RIGHT);\r
+        tolerance.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.SysdynModel_tolerance));\r
+        tolerance.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.SysdynModel_tolerance));\r
+        tolerance.setInputValidator(new DoubleValidator());\r
+        \r
+        variableFilterLabel = new Label(composite, SWT.NONE);\r
+        variableFilterLabel.setText("Variable filter");\r
+        variableFilterLabel.setToolTipText("Variable filter as regular expression.\n" +\r
+                       "To include variables Auxiliary1, Auxiliary2 and Auxiliary3: \n" +\r
+                       "Auxiliary[1-3]\n" +\r
+                       "or\n" +\r
+                       "Auxiliary1|Auxiliary2|Auxiliary3\n" +\r
+                       "NOTE: whitespace must be replaced with an underscore ('_') character" +\r
+                       "e.g. 'Growth Rate' -> 'Growth_Rate'");\r
+\r
+        variableFilter = new TrackedText(composite, support, SWT.BORDER);\r
+        variableFilter.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.SysdynModel_variableFilter, ""));\r
+        variableFilter.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.SysdynModel_variableFilter));\r
+        variableFilter.getWidget().setToolTipText("Variable filter as regular expression.\n" +\r
+                "To include variables Auxiliary1, Auxiliary2 and Auxiliary3: \n" +\r
+                "Auxiliary[1-3]\n" +\r
+                "or\n" +\r
+                "Auxiliary1|Auxiliary2|Auxiliary3\n" +\r
+                       "NOTE: whitespace must be replaced with an underscore ('_') character" +\r
+                       "e.g. 'Growth Rate' -> 'Growth_Rate'");\r
+        \r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(nameLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(name.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(startTimeLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(startTime.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(stopTimeLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(stopTime.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(stepLengthLabel);\r
+        stepLengthLabel.setAlignment(SWT.LEFT);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(stepLength.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(outputIntervalLabel);\r
+        outputIntervalLabel.setAlignment(SWT.LEFT);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(outputInterval.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(methodLabel);\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(validateUnits.getWidget());\r
+        GridDataFactory.fillDefaults().span(2, 1).align(SWT.BEGINNING, SWT.CENTER).applyTo(equivalentUnitsWidget.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(toleranceLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(tolerance.getWidget());\r
+        GridDataFactory.fillDefaults().span(2, 1).align(SWT.BEGINNING, SWT.CENTER).applyTo(variableFilterLabel);\r
+        GridDataFactory.fillDefaults().span(2, 1).grab(true, false).hint(100, SWT.DEFAULT).applyTo(variableFilter.getWidget());\r
+        \r
+        sc.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(wideScreen ? 13 : 6).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(nameLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).span(wideScreen ? 12 : 5, 1).hint(200, SWT.DEFAULT).applyTo(name.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(startTimeLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(startTime.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(stopTimeLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(stopTime.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(stepLengthLabel);\r
+        stepLengthLabel.setAlignment(SWT.RIGHT);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(stepLength.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(outputIntervalLabel);\r
+        outputIntervalLabel.setAlignment(SWT.RIGHT);\r
+        GridDataFactory.fillDefaults().grab(true, false).hint(50, SWT.DEFAULT).applyTo(outputInterval.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(methodLabel);\r
+        GridDataFactory.fillDefaults().span(wideScreen ? 1 : 3, 1).align(SWT.BEGINNING, SWT.CENTER).applyTo(method.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(validateUnits.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(timeUnit.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(equivalentUnitsWidget.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(toleranceLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).span(wideScreen ? 1 : 2, 1).hint(60, SWT.DEFAULT).applyTo(tolerance.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(variableFilterLabel);\r
+        GridDataFactory.fillDefaults().grab(true, false).span(wideScreen ? 10 : 5, 1).hint(200, SWT.DEFAULT).applyTo(variableFilter.getWidget());\r
+        \r
+        sc.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));\r
+       }  \r
+       \r
+    private class DoubleValidator implements IInputValidator {\r
+\r
+        @Override\r
+        public String isValid(String newText) {\r
+            for(int i = 0; i < newText.length(); i++){\r
+                if(!Character.isDigit(newText.charAt(i))){\r
+                    if(newText.charAt(i) != '.') {\r
+                        return "Invalid character '" + newText.charAt(i) + "'";\r
+                    } else if(newText.indexOf('.') != newText.lastIndexOf('.')) {\r
+                        return "There can be only one '.'";\r
+                    }\r
+                }\r
+            }\r
+            return null;\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/DependencyTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/DependencyTab.java
new file mode 100644 (file)
index 0000000..1acc021
--- /dev/null
@@ -0,0 +1,314 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.Scale;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.util.ObjectUtils;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.connections.DependencyEdgeClass;\r
+import org.simantics.sysdyn.ui.elements.connections.DependencyNode;\r
+import org.simantics.sysdyn.ui.properties.widgets.ArrowHeadWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.DelayMarkWidget;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.datastructures.Triple;\r
+\r
+/**\r
+ * Tab displaying dependency properties.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class DependencyTab  extends AdjustableTab {\r
+\r
+    Button none, plus, minus, other, inside, outside;\r
+    TrackedText polarityText, polarityLocationText;\r
+    Scale lineThicknessScale;\r
+    private DelayMarkWidget delayMark;\r
+    private ArrowHeadWidget arrowhead;\r
+       private Group polarityGroup;\r
+       private Group locationGroup;\r
+       private Composite misc;\r
+       private Group lineThicknessGroup;\r
+    \r
+    class LineThicknessSelectionListener extends SelectionListenerImpl<Resource> {\r
+       Scale scale;\r
+               private int selection;\r
+\r
+        public LineThicknessSelectionListener(ISessionContext context, Scale scale) {\r
+               super(context);\r
+               this.scale = scale;\r
+        }\r
+        \r
+        @Override\r
+        public void beforeApply() {\r
+            this.selection = scale.getWidget().getSelection();\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, Resource connectionElement) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            float width = ((float)selection) / 10.0f;\r
+            graph.claimLiteral(connectionElement, sr.DependencyConnection_strokeWidth, width);\r
+        }\r
+        \r
+    }\r
+    \r
+    class LineThicknessRadioSelectionFactory extends ReadFactoryImpl<Resource, Integer> {\r
+\r
+        public LineThicknessRadioSelectionFactory() {\r
+        }\r
+\r
+        @Override\r
+        public Integer perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            Float width = graph.getPossibleRelatedValue(dependencyConnection, sr.DependencyConnection_strokeWidth, Bindings.FLOAT);  \r
+            if(width == null)\r
+                return (int)Math.round(DependencyEdgeClass.DEFAULT_STROKE_WIDTH * 10);\r
+            else\r
+                return (int)Math.round(width * 10);\r
+        }\r
+    }\r
+    \r
+    class PolarityLocationSelectionListener extends SelectionListenerImpl<Resource> {\r
+        private String location;\r
+\r
+        public PolarityLocationSelectionListener(ISessionContext context, String location) {\r
+            super(context);\r
+            this.location = location;\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, Resource connectionElement) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            graph.claimLiteral(connectionElement, sr.DependencyConnection_polarityLocation, location);\r
+        }\r
+        \r
+    }\r
+    \r
+    class PolarityLocationRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        private String location;\r
+\r
+        public PolarityLocationRadioSelectionFactory(String location) {\r
+            this.location = location;\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, location, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            String location = graph.getPossibleRelatedValue(dependencyConnection, sr.DependencyConnection_polarityLocation, Bindings.STRING);  \r
+            if(DependencyNode.OUTSIDE.equals(this.location)) {\r
+                return ObjectUtils.objectEquals(this.location, location);\r
+            } else {\r
+                if(location == null)\r
+                    return true;\r
+                else\r
+                    return ObjectUtils.objectEquals(this.location, location);\r
+            }\r
+        }\r
+    }\r
+    \r
+    class PolaritySelectionListener extends SelectionListenerImpl<Resource> {\r
+        private String polarity;\r
+\r
+        public PolaritySelectionListener(ISessionContext context, String polarity) {\r
+            super(context);\r
+            this.polarity = polarity;\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, Resource connectionElement) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            graph.claimLiteral(connectionElement, sr.DependencyConnection_polarity, polarity.trim());\r
+        }\r
+        \r
+    }\r
+    \r
+    class PolarityRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        private String polarity;\r
+\r
+        public PolarityRadioSelectionFactory(String polarity) {\r
+            this.polarity = polarity;\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, polarity, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            String polarity = graph.getPossibleRelatedValue(dependencyConnection, sr.DependencyConnection_polarity, Bindings.STRING);     \r
+            if(polarity == null && this.polarity.equals(""))\r
+                return true;\r
+            return ObjectUtils.objectEquals(polarity, this.polarity);\r
+        }\r
+    }\r
+    \r
+    class OtherPolaritySelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+\r
+        String[] limits;\r
+        \r
+        public OtherPolaritySelectionFactory(String[] limits) {\r
+            this.limits = limits;\r
+        }\r
+        \r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Pair<Object, Class<?>>(inputContents, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            String polarity = graph.getPossibleRelatedValue(dependencyConnection, sr.DependencyConnection_polarity, Bindings.STRING);\r
+            for(String s : limits) {\r
+                if(ObjectUtils.objectEquals(polarity, s))\r
+                    return false;\r
+            }\r
+            return true;\r
+        }\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               composite = new Composite(body, SWT.NONE);\r
+        \r
+        polarityGroup = new Group(composite, SWT.NONE);\r
+        polarityGroup.setText("Polarity");\r
+        \r
+        none = new Button(polarityGroup, support, SWT.RADIO);\r
+        none.setText("None");\r
+        none.setSelectionFactory(new PolarityRadioSelectionFactory(""));\r
+        none.addSelectionListener(new PolaritySelectionListener(context, ""));\r
+        \r
+        plus = new Button(polarityGroup, support, SWT.RADIO);\r
+        plus.setText("+");\r
+        plus.setSelectionFactory(new PolarityRadioSelectionFactory("+"));\r
+        plus.addSelectionListener(new PolaritySelectionListener(context, "+"));\r
+        \r
+        minus = new Button(polarityGroup, support, SWT.RADIO);\r
+        minus.setText("-");\r
+        minus.setSelectionFactory(new PolarityRadioSelectionFactory("-"));\r
+        minus.addSelectionListener(new PolaritySelectionListener(context, "-"));\r
+        \r
+        other = new Button(polarityGroup, support, SWT.RADIO);\r
+        other.setText("other");\r
+        other.setSelectionFactory(new OtherPolaritySelectionFactory(new String[] {null, "+", "-", ""}));\r
+        \r
+        polarityText = new TrackedText(polarityGroup, support, SWT.BORDER);\r
+        polarityText.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.DependencyConnection_polarity));\r
+        polarityText.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.DependencyConnection_polarity));\r
+        \r
+        locationGroup = new Group(composite, SWT.NONE);\r
+        locationGroup.setText("Location");\r
+        \r
+        inside = new Button(locationGroup, support, SWT.RADIO);\r
+        inside.setText("Inside");\r
+        inside.setSelectionFactory(new PolarityLocationRadioSelectionFactory(DependencyNode.INSIDE));\r
+        inside.addSelectionListener(new PolarityLocationSelectionListener(context, DependencyNode.INSIDE));\r
+        \r
+        outside = new Button(locationGroup, support, SWT.RADIO);\r
+        outside.setText("Outside");\r
+        outside.setSelectionFactory(new PolarityLocationRadioSelectionFactory(DependencyNode.OUTSIDE));\r
+        outside.addSelectionListener(new PolarityLocationSelectionListener(context, DependencyNode.OUTSIDE));\r
+        \r
+        misc = new Composite(composite, SWT.NONE);\r
+        \r
+        arrowhead = new ArrowHeadWidget(misc, support, SWT.NULL);\r
+        delayMark = new DelayMarkWidget(misc, support, SWT.NULL);\r
+        \r
+        lineThicknessGroup = new Group(misc, SWT.NONE);\r
+        lineThicknessGroup.setText("Line thickness:");\r
+        lineThicknessScale = new Scale(lineThicknessGroup, support, SWT.HORIZONTAL);\r
+        lineThicknessScale.getWidget().setMinimum(1);\r
+        lineThicknessScale.getWidget().setMaximum(15);\r
+        lineThicknessScale.getWidget().setPageIncrement(1);\r
+        lineThicknessScale.getWidget().setIncrement(1);\r
+        lineThicknessScale.setSelectionFactory(new LineThicknessRadioSelectionFactory());\r
+        lineThicknessScale.addSelectionListener(new LineThicknessSelectionListener(context, lineThicknessScale));\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(composite);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityGroup);\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(polarityGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityText.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(locationGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(locationGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(misc);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(misc);\r
+\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).applyTo(arrowhead.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).applyTo(delayMark.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().span(2, 1).applyTo(lineThicknessGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(lineThicknessGroup);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityGroup);\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(polarityGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityText.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(locationGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(locationGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(misc);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(misc);\r
+\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).applyTo(arrowhead.getWidget());\r
+        GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).applyTo(delayMark.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().span(1, 1).applyTo(lineThicknessGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(lineThicknessGroup);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EnumerationTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EnumerationTab.java
new file mode 100644 (file)
index 0000000..833a626
--- /dev/null
@@ -0,0 +1,384 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.eclipse.swt.widgets.Listener;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.swt.widgets.TreeItem;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.Table;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationIndexNode;\r
+import org.simantics.sysdyn.ui.properties.widgets.arrays.ReplaceableIndexesWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNamePropertyModifier;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNameInputValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class EnumerationTab extends LabelPropertyTabContributor implements Widget {\r
+\r
+       GraphExplorerComposite indexExplorer;\r
+       \r
+       Button showAll;\r
+       Variable variable;\r
+       \r
+       Table table;\r
+       @Override\r
+       public void createControls(Composite body, IWorkbenchSite site,\r
+                       final ISessionContext context, WidgetSupport support) {\r
+\r
+               support.register(this);\r
+               \r
+               Composite container = new Composite(body, SWT.None);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(container);\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(4).applyTo(container);\r
+\r
+        TrackedText nameText = new TrackedText(container, support, SWT.BORDER);\r
+        nameText.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName));\r
+        nameText.addModifyListener(new VariableNamePropertyModifier(context, Layer0.URIs.HasName));\r
+        nameText.setInputValidator(new VariableNameInputValidator(support));\r
+        GridDataFactory.fillDefaults().grab(true, false).span(4,1).applyTo(nameText.getWidget());\r
+        \r
+        indexExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                               "displaySelectors", "displayFilter").values(false, false), site, container, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI | SWT.CHECK);\r
+               \r
+        indexExplorer\r
+               .setBrowseContexts(SysdynResource.URIs.EnumerationIndexes);\r
+        indexExplorer.setInputSource(new SingleSelectionInputSource(\r
+                               Resource.class));\r
+        ((Tree)indexExplorer.getExplorerControl()).addListener(SWT.Selection, new Listener () {\r
+        \r
+            @Override\r
+            public void handleEvent (Event event) {\r
+                if(event.detail == SWT.CHECK) {\r
+                    final TreeItem item = (TreeItem)event.item;\r
+                    final boolean checked = item.getChecked();\r
+                    NodeContext context = (NodeContext)item.getData();\r
+                    final EnumerationIndexNode node = (EnumerationIndexNode) context.getAdapter(EnumerationIndexNode.class);\r
+                    node.setShowInChartsSelected(checked);\r
+                    \r
+                    SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                                               @Override\r
+                                               public void run(ReadGraph graph) throws DatabaseException {\r
+                                                       updateModelResults(graph);\r
+                                               }\r
+                                       });\r
+                }\r
+            }\r
+        });\r
+        \r
+\r
+        indexExplorer.finish();\r
+\r
+               GridDataFactory.fillDefaults().grab(true, true).span(4, 1).applyTo(\r
+                               indexExplorer);\r
+               \r
+               Control c = indexExplorer.getExplorerControl();\r
+               if (c instanceof Tree)\r
+                       ((Tree) c).setLinesVisible(true);\r
+\r
+\r
+               final Button add = new Button(container, support, SWT.None);\r
+               add.setText("Add");\r
+               add.addSelectionListener(new addEnumerationIndexListener(support));\r
+\r
+               final Button remove = new Button(container, support, SWT.None);\r
+               remove.setText("Remove");\r
+               remove.addSelectionListener(new removeEnumerationIndexListener(support));\r
+               \r
+               ReplaceableIndexesWidget externalIndexes = new ReplaceableIndexesWidget(container, support, SWT.NULL);\r
+               GridDataFactory.fillDefaults().applyTo(externalIndexes.getWidget());\r
+               \r
+               showAll = new Button(container, support, SWT.CHECK);\r
+               showAll.setText("Show all in charts");\r
+               showAll.addSelectionListener(new ShowAllIndexesListener(support));\r
+               \r
+       }\r
+\r
+       private class addEnumerationIndexListener implements SelectionListener, Widget {\r
+\r
+               Resource enumerationIndexes;\r
+\r
+               public addEnumerationIndexListener(WidgetSupport support) {\r
+                       support.register(this);\r
+               }\r
+\r
+               @Override\r
+               public void setInput(ISessionContext context, Object input) {\r
+                       final Resource enumeration = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+                       try {\r
+                               context.getSession().syncRequest(new ReadRequest() {\r
+\r
+                                       @Override\r
+                                       public void run(ReadGraph graph) throws DatabaseException {\r
+                                               enumerationIndexes = graph.getSingleObject(enumeration, SysdynResource.getInstance(graph).Enumeration_enumerationIndexList);\r
+                                       }\r
+                               });\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+               }\r
+\r
+               @Override\r
+               public void widgetSelected(SelectionEvent e) {\r
+                       try {\r
+                               SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               \r
+                                               HashSet<String> names = new HashSet<String>();\r
+                        for(Resource r : ListUtils.toList(graph, enumerationIndexes)) {\r
+                                                       names.add(NameUtils.getSafeName(graph, r));\r
+                                               }\r
+                                               \r
+                                               Resource ei = GraphUtils.create2(graph, \r
+                                                               sr.EnumerationIndex,\r
+                                                               l0.HasName, NameUtils.findFreshName(graph, "index", names, ""));\r
+                                               ArrayList<Resource> index = new ArrayList<Resource>();\r
+                                               index.add(ei);\r
+                                               ListUtils.insertBack(graph, enumerationIndexes, index);\r
+                                       }\r
+                               });\r
+                       } catch (DatabaseException e1) {\r
+                               e1.printStackTrace();\r
+                       }\r
+\r
+               }\r
+\r
+               @Override\r
+               public void widgetDefaultSelected(SelectionEvent e) {\r
+\r
+               }\r
+\r
+       }\r
+\r
+       private class removeEnumerationIndexListener implements SelectionListener, Widget {\r
+\r
+               Resource enumerationIndexes;\r
+\r
+               public removeEnumerationIndexListener(WidgetSupport support) {\r
+                       support.register(this);\r
+               }\r
+\r
+               @Override\r
+               public void setInput(ISessionContext context, Object input) {\r
+                       final Resource enumeration = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+                       try {\r
+                               context.getSession().syncRequest(new ReadRequest() {\r
+\r
+                                       @Override\r
+                                       public void run(ReadGraph graph) throws DatabaseException {\r
+                                               enumerationIndexes = graph.getSingleObject(enumeration, SysdynResource.getInstance(graph).Enumeration_enumerationIndexList);\r
+                                       }\r
+                               });\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+               }\r
+\r
+               @Override\r
+               public void widgetSelected(SelectionEvent e) {\r
+                       ISelectionProvider selectionProvider = (ISelectionProvider)indexExplorer.getAdapter(ISelectionProvider.class);\r
+                       final IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
+\r
+                       try {\r
+                               SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               for(Object o : selection.toList()) {\r
+                                                       Resource r = AdaptionUtils.adaptToSingle(o, Resource.class);\r
+                                                       if(r == null)\r
+                                                               continue;\r
+                                                       ListUtils.removeElement(graph, enumerationIndexes, r);\r
+                                               }\r
+                                       }\r
+                               });\r
+                       } catch (DatabaseException e1) {\r
+                               e1.printStackTrace();\r
+                       }\r
+                       \r
+\r
+               }\r
+\r
+               @Override\r
+               public void widgetDefaultSelected(SelectionEvent e) {\r
+\r
+               }\r
+\r
+       }\r
+       \r
+       private class ShowAllIndexesListener implements SelectionListener, Widget {\r
+\r
+                       Resource enumerationIndexes;\r
+\r
+                       public ShowAllIndexesListener(WidgetSupport support) {\r
+                               support.register(this);\r
+                       }\r
+\r
+                       @Override\r
+                       public void setInput(ISessionContext context, Object input) {\r
+                               final Resource enumeration = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+                               \r
+                               context.getSession().asyncRequest(new Read<Boolean>() {\r
+\r
+                                       @Override\r
+                                       public Boolean perform(ReadGraph graph)\r
+                                                       throws DatabaseException {\r
+                                           if(!graph.hasStatement(enumeration))\r
+                                               return null;\r
+                                           \r
+                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                               enumerationIndexes = graph.getSingleObject(enumeration, sr.Enumeration_enumerationIndexList);\r
+                                               List<Resource> indexes = ListUtils.toList(graph, enumerationIndexes);\r
+                                               for(Resource index : indexes) {\r
+                                                       Boolean show = graph.getPossibleRelatedValue(index, sr.EnumerationIndex_showEnumerationIndexInCharts, Bindings.BOOLEAN);\r
+                                                       if(!Boolean.TRUE.equals(show))\r
+                                                               return false;\r
+                                               }\r
+                                               return true;\r
+                                       }\r
+                                       \r
+                               }, new org.simantics.db.procedure.Listener<Boolean>() {\r
+\r
+                                       @Override\r
+                                       public void execute(final Boolean result) {\r
+                                               showAll.getWidget().getDisplay().asyncExec(new Runnable() {\r
+\r
+                                                       @Override\r
+                                                       public void run() {\r
+                                                           if(result != null && !showAll.getWidget().isDisposed())\r
+                                                               showAll.getWidget().setSelection(result.booleanValue());\r
+                                                       }\r
+                                               });\r
+                                       }\r
+                                                       \r
+\r
+                                       @Override\r
+                                       public void exception(Throwable t) {\r
+                                               t.printStackTrace();\r
+                                       }\r
+\r
+                                       @Override\r
+                                       public boolean isDisposed() {\r
+                                               if(showAll == null)\r
+                                                       return true;\r
+                                               return showAll.getWidget().isDisposed();\r
+                                       }\r
+                               });\r
+                               \r
+                       }\r
+\r
+                       @Override\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               final boolean selected = showAll.getWidget().getSelection();\r
+                               try {\r
+                                       SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                                               @Override\r
+                                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                                       List<Resource> indexes = ListUtils.toList(graph, enumerationIndexes);\r
+                                                       for(Resource index : indexes) {\r
+                                                               Boolean show = graph.getPossibleRelatedValue(index, sr.EnumerationIndex_showEnumerationIndexInCharts, Bindings.BOOLEAN);\r
+                                                               if(selected && !Boolean.TRUE.equals(show)) {\r
+                                                                       graph.claimLiteral(index, sr.EnumerationIndex_showEnumerationIndexInCharts, true, Bindings.BOOLEAN);\r
+                                                               } else if(!selected && !Boolean.FALSE.equals(show)) {\r
+                                                                       graph.claimLiteral(index, sr.EnumerationIndex_showEnumerationIndexInCharts, false, Bindings.BOOLEAN);\r
+                                                               }\r
+                                                       }\r
+                                                       \r
+                                                       updateModelResults(graph);\r
+                                               }\r
+                                       });\r
+                               } catch (DatabaseException e1) {\r
+                                       e1.printStackTrace();\r
+                               }\r
+                               \r
+\r
+                       }\r
+\r
+                       @Override\r
+                       public void widgetDefaultSelected(SelectionEvent e) {\r
+\r
+                       }\r
+\r
+               }\r
+       \r
+       private void updateModelResults(ReadGraph graph) {\r
+               try {\r
+                       if(variable != null ) {\r
+                               Resource modelResource = Variables.getModel(graph, variable);\r
+                               if(modelResource != null) {\r
+                                       Resource configuration = graph.getSingleObject(\r
+                                                       modelResource, \r
+                                                       SimulationResource.getInstance(graph).HasConfiguration);\r
+                                       SysdynModel model = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configuration);\r
+                                       // update results in graphs\r
+                                       model.resultChanged();\r
+                               }\r
+                       }\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               variable = AdaptionUtils.adaptToSingle(input, Variable.class);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java
new file mode 100644 (file)
index 0000000..633cdfa
--- /dev/null
@@ -0,0 +1,764 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.StyledText;\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.MouseEvent;\r
+import org.eclipse.swt.events.MouseListener;\r
+import org.eclipse.swt.events.VerifyEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableItem;\r
+import org.eclipse.ui.IWorkbenchPartReference;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.platform.PropertyPageView;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.VirtualGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.request.WriteResultRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.AsyncListener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.ui.properties.widgets.ArrayExpressionCombo;\r
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes;\r
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes.ExpressionType;\r
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.IsOutputWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.ShortcutTabWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.arrays.NameAndArrayRangeModifyListener;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.DelayExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionComposite;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionWidgetInput;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNameInputValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Tab for displaying equation information of a variable\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class EquationTab extends AdjustableTab implements Widget {\r
+\r
+       private TrackedCombo expressionTypeCombo, unitCombo, arrayEquationCombo;\r
+       private ShortcutTabWidget shortcutTabWidget;\r
+       private ExpressionWidget expressionWidget;\r
+       private org.eclipse.ui.IPartListener2 focusLostListener;  \r
+       private IWorkbenchSite site;\r
+       private Button deleteExpression, newExpression;\r
+       private WidgetSupportImpl support;\r
+       private ExpressionComposite expressionComposite;\r
+       private final WidgetSupportImpl expressionSupport = new WidgetSupportImpl();\r
+       private Composite nameComposite;\r
+       private Composite TypeAndUnit;\r
+       private Label typeLabel;\r
+       private Label unitLabel;\r
+       private IsOutputWidget isOutput;\r
+\r
+       @Override\r
+       public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport _support) {\r
+               _support.register(this);\r
+               setSupport();\r
+               this.site = site;\r
+               super.createControls(body, site, context, _support);\r
+       }\r
+       \r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
+\r
+               GridLayoutFactory.fillDefaults().numColumns(wideScreen ? 4 : 3).applyTo(nameComposite);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(nameComposite);\r
+\r
+               GridDataFactory.fillDefaults().grab(true, false).hint(280, SWT.DEFAULT).applyTo(arrayEquationCombo.getWidget());\r
+               GridDataFactory.fillDefaults().applyTo(deleteExpression.getWidget());\r
+               GridDataFactory.fillDefaults().applyTo(newExpression.getWidget());\r
+\r
+               GridDataFactory.fillDefaults().span(1, wideScreen ? 2 : 3).grab(false, true).hint(250, SWT.DEFAULT).applyTo(shortcutTabWidget.getWidget());\r
+\r
+               GridDataFactory.fillDefaults().span(wideScreen ? 1 : 3, 1).grab(true, false).applyTo(TypeAndUnit);\r
+               GridLayoutFactory.fillDefaults().numColumns(5).applyTo(TypeAndUnit);\r
+               GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(typeLabel);\r
+               GridDataFactory.fillDefaults().applyTo(expressionTypeCombo.getWidget());\r
+               GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(unitLabel);\r
+               GridDataFactory.fillDefaults().grab(true, false).hint(160, SWT.DEFAULT).applyTo(unitCombo.getWidget());\r
+               GridDataFactory.fillDefaults().applyTo(isOutput.getWidget());\r
+\r
+               GridDataFactory.fillDefaults().span(wideScreen ? 4 : 3, 1).grab(true, true).applyTo(expressionComposite);\r
+       }\r
+               \r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+               \r
+               GridLayoutFactory.fillDefaults().numColumns(3).applyTo(nameComposite);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(nameComposite);\r
+\r
+               GridDataFactory.fillDefaults().grab(true, false).applyTo(arrayEquationCombo.getWidget());\r
+               GridDataFactory.fillDefaults().applyTo(deleteExpression.getWidget());\r
+               GridDataFactory.fillDefaults().applyTo(newExpression.getWidget());\r
+\r
+               GridDataFactory.fillDefaults().span(3, 1).applyTo(TypeAndUnit);\r
+               GridLayoutFactory.fillDefaults().numColumns(2).applyTo(TypeAndUnit);\r
+               GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(typeLabel);\r
+               GridDataFactory.fillDefaults().applyTo(expressionTypeCombo.getWidget());\r
+               GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(unitLabel);\r
+               GridDataFactory.fillDefaults().grab(true, false).hint(160, SWT.DEFAULT).applyTo(unitCombo.getWidget());\r
+               GridDataFactory.fillDefaults().span(3, 1).align(SWT.END, SWT.CENTER).applyTo(isOutput.getWidget());\r
+\r
+               GridDataFactory.fillDefaults().span(3, 1).grab(true, true).hint(SWT.DEFAULT, 250).applyTo(expressionComposite);\r
+               \r
+               GridDataFactory.fillDefaults().span(3, 1).grab(true, true).hint(SWT.DEFAULT, 300).applyTo(shortcutTabWidget.getWidget());\r
+       }\r
+       \r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport _support) {\r
+               // Composite for the whole tab\r
+               Composite composite = new Composite(body, SWT.NONE);\r
+               this.composite = composite;\r
+               \r
+               // Composite holding name controls and controls for adding and removing expressions\r
+               nameComposite = new Composite(composite, SWT.NONE);\r
+               arrayEquationCombo =  new ArrayExpressionCombo(nameComposite, support, SWT.DROP_DOWN | SWT.BORDER);\r
+               arrayEquationCombo.setInputValidator(new VariableNameInputValidator(support));\r
+               arrayEquationCombo.addModifyListener(new NameAndArrayRangeModifyListener(support, expressionWidget, (ArrayExpressionCombo)arrayEquationCombo));\r
+               deleteExpression = new Button(nameComposite, support, SWT.NONE);\r
+               deleteExpression.setText("Delete");\r
+               newExpression = new Button(nameComposite, support, SWT.NONE);\r
+               newExpression.setText("New");\r
+                               \r
+               // Shortcut widget. Tabular widget containing tabs for functions and connected variables\r
+               shortcutTabWidget = new ShortcutTabWidget(composite, support, SWT.NONE);\r
+               \r
+               TypeAndUnit = new Composite(nameComposite, SWT.NONE);\r
+               typeLabel = new Label(TypeAndUnit, SWT.SINGLE );\r
+               typeLabel.setText("Type:");\r
+               expressionTypeCombo = new TrackedCombo(TypeAndUnit, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
+               unitLabel = new Label(TypeAndUnit, SWT.SINGLE );\r
+               unitLabel.setText("Unit:");\r
+               unitCombo = new TrackedCombo(TypeAndUnit, support, SWT.DROP_DOWN | SWT.BORDER);\r
+               isOutput = new IsOutputWidget(TypeAndUnit, support, SWT.NULL);\r
+               \r
+               // The actual expression\r
+               expressionComposite = new ExpressionComposite(nameComposite, SWT.NONE);\r
+               expressionWidget = new ExpressionWidget(expressionComposite, expressionSupport, SWT.NONE);\r
+               expressionWidget.setVariableTable(shortcutTabWidget.getVariableTable());\r
+\r
+               addListeners(context);\r
+       }\r
+       \r
+       private void setSupport() {\r
+               support = new WidgetSupportImpl() {\r
+                       \r
+               @Override\r
+               public void fireInput(ISessionContext context, Object input) {\r
+                       final Variable var = AdaptionUtils.adaptToSingle(input, Variable.class);\r
+                       if(var != null) {\r
+                               Resource r;\r
+                                       try {\r
+                                               r = context.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                                                       @Override\r
+                                                       public Resource perform(ReadGraph graph)\r
+                                                                       throws DatabaseException {\r
+                                                               return var.getRepresents(graph);\r
+                                                       }\r
+                                               });\r
+                                       input = new StructuredSelection(r);\r
+                                       } catch (DatabaseException e) {\r
+                                               e.printStackTrace();\r
+                                       }\r
+                               \r
+                       }\r
+                       \r
+                       super.fireInput(context, input);\r
+               }\r
+       };\r
+       }\r
+       \r
+       @Override\r
+       public void setInput(ISessionContext context, final Object input) {\r
+               support.fireInput(context, input);\r
+               \r
+               final Variable var = AdaptionUtils.adaptToSingle(input, Variable.class);\r
+               final Resource variable;\r
+               \r
+               // Find variable resource either from Variable var or from input\r
+               if(var != null)\r
+                       try {\r
+                               variable = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                                       @Override\r
+                                       public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                                               return var.getRepresents(graph);\r
+                                       }\r
+                               });\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                               return;\r
+                       }\r
+               else\r
+                       variable = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+               \r
+               if(var == null && variable == null)\r
+                       return;\r
+               \r
+               \r
+               Resource expression = null;\r
+               try {\r
+                       expression = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                                       return getActiveExpression(graph, variable);\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+               // The variable has no expressions -> creating a new ordered set expressions and the active expression\r
+               if(expression == null && variable != null) {\r
+                       try {\r
+                               expression = SimanticsUI.getSession().syncRequest(new WriteResultRequest<Resource>() {\r
+\r
+                                       @Override\r
+                                       public Resource perform(WriteGraph graph)\r
+                                       throws DatabaseException {\r
+                                           if(!graph.hasStatement(variable)) {\r
+                                            /* Trying to create empty experiment for removed variable due to \r
+                                             * async setInput\r
+                                             */\r
+                                               return null; \r
+                                           }\r
+                                           \r
+                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               Resource expressions = ListUtils.create(graph, Collections.<Resource>emptyList());\r
+                                               graph.claim(variable, sr.Variable_expressionList, expressions);\r
+                                               final Resource expression = graph.newResource();\r
+\r
+                                               if(graph.isInstanceOf(variable, sr.Auxiliary) ||\r
+                                                               graph.isInstanceOf(variable, sr.Valve)) {\r
+                                                       graph.claim(expression, l0.InstanceOf, null, sr.NormalExpression);\r
+                                                       graph.claimLiteral(expression, sr.Expression_equation, "");\r
+                                               }\r
+                                               else if(graph.isInstanceOf(variable, sr.Stock)) {\r
+                                                       graph.claim(expression, l0.InstanceOf, null, sr.StockExpression);\r
+                                                       graph.claimLiteral(expression, sr.StockExpression_initialEquation, "");\r
+                                               }\r
+                                               ArrayList<Resource> addition = new ArrayList<Resource>(1);\r
+                                               addition.add(expression);\r
+                                               ListUtils.insertBack(graph, expressions, addition);\r
+\r
+                                               graph.claim(variable, l0.ConsistsOf, expression);\r
+\r
+                                               VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
+                                               final Session session = graph.getSession();\r
+                                               session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
+                                                       @Override\r
+                                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                               VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
+                                                               session.asyncRequest(new WriteRequest(runtime) {\r
+                                                                       @Override\r
+                                                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                                                               if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
+                                                                                       graph.deny(variable, sr.IndependentVariable_activeExpression);\r
+                                                                               graph.claim(variable, sr.IndependentVariable_activeExpression, expression);\r
+                                                                       }\r
+                                                               }\r
+                                                               );\r
+                                                       }\r
+                                               });\r
+                                               return expression;\r
+                                       }\r
+                               });\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+                       \r
+                       if(expression == null)\r
+                           return;\r
+               }\r
+\r
+               // Now the variable should have an expression\r
+               SimanticsUI.getSession().asyncRequest(new Read<Pair<Boolean, Boolean>>() {\r
+\r
+                   /**\r
+                    * Find out if user can add a new expression or delete the current expression\r
+                    */\r
+                       @Override\r
+                       public Pair<Boolean, Boolean> perform(ReadGraph graph) throws DatabaseException {\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);\r
+                               if(expressions == null) {\r
+                                       return new Pair<Boolean, Boolean>(false, false);\r
+                               }\r
+                               List<Resource> expressionList = ListUtils.toList(graph, expressions);\r
+                               if(expressionList.isEmpty()) {\r
+                                       return new Pair<Boolean, Boolean>(false, false);\r
+                               }\r
+\r
+                               boolean canAdd = true;\r
+                               boolean canDelete = false;\r
+                               // If there are multiple expressions, one can be removed\r
+                               if(expressionList.size() > 1)\r
+                                       canDelete = true;\r
+                               String defaultRange = ArrayExpressionCombo.getDefaultRange(graph, variable);\r
+\r
+                               /* If the variable is an array variable, a range has been set to all expressions and none of\r
+                                * the ranges is the default range, an expression can be added\r
+                                */ \r
+                               for(Resource expression : expressionList) {\r
+                                       String range = graph.getPossibleRelatedValue(expression, sr.Expression_arrayRange);\r
+                                       if(range == null || range.equals("") || range.equals(defaultRange)) {\r
+                                               canAdd = false;\r
+                                               break;\r
+                                       }\r
+                               }\r
+                               return new Pair<Boolean, Boolean>(canAdd, canDelete);\r
+                       }\r
+               }, new AsyncListener<Pair<Boolean, Boolean>>() {\r
+\r
+                       @Override\r
+                       public void execute(AsyncReadGraph graph,\r
+                                       final Pair<Boolean, Boolean> result) {\r
+                               newExpression.getWidget().getDisplay().asyncExec(new Runnable() {\r
+                                       \r
+                                       @Override\r
+                                       public void run() {\r
+                                               if(!newExpression.getWidget().isDisposed())\r
+                                                       newExpression.getWidget().setEnabled(result.first);\r
+                                               if(!deleteExpression.getWidget().isDisposed())\r
+                                                       deleteExpression.getWidget().setEnabled(result.second);                                         \r
+                                       }\r
+                               });\r
+\r
+                       }\r
+\r
+                       @Override\r
+                       public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                               throwable.printStackTrace();\r
+                       }\r
+\r
+                       @Override\r
+                       public boolean isDisposed() {\r
+                               return newExpression.getWidget().isDisposed() || deleteExpression.getWidget().isDisposed();\r
+                       }\r
+               });\r
+               \r
+        // Set input to widgets using expressionSupport\r
+               StructuredSelection ss = new StructuredSelection(new ExpressionWidgetInput(var, expression));\r
+               expressionSupport.fireInput(context, ss);\r
+       }\r
+\r
+       /**\r
+        * Adds listeners to widgets in this tab\r
+        * \r
+        * @param context ISessionContext\r
+        */\r
+       private void addListeners(ISessionContext context) {\r
+\r
+           // Validate expression fields when a dependency has been added or removed\r
+               shortcutTabWidget.addDependencyListener(new Runnable() {\r
+                       \r
+                       @Override\r
+                       public void run() {\r
+                               expressionWidget.validateFields();\r
+                       }\r
+               });\r
+               \r
+               // Deletes a selected expression\r
+               deleteExpression.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+                       @Override\r
+                       public void apply(WriteGraph graph, final Resource input)\r
+                       throws DatabaseException {\r
+\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               \r
+                               // Currently active expression should be located in (Model sr.HasActiveExpression expression)\r
+                               Resource activeExpression = graph.getPossibleObject(input, sr.IndependentVariable_activeExpression);\r
+                               if(activeExpression == null)\r
+                                       return;\r
+\r
+                Resource expressionList = graph.getPossibleObject(input, sr.Variable_expressionList);\r
+\r
+                List<Resource> list = ListUtils.toList(graph, expressionList);\r
+                if(list.size() <= 1)\r
+                                       return;\r
+\r
+                               // Get the previous expression in expression list to be activated\r
+                int index = list.indexOf(activeExpression);\r
+                \r
+                ListUtils.removeElement(graph, expressionList, activeExpression);\r
+                               graph.deny(input, l0.ConsistsOf, activeExpression);\r
+                               \r
+                               final Resource newActive = index == 0 ? list.get(1) : list.get(index - 1);\r
+\r
+                               // Set newActive as active in virtual graph\r
+                               VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
+                               final Session session = graph.getSession();\r
+                               session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
+                                               session.asyncRequest(new WriteRequest(runtime) {\r
+                                                       @Override\r
+                                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                                               if(graph.hasStatement(input, sr.IndependentVariable_activeExpression))\r
+                                                                       graph.deny(input, sr.IndependentVariable_activeExpression);\r
+                                                               graph.claim(input, sr.IndependentVariable_activeExpression, newActive);\r
+                                                       }\r
+                                               }\r
+                                               );\r
+                                       }\r
+                               });\r
+                       }\r
+               });\r
+\r
+               // Creates a new expression\r
+               newExpression.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+                       @Override\r
+                       public void apply(WriteGraph graph, Resource input)\r
+                       throws DatabaseException {\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+                               Resource expressions = graph.getPossibleObject(input, sr.Variable_expressionList);\r
+                               if(expressions == null) {\r
+                                       return;\r
+                               }\r
+                               // Get the currently active expression\r
+                               Resource activeExpression = graph.getPossibleObject(input, sr.IndependentVariable_activeExpression);\r
+                               Resource newExpression = graph.newResource();\r
+                               if(activeExpression != null) {\r
+                                   // Create a new expression based on the old expression\r
+                                       graph.claim(newExpression, l0.InstanceOf, graph.getSingleObject(activeExpression, l0.InstanceOf));\r
+                                       if(graph.isInstanceOf(newExpression, sr.StockExpression)) {\r
+                                               graph.claimLiteral(newExpression, sr.StockExpression_initialEquation, "");\r
+                                       }\r
+                               } else {\r
+                                   // If there was no active expression, create a normal expression\r
+                                       graph.claim(newExpression, l0.InstanceOf, sr.NormalExpression);\r
+                               }\r
+                               ArrayList<Resource> addition = new ArrayList<Resource>(1);\r
+                               addition.add(newExpression);\r
+                               ListUtils.insertBack(graph, expressions, addition);\r
+                               graph.claim(input, l0.ConsistsOf, newExpression);\r
+                       }\r
+               });\r
+\r
+               // Item factory for expression type combo\r
+               expressionTypeCombo.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+                       @Override\r
+                       public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+\r
+                               Map<String, Object> map = new HashMap<String, Object>();\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                               // Select expression types based on the type of the variable\r
+                               final ExpressionType[] expressionTypes;\r
+                               if(graph.isInstanceOf(input, sr.Auxiliary))\r
+                                       expressionTypes = ExpressionTypes.auxiliaryExpressions;\r
+                               else if(graph.isInstanceOf(input, sr.Stock))\r
+                                       expressionTypes = ExpressionTypes.stockExpressions;\r
+                               else if(graph.isInstanceOf(input, sr.Valve))\r
+                                       expressionTypes = ExpressionTypes.valveExpressions;\r
+                               else\r
+                                       expressionTypes = new ExpressionType[] {};\r
+\r
+                               for(ExpressionType et : expressionTypes) {\r
+                                       map.put(et.toString(), et);\r
+                               }\r
+                               return map;\r
+                       }\r
+               });\r
+\r
+               // Initial selection to the combo from active expression\r
+               expressionTypeCombo.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+                       @Override\r
+                       public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                               Resource activeExpression = getActiveExpression(graph, input);\r
+                               if(activeExpression == null)\r
+                                       return null;\r
+                               return ExpressionTypes.getExpressionType(graph, activeExpression).toString();\r
+                       }\r
+               });\r
+\r
+               // Modify listener for selecting expression type\r
+               expressionTypeCombo.addModifyListener(new TextModifyListener() {\r
+\r
+                       @Override\r
+                       public void modifyText(TrackedModifyEvent e) {\r
+                               expressionWidget.displayExpression(e.getText(), false);\r
+                               expressionWidget.save();                \r
+                       }\r
+               });\r
+\r
+\r
+               // Add all units used in the model to the unit combo\r
+               unitCombo.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+                       @Override\r
+                       public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                               Map<String, Object> map = new HashMap<String, Object>();\r
+\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               Resource model = graph.getPossibleObject(input, l0.PartOf);\r
+                               if (model != null) {\r
+                                       Collection<Resource> variables = graph.getObjects(model, l0.ConsistsOf);\r
+                                       for(Resource v : variables) {\r
+                                               Object unit = graph.getPossibleRelatedValue(v, sr.Variable_unit);\r
+                                               if (unit != null && !map.keySet().contains(unit)) {\r
+                                                       map.put((String)unit, (String)unit);\r
+\r
+                                               }\r
+                                       }\r
+                               }\r
+                               return map;\r
+                       }\r
+               });\r
+               \r
+               // Set initial selection of unit combo\r
+               unitCombo.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+                       @Override\r
+                       public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                               String unit = graph.getPossibleRelatedValue(input, SysdynResource.getInstance(graph).Variable_unit);\r
+                               if(unit == null)\r
+                                       return "";\r
+                               else \r
+                                       return unit;\r
+                       }\r
+               });\r
+\r
+               // Modify unit\r
+               unitCombo.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
+\r
+                       @Override\r
+                       public void applyText(WriteGraph graph, Resource input, String text) throws DatabaseException {\r
+                           graph.denyValue(input, SysdynResource.getInstance(graph).Variable_unit);\r
+                               graph.claimLiteral(input, SysdynResource.getInstance(graph).Variable_unit, text);\r
+                               \r
+                               Resource conf = graph.getPossibleObject(input, Layer0.getInstance(graph).PartOf);\r
+                               SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+                               SysdynModel sm = smm.getModel(graph, conf);\r
+                               sm.getMapping().domainModified(input);\r
+                               sm.update(graph);\r
+                       }\r
+               });\r
+\r
+\r
+               /*\r
+                * Double-clicking something in shortcut tab widget\r
+                * writes the clicked element into expression widget,\r
+                * sets focus on expression widget and validates its fields\r
+                */\r
+               shortcutTabWidget.addMouseListener(new MouseListener(){\r
+\r
+                       @Override\r
+                       public void mouseDoubleClick(MouseEvent e) {\r
+                               Table table = (Table)e.widget;\r
+                               TableItem item = table.getItem(new Point(e.x, e.y));\r
+                               if(item != null) {\r
+                                       final String var = (String)item.getData();\r
+                                       table.getDisplay().asyncExec(new Runnable() {\r
+\r
+                                               @Override\r
+                                               public void run() {\r
+                                                       if(expressionWidget!= null) {\r
+                                                           expressionWidget.getExpression().focus();\r
+                                                               expressionWidget.getExpression().replaceSelection(var);\r
+                                                               expressionWidget.validateFieldsTimed();\r
+                                                       }\r
+                                               }\r
+                                       });\r
+                               }\r
+                       }\r
+\r
+                       @Override\r
+                       public void mouseDown(MouseEvent e) {\r
+                               expressionWidget.getExpression().focus();\r
+                       }\r
+\r
+                       @Override\r
+                       public void mouseUp(MouseEvent e) {\r
+                       }\r
+\r
+               });\r
+\r
+               /* Modifying an expression sets a timed validation. The timer is\r
+                * reset after each modification \r
+                */ \r
+               expressionWidget.addModifyListener(new ModifyListener() {\r
+\r
+                       @Override\r
+                       public void modifyText(ModifyEvent e) {\r
+                               expressionWidget.validateFieldsTimed();\r
+                       }\r
+               });\r
+               \r
+               // Pressing return without shift key triggers saving the expression\r
+               expressionWidget.addVerifyKeyListener(new VerifyKeyListener() {\r
+\r
+                       @Override\r
+                       public void verifyKey(VerifyEvent event) {\r
+                           // Check if some of the expression fields has active completion assistant\r
+                               boolean isAnyAssistSessionActive = false;\r
+                               for (int i = 0; i < expressionWidget.getExpression().getExpressionFields().size(); ++i) {\r
+                                       if (expressionWidget.getExpression().getExpressionFields().get(i).isAssistSessionActive()) {\r
+                                               isAnyAssistSessionActive = true;\r
+                                               break;\r
+                                       }\r
+                               }\r
+                               if(event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR) {\r
+                                   if (!isAnyAssistSessionActive) {\r
+                                       if((event.stateMask & SWT.SHIFT) == 0) {\r
+                                           event.doit = false;\r
+                                                       ((StyledText)event.widget).getParent().forceFocus();\r
+                                                       expressionWidget.save();\r
+                                               }\r
+                                   } else {\r
+                                       // When a proposed expression is selected with enter, fields are validated.\r
+                           expressionWidget.validateFieldsTimed();\r
+                                       }\r
+                               }\r
+                       }\r
+               });\r
+               \r
+           // Triggers save when equation tab loses focus\r
+        if(focusLostListener == null) {\r
+            focusLostListener = new org.eclipse.ui.IPartListener2()\r
+            {\r
+                @Override\r
+                public void partInputChanged(IWorkbenchPartReference partRef) {}\r
+                @Override\r
+                public void partVisible(IWorkbenchPartReference partRef) {}\r
+                @Override\r
+                public void partHidden(IWorkbenchPartReference partRef) {}\r
+                @Override\r
+                public void partOpened(IWorkbenchPartReference partRef) {}\r
+                @Override\r
+                public void partDeactivated(IWorkbenchPartReference partRef)\r
+                {\r
+                    if(partRef.getPart(false) instanceof PropertyPageView) {\r
+                        PropertyPageView ppv = (PropertyPageView)partRef.getPart(false);\r
+                        if(ppv.getCurrentPage() instanceof SysdynPropertyPage) {\r
+                            // Save expressions\r
+                            if(expressionWidget != null) {\r
+                                expressionWidget.save();\r
+                            }\r
+//                          site.getPage().removePartListener(this);\r
+                        }\r
+                    }\r
+                }\r
+                @Override\r
+                public void partClosed(IWorkbenchPartReference partRef) {}\r
+                @Override\r
+                public void partBroughtToTop(IWorkbenchPartReference partRef) {}\r
+                @Override\r
+                public void partActivated(IWorkbenchPartReference partRef) {}\r
+            };\r
+            site.getPage().addPartListener(focusLostListener);\r
+        }\r
+       }\r
+\r
+       @Override\r
+       public void dispose() {\r
+        if(expressionWidget != null && !(expressionWidget.getExpression() instanceof DelayExpression)) {\r
+               // For delay expression this doesn't work, \r
+               // but it doesn't matter since the saving is succeeded elsewhere.\r
+            expressionWidget.save();\r
+        }\r
+               if(focusLostListener != null && site != null)\r
+                       site.getPage().removePartListener(focusLostListener);\r
+               super.dispose();\r
+               if(expressionComposite != null && !expressionComposite.isDisposed())\r
+                   expressionComposite.dispose();\r
+       }\r
+\r
+       /**\r
+        * Get the currently active expression of the first expression in expression list if\r
+        * no expression has been set to active\r
+        * \r
+        * @param graph ReadGraph\r
+        * @param variable Variable\r
+        * @return active expression or the first expression in variables expression list\r
+        * @throws DatabaseException\r
+        */\r
+       private Resource getActiveExpression(ReadGraph graph, Resource variable) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Resource expression = graph.getPossibleObject(variable, sr.IndependentVariable_activeExpression);\r
+               if(expression == null) {\r
+                       Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);\r
+                       if(expressions == null) {\r
+                               return null;\r
+                       }\r
+                       List<Resource> expressionList = ListUtils.toList(graph, expressions);\r
+                       if(expressionList.isEmpty()) {\r
+                               return null;\r
+                       }\r
+                       expression = expressionList.get(0);\r
+               }\r
+               return expression;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExperimentTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExperimentTab.java
new file mode 100644 (file)
index 0000000..0c291db
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+\r
+public class ExperimentTab extends LabelPropertyTabContributor {\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExternalFilesTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExternalFilesTab.java
new file mode 100644 (file)
index 0000000..a4a91c9
--- /dev/null
@@ -0,0 +1,208 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.handlers.RemoveNodeHandler;\r
+import org.simantics.sysdyn.ui.handlers.exports.ExportExternalFunctionFilesHandler;\r
+import org.simantics.sysdyn.ui.handlers.imports.ImportExternalFunctionFilesHandler;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * Tab for properties of a SysdynModelicaFunction containing all external files added to that function \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ExternalFilesTab extends LabelPropertyTabContributor implements Widget {\r
+\r
+       GraphExplorerComposite externalFilesExplorer;\r
+       Button importButton, exportButton, removeButton; \r
+       \r
+       @Override\r
+       public void createControls(Composite body, IWorkbenchSite site,\r
+                       final ISessionContext context, WidgetSupport support) {\r
+               support.register(this);\r
+               \r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+        \r
+        // Create the graph explorer displaying external files                 \r
+               externalFilesExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                               "displaySelectors", "displayFilter").values(false, false), site, composite, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);\r
+               \r
+               externalFilesExplorer\r
+               .setBrowseContexts(SysdynResource.URIs.ExternalFiles);\r
+               externalFilesExplorer.setInputSource(new SingleSelectionInputSource(\r
+                               Resource.class));\r
+\r
+               externalFilesExplorer.setContextMenuId("#ExternalFunctionFileBrowser");\r
+               externalFilesExplorer.finish();\r
+\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                               externalFilesExplorer);\r
+               \r
+               Control c = externalFilesExplorer.getExplorerControl();\r
+               if (c instanceof Tree)\r
+                       ((Tree) c).setLinesVisible(true);\r
+               \r
+               \r
+               // Create controls for importing, exporting and removing external files\r
+               Composite buttonRow = new Composite(composite, SWT.NONE);\r
+               GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonRow);\r
+               GridDataFactory.fillDefaults().grab(true, false).applyTo(buttonRow);\r
+               \r
+               importButton = new Button(buttonRow, support, SWT.NONE);\r
+               importButton.setText("Import");\r
+               importButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+                       @Override\r
+                       public void apply(WriteGraph graph, final Resource input)\r
+                                       throws DatabaseException {\r
+                               \r
+                               importButton.getWidget().getDisplay().asyncExec(new Runnable() {\r
+                                       \r
+                                       @Override\r
+                                       public void run() {\r
+                                               Shell shell = importButton.getWidget().getShell();\r
+                                               \r
+                                               final Pair<String, String[]> importedFiles = ImportExternalFunctionFilesHandler.importFiles(shell, "Import files", ImportExternalFunctionFilesHandler.C_EXTENSIONS);\r
+                                               \r
+                                               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                                                       @Override\r
+                                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                               ImportExternalFunctionFilesHandler.addFilesToFunction(graph, input, importedFiles);\r
+                                                       }\r
+                                               });\r
+                                       }\r
+                               });\r
+\r
+\r
+                       }\r
+               });\r
+\r
+               exportButton = new Button(buttonRow, support, SWT.NONE);\r
+               exportButton.setText("Export");\r
+               exportButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+                       @Override\r
+                       public void apply(WriteGraph graph, final Resource input)\r
+                       throws DatabaseException {\r
+\r
+                               exportButton.getWidget().getDisplay().asyncExec(new Runnable() {\r
+\r
+                                       @Override\r
+                                       public void run() {\r
+                                               Shell shell = exportButton.getWidget().getShell();\r
+                                               List<Resource> resourceList = getSelectedResources(externalFilesExplorer);\r
+                                               Resource[] resources = resourceList.toArray(new Resource[resourceList.size()]);\r
+                                               if (resources.length > 0)\r
+                                                       ExportExternalFunctionFilesHandler.exportFiles(shell, resources);\r
+                                       }\r
+                               });\r
+\r
+\r
+                       }\r
+               });\r
+\r
+               removeButton = new Button(buttonRow, support, SWT.NONE);\r
+               removeButton.setText("Remove");\r
+               removeButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+                       @Override\r
+                       public void apply(WriteGraph graph, final Resource input)\r
+                       throws DatabaseException {\r
+\r
+                               removeButton.getWidget().getDisplay().asyncExec(new Runnable() {\r
+\r
+                                       @Override\r
+                                       public void run() {\r
+                                               Shell shell = removeButton.getWidget().getShell();\r
+\r
+                                               List<Resource> resourceList = getSelectedResources(externalFilesExplorer);\r
+                                               Resource[] resources = resourceList.toArray(new Resource[resourceList.size()]);\r
+                                               if(resources.length > 0) {\r
+                                                       MessageDialog dialog = new MessageDialog(shell, resources.length > 1 ? "Remove selected items" : "Remove selected item" , null, "Are you sure?", 0,\r
+                                                                       new String[] { "OK", "Cancel" }, 0);\r
+                                                       dialog.create();\r
+                                                       if (dialog.open() == 0) {\r
+                                                               RemoveNodeHandler.deleteItem(resources);\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                               });\r
+\r
+\r
+                       }\r
+               });\r
+       }\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               externalFilesExplorer.setInput(context, input);\r
+       }\r
+\r
+       /**\r
+        * Method for retreiving selected resources from a GraphExplorerComposite\r
+        * @param explorer\r
+        * @return\r
+        */\r
+       private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {\r
+               List<Resource> result = new ArrayList<Resource>();\r
+               \r
+               ISelection selection = ((ISelectionProvider) explorer\r
+                               .getAdapter(ISelectionProvider.class)).getSelection();\r
+               if (selection == null)\r
+                       return result;\r
+               IStructuredSelection iss = (IStructuredSelection) selection;\r
+               @SuppressWarnings("unchecked")\r
+               List<AdaptableHintContext> selections = iss.toList();\r
+               for(AdaptableHintContext ahc : selections) {\r
+                       Resource resource = (Resource) ahc.getAdapter(Resource.class);\r
+                       result.add(resource);\r
+               }\r
+               return result;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FlowTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FlowTab.java
new file mode 100644 (file)
index 0000000..885d4ab
--- /dev/null
@@ -0,0 +1,96 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Scale;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements.connections.FlowConnectionStyle;\r
+\r
+public class FlowTab  extends LabelPropertyTabContributor {\r
+\r
+    Scale lineThicknessScale;\r
+    \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(composite);\r
+        \r
+        Group lineThicknessGroup = new Group(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().applyTo(lineThicknessGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(lineThicknessGroup);\r
+        lineThicknessGroup.setText("Flow thickness:");\r
+        lineThicknessScale = new Scale(lineThicknessGroup, support, SWT.HORIZONTAL);\r
+        lineThicknessScale.getWidget().setMinimum(1);\r
+        lineThicknessScale.getWidget().setMaximum(9);\r
+        lineThicknessScale.getWidget().setPageIncrement(1);\r
+        lineThicknessScale.getWidget().setIncrement(1);\r
+        lineThicknessScale.setSelectionFactory(new LineThicknessRadioSelectionFactory());\r
+        lineThicknessScale.addSelectionListener(new LineThicknessSelectionListener(context, lineThicknessScale));\r
+    }\r
+    \r
+    class LineThicknessSelectionListener extends SelectionListenerImpl<Resource> {\r
+       Scale scale;\r
+               private int selection;\r
+\r
+        public LineThicknessSelectionListener(ISessionContext context, Scale scale) {\r
+               super(context);\r
+               this.scale = scale;\r
+        }\r
+        \r
+        @Override\r
+        public void beforeApply() {\r
+            this.selection = scale.getWidget().getSelection();\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, Resource connectionElement) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            float width = ((float)selection) / 3.0f;\r
+            graph.claimLiteral(connectionElement, sr.FlowConnection_width, width);\r
+        }\r
+        \r
+    }\r
+    \r
+    class LineThicknessRadioSelectionFactory extends ReadFactoryImpl<Resource, Integer> {\r
+\r
+        public LineThicknessRadioSelectionFactory() {\r
+        }\r
+\r
+        @Override\r
+        public Integer perform(ReadGraph graph, Resource flowConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            Float width = graph.getPossibleRelatedValue(flowConnection, sr.FlowConnection_width, Bindings.FLOAT);  \r
+            if(width == null)\r
+                return (int)Math.round(FlowConnectionStyle.DEFAULT_LINE_WIDTH * 3);\r
+            else\r
+                return (int)Math.round(width * 3);\r
+        }\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FunctionLibraryTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FunctionLibraryTab.java
new file mode 100644 (file)
index 0000000..9704d07
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.FunctionLibraryNameInputValidator;\r
+\r
+public class FunctionLibraryTab extends LabelPropertyTabContributor {\r
+\r
+       @Override\r
+       public void createControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               Composite composite = new Composite(body, SWT.NONE);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+\r
+\r
+               TrackedText nameText = new TrackedText(composite, support, SWT.BORDER);\r
+               nameText.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName));\r
+               nameText.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasName));\r
+        nameText.setInputValidator(new FunctionLibraryNameInputValidator(support));\r
+               GridDataFactory.fillDefaults().grab(true, false).applyTo(nameText.getWidget());\r
+\r
+\r
+               TrackedText information = new TrackedText(composite, support, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);\r
+               information.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasDescription));\r
+               information.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasDescription));\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FunctionTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/FunctionTab.java
new file mode 100644 (file)
index 0000000..c20ede2
--- /dev/null
@@ -0,0 +1,126 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.properties.widgets.FunctionLabelFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.FunctionNameInputValidator;\r
+import org.simantics.sysdyn.ui.properties.widgets.functions.FunctionCodeWidget;\r
+\r
+public class FunctionTab extends AdjustableTab {\r
+       \r
+       ExpressionField modelicaCode;\r
+       private TrackedText nameText;\r
+       private Group modelicaGroup;\r
+       private Label startLabel;\r
+       private Label endLabel;\r
+       private Group documentationGroup;\r
+       private TrackedText information;\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               composite = new Composite(body, SWT.NONE);\r
+\r
+        nameText = new TrackedText(composite, support, SWT.BORDER);\r
+        nameText.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName));\r
+        nameText.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasName));\r
+        nameText.setInputValidator(new FunctionNameInputValidator(support));\r
+        \r
+        \r
+        modelicaGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);\r
+        modelicaGroup.setText("Modelica code");\r
+        \r
+        startLabel = new Label(modelicaGroup, support, SWT.NONE);\r
+        startLabel.setTextFactory(new FunctionLabelFactory(Layer0.URIs.HasName, false));\r
+        \r
+        new FunctionCodeWidget(modelicaGroup, support, SWT.BORDER);\r
+        /*\r
+        TrackedText modelicaCode = new TrackedText(modelicaGroup, support, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP);\r
+        modelicaCode.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.HasModelicaFunctionCode));\r
+        modelicaCode.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.HasModelicaFunctionCode));\r
+        modelicaCode.addModifyListener(new TextModifyListenerImpl<Resource>() {\r
+\r
+                       @Override\r
+                       public void applyText(WriteGraph graph, Resource input, String text)\r
+                                       throws DatabaseException {\r
+                               Resource library = graph.getSingleObject(input, Layer0.getInstance(graph).PartOf);\r
+                               FunctionUtils.updateFunctionFileForLibrary(graph, library);\r
+                       }\r
+               });*/\r
+        \r
+        endLabel = new Label(modelicaGroup, support, SWT.NONE);\r
+        endLabel.setTextFactory(new FunctionLabelFactory(Layer0.URIs.HasName, true));\r
+\r
+        documentationGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);\r
+        documentationGroup.setText("Documentation");\r
+\r
+        information = new TrackedText(documentationGroup, support, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);\r
+        information.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasDescription));\r
+        information.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasDescription));\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().span(1, 1).grab(true, false).applyTo(nameText.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).minSize(150, 0).applyTo(modelicaGroup);\r
+        GridLayoutFactory.fillDefaults().spacing(0, 0).margins(3, 3).applyTo(modelicaGroup);\r
+        \r
+        /*\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(modelicaCode.getWidget());\r
+        */\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(documentationGroup);\r
+        GridLayoutFactory.fillDefaults().spacing(0, 0).margins(3, 3).applyTo(documentationGroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(nameText.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).minSize(150, 0).applyTo(modelicaGroup);\r
+        GridLayoutFactory.fillDefaults().spacing(0, 0).margins(3, 3).applyTo(modelicaGroup);\r
+        \r
+        /*\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(modelicaCode.getWidget());\r
+        */\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(documentationGroup);\r
+        GridLayoutFactory.fillDefaults().spacing(0, 0).margins(3, 3).applyTo(documentationGroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/GameExperimentTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/GameExperimentTab.java
new file mode 100644 (file)
index 0000000..8e26cc3
--- /dev/null
@@ -0,0 +1,86 @@
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+import org.simantics.utils.ui.validators.DoubleValidator;\r
+\r
+/**\r
+ * Tab for displaying game experiment properties\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class GameExperimentTab extends LabelPropertyTabContributor {\r
+\r
+       @Override\r
+       public void createControls(Composite body, IWorkbenchSite site,\r
+               ISessionContext context, WidgetSupport support) {\r
+               \r
+        ScrolledComposite sc = new ScrolledComposite(body,  SWT.H_SCROLL | SWT.V_SCROLL);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().applyTo(sc);\r
+        \r
+        Composite composite = new RemoveFocusBeforeExperimentComposite(sc, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
+        \r
+        // Label\r
+        Label label = new Label(composite, SWT.NONE);\r
+        label.setText("Name");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+\r
+        TrackedText name = new TrackedText(composite, support, SWT.BORDER);\r
+        name.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));\r
+        name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasName));\r
+        name.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), name.getWidget())));\r
+        \r
+        // Step duration (i.e. how many time units is one step in user's perspective)\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Step duration");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+\r
+        TrackedText stepDuration = new TrackedText(composite, support, SWT.BORDER);\r
+        stepDuration.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.GameExperiment_stepDuration));\r
+        stepDuration.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.GameExperiment_stepDuration));\r
+        stepDuration.setInputValidator(new DoubleValidator());\r
+        stepDuration.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), stepDuration.getWidget())));\r
+        GridDataFactory.fillDefaults().hint(80, SWT.DEFAULT).grab(true, false).applyTo(name.getWidget());\r
+\r
+        // Integrator step length (i.e. how long is a integration step in the simulator. This time is stepped until stepDuration is full)\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Integrator step length");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+\r
+        TrackedText integratorStep = new TrackedText(composite, support, SWT.BORDER);\r
+        integratorStep.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.GameExperiment_stepLength));\r
+        integratorStep.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.GameExperiment_stepLength));\r
+        integratorStep.setInputValidator(new DoubleValidator());\r
+        integratorStep.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), integratorStep.getWidget())));\r
+        \r
+        // Scrolled composite settings\r
+        sc.setContent(composite);\r
+        sc.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));\r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/HistoryDataTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/HistoryDataTab.java
new file mode 100644 (file)
index 0000000..ceed5ad
--- /dev/null
@@ -0,0 +1,287 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.Collection;\r
+import java.util.LinkedHashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.widgets.Combo;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Tab for displaying and modifying history data settings in SysDyn.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class HistoryDataTab  extends LabelPropertyTabContributor {\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        \r
+        // Scrolled composite for scrollable tab\r
+        ScrolledComposite sc = new ScrolledComposite(body, SWT.H_SCROLL | SWT.V_SCROLL);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(sc);\r
+\r
+        // Container for all components\r
+        Composite composite = new Composite(sc, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).margins(3, 3).applyTo(composite);\r
+\r
+        // Name\r
+        Label label = new Label(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        label.setText("Name: ");\r
+        \r
+        TrackedText nameText = new TrackedText(composite, support, SWT.BORDER);\r
+        nameText.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));\r
+        nameText.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(nameText.getWidget());\r
+\r
+        // Sheet selection \r
+        label = new Label(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        label.setText("Sheet: ");\r
+        \r
+        TrackedCombo sheet = new TrackedCombo(composite, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
+        sheet.setItemFactory(new SheetItemFactory());\r
+        sheet.setSelectionFactory(new SheetSelectionFactory());\r
+        sheet.addModifyListener(new SheetModifyListener());\r
+        GridDataFactory.fillDefaults().span(2, 1).applyTo(sheet.getWidget());\r
+\r
+        // Orientation (columns or rows)\r
+        label = new Label(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        label.setText("Orientation: ");\r
+        \r
+        Composite orientation = new Composite(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().applyTo(orientation);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(orientation);\r
+        \r
+        // Radio buttons for orientation\r
+        Button columns = new Button(orientation, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().applyTo(columns.getWidget());\r
+        columns.setText("Columns");\r
+        columns.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                graph.claimLiteral(input, SysdynResource.getInstance(graph).HistoryDataset_columns, Boolean.TRUE, Bindings.BOOLEAN);\r
+            }\r
+        });\r
+        columns.setSelectionFactory(new ReadFactoryImpl<Resource, Boolean>() {\r
+\r
+            @Override\r
+            public Boolean perform(ReadGraph graph, Resource input) throws DatabaseException {\r
+                return graph.getPossibleRelatedValue(input, SysdynResource.getInstance(graph).HistoryDataset_columns);\r
+            }\r
+        });\r
+        \r
+        Button rows = new Button(orientation, support, SWT.RADIO);\r
+        rows.setText("Rows");\r
+        rows.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                graph.claimLiteral(input, SysdynResource.getInstance(graph).HistoryDataset_columns, Boolean.FALSE, Bindings.BOOLEAN);\r
+            }\r
+        });\r
+        rows.setSelectionFactory(new ReadFactoryImpl<Resource, Boolean>() {\r
+\r
+            @Override\r
+            public Boolean perform(ReadGraph graph, Resource input) throws DatabaseException {\r
+                return Boolean.FALSE.equals(graph.getPossibleRelatedValue(input, SysdynResource.getInstance(graph).HistoryDataset_columns));\r
+            }\r
+        });\r
+        \r
+        \r
+        // Group container displaying all variables found in the defined range\r
+        Group c = new Group(composite, SWT.NONE);\r
+        c.setText("Variables in range");\r
+        GridDataFactory.fillDefaults().span(1, 4).applyTo(c);\r
+        GridLayoutFactory.fillDefaults().margins(3, 1).spacing(0, 0).applyTo(c);\r
+        \r
+        GraphExplorerComposite explorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter").values(false, false), site, c, support, SWT.FULL_SELECTION | SWT.BORDER);\r
+        explorer.setBrowseContexts(SysdynResource.URIs.HistoryDataset_HistoryDatasetVariablesBrowseContext);\r
+        explorer.setInputSource(new SingleSelectionInputSource(Resource.class));\r
+        explorer.finish();\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT,100).grab(true, false).applyTo(explorer);\r
+        \r
+        // Range start \r
+        label = new Label(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        label.setText("Range Start: ");\r
+        \r
+        TrackedText start = new TrackedText(composite, support, SWT.BORDER);\r
+        start.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.HistoryDataset_start));\r
+        start.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.HistoryDataset_start));\r
+        GridDataFactory.fillDefaults().applyTo(start.getWidget());\r
+        \r
+        // Range end\r
+        label = new Label(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        label.setText("Range End: ");\r
+        \r
+        TrackedText end = new TrackedText(composite, support, SWT.BORDER);\r
+        end.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.HistoryDataset_end));\r
+        end.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.HistoryDataset_end));\r
+        GridDataFactory.fillDefaults().applyTo(end.getWidget());\r
+        \r
+        // Time variable. This variable is used as time values in the history dataset\r
+        label = new Label(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        label.setText("Time variable: ");\r
+        \r
+        TrackedText time = new TrackedText(composite, support, SWT.BORDER);\r
+        time.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.HistoryDataset_timeName));\r
+        time.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.HistoryDataset_timeName));\r
+        GridDataFactory.fillDefaults().applyTo(time.getWidget());\r
+        \r
+        \r
+        // Scrolled composite settings\r
+        sc.setContent(composite);\r
+        sc.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));\r
+        sc.setExpandHorizontal(true);\r
+        sc.setExpandVertical(true);\r
+\r
+\r
+    }\r
+\r
+    /**\r
+     * Item factory for finding spreadsheets from a model\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class SheetItemFactory extends ReadFactoryImpl<Resource, Map<String,Object>> {\r
+\r
+        @Override\r
+        public Map<String, Object> perform(ReadGraph graph, Resource historyData) throws DatabaseException {\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            SimulationResource simu = SimulationResource.getInstance(graph);\r
+            SpreadsheetResource spreadSheet = SpreadsheetResource.getInstance(graph);\r
+\r
+            Resource model = graph.getPossibleObject(historyData, l0.PartOf);\r
+            Resource config = graph.getPossibleObject(model, simu.HasConfiguration);\r
+            Resource book = graph.syncRequest(new PossibleObjectWithType(config, l0.ConsistsOf, spreadSheet.Book));\r
+            Collection<Resource> sheets = graph.syncRequest(new ObjectsWithType(book, l0.ConsistsOf, spreadSheet.Spreadsheet));\r
+\r
+            Map<String, Object> map = new LinkedHashMap<String, Object>();\r
+\r
+            for(Resource sheet : sheets) {\r
+                map.put(NameUtils.getSafeName(graph, sheet), sheet);\r
+            }\r
+            return map;\r
+        }\r
+    };\r
+    \r
+    /**\r
+     * Selection factory for finding the defined sheet name for a history dataset\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class SheetSelectionFactory extends ReadFactoryImpl<Resource, String> {\r
+\r
+        @Override\r
+        public String perform(ReadGraph graph, Resource historyData) throws DatabaseException {\r
+            Resource selectedSheet = graph.getPossibleObject(historyData, SysdynResource.getInstance(graph).HistoryDataset_sheet);\r
+            if(selectedSheet != null) {\r
+                String name = NameUtils.getSafeName(graph, selectedSheet);\r
+                return name;// Return the selected sheet, if it exits\r
+            } else {\r
+                return null;\r
+            }\r
+        }\r
+    };\r
+\r
+    /**\r
+     * Listener for listening sheet selections in sheet combo\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class SheetModifyListener implements TextModifyListener, Widget {\r
+\r
+        private ISessionContext context;\r
+        private Object lastInput = null;\r
+\r
+        @Override\r
+        public void modifyText(TrackedModifyEvent e) {\r
+\r
+            Combo combo = (Combo)e.getWidget();\r
+            String textValue = combo.getText();\r
+            Map<?,?> data = (Map<?, ?>) combo.getData();\r
+            if(data == null) return;\r
+            final Resource value = (Resource) data.get(textValue);\r
+            if(value == null) return;\r
+            final Object input = lastInput;\r
+\r
+            try {\r
+                context.getSession().syncRequest(new WriteRequest() {\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+\r
+                        Resource resource = (Resource) ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);\r
+                        SysdynResource sr = SysdynResource.getInstance(graph);\r
+                        graph.deny(resource, sr.HistoryDataset_sheet);\r
+                        graph.claim(resource, SysdynResource.getInstance(graph).HistoryDataset_sheet, value);\r
+                    }\r
+\r
+                });\r
+            } catch (DatabaseException e1) {\r
+                e1.printStackTrace();\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void setInput(ISessionContext context, Object parameter) {\r
+            this.context = context;\r
+            lastInput = parameter;\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/InputVariableTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/InputVariableTab.java
new file mode 100644 (file)
index 0000000..fd5480e
--- /dev/null
@@ -0,0 +1,168 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.ui.properties.widgets.IsOutputWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.UnitComboWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNamePropertyModifier;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNameInputValidator;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.ui.validators.DoubleValidator;\r
+\r
+/**\r
+ * Properties for input variables: Name, default value, isOutput\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class InputVariableTab  extends LabelPropertyTabContributor {\r
+\r
+    \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).grab(false, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+\r
+        TrackedText nameText = new TrackedText(composite, support, SWT.BORDER);\r
+        nameText.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName));\r
+        nameText.addModifyListener(new VariableNamePropertyModifier(context, Layer0.URIs.HasName));\r
+        nameText.setInputValidator(new VariableNameInputValidator(support));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(nameText.getWidget());\r
+\r
+        Composite defaultValueComposite = new Composite(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(false, false).applyTo(defaultValueComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(defaultValueComposite);\r
+        \r
+        Label label = new Label(defaultValueComposite, SWT.NULL);\r
+        label.setText("Default Value:");\r
+        \r
+        TrackedText defaultValue = new TrackedText(defaultValueComposite, support, SWT.RIGHT | SWT.BORDER);\r
+        defaultValue.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.Input_defaultInputValue));\r
+        defaultValue.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.Input_defaultInputValue));\r
+        defaultValue.setInputValidator(new DoubleValidator());\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(defaultValue.getWidget());\r
+\r
+\r
+        Composite unitComposite = new Composite(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().applyTo(unitComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(unitComposite);\r
+        \r
+        label = new Label(unitComposite, SWT.NULL );\r
+        label.setText("Unit:");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+\r
+        TrackedCombo unitCombo = new UnitComboWidget(unitComposite, support, SWT.DROP_DOWN | SWT.BORDER);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(unitCombo.getWidget());\r
+        \r
+        \r
+        Composite variabilityComposite = new Composite(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(variabilityComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(variabilityComposite);\r
+        \r
+        label = new Label(variabilityComposite, SWT.NULL);\r
+        label.setText("Variability:");\r
+        \r
+        TrackedCombo variability = new TrackedCombo(variabilityComposite, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(variability.getWidget());\r
+        setVariabilityFactories(variability);\r
+        \r
+        new IsOutputWidget(composite, support, SWT.NULL);\r
+    }\r
+    \r
+    /**\r
+     * set item, selection and modify properties for variability combo\r
+     * @param variability\r
+     */\r
+    private void setVariabilityFactories(TrackedCombo variability) {\r
+        variability.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+            @Override\r
+            public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                Map<String, Object> map = new HashMap<String, Object>();\r
+                map.put("continuous", "continuous");\r
+                map.put("parameter", "parameter");\r
+                map.put("constant", "constant");\r
+                return map;\r
+            }\r
+        });\r
+        \r
+        variability.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+            \r
+            public Object getIdentity(Object inputContents) {\r
+                return new Pair<Object, Class<?>>(inputContents, getClass());\r
+            }\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                String variability = graph.getPossibleRelatedValue(input, sr.Variable_variability);\r
+                if(variability == null || variability.isEmpty())\r
+                    return "continuous";\r
+                else \r
+                    return variability;\r
+            }\r
+        });\r
+        \r
+        variability.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
+\r
+            @Override\r
+            public void applyText(WriteGraph graph, Resource input, String text) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                String variability = text;\r
+                if(text.equals("continuous"))\r
+                    variability = "";\r
+                \r
+                if(variability != null) {\r
+                    graph.denyValue(input, sr.Variable_variability);\r
+                    graph.claimLiteral(input, sr.Variable_variability, variability);\r
+                    \r
+                    Resource conf = graph.getPossibleObject(input, Layer0.getInstance(graph).PartOf);\r
+                    SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+                    SysdynModel sm = smm.getModel(graph, conf);\r
+                    sm.getMapping().domainModified(input);\r
+                    sm.update(graph);\r
+                    \r
+                }\r
+            }\r
+            \r
+        });\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LookupTableTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LookupTableTab.java
new file mode 100644 (file)
index 0000000..25de7c9
--- /dev/null
@@ -0,0 +1,88 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.ChartTableWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.ChartWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+\r
+public class LookupTableTab extends LabelPropertyTabContributor {\r
+    \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+\r
+        \r
+        Composite baseContainer = new Composite(body, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(3).applyTo(baseContainer);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(baseContainer);\r
+\r
+        Composite Ycontainer = new Composite(baseContainer, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().applyTo(Ycontainer);\r
+        GridDataFactory.fillDefaults().grab(false, true).applyTo(Ycontainer);\r
+\r
+        TrackedText maxYText = new TrackedText(Ycontainer, support, SWT.BORDER);\r
+        maxYText.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.WithLookupExpression_maxY));\r
+        maxYText.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.WithLookupExpression_maxY));\r
+\r
+        Label l = new Label(Ycontainer, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).grab(false, true).applyTo(l);\r
+\r
+        TrackedText minYText = new TrackedText(Ycontainer, support, SWT.BORDER);\r
+        minYText.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.WithLookupExpression_minY));\r
+        minYText.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.WithLookupExpression_minY));\r
+\r
+\r
+        Composite chartContainer = new Composite(baseContainer, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(chartContainer);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(chartContainer);\r
+\r
+        @SuppressWarnings("unused")\r
+        ChartWidget chartWidget = new ChartWidget(chartContainer, support, SWT.NONE);\r
+             \r
+        Composite chartTableContainer = new Composite(baseContainer, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().applyTo(chartTableContainer);\r
+        GridDataFactory.fillDefaults().grab(false, true).span(1, 2).applyTo(chartTableContainer);       \r
+        \r
+        @SuppressWarnings("unused")\r
+        ChartTableWidget chartTableWidget = new ChartTableWidget(chartTableContainer, support, SWT.NONE);\r
+        \r
+        l = new Label(baseContainer, SWT.NONE);\r
+\r
+        Composite Xcontainer = new Composite(baseContainer, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(Xcontainer);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(Xcontainer);\r
+\r
+        TrackedText minXText = new TrackedText(Xcontainer, support, SWT.BORDER);\r
+        minXText.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.WithLookupExpression_minX));\r
+        minXText.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.WithLookupExpression_minX));\r
+\r
+        l = new Label(Xcontainer, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).grab(true, false).applyTo(l);\r
+\r
+        TrackedText maxXText = new TrackedText(Xcontainer, support, SWT.BORDER);\r
+        maxXText.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.WithLookupExpression_maxX));\r
+        maxXText.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.WithLookupExpression_maxX));\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LoopTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LoopTab.java
new file mode 100644 (file)
index 0000000..ee43cbb
--- /dev/null
@@ -0,0 +1,406 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Combo;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.util.ObjectUtils;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.utils.LoopUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.datastructures.Triple;\r
+\r
+/**\r
+ * Tab for displaying information of a loop\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class LoopTab extends AdjustableTab {\r
+\r
+       private Label loopItemsLabel;\r
+       private TrackedCombo loopItemsDropdown;\r
+       Button auto, balancing, reinforcing, other, inside, outside;\r
+    TrackedText loopComment, polarityLocationText;\r
+    Composite loopItems;\r
+    Group commentGroup, rotationGroup;\r
+       protected Resource resource;\r
+       public static final String AUTO = "$$AUTO$$";\r
+       \r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport support) {\r
+               composite = new Composite(body, SWT.NONE);\r
+\r
+               loopItems = new Composite(composite, SWT.NONE);\r
+               loopItemsLabel = new Label(loopItems, SWT.SINGLE);\r
+               loopItemsLabel.setText("Loop Items:");\r
+               loopItemsDropdown = new TrackedCombo(loopItems, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
+                               \r
+        commentGroup = new Group(composite, SWT.NONE);\r
+        commentGroup.setText("Comment");\r
+        \r
+        auto = new Button(commentGroup, support, SWT.RADIO);\r
+        auto.setText("Auto");\r
+        auto.setSelectionFactory(new CommentRadioSelectionFactory(AUTO));\r
+        auto.addSelectionListener(new CommentSelectionListener(context, AUTO));\r
+        \r
+        balancing = new Button(commentGroup, support, SWT.RADIO);\r
+        balancing.setText("B");\r
+        balancing.setSelectionFactory(new CommentRadioSelectionFactory("B"));\r
+        balancing.addSelectionListener(new CommentSelectionListener(context, "B"));\r
+        \r
+        reinforcing = new Button(commentGroup, support, SWT.RADIO);\r
+        reinforcing.setText("R");\r
+        reinforcing.setSelectionFactory(new CommentRadioSelectionFactory("R"));\r
+        reinforcing.addSelectionListener(new CommentSelectionListener(context, "R"));\r
+        \r
+        other = new Button(commentGroup, support, SWT.RADIO);\r
+        other.setText("other");\r
+        other.setSelectionFactory(new OtherCommentSelectionFactory(new String[] {null, "B", "R", AUTO}));\r
+        other.addSelectionListener(new CommentSelectionListener(context, ""));\r
+        \r
+        loopComment = new TrackedText(commentGroup, support, SWT.BORDER);\r
+        loopComment.setTextFactory(new OtherCommentStringPropertyFactory());\r
+        loopComment.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.Loop_Comment));\r
+        \r
+        rotationGroup = new Group(composite, SWT.NONE);\r
+        rotationGroup.setText("Direction of Rotation");\r
+        \r
+        inside = new Button(rotationGroup, support, SWT.RADIO);\r
+        inside.setText("Clockwise");\r
+        inside.setSelectionFactory(new ClockwiseRotationRadioSelectionFactory(true));\r
+        inside.addSelectionListener(new ClockwiseRotationSelectionListener(context, true));\r
+        \r
+        outside = new Button(rotationGroup, support, SWT.RADIO);\r
+        outside.setText("Counterclockwise");\r
+        outside.setSelectionFactory(new ClockwiseRotationRadioSelectionFactory(false));\r
+        outside.addSelectionListener(new ClockwiseRotationSelectionListener(context, false));\r
+        \r
+        addListeners(context);\r
+       }\r
+\r
+       private void addListeners(ISessionContext context) {\r
+               // Item factory for loopItemsDropdown combo\r
+               loopItemsDropdown.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+                       @Override\r
+                       public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+\r
+                               LoopTab.this.resource = input;\r
+                               Map<String, Object> map = new HashMap<String, Object>();\r
+                               List<List<Resource>> loops = LoopUtils.getAllLoopsInDiagram(graph, input);\r
+                               map.put("", null);\r
+                               for (List<Resource> loop : loops) {\r
+                                       map.put(LoopUtils.cycleToString(graph, loop), loop);\r
+                               }\r
+                               return map;\r
+                       }\r
+               });\r
+\r
+               // Initial selection to the combo\r
+               loopItemsDropdown.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+                       @Override\r
+                       public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                Resource itemListResource = graph.getPossibleObject(input, sr.Loop_Items);\r
+                \r
+                // If the loop hasn't been defined, return empty.\r
+                               if (itemListResource == null) {\r
+                                       return "";\r
+                               }\r
+                               List<Resource> itemList = ListUtils.toPossibleList(graph, itemListResource);\r
+                               if (itemList == null) {\r
+                                       return "";\r
+                               }\r
+                               \r
+                               // See if the defined loop still exists.\r
+                               List<List<Resource>> loops = LoopUtils.getAllLoopsInDiagram(graph, input);\r
+                               Resource first = itemList.get(0);\r
+                               for (List<Resource> loop : loops) {\r
+                                       // If the loops are of different size, continue.\r
+                                       if (loop.size() != itemList.size())\r
+                                               continue;\r
+                                       \r
+                                       // If the first element of the sought loop is not found, continue. \r
+                                       int indexOfFirst = loop.indexOf(first);\r
+                                       if (indexOfFirst < 0) {\r
+                                               continue;\r
+                                       }\r
+                                       \r
+                                       // Check if the loops are the same,\r
+                                       // even if they start at different Resources\r
+                                       boolean match = true;\r
+                                       int i = 1;// = indexOfFirst + 1;\r
+                                       do {\r
+                                               // Get the next Resource in the loop\r
+                                               Resource next = loop.get((i + indexOfFirst) % loop.size());\r
+                                               // If it is other than what should be, continue to the next loop.\r
+                                               if (!next.equalsResource(itemList.get(i))) {\r
+                                                       match = false;\r
+                                                       break;\r
+                                               }\r
+                                       } while (++i != itemList.size());\r
+                                       if (!match)\r
+                                               continue;\r
+                                       \r
+                                       return LoopUtils.cycleToString(graph, loop);\r
+                               }\r
+                               \r
+                               // No match found, hence empty\r
+                               return "";\r
+                       }\r
+               });\r
+\r
+               // Modify listener for selecting loop items\r
+               loopItemsDropdown.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
+\r
+                       @SuppressWarnings("unchecked")\r
+                       @Override\r
+                       public void applyText(WriteGraph graph, final Resource input, String text) throws DatabaseException  {\r
+                               final Combo c = loopItemsDropdown.getWidget();\r
+                               Display.getDefault().asyncExec(new Runnable() {\r
+                                   public void run() {\r
+                                       Object o = c.getData();\r
+                                               if (o != null && !(o instanceof HashMap<?, ?>))\r
+                                                       return;\r
+                                               \r
+                                               Object loopObject = ((HashMap<?, ?>)o).get(c.getText());\r
+                                               if (loopObject == null || !(loopObject instanceof List<?>))\r
+                                                       return;\r
+                                               \r
+                                               final List<Resource> loop = (List<Resource>)loopObject;\r
+                                               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                                                       @Override\r
+                                                       public void perform(WriteGraph graph)\r
+                                                                       throws DatabaseException {\r
+                                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                               Resource loopResource = graph.getPossibleObject(input, sr.Loop_Items);\r
+                                               // Delete the current list if it exists.\r
+                                                               if (loopResource != null) {\r
+                                                       List<Resource> removedList = ListUtils.toPossibleList(graph, loopResource);\r
+                                                                       for (Resource r : removedList)\r
+                                                                               ListUtils.removeElement(graph, loopResource, r);\r
+                                                                       graph.deny(loopResource);\r
+                                               }\r
+                                               // Create new list.\r
+                                               Resource newList = ListUtils.create(graph, loop);\r
+                                               graph.claim(input, sr.Loop_Items, newList);\r
+                                                       }\r
+                                               });\r
+                                   }\r
+                               });\r
+                               \r
+                       }\r
+               });\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+               GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(loopItems);\r
+               GridLayoutFactory.fillDefaults().numColumns(1).applyTo(loopItems);\r
+               GridDataFactory.fillDefaults().grab(false, false).applyTo(loopItemsLabel);\r
+               GridDataFactory.fillDefaults().grab(true, false).applyTo(loopItemsDropdown.getWidget());\r
+        \r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(composite);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(commentGroup);\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(commentGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(loopComment.getWidget());\r
+        GridDataFactory.fillDefaults().grab(false, false).applyTo(rotationGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(rotationGroup);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+               GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(loopItems);\r
+               GridLayoutFactory.fillDefaults().numColumns(2).applyTo(loopItems);\r
+               GridDataFactory.fillDefaults().grab(false, false).applyTo(loopItemsLabel);\r
+               GridDataFactory.fillDefaults().grab(true, false).applyTo(loopItemsDropdown.getWidget());\r
+        \r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(commentGroup);\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(commentGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(loopComment.getWidget());\r
+        GridDataFactory.fillDefaults().grab(false, false).applyTo(rotationGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(rotationGroup);\r
+       }\r
+       \r
+       class OtherCommentStringPropertyFactory extends ReadFactoryImpl<Resource, String> {\r
+\r
+           private final String propertyURI;\r
+\r
+           public OtherCommentStringPropertyFactory() {\r
+               this.propertyURI = SysdynResource.URIs.Loop_Comment;\r
+           }\r
+\r
+           @Override\r
+           public Object getIdentity(Object inputContents) {\r
+               return new Triple<Resource, String, Object>((Resource)inputContents, propertyURI, getClass());\r
+           }\r
+\r
+           @Override\r
+           public String perform(ReadGraph graph, Resource resource) throws DatabaseException {\r
+               String value = graph.getPossibleRelatedValue(resource, graph.getResource(propertyURI));;\r
+               if (value == null || AUTO.equals(value))\r
+                       return "";\r
+               return value;\r
+           }           \r
+    }\r
+       \r
+    class ClockwiseRotationSelectionListener extends SelectionListenerImpl<Resource> {\r
+        private boolean clockwise;\r
+\r
+        public ClockwiseRotationSelectionListener(ISessionContext context, boolean clockwise) {\r
+            super(context);\r
+            this.clockwise = clockwise;\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, Resource component) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            ModelingResources mr = ModelingResources.getInstance(graph);\r
+               Resource symbol = graph.getPossibleObject(component, mr.ComponentToElement);\r
+            if(symbol != null) {\r
+               graph.deny(symbol, sr.LoopSymbol_Clockwise);\r
+               graph.claimLiteral(symbol, sr.LoopSymbol_Clockwise, clockwise);\r
+            }\r
+        }\r
+        \r
+    }\r
+    \r
+    class ClockwiseRotationRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        private boolean clockwise;\r
+\r
+        public ClockwiseRotationRadioSelectionFactory(boolean clockwise) {\r
+            this.clockwise = clockwise;\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, clockwise, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource component) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph); \r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               Resource symbol = graph.getPossibleObject(component, mr.ComponentToElement);\r
+            if(symbol != null) {\r
+               Boolean clockwise = graph.getPossibleRelatedValue(symbol, sr.LoopSymbol_Clockwise, Bindings.BOOLEAN);  \r
+               return ObjectUtils.objectEquals(this.clockwise, clockwise);\r
+            }\r
+            return Boolean.TRUE;\r
+        }\r
+    }\r
+    \r
+    class CommentSelectionListener extends SelectionListenerImpl<Resource> {\r
+        private String comment;\r
+\r
+        public CommentSelectionListener(ISessionContext context, String comment) {\r
+            super(context);\r
+            this.comment = comment;\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, Resource connectionElement) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            graph.deny(connectionElement, sr.Loop_Comment);\r
+            graph.claimLiteral(connectionElement, sr.Loop_Comment, comment.trim());\r
+        }\r
+        \r
+    }\r
+    \r
+    class CommentRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        private String comment;\r
+\r
+        public CommentRadioSelectionFactory(String comment) {\r
+            this.comment = comment;\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, comment, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            String comment = graph.getPossibleRelatedValue(dependencyConnection, sr.Loop_Comment, Bindings.STRING);     \r
+            if(comment == null && this.comment.equals(""))\r
+                return true;\r
+            return ObjectUtils.objectEquals(comment, this.comment);\r
+        }\r
+    }\r
+    \r
+    class OtherCommentSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+\r
+        String[] limits;\r
+        \r
+        public OtherCommentSelectionFactory(String[] limits) {\r
+            this.limits = limits;\r
+        }\r
+        \r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Pair<Object, Class<?>>(inputContents, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            String comment = graph.getPossibleRelatedValue(dependencyConnection, sr.Loop_Comment, Bindings.STRING);\r
+            for(String s : limits) {\r
+                if(ObjectUtils.objectEquals(comment, s))\r
+                    return false;\r
+            }\r
+            return true;\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleInputTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleInputTab.java
new file mode 100644 (file)
index 0000000..320fb90
--- /dev/null
@@ -0,0 +1,92 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.eclipse.jface.viewers.ArrayContentProvider;\r
+import org.eclipse.jface.viewers.TableViewerColumn;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.ModuleInputEditingSupport;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.ReferenceRow;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.ReferenceRowLabelProvider;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.ReferenceTable;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.RowProvider;\r
+\r
+public class ModuleInputTab extends LabelPropertyTabContributor {\r
+\r
+    public static final String FIRSTCOLUMN = "Input in Module";\r
+    public static final String SECONDCOLUMN = "Refers to output";\r
+    \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        ReferenceTable referenceTable = new ReferenceTable(body, support, SWT.NONE);\r
+        \r
+        String[] titles = { FIRSTCOLUMN, SECONDCOLUMN};\r
+        int[] bounds = { 200, 200 };\r
+        for (int i = 0; i < titles.length; i++) {\r
+            TableViewerColumn column = new TableViewerColumn(referenceTable.getTableViewer(), SWT.NONE);\r
+            column.getColumn().setText(titles[i]);\r
+            column.getColumn().setWidth(bounds[i]);\r
+            column.getColumn().setResizable(true);\r
+            column.getColumn().setMoveable(false);\r
+            // enable editing support\r
+            column.setEditingSupport(new ModuleInputEditingSupport(referenceTable.getTableViewer(), i));\r
+        }\r
+        referenceTable.setContentProvider (new ArrayContentProvider());\r
+        referenceTable.setLabelProvider (new ReferenceRowLabelProvider());\r
+        \r
+        RowProvider rp = new RowProvider() {\r
+            \r
+            @Override\r
+            public ArrayList<ReferenceRow> getRows(ReadGraph graph, Resource module) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+                ArrayList<ReferenceRow> result = new ArrayList<ReferenceRow>();\r
+                Resource instanceOf = graph.getPossibleObject(module, l0.InstanceOf);\r
+                if(instanceOf == null) return result;\r
+                Resource configuration = graph.getSingleObject(instanceOf, sr2.IsDefinedBy);\r
+                for(Resource input : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Input))) {\r
+                    if(!graph.getObjects(input, sr.Variable_isHeadOf).isEmpty())\r
+                        continue; // Only inputs with tail dependencies allowed.\r
+                    \r
+                    Resource dependency = null;\r
+                    for(Resource dep : graph.getObjects(module, sr.Variable_isHeadOf)) {\r
+                        Resource refersTo = graph.getPossibleObject(dep, sr.Dependency_refersTo);\r
+                        if(refersTo != null && refersTo.equals(input)) {\r
+                            dependency = dep;\r
+                            break;\r
+                        }\r
+                    }\r
+                    ReferenceRow rr = new ReferenceRow(module, dependency, input); \r
+                    result.add(rr);\r
+                }\r
+                return result;\r
+            }\r
+        };\r
+        referenceTable.setRowProvider(rp);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleOutputTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleOutputTab.java
new file mode 100644 (file)
index 0000000..9691f7e
--- /dev/null
@@ -0,0 +1,90 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.eclipse.jface.viewers.ArrayContentProvider;\r
+import org.eclipse.jface.viewers.TableViewerColumn;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.ModuleOutputEditingSupport;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.ReferenceRow;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.ReferenceRowLabelProvider;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.ReferenceTable;\r
+import org.simantics.sysdyn.ui.properties.widgets.modules.RowProvider;\r
+\r
+public class ModuleOutputTab extends LabelPropertyTabContributor {\r
+\r
+    public static final String FIRSTCOLUMN = "Output in module";\r
+    public static final String SECONDCOLUMN = "Referes to input";\r
+    \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        ReferenceTable referenceTable = new ReferenceTable(body, support, SWT.NONE);\r
+        \r
+        String[] titles = { FIRSTCOLUMN, SECONDCOLUMN};\r
+        int[] bounds = { 200, 200 };\r
+        for (int i = 0; i < titles.length; i++) {\r
+            TableViewerColumn column = new TableViewerColumn(referenceTable.getTableViewer(), SWT.NONE);\r
+            column.getColumn().setText(titles[i]);\r
+            column.getColumn().setWidth(bounds[i]);\r
+            column.getColumn().setResizable(true);\r
+            column.getColumn().setMoveable(false);\r
+            // enable editing support\r
+            column.setEditingSupport(new ModuleOutputEditingSupport(referenceTable.getTableViewer(), i));\r
+        }\r
+        referenceTable.setContentProvider (new ArrayContentProvider());\r
+        referenceTable.setLabelProvider (new ReferenceRowLabelProvider());\r
+        \r
+        RowProvider rp = new RowProvider() {\r
+            \r
+            @Override\r
+            public ArrayList<ReferenceRow> getRows(ReadGraph graph, Resource module) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+                ArrayList<ReferenceRow> result = new ArrayList<ReferenceRow>();\r
+                Resource instanceOf = graph.getPossibleObject(module, l0.InstanceOf);\r
+                if(instanceOf == null) return result;\r
+                Resource configuration = graph.getSingleObject(instanceOf, sr2.IsDefinedBy);\r
+                for(Resource variable : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Variable))) {\r
+                    if(!graph.hasStatement(variable, sr.IsOutput)) continue;\r
+                    \r
+                    Resource dependency = null;\r
+                    for(Resource dep : graph.getObjects(module, sr.Variable_isTailOf)) {\r
+                        Resource refersTo = graph.getPossibleObject(dep, sr.Dependency_refersTo);\r
+                        if(refersTo != null && refersTo.equals(variable)) {\r
+                            dependency = dep;\r
+                            break;\r
+                        }\r
+                    }\r
+                    ReferenceRow rr = new ReferenceRow(module, dependency, variable); \r
+                    result.add(rr);\r
+                }\r
+                return result;\r
+            }\r
+        };\r
+        referenceTable.setRowProvider(rp);\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleParameterTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleParameterTab.java
new file mode 100644 (file)
index 0000000..5e3f124
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+\r
+public class ModuleParameterTab extends LabelPropertyTabContributor {\r
+\r
+    GraphExplorerComposite explorer;\r
+    \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+        \r
+        explorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER);\r
+        \r
+        explorer.setBrowseContexts(SysdynResource.URIs.Module_ParameterOverrideBrowseContext);\r
+        explorer.setColumns(ColumnKeys.MODULE_PARAMETER_COLUMNS);\r
+        explorer.setInputSource(new SingleSelectionInputSource(\r
+                Resource.class));\r
+\r
+        explorer.finish();\r
+\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                explorer);\r
+        \r
+        Control c = explorer.getExplorerControl();\r
+        if (c instanceof Tree)\r
+            ((Tree) c).setLinesVisible(true);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleTab.java
new file mode 100644 (file)
index 0000000..64a558b
--- /dev/null
@@ -0,0 +1,82 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNameInputValidator;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+\r
+public class ModuleTab extends LabelPropertyTabContributor implements Widget {\r
+\r
+       GraphExplorerComposite enumerationRedeclarationExplorer;\r
+       \r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+       support.register(this);\r
+       \r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+        TrackedText nameText = new TrackedText(composite, support, SWT.BORDER);\r
+        nameText.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName));\r
+        nameText.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasName));\r
+        nameText.setInputValidator(new VariableNameInputValidator(support));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(nameText.getWidget());\r
+        \r
+        Label label = new Label(composite, SWT.NONE);\r
+               label.setText("Replaceable enumerations");\r
+               enumerationRedeclarationExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                               "displaySelectors", "displayFilter").values(false, false), site, composite, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);\r
+               \r
+               enumerationRedeclarationExplorer\r
+               .setBrowseContexts(SysdynResource.URIs.EnumerationReplacement);\r
+               enumerationRedeclarationExplorer.setColumns(ColumnKeys.ENUMERATION_REDECLARATION_COLUMNS);\r
+               enumerationRedeclarationExplorer.setInputSource(new SingleSelectionInputSource(\r
+                               Resource.class));\r
+\r
+               enumerationRedeclarationExplorer.finish();\r
+\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                               enumerationRedeclarationExplorer);\r
+               \r
+               Control c = enumerationRedeclarationExplorer.getExplorerControl();\r
+               if (c instanceof Tree)\r
+                       ((Tree) c).setLinesVisible(true);\r
+        \r
+    }\r
+    \r
+    \r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               enumerationRedeclarationExplorer.setInput(context, input);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleTypeTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ModuleTypeTab.java
new file mode 100644 (file)
index 0000000..918dafd
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.ModuleTypeNameInputValidator;\r
+\r
+public class ModuleTypeTab extends LabelPropertyTabContributor {\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(6).applyTo(composite);\r
+        TrackedText nameText = new TrackedText(composite, support, SWT.BORDER);\r
+        nameText.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName));\r
+        nameText.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasName));\r
+        nameText.setInputValidator(new ModuleTypeNameInputValidator(support));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(nameText.getWidget());\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/PlaybackExperimentTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/PlaybackExperimentTab.java
new file mode 100644 (file)
index 0000000..a1038bc
--- /dev/null
@@ -0,0 +1,211 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.graphics.Image;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.utils.datastructures.Triple;\r
+import org.simantics.utils.ui.color.Color;\r
+import org.simantics.utils.ui.color.ColorGradient;\r
+import org.simantics.utils.ui.color.ColorValue;\r
+\r
+public class PlaybackExperimentTab extends LabelPropertyTabContributor {\r
+\r
+    private static int gradientWidth = 250;\r
+    private static int gradientHeight = 20;\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+\r
+        Group gradientGroup = new Group(composite, SWT.NONE);\r
+        gradientGroup.setText("Color scale");\r
+        GridDataFactory.fillDefaults().applyTo(gradientGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(gradientGroup);\r
+\r
+\r
+        ColorValue cv1 = new ColorValue(new Color(0, 62, 133), 0.0);\r
+        ColorValue cv2 = new ColorValue(new Color(255, 230, 0), 1.0);\r
+        ColorValue[] values = new ColorValue[] {cv1, cv2};\r
+        ColorGradient cg = new ColorGradient(values, ColorGradient.HSV);\r
+        Image image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        Button b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+\r
+        cv1 = new ColorValue(new Color(255, 230, 0), 0.0);\r
+        cv2 = new ColorValue(new Color(0, 62, 133), 1.0);\r
+        values = new ColorValue[] {cv1, cv2};\r
+        cg = new ColorGradient(values, ColorGradient.HSV);\r
+        image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+        \r
+        cv1 = new ColorValue(new Color(0, 0, 0), 0.0);\r
+        cv2 = new ColorValue(new Color(255, 255, 255), 1.0);\r
+        values = new ColorValue[] {cv1, cv2};\r
+        cg = new ColorGradient(values, ColorGradient.HSV);\r
+        image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+        \r
+        cv1 = new ColorValue(new Color(0, 0, 255), 0.0);\r
+        cv2 = new ColorValue(new Color(255, 0, 0), 1.0);\r
+        values = new ColorValue[] {cv1, cv2};\r
+        cg = new ColorGradient(values, ColorGradient.HSV);\r
+        image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+        \r
+      \r
+        cv1 = new ColorValue(new Color(255, 0, 0), 0.0);\r
+        cv2 = new ColorValue(new Color(0, 0, 255), 1.0);\r
+        values = new ColorValue[] {cv1, cv2};\r
+        cg = new ColorGradient(values, ColorGradient.HSV);\r
+        image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+    }\r
+\r
+\r
+    class GradientSelectionListener extends SelectionListenerImpl<Resource> {\r
+        private ArrayList<ColorValue> colorValues;\r
+\r
+        public GradientSelectionListener(ISessionContext context, ColorValue[] colorValues) {\r
+            super(context);\r
+            this.colorValues = new ArrayList<ColorValue>();\r
+            for(ColorValue cv : colorValues)\r
+                this.colorValues.add(cv);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource experiment) throws DatabaseException {\r
+            G2DResource g2d = G2DResource.getInstance(graph);\r
+\r
+            Resource gradient = graph.getPossibleObject(experiment, g2d.HasColorGradient);\r
+\r
+            if(gradient != null) {\r
+                graph.denyStatement(experiment, g2d.HasColorGradient, gradient);\r
+                RemoverUtil.remove(graph, gradient);\r
+            }\r
+\r
+            gradient = GraphUtils.create2(graph, g2d.ColorGradient);\r
+            graph.claim(experiment, g2d.HasColorGradient, gradient);\r
+\r
+            for(ColorValue cv : colorValues) {\r
+                Resource placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
+                        g2d.HasGradientPosition, cv.getValue());\r
+                graph.claimLiteral(placement, g2d.HasColor, g2d.Color, cv.getColor().getAWTColor().getColorComponents(new float[4]));\r
+                graph.claim(gradient, g2d.HasColorPlacement, placement);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    class GradientSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        private ArrayList<ColorValue> colorValues;\r
+\r
+        public GradientSelectionFactory(ColorValue[] colorValues) {\r
+            this.colorValues = new ArrayList<ColorValue>();\r
+            for(ColorValue cv : colorValues)\r
+                this.colorValues.add(cv);\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, colorValues, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource experiment) throws DatabaseException {\r
+            G2DResource g2d = G2DResource.getInstance(graph);\r
+            Resource gradient = graph.getPossibleObject(experiment, g2d.HasColorGradient);\r
+            if(gradient == null) {\r
+                return Boolean.FALSE;\r
+            }\r
+            Collection<Resource> placements =  graph.syncRequest(new ObjectsWithType(gradient, g2d.HasColorPlacement, g2d.ColorPlacement));\r
+            if(placements.isEmpty())\r
+                return Boolean.FALSE;\r
+            \r
+            for(Resource placement : placements) {\r
+                Double position = graph.getPossibleRelatedValue(placement, g2d.HasGradientPosition);\r
+                if(position == null) \r
+                    return Boolean.FALSE;\r
+                int index = -1;\r
+                \r
+                // First look for a color with matching value\r
+                for(int i = 0; i < colorValues.size(); i++) {\r
+                    if(position.equals(colorValues.get(i).getValue())) {\r
+                        \r
+                        index = i;\r
+                        break;\r
+                    }\r
+                }\r
+                \r
+                // If matching value was found, see if the color is the same\r
+                if(index >= 0) {\r
+                    Color c = colorValues.get(index).getColor();\r
+                    float[] cArray = c.getAWTColor().getColorComponents(new float[4]);\r
+                    float[] color = graph.getPossibleRelatedValue(placement, g2d.HasColor, Bindings.FLOAT_ARRAY);\r
+                    for(int i = 0; i < color.length; i++) {\r
+                        if(cArray[i] != color[i])\r
+                            // Some inconsistency found in colors, return false\r
+                            return Boolean.FALSE;\r
+                    }\r
+                }\r
+            }\r
+            \r
+            // Everything matched\r
+            return Boolean.TRUE;\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ReferenceDependencyTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ReferenceDependencyTab.java
new file mode 100644 (file)
index 0000000..55c4ce9
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+\r
+public class ReferenceDependencyTab extends LabelPropertyTabContributor {\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/RemoveFocusBeforeExperimentComposite.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/RemoveFocusBeforeExperimentComposite.java
new file mode 100644 (file)
index 0000000..1966ecc
--- /dev/null
@@ -0,0 +1,29 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
+\r
+/**\r
+ * Composite for providing info for {@link HandlerUtils}.saveBeforeExperimentRun to force focus\r
+ * of text and other widgets before simulation. Forcing focus off makes the widget to save its value. \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class RemoveFocusBeforeExperimentComposite extends Composite {\r
+\r
+    public RemoveFocusBeforeExperimentComposite(Composite parent, int style) {\r
+        super(parent, style);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ResourceSelectionProcessor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ResourceSelectionProcessor.java
new file mode 100644 (file)
index 0000000..49407d6
--- /dev/null
@@ -0,0 +1,542 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.model.nodetypes.NodeType;\r
+import org.simantics.browsing.ui.model.nodetypes.SpecialNodeType;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.layer0.request.PossibleActiveVariableFromVariable;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.jfreechart.ChartSelectionTabContributor;\r
+import org.simantics.jfreechart.chart.properties.ChartTab;\r
+import org.simantics.jfreechart.chart.properties.xyline.XYLineGeneralPropertiesTab;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.ui.property.svg.SVGElementComposite;\r
+import org.simantics.selectionview.ComparableTabContributor;\r
+import org.simantics.selectionview.SelectionProcessor;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder;\r
+import org.simantics.sysdyn.ui.trend.SensitivityChartAxisAndVariablesTab;\r
+import org.simantics.ui.selection.AnyVariable;\r
+import org.simantics.ui.selection.WorkbenchSelectionElement;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * SelectionProcessor for processing selections for property view in system dynamics\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ResourceSelectionProcessor implements SelectionProcessor<Object, ReadGraph>  {\r
+\r
+    private SpecialNodeType sharedFunctionsTestNode;\r
+\r
+    @Override\r
+    public Collection<?> process(Object selection, ReadGraph backend) {\r
+        List<ComparableTabContributor> tabs = new ArrayList<ComparableTabContributor>();\r
+        SysdynResource sr = SysdynResource.getInstance(backend);\r
+        DiagramResource dr = DiagramResource.getInstance(backend);\r
+        ModelingResources mr = ModelingResources.getInstance(backend);\r
+        SimulationResource simu = SimulationResource.getInstance(backend);\r
+//        JFreeChartResource jfree = JFreeChartResource.getInstance(backend);\r
+\r
+        // Test nodes\r
+        if(sharedFunctionsTestNode == null)\r
+            sharedFunctionsTestNode = new SpecialNodeType(sr.ModelingBrowseContext_SharedFunctionsFolder, Resource.class);\r
+\r
+        try {\r
+            // Many elements \r
+            if (selection instanceof ArrayList<?> && ((ArrayList<?>) selection).size() > 1) {\r
+               List<Resource> variables = new ArrayList<Resource>();\r
+               List<Resource> dependencies = new ArrayList<Resource>();\r
+               List<Resource> flows = new ArrayList<Resource>();\r
+                Resource model = null;\r
+                for(Object o : (ArrayList<?>)selection) {\r
+                    Resource r = AdaptionUtils.adaptToSingle(o, Resource.class);\r
+                    if (r == null)\r
+                       continue;\r
+                    Resource component = backend.getPossibleObject(r, mr.ElementToComponent);\r
+                    if (component != null) {\r
+                        r = component;\r
+                    } else {\r
+                       // Try connection\r
+                        Resource connection = backend.getPossibleObject(r, mr.DiagramConnectionToConnection);\r
+                        if(connection != null)\r
+                            r = connection;\r
+                    }\r
+                    \r
+                    if(r != null) {\r
+                        if(model == null)\r
+                            model = backend.getPossibleObject(r, Layer0.getInstance(backend).PartOf);\r
+                        if(model != null && model.equals( backend.getSingleObject(r, Layer0.getInstance(backend).PartOf))) {\r
+                               if (backend.isInstanceOf(r, sr.Variable)) {\r
+                                       variables.add(r);\r
+                               } else if (backend.isInstanceOf(r, sr.Dependency)) {\r
+                                       Resource diaConnection = backend.getPossibleObject(r, ModelingResources.getInstance(backend).ConnectionToDiagramConnection);\r
+                                       dependencies.add(diaConnection);\r
+                               } else if (backend.isInstanceOf(r, sr.Flow)) {\r
+                                       Resource diaConnection = backend.getPossibleObject(r, ModelingResources.getInstance(backend).ConnectionToDiagramConnection);\r
+                                       flows.add(diaConnection);\r
+                               }\r
+                        }\r
+                    }\r
+                }\r
+                \r
+                if (!variables.isEmpty())\r
+                       // Do we have at least one variable\r
+                       tabs.add(new ComparableTabContributor(\r
+                               new ArrayIndexesTab(),\r
+                               1,\r
+                               variables,\r
+                               "Indexes"));\r
+                else if (!dependencies.isEmpty()) {\r
+                    // Dependencies only\r
+                       tabs.add(new ComparableTabContributor(\r
+                            new ArrayDependencyTab(),\r
+                            1,\r
+                            dependencies,\r
+                            "Dependency Properties"));\r
+                }\r
+                else if (!flows.isEmpty()) {\r
+                    // Flows only\r
+                       tabs.add(new ComparableTabContributor(\r
+                            new ArrayFlowTab(),\r
+                            1,\r
+                            flows,\r
+                            "Flow Properties"));\r
+                }\r
+                return tabs;\r
+            }\r
+\r
+            // Single element\r
+            Variable var = null; \r
+            WorkbenchSelectionElement wse = ISelectionUtils.filterSingleSelection(selection, WorkbenchSelectionElement.class);\r
+            if(wse != null) {\r
+                var = wse.getContent(new AnyVariable(backend));\r
+                if(var == null) {\r
+                    var = AdaptionUtils.adaptToSingle(selection, Variable.class);\r
+                    if(var != null) {\r
+                        Variable possibleActiveVariable = backend.syncRequest(new PossibleActiveVariableFromVariable(var));\r
+                        if(possibleActiveVariable != null)\r
+                            var = possibleActiveVariable;\r
+                    }\r
+                }\r
+            }\r
+\r
+            Resource r = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
+            if(r == null) {\r
+                // Selection is not directly a resource, try if it is a variable \r
+                var = AdaptionUtils.adaptToSingle(selection, Variable.class);\r
+                if(var != null)\r
+                    r = var.getRepresents(backend);\r
+            }\r
+            \r
+            if(r == null) {\r
+                // SharedFunctionsFolder has properties but no adapted resource\r
+                SharedFunctionsFolder sff = AdaptionUtils.adaptToSingle(selection, SharedFunctionsFolder.class);\r
+                if (sff != null) {\r
+                    return Collections.singleton(new ComparableTabContributor(\r
+                            new SharedFunctionLibrariesTab(),\r
+                            2,\r
+                            sff.data,\r
+                            "Shared Functions"));\r
+                }\r
+\r
+                return Collections.emptyList();\r
+            }\r
+\r
+            NodeContext nc = AdaptionUtils.adaptToSingle(selection, NodeContext.class);\r
+            if(nc != null) {\r
+                NodeType type = nc.getConstant(NodeType.TYPE);\r
+                if(type != null && type.equals(sharedFunctionsTestNode)) {\r
+                    return Collections.singleton(new ComparableTabContributor(\r
+                            new SharedFunctionLibrariesTab(),\r
+                            2,\r
+                            r,\r
+                            "Shared Functions"));\r
+                }\r
+            }\r
+\r
+            // SVG elements in symbol editor\r
+            if (backend.isInstanceOf(r, dr.SVGElement))\r
+                return Collections.singleton(SVGElementComposite.make(r, 1, "SVG"));\r
+\r
+            // if r == diagram element, change it to component\r
+            if (backend.isInstanceOf(r, dr.Element)) {\r
+                Resource component = backend.getPossibleObject(r, mr.ElementToComponent);\r
+                if (component != null) {\r
+                    r = component;\r
+                } else {\r
+                    Resource connection = backend.getPossibleObject(r, mr.DiagramConnectionToConnection);\r
+                    if(connection != null)\r
+                        r = connection;\r
+                }\r
+            }\r
+            \r
+            \r
+            // Check that var has found the correct variable\r
+            if(r != null && var != null) {\r
+                if(!r.equals(var.getRepresents(backend)))\r
+                    // Var found the wrong variable. This may happen with ModuleType editors\r
+                    var = null;\r
+            }\r
+            \r
+            \r
+            // If shadow variable, display properties of the original variable\r
+            if(backend.isInstanceOf(r, sr.Shadow)) {\r
+                Resource original = backend.getPossibleObject(r, sr.Shadow_original);\r
+                if(original != null && var != null) {\r
+                    r = original;\r
+                    Variable parent = var.getParent(backend);\r
+                    var = parent.getPossibleChild(backend, NameUtils.getSafeName(backend, r));\r
+                }\r
+            }\r
+\r
+            // If loop\r
+            if(backend.isInstanceOf(r, sr.Loop)) {\r
+               return Collections.singleton(\r
+                               (new ComparableTabContributor(\r
+                               new LoopTab(),\r
+                               1,\r
+                               r,\r
+                               "Loop")));\r
+            }\r
+\r
+            // Independent variable\r
+            if (backend.isInstanceOf(r, sr.IndependentVariable)) {\r
+                Resource activeExpression = backend.getPossibleObject(r, sr.IndependentVariable_activeExpression);\r
+                Resource expression = null;\r
+                if(activeExpression != null)\r
+                    // if variable has active expression, display it\r
+                    expression = activeExpression;\r
+                else if (backend.hasStatement(r, sr.Variable_expressionList)){\r
+                    // else display the first expression of the variable\r
+                    Resource expressions = backend.getPossibleObject(r, sr.Variable_expressionList);\r
+                    List<Resource> expressionList = ListUtils.toList(backend, expressions);\r
+                    if(expressionList.isEmpty()) {\r
+                        System.err.println("expressionList is empty for " + r);\r
+                        return Collections.emptyList();\r
+                    }\r
+                    expression = expressionList.get(0);\r
+                }\r
+                tabs.add(new ComparableTabContributor(\r
+                        new EquationTab(),\r
+                        3,\r
+                        var != null ? var : r,\r
+                        "Equation"));\r
+                if(expression != null && backend.isInstanceOf(expression, sr.WithLookupExpression)) {\r
+                    // WithLookupExpression has its own extra tab for visual configuration\r
+                    tabs.add(new ComparableTabContributor(\r
+                            new LookupTableTab(),\r
+                            2,\r
+                            expression,\r
+                            "Lookup Table"));\r
+                }\r
+\r
+                tabs.add(new ComparableTabContributor(\r
+                        new ArrayIndexesTab(),\r
+                        1,\r
+                        r,\r
+                        "Indexes"));\r
+\r
+                tabs.add(new ComparableTabContributor(\r
+                        new VariableInformationTab(),\r
+                        0,\r
+                        r,\r
+                        "Additional Information"));\r
+                return tabs;\r
+            }\r
+\r
+            // Input variable\r
+            if (backend.isInstanceOf(r, sr.Input)) {\r
+                tabs.add(new ComparableTabContributor(\r
+                        new InputVariableTab(),\r
+                        2,\r
+                        r,\r
+                        "Input"));\r
+\r
+                tabs.add(new ComparableTabContributor(\r
+                        new ArrayIndexesTab(),\r
+                        1,\r
+                        r,\r
+                        "Indexes"));\r
+\r
+                tabs.add(new ComparableTabContributor(\r
+                        new VariableInformationTab(),\r
+                        0,\r
+                        r,\r
+                        "Additional Information"));\r
+                return tabs;\r
+            }\r
+\r
+            // Enumeration\r
+            if (backend.isInstanceOf(r, sr.Enumeration)) {\r
+                Object s = AdaptionUtils.adaptToSingle(selection, ISelection.class);\r
+                if(s == null)\r
+                    s = r;\r
+                // give either variable or the actual resource\r
+                return Collections.singleton(new ComparableTabContributor(\r
+                        new EnumerationTab(),\r
+                        2,\r
+                        s,\r
+                        "Enumeration"));\r
+            }\r
+\r
+            // Configuration and model. They both show the properties of the configuration\r
+            if ( backend.isInstanceOf(r, sr.Configuration) || backend.isInstanceOf(r, sr.SysdynModel)) {\r
+                if(!backend.isInstanceOf(r, sr.SysdynModel))\r
+                    r = backend.getPossibleObject(r, SimulationResource.getInstance(backend).IsConfigurationOf);\r
+                if (r != null)\r
+                    return Collections.singleton(\r
+                            new ComparableTabContributor(\r
+                                    new ConfigurationTab(),\r
+                                    0,\r
+                                    r,\r
+                                    "Model Properties"));\r
+            }\r
+\r
+            // Module\r
+            if (backend.isInstanceOf(r, sr.Module)){\r
+                tabs.add(new ComparableTabContributor(\r
+                        new ModuleTab(),\r
+                        10,\r
+                        r,\r
+                        "Module Properties"));\r
+                tabs.add(new ComparableTabContributor(\r
+                        new ModuleParameterTab(),\r
+                        9,\r
+                        r,\r
+                        "Parameters"));\r
+                tabs.add(new ComparableTabContributor(\r
+                        new ModuleInputTab(),\r
+                        2,\r
+                        r,\r
+                        "Inputs"));\r
+                tabs.add(new ComparableTabContributor(\r
+                        new ModuleOutputTab(),\r
+                        1,\r
+                        r,\r
+                        "Outputs"));\r
+                return tabs;\r
+            }\r
+\r
+            // Playback experiment\r
+            if (backend.isInstanceOf(r, sr.PlaybackExperiment))\r
+                return Collections.singleton(\r
+                        new ComparableTabContributor(\r
+                                new PlaybackExperimentTab(),\r
+                                0,\r
+                                r,\r
+                                "Experiment Properties"));\r
+\r
+         // Game experiment\r
+            if (backend.isInstanceOf(r, sr.GameExperiment))\r
+                return Collections.singleton(\r
+                        new ComparableTabContributor(\r
+                                new GameExperimentTab(),\r
+                                0,\r
+                                r,\r
+                                "Experiment Properties"));\r
+\r
+         // Sensitivity analysis experiment\r
+            if (backend.isInstanceOf(r, sr.SensitivityAnalysisExperiment))\r
+                return Collections.singleton(\r
+                        new ComparableTabContributor(\r
+                                new SensitivityAnalysisExperimentTab(),\r
+                                0,\r
+                                r,\r
+                                "Experiment Properties"));\r
+\r
+         // Default experiment\r
+            if (backend.isInstanceOf(r, simu.Experiment))\r
+                return Collections.singleton(\r
+                        new ComparableTabContributor(\r
+                                new ExperimentTab(),\r
+                                0,\r
+                                r,\r
+                                "Experiment Properties"));\r
+\r
+            // History data\r
+            if (backend.isInstanceOf(r, sr.HistoryDataset))\r
+                return Collections.singleton(\r
+                        new ComparableTabContributor(\r
+                                new HistoryDataTab(),\r
+                                0,\r
+                                r,\r
+                                "History Data Properties"));\r
+\r
+            // Saved simulation result\r
+            if (backend.isInstanceOf(r, sr.Result))\r
+                return Collections.singleton(\r
+                        new ComparableTabContributor(\r
+                                new ResultTab(),\r
+                                0,\r
+                                r,\r
+                                "Result Properties"));\r
+\r
+            // Dependency\r
+            if (backend.isInstanceOf(r, sr.Dependency))\r
+                if (backend.hasStatement(r, sr.Dependency_refersTo)) {\r
+                    Resource diaConnection = backend.getPossibleObject(r, ModelingResources.getInstance(backend).ConnectionToDiagramConnection);\r
+                    return Collections.singleton(\r
+                            new ComparableTabContributor(\r
+                                    new DependencyTab(),\r
+                                    0,\r
+                                    diaConnection,\r
+                                    "Reference Properties"));\r
+                } else {\r
+                    Resource diaConnection = backend.getPossibleObject(r, ModelingResources.getInstance(backend).ConnectionToDiagramConnection);\r
+                    return Collections.singleton(\r
+                            new ComparableTabContributor(\r
+                                    new DependencyTab(),\r
+                                    0,\r
+                                    diaConnection,\r
+                                    "Dependency Properties"));\r
+                }\r
+\r
+            // Flow\r
+            if (backend.isInstanceOf(r, sr.Flow)) {\r
+               Resource diaConnection = backend.getPossibleObject(r, ModelingResources.getInstance(backend).ConnectionToDiagramConnection);\r
+               return Collections.singleton(\r
+                       new ComparableTabContributor(\r
+                                       new FlowTab(),\r
+                                       0,\r
+                                       diaConnection,\r
+                                       "Flow Properties"));\r
+            }\r
+\r
+            // Module symbol. Modules in modules-folder are actually symbol resources\r
+            if (backend.isInheritedFrom(r, sr.ModuleSymbol)) {\r
+                // Find the component resource\r
+                r =  backend.getPossibleObject(r, mr.SymbolToComponentType);\r
+                if(r != null)\r
+                    return Collections.singleton(\r
+                            new ComparableTabContributor(\r
+                                    new ModuleTypeTab(),\r
+                                    0,\r
+                                    r,\r
+                                    "Module Type Properties"));\r
+            }\r
+\r
+            // Function\r
+            if (backend.isInstanceOf(r, sr.SysdynModelicaFunction)) {\r
+                tabs.add(new ComparableTabContributor(\r
+                        new FunctionTab(),\r
+                        2,\r
+                        r,\r
+                        "Function"));\r
+                tabs.add(new ComparableTabContributor(\r
+                        new ExternalFilesTab(),\r
+                        1,\r
+                        r,\r
+                        "External files"));\r
+                return tabs;\r
+            }\r
+\r
+            // Function library\r
+            if (backend.isInstanceOf(r, sr.SysdynModelicaFunctionLibrary)) {\r
+                Object s = AdaptionUtils.adaptToSingle(selection, ISelection.class);\r
+                if(s == null)\r
+                    s = r;\r
+                // give either variable or the actual resource\r
+                return Collections.singleton(new ComparableTabContributor(\r
+                        new FunctionLibraryTab(),\r
+                        2,\r
+                        s,\r
+                        "Function library"));\r
+            }\r
+            \r
+            // Try sensitivity chart before other charts\r
+            if (contributeSensitivityChart(backend, r, tabs)) {\r
+                return tabs;\r
+            }\r
+            \r
+            // Try normal charts\r
+            if (ChartSelectionTabContributor.contibuteTabs(backend, r, tabs)) {\r
+               return tabs;\r
+            }\r
+\r
+            // Default experiment\r
+            if (backend.isInstanceOf(r, sr.AdditionalSymbols_MultilineText))\r
+                return Collections.singleton(\r
+                        new ComparableTabContributor(\r
+                                new CommentTab(),\r
+                                0,\r
+                                r,\r
+                                "Comment"));\r
+\r
+        } catch (ServiceException e) {\r
+            e.printStackTrace();\r
+        } catch (ManyObjectsForFunctionalRelationException e) {\r
+            e.printStackTrace();\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return Collections.emptyList();\r
+    }\r
+    \r
+    public static boolean contributeSensitivityChart(ReadGraph backend, Resource r, List<ComparableTabContributor> tabs) throws DatabaseException {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(backend);\r
+        if(backend.isInstanceOf(r, jfree.ChartElement)) {\r
+            if(backend.hasStatement(r, jfree.ChartElement_component))\r
+                r = backend.getSingleObject(r, jfree.ChartElement_component);\r
+        }\r
+\r
+        if (backend.isInstanceOf(r, jfree.Chart)) {\r
+\r
+            Collection<Resource> plots = backend.syncRequest(new ObjectsWithType(r, Layer0.getInstance(backend).ConsistsOf, jfree.Plot));\r
+            if(!plots.isEmpty()) {\r
+                Resource plot = plots.iterator().next();\r
+\r
+                if(backend.isInstanceOf(plot, SysdynResource.getInstance(backend).Charts_SensitivityPlot)) {\r
+                    tabs.add(new ComparableTabContributor(\r
+                            new XYLineGeneralPropertiesTab(),\r
+                            10,\r
+                            r,\r
+                            "General"));\r
+                    tabs.add(new ComparableTabContributor(\r
+                            new SensitivityChartAxisAndVariablesTab(),\r
+                            9,\r
+                            r,\r
+                            "Axis and Variables"));\r
+                    tabs.add(new ComparableTabContributor(\r
+                            new ChartTab(),\r
+                            1,\r
+                            r,\r
+                            "Chart"));\r
+                    return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ResultTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ResultTab.java
new file mode 100644 (file)
index 0000000..fee1f4c
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+\r
+public class ResultTab extends LabelPropertyTabContributor {\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SensitivityAnalysisExperimentTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SensitivityAnalysisExperimentTab.java
new file mode 100644 (file)
index 0000000..ee1a455
--- /dev/null
@@ -0,0 +1,643 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.core.runtime.IAdaptable;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.events.DisposeEvent;\r
+import org.eclipse.swt.events.DisposeListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Listener;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.swt.widgets.TreeItem;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.BuiltinKeys;\r
+import org.simantics.browsing.ui.Column;\r
+import org.simantics.browsing.ui.Column.Align;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.common.NodeContextBuilder.MapNodeContext;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.procedure.adapter.DisposableListener;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.jfreechart.chart.properties.RangeComposite;\r
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.IntegerPropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.IntegerPropertyModifier;\r
+import org.simantics.sysdyn.ui.properties.widgets.sensitivity.DistributionPropertyWidget;\r
+import org.simantics.sysdyn.ui.properties.widgets.sensitivity.ParameterChildRule;\r
+import org.simantics.sysdyn.ui.properties.widgets.sensitivity.VariableNameModifier;\r
+import org.simantics.sysdyn.ui.validation.ParameterExistsValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.RunnableWithObject;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.validators.IntegerValidator;\r
+\r
+/**\r
+ * Tab for displaying sensitivity analysis experiment properties\r
+ * \r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SensitivityAnalysisExperimentTab extends AdjustableTab implements Widget {\r
+\r
+    private GraphExplorerComposite explorer;\r
+    private WidgetSupportImpl parameterSupport = new WidgetSupportImpl();\r
+    private ScrolledComposite propertyContainer;\r
+    private Composite parameterProperties;\r
+    private Composite content;\r
+    private Button remove;\r
+    private Resource experiment;\r
+    \r
+    private boolean dirty = false;\r
+    private boolean dirtyMethod = false;\r
+    \r
+    private DisposableListener<Collection<Resource>> contentListener;\r
+       private Composite labelComposite;\r
+       private Label labelName;\r
+       private Label labelNumber;\r
+       private Label labelMethod;\r
+       private TrackedCombo methodSelector;\r
+       private Label labelSeed;\r
+       private TrackedText seed;\r
+       private Tree tree;\r
+       private Composite buttonComposite;\r
+       private Group parameterPropertyGroup;\r
+       private Label labelVariable;\r
+       private TrackedText variable;\r
+       private Label labelRange;\r
+       private RangeComposite rangeComposite;\r
+       private Label labelDistribution;\r
+       private TrackedCombo distributionSelector;\r
+       private DistributionPropertyWidget dpw;\r
+       private TrackedText name;\r
+       private TrackedText n;\r
+       private Button addVariable;\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site,\r
+            final ISessionContext context, final WidgetSupport support) {\r
+        support.register(this);\r
+        super.createControls(body, site, context, support);\r
+    }\r
+\r
+    /**\r
+     * Updates the content of propertyContainer  \r
+     * @param context\r
+     */\r
+    private void updateSelection(ISessionContext context) {\r
+        ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
+        IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
+        parameterSupport.fireInput(context, selection);\r
+\r
+        propertyContainer.setContent(content);\r
+        Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        propertyContainer.setMinSize(size);\r
+    }\r
+\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        experiment = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        if(contentListener == null) {\r
+            contentListener = new DisposableListener<Collection<Resource>>() {\r
+\r
+                @Override\r
+                public void execute(Collection<Resource> result) {\r
+                    if(remove != null && !remove.getWidget().isDisposed() && result != null) {\r
+                        remove.getWidget().getDisplay().asyncExec(new RunnableWithObject(result) {\r
+                            @Override\r
+                            public void run() {\r
+                                if(!remove.getWidget().isDisposed()) {\r
+                                    @SuppressWarnings("unchecked")\r
+                                    Collection<Resource> result = (Collection<Resource>) getObject();\r
+                                    if(result.size() > 1)\r
+                                        remove.getWidget().setEnabled(true);\r
+                                    else\r
+                                        remove.getWidget().setEnabled(false);\r
+                                }\r
+                            }\r
+                        });\r
+\r
+                    }\r
+                }\r
+\r
+                @Override\r
+                public void exception(Throwable t) {\r
+                    t.printStackTrace();\r
+                }\r
+            };\r
+\r
+            SimanticsUI.getSession().asyncRequest(new Read<Collection<Resource>> () {\r
+\r
+                @SuppressWarnings("unchecked")\r
+                @Override\r
+                public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                    return (Collection<Resource>) new ParameterChildRule().getChildren(graph, experiment);\r
+                }\r
+\r
+            }, contentListener);\r
+        }\r
+\r
+    }\r
+\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       final ISessionContext context, final WidgetSupport support) {\r
+\r
+        composite = new RemoveFocusBeforeExperimentComposite(body, SWT.NONE);\r
+        \r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
+        propertyContainer.setExpandHorizontal(true);\r
+        propertyContainer.setExpandVertical(true);\r
+        \r
+        content = new Composite(propertyContainer, SWT.NONE);\r
+\r
+        // Label\r
+        labelComposite = new Composite(content, SWT.NONE);\r
+        labelName = new Label(labelComposite, SWT.NONE);\r
+        labelName.setText("Name");\r
+\r
+        name = new TrackedText(labelComposite, support, SWT.BORDER);\r
+        name.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));\r
+        name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
+        name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasName));\r
+        name.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), name.getWidget())));\r
+        \r
+        labelNumber = new Label(labelComposite, SWT.NONE);\r
+        labelNumber.setText("Number of runs");\r
+        \r
+        n = new TrackedText(labelComposite, support, SWT.BORDER);\r
+        n.setTextFactory(new IntegerPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_numberOfValues));\r
+        n.addModifyListener(new IntegerPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_numberOfValues));\r
+        n.setInputValidator(new IntegerValidator());\r
+        n.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), n.getWidget())));\r
+        \r
+        labelMethod = new Label(labelComposite, SWT.NONE);\r
+        labelMethod.setText("Method");\r
+        \r
+        methodSelector = new TrackedCombo(labelComposite, support, SWT.DROP_DOWN);\r
+        methodSelector.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+            @Override\r
+            public Map<String, Object> perform(ReadGraph graph, Resource input) throws DatabaseException {\r
+                SysdynResource SR = SysdynResource.getInstance(graph);\r
+                Map<String, Object> items = new HashMap<String, Object>();\r
+\r
+                items.put("Halton", SR.HaltonSequenceGenerator);\r
+                items.put("Random", SR.RandomGenerator);\r
+                \r
+                return items;\r
+            }\r
+\r
+        });\r
+        methodSelector.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph, Resource parameter) throws DatabaseException {\r
+                SysdynResource SR = SysdynResource.getInstance(graph);\r
+                Resource method = graph.getPossibleObject(parameter, SR.SensitivityAnalysisExperiment_method);\r
+                if(method == null)\r
+                    return null;\r
+                \r
+                if(graph.isInstanceOf(method, SR.RandomGenerator))\r
+                    return "Random";\r
+                else if(graph.isInstanceOf(method, SR.HaltonSequenceGenerator))\r
+                    return "Halton";\r
+                else\r
+                    return "";\r
+\r
+            }\r
+        });\r
+        methodSelector.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
+\r
+            @Override\r
+            public void applyText(WriteGraph graph, Resource input, String text)\r
+                    throws DatabaseException {\r
+                if(text == null || text.isEmpty())\r
+                    return;\r
+\r
+                SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+                Resource type = SR.RandomGenerator;\r
+\r
+                if("Halton".equals(text))\r
+                    type = SR.HaltonSequenceGenerator;\r
+                \r
+                graph.deny(input, SR.SensitivityAnalysisExperiment_method);\r
+\r
+                GraphUtils.create2(graph, type,\r
+                        SR.SensitivityAnalysisExperiment_method_Inverse, input);\r
+\r
+                dirtyMethod = true;\r
+            }\r
+        });\r
+        methodSelector.addModifyListener(new TextModifyListener() {\r
+\r
+            @Override\r
+            public void modifyText(TrackedModifyEvent e) {\r
+                if(dirtyMethod) {\r
+                    support.update();\r
+                    dirtyMethod = false;\r
+                    propertyContainer.setContent(content);\r
+                    Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+                    propertyContainer.setMinSize(size);\r
+                }\r
+            }\r
+        });\r
+        \r
+        labelSeed = new Label(labelComposite, SWT.NONE);\r
+        labelSeed.setText("Seed");\r
+        \r
+        seed = new TrackedText(labelComposite, support, SWT.BORDER);\r
+        seed.setTextFactory(new IntegerPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_randomSeed));\r
+        seed.addModifyListener(new IntegerPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_randomSeed));\r
+        seed.setInputValidator(new IntegerValidator());\r
+        seed.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), seed.getWidget())));\r
+\r
+        // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis\r
+        explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter", "treeView").values(false, false, true), site, content, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
+        \r
+        explorer.setBrowseContexts(SysdynResource.URIs.SensitivityAnalysisExperiment_ParameterBrowseContext);\r
+        explorer.setInputSource(new SingleSelectionInputSource(\r
+                Resource.class));\r
+        explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
+        explorer.setColumns( new Column[] { new Column(ColumnKeys.SINGLE, Align.LEFT, 0, "", true) });\r
+        explorer.finish();\r
+        \r
+        \r
+        ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
+            public void widgetSelected(SelectionEvent e) {\r
+                updateSelection(context);\r
+            }\r
+        });\r
+\r
+        /* Listener for displaying information of the first parameter during view initialization\r
+         * The view does not have focus, so normal selection listener mechanisms do not work. \r
+         * Need to do it the hard way. \r
+         */ \r
+        Listener listener = new Listener() {\r
+\r
+            boolean flag = false;\r
+            @Override\r
+            public void handleEvent(Event event) {\r
+                switch (event.type) {\r
+                    case SWT.Activate:\r
+                    case SWT.Show:\r
+                    case SWT.Paint:\r
+                    {\r
+                        if(!flag && ((Tree) event.widget).getItems().length > 0) {\r
+                            flag = true;\r
+                            TreeItem item = ((Tree) event.widget).getItems()[0];\r
+                            IAdaptable adaptable = (IAdaptable) item.getData();\r
+                            MapNodeContext nc = (MapNodeContext) adaptable.getAdapter(NodeContext.class);\r
+                            parameterSupport.fireInput(context, new StructuredSelection(nc.getConstant(BuiltinKeys.INPUT)));\r
+                            propertyContainer.setContent(content);\r
+                            Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+                            propertyContainer.setMinSize(size);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        };\r
+\r
+        tree = explorer.getExplorerControl();\r
+        tree.addListener(SWT.Activate, listener);\r
+        tree.addListener(SWT.Show, listener);\r
+        tree.addListener(SWT.Paint,listener);\r
+        /* End listener for displaying information for first parameter during view initialization*/\r
+        \r
+        explorer.addDisposeListener(new DisposeListener() {\r
+            \r
+            @Override\r
+            public void widgetDisposed(DisposeEvent e) {\r
+                if(contentListener != null)\r
+                    contentListener.dispose();              \r
+            }\r
+        });\r
+        \r
+        \r
+        buttonComposite = new Composite(explorer, SWT.NONE);\r
+        \r
+        addVariable = new Button(buttonComposite, support, SWT.NONE);\r
+        addVariable.setText("Add parameter");\r
+        addVariable.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                Layer0 L0 = Layer0.getInstance(graph);\r
+                \r
+                Resource distribution = GraphUtils.create2(graph, sr.UniformDistribution,\r
+                        sr.UniformDistribution_minValue, 0.0,\r
+                        sr.UniformDistribution_maxValue, 10.0);\r
+                \r
+                Resource parameter = GraphUtils.create2(graph, sr.SensitivityAnalysisExperiment_Parameter,\r
+                        sr.SensitivityAnalysisExperiment_Parameter_propabilityDistribution, distribution,\r
+                        sr.SensitivityAnalysisExperiment_Parameter_variable, ChartUtils.emptyVariableName,\r
+                        L0.PartOf, input);\r
+                \r
+                Resource parameterList = graph.getPossibleObject(input, sr.SensitivityAnalysisExperiment_parameterList);\r
+                ListUtils.insertBack(graph, parameterList, Collections.singleton(parameter));\r
+            }\r
+        });\r
+\r
+        remove = new Button(buttonComposite, parameterSupport, SWT.NONE);\r
+        remove.setText("Remove");\r
+        remove.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                if(input == null)\r
+                    return;\r
+                \r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                Layer0 L0 = Layer0.getInstance(graph);\r
+                \r
+                Resource experiment = graph.getPossibleObject(input, L0.PartOf);\r
+                Resource parameterList = graph.getPossibleObject(experiment, sr.SensitivityAnalysisExperiment_parameterList);\r
+                \r
+                if(ListUtils.toList(graph, parameterList).size() > 1)\r
+                    ListUtils.removeElement(graph, parameterList, input);\r
\r
+            }\r
+            \r
+        });\r
+        propertyContainer.setContent(content);\r
+        \r
+        \r
+        parameterPropertyGroup = new Group(content, SWT.NONE);\r
+        \r
+        parameterProperties = new Composite(parameterPropertyGroup, SWT.NONE);\r
+\r
+        // Label\r
+        labelVariable = new Label(parameterProperties, SWT.NONE);\r
+        labelVariable.setText("Variable:");\r
+\r
+        variable = new TrackedText(parameterProperties, parameterSupport, SWT.BORDER);\r
+        variable.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));\r
+        variable.addModifyListener(new VariableNameModifier(variable.getWidget(), parameterSupport, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_indexes));\r
+        variable.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), variable.getWidget())));\r
+        variable.setInputValidator(new ParameterExistsValidator(parameterSupport, variable));\r
+        \r
+        labelRange = new Label(parameterProperties, SWT.NONE);\r
+        labelRange.setText("Range:");\r
+        \r
+        rangeComposite = new RangeComposite(parameterProperties, context, parameterSupport, SWT.NONE) {\r
+            @Override\r
+            protected Resource getIndexRelation(ReadGraph graph) {\r
+                return SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_indexes;\r
+            }\r
+        };\r
+        \r
+//        TrackedText variable = new TrackedText(parameterProperties, parameterSupport, SWT.BORDER);\r
+//        variable.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));\r
+//        variable.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));\r
+//        variable.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), variable.getWidget())));\r
+//        GridDataFactory.fillDefaults().grab(true, false).applyTo(variable.getWidget());\r
+\r
+        labelDistribution = new Label(parameterProperties, SWT.NONE);\r
+        labelDistribution.setText("Distribution:");\r
+\r
+        distributionSelector = new TrackedCombo(parameterProperties, parameterSupport, SWT.DROP_DOWN);\r
+        distributionSelector.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+            @Override\r
+            public Map<String, Object> perform(ReadGraph graph, Resource input) throws DatabaseException {\r
+                SysdynResource SR = SysdynResource.getInstance(graph);\r
+                Map<String, Object> items = new HashMap<String, Object>();\r
+\r
+                items.put("Normal", SR.NormalDistribution);\r
+                items.put("Uniform", SR.UniformDistribution);\r
+                items.put("Interval", SR.Interval);\r
+\r
+                return items;\r
+            }\r
+\r
+        });\r
+\r
+        distributionSelector.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph, Resource parameter) throws DatabaseException {\r
+                SysdynResource SR = SysdynResource.getInstance(graph);\r
+                Resource distribution = graph.getPossibleObject(parameter, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution);\r
+                if(distribution == null)\r
+                    return null;\r
+                \r
+                if(graph.isInstanceOf(distribution, SR.UniformDistribution))\r
+                    return "Uniform";\r
+                else if(graph.isInstanceOf(distribution, SR.NormalDistribution))\r
+                    return "Normal";\r
+                else if(graph.isInstanceOf(distribution, SR.Interval))\r
+                    return "Interval";\r
+                else\r
+                    return "";\r
+\r
+            }\r
+        });\r
+\r
+        distributionSelector.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
+\r
+            @Override\r
+            public void applyText(WriteGraph graph, Resource input, String text)\r
+                    throws DatabaseException {\r
+                if(text == null || text.isEmpty())\r
+                    return;\r
+\r
+                SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+                Resource type = SR.UniformDistribution;\r
+\r
+                if("Normal".equals(text))\r
+                    type = SR.NormalDistribution;\r
+                else if("Interval".equals(text))\r
+                    type = SR.Interval; \r
+\r
+                graph.deny(input, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution);\r
+\r
+                GraphUtils.create2(graph, type,\r
+                        SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse, input);\r
+\r
+                dirty = true;\r
+            }\r
+        });\r
+\r
+        distributionSelector.addModifyListener(new TextModifyListener() {\r
+\r
+            @Override\r
+            public void modifyText(TrackedModifyEvent e) {\r
+                if(dirty) {\r
+                    parameterSupport.update();\r
+                    dirty = false;\r
+                    propertyContainer.setContent(content);\r
+                    Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+                    propertyContainer.setMinSize(size);\r
+                }\r
+            }\r
+        });\r
+\r
+        dpw = new DistributionPropertyWidget(parameterProperties, context, parameterSupport, SWT.NONE);\r
+    }\r
+\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+       \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+        \r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(content);\r
+        GridLayoutFactory.fillDefaults().numColumns(1).applyTo(content);\r
+\r
+        // Label\r
+        GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(labelComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(labelComposite);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(n.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(seed.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+        \r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+        \r
+        Point tsize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        propertyContainer.setMinSize(tsize);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterPropertyGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(parameterPropertyGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterProperties);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parameterProperties);\r
+\r
+        // Label\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelVariable);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(variable.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelRange);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(rangeComposite);\r
+        \r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelDistribution);\r
+        \r
+        GridDataFactory.fillDefaults().span(3, 1).grab(true, true).applyTo(dpw);\r
+        GridLayoutFactory.fillDefaults().margins(6, 0).applyTo(dpw);\r
+       }\r
+       \r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+        \r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(content);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(content);\r
+\r
+        // Label\r
+        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(labelComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(8).applyTo(labelComposite);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(n.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(seed.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
+        \r
+        Point tsize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        propertyContainer.setMinSize(tsize);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterPropertyGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(parameterPropertyGroup);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterProperties);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parameterProperties);\r
+\r
+        // Label\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelVariable);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(variable.getWidget());\r
+        \r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelRange);\r
+        \r
+        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(rangeComposite);\r
+        \r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelDistribution);\r
+\r
+        GridDataFactory.fillDefaults().span(1, 1).grab(true, true).applyTo(dpw);\r
+        GridLayoutFactory.fillDefaults().margins(6, 0).applyTo(dpw);\r
+\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java
new file mode 100644 (file)
index 0000000..ac3d2e7
--- /dev/null
@@ -0,0 +1,239 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+import org.eclipse.core.runtime.IAdaptable;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class SharedFunctionLibrariesTab extends LabelPropertyTabContributor implements Widget {\r
+       \r
+       GraphExplorerComposite availableSharedFunctionLibraries;\r
+       GraphExplorerComposite usedSharedFunctionLibraries;\r
+       Resource model;\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+               support.register(this);\r
+               \r
+               GridLayoutFactory.fillDefaults().numColumns(4).applyTo(body);\r
+               \r
+               \r
+               Composite available = new Composite(body, SWT.NONE);\r
+               GridLayoutFactory.fillDefaults().applyTo(available);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(available);\r
+               Label label = new Label(available, SWT.None);\r
+               label.setText("Available Shared Function Libraries");\r
+               availableSharedFunctionLibraries = new GraphExplorerComposite(ArrayMap.keys(\r
+                               "displaySelectors", "displayFilter").values(false, false), site, available, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI) {\r
+                   \r
+                       @Override\r
+                       protected void handleDrop(Object data, NodeContext target) {\r
+                       if (!(data instanceof IStructuredSelection))\r
+                               return;\r
+                       \r
+                       IStructuredSelection iss = (IStructuredSelection)data;\r
+                       if (iss == null || iss.isEmpty())\r
+                               return;\r
+                       \r
+                       for (Iterator<?> iterator = iss.iterator(); iterator.hasNext();) {\r
+                           Object o = iterator.next();\r
+                           if(o instanceof IAdaptable) {\r
+                               IAdaptable a = (IAdaptable)o;\r
+                               final SharedFunctionLibraryNode node = (SharedFunctionLibraryNode)a.getAdapter(SharedFunctionLibraryNode.class);\r
+                               if(node != null) {\r
+                                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                                               @Override\r
+                                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                       if(getModel() != null && node.data != null)\r
+                                                               graph.deny(getModel(), Layer0.getInstance(graph).IsLinkedTo, node.data);                                                                \r
+                                               }\r
+                                       });\r
+                               }\r
+                           }\r
+                       }\r
+                   }\r
+               };\r
+               \r
+               availableSharedFunctionLibraries\r
+               .setBrowseContexts(SysdynResource.URIs.AvailableSharedFunctionLibraries);\r
+               availableSharedFunctionLibraries.setInputSource(new SingleSelectionInputSource(\r
+                               Resource.class));\r
+\r
+               availableSharedFunctionLibraries.finish();\r
+\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                               availableSharedFunctionLibraries);\r
+               \r
+               Composite middleButtons = new Composite(body, SWT.NONE);\r
+               GridLayoutFactory.fillDefaults().applyTo(middleButtons);\r
+               GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, true).applyTo(middleButtons);\r
+               \r
+               Button add = new Button(middleButtons, support, SWT.NONE);\r
+               add.setText(" -> ");\r
+               \r
+               add.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+                   List<Resource> selectedLibraries;\r
+\r
+                   public void beforeApply() {\r
+                       selectedLibraries = getSelectedResources(availableSharedFunctionLibraries);\r
+                   }\r
+\r
+                   @Override\r
+                   public void apply(WriteGraph graph, Resource input)\r
+                           throws DatabaseException {\r
+                       if(selectedLibraries != null) {\r
+                           Layer0 l0 = Layer0.getInstance(graph);\r
+                           for(Resource library : selectedLibraries) {\r
+                               graph.claim(input, l0.IsLinkedTo, library);\r
+                           }\r
+                       }\r
+                   }\r
+               });\r
+\r
+               Button remove = new Button(middleButtons, support, SWT.NONE);\r
+               remove.setText(" <- ");\r
+               \r
+               remove.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+                   \r
+                   List<Resource> selectedLibraries;\r
+                   \r
+                   public void beforeApply() {\r
+                       selectedLibraries = getSelectedResources(usedSharedFunctionLibraries);\r
+                   }\r
+\r
+                       @Override\r
+                       public void apply(WriteGraph graph, Resource input)\r
+                               throws DatabaseException {\r
+                           if(selectedLibraries != null) {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               for(Resource library : selectedLibraries) {\r
+                                   graph.deny(input, l0.IsLinkedTo, library);\r
+                               }\r
+                           }\r
+                       }\r
+               });\r
+               \r
+               \r
+               Composite used = new Composite(body, SWT.NONE);\r
+               GridLayoutFactory.fillDefaults().applyTo(used);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(used);\r
+               label = new Label(used, SWT.None);\r
+               label.setText("Selected Shared Function Libraries");\r
+               \r
+               usedSharedFunctionLibraries = new GraphExplorerComposite(ArrayMap.keys(\r
+                               "displaySelectors", "displayFilter").values(false, false), site, used, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI)  {\r
+                   \r
+                       @Override\r
+                       protected void handleDrop(Object data, NodeContext target) {\r
+                       if (!(data instanceof IStructuredSelection))\r
+                               return;\r
+                       \r
+                       IStructuredSelection iss = (IStructuredSelection)data;\r
+                       if (iss == null || iss.isEmpty())\r
+                               return;\r
+                       \r
+                       for (Iterator<?> iterator = iss.iterator(); iterator.hasNext();) {\r
+                           Object o = iterator.next();\r
+                           if(o instanceof IAdaptable) {\r
+                               IAdaptable a = (IAdaptable)o;\r
+                               final SharedFunctionLibraryNode node = (SharedFunctionLibraryNode)a.getAdapter(SharedFunctionLibraryNode.class);\r
+                               if(node != null) {\r
+                                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                                               @Override\r
+                                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                       if(getModel() != null && node.data != null)\r
+                                                               graph.claim(getModel(), Layer0.getInstance(graph).IsLinkedTo, node.data);                                                               \r
+                                               }\r
+                                       });\r
+                               }\r
+                           }\r
+                       }\r
+                   }\r
+               };\r
+               \r
+               usedSharedFunctionLibraries\r
+               .setBrowseContexts(SysdynResource.URIs.SelectedSharedFunctionLibraries);\r
+               usedSharedFunctionLibraries.setInputSource(new SingleSelectionInputSource(\r
+                               Resource.class));\r
+\r
+               usedSharedFunctionLibraries.finish();\r
+\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                               usedSharedFunctionLibraries);\r
+       }\r
+       \r
+       \r
+       private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {\r
+               List<Resource> result = new ArrayList<Resource>();\r
+               \r
+               ISelection selection = ((ISelectionProvider) explorer\r
+                               .getAdapter(ISelectionProvider.class)).getSelection();\r
+               if (selection == null)\r
+                       return result;\r
+               IStructuredSelection iss = (IStructuredSelection) selection;\r
+               @SuppressWarnings("unchecked")\r
+               List<AdaptableHintContext> selections = iss.toList();\r
+               for(AdaptableHintContext ahc : selections) {\r
+                       Resource resource = (Resource) ahc.getAdapter(Resource.class);\r
+                       result.add(resource);\r
+               }\r
+               return result;\r
+       }\r
+\r
+       private Resource getModel() {\r
+               return model;\r
+       }\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               availableSharedFunctionLibraries.setInput(context, input);\r
+               usedSharedFunctionLibraries.setInput(context, input);\r
+               this.model = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+       }\r
+\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SysdynBasicColorProvider.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SysdynBasicColorProvider.java
new file mode 100644 (file)
index 0000000..e5444a8
--- /dev/null
@@ -0,0 +1,57 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import org.eclipse.jface.resource.ColorDescriptor;\r
+import org.eclipse.jface.resource.ResourceManager;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ITrackedColorProvider;\r
+\r
+/**\r
+ * Color provider for sysdyn tool. Use this color provider to get a consistent look for the product.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynBasicColorProvider  implements ITrackedColorProvider {\r
+    \r
+    private final ResourceManager resourceManager;\r
+    \r
+    private final ColorDescriptor highlightColor = ColorDescriptor.createFrom(new RGB(254, 255, 197));\r
+    private final ColorDescriptor inactiveColor = ColorDescriptor.createFrom(new RGB(255, 255, 255));\r
+    private final ColorDescriptor invalidInputColor = ColorDescriptor.createFrom(new RGB(255, 128, 128));\r
+\r
+    public SysdynBasicColorProvider(ResourceManager resourceManager) {\r
+        this.resourceManager = resourceManager;\r
+    }\r
+    \r
+    @Override\r
+    public Color getEditingBackground() {\r
+        return resourceManager.createColor(inactiveColor);\r
+    }\r
+\r
+    @Override\r
+    public Color getHoverBackground() {\r
+        return resourceManager.createColor(highlightColor);\r
+    }\r
+\r
+    @Override\r
+    public Color getInactiveBackground() {\r
+        return resourceManager.createColor(inactiveColor);\r
+    }\r
+\r
+    @Override\r
+    public Color getInvalidBackground() {\r
+        return resourceManager.createColor(invalidInputColor);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SysdynPropertyPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SysdynPropertyPage.java
new file mode 100644 (file)
index 0000000..59e61e5
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.Set;\r
+\r
+import org.eclipse.ui.IWorkbenchPartSite;\r
+import org.simantics.selectionview.StandardPropertyPage;\r
+\r
+public class SysdynPropertyPage extends StandardPropertyPage {\r
+\r
+    public SysdynPropertyPage(IWorkbenchPartSite site, Set<String> set) {\r
+        super(site, set);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/VariableInformationTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/VariableInformationTab.java
new file mode 100644 (file)
index 0000000..2e4fc80
--- /dev/null
@@ -0,0 +1,432 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.FontDescriptor;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.SWTException;\r
+import org.eclipse.swt.graphics.FontData;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.CustomFontDialog;\r
+import org.simantics.sysdyn.ui.properties.widgets.ValveOrientationGroup;\r
+import org.simantics.sysdyn.ui.properties.widgets.ValveTextLocationGroup;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.datastructures.Triple;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+import org.simantics.utils.ui.validators.DoubleValidator;\r
+\r
+/**\r
+ * Information tab for additional information of variables. \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class VariableInformationTab extends AdjustableTab implements Widget {\r
+    private Composite orientationComposite;\r
+    private WidgetSupport support;\r
+    private Resource component;\r
+    private org.simantics.browsing.ui.swt.widgets.Label sample;\r
+    private LocalResourceManager resourceManager;\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        this.support = support;\r
+        support.register(this);\r
+        \r
+        // Create a ResourceManager to dispose images when the widget is disposed.\r
+        this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), body);\r
+        \r
+        super.createControls(body, site, context, support);\r
+    }\r
+\r
+    private Read<Pair<Font, Color>> fontAndColorRead;\r
+       private Group informationGroup;\r
+       private TrackedText information;\r
+       private Group rangeGroup;\r
+       private Label label;\r
+       private TrackedText rangeStart;\r
+       private TrackedText rangeEnd;\r
+       private TrackedText rangeStep;\r
+       private Composite fontComposite;\r
+       private Button b;\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        component = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        // is the displayed variable a valve?\r
+        Boolean isValve = false;\r
+        try {\r
+            isValve = context.getSession().syncRequest(new Read<Boolean>() {\r
+\r
+                @Override\r
+                public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    return graph.isInstanceOf(component, sr.Valve);\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        // if it is a valve, display the orientation information\r
+        if(isValve) {\r
+            ValveOrientationGroup vog = new ValveOrientationGroup(orientationComposite, context, support, SWT.NONE);\r
+            vog.setInput(context, input);\r
+            ValveTextLocationGroup vtlg = new ValveTextLocationGroup(orientationComposite, context, support, SWT.NONE);\r
+            vtlg.setInput(context, input);\r
+            orientationComposite.getParent().layout();\r
+        }\r
+\r
+        // Read font and color information for sample text\r
+        if(fontAndColorRead == null) {\r
+            fontAndColorRead = new Read<Pair<Font, Color>>() {\r
+\r
+                @Override\r
+                public Pair<Font, Color> perform(ReadGraph graph) throws DatabaseException {\r
+                    Font font = null;\r
+                    Color color = null;\r
+                    if(component != null) {\r
+                        Resource element = graph.getPossibleObject(component, ModelingResources.getInstance(graph).ComponentToElement);\r
+                        if(element != null) {\r
+                            G2DResource g2d = G2DResource.getInstance(graph);\r
+                            Resource fontResource = graph.getPossibleObject(element, g2d.HasFont);\r
+                            if(fontResource != null)\r
+                                font = G2DUtils.getFont(graph, fontResource);\r
+                            Resource colorResource = graph.getPossibleObject(element, g2d.HasColor);\r
+                            if(colorResource != null)\r
+                                color = G2DUtils.getColor(graph, colorResource);\r
+                        }\r
+                    }\r
+                    return new Pair<Font, Color>(font, color);\r
+                }\r
+            };\r
+\r
+            SimanticsUI.getSession().asyncRequest(fontAndColorRead, new Listener<Pair<Font, Color>>() {\r
+\r
+                @Override\r
+                public void execute(final Pair<Font, Color> result) {\r
+                    final Display device;\r
+                    try {\r
+                        device = sample.getWidget().getDisplay();\r
+                    } catch (SWTException e) {\r
+                        // Widget is disposed, the GUI probably did'n function as fast as the user commanded.\r
+                        // Thus do nothing.\r
+                        return;\r
+                    }\r
+                    \r
+                    device.asyncExec(new Runnable() {\r
+                        \r
+                        @Override\r
+                        public void run() {\r
+                            try {\r
+                                if(sample.getWidget().isDisposed())\r
+                                    return;\r
+                            } catch (SWTException e) {\r
+                                // Widget is disposed, the GUI probably did'n function as fast as the user commanded.\r
+                                // Thus do nothing.\r
+                                return;\r
+                            }\r
+                            if(result.first != null) {\r
+                                FontData fd = toSwtFontData(result.first);\r
+                                sample.setFont(resourceManager.createFont(FontDescriptor.createFrom(fd)));\r
+                            }\r
+                            if(result.second != null) {\r
+                                RGB rgb = new RGB(result.second.getRed(), result.second.getGreen(), \r
+                                        result.second.getBlue());\r
+                                sample.setForeground(resourceManager.createColor(rgb));\r
+                            }\r
+                            try {\r
+                                sample.getWidget().getParent().getParent().layout();\r
+                            } catch (SWTException e) {\r
+\r
+                            }\r
+                        }\r
+                    });\r
+\r
+                }\r
+\r
+                @Override\r
+                public void exception(Throwable t) {\r
+                    t.printStackTrace();\r
+                }\r
+\r
+                @Override\r
+                public boolean isDisposed() {\r
+                    return sample == null || sample.getWidget().isDisposed();\r
+                }\r
+\r
+            });\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Create SWT FontData based on AWT Font\r
+     * @param font AWT Font\r
+     * @return SWT FontData based on AWT Font\r
+     */\r
+    private static FontData toSwtFontData(Font font) {\r
+        FontData fontData = new FontData();\r
+        fontData.setName(font.getFamily());\r
+        fontData.setStyle(font.getStyle());\r
+        fontData.setHeight(font.getSize());\r
+        return fontData;\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       ISessionContext context, WidgetSupport _support) {\r
+\r
+        composite = new Composite(body, SWT.NONE);\r
+\r
+        informationGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);\r
+        informationGroup.setText("Information");\r
+\r
+        // Textual format documentation\r
+        information = new TrackedText(informationGroup, support, SWT.MULTI | SWT.BORDER);\r
+        information.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasDescription));\r
+        information.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasDescription));\r
+\r
+        // Orientation information for valves\r
+        orientationComposite = new Composite(composite, SWT.NONE);\r
+\r
+        // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts\r
+        rangeGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);\r
+        rangeGroup.setText("Range");\r
+\r
+        label = new Label(rangeGroup, SWT.NONE);\r
+        label.setText("Start");\r
+\r
+        rangeStart = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);\r
+        rangeStart.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeStart));\r
+        rangeStart.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeStart));\r
+        rangeStart.setInputValidator(new DoubleValidator());\r
+\r
+        label = new Label(rangeGroup, SWT.NONE);\r
+        label.setText("End");\r
+\r
+\r
+        rangeEnd = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);\r
+        rangeEnd.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeEnd));\r
+        rangeEnd.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeEnd));\r
+        rangeEnd.setInputValidator(new DoubleValidator());\r
+\r
+        label = new Label(rangeGroup, SWT.NONE);\r
+        label.setText("Step");\r
+\r
+        rangeStep = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);\r
+        rangeStep.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeStep));\r
+        rangeStep.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeStep));\r
+        rangeStep.setInputValidator(new DoubleValidator());\r
+\r
+        \r
+        // Font options. FIXME: very bad appearance right now\r
+        \r
+        fontComposite = new Composite(composite, SWT.NONE);\r
+        b = new Button(fontComposite, support, SWT.PUSH);\r
+        b.setText("Choose Font");\r
+\r
+        // Sample text with selected font\r
+        sample = new org.simantics.browsing.ui.swt.widgets.Label(fontComposite, support, SWT.NONE);\r
+        sample.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName, "Sample"));\r
+\r
+        b.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+            Font f;\r
+            Color color;\r
+            Object input;\r
+\r
+            @Override\r
+            public void beforeApply() {\r
+\r
+                Triple<Font, Color, String> result = null;\r
+\r
+                try {\r
+                    result = SimanticsUI.getSession().syncRequest(new Read<Triple<Font, Color, String>>(){\r
+\r
+                        @Override\r
+                        public Triple<Font, Color, String> perform(ReadGraph graph) throws DatabaseException {\r
+                            Resource component = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
+                            String name = NameUtils.getSafeName(graph, component);\r
+\r
+                            Resource element = graph.getPossibleObject(component, ModelingResources.getInstance(graph).ComponentToElement);\r
+                            if(element != null) {\r
+                                G2DResource g2d = G2DResource.getInstance(graph);\r
+                                Resource fontResource = graph.getPossibleObject(element, g2d.HasFont);\r
+                                Resource colorResource = graph.getPossibleObject(element, g2d.HasColor);\r
+\r
+                                Font font = null;\r
+                                if(fontResource != null)\r
+                                    font = G2DUtils.getFont(graph, fontResource);\r
+                                Color color = null;\r
+                                if(colorResource != null)\r
+                                    color = G2DUtils.getColor(graph, colorResource);\r
+\r
+                                return new Triple<Font, Color, String>(font, color, name);\r
+                            }\r
+\r
+                            return null;\r
+                        }\r
+\r
+                    });\r
+                } catch (DatabaseException e) {\r
+                }\r
+\r
+\r
+                CustomFontDialog dialog = new CustomFontDialog(composite.getShell(), (result != null ? result.third : null));\r
+\r
+                if(result != null) {\r
+                    if(result.first != null) {\r
+                        dialog.setAWTFont(result.first);\r
+                        f = result.first;\r
+                    }\r
+                    if(result.second != null) {\r
+                        dialog.setColor(result.second);\r
+                        color = result.second;\r
+                    }\r
+                }\r
+\r
+                dialog.open();\r
+                if(dialog.getAWTFont() != null)\r
+                    f = dialog.getAWTFont();\r
+                if(dialog.getAWTColor() != null) {\r
+                    color = dialog.getAWTColor();\r
+                }\r
+\r
+                FontData fd = dialog.getSWTFontData();\r
+                if(fd != null)\r
+                    sample.setFont(resourceManager.createFont(FontDescriptor.createFrom(fd)));\r
+                RGB rgb = dialog.getRGB(); \r
+                if(rgb != null)\r
+                    sample.setForeground(resourceManager.createColor(rgb));\r
+                fontComposite.layout();\r
+            }\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                Resource element = graph.getPossibleObject(input, ModelingResources.getInstance(graph).ComponentToElement);\r
+                if(element != null) {\r
+                    G2DResource g2d = G2DResource.getInstance(graph);\r
+                    graph.deny(element, g2d.HasFont);\r
+                    if(f != null)\r
+                        graph.claim(element, g2d.HasFont, G2DUtils.createFont(graph, f));\r
+                    graph.deny(element, g2d.HasColor);\r
+                    if(color != null)\r
+                        graph.claim(element,  g2d.HasColor, G2DUtils.createColor(graph, color));\r
+                }\r
+            }\r
+\r
+            @Override\r
+            public void setInput(ISessionContext context, Object parameter) {\r
+                super.setInput(context, parameter);\r
+                input = parameter;\r
+            }\r
+\r
+        });\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(informationGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(informationGroup);\r
+\r
+        // Textual format documentation\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());\r
+\r
+        // Orientation information for valves\r
+        GridDataFactory.fillDefaults().span(1, 2).applyTo(orientationComposite);\r
+        GridLayoutFactory.fillDefaults().margins(3,3).applyTo(orientationComposite);\r
+\r
+        // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts\r
+        GridDataFactory.fillDefaults().applyTo(rangeGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(rangeGroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStart.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeEnd.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStep.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().applyTo(fontComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(1).applyTo(fontComposite);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(informationGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(informationGroup);\r
+\r
+        // Textual format documentation\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());\r
+\r
+        // Orientation information for valves\r
+        GridDataFactory.fillDefaults().span(1, 2).applyTo(orientationComposite);\r
+        GridLayoutFactory.fillDefaults().margins(3,3).applyTo(orientationComposite);\r
+\r
+        // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts\r
+        GridDataFactory.fillDefaults().applyTo(rangeGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(6).applyTo(rangeGroup);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStart.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeEnd.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStep.getWidget());\r
+\r
+        GridDataFactory.fillDefaults().applyTo(fontComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(fontComposite);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrayExpressionCombo.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrayExpressionCombo.java
new file mode 100644 (file)
index 0000000..42607db
--- /dev/null
@@ -0,0 +1,191 @@
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Iterator;\r
+import java.util.LinkedHashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.swt.widgets.Combo;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ArrayExpressionCombo extends TrackedCombo {\r
+\r
+       int lastSelectedIndex = -2;\r
+\r
+       public ArrayExpressionCombo(Composite parent, WidgetSupport support,\r
+                       int style) {\r
+               super(parent, support, style);\r
+\r
+               /*\r
+               this.setInputValidator(new VariableNameValidator(support));\r
+                */\r
+\r
+               this.setItemFactory(new ReadFactoryImpl<Resource, Map<String, Object>>()  {\r
+\r
+                       @Override\r
+                       public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                               Map<String, Object> map = new LinkedHashMap<String, Object>();\r
+                               if(input == null) {\r
+                                       return map;\r
+                               }\r
+\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               String name = graph.getPossibleRelatedValue(input, l0.HasName);\r
+                               if(name == null)\r
+                                       return map;\r
+\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                               String defaultRange = getDefaultRange(graph, input);\r
+                               for(Resource expression : getExpressions(graph, input)) {\r
+                                       String arrayRange = graph.getPossibleRelatedValue(expression, sr.Expression_arrayRange); \r
+                                       if(arrayRange != null) {\r
+                                               map.put(name + arrayRange, expression);\r
+                                       } else if(defaultRange != null) {\r
+                                               map.put(name + defaultRange, expression);\r
+                                       } else {\r
+                                               map.put(name, expression);\r
+                                       }\r
+                               }\r
+                               if(map.isEmpty()) {\r
+                                       map.put(name, input);\r
+                               }\r
+                               return map;\r
+                       }\r
+\r
+               });\r
+\r
+\r
+               this.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+                       @Override\r
+                       public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                               String name = graph.getPossibleRelatedValue(input,  Layer0.getInstance(graph).HasName);\r
+                               if(name == null)\r
+                                       return "";\r
+                               \r
+                               String defaultRange = getDefaultRange(graph, input);\r
+                               if(defaultRange == null)\r
+                                       return name;\r
+\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                               Resource activeExpression = graph.getPossibleObject(input, sr.IndependentVariable_activeExpression);\r
+                               Resource expression;\r
+                               if(activeExpression == null) {\r
+                                       ArrayList<Resource> expressions = getExpressions(graph, input);\r
+                                       if(expressions == null || expressions.isEmpty())\r
+                                               return name;\r
+                                       expression = expressions.get(0);\r
+                               } else {\r
+                                       expression = activeExpression;\r
+                               }\r
+                               String range = graph.getPossibleRelatedValue(expression, sr.Expression_arrayRange);\r
+                               if(range != null)\r
+                                       return name + range;\r
+                               else\r
+                                       return name + defaultRange;\r
+                       }\r
+               });\r
+\r
+       }\r
+\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               super.setInput(context, input);\r
+\r
+               if(selectionFactory != null) {\r
+                       selectionFactory.listen(context, input, new Listener<String>() {\r
+\r
+                               @Override\r
+                               public void execute(final String result) {\r
+                                       if(getWidget().isDisposed()) return;\r
+                                       getWidget().getDisplay().asyncExec(new Runnable() {\r
+                                               \r
+                                               @Override\r
+                                               public void run() {\r
+                                                       Combo combo = getWidget();\r
+                                                       if(combo != null && !combo.isDisposed() && result != null) {\r
+                                                               Object o = getWidget().getData(result);\r
+                                                               if(o != null)\r
+                                                                       lastSelectedIndex = (Integer)o;\r
+                                                       }\r
+                                                               \r
+                                               }\r
+                                       });\r
+                               }\r
+\r
+                               @Override\r
+                               public void exception(Throwable t) {\r
+                                       t.printStackTrace();\r
+                               }\r
+\r
+                               @Override\r
+                               public boolean isDisposed() {\r
+                                       return getWidget().isDisposed();\r
+                               }\r
+\r
+                       });\r
+               }\r
+       }\r
+\r
+       private ArrayList<Resource> getExpressions(ReadGraph graph, Resource variable) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Resource hasExpressions = graph.getPossibleObject(variable, sr.Variable_expressionList);\r
+               if(hasExpressions == null)\r
+                       return new ArrayList<Resource>();\r
+               else\r
+                       return new ArrayList<Resource>(ListUtils.toList(graph, hasExpressions));\r
+       }\r
+\r
+       public static String getDefaultRange(ReadGraph graph, Resource variable) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Resource hasArrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
+\r
+               if(hasArrayIndexes == null)\r
+                       return null;\r
+\r
+               Iterator<Resource> iterator = ListUtils.toList(graph, hasArrayIndexes).iterator();\r
+               if(!iterator.hasNext())\r
+                       return null;\r
+\r
+               StringBuilder sb = new StringBuilder();\r
+               sb.append("[");\r
+\r
+               while(iterator.hasNext()) {\r
+                       sb.append(NameUtils.getSafeName(graph, iterator.next()));\r
+                       if(iterator.hasNext()) {\r
+                               sb.append(", ");\r
+                       }\r
+               }\r
+               sb.append("]");\r
+               return sb.toString();\r
+       }\r
+       \r
+       /**\r
+        * Get the index that has previously been selected\r
+        * @return\r
+        */\r
+       public int getLastSelectedIndex() {\r
+               return lastSelectedIndex;\r
+       }\r
+       \r
+       public void setLastSelectedIndex(int lastSelectedIndex) {\r
+               this.lastSelectedIndex = lastSelectedIndex;\r
+       }\r
+\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrowHeadWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ArrowHeadWidget.java
new file mode 100644 (file)
index 0000000..7698135
--- /dev/null
@@ -0,0 +1,169 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Widget for showing arrow head in dependencies.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ArrowHeadWidget implements Widget{\r
+\r
+    List<Resource> variables = null; \r
+    org.simantics.browsing.ui.swt.widgets.Button arrowheadButton;\r
+    \r
+    public ArrowHeadWidget(Composite parent, WidgetSupport support, int style) {\r
+        support.register(this);\r
+        arrowheadButton = new org.simantics.browsing.ui.swt.widgets.Button(parent, support, style |= SWT.CHECK);\r
+        arrowheadButton.setText("Arrowhead");\r
+    }\r
+\r
+    @SuppressWarnings({ "rawtypes", "unchecked" })\r
+       @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        if(input instanceof ISelection) {\r
+            ISelection selection = (ISelection)input;\r
+            if(selection instanceof IStructuredSelection) {\r
+               List<Resource> resources = ISelectionUtils.filterSelection(selection, Resource.class);\r
+                if(resources != null && !resources.isEmpty()) {\r
+                    variables = resources;\r
+                } else {\r
+                       List<ArrayList> resourceLists = ISelectionUtils.filterSelection(selection, ArrayList.class);\r
+                       variables = resourceLists.get(0);\r
+                }\r
+            }\r
+        }\r
+\r
+        if(variables == null) return;\r
+        \r
+        try {\r
+            context.getSession().syncRequest(new ReadRequest() {\r
+                \r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    \r
+                    // Determine if there are arrowheads in some of the variables.\r
+                    boolean hasArrowheads = false, hasNotArrowheads = false;\r
+                    for (Resource variable : variables) {\r
+                       if (!graph.hasStatement(variable, sr.DependencyConnection_hideArrow)) {\r
+                               hasArrowheads = true;\r
+                       } else {\r
+                               hasNotArrowheads = true;\r
+                       }\r
+                    }\r
+                    \r
+                    // If some have arrowheads but others don't, the check box is grayed.\r
+                    final Button button = getWidget();\r
+                    final boolean arrowhead = hasArrowheads;\r
+                    final boolean mixedArrowheads = hasArrowheads && hasNotArrowheads;\r
+                       button.getDisplay().asyncExec(new Runnable() {\r
+                               \r
+                        @Override\r
+                        public void run() {\r
+                            if(button.isDisposed()) return;\r
+                            button.setSelection(arrowhead);\r
+                            button.setGrayed(mixedArrowheads);\r
+                        }\r
+                    });\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        // Multiple selections\r
+        arrowheadButton.addSelectionListener(new SelectionListenerImpl<ArrayList<Resource>>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, ArrayList<Resource> inputs) throws DatabaseException {\r
+                if (inputs == null)\r
+                       return;\r
+                \r
+                final SysdynResource sr =  SysdynResource.getInstance(graph);\r
+                boolean nextState = true; // The next state of the checkbox\r
+                for (Resource variable : variables) {\r
+                       if (!graph.hasStatement(variable, sr.DependencyConnection_hideArrow)) {\r
+                               nextState = false; // The next state is true iff all have hideArrow.\r
+                               break;\r
+                       }\r
+                }\r
+\r
+               try {\r
+                       if (nextState) {\r
+                                               for (Resource input : inputs) {\r
+                                                       graph.deny(input, sr.DependencyConnection_hideArrow);\r
+                                               }\r
+                                       } else {\r
+                                               for (Resource input : inputs) {\r
+                                                       graph.claim(input, SysdynResource.getInstance(graph).DependencyConnection_hideArrow, null, input);\r
+                                               }\r
+                                       }\r
+               } catch (DatabaseException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+                \r
+               // Get the button out of the grayed state.\r
+               final Button button = getWidget();\r
+                button.getDisplay().asyncExec(new Runnable() {\r
+                    \r
+                    @Override\r
+                    public void run() {\r
+                       button.setGrayed(false);\r
+                    }\r
+                });\r
+            }\r
+        });\r
+        \r
+        // One selection\r
+        arrowheadButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                if (input == null)\r
+                       return;\r
+                \r
+                final SysdynResource sr =  SysdynResource.getInstance(graph);\r
+                if(graph.hasStatement(input, sr.DependencyConnection_hideArrow)) {\r
+                           graph.deny(input, sr.DependencyConnection_hideArrow);\r
+                       } else {\r
+                           graph.claim(input, SysdynResource.getInstance(graph).DependencyConnection_hideArrow, null, input);\r
+                       }\r
+            }  \r
+        });\r
+    }\r
+    \r
+    public Button getWidget() {\r
+        return arrowheadButton.getWidget();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartTableWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartTableWidget.java
new file mode 100644 (file)
index 0000000..b600df8
--- /dev/null
@@ -0,0 +1,247 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.awt.event.MouseEvent;\r
+import java.awt.geom.Point2D;\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.Iterator;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.FocusEvent;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyEvent;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.MouseListener;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableItem;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.tableParser.ParseException;\r
+import org.simantics.sysdyn.tableParser.TableParser;\r
+import org.simantics.sysdyn.tableParser.Token;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupInputOutputTable;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupInputOutputTable.InputOutput;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+public class ChartTableWidget implements Widget {\r
+\r
+    Text input, output;\r
+    Button add;\r
+    LookupInputOutputTable table;\r
+    Resource expression;\r
+\r
+    public ChartTableWidget(Composite parent, WidgetSupport support, int style) {\r
+        support.register(this);\r
+        Composite valueTableComposite = new Composite(parent, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(valueTableComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(valueTableComposite);\r
+\r
+        table = new LookupInputOutputTable(valueTableComposite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().span(3, 1).grab(false, true).applyTo(table);\r
+        table.getTableViewer().getTable().addMouseListener(new MouseListener() {\r
+\r
+            @Override\r
+            public void mouseUp(org.eclipse.swt.events.MouseEvent e) {\r
+                if(e.button == MouseEvent.BUTTON3) {\r
+                    Table t = (Table)e.widget;\r
+                    TableItem item = (TableItem)t.getItem(new org.eclipse.swt.graphics.Point(e.x, e.y));\r
+                    table.removeItem(t.indexOf(item));\r
+                    tableModified();\r
+                }\r
+            }\r
+            @Override\r
+            public void mouseDown(org.eclipse.swt.events.MouseEvent e) { }\r
+            @Override\r
+            public void mouseDoubleClick(org.eclipse.swt.events.MouseEvent e) { }\r
+        });\r
+\r
+        input = new Text(valueTableComposite, SWT.BORDER | SWT.RIGHT);\r
+        input.setText("");\r
+        output = new Text(valueTableComposite, SWT.BORDER | SWT.RIGHT);\r
+        output.setText("");\r
+\r
+        add = new Button(valueTableComposite, SWT.None);\r
+        add.setText("Add");\r
+        add.addSelectionListener(new SelectionListener() {\r
+\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                try {\r
+                    Double in = Double.parseDouble(input.getText());\r
+                    Double out = Double.parseDouble(output.getText());\r
+                    table.addLocation(new Point2D.Double(in, out));\r
+                    tableModified();\r
+                } catch (NumberFormatException e1) {\r
+                }\r
+                input.setText("");\r
+                output.setText("");\r
+            }\r
+\r
+            @Override\r
+            public void widgetDefaultSelected(SelectionEvent e) {}\r
+        });\r
+\r
+        FocusListener flistener = new FocusListener() {\r
+            @Override\r
+            public void focusGained(FocusEvent e) {\r
+                Text text = (Text)e.widget;\r
+                text.setSelection(0, text.getCharCount());\r
+            }\r
+            @Override\r
+            public void focusLost(FocusEvent e) { }\r
+        };\r
+\r
+\r
+        KeyListener listener = new KeyListener() {\r
+\r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+                if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {\r
+                    try {\r
+                        Double in = Double.parseDouble(input.getText());\r
+                        Double out = Double.parseDouble(output.getText());\r
+                        table.addLocation(new Point2D.Double(in, out));\r
+                        tableModified();\r
+                    } catch (NumberFormatException e1) {\r
+                        if(input.getText().isEmpty() && output.getText().isEmpty()) {\r
+                            add.forceFocus();\r
+                            return;\r
+                        }\r
+                    }\r
+                    input.setText("");\r
+                    output.setText("");\r
+                    input.setFocus();\r
+                }          \r
+            }\r
+\r
+            @Override\r
+            public void keyReleased(KeyEvent e) { }\r
+\r
+        };\r
+\r
+        input.addFocusListener(flistener);\r
+        input.addKeyListener(listener);\r
+        output.addFocusListener(flistener);\r
+        output.addKeyListener(listener);\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+\r
+        expression = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);\r
+\r
+\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                @Override\r
+                public String perform(ReadGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    if(!graph.isInstanceOf(expression, sr.WithLookupExpression))\r
+                       return null;\r
+                    return graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);\r
+                }\r
+            }, new Listener<String>() {\r
+\r
+                @Override\r
+                public void exception(Throwable t) {\r
+                    t.printStackTrace();\r
+                }\r
+\r
+                @Override\r
+                public void execute(String lookup) {\r
+                       if(lookup == null) return;\r
+                    TableParser parser = new TableParser(new StringReader(""));\r
+                    parser.ReInit(new StringReader(lookup));\r
+                    table.clearTable();\r
+                    try {\r
+                        parser.table();\r
+                        ArrayList<Token> xTokens = parser.getXTokens();\r
+                        ArrayList<Token> yTokens = parser.getYTokens();\r
+                        for(int i = 0; i < xTokens.size(); i++) {\r
+                            table.addLocation(new Point2D.Double(\r
+                                    Double.parseDouble(xTokens.get(i).image), \r
+                                    Double.parseDouble(yTokens.get(i).image)));\r
+                        }\r
+                    } catch (ParseException e1) {\r
+                    }\r
+                }\r
+\r
+                @Override\r
+                public boolean isDisposed() {\r
+                    return table.isDisposed();\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        table.addListener(SWT.Modify, new org.eclipse.swt.widgets.Listener() {\r
+\r
+            @Override\r
+            public void handleEvent(Event event) {\r
+                tableModified();\r
+            }\r
+        });\r
+    }\r
+    \r
+    \r
+    @SuppressWarnings("unchecked")\r
+    private void tableModified() {\r
+        StringBuilder b = new StringBuilder();\r
+        b.append("{");\r
+        ArrayList<InputOutput> inputOutputList = (ArrayList<InputOutput>)table.getTableViewer().getInput();\r
+        Collections.sort(inputOutputList, table.new InputOutputComparator());\r
+        Iterator<InputOutput> iterator = inputOutputList.iterator();\r
+        while(iterator.hasNext()){\r
+            InputOutput io = iterator.next();\r
+            b.append("{" + io.getInput(String.class) + "," + io.getOutput(String.class) + "}");\r
+            if(iterator.hasNext())\r
+                b.append(",");\r
+        }\r
+        b.append("}");\r
+        final String table =  b.toString();\r
+\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                graph.claimLiteral(expression, sr.WithLookupExpression_lookup, table);\r
+            }\r
+        });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartWidget.java
new file mode 100644 (file)
index 0000000..2dd769d
--- /dev/null
@@ -0,0 +1,240 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.GridLayout;\r
+import java.awt.geom.Ellipse2D;\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.Iterator;\r
+\r
+import javax.swing.JComponent;\r
+import javax.swing.JPanel;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.jfree.chart.ChartFactory;\r
+import org.jfree.chart.JFreeChart;\r
+import org.jfree.chart.axis.ValueAxis;\r
+import org.jfree.chart.plot.PlotOrientation;\r
+import org.jfree.chart.plot.XYPlot;\r
+import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;\r
+import org.jfree.data.general.SeriesChangeEvent;\r
+import org.jfree.data.general.SeriesChangeListener;\r
+import org.jfree.data.xy.XYDataItem;\r
+import org.jfree.data.xy.XYDataset;\r
+import org.jfree.data.xy.XYSeries;\r
+import org.jfree.data.xy.XYSeriesCollection;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.tableParser.ParseException;\r
+import org.simantics.sysdyn.tableParser.TableParser;\r
+import org.simantics.sysdyn.tableParser.Token;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupChartPanel;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+import org.simantics.utils.ui.SWTAWTComponent;\r
+\r
+public class ChartWidget implements Widget {\r
+\r
+    JFreeChart chart;\r
+    LookupChartPanel chartPanel;\r
+    SWTAWTComponent swtawtcomponent;\r
+\r
+    public ChartWidget(Composite parent, WidgetSupport support, int style) {\r
+        support.register(this);\r
+        chartPanel = new LookupChartPanel(createChart());\r
+        chartPanel.setMouseZoomable(true, false);\r
+        chartPanel.setDomainZoomable(false);\r
+        chartPanel.setRangeZoomable(false);\r
+\r
+        swtawtcomponent = new SWTAWTComponent(parent, SWT.BORDER) {\r
+            @Override\r
+            protected JComponent createSwingComponent() {\r
+                JPanel panel = new JPanel();\r
+                panel.setLayout(new GridLayout(1, 1));\r
+                panel.add(chartPanel);\r
+                panel.doLayout();\r
+                return panel;\r
+            }\r
+        };\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(swtawtcomponent);\r
+        swtawtcomponent.populate();\r
+\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+\r
+        final Resource expression = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);\r
+\r
+        class Auxiliary {\r
+            Double minX, minY, maxX, maxY;\r
+            String table;\r
+        }\r
+\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new Read<Auxiliary>() {\r
+\r
+                @Override\r
+                public Auxiliary perform(ReadGraph graph) throws DatabaseException {\r
+                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                       if(!graph.isInstanceOf(expression, sr.WithLookupExpression))\r
+                               return null;\r
+                       Auxiliary auxiliary = new Auxiliary();\r
+                    auxiliary.minX = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_minX);\r
+                    auxiliary.maxX = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_maxX);\r
+                    auxiliary.minY = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_minY);\r
+                    auxiliary.maxY = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_maxY);\r
+                    auxiliary.table = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);\r
+                    return auxiliary;\r
+                }\r
+            }, new Listener<Auxiliary>() {\r
+\r
+                @Override\r
+                public void exception(Throwable t) {\r
+                    t.printStackTrace();\r
+                }\r
+\r
+                @Override\r
+                public void execute(Auxiliary result) {\r
+                       if(result == null) return;\r
+                    XYDataset dataset = createDataset(result.table);\r
+                    chartPanel.resetChart(dataset);\r
+                    chartPanel.addSeriesChangeListener(new _SeriesChangeListener(expression));\r
+                    \r
+                    XYPlot plot = (XYPlot) chart.getPlot();\r
+                    ValueAxis rangeAxis = plot.getRangeAxis();\r
+                    rangeAxis.setAutoRange(false);\r
+                    if(result.minY == null) result.minY = rangeAxis.getLowerBound();\r
+                    if(result.maxY == null) result.maxY = rangeAxis.getUpperBound();\r
+                    rangeAxis.setRange(result.minY, result.maxY);\r
+                    ValueAxis domainAxis = plot.getDomainAxis();\r
+                    domainAxis.setAutoRange(false);\r
+                    if(result.minX == null) result.minX = domainAxis.getLowerBound();\r
+                    if(result.maxX == null) result.maxX = domainAxis.getUpperBound();\r
+                    domainAxis.setRange(result.minX, result.maxX);\r
+\r
+                }\r
+\r
+                @Override\r
+                public boolean isDisposed() {\r
+                    return swtawtcomponent.isDisposed();\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+\r
+    private JFreeChart createChart() {\r
+        XYDataset dataset = createDataset(null);\r
+        chart = ChartFactory.createXYLineChart(null, null, null,\r
+                dataset, PlotOrientation.VERTICAL, false, true, false);\r
+        XYPlot plot = (XYPlot) chart.getPlot();\r
+        XYLineAndShapeRenderer renderer\r
+        = (XYLineAndShapeRenderer) plot.getRenderer();\r
+        renderer.setBaseShapesVisible(true);\r
+        renderer.setDrawOutlines(true);\r
+        renderer.setUseFillPaint(true);\r
+        renderer.setBaseFillPaint(Color.white);\r
+        renderer.setSeriesStroke(0, new BasicStroke(3.0f));\r
+        renderer.setSeriesOutlineStroke(0, new BasicStroke(2.0f));\r
+        renderer.setSeriesShape(0, new Ellipse2D.Double(-5.0, -5.0, 10.0, 10.0));\r
+        return chart;\r
+    }\r
+\r
+    public XYDataset createDataset(String table) {\r
+        XYSeries series = new XYSeries("Series");\r
+        \r
+        if(table != null) {\r
+            TableParser parser = new TableParser(new StringReader(""));\r
+            parser.ReInit(new StringReader(table));\r
+            try {\r
+                parser.table();\r
+                ArrayList<Token> xTokens = parser.getXTokens();\r
+                ArrayList<Token> yTokens = parser.getYTokens();\r
+                for(int i = 0; i < xTokens.size(); i++) {\r
+                    series.add(\r
+                            Double.parseDouble(xTokens.get(i).image), \r
+                            Double.parseDouble(yTokens.get(i).image));\r
+                }\r
+            } catch (ParseException e1) {\r
+            }\r
+        }\r
+        \r
+        XYSeriesCollection dataset = new XYSeriesCollection();\r
+        dataset.addSeries(series);\r
+        return dataset;\r
+    }\r
+\r
+    public LookupChartPanel getChartPanel() {\r
+        return this.chartPanel;\r
+    }\r
+\r
+    public JFreeChart getChart() {\r
+        return this.chart;\r
+    }\r
+\r
+    private class _SeriesChangeListener implements SeriesChangeListener {\r
+\r
+        Resource expression;\r
+        \r
+        public _SeriesChangeListener(Resource expression) {\r
+            this.expression = expression;\r
+        }\r
+        @Override\r
+        public void seriesChanged(SeriesChangeEvent event) {\r
+            if(chartPanel.isDragging()) return;\r
+\r
+            StringBuilder b = new StringBuilder();\r
+            b.append("{");\r
+            XYSeriesCollection collection = (XYSeriesCollection) ((XYPlot)chart.getPlot()).getDataset();\r
+            XYSeries series = collection.getSeries(0);\r
+            if(series.isEmpty())\r
+                return;\r
+            Iterator<?> iterator = series.getItems().iterator();\r
+            while(iterator.hasNext()){\r
+                XYDataItem item = (XYDataItem)iterator.next();\r
+                b.append("{" + item.getX() + "," + item.getY() + "}");\r
+                if(iterator.hasNext())\r
+                    b.append(",");\r
+            }\r
+            b.append("}");\r
+            final String table = b.toString();\r
+\r
+            SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    graph.claimLiteral(expression, sr.WithLookupExpression_lookup, table);\r
+                }\r
+            });\r
+\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ColumnKeys.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ColumnKeys.java
new file mode 100644 (file)
index 0000000..1a9dda4
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import org.simantics.browsing.ui.Column;\r
+import org.simantics.browsing.ui.Column.Align;\r
+\r
+public class ColumnKeys {\r
+       \r
+       public static final String   ENUMERATION           = "Enumeration";\r
+       public static final String   INDEXES               = "Indexes";\r
+       public static final String   SHOW_IN_CHARTS    = "ShowInCharts";\r
+       public static final String   REPLACED_WITH     = "Replaced with";\r
+       public static final String   MODULE_PARAMETER  = "Parameter in Module";\r
+       public static final String   VALUE             = "Value";\r
+       \r
+       public static String[] ENUMERATION_COLUMNS_KEYS = { ENUMERATION, INDEXES };\r
+    public static Column[] ENUMERATION_TABLE_COLUMNS = new Column[] {\r
+        new Column(ENUMERATION, Align.LEFT, 100, "Enumeration", false),\r
+        new Column(INDEXES, Align.LEFT, 100, "Indexes", true),\r
+    };\r
+    \r
+\r
+       public static String[] ENUMERATION_INDEX_COLUMNS_KEYS = { ENUMERATION, SHOW_IN_CHARTS };\r
+    public static Column[] ENUMERATION_INDEX_TABLE_COLUMNS = new Column[] {\r
+        new Column(ENUMERATION, Align.LEFT, 100, "Enumeration", true),\r
+        new Column(SHOW_IN_CHARTS, Align.LEFT, 20, "Show in charts", false),\r
+    };\r
+    \r
+       public static String[] ENUMERATION_REDECLARATION_KEYS = { ENUMERATION, REPLACED_WITH };\r
+    public static Column[] ENUMERATION_REDECLARATION_COLUMNS = new Column[] {\r
+        new Column(ENUMERATION, Align.LEFT, 200, "Enumeration in module", false),\r
+        new Column(REPLACED_WITH, Align.LEFT, 200, "Replaced with", true),\r
+    };\r
+    \r
+    public static String[] MODULE_PARAMETER_KEYS = { MODULE_PARAMETER, VALUE };\r
+    public static Column[] MODULE_PARAMETER_COLUMNS = new Column[] {\r
+        new Column(MODULE_PARAMETER, Align.LEFT, 200, MODULE_PARAMETER, false),\r
+        new Column(VALUE, Align.LEFT, 200, VALUE, true),\r
+    };\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/CustomFontDialog.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/CustomFontDialog.java
new file mode 100644 (file)
index 0000000..8bf97ce
--- /dev/null
@@ -0,0 +1,380 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.awt.Color;\r
+import java.awt.Font;\r
+import java.util.LinkedHashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.dialogs.Dialog;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.preference.IPreferenceStore;\r
+import org.eclipse.jface.preference.PreferenceConverter;\r
+import org.eclipse.jface.resource.FontDescriptor;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.nebula.widgets.tablecombo.TableCombo;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.graphics.FontData;\r
+import org.eclipse.swt.graphics.Image;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.eclipse.swt.graphics.Rectangle;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableItem;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferences;\r
+import org.simantics.utils.ui.gfx.ColorImageDescriptor;\r
+\r
+/**\r
+ * Custom dialog for selecting font and font color. Similar to SWT FontDialog.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class CustomFontDialog extends Dialog {\r
+    \r
+    private Map<String, Integer> systemColors = createColorMap();\r
+    \r
+    private FontData resultSWTFontData;\r
+    private Font awtFont;\r
+    private Font resultAWTFont;\r
+    private Color color;\r
+    private Color resultAWTColor;\r
+    \r
+    private FontSelectionComposite vpc;\r
+    private TableCombo tc;\r
+    \r
+    private String example = "Example";\r
+    private Label sample;\r
+    private Group sampleGroup;\r
+    private RGB rgb;\r
+    \r
+    private LocalResourceManager resourceManager;\r
+\r
+\r
+    // Default color map\r
+    protected static Map<String, Integer> createColorMap() {\r
+        LinkedHashMap<String, Integer> colors  =     new LinkedHashMap<String, Integer>();\r
+        colors.put("Black", SWT.COLOR_BLACK);\r
+        colors.put("White", SWT.COLOR_WHITE);\r
+        colors.put("Blue", SWT.COLOR_BLUE);\r
+        colors.put("Dark Blue", SWT.COLOR_DARK_BLUE);\r
+        colors.put("Red", SWT.COLOR_RED);\r
+        colors.put("Dark Red", SWT.COLOR_DARK_RED);\r
+        colors.put("Yellow", SWT.COLOR_YELLOW);\r
+        colors.put("Dark Yellow", SWT.COLOR_DARK_YELLOW);\r
+        colors.put("Gray", SWT.COLOR_GRAY);\r
+        colors.put("Dark Gray", SWT.COLOR_DARK_GRAY);\r
+        colors.put("Green", SWT.COLOR_GREEN);\r
+        colors.put("Dark Green", SWT.COLOR_DARK_GREEN);\r
+        colors.put("Cyan", SWT.COLOR_CYAN);\r
+        colors.put("Dark Cyan", SWT.COLOR_DARK_CYAN);\r
+        colors.put("Magenta", SWT.COLOR_MAGENTA);\r
+        colors.put("Dark Magenta", SWT.COLOR_DARK_MAGENTA);\r
+        return colors;\r
+    }\r
+\r
+    /**\r
+     * Creates a font dialog with sample text\r
+     * @param parentShell\r
+     * @param example Sample text in the dialog. Null example => "Example"\r
+     */\r
+    public CustomFontDialog(Shell parentShell, String example) {\r
+        super(parentShell);\r
+        if(example != null)\r
+            this.example = example;\r
+    }\r
+\r
+    /**\r
+     * Sets the initial font for this dialog\r
+     * @param awtFont Current AWT font\r
+     */\r
+    public void setAWTFont(java.awt.Font awtFont) {\r
+        this.awtFont = awtFont; \r
+        this.resultAWTFont = awtFont;\r
+    }\r
+\r
+    /**\r
+     * Get selected font as AWT font\r
+     * @return AWT font\r
+     */\r
+    public java.awt.Font getAWTFont() {\r
+        return resultAWTFont;\r
+    }\r
+    \r
+    /**\r
+     * Get selected font as SWT font dta\r
+     * @return\r
+     */\r
+    public FontData getSWTFontData() {\r
+        return resultSWTFontData;\r
+    }\r
+    \r
+    /**\r
+     * Set initial color for this dialog\r
+     * @param color AWT color\r
+     */\r
+    public void setColor(Color color) {\r
+        this.color = color;\r
+        this.resultAWTColor = color;\r
+    }\r
+    \r
+    /**\r
+     * Get selected color as AWT color\r
+     * @return\r
+     */\r
+    public Color getAWTColor() {\r
+        return resultAWTColor;\r
+    }\r
+    \r
+    /**\r
+     * Get selected color as RGB\r
+     * @return\r
+     */\r
+    public RGB getRGB() {\r
+        return rgb;\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Creates font choosing area\r
+     * @param parent Parent composite\r
+     */\r
+    protected void createFontChooser(Composite parent) {\r
+        vpc = new FontSelectionComposite(parent, SWT.NONE);\r
+        vpc.setFont(awtFont, false);\r
+        GridDataFactory.fillDefaults().span(2, 1).applyTo(vpc);\r
+        \r
+        vpc.addFontModifiedListener(new FontModifyListener() {\r
+            \r
+            @Override\r
+            public void swtFontDataChanged(FontData fd) {\r
+                sample.setFont(resourceManager.createFont(FontDescriptor.createFrom(fd)));\r
+                sampleGroup.layout();\r
+            }\r
+            \r
+            @Override\r
+            public void awtFontChanged(Font font) {\r
+            }\r
+        });      \r
+        \r
+    }\r
+    \r
+    /**\r
+     * Creates a TableCombo for choosing a color for a font\r
+     * @param parent Parent composite\r
+     */\r
+    protected void createColorChooser(Composite parent) {\r
+        // Create a ResourceManager to dispose images when the widget is disposed.\r
+        this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent);\r
+        \r
+        Composite colorComposite = new Composite(parent, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).applyTo(colorComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(colorComposite);\r
+        \r
+        Label label = new Label(colorComposite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).applyTo(label);\r
+        label.setText("Color: ");        \r
+\r
+        tc = new TableCombo(colorComposite, SWT.BORDER | SWT.READ_ONLY);\r
+        GridDataFactory.fillDefaults().hint(170, SWT.DEFAULT).applyTo(tc);\r
+        \r
+        tc.defineColumns(2);\r
+        tc.setDisplayColumnIndex(1);\r
+        tc.setToolTipText("this is tooltip");\r
+        \r
+        createColorItems(tc.getTable());\r
+\r
+        if(this.color != null) {\r
+            for(int i = 0; i < tc.getTable().getItemCount(); i++) {\r
+                TableItem ti = tc.getTable().getItem(i);\r
+                RGB rgb = (RGB) ti.getData();\r
+                if(rgb.red == this.color.getRed() &&\r
+                        rgb.green == this.color.getGreen() &&\r
+                        rgb.blue == this.color.getBlue()) {\r
+                    tc.setText(ti.getText(1));\r
+                    tc.setForeground(resourceManager.createColor(rgb));\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+        \r
+        // add listener\r
+        tc.addSelectionListener(new SelectionListener() {\r
+            \r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                TableItem[] selection = tc.getTable().getSelection();\r
+                if(selection.length == 1) {\r
+                    rgb = (RGB) selection[0].getData();\r
+                    org.eclipse.swt.graphics.Color swtColor = resourceManager.createColor(rgb);\r
+                    sample.setForeground(swtColor);\r
+                    tc.setForeground(swtColor);\r
+                }\r
+                tc.getTextControl().setSelection(0);\r
+                tc.getParent().forceFocus();\r
+            }\r
+            \r
+            @Override\r
+            public void widgetDefaultSelected(SelectionEvent e) {\r
+            }\r
+        });\r
+    }\r
+\r
+    /**\r
+     * Creates a sample text area\r
+     * @param parent Parent composite\r
+     */\r
+    protected void createSampleArea(Composite parent) {\r
+        sampleGroup = new Group(parent, SWT.NONE);\r
+        sampleGroup.setText("Sample");\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 70).applyTo(sampleGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(sampleGroup);\r
+\r
+        sample = new Label(sampleGroup, SWT.NONE);\r
+        sample.setText(example);\r
+        if(awtFont != null) {\r
+            sample.setFont(resourceManager.createFont(FontDescriptor.createFrom(toSwtFontData(awtFont))));\r
+        }\r
+        if(rgb != null) {\r
+            sample.setForeground(resourceManager.createColor(rgb));\r
+        }\r
+        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).grab(true, true).applyTo(sample);\r
+    }\r
+    \r
+    @Override\r
+    protected Control createDialogArea(Composite parent)\r
+    {\r
+        Composite composite = ( Composite )super.createDialogArea(parent);\r
+        composite.getShell().setText("Choose Font");\r
+\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
+        \r
+        // Init SWT RGB, if AWT color has been set\r
+        if(color != null)\r
+            this.rgb = new RGB(color.getRed(), color.getGreen(), color.getBlue());\r
+\r
+        // Font selection composite\r
+        createFontChooser(composite);\r
+        \r
+        // Color selection\r
+        createColorChooser(composite);\r
+        \r
+        // Sample text\r
+        createSampleArea(composite);\r
+\r
+        //Set the dialog position in the middle of the monitor\r
+        setDialogLocationToMonitorCenter();\r
+\r
+        return composite;\r
+    }\r
+\r
+    @Override\r
+    protected void cancelPressed() {\r
+        resultAWTFont = awtFont;\r
+        resultAWTColor = color;\r
+        if(resultAWTFont != null)\r
+               resultSWTFontData =  toSwtFontData(resultAWTFont);\r
+\r
+        setReturnCode(CANCEL);\r
+        close();\r
+    }\r
+\r
+    @Override\r
+    protected void okPressed() {\r
+        resultAWTFont = vpc.getAWTFont();\r
+        resultSWTFontData =  toSwtFontData(resultAWTFont);\r
+        \r
+        TableItem[] selection = tc.getTable().getSelection();\r
+        if(selection.length == 1) {\r
+            RGB rgb = (RGB) selection[0].getData();\r
+            resultAWTColor = new Color(rgb.red, rgb.green, rgb.blue);\r
+        }\r
+\r
+        setReturnCode(OK);\r
+        close();\r
+    }\r
+\r
+    /**\r
+     * Sets the dialog location to the middle of the screen\r
+     */\r
+    protected void setDialogLocationToMonitorCenter() {\r
+        Rectangle monitorArea = getShell().getDisplay().getPrimaryMonitor().getBounds();\r
+        Rectangle shellArea = getShell().getBounds();\r
+        int x = monitorArea.x + (monitorArea.width - shellArea.width)/2;\r
+        int y = monitorArea.y + (monitorArea.height - shellArea.height)/2;\r
+        getShell().setLocation(x,y);\r
+    }\r
+    \r
+    /**\r
+     * Builds SWT FontData from AWT font. Simple conversion.\r
+     * \r
+     * @param font AWT font\r
+     * @param height Height for the created data (or -1 if inherited directly from awt font, size matching not guaranteed)\r
+     * @return\r
+     */\r
+    protected static FontData toSwtFontData(Font font) {\r
+        FontData fontData = new FontData();\r
+        fontData.setName(font.getFontName());\r
+        fontData.setStyle(font.getStyle());\r
+        fontData.setHeight(font.getSize());\r
+        return fontData;\r
+    }\r
+    \r
+    /**\r
+     * Creates color items for color combo\r
+     * @param table\r
+     */\r
+    protected void createColorItems(Table table) {\r
+        Image image;\r
+        TableItem ti;\r
+        int code;\r
+        RGB color;\r
+        Display display = Display.getCurrent();\r
+        \r
+        //IWorkbenchPage iwp = SysdynWorkbenchUtils.getActivePageOfEditor();\r
+               //final ICanvasContext context = (ICanvasContext)iwp.getActiveEditor().getAdapter(ICanvasContext.class);\r
+        \r
+        IPreferenceStore store = Activator.getDefault().getPreferenceStore();\r
+        color = PreferenceConverter.getColor(store, SysdynDiagramPreferences.ARROW_COLOR);\r
+        image = resourceManager.createImage(new ColorImageDescriptor(color.red, color.green, color.blue, 25, 15, false));\r
+        \r
+        ti = new TableItem(table, SWT.NONE);\r
+        ti.setImage(0, image);\r
+        ti.setText(1, "Default Arrow");\r
+        ti.setForeground(display.getSystemColor(SWT.COLOR_BLACK));\r
+        ti.setData(color);\r
+        \r
+        for(String text : systemColors.keySet()) {\r
+            code = systemColors.get(text);\r
+            color = display.getSystemColor(code).getRGB();\r
+            image = resourceManager.createImage(new ColorImageDescriptor(color.red, color.green, color.blue, 25, 15, false));\r
+            \r
+            ti = new TableItem(table, SWT.NONE);\r
+            ti.setImage(0, image);\r
+            ti.setText(1, text);\r
+            ti.setForeground(display.getSystemColor(SWT.COLOR_BLACK));\r
+            ti.setData(color);\r
+        }\r
+        \r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/DelayMarkWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/DelayMarkWidget.java
new file mode 100644 (file)
index 0000000..e5d4e0e
--- /dev/null
@@ -0,0 +1,169 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Widget for Delay marks in dependencies.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class DelayMarkWidget implements Widget{\r
+\r
+    List<Resource> variables = null; \r
+    org.simantics.browsing.ui.swt.widgets.Button delayMarkButton;\r
+    \r
+    public DelayMarkWidget(Composite parent, WidgetSupport support, int style) {\r
+        support.register(this);\r
+        delayMarkButton = new org.simantics.browsing.ui.swt.widgets.Button(parent, support, style |= SWT.CHECK);\r
+        delayMarkButton.setText("Delay mark");\r
+    }\r
+\r
+    @SuppressWarnings({ "rawtypes", "unchecked" })\r
+       @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        if(input instanceof ISelection) {\r
+            ISelection selection = (ISelection)input;\r
+            if(selection instanceof IStructuredSelection) {\r
+               List<Resource> resources = ISelectionUtils.filterSelection(selection, Resource.class);\r
+                if(resources != null && !resources.isEmpty()) {\r
+                    variables = resources;\r
+                } else {\r
+                       List<ArrayList> resourceLists = ISelectionUtils.filterSelection(selection, ArrayList.class);\r
+                       variables = resourceLists.get(0);\r
+                }\r
+            }\r
+        }\r
+\r
+        if(variables == null) return;\r
+        \r
+        try {\r
+            context.getSession().syncRequest(new ReadRequest() {\r
+                \r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    \r
+                    // Determine if there are delay marks in some of the variables.\r
+                    boolean hasDelayMarks = false, hasNotDelayMarks = false;\r
+                    for (Resource variable : variables) {\r
+                       if (graph.hasStatement(variable, sr.DependencyConnection_delayMark)) {\r
+                               hasDelayMarks = true;\r
+                       } else {\r
+                               hasNotDelayMarks = true;\r
+                       }\r
+                    }\r
+                    \r
+                    // If some have delay marks but others don't, the check box is grayed.\r
+                    final Button button = getWidget();\r
+                    final boolean delayMark = hasDelayMarks;\r
+                    final boolean mixedDelayMarks = hasDelayMarks && hasNotDelayMarks;\r
+                       button.getDisplay().asyncExec(new Runnable() {\r
+                               \r
+                        @Override\r
+                        public void run() {\r
+                            if(button.isDisposed()) return;\r
+                            button.setSelection(delayMark);\r
+                            button.setGrayed(mixedDelayMarks);\r
+                        }\r
+                    });\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        // Multiple selections\r
+        delayMarkButton.addSelectionListener(new SelectionListenerImpl<ArrayList<Resource>>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, ArrayList<Resource> inputs) throws DatabaseException {\r
+                if (inputs == null)\r
+                       return;\r
+                \r
+                final SysdynResource sr =  SysdynResource.getInstance(graph);\r
+                boolean nextState = true; // The next state of the checkbox\r
+                for (Resource variable : variables) {\r
+                       if (graph.hasStatement(variable, sr.DependencyConnection_delayMark)) {\r
+                               nextState = false; // The next state is true iff at least one has the delay mark.\r
+                               break;\r
+                       }\r
+                }\r
+\r
+               try {\r
+                       if (nextState) {\r
+                                               for (Resource input : inputs) {\r
+                                                       graph.claim(input, SysdynResource.getInstance(graph).DependencyConnection_delayMark, null, input);\r
+                                               }\r
+                                       } else {\r
+                                               for (Resource input : inputs) {\r
+                                                       graph.deny(input, sr.DependencyConnection_delayMark);\r
+                                               }\r
+                                       }\r
+               } catch (DatabaseException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+                \r
+               // Get the button out of the grayed state.\r
+               final Button button = getWidget();\r
+                button.getDisplay().asyncExec(new Runnable() {\r
+                    \r
+                    @Override\r
+                    public void run() {\r
+                       button.setGrayed(false);\r
+                    }\r
+                });\r
+            }\r
+        });\r
+        \r
+        // One selection\r
+        delayMarkButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                if (input == null)\r
+                       return;\r
+                \r
+                final SysdynResource sr =  SysdynResource.getInstance(graph);\r
+                if(graph.hasStatement(input, sr.DependencyConnection_delayMark)) {\r
+                           graph.deny(input, sr.DependencyConnection_delayMark);\r
+                       } else {\r
+                           graph.claim(input, SysdynResource.getInstance(graph).DependencyConnection_delayMark, null, input);\r
+                       }\r
+            }  \r
+        });\r
+    }\r
+    \r
+    public Button getWidget() {\r
+        return delayMarkButton.getWidget();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/EquivalentUnitsWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/EquivalentUnitsWidget.java
new file mode 100644 (file)
index 0000000..1310655
--- /dev/null
@@ -0,0 +1,143 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.issues.ontology.IssueResource;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Widget for equivalent units selection.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class EquivalentUnitsWidget implements Widget{\r
+\r
+    Resource model = null; \r
+    org.simantics.browsing.ui.swt.widgets.Button unitEquivalents;\r
+    \r
+    public EquivalentUnitsWidget(Composite parent, WidgetSupport support, int style) {\r
+        support.register(this);\r
+        unitEquivalents = new org.simantics.browsing.ui.swt.widgets.Button(parent, support, style |= SWT.CHECK);\r
+        unitEquivalents.setText("Unit equivalents");\r
+        unitEquivalents.getWidget().setToolTipText("Supported equivalent units:\n" +\r
+                       "$, $s, dollar, dollars, usd\n"+\r
+                       "\u20ac, \u20acs, eur, euro, euros, e, ecu\n"+\r
+                       "£, Â£s, pound, pounds, gbp\n"+\r
+                       "Unit, Units\n"+\r
+                       "Person, People, Persons\n"+\r
+                       "second, seconds, sec, s\n"+\r
+                       "minute, minutes, min\n"+\r
+                       "hour, hours, h, hr\n"+\r
+                       "day, days, d\n"+\r
+                       "month, months, mon, mth, mo, mos\n"+\r
+                       "year, years, a, y, yr");\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        if(input instanceof ISelection) {\r
+            ISelection selection = (ISelection)input;\r
+            if(selection instanceof IStructuredSelection) {\r
+                Resource resource = ISelectionUtils.filterSingleSelection(selection, Resource.class);\r
+                if(resource != null) {\r
+                    model = resource;\r
+                }\r
+            }\r
+        }\r
+        \r
+        if(model == null) return;\r
+        \r
+        try {\r
+            context.getSession().syncRequest(new ReadRequest() {\r
+                \r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                       // Determine if unit validation is enabled.\r
+                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    final Resource unitIssueSource = graph.syncRequest(\r
+                            new PossibleObjectWithType(model, \r
+                                    Layer0X.getInstance(graph).Activates, \r
+                                    sr.Validations_Units_UnitIssueSource));\r
+                    IssueResource ISSUE = IssueResource.getInstance(graph);\r
+                    final Boolean issueSource_active = graph.getPossibleRelatedValue(unitIssueSource, ISSUE.IssueSource_active, Bindings.BOOLEAN);\r
+                    \r
+                    Boolean result = false;\r
+                    if(unitIssueSource != null) {\r
+                       result = graph.getPossibleRelatedValue(unitIssueSource, sr.Validations_Units_UnitIssueSource_allowEquivalents, Bindings.BOOLEAN);\r
+                    }\r
+\r
+                    final boolean enable = result;\r
+                    final Button button = getWidget();\r
+                    button.getDisplay().asyncExec(new Runnable() {\r
+                        \r
+                        @Override\r
+                        public void run() {\r
+                            if(button.isDisposed()) return;\r
+                            \r
+                            // Is unit validation is enabled, enable the button.\r
+                            getWidget().setEnabled(unitIssueSource!=null && issueSource_active);\r
+                            if(Boolean.TRUE.equals(enable))\r
+                               button.setSelection(true);\r
+                            else\r
+                                button.setSelection(false);\r
+                        }\r
+                    });                        \r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        unitEquivalents.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource model) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                Resource unitIssueSource = graph.syncRequest(\r
+                        new PossibleObjectWithType(model, \r
+                                Layer0X.getInstance(graph).Activates, \r
+                                sr.Validations_Units_UnitIssueSource));\r
+                if(unitIssueSource == null)\r
+                    return;\r
+                \r
+                Boolean result = graph.getPossibleRelatedValue(unitIssueSource, sr.Validations_Units_UnitIssueSource_allowEquivalents, Bindings.BOOLEAN);\r
+                if(result == null)\r
+                    result = false;\r
+                graph.claimLiteral(unitIssueSource, sr.Validations_Units_UnitIssueSource_allowEquivalents, Boolean.FALSE.equals(result));\r
+            }\r
+        });\r
+    }\r
+    \r
+    public Button getWidget() {\r
+        return unitEquivalents.getWidget();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionTypes.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionTypes.java
new file mode 100644 (file)
index 0000000..7b3b20b
--- /dev/null
@@ -0,0 +1,87 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Expression type representations\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ExpressionTypes {\r
+\r
+       public static enum ExpressionType {Auxiliary, Parameter, Constant, Lookup, WithLookup, Stock, Delay, Empty};\r
+\r
+       public static ExpressionType[] auxiliaryExpressions = new ExpressionType[] {\r
+               ExpressionType.Auxiliary, \r
+               ExpressionType.Parameter, \r
+               ExpressionType.Constant, \r
+               ExpressionType.Delay,\r
+               // ExpressionType.Lookup, \r
+               ExpressionType.WithLookup};\r
+\r
+       public static ExpressionType[] valveExpressions = new ExpressionType[] {\r
+               ExpressionType.Auxiliary, \r
+               ExpressionType.Parameter, \r
+               ExpressionType.Constant, \r
+               ExpressionType.Delay,\r
+               ExpressionType.WithLookup};\r
+\r
+       public static ExpressionType[] stockExpressions = new ExpressionType[] {\r
+               ExpressionType.Stock};\r
+\r
+       public static ExpressionType getExpressionType(final Resource expression) {\r
+               try {\r
+                       return SimanticsUI.getSession().syncRequest(new Read<ExpressionType>() {\r
+\r
+                               @Override\r
+                               public ExpressionType perform(ReadGraph graph) throws DatabaseException {\r
+                                       return getExpressionType(graph, expression);\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+                       return null;\r
+               }\r
+\r
+       }\r
+       \r
+       public static ExpressionType getExpressionType(ReadGraph graph, final Resource expression) throws DatabaseException {\r
+               ExpressionType et = null;\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               if(graph.isInstanceOf(expression, sr.NormalExpression)) {\r
+                       et = ExpressionType.Auxiliary;\r
+               } else if (graph.isInstanceOf(expression, sr.StockExpression)) {\r
+                       et = ExpressionType.Stock;\r
+               } else if (graph.isInstanceOf(expression, sr.ParameterExpression)) {\r
+                       et = ExpressionType.Parameter;\r
+               } else if (graph.isInstanceOf(expression, sr.ConstantExpression)) {\r
+                       et = ExpressionType.Constant;\r
+               } else if (graph.isInstanceOf(expression, sr.DelayExpression)) {\r
+                       et = ExpressionType.Delay;\r
+               } else if (graph.isInstanceOf(expression, sr.LookupExpression)) {\r
+                       et = ExpressionType.Lookup;\r
+               } else if (graph.isInstanceOf(expression, sr.WithLookupExpression)) {\r
+                       et = ExpressionType.WithLookup;\r
+               } else {\r
+                       et =  ExpressionType.Empty;\r
+               }\r
+               return et;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionWidget.java
new file mode 100644 (file)
index 0000000..07b448b
--- /dev/null
@@ -0,0 +1,272 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.awt.event.ActionEvent;\r
+import java.awt.event.ActionListener;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import javax.swing.Timer;\r
+\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes.ExpressionType;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.AuxiliaryExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ConstantExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.DelayExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.EmptyExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionComposite;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionWidgetInput;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.IExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ParameterExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.StockExpression;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.WithLookupExpression;\r
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+/**\r
+ * Widget for displaying an expression. Widget creates the IExpression for displaying\r
+ * properties for each expression type and adds validation, saving and other services\r
+ * to the active IExpression.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ExpressionWidget implements Widget {\r
+\r
+    private ExpressionWidgetInput input;\r
+       private Resource expr;\r
+       private Variable variable;\r
+       private Composite parent;\r
+       private Map<String, Object> data;\r
+       private IExpression expression;\r
+       private ModifyListener modifyListener;\r
+       private FocusListener focusListener;\r
+       private Table variableTable;\r
+       private VerifyKeyListener verifyKeyListener;\r
+    private Timer validationTimer;\r
+    private static int VALIDATION_DELAY_TIME = 500;\r
+    private final LocalResourceManager resourceManager;\r
+    \r
+    /**\r
+     * Create a new expression widget\r
+     * @param parent\r
+     * @param support\r
+     * @param style\r
+     */\r
+    public ExpressionWidget(Composite parent, WidgetSupport support, int style) {\r
+               support.register(this);\r
+               this.parent = parent;\r
+               if (parent instanceof ExpressionComposite) {\r
+                   ExpressionComposite expressionComposite = (ExpressionComposite)parent;\r
+                   expressionComposite.setExpressionWidget(this);\r
+               }\r
+               this.data = new HashMap<String, Object>();\r
+               \r
+               // Create a ResourceManager to dispose images when the widget is disposed.\r
+        this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), this.parent);\r
+        \r
+               /*\r
+                *  Create a validation timer for expression fields. Validation timer\r
+                *  validates the field as the modeler is typing an expression \r
+                */\r
+               validationTimer = new Timer(VALIDATION_DELAY_TIME, new ActionListener() {\r
+\r
+            @Override\r
+            public void actionPerformed(ActionEvent e) {\r
+               if(variableTable == null || variableTable.isDisposed())\r
+                       return;\r
+                       variableTable.getDisplay().asyncExec(new Runnable() {\r
+                               \r
+                               @Override\r
+                               public void run() {\r
+                                       validateFields();\r
+                               }\r
+                       });\r
+            }\r
+        });\r
+               validationTimer.setRepeats(false);\r
+       }\r
+   \r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {  \r
+           // Update IExpression based on the newly selected expression\r
+               ExpressionWidgetInput i =  AdaptionUtils.adaptToSingle(input, ExpressionWidgetInput.class);\r
+               this.input = i;\r
+               expr = i.expression;\r
+               variable = i.variable;\r
+               ExpressionType et = ExpressionTypes.getExpressionType(expr);\r
+               displayExpression(et.toString(), true);\r
+       }\r
+\r
+       /**\r
+        * Displays IExpression corresponding to expressionType.\r
+        * @param expressionType Expression type\r
+        * @param original Is the displayed expression for a newly selected expression (true) or did the\r
+        * expression change its type (false) \r
+        */\r
+       public void displayExpression(String expressionType, boolean original) {\r
+               if(expressionType == null || parent.isDisposed()) {\r
+                       return;\r
+               }\r
+\r
+               // Get up-to-date data to data-map\r
+               if(this.expression != null) expression.updateData(data);\r
+               \r
+               // Create the new expression\r
+               ExpressionType et = ExpressionType.valueOf(expressionType);\r
+               IExpression exp = null;\r
+               switch (et) {\r
+               case Auxiliary: \r
+                       exp = new AuxiliaryExpression(input); break;\r
+               case Parameter: \r
+                       exp = new ParameterExpression(input); break;\r
+               case Constant: \r
+                       exp = new ConstantExpression(input); break;\r
+               case Lookup: \r
+                       exp = new LookupExpression(); break;\r
+               case WithLookup: \r
+                       exp = new WithLookupExpression(input); break;\r
+               case Stock: \r
+                       exp = new StockExpression(input); break;\r
+               case Delay: \r
+                       exp = new DelayExpression(input); break;\r
+               default: \r
+                       exp = new EmptyExpression();\r
+               }\r
+\r
+               if (exp != null) {\r
+                   // If expression was created, remove the old one\r
+                       for(Control c : parent.getChildren()) {\r
+                               c.dispose();\r
+                       } \r
+\r
+                       // If a completely new expression was selected, read data\r
+                       if(original) \r
+                               exp.readData(expr, data);\r
+\r
+                       // Create the visual representation of the expression type\r
+                       exp.createExpressionFields(parent, data, variableTable);\r
+                       \r
+                       // Add listeners\r
+                       if(modifyListener != null)\r
+                               exp.addModifyListener(modifyListener);\r
+                       if(focusListener != null)\r
+                               exp.addFocusListener(focusListener);\r
+                       if(verifyKeyListener != null)\r
+                               exp.addVerifyKeyListener(verifyKeyListener);\r
+                       this.expression = exp;\r
+                       this.parent.layout();\r
+                       validateFieldsTimed();\r
+\r
+                       save();\r
+               }  \r
+       }\r
+\r
+       /**\r
+        * Get current IExpression\r
+        * @return current IExpression\r
+        */\r
+       public IExpression getExpression() {\r
+               return expression;\r
+       }\r
+\r
+       /**\r
+        * Set the variable table that contains information about variables that are connected \r
+        * to this expression\r
+        * @param table\r
+        */\r
+       public void setVariableTable(Table table) {\r
+               this.variableTable = table;\r
+       }\r
+\r
+       /**\r
+        * Set timed field validation with default delay time\r
+        */\r
+    public void validateFieldsTimed() {        \r
+       validateFieldsTimed(VALIDATION_DELAY_TIME);\r
+    }\r
+    \r
+    /**\r
+     * Set timed field validation\r
+     * @param delay Delay time for validation\r
+     */\r
+    public void validateFieldsTimed(int delay) {\r
+        validationTimer.setDelay(delay);\r
+        if(!validationTimer.isRunning())\r
+            validationTimer.start();\r
+        else\r
+            validationTimer.restart();\r
+    }\r
+    \r
+    /**\r
+     * Validates expression fields in current IExpression\r
+     */\r
+       public void validateFields() {\r
+               if(this.variableTable == null) return;\r
+        \r
+               try {\r
+                   // Find the variable for this experession\r
+                       Resource variable = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       return graph.getPossibleObject(expr, l0.PartOf);\r
+                               }\r
+                       });\r
+                       // Validate the variable\r
+                       if(variable != null)\r
+                               ExpressionUtils.validateExpressionFields(variable, expression, variableTable, resourceManager);\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+       }\r
+\r
+       public void addModifyListener(ModifyListener listener) {\r
+               this.modifyListener = listener;\r
+       }\r
+\r
+       public void addVerifyKeyListener(VerifyKeyListener listener) {\r
+               this.verifyKeyListener = listener;\r
+       }\r
+       \r
+       public void addFocusListener(FocusListener listener) {\r
+               this.focusListener = listener;\r
+       }\r
+\r
+       public void save() {\r
+               if(this.expression != null)\r
+                       this.expression.save(expr, data);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FontModifyListener.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FontModifyListener.java
new file mode 100644 (file)
index 0000000..eb1e11b
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.awt.Font;\r
+\r
+import org.eclipse.swt.graphics.FontData;\r
+\r
+/**\r
+ * Font change listening interface\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface FontModifyListener {\r
+    \r
+    /**\r
+     * Called when font is changed\r
+     * @param font New font as AWT font\r
+     */\r
+    public void awtFontChanged(Font font);\r
+    \r
+    /**\r
+     * Called when font is changed\r
+     * @param font New font data as SWT font data\r
+     */\r
+    public void swtFontDataChanged(FontData font);\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FontSelectionComposite.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FontSelectionComposite.java
new file mode 100644 (file)
index 0000000..9a8f438
--- /dev/null
@@ -0,0 +1,681 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.awt.Font;\r
+import java.awt.GraphicsEnvironment;\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.TreeMap;\r
+\r
+import org.eclipse.core.runtime.ListenerList;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.FontDescriptor;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.KeyEvent;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.graphics.FontData;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.graphics.Rectangle;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.eclipse.swt.widgets.Listener;\r
+import org.eclipse.swt.widgets.ScrollBar;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableColumn;\r
+import org.eclipse.swt.widgets.TableItem;\r
+import org.eclipse.swt.widgets.Text;\r
+\r
+/**\r
+ * Composite for displaying font selection tools. By default, the composite contains\r
+ * font family, font style and font size.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FontSelectionComposite extends Composite {\r
+\r
+\r
+    protected Text fontName, fontStyle, fontSize;\r
+    protected ArrayList<String> familyIndex = new ArrayList<String>();\r
+    protected TreeMap<String, ArrayList<Font>> fonts = getFonts(familyIndex);\r
+    protected Table fontFamilyTable, fontStyleTable, fontSizeTable;\r
+    protected String[] sizes = new String[] {"8", "9", "10", "11", "12", "14", "16", "18", "20", "24", "26", "28", "36", "48", "72"};\r
+\r
+    private ListenerList modifyListeners;\r
+    \r
+    private final LocalResourceManager resourceManager;\r
+\r
+    /**\r
+     * Gets all available fonts\r
+     * @param familyIndex Optional list for indexing font families\r
+     * @return Tree where key is font family name and object a list of fonts belonging to that family\r
+     */\r
+    private static TreeMap<String, ArrayList<Font>> getFonts(ArrayList<String> familyIndex) {\r
+        TreeMap<String, ArrayList<Font>> fonts = new TreeMap<String, ArrayList<Font>>();\r
+\r
+        GraphicsEnvironment gEnv = GraphicsEnvironment\r
+                .getLocalGraphicsEnvironment();\r
+        Font allFonts[] = gEnv.getAllFonts();\r
+\r
+        for(Font font : allFonts) {\r
+            String family = font.getFamily(Locale.ROOT);\r
+            if(!fonts.containsKey(family)) {\r
+                if(familyIndex != null)\r
+                    familyIndex.add(family);\r
+                fonts.put(family, new ArrayList<Font>());\r
+            }\r
+\r
+            boolean add = true;\r
+            for(Font f : fonts.get(family)) {\r
+                if(f.getFontName().equals(font.getFontName())) {\r
+                    add = false;\r
+                    break;\r
+                }\r
+            }\r
+\r
+            if(add)\r
+                fonts.get(family).add(font);\r
+        }\r
+        return fonts;\r
+    }\r
+\r
+    /**\r
+     * Composite containing components for selecting a font\r
+     * \r
+     * @param parent Parent composite\r
+     * @param style SWT style\r
+     */\r
+    public FontSelectionComposite(Composite parent, int style) {\r
+        super(parent, style);\r
+        \r
+        // Create a ResourceManager to dispose images when the widget is disposed.\r
+        this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), this);\r
+\r
+        modifyListeners = new ListenerList();\r
+\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(this);\r
+        GridDataFactory.fillDefaults().applyTo(this);\r
+\r
+        /*\r
+         * Two-row layout. First row consists of editable text boxes,\r
+         * second row consists of tables containing possible options\r
+         */\r
+\r
+        // First row\r
+        fontName = new Text(this, SWT.BORDER);\r
+        GridDataFactory.fillDefaults().applyTo(fontName);\r
+\r
+        fontStyle = new Text(this, SWT.BORDER);\r
+        GridDataFactory.fillDefaults().applyTo(fontStyle);\r
+\r
+        fontSize = new Text(this, SWT.BORDER);\r
+        GridDataFactory.fillDefaults().applyTo(fontSize);\r
+\r
+        // Second row\r
+        fontFamilyTable = new Table (this, SWT.VIRTUAL | SWT.BORDER | SWT.FULL_SELECTION);\r
+        fontFamilyTable.setLinesVisible (false);\r
+        fontFamilyTable.setHeaderVisible (false);\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 100).applyTo(fontFamilyTable);\r
+        fontFamilyTable.setItemCount(familyIndex.size());\r
+        TableColumn column = new TableColumn (fontFamilyTable, SWT.NONE);\r
+        column.setWidth(200);\r
+\r
+\r
+        fontStyleTable = new Table (this, SWT.BORDER | SWT.FULL_SELECTION);\r
+        fontStyleTable.setLinesVisible (false);\r
+        fontStyleTable.setHeaderVisible (false);\r
+        GridDataFactory.fillDefaults().hint(100, 100).applyTo(fontStyleTable);\r
+        column = new TableColumn (fontStyleTable, SWT.NONE);\r
+        setFontStyleTableWidth();\r
+\r
+\r
+\r
+        fontSizeTable = new Table (this, SWT.VIRTUAL | SWT.BORDER | SWT.FULL_SELECTION);\r
+        fontSizeTable.setLinesVisible (false);\r
+        fontSizeTable.setHeaderVisible (false);\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 100).applyTo(fontSizeTable);\r
+        column = new TableColumn (fontSizeTable, SWT.NONE);\r
+        column.setWidth(70);\r
+        for(String size : sizes) {\r
+            TableItem item = new TableItem(fontSizeTable, SWT.NONE);\r
+            item.setText(0, size);\r
+        }\r
+\r
+        // Listeners for components\r
+        addFontFamilyListeners();\r
+        addFontStyleListeners();\r
+        addFontSizeListeners();\r
+    }\r
+\r
+\r
+    /**\r
+     * Set controls to display given font\r
+     */\r
+    public void setFont(Font font, boolean notify) {\r
+        if(font == null)\r
+            return;\r
+        \r
+        Object[] listeners = new Object[0];\r
+        if(!notify) {\r
+            listeners = modifyListeners.getListeners();\r
+            for(Object listener : listeners)\r
+                modifyListeners.remove(listener);\r
+        }\r
+\r
+        String fontFamily = font.getFamily(Locale.ROOT);\r
+        String fontName = font.getFontName(Locale.ROOT);\r
+        this.fontName.setText(fontFamily);\r
+        this.fontFamilyTable.setTopIndex(this.fontFamilyTable.getSelectionIndex());\r
+\r
+        String style = "Regular";\r
+        if(fontName.length() > fontFamily.length())\r
+            style = fontName.substring(fontFamily.length() + 1);\r
+        this.fontStyle.setText(style);\r
+\r
+        int size = font.getSize();\r
+        fontSize.setText("" + size);\r
+\r
+        for(int i = 0; i < sizes.length; i++) {\r
+            if(sizes[i].equals("" + size)) {\r
+                fontSizeTable.select(i);\r
+                fontSizeTable.setTopIndex(i);\r
+                fontChanged();\r
+                break;\r
+            }\r
+        }  \r
+        \r
+        if(!notify) {\r
+            for(Object listener : listeners)\r
+                modifyListeners.add(listener);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Get the AWT font defined in this composite\r
+     * @return AWT font\r
+     */\r
+    public Font getAWTFont() {\r
+        String family = fontName.getText();\r
+        String style = fontStyle.getText();\r
+        if(style.equals("Regular"))\r
+            style = null;\r
+        \r
+        int stylebits = 0;\r
+        if(style != null) {\r
+            if(style.toLowerCase().contains("bold"))\r
+                stylebits |= SWT.BOLD;\r
+            if(style.toLowerCase().contains("italic"))\r
+                stylebits |= SWT.ITALIC;\r
+        }\r
+\r
+        String name = family + (style != null ? " " + style : "");\r
+\r
+        int size = 10;\r
+        try {\r
+            size = Integer.parseInt(fontSize.getText());\r
+        } catch (NumberFormatException e) {\r
+        }\r
+\r
+        if(name != null && name.length() > 0)\r
+            return new Font(name, stylebits, size);\r
+        else\r
+            return null;\r
+    }\r
+    \r
+    /**\r
+     * Adds listeners for font family name text and table\r
+     */\r
+    protected void addFontFamilyListeners() {\r
+\r
+        // Font name modify listener\r
+        fontName.addModifyListener(new ModifyListener() {\r
+\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                Text text = (Text) e.widget;\r
+                String name = text.getText();\r
+                fontFamilyTextModified(name, false);\r
+            }\r
+        });\r
+\r
+        // Font name key listener for auto-completion\r
+        fontName.addKeyListener(new KeyListener() {\r
+\r
+            @Override\r
+            public void keyReleased(KeyEvent e) {\r
+            }\r
+\r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+                if ((e.character == ' ') && ((e.stateMask & SWT.CTRL) != 0) ) {\r
+                    fontFamilyTextModified(fontName.getText(), true);\r
+                    e.doit = false;\r
+                } else if(e.keyCode == SWT.CR || e.keyCode == SWT.LF || e.keyCode == SWT.KEYPAD_CR) {\r
+                    fontChanged();\r
+                }\r
+            }\r
+        });\r
+        \r
+        // Call listener when editing has ended\r
+        fontName.addListener(SWT.FocusOut, new Listener() {\r
+            public void handleEvent(Event e) {\r
+                fontChanged();\r
+            }\r
+        });\r
+\r
+        // Font family data listener for lazy initialization of the table\r
+        fontFamilyTable.addListener (SWT.SetData, new Listener () {\r
+            public void handleEvent (Event event) {\r
+                TableItem item = (TableItem) event.item;\r
+                int index = fontFamilyTable.indexOf (item);\r
+\r
+                String family = familyIndex.get(index);\r
+                item.setText (family);\r
+\r
+                Font font = fonts.get(family).get(0);\r
+                if(font.canDisplay('a')) {\r
+                    FontData fontData =  toSwtFontData(font, 10);\r
+                    org.eclipse.swt.graphics.Font swtFont = resourceManager.createFont(FontDescriptor.createFrom(fontData));\r
+                    item.setFont(swtFont);\r
+                }\r
+            }\r
+        });\r
+\r
+\r
+        // Updates selected font to font name text\r
+        fontFamilyTable.addSelectionListener(new SelectionListener() {\r
+\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                TableItem[] selection = fontFamilyTable.getSelection();\r
+\r
+                if(selection.length > 0) {\r
+                    String family = selection[0].getText();\r
+                    fontName.setText(family);\r
+                    fontChanged();\r
+                }\r
+            }\r
+\r
+            @Override\r
+            public void widgetDefaultSelected(SelectionEvent e) {\r
+            }\r
+        });\r
+\r
+        /*\r
+         *  Forces focus to font name texts and starts editing it, \r
+         *  if user presses a letter when focus is in font family table\r
+         */\r
+        fontFamilyTable.addKeyListener(new KeyListener() {\r
+            @Override\r
+            public void keyReleased(KeyEvent e) {\r
+            }\r
+\r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+                if(Character.isLetter(e.character)) {\r
+                    fontName.forceFocus();\r
+                    fontName.setTextChars(new char[] {e.character});\r
+                    fontName.setSelection(1, 1);\r
+                }\r
+            }\r
+        });\r
+    }\r
+\r
+    /**\r
+     * Implements interactions between font name text and font family table, when \r
+     * the text in font name text has been changed.\r
+     * @param name New name\r
+     * @param autoComplete Has autocomplete been called\r
+     */\r
+    protected void fontFamilyTextModified(String name, boolean autoComplete) {\r
+        if(name.isEmpty())\r
+            return;\r
+        for(int i = 0; i < familyIndex.size(); i++) {\r
+            String family = familyIndex.get(i);\r
+            if(family.equals(name)) {\r
+                //complete match\r
+                fontFamilyTable.select(i);\r
+                selectFontFamily(name);\r
+                break;\r
+            } else if(family.toLowerCase().equals(name.toLowerCase())) {\r
+                // Wrong case but correct name\r
+                fontName.setText(family);\r
+                fontName.setSelection(family.length(), family.length());\r
+                fontFamilyTable.setTopIndex(i);\r
+                fontChanged();\r
+                break;\r
+            } else if(family.toLowerCase().startsWith(name.toLowerCase())) {\r
+                if(autoComplete) {\r
+                    // Fill in the rest of the name\r
+                    fontName.setText(family);\r
+                    fontName.setSelection(family.length());\r
+                    fontChanged();\r
+                    // The beginning is correct, help user by displaying the nearest name\r
+                } else { \r
+                    fontFamilyTable.setTopIndex(i);\r
+                }\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * Adds listeners for font style text and table\r
+     */\r
+    protected void addFontStyleListeners() {\r
+\r
+        // Font style modify listener\r
+        fontStyle.addModifyListener(new ModifyListener() {\r
+\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                Text text = (Text) e.widget;\r
+                String name = text.getText();\r
+                fontStyleTextModified(name, false);\r
+            }\r
+        });\r
+\r
+        // Font style key listener for auto-complete\r
+        fontStyle.addKeyListener(new KeyListener() {\r
+\r
+            @Override\r
+            public void keyReleased(KeyEvent e) {\r
+            }\r
+\r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+                if ((e.character == ' ') && ((e.stateMask & SWT.CTRL) != 0) ) {\r
+                    fontStyleTextModified(fontStyle.getText(), true);\r
+                    e.doit = false;\r
+                } else if(e.keyCode == SWT.CR || e.keyCode == SWT.LF || e.keyCode == SWT.KEYPAD_CR) {\r
+                    fontChanged();\r
+                }\r
+            }\r
+        });\r
+\r
+        // Update selected style to font style text\r
+        fontStyleTable.addSelectionListener(new SelectionListener() {\r
+\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                TableItem[] selection = fontStyleTable.getSelection();\r
+\r
+                if(selection.length > 0) {\r
+                    String family = selection[0].getText();\r
+                    fontStyle.setText(family);\r
+                    fontChanged();\r
+                }\r
+            }\r
+\r
+            @Override\r
+            public void widgetDefaultSelected(SelectionEvent e) {\r
+            }\r
+        });\r
+\r
+        /*\r
+         *  Forces focus to font style text and starts editing it, \r
+         *  if user presses a letter when focus is in font style table\r
+         */\r
+        fontStyleTable.addKeyListener(new KeyListener() {\r
+            @Override\r
+            public void keyReleased(KeyEvent e) {\r
+            }\r
+\r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+                if(Character.isLetter(e.character)) {\r
+                    fontStyle.forceFocus();\r
+                    fontStyle.setTextChars(new char[] {e.character});\r
+                    fontStyle.setSelection(1, 1);\r
+                    e.doit = false;\r
+                } else if(e.keyCode == SWT.CR || e.keyCode == SWT.LF || e.keyCode == SWT.KEYPAD_CR) {\r
+                    fontChanged();\r
+                }\r
+            }\r
+        });\r
+    }\r
+\r
+    /**\r
+     * Handles interactions between font style text and font style table, when\r
+     * font style text has been changed\r
+     * \r
+     * @param name New text for font style \r
+     * @param autoComplete is auto-completion used\r
+     */\r
+    protected void fontStyleTextModified(String name, boolean autoComplete) {\r
+        if(name.isEmpty())\r
+            return;\r
+\r
+        for(int i = 0; i < fontStyleTable.getItemCount(); i++) {\r
+            TableItem item = fontStyleTable.getItem(i);\r
+            String style = item.getText();\r
+\r
+            if(style.equals(name)) {\r
+                //complete match\r
+                fontStyleTable.select(i);\r
+                break;\r
+            } else if(style.toLowerCase().equals(name.toLowerCase())) {\r
+                // Wrong case, correct style. -> fix the case\r
+                fontStyle.setText(style);\r
+                fontStyle.setSelection(style.length());\r
+                fontStyleTable.setTopIndex(i);\r
+                fontChanged();\r
+                break;\r
+            } else if(style.toLowerCase().startsWith(name.toLowerCase())) {\r
+                // The beginning of the word is correct\r
+                fontStyleTable.setTopIndex(i);\r
+                if(autoComplete) {\r
+                    // Fill in the rest of the name\r
+                    fontStyle.setText(style);\r
+                    fontStyle.setSelection(style.length());\r
+                    fontChanged();\r
+                    // The beginning is correct, help user by displaying the nearest name\r
+                } else { \r
+                    fontStyleTable.setTopIndex(i);\r
+                }\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * Listeners for font size text and font size table\r
+     */\r
+    protected void addFontSizeListeners() {\r
+\r
+        // Select an item from size table, if there is a matching item \r
+        fontSize.addKeyListener(new KeyListener() {\r
+\r
+            @Override\r
+            public void keyReleased(KeyEvent e) {\r
+                Text text = (Text) e.widget;\r
+                String size = text.getText();\r
+\r
+                for(int i = 0; i < sizes.length; i++) {\r
+                    if(sizes[i].equals(size)) {\r
+                        fontSizeTable.select(i);\r
+                        fontSizeTable.setTopIndex(i);\r
+                        fontChanged();\r
+                        break;\r
+                    }\r
+                }  \r
+            }\r
+\r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+            }\r
+        });\r
+\r
+        // Change the text in size text according to the selection in size table\r
+        fontSizeTable.addSelectionListener(new SelectionListener() {\r
+\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                fontSize.setText(fontSizeTable.getSelection()[0].getText());\r
+                fontChanged();\r
+            }\r
+\r
+            @Override\r
+            public void widgetDefaultSelected(SelectionEvent e) {\r
+            }\r
+        });\r
+\r
+        // Change focus from table to text, if user starts to write a number \r
+        fontSizeTable.addKeyListener(new KeyListener() {\r
+\r
+            @Override\r
+            public void keyReleased(KeyEvent e) { }\r
+\r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+                if(Character.isDigit(e.character)) {\r
+                    fontSize.setTextChars(new char[]{e.character});\r
+                    fontSize.setSelection(1);\r
+                    fontSize.forceFocus();\r
+                    e.doit = false;\r
+                }\r
+            }\r
+        });\r
+\r
+    }\r
+\r
+    /**\r
+     * Creates the contents of fontStyleTable according to the selected font family \r
+     * @param family Selected font family\r
+     */\r
+    protected void selectFontFamily(String family) {\r
+        String old = fontStyle.getText();\r
+        String selection = null, optionalSelection = null;\r
+\r
+        // Clear the table\r
+        fontStyleTable.removeAll();\r
+\r
+        if(familyIndex.indexOf(family) > -1) {\r
+            for(int i = 0; i < fonts.get(family).size(); i++) {\r
+                Font font = fonts.get(family).get(i);\r
+\r
+                String name = font.getFontName(Locale.ROOT);\r
+\r
+                // Style is "Regular", unless otherwise defined\r
+                String style = "Regular";\r
+                if(name.length() > family.length())\r
+                    style = name.substring(family.length() + 1);\r
+\r
+                // If previous font was bold, try to conserve the style\r
+                if(old.equals(style))\r
+                    selection  = style;\r
+                else if((!old.isEmpty() && style.contains(old)) || optionalSelection == null)\r
+                    optionalSelection = style;\r
+\r
+                TableItem item = new TableItem (fontStyleTable, SWT.NONE);\r
+                item.setText (0, style);\r
+                item.setData(font);\r
+\r
+                // If the font is not symbolic, use the font in the created item\r
+                if(font.canDisplay('a')) {\r
+                    FontData fontData = toSwtFontData(font, 10);\r
+                    org.eclipse.swt.graphics.Font swtFont = resourceManager.createFont(FontDescriptor.createFrom(fontData));\r
+                    item.setFont(swtFont);\r
+                }\r
+            }\r
+            fontStyleTable.setItemCount(fonts.get(family).size());\r
+\r
+            if(selection == null)\r
+                selection = optionalSelection;\r
+\r
+            fontStyle.setText(selection);\r
+            fontStyle.setSelection(selection.length(), selection.length());\r
+\r
+            setFontStyleTableWidth();\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Set width for style table column. Width can change, if scroll bar appears \r
+     */\r
+    protected void setFontStyleTableWidth() {\r
+        Rectangle area = fontStyleTable.getClientArea();\r
+        Point size = fontStyleTable.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+        ScrollBar vBar = fontStyleTable.getVerticalBar();\r
+        int width = 100;\r
+        if (area.height == 0 || size.y <= area.height) {\r
+            Point vBarSize = vBar.getSize();\r
+            width += vBarSize.x;\r
+        }\r
+        fontStyleTable.getColumn(0).setWidth(width);\r
+    }\r
+\r
+\r
+    /**\r
+     * Builds SWT FontData from AWT font. Simple conversion.\r
+     * \r
+     * @param font AWT font\r
+     * @param height Height for the created data (or -1 if inherited directly from awt font, size matching not guaranteed)\r
+     * @return\r
+     */\r
+    protected static FontData toSwtFontData(Font font, int height) {\r
+        FontData fontData = new FontData();\r
+        fontData.setName(font.getFontName());\r
+        fontData.setStyle(font.getStyle());\r
+        fontData.setHeight(height > 0 ? height : font.getSize());\r
+        return fontData;\r
+    }\r
+\r
+\r
+    public void addFontModifiedListener(FontModifyListener listener) {\r
+        modifyListeners.add(listener);\r
+    }\r
+\r
+    public void removeFontModifiedListener(FontModifyListener listener) {\r
+        modifyListeners.remove(listener);\r
+    }\r
+\r
+    public List<FontModifyListener> getFontModifiedListener() {\r
+        ArrayList<FontModifyListener> listeners = new ArrayList<FontModifyListener>(modifyListeners.size());\r
+        for(Object l : modifyListeners.getListeners())\r
+            listeners.add((FontModifyListener)l);\r
+        return listeners;\r
+    }\r
+\r
+    /**\r
+     * Called when some property of the font definiton has changed.\r
+     * Calls font change listeners.\r
+     */\r
+    protected void fontChanged() {\r
+        Font font = getAWTFont();\r
+        if(font != null) {\r
+            \r
+            int style = 0;\r
+            style |= (font.getFontName(Locale.ROOT).contains("Bold") ? SWT.BOLD : 0);\r
+            style |= (font.getFontName(Locale.ROOT).contains("Italic") ? SWT.ITALIC : 0);\r
+            FontData fontData = new FontData(font.getFamily(Locale.ROOT), font.getSize(), style);\r
+            \r
+            Object[] listenersArray = modifyListeners.getListeners();\r
+            for (int i = 0; i < listenersArray.length; i++) {\r
+                ((FontModifyListener)listenersArray[i]).awtFontChanged(font);\r
+                ((FontModifyListener)listenersArray[i]).swtFontDataChanged(fontData);\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FunctionLabelFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/FunctionLabelFactory.java
new file mode 100644 (file)
index 0000000..2b4cdcb
--- /dev/null
@@ -0,0 +1,49 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.utils.datastructures.Quad;\r
+\r
+\r
+\r
+public class FunctionLabelFactory  extends ReadFactoryImpl<Resource, String> {\r
+\r
+    private final String propertyURI;\r
+    private boolean end;\r
+    \r
+    public FunctionLabelFactory(String propertyURI, boolean end) {\r
+        this.propertyURI = propertyURI;\r
+        this.end = end;\r
+    }\r
+\r
+    @Override\r
+    public Object getIdentity(Object inputContents) {\r
+        return new Quad<Resource, String, Object, Boolean>((Resource) inputContents, propertyURI, getClass(), end);\r
+    }\r
+\r
+       \r
+    @Override\r
+    public String perform(ReadGraph graph, Resource resource) throws DatabaseException {\r
+        String value = graph.getPossibleRelatedValue(resource, graph.getResource(propertyURI));\r
+        if(end) {\r
+               return "end " + value + ";";\r
+        } else {\r
+               return "function " + value;\r
+        }\r
+    }\r
+       \r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/IsOutputWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/IsOutputWidget.java
new file mode 100644 (file)
index 0000000..5297182
--- /dev/null
@@ -0,0 +1,102 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+public class IsOutputWidget implements Widget{\r
+    \r
+    Resource variable = null; \r
+    org.simantics.browsing.ui.swt.widgets.Button isOutputButton;\r
+    \r
+    public IsOutputWidget(Composite parent, WidgetSupport support, int style) {\r
+        support.register(this);\r
+        isOutputButton = new org.simantics.browsing.ui.swt.widgets.Button(parent, support, style |= SWT.CHECK);\r
+        isOutputButton.setText("Is Output");\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        if(input instanceof ISelection) {\r
+            ISelection selection = (ISelection)input;\r
+            if(selection instanceof IStructuredSelection) {\r
+                Resource resource = ISelectionUtils.filterSingleSelection(selection, Resource.class);\r
+                if(resource != null) {\r
+                    variable = resource;\r
+                }\r
+            }\r
+        }\r
+        \r
+        if(variable == null) return;\r
+        \r
+        try {\r
+            context.getSession().syncRequest(new ReadRequest() {\r
+                \r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    final boolean isOutput = graph.hasStatement(variable, sr.IsOutput);\r
+                    final Button button = getWidget();\r
+                    button.getDisplay().asyncExec(new Runnable() {\r
+                        \r
+                        @Override\r
+                        public void run() {\r
+                            if(button.isDisposed()) return;\r
+                            \r
+                            if(isOutput)\r
+                                button.setSelection(true);\r
+                            else\r
+                                button.setSelection(false);\r
+                        }\r
+                    });\r
+\r
+                        \r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        isOutputButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                SysdynResource sr =  SysdynResource.getInstance(graph);\r
+                if(graph.hasStatement(input, sr.IsOutput)) {\r
+                    graph.deny(input, sr.IsOutput);\r
+                } else {\r
+                    graph.claim(input, SysdynResource.getInstance(graph).IsOutput, null, input);\r
+                }\r
+            }\r
+        });\r
+    }\r
+    \r
+    public Button getWidget() {\r
+        return isOutputButton.getWidget();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ShortcutTabWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ShortcutTabWidget.java
new file mode 100644 (file)
index 0000000..56488ec
--- /dev/null
@@ -0,0 +1,322 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.text.Collator;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.HashSet;\r
+import java.util.Locale;\r
+import java.util.concurrent.CopyOnWriteArrayList;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.MouseListener;\r
+import org.eclipse.swt.graphics.Image;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.TabFolder;\r
+import org.eclipse.swt.widgets.TabItem;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableItem;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.AsyncListener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.validation.ValidationUtils;\r
+import org.simantics.sysdyn.utils.Function;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+public class ShortcutTabWidget implements Widget {\r
+\r
+    TabFolder tabFolder;\r
+    TabItem variables;\r
+    TabItem functions;\r
+    Table variableTable;\r
+    Table functionTable;\r
+    Composite composite;\r
+    TableItem item2;\r
+    \r
+       CopyOnWriteArrayList<Runnable> dependencyListeners =\r
+               new CopyOnWriteArrayList<Runnable>();\r
+       \r
+    private final LocalResourceManager resourceManager;\r
+\r
+    public ShortcutTabWidget(Composite parent, WidgetSupport support, int style) {\r
+       if(support!=null)\r
+               support.register(this);\r
+\r
+        composite = new Composite(parent, style);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);\r
+        \r
+        tabFolder = new TabFolder (composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(tabFolder);\r
+        GridLayoutFactory.fillDefaults().applyTo(tabFolder);\r
+        variables = new TabItem(tabFolder, SWT.NULL);\r
+        variables.setText("Variables");\r
+        variableTable = new Table (tabFolder, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.NO_FOCUS | SWT.HIDE_SELECTION);\r
+        \r
+        variables.setControl(variableTable);\r
+\r
+        functions = new TabItem(tabFolder, SWT.NULL);\r
+        functions.setText("Functions"); \r
+\r
+        functionTable = new Table (tabFolder, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.NO_FOCUS | SWT.HIDE_SELECTION);\r
+        \r
+        // Create a ResourceManager to dispose images when the widget is disposed.\r
+        this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), functionTable);\r
+        \r
+        functions.setControl(functionTable);\r
+        \r
+        // Add the functions only after we know which variable is connected to this widget.\r
+    }\r
+\r
+    public Composite getWidget() {\r
+       return composite;\r
+    }\r
+    \r
+    private void addFunctions(Resource model) {\r
+        TableItem item;\r
+        \r
+        ArrayList<Function> functionList = Function.getUserDefinedFunctions(model);\r
+        functionList.addAll(Function.getSharedFunctions(model));        \r
+        functionList.addAll(Function.getAllBuiltInFunctions());        \r
+        \r
+        Collections.sort(functionList);\r
+        \r
+        for(Function function : functionList){\r
+            item = new TableItem(functionTable, SWT.NONE);\r
+            item.setText(function.getName() + "()");\r
+            String parameterList = Function.inputListToString(function.getInputList());\r
+            item.setData(function.getName() + "(" + parameterList + ")");\r
+            item.setImage(getImage(this.resourceManager, function));\r
+        }\r
+        \r
+    }\r
+    \r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        if(input instanceof IStructuredSelection) {\r
+            final Resource variable = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
+            if(variable != null) {\r
+                \r
+                // Fill the function table\r
+                try { \r
+                    Resource model = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                        @Override\r
+                        public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                            return graph.syncRequest(new PossibleModel(variable));\r
+                        }\r
+                    });\r
+                    addFunctions(model);\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                }\r
+\r
+                // Fill the variable table\r
+               SimanticsUI.getSession().asyncRequest(new Read<HashSet<String>>() {\r
+\r
+                                       @Override\r
+                                       public HashSet<String> perform(ReadGraph graph)\r
+                                                       throws DatabaseException {\r
+                                               return ValidationUtils.getDependencies(graph, variable);\r
+                                       }\r
+                               }, new AsyncListener<HashSet<String>>() {\r
+\r
+                                       @Override\r
+                                       public void execute(AsyncReadGraph graph,\r
+                                                       HashSet<String> result) {\r
+                                               \r
+                                               final HashSet<String> dependencies = result;\r
+                                               variableTable.getDisplay().asyncExec(new Runnable() {\r
+                                                       \r
+                                                       @Override\r
+                                                       public void run() {\r
+                                                               if(variableTable.isDisposed()) return;\r
+                                                               \r
+                                                               TableItem[] items = variableTable.getItems();\r
+                                                               \r
+                                                               // Remove deleted dependencies and create the list of current dependencies (itemStrings)\r
+                                                               ArrayList<String> itemStrings = new ArrayList<String>();\r
+                                               for(TableItem i : items) {\r
+                                                       String text = i.getText();\r
+                                                       if(dependencies.contains(text))\r
+                                                               itemStrings.add(text);\r
+                                                       else\r
+                                                               variableTable.remove(variableTable.indexOf(i));\r
+                                               }\r
+                                               \r
+                                               // Add all new dependencies\r
+                                               TableItem item;\r
+                                               for(String d : dependencies) {\r
+                                                       if(!itemStrings.contains(d)) {\r
+                                                               item = new TableItem(variableTable, SWT.NONE);\r
+                                                               item.setText(d);\r
+                                                               item.setData(d);\r
+                                                       }\r
+                                               }\r
+                                               \r
+                                               sort();\r
+                                               \r
+                                               String selfName = getName();\r
+\r
+                                               // Time and self are not added if selfName (we have an error or a stock).\r
+                                               if (selfName != null)\r
+                                               {\r
+                                    item = new TableItem(variableTable, SWT.NONE);\r
+                                    item.setText(selfName);\r
+                                    item.setData(selfName);\r
+                                    \r
+                                    item = new TableItem(variableTable, SWT.NONE);\r
+                                    item.setText("time");\r
+                                    item.setData("time");\r
+                                               }\r
+                                               \r
+                                                               synchronized(dependencyListeners) {\r
+                                                                       for(Runnable listener : dependencyListeners)\r
+                                                                               listener.run();\r
+                                                               }                                                               \r
+                                                       }\r
+                                               });\r
+                                       }\r
+                                       \r
+                                       /**\r
+                                        * Sort items to alphabetical order.\r
+                                        */\r
+                                       private void sort() {\r
+                                           TableItem[] connectedVariables = variableTable.getItems();\r
+                                           Collator collator = Collator.getInstance(Locale.getDefault());\r
+                                           for (int i = 1; i < connectedVariables.length; i++) {\r
+                                               String value1 = connectedVariables[i].getText(0);\r
+                                               for (int j = 0; j < i; j++) {\r
+                                                   String value2 = connectedVariables[j].getText(0);\r
+                                                   if (collator.compare(value1, value2) < 0) {\r
+                                                       String value = connectedVariables[i].getText(0);\r
+                                                       connectedVariables[i].dispose();\r
+                                                       TableItem item2 = new TableItem(variableTable, SWT.NONE, j);\r
+                                                       item2.setText(value);\r
+                                                       item2.setData(value);\r
+                                                       connectedVariables = variableTable.getItems();\r
+                                                       break;\r
+                                                   }\r
+                                               }\r
+                                           }\r
+                                       }\r
+                                       \r
+                                       /**\r
+                                        * Get the name of the respective variable.\r
+                                        */\r
+                                       private String getName() {\r
+                                           String selfName = null;\r
+                        try {\r
+                                               selfName = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+                                @Override\r
+                                public String perform(ReadGraph graph)\r
+                                        throws DatabaseException {\r
+                                    Layer0 l0 = Layer0.getInstance(graph);\r
+                                    Object selfName = graph.getPossibleRelatedValue(variable, l0.HasName);\r
+                                    if (selfName instanceof String) {\r
+                                        return (String)selfName;\r
+                                    }\r
+                                    return null;\r
+                                }\r
+                            });\r
+                        }\r
+                        catch (DatabaseException e) {\r
+                            e.printStackTrace();\r
+                        }\r
+                                           return selfName;\r
+                                       }\r
+\r
+                                       @Override\r
+                                       public void exception(AsyncReadGraph graph,\r
+                                                       Throwable throwable) {\r
+                                               throwable.printStackTrace();\r
+                                       }\r
+\r
+                                       @Override\r
+                                       public boolean isDisposed() {\r
+                                               return variableTable.isDisposed();\r
+                                       }\r
+                               });\r
+            }\r
+        }\r
+    }\r
+\r
+\r
+    \r
+    public void addFocusListener(FocusListener listener) {\r
+        this.functionTable.addFocusListener(listener);\r
+        this.variableTable.addFocusListener(listener);\r
+    }\r
+    \r
+    public void addMouseListener(MouseListener listener) {\r
+        this.functionTable.addMouseListener(listener);\r
+        this.variableTable.addMouseListener(listener);\r
+    }\r
+    \r
+       public void addDependencyListener(Runnable listener) {\r
+               synchronized(dependencyListeners) {\r
+                       dependencyListeners.add(listener);\r
+               }\r
+       }\r
+\r
+       public void removeDependencyListener(Runnable listener) {\r
+               synchronized(dependencyListeners) {\r
+                       dependencyListeners.remove(listener);\r
+               }\r
+       }\r
+    \r
+    public Table getVariableTable() {\r
+        return variableTable;\r
+    }\r
+\r
+    /**\r
+     * Get the icon image for each type of Modelica function.\r
+     * @param rm LocalResourceManager for which the image is created.\r
+     * @param function Modelica function\r
+     * @return Image to be shown e.g. in assistive text feed and ShortcutTab\r
+     */\r
+    public static Image getImage(LocalResourceManager rm, Function function) {\r
+        switch (function.getType()) {\r
+            case USER_DEFINED:\r
+                return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/function.png")));\r
+            case SHARED:\r
+                return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/functionLink.png")));\r
+            case VENSIM:\r
+                return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/vensimFunction.png")));\r
+            case SYSDYN:\r
+                return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/sysdynFunction.png")));\r
+            case MODELICA:\r
+                return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/modelicaFunction.png")));\r
+            case MODELICA_ARRAY:\r
+                return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/modelicaArrayFunction.png")));\r
+            default:\r
+                return null;\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/UnitComboWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/UnitComboWidget.java
new file mode 100644 (file)
index 0000000..d2a770f
--- /dev/null
@@ -0,0 +1,95 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+\r
+public class UnitComboWidget extends TrackedCombo {\r
+\r
+    public UnitComboWidget(Composite parent, WidgetSupport support, int style) {\r
+        super(parent, support, style);\r
+        \r
+        \r
+        // Add all units used in the model to the unit combo\r
+        setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
+\r
+            @Override\r
+            public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                Map<String, Object> map = new HashMap<String, Object>();\r
+\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                Resource model = graph.getPossibleObject(input, l0.PartOf);\r
+                if (model != null) {\r
+                    Collection<Resource> variables = graph.getObjects(model, l0.ConsistsOf);\r
+                    for(Resource v : variables) {\r
+                        Object unit = graph.getPossibleRelatedValue(v, sr.Variable_unit);\r
+                        if (unit != null && !map.keySet().contains(unit)) {\r
+                            map.put((String)unit, (String)unit);\r
+\r
+                        }\r
+                    }\r
+                }\r
+                return map;\r
+            }\r
+        });\r
+        \r
+        // Set initial selection of unit combo\r
+        setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
+                String unit = graph.getPossibleRelatedValue(input, SysdynResource.getInstance(graph).Variable_unit);\r
+                if(unit == null)\r
+                    return "";\r
+                else \r
+                    return unit;\r
+            }\r
+        });\r
+\r
+        // Modify unit\r
+        addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
+\r
+            @Override\r
+            public void applyText(WriteGraph graph, Resource input, String text) throws DatabaseException {\r
+                graph.denyValue(input, SysdynResource.getInstance(graph).Variable_unit);\r
+                graph.claimLiteral(input, SysdynResource.getInstance(graph).Variable_unit, text);\r
+                \r
+                Resource conf = graph.getPossibleObject(input, Layer0.getInstance(graph).PartOf);\r
+                SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+                SysdynModel sm = smm.getModel(graph, conf);\r
+                sm.getMapping().domainModified(input);\r
+                sm.update(graph);\r
+            }\r
+        });\r
+\r
+    }\r
+    \r
+    \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ValveOrientationGroup.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ValveOrientationGroup.java
new file mode 100644 (file)
index 0000000..dbdf951
--- /dev/null
@@ -0,0 +1,143 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.WidgetImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.datastructures.Quad;\r
+\r
+public class ValveOrientationGroup extends WidgetImpl {\r
+\r
+    Group group;\r
+    Button vertical, horizontal;\r
+    \r
+    public ValveOrientationGroup(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
+        super(support);\r
+        group = new Group(parent, SWT.NONE);\r
+        group.setText("Valve orientation");\r
+        GridDataFactory.fillDefaults().applyTo(group);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(group);\r
+        \r
+        horizontal = new Button(group, support, SWT.RADIO);\r
+        horizontal.setText("Horizontal");\r
+        horizontal.setSelectionFactory(new OrientationSelectionFactory(horizontal, SysdynResource.URIs.Horizontal, true));\r
+        horizontal.addSelectionListener(new OrientationSelectionListener(context, SysdynResource.URIs.Horizontal));\r
+        \r
+        vertical = new Button(group, support, SWT.RADIO);\r
+        vertical.setText("Vertical");\r
+        vertical.setSelectionFactory(new OrientationSelectionFactory(vertical, SysdynResource.URIs.Vertical));\r
+        vertical.addSelectionListener(new OrientationSelectionListener(context, SysdynResource.URIs.Vertical));\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        horizontal.setInput(context, input);\r
+        vertical.setInput(context, input);\r
+    }\r
+\r
+    @Override\r
+    public Control getControl() {\r
+        return this.group;\r
+    }\r
+    \r
+    private class OrientationSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        \r
+        boolean defaultSelected;\r
+        String uri;\r
+        Button button;\r
+        \r
+        public OrientationSelectionFactory(Button button, String uri) {\r
+            this(button, uri, false);\r
+        }\r
+\r
+        public OrientationSelectionFactory(Button button, String uri, boolean defaultSelected) {\r
+            this.uri = uri;\r
+            this.defaultSelected = defaultSelected;\r
+            this.button = button;\r
+        }\r
+        \r
+        public Object getIdentity(Object inputContents) {\r
+            return new Quad<Object, Object, Object, Class<?>>(button, uri, defaultSelected, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource valve) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            ModelingResources mr = ModelingResources.getInstance(graph);\r
+            if(!graph.isInstanceOf(valve, sr.Valve))\r
+                return Boolean.FALSE;\r
+            \r
+            Resource symbol = graph.getPossibleObject(valve, mr.ComponentToElement);\r
+            if(symbol == null)\r
+                return Boolean.FALSE;\r
+            \r
+            Resource orientation = graph.getPossibleObject(symbol, sr.ValveSymbol_orientation);\r
+            \r
+            if(orientation == null)\r
+                return defaultSelected;\r
+            \r
+            return orientation.equals(graph.getResource(uri));\r
+        }\r
+        \r
+    }\r
+    \r
+    \r
+    private class OrientationSelectionListener extends SelectionListenerImpl<Resource> {\r
+        \r
+        String uri;\r
+        \r
+        public OrientationSelectionListener(ISessionContext context, String uri) {\r
+            super(context);\r
+            this.uri = uri;\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource valve) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            ModelingResources mr = ModelingResources.getInstance(graph);\r
+            if(!graph.isInstanceOf(valve, sr.Valve))\r
+                return;\r
+            \r
+            Resource symbol = graph.getPossibleObject(valve, mr.ComponentToElement);\r
+            if(symbol == null)\r
+                return;\r
+            \r
+            if(graph.hasStatement(symbol, sr.ValveSymbol_orientation))\r
+                graph.deny(symbol, sr.ValveSymbol_orientation);\r
+            graph.claim(symbol, sr.ValveSymbol_orientation, graph.getResource(uri));\r
+            \r
+            if(graph.hasStatement(symbol, sr.ValveSymbol_textLocation))\r
+                graph.deny(symbol, sr.ValveSymbol_textLocation);\r
+            if(sr.Vertical.equals(graph.getResource(uri)))\r
+                graph.claim(symbol, sr.ValveSymbol_textLocation, sr.Right);\r
+                \r
+        }\r
+        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ValveTextLocationGroup.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ValveTextLocationGroup.java
new file mode 100644 (file)
index 0000000..8761596
--- /dev/null
@@ -0,0 +1,152 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.WidgetImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.datastructures.Quad;\r
+\r
+public class ValveTextLocationGroup extends WidgetImpl {\r
+\r
+    Group group;\r
+    Button top, bottom, left, right;\r
+    \r
+    public ValveTextLocationGroup(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
+        super(support);\r
+        \r
+        group = new Group(parent, SWT.NONE);\r
+        group.setText("Text location");\r
+        GridDataFactory.fillDefaults().applyTo(group);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(group);\r
+        \r
+        top = new Button(group, support, SWT.RADIO);\r
+        top.setText("Top");\r
+        top.setSelectionFactory(new LocationSelectionFactory(top, SysdynResource.URIs.Top));\r
+        top.addSelectionListener(new LocationSelectionListener(context, SysdynResource.URIs.Top));\r
+        \r
+        bottom = new Button(group, support, SWT.RADIO);\r
+        bottom.setText("Bottom");\r
+        bottom.setSelectionFactory(new LocationSelectionFactory(bottom, SysdynResource.URIs.Bottom, true));\r
+        bottom.addSelectionListener(new LocationSelectionListener(context, SysdynResource.URIs.Bottom));\r
+        \r
+        left = new Button(group, support, SWT.RADIO);\r
+        left.setText("Left");\r
+        left.setSelectionFactory(new LocationSelectionFactory(left, SysdynResource.URIs.Left));\r
+        left.addSelectionListener(new LocationSelectionListener(context, SysdynResource.URIs.Left));\r
+        \r
+        right = new Button(group, support, SWT.RADIO);\r
+        right.setText("Right");\r
+        right.setSelectionFactory(new LocationSelectionFactory(right, SysdynResource.URIs.Right));\r
+        right.addSelectionListener(new LocationSelectionListener(context, SysdynResource.URIs.Right));\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        top.setInput(context, input);\r
+        bottom.setInput(context, input);\r
+        left.setInput(context, input);\r
+        right.setInput(context, input);\r
+    }\r
+\r
+    @Override\r
+    public Control getControl() {\r
+        return this.group;\r
+    }\r
+    \r
+    \r
+    private class LocationSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        \r
+        boolean defaultSelected;\r
+        String uri;\r
+        Button button;\r
+        \r
+        public LocationSelectionFactory(Button button, String uri) {\r
+            this(button, uri, false);\r
+        }\r
+\r
+        public LocationSelectionFactory(Button button, String uri, boolean defaultSelected) {\r
+            this.uri = uri;\r
+            this.defaultSelected = defaultSelected;\r
+            this.button = button;\r
+        }\r
+        \r
+        public Object getIdentity(Object inputContents) {\r
+            return new Quad<Object, Object, Object, Class<?>>(button, uri, defaultSelected, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource valve) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            ModelingResources mr = ModelingResources.getInstance(graph);\r
+            if(!graph.isInstanceOf(valve, sr.Valve))\r
+                return Boolean.FALSE;\r
+            \r
+            Resource symbol = graph.getPossibleObject(valve, mr.ComponentToElement);\r
+            if(symbol == null)\r
+                return Boolean.FALSE;\r
+            \r
+            Resource location = graph.getPossibleObject(symbol, sr.ValveSymbol_textLocation);\r
+            \r
+            if(location == null)\r
+                return defaultSelected;\r
+            \r
+            return location.equals(graph.getResource(uri));\r
+        }\r
+        \r
+    }\r
+    \r
+    \r
+    private class LocationSelectionListener extends SelectionListenerImpl<Resource> {\r
+        \r
+        String uri;\r
+        \r
+        public LocationSelectionListener(ISessionContext context, String uri) {\r
+            super(context);\r
+            this.uri = uri;\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource valve) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            ModelingResources mr = ModelingResources.getInstance(graph);\r
+            if(!graph.isInstanceOf(valve, sr.Valve))\r
+                return;\r
+            \r
+            Resource symbol = graph.getPossibleObject(valve, mr.ComponentToElement);\r
+            if(symbol == null)\r
+                return;\r
+            \r
+            if(graph.hasStatement(symbol, sr.ValveSymbol_textLocation))\r
+                graph.deny(symbol, sr.ValveSymbol_textLocation);\r
+            graph.claim(symbol, sr.ValveSymbol_textLocation, graph.getResource(uri));\r
+        }\r
+        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/AvailableEnumerations.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/AvailableEnumerations.java
new file mode 100644 (file)
index 0000000..76a46f0
--- /dev/null
@@ -0,0 +1,53 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.impl.contributor.viewpoint.ViewpointContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.ResourceArray;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class AvailableEnumerations extends ViewpointContributorImpl<ResourceArray> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, ResourceArray input)\r
+                       throws DatabaseException {\r
+               Resource[] selection = input.resources;\r
+               if(selection.length < 1)\r
+                   return Collections.emptyList();\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               Resource configuration = null;\r
+               \r
+               // Variables need to be from the same configuration\r
+               for(Resource r : selection) {\r
+                   Resource conf = graph.getPossibleObject(r, l0.PartOf);\r
+                   if(configuration == null || conf.equals(configuration))\r
+                       configuration = conf;\r
+                   else\r
+                       return Collections.emptyList();\r
+               }\r
+               \r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        if(configuration == null) \r
+               return result;\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {\r
+                result.add(new EnumerationNode(r));\r
+        }\r
+        return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "Available enumerations";\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ComboBoxModifier.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ComboBoxModifier.java
new file mode 100644 (file)
index 0000000..d45b1a2
--- /dev/null
@@ -0,0 +1,136 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.widgets.Combo;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.common.modifiers.EnumeratedValue;\r
+import org.simantics.browsing.ui.common.modifiers.Enumeration;\r
+import org.simantics.browsing.ui.content.Labeler.CustomModifier;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.utils.ObjectUtils;\r
+\r
+public abstract class ComboBoxModifier<T> implements CustomModifier {\r
+\r
+       private final Enumeration<T> enumeration;\r
+       private final EnumeratedValue<T> value;\r
+       private final List<String> values;\r
+       private final Session session;\r
+       private Combo combo;\r
+       int select;\r
+\r
+       public ComboBoxModifier(Session session, Enumeration<T> enumeration, T value) {\r
+               this(session, enumeration, enumeration.find(value));\r
+       }\r
+\r
+       public ComboBoxModifier(Session session, Enumeration<T> enumeration,\r
+                       EnumeratedValue<T> value) {\r
+               if (session == null)\r
+                       throw new NullPointerException("null session");\r
+               if (enumeration == null)\r
+                       throw new NullPointerException("null enumeration");\r
+               if (enumeration.size() == 0)\r
+                       throw new IllegalArgumentException("");\r
+\r
+               this.enumeration = enumeration;\r
+               this.value = value;\r
+               this.session = session;\r
+\r
+               select = 0;\r
+               boolean found = false;\r
+               \r
+               this.values = new ArrayList<String>();\r
+               for (EnumeratedValue<T> v : enumeration.values()) {\r
+                       values.add(v.getName());\r
+                       \r
+                       if(v == value) \r
+                               found = true;\r
+                       \r
+                       if(found == false)\r
+                               select++;\r
+               }\r
+       }\r
+\r
+       @Override\r
+       public Object createControl(Object parentControl, Object controlItem,\r
+                       int columnIndex, NodeContext context) {\r
+\r
+               combo = new Combo((Composite) parentControl, SWT.DROP_DOWN\r
+                               | SWT.BORDER | SWT.READ_ONLY);\r
+\r
+               for (String item : values) {\r
+                       combo.add(item);\r
+               }\r
+               \r
+               combo.addSelectionListener(new SelectionAdapter() {\r
+                       @Override\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               String index = ((Combo) e.getSource()).getText();\r
+                               modify(index);\r
+                       }\r
+               });\r
+               \r
+               combo.select(select);\r
+               \r
+               return combo;\r
+\r
+       }\r
+\r
+       @Override\r
+       public String getValue() {\r
+               return enumeration.values().get(0).getName();\r
+       }\r
+\r
+    @Override\r
+    public final String isValid(String label) {\r
+        if (enumeration.findByName(label) == null)\r
+            return "Value '" + label + "' is not among the enumerated values " + enumeration.values();\r
+        return null;\r
+    }\r
+\r
+       @Override\r
+       public void modify(String label) {\r
+               \r
+        int index = values.indexOf(label);\r
+        if (index == -1)\r
+            throw new IllegalArgumentException("Cannot modify enumeration with value '" + label + "', not among the enumerated values " + values);\r
+               \r
+        EnumeratedValue<T> oldEnumValue = value;\r
+        EnumeratedValue<T> newEnumValue = enumeration.values().get(index);\r
+        \r
+        final T oldObject = oldEnumValue != null ? oldEnumValue.getObject() : null;\r
+        final T newObject = newEnumValue != null ? newEnumValue.getObject() : null;\r
+        \r
+        if (ObjectUtils.objectEquals(oldObject, newObject))\r
+            return;\r
+\r
+        try {\r
+            session.getSession().syncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                    modifyWithObject(graph, oldObject, newObject);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            handleException(e);\r
+        }\r
+        \r
+               combo.dispose();                \r
+       }\r
+       \r
+       protected abstract void modifyWithObject(WriteGraph graph, T oldEnumObject, T enumObject) throws DatabaseException;\r
+       \r
+    protected void handleException(DatabaseException e) {\r
+        throw new RuntimeException(e);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ConflictingEnumerationLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ConflictingEnumerationLabeler.java
new file mode 100644 (file)
index 0000000..4fa7ef9
--- /dev/null
@@ -0,0 +1,41 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.labeler.ColumnLabelerContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+\r
+public class ConflictingEnumerationLabeler extends ColumnLabelerContributorImpl<ConflictingEnumerationNode>{\r
+\r
+    @Override\r
+    public Map<String, String> getLabel(ReadGraph graph, ConflictingEnumerationNode input)\r
+            throws DatabaseException {\r
+        HashMap<String, String> map = new HashMap<String, String>();\r
+\r
+        boolean first = true;\r
+        StringBuilder names = new StringBuilder();\r
+        for(Resource r : (Resource[])input.data) {\r
+            if(!first)\r
+                names.append(", ");\r
+            first = false;\r
+\r
+            String name = "empty";\r
+            if(r != null)\r
+                name =  NameUtils.getSafeName(graph, r);\r
+            names.append(name);\r
+        }\r
+        map.put(ColumnKeys.ENUMERATION, names.toString());\r
+\r
+        map.put(ColumnKeys.INDEXES, "Conflicting enumerations");\r
+        \r
+        return map;\r
+    }\r
+\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ConflictingEnumerationNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ConflictingEnumerationNode.java
new file mode 100644 (file)
index 0000000..b93f849
--- /dev/null
@@ -0,0 +1,11 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+\r
+public class ConflictingEnumerationNode extends AbstractNode<Object> {\r
+\r
+    public ConflictingEnumerationNode(Object resources) {\r
+        super(resources);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexLabeler.java
new file mode 100644 (file)
index 0000000..a740831
--- /dev/null
@@ -0,0 +1,20 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+\r
+public class EnumerationIndexLabeler  extends LabelerContributor<EnumerationIndexNode>{\r
+\r
+    @Override\r
+    public String getLabel(ReadGraph graph, EnumerationIndexNode index) throws DatabaseException {\r
+       Resource r = index.data;\r
+       if(r == null) return "Null resource";\r
+       String name = graph.getPossibleRelatedValue(r, Layer0.getInstance(graph).HasName);\r
+        return name == null ? "No name" : name;\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexNode.java
new file mode 100644 (file)
index 0000000..ff7b702
--- /dev/null
@@ -0,0 +1,93 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class EnumerationIndexNode  extends AbstractNode<Resource> implements IModifiableNode, IDoubleClickableNode {\r
+\r
+       public EnumerationIndexNode(Resource resource) {\r
+               super(resource);\r
+       }\r
+       \r
+       @Override\r
+       public Modifier getModifier(String columnId) {\r
+        Modifier modifier = new Modifier() {\r
+\r
+            @Override\r
+            public String getValue() {\r
+                Read<String> request =\r
+                    new Read<String>() {\r
+\r
+                    @Override\r
+                    public String perform(ReadGraph graph) throws DatabaseException {\r
+                        String name = graph.getPossibleRelatedValue(data, Layer0.getInstance(graph).HasName);\r
+                        return name != null ? name : "";\r
+                    }\r
+\r
+                };\r
+                try {\r
+                    return SimanticsUI.getSession().syncRequest(request);\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                    return "";\r
+                }\r
+            }\r
+\r
+            @Override\r
+            public String isValid(String label) {\r
+               if(!new VariableNameValidator().isValidModelica(label, true))\r
+                       return "Not valid";\r
+                return null;\r
+            }\r
+\r
+            @Override\r
+            public void modify(final String label) {\r
+               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);\r
+                    }\r
+                });\r
+            }\r
+\r
+        };\r
+        \r
+        return modifier;\r
+        \r
+        \r
+        \r
+        \r
+       }\r
+\r
+       @Override\r
+       public boolean handleDoubleClick() {\r
+               return true;\r
+       }\r
+       \r
+       public void setShowInChartsSelected(final boolean selected) {\r
+       try {\r
+                       SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                           @Override\r
+                           public void perform(WriteGraph graph) throws DatabaseException {\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               graph.claimLiteral(data, sr.EnumerationIndex_showEnumerationIndexInCharts, selected);\r
+                           }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexes.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationIndexes.java
new file mode 100644 (file)
index 0000000..a4758fc
--- /dev/null
@@ -0,0 +1,40 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.impl.contributor.viewpoint.ViewpointContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class EnumerationIndexes extends ViewpointContributorImpl<Resource> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, Resource input)\r
+                       throws DatabaseException {\r
+               if(input == null) \r
+                       return null;\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               if(!graph.isInstanceOf(input, sr.Enumeration))\r
+                       return null;\r
+               Resource enumerationIndexList = graph.getPossibleObject(input, sr.Enumeration_enumerationIndexList);\r
+               if(enumerationIndexList == null)\r
+                       return null;\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+        for(Resource r : ListUtils.toList(graph, enumerationIndexList)) {\r
+            result.add(new EnumerationIndexNode(r));\r
+    }\r
+        return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "Enumeration indexes";\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationLabeler.java
new file mode 100644 (file)
index 0000000..f274331
--- /dev/null
@@ -0,0 +1,52 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.labeler.ColumnLabelerContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+\r
+public class EnumerationLabeler extends ColumnLabelerContributorImpl<EnumerationNode>{\r
+\r
+       @Override\r
+       public Map<String, String> getLabel(ReadGraph graph, EnumerationNode input)\r
+                       throws DatabaseException {\r
+               \r
+               String name =  NameUtils.getSafeName(graph, input.data);\r
+               HashMap<String, String> map = new HashMap<String, String>();\r
+               map.put(ColumnKeys.ENUMERATION, name);\r
+               \r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               Resource enumerationIndexes = graph.getPossibleObject(input.data, sr.Enumeration_enumerationIndexList);\r
+               Iterator<Resource> indexes = ListUtils.toList(graph, enumerationIndexes).iterator();\r
+               StringBuilder sb = new StringBuilder();\r
+               sb.append("[");\r
+               while(indexes.hasNext()) {\r
+                       Resource i = indexes.next();\r
+                       sb.append(NameUtils.getSafeName(graph, i));\r
+                       if(indexes.hasNext())\r
+                               sb.append(", ");\r
+               }\r
+               sb.append("]");\r
+               \r
+               Boolean relaceable = graph.getPossibleRelatedValue(input.data, sr.Enumeration_isReplaceable);\r
+               if(Boolean.TRUE.equals(relaceable)) {\r
+                       sb.append(" Replaceable");\r
+               }\r
+               \r
+               map.put(ColumnKeys.INDEXES, sb.toString());\r
+               \r
+               return map;\r
+       }\r
+\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/EnumerationNode.java
new file mode 100644 (file)
index 0000000..2d96005
--- /dev/null
@@ -0,0 +1,12 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.db.Resource;\r
+\r
+public class EnumerationNode  extends AbstractNode<Resource> {\r
+\r
+       public EnumerationNode(Resource resource) {\r
+               super(resource);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/NameAndArrayRangeModifyListener.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/NameAndArrayRangeModifyListener.java
new file mode 100644 (file)
index 0000000..6807d49
--- /dev/null
@@ -0,0 +1,149 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.LinkedHashMap;\r
+import java.util.StringTokenizer;\r
+\r
+import org.eclipse.swt.widgets.Combo;\r
+import org.simantics.Simantics;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.VirtualGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.ArrayExpressionCombo;\r
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Modification listener ONLY for ArrayExpressionCombos in EquationTabs.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class NameAndArrayRangeModifyListener extends ComboModifyListenerImpl<Resource> implements Widget {\r
+\r
+       Resource lastExpression; \r
+       ExpressionWidget expressionWidget;\r
+       ArrayExpressionCombo arrayExpressionCombo;\r
+       Object lastInput;\r
+\r
+       public NameAndArrayRangeModifyListener(WidgetSupport support, ExpressionWidget expressionWidget, ArrayExpressionCombo arrayExpressionCombo) {\r
+               support.register(this);\r
+               this.expressionWidget = expressionWidget;\r
+               this.arrayExpressionCombo = arrayExpressionCombo;\r
+       }\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               super.setInput(context, input);\r
+               this.lastInput = input;\r
+       } \r
+               \r
+       @Override\r
+    public void modifyText(TrackedModifyEvent e) {             \r
+               Combo combo = (Combo)e.getWidget();\r
+               LinkedHashMap<?, ?> data = (LinkedHashMap<?, ?>) combo.getData();\r
+               \r
+               Resource activeExpression = null;\r
+               try {\r
+               final Object input = lastInput;\r
+                       activeExpression = Simantics.getSession().syncRequest(new Read<Resource>() {\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph)\r
+                                               throws DatabaseException {\r
+                                       Resource variable = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
+                                       return graph.getPossibleObject(variable, SysdynResource.getInstance(graph).IndependentVariable_activeExpression);\r
+                               }\r
+                               \r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               \r
+\r
+               Resource expression = (Resource) data.get(combo.getText());\r
+               if(expression != null) {\r
+                       lastExpression = expression;\r
+                       arrayExpressionCombo.setLastSelectedIndex(combo.getSelectionIndex());\r
+               } else {\r
+                       for(Object key : data.keySet()) {\r
+                               int index = arrayExpressionCombo.getLastSelectedIndex() < 0 ? 0 : arrayExpressionCombo.getLastSelectedIndex();\r
+                               if((Integer)combo.getData((String)key) == index) {\r
+                                       lastExpression =  (Resource) data.get(key);\r
+                                       break;\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               // If expression has changed (i.e. user actually selects a different item in the combo), save the previous \r
+               if(lastExpression != null \r
+                               && !lastExpression.equals(activeExpression)\r
+                               && expressionWidget != null) {\r
+                       expressionWidget.save();\r
+               }\r
+\r
+               super.modifyText(e);\r
+       }\r
+\r
+       @Override\r
+       public void applyText(WriteGraph graph, final Resource variable, String text)\r
+                       throws DatabaseException {\r
+               StringTokenizer st = new StringTokenizer(text, "[]");\r
+               final String newName = st.nextToken();\r
+               String range = null;\r
+               if(st.hasMoreTokens()) {\r
+                       range = st.nextToken();\r
+               }\r
+               String originalName = graph.getRelatedValue(variable, Layer0.getInstance(graph).HasName);\r
+               if(!originalName.equals(newName)) {\r
+                   Resource configuration = graph.getPossibleObject(variable, Layer0.getInstance(graph).PartOf);\r
+                   new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, newName);\r
+                       graph.claimLiteral(variable, Layer0.getInstance(graph).HasName, newName);\r
+               }\r
+\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+               if(range != null && lastExpression != null) {\r
+                       String oldRange = graph.getPossibleRelatedValue(lastExpression, sr.Expression_arrayRange);\r
+                       if(oldRange == null || !range.equals(oldRange)) {\r
+                               graph.claimLiteral(lastExpression, sr.Expression_arrayRange, "[" + range + "]");\r
+                       }\r
+               } else if (range == null && lastExpression != null && graph.hasStatement(lastExpression, sr.Expression_arrayRange)) {\r
+                       graph.deny(lastExpression, sr.Expression_arrayRange);\r
+               }\r
+\r
+               Resource activeExpression = graph.getPossibleObject(variable, sr.IndependentVariable_activeExpression);\r
+\r
+               if(lastExpression != null && !lastExpression.equals(activeExpression)) {\r
+                       VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
+                       final Session session = graph.getSession();\r
+                       session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
+                                       session.asyncRequest(new WriteRequest(runtime) {\r
+                                               @Override\r
+                                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                                       if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
+                                                               graph.deny(variable, sr.IndependentVariable_activeExpression);\r
+                                                       graph.claim(variable, sr.IndependentVariable_activeExpression, lastExpression);\r
+                                               }\r
+                                       });\r
+                               }\r
+                       });\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/RedeclarationNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/RedeclarationNode.java
new file mode 100644 (file)
index 0000000..6c2b678
--- /dev/null
@@ -0,0 +1,172 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.browsing.ui.common.modifiers.EnumeratedValue;\r
+import org.simantics.browsing.ui.common.modifiers.Enumeration;\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class RedeclarationNode  extends AbstractNode<Resource> implements IModifiableNode {\r
+\r
+       private Resource module;\r
+       \r
+       public RedeclarationNode(ReadGraph graph, final Resource module, Resource enumeration) {\r
+               super(enumeration);\r
+               this.module = module;\r
+       }\r
+       \r
+       /**\r
+        * \r
+        * @param graph\r
+        * @return\r
+        */\r
+       public Resource getReplacingEnumeration(ReadGraph graph) {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Resource result = null;\r
+               try {\r
+                       Resource redeclaration = getRedeclaration(graph);\r
+                       if(redeclaration != null) {\r
+                               result = graph.getSingleObject(redeclaration, sr.Redeclaration_replacingEnumeration);\r
+                       }\r
+               } catch(DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+               return result;\r
+       }\r
+       \r
+\r
+       public Resource getModule() {\r
+               return module;\r
+       }\r
+\r
+       public void setModule(Resource module) {\r
+               this.module = module;\r
+       }\r
+\r
+       public Resource getRedeclaration(ReadGraph graph) {\r
+               try {\r
+                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                       for(Resource redeclaration : graph.syncRequest(new ObjectsWithType(module, sr.Module_redeclaration, sr.Redeclaration))) {\r
+                               Resource replacedEnumeration = graph.getPossibleObject(redeclaration, sr.Redeclaration_replacedEnumeration);\r
+                               if(replacedEnumeration != null && replacedEnumeration.equals(getReplacedEnumeration())) {\r
+                                       return redeclaration;\r
+                               }\r
+                       }\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               return null;\r
+       }\r
+\r
+       public void setRedeclaration(WriteGraph graph, Resource redeclaration) {\r
+               try {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Resource oldRedeclaration = getRedeclaration(graph);\r
+               if(oldRedeclaration != null || redeclaration == null) {\r
+                       graph.deny(module, sr.Module_redeclaration, oldRedeclaration);\r
+               }\r
+               \r
+               if(redeclaration != null)\r
+                       graph.claim(module, sr.Module_redeclaration, redeclaration);\r
+               \r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+\r
+       public Resource getReplacedEnumeration() {\r
+               return this.data;\r
+       }\r
+\r
+       @Override\r
+       public Modifier getModifier(String columnId) {\r
+               \r
+               if(!ColumnKeys.REPLACED_WITH.equals(columnId))\r
+                       return null;\r
+               \r
+               ComboBoxModifier<Resource> cbm = null;\r
+               \r
+               try {\r
+                       cbm = SimanticsUI.getSession().syncRequest(new Read<ComboBoxModifier<Resource>>() {\r
+                               \r
+                               @Override\r
+                               public ComboBoxModifier<Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       \r
+                                       ArrayList<EnumeratedValue<Resource>> values = new ArrayList<EnumeratedValue<Resource>>();\r
+                                       \r
+                                       \r
+                               Resource configuration = graph.getSingleObject(module, l0.PartOf);\r
+                               \r
+                                       for(Resource enumeration : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {\r
+                                               String name = NameUtils.getSafeName(graph, enumeration);\r
+                                               values.add(new EnumeratedValue<Resource>(name, enumeration));                                   \r
+                                       }\r
+\r
+                                       if(values.size() == 0)\r
+                                               return null;\r
+                                       \r
+                                       values.add(0, new EnumeratedValue<Resource>("", null));\r
+                                       Enumeration<Resource> enumeration = new Enumeration<Resource>(values);  \r
+                                       \r
+                                       ComboBoxModifier<Resource> cbm = new ComboBoxModifier<Resource>(graph.getSession(), enumeration, getReplacingEnumeration(graph)) {\r
+                                               \r
+                                               @Override\r
+                                               protected void modifyWithObject(WriteGraph graph, Resource oldEnumObject,\r
+                                                               Resource enumObject) throws DatabaseException {\r
+                                                       \r
+                                                       if(enumObject == null) {\r
+                                                               setRedeclaration(graph, null);\r
+                                                       } else if(!enumObject.equals(oldEnumObject)) {\r
+                                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                                               Resource redeclaration = GraphUtils.create2(graph, \r
+                                                                               sr.Redeclaration, \r
+                                                                               sr.Redeclaration_replacedEnumeration, getReplacedEnumeration(),\r
+                                                                               sr.Redeclaration_replacingEnumeration, enumObject);\r
+                                                               setRedeclaration(graph, redeclaration);\r
+                                                       }\r
+                                                       \r
+                                               }\r
+                                       };\r
+                                       \r
+                                       return cbm;\r
+                                       \r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       // TODO Auto-generated catch block\r
+                       e.printStackTrace();\r
+               }\r
+\r
+               return cbm;\r
+       }\r
+       \r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableEnumerations.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableEnumerations.java
new file mode 100644 (file)
index 0000000..7f8a1fa
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.viewpoint.ViewpointContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ReplaceableEnumerations  extends ViewpointContributorImpl<Resource> {\r
+       \r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, Resource input)\r
+                       throws DatabaseException {\r
+        ArrayList<RedeclarationNode> result = new ArrayList<RedeclarationNode>();\r
+        if(input == null)\r
+               return result;\r
+        \r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+        \r
+        Resource moduleType = graph.getPossibleObject(input, l0.InstanceOf);\r
+        if(moduleType == null)\r
+            return result;\r
+        Resource configuration = graph.getPossibleObject(moduleType, sr2.IsDefinedBy);\r
+        if(configuration == null)\r
+            return result;\r
+        \r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {\r
+                       if(Boolean.TRUE.equals(graph.getRelatedValue(r, sr.Enumeration_isReplaceable)))\r
+                               result.add(new RedeclarationNode(graph, input, r));\r
+               }\r
+               \r
+        return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "Replaceable enumerations";\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableEnumerationsLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableEnumerationsLabeler.java
new file mode 100644 (file)
index 0000000..68a44db
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.labeler.ColumnLabelerContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+\r
+public class ReplaceableEnumerationsLabeler extends ColumnLabelerContributorImpl<RedeclarationNode>{\r
+\r
+       @Override\r
+       public Map<String, String> getLabel(ReadGraph graph, RedeclarationNode input)\r
+                       throws DatabaseException {\r
+               HashMap<String, String> map = new HashMap<String, String>();\r
+               \r
+               String name = NameUtils.getSafeName(graph, input.data);\r
+               map.put(ColumnKeys.ENUMERATION, name);\r
+               \r
+               Resource replacingEnumeration = input.getReplacingEnumeration(graph); \r
+               String replacingEnumerationName = "";\r
+               if(replacingEnumeration != null)\r
+                       replacingEnumerationName = NameUtils.getSafeName(graph, replacingEnumeration);\r
+               \r
+               map.put(ColumnKeys.REPLACED_WITH, replacingEnumerationName);\r
+               return map;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableIndexesWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ReplaceableIndexesWidget.java
new file mode 100644 (file)
index 0000000..0dd0a49
--- /dev/null
@@ -0,0 +1,117 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+public class ReplaceableIndexesWidget implements Widget {\r
+       \r
+    Resource variable = null; \r
+    boolean selected = false;\r
+    org.simantics.browsing.ui.swt.widgets.Button isReplaceableButton;\r
+    \r
+    public ReplaceableIndexesWidget(Composite parent, WidgetSupport support, int style) {\r
+        support.register(this);\r
+        isReplaceableButton = new org.simantics.browsing.ui.swt.widgets.Button(parent, support, style |= SWT.CHECK);\r
+        isReplaceableButton.setText("Can be replaced by parent module");\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        if(input instanceof ISelection) {\r
+            ISelection selection = (ISelection)input;\r
+            if(selection instanceof IStructuredSelection) {\r
+                Resource resource = ISelectionUtils.filterSingleSelection(selection, Resource.class);\r
+                if(resource != null) {\r
+                    variable = resource;\r
+                }\r
+            }\r
+        }\r
+        \r
+        if(variable == null) return;\r
+        \r
+        try {\r
+            context.getSession().syncRequest(new ReadRequest() {\r
+                \r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    final Boolean replaceable = graph.getPossibleRelatedValue(variable, sr.Enumeration_isReplaceable);\r
+                    if(replaceable != null)\r
+                       selected = replaceable;\r
+                    final Button button = getWidget();\r
+                    button.getDisplay().asyncExec(new Runnable() {\r
+                        \r
+                        @Override\r
+                        public void run() {\r
+                            if(button.isDisposed()) return;\r
+                            \r
+                            if(replaceable)\r
+                                button.setSelection(true);\r
+                            else\r
+                                button.setSelection(false);\r
+                        }\r
+                    });\r
+\r
+                        \r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        isReplaceableButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
+                SysdynResource sr =  SysdynResource.getInstance(graph);\r
+                Boolean replaceable = graph.getPossibleRelatedValue(input, sr.Enumeration_isReplaceable);\r
+                if(Boolean.TRUE.equals(replaceable)) {\r
+                    graph.claimLiteral(input, sr.Enumeration_isReplaceable, false);\r
+                    selected = false;\r
+                } else {\r
+                       graph.claimLiteral(input, sr.Enumeration_isReplaceable, true);\r
+                       selected = true;\r
+                }\r
+            }\r
+        });\r
+    }\r
+    \r
+    public Button getWidget() {\r
+        return isReplaceableButton.getWidget();\r
+    }\r
+    \r
+    public boolean getSelection() {\r
+       return selected;\r
+    }\r
+    \r
+    public void addSelectionListener(SelectionListener listener) {\r
+       isReplaceableButton.addSelectionListener(listener);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ShowInChartsCheckBox.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/ShowInChartsCheckBox.java
new file mode 100644 (file)
index 0000000..da412f4
--- /dev/null
@@ -0,0 +1,21 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import org.simantics.browsing.ui.CheckedState;\r
+import org.simantics.browsing.ui.graph.contributor.labeler.CheckedStateContributor;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ShowInChartsCheckBox extends CheckedStateContributor<EnumerationIndexNode> {\r
+\r
+       @Override\r
+       public CheckedState getState(ReadGraph graph, EnumerationIndexNode input)\r
+                       throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Boolean selected = graph.getPossibleRelatedValue(input.data, sr.EnumerationIndex_showEnumerationIndexInCharts, Bindings.BOOLEAN);\r
+               return selected ? CheckedState.CHECKED : CheckedState.NOT_CHECKED;\r
+       }\r
+       \r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/UsedEnumerations.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/UsedEnumerations.java
new file mode 100644 (file)
index 0000000..2940291
--- /dev/null
@@ -0,0 +1,115 @@
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.impl.contributor.viewpoint.ViewpointContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.ResourceArray;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class UsedEnumerations extends ViewpointContributorImpl<ResourceArray> {\r
+\r
+               @Override\r
+               public Collection<?> getContribution(ReadGraph graph, ResourceArray input)\r
+                               throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               Resource[] selection = input.resources;\r
+               if(selection.length < 1)\r
+                   return Collections.emptyList();\r
+               \r
+               /* Collect enumerations for all variables\r
+                * var1\r
+                *     - enum1\r
+                *     - enum2\r
+                * var2\r
+                *     - enum1\r
+                *     - enum2\r
+                *     - enum3\r
+                */\r
+               ArrayList<List<Resource>> variableEnumerations = new ArrayList<List<Resource>>();\r
+               for(Resource variable : selection) {\r
+                   Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
+                   if(arrayIndexes != null) {\r
+                       variableEnumerations.add(ListUtils.toList(graph, arrayIndexes));\r
+                   } else {\r
+                       variableEnumerations.add(new ArrayList<Resource>());\r
+                   }\r
+               }\r
+\r
+\r
+               /* Construct a list of enumerations\r
+                * FirstEnumeration\r
+                *     - var1.first\r
+                *     - var2.first\r
+                *     - var3.first\r
+                * SecondEnumeration\r
+                *     - var1.second\r
+                *     - ...\r
+                */\r
+               ArrayList<List<Resource>> enumerations = new ArrayList<List<Resource>>();\r
+\r
+               int index = 0;\r
+               while(true) {\r
+\r
+                   // Break loop if enumerations for all variables have been recorded\r
+                   boolean b = true;\r
+                   for(List<Resource> varEnums : variableEnumerations) {\r
+                       if(index < varEnums.size()) {\r
+                           b = false;\r
+                           break;\r
+                       }\r
+                   }\r
+                   \r
+                   if(b) break;\r
+                   \r
+                   for(List<Resource> current : variableEnumerations) {\r
+                       if(index == enumerations.size())\r
+                           enumerations.add(index, new ArrayList<Resource>());\r
+                       Resource enumeration =  index < current.size()? current.get(index) : null;\r
+                       enumerations.get(index).add(enumeration);\r
+                   }\r
+                   \r
+                   index++;\r
+               }\r
+               \r
+               // Build nodes\r
+               ArrayList<AbstractNode<?>> result = new ArrayList<AbstractNode<?>>();\r
+\r
+               if(enumerations.size() == 1 && (enumerations.get(0).size() == 0 || (enumerations.get(0).size() == 1 && enumerations.get(0).get(0) == null)))\r
+                   return result;\r
+               \r
+               for(List<Resource> enumeration : enumerations) {\r
+                   boolean same = true;\r
+                   for(int i = 0; i < enumeration.size() - 1; i++) {\r
+                       if(enumeration.get(i) == null || enumeration.get(i + 1) == null ||\r
+                               !enumeration.get(i).equals(enumeration.get(i + 1))) {\r
+                           same = false;\r
+                           break;\r
+                       }\r
+                   }\r
+                   \r
+                   if(!same) {\r
+                       result.add(new ConflictingEnumerationNode(enumeration.toArray(new Resource[enumeration.size()])));\r
+                   } else {\r
+                       result.add(new EnumerationNode(enumeration.get(0)));\r
+                   }\r
+               }\r
+               \r
+\r
+               \r
+               return result;\r
+               }\r
+\r
+               @Override\r
+               public String getViewpointId() {\r
+                       return "Used enumerations";\r
+               }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/UsedEnumerationsManyVariables.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/UsedEnumerationsManyVariables.java
new file mode 100644 (file)
index 0000000..28defab
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.List;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.impl.contributor.viewpoint.ViewpointContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public class UsedEnumerationsManyVariables  extends ViewpointContributorImpl<List<Resource>> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, List<Resource> input)\r
+                       throws DatabaseException {\r
+               \r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+\r
+        return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "Available enumerations";\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/AuxiliaryExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/AuxiliaryExpression.java
new file mode 100644 (file)
index 0000000..48a5e7d
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class AuxiliaryExpression extends BasicExpression {\r
+\r
+    public AuxiliaryExpression(ExpressionWidgetInput input) {\r
+        super(input);\r
+        try {\r
+            this.expressionType = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                @Override\r
+                public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                    return SysdynResource.getInstance(graph).NormalExpression;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
+        // Create the single field\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
+        String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
+\r
+        Label l = new Label(parent, SWT.NONE);\r
+        l.setText("=");\r
+\r
+        expression = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
+        expression.setExpression(equation);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/BasicExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/BasicExpression.java
new file mode 100644 (file)
index 0000000..12ad3c8
--- /dev/null
@@ -0,0 +1,239 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.text.BadLocationException;\r
+import org.eclipse.jface.text.IDocument;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.CommentMetadata;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Basic expression that is used with parameter, auxiliary and constant\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class BasicExpression implements IExpression {\r
+\r
+    protected ExpressionField expression;\r
+    protected Resource expressionType;\r
+    protected ExpressionWidgetInput input;\r
+    \r
+    public BasicExpression(ExpressionWidgetInput input) {\r
+        this.input = input;\r
+    }\r
+    \r
+    @Override\r
+    public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
+        // Create the single field\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
+        String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
+\r
+        Label l = new Label(parent, SWT.NONE);\r
+        l.setText("=");\r
+\r
+        expression = new ExpressionField(parent, SWT.BORDER, null, false, input);\r
+        expression.setExpression(equation);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
+\r
+    }\r
+\r
+    @Override\r
+    public void focus() {\r
+        this.expression.focus();\r
+\r
+    }\r
+\r
+    @Override\r
+    public List<ExpressionField> getExpressionFields() {\r
+        return Arrays.asList(this.expression);\r
+    }\r
+\r
+    @Override\r
+    public void readData(final Resource expression, Map<String, Object> data) {\r
+        String equation = null;\r
+        if (expression != null && data.get("equation") == null) {\r
+            try {\r
+                equation = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                    @Override\r
+                    public String perform(ReadGraph graph) throws DatabaseException {\r
+                        SysdynResource sr = SysdynResource.getInstance(graph);\r
+                        if (expression != null) {\r
+                            String equation = graph.getPossibleRelatedValue(expression, sr.Expression_equation);\r
+                            if(equation != null)\r
+                               return equation;\r
+                        }\r
+                        \r
+                        return "";\r
+                        \r
+                    }\r
+\r
+                });\r
+            } catch (DatabaseException e1) {\r
+                e1.printStackTrace();\r
+            }\r
+            data.put("equation", equation);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void replaceSelection(String var) {\r
+        if(expression != null) {\r
+            IDocument doc = expression.getDocument();\r
+            try {\r
+                Point selection = expression.getSelection();\r
+                doc.replace(selection.x, selection.y, var);\r
+                expression.setSelection(selection.x + var.length());\r
+            } catch (BadLocationException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void save(final Resource expression, Map<String, Object> data) {\r
+        final String currentText = this.expression.getExpression();\r
+        final String oldEquation = (String)data.get("equation");\r
+\r
+        if(oldEquation == null || \r
+                (currentText != null && expressionType != null)) {\r
+            data.put("equation", currentText);\r
+            SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph g)\r
+                throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(g);\r
+                    Layer0 l0 = Layer0.getInstance(g);\r
+\r
+                    // If nothing has changed, do nothing\r
+                    if (oldEquation != null \r
+                            && expression != null \r
+                            && g.isInstanceOf(expression, expressionType) \r
+                            && currentText.equals(oldEquation)) {\r
+                        return;\r
+                    }\r
+                    \r
+                    // Force change to parameter, if the equation is a parameter\r
+                    if(ExpressionUtils.isParameter(currentText)) {\r
+                       if(!expressionType.equals(sr.ConstantExpression))\r
+                               expressionType = sr.ParameterExpression;\r
+                    } else {\r
+                       expressionType = sr.NormalExpression;\r
+                    }\r
+                    \r
+                    g.markUndoPoint();\r
+                               CommentMetadata cm = g.getMetadata(CommentMetadata.class);\r
+                               g.addMetadata(cm.add("Set equation"));\r
+\r
+                    // If the current expression type is different than the target expression type, create a new expression\r
+                    if(!g.isInstanceOf(expression, expressionType)) {\r
+\r
+                       final Resource newExpression = GraphUtils.create2(g, expressionType, \r
+                                       sr.Expression_equation, currentText);\r
+                       String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);\r
+                       if(arrayRange != null)\r
+                               g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);\r
+                       \r
+                       final Resource variable = g.getPossibleObject(expression, l0.PartOf);\r
+                       if(variable == null)\r
+                           return;\r
+                       Resource ownerList = g.getPossibleObject(variable, sr.Variable_expressionList);\r
+                       if(ownerList == null)\r
+                           return;\r
+                       \r
+                       ListUtils.replace(g, ownerList, expression, newExpression);\r
+                       \r
+                       g.deny(expression, l0.PartOf);\r
+                       \r
+                       g.claim(newExpression, l0.PartOf, variable);\r
+                       \r
+                       \r
+                        VirtualGraphSupport support = g.getService(VirtualGraphSupport.class);\r
+                                               g.syncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
+                                                       @Override\r
+                                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                                               if(variable != null) {\r
+                                                                       if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
+                                                                               graph.deny(variable, sr.IndependentVariable_activeExpression);\r
+                                                                       graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                               );\r
+                    } else {\r
+                        // Claim value for the expression\r
+                       g.claimLiteral(expression, sr.Expression_equation, currentText);\r
+                    }\r
+                }\r
+\r
+            });\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void updateData(Map<String, Object> data) {\r
+        if(this.expression != null && this.expression.getExpression() != null)\r
+            data.put("equation", this.expression.getExpression());\r
+    }\r
+\r
+    @Override\r
+    public void addKeyListener(KeyListener listener) {\r
+        this.expression.getSourceViewer().getTextWidget().addKeyListener(listener);\r
+\r
+    }\r
+\r
+    @Override\r
+    public void addModifyListener(ModifyListener listener) {\r
+        this.expression.getSourceViewer().getTextWidget().addModifyListener(listener);\r
+\r
+    }\r
+\r
+    @Override\r
+    public void addFocusListener(FocusListener listener) {\r
+        this.expression.getSourceViewer().getTextWidget().addFocusListener(listener);\r
+    }\r
+\r
+       @Override\r
+       public void addVerifyKeyListener(VerifyKeyListener listener) {\r
+               this.expression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ColorManager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ColorManager.java
new file mode 100644 (file)
index 0000000..a25d215
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import gnu.trove.THashMap;\r
+\r
+import org.eclipse.jface.text.source.ISharedTextColors;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.eclipse.swt.widgets.Display;\r
+\r
+public class ColorManager implements ISharedTextColors {\r
+\r
+    THashMap<RGB,Color> map = new THashMap<RGB,Color>();\r
+\r
+    @Override\r
+    public void dispose() {\r
+        for(Color c : map.values())\r
+            c.dispose();\r
+        map.clear();\r
+    }\r
+\r
+    @Override\r
+    public Color getColor(RGB rgb) {\r
+        Color color = map.get(rgb);\r
+        if (color == null) {\r
+            color = new Color(Display.getCurrent(), rgb);\r
+            map.put(rgb, color);\r
+        }\r
+        return color;\r
+\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/CompletionProcessor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/CompletionProcessor.java
new file mode 100644 (file)
index 0000000..d2d78a5
--- /dev/null
@@ -0,0 +1,348 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.Comparator;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.jface.text.ITextViewer;\r
+import org.eclipse.jface.text.contentassist.CompletionProposal;\r
+import org.eclipse.jface.text.contentassist.ICompletionProposal;\r
+import org.eclipse.jface.text.contentassist.IContentAssistProcessor;\r
+import org.eclipse.jface.text.contentassist.IContextInformation;\r
+import org.eclipse.jface.text.contentassist.IContextInformationValidator;\r
+import org.eclipse.swt.graphics.Image;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableItem;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.properties.widgets.ShortcutTabWidget;\r
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
+import org.simantics.sysdyn.utils.Function;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+\r
+/**\r
+ * IContentAssistProcessor to determine which options (the functions and \r
+ * variables available) are shown for ContentAssistant; this assist of\r
+ * text field allows long variable names to be selected from a popup menu.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class CompletionProcessor implements IContentAssistProcessor {\r
+       \r
+    private final Table allowedVariables;\r
+    private ArrayList<Function> functions;\r
+    private ArrayList<String> variables = null;\r
+    private ArrayList<String> timeAndSelfVariables = null;\r
+    private final ExpressionWidgetInput input;\r
+    \r
+    private LocalResourceManager resourceManager;\r
+    \r
+       private static final char[] ALLOWED_CHARACTERS = {\r
+               'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','Ã¥','ä','ö',\r
+               'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Ã…','Ä','Ö',\r
+               '1','2','3','4','5','6','7','8','9','0','.','(',')'};\r
+           \r
+       private static final String ALLOWED_CONNECTED_CHARACTERS_REG_EXP = "[\\Q({[:;,<=>+-*/^\\E]";\r
+       \r
+       private static final ArrayList<String> ALLOW_ALL_COMPLETIONS_LIST = new ArrayList<String>();\r
+       static {\r
+               ALLOW_ALL_COMPLETIONS_LIST.add("");\r
+       }\r
+       \r
+       public CompletionProcessor(Table allowedVariables, boolean allowFunctions, ExpressionWidgetInput input) {\r
+               this.allowedVariables = allowedVariables;\r
+               this.input = input;\r
+               this.functions = new ArrayList<Function>();\r
+               \r
+               if (allowFunctions) {\r
+                   if (input != null && CompletionProcessor.this.input.variable != null) {\r
+                       // Get the respective model\r
+                       Resource model = null;\r
+                   try {\r
+                    model = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                        @Override\r
+                        public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                            return Variables.getModel(graph, CompletionProcessor.this.input.variable);\r
+                        }\r
+                    });\r
+                    \r
+                    //User defined functions\r
+                    functions.addAll(Function.getUserDefinedFunctions(model));\r
+                    // Shared functions\r
+                    functions.addAll(Function.getSharedFunctions(model));\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                }\r
+                   }\r
\r
+                   // Collect built in functions and sort all functions.\r
+               functions.addAll(Function.getAllBuiltInFunctions());\r
+            Collections.sort(functions);\r
+       }\r
+       }\r
+    \r
+       /**\r
+        * Collect and sort all variables.\r
+        */\r
+       private void findVariables() {\r
+           if (variables == null) {\r
+            variables = new ArrayList<String>();\r
+            timeAndSelfVariables = new ArrayList<String>();\r
+            if(allowedVariables != null && !allowedVariables.isDisposed()) {\r
+                TableItem[] connectedVariables = allowedVariables.getItems();\r
+                for(TableItem ti : connectedVariables) {\r
+                    // The status of the variable is determined using the color of its table item :(\r
+                    if (ExpressionUtils.variableTimeAndSelfColor(resourceManager).equals(ti.getForeground())) {\r
+                        this.timeAndSelfVariables.add(ti.getText());\r
+                    } else {\r
+                        this.variables.add(ti.getText());\r
+                    }\r
+                    \r
+                }\r
+            }\r
+            Collections.sort(variables);\r
+            Collections.sort(timeAndSelfVariables);\r
+        }\r
+       }\r
+       \r
+       /**\r
+        * Create CompletionProposals of the variables and add them to array. Do not allow duplicates.\r
+        * @param array result array of CompletionProposals\r
+        * @param token current token\r
+        * @param offset an offset within the document for which completions should be computed\r
+        */\r
+       private void addVariables(ArrayList<ICompletionProposal> array, String token, int offset) {\r
+           Image imageVariable = resourceManager.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/variable.png")));\r
+        Image imageVariableGray = resourceManager.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/variableGray.png")));\r
+        \r
+        for (String variable : variables) {\r
+            if ((token.length() == 0 || variable.toUpperCase().startsWith(token.toUpperCase()))\r
+                       && !listContainsVariable(array, variable)) {\r
+               array.add(new CompletionProposal(variable, \r
+                        offset - token.length(),\r
+                        token.length(), \r
+                        variable.length(), \r
+                        imageVariable, \r
+                        variable, \r
+                        null, \r
+                        null));\r
+            }   \r
+        }\r
+        for (String variable : timeAndSelfVariables) {\r
+            if ((token.length() == 0 || variable.toUpperCase().startsWith(token.toUpperCase()))\r
+                       && !listContainsVariable(array, variable)) {\r
+                array.add(new CompletionProposal(variable, \r
+                        offset - token.length(),\r
+                        token.length(), \r
+                        variable.length(), \r
+                        imageVariableGray, \r
+                        variable, \r
+                        null, \r
+                        null));\r
+            }   \r
+        }\r
+       }\r
+       \r
+       private boolean listContainsVariable(ArrayList<ICompletionProposal> array,\r
+                       String variable) {\r
+               for (ICompletionProposal proposal : array) {\r
+                       if (proposal.getDisplayString().equals(variable))\r
+                               return true;\r
+               }\r
+               return false;\r
+       }\r
+\r
+       /**\r
+     * Create CompletionProposals of the functions and add them to array.\r
+     * @param array result array of CompletionProposals\r
+     * @param token current token\r
+     * @param offset an offset within the document for which completions should be computed\r
+     */\r
+       private void addFunctions(ArrayList<ICompletionProposal> array, String token, int offset) {\r
+           // Parameters don't have functions\r
+           if (functions == null)\r
+               return;\r
+           \r
+           // Create CompletionProposals out of Functions\r
+        for (Function function : functions) {\r
+            if (token.length() == 0 || function.getName().toUpperCase().startsWith(token.toUpperCase())) {\r
+                Image image = ShortcutTabWidget.getImage(resourceManager, function);\r
+                String parameterList = Function.inputListToString(function.getInputList());\r
+                array.add(new CompletionProposal(\r
+                        function.getName() + "(" + parameterList + ")", \r
+                        offset - token.length(),\r
+                        token.length(), \r
+                        function.getName().length() + 1,\r
+                        image, \r
+                        function.getName() + "(" + parameterList + ")", \r
+                        null, \r
+                        function.getDescriptionHTML()));\r
+            }   \r
+        }\r
+       }\r
+       \r
+       /**\r
+     * Collect all matching proposals. Duplicates are removed; the one with the longest token stays.\r
+     * @param possibleLabelBeginnings sets of whitespace delimited tokens (as Strings)\r
+     * @param offset an offset within the document for which completions should be computed\r
+     * @return Array of matching proposals\r
+     */\r
+    private ICompletionProposal[] collectProposals(ArrayList<String> possibleLabelBeginnings, int offset) {\r
+           ArrayList<ICompletionProposal> resultArray = new ArrayList<ICompletionProposal>();\r
+        \r
+           // Find variables and functions and create CompletionProposals out of them.\r
+           findVariables();\r
+           \r
+           // Sort the list based on the length of the tokens (descending) to get "" to end.\r
+           Collections.sort(possibleLabelBeginnings, new Comparator<String>(){\r
+                       @Override\r
+                       public int compare(String o1, String o2) {\r
+                               if (o1.length() > o2.length()) {\r
+                                       return -1;\r
+                               } else if (o1.length() < o2.length()) {\r
+                                       return 1;\r
+                               }\r
+                               return 0;\r
+                       }\r
+               });\r
+           \r
+           for (String possibleLabelBeginning : possibleLabelBeginnings) {\r
+               addVariables(resultArray, possibleLabelBeginning, offset);\r
+           }\r
\r
+           // No support for whitespace in function names; get shortest beginning\r
+       addFunctions(resultArray, possibleLabelBeginnings.get(possibleLabelBeginnings.size() - 1), offset);\r
+\r
+       ICompletionProposal[] result = new ICompletionProposal[resultArray.size()];\r
+               for (int i = 0; i < result.length; ++i) {\r
+                       result[i] = resultArray.get(i);\r
+               }\r
+               return result;\r
+       }\r
+       \r
+    @Override\r
+       public ICompletionProposal[] computeCompletionProposals(\r
+                       ITextViewer viewer, int offset) {\r
+               String equation = viewer.getDocument().get();\r
+               Control control = viewer.getTextWidget();\r
+               this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), control);\r
+               \r
+               if (equation.length() == 0 || offset == 0) {\r
+                       return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);\r
+               }\r
+               \r
+               equation = equation.substring(0, offset);\r
+               \r
+           // Split the equation on '+', '-', etc. characters\r
+        String stringsBetweenConnectedCharacters[] = equation.split(ALLOWED_CONNECTED_CHARACTERS_REG_EXP);\r
+               if (stringsBetweenConnectedCharacters.length == 0) {\r
+                       return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);\r
+               }\r
+               String stringAfterLastConnectedCharacter = stringsBetweenConnectedCharacters[stringsBetweenConnectedCharacters.length - 1];\r
+               String stringAfterWhitespaceAfterLastConnectedCharacter = removeLeadingWhitespace(stringAfterLastConnectedCharacter);\r
+                               \r
+               // Split into tokens on whitespace characters, include also the trailing empty strings\r
+               String[] tokens = stringAfterWhitespaceAfterLastConnectedCharacter.split("[\\s]", -42);\r
+               \r
+               // Only whitespace after the last connection character\r
+               if (allTokensAreEmpty(tokens))\r
+                       return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);\r
+                       \r
+               return collectProposals(getPossibleLabelBeginnings(tokens), offset);\r
+       }\r
+\r
+       /**\r
+        * Collect all possible strings (with each whitespace replaced by a space character)\r
+        * which may be a beginning of a variable. \r
+        * Create the beginnings by adding whitespace between. E.g.:\r
+        *       {"multi", "part", "variab"}\r
+        *   -> { "multi part variab",\r
+        *        "part variab",\r
+        *        "variab" }\r
+        * @param tokens list of tokens\r
+     * @return all possible label beginnings\r
+        */\r
+    private ArrayList<String> getPossibleLabelBeginnings(String[] tokens) {\r
+               ArrayList<String> possibleLabelBeginnings = new ArrayList<String>();\r
+               for (int i = 0; i < tokens.length; ++i) {\r
+                       String token = new String();\r
+                       for (int j = i; j < tokens.length; ++j) {\r
+                               token += " " + tokens[j];\r
+                       }\r
+                       // Remove the excess space character from the beginning\r
+                       token = token.substring(1);\r
+                       \r
+                       possibleLabelBeginnings.add(token);\r
+               }\r
+               return possibleLabelBeginnings;\r
+       }\r
+\r
+       /**\r
+     * Remove leading whitespace\r
+     * @param input\r
+     * @return\r
+     */\r
+       private String removeLeadingWhitespace(String input) {\r
+               for (int i = 0; i < input.length(); ++i) {\r
+                       if (!Character.isWhitespace(input.charAt(i))) {\r
+                               return input.substring(i);\r
+                       }\r
+               }\r
+               return "";\r
+       }\r
+\r
+       private boolean allTokensAreEmpty(String[] tokens) {\r
+               for (String token : tokens)\r
+                       if (!token.equals(""))\r
+                               return false;\r
+               return true;\r
+       }\r
+\r
+       @Override\r
+       public IContextInformation[] computeContextInformation(\r
+                       ITextViewer viewer, int offset) {\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public char[] getCompletionProposalAutoActivationCharacters() {\r
+               return ALLOWED_CHARACTERS;\r
+       }\r
+\r
+       @Override\r
+       public char[] getContextInformationAutoActivationCharacters() {\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public String getErrorMessage() {\r
+               return "Error in CompletionProcessor";\r
+       }\r
+\r
+       @Override\r
+       public IContextInformationValidator getContextInformationValidator() {\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ConstantExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ConstantExpression.java
new file mode 100644 (file)
index 0000000..28a502d
--- /dev/null
@@ -0,0 +1,60 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ConstantExpression extends BasicExpression {\r
+\r
+    public ConstantExpression(ExpressionWidgetInput input) {\r
+        super(input);\r
+        try {\r
+            this.expressionType = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                @Override\r
+                public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                    return SysdynResource.getInstance(graph).ConstantExpression;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
+        // Create the single field\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
+        String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
+\r
+        Label l = new Label(parent, SWT.NONE);\r
+        l.setText("=");\r
+        //System.out.println("ConstantExpression");\r
+        expression = new ExpressionField(parent, SWT.BORDER, null, false, input);\r
+        expression.setExpression(equation);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
+\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/DelayExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/DelayExpression.java
new file mode 100644 (file)
index 0000000..e6b1962
--- /dev/null
@@ -0,0 +1,385 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.text.BadLocationException;\r
+import org.eclipse.jface.text.IDocument;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusAdapter;\r
+import org.eclipse.swt.events.FocusEvent;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Combo;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Spinner;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.VirtualGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.CommentMetadata;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * IExpression for displaying fields of DelayExpression\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class DelayExpression implements IExpression {\r
+\r
+    private ExpressionField equation, delayTime, initialValue;\r
+    private ExpressionField lastSelectedText;\r
+    private Spinner order;\r
+    private final ExpressionWidgetInput input;\r
+    private Resource expression;\r
+       private Combo delayTypeCombo;\r
+\r
+    /**\r
+     * Creates a new DelayExpression\r
+     * @param expression\r
+     */\r
+    public DelayExpression(ExpressionWidgetInput input) {\r
+        this.input = input;\r
+        this.expression = input.expression;\r
+    }\r
+\r
+    /**\r
+     * Displays the fields for delayExpression\r
+     */\r
+    @Override\r
+    public void createExpressionFields(Composite parent, final Map<String, Object> data, Table allowedVariables) {\r
+        // Get possible existing data\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(parent);\r
+        String eq = data.get("equation") != null ? (String)data.get("equation") : "";\r
+        String dt = data.get("delayTime") != null ? (String)data.get("delayTime") : "";\r
+        String iv = data.get("initialValue") != null ? (String)data.get("initialValue") : "";\r
+        int o = data.get("order") != null ? (Integer)data.get("order") : 3;\r
+\r
+        Label l = new Label(parent, SWT.NONE);\r
+        l.setText("Expression");\r
+\r
+        // Equation that is delayed\r
+        equation = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
+        equation.setExpression(eq);\r
+        GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(equation);\r
+        equation.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
+\r
+            @Override\r
+            public void focusLost(FocusEvent e) {\r
+                lastSelectedText = equation;\r
+            }\r
+        });\r
+\r
+        l = new Label(parent, SWT.NONE);\r
+        l.setText("Delay time");\r
+\r
+        // How much the equation is delayed\r
+        delayTime = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
+        delayTime.setExpression(dt);\r
+        GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(delayTime);\r
+\r
+        delayTime.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
+\r
+            @Override\r
+            public void focusLost(FocusEvent e) {\r
+                lastSelectedText = delayTime;\r
+            }\r
+        });\r
+\r
+        l = new Label(parent, SWT.NONE);\r
+        l.setText("Initial value");\r
+\r
+        // What is the initial value of the delay (empty == same as equation)\r
+        initialValue = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
+        initialValue.setExpression(iv);\r
+        GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(initialValue);\r
+\r
+        initialValue.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
+\r
+            @Override\r
+            public void focusLost(FocusEvent e) {\r
+                lastSelectedText = initialValue;\r
+            }\r
+        });\r
+\r
+\r
+        l = new Label(parent, SWT.NONE);\r
+        l.setText("Order");\r
+\r
+        // The order of the delay (default == 3)\r
+        order = new Spinner(parent, SWT.BORDER);\r
+        order.setMinimum(1);\r
+        order.setSelection(o);\r
+        order.addSelectionListener(new SelectionAdapter() {\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                save(expression, data);\r
+            }\r
+        });\r
+        GridDataFactory.fillDefaults().grab(false, false).applyTo(order);\r
+        \r
+        l = new Label(parent, SWT.NONE);\r
+        l.setText("Delay type");\r
+        GridDataFactory.fillDefaults().grab(true, false).align(SWT.END, SWT.CENTER).applyTo(l);\r
+        \r
+        // The type of the delay (material / information delay)\r
+        delayTypeCombo = new Combo(parent, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
+        delayTypeCombo.add("Material");\r
+        delayTypeCombo.add("Information");\r
+        GridDataFactory.fillDefaults().applyTo(delayTypeCombo);\r
+        \r
+               // Initial selection to the combo\r
+        try {\r
+                       boolean isInformationDelay = SimanticsUI.getSession().syncRequest(new Read<Boolean>(){\r
+\r
+                               @Override\r
+                               public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       return graph.hasStatement(expression, sr.DelayExpression_isInformationDelay, expression);\r
+                               }\r
+                       });\r
+                       delayTypeCombo.select(isInformationDelay ? 1 : 0);\r
+           } catch (DatabaseException e1) {\r
+                       delayTypeCombo.select(0);\r
+               e1.printStackTrace();\r
+               }\r
+        \r
+        // Modify listener for selecting the delay type\r
+        delayTypeCombo.addModifyListener(new ModifyListener() {\r
+\r
+                       @Override\r
+                       public void modifyText(ModifyEvent e) {\r
+                               save(expression, data);\r
+                       }\r
+               });\r
+        \r
+        lastSelectedText = equation;\r
+    }\r
+\r
+    @Override\r
+    public void focus() {\r
+        lastSelectedText.setFocus();\r
+    }\r
+\r
+    @Override\r
+    public List<ExpressionField> getExpressionFields() {\r
+        return Arrays.asList(equation, delayTime, initialValue);\r
+    }\r
+\r
+    @Override\r
+    public void readData(final Resource expression, Map<String, Object> data) {\r
+        class Auxiliary {\r
+            String equation, delayTime, initialValue;\r
+            Integer order;\r
+            Boolean isInformationDelay;\r
+        }\r
+\r
+        Auxiliary results = null;\r
+\r
+        try {\r
+            results = SimanticsUI.getSession().syncRequest(new Read<Auxiliary>() {\r
+\r
+                @Override\r
+                public Auxiliary perform(ReadGraph graph) throws DatabaseException {\r
+                    Auxiliary results = new Auxiliary();\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    if (expression != null && graph.isInstanceOf(expression, sr.DelayExpression)) {\r
+                        results.equation = graph.getPossibleRelatedValue(expression, sr.DelayExpression_expression);\r
+                        results.delayTime = graph.getPossibleRelatedValue(expression, sr.DelayExpression_delayTime);\r
+                        results.initialValue = graph.getPossibleRelatedValue(expression, sr.DelayExpression_initialValue);\r
+                        results.order = graph.getPossibleRelatedValue(expression, sr.DelayExpression_order);\r
+                        results.isInformationDelay = graph.hasStatement(expression, sr.DelayExpression_isInformationDelay, expression);\r
+                    } else {\r
+                        results.equation = "";\r
+                        results.delayTime = "";\r
+                        results.order = 1;\r
+                        results.isInformationDelay = false;\r
+                    }\r
+                    return results;\r
+                }\r
+            });\r
+        } catch (DatabaseException e1) {\r
+            e1.printStackTrace();\r
+        }\r
+        if(results.equation != null)\r
+            data.put("equation", results.equation);\r
+        if(results.delayTime != null)\r
+            data.put("delayTime", results.delayTime);\r
+        if(results.initialValue != null)\r
+            data.put("initialValue", results.initialValue);\r
+        if(results.order != null)\r
+            data.put("order", results.order);\r
+        if(results.isInformationDelay != null)\r
+            data.put("isInformationDelay", results.isInformationDelay);\r
+    }\r
+\r
+    @Override\r
+    public void replaceSelection(String var) {\r
+        if(lastSelectedText != null) {\r
+            IDocument doc = lastSelectedText.getDocument();\r
+            try {\r
+                Point selection = lastSelectedText.getSelection();\r
+                doc.replace(selection.x, selection.y, var);\r
+                lastSelectedText.setSelection(selection.x + var.length());\r
+            } catch (BadLocationException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }    \r
+    }\r
+\r
+    @Override\r
+    public void save(Resource expr, Map<String, Object> data) {\r
+        this.expression = expr;\r
+        final String currentEquation = this.equation.getExpression();\r
+        final String currentDelayTime =  this.delayTime.getExpression();\r
+        final String currentInitialValue = this.initialValue.getExpression();\r
+        final Integer currentOrder = this.order.getSelection();\r
+        final Boolean currentIsInformationDelay = (this.delayTypeCombo.getSelectionIndex() == 1);\r
+\r
+        String oldEquation = (String)data.get("equation");\r
+        String oldDelayTime = (String)data.get("delayTime");\r
+        String oldInitialValue = (String)data.get("initialValue");\r
+        Integer oldOrder = (Integer)data.get("order");\r
+        Boolean oldIsInformationDelay = (Boolean)data.get("isInformationDelay");\r
+\r
+        if(oldEquation == null || oldDelayTime == null || oldOrder == null \r
+                       || oldInitialValue == null || oldIsInformationDelay == null \r
+                       || !oldEquation.equals(currentEquation) || !oldDelayTime.equals(currentDelayTime) \r
+                       || !oldOrder.equals(currentOrder) || !oldInitialValue.equals(currentInitialValue)\r
+                       || !oldIsInformationDelay.equals(currentIsInformationDelay)) {\r
+            // old value was null or value has changed -> Do save\r
+\r
+            data.putAll(data);\r
+            data.put("equation", currentEquation);\r
+            data.put("delayTime", currentDelayTime);\r
+            data.put("initialValue", currentInitialValue);\r
+            data.put("order", currentOrder);\r
+            data.put("isInformationDelay", currentIsInformationDelay);\r
+\r
+            SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph g)\r
+                        throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(g);\r
+                    Layer0 l0 = Layer0.getInstance(g);\r
+\r
+                    if(!g.isInstanceOf(expression, sr.DelayExpression)) {\r
+                        // Create a new DelayExpression, if the old expression was something else\r
+                        final Resource newExpression = GraphUtils.create2(g, sr.DelayExpression);\r
+                        String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);\r
+                        if(arrayRange != null)\r
+                            g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);\r
+\r
+                        final Resource variable = g.getPossibleObject(expression, l0.PartOf);\r
+                        Resource ownerList = g.getPossibleObject(variable, sr.Variable_expressionList);\r
+                        ListUtils.replace(g, ownerList, expression, newExpression);\r
+                        g.deny(expression, l0.PartOf);\r
+                        g.claim(newExpression, l0.PartOf, variable);\r
+\r
+                        VirtualGraph runtime = g.getService(VirtualGraph.class);\r
+                        g.syncRequest(new WriteRequest(runtime) {\r
+                            @Override\r
+                            public void perform(WriteGraph graph) throws DatabaseException {\r
+                                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
+                                    graph.deny(variable, sr.IndependentVariable_activeExpression);\r
+                                graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);\r
+                            }\r
+                        });\r
+                        expression = newExpression;\r
+                    }\r
+                    \r
+                    // Claim values\r
+                    g.claimLiteral(expression, sr.DelayExpression_expression, currentEquation);\r
+                    g.claimLiteral(expression, sr.DelayExpression_delayTime, currentDelayTime);\r
+                    g.claimLiteral(expression, sr.DelayExpression_initialValue, currentInitialValue);\r
+                    g.claimLiteral(expression, sr.DelayExpression_order, currentOrder);\r
+                    if (currentIsInformationDelay)\r
+                       g.claim(expression, sr.DelayExpression_isInformationDelay, expression);\r
+                    else\r
+                       g.deny(expression, sr.DelayExpression_isInformationDelay, expression);\r
+                    \r
+                    g.markUndoPoint();\r
+                               CommentMetadata cm = g.getMetadata(CommentMetadata.class);\r
+                               g.addMetadata(cm.add("Set delay expression"));\r
+                    \r
+                }\r
+            });\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public void updateData(Map<String, Object> data) {\r
+        if(this.equation != null && this.equation.getExpression() != null)\r
+            data.put("equation", this.equation.getExpression());\r
+        if(this.delayTime != null && this.delayTime.getExpression() != null)\r
+            data.put("delayTime", this.delayTime.getExpression());   \r
+        if(this.initialValue != null && this.initialValue.getExpression() != null)\r
+            data.put("initialValue", this.initialValue.getExpression());   \r
+        if(this.order != null)\r
+            data.put("order", this.order.getSelection());   \r
+        if(this.delayTypeCombo != null)\r
+            data.put("isInformationDelay", (this.delayTypeCombo.getSelectionIndex() == 1));\r
+    }\r
+\r
+    @Override\r
+    public void addKeyListener(KeyListener listener) {\r
+        this.equation.getSourceViewer().getTextWidget().addKeyListener(listener);\r
+        this.delayTime.getSourceViewer().getTextWidget().addKeyListener(listener);\r
+        this.initialValue.getSourceViewer().getTextWidget().addKeyListener(listener);\r
+    }\r
+\r
+    @Override\r
+    public void addModifyListener(ModifyListener listener) {\r
+        this.equation.getSourceViewer().getTextWidget().addModifyListener(listener);\r
+        this.delayTime.getSourceViewer().getTextWidget().addModifyListener(listener);\r
+        this.initialValue.getSourceViewer().getTextWidget().addModifyListener(listener);\r
+    }\r
+\r
+    @Override\r
+    public void addFocusListener(FocusListener listener) {\r
+        this.equation.getSourceViewer().getTextWidget().addFocusListener(listener);\r
+        this.delayTime.getSourceViewer().getTextWidget().addFocusListener(listener);\r
+        this.initialValue.getSourceViewer().getTextWidget().addFocusListener(listener);\r
+    }\r
+\r
+    @Override\r
+    public void addVerifyKeyListener(VerifyKeyListener listener) {\r
+        this.equation.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
+        this.delayTime.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
+        this.initialValue.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/EmptyExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/EmptyExpression.java
new file mode 100644 (file)
index 0000000..f36fac9
--- /dev/null
@@ -0,0 +1,93 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.db.Resource;\r
+\r
+public class EmptyExpression implements IExpression {\r
+\r
+    @Override\r
+    public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void focus() {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public List<ExpressionField> getExpressionFields() {\r
+        // TODO Auto-generated method stub\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void readData(Resource variable, Map<String, Object> data) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void replaceSelection(String var) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void save(Resource variable, Map<String, Object> data) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void updateData(Map<String, Object> data) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void addKeyListener(KeyListener listener) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void addModifyListener(ModifyListener listener) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void addFocusListener(FocusListener listener) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+       @Override\r
+       public void addVerifyKeyListener(VerifyKeyListener listener) {\r
+               // TODO Auto-generated method stub\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionComposite.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionComposite.java
new file mode 100644 (file)
index 0000000..6459dab
--- /dev/null
@@ -0,0 +1,27 @@
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget;\r
+\r
+/**\r
+ * A composite class for access to save equation in expressionWidget.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ExpressionComposite extends Composite {\r
+\r
+    private ExpressionWidget expressionWidget;\r
+    \r
+    public ExpressionComposite(Composite parent, int style) {\r
+        super(parent, style);\r
+\r
+    }\r
+\r
+    public void saveExpression() {\r
+        expressionWidget.save();\r
+    }\r
+\r
+    public void setExpressionWidget(ExpressionWidget expressionWidget) {\r
+        this.expressionWidget = expressionWidget;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionField.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionField.java
new file mode 100644 (file)
index 0000000..5b5b3af
--- /dev/null
@@ -0,0 +1,300 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.jface.text.Document;\r
+import org.eclipse.jface.text.IDocument;\r
+import org.eclipse.jface.text.PaintManager;\r
+import org.eclipse.jface.text.Position;\r
+import org.eclipse.jface.text.source.Annotation;\r
+import org.eclipse.jface.text.source.AnnotationModel;\r
+import org.eclipse.jface.text.source.AnnotationPainter;\r
+import org.eclipse.jface.text.source.DefaultCharacterPairMatcher;\r
+import org.eclipse.jface.text.source.IAnnotationAccess;\r
+import org.eclipse.jface.text.source.MatchingCharacterPainter;\r
+import org.eclipse.jface.text.source.SourceViewer;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.StyledText;\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusEvent;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyEvent;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.VerifyEvent;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess;\r
+import org.simantics.sysdyn.ui.utils.SyntaxError;\r
+\r
+/**\r
+ * Field for displaying a part of an expression. Expression field uses SourceViewer\r
+ * to display annotations and other visual elements just like any other\r
+ * source viewer in eclipse.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ExpressionField extends Composite {\r
+\r
+    protected SourceViewer                  _sourceViewer;\r
+    protected IDocument                     _document;\r
+    protected AnnotationModel               _annotationModel;\r
+    \r
+    public static final String MISSING_LINK = "MissingLink";\r
+    public static final String NO_SUCH_VARIABLE = "NoSuchVariable";\r
+    public static final String SYNTAX_ERROR = "SyntaxError";\r
+    public static final String SYNTAX_WARNING = "SyntaxWarning";\r
+\r
+    String oldExpression;\r
+\r
+    IAnnotationAccess annotationAccess = new DefaultMarkerAnnotationAccess();\r
+\r
+    ExpressionFieldConfiguration expressionFieldConfiguration;\r
+    \r
+    private final LocalResourceManager resourceManager;\r
+    private final RGB warningRGB = new RGB(255,215,0);\r
+    private final RGB errorRGB = new RGB(255,0,0);\r
+\r
+    /**\r
+     * Create a new expression field\r
+     * @param parent\r
+     * @param style\r
+     */\r
+    public ExpressionField(Composite parent, int style, Table allowedVariables, boolean allowFunctions, ExpressionWidgetInput input) {\r
+        super(parent, style);\r
+        \r
+        // Create a ResourceManager to dispose images when the widget is disposed.\r
+        this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), this);\r
+        \r
+        GridLayoutFactory.fillDefaults().applyTo(this);\r
+        \r
+        int styles = SWT.V_SCROLL\r
+        | SWT.MULTI\r
+        | SWT.FULL_SELECTION\r
+        | SWT.WRAP;\r
+\r
+        _document = new Document();\r
+        _document.set("");\r
+\r
+        _annotationModel = new AnnotationModel();\r
+        _annotationModel.connect(_document);\r
+\r
+        _sourceViewer = new SourceViewer(this,\r
+\r
+                null,\r
+                null,\r
+                true,\r
+                styles);\r
+        \r
+        // Configuration for color management\r
+        expressionFieldConfiguration = new ExpressionFieldConfiguration(\r
+                new LocalResourceManager(JFaceResources.getResources(), _sourceViewer.getControl()), \r
+                allowedVariables, allowFunctions, input);\r
+        _sourceViewer.configure(expressionFieldConfiguration);\r
+        AnnotationPainter painter = new AnnotationPainter(_sourceViewer, annotationAccess);\r
+        _sourceViewer.addPainter(painter);\r
+\r
+        // Annotation types\r
+        Color warningColor =  resourceManager.createColor(warningRGB);\r
+        Color errorColor = resourceManager.createColor(errorRGB);\r
+        painter.addAnnotationType(MISSING_LINK);\r
+        painter.setAnnotationTypeColor(MISSING_LINK, warningColor);\r
+        painter.addAnnotationType(NO_SUCH_VARIABLE);\r
+        painter.setAnnotationTypeColor(NO_SUCH_VARIABLE, errorColor);\r
+        painter.addAnnotationType(SYNTAX_ERROR);\r
+        painter.setAnnotationTypeColor(SYNTAX_ERROR, errorColor);        \r
+        painter.addAnnotationType(SYNTAX_WARNING);\r
+        painter.setAnnotationTypeColor(SYNTAX_WARNING, warningColor);\r
+        \r
+        _sourceViewer.setDocument(_document, _annotationModel);\r
+\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(_sourceViewer.getControl());\r
+\r
+        // Parenthesis matching\r
+        PaintManager paintManager = new PaintManager(_sourceViewer);\r
+        MatchingCharacterPainter matchingCharacterPainter = new MatchingCharacterPainter(_sourceViewer,\r
+                new DefaultCharacterPairMatcher( new char[] {'(', ')', '{', '}', '[', ']'} ));\r
+        matchingCharacterPainter.setColor(resourceManager.createColor(new RGB(160, 160, 160)));\r
+        paintManager.addPainter(matchingCharacterPainter);\r
+        \r
+        \r
+        // Listener for canceling editing. ESC -> revert back to original text\r
+        _sourceViewer.getTextWidget().addKeyListener(new KeyListener() {\r
+\r
+            @Override\r
+            public void keyReleased(KeyEvent e) {\r
+            }\r
+\r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+               // Check if the expression field has an active completion assistant\r
+                               if (!isAssistSessionActive()) {\r
+                                       if(e.keyCode == SWT.ESC && getExpression() != null) {\r
+                           ((StyledText)e.widget).setText(oldExpression);\r
+                           ((StyledText)e.widget).setSelection(getExpression().length());\r
+                                       }\r
+                }   \r
+            }\r
+        });\r
+       \r
+        /* Focus listener saving and restoring selections\r
+         * When focus is lost, current selection is saved, but the selection is removed.\r
+         * When focus is gained back, the selection is restored\r
+         */\r
+        _sourceViewer.getTextWidget().addFocusListener(new FocusListener() {\r
+            \r
+            Point selection = null;\r
+            @Override\r
+            public void focusLost(FocusEvent e) {\r
+                selection = ((StyledText)e.widget).getSelection();\r
+                ((StyledText)e.widget).setSelection(0);\r
+            }\r
+            \r
+            @Override\r
+            public void focusGained(FocusEvent e) {\r
+                if(selection != null)\r
+                    ((StyledText)e.widget).setSelection(selection);\r
+            }\r
+        });\r
+        \r
+        _sourceViewer.appendVerifyKeyListener(new VerifyKeyListener() {\r
+                       @Override\r
+                       public void verifyKey(VerifyEvent event) {\r
+                               // Check for Ctrl+Spacebar\r
+                               if (event.stateMask == SWT.CTRL && event.character == ' ') {\r
+                                       // Check if source viewer is able to perform operation\r
+                                       if (_sourceViewer.canDoOperation(SourceViewer.CONTENTASSIST_PROPOSALS)) {\r
+                                               // Perform operation\r
+                                               _sourceViewer.doOperation(SourceViewer.CONTENTASSIST_PROPOSALS);\r
+                                       }\r
+                                       // Veto this key press to avoid further processing\r
+                                       event.doit = false;\r
+                               }\r
+                       }\r
+\r
+               });\r
+        \r
+    }\r
+\r
+    /**\r
+     * Returns the {@link SourceViewer} of this ExpressionField\r
+     * @return Returns the {@link SourceViewer} of this ExpressionField\r
+     */\r
+    public SourceViewer getSourceViewer() {\r
+        return this._sourceViewer;\r
+    }\r
+    \r
+       public boolean isAssistSessionActive() {\r
+               return expressionFieldConfiguration.isAssistSessionActive();\r
+       }\r
+\r
+    /**\r
+     * Sets missing link annotations to given positions\r
+     * @param positions Positions for missing link annotations\r
+     */\r
+    public void setMissingLinkAnnotations(List<Position> positions){\r
+        for(Position p : positions) {\r
+            Annotation annotation = new Annotation(false);\r
+            annotation.setType(MISSING_LINK);\r
+            annotation.setText("No link to this variable");\r
+            _annotationModel.addAnnotation(annotation, p);        \r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Sets no such variable annotations to given positions\r
+     * @param positions Positions for no such variable annotations\r
+     */\r
+    public void setNoSuchVariableAnnotations(List<Position> positions){\r
+        for(Position p : positions) {\r
+            Annotation annotation = new Annotation(false);\r
+            annotation.setType(NO_SUCH_VARIABLE);\r
+            annotation.setText("No such variable in model");\r
+            _annotationModel.addAnnotation(annotation, p);        \r
+        }\r
+    }\r
+\r
+    \r
+    /**\r
+     * Sets a syntax error annoattion to the expression field\r
+     * @param syntaxError\r
+     */\r
+    public void setSyntaxError(SyntaxError syntaxError) {\r
+        Annotation annotation = new Annotation(false);\r
+        annotation.setType(syntaxError.getType());\r
+        annotation.setText(syntaxError.getMessage());\r
+        Position p = new Position(syntaxError.getStart(_document), syntaxError.getOffset(_document));\r
+        _annotationModel.addAnnotation(annotation, p);      \r
+    }\r
+\r
+    /**\r
+     * Resets all annotations\r
+     */\r
+    public void resetAnnotations() {\r
+        _annotationModel.removeAllAnnotations();\r
+    }\r
+    \r
+    /**\r
+     * Sets an expression to this expression field\r
+     * @param expression\r
+     */\r
+    public void setExpression(String expression) {\r
+        _document.set(expression);\r
+        this.oldExpression = expression;\r
+    }\r
+\r
+    /**\r
+     * Returns the expression of this expression field\r
+     * @return\r
+     */\r
+    public String getExpression() {\r
+        return this._document.get();\r
+    }\r
+\r
+    /**\r
+     * Returns the current selection\r
+     * @return current selection\r
+     */\r
+    public Point getSelection() {\r
+        return _sourceViewer.getSelectedRange();\r
+    }\r
+\r
+    /**\r
+     * Set selection for this expression field. The length of the selection is 0\r
+     * @param selection Selection location\r
+     */\r
+    public void setSelection(int selection) {\r
+        this._sourceViewer.setSelectedRange(selection, 0);\r
+    }\r
+\r
+    public IDocument getDocument() {\r
+        return _document;\r
+    }\r
+\r
+    /**\r
+     * Focus to this expression field\r
+     */\r
+    public void focus() {\r
+        this._sourceViewer.getTextWidget().forceFocus();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionFieldConfiguration.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionFieldConfiguration.java
new file mode 100644 (file)
index 0000000..205d41d
--- /dev/null
@@ -0,0 +1,204 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import org.eclipse.jface.internal.text.html.HTMLTextPresenter;\r
+import org.eclipse.jface.resource.ResourceManager;\r
+import org.eclipse.jface.text.DefaultInformationControl;\r
+import org.eclipse.jface.text.DefaultTextHover;\r
+import org.eclipse.jface.text.IDocument;\r
+import org.eclipse.jface.text.IInformationControl;\r
+import org.eclipse.jface.text.IInformationControlCreator;\r
+import org.eclipse.jface.text.ITextHover;\r
+import org.eclipse.jface.text.TextAttribute;\r
+import org.eclipse.jface.text.contentassist.ContentAssistEvent;\r
+import org.eclipse.jface.text.contentassist.ContentAssistant;\r
+import org.eclipse.jface.text.contentassist.ICompletionListener;\r
+import org.eclipse.jface.text.contentassist.ICompletionProposal;\r
+import org.eclipse.jface.text.contentassist.IContentAssistant;\r
+import org.eclipse.jface.text.presentation.IPresentationReconciler;\r
+import org.eclipse.jface.text.presentation.PresentationReconciler;\r
+import org.eclipse.jface.text.rules.DefaultDamagerRepairer;\r
+import org.eclipse.jface.text.rules.IRule;\r
+import org.eclipse.jface.text.rules.ITokenScanner;\r
+import org.eclipse.jface.text.rules.IWordDetector;\r
+import org.eclipse.jface.text.rules.MultiLineRule;\r
+import org.eclipse.jface.text.rules.RuleBasedScanner;\r
+import org.eclipse.jface.text.rules.Token;\r
+import org.eclipse.jface.text.rules.WordRule;\r
+import org.eclipse.jface.text.source.DefaultAnnotationHover;\r
+import org.eclipse.jface.text.source.IAnnotationHover;\r
+import org.eclipse.jface.text.source.ISourceViewer;\r
+import org.eclipse.jface.text.source.SourceViewerConfiguration;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.sysdyn.ui.modelica.ModelicaSourceViewerConfiguration;\r
+\r
+@SuppressWarnings("restriction")\r
+public class ExpressionFieldConfiguration extends SourceViewerConfiguration {\r
+\r
+       private final long WAIT_BEFORE_STATUS_CHANGE = 100;\r
+       \r
+       Table allowedVariables;\r
+       boolean allowFunctions;\r
+       boolean assistSessionActive; \r
+       CompletionProcessor completionProcessor;\r
+       ResourceManager resourceManager;\r
+\r
+       private final ExpressionWidgetInput input;\r
+       \r
+       public ExpressionFieldConfiguration(ResourceManager resourceManager, Table allowedVariables, boolean allowFunctions, ExpressionWidgetInput input) {\r
+               super();\r
+               this.resourceManager = resourceManager;\r
+               this.allowedVariables = allowedVariables;\r
+               this.allowFunctions = allowFunctions;\r
+               this.assistSessionActive = false;\r
+               this.completionProcessor = null;\r
+               this.input = input;\r
+       }\r
+       \r
+       public boolean isAssistSessionActive() {\r
+               return assistSessionActive;\r
+       }\r
+       \r
+       @Override\r
+    public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {\r
+               return new String[] {\r
+                               IDocument.DEFAULT_CONTENT_TYPE\r
+               };\r
+       }\r
+\r
+       @Override\r
+    public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {\r
+               PresentationReconciler reconciler = new PresentationReconciler();\r
+\r
+               DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getTokenScanner());\r
+\r
+               reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);\r
+               reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);\r
+\r
+               return reconciler;\r
+       }\r
+\r
+\r
+       ITokenScanner getTokenScanner() {\r
+               RuleBasedScanner scanner = new RuleBasedScanner();\r
+\r
+               final Token reserved = new Token(\r
+                               new TextAttribute(\r
+                                       resourceManager.createColor(new RGB(127, 0, 85)),\r
+                                               null,\r
+                                               SWT.BOLD\r
+                               ));\r
+           final Token defaultToken = new Token(new TextAttribute(resourceManager.createColor(new RGB(0, 0, 0))));\r
+\r
+                final Token comment = new Token(new TextAttribute(resourceManager.createColor(new RGB(63, 127, 95))));\r
+\r
+               WordRule reservedWord = new WordRule(new IWordDetector() {   \r
+                       @Override\r
+                       public boolean isWordStart(char c) {\r
+                               return Character.isLetter(c);\r
+                       }\r
+\r
+                       @Override\r
+                       public boolean isWordPart(char c) {\r
+                               return Character.isLetter(c);\r
+                       }\r
+               }, defaultToken);\r
+               \r
+\r
+               for(String s : ModelicaSourceViewerConfiguration.keywords) {\r
+                       reservedWord.addWord(s, reserved);\r
+               }\r
+\r
+               IRule[] rules = new IRule[] {\r
+                               reservedWord,\r
+                               new MultiLineRule("/*", "*/", comment),\r
+                               new MultiLineRule("\"", "\"", comment)\r
+               };\r
+               scanner.setRules(rules);\r
+\r
+               return scanner;  \r
+       }\r
+\r
+       @Override\r
+       public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {\r
+               return new DefaultTextHover(sourceViewer);\r
+       }\r
+\r
+       @Override\r
+       public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {\r
+               return new DefaultAnnotationHover();\r
+       }\r
+\r
+       @Override\r
+       public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {\r
+               ContentAssistant assistant = new ContentAssistant();\r
+               completionProcessor = new CompletionProcessor(allowedVariables, allowFunctions, input);\r
+               assistant.setContentAssistProcessor(completionProcessor, IDocument.DEFAULT_CONTENT_TYPE);\r
+               assistant.enableAutoActivation(true);\r
+               assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));\r
+               assistant.enableAutoInsert(true);\r
+               assistant.setAutoActivationDelay(0);\r
+               assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);\r
+               assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);\r
+               assistant.addCompletionListener(new CompletionListener());\r
+               return assistant;\r
+       }\r
+       \r
+    @Override\r
+    public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {\r
+        return new IInformationControlCreator() {\r
+            @Override\r
+            public IInformationControl createInformationControl(Shell parent) {\r
+                return new DefaultInformationControl(parent,new HTMLTextPresenter(false));\r
+            }\r
+        };\r
+    }\r
+       \r
+       private class CompletionListener implements ICompletionListener {\r
+\r
+               @Override\r
+               public void assistSessionStarted(ContentAssistEvent event) {\r
+                       if (event.processor.equals(completionProcessor)) {\r
+                               assistSessionActive = true;\r
+                       }\r
+               }\r
+\r
+               @Override\r
+               public void assistSessionEnded(ContentAssistEvent event) {\r
+                       if (event.processor.equals(completionProcessor)) {\r
+                               Thread waitBeforeStateChange = new Thread() {\r
+                                       @Override\r
+                    public void run() {\r
+                                               try {\r
+                                                       sleep(WAIT_BEFORE_STATUS_CHANGE);\r
+                                                       assistSessionActive = false;\r
+                                               } catch (InterruptedException e) {\r
+                                                       assistSessionActive = false;\r
+                                               }\r
+                                       }\r
+                               };\r
+                               waitBeforeStateChange.start();\r
+                       }\r
+               }\r
+\r
+               @Override\r
+               public void selectionChanged(ICompletionProposal proposal,\r
+                               boolean smartToggle) {\r
+               }\r
+               \r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionWidgetInput.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ExpressionWidgetInput.java
new file mode 100644 (file)
index 0000000..9f6481c
--- /dev/null
@@ -0,0 +1,30 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.layer0.variable.Variable;\r
+\r
+/**\r
+ * Inputs for expression widgets contain both Variable and the expression resource\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ExpressionWidgetInput {\r
+       public Variable variable;\r
+       public Resource expression;\r
+       \r
+       public ExpressionWidgetInput(Variable variable, Resource expression) {\r
+               this.variable = variable;\r
+               this.expression = expression;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/IExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/IExpression.java
new file mode 100644 (file)
index 0000000..c2c6eff
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.db.Resource;\r
+\r
+public interface IExpression {\r
+\r
+    public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVaribles);\r
+\r
+    public void readData(final Resource expression, Map<String, Object> data);\r
+\r
+    public void save(final Resource expression, Map<String, Object> data);\r
+\r
+    public void focus();\r
+\r
+    public void replaceSelection(String var);\r
+\r
+    public void updateData(Map<String, Object> data);\r
+\r
+    public List<ExpressionField> getExpressionFields();\r
+    \r
+    public void addModifyListener(ModifyListener listener);\r
+    \r
+    public void addKeyListener(KeyListener listener);\r
+    \r
+    public void addVerifyKeyListener(VerifyKeyListener listener);\r
+\r
+    public void addFocusListener(FocusListener listener);\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupChartPanel.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupChartPanel.java
new file mode 100644 (file)
index 0000000..44db3f0
--- /dev/null
@@ -0,0 +1,176 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.awt.Point;\r
+import java.awt.event.MouseEvent;\r
+import java.awt.geom.Point2D;\r
+import java.awt.geom.Rectangle2D;\r
+\r
+import org.jfree.chart.ChartPanel;\r
+import org.jfree.chart.ChartRenderingInfo;\r
+import org.jfree.chart.JFreeChart;\r
+import org.jfree.chart.axis.ValueAxis;\r
+import org.jfree.chart.entity.ChartEntity;\r
+import org.jfree.chart.entity.PlotEntity;\r
+import org.jfree.chart.entity.XYItemEntity;\r
+import org.jfree.chart.plot.XYPlot;\r
+import org.jfree.data.general.SeriesChangeListener;\r
+import org.jfree.data.xy.XYDataset;\r
+import org.jfree.data.xy.XYSeries;\r
+import org.jfree.data.xy.XYSeriesCollection;\r
+\r
+@SuppressWarnings("serial")\r
+public class LookupChartPanel extends ChartPanel {\r
+\r
+    private XYItemEntity dragPrevEntity;\r
+    private boolean drawing;\r
+    private XYSeries series; \r
+    private JFreeChart chart;\r
+    private SeriesChangeListener changeListener;\r
+\r
+    public LookupChartPanel(JFreeChart chart) {\r
+        super(chart);\r
+        this.chart = chart;\r
+        XYSeriesCollection collection = (XYSeriesCollection) ((XYPlot)chart.getPlot()).getDataset();\r
+        series = collection.getSeries(0); \r
+    }\r
+\r
+    public void mouseDragged(MouseEvent e)\r
+    {\r
+        if(dragPrevEntity != null) {\r
+\r
+            int item = dragPrevEntity.getItem();\r
+            XYPlot plot = (XYPlot)chart.getPlot();\r
+            ValueAxis rangeAxis = plot.getRangeAxis();\r
+            ValueAxis domainAxis = plot.getDomainAxis();\r
+            Point2D location = getLocationOnChart(getMouseLocation(e));\r
+            Number prevX = item == 0 ? null : series.getX(item - 1);\r
+            Number nextX = item == series.getItemCount() - 1 ? null : series.getX(item + 1);\r
+\r
+\r
+            if(series.indexOf(location.getX()) >= 0 && series.indexOf(location.getX()) != item)\r
+                return;\r
+            else if (prevX != null && location.getX() < prevX.doubleValue())\r
+                location.setLocation(series.getX(item).doubleValue(), location.getY());\r
+            else if (nextX != null && location.getX() > nextX.doubleValue())\r
+                location.setLocation(series.getX(item).doubleValue(), location.getY());\r
+            else if (location.getX() > domainAxis.getUpperBound())\r
+                location.setLocation(domainAxis.getUpperBound(), location.getY());\r
+            else if (location.getX() < domainAxis.getLowerBound()) \r
+                location.setLocation(domainAxis.getLowerBound(), location.getY());    \r
+\r
+            if (location.getY() > rangeAxis.getUpperBound())\r
+                location.setLocation(location.getX(), rangeAxis.getUpperBound());\r
+            else if (location.getY() < rangeAxis.getLowerBound()) \r
+                location.setLocation(location.getX(), rangeAxis.getLowerBound());    \r
+\r
+            removeItemFromSeries(dragPrevEntity.getItem());\r
+            addLocationToSeries(location);\r
+        } else {\r
+            ChartEntity currEntity = this.getEntityForPoint(e.getX(),e.getY());\r
+            if(!drawing && currEntity instanceof XYItemEntity) {\r
+                dragPrevEntity = ((XYItemEntity)currEntity);\r
+            } else if (currEntity instanceof PlotEntity){\r
+                drawing = true;\r
+                Point2D locationOnChart = getLocationOnChart(getMouseLocation(e));\r
+                int item = series.indexOf(locationOnChart.getX());\r
+                if (item >= 0) {\r
+                    Point2D location = new Point2D.Double(series.getX(item).doubleValue(), series.getY(item).doubleValue());\r
+                    Point2D javaLocation = getLocationOnJava2D(location);\r
+                    removeItemFromSeries(item);\r
+                    addLocationToSeries(getLocationOnChart(new Point2D.Double(javaLocation.getX(), e.getY())));\r
+                }\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    public void mouseReleased(MouseEvent e) {\r
+        if(isDragging()) {\r
+            dragPrevEntity = null;\r
+            if(changeListener != null)\r
+                changeListener.seriesChanged(null);\r
+        }\r
+        drawing = false;\r
+\r
+    }\r
+\r
+    public void mouseClicked(MouseEvent e)\r
+    {\r
+        if(e.getButton() == MouseEvent.BUTTON1) {\r
+            addLocationToSeries(getLocationOnChart(getMouseLocation(e)));\r
+        } else if (e.getButton() == MouseEvent.BUTTON3) {\r
+            ChartEntity entity = this.getEntityForPoint(e.getX(),e.getY());\r
+            if(entity instanceof XYItemEntity) {\r
+                XYItemEntity xyentity = ((XYItemEntity)entity);\r
+                removeItemFromSeries(xyentity.getItem());\r
+            }\r
+        }\r
+    }         \r
+\r
+    private Point2D getLocationOnChart(Point2D coordinates) {\r
+        XYPlot plot = (XYPlot)chart.getPlot();\r
+        ChartRenderingInfo info = getChartRenderingInfo();\r
+        Rectangle2D dataArea = info.getPlotInfo().getDataArea();\r
+        double chartX = plot.getDomainAxis().java2DToValue(coordinates.getX(), dataArea,\r
+                plot.getDomainAxisEdge());\r
+        double chartY = plot.getRangeAxis().java2DToValue(coordinates.getY(), dataArea,\r
+                plot.getRangeAxisEdge());\r
+        return new Point2D.Double(chartX, chartY);\r
+    }\r
+\r
+    private Point2D getLocationOnJava2D(Point2D location) {\r
+        XYPlot plot = (XYPlot)chart.getPlot();\r
+        ChartRenderingInfo info = getChartRenderingInfo();\r
+        Rectangle2D dataArea = info.getPlotInfo().getDataArea();\r
+        double javaX = plot.getDomainAxis().valueToJava2D(location.getX(), dataArea,\r
+                plot.getDomainAxisEdge());\r
+        double javaY = plot.getRangeAxis().valueToJava2D(location.getY(), dataArea,\r
+                plot.getRangeAxisEdge());\r
+        return new Point2D.Double(javaX, javaY);\r
+    }\r
+\r
+    public void addLocationToSeries(Point2D location) {\r
+        if(series.indexOf(location.getX()) < 0) {\r
+            series.add(location.getX(), location.getY());\r
+        }\r
+    }\r
+\r
+    public void removeItemFromSeries(int item){\r
+        series.remove(item);\r
+    }\r
+    \r
+    public void resetChart(XYDataset dataset) {\r
+        XYPlot plot = (XYPlot)chart.getPlot();\r
+        plot.setDataset(dataset);\r
+        XYSeriesCollection collection = (XYSeriesCollection) plot.getDataset();\r
+        series = collection.getSeries(0); \r
+    }\r
+\r
+    private Point2D getMouseLocation(MouseEvent e) {\r
+        int mouseX = e.getX();\r
+        int mouseY = e.getY();\r
+        Point2D p = translateScreenToJava2D(\r
+                new Point(mouseX, mouseY));\r
+        return p;\r
+    }\r
+\r
+    public void addSeriesChangeListener(SeriesChangeListener listener) {\r
+        this.changeListener = listener;\r
+        this.series.addChangeListener(changeListener);\r
+    }\r
+\r
+    public boolean isDragging() {\r
+        return dragPrevEntity != null;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupExpression.java
new file mode 100644 (file)
index 0000000..cf0f230
--- /dev/null
@@ -0,0 +1,93 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.db.Resource;\r
+\r
+public class LookupExpression implements IExpression {\r
+\r
+    @Override\r
+    public void focus() {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public List<ExpressionField> getExpressionFields() {\r
+        // TODO Auto-generated method stub\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void readData(final Resource variable, Map<String, Object> data) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void replaceSelection(String var) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void save(final Resource variable, Map<String, Object> data) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void updateData(Map<String, Object> data) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void addKeyListener(KeyListener listener) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void addModifyListener(ModifyListener listener) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+    @Override\r
+    public void addFocusListener(FocusListener listener) {\r
+        // TODO Auto-generated method stub\r
+        \r
+    }\r
+\r
+       @Override\r
+       public void addVerifyKeyListener(VerifyKeyListener listener) {\r
+               // TODO Auto-generated method stub\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupInputOutputTable.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/LookupInputOutputTable.java
new file mode 100644 (file)
index 0000000..e6eb477
--- /dev/null
@@ -0,0 +1,279 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.awt.geom.Point2D;\r
+import java.util.ArrayList;\r
+import java.util.Comparator;\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ArrayContentProvider;\r
+import org.eclipse.jface.viewers.CellEditor;\r
+import org.eclipse.jface.viewers.ICellModifier;\r
+import org.eclipse.jface.viewers.ITableLabelProvider;\r
+import org.eclipse.jface.viewers.LabelProvider;\r
+import org.eclipse.jface.viewers.TableViewer;\r
+import org.eclipse.jface.viewers.TextCellEditor;\r
+import org.eclipse.jface.viewers.Viewer;\r
+import org.eclipse.jface.viewers.ViewerComparator;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.graphics.Image;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.eclipse.swt.widgets.Item;\r
+import org.eclipse.swt.widgets.Listener;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableColumn;\r
+\r
+public class LookupInputOutputTable extends Composite {\r
+\r
+    public static final String INPUT = "Input";\r
+    public static final String OUTPUT = "Output";\r
+    public static final String[] PROPS = { INPUT, OUTPUT };\r
+\r
+    private Table table;\r
+    private TableViewer tableViewer;\r
+    private List<InputOutput> tableRows;\r
+\r
+    public LookupInputOutputTable(Composite parent, int style) {\r
+        super(parent, style);\r
+\r
+        GridLayoutFactory.fillDefaults().applyTo(this);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(this);\r
+        table = new Table(this, SWT.BORDER|SWT.SINGLE|SWT.FULL_SELECTION);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(table);\r
+        table.setHeaderVisible (true);\r
+        table.setLinesVisible(true);\r
+        table.getVerticalBar().setVisible(true);\r
+        TableColumn column1 = new TableColumn (table, SWT.LEFT);\r
+        column1.setText (INPUT);\r
+        column1.setWidth (85);\r
+\r
+        TableColumn column2 = new TableColumn (table, SWT.LEFT);\r
+        column2.setText (OUTPUT);\r
+        column2.setWidth (85);\r
+\r
+        // Create the viewer and connect it to the view\r
+        tableViewer = new TableViewer (table);\r
+\r
+        tableViewer.setContentProvider (new ArrayContentProvider());\r
+        tableViewer.setLabelProvider (new InputOutputLabelProvider());\r
+        tableViewer.setCellModifier(new InputOutputCellModifier());\r
+\r
+        tableRows = new ArrayList<InputOutput>();     \r
+        tableViewer.setInput(tableRows);\r
+\r
+        CellEditor[] editors = new CellEditor[2];\r
+        editors[0] = new TextCellEditor(table);\r
+        editors[1] = new TextCellEditor(table);\r
+        tableViewer.setCellEditors(editors);\r
+        tableViewer.setColumnProperties(PROPS);\r
+\r
+    }\r
+\r
+    private class InputOutputLabelProvider extends LabelProvider implements ITableLabelProvider {\r
+        public Image getColumnImage (Object element, int columnIndex) {\r
+            return null;\r
+        }\r
+        public String getColumnText (Object element, int columnIndex) {\r
+            if(element instanceof InputOutput) {\r
+                InputOutput io = (InputOutput)element;\r
+                switch (columnIndex) {\r
+                    case 0: return (String)io.getInput(String.class);\r
+                    case 1: return (String)io.getOutput(String.class);\r
+                }\r
+            }\r
+            return "";\r
+        }\r
+    }\r
+\r
+    public void addLocation(Point2D location) {\r
+        tableRows.add(new InputOutput(location.getX(), location.getY()));\r
+        tableViewer.getTable().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                refresh();\r
+            }\r
+        });\r
+\r
+    }\r
+\r
+    public void removeItem(int index) {\r
+        tableRows.remove(index);\r
+        tableViewer.getTable().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                refresh();\r
+            }\r
+        });\r
+    }\r
+\r
+    public void clearTable() {\r
+        this.tableRows.clear();\r
+        tableViewer.getTable().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                refresh();\r
+            }\r
+        });\r
+    }\r
+\r
+\r
+    public class InputOutput {\r
+        private double input, output;\r
+\r
+        public InputOutput(double input, double output) {\r
+            this.input = input;\r
+            this.output = output;\r
+        }\r
+\r
+        /**\r
+         * \r
+         * @param clazz String.class or Double.class\r
+         * @return input as string or double or null if asked for something else\r
+         */\r
+        @SuppressWarnings("rawtypes")\r
+               public Object getInput(Class clazz) {\r
+            if(clazz == String.class) {\r
+                return "" + input;\r
+            } else if (clazz == Double.class) {\r
+                return input;\r
+            }\r
+            return null;\r
+        }\r
+\r
+        public Double setInput(String input) {\r
+            try {\r
+                this.input = Double.parseDouble(input);\r
+                return this.input;\r
+            } catch (NumberFormatException e) {\r
+                return null;\r
+            }\r
+        }\r
+\r
+        public void setInput(double input) {\r
+            this.input = input;\r
+        }\r
+\r
+        /**\r
+         * \r
+         * @param clazz String.class or Double.class\r
+         * @return output as string or double or null if asked for something else\r
+         */\r
+        @SuppressWarnings("rawtypes")\r
+               public Object getOutput(Class clazz) {\r
+            if(clazz == String.class) {\r
+                return "" + output;\r
+            } else if (clazz == Double.class) {\r
+                return output;\r
+            }\r
+            return null;\r
+        }\r
+\r
+        public void setOutput(String output) {\r
+            try {\r
+                this.output = Double.parseDouble(output);\r
+            } catch (NumberFormatException e) {\r
+\r
+            }\r
+        }\r
+\r
+        public void setOutput(double output) {\r
+            this.output = output;\r
+        }\r
+\r
+    }\r
+\r
+    public class InputOutputComparator extends ViewerComparator implements Comparator<InputOutput>{\r
+        @Override\r
+        public int compare(Viewer viewer, Object e1, Object e2) {\r
+            if ((e1 instanceof InputOutput) &&\r
+                    (e2 instanceof InputOutput)) {\r
+               return compare((InputOutput)e1, (InputOutput)e2);\r
+            } else {\r
+               return 0;\r
+            }\r
+        }\r
+\r
+               @Override\r
+               public int compare(InputOutput e1, InputOutput e2) {\r
+                InputOutput io1 = (InputOutput)e1;\r
+                InputOutput io2 = (InputOutput)e2;\r
+                Double d1 = (Double)io1.getInput((Double.class));\r
+                Double d2 = (Double)io2.getInput((Double.class));\r
+                return d1.compareTo(d2);\r
+               }\r
+    }\r
+\r
+    public TableViewer getTableViewer() {\r
+        return this.tableViewer;\r
+    }\r
+\r
+    public void refresh() {\r
+        if(!tableViewer.getTable().isDisposed()) {\r
+            tableViewer.setComparator(new InputOutputComparator());\r
+            tableViewer.refresh();\r
+        }\r
+    }\r
+\r
+    class InputOutputCellModifier implements ICellModifier {\r
+\r
+        public InputOutputCellModifier() {}\r
+\r
+        public boolean canModify(Object element, String property) {\r
+            return true;\r
+        }\r
+\r
+        public Object getValue(Object element, String property) {\r
+            InputOutput io = (InputOutput)element;\r
+            if (LookupInputOutputTable.INPUT.equals(property))\r
+                return (String)io.getInput(String.class);\r
+            else if (LookupInputOutputTable.OUTPUT.equals(property))\r
+                return (String)io.getOutput(String.class);\r
+            else\r
+                return null;\r
+        }\r
+\r
+        public void modify(Object element, String property, Object value) {\r
+            if (element instanceof Item) element = ((Item) element).getData();\r
+\r
+            InputOutput io = (InputOutput)element;\r
+\r
+            if (LookupInputOutputTable.INPUT.equals(property)) {\r
+                io.setInput((String)value);\r
+            } else if (LookupInputOutputTable.OUTPUT.equals(property)) {\r
+                io.setOutput((String)value);\r
+            }\r
+            tableModified();\r
+            refresh();\r
+        }\r
+    }\r
+\r
+    private void tableModified() {\r
+        tableViewer.getTable().getDisplay().asyncExec(new Runnable() {\r
+\r
+            @Override\r
+            public void run() {\r
+                for (Listener listener : getListeners(SWT.Modify)) {\r
+                    Event e = new Event();\r
+                    listener.handleEvent(e);\r
+                }\r
+            }\r
+        });\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ParameterExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ParameterExpression.java
new file mode 100644 (file)
index 0000000..772f083
--- /dev/null
@@ -0,0 +1,182 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.CommentMetadata;\r
+import org.simantics.db.common.request.WriteResultRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ParameterExpression extends BasicExpression {\r
+\r
+       Variable variable;\r
+\r
+       public ParameterExpression(ExpressionWidgetInput input) {\r
+           super(input);\r
+           try {\r
+                       this.expressionType = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                                       return SysdynResource.getInstance(graph).ParameterExpression;\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }               \r
+           \r
+           this.variable = input.variable;\r
+       }\r
+\r
+\r
+       @Override\r
+       public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
+               // Create the single field\r
+               GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
+               String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
+\r
+               Label l = new Label(parent, SWT.NONE);\r
+               l.setText("=");\r
+\r
+               expression = new ExpressionField(parent, SWT.BORDER, null, false, input);\r
+               expression.setExpression(equation);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
+\r
+       }\r
+\r
+       @Override\r
+       public void readData(final Resource expression, Map<String, Object> data) {\r
+               IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+               IExperiment experiment = manager.getActiveExperiment();\r
+               if(experiment == null || !(experiment instanceof SysdynGameExperimentBase)) {\r
+                       super.readData(expression, data);\r
+               } else {\r
+                       Double value;\r
+                       ExperimentState state = ((SysdynGameExperimentBase)experiment).getSysdynExperimentState();\r
+                       if(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)) {\r
+                           try {\r
+                               value = SimanticsUI.getSession().syncRequest(new Read<Double>() {\r
+\r
+                                   @Override\r
+                                   public Double perform(ReadGraph graph) throws DatabaseException {\r
+                                       try {\r
+                                           Variable valuesVariable = variable.browsePossible(graph, "#value#");\r
+                                           double[] res = valuesVariable.getValue(graph);\r
+                                           if(res != null && res.length == 1)\r
+                                               return res[0];\r
+                                           else\r
+                                               return null;\r
+                                       } catch (DatabaseException e) {\r
+                                           throw new DatabaseException(e.getMessage());\r
+                                       } \r
+                                   }\r
+                               });\r
+                               if(value != null)\r
+                                   data.put("equation", value.toString());\r
+                           } catch (DatabaseException e) {}\r
+                       }\r
+                       super.readData(expression, data);\r
+\r
+               }\r
+       }\r
+\r
+       @Override\r
+       public void save(final Resource expression, Map<String, Object> data) {\r
+\r
+               IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+               IExperiment experiment = manager.getActiveExperiment();\r
+               if(experiment != null && experiment instanceof SysdynGameExperimentBase) {\r
+                       final String currentText = this.expression.getExpression();\r
+                       final String oldEquation = (String)data.get("equation");\r
+                       if(oldEquation == null || \r
+                               (currentText != null && oldEquation != null && !currentText.equals(oldEquation) && expressionType != null)) {\r
+                           if(ExpressionUtils.isParameter(currentText)) {\r
+                               Boolean savedIntoFMU = false;\r
+\r
+                               ExperimentState state = ((SysdynGameExperimentBase)experiment).getSysdynExperimentState();\r
+                               // Set value to control only if the simulation is running or stopped, not before initialization\r
+                               if(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)) {\r
+                                   try {\r
+                                       savedIntoFMU = SimanticsUI.getSession().syncRequest(new WriteResultRequest<Boolean>() {\r
+\r
+                                           @Override\r
+                                           public Boolean perform(WriteGraph graph)\r
+                                                   throws DatabaseException {\r
+                                               try {\r
+                                                   Variable valuesVariable = variable.browsePossible(graph, "#value#");\r
+                                                   if(valuesVariable == null)\r
+                                                       return false;\r
+                                                   valuesVariable.setValue(graph, new double[] {Double.parseDouble(currentText)});\r
+                                                   \r
+                                                   graph.markUndoPoint();\r
+                                                               CommentMetadata cm = graph.getMetadata(CommentMetadata.class);\r
+                                                               graph.addMetadata(cm.add("Set parameter"));\r
+                                                   \r
+                                                   return true;\r
+                                               } catch (Exception e) {\r
+                                                   return false;\r
+                                               }\r
+                                           }\r
+\r
+                                       });\r
+                                   } catch (DatabaseException e) {}\r
+                               }\r
+\r
+                               if(savedIntoFMU) {\r
+                                               data.put("equation", currentText);\r
+                                               return;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+\r
+               // If setting a parameter value was not succesful, use the normal save-method\r
+               super.save(expression, data);\r
+       }\r
+\r
+       public ParameterExpression() {\r
+           super(null);\r
+               try {\r
+                       this.expressionType = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                                       return SysdynResource.getInstance(graph).ParameterExpression;\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/StockExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/StockExpression.java
new file mode 100644 (file)
index 0000000..d92c9a1
--- /dev/null
@@ -0,0 +1,379 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.text.BadLocationException;\r
+import org.eclipse.jface.text.IDocument;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusAdapter;\r
+import org.eclipse.swt.events.FocusEvent;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Listener;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.CommentMetadata;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Valve;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class StockExpression implements IExpression {\r
+\r
+    private final ExpressionWidgetInput input;\r
+    private ExpressionField integralExpression, initialExpression;\r
+    private ExpressionField lastSelectedText;\r
+    \r
+    public StockExpression(ExpressionWidgetInput input) {\r
+        this.input = input;\r
+    }\r
+    \r
+    @Override\r
+    public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
+        String initialEquation = data.get("initialEquation") != null ? (String)data.get("initialEquation") : "";\r
+        String integralEquation = data.get("integral") != null ? (String)data.get("integral") : getDefaultIntegral(input.expression);\r
+\r
+\r
+        Label label = new Label(parent, SWT.NONE);\r
+        label.setText("Integral");\r
+\r
+        Composite integralComposite = new Composite(parent, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(integralComposite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(integralComposite);\r
+        \r
+        integralExpression = new ExpressionField(integralComposite, SWT.BORDER, allowedVariables, true, input);\r
+        integralExpression.setExpression(integralEquation);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(integralExpression);\r
+        integralExpression.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
+\r
+            @Override\r
+            public void focusLost(FocusEvent e) {\r
+                lastSelectedText = integralExpression;\r
+            }\r
+        });\r
+        \r
+        Button defaultButton = new Button(integralComposite, SWT.PUSH);\r
+        defaultButton.setText("Use default");\r
+        defaultButton.addListener(SWT.Selection, new Listener() {\r
+\r
+               @Override\r
+               public void handleEvent(Event event) {\r
+                       switch (event.type) {\r
+                       case SWT.Selection:\r
+                               StockExpression.this.integralExpression.setExpression(getDefaultIntegral(input.expression));\r
+                               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph)\r
+                                                       throws DatabaseException {\r
+                                               // Delete the possible integral expression from the database to note \r
+                                               // that we are in the "default" mode.\r
+                                               graph.markUndoPoint();\r
+                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                               graph.deny(input.expression, sr.StockExpression_useCustomIntegral);\r
+                                               graph.claimLiteral(input.expression, sr.StockExpression_integralEquation, getDefaultIntegral(graph, input.expression));\r
+                                               \r
+                                       CommentMetadata cm = graph.getMetadata(CommentMetadata.class);\r
+                                       graph.addMetadata(cm.add("Use default"));\r
+                                               \r
+                                       }\r
+                               });\r
+                               break;\r
+                       }\r
+               }\r
+\r
+        });\r
+\r
+        label = new Label(parent, SWT.NONE);\r
+        label.setText("Initial\nValue");\r
+\r
+        initialExpression = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
+        initialExpression.setExpression(initialEquation);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(initialExpression);\r
+        initialExpression.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
+\r
+            @Override\r
+            public void focusLost(FocusEvent e) {\r
+                lastSelectedText = initialExpression;\r
+            }\r
+        });\r
+\r
+        lastSelectedText = initialExpression;\r
+    }\r
+\r
+    @Override\r
+    public void focus() {\r
+        this.lastSelectedText.focus();\r
+    }\r
+\r
+    @Override\r
+    public List<ExpressionField> getExpressionFields() {\r
+        return Arrays.asList(this.integralExpression, this.initialExpression);\r
+    }\r
+\r
+    @Override\r
+    public void readData(final Resource expression, final Map<String, Object> data) {\r
+        Pair<String, String> equations = null;\r
+        if (expression != null && data.get("initialEquation") == null) {\r
+               try {\r
+                   equations = SimanticsUI.getSession().syncRequest(new Read<Pair<String, String>>() {\r
+       \r
+                       @Override\r
+                       public Pair<String, String> perform(ReadGraph graph) throws DatabaseException {\r
+                           SysdynResource sr = SysdynResource.getInstance(graph);\r
+                           if (graph.isInstanceOf(expression, sr.StockExpression)) {\r
+                               String initialEquation = graph.getPossibleRelatedValue(expression, sr.StockExpression_initialEquation);\r
+                               String integralEquation = graph.getPossibleRelatedValue(expression, sr.StockExpression_integralEquation);\r
+                               initialEquation = (initialEquation != null) ? initialEquation : "";\r
+                               return new Pair<String, String>(integralEquation, initialEquation);\r
+                           } else {\r
+                               return new Pair<String, String>(null, "");\r
+                           }\r
+                       }\r
+       \r
+                   });\r
+               } catch (DatabaseException e1) {\r
+                   e1.printStackTrace();\r
+               }\r
+               data.put("initialEquation", equations.second);\r
+        }\r
+\r
+        if (equations.first == null) {\r
+               try {\r
+                               SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       graph.claimLiteral(input.expression, sr.StockExpression_integralEquation, getDefaultIntegral(graph, input.expression));\r
+                                       graph.markUndoPoint();\r
+                               CommentMetadata cm = graph.getMetadata(CommentMetadata.class);\r
+                               graph.addMetadata(cm.add("Set expression"));\r
+                                       }\r
+\r
+                               });\r
+                       } catch (DatabaseException e) {\r
+                               // TODO Auto-generated catch block\r
+                               e.printStackTrace();\r
+                       }\r
+               \r
+               data.put("integral", getDefaultIntegral(expression));\r
+        } else {\r
+               try {\r
+                       final String integral = equations.first;\r
+                               SimanticsUI.getSession().syncRequest(new ReadRequest() {\r
+\r
+                                       @Override\r
+                                       public void run(ReadGraph graph) throws DatabaseException {\r
+                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       if (graph.hasStatement(input.expression, sr.StockExpression_useCustomIntegral)) {\r
+                                               data.put("integral", integral);\r
+                                       } else {\r
+                                               data.put("integral", getDefaultIntegral(graph, expression));\r
+                                       }\r
+                                       }\r
+\r
+                               });\r
+                       } catch (DatabaseException e) {\r
+                               data.put("integral", equations.first);\r
+                               e.printStackTrace();\r
+                       }\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public void replaceSelection(String var) {\r
+        if(lastSelectedText != null) {\r
+            IDocument doc = lastSelectedText.getDocument();\r
+            try {\r
+                Point selection = lastSelectedText.getSelection();\r
+                doc.replace(selection.x, selection.y, var);\r
+                lastSelectedText.setSelection(selection.x + var.length());\r
+            } catch (BadLocationException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void save(final Resource expression, final Map<String, Object> data) {\r
+       final String currentInitial = this.initialExpression.getExpression();\r
+       final String currentIntegral = this.integralExpression.getExpression();\r
+       if (currentIntegral == null) {\r
+               this.integralExpression.setExpression(getDefaultIntegral(expression));\r
+        }\r
+        if(!currentInitial.equals(data.get("initialEquation"))\r
+                       || currentIntegral == null\r
+                       || !currentIntegral.equals(data.get("integral"))) {\r
+            SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph g)\r
+                throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(g);\r
+                    Layer0 l0 = Layer0.getInstance(g);\r
+                    \r
+                    if(!g.isInstanceOf(expression, sr.StockExpression)) {\r
+                        Resource variable = g.getPossibleObject(expression, l0.PartOf);\r
+                        Resource expressionList = g.getPossibleObject(variable, sr.Variable_expressionList);\r
+                       Resource temp = g.newResource();\r
+                       ListUtils.replace(g, expressionList, expression, temp);\r
+                       \r
+                       for(Resource predicate : g.getPredicates(expression)) {\r
+                           g.deny(expression, predicate);\r
+                       }\r
+                       g.claim(expression, l0.InstanceOf, null, sr.StockExpression);\r
+\r
+                        ListUtils.replace(g, expressionList, temp, expression);\r
+\r
+                       RemoverUtil.remove(g, temp);\r
+\r
+                       g.claim(expression, l0.PartOf, variable);\r
+                    }\r
+                    g.claimLiteral(expression, sr.StockExpression_initialEquation, currentInitial);\r
+                    \r
+                    if (!currentIntegral.equals(g.getPossibleRelatedValue(expression, sr.StockExpression_integralEquation, Bindings.STRING))) {\r
+                       // If the value is not same as default, enable the custom tag\r
+                       g.claim(expression, sr.StockExpression_useCustomIntegral, expression);\r
+                    }\r
+                    g.claimLiteral(expression, sr.StockExpression_integralEquation, currentIntegral);\r
+                    \r
+                    g.markUndoPoint();\r
+                               CommentMetadata cm = g.getMetadata(CommentMetadata.class);\r
+                               g.addMetadata(cm.add("Save"));\r
+\r
+                }\r
+\r
+            });\r
+        }\r
+        this.initialExpression.setExpression(currentInitial);\r
+        this.integralExpression.setExpression(currentIntegral);\r
+    }\r
+\r
+    @Override\r
+    public void updateData(Map<String, Object> data) {\r
+       if(this.initialExpression != null && this.initialExpression.getExpression() != null)\r
+            data.put("initialEquation", this.initialExpression.getExpression());\r
+       if(this.integralExpression != null && this.integralExpression.getExpression() != null)\r
+            data.put("integral", this.integralExpression.getExpression());\r
+    }\r
+\r
+    \r
+    private static String getDefaultIntegral(ReadGraph graph, Resource expression) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+    \r
+           // find the variable\r
+           Resource variable = graph.getPossibleObject(expression, l0.PartOf);\r
+           if(variable == null)\r
+               return "";\r
+           \r
+               SysdynModelManager sdm = SysdynModelManager.getInstance(graph.getSession());\r
+               SysdynModel model = sdm.getModel(graph, graph.getSingleObject(variable, l0.PartOf));\r
+               model.update(graph);\r
+               \r
+               Stock stock = (Stock)model.getElement(variable);\r
+           \r
+               String range = graph.getPossibleRelatedValue(expression, sr.Expression_arrayRange);\r
+               if(range == null)\r
+                       range = "";\r
+       \r
+           StringBuilder builder = new StringBuilder();\r
+           builder.append("");\r
+           for(Valve in : stock.getIncomingValves()) {\r
+               builder.append(" + " + in.getName() + range);\r
+           }\r
+           for(Valve out : stock.getOutgoingValves()) {\r
+               builder.append(" - " + out.getName() + range);\r
+           }\r
+           if (builder.indexOf(" + ") == 0)\r
+               builder.delete(0, 3);\r
+           \r
+           return builder.toString().trim();   \r
+    }\r
+    \r
+    \r
+    private static String getDefaultIntegral(final Resource expression) {\r
+       \r
+        String integral = "";\r
+        if(expression == null)\r
+               return integral;\r
+        try {\r
+            integral = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                @Override\r
+                public String perform(ReadGraph graph) throws DatabaseException {\r
+                       return getDefaultIntegral(graph, expression);\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return integral;\r
+    }\r
+\r
+    @Override\r
+    public void addKeyListener(KeyListener listener) {\r
+        this.initialExpression.getSourceViewer().getTextWidget().addKeyListener(listener);\r
+        this.integralExpression.getSourceViewer().getTextWidget().addKeyListener(listener);\r
+\r
+    }\r
+\r
+    @Override\r
+    public void addModifyListener(ModifyListener listener) {\r
+        this.initialExpression.getSourceViewer().getTextWidget().addModifyListener(listener);\r
+        this.integralExpression.getSourceViewer().getTextWidget().addModifyListener(listener);\r
+\r
+    }\r
+\r
+    @Override\r
+    public void addFocusListener(FocusListener listener) {\r
+        this.initialExpression.getSourceViewer().getTextWidget().addFocusListener(listener);\r
+        this.integralExpression.getSourceViewer().getTextWidget().addFocusListener(listener);\r
+    }\r
+    \r
+       @Override\r
+       public void addVerifyKeyListener(VerifyKeyListener listener) {\r
+               this.initialExpression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
+               this.integralExpression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/WithLookupExpression.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/WithLookupExpression.java
new file mode 100644 (file)
index 0000000..66132ab
--- /dev/null
@@ -0,0 +1,462 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Frame;\r
+import java.awt.event.ActionEvent;\r
+import java.awt.event.ActionListener;\r
+import java.awt.geom.Point2D;\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import javax.swing.Timer;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.text.BadLocationException;\r
+import org.eclipse.jface.text.IDocument;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.awt.SWT_AWT;\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusAdapter;\r
+import org.eclipse.swt.events.FocusEvent;\r
+import org.eclipse.swt.events.FocusListener;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.jfree.chart.ChartFactory;\r
+import org.jfree.chart.ChartPanel;\r
+import org.jfree.chart.JFreeChart;\r
+import org.jfree.chart.plot.PlotOrientation;\r
+import org.jfree.data.xy.XYDataset;\r
+import org.jfree.data.xy.XYSeries;\r
+import org.jfree.data.xy.XYSeriesCollection;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.VirtualGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.CommentMetadata;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.tableParser.ParseException;\r
+import org.simantics.sysdyn.tableParser.TableParser;\r
+import org.simantics.sysdyn.tableParser.Token;\r
+import org.simantics.sysdyn.ui.utils.SyntaxError;\r
+import org.simantics.sysdyn.utils.SheetUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class WithLookupExpression implements IExpression {\r
+\r
+    private ExpressionField expression;\r
+    private ExpressionField lookup;\r
+    private ExpressionField lastSelectedText = expression;\r
+    private Timer updateChartTimer;\r
+\r
+    private ChartPanel smallPanel;\r
+    private Frame smallFrame;\r
+\r
+    private final ExpressionWidgetInput input;\r
+    private Resource expr;\r
+\r
+    public WithLookupExpression(ExpressionWidgetInput input) {\r
+        this.input = input;\r
+        this.expr = input.expression;\r
+    }\r
+\r
+    @Override\r
+    public void createExpressionFields(Composite parent, final Map<String, Object> data, Table allowedVariables) {\r
+        GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parent);\r
+\r
+        updateChartTimer = new Timer(1000, new ActionListener() {\r
+\r
+            @Override\r
+            public void actionPerformed(ActionEvent e) {\r
+                updateChart();\r
+            }\r
+        });\r
+        updateChartTimer.setRepeats(false);\r
+\r
+        String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
+        String lookupTable = data.get("lookup") != null ? (String)data.get("lookup") : "";\r
+\r
+        Label l = new Label(parent, SWT.NONE);\r
+        l.setText("With\nLookup");\r
+\r
+        expression = new ExpressionField(parent, SWT.BORDER, allowedVariables, true ,input);\r
+        expression.setExpression(equation);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
+\r
+        expression.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
+\r
+            @Override\r
+            public void focusLost(FocusEvent e) {\r
+                lastSelectedText = expression;\r
+            }\r
+        });\r
+\r
+        Composite chartContainer = new Composite(parent, SWT.NONE);\r
+        createChart(chartContainer, data);\r
+\r
+\r
+        l = new Label(parent, SWT.NONE);\r
+        l.setText("Lookup\ntable");\r
+\r
+        lookup = new ExpressionField(parent, SWT.BORDER, null, false, input);\r
+        lookup.setExpression(lookupTable);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(lookup);\r
+\r
+        lookup.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
+\r
+            @Override\r
+            public void focusLost(FocusEvent e) {\r
+                lastSelectedText = lookup;\r
+                save(expr, data);\r
+            }\r
+        });\r
+\r
+        lookup.getSourceViewer().getTextWidget().addModifyListener(new ModifyListener() {\r
+\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                if(!updateChartTimer.isRunning())\r
+                    updateChartTimer.start();\r
+                else\r
+                    updateChartTimer.restart();\r
+            }\r
+        });\r
+\r
+\r
+        SimanticsUI.getSession().asyncRequest(new Read<String>() {\r
+\r
+            @Override\r
+            public String perform(ReadGraph graph) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                String result = "";\r
+                if (expr != null && graph.isInstanceOf(expr, sr.WithLookupExpression)) {\r
+                    result = graph.getPossibleRelatedValue(expr, sr.WithLookupExpression_lookup);\r
+                }\r
+                return result;\r
+            }\r
+        }, new Listener<String>() {\r
+\r
+            @Override\r
+            public void exception(Throwable t) {\r
+                t.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public void execute(final String result) {\r
+                if(lookup != null)\r
+                    lookup.getDisplay().asyncExec(new Runnable() {\r
+\r
+                        @Override\r
+                        public void run() {\r
+                            lookup.setExpression(result);       \r
+                            updateChart();\r
+                        }\r
+                    });\r
+            }\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                if(lookup != null && !lookup.isDisposed()) {\r
+                    return false;\r
+                }\r
+                return true;\r
+            }\r
+        });\r
+\r
+        updateChart();\r
+    }\r
+\r
+    @Override\r
+    public void focus() {\r
+        if(this.lastSelectedText != null) this.lastSelectedText.focus();        \r
+    }\r
+\r
+    @Override\r
+    public List<ExpressionField> getExpressionFields() {\r
+        return Arrays.asList(this.expression, this.lookup);\r
+    }\r
+\r
+    @Override\r
+    public void readData(final Resource expression, Map<String, Object> data) {\r
+\r
+        class Auxiliary {\r
+            String equation, lookup;\r
+        }\r
+\r
+        Auxiliary results = null;\r
+\r
+        if (data.get("equation") == null) {\r
+            try {\r
+                results = SimanticsUI.getSession().syncRequest(new Read<Auxiliary>() {\r
+\r
+                    @Override\r
+                    public Auxiliary perform(ReadGraph graph) throws DatabaseException {\r
+                        Auxiliary results = new Auxiliary();\r
+                        SysdynResource sr = SysdynResource.getInstance(graph);\r
+                        if (expression != null && graph.isInstanceOf(expression, sr.WithLookupExpression)) {\r
+                            results.equation = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_expression);\r
+                            results.lookup = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);\r
+                        } else {\r
+                            results.equation = "";\r
+                            results.lookup = "";\r
+                        }\r
+                        return results;\r
+                    }\r
+                });\r
+            } catch (DatabaseException e1) {\r
+                e1.printStackTrace();\r
+            }\r
+            data.put("equation", results.equation == null ? "" : results.equation);\r
+            data.put("lookup", results.lookup == null ? "" : results.lookup);\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public void replaceSelection(String var) {\r
+        if(lastSelectedText != null) {\r
+            IDocument doc = lastSelectedText.getDocument();\r
+            try {\r
+                Point selection = lastSelectedText.getSelection();\r
+                doc.replace(selection.x, selection.y, var);\r
+                lastSelectedText.setSelection(selection.x + var.length());\r
+            } catch (BadLocationException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }        \r
+    }\r
+\r
+    @Override\r
+    public void save(final Resource expression, Map<String, Object> data) {\r
+        final String currentExpression = this.expression.getExpression();\r
+        final String currentLookupTable = lookup.getExpression();\r
+        String oldExpression = (String)data.get("equation");\r
+        String oldLookupTable = (String)data.get("lookup");\r
+\r
+        if(oldExpression == null || oldLookupTable == null ||\r
+                (currentExpression != null && currentLookupTable != null\r
+                && (!currentExpression.equals(oldExpression) || \r
+                        !currentLookupTable.equals(oldLookupTable)))) {\r
+            data.putAll(data);\r
+            data.put("equation", currentExpression);\r
+            data.put("lookup", currentLookupTable);\r
+            SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                @Override\r
+                public void perform(WriteGraph g)\r
+                        throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(g);\r
+                    Layer0 l0 = Layer0.getInstance(g);\r
+\r
+                    if(!g.isInstanceOf(expr, sr.WithLookupExpression)) {\r
+\r
+\r
+                        final Resource newExpression = GraphUtils.create2(g, sr.WithLookupExpression,\r
+                                sr.WithLookupExpression_minX, 0.0,\r
+                                sr.WithLookupExpression_maxX, 10.0,\r
+                                sr.WithLookupExpression_minY, 0.0,\r
+                                sr.WithLookupExpression_maxY, 10.0);\r
+                        String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);\r
+                        if(arrayRange != null)\r
+                            g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);\r
+\r
+                        final Resource variable = g.getSingleObject(expression, l0.PartOf);\r
+                        Resource expressions = g.getPossibleObject(variable, sr.Variable_expressionList);\r
+                        Resource node = ListUtils.getNode(g, expressions, expression);\r
+                        g.deny(node, l0.List_Element);\r
+                        g.claim(node, l0.List_Element, newExpression);\r
+\r
+                        g.deny(expression, l0.PartOf);\r
+                        g.claim(newExpression, l0.PartOf, variable);\r
+\r
+                        VirtualGraph runtime = g.getService(VirtualGraph.class);\r
+                        g.syncRequest(new WriteRequest(runtime) {\r
+                            @Override\r
+                            public void perform(WriteGraph graph) throws DatabaseException {\r
+                                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
+                                    graph.deny(variable, sr.IndependentVariable_activeExpression);\r
+                                graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);\r
+                            }\r
+                        }\r
+                                );\r
+                        expr = newExpression;\r
+\r
+                    }\r
+                    g.claimLiteral(expr, sr.WithLookupExpression_expression, currentExpression);\r
+                    g.claimLiteral(expr, sr.WithLookupExpression_lookup, currentLookupTable);\r
+                    \r
+                    g.markUndoPoint();\r
+                               CommentMetadata cm = g.getMetadata(CommentMetadata.class);\r
+                               g.addMetadata(cm.add("Set lookup expression"));\r
+                    \r
+                }\r
+            });\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public void updateData(Map<String, Object> data) {\r
+        if(this.expression != null && this.expression.getExpression() != null)\r
+            data.put("equation", this.expression.getExpression());\r
+        if(this.lookup != null && this.lookup.getExpression() != null)\r
+            data.put("lookup", this.lookup.getExpression());   \r
+    }\r
+\r
+    @Override\r
+    public void addKeyListener(KeyListener listener) {\r
+        this.expression.getSourceViewer().getTextWidget().addKeyListener(listener);\r
+        this.lookup.getSourceViewer().getTextWidget().addKeyListener(listener);\r
+    }\r
+\r
+    @Override\r
+    public void addVerifyKeyListener(VerifyKeyListener listener) {\r
+        this.expression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
+        this.lookup.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
+    }\r
+\r
+    @Override\r
+    public void addModifyListener(ModifyListener listener) {\r
+        this.expression.getSourceViewer().getTextWidget().addModifyListener(listener);\r
+        this.lookup.getSourceViewer().getTextWidget().addModifyListener(listener);\r
+    }\r
+\r
+    @Override\r
+    public void addFocusListener(FocusListener listener) {\r
+        this.expression.getSourceViewer().getTextWidget().addFocusListener(listener);\r
+        this.lookup.getSourceViewer().getTextWidget().addFocusListener(listener);\r
+    }\r
+\r
+    private void createChart(Composite composite, final Map<String, Object> data) {\r
+        GridLayoutFactory.fillDefaults().applyTo(composite);\r
+        GridDataFactory.fillDefaults().span(1, 2).hint(150, SWT.DEFAULT).applyTo(composite);\r
+        final Composite chartComposite = new Composite(composite, \r
+                SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(chartComposite);\r
+        smallFrame = SWT_AWT.new_Frame(chartComposite);\r
+\r
+        XYDataset dataset = new XYSeriesCollection(new XYSeries("Lookup Table"));\r
+        JFreeChart chart = createChart(dataset);\r
+        smallPanel = new ChartPanel(chart);\r
+        smallFrame.add(smallPanel);\r
+\r
+    }\r
+\r
+    private static JFreeChart createChart(XYDataset dataset) {\r
+        JFreeChart chart = ChartFactory.createXYLineChart(\r
+                null,\r
+                null,\r
+                null,\r
+                dataset,\r
+                PlotOrientation.VERTICAL,\r
+                true,\r
+                true,\r
+                false\r
+                );\r
+        chart.removeLegend();\r
+        chart.getXYPlot().getDomainAxis().setTickLabelsVisible(true);\r
+        chart.getXYPlot().getDomainAxis().setAxisLineVisible(false);\r
+        chart.getXYPlot().getDomainAxis().setTickMarksVisible(true);\r
+        chart.getXYPlot().getRangeAxis().setTickLabelsVisible(true);\r
+        chart.getXYPlot().getRangeAxis().setAxisLineVisible(false);\r
+        chart.getXYPlot().getRangeAxis().setTickMarksVisible(true);\r
+        chart.getXYPlot().getRenderer().setSeriesStroke(0, new BasicStroke(3.0f));\r
+        return chart;\r
+    }\r
+\r
+    private void updateChart() {\r
+        ArrayList<Point2D> dataPoints = new ArrayList<Point2D>();\r
+        TableParser parser = new TableParser(new StringReader(""));\r
+        parser.ReInit(new StringReader(lookup.getExpression()));\r
+        try {\r
+            parser.table();\r
+            ArrayList<Token> xTokens = parser.getXTokens();\r
+            ArrayList<Token> yTokens = parser.getYTokens();\r
+            for(int i = 0; i < xTokens.size(); i++) {\r
+                dataPoints.add(new Point2D.Double(\r
+                        Double.parseDouble(xTokens.get(i).image), \r
+                        Double.parseDouble(yTokens.get(i).image)));\r
+            }\r
+        } catch (ParseException e1) {\r
+            if(lookup.getExpression().matches("[a-zA-Z0-9]*\\([a-zA-Z0-9:]*\\)")) {\r
+                // Might be a sheet reference\r
+                try {\r
+                    final String name = lookup.getExpression().substring(0, lookup.getExpression().indexOf("("));\r
+                    final String range = lookup.getExpression().substring(lookup.getExpression().indexOf("(") + 1, lookup.getExpression().indexOf(")"));\r
+                    String possibleTable = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                        @Override\r
+                        public String perform(ReadGraph graph) throws DatabaseException {\r
+                            Variable variable = input.variable;\r
+                            Resource model = Variables.getModel(graph, variable);\r
+                            return SheetUtils.getStringRepresentation(graph, model, name, range);\r
+                        }\r
+\r
+                    });\r
+                    \r
+\r
+                    try {\r
+                        if(possibleTable == null) {\r
+                            ParseException e = new ParseException(e1.getMessage());\r
+                            e.currentToken = e1.currentToken;\r
+                            throw e;\r
+                        }\r
+                            \r
+                        parser.ReInit(new StringReader(possibleTable));\r
+                        parser.table();\r
+                        ArrayList<Token> xTokens = parser.getXTokens();\r
+                        ArrayList<Token> yTokens = parser.getYTokens();\r
+                        for(int i = 0; i < xTokens.size(); i++) {\r
+                            dataPoints.add(new Point2D.Double(\r
+                                    Double.parseDouble(xTokens.get(i).image), \r
+                                    Double.parseDouble(yTokens.get(i).image)));\r
+                        }\r
+                    } catch (ParseException e2) {\r
+                        this.lookup.setSyntaxError(new SyntaxError(e2.currentToken, "Syntax Error"));\r
+                        System.out.println("MESSAGE: " + e2.getMessage());\r
+                        return;\r
+                    }\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                }\r
+            }\r
+        }\r
+\r
+        XYSeries series = new XYSeries("Lookup Table");\r
+        for(Point2D point : dataPoints) {\r
+            series.add(point.getX(), point.getY());\r
+        }\r
+        XYSeriesCollection dataset =  new XYSeriesCollection(series);\r
+        smallPanel.getChart().getXYPlot().setDataset(dataset);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileImager.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileImager.java
new file mode 100644 (file)
index 0000000..9af9a0d
--- /dev/null
@@ -0,0 +1,28 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.externalFiles;\r
+\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.simantics.browsing.ui.swt.ImagerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public class ExternalFileImager extends ImagerContributor<ExternalFileNode> {\r
+\r
+       @Override\r
+       public ImageDescriptor getDescriptor(ReadGraph graph, ExternalFileNode input)\r
+                       throws DatabaseException {\r
+               return null;\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileLabeler.java
new file mode 100644 (file)
index 0000000..ee94d5a
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.externalFiles;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.labeler.LabelerContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public class ExternalFileLabeler extends LabelerContributorImpl<ExternalFileNode>{\r
+\r
+       @Override\r
+       public String getLabel(ReadGraph graph, ExternalFileNode input)\r
+                       throws DatabaseException {\r
+               return NameUtils.getSafeName(graph, input.data);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileNode.java
new file mode 100644 (file)
index 0000000..1150817
--- /dev/null
@@ -0,0 +1,77 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.externalFiles;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.request.Write;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ExternalFileNode extends AbstractNode<Resource> implements IModifiableNode, IDeletableNode {\r
+\r
+       public ExternalFileNode(Resource data) {\r
+               super(data);\r
+       }\r
+\r
+       @Override\r
+       public Modifier getModifier(String columnId) {\r
+               try {\r
+                       final Resource hasName = Layer0.getInstance(SimanticsUI.getSession()).HasName;\r
+                       LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data, hasName) {\r
+                               @Override\r
+                               public String isValid(String label) {\r
+                                       if (label.isEmpty())\r
+                                               return "Empty label not allowed";\r
+                                       if (label.contains(" "))\r
+                                               return "Spaces are not allowed";\r
+                                       return null;\r
+                               }\r
+\r
+                               @Override\r
+                               protected Write getWriteRequest(final String label) {\r
+                                       return new WriteRequest() {\r
+                                               @Override\r
+                                               public void perform(WriteGraph g) throws DatabaseException {\r
+                                                       g.claimLiteral(data, hasName, label);\r
+                                               }\r
+                                       };\r
+                               }\r
+                       };\r
+                       return modifier;\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public void delete() throws DeleteException {\r
+               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               RemoverUtil.remove(graph, data);\r
+                       }\r
+               });\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFiles.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFiles.java
new file mode 100644 (file)
index 0000000..59ad535
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.externalFiles;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.viewpoint.ViewpointContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ExternalFiles extends ViewpointContributorImpl<Resource> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, Resource input)\r
+                       throws DatabaseException {\r
+               \r
+               if(input == null) \r
+                       return null;\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               \r
+               ArrayList<ExternalFileNode> result = new ArrayList<ExternalFileNode>();\r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(input, l0.ConsistsOf, sr.ExternalFunctionFile))) {\r
+                       result.add(new ExternalFileNode(r));\r
+               }\r
+               \r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "External Files";\r
+       }\r
+       \r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ComboStringPropertyModifier.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ComboStringPropertyModifier.java
new file mode 100644 (file)
index 0000000..a029acd
--- /dev/null
@@ -0,0 +1,70 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.widgets.Combo;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.utils.ReflectionUtils;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+abstract public class ComboStringPropertyModifier<T> implements TextModifyListener, Widget {\r
+\r
+       private ISessionContext context;\r
+       private Object lastInput = null;\r
+       \r
+    final private Class<?> clazz;\r
+       \r
+       public ComboStringPropertyModifier() {\r
+        clazz = ReflectionUtils.getSingleParameterType(getClass());\r
+       }\r
+       \r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               this.context = context;\r
+               lastInput = input;\r
+       }\r
+\r
+       @Override\r
+       public void modifyText(TrackedModifyEvent e) {\r
+               Combo text = (Combo)e.getWidget();\r
+               final String textValue = text.getText();\r
+               final Object input = lastInput;\r
+               \r
+               try {\r
+                       context.getSession().syncRequest(new WriteRequest() {\r
+\r
+                               @SuppressWarnings("unchecked")\r
+                @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+\r
+                                       T single = (T) ISelectionUtils.filterSingleSelection((ISelection)input, clazz);\r
+                                       applyText(graph, single, textValue);\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               \r
+       }\r
+       \r
+       abstract public void applyText(WriteGraph graph, T input, String text) throws DatabaseException;\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/DoublePropertyFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/DoublePropertyFactory.java
new file mode 100644 (file)
index 0000000..1cc23fe
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.utils.datastructures.Triple;\r
+\r
+public class DoublePropertyFactory extends ReadFactoryImpl<Resource, String> {\r
+\r
+    final private String propertyURI;\r
+    \r
+    public DoublePropertyFactory(String propertyURI) {\r
+        this.propertyURI = propertyURI;\r
+    }\r
+\r
+    @Override\r
+    public Object getIdentity(Object inputContents) {\r
+        return new Triple<Resource, String, Object>((Resource)inputContents, propertyURI, getClass());\r
+    }\r
+    \r
+    @Override\r
+    public String perform(ReadGraph graph, Resource issue) throws DatabaseException {\r
+        \r
+        Double value = graph.getPossibleRelatedValue(issue, graph.getResource(propertyURI));\r
+        if (value != null)\r
+            return value.toString();\r
+        else\r
+            return "";\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/DoublePropertyModifier.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/DoublePropertyModifier.java
new file mode 100644 (file)
index 0000000..58dc654
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+\r
+public class DoublePropertyModifier extends TextModifyListenerImpl<Resource> {\r
+\r
+    final private String propertyURI;\r
+    \r
+    public DoublePropertyModifier(ISessionContext context, String propertyURI) {\r
+        this.propertyURI = propertyURI;\r
+    }\r
+\r
+    @Override\r
+    public void applyText(WriteGraph graph, Resource input, String text) throws DatabaseException {\r
+       if (text == null || text.equals("")) {\r
+               if(graph.hasStatement(input, graph.getResource(propertyURI)))\r
+                       graph.deny(input, graph.getResource(propertyURI));\r
+       } else {\r
+               graph.claimLiteral(input, graph.getResource(propertyURI), Double.parseDouble(text), Bindings.DOUBLE);\r
+       }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/FunctionLibraryNameInputValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/FunctionLibraryNameInputValidator.java
new file mode 100644 (file)
index 0000000..18c1a41
--- /dev/null
@@ -0,0 +1,52 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.eclipse.jface.dialogs.IInputValidator;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.ui.utils.FunctionLibraryNameValidator;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Name validator container for user defined function libraries.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class FunctionLibraryNameInputValidator implements IInputValidator, Widget {\r
+\r
+    private Resource lastInput = null;\r
+    \r
+    public FunctionLibraryNameInputValidator(WidgetSupport support) {\r
+        support.register(this);\r
+    }\r
+    \r
+    /**\r
+     * Checks that the syntax of the given name is valid and there \r
+     * are no other components that have the same name in the configuration.\r
+     */\r
+    @Override\r
+    public String isValid(final String newText) {\r
+        if (!new FunctionLibraryNameValidator().isValid(lastInput, newText))\r
+            return "Not valid";\r
+        else\r
+            return null;\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        lastInput = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/FunctionNameInputValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/FunctionNameInputValidator.java
new file mode 100644 (file)
index 0000000..a5cce2b
--- /dev/null
@@ -0,0 +1,52 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.eclipse.jface.dialogs.IInputValidator;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.ui.utils.FunctionNameValidator;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Name validator container for user defined functions.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class FunctionNameInputValidator implements IInputValidator, Widget {\r
+\r
+    private Resource lastInput = null;\r
+    \r
+    public FunctionNameInputValidator(WidgetSupport support) {\r
+        support.register(this);\r
+    }\r
+    \r
+    /**\r
+     * Checks that the syntax of the given name is valid and there \r
+     * are no other components that have the same name in the configuration.\r
+     */\r
+    @Override\r
+    public String isValid(final String newText) {\r
+        if (!new FunctionNameValidator().isValid(lastInput, newText))\r
+            return "Not valid";\r
+        else\r
+            return null;\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        lastInput = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/IntegerPropertyFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/IntegerPropertyFactory.java
new file mode 100644 (file)
index 0000000..d362956
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.utils.datastructures.Triple;\r
+\r
+public class IntegerPropertyFactory extends ReadFactoryImpl<Resource, String> {\r
+\r
+    final private String propertyURI;\r
+    \r
+    public IntegerPropertyFactory(String propertyURI) {\r
+        this.propertyURI = propertyURI;\r
+    }\r
+\r
+    @Override\r
+    public Object getIdentity(Object inputContents) {\r
+        return new Triple<Resource, String, Object>((Resource)inputContents, propertyURI, getClass());\r
+    }\r
+    \r
+    @Override\r
+    public String perform(ReadGraph graph, Resource issue) throws DatabaseException {\r
+        \r
+        Integer value = graph.getPossibleRelatedValue(issue, graph.getResource(propertyURI));\r
+        if (value != null)\r
+            return value.toString();\r
+        else\r
+            return "";\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/IntegerPropertyModifier.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/IntegerPropertyModifier.java
new file mode 100644 (file)
index 0000000..fb61240
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+\r
+public class IntegerPropertyModifier extends TextModifyListenerImpl<Resource> {\r
+\r
+    final private String propertyURI;\r
+    \r
+    public IntegerPropertyModifier(ISessionContext context, String propertyURI) {\r
+        this.propertyURI = propertyURI;\r
+    }\r
+\r
+    @Override\r
+    public void applyText(WriteGraph graph, Resource input, String text) throws DatabaseException {\r
+       if (text == null || text.equals("")) {\r
+               if(graph.hasStatement(input, graph.getResource(propertyURI)))\r
+                       graph.deny(input, graph.getResource(propertyURI));\r
+       } else {\r
+               graph.claimLiteral(input, graph.getResource(propertyURI), Integer.parseInt(text), Bindings.INTEGER);\r
+       }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ModelNameInputValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ModelNameInputValidator.java
new file mode 100644 (file)
index 0000000..625e955
--- /dev/null
@@ -0,0 +1,52 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.eclipse.jface.dialogs.IInputValidator;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.ui.utils.ModelNameValidator;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Name validator container for model.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ModelNameInputValidator implements IInputValidator, Widget {\r
+\r
+    private Resource lastInput = null;\r
+    \r
+    public ModelNameInputValidator(WidgetSupport support) {\r
+        support.register(this);\r
+    }\r
+    \r
+    /**\r
+     * Checks that the syntax of the given name is valid and there \r
+     * are no other components that have the same name in the configuration.\r
+     */\r
+    @Override\r
+    public String isValid(final String newText) {\r
+        if (!new ModelNameValidator().isValid(lastInput, newText))\r
+            return "Not valid";\r
+        else\r
+            return null;\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        lastInput = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ModuleTypeNameInputValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/ModuleTypeNameInputValidator.java
new file mode 100644 (file)
index 0000000..1340525
--- /dev/null
@@ -0,0 +1,52 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.eclipse.jface.dialogs.IInputValidator;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.ui.utils.ModuleTypeNameValidator;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Name validator container for module types.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ModuleTypeNameInputValidator implements IInputValidator, Widget {\r
+\r
+    private Resource lastInput = null;\r
+    \r
+    public ModuleTypeNameInputValidator(WidgetSupport support) {\r
+        support.register(this);\r
+    }\r
+    \r
+    /**\r
+     * Checks that the syntax of the given name is valid and there \r
+     * are no other components that have the same name in the configuration.\r
+     */\r
+    @Override\r
+    public String isValid(final String newText) {\r
+        if (!new ModuleTypeNameValidator().isValid(lastInput, newText))\r
+            return "Not valid";\r
+        else\r
+            return null;\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        lastInput = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/VariableNameInputValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/VariableNameInputValidator.java
new file mode 100644 (file)
index 0000000..3a6af0c
--- /dev/null
@@ -0,0 +1,53 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.eclipse.jface.dialogs.IInputValidator;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Name validator container for module types.\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class VariableNameInputValidator implements IInputValidator, Widget {\r
+\r
+       private Resource lastInput = null;\r
+       \r
+       public VariableNameInputValidator(WidgetSupport support) {\r
+               support.register(this);\r
+       }\r
+       \r
+       /**\r
+        * Checks that the syntax of the given name is valid and there \r
+        * are no other components that have the same name in the configuration.\r
+        */\r
+       @Override\r
+       public String isValid(final String newText) {\r
+           if (!new VariableNameValidator().isValid(lastInput, newText, true))\r
+               return "Not valid";\r
+        else\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               lastInput = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/VariableNamePropertyModifier.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/factories/VariableNamePropertyModifier.java
new file mode 100644 (file)
index 0000000..297b12b
--- /dev/null
@@ -0,0 +1,46 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.factories;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
+\r
+public class VariableNamePropertyModifier extends TextModifyListenerImpl<Resource> {\r
+\r
+       final private String propertyURI;\r
+\r
+       public VariableNamePropertyModifier(ISessionContext context, String propertyURI) {\r
+               this.propertyURI = propertyURI;\r
+       }\r
+\r
+       /**\r
+        * Overrides the original applyText. Renames variables also in equations in the same configuration.\r
+        */\r
+       @Override\r
+       public void applyText(WriteGraph graph, Resource variable, String text) throws DatabaseException {\r
+               \r
+               // TODO: separate possible array indexes\r
+               \r
+               // TODO: add enumerations to the variable\r
+           Layer0 L0 = Layer0.getInstance(graph);\r
+               String originalName = graph.getRelatedValue(variable, L0.HasName);\r
+        Resource configuration = graph.getPossibleObject(variable, L0.PartOf);\r
+        new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, text);\r
+               graph.claimLiteral(variable, graph.getResource(propertyURI), text, Bindings.STRING);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/FunctionCodeWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/FunctionCodeWidget.java
new file mode 100644 (file)
index 0000000..696f481
--- /dev/null
@@ -0,0 +1,334 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.functions;\r
+\r
+import java.awt.event.ActionEvent;\r
+import java.awt.event.ActionListener;\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+\r
+import javax.swing.Timer;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.StyledText;\r
+import org.eclipse.swt.custom.VerifyKeyListener;\r
+import org.eclipse.swt.events.FocusAdapter;\r
+import org.eclipse.swt.events.FocusEvent;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.VerifyEvent;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Listener;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelParser.ModelParser;\r
+import org.simantics.sysdyn.modelParser.ModelParser.Parameter;\r
+import org.simantics.sysdyn.modelParser.ParseException;\r
+import org.simantics.sysdyn.modelParser.Token;\r
+import org.simantics.sysdyn.modelParser.TokenMgrError;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;\r
+import org.simantics.sysdyn.ui.utils.SyntaxError;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class FunctionCodeWidget implements Widget {\r
+       \r
+       private ExpressionField modelicaCode;\r
+       private Resource function;\r
+       \r
+    private Timer updateChartTimer;\r
+    private static int VALIDATION_DELAY_TIME = 500;\r
+       \r
+    private ArrayList<Parameter> inputs;\r
+    private ArrayList<Parameter> outputs;\r
+    \r
+       public FunctionCodeWidget(Composite parent, WidgetSupport support, int style) {\r
+               support.register(this);\r
+        modelicaCode = new ExpressionField(parent, SWT.BORDER, null, false, null);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(modelicaCode);\r
+        \r
+\r
+        // Support shift+enter for line change\r
+        modelicaCode.getSourceViewer().getTextWidget().addVerifyKeyListener(new VerifyKeyListener() {\r
+\r
+               @Override\r
+               public void verifyKey(VerifyEvent event) {\r
+                       if(event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR) {\r
+                               if((event.stateMask & SWT.SHIFT) == 0) {\r
+                                       event.doit = false;\r
+                                       Listener[] listeners = modelicaCode.getSourceViewer().getTextWidget().getListeners(SWT.FocusOut);\r
+                                       for(Listener l : listeners) {\r
+                                               modelicaCode.getSourceViewer().getTextWidget().removeListener(SWT.FocusOut, l);\r
+                                       }\r
+                                       ((StyledText)event.widget).getParent().forceFocus();\r
+                                       save();\r
+                                       for(Listener l : listeners) {\r
+                                               modelicaCode.getSourceViewer().getTextWidget().addListener(SWT.FocusOut, l);\r
+                                       }\r
+                               \r
+                               }\r
+                       }\r
+               }\r
+        });\r
+        \r
+        \r
+        modelicaCode.getSourceViewer().getTextWidget().addModifyListener(new ModifyListener() {\r
+\r
+                       @Override\r
+                       public void modifyText(ModifyEvent e) {\r
+                               validateFieldsTimed();\r
+                       }\r
+               });\r
+        \r
+        modelicaCode.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
+                       @Override\r
+                       public void focusLost(FocusEvent e) {\r
+                               save();\r
+                       }\r
+               });\r
+               \r
+        \r
+        updateChartTimer = new Timer(VALIDATION_DELAY_TIME, new ActionListener() {\r
+\r
+            @Override\r
+            public void actionPerformed(ActionEvent e) {\r
+               if(modelicaCode == null || modelicaCode.isDisposed())\r
+                       return;\r
+               modelicaCode.getDisplay().asyncExec(new Runnable() {\r
+                               \r
+                               @Override\r
+                               public void run() {\r
+                                       validate();\r
+                               }\r
+                       });\r
+            }\r
+        });\r
+        updateChartTimer.setRepeats(false);\r
+       }\r
+\r
+       @Override\r
+       public void setInput(ISessionContext context, Object input) {\r
+               function = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+               \r
+               try {\r
+                       String code = context.getSession().syncRequest(new Read<String>() {\r
+\r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       String code = graph.getPossibleRelatedValue(\r
+                                                       function, SysdynResource.getInstance(graph).SysdynModelicaFunction_modelicaFunctionCode);\r
+                                       if (code == null) {\r
+                                           code = graph.getPossibleRelatedValue(\r
+                                                   function, SysdynResource.getInstance(graph).SysdynModelicaFunction_modelicaFunctionInterface);\r
+                                           if (code == null) {\r
+                               code = new String("");\r
+                           }\r
+                                       }\r
+                                       return code;\r
+                               }\r
+                               \r
+                       });\r
+                       if(code != null) {\r
+                               modelicaCode.setExpression(code);\r
+                               validate();\r
+                       }\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+       \r
+       \r
+    public void validateFieldsTimed() {        \r
+       validateFieldsTimed(VALIDATION_DELAY_TIME);\r
+    }\r
+    \r
+    public void validateFieldsTimed(int delay) {\r
+       updateChartTimer.setDelay(delay);\r
+        if(!updateChartTimer.isRunning())\r
+            updateChartTimer.start();\r
+        else\r
+            updateChartTimer.restart();\r
+    }\r
+    \r
+    public void validate() {\r
+       modelicaCode.resetAnnotations();\r
+       String code = modelicaCode.getExpression();\r
+       StringReader sr = new StringReader(code);\r
+       ModelParser modelParser = new ModelParser(sr);\r
+       \r
+       try {\r
+                       modelParser.parse_composition();\r
+                       \r
+                       inputs = modelParser.getInputs();\r
+                   outputs = modelParser.getOutputs();\r
+\r
+               } catch (ParseException e1) {\r
+                       Token token = e1.currentToken;\r
+                       modelicaCode.setSyntaxError(new SyntaxError(token.image, "Syntax error", token.beginLine, token.beginColumn, token.endLine, token.endColumn));\r
+               } catch (TokenMgrError err) {\r
+                       String message = err.getMessage();\r
+                       String line = message.substring(0, message.indexOf(","));\r
+                       line = line.substring(line.lastIndexOf(" ") + 1);\r
+                       String column = message.substring(message.indexOf(",") + 1, message.indexOf("."));\r
+                       column = column.substring(column.lastIndexOf(" ") + 1);\r
+                       try {\r
+                               Integer endLine = Integer.parseInt(line);\r
+                               Integer endColumn = Integer.parseInt(column);\r
+                               Token token = modelParser.token;\r
+                               modelicaCode.setSyntaxError(new SyntaxError(token.image, "Syntax error", token.endLine, token.endColumn, endLine, endColumn));\r
+                       } catch (NumberFormatException e) {\r
+                               \r
+                       }\r
+                       \r
+               }\r
+       }\r
+    \r
+    private void save() {\r
+       final String code = modelicaCode.getExpression();\r
+       \r
+       // Update input and output lists.\r
+       validate();\r
+       \r
+       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+            \r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                // Remove the existing input list\r
+                removeInputList(graph);\r
+                // Create the new input list\r
+                createInputList(graph);\r
+\r
+                // Remove the existing output list\r
+                removeOutputList(graph);\r
+                // Create the new output list\r
+                createOutputList(graph);\r
+                \r
+                // Update the function code\r
+                graph.claimLiteral(\r
+                        function, \r
+                        sr.SysdynModelicaFunction_modelicaFunctionCode, \r
+                        code);\r
+            }\r
+            \r
+           private void removeInputList(WriteGraph graph) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                \r
+                Resource oldInputList = graph.getPossibleObject(function, sr.SysdynModelicaFunction_inputs);\r
+                if (oldInputList != null) {\r
+                    // Find all the inputs \r
+                    for (Resource input : ListUtils.toList(graph, oldInputList)) {\r
+                        // Check if we have a variable length input\r
+                        if (graph.isInstanceOf(input, sr.SysdynModelicaFunction_VariableLengthInput)) {\r
+                            // The variable length inputs are found here\r
+                            Resource variableLengthInputLabels = graph.getPossibleObject(input, sr.SysdynModelicaFunction_VariableLengthInput_shownLabels);\r
+                            if (variableLengthInputLabels != null) {\r
+                                // Find labels (strings)\r
+                                for (Resource label : ListUtils.toList(graph, variableLengthInputLabels)) {\r
+                                    //Remove string\r
+                                    RemoverUtil.remove(graph, label);\r
+                                }\r
+                                // Remove list\r
+                                RemoverUtil.remove(graph, variableLengthInputLabels);\r
+                            }\r
+                        }                       \r
+                        // Remove the input\r
+                        RemoverUtil.remove(graph, input);\r
+                    }\r
+                    // Remove the list\r
+                    RemoverUtil.remove(graph, oldInputList);\r
+                }\r
+           }\r
+           \r
+           private void createInputList(WriteGraph graph) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                \r
+                ArrayList<Resource> inputResources = new ArrayList<Resource>();\r
+                // Create inputs\r
+                if (inputs != null) {\r
+                    for (Parameter input : inputs) {\r
+                        Resource r = GraphUtils.create2(graph, sr.SysdynModelicaFunction_Input,\r
+                                l0.HasName, input.name, \r
+                                sr.Variable_type, input.type,\r
+                                sr.SysdynModelicaFunction_optional, input.optional ? l0.True : l0.False);\r
+                        if (input.description != null) {\r
+                            // Description is optional\r
+                            graph.claimLiteral(r, sr.SysdynModelicaFunction_definition, input.description);\r
+                        }\r
+                        inputResources.add(r);\r
+                    }\r
+                    graph.claim(\r
+                            function, \r
+                            sr.SysdynModelicaFunction_inputs, \r
+                            ListUtils.create(graph, inputResources));\r
+                }\r
+           }\r
+           \r
+           private void removeOutputList(WriteGraph graph) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                Resource oldOutputList = graph.getPossibleObject(function, sr.SysdynModelicaFunction_outputs);\r
+                if (oldOutputList != null) {\r
+                    // Find all the outputs \r
+                    for (Resource output : ListUtils.toList(graph, oldOutputList)) {\r
+                        // Remove the output\r
+                        RemoverUtil.remove(graph, output);\r
+                    }\r
+                    // Remove the list\r
+                    RemoverUtil.remove(graph, oldOutputList);\r
+                }\r
+           }\r
+                       \r
+           private void createOutputList(WriteGraph graph) throws DatabaseException {\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                ArrayList<Resource> outputResources = new ArrayList<Resource>();\r
+                // Create outputs\r
+                if (outputs != null) {\r
+                    for (Parameter output : outputs) {\r
+                        Resource r = GraphUtils.create2(graph, sr.SysdynModelicaFunction_Output,\r
+                                l0.HasName, output.name, \r
+                                sr.Variable_type, output.type);\r
+                        if (output.description != null) {\r
+                            // Description is optional\r
+                            graph.claimLiteral(r, sr.SysdynModelicaFunction_definition, output.description);\r
+                        }\r
+                        outputResources.add(r);\r
+                    }\r
+                    graph.claim(\r
+                            function, \r
+                            sr.SysdynModelicaFunction_outputs, \r
+                            ListUtils.create(graph, outputResources));\r
+                }\r
+                \r
+           }\r
+\r
+               });\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/SelectedSharedFunctionLibraries.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/SelectedSharedFunctionLibraries.java
new file mode 100644 (file)
index 0000000..255555b
--- /dev/null
@@ -0,0 +1,46 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.functions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;\r
+\r
+public class SelectedSharedFunctionLibraries extends ViewpointContributor<Resource> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, Resource input)\r
+                       throws DatabaseException {\r
+        ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+\r
+        \r
+        for(Resource sharedLibrary : graph.syncRequest(new ObjectsWithType(\r
+                       input, \r
+                       Layer0.getInstance(graph).IsLinkedTo, \r
+                       SysdynResource.getInstance(graph).SharedFunctionOntology)))\r
+        {\r
+               result.add(new SharedFunctionLibraryNode(sharedLibrary));\r
+        }\r
+        \r
+               return result;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/SharedFunctionLibraries.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/SharedFunctionLibraries.java
new file mode 100644 (file)
index 0000000..70dbb6f
--- /dev/null
@@ -0,0 +1,77 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.functions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;\r
+\r
+public class SharedFunctionLibraries extends ViewpointContributor<Resource> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, Resource input)\r
+       throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+\r
+               // Find shared ontologies. graph.getPossibleResource("http://SharedOntologies") does not update if it was null for the first time.\r
+               Resource sharedOntologies = null;\r
+               Resource root = input;\r
+               while(graph.getPossibleObject(root, l0.PartOf) != null)\r
+                       root = graph.getPossibleObject(root, l0.PartOf);\r
+               \r
+               for(Resource r : graph.getObjects(root, l0.ConsistsOf)) {\r
+                       if("SharedOntologies".equals(NameUtils.getSafeName(graph, r))) {\r
+                               sharedOntologies = r;\r
+                               break;\r
+                       }\r
+               }\r
+               \r
+               if(sharedOntologies == null) {\r
+                       return result;\r
+               }\r
+               \r
+               // Find all shared function ontologies. \r
+               // (Don't know why ObjectsWithType works only the first time, then gives nothing) \r
+               ArrayList<Resource> sharedFunctionLibraries = new ArrayList<Resource>();\r
+               for(Resource r : graph.getObjects(sharedOntologies, l0.ConsistsOf)) {\r
+                       if(graph.isInstanceOf(r, sr.SharedFunctionOntology))\r
+                               sharedFunctionLibraries.add(r);\r
+               }\r
+\r
+               // Find all shared function ontologies that have already been selected\r
+               Collection<Resource> selectedSharedFunctionLibraries = graph.syncRequest(new ObjectsWithType(\r
+                               input, l0.IsLinkedTo, sr.SharedFunctionOntology));\r
+\r
+               // Remove all selected ontologies from the shared function ontologies\r
+               sharedFunctionLibraries.removeAll(selectedSharedFunctionLibraries);\r
+\r
+               for(Resource ontology : sharedFunctionLibraries) {\r
+                       result.add(new SharedFunctionLibraryNode(ontology));\r
+               }\r
+\r
+               return result;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/historyDataset/VariableChildRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/historyDataset/VariableChildRule.java
new file mode 100644 (file)
index 0000000..45b2924
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.historyDataset;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.manager.HistoryDatasetUtils;\r
+import org.simantics.sysdyn.ui.properties.HistoryDataTab;\r
+\r
+/**\r
+ * Variable child rule for GE in {@link HistoryDataTab}\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class VariableChildRule implements ChildRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {\r
+        ArrayList<String> result = new ArrayList<String>();\r
+        if(!(parent instanceof Resource))\r
+            return result;\r
+        result.addAll(HistoryDatasetUtils.getVariableNamesInRange(graph, (Resource)parent));\r
+        return result;\r
+\r
+\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getParents(ReadGraph graph, Object child) throws DatabaseException {\r
+        return new ArrayList<Resource>();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/historyDataset/VariableLabelRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/historyDataset/VariableLabelRule.java
new file mode 100644 (file)
index 0000000..0cb9459
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.historyDataset;\r
+\r
+import java.util.Collections;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.labels.LabelRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.properties.HistoryDataTab;\r
+\r
+/**\r
+ * Variable label rule for GE in {@link HistoryDataTab}\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class VariableLabelRule implements LabelRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(String.class);\r
+    }\r
+\r
+    @Override\r
+    public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
+        return Collections.singletonMap(ColumnKeys.SINGLE, (content instanceof String ? (String)content : "No content"));\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleInputEditingSupport.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleInputEditingSupport.java
new file mode 100644 (file)
index 0000000..42a751a
--- /dev/null
@@ -0,0 +1,143 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.viewers.CellEditor;\r
+import org.eclipse.jface.viewers.ComboBoxCellEditor;\r
+import org.eclipse.jface.viewers.EditingSupport;\r
+import org.eclipse.jface.viewers.TableViewer;\r
+import org.eclipse.jface.viewers.TextCellEditor;\r
+import org.eclipse.swt.SWT;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ModuleInputEditingSupport extends EditingSupport {\r
+    private CellEditor editor;\r
+    private int column;\r
+    private HashMap<String, Resource> optionResources;\r
+    private String[] options;\r
+    private TableViewer tableViewer;\r
+\r
+    public ModuleInputEditingSupport(TableViewer viewer, int column) {\r
+        super(viewer);\r
+        this.tableViewer = (TableViewer)viewer;\r
+        this.column = column;\r
+    }\r
+\r
+    @Override\r
+    protected boolean canEdit(Object element) {\r
+        switch (this.column) {\r
+            case 0: return false;\r
+            default: return true;\r
+        }\r
+    }\r
+\r
+    \r
+    @Override\r
+    protected CellEditor getCellEditor(Object element) {\r
+        // Create the correct editor based on the column index\r
+        switch (column) {\r
+            case 0: \r
+                editor = new TextCellEditor(this.tableViewer.getTable());\r
+            case 1:\r
+                ReferenceRow row = (ReferenceRow)element;\r
+                final Resource module = row.getModule();\r
+                final Resource inputVariable = row.getVariable();\r
+\r
+                optionResources = new HashMap<String, Resource>();\r
+                try {\r
+                    optionResources = SimanticsUI.getSession().syncRequest(new Read<HashMap<String, Resource>>() {\r
+\r
+                        @Override\r
+                        public HashMap<String, Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                            SysdynResource sr = SysdynResource.getInstance(graph);\r
+                            HashMap<String, Resource> result = new HashMap<String, Resource>();\r
+                            for(Resource dependency : graph.syncRequest(new ObjectsWithType(module, sr.Variable_isHeadOf, sr.Dependency))) {\r
+                                if(graph.getPossibleObject(dependency, sr.Dependency_refersTo) == null ||\r
+                                        graph.getPossibleObject(dependency, sr.Dependency_refersTo).equals(inputVariable)) {\r
+                                    Resource output = graph.getSingleObject(dependency, sr.Variable_HasTail);\r
+                                    \r
+                                    if(graph.isInstanceOf(output, sr.Shadow)) {\r
+                                        output = graph.getPossibleObject(output, sr.Shadow_original);\r
+                                    }\r
+                                    \r
+                                    if(output != null)\r
+                                        result.put((String)graph.getRelatedValue(output, l0.HasName), dependency);\r
+                                }\r
+                            }\r
+                            return result;\r
+                        }\r
+                    });\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                }\r
+\r
+                options = optionResources.keySet().toArray(new String[optionResources.keySet().size() + 1]);\r
+                options[optionResources.keySet().size()] = "";\r
+                ComboBoxCellEditor ceditor = new ComboBoxCellEditor(this.tableViewer.getTable(), options, SWT.READ_ONLY);\r
+                ceditor.setActivationStyle(1);\r
+                editor = ceditor;\r
+                break;\r
+            default:\r
+                editor = null;\r
+        }\r
+\r
+        return editor;\r
+    }\r
+\r
+    @Override\r
+    protected Object getValue(Object element) {\r
+        ReferenceRow referenceRow = (ReferenceRow) element;\r
+\r
+        switch (this.column) {\r
+            case 0:\r
+                return referenceRow.getName();\r
+            case 1:\r
+                String refersToName = referenceRow.getValue();\r
+                if (refersToName == null) return options.length - 1;\r
+                for(int i = 0; i < options.length ; i++) {\r
+                    if(refersToName.equals(options[i])) return i;\r
+                }\r
+                return options[options.length - 1];\r
+            default:\r
+                break;\r
+        }\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    protected void setValue(Object element, Object value) {\r
+        ReferenceRow referenceRow = (ReferenceRow) element;\r
+        String valueString = String.valueOf(value);\r
+        switch (this.column) {\r
+            case 0:\r
+                break;\r
+            case 1:\r
+                referenceRow.setRefersTo(optionResources.get(options[Integer.parseInt(valueString)]));\r
+                break;\r
+            default:\r
+                break;\r
+        }\r
+\r
+        getViewer().update(element, null);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleOutputEditingSupport.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleOutputEditingSupport.java
new file mode 100644 (file)
index 0000000..4b64f3b
--- /dev/null
@@ -0,0 +1,138 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.viewers.CellEditor;\r
+import org.eclipse.jface.viewers.ComboBoxCellEditor;\r
+import org.eclipse.jface.viewers.EditingSupport;\r
+import org.eclipse.jface.viewers.TableViewer;\r
+import org.eclipse.jface.viewers.TextCellEditor;\r
+import org.eclipse.swt.SWT;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ModuleOutputEditingSupport  extends EditingSupport {\r
+    private CellEditor editor;\r
+    private int column;\r
+    private HashMap<String, Resource> optionResources;\r
+    private String[] options;\r
+    private TableViewer tableViewer;\r
+\r
+    public ModuleOutputEditingSupport(TableViewer viewer, int column) {\r
+        super(viewer);\r
+        this.tableViewer = (TableViewer)viewer;\r
+        this.column = column;\r
+    }\r
+\r
+    @Override\r
+    protected boolean canEdit(Object element) {\r
+        switch (this.column) {\r
+            case 0: return false;\r
+            default: return true;\r
+        }\r
+    }\r
+\r
+    \r
+    @Override\r
+    protected CellEditor getCellEditor(Object element) {\r
+        // Create the correct editor based on the column index\r
+        switch (column) {\r
+            case 0: \r
+                editor = new TextCellEditor(this.tableViewer.getTable());\r
+            case 1:\r
+                ReferenceRow row = (ReferenceRow)element;\r
+                final Resource module = row.getModule();\r
+                final Resource outputVariable = row.getVariable();\r
+\r
+                optionResources = new HashMap<String, Resource>();\r
+                try {\r
+                    optionResources = SimanticsUI.getSession().syncRequest(new Read<HashMap<String, Resource>>() {\r
+\r
+                        @Override\r
+                        public HashMap<String, Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                            SysdynResource sr = SysdynResource.getInstance(graph);\r
+                            HashMap<String, Resource> result = new HashMap<String, Resource>();\r
+                            for(Resource dependency : graph.syncRequest(new ObjectsWithType(module, sr.Variable_isTailOf, sr.Dependency))) {\r
+                                if(graph.getPossibleObject(dependency, sr.Dependency_refersTo) == null \r
+                                               || !graph.hasStatement(graph.getPossibleObject(dependency, sr.Dependency_refersTo), l0.HasName)\r
+                                               || graph.getPossibleObject(dependency, sr.Dependency_refersTo).equals(outputVariable)) {\r
+                                    Resource input = graph.getSingleObject(dependency, sr.Variable_HasHead);\r
+                                    result.put((String)graph.getRelatedValue(input, l0.HasName), dependency);\r
+                                }\r
+                            }\r
+                            return result;\r
+                        }\r
+                    });\r
+                } catch (DatabaseException e) {\r
+                    e.printStackTrace();\r
+                }\r
+\r
+                options = optionResources.keySet().toArray(new String[optionResources.keySet().size() + 1]);\r
+                options[optionResources.keySet().size()] = "";\r
+                ComboBoxCellEditor ceditor = new ComboBoxCellEditor(this.tableViewer.getTable(), options, SWT.READ_ONLY);\r
+                ceditor.setActivationStyle(1);\r
+                editor = ceditor;\r
+                break;\r
+            default:\r
+                editor = null;\r
+        }\r
+\r
+        return editor;\r
+    }\r
+\r
+    @Override\r
+    protected Object getValue(Object element) {\r
+        ReferenceRow referenceRow = (ReferenceRow) element;\r
+\r
+        switch (this.column) {\r
+            case 0:\r
+                return referenceRow.getName();\r
+            case 1:\r
+                String refersToName = referenceRow.getValue();\r
+                if (refersToName == null) return options.length - 1;\r
+                for(int i = 0; i < options.length ; i++) {\r
+                    if(refersToName.equals(options[i])) return i;\r
+                }\r
+                return options[options.length - 1];\r
+            default:\r
+                break;\r
+        }\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    protected void setValue(Object element, Object value) {\r
+        ReferenceRow referenceRow = (ReferenceRow) element;\r
+        String valueString = String.valueOf(value);\r
+        switch (this.column) {\r
+            case 0:\r
+                break;\r
+            case 1:\r
+                referenceRow.setRefersTo(optionResources.get(options[Integer.parseInt(valueString)]));\r
+                break;\r
+            default:\r
+                break;\r
+        }\r
+\r
+        getViewer().update(element, null);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleParameterOverrideUtils.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleParameterOverrideUtils.java
new file mode 100644 (file)
index 0000000..06a9e2b
--- /dev/null
@@ -0,0 +1,102 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+\r
+/**\r
+ * Utilities for module parameter override functionalities\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ModuleParameterOverrideUtils {\r
+\r
+    /**\r
+     * Get the parameter expression of a variable or null, if it does not contain a parameter expression,\r
+     * or there are many parameter expressions\r
+     * @param graph ReadGraph\r
+     * @param variable IndependentVariable\r
+     * @return parameter expression or null\r
+     * @throws DatabaseException\r
+     */\r
+    public static String getParameterExpression(IndependentVariable variable) throws DatabaseException {\r
+        String result = null;\r
+        try {\r
+            result = variable.getExpressions().get(0).getExpression();\r
+        if(result.contains("/* Actual value read from init file */"))\r
+            result = result.substring(0, result.indexOf("/* Actual value read from init file */"));\r
+        } catch (NullPointerException e) {\r
+        }\r
+        return result;\r
+    }\r
+    \r
+    /**\r
+     * Get the expression, or the overriding expression, of a parameter\r
+     * @param graph ReadGraph\r
+     * @param parent Parent resource\r
+     * @param variable IndependentVariable\r
+     * @return Overriding expression, or the default parameter expression, or null\r
+     * @throws DatabaseException\r
+     */\r
+    public static String getParameterExpressionOrOverride(ReadGraph graph, Resource parent, IndependentVariable variable)\r
+            throws DatabaseException {\r
+        String result = null;\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+\r
+        // Get possible override\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(parent, L0.ConsistsOf, sr.Module_ParameterOverride))) {\r
+            Resource overridden = graph.getPossibleObject(r, sr.Module_ParameterOverride_overriddenParameter);\r
+            if(variable.getName().equals(NameUtils.getSafeName(graph, overridden))) {\r
+                result = graph.getPossibleRelatedValue(r, sr.Module_ParameterOverride_overrideExpression);\r
+            }\r
+        }\r
+        \r
+        if(result == null) {\r
+            // Parameter is not overridden, find the actual expression\r
+            result = getParameterExpression(variable);\r
+        }\r
+        return result;\r
+    }\r
+    \r
+    /**\r
+     * Find out if a variable has a single parameter expression \r
+     * @param graph ReadGraph\r
+     * @param variable Variable\r
+     * @return does the variable have a single parameter expression\r
+     * @throws DatabaseException\r
+     */\r
+    public static boolean hasParameterExpression(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        boolean result = false;\r
+        Resource expressionsResource = graph.getPossibleObject(variable, sr.Variable_expressionList);\r
+        if(expressionsResource != null) {\r
+            List<Resource> expressions = ListUtils.toList(graph, expressionsResource);\r
+            if(expressions.size() == 1 && graph.isInstanceOf(expressions.get(0), sr.ParameterExpression)) {\r
+                result = true;\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterChildRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterChildRule.java
new file mode 100644 (file)
index 0000000..5d88453
--- /dev/null
@@ -0,0 +1,77 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Variability;\r
+\r
+public class ParameterChildRule implements ChildRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {\r
+        ArrayList<ParameterNode> result = new ArrayList<ParameterNode>();\r
+        if(!(parent instanceof Resource))\r
+            return result;\r
+        \r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        StructuralResource2 STR = StructuralResource2.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+        Resource moduleInstance = (Resource) parent;\r
+        \r
+        Resource type = graph.getSingleObject(moduleInstance, L0.InstanceOf);\r
+        Resource configuration = graph.getSingleObject(type, STR.IsDefinedBy);\r
+        SysdynModelManager sdm = SysdynModelManager.getInstance(graph.getSession());\r
+        SysdynModel model = sdm.getModel(graph, configuration);\r
+        \r
+        Resource varConfRes = graph.getSingleObject(moduleInstance, L0.PartOf);\r
+        Configuration varConf = sdm.getModel(graph, varConfRes).getConfiguration();\r
+        \r
+        for(Resource variable : graph.syncRequest(new ObjectsWithType(configuration, L0.ConsistsOf, sr.IndependentVariable))) {\r
+            IElement element = model.getElement(variable);\r
+            if(element instanceof IndependentVariable && !(element instanceof Stock)) \r
+                if(!Variability.CONTINUOUS.equals(Variability.getVariability((IndependentVariable)element, false, varConf)))\r
+                    result.add(new ParameterNode(moduleInstance, varConf, variable, (IndependentVariable)element));\r
+        }\r
+        \r
+        return result;\r
+\r
+\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getParents(ReadGraph graph, Object child) throws DatabaseException {\r
+        return new ArrayList<Resource>();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterLabelDecorationRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterLabelDecorationRule.java
new file mode 100644 (file)
index 0000000..993d613
--- /dev/null
@@ -0,0 +1,57 @@
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import org.eclipse.jface.resource.ColorDescriptor;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.simantics.browsing.ui.content.LabelDecorator;\r
+import org.simantics.browsing.ui.model.labeldecorators.LabelDecorationRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+\r
+public class ParameterLabelDecorationRule implements LabelDecorationRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Object.class);\r
+    }\r
+\r
+    @Override\r
+    public LabelDecorator getLabelDecorator(ReadGraph graph, Object content) throws DatabaseException {\r
+        if(content instanceof ParameterNode) {\r
+            ParameterNode node = (ParameterNode) content;\r
+            String notOverriding = ModuleParameterOverrideUtils.getParameterExpression(node.getIndependentVariable());\r
+            String overriding = ModuleParameterOverrideUtils.getParameterExpressionOrOverride(graph, node.getParent(), node.getIndependentVariable());\r
+\r
+            if(notOverriding == null)\r
+                return null;\r
+\r
+            final boolean original = notOverriding.equals(overriding);\r
+\r
+            return new LabelDecorator.Stub() {\r
+                @Override\r
+                public String decorateLabel(String label, String column, int itemIndex) {\r
+                    if(ColumnKeys.VALUE.equals(column)) {\r
+                        return original ? label : label + " [Overridden]";\r
+                    } else {\r
+                        return label;\r
+                    }\r
+                }\r
+\r
+                @SuppressWarnings("unchecked")\r
+                @Override\r
+                public <Color> Color decorateForeground(Color color, String column, int itemIndex) {\r
+                    Color result = null;\r
+                    if(ColumnKeys.VALUE.equals(column)) {\r
+                        if(original)\r
+                            result = (Color) ColorDescriptor.createFrom(new RGB(125,125,125));\r
+                        else\r
+                            result = (Color) ColorDescriptor.createFrom(new RGB(0,0,0));\r
+                    }\r
+                    return result;\r
+                }\r
+            };\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterLabelRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterLabelRule.java
new file mode 100644 (file)
index 0000000..0640bc3
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.model.labels.LabelRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+\r
+public class ParameterLabelRule implements LabelRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Object.class);\r
+    }\r
+\r
+    @Override\r
+    public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
+        Map<String, String> result = new HashMap<String, String>();\r
+\r
+        if(content instanceof ParameterNode) {\r
+            ParameterNode node = (ParameterNode) content;\r
+            String parameterExpression = ModuleParameterOverrideUtils.getParameterExpressionOrOverride(graph, node.getParent(), node.getIndependentVariable());\r
+            String name = node.getIndependentVariable().getName();\r
+\r
+            result.put(ColumnKeys.MODULE_PARAMETER, name);\r
+            result.put(ColumnKeys.VALUE, parameterExpression);\r
+        }\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterModifierRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterModifierRule.java
new file mode 100644 (file)
index 0000000..a964c5b
--- /dev/null
@@ -0,0 +1,113 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.model.modifiers.ModifierRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.Variability;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ParameterModifierRule implements ModifierRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Object.class);\r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(ReadGraph graph, Object content, String columnKey) throws DatabaseException {\r
+        if(content instanceof ParameterNode && ColumnKeys.VALUE.equals(columnKey)) {\r
+            final ParameterNode node = (ParameterNode) content;\r
+            return new Modifier() {\r
+\r
+                @Override\r
+                public String getValue() {\r
+                    Read<String> request =\r
+                            new Read<String>() {\r
+\r
+                        @Override\r
+                        public String perform(ReadGraph graph) throws DatabaseException {\r
+                            String parameterExpression =  ModuleParameterOverrideUtils.getParameterExpressionOrOverride(\r
+                                    graph, \r
+                                    node.getParent(), \r
+                                    node.getIndependentVariable());\r
+\r
+                            return parameterExpression != null ? parameterExpression : "";\r
+                        }\r
+\r
+                    };\r
+                    try {\r
+                        return SimanticsUI.getSession().syncRequest(request);\r
+                    } catch (DatabaseException e) {\r
+                        e.printStackTrace();\r
+                        return "";\r
+                    }\r
+                }\r
+\r
+                @Override\r
+                public String isValid(String label) {\r
+                    if(label.isEmpty())\r
+                        return null;\r
+                    \r
+                    if(Variability.CONTINUOUS.equals(Variability.getVariability(node.getIndependentVariable(), label, false, node.getParentConfiguration()))) \r
+                        return "Not valid";\r
+                    else\r
+                        return null;\r
+                }\r
+\r
+                @Override\r
+                public void modify(final String label) {\r
+                    SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                        @Override\r
+                        public void perform(WriteGraph graph) throws DatabaseException {\r
+                            SysdynResource sr = SysdynResource.getInstance(graph);\r
+                            Layer0 L0 = Layer0.getInstance(graph);\r
+\r
+                            // Remove possible old override\r
+                            for(Resource r : graph.syncRequest(new ObjectsWithType(node.getParent(), L0.ConsistsOf, sr.Module_ParameterOverride))) {\r
+                                if(node.getVariableResource().equals(graph.getPossibleObject(r, sr.Module_ParameterOverride_overriddenParameter))) {\r
+                                    RemoverUtil.remove(graph, r);\r
+                                    break;\r
+                                }\r
+                            }\r
+\r
+                            // Write the new override, if there is one\r
+                            if(label != null && !label.isEmpty()) {\r
+                                GraphUtils.create2(graph, sr.Module_ParameterOverride,\r
+                                        sr.Module_ParameterOverride_overriddenParameter, node.getVariableResource(),\r
+                                        sr.Module_ParameterOverride_overrideExpression, label,\r
+                                        L0.PartOf, node.getParent()\r
+                                        );\r
+                            }\r
+                        }\r
+                    });\r
+                }\r
+\r
+            };\r
+        } else {\r
+            return null;\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterNode.java
new file mode 100644 (file)
index 0000000..49e3586
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+\r
+public class ParameterNode {\r
+    \r
+    private Resource moduleInstance;\r
+    private Resource variableResource;\r
+    private IndependentVariable independentVariable;\r
+    private Configuration parentConfiguration;\r
+    \r
+    public ParameterNode(Resource parent, Configuration parentConfiguration, Resource variableResource, IndependentVariable independentVariable) {\r
+        this.moduleInstance = parent;\r
+        this.variableResource = variableResource;\r
+        this.independentVariable = independentVariable;\r
+        this.parentConfiguration = parentConfiguration;\r
+    }\r
+\r
+    public Resource getParent() {\r
+        return moduleInstance;\r
+    }\r
+\r
+    public Resource getVariableResource() {\r
+        return variableResource;\r
+    }\r
+    \r
+    public IndependentVariable getIndependentVariable() {\r
+        return independentVariable;\r
+    }\r
+    \r
+    public Configuration getParentConfiguration() {\r
+        return parentConfiguration;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterSorter.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterSorter.java
new file mode 100644 (file)
index 0000000..802e193
--- /dev/null
@@ -0,0 +1,47 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.NodeContext;\r
+import org.simantics.browsing.ui.model.browsecontexts.BrowseContext;\r
+import org.simantics.browsing.ui.model.sorters.AbstractSorter;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
+\r
+/**\r
+ * Sorter for sorting module parameters into alphabetic order.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ParameterSorter  extends AbstractSorter<String> {\r
+    \r
+    public static ParameterSorter INSTANCE = new ParameterSorter();\r
+\r
+    @Override\r
+    public String getSortingCriterion(ReadGraph graph, BrowseContext context,\r
+            NodeContext node) throws DatabaseException {\r
+        Map<String,String> labels = context.getLabel(graph, node);\r
+        String label = labels.get(ColumnKeys.MODULE_PARAMETER);\r
+        return label;\r
+    }\r
+\r
+    @Override\r
+    public int compare(String a, String b) {\r
+        return AlphanumComparator.CASE_INSENSITIVE_COMPARATOR.compare(a, b);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterSorterRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterSorterRule.java
new file mode 100644 (file)
index 0000000..20db86b
--- /dev/null
@@ -0,0 +1,37 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import org.simantics.browsing.ui.model.sorters.Sorter;\r
+import org.simantics.browsing.ui.model.sorters.SorterRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+/**\r
+ * SorterRule for sorting module parameters into alphabetic order.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ParameterSorterRule implements SorterRule {    \r
+        \r
+        @Override\r
+        public boolean isCompatible(Class<?> contentType) {\r
+            return true;\r
+        }\r
+\r
+        @Override\r
+        public Sorter getSorter(ReadGraph graph, Object content)\r
+                throws DatabaseException {\r
+            return ParameterSorter.INSTANCE;\r
+        }\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRow.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRow.java
new file mode 100644 (file)
index 0000000..e668512
--- /dev/null
@@ -0,0 +1,118 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ReferenceRow {\r
+\r
+    Resource variable, module, dependency;\r
+    String name;\r
+\r
+    public ReferenceRow(Resource module, Resource dependency, Resource variable) {\r
+        this.module = module;\r
+        this.variable = variable;\r
+        this.dependency = dependency;\r
+    }\r
+\r
+\r
+    public Resource getModule() {\r
+        return this.module;\r
+    }\r
+\r
+    public Resource getVariable() {\r
+        return this.variable;\r
+    }\r
+\r
+    public Resource getDependency() {\r
+        return this.dependency;\r
+    }\r
+\r
+    public String getName() {\r
+        String name = null;\r
+        try {\r
+            name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                @Override\r
+                public String perform(ReadGraph graph) throws DatabaseException {\r
+                    return (String)graph.getRelatedValue(getVariable(), Layer0.getInstance(graph).HasName);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return name;\r
+    }\r
+\r
+    public String getValue() {\r
+        if(dependency == null) return "";\r
+\r
+        String value = null;\r
+        try {\r
+            value = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                @Override\r
+                public String perform(ReadGraph graph) throws DatabaseException {\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    Resource valueResource = graph.getPossibleObject(dependency, sr.Variable_HasTail);\r
+                    if(!graph.isInstanceOf(valueResource, sr.Variable))\r
+                        valueResource = graph.getPossibleObject(dependency, sr.Variable_HasHead);\r
+                    \r
+                    if(graph.isInstanceOf(valueResource, sr.Shadow))\r
+                        valueResource = graph.getPossibleObject(valueResource, sr.Shadow_original);\r
+                    \r
+                    if(valueResource == null || !graph.isInstanceOf(valueResource, sr.Variable))\r
+                        return "";\r
+                    \r
+                    return (String)graph.getRelatedValue(valueResource, l0.HasName, Bindings.STRING);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return value;\r
+    }\r
+\r
+    public void setRefersTo(final Resource dependency) {\r
+        if(dependency != null && dependency.equals(this.dependency)) return;\r
+        SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                if(getDependency() != null && graph.hasStatement(getDependency(), sr.Dependency_refersTo))\r
+                    graph.deny(getDependency(), sr.Dependency_refersTo);\r
+                if(dependency != null && graph.hasStatement(dependency, sr.Dependency_refersTo))\r
+                       graph.deny(dependency, sr.Dependency_refersTo);\r
+                setDependency(null);\r
+                if(dependency != null) {\r
+                    setDependency(dependency);\r
+                    graph.claim(getDependency(), SysdynResource.getInstance(graph).Dependency_refersTo, getVariable());\r
+                }\r
+            }\r
+        });\r
+    }\r
+\r
+    private void setDependency(Resource dependency) {\r
+        this.dependency = dependency;\r
+    }\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRowLabelProvider.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRowLabelProvider.java
new file mode 100644 (file)
index 0000000..763e841
--- /dev/null
@@ -0,0 +1,37 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import org.eclipse.jface.viewers.ITableLabelProvider;\r
+import org.eclipse.jface.viewers.LabelProvider;\r
+import org.eclipse.swt.graphics.Image;\r
+\r
+public class ReferenceRowLabelProvider extends LabelProvider implements ITableLabelProvider {\r
+\r
+    @Override\r
+    public Image getColumnImage(Object element, int columnIndex) {\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public String getColumnText(Object element, int columnIndex) {\r
+        ReferenceRow referenceRow = (ReferenceRow) element;\r
+        switch (columnIndex) {\r
+            case 0:\r
+                return referenceRow.getName();\r
+            case 1:\r
+                return referenceRow.getValue();\r
+            default:\r
+                throw new RuntimeException("Should not happen");\r
+        }\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceTable.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceTable.java
new file mode 100644 (file)
index 0000000..aeb5daf
--- /dev/null
@@ -0,0 +1,132 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import java.util.ArrayList;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.IBaseLabelProvider;\r
+import org.eclipse.jface.viewers.IContentProvider;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.TableViewer;\r
+import org.eclipse.jface.viewers.Viewer;\r
+import org.eclipse.jface.viewers.ViewerComparator;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+public class ReferenceTable implements Widget{\r
+\r
+    private TableViewer tableViewer;\r
+    private RowProvider rowProvider;\r
+\r
+    public static final String FIRSTCOLUMN = "Inputs";\r
+    public static final String SECONDCOLUMN = "Outputs";\r
+    \r
+    public ReferenceTable(Composite parent, WidgetSupport support, int style) {\r
+        support.register(this);\r
+\r
+        Composite base = new Composite(parent, style);\r
+        GridLayoutFactory.fillDefaults().applyTo(base);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(base);\r
+\r
+        Table table = new Table(base, SWT.BORDER|SWT.SINGLE|SWT.FULL_SELECTION);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(table);\r
+        table.setHeaderVisible (true);\r
+        table.setLinesVisible(true);\r
+        table.getVerticalBar().setVisible(true);\r
+\r
+        tableViewer = new TableViewer (table);\r
+        tableViewer.setComparator(new ReferenceRowComparator());\r
+    }\r
+\r
+    public TableViewer getTableViewer() {\r
+        return this.tableViewer;\r
+    }\r
+\r
+    public void setRowProvider(RowProvider rowProvider) {\r
+        this.rowProvider = rowProvider;\r
+    }\r
+    \r
+    public void setContentProvider(IContentProvider provider) {\r
+        tableViewer.setContentProvider(provider);\r
+    }\r
+    \r
+    public void setLabelProvider(IBaseLabelProvider labelProvider) {\r
+        tableViewer.setLabelProvider(labelProvider);\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        final Resource module = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);\r
+        if(this.rowProvider != null) {\r
+            try {\r
+                SimanticsUI.getSession().syncRequest(new Read<ArrayList<ReferenceRow>>() {\r
+\r
+                    @Override\r
+                    public ArrayList<ReferenceRow> perform(ReadGraph graph) throws DatabaseException {\r
+                        return rowProvider.getRows(graph, module);\r
+                    }\r
+                } , new Listener<ArrayList<ReferenceRow>>() {\r
+\r
+                    @Override\r
+                    public boolean isDisposed() {\r
+                        if(tableViewer != null && tableViewer.getTable() != null)\r
+                            return getTableViewer().getTable().isDisposed();\r
+                        else\r
+                            return true;\r
+                    }\r
+\r
+                    @Override\r
+                    public void execute(final ArrayList<ReferenceRow> result) {\r
+                        if(!isDisposed())\r
+                            getTableViewer().getTable().getDisplay().asyncExec(new Runnable() {\r
+                                \r
+                                @Override\r
+                                public void run() {\r
+                                    if(!isDisposed())\r
+                                        getTableViewer().setInput(result);\r
+                                }\r
+                            });\r
+                    }\r
+\r
+                    @Override\r
+                    public void exception(Throwable t) {\r
+                    }\r
+                }\r
+                );\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+    }\r
+\r
+    private class ReferenceRowComparator extends ViewerComparator {\r
+        @Override\r
+        public int compare(Viewer viewer, Object e1, Object e2) {\r
+            ReferenceRow rr1 = (ReferenceRow)e1;\r
+            ReferenceRow rr2 = (ReferenceRow)e2;\r
+            return rr1.getName().compareTo(rr2.getName());\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/RowProvider.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/RowProvider.java
new file mode 100644 (file)
index 0000000..9b424d2
--- /dev/null
@@ -0,0 +1,22 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.modules;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public abstract class RowProvider {    \r
+    public abstract ArrayList<ReferenceRow> getRows(ReadGraph graph, Resource module) throws DatabaseException;\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/DistributionPropertyWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/DistributionPropertyWidget.java
new file mode 100644 (file)
index 0000000..93a62b2
--- /dev/null
@@ -0,0 +1,118 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class DistributionPropertyWidget extends Composite implements Widget {\r
+    \r
+    private IDistributionProperties distributionProperties = null;\r
+    private WidgetSupportImpl distributionSupport = new WidgetSupportImpl();\r
+    private HashMap<String, String> cache = new HashMap<String, String>();\r
+    private Resource oldInput;\r
+\r
+    public DistributionPropertyWidget(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
+        super(parent, style);\r
+        GridLayoutFactory.fillDefaults().applyTo(this);\r
+        support.register(this);\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+\r
+        IDistributionProperties newProperties = null;\r
+        Resource distribution = null;\r
+        try {\r
+            distribution = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                @Override\r
+                public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                    Resource distribution = graph.getPossibleObject(\r
+                            resource, \r
+                            SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_propabilityDistribution\r
+                            );\r
+                    \r
+                    return distribution;\r
+                }\r
+\r
+            });\r
+            \r
+            newProperties = SimanticsUI.getSession().syncRequest(new Read<IDistributionProperties>() {\r
+\r
+                @Override\r
+                public IDistributionProperties perform(ReadGraph graph) throws DatabaseException {\r
+                    Resource distribution = graph.getPossibleObject(\r
+                            resource, \r
+                            SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_propabilityDistribution\r
+                            );\r
+                    \r
+                    return graph.adapt(distribution, IDistributionProperties.class);\r
+                }\r
+\r
+            });\r
+            \r
+            // Create a PropertyComposite for the selected node\r
+            if(newProperties != null) {\r
+\r
+                if(distributionProperties != null)\r
+                    distributionProperties.getCachedValues(cache);\r
+                \r
+                if(oldInput != null && !oldInput.equals(resource))\r
+                    cache.clear();\r
+                \r
+                oldInput = resource;\r
+                \r
+                for(Control child : this.getChildren()) {\r
+                    child.dispose();\r
+                }\r
+                \r
+                newProperties.createContent(this, context, distributionSupport);\r
+                distributionProperties = newProperties;\r
+                \r
+                SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                    \r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        distributionProperties.applyCache(graph, cache);\r
+                        \r
+                    }\r
+                });\r
+                \r
+                distributionSupport.fireInput(context, new StructuredSelection(distribution));\r
+            }\r
+            \r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/IDistributionProperties.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/IDistributionProperties.java
new file mode 100644 (file)
index 0000000..0c628e9
--- /dev/null
@@ -0,0 +1,30 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+\r
+public interface IDistributionProperties {\r
+    \r
+    public Composite createContent(Composite parent, ISessionContext context, WidgetSupport support);\r
+    \r
+    public void getCachedValues(HashMap<String, String> cachedValues);\r
+    \r
+    public void applyCache(WriteGraph graph, HashMap<String, String> cachedValues) throws DatabaseException;\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/IntervalProperties.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/IntervalProperties.java
new file mode 100644 (file)
index 0000000..9f3b7bc
--- /dev/null
@@ -0,0 +1,115 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+\r
+public class IntervalProperties implements IDistributionProperties {\r
+\r
+    private Resource resource;\r
+    private TrackedText minValue; \r
+    private TrackedText maxValue;\r
+    \r
+    public IntervalProperties(Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+    \r
+    @Override\r
+    public Composite createContent(Composite parent, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(parent, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);\r
+        \r
+        // minValue\r
+        Label label = new Label(composite, SWT.NONE);\r
+        label.setText("Min value");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+        \r
+        minValue = new TrackedText(composite, support, SWT.BORDER);\r
+        minValue.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.Interval_minValue));\r
+        minValue.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.Interval_minValue));\r
+        minValue.setInputValidator(new DoubleValidator(false));\r
+        minValue.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), minValue.getWidget())));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(minValue.getWidget());\r
+\r
+        // maxValue\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Max value");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+        \r
+        maxValue = new TrackedText(composite, support, SWT.BORDER);\r
+        maxValue.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.Interval_maxValue));\r
+        maxValue.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.Interval_maxValue));\r
+        maxValue.setInputValidator(new DoubleValidator(false));\r
+        maxValue.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), maxValue.getWidget())));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(maxValue.getWidget());\r
+        \r
+        return composite;\r
+    }\r
+    \r
+\r
+    @Override\r
+    public void getCachedValues(HashMap<String, String> cahcedValues) {\r
+        if(!minValue.isDisposed())\r
+            cahcedValues.put(SensitivityDistributionKeys.MIN, minValue.getText());\r
+        if(!maxValue.isDisposed())\r
+            cahcedValues.put(SensitivityDistributionKeys.MAX, maxValue.getText());\r
+    }\r
+\r
+\r
+\r
+    @Override\r
+    public void applyCache(WriteGraph graph, HashMap<String, String> cachedValues) throws DatabaseException {\r
+        if(resource == null)\r
+            return;\r
+        \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        String min = cachedValues.get(SensitivityDistributionKeys.MIN);\r
+        if(min != null) {\r
+            try {\r
+                Double d = Double.parseDouble(min);\r
+                graph.claimLiteral(resource, SR.Interval_minValue, d, Bindings.DOUBLE);\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+        \r
+        String max = cachedValues.get(SensitivityDistributionKeys.MAX);\r
+        if(max != null) {\r
+            try {\r
+                Double d = Double.parseDouble(max);\r
+                graph.claimLiteral(resource, SR.Interval_maxValue, d, Bindings.DOUBLE);\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+    }\r
+\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/NormalDistributionProperties.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/NormalDistributionProperties.java
new file mode 100644 (file)
index 0000000..ccb5fb2
--- /dev/null
@@ -0,0 +1,158 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+\r
+public class NormalDistributionProperties implements IDistributionProperties {\r
+\r
+    private TrackedText minValue; \r
+    private TrackedText maxValue;\r
+    private TrackedText mean;\r
+    private TrackedText stdDeviation;\r
+    private Resource resource;\r
+    \r
+    public NormalDistributionProperties(Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+    \r
+    @Override\r
+    public Composite createContent(Composite parent, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(parent, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().numColumns(4).applyTo(composite);\r
+        \r
+        // mean\r
+        Label label = new Label(composite, SWT.NONE);\r
+        label.setText("Mean (\u03BC)");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        mean = new TrackedText(composite, support, SWT.BORDER);\r
+        mean.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.NormalDistribution_mean));\r
+        mean.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.NormalDistribution_mean));\r
+        mean.setInputValidator(new DoubleValidator(true));\r
+        mean.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), mean.getWidget())));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(mean.getWidget());\r
+        \r
+        // minValue\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Min value");\r
+        GridDataFactory.fillDefaults().indent(15, 0).align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        minValue = new TrackedText(composite, support, SWT.BORDER);\r
+        minValue.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.NormalDistribution_minValue));\r
+        minValue.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.NormalDistribution_minValue));\r
+        minValue.setInputValidator(new DoubleValidator(true));\r
+        minValue.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), minValue.getWidget())));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(minValue.getWidget());\r
+\r
+        // stdDeviation\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Standard deviation (\u03C3)");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        stdDeviation = new TrackedText(composite, support, SWT.BORDER);\r
+        stdDeviation.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.NormalDistribution_stdDeviation));\r
+        stdDeviation.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.NormalDistribution_stdDeviation));\r
+        stdDeviation.setInputValidator(new DoubleValidator(true));\r
+        stdDeviation.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), stdDeviation.getWidget())));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(stdDeviation.getWidget());\r
+        \r
+        // maxValue\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Max value");\r
+        GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(label);\r
+        \r
+        maxValue = new TrackedText(composite, support, SWT.BORDER);\r
+        maxValue.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.NormalDistribution_maxValue));\r
+        maxValue.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.NormalDistribution_maxValue));\r
+        maxValue.setInputValidator(new DoubleValidator(true));\r
+        maxValue.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), maxValue.getWidget())));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(maxValue.getWidget());\r
+        \r
+        return composite;\r
+    }\r
+\r
+    @Override\r
+    public void getCachedValues(HashMap<String, String> cahcedValues) {\r
+        if(!minValue.isDisposed())\r
+            cahcedValues.put(SensitivityDistributionKeys.MIN, minValue.getText());\r
+        if(!maxValue.isDisposed())\r
+            cahcedValues.put(SensitivityDistributionKeys.MAX, maxValue.getText());\r
+        if(!mean.isDisposed())\r
+            cahcedValues.put(SensitivityDistributionKeys.MEAN, mean.getText());\r
+        if(!stdDeviation.isDisposed())\r
+            cahcedValues.put(SensitivityDistributionKeys.STD_DEVIATION, stdDeviation.getText());\r
+    }\r
+\r
+\r
+\r
+    @Override\r
+    public void applyCache(WriteGraph graph, HashMap<String, String> cachedValues) throws DatabaseException {\r
+        if(resource == null)\r
+            return;\r
+        \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        String min = cachedValues.get(SensitivityDistributionKeys.MIN);\r
+        if(min != null) {\r
+            try {\r
+                Double d = Double.parseDouble(min);\r
+                graph.claimLiteral(resource, SR.NormalDistribution_minValue, d, Bindings.DOUBLE);\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+        \r
+        String max = cachedValues.get(SensitivityDistributionKeys.MAX);\r
+        if(max != null) {\r
+            try {\r
+                Double d = Double.parseDouble(max);\r
+                graph.claimLiteral(resource, SR.NormalDistribution_maxValue, d, Bindings.DOUBLE);\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+        \r
+        String mean = cachedValues.get(SensitivityDistributionKeys.MEAN);\r
+        if(mean != null) {\r
+            try {\r
+                Double d = Double.parseDouble(mean);\r
+                graph.claimLiteral(resource, SR.NormalDistribution_mean, d, Bindings.DOUBLE);\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+        \r
+        String stdDeviation = cachedValues.get(SensitivityDistributionKeys.STD_DEVIATION);\r
+        if(stdDeviation != null) {\r
+            try {\r
+                Double d = Double.parseDouble(stdDeviation);\r
+                graph.claimLiteral(resource, SR.NormalDistribution_stdDeviation, d, Bindings.DOUBLE);\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterChildRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterChildRule.java
new file mode 100644 (file)
index 0000000..30274d6
--- /dev/null
@@ -0,0 +1,50 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.simantics.browsing.ui.model.children.ChildRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ParameterChildRule implements ChildRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        Resource experiment = (Resource) parent;\r
+        Resource parameterList = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_parameterList);\r
+        \r
+        if(parameterList != null)\r
+            return ListUtils.toList(graph, parameterList);\r
+        else\r
+            return Collections.emptyList();\r
+    }\r
+\r
+    @Override\r
+    public Collection<?> getParents(ReadGraph graph, Object child) throws DatabaseException {\r
+        return Collections.emptyList();\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterLabelRule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterLabelRule.java
new file mode 100644 (file)
index 0000000..fd67dc8
--- /dev/null
@@ -0,0 +1,50 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.common.ColumnKeys;\r
+import org.simantics.browsing.ui.model.labels.LabelRule;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ParameterLabelRule implements LabelRule {\r
+\r
+    @Override\r
+    public boolean isCompatible(Class<?> contentType) {\r
+        return contentType.equals(Resource.class);\r
+    }\r
+\r
+    @Override\r
+    public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
+        HashMap<String, String> result = new HashMap<String, String>();\r
+        \r
+        String variable = graph.getPossibleRelatedValue((Resource)content, SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_variable);\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        \r
+        if(variable != null)\r
+            sb.append(variable);\r
+        else\r
+            sb.append("No variable");\r
+        \r
+        result.put(ColumnKeys.SINGLE, sb.toString()) ;\r
+        \r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterProposalProvider.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/ParameterProposalProvider.java
new file mode 100644 (file)
index 0000000..84b0c21
--- /dev/null
@@ -0,0 +1,16 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+public class ParameterProposalProvider {\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/SensitivityDistributionKeys.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/SensitivityDistributionKeys.java
new file mode 100644 (file)
index 0000000..d1019b2
--- /dev/null
@@ -0,0 +1,21 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+public class SensitivityDistributionKeys {\r
+    \r
+    public static String MAX = "MAX";\r
+    public static String MIN = "MIN";\r
+    public static String STD_DEVIATION = "STD_DEVIATION";\r
+    public static String MEAN = "MEAN";\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/SensitivityRangeHandlerFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/SensitivityRangeHandlerFactory.java
new file mode 100644 (file)
index 0000000..aca7931
--- /dev/null
@@ -0,0 +1,33 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.trend.SysdynRangeHandlerFactory;\r
+\r
+public class SensitivityRangeHandlerFactory extends SysdynRangeHandlerFactory {\r
+\r
+    @Override\r
+    protected Resource getRVIRelation(ReadGraph graph) {\r
+        return SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_variable;\r
+    }\r
+    \r
+    @Override\r
+    public ReadFactoryImpl<Resource, Map<String, Object>> getRangeItemFactory(int index, Resource res) {\r
+        return new RangeItemFactory(index, res, false);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/UniformDistributionProperties.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/UniformDistributionProperties.java
new file mode 100644 (file)
index 0000000..2b78a9d
--- /dev/null
@@ -0,0 +1,110 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.resource.JFaceResources;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.DoubleValidator;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+\r
+public class UniformDistributionProperties implements IDistributionProperties{\r
+\r
+    private TrackedText minValue; \r
+    private TrackedText maxValue;\r
+    private Resource resource;\r
+    \r
+    public UniformDistributionProperties(Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+    \r
+    @Override\r
+    public Composite createContent(Composite parent, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(parent, SWT.NONE);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);\r
+        \r
+        // minValue\r
+        Label label = new Label(composite, SWT.NONE);\r
+        label.setText("Min value");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+        \r
+        minValue = new TrackedText(composite, support, SWT.BORDER);\r
+        minValue.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.UniformDistribution_minValue));\r
+        minValue.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.UniformDistribution_minValue));\r
+        minValue.setInputValidator(new DoubleValidator(false));\r
+        minValue.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), minValue.getWidget())));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(minValue.getWidget());\r
+\r
+        // maxValue\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Max value");\r
+        GridDataFactory.fillDefaults().applyTo(label);\r
+        \r
+        maxValue = new TrackedText(composite, support, SWT.BORDER);\r
+        maxValue.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.UniformDistribution_maxValue));\r
+        maxValue.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.UniformDistribution_maxValue));\r
+        maxValue.setInputValidator(new DoubleValidator(false));\r
+        maxValue.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), maxValue.getWidget())));\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(maxValue.getWidget());\r
+        \r
+        return composite;\r
+    }\r
+\r
+    @Override\r
+    public void getCachedValues(HashMap<String, String> cahcedValues) {\r
+        cahcedValues.put(SensitivityDistributionKeys.MIN, minValue.getText());\r
+        cahcedValues.put(SensitivityDistributionKeys.MAX, maxValue.getText());\r
+    }\r
+\r
+\r
+\r
+    @Override\r
+    public void applyCache(WriteGraph graph, HashMap<String, String> cachedValues) throws DatabaseException {\r
+        if(resource == null)\r
+            return;\r
+        \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        String min = cachedValues.get(SensitivityDistributionKeys.MIN);\r
+        if(min != null) {\r
+            try {\r
+                Double d = Double.parseDouble(min);\r
+                graph.claimLiteral(resource, SR.UniformDistribution_minValue, d, Bindings.DOUBLE);\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+        \r
+        String max = cachedValues.get(SensitivityDistributionKeys.MAX);\r
+        if(max != null) {\r
+            try {\r
+                Double d = Double.parseDouble(max);\r
+                graph.claimLiteral(resource, SR.UniformDistribution_maxValue, d, Bindings.DOUBLE);\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/VariableNameModifier.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/VariableNameModifier.java
new file mode 100644 (file)
index 0000000..eaac45d
--- /dev/null
@@ -0,0 +1,121 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
+\r
+import org.eclipse.jface.bindings.keys.KeyStroke;\r
+import org.eclipse.jface.bindings.keys.ParseException;\r
+import org.eclipse.jface.fieldassist.ContentProposalAdapter;\r
+import org.eclipse.jface.fieldassist.IContentProposal;\r
+import org.eclipse.jface.fieldassist.IContentProposalListener;\r
+import org.eclipse.jface.fieldassist.IContentProposalListener2;\r
+import org.eclipse.jface.fieldassist.TextContentAdapter;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.jfreechart.chart.properties.VariableProposalProvider;\r
+\r
+public class VariableNameModifier extends TextModifyListenerImpl<Resource> {\r
+\r
+    private boolean active;\r
+    private Control control;\r
+    private String variableNameRelationUri;\r
+    private String indexUri;\r
+    \r
+    private char[] alphaNumericCharacters = {\r
+        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','Ã¥','ä','ö',\r
+        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Ã…','Ä','Ö',\r
+        '1','2','3','4','5','6','7','8','9','0','.'};\r
+    \r
+        \r
+    public VariableNameModifier(Control control, WidgetSupport support, String variableNameRelationUri, String indexUri) {\r
+        this.variableNameRelationUri = variableNameRelationUri;\r
+        this.indexUri = indexUri;\r
+        \r
+        this.control = control;\r
+        this.active = true;\r
+        \r
+        KeyStroke keyStroke = null;\r
+        try {\r
+            keyStroke = KeyStroke.getInstance("Ctrl+Space");\r
+        } catch (ParseException e1) {\r
+            e1.printStackTrace();\r
+        }\r
+        \r
+        //SimpleContentProposalProvider scpp = new VariableProposalProvider(control, support);\r
+        VariableProposalProvider scpp = new VariableProposalProvider(control, support);\r
+        scpp.setFiltering(true);\r
+\r
+        ContentProposalAdapter adapter = new ContentProposalAdapter(\r
+                control, new TextContentAdapter(), scpp, keyStroke, alphaNumericCharacters);\r
+        adapter.setAutoActivationDelay(0);\r
+        adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);\r
+        adapter.addContentProposalListener(new IContentProposalListener2() {\r
+\r
+            @Override\r
+            public void proposalPopupOpened(ContentProposalAdapter adapter) {\r
+                if(VariableNameModifier.this != null)\r
+                    VariableNameModifier.this.deactivate();\r
+            }\r
+\r
+            @Override\r
+            public void proposalPopupClosed(ContentProposalAdapter adapter) {\r
+                if(VariableNameModifier.this != null)\r
+                    VariableNameModifier.this.activate();\r
+            }\r
+        });\r
+\r
+        adapter.addContentProposalListener(new IContentProposalListener() {\r
+\r
+            @Override\r
+            public void proposalAccepted(IContentProposal proposal) {\r
+                if(VariableNameModifier.this.control != null && !VariableNameModifier.this.control.isDisposed())\r
+                    VariableNameModifier.this.modifyText(new TrackedModifyEvent(VariableNameModifier.this.control, proposal.getContent()));\r
+            }\r
+        });\r
+    \r
+    \r
+    }\r
+    \r
+\r
+    @Override\r
+    public void applyText(WriteGraph graph, Resource resource, String text) throws DatabaseException {\r
+        if(active) {\r
+            graph.claimLiteral(resource, getVariableNameRelation(graph), text, Bindings.STRING);\r
+            graph.deny(resource, getIndexRelation(graph));\r
+        } else {\r
+            System.out.println("NÄHÄÄ");\r
+        }\r
+    }\r
+    \r
+    private Resource getVariableNameRelation(ReadGraph graph) throws DatabaseException {\r
+        return graph.getResource(variableNameRelationUri);\r
+    }\r
+    \r
+    private Resource getIndexRelation(ReadGraph graph) throws DatabaseException {\r
+        return graph.getResource(indexUri);\r
+    }\r
+\r
+    public void deactivate() {\r
+        active = false;\r
+    }\r
+\r
+    public void activate() {\r
+        active = true;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Dependencies.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Dependencies.java
new file mode 100644 (file)
index 0000000..02e052d
--- /dev/null
@@ -0,0 +1,113 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.structure;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.CTabFolder;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.layout.RowLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Spinner;\r
+import org.simantics.db.Resource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class Dependencies extends StructureTabItem {\r
+    \r
+    private boolean isInverted = false;\r
+    private Button bButton, fButton;\r
+    private int levels = 3;\r
+\r
+    private static int MAXLEVELS = 4;\r
+    private static int MINLEVELS = 1;\r
+\r
+    public Dependencies(CTabFolder parent, int style) {\r
+        super(parent, style);\r
+        \r
+        Label line = new Label(structureComposite, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL);\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(line);\r
+        \r
+        Composite composite = new Composite(structureComposite, SWT.NONE);\r
+        RowLayout layout = new RowLayout();\r
+        layout.center = true;\r
+        composite.setLayout(layout);\r
+\r
+        Label label = new Label(composite, SWT.NONE);\r
+        label.setText("Direction: ");\r
+\r
+        bButton = new Button(composite, SWT.RADIO);\r
+        bButton.setText("Backward");\r
+        bButton.setSelection(true);\r
+        bButton.addSelectionListener(new SelectionAdapter() {\r
+            public void widgetSelected(SelectionEvent event) {\r
+                if(bButton.getSelection())\r
+                    isInverted = false;\r
+                else \r
+                    isInverted = true;\r
+                if(currentSelection != null) {\r
+                    readGraph(currentSelection);\r
+                }\r
+            }\r
+        });\r
+\r
+        fButton = new Button(composite, SWT.RADIO);\r
+        fButton.setText("Forward");\r
+\r
+        label = new Label(composite, SWT.NONE);\r
+        label.setText("Steps: ");\r
+\r
+        Spinner spinner = new Spinner(composite, SWT.BORDER);\r
+        spinner.setMaximum(MAXLEVELS);\r
+        spinner.setMinimum(MINLEVELS);\r
+        spinner.setTextLimit(1);\r
+        spinner.setSelection(levels);\r
+\r
+        spinner.addModifyListener(new ModifyListener() {\r
+\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                Spinner s = (Spinner)e.widget;\r
+                int lvls = Integer.parseInt(s.getText());\r
+                if(lvls > MAXLEVELS)\r
+                    levels = MAXLEVELS;\r
+                else if (lvls < MINLEVELS)\r
+                    levels = MINLEVELS;\r
+                levels = lvls;\r
+                if(currentSelection != null) {\r
+                    readGraph(currentSelection);\r
+                }\r
+\r
+            }\r
+        });\r
+        \r
+        this.setText("Dependencies");\r
+        this.setControl(structureComposite);\r
+    }\r
+\r
+    protected void readGraph(Resource resource) {\r
+        if(graphListener != null)\r
+            graphListener.dispose();\r
+        \r
+        graphListener = new GraphListener();\r
+        SimanticsUI.getSession().asyncRequest(new DependencyGraphRequest(\r
+                resource, levels, isInverted), graphListener);\r
+    }\r
+\r
+    protected String getJobLabel() {\r
+       return "Loading dependencies graph";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/DependencyGraphRequest.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/DependencyGraphRequest.java
new file mode 100644 (file)
index 0000000..2907559
--- /dev/null
@@ -0,0 +1,192 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.structure;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.graphviz.Edge;\r
+import org.simantics.graphviz.Graph;\r
+import org.simantics.graphviz.IGraph;\r
+import org.simantics.graphviz.Node;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Builds a graph of the dependencies of a selected variable\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class DependencyGraphRequest implements Read<Graph> {\r
+\r
+       protected Resource root;\r
+       protected HashMap<Resource, Node> nodes;\r
+       protected boolean isInverted;\r
+       protected int levels;\r
+\r
+       /**\r
+        * Builds a graph of the dependencies of a selected variable\r
+        * \r
+        * @param root Variable from which to find dependencies\r
+        * @param levels How many steps of dependencies are calculated from the variable\r
+        * @param isInverted true => variables that affect root; false => variables that are affected by root \r
+        */\r
+       public DependencyGraphRequest(Resource root, int levels, boolean isInverted) {\r
+               this.root = root;\r
+               this.isInverted = isInverted;    \r
+               this.levels = levels;\r
+       }\r
+\r
+       @Override\r
+       public Graph perform(ReadGraph g) throws DatabaseException {\r
+\r
+               nodes = new HashMap<Resource, Node>();\r
+               Graph graph = new Graph();\r
+               graph.setRankdir("LR");\r
+               ModelingResources mr = ModelingResources.getInstance(g);\r
+               Resource element = g.getPossibleObject(root, mr.ElementToComponent);\r
+               if (element != null) {\r
+                       root = element;\r
+               }\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+               if (g.isInstanceOf(root, sr.IndependentVariable) || g.isInstanceOf(root, sr.Input)) {\r
+                       setRoot(g, graph, root);\r
+                       Collection<Resource> resources = new ArrayList<Resource>(); \r
+                       resources.add(root);\r
+                       for (int i = 0; i < levels && !resources.isEmpty(); i++) {\r
+                               Collection<Resource> newResources = new ArrayList<Resource>();\r
+                               for(Resource r : resources) {\r
+                                       newResources.addAll(setDependencies(g, graph, r));\r
+                               }\r
+                               resources = new ArrayList<Resource>(newResources);\r
+                       }\r
+               }\r
+               return graph;\r
+       }\r
+\r
+       /**\r
+        * Create a root node and set appearance settings for it\r
+        * @param g ReadGraph\r
+        * @param graph Graphviz graph\r
+        * @param root Root resource\r
+        * @throws DatabaseException\r
+        */\r
+       protected void setRoot(ReadGraph g, IGraph graph, Resource root) throws DatabaseException {\r
+               Node n;\r
+               n = new Node(graph, getName(g, root));\r
+               setShape(g, root, n);\r
+               n.set("style", "filled");\r
+               n.setFillColor("#d3d3d3");\r
+               nodes.put(root, n);\r
+       }\r
+\r
+\r
+       /**\r
+        * Call for calculating  \r
+        * @param g\r
+        * @param graph\r
+        * @param r\r
+        * @param toDependency\r
+        * @param fromDependency\r
+        * @param connectionType\r
+        * @return\r
+        * @throws DatabaseException\r
+        */\r
+       private Collection<Resource> getDependants(ReadGraph g, IGraph graph, Resource r, Resource toDependency, Resource fromDependency, Resource connectionType) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+\r
+               Collection<Resource> dependencies = g.syncRequest(new ObjectsWithType(r, toDependency, connectionType));\r
+\r
+               Collection<Resource> dependants = new ArrayList<Resource>();\r
+               Node n;\r
+               for(Resource d : dependencies) {\r
+                       Resource dependant = g.getPossibleObject(d, fromDependency);\r
+                       if(dependant == null)\r
+                               continue;\r
+                       if(g.isInstanceOf(dependant, sr.Cloud)) {\r
+                               break;\r
+                       }\r
+                       if( !nodes.containsKey(dependant)) {\r
+                               n= new Node(graph, getName(g, dependant));\r
+                               setShape(g, dependant, n);\r
+                               nodes.put(dependant, n);\r
+                               dependants.add(dependant);\r
+                       }\r
+\r
+                       if(isInverted) {\r
+                               new Edge(graph, nodes.get(r), nodes.get(dependant));\r
+                       } else {\r
+                               new Edge(graph, nodes.get(dependant), nodes.get(r));\r
+                       }\r
+               }\r
+               return dependants;\r
+       }\r
+       \r
+       private Collection<Resource> setDependencies(ReadGraph g, IGraph graph, Resource r) throws DatabaseException{\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+\r
+               // stop here if element is a module\r
+               if (g.isInstanceOf(r, sr.Module))\r
+                       return Collections.emptyList();\r
+\r
+               Collection<Resource> dependants;\r
+               if(isInverted) {\r
+                   dependants = getDependants(g, graph, r, sr.Variable_isTailOf, sr.Variable_HasHead, sr.Dependency);\r
+                   if (g.isInstanceOf(r, sr.Valve)) {\r
+                       dependants.addAll(getDependants(g, graph, r, sr.Variable_isTailOf, sr.Variable_HasHead, sr.Flow));\r
+                       dependants.addAll(getDependants(g, graph, r, sr.Variable_isHeadOf, sr.Variable_HasTail, sr.Flow));\r
+                   }\r
+               } else {\r
+                   dependants = getDependants(g, graph, r, sr.Variable_isHeadOf, sr.Variable_HasTail, sr.Dependency);\r
+                   if (g.isInstanceOf(r, sr.Stock)) {\r
+                       dependants.addAll(getDependants(g, graph, r, sr.Variable_isTailOf, sr.Variable_HasHead, sr.Flow));\r
+                       dependants.addAll(getDependants(g, graph, r, sr.Variable_isHeadOf, sr.Variable_HasTail, sr.Flow));\r
+                   }\r
+               }\r
+\r
+               return dependants;\r
+       }\r
+       \r
+       /**\r
+        * Set shape for a node. Rectangle for stocks, ellipse for auxiliaries and rounded rectangle for modules. \r
+        * @param g ReadGraph\r
+        * @param r Resource\r
+        * @param n Node\r
+        * @throws DatabaseException\r
+        */\r
+       protected void setShape(ReadGraph g, Resource r, Node n) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+               if(g.isInstanceOf(r, sr.Stock))\r
+                       n.setShape("rectangle");\r
+               else if(g.isInstanceOf(r, sr.Module)) {\r
+                       n.setShape("rectangle");\r
+                       n.setStyle("rounded"); \r
+               }\r
+               else\r
+                       n.setShape("ellipse");\r
+       }\r
+\r
+       protected String getName(ReadGraph g, Resource r) throws DatabaseException {\r
+               return (String)g.getRelatedValue(r, Layer0.getInstance(g).HasName);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/LoopGraphRequest.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/LoopGraphRequest.java
new file mode 100644 (file)
index 0000000..6063be5
--- /dev/null
@@ -0,0 +1,125 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.structure;\r
+\r
+import java.util.HashMap;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.graphviz.Edge;\r
+import org.simantics.graphviz.Graph;\r
+import org.simantics.graphviz.IGraph;\r
+import org.simantics.graphviz.Node;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.utils.LoopUtils;\r
+import org.simantics.utils.datastructures.MapList;\r
+\r
+/**\r
+ * Builds a graph of the loops of a selected variable\r
+ * \r
+ * @author Tuomas Miettinen\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class LoopGraphRequest extends DependencyGraphRequest {\r
+\r
+       MapList<Resource, Edge> edges;\r
+\r
+       /**\r
+        * Builds a graph of the dependencies of a selected variable\r
+        * \r
+        * @param root Variable from which to find dependencies\r
+        * @param levels How many steps of dependencies are calculated from the variable\r
+        * @param isInverted true => variables that affect root; false => variables that are affected by root \r
+        */\r
+       public LoopGraphRequest(Resource root) {\r
+               super(root, 999, false);\r
+       }\r
+\r
+       @Override\r
+       public Graph perform(ReadGraph g) throws DatabaseException {\r
+\r
+               nodes = new HashMap<Resource, Node>();\r
+               Graph graph = new Graph();\r
+               graph.setRankdir("LR");\r
+               ModelingResources mr = ModelingResources.getInstance(g);\r
+               Resource element = g.getPossibleObject(root, mr.ElementToComponent);\r
+               if (element != null) {\r
+                       root = element;\r
+               }\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+               if (g.isInstanceOf(root, sr.IndependentVariable) || g.isInstanceOf(root, sr.Input)) {\r
+                       // Get ALL loops in the diagram in which the root exists.\r
+                       List<List<Resource>> loops = LoopUtils.getLoops(g, root);\r
+                       setRoot(g, graph, root);\r
+                       \r
+                       // Add the edges to the graph.\r
+                       edges = new MapList<Resource, Edge>();\r
+                       for (List<Resource> loop : loops) {\r
+                               Resource prev = null;\r
+                               for (Resource r : loop) {\r
+                                       // Add node if not already added.\r
+                                       if(!nodes.containsKey(r)) {\r
+                                               Node n = new Node(graph, getName(g, r));\r
+                                               setShape(g, r, n);\r
+                                               nodes.put(r, n);\r
+                                       }\r
+                                       // Add edge if not already added.\r
+                                       if (prev != null)\r
+                                               claimEdge(g, graph, prev, r);\r
+                                       \r
+                                       prev = r;\r
+                               }\r
+                               // Add edge between the last and first node in the loop.\r
+                               if (prev != null && loop.get(0) != null)\r
+                                       claimEdge(g, graph, prev, loop.get(0));\r
+                       }\r
+               }\r
+               return graph;\r
+       }\r
+\r
+       /**\r
+        * Create and edge between _tail and _head nodes. If the edge already exists, do nothing.\r
+        * If an opposite direction edge exists, draw an arrow also to the tail of the edge.\r
+        * @param g \r
+        * @param graph Graph in which the nodes lie.\r
+        * @param tail The tail node.\r
+        * @param head The head node.\r
+        * @throws DatabaseException \r
+        */\r
+       private void claimEdge(ReadGraph g, IGraph graph, Resource tail, Resource head) throws DatabaseException {\r
+               // If edge exists, increase the size of the arrowhead and return.\r
+               for (Edge e : edges.getValues(tail)) {\r
+                       if (((Node)e.getHead()).get("label").equals(getName(g, head))) {\r
+                               // Change the size of the arrowhead (fancily :-)\r
+                               String arrowsize = e.get("arrowsize");\r
+                               if (arrowsize == null)\r
+                                       arrowsize = "1.0";\r
+                               e.setArrowsize(Math.min(2.2, Math.sqrt(Double.valueOf(arrowsize) + 0.8)));\r
+                               return;\r
+                       }\r
+               }\r
+\r
+               for (Edge e : edges.getValues(head)) { // Seek for opposite edges\r
+                       if (((Node)e.getHead()).get("label").equals(getName(g, tail))) {\r
+                               e.setDir("both");\r
+                               return;\r
+                       }\r
+               }\r
+               \r
+               // If no edge has been found, add one. \r
+               edges.add(tail, new Edge(graph, nodes.get(tail), nodes.get(head)));\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Loops.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Loops.java
new file mode 100644 (file)
index 0000000..798b504
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.structure;\r
+\r
+import org.eclipse.swt.custom.CTabFolder;\r
+import org.simantics.db.Resource;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Tab for loops.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Loops extends StructureTabItem {\r
+\r
+    public Loops(CTabFolder parent, int style) {\r
+        super(parent, style);\r
+        this.setText("Loops");\r
+        this.setControl(structureComposite);\r
+    }\r
+\r
+    protected void readGraph(Resource resource) {\r
+        if(graphListener != null)\r
+            graphListener.dispose();\r
+        \r
+        graphListener = new GraphListener();\r
+        SimanticsUI.getSession().asyncRequest(new LoopGraphRequest(\r
+                resource), graphListener);\r
+    }\r
+\r
+    protected String getJobLabel() {\r
+       return "Loading loops graph";\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructure.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructure.java
new file mode 100644 (file)
index 0000000..c3b2799
--- /dev/null
@@ -0,0 +1,135 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.structure;\r
+\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.CTabFolder;\r
+import org.eclipse.swt.custom.CTabItem;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.graphviz.Graph;\r
+import org.simantics.graphviz.ui.GraphvizComponent;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.RunnableWithObject;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Tab for displaying hierarchical model structure\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ModuleStructure extends CTabItem {\r
+\r
+    private GraphvizComponent component;\r
+    private GraphListener graphListener;\r
+\r
+    \r
+    public ModuleStructure(CTabFolder parent, int style) {\r
+        super(parent, style);\r
+        \r
+        Composite moduleStructure = new Composite(parent, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(moduleStructure);\r
+        GridLayoutFactory.fillDefaults().applyTo(moduleStructure);\r
+\r
+        component = new GraphvizComponent(moduleStructure, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(component);\r
+        \r
+        this.setText("Model Hierarchy");\r
+        this.setControl(moduleStructure);\r
+\r
+    }\r
+\r
+    /**\r
+     * Draw a graph about the model of the selected resource\r
+     * @param selection\r
+     */\r
+    public void drawSelection(ISelection selection) {\r
+        if(selection == null || selection.isEmpty())\r
+            return;\r
+\r
+        if(selection instanceof IStructuredSelection) {                    \r
+            Object[] els = ((IStructuredSelection) selection).toArray();\r
+            if(els.length == 1) {\r
+                Set<Resource> ress = ISelectionUtils.filterSetSelection(selection, Resource.class);\r
+                if(ress.isEmpty()) return;\r
+                Resource r = (ress.toArray(Resource.NONE))[0];\r
+                if(r != null) {\r
+                    // Read graph for the resource\r
+                    if(graphListener != null)\r
+                        graphListener.dispose(); // Dispose possible previous listener\r
+                    \r
+                    graphListener = new GraphListener();\r
+                    SimanticsUI.getSession().asyncRequest(new ModuleStructureGraphRequest(r), graphListener);\r
+                }\r
+            }\r
+        }           \r
+    }\r
+    \r
+    /**\r
+     * Listener for updating hierarchical model graph\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class GraphListener implements Listener<Graph> {\r
+        private boolean disposed = false;\r
+        \r
+        public void dispose() {\r
+            disposed = true;\r
+        }\r
+        \r
+        @Override\r
+        public void exception(Throwable e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        @Override\r
+        public void execute(final Graph graph) {\r
+            Job job = new Job("Loading model structure graph") {\r
+\r
+                @Override\r
+                protected IStatus run(IProgressMonitor monitor) {\r
+                    if(!isDisposed()) {\r
+                        component.getDisplay().asyncExec(new RunnableWithObject(graph) {\r
+                            \r
+                            @Override\r
+                            public void run() {\r
+                                if (component.isDisposed()) return;\r
+                                component.setGraph((Graph)getObject(), "dot");\r
+                                component.fit();    \r
+                            }\r
+                        });\r
+                     \r
+                    }\r
+                    return Status.OK_STATUS;\r
+                }\r
+            };\r
+            job.schedule();\r
+        }\r
+\r
+        @Override\r
+        public boolean isDisposed() {\r
+            return disposed;\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructureGraphRequest.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructureGraphRequest.java
new file mode 100644 (file)
index 0000000..c32a300
--- /dev/null
@@ -0,0 +1,148 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.structure;\r
+\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.graphviz.Edge;\r
+import org.simantics.graphviz.Graph;\r
+import org.simantics.graphviz.Node;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Builds a graph about the modular structure of the model where a selected object is located.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ModuleStructureGraphRequest implements Read<Graph> {\r
+\r
+    private Resource resource;\r
+\r
+    /**\r
+     * Request a hierarchical graph about the model of resource\r
+     * @param resource\r
+     */\r
+    public ModuleStructureGraphRequest(Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+\r
+    @Override\r
+    public Graph perform(ReadGraph graph) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+        Graph g = new Graph();\r
+        g.setRankdir("TB");\r
+\r
+        // Find model resource, the root of this\r
+        Resource model = resource;\r
+        while(model != null && !graph.isInstanceOf(model, sr.SysdynModel)) {\r
+            model = graph.getPossibleObject(model, l0.PartOf);\r
+        }\r
+\r
+        // Model root was not found, return empty graph\r
+        if(model == null)\r
+            return g;\r
+        \r
+        // Find the parent module/model of the selected resource\r
+        Resource parentResource = graph.getPossibleObject(resource, l0.PartOf);\r
+        if(graph.isInstanceOf(parentResource, sr.ConfigurationDiagram)) {\r
+               parentResource = graph.getPossibleObject(parentResource, ModelingResources.getInstance(graph).DiagramToComposite);\r
+        } else if(graph.isInstanceOf(parentResource, sr.SysdynModel)) {\r
+               parentResource = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+        }\r
+\r
+        // Set root node\r
+        Node rootNode = new Node(g, NameUtils.getSafeLabel(graph, model));\r
+        rootNode.setShape("rectangle");\r
+        HashSet<Resource> visited = new HashSet<Resource>();\r
+        visited.add(model);\r
+        findChildModules(g, rootNode, graph, model, parentResource, visited);\r
+\r
+\r
+        return g;\r
+    }\r
+\r
+    /**\r
+     * Recursive call for finding child modules \r
+     * @param g GraphViz graph\r
+     * @param parent Parent module or model\r
+     * @param graph ReadGraph\r
+     * @param resource Module type or model\r
+     * @param parent2 \r
+     * @param visited All visited modules. Needed to check for loops in the structure. Loops are not allowed.\r
+     * @throws DatabaseException\r
+     */\r
+    private void findChildModules(Graph g, Node parent, ReadGraph graph, Resource resource, Resource parentResource, HashSet<Resource> visited) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+        Resource configuration = graph.syncRequest(new PossibleObjectWithType(resource, l0.ConsistsOf, sr.Configuration));\r
+\r
+        // Set the parent color different, if it is the parent of the selected resource\r
+        if(configuration.equals(parentResource))\r
+               parent.setColor("#ff8c00");\r
+        \r
+        HashMap<Resource, Integer> modules = new HashMap<Resource, Integer>();\r
+\r
+        // Find all module children\r
+        for(Resource m : graph.getObjects(configuration, l0.ConsistsOf)) {\r
+            Resource type = graph.getPossibleObject(m, l0.InstanceOf);\r
+            if(graph.isInheritedFrom(type, sr.Module)) {\r
+                if(!modules.containsKey(type))\r
+                    modules.put(type, 0);\r
+                modules.put(type, modules.get(type) + 1);\r
+            }\r
+        }\r
+\r
+        // Display module children in graph\r
+        for(Resource type : modules.keySet()) {\r
+\r
+            Node node = new Node(g, NameUtils.getSafeName(graph, type));\r
+            node.setShape("rectangle");\r
+            Edge edge = new Edge(g, parent, node);\r
+            edge.set("labeldistance", "1.5");\r
+            edge.set("labelfontsize", "7");\r
+            edge.setFontColor("#4f4f4f");\r
+            if(modules.get(type) > 1)\r
+                edge.setHeadLabel(modules.get(type).toString());\r
+            \r
+            if(visited.contains(type)) {\r
+                // Found a loop. Stop recursive call and display error.\r
+                edge.setFontColor("#FF0000");\r
+                edge.setColor("#FF000");\r
+                edge.setLabel("Error: loop");\r
+                node.setColor("#FF0000");\r
+                node.setFontColor("#FF0000");\r
+                continue;\r
+            } else {\r
+               HashSet<Resource> copy = new HashSet<Resource>(visited);\r
+               copy.add(type);\r
+                findChildModules(g, node, graph, type, parentResource, copy);\r
+            }\r
+            \r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/StructureTabItem.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/StructureTabItem.java
new file mode 100644 (file)
index 0000000..ceadd9d
--- /dev/null
@@ -0,0 +1,115 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.structure;\r
+\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.CTabFolder;\r
+import org.eclipse.swt.custom.CTabItem;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.graphviz.Graph;\r
+import org.simantics.graphviz.ui.GraphvizComponent;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Super class for certain kinds of structure tabs.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public abstract class StructureTabItem extends CTabItem {\r
+    \r
+    protected GraphvizComponent component;\r
+    protected GraphListener graphListener;\r
+    protected Composite structureComposite;\r
+    protected Resource currentSelection;\r
+    \r
+    public StructureTabItem(CTabFolder parent, int style) {\r
+        super(parent, style);\r
+        \r
+        structureComposite = new Composite(parent, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(structureComposite);\r
+        GridLayoutFactory.fillDefaults().spacing(0,0).applyTo(structureComposite);\r
+\r
+        component = new GraphvizComponent(structureComposite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(component);\r
+    }\r
+\r
+\r
+    public void drawSelection(ISelection selection) {\r
+        if(selection == null || selection.isEmpty())\r
+            return;\r
+        if(selection instanceof IStructuredSelection) {                    \r
+            Object[] els = ((IStructuredSelection) selection).toArray();\r
+            if(els.length == 1) {\r
+                Set<Resource> ress = ISelectionUtils.filterSetSelection(selection, Resource.class);\r
+                if(ress.isEmpty()) return;\r
+                Resource r = (ress.toArray(Resource.NONE))[0];\r
+                if(r != null && !r.equals(currentSelection)) {\r
+                    currentSelection = r;\r
+                    readGraph(currentSelection);\r
+                }\r
+            }\r
+        }           \r
+    }\r
+\r
+    abstract protected void readGraph(Resource resource);\r
+\r
+    class GraphListener implements Listener<Graph> {\r
+        \r
+        private boolean disposed = false;\r
+        \r
+        public void dispose() {\r
+            disposed = true;\r
+        }\r
+        \r
+        @Override\r
+        public void exception(Throwable e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        @Override\r
+        public void execute(final Graph graph) {\r
+            Job job = new Job(getJobLabel()) {\r
+\r
+                @Override\r
+                protected IStatus run(IProgressMonitor monitor) {\r
+                    if(!isDisposed()) {\r
+                        component.setGraph(graph, "dot");\r
+                        component.fit();                            \r
+                    }\r
+                    return Status.OK_STATUS;\r
+                }\r
+            };\r
+            job.schedule();\r
+        }\r
+\r
+        @Override\r
+        public boolean isDisposed() {\r
+            return disposed;\r
+        }\r
+    }\r
+    \r
+    protected String getJobLabel() {\r
+       return "Loading dependencies graph";\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/StructureView.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/StructureView.java
new file mode 100644 (file)
index 0000000..39dc59d
--- /dev/null
@@ -0,0 +1,132 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.structure;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.CTabFolder;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.ISelectionListener;\r
+import org.eclipse.ui.IWorkbenchPart;\r
+import org.eclipse.ui.part.ViewPart;\r
+\r
+/**\r
+ * View for displaying different types of structural visualizations\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class StructureView extends ViewPart {\r
+\r
+    private CTabFolder tabFolder;\r
+    private ISelectionListener selectionListener;\r
+    private StructureTabItem dependencies;\r
+    private ModuleStructure moduleStructure;\r
+    private Loops loops;\r
+    \r
+    @Override\r
+    public void createPartControl(Composite parent) {\r
+        tabFolder = new CTabFolder(parent, SWT.BORDER);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(tabFolder);\r
+        GridLayoutFactory.fillDefaults().applyTo(tabFolder);\r
+\r
+        final ISelection currentSeletion = getSite().getWorkbenchWindow().getSelectionService().getSelection();\r
+        \r
+        // Dependencies\r
+        dependencies = new Dependencies(tabFolder, SWT.NONE);\r
+        dependencies.drawSelection(currentSeletion);\r
+        \r
+        // Hierarchical model structure\r
+        moduleStructure = new ModuleStructure(tabFolder, SWT.NONE);\r
+\r
+        // Loops\r
+        loops = new Loops(tabFolder, SWT.NONE);\r
+\r
+        selectionListener = new ISelectionListener() {\r
+\r
+            @Override\r
+            public void selectionChanged(IWorkbenchPart part, ISelection selection) {\r
+                drawSelection(selection);\r
+            }\r
+        };    \r
+        getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(selectionListener);\r
+        \r
+        \r
+        // Listener for refreshing module structure visualization on first loading\r
+        tabFolder.addSelectionListener(new SelectionListener() {\r
+            \r
+            private boolean openedOnce = false;\r
+            \r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                if(!openedOnce && e.item.equals(moduleStructure)) {\r
+                    openedOnce = true;\r
+                    moduleStructure.drawSelection(currentSeletion);\r
+                }\r
+            }\r
+            \r
+            @Override\r
+            public void widgetDefaultSelected(SelectionEvent e) {\r
+            }\r
+        });\r
+        \r
+        // Listener for refreshing module structure visualization on first loading\r
+        tabFolder.addSelectionListener(new SelectionListener() {\r
+            \r
+            private boolean openedOnce = false;\r
+            \r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                if(!openedOnce && e.item.equals(loops)) {\r
+                    openedOnce = true;\r
+                    loops.drawSelection(currentSeletion);\r
+                }\r
+            }\r
+            \r
+            @Override\r
+            public void widgetDefaultSelected(SelectionEvent e) {\r
+            }\r
+        });\r
+    }\r
+    \r
+    /**\r
+     * Draw structural visualizations for selected object(s)\r
+     * \r
+     * @param selection Current selection\r
+     */\r
+    private void drawSelection(ISelection selection) {\r
+        dependencies.drawSelection(selection);\r
+        moduleStructure.drawSelection(selection);\r
+        loops.drawSelection(selection);\r
+    }\r
+    \r
+\r
+    @Override\r
+    public void setFocus() {\r
+        if(tabFolder != null && !tabFolder.isDisposed()) {\r
+            tabFolder.setFocus();\r
+        }\r
+    }\r
+\r
+\r
+    @Override\r
+    public void dispose() {\r
+        super.dispose();\r
+        getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(selectionListener);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllParametersOfModel.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllParametersOfModel.java
new file mode 100644 (file)
index 0000000..de84ecf
--- /dev/null
@@ -0,0 +1,132 @@
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.properties.ChartVariable;\r
+import org.simantics.jfreechart.chart.properties.IAllVariablesOfModel;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Variability;\r
+\r
+/**\r
+ * Request for getting all variables of a model in a String array. Includes also \r
+ * variables inside modules.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class AllParametersOfModel implements IAllVariablesOfModel {\r
+    \r
+    protected final Resource model;\r
+    \r
+    public AllParametersOfModel(Resource model) {\r
+        this.model = model;\r
+    }\r
+\r
+       @Override\r
+       public Read<Collection<ChartVariable>> getVariablesQuery() {\r
+               return new VariableQuery();\r
+       }   \r
+       \r
+       \r
+    private class VariableQuery implements Read<Collection<ChartVariable>> {\r
+        @Override\r
+           public Collection<ChartVariable> perform(ReadGraph graph) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SimulationResource simu = SimulationResource.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               List<ChartVariable> result = new ArrayList<ChartVariable>();\r
+               // Find the model of this resource\r
+               Resource model = AllParametersOfModel.this.model;\r
+               while(model != null && !graph.isInstanceOf(model, sr.SysdynModel))\r
+                   model = graph.getPossibleObject(model, l0.PartOf);\r
+               \r
+               if(model == null)\r
+                   return result;\r
+               \r
+               // Find the models configuration\r
+               Resource conf = graph.getSingleObject(model, simu.HasConfiguration);\r
+              \r
+               // Recursively read all configurations and add items\r
+               ReadConfiguration(graph, conf, "", result);\r
+                               \r
+               // Finally sort the results\r
+               Collections.sort(result, AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+               return result;\r
+           }\r
+    }\r
+    \r
+    \r
+    \r
+    /**\r
+     * Read components in a configuration and recursively all module configurations\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param configuration Resource to be read\r
+     * @param path Current path from base realization\r
+     * @param items Found variables\r
+     * @throws DatabaseException\r
+     */\r
+    private void ReadConfiguration(ReadGraph graph, Resource configuration, String path, Collection<ChartVariable> items) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+\r
+        SysdynModelManager sdm = SysdynModelManager.getInstance(SimanticsUI.getSession());\r
+        SysdynModel sm = sdm.getModel(graph, configuration);\r
+        try {\r
+            sm.update(graph);\r
+        } catch (DatabaseException e1) {\r
+            e1.printStackTrace();\r
+        }\r
+        \r
+        String name;\r
+        for(Resource resource : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.IndependentVariable))) {\r
+            name = path + NameUtils.getSafeName(graph, resource);\r
+            IElement element = sm.getElement(resource);\r
+            if (element instanceof IndependentVariable) {\r
+               IndependentVariable variable = (IndependentVariable)element; \r
+               Variability variability = Variability.getVariability(variable, false, null);\r
+               if (variability == Variability.PARAMETER) {\r
+                       items.add(new ChartVariable(name, name));\r
+               }\r
+            }\r
+        }\r
+        \r
+        for(Resource module : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {\r
+            Resource instanceOf = graph.getPossibleObject(module, l0.InstanceOf);\r
+            Resource conf = graph.getPossibleObject(instanceOf, sr2.IsDefinedBy);\r
+            if(conf != null) {\r
+                String p = path + NameUtils.getSafeName(graph, module)  + ".";\r
+                ReadConfiguration(graph, conf, p, items);\r
+            }\r
+        }\r
+    }\r
+       \r
+       @Override\r
+    public String getVariablesLabel(ReadGraph graph, String variableId)\r
+                       throws DatabaseException {\r
+                  return variableId.substring(1).replace('/', '.');\r
+       }\r
+\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllVariablesOfModel.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllVariablesOfModel.java
new file mode 100644 (file)
index 0000000..241b7cb
--- /dev/null
@@ -0,0 +1,120 @@
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.properties.ChartVariable;\r
+import org.simantics.jfreechart.chart.properties.IAllVariablesOfModel;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.strings.AlphanumComparator;\r
+\r
+/**\r
+ * Request for getting all variables of a model in a String array. Includes also \r
+ * variables inside modules.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class AllVariablesOfModel implements IAllVariablesOfModel{\r
+    \r
+    private final Resource model;\r
+    \r
+    public AllVariablesOfModel(Resource model) {\r
+        this.model = model;\r
+    }\r
+\r
+       @Override\r
+       public Read<Collection<ChartVariable>> getVariablesQuery() {\r
+               return new VariableQuery();\r
+       }   \r
+       \r
+       \r
+       @Override\r
+    public String getVariablesLabel(ReadGraph graph, String variableId)\r
+                       throws DatabaseException {\r
+                  return variableId.substring(1).replace('/', '.');\r
+       }\r
+    \r
+    private class VariableQuery implements Read<Collection<ChartVariable>> {\r
+        @Override\r
+           public Collection<ChartVariable> perform(ReadGraph graph) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SimulationResource simu = SimulationResource.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               List<ChartVariable> result = new ArrayList<ChartVariable>();\r
+               // Find the model of this resource\r
+               Resource model = AllVariablesOfModel.this.model;\r
+               while(model != null && !graph.isInstanceOf(model, sr.SysdynModel))\r
+                   model = graph.getPossibleObject(model, l0.PartOf);\r
+               \r
+               if(model == null)\r
+                   return result;;\r
+               \r
+               // Find the models configuration\r
+               Resource conf = graph.getSingleObject(model, simu.HasConfiguration);\r
+              \r
+               \r
+               // Recursively read all configurations and add items\r
+               ReadConfiguration(graph, conf, "", result);\r
+               \r
+               // Add time to the variable list\r
+               result.add(new ChartVariable("time", "time"));\r
+               \r
+               // Finally sort the results\r
+               Collections.sort(result, AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
+               return result;\r
+           }\r
+    }\r
+    \r
+    \r
+    \r
+    /**\r
+     * Read components in a configuration and recursively all module configurations\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param configuration Resource to be read\r
+     * @param path Current path from base realization\r
+     * @param items Found variables\r
+     * @throws DatabaseException\r
+     */\r
+    private void ReadConfiguration(ReadGraph graph, Resource configuration, String path, Collection<ChartVariable> items) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+\r
+        String name;\r
+        for(Resource resource : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.IndependentVariable))) {\r
+            name = path + NameUtils.getSafeName(graph, resource);\r
+            items.add(new ChartVariable(name, name));\r
+        }\r
+        \r
+        for(Resource resource : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Input))) {\r
+            name = path + NameUtils.getSafeName(graph, resource);\r
+            items.add(new ChartVariable(name, name));\r
+        }\r
+\r
+        for(Resource module : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {\r
+            Resource instanceOf = graph.getPossibleObject(module, l0.InstanceOf);\r
+            Resource conf = graph.getPossibleObject(instanceOf, sr2.IsDefinedBy);\r
+            if(conf != null) {\r
+                String p = path + NameUtils.getSafeName(graph, module)  + ".";\r
+                ReadConfiguration(graph, conf, p, items);\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/CategoryDataset.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/CategoryDataset.java
new file mode 100644 (file)
index 0000000..4a5f80f
--- /dev/null
@@ -0,0 +1,315 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import javax.swing.SwingUtilities;\r
+\r
+import org.jfree.chart.plot.DefaultDrawingSupplier;\r
+import org.jfree.chart.renderer.AbstractRenderer;\r
+import org.jfree.chart.renderer.category.BarRenderer;\r
+import org.jfree.data.category.DefaultCategoryDataset;\r
+import org.jfree.data.general.Dataset;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.request.PossibleActiveExperiment;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.AbstractDataset;\r
+import org.simantics.jfreechart.chart.IRenderer;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.Functions;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.adapter.VariableRVIUtils;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Class representing a JFreeChart.CategoryDataset\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class CategoryDataset extends AbstractDataset implements org.simantics.jfreechart.chart.CategoryDataset{\r
+\r
+    private List<Resource> seriesList;\r
+    private String realizationURI;\r
+    private IRenderer renderer;\r
+    private DefaultCategoryDataset dataset;\r
+\r
+    public CategoryDataset(ReadGraph graph, Resource resource) throws DatabaseException  {\r
+        super(graph, resource);\r
+\r
+       \r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            ModelingResources mr = ModelingResources.getInstance(graph);\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+            // Find the model where the chart is located\r
+            Resource model = resource;\r
+            do {\r
+                model = graph.getPossibleObject(model, l0.PartOf);\r
+            } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));\r
+\r
+            // Find the variable realization of the current experiment\r
+            realizationURI = null;\r
+            Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));\r
+            if (realization == null) {\r
+                Layer0X L0X = Layer0X.getInstance(graph);\r
+                realization = graph.getPossibleObject(model, L0X.HasBaseRealization);\r
+            }\r
+            if (realization != null)\r
+                realizationURI = graph.getURI(realization);\r
+\r
+            if(realizationURI == null)\r
+                return; // No experiment -> No results\r
+\r
+            Resource seriesList = graph.getPossibleObject(resource, jfree.Dataset_seriesList);\r
+            if(seriesList != null)\r
+                this.seriesList = ListUtils.toList(graph, seriesList);\r
+\r
+            Resource rendererResource = graph.getPossibleObject(resource, jfree.Dataset_renderer);\r
+            renderer = graph.adapt(rendererResource, IRenderer.class);\r
+\r
+       \r
+    }\r
+\r
+    private DatasetListener listener;\r
+\r
+    @Override\r
+    public Dataset getDataset() {\r
+\r
+        if(seriesList == null || seriesList.isEmpty() || SimanticsUI.getSession() == null)\r
+            return null;\r
+\r
+        if(dataset == null) {\r
+            dataset = new DefaultCategoryDataset();\r
+        }\r
+\r
+        if(listener == null || listener.isDisposed()) {\r
+            listener = new DatasetListener();\r
+            SimanticsUI.getSession().asyncRequest(new Read<ArrayList<TempSeries>>() {\r
+\r
+                @Override\r
+                public ArrayList<TempSeries> perform(ReadGraph graph) throws DatabaseException {\r
+                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+                    ArrayList<TempSeries> series = new ArrayList<TempSeries>();\r
+                    // Get properties for all series\r
+                    if(seriesList != null) {\r
+                        for(Resource r : seriesList) {\r
+                            String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);\r
+                            if(rvi == null)\r
+                                continue;\r
+\r
+                            try {\r
+                                // Get a variable for the series\r
+                                Variable v = Variables.getVariable(graph, realizationURI + rvi);\r
+                                // Get values\r
+                                Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
+                                if(dsVariable == null)\r
+                                       return series;\r
+                                \r
+                                Object object = dsVariable.getValue(graph);\r
+                                \r
+                                if(object == null || !(object instanceof ArrayList<?>))\r
+                                    return series;\r
+\r
+                                ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
+\r
+                                for(Object o : (ArrayList<?>)object) {\r
+                                    if(o instanceof SysdynDataSet)\r
+                                        datasets.add((SysdynDataSet)o);\r
+                                }\r
+\r
+                                String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter);\r
+                                if(filter != null) {\r
+                                    ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);\r
+                                    if(result2 != null) {\r
+                                        datasets = result2;\r
+                                    }\r
+                                }\r
+\r
+                                // Find if a specific time is set for this chart\r
+                                Double chartTime = null;\r
+                                if(!datasets.isEmpty()) {\r
+                                    Layer0 l0 = Layer0.getInstance(graph);\r
+                                    Resource datasetResource = graph.getPossibleObject(r, l0.PartOf);\r
+                                    if(datasetResource != null) {\r
+                                        Resource plot = graph.getPossibleObject(datasetResource, l0.PartOf);\r
+                                        if(plot != null) {\r
+                                            Resource chart = graph.getPossibleObject(plot, l0.PartOf);\r
+                                            if(chart != null)\r
+                                                chartTime = graph.getPossibleRelatedValue(chart, jfree.Chart_time);\r
+                                        }\r
+                                    }\r
+                                }\r
+\r
+                                for(SysdynDataSet dataset : datasets) {\r
+                                    double[] va = dataset.values;\r
+\r
+\r
+                                    if(va == null || va.length == 0)\r
+                                        continue;\r
+\r
+                                    /*\r
+                                     *  Time\r
+                                     *  \r
+                                     *  1. find time for the individual series.\r
+                                     *  2. find time for the whole chart\r
+                                     *  3. find simulation time\r
+                                     */\r
+                                    Double time = graph.getPossibleRelatedValue(r, jfree.Series_time, Bindings.DOUBLE);\r
+                                    if(time == null)\r
+                                        time = chartTime;\r
+                                    if(time == null) {\r
+                                        // Get a variable for the experiment run\r
+                                        Variable run = Variables.getVariable(graph, realizationURI);\r
+                                        if(run == null)\r
+                                            return null;\r
+                                        Variable timeVar = run.browsePossible(graph, "#" + Functions.TIME + "#");\r
+                                        if(timeVar != null)\r
+                                            time = timeVar.getValue(graph, Bindings.DOUBLE);\r
+            \r
+                                    }\r
+\r
+                                    // Value\r
+                                    Double value = null;\r
+                                    if(time == null) {\r
+                                        value = va[va.length - 1];\r
+                                    } else {\r
+                                        double[] ta = dataset.times;\r
+                                        for(int i = 0; i < ta.length; i++) {\r
+                                            double t = ta[i];\r
+                                            if(time <= t) {\r
+                                                value = va[i]; \r
+                                                break;\r
+                                            }\r
+                                        }\r
+\r
+                                        if(value == null)\r
+                                            value = va[va.length - 1];\r
+                                    }\r
+                                    String label = graph.getPossibleRelatedValue(r, Layer0.getInstance(graph).HasLabel); // Called to refresh paints when label changes\r
+                                    String name = label == null || label.isEmpty() ? dataset.name : label;\r
+                                    if (dataset.resultIndex != null) {\r
+                                       name += "(" + dataset.resultIndex + ")"; \r
+                                    }\r
+                                    series.add(new TempSeries(name, dataset.result, value));\r
+                                }\r
+                            } catch (MissingVariableException e) {\r
+                                // Do nothing, if variable was not found. Move on to the next series\r
+                            }\r
+                        }\r
+                    }\r
+                    return series;\r
+                }\r
+\r
+            }, listener);\r
+        }\r
+        return dataset;\r
+    }\r
+\r
+    @Override\r
+    public AbstractRenderer getRenderer() {\r
+        return renderer.getRenderer();\r
+    }\r
+\r
+    private class DatasetListener implements Listener<ArrayList<TempSeries>> {\r
+        private boolean disposed = false;\r
+\r
+        public void dispose() {\r
+            disposed = true;\r
+        }\r
+\r
+        @Override\r
+        public void execute(final ArrayList<TempSeries> series) {\r
+            // Modify series in AWT thread to avoid synchronization problems\r
+            SwingUtilities.invokeLater(new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+                    // Remove all unused series\r
+                    dataset.clear();\r
+                    BarRenderer renderer = ((BarRenderer)getRenderer());\r
+                    renderer.getPlot().setDrawingSupplier(new DefaultDrawingSupplier());\r
+\r
+                    // Add found series\r
+                    for(int i = 0; i < series.size(); i++) {\r
+                        TempSeries s = series.get(i);\r
+                        if(renderer instanceof org.jfree.chart.renderer.category.StackedBarRenderer && s.name.contains("[")) {\r
+                            String category = s.name.substring(0, s.name.indexOf('['));\r
+                            if(s.result != null)\r
+                                category = category + " : " + s.result;\r
+                            String series = s.name.substring(s.name.indexOf('['));\r
+                            dataset.addValue(s.value, series, category);\r
+                        } else {\r
+                            dataset.addValue(s.value, s.result == null ? "Current" : s.result, s.name);\r
+                        }\r
+                    }\r
+                }\r
+            });\r
+        }\r
+\r
+        @Override\r
+        public void exception(Throwable t) {\r
+            t.printStackTrace();\r
+        }\r
+\r
+        @Override\r
+        public boolean isDisposed() {\r
+            return disposed;\r
+        }\r
+    };\r
+\r
+    @Override\r
+    public void dispose() {\r
+        super.dispose();\r
+        if(listener != null) {\r
+            listener.dispose();\r
+            listener = null;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Auxiliary class containing all information needed to define a single series\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class TempSeries {\r
+        public String name;\r
+        public String result;\r
+        public Double value;\r
+\r
+        public TempSeries(String name, String result, Double value) {\r
+            this.name = name;\r
+            this.value = value;\r
+            this.result = result;\r
+        }\r
+\r
+        @Override\r
+        public String toString() {\r
+            return "TempSeries: " + name + ", " + value + ", " + result;\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBound.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBound.java
new file mode 100644 (file)
index 0000000..1dc7869
--- /dev/null
@@ -0,0 +1,46 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.awt.Color;\r
+\r
+/**\r
+ * Container class for confidence bound properties\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ConfidenceBound implements Comparable<ConfidenceBound> {\r
+    \r
+    private double percent;\r
+    private Color color;\r
+    \r
+    public ConfidenceBound(double percent, Color color) {\r
+        this.percent = percent;\r
+        this.color = color;\r
+    }\r
+    \r
+    public double getPercent() {\r
+        return percent;\r
+    }\r
+    \r
+    public Color getColor() {\r
+        return color;\r
+    }\r
+\r
+    @Override\r
+    public int compareTo(ConfidenceBound other) {\r
+        return Double.compare(percent, other.getPercent());\r
+//        return Double.compare(other.getPercent(), percent);\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBoundWidget.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBoundWidget.java
new file mode 100644 (file)
index 0000000..b7d009b
--- /dev/null
@@ -0,0 +1,116 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.properties.ColorPicker;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+import org.simantics.utils.ui.validators.DoubleValidator;\r
+\r
+/**\r
+ * Widget for setting percentage and color for a confidence bound\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ConfidenceBoundWidget extends Composite implements Widget {\r
+\r
+    private WidgetSupportImpl confidenceBoundSupport;\r
+    private int index;\r
+    \r
+    public ConfidenceBoundWidget(Composite parent, ISessionContext context, WidgetSupport support, int style, int index) {\r
+        super(parent, style);\r
+        this.index = index;\r
+        \r
+        support.register(this);\r
+        \r
+        GridLayoutFactory.fillDefaults().applyTo(this);\r
+        \r
+        confidenceBoundSupport = new WidgetSupportImpl();\r
+        \r
+        ColorPicker colorPicker = new ColorPicker(this, context, confidenceBoundSupport, SWT.NONE, false) {\r
+            @Override\r
+            protected Resource getColorRelation(ReadGraph graph) throws DatabaseException {\r
+                return SysdynResource.getInstance(graph).Charts_SensitivityDataset_ConfidenceBound_color;\r
+            }\r
+        };\r
+        GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.BEGINNING).applyTo(colorPicker);\r
+        \r
+        TrackedText variable = new TrackedText(this, confidenceBoundSupport, SWT.BORDER);\r
+        variable.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.Charts_SensitivityDataset_ConfidenceBound_percent));\r
+        variable.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.Charts_SensitivityDataset_ConfidenceBound_percent));\r
+        variable.setColorProvider(new SysdynBasicColorProvider(variable.getResourceManager()));\r
+        variable.setInputValidator(new DoubleValidator() {\r
+            public String isValid(String newText) {\r
+                if(newText == null || newText.isEmpty())\r
+                    return null;\r
+                else\r
+                    return super.isValid(newText);\r
+            }\r
+\r
+        });\r
+        GridDataFactory.fillDefaults().hint(27, SWT.DEFAULT).align(SWT.CENTER, SWT.CENTER).applyTo(variable.getWidget());\r
+    }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        try {\r
+            Resource confidenceBound = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                @Override\r
+                public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                    return getResource(graph, resource);\r
+                }\r
+                \r
+            });\r
+            \r
+            if(confidenceBound != null)\r
+                confidenceBoundSupport.fireInput(context, new StructuredSelection(confidenceBound));\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    private Resource getResource(ReadGraph graph, Resource input) throws DatabaseException {\r
+        Resource dataset = graph.getPossibleObject(input, Layer0.getInstance(graph).PartOf);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        Resource confidenceBoundsList = graph.getPossibleObject(dataset, SR.Charts_SensitivityDataset_confidenceBounds);\r
+        if(confidenceBoundsList == null)\r
+            return null;\r
+        List<Resource> confidenceBounds = ListUtils.toList(graph, confidenceBoundsList);\r
+        return confidenceBounds.get(index);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PieDataset.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PieDataset.java
new file mode 100644 (file)
index 0000000..81d7310
--- /dev/null
@@ -0,0 +1,333 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.awt.Color;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+\r
+import javax.swing.SwingUtilities;\r
+\r
+import org.jfree.chart.renderer.AbstractRenderer;\r
+import org.jfree.data.general.Dataset;\r
+import org.jfree.data.general.DefaultPieDataset;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.request.PossibleActiveExperiment;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.jfreechart.chart.AbstractDataset;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.Functions;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.adapter.VariableRVIUtils;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Class representing a PieDataset in JFreeChart ontology\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class PieDataset extends AbstractDataset implements org.simantics.jfreechart.chart.PieDataset<String> {\r
+\r
+    private List<Resource> seriesList;\r
+    private String realizationURI;\r
+    private DefaultPieDataset dataset;\r
+\r
+    private HashMap<String, Color> colorMap;\r
+    private HashMap<String, Boolean> explodedMap;\r
+\r
+    public PieDataset(ReadGraph graph, Resource resource) throws DatabaseException {\r
+        super(graph, resource);\r
+\r
+       \r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            ModelingResources mr = ModelingResources.getInstance(graph);\r
+            JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+            // Find the model where the chart is located\r
+            Resource model = resource;\r
+            do {\r
+                model = graph.getPossibleObject(model, l0.PartOf);\r
+            } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));\r
+\r
+            // Find the variable realization of the current experiment\r
+            realizationURI = null;\r
+            Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));\r
+            if (realization == null) {\r
+                Layer0X L0X = Layer0X.getInstance(graph);\r
+                realization = graph.getPossibleObject(model, L0X.HasBaseRealization);\r
+            }\r
+            if (realization != null)\r
+                realizationURI = graph.getURI(realization);\r
+\r
+            if(realizationURI == null)\r
+                return; // No experiment -> No results\r
+\r
+            Resource seriesList = graph.getPossibleObject(resource, jfree.Dataset_seriesList);\r
+            if(seriesList != null) {\r
+                this.seriesList = ListUtils.toList(graph, seriesList);\r
+            }\r
+        \r
+\r
+    }\r
+\r
+    /**\r
+     * Map of colors for different slices in a pie chart. Name \r
+     * indicates the key of the value.\r
+     * @return  Map of colors for different slices in a pie chart\r
+     */\r
+    public HashMap<String, Color> getColorMap() {\r
+        return colorMap;\r
+    }\r
+\r
+    /**\r
+     * Map of exploded statuses for slices in a pie chart. Name\r
+     * indicates the key of the slice.\r
+     * @return\r
+     */\r
+    public HashMap<String, Boolean> getExplodedMap() {\r
+        return explodedMap;\r
+    }\r
+\r
+    @Override\r
+    public Dataset getDataset() {\r
+        if(seriesList == null || seriesList.isEmpty() ||  SimanticsUI.getSession() == null)\r
+            return null;\r
+\r
+        if(dataset == null) {\r
+            dataset = new DefaultPieDataset();\r
+        }\r
+\r
+        if(listener == null) {\r
+            listener = new DatasetListener();\r
+            SimanticsUI.getSession().asyncRequest(new Read<ArrayList<TempSeries>>() {\r
+\r
+                @Override\r
+                public ArrayList<TempSeries> perform(ReadGraph graph) throws DatabaseException {\r
+                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+                    ArrayList<TempSeries> series = new ArrayList<TempSeries>();\r
+                    // Get properties for all series\r
+                    if(seriesList != null) {\r
+\r
+                        colorMap = new HashMap<String, Color>();\r
+                        explodedMap = new HashMap<String, Boolean>();\r
+\r
+                        for(Resource r : seriesList) {\r
+                            String label = graph.getPossibleRelatedValue(r, Layer0.getInstance(graph).HasLabel);\r
+                            String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);\r
+                            if(rvi == null)\r
+                                continue;\r
+\r
+                            try {\r
+                                // Get visual properties\r
+                                Resource c = graph.getPossibleObject(r, jfree.color);\r
+                                Color color = c == null ? null : G2DUtils.getColor(graph, c);\r
+                                Boolean exploded = graph.getPossibleRelatedValue(r, jfree.Series_exploded, Bindings.BOOLEAN);\r
+\r
+                                // Get a variable for the series\r
+                                Variable v = Variables.getVariable(graph, realizationURI + rvi);\r
+\r
+                                // Get values\r
+                                Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
+                                if(dsVariable == null)\r
+                                       return series;\r
+                                \r
+                                Object object = dsVariable.getValue(graph);\r
+                                if(object == null || !(object instanceof ArrayList<?>))\r
+                                    return series;\r
+\r
+                                ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
+\r
+                                for(Object o : (ArrayList<?>)object) {\r
+                                    if(o instanceof SysdynDataSet)\r
+                                        datasets.add((SysdynDataSet)o);\r
+                                }\r
+\r
+                                String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter);\r
+                                if(filter != null) {\r
+                                    ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);\r
+                                    if(result2 != null) {\r
+                                        datasets = result2;\r
+                                    }\r
+                                }\r
+\r
+                                // Find if a specific time is set for this chart\r
+                                Double chartTime = null;\r
+                                if(!datasets.isEmpty()) {\r
+                                    Layer0 l0 = Layer0.getInstance(graph);\r
+                                    Resource datasetResource = graph.getPossibleObject(r, l0.PartOf);\r
+                                    if(datasetResource != null) {\r
+                                        Resource plot = graph.getPossibleObject(datasetResource, l0.PartOf);\r
+                                        if(plot != null) {\r
+                                            Resource chart = graph.getPossibleObject(plot, l0.PartOf);\r
+                                            if(chart != null)\r
+                                                chartTime = graph.getPossibleRelatedValue(chart, jfree.Chart_time);\r
+                                        }\r
+                                    }\r
+                                }\r
+                                \r
+                                for(SysdynDataSet dataset : datasets) {\r
+                                    double[] va = dataset.values;\r
+\r
+                                    if(va == null || va.length == 0)\r
+                                        continue;\r
+\r
+                                    /*\r
+                                     *  Time\r
+                                     *  \r
+                                     *  1. find time for the individual series.\r
+                                     *  2. find time for the whole chart\r
+                                     *  3. find simulation time\r
+                                     */\r
+                                    Double time = graph.getPossibleRelatedValue(r, jfree.Series_time, Bindings.DOUBLE);\r
+                                    if(time == null)\r
+                                        time = chartTime;\r
+                                    if(time == null) {\r
+                                        // Get a variable for the experiment run\r
+                                        Variable run = Variables.getVariable(graph, realizationURI);\r
+                                        if(run == null)\r
+                                            return null;\r
+                                        Variable timeVar = run.browsePossible(graph, "#" + Functions.TIME + "#");\r
+                                        if(timeVar != null)\r
+                                            time =  timeVar.getValue(graph, Bindings.DOUBLE);\r
+                                    }\r
+                                    \r
+                                    // Value\r
+                                    Double value = null;\r
+                                    if(time == null) {\r
+                                        value = va[va.length - 1];\r
+                                    } else {\r
+                                        double[] ta = dataset.times;\r
+                                        for(int i = 0; i < ta.length; i++) {\r
+                                            double t = ta[i];\r
+                                            if(time <= t) {\r
+                                                value = va[i]; \r
+                                                break;\r
+                                            }\r
+                                        }\r
+\r
+                                        if(value == null)\r
+                                            value = va[va.length - 1];\r
+                                    }\r
+\r
+                                    String name = label == null || label.isEmpty() ? dataset.name : label;\r
+                                    if (dataset.resultIndex != null) {\r
+                                       name += "(" + dataset.resultIndex + ")"; \r
+                                    }\r
+                                    if(dataset.result != null)\r
+                                        name = name + " : " + dataset.result; \r
+                                    colorMap.put(name, color);\r
+                                    explodedMap.put(name, exploded);\r
+                                    series.add(new TempSeries(name, value));\r
+                                }\r
+                            } catch (MissingVariableException e) {\r
+                                // Do nothing, if variable was not found. Move on to the next series\r
+                            }\r
+                        }\r
+                    }\r
+                    return series;\r
+                }\r
+\r
+            }, listener);\r
+        }\r
+        return dataset;\r
+    }\r
+\r
+    private DatasetListener listener;\r
+\r
+    private class DatasetListener implements Listener<ArrayList<TempSeries>> {\r
+\r
+        private boolean disposed = false;\r
+\r
+        @Override\r
+        public void execute(final ArrayList<TempSeries> series) {\r
+            // Modify series in AWT thread to avoid synchronization problems\r
+            SwingUtilities.invokeLater(new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+                    // Remove all series\r
+                    dataset.clear();\r
+\r
+                    // Add found series\r
+                    for(int i = 0; i < series.size(); i++) {\r
+                        TempSeries s = series.get(i);\r
+                        dataset.setValue(s.name, s.value);\r
+                    }\r
+                }\r
+            });\r
+        }\r
+\r
+        @Override\r
+        public void exception(Throwable t) {\r
+            t.printStackTrace();\r
+        }\r
+\r
+        @Override\r
+        public boolean isDisposed() {\r
+            return disposed;\r
+        }\r
+\r
+        public void dispose() {\r
+            disposed = true;\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public AbstractRenderer getRenderer() {\r
+        // No renderer for pie chart\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        super.dispose();\r
+        if(listener != null) {\r
+            listener.dispose();\r
+            listener = null;\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * Auxiliary class containing all information needed to define a single series\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class TempSeries {\r
+        public String name;\r
+        public Double value;\r
+\r
+        public TempSeries(String name, Double value) {\r
+            this.name = name;\r
+            this.value = value;\r
+        }\r
+\r
+        @Override\r
+        public String toString() {\r
+            return "TempSeries: " + name + ", " + value;\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PinTrend.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PinTrend.java
new file mode 100644 (file)
index 0000000..a350998
--- /dev/null
@@ -0,0 +1,47 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.Command;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.commands.State;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.commands.ICommandService;\r
+\r
+\r
+public class PinTrend extends AbstractHandler {\r
+\r
+    public static final String COMMAND = "org.simantics.sysdyn.ui.trend.view.pin";\r
+    public static final String STATE = "org.simantics.sysdyn.ui.trend.view.pin.state";\r
+    \r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = service.getCommand(COMMAND);\r
+        State state = command.getState(STATE);\r
+        Boolean value = (Boolean) state.getValue();\r
+        value = !value;\r
+        state.setValue(value);\r
+\r
+        return null;\r
+    }\r
+    \r
+    public static Boolean getState() {\r
+        ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
+        Command command = service.getCommand(COMMAND);\r
+        State state = command.getState(STATE);\r
+        return (Boolean)state.getValue();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityChartAxisAndVariablesTab.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityChartAxisAndVariablesTab.java
new file mode 100644 (file)
index 0000000..ab53b0f
--- /dev/null
@@ -0,0 +1,161 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.ScrolledComposite;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.graphics.Point;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
+import org.simantics.jfreechart.chart.properties.xyline.AxisPropertyComposite;\r
+import org.simantics.jfreechart.chart.properties.xyline.SeriesPropertyComposite;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class SensitivityChartAxisAndVariablesTab extends AdjustableTab {\r
+\r
+    private GraphExplorerComposite explorer;\r
+    private ScrolledComposite propertyContainer;\r
+    private WidgetSupportImpl additionalSupport;\r
+\r
+    public SensitivityChartAxisAndVariablesTab() {\r
+        additionalSupport = new WidgetSupportImpl();\r
+    }\r
+\r
+    /**\r
+     * Updates the content of propertyContainer  \r
+     * @param context\r
+     */\r
+    private void updateSelection(ISessionContext context) {\r
+        ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
+        IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
+        final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+\r
+        // Get the type of the selected node (axis or series)\r
+        String typeUri = null;\r
+        try {\r
+            typeUri = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                @Override\r
+                public String perform(ReadGraph graph) throws DatabaseException {\r
+                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                    if(graph.isInstanceOf(resource, jfree.Axis))\r
+                        return graph.getURI(jfree.Axis);\r
+                    else if (graph.isInstanceOf(resource, jfree.Series))\r
+                        return graph.getURI(jfree.Series);\r
+                    return null;\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        // Create a PropertyComposite for the selected node\r
+        if(typeUri != null) {\r
+\r
+            for(Control child : propertyContainer.getChildren()) {\r
+                child.dispose();\r
+            }\r
+\r
+            if(typeUri.equals(JFreeChartResource.URIs.Axis)) {\r
+                AxisPropertyComposite apc = new AxisPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE, isVertical());\r
+                propertyContainer.setContent(apc);\r
+                Point size = apc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+                propertyContainer.setMinSize(size);\r
+            } else if(typeUri.equals(JFreeChartResource.URIs.Series)) {\r
+                SeriesPropertyComposite spc = new SensitivitySeriesPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE);\r
+                propertyContainer.setContent(spc);\r
+                Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
+                propertyContainer.setMinSize(size);\r
+            }\r
+        }\r
+\r
+        additionalSupport.fireInput(context, selection);\r
+    }\r
+\r
+       @Override\r
+       protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
+                       final ISessionContext context, WidgetSupport support) {\r
+               composite = new Composite(body, SWT.NONE);\r
+\r
+        // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis\r
+        explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
+                "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
+        explorer.setBrowseContexts(JFreeChartResource.URIs.ChartAxisAndVariablesBrowseContext);\r
+        explorer.setInputSource(new SingleSelectionInputSource(\r
+                Resource.class));\r
+        explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
+        explorer.finish();\r
+\r
+        ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
+            public void widgetSelected(SelectionEvent e) {\r
+                updateSelection(context);\r
+            }\r
+        });\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
+        propertyContainer.setExpandHorizontal(true);\r
+        propertyContainer.setExpandVertical(true);\r
+\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutVertical() {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().hint(220, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().span(1, 1).hint(SWT.DEFAULT, 210).grab(true, false).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+       }\r
+\r
+       @Override\r
+       protected void createControlLayoutHorizontal(boolean wideScreen) {\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
+\r
+        GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
+\r
+        // Scrolled composite for displaying properties of a selection in explorer\r
+        GridDataFactory.fillDefaults().span(1, 2).hint(SWT.DEFAULT, SWT.DEFAULT).grab(true, true).applyTo(propertyContainer);\r
+        GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDataset.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDataset.java
new file mode 100644 (file)
index 0000000..c4aba21
--- /dev/null
@@ -0,0 +1,292 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import javax.swing.SwingUtilities;\r
+\r
+import org.jfree.chart.LegendItem;\r
+import org.jfree.chart.renderer.AbstractRenderer;\r
+import org.jfree.chart.renderer.xy.DeviationRenderer;\r
+import org.jfree.data.general.Dataset;\r
+import org.jfree.data.xy.YIntervalSeries;\r
+import org.jfree.data.xy.YIntervalSeriesCollection;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.procedure.adapter.DisposableListener;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.jfreechart.chart.IRenderer;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * Dataset for sensitivity analysis fan charts.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SensitivityDataset extends XYDataset {\r
+\r
+    DeviationRenderer renderer;\r
+    \r
+    public SensitivityDataset(ReadGraph graph, Resource resource) throws DatabaseException {\r
+        super(graph, resource);\r
+    }\r
+\r
+    @SuppressWarnings("unchecked")\r
+    @Override\r
+    public Dataset getDataset() {\r
+        if(dataset == null) {\r
+            dataset = new YIntervalSeriesCollection();\r
+        }   \r
+\r
+        if(datasetListener == null || datasetListener.isDisposed()) {\r
+            datasetListener = new SensitivityDatasetListener();\r
+            SimanticsUI.getSession().asyncRequest(\r
+                    new SensitivityDatasetRequest(resource), \r
+                    (DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>>) datasetListener); \r
+        }\r
+\r
+        if(timeListener == null || timeListener.isDisposed()) {\r
+            SimanticsUI.getSession().asyncRequest(getTimeRequest(), getTimeListener());\r
+        }\r
+        return dataset;\r
+    }\r
+    \r
+    /**\r
+     * SensitivityDatasetRequest uses {@link XYDatasetRequest} to get values for all sensitivity analysis runs.\r
+     * \r
+     * In addition, the request finds fan chart properties from dataset resource and passes them to {@link SensitivityDatasetListener}\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class SensitivityDatasetRequest implements Read<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>> {\r
+\r
+        private Resource dataset;\r
+        \r
+        public SensitivityDatasetRequest(Resource dataset) {\r
+            this.dataset = dataset;\r
+        }\r
+        \r
+        @Override\r
+        public Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> perform(ReadGraph graph) throws DatabaseException {\r
+            \r
+            Pair<ArrayList<XYDatasetTempSeries>, IRenderer> XYDatasetRequestResult = graph.syncRequest(new XYDatasetRequest(dataset));\r
+            \r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+            Boolean median = graph.getPossibleRelatedValue(dataset, SR.Charts_SensitivityDataset_median);\r
+            if (median == null)\r
+               median = false;\r
+            \r
+            Resource confidenceBoundsList = graph.getPossibleObject(dataset, SR.Charts_SensitivityDataset_confidenceBounds);\r
+            ArrayList<ConfidenceBound> confidenceBounds = new ArrayList<ConfidenceBound>();\r
+\r
+            if(confidenceBoundsList != null) {\r
+                List<Resource> confidenceBoundResources = ListUtils.toList(graph, confidenceBoundsList);\r
+\r
+                for(Resource cb : confidenceBoundResources) {\r
+                    Double percent = graph.getPossibleRelatedValue(cb, SR.Charts_SensitivityDataset_ConfidenceBound_percent);\r
+                    Resource c = graph.getPossibleObject(cb, SR.Charts_SensitivityDataset_ConfidenceBound_color);\r
+                    Color color = c == null ? null : G2DUtils.getColor(graph, c);\r
+                    if(percent != null && color != null)\r
+                        confidenceBounds.add(new ConfidenceBound(percent, color));\r
+                }\r
+            }\r
+            \r
+            SensitivityDatasetProperties properties = new SensitivityDatasetProperties(median, confidenceBounds);\r
+            \r
+            return new Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> (XYDatasetRequestResult.first, properties);\r
+        }\r
+        \r
+    }\r
+\r
+    @Override\r
+    public AbstractRenderer getRenderer() {\r
+        if(renderer == null)\r
+            renderer = new DeviationRenderer(true, false) {\r
+            private static final long serialVersionUID = 633310754812851862L;\r
+\r
+            /* \r
+             * Overridden getLegendElement to provide thick lines for legend.\r
+             */\r
+            @Override\r
+            public LegendItem getLegendItem(int datasetIndex, int series) {\r
+                LegendItem item = super.getLegendItem(datasetIndex, series);\r
+                return new LegendItem(item.getLabel(), item.getDescription(), item.getToolTipText(), item.getURLText(), item.getLine(), new BasicStroke(5F), item.getLinePaint());\r
+            }\r
+        };\r
+        return renderer;\r
+    }\r
+    \r
+    /**\r
+     * SensitivityDatasetListener calculates confidence bounds from all sensitivity analysis run results.\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    private class SensitivityDatasetListener extends DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>> {\r
+\r
+        @Override\r
+        public void execute(Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> result) {\r
+            final ArrayList<XYDatasetTempSeries> series = result.first;\r
+            final SensitivityDatasetProperties properties = result.second;\r
+            \r
+            // Modify series in AWT thread to avoid synchronization problems\r
+            SwingUtilities.invokeLater(new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+\r
+                    if(dataset == null || !(dataset instanceof YIntervalSeriesCollection))\r
+                        return;\r
+                    \r
+                    YIntervalSeriesCollection ds = (YIntervalSeriesCollection)dataset;\r
+\r
+                    DeviationRenderer dr = (DeviationRenderer)getRenderer();\r
+                    \r
+                    ArrayList<ConfidenceBound> confidenceBounds = properties.getConfidenceBounds();\r
+\r
+                    \r
+                    // CONFIDENCE BOUND PAINTS\r
+                    for(int i = 1; i <= confidenceBounds.size(); i++) {\r
+                        dr.setSeriesStroke(i, new BasicStroke(0F));\r
+                        dr.setSeriesPaint(i, confidenceBounds.get(i-1).getColor());\r
+                        dr.setSeriesFillPaint(i, confidenceBounds.get(i-1).getColor());\r
+                    }\r
+                    \r
+                    Color medianColor = Color.RED;\r
+                    // MEDIAN PAINTS\r
+                    dr.setSeriesStroke(0, new BasicStroke(2F));\r
+                    dr.setSeriesPaint(0, medianColor);\r
+                    dr.setSeriesFillPaint(0, medianColor);\r
+                    dr.setSeriesVisibleInLegend(0, true);\r
+\r
+                    \r
+                    if(!properties.displayMedian()) {\r
+                        /*\r
+                         *  Median is in the first index position. If it\r
+                         *  is not visible, make it the same color as\r
+                         *  the next series and hide it from legend\r
+                         */\r
+                        dr.setSeriesVisibleInLegend(0, false);\r
+                        dr.setSeriesPaint(0, dr.getSeriesPaint(1));\r
+                    }\r
+                    \r
+                    dr.setAlpha(1);\r
+                    \r
+                    // Remove all series\r
+                    for(int i = ds.getSeriesCount() - 1; i >= 0; i-- ) {\r
+                        ds.removeSeries(ds.getSeries(i));\r
+                    }\r
+                    \r
+                    int n = series.size();\r
+                    if(n < 1)\r
+                        return;\r
+                    \r
+                    int length = series.get(0).values[0].length;\r
+                    \r
+                    \r
+                    YIntervalSeries median = new YIntervalSeries("Median");\r
+                    \r
+                    YIntervalSeries[] yIntervalSeries = new YIntervalSeries[confidenceBounds.size()];\r
+                    for(int i = 0; i < confidenceBounds.size(); i++) {\r
+                        yIntervalSeries[i] = new YIntervalSeries(confidenceBounds.get(i).getPercent() + "%");\r
+                    }\r
+\r
+                    ArrayList<Double> sorter = new ArrayList<Double>();\r
+                    for(int i = 0; i < length; i++) {\r
+                        sorter.clear();\r
+                        for(int j = 0; j < n; j++) {\r
+                            if(series.get(j).values[1].length == 0)\r
+                                continue; // If there are no values, move on to next dataset\r
+                            sorter.add(series.get(j).values[1][i]); // values is a two-dimensional array. 0 dimension == times, 1 == values\r
+                        }\r
+                        Collections.sort(sorter);\r
+                        \r
+                        int sorterSize = sorter.size();\r
+                        int intervals = sorterSize - 1;\r
+                       \r
+                        // MEDIAN\r
+                        double medianX = series.get(0).values[0][i];\r
+                        double medianY = sorter.get(sorterSize/2);\r
+                        median.add(\r
+                                       medianX, \r
+                                medianY,\r
+                                medianY,\r
+                                medianY\r
+                                );\r
+\r
+                        // CONFIDENCE BOUNDS\r
+                        for(int j = 0; j < yIntervalSeries.length; j++) {\r
+                               YIntervalSeries yis = yIntervalSeries[j];\r
+                            double percent = properties.getConfidenceBounds().get(j).getPercent() / 100;\r
+                            if(n >= (1 / percent) * 2) {\r
+                               // Estimate the confidence limits\r
+                               double indexLow = (1 - percent) * intervals / 2;\r
+                               int indexLowLow = (int)Math.floor(indexLow);\r
+                               int indexLowHigh = (int)Math.ceil(indexLow);\r
+                               double valueLowLow = sorter.get(indexLowLow);\r
+                               double valueLowHigh = sorter.get(indexLowHigh);\r
+                               double decimalLow = indexLow - indexLowLow;\r
+                               // Linear interpolation; to decrease execution time, use interpolation of degree 0, \r
+                               // but I didn't find the current approach too time consuming in a simple test. \r
+                               double estimateLow = (valueLowHigh - valueLowLow) * decimalLow + valueLowLow;\r
+                               \r
+                               double indexHigh = (1 + percent) * intervals / 2;;\r
+                               int indexHighLow = (int)Math.floor(indexHigh);\r
+                               int indexHighHigh = (int)Math.ceil(indexHigh);\r
+                               double valueHighLow = sorter.get(indexHighLow);\r
+                               double valueHighHigh = sorter.get(indexHighHigh);\r
+                               double decimalHigh = 1 - decimalLow;  \r
+                               double estimateHigh = (valueHighHigh - valueHighLow) * decimalHigh + valueHighLow;\r
+                               yis.add(\r
+                                               medianX, \r
+                                               medianY,\r
+                                               estimateLow,\r
+                                               estimateHigh\r
+                                               );\r
+                            }\r
+                        }\r
+                    }\r
+                    \r
+                    // ADD MEDIAN\r
+                    ds.addSeries(median);\r
+                    \r
+                    // ADD OTHERS\r
+                    // CONFIDENCE BOUNDS\r
+                    for(int j = 0; j < yIntervalSeries.length; j++) {\r
+                        YIntervalSeries yis = yIntervalSeries[j];\r
+                        double percent = properties.getConfidenceBounds().get(j).getPercent();\r
+                        if(n >= (1 / percent) * 2)\r
+                            ds.addSeries(yis);\r
+                    }\r
+                }\r
+            });\r
+        }\r
+\r
+        @Override\r
+        public void exception(Throwable t) {\r
+            t.printStackTrace();\r
+        }\r
+\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDatasetProperties.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDatasetProperties.java
new file mode 100644 (file)
index 0000000..a216b52
--- /dev/null
@@ -0,0 +1,37 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+\r
+public class SensitivityDatasetProperties {\r
+    \r
+    private boolean median;\r
+    private ArrayList<ConfidenceBound> confidenceBounds;\r
+    \r
+    public SensitivityDatasetProperties(boolean median, ArrayList<ConfidenceBound> confidenceBounds) {\r
+        this.median = median;\r
+        this.confidenceBounds = new ArrayList<ConfidenceBound>(confidenceBounds);\r
+        Collections.sort(this.confidenceBounds);\r
+    }\r
+    \r
+    public boolean displayMedian() {\r
+        return median;\r
+    }\r
+    \r
+    public ArrayList<ConfidenceBound> getConfidenceBounds() {\r
+        return confidenceBounds;\r
+    }\r
+    \r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivitySeriesPropertyComposite.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivitySeriesPropertyComposite.java
new file mode 100644 (file)
index 0000000..4be6de7
--- /dev/null
@@ -0,0 +1,107 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.jfreechart.chart.properties.xyline.SeriesPropertyComposite;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * UI for setting properties for sensitivity analysis series. Sensitivity analysis \r
+ * charts display only one variable as a "fan" chart.\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SensitivitySeriesPropertyComposite extends SeriesPropertyComposite {\r
+\r
+    public SensitivitySeriesPropertyComposite(Composite parent, ISessionContext context, WidgetSupport support,\r
+            int style) {\r
+        super(parent, context, support, style);\r
+    }\r
+\r
+    @Override\r
+    protected void createContent(ISessionContext context, WidgetSupport support) {\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(this);\r
+\r
+        // Variable for the series\r
+        variable(this, context, support);\r
+\r
+        // Range\r
+        range(this, context, support);\r
+\r
+        // Label to be displayed in chart for this series \r
+//        seriesLabel(this, context, support);\r
+        \r
+        Button validateUnits = new Button(this, support, SWT.CHECK);\r
+        validateUnits.setText("Display median");\r
+        GridDataFactory.fillDefaults().span(2, 1).applyTo(validateUnits.getWidget());\r
+        validateUnits.setSelectionFactory(new ReadFactoryImpl<Resource, Boolean>() {\r
+\r
+            @Override\r
+            public Boolean perform(ReadGraph graph, Resource series) throws DatabaseException {\r
+                Resource dataset = graph.getPossibleObject(series, Layer0.getInstance(graph).PartOf);\r
+                Boolean result = graph.getPossibleRelatedValue(dataset, SysdynResource.getInstance(graph).Charts_SensitivityDataset_median, Bindings.BOOLEAN);\r
+                return Boolean.TRUE.equals(result);\r
+            }\r
+        });\r
+        \r
+        validateUnits.addSelectionListener(new SelectionListenerImpl<Resource>(context){\r
+\r
+            @Override\r
+            public void apply(WriteGraph graph, Resource series) throws DatabaseException {\r
+                SysdynResource SR = SysdynResource.getInstance(graph);\r
+                Resource dataset = graph.getPossibleObject(series, Layer0.getInstance(graph).PartOf);\r
+                if(dataset == null)\r
+                    return;\r
+                \r
+                Boolean result = graph.getPossibleRelatedValue(dataset, SR.Charts_SensitivityDataset_median, Bindings.BOOLEAN);\r
+                if(result == null)\r
+                    result = false;\r
+                graph.claimLiteral(dataset, SR.Charts_SensitivityDataset_median, Boolean.FALSE.equals(result));\r
+            }\r
+            \r
+        });\r
+        \r
+        Composite c = new Composite(this, SWT.NONE);\r
+        GridDataFactory.fillDefaults().span(2, 1).applyTo(c);\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(c);\r
+        ConfidenceBoundWidget cbWidget = new ConfidenceBoundWidget(c, context, support, SWT.NONE, 0);\r
+        GridDataFactory.fillDefaults().applyTo(cbWidget);\r
+        cbWidget = new ConfidenceBoundWidget(c, context, support, SWT.NONE, 1);\r
+        GridDataFactory.fillDefaults().applyTo(cbWidget);\r
+        cbWidget = new ConfidenceBoundWidget(c, context, support, SWT.NONE, 2);\r
+        GridDataFactory.fillDefaults().applyTo(cbWidget);\r
+        cbWidget = new ConfidenceBoundWidget(c, context, support, SWT.NONE, 3);\r
+        GridDataFactory.fillDefaults().applyTo(cbWidget);\r
+        cbWidget = new ConfidenceBoundWidget(c, context, support, SWT.NONE, 4);\r
+        GridDataFactory.fillDefaults().applyTo(cbWidget);\r
+        \r
+    }\r
+    \r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SysdynRangeHandlerFactory.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SysdynRangeHandlerFactory.java
new file mode 100644 (file)
index 0000000..9f804e5
--- /dev/null
@@ -0,0 +1,166 @@
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.util.HashMap;\r
+import java.util.LinkedHashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.jfreechart.chart.properties.RangeHandlerFactory;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.datastructures.Quad;\r
+\r
+public class SysdynRangeHandlerFactory implements RangeHandlerFactory {\r
+    \r
+    protected Resource getRVIRelation(ReadGraph graph) {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+        return jfree.variableRVI;\r
+    }\r
+       \r
+       @Override\r
+       public Read<LinkedHashMap<String, Resource>> getRequest(final Resource series) {\r
+               // TODO Auto-generated method stub\r
+               return new Read<LinkedHashMap<String, Resource>>() {\r
+\r
+            @Override\r
+            public LinkedHashMap<String, Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                String realizationURI = ChartUtils.getCurrentRealizationURI(graph, series);\r
+                String rvi = graph.getPossibleRelatedValue(series, getRVIRelation(graph));\r
+                if(rvi == null)\r
+                    return null;\r
+                \r
+                rvi = rvi.replace(".", "/");\r
+                \r
+                if(!rvi.startsWith("/"))\r
+                    rvi = "/" + rvi;\r
+                \r
+                try {\r
+                    // Find the variable for the current variableRVI\r
+                    Variable v = Variables.getVariable(graph, realizationURI + rvi.trim());\r
+                    if(v == null)\r
+                        return null;\r
+                    \r
+                    // Find all enumeration replacements in the variable's path\r
+                    HashMap<Resource, Resource> redeclarations = new HashMap<Resource, Resource>();\r
+                    Variable parent = v;\r
+                    while((parent = parent.getParent(graph)) != null) {\r
+                       Resource represents = parent.getRepresents(graph);\r
+                       Resource type = graph.getSingleObject(represents, Layer0.getInstance(graph).InstanceOf);\r
+                       if(!graph.isInheritedFrom(type, sr.Module))\r
+                               break;\r
+                       \r
+                       for(Resource redeclaration : graph.getObjects(represents, sr.Module_redeclaration)) {\r
+                               redeclarations.put(\r
+                                               graph.getPossibleObject(redeclaration, sr.Redeclaration_replacedEnumeration), \r
+                                               graph.getPossibleObject(redeclaration, sr.Redeclaration_replacingEnumeration)\r
+                                               );\r
+                       }\r
+                    }\r
+                    \r
+                    \r
+                    \r
+                    \r
+                    Resource variable = v.getRepresents(graph);\r
+                    \r
+                    // Return the enumerations assigned to that variable\r
+                    Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
+                    if(arrayIndexes != null) {\r
+                        LinkedHashMap<String, Resource> result = new LinkedHashMap<String, Resource>();\r
+                        for(Resource enumeration : ListUtils.toList(graph, arrayIndexes)) {\r
+                               \r
+                               // Find possible redeclarations for enumeration\r
+                               Resource redeclaration = enumeration;\r
+                               while(redeclarations.get(redeclaration) != null)\r
+                                       redeclaration = redeclarations.get(redeclaration);\r
+                               \r
+                            String enumerationName = NameUtils.getSafeName(graph, redeclaration);\r
+                            result.put(enumerationName, redeclaration);\r
+                        }\r
+                        return result;\r
+                    }\r
+                } catch (DatabaseException e) {\r
+                    // No variable was found, return null\r
+                }\r
+                return null;\r
+            }\r
+\r
+        };\r
+       }\r
+       \r
+       @Override\r
+       public ReadFactoryImpl<Resource, Map<String, Object>> getRangeItemFactory(int index, Resource res) {\r
+               return new RangeItemFactory(index, res);\r
+       }\r
+       \r
+       \r
+    /**\r
+     * RangeItemFactory finds all inexes of a given enumeration \r
+     * and adds "Sum" and "All" to the returned indexes\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    public class RangeItemFactory extends ReadFactoryImpl<Resource, Map<String, Object>> {\r
+\r
+        private int index;\r
+        private Resource enumeration;\r
+        private boolean addCollections;\r
+\r
+        \r
+        /**\r
+         * \r
+         * @param index Index of the enumeration in the variable\r
+         * @param enumeration The enumeration\r
+         */\r
+        public RangeItemFactory(int index, Resource enumeration) {\r
+            this(index, enumeration, true);\r
+        }\r
+        \r
+        /**\r
+         * \r
+         * @param index Index of the enumeration in the variable\r
+         * @param enumeration The enumeration\r
+         * @param addCollections add "Sum" and "All"\r
+         */\r
+        public RangeItemFactory(int index, Resource enumeration, boolean addCollections) {\r
+            this.index = index;\r
+            this.enumeration = enumeration;\r
+            this.addCollections = addCollections;\r
+        }\r
+\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Quad<Object, Integer, Resource, Class<?>>(inputContents, index, enumeration, getClass());\r
+        }\r
+        @Override\r
+        public Map<String, Object> perform(ReadGraph graph, Resource series) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();\r
+            Resource enumerationIndexes = graph.getPossibleObject(enumeration, sr.Enumeration_enumerationIndexList);\r
+            List<Resource> indexes = ListUtils.toList(graph, enumerationIndexes);\r
+            if(addCollections) {\r
+                // First add "All" and "Sum", then all of the enumeration indexes in order\r
+                result.put("All", "All");\r
+                result.put("Sum", "Sum");\r
+            }\r
+            for(Resource index : indexes) {\r
+                String name = NameUtils.getSafeName(graph, index);\r
+                result.put(name, name);\r
+            }\r
+            \r
+            return result;\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendEditor.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendEditor.java
new file mode 100644 (file)
index 0000000..258bae5
--- /dev/null
@@ -0,0 +1,32 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.simantics.jfreechart.chart.ChartComposite;\r
+import org.simantics.ui.workbench.ResourceEditorPart;\r
+\r
+public class TrendEditor extends ResourceEditorPart {\r
+\r
+    private ChartComposite chart;\r
+    \r
+    @Override\r
+    public void createPartControl(Composite parent) {\r
+        chart = new ChartComposite(parent, getResourceInput().getResource(), SWT.NONE);\r
+    }\r
+\r
+    @Override\r
+    public void setFocus() {\r
+        chart.forceFocus();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendToPng.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendToPng.java
new file mode 100644 (file)
index 0000000..dae65d7
--- /dev/null
@@ -0,0 +1,80 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.expressions.EvaluationContext;\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.jfree.chart.ChartUtilities;\r
+import org.jfree.chart.JFreeChart;\r
+\r
+/**\r
+ * Exports the current chart in TrendView\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class TrendToPng extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        EvaluationContext c = (EvaluationContext)event.getApplicationContext();\r
+        Object o = c.getParent().getVariable("activePart");\r
+        if(o != null && o instanceof TrendView) {\r
+            TrendView trendView = (TrendView) o;\r
+            int width = trendView.getPanel().getSize().width;\r
+            int height =  trendView.getPanel().getSize().height;\r
+            int compressionLevel = 0;\r
+\r
+            final Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+\r
+            while(true) {\r
+                FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
+                fd.setText("Export trend to PNG");\r
+                String[] ext = {"*.png"};\r
+                fd.setFilterExtensions(ext);\r
+                String selected = fd.open();\r
+\r
+                if(selected == null)\r
+                    return null;\r
+\r
+                File file = new File(selected);\r
+\r
+                if(file.exists()) {\r
+                    MessageDialog dialog = new MessageDialog(shell, "Overwrite " + file.getName() + "?", null, file.getName() + " exits. Do you wan't to overwrite it?", 0,\r
+                            new String[] { "Yes", "No" }, 0);\r
+                    dialog.create();\r
+                    if (dialog.open() == 1)\r
+                        continue;\r
+                }\r
+\r
+                JFreeChart chart =  trendView.getPanel().getChart();\r
+                try {\r
+                    ChartUtilities.saveChartAsPNG(file, chart, width, height, null, true, compressionLevel);\r
+                } catch (IOException e) {\r
+                    e.printStackTrace();\r
+                }\r
+                return null;\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendToSvg.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendToSvg.java
new file mode 100644 (file)
index 0000000..9da9370
--- /dev/null
@@ -0,0 +1,73 @@
+package org.simantics.sysdyn.ui.trend;\r
+\r
+//import java.awt.geom.Rectangle2D;\r
+//import java.io.File;\r
+//import java.io.FileNotFoundException;\r
+//import java.io.FileOutputStream;\r
+//import java.io.OutputStreamWriter;\r
+//import java.io.UnsupportedEncodingException;\r
+//import java.io.Writer;\r
+\r
+import java.awt.geom.Rectangle2D;\r
+import java.io.File;\r
+import java.io.IOException;\r
+\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.expressions.EvaluationContext;\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+\r
+public class TrendToSvg extends AbstractHandler {\r
+\r
+    @Override\r
+    public Object execute(ExecutionEvent event) throws ExecutionException {\r
+        EvaluationContext c = (EvaluationContext)event.getApplicationContext();\r
+        Object o = c.getParent().getVariable("activePart");\r
+        if(o != null && o instanceof TrendView) {\r
+            TrendView trendView = (TrendView) o;\r
+\r
+            Shell shell = HandlerUtil.getActiveShellChecked(event);\r
+            \r
+            while(true) {\r
+                FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
+                fd.setText("Export trend to SVG");\r
+                String[] ext = {"*.svg"};\r
+                fd.setFilterExtensions(ext);\r
+                String selected = fd.open();\r
+\r
+                if(selected == null)\r
+                    return null;\r
+\r
+                File file = new File(selected);\r
+\r
+                if(file.exists()) {\r
+                    MessageDialog dialog = new MessageDialog(shell, "Overwrite " + file.getName() + "?", null, file.getName() + " exits. Do you wan't to overwrite it?", 0,\r
+                            new String[] { "Yes", "No" }, 0);\r
+                    dialog.create();\r
+                    if (dialog.open() == 1)\r
+                        continue;\r
+                }\r
+\r
+                try {\r
+                    ChartUtils.writeSVG(\r
+                            trendView.getPanel().getChart(), \r
+                            new Rectangle2D.Double(0, 0, trendView.getPanel().getWidth(), trendView.getPanel().getHeight()),\r
+                            file);\r
+                } catch (IOException e) {\r
+                    e.printStackTrace();\r
+                } \r
+                \r
+                return null;\r
+            }\r
+        }\r
+\r
+        return null;\r
+    }\r
+   \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendView.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendView.java
new file mode 100644 (file)
index 0000000..ef13a42
--- /dev/null
@@ -0,0 +1,299 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.awt.Frame;\r
+import java.util.Collection;\r
+\r
+import javax.swing.SwingUtilities;\r
+\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.awt.SWT_AWT;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.ui.part.ViewPart;\r
+import org.jfree.chart.ChartPanel;\r
+import org.jfree.chart.JFreeChart;\r
+import org.jfree.chart.axis.NumberAxis;\r
+import org.jfree.chart.plot.XYPlot;\r
+import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;\r
+import org.jfree.data.xy.AbstractXYDataset;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.IJFreeChart;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.ui.viewUtils.SysdynDatasetSelectionListener;\r
+import org.simantics.utils.RunnableWithObject;\r
+\r
+/**\r
+ * Trend view that shows all active simulation results for selected variables.\r
+ *  \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class TrendView extends ViewPart {\r
+\r
+    private Frame frame;\r
+    private ChartPanel panel;\r
+    private SysdynDatasets sysdynDatasets = new SysdynDatasets();\r
+    private SysdynDatasetSelectionListener sysdynDatasetSelectionListener;\r
+    private JFreeChart defaultchart;\r
+    private Composite composite;\r
+\r
+    \r
+    public Frame getFrame() {\r
+        return frame;\r
+    }\r
+\r
+    public ChartPanel getPanel() {\r
+        return panel;\r
+    }\r
+    \r
+    public void setPanel(ChartPanel panel) {\r
+        this.panel = panel;\r
+    }\r
+\r
+    public SysdynDatasets getSysdynDatasets() {\r
+        return sysdynDatasets;\r
+    }\r
+\r
+    /**\r
+     * Dataset for jFreeChart\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    @SuppressWarnings("serial")\r
+    class SysdynDatasets extends AbstractXYDataset {\r
+\r
+        SysdynDataSet[] sets = new SysdynDataSet[0];\r
+\r
+        public void setDatasets(SysdynDataSet[] sets) {\r
+            this.sets = sets;\r
+            fireDatasetChanged();\r
+        }\r
+\r
+        @Override\r
+        public Number getY(int series, int item) {\r
+            return sets[series].values[item];\r
+        }\r
+\r
+        @Override\r
+        public Number getX(int series, int item) {\r
+            return sets[series].times[item];\r
+        }\r
+\r
+        @Override\r
+        public int getItemCount(int series) {\r
+            return sets[series].times.length;\r
+        }\r
+\r
+        @Override\r
+        public Comparable<String> getSeriesKey(int series) {\r
+            SysdynDataSet sds = sets[series];\r
+            String name = sds.name;\r
+            if(sds.resultIndex != null)\r
+               name += "(" + sds.resultIndex + ")"; \r
+            if(sds.result == null)\r
+                return name;\r
+            else\r
+                return name + " : " + sds.result;\r
+        }\r
+\r
+        @Override\r
+        public int getSeriesCount() {\r
+            return sets.length;\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public void createPartControl(Composite parent) {\r
+\r
+        composite = new Composite(parent,\r
+                SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
+        frame = SWT_AWT.new_Frame(composite);\r
+\r
+        // Create the chart\r
+        displayDefaultChart();\r
+\r
+        // Add a dataset listener that updates datasets for the chart according to current selection \r
+        sysdynDatasetSelectionListener = new TrendViewSelectionListner(this);\r
+\r
+        getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(sysdynDatasetSelectionListener);\r
+\r
+    }\r
+    \r
+    private class TrendViewSelectionListner extends SysdynDatasetSelectionListener {\r
+        \r
+        private TrendView trendView;\r
+        private CustomChartListener listener;\r
+\r
+        public TrendViewSelectionListner(TrendView trendView) {\r
+            this.trendView = trendView;\r
+        }\r
+\r
+        @Override\r
+        protected void selectionChanged(final Collection<SysdynDataSet> activeDatasets) {\r
+            SwingUtilities.invokeLater(new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+                    if(listener != null) {\r
+                        listener.dispose();\r
+                    }\r
+                    trendView.getSysdynDatasets().setDatasets(activeDatasets.toArray(new SysdynDataSet[activeDatasets.size()]));\r
+                    displayDefaultChart();\r
+                }\r
+\r
+            });\r
+        }\r
+\r
+        @Override\r
+        protected void selectionChanged(ReadGraph graph, final Resource chartResource) {\r
+\r
+            if(listener != null) {\r
+                listener.dispose();\r
+            }\r
+\r
+            listener = new CustomChartListener(trendView);\r
+\r
+            graph.asyncRequest(new Read<JFreeChart>() {\r
+\r
+                @Override\r
+                public JFreeChart perform(ReadGraph graph) throws DatabaseException {\r
+                    if(graph.hasStatement(chartResource)) {\r
+                        IJFreeChart chart = graph.adapt(chartResource, IJFreeChart.class);\r
+                        if(chart != null) {\r
+                            return chart.getChart();\r
+                        }\r
+                    }\r
+                    return null;\r
+                }\r
+            }, listener);\r
+        }\r
+    }\r
+\r
+    private class CustomChartListener implements Listener<JFreeChart> {\r
+\r
+        private boolean disposed = false;\r
+        private TrendView trendView;\r
+        \r
+        public CustomChartListener(TrendView trendView) {\r
+            this.trendView = trendView;\r
+        }\r
+\r
+        @Override\r
+        public void execute(JFreeChart result) {\r
+            if(!disposed)\r
+                displayChart(result, trendView);\r
+        }\r
+\r
+        @Override\r
+        public void exception(Throwable t) {\r
+            t.printStackTrace();\r
+        }\r
+\r
+        @Override\r
+        public boolean isDisposed() {\r
+            return disposed;\r
+        }\r
+\r
+        public void dispose() {\r
+            this.disposed = true;\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Displays jFreeChart\r
+     * @param jFreeChart\r
+     */\r
+    private void displayChart(JFreeChart jFreeChart, TrendView trendView) {\r
+        SwingUtilities.invokeLater(new RunnableWithObject(jFreeChart, trendView) {\r
+\r
+            @Override\r
+            public void run() {\r
+                if(count() != 2 || getObject(0) == null || getObject(1) == null)\r
+                    return;\r
+                \r
+                if(!(getObject(0) instanceof JFreeChart && getObject(1) instanceof TrendView))\r
+                    return;\r
+                \r
+                JFreeChart jFreeChart = (JFreeChart) getObject(0);\r
+                TrendView trendView = (TrendView) getObject(1);\r
+                \r
+                Frame frame = trendView.getFrame();\r
+                ChartPanel panel = trendView.getPanel();\r
+                \r
+                // Do not just simply frame.removeAll();\r
+                // Instead, use and reuse only the first component of the frame.\r
+                if(jFreeChart != null) {\r
+                    if (panel == null || frame.getComponentCount() == 0){\r
+                        panel = new ChartPanel(jFreeChart, false, true, true, true, true);\r
+                        trendView.setPanel(panel);\r
+                        frame.add(panel);\r
+                    } else {\r
+//                        panel.setChart(jFreeChart);\r
+                        if ( frame.getComponent(0) instanceof ChartPanel ){\r
+                            ChartPanel tempPanel = (ChartPanel)frame.getComponent(0);\r
+                            tempPanel.setChart(jFreeChart);\r
+                            trendView.setPanel(tempPanel);\r
+                        }\r
+                    }\r
+                }\r
+                frame.repaint();\r
+                frame.validate();\r
+                panel.requestFocusInWindow();\r
+                //panel.requestFocus();\r
+            }\r
+\r
+        });\r
+    }\r
+\r
+    /**\r
+     * displays a default chart\r
+     */\r
+    private void displayDefaultChart() {\r
+        if(defaultchart == null) {\r
+               NumberAxis domainAxis = new NumberAxis("time");\r
+               domainAxis.setAutoRangeIncludesZero(false);\r
+            XYPlot plot = new XYPlot(\r
+                    sysdynDatasets,\r
+                    domainAxis,\r
+                    new NumberAxis(""),\r
+                    new XYLineAndShapeRenderer(true, false)\r
+                    );\r
+            defaultchart = new JFreeChart(plot);\r
+        }\r
+        displayChart(defaultchart, this);\r
+    }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        super.dispose();\r
+        getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(sysdynDatasetSelectionListener);\r
+    }\r
+\r
+    @Override\r
+    public void setFocus() {\r
+        if(panel != null)\r
+            panel.requestFocus();\r
+    }\r
+\r
+\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDataset.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDataset.java
new file mode 100644 (file)
index 0000000..4866e21
--- /dev/null
@@ -0,0 +1,349 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.awt.BasicStroke;\r
+import java.awt.Color;\r
+import java.awt.Paint;\r
+import java.awt.Stroke;\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import javax.swing.SwingUtilities;\r
+\r
+import org.jfree.chart.ChartColor;\r
+import org.jfree.chart.labels.StandardXYToolTipGenerator;\r
+import org.jfree.chart.plot.DefaultDrawingSupplier;\r
+import org.jfree.chart.plot.ValueMarker;\r
+import org.jfree.chart.renderer.AbstractRenderer;\r
+import org.jfree.chart.renderer.xy.AbstractXYItemRenderer;\r
+import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;\r
+import org.jfree.data.general.Dataset;\r
+import org.jfree.data.xy.DefaultXYDataset;\r
+import org.jfree.ui.Layer;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.procedure.adapter.DisposableListener;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.request.PossibleActiveExperiment;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.jfreechart.chart.AbstractDataset;\r
+import org.simantics.jfreechart.chart.IRenderer;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.Functions;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * Class representing a JFreeChart.XYDataset\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class XYDataset extends AbstractDataset implements org.simantics.jfreechart.chart.XYDataset{\r
+\r
+    protected IRenderer renderer;\r
+\r
+    public XYDataset(ReadGraph graph, final Resource datasetResource) throws DatabaseException {\r
+        super(graph, datasetResource);\r
+    }\r
+\r
+    protected Dataset dataset;\r
+    protected DisposableListener<?> datasetListener;\r
+    protected DisposableListener<Double> timeListener;\r
+    \r
+    protected DisposableListener<Double> getTimeListener() {\r
+        if(timeListener == null || timeListener.isDisposed()) {\r
+            timeListener = new TimeListener();\r
+        }\r
+        return timeListener;\r
+    }\r
+    \r
+    protected Read<Double> getTimeRequest() {\r
+        return new Read<Double>() {\r
+            @Override\r
+            public Double perform(ReadGraph graph) throws DatabaseException {\r
+                JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                // Get properties for all series\r
+                Resource series = graph.getPossibleObject(resource, jfree.Dataset_seriesList);\r
+                if(series != null) {\r
+                    List<Resource> seriesList = ListUtils.toList(graph, series);\r
+                    if(seriesList != null) {\r
+                        String realizationURI = getRealizationURI(graph, resource);\r
+                        for(Resource r : seriesList) {\r
+                            String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);\r
+                            if(rvi == null)\r
+                                continue;\r
+                            try {\r
+                                // Get a variable for the experiment run\r
+                                Variable v = Variables.getVariable(graph, realizationURI);\r
+                                if(v == null)\r
+                                    return null;\r
+                                Variable timeVar = v.browsePossible(graph, "#" + Functions.TIME + "#");\r
+                                if(timeVar != null)\r
+                                    return timeVar.getValue(graph, Bindings.DOUBLE);\r
+                            } catch (MissingVariableException e) {\r
+                                // Do nothing, if variable was not found.\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+                return null;\r
+            }\r
+\r
+        };\r
+    }\r
+\r
+    @SuppressWarnings("unchecked")\r
+    @Override\r
+    public Dataset getDataset() {\r
+        if(dataset == null) {\r
+            dataset = new DefaultXYDataset();\r
+        }   \r
+\r
+        if(datasetListener == null || datasetListener.isDisposed()) {\r
+            datasetListener = new DataSetListener();\r
+            SimanticsUI.getSession().asyncRequest(\r
+                    new XYDatasetRequest(resource), \r
+                    (DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, IRenderer>>) datasetListener); \r
+\r
+        }\r
+\r
+        if(timeListener == null || timeListener.isDisposed()) {\r
+            SimanticsUI.getSession().asyncRequest(getTimeRequest(), getTimeListener());\r
+        }\r
+        return dataset;\r
+    }\r
+\r
+    /**\r
+     * Class for identifying a time marker in a plot\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    protected class TimeMarker extends ValueMarker {\r
+        private static final long serialVersionUID = 2018755066561629172L;\r
+\r
+        public TimeMarker(double value, Paint paint, Stroke stroke) {\r
+            super(value, paint, stroke);\r
+        }\r
+    }\r
+\r
+    private class DataSetListener extends DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, IRenderer>> {\r
+\r
+        @Override\r
+        public void execute(Pair<ArrayList<XYDatasetTempSeries>, IRenderer> result) {\r
+            final ArrayList<XYDatasetTempSeries> series = result.first;\r
+            renderer = result.second;\r
+            \r
+            // Modify series in AWT thread to avoid synchronization problems\r
+            SwingUtilities.invokeLater(new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+\r
+                    if(dataset == null || !(dataset instanceof DefaultXYDataset))\r
+                        return;\r
+                    \r
+                    DefaultXYDataset ds = (DefaultXYDataset)dataset;\r
+                    org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();\r
+                    \r
+                    if(plot != null) {\r
+                        /*\r
+                         *  Drawing supplier with a modified first yellow. The default first\r
+                         *  yellow is too light to be visible against a white background\r
+                         */\r
+                        Paint[] paintSequence = ChartColor.createDefaultPaintArray();\r
+                        paintSequence[3] = new Color(0xFF, 0xDD, 0x00);\r
+                        DefaultDrawingSupplier drawingsupplier = new DefaultDrawingSupplier(\r
+                                paintSequence,\r
+                                DefaultDrawingSupplier.DEFAULT_FILL_PAINT_SEQUENCE,\r
+                                DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,\r
+                                DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,\r
+                                DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,\r
+                                DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);\r
+                        plot.setDrawingSupplier(drawingsupplier);\r
+                    }\r
+                    // Remove all series\r
+                    for(int i = ds.getSeriesCount() - 1; i >= 0; i-- ) {\r
+                        ds.removeSeries(ds.getSeriesKey(i));\r
+                    }\r
+\r
+                    // Add found series\r
+                    for(int i = 0; i < series.size(); i++) {\r
+                        XYDatasetTempSeries s = series.get(i);\r
+                        String name = s.name;\r
+                        if(ds.indexOf(name) >= 0)\r
+                            name = name + (i + 1);\r
+                        ds.addSeries(name, s.values);\r
+                        getRenderer().setSeriesStroke(i, new BasicStroke((float)s.width));\r
+                        getRenderer().setSeriesPaint(i, s.color);\r
+                    } \r
+                }\r
+            });\r
+        }\r
+\r
+        @Override\r
+        public void exception(Throwable t) {\r
+            t.printStackTrace();\r
+        }\r
+\r
+    }\r
+\r
+\r
+    /**\r
+     * Listener for updating the time indicator for XY plots\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    protected class TimeListener extends DisposableListener<Double> {\r
+\r
+        private ValueMarker marker;\r
+        private Stroke dashStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,\r
+                BasicStroke.JOIN_MITER, 10.0f, new float[] {5.0f, 3.0f, 1.0f, 3.0f}, 0.0f);\r
+\r
+        public TimeListener() {\r
+            this.marker = new TimeMarker(0.0, Color.red, dashStroke);\r
+        }\r
+\r
+        public void dispose() {\r
+            super.dispose();\r
+            if(marker != null) {\r
+                org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();\r
+                if(plot != null)\r
+                    plot.removeDomainMarker(marker);\r
+            }\r
+        }\r
+\r
+        @Override\r
+        public void execute(final Double time) {\r
+            // Modify in AWT thread to avoid synchronization problems\r
+            SwingUtilities.invokeLater(new Runnable() {\r
+\r
+                @Override\r
+                public void run() {\r
+                    org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();\r
+\r
+                    if(plot == null)\r
+                        return;\r
+\r
+                    plot.removeDomainMarker(marker);\r
+                    if(time != null) {\r
+                        marker.setValue(time);\r
+                        if(plot.getDomainMarkers(Layer.FOREGROUND) == null || !plot.getDomainMarkers(Layer.FOREGROUND).contains(marker)) {\r
+                            int i = 0;\r
+                            for(i = 0; i < plot.getDatasetCount(); i++) {\r
+                                if(plot.getDataset(i) != null && plot.getDataset(i).equals(dataset))\r
+                                    break;\r
+                            }\r
+                            plot.addDomainMarker(i, marker, Layer.FOREGROUND);\r
+                        }\r
+                    }\r
+\r
+                }\r
+            });\r
+        }\r
+\r
+        @Override\r
+        public void exception(Throwable t) {\r
+            t.printStackTrace();\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public void dispose() {\r
+        if(timeListener != null) {\r
+            timeListener.dispose();\r
+            timeListener = null;\r
+        }\r
+\r
+        if(datasetListener != null) {\r
+            datasetListener.dispose();\r
+            datasetListener = null;\r
+        }\r
+    }\r
+\r
+\r
+    @Override\r
+    public AbstractRenderer getRenderer() {\r
+        if(renderer == null) {\r
+\r
+            try {\r
+                renderer = SimanticsUI.getSession().syncRequest(new Read<IRenderer>() {\r
+\r
+                    @Override\r
+                    public IRenderer perform(ReadGraph graph) throws DatabaseException {\r
+                        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                        IRenderer renderer = null;\r
+                        Resource rendererResource = graph.getPossibleObject(resource, jfree.Dataset_renderer);\r
+                        if(rendererResource != null)\r
+                            renderer = graph.adapt(rendererResource, IRenderer.class);\r
+                        return renderer;\r
+                    }\r
+                });\r
+            } catch (DatabaseException e) {\r
+            }\r
+            if(renderer == null) {\r
+                XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);\r
+                renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());\r
+                return renderer;\r
+            } else {\r
+                return renderer.getRenderer();\r
+            }\r
+        } else {\r
+            return renderer.getRenderer();\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Get the realization uri of the current dataset resource\r
+     * @param graph ReadGraph\r
+     * @return realization uri for current dataset resource\r
+     * @throws DatabaseException\r
+     */\r
+    public static String getRealizationURI(ReadGraph graph, Resource resource) throws DatabaseException {\r
+        if(resource == null)\r
+            return null;\r
+\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        ModelingResources mr = ModelingResources.getInstance(graph);\r
+\r
+        // Find the model where the chart is located\r
+        Resource model = resource;\r
+        do {\r
+            model = graph.getPossibleObject(model, l0.PartOf);\r
+        } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));\r
+\r
+        if(model == null)\r
+            return null;\r
+\r
+        // Find the variable realization of the current experiment\r
+        String realizationURI = null;\r
+        Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));\r
+        if (realization == null) {\r
+            Layer0X L0X = Layer0X.getInstance(graph);\r
+            realization = graph.getPossibleObject(model, L0X.HasBaseRealization);\r
+        }\r
+        if (realization != null)\r
+            realizationURI = graph.getURI(realization);\r
+\r
+        return realizationURI;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDatasetRequest.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDatasetRequest.java
new file mode 100644 (file)
index 0000000..2a34593
--- /dev/null
@@ -0,0 +1,189 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.awt.Color;\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.G2DUtils;\r
+import org.simantics.jfreechart.chart.IRenderer;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.Functions;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.adapter.VariableRVIUtils;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class XYDatasetRequest implements Read<Pair<ArrayList<XYDatasetTempSeries>, IRenderer>>{\r
+    \r
+    protected Resource dataset;\r
+    \r
+    public XYDatasetRequest(Resource dataset) {\r
+        this.dataset = dataset;\r
+    }\r
+    \r
+    @Override\r
+    public Pair<ArrayList<XYDatasetTempSeries>, IRenderer> perform(ReadGraph graph) throws DatabaseException {\r
+        JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+\r
+        // Renderer\r
+        IRenderer renderer = null;\r
+        Resource rendererResource = graph.getPossibleObject(dataset, jfree.Dataset_renderer);\r
+        if(rendererResource != null)\r
+            renderer = graph.adapt(rendererResource, IRenderer.class);\r
+\r
+        ArrayList<XYDatasetTempSeries> series = new ArrayList<XYDatasetTempSeries>();\r
+\r
+        String realizationURI = XYDataset.getRealizationURI(graph, dataset);\r
+\r
+        if(realizationURI == null)\r
+            return new Pair<ArrayList<XYDatasetTempSeries>, IRenderer>(series, renderer); // No experiment -> No results\r
+\r
+        // Get a variable for the x-axis (if not time)\r
+        double[] domainValues = null;\r
+        Resource domainAxis = graph.getPossibleObject(dataset, jfree.Dataset_mapToDomainAxis);\r
+        if(domainAxis != null) {\r
+            String rvi = graph.getPossibleRelatedValue(domainAxis, jfree.variableRVI);\r
+            if(rvi != null && !rvi.isEmpty()) {\r
+                try {\r
+                    Variable domainVariable = Variables.getVariable(graph, realizationURI + rvi);\r
+                    Variable valuesVariable = domainVariable.browsePossible(graph, "#" + Functions.VALUES +"#");\r
+                    if(valuesVariable != null) {\r
+                        double[][] valuesArray = valuesVariable.getValue(graph);\r
+                        if(valuesArray.length > 0)\r
+                            domainValues = valuesArray[0];\r
+                    }\r
+                } catch(MissingVariableException e) {\r
+                    //Do nothing, use time as domain axis\r
+                }\r
+            }\r
+        }\r
+\r
+        Resource seriesList = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
+\r
+        // Get properties for all series\r
+        if(seriesList != null) {\r
+            for(Resource r : ListUtils.toList(graph, seriesList)) {\r
+                String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);\r
+                if(rvi == null)\r
+                    continue;\r
+\r
+                try {\r
+                    // Get visual properties\r
+                    Integer width = graph.getPossibleRelatedValue(r, jfree.Series_lineWidth, Bindings.INTEGER);\r
+                    if(width == null) width = 1;\r
+\r
+                    Resource c = graph.getPossibleObject(r, jfree.color);\r
+                    Color color = c == null ? null : G2DUtils.getColor(graph, c);\r
+                    \r
+                    String label = graph.getPossibleRelatedValue(r, Layer0.getInstance(graph).HasLabel);\r
+\r
+                    // Get a variable for the series\r
+                    Variable v = Variables.getVariable(graph, realizationURI + rvi);\r
+                    if(v == null)\r
+                        return new Pair<ArrayList<XYDatasetTempSeries>, IRenderer>(series, renderer);\r
+\r
+                    // Get values\r
+                    Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
+                    Object object = null;\r
+                    if(dsVariable != null)\r
+                         object = dsVariable.getValue(graph);\r
+\r
+                    if(object == null || !(object instanceof ArrayList<?>))\r
+                        return new Pair<ArrayList<XYDatasetTempSeries>, IRenderer>(series, renderer);\r
+\r
+                    ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
+\r
+                    for(Object o : (ArrayList<?>)object) {\r
+                        if(o instanceof SysdynDataSet)\r
+                            datasets.add((SysdynDataSet)o);\r
+                    }\r
+\r
+\r
+                    String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter);\r
+                    if(filter != null) {\r
+                        ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);\r
+                        if(result2 != null) {\r
+                            datasets = result2;\r
+                        }\r
+                    }\r
+\r
+                    for(SysdynDataSet dataset : datasets) {\r
+                        double[] va = dataset.values;\r
+\r
+                        // Get domain axis values (time OR other variable) \r
+                        double[] ta;\r
+                        if(domainValues != null) {\r
+                            ta = domainValues;\r
+\r
+                            // If domainAxis is other than time, parameter values size is different. \r
+                            if(domainValues.length > va.length) {\r
+                                double value = va[0];\r
+                                va = new double[domainValues.length];\r
+                                for(int i = 0; i < domainValues.length; i++)\r
+                                    va[i] = value;\r
+                            }\r
+\r
+                            // If domainAxis is a parameter, the domainValues array is too short\r
+                            if(domainValues.length < va.length && domainValues.length == 2 && domainValues[0] == domainValues[1]) {\r
+                                double value = domainValues[0];\r
+                                ta = new double[va.length];\r
+                                for(int i = 0; i < va.length; i++)\r
+                                    ta[i] = value;\r
+                            }\r
+\r
+                        } else {\r
+                            ta = dataset.times;\r
+                        }\r
+\r
+                        if(ta!=null && va!=null && (va.length == ta.length)) {\r
+                            // Add series if everything OK\r
+                            String name = dataset.name;\r
+                            if(label != null)\r
+                                name = label;\r
+                            if (dataset.resultIndex != null) {\r
+                               name += "(" + dataset.resultIndex + ")"; \r
+                            }\r
+                            if(dataset.result != null && !dataset.result.isEmpty())\r
+                                name = name + " : " + dataset.result;\r
+                            if(ta.length != 0 && va.length != 0) {\r
+                                XYDatasetTempSeries tempSeries = new XYDatasetTempSeries(name, new double[][] {ta, va}, width, color);\r
+                                getAdditionalSeriesProperties(graph, r, tempSeries);\r
+                                series.add(tempSeries);\r
+                                \r
+                            }\r
+                            \r
+                        }\r
+                    }\r
+\r
+                } catch (MissingVariableException e) {\r
+                    // Do nothing, if variable was not found. Move on to the next series\r
+                }\r
+            }\r
+        }\r
+        return new Pair<ArrayList<XYDatasetTempSeries>, IRenderer>(series, renderer);\r
+    }\r
+\r
+    \r
+    protected void getAdditionalSeriesProperties(ReadGraph graph, Resource r, XYDatasetTempSeries tempSeries) throws DatabaseException {\r
+        \r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDatasetTempSeries.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDatasetTempSeries.java
new file mode 100644 (file)
index 0000000..d919bae
--- /dev/null
@@ -0,0 +1,37 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.trend;\r
+\r
+import java.awt.Color;\r
+import java.util.HashMap;\r
+\r
+/**\r
+ * Container class for holding XYDataset series\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class XYDatasetTempSeries {\r
+    \r
+    public double[][] values;\r
+    public String name;\r
+    public int width;\r
+    public Color color;\r
+    public HashMap<String, Object> properties = new HashMap<String, Object>();\r
+\r
+    public XYDatasetTempSeries(String name, double[][] values, int width, Color color) {\r
+        this.name = name;\r
+        this.values = values;\r
+        this.width = width;\r
+        this.color = color;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ArrayVariableUtils.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ArrayVariableUtils.java
new file mode 100644 (file)
index 0000000..73663c7
--- /dev/null
@@ -0,0 +1,201 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.EnumerationIndex;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Variable;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;\r
+import org.simantics.sysdyn.utils.ModelUtils;\r
+\r
+public class ArrayVariableUtils {\r
+\r
+\r
+    /**\r
+     * Checks if the given range elements can be applied to the given variable.\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param variable Resource of the variable \r
+     * @param range Range elements in the correct order. Elements are separated in range definition by ',' \r
+     * @return true if range is valid, false if not\r
+     * @throws DatabaseException\r
+     */\r
+    public static Map<Integer, SyntaxError> isRangeValid(ReadGraph graph, Variable variable, String[] elements) throws DatabaseException {\r
+        SyntaxError error;\r
+        if(variable == null)\r
+            return null;\r
+        Map<Integer, SyntaxError> result = new HashMap<Integer, SyntaxError>();\r
+        // Not an array variable\r
+        if(variable.getArrayIndexes() == null || \r
+                variable.getArrayIndexes() == null || \r
+                variable.getArrayIndexes().size() == 0) {\r
+            for(int i = 0; i < elements.length ; i++) {\r
+                error = new SyntaxError();\r
+                error.setMessage("Variable is not an array variable");\r
+                error.setType(ExpressionField.SYNTAX_ERROR);\r
+                result.put(i, error);\r
+            }\r
+\r
+            return result;\r
+        }\r
+        ArrayList<Enumeration> enumerations = variable.getArrayIndexes();\r
+        // Too many elements\r
+        if(elements.length > enumerations.size()) {\r
+            error = new SyntaxError();\r
+            error.setMessage( "Too many elements");\r
+            error.setType(ExpressionField.SYNTAX_ERROR);\r
+            result.put(enumerations.size(), error);\r
+        } else if(elements.length < enumerations.size()) {\r
+            error = new SyntaxError();\r
+            error.setMessage("Too few elements");\r
+            error.setType(ExpressionField.SYNTAX_ERROR);\r
+            result.put(elements.length > 0 ? elements.length - 1 : 0, error);\r
+        }\r
+\r
+        for(int i = 0; i < elements.length && i < enumerations.size(); i++) {\r
+               String trimmedElement = elements[i].trim();\r
+            if (trimmedElement.charAt(0) == '{' && trimmedElement.charAt(trimmedElement.length() - 1) == '}') {\r
+               // Something like "{a, b, c}"\r
+               String[] rangeComponents = trimmedElement.substring(1, trimmedElement.length() - 1).split(",");\r
+               // Single range component, equals to the enumeration at that index\r
+                if(rangeComponents.length == 1 && rangeComponents[0].trim().equals(enumerations.get(i).getName()))\r
+                       continue;\r
+                   // more than one range component, they all equal to individual indexes in the enumeration\r
+                result.putAll(areRangeComponentsValid(rangeComponents, enumerations, i));\r
+            } else if(trimmedElement.equals(":")) {\r
+                continue; // Just a ":"\r
+               } else if(elements[i].indexOf(":") != elements[i].lastIndexOf(":")) {\r
+                       // Something like "a : b : c"\r
+                error = new SyntaxError();\r
+                error.setMessage( "Too many ':' elements");\r
+                error.setType(ExpressionField.SYNTAX_ERROR);\r
+                result.put(i, error);\r
+                continue;\r
+            } else {\r
+               // Something like "a : c" OR "a"\r
+                   String[] rangeComponents = elements[i].split(":");\r
+                   if(rangeComponents.length > 2){\r
+                       error = new SyntaxError();\r
+                       error.setMessage( "Too many ':' elements");\r
+                       error.setType(ExpressionField.SYNTAX_ERROR);\r
+                       result.put(i, error);\r
+                       continue;\r
+                   }\r
+                   // Single range component, equals to the enumeration at that index\r
+                   if(rangeComponents.length == 1 && rangeComponents[0].trim().equals(enumerations.get(i).getName()))\r
+                       continue;\r
+                   // one or two range components, they all equal to individual indexes in the enumeration\r
+                   result.putAll(areRangeComponentsValid(rangeComponents, enumerations, i));\r
+            }\r
+        }\r
+        if(result.isEmpty())\r
+            return null;\r
+        else\r
+            return result;\r
+    }\r
+\r
+    private static Map<Integer, SyntaxError> areRangeComponentsValid(String[] rangeComponents, ArrayList<Enumeration> enumerations, int i) {\r
+       SyntaxError error;\r
+       Map<Integer, SyntaxError> result = new HashMap<Integer, SyntaxError>();\r
+        for(String r : rangeComponents) {\r
+            r = r.trim();\r
+            boolean componentIsValid = false;\r
+            Enumeration enumeration = enumerations.get(i);\r
+            for(EnumerationIndex ei : enumeration.getEnumerationIndexes()) {\r
+                if(ei.getName().equals(r)) {\r
+                    componentIsValid = true;\r
+                    break;\r
+                }\r
+            }\r
+            if(!componentIsValid  && r.length() > 0) {\r
+                // Check if the range is an integer that is between 0 and enumeration indexes size\r
+                try {\r
+                    int index = Integer.parseInt(r);\r
+                    int min = 1;\r
+                    int max = enumeration.getEnumerationIndexes().size();\r
+                    if(index >= min && index <= max || enumeration.isReplaceable()) {\r
+                        componentIsValid = true;\r
+                        error = new SyntaxError();\r
+                        error.setMessage("Using numbers as array indexes is not encouraged");\r
+                        error.setType(ExpressionField.SYNTAX_WARNING);\r
+                        result.put(i, error);\r
+                    } else {\r
+                        error = new SyntaxError();\r
+                        error.setMessage("Invalid array index " + index + ". Numbered index must be between " + min + " and " + max);\r
+                        error.setType(ExpressionField.SYNTAX_ERROR);\r
+                        result.put(i, error);\r
+                    }\r
+                } catch (NumberFormatException e) {\r
+                    error = new SyntaxError();\r
+                    error.setMessage("Invalid range");\r
+                    error.setType(ExpressionField.SYNTAX_ERROR);\r
+                    result.put(i, error);\r
+                }\r
+            }\r
+        }\r
+               return result;\r
+       }\r
+\r
+       /**\r
+     * Checks if the given range can be applied to the given variable.\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param variable Resource of the variable \r
+     * @param range Range WITHOUT [ and ] brackets\r
+     * @return true if range is valid, false if not\r
+     * @throws DatabaseException\r
+     */\r
+    public static boolean isRangeValid(ReadGraph graph, Resource variable, String range) throws DatabaseException {\r
+        if(variable == null)\r
+            return true;\r
+        String[] elements = range.split(",");\r
+        // Connect arrays, e.g. {a,b,c}\r
+        ArrayList<String> connectedElements = new ArrayList<String>();\r
+        for (int i = 0; i < elements.length; ++i) {\r
+               String lastElement = elements[i];\r
+               String fullElement = new String();\r
+               if (lastElement.length() > 0 && lastElement.charAt(0) == '{') {\r
+                       while (lastElement.charAt(lastElement.length() - 1) != '}' && i < elements.length - 1) {\r
+                               fullElement += lastElement + ",";\r
+                               ++i;\r
+                               lastElement = elements[i];\r
+                       }\r
+               }\r
+               fullElement += lastElement;\r
+               connectedElements.add(fullElement);\r
+        }\r
+        String fullElements[] = connectedElements.toArray(new String[connectedElements.size()]);\r
+        \r
+        SysdynModel model = ModelUtils.getModel(graph, variable);\r
+        if(model == null)\r
+            return false;\r
+        IElement e = model.getElement(variable);\r
+        if(e != null && e instanceof Variable) {\r
+            Variable v = (Variable) e;\r
+            if(isRangeValid(graph, v, fullElements) == null)\r
+                return true;\r
+            else\r
+                return false;\r
+        } else {\r
+            return false;\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java
new file mode 100644 (file)
index 0000000..70a0d43
--- /dev/null
@@ -0,0 +1,647 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.eclipse.jface.resource.ColorDescriptor;\r
+import org.eclipse.jface.resource.LocalResourceManager;\r
+import org.eclipse.jface.text.Position;\r
+import org.eclipse.swt.custom.StyledText;\r
+import org.eclipse.swt.graphics.Color;\r
+import org.eclipse.swt.graphics.RGB;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableItem;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+import org.simantics.sysdyn.expressionParser.TokenMgrError;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.EnumerationIndex;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Model;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.Sheet;\r
+import org.simantics.sysdyn.representation.Variable;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.IExpression;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ExpressionUtils {\r
+\r
+    /**\r
+     * Determines if the given expression is a parameter expression. Parameters are numbers.\r
+     * If the expression contains anything other than numbers, it is not a parameter.\r
+     * \r
+     * @param expression The expression to be checked\r
+     * @return is the expression a parameter\r
+     */\r
+    static public boolean isParameter(String expression) {\r
+        try {\r
+            /*\r
+                       StringTokenizer st = new StringTokenizer(expression, "{}[],;");\r
+                       while(st.hasMoreTokens()) {\r
+                               Double.parseDouble(st.nextToken().trim());\r
+                       }\r
+             */\r
+            Double.parseDouble(expression.trim());\r
+            return true;\r
+        } catch (NumberFormatException e) {\r
+            return false;\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Color for a variable found in an expression field, used in shortcut tab.\r
+     * This is a bit silly means of communicating the state of a variable using its color.\r
+     * @param resourceManager LocalResourceManager for which the color is created.\r
+     * @return Color for such variable.\r
+     */\r
+    public static Color variableFoundColor(LocalResourceManager resourceManager) {\r
+        return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(0,0,0)));\r
+    }\r
+    \r
+    /**\r
+     * Color for a variable not found in an expression field, used in shortcut tab.\r
+     * This is a bit silly means of communicating the state of a variable using its color.\r
+     * @param resourceManager LocalResourceManager for which the color is created.\r
+     * @return Color for such variable.\r
+     */\r
+    public static Color variableNotFoundColor(LocalResourceManager resourceManager) {\r
+        return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(255,125,0)));\r
+    }\r
+    \r
+    /**\r
+     * Color for a variable itself and for the time variable, used in shortcut tab.\r
+     * This is a bit silly means of communicating the state of a variable using its color.\r
+     * @param resourceManager LocalResourceManager for which the color is created.\r
+     * @return Color for such variable.\r
+     */\r
+    public static Color variableTimeAndSelfColor(LocalResourceManager resourceManager) {\r
+        return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(127,127,127)));\r
+    }\r
+    \r
+    /**\r
+     * Validates the expressionfield of a given IExpression\r
+     * \r
+     * @param expression The expression whose fields are validated\r
+     * @param resourceManager \r
+     * @param connectedVariables Table items from the shortcut widget. (Items needed so that they can be coloured)\r
+     * @param configuration configuration where the variable is located\r
+     */\r
+    static public void validateExpressionFields(final Resource variable, \r
+            IExpression expression, \r
+            Table variableTable, \r
+            LocalResourceManager resourceManager) {\r
+       if(variable == null || expression == null || variableTable == null)\r
+               return;\r
+       \r
+        Resource configuration = null;\r
+        try {\r
+            configuration = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                @Override\r
+                public Resource perform(ReadGraph graph) throws DatabaseException {\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    Resource configuration = variable;\r
+                    while (configuration != null) {\r
+                        configuration = graph.getPossibleObject(configuration, Layer0.getInstance(graph).PartOf);\r
+\r
+                        if(configuration == null || graph.isInstanceOf(configuration, sr.Configuration)) {\r
+                            break;\r
+                        }\r
+                    }\r
+                    return configuration;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+            return;\r
+        }\r
+\r
+        if(configuration == null)\r
+            return;\r
+\r
+        ExpressionParser parser = new ExpressionParser(new StringReader(""));\r
+        Set<String> variables = new HashSet<String>();\r
+        HashMap<ExpressionField, HashMap<String, List<Token>>> references = new HashMap<ExpressionField, HashMap<String, List<Token>>>();\r
+        final HashMap<ExpressionField, HashMap<String, List<List<Token>>>> ranges = new HashMap<ExpressionField, HashMap<String, List<List<Token>>>>();\r
+        HashMap<ExpressionField, HashMap<Token, List<Token>>> forIndices = new HashMap<ExpressionField, HashMap<Token, List<Token>>>();\r
+        HashMap<ExpressionField, HashMap<String, List<Token>>> enumerationReferences = new HashMap<ExpressionField, HashMap<String, List<Token>>>();\r
+        HashMap<ExpressionField, HashMap<String, List<Token>>> functionReferences = new HashMap<ExpressionField, HashMap<String, List<Token>>>();\r
+\r
+        // Build references and variable array\r
+        boolean parsingSucceeded = false;\r
+        for(ExpressionField ef : expression.getExpressionFields()) {\r
+            ef.resetAnnotations();\r
+            String textString = ef.getExpression();\r
+            parser.ReInit(new StringReader(textString));\r
+            try {\r
+                parser.expr();\r
+                HashMap<String, List<Token>> refs = parser.getReferences();\r
+                references.put(ef, refs);\r
+                variables.addAll(refs.keySet());\r
+\r
+                ranges.put(ef, parser.getRanges());\r
+\r
+                forIndices.put(ef,  parser.getForIndices());\r
+\r
+                enumerationReferences.put(ef, parser.getEnumerationReferences());\r
+\r
+                functionReferences.put(ef, parser.getFunctionCallReferences());\r
+\r
+                parsingSucceeded = true;\r
+            } catch (ParseException e1) {\r
+                ef.setSyntaxError(new SyntaxError(e1.currentToken, "Syntax Error"));\r
+                \r
+                /* \r
+                 * If the equation is empty, set the parsingSucceeded = true\r
+                 * to allow the coloring of the variables succeed. \r
+                 */\r
+                if (textString.equals("")) {\r
+                    parsingSucceeded = true;\r
+                }\r
+            } catch (TokenMgrError err) {\r
+                ef.setSyntaxError(new SyntaxError(0, textString.length(), ExpressionField.SYNTAX_ERROR, "Expression contains unsupported characters"));\r
+            }\r
+        }\r
+\r
+\r
+        // Get model configuration\r
+        SysdynModelManager sdm = SysdynModelManager.getInstance(SimanticsUI.getSession());\r
+        SysdynModel model = sdm.getModel(configuration);\r
+//        try {\r
+//            model.update();\r
+//        } catch (DatabaseException e1) {\r
+//            e1.printStackTrace();\r
+//        }\r
+        Configuration conf = model.getConfiguration();\r
+        \r
+        // Check variable references\r
+        final HashMap<String, Variable> modelVariables = new HashMap<String, Variable>();\r
+        HashSet<String> ignoreVariables = new HashSet<String>();\r
+        if(!variables.isEmpty() || !functionReferences.isEmpty()) {\r
+            Set<String> noSuchVariables = new HashSet<String>();\r
+            ArrayList<IElement> elements = conf.getElements();\r
+            for(IElement e : elements) {\r
+                if(e instanceof Variable) {\r
+                    Variable v = (Variable) e;\r
+                    modelVariables.put(v.getName(), v);\r
+                } else if(e instanceof Module) {\r
+                    ignoreVariables.add(((Module)e).getName());\r
+                }\r
+            }\r
+\r
+            // VARIABLE NAMES\r
+\r
+            if(variables.contains("time"))\r
+                variables.remove("time");\r
+            \r
+            // Remove variable references to for indices\r
+            for(ExpressionField ef : forIndices.keySet()) {\r
+                for(Token t : forIndices.get(ef).keySet()) {\r
+                    if(variables.contains(t.image))\r
+                        variables.remove(t.image);\r
+                }\r
+            }\r
+\r
+            // Examine sheets\r
+            for(ExpressionField ef : functionReferences.keySet()) {\r
+                for(String key : functionReferences.get(ef).keySet()) {\r
+                    \r
+                    List<SyntaxError> errors = examineSheetReferences(conf, key, functionReferences.get(ef).get(key), ef.getExpression(), references.get(ef));\r
+                    if(errors != null) {\r
+                        for(SyntaxError error : errors)\r
+                            ef.setSyntaxError(error);\r
+                    }\r
+                }\r
+            }\r
+\r
+            // Examine variable references\r
+            for(String v : variables) {\r
+                ReferenceOption option = getReferenceOption(conf, v);\r
+                switch(option) {\r
+                    case DOES_NOT_EXIST:\r
+                        noSuchVariables.add(v);\r
+                        break;\r
+                    case CANNOT_BE_CONNECTED:\r
+                        ignoreVariables.add(v);\r
+                        break;\r
+                    case CAN_BE_CONNECTED:\r
+                }\r
+            }\r
+\r
+            if(!noSuchVariables.isEmpty()) {\r
+                noSuchVariables.removeAll(ignoreVariables);\r
+                // remove no such variables from variable list\r
+                for(String s : noSuchVariables)\r
+                    variables.remove(s);\r
+                // create annotations\r
+                HashMap<ExpressionField ,ArrayList<Position>> positions = getPositionsForVariables(references, noSuchVariables);\r
+                for(ExpressionField ef : positions.keySet()) {\r
+                    ef.setNoSuchVariableAnnotations(positions.get(ef));\r
+                }\r
+            }      \r
+        }\r
+\r
+        // Check that the variables that exist have connections and the connected variables have references in the expressions\r
+        // If there are syntax errors, keep the previous coloring.\r
+        String selfName = null;\r
+        if(variableTable != null && !variableTable.isDisposed()) {\r
+            \r
+            // Get the name of the variable itself\r
+            try {\r
+                selfName = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                    @Override\r
+                    public String perform(ReadGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        Object selfName = graph.getPossibleRelatedValue(variable, l0.HasName);\r
+                        if(selfName != null) {\r
+                            return (String)selfName;\r
+                        }\r
+                        return null;\r
+                    }\r
+                });\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+  \r
+            // Color the items in the table\r
+            TableItem[] connectedVariables = variableTable.getItems();\r
+            for(TableItem ti : connectedVariables) {\r
+                if (ti.getText().equals("time") || ti.getText().equals(selfName)) {\r
+                    ti.setForeground(variableTimeAndSelfColor(resourceManager));\r
+                } else if (parsingSucceeded && !variables.contains(ti.getText())) {\r
+                    ti.setForeground(variableNotFoundColor(resourceManager));\r
+                } else if (parsingSucceeded) {\r
+                    ti.setForeground(variableFoundColor(resourceManager));\r
+                    variables.remove(ti.getText());\r
+                }\r
+            }\r
+\r
+            // Remove all enumerations and sheets, they cannot have connections\r
+            variables.removeAll(ignoreVariables);\r
+\r
+            // Always remove self\r
+            variables.remove(selfName);\r
+\r
+            if(!variables.isEmpty()) {\r
+                HashMap<ExpressionField ,ArrayList<Position>> positions = getPositionsForVariables(references, variables);\r
+                for(ExpressionField ef : positions.keySet()) {\r
+                    ef.setMissingLinkAnnotations(positions.get(ef));\r
+                }\r
+\r
+            }\r
+        } \r
+\r
+        for(final ExpressionField ef : ranges.keySet()) {\r
+            List<SyntaxError> errors = new ArrayList<SyntaxError>();\r
+            // RANGES\r
+            errors.addAll(examineArrayRanges(conf, ranges.get(ef), forIndices.get(ef)));\r
+            \r
+            // ENUMERATION REFERENCES IN FOR-LOOPS\r
+            errors.addAll(examineEnumerationReferences(conf, enumerationReferences.get(ef)));\r
+\r
+            for(SyntaxError error : errors)\r
+                ef.setSyntaxError(error);\r
+        }                                      \r
+    }\r
+    \r
+    \r
+    static public List<SyntaxError> examineArrayRanges(\r
+            final Configuration configuration,\r
+            final HashMap<String, List<List<Token>>> ranges,\r
+            final HashMap<Token, List<Token>> forIndices) {\r
+        \r
+        List<SyntaxError> result = Collections.emptyList();\r
+        try {\r
+            result = SimanticsUI.getSession().syncRequest(new Read<List<SyntaxError>>() {\r
+\r
+                @Override\r
+                public List<SyntaxError> perform(ReadGraph graph) throws DatabaseException {\r
+                    return examineArrayRanges(graph, configuration, ranges, forIndices);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return result;\r
+    }\r
+\r
+    static public List<SyntaxError> examineEnumerationReferences(Configuration configuration, HashMap<String, List<Token>> enumRefList) {\r
+        ArrayList<SyntaxError> result = new ArrayList<SyntaxError>();\r
+        for(String enumeration : enumRefList.keySet()) {\r
+            for(Token et : enumRefList.get(enumeration)) {\r
+                Object o = getElement(configuration, enumeration);\r
+                if(o != null && o instanceof Enumeration) {\r
+                    boolean isFound = false;\r
+                    Enumeration e = (Enumeration)o;\r
+\r
+                    if(enumeration.equals(et.image) ||\r
+                            "size".equals(et.image) || \r
+                            "elements".equals(et.image)){\r
+                        // The full enumeration\r
+                        isFound = true;\r
+                    } else {\r
+                        for(EnumerationIndex ei : e.getEnumerationIndexes()) {\r
+                            if(ei.getName().equals(et.image)) {\r
+                                isFound = true;\r
+                                break;\r
+                            }\r
+                        }\r
+                    }\r
+\r
+                    if(!isFound) {\r
+                        StringBuilder sb = new StringBuilder();\r
+                        sb.append("Enumeration ");\r
+                        sb.append(enumeration);\r
+                        sb.append(" has no such index.\nAvailable indexes are: ");\r
+                        Iterator<EnumerationIndex> iterator = e.getEnumerationIndexes().iterator();\r
+                        while(iterator.hasNext()) {\r
+                            sb.append(iterator.next().getName());\r
+                            if(iterator.hasNext()) \r
+                                sb.append(", ");\r
+                        }\r
+                        result.add(new SyntaxError(et, sb.toString()));\r
+                    }\r
+\r
+\r
+                } else {\r
+                    result.add(new SyntaxError(et, "No such enumeration (" + enumeration + ")")); \r
+                }\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @param graph\r
+     * @param configuration\r
+     * @param ranges\r
+     * @param forIndices\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    static public List<SyntaxError> examineArrayRanges(\r
+            ReadGraph graph, \r
+            Configuration configuration,\r
+            HashMap<String, List<List<Token>>> ranges,\r
+            HashMap<Token, List<Token>> forIndices) throws DatabaseException {\r
+        HashMap<Token, SyntaxError> errors = new HashMap<Token, SyntaxError>();\r
+        for(String name : ranges.keySet()) {\r
+            if(ranges.get(name) != null) {\r
+                for(List<Token> l : ranges.get(name)) {\r
+                    String[] rangeReferences = new String[l.size()];\r
+                    for(int i = 0; i < l.size(); i++) {\r
+                        rangeReferences[i] = l.get(i).image;\r
+                    }\r
+\r
+                    Object o = getElement(configuration, name);\r
+                    if(o != null && o instanceof Variable) {\r
+                        Map<Integer, SyntaxError> invalidRanges = ArrayVariableUtils.isRangeValid(graph, (Variable)o, rangeReferences);\r
+                        if(invalidRanges != null && !invalidRanges.isEmpty()) {\r
+                            for(Integer i : invalidRanges.keySet()) {\r
+                                SyntaxError error = invalidRanges.get(i);\r
+                                error.setToken(l.get(i));\r
+                                errors.put(l.get(i), error);\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        } \r
+\r
+\r
+        // FOR-INDICES\r
+\r
+        HashSet<Token> removes = new HashSet<Token>();\r
+        for(Token t : forIndices.keySet()) {\r
+//            boolean isFound = false;\r
+            for(Token rt : errors.keySet()) {\r
+                if(rt.image.equals(t.image)) {\r
+//                    isFound = true;\r
+                    // remove range token from invalid ranges\r
+                    removes.add(rt);\r
+                }\r
+            }\r
+//            Why would this be invalid if the index just is not used anywhere?\r
+//            {1+2 for i in range} \r
+            \r
+//            if(!isFound) {\r
+//                SyntaxError error = new SyntaxError(t, "Invalid index"); \r
+//                errors.put(t, error);\r
+//            }\r
+        }\r
+        \r
+        for(Token t : removes)\r
+            errors.remove(t);\r
+\r
+        return new ArrayList<SyntaxError>(errors.values());\r
+    }\r
+\r
+\r
+    /**\r
+     * Examine if a given functionKey is a sheet reference and whether all the tokens in the function ( Sheet1(token1, token2) )\r
+     * are valid.\r
+     *  \r
+     * @param configuration Configuration where the function is called\r
+     * @param functionKey Function name\r
+     * @param functionTokens Function parameters (sheet reference, either a cell or cell range)\r
+     * @param expression The whole expression where the function reference is\r
+     * @param expressionReferences All variable references, including function parameters\r
+     * @return A list of possible errors\r
+     */\r
+    static public List<SyntaxError> examineSheetReferences(\r
+            Configuration configuration, \r
+            String functionKey, \r
+            List<Token> functionTokens,\r
+            String expression, \r
+            HashMap<String, List<Token>> expressionReferences) {\r
+        \r
+        List<SyntaxError> result = new ArrayList<SyntaxError>();\r
+        \r
+        String[] parts = functionKey.split("\\.");\r
+        Object current = configuration;\r
+        for(int i = 0; i < parts.length && current != null; i++) {\r
+            current = getElement(current, parts[i]);\r
+        }\r
+        \r
+        if(current == null && configuration.getModuleType() != null) {\r
+            // Sheets are currently located in the model root. Try to find the sheet.\r
+            current = configuration.getModuleType().getParent(); // Get module type parent (should be a model)\r
+            if(current instanceof Model)\r
+                current = getElement(((Model)current).getModelConfiguration(), parts[0]); // Try to get the sheet\r
+        }\r
+        \r
+        if(current != null && current instanceof Sheet) {\r
+            Sheet sheet = (Sheet) current;\r
+            int start = 0, end = 0, call = 0;\r
+            String cellOrRange = null;\r
+            while((call = expression.indexOf(functionKey, end)) >= 0) {\r
+                start = expression.indexOf("(", call) +1;\r
+                end = expression.indexOf(")", start);\r
+                if(start < 0 || end < 0 || end < start) {\r
+                    break;\r
+                }\r
+                Pattern p = Pattern.compile("[-\\+\\*\\/\\(\\)\\{\\}\\[\\],\\.\\t\\n\\r\\f]");\r
+                cellOrRange = expression.substring(start, end);\r
+                Matcher m = p.matcher(cellOrRange);\r
+                if (m.find() || cellOrRange.split(":").length > 2) {\r
+                    result.add(new SyntaxError(start, end - start, ExpressionField.SYNTAX_ERROR, "Not a valid cell or range", cellOrRange));\r
+                }\r
+            }\r
+            \r
+            \r
+            for(Token cell : functionTokens) {\r
+                List<Token> refs = expressionReferences.get(cell.image);\r
+                if(refs != null)\r
+                    refs.remove(cell);\r
+                if(!sheet.getCells().containsKey(cell.image))\r
+                    result.add(new SyntaxError(cell.image, "Invalid cell", cell.beginLine, cell.beginColumn, cell.endLine, cell.endColumn)); \r
+            }\r
+\r
+        }\r
+        \r
+        return result;\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Option for a reference. Whether the reference does not exist, \r
+     * it can be connected (normal variable) or it cannot be \r
+     * connected even though it exists (e.g. enumeration index)\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    static public enum ReferenceOption {DOES_NOT_EXIST, CAN_BE_CONNECTED, CANNOT_BE_CONNECTED};\r
+    \r
+    /**\r
+     * Get the reference option for a reference (name) in a configuration.\r
+     * \r
+     * @param conf Configuration\r
+     * @param name Referred variable\r
+     * @return The result tells does the referred name exist and can it be connected to \r
+     */\r
+    static public ReferenceOption getReferenceOption(Configuration conf, String name) {\r
+        \r
+        String[] parts = name.split("\\.");\r
+        Object element = conf;\r
+        for(int i = 0; i < parts.length && element != null; i++) {\r
+            element = getElement(element, parts[i]);\r
+        }\r
+        if(element == null)\r
+            return ReferenceOption.DOES_NOT_EXIST;\r
+        else if(Boolean.TRUE.equals(element))\r
+            return ReferenceOption.CANNOT_BE_CONNECTED;\r
+        else if(element instanceof Variable || element instanceof Module) {\r
+            if(element instanceof Enumeration || element instanceof Sheet || element instanceof Module || parts.length > 1)\r
+                return ReferenceOption.CANNOT_BE_CONNECTED;\r
+            else\r
+                return ReferenceOption.CAN_BE_CONNECTED;\r
+        }\r
+        else \r
+            return ReferenceOption.DOES_NOT_EXIST;\r
+    }\r
+\r
+    static private Object getElement(Object parent, String name) {\r
+        Configuration c = null;\r
+        if(parent instanceof Module) {\r
+            Module m = (Module)parent;\r
+            c = m.getType().getConfiguration();\r
+        } else if (parent instanceof Configuration) {\r
+            c = (Configuration)parent;\r
+        }\r
+\r
+        if(c != null) {\r
+            for(IElement e : c.getElements()) {\r
+                if(e instanceof Variable && ((Variable)e).getName().equals(name)) {\r
+                    return e;\r
+                } else if(e instanceof Module && ((Module)e).getName().equals(name)) {\r
+                    return e;\r
+                }\r
+            }\r
+        } else if(parent instanceof Sheet) {\r
+            Sheet s = (Sheet)parent;\r
+            for(String key : s.getCells().keySet()) {\r
+                if(key.equals(name)) {\r
+                    return Boolean.TRUE;\r
+                }\r
+            }\r
+\r
+        } else if(parent instanceof Enumeration) {\r
+            Enumeration e = (Enumeration)parent;\r
+            if(name.equals("size") || name.equals("elements"))\r
+                return Boolean.TRUE;\r
+\r
+            for(EnumerationIndex ei : e.getEnumerationIndexes()) {\r
+                if(ei.getName().equals(name)) {\r
+                    return Boolean.TRUE;\r
+                }\r
+            }\r
+\r
+        }\r
+\r
+        return null;\r
+    }\r
+\r
+    @SuppressWarnings("unchecked")\r
+    static private HashMap<ExpressionField ,ArrayList<Position>> getPositionsForVariables(HashMap<ExpressionField, HashMap<String, List<Token>>> references, Set<String> variables) {\r
+        HashMap<ExpressionField ,ArrayList<Position>> result = new HashMap<ExpressionField ,ArrayList<Position>>();\r
+        for(String s : variables) {\r
+            List<Token> tlist = new ArrayList<Token>();\r
+            for(ExpressionField ef : references.keySet()) {\r
+                ArrayList<Position> positions = new ArrayList<Position>();\r
+                tlist = references.get(ef).get(s);\r
+                if(tlist != null)\r
+                    for(Token t : tlist) {\r
+                        StyledText st = ef.getSourceViewer().getTextWidget();\r
+                        if (st != null) {\r
+                            int start =  st.getOffsetAtLine(t.beginLine - 1) + t.beginColumn - 1;\r
+                            int offset = st.getOffsetAtLine(t.endLine - 1) + t.endColumn - start;\r
+                            positions.add(new Position(\r
+                                    start,\r
+                                    offset));\r
+                        }\r
+                    }\r
+                if(result.keySet().contains(ef)) {\r
+                    result.get(ef).addAll((ArrayList<Position>)positions.clone());\r
+                } else {\r
+                    result.put(ef, (ArrayList<Position>)positions.clone());\r
+                }\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/FunctionLibraryNameValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/FunctionLibraryNameValidator.java
new file mode 100644 (file)
index 0000000..bf67e47
--- /dev/null
@@ -0,0 +1,74 @@
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+\r
+/**\r
+ * Name validator for function libraries.\r
+ * @author Tuomas Miettinen\r
+ * \r
+ */\r
+public class FunctionLibraryNameValidator extends NameValidator {\r
+\r
+    @Override\r
+    protected boolean nameIsTaken(ReadGraph graph, Resource functionLibrary, String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        \r
+        if(functionLibrary == null)\r
+            return false;\r
+        \r
+        Resource containingLibrary = graph.getPossibleObject(functionLibrary, l0.PartOf);\r
+        if(containingLibrary == null)\r
+            return true;\r
+        \r
+        // Check if the function is right under the model.\r
+        if (graph.isInstanceOf(containingLibrary, sr.SysdynModel)) {\r
+            Resource configurationResource = graph.getPossibleObject(containingLibrary, SIMU.HasConfiguration);\r
+            if(configurationResource == null)\r
+                return true;\r
+            SysdynModel sysdynModel = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configurationResource);\r
+            sysdynModel.update(graph);\r
+            \r
+            if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, null, name)) return true;\r
+            \r
+            // Check that the functioLibrary name != model name (== containingLibrary name)\r
+            if (NameUtils.getSafeName(graph, containingLibrary).equals(name)) return true;\r
+            \r
+            if (nameTakenByBuiltInFunction(graph, name)) return true;\r
+\r
+            if (nameTakenBySharedFunctionLibrary(graph, containingLibrary, null, name)) return true;\r
+            \r
+            if (nameTakenBySheet(sysdynModel, name)) return true;\r
+        }\r
+\r
+        // Containing library may also be the model\r
+        if (nameTakenByItemUnderLibrary(graph, containingLibrary, functionLibrary, name)) return true;\r
+\r
+        return false;\r
+    }\r
+\r
+    @Override\r
+    public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName)\r
+            throws DatabaseException {\r
+        // TODO Auto-generated method stub\r
+\r
+    }\r
+\r
+    @Override\r
+    public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName)\r
+            throws DatabaseException {\r
+        // TODO Auto-generated method stub\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/FunctionNameValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/FunctionNameValidator.java
new file mode 100644 (file)
index 0000000..95b7d97
--- /dev/null
@@ -0,0 +1,70 @@
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+\r
+/**\r
+ * Name validator for functions.\r
+ * @author Tuomas Miettinen\r
+ * \r
+ */\r
+public class FunctionNameValidator extends NameValidator {\r
+\r
+    @Override\r
+    public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName) throws DatabaseException {\r
+        // TODO\r
+    }\r
+    \r
+    @Override\r
+    public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName) throws DatabaseException {\r
+        // TODO\r
+    }\r
+\r
+    @Override\r
+    protected boolean nameIsTaken(ReadGraph graph, Resource function, String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        \r
+        if(function == null)\r
+            return false;\r
+        \r
+        Resource library = graph.getPossibleObject(function, l0.PartOf);\r
+        if(library == null)\r
+            return true;\r
+        \r
+        // Check if the function is right under the model.\r
+        if (graph.isInstanceOf(library, sr.SysdynModel)) {\r
+            Resource configurationResource = graph.getPossibleObject(library, SIMU.HasConfiguration);\r
+            if(configurationResource == null)\r
+                return true;\r
+            SysdynModel sysdynModel = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configurationResource);\r
+            sysdynModel.update(graph);\r
+            \r
+            if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, null, name)) return true;\r
+            \r
+            // Check that the function name != model name (== library name)\r
+            if (NameUtils.getSafeName(graph, library).equals(name)) return true;\r
+            \r
+            if (nameTakenByBuiltInFunction(graph, name)) return true;\r
+\r
+            if (nameTakenBySharedFunctionLibrary(graph, library, null, name)) return true;\r
+            \r
+            if (nameTakenBySheet(sysdynModel, name)) return true;\r
+        }\r
+\r
+        // Containing library may also be the model\r
+        if (nameTakenByItemUnderLibrary(graph, library, function, name)) return true;\r
+\r
+        return false;\r
+    }\r
+
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/HandlerUtils.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/HandlerUtils.java
new file mode 100644 (file)
index 0000000..cfc8855
--- /dev/null
@@ -0,0 +1,49 @@
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Control;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.simantics.sysdyn.ui.properties.RemoveFocusBeforeExperimentComposite;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionComposite;\r
+\r
+/**\r
+ * Utility methods for handlers.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class HandlerUtils {\r
+    \r
+    /**\r
+     * Save the equation of EquationTab, if the keyboard focus is somewhere inside an EquationTab.\r
+     * \r
+     * @param event ExecutionEvent of which triggering event is used to determine who has focus. \r
+     */\r
+    public static void saveBeforeExperimentRun(ExecutionEvent event) {\r
+        if (event.getTrigger() instanceof Event) {\r
+            Event trigger = (Event)event.getTrigger();\r
+            Control focusControl = trigger.display.getFocusControl();\r
+            if(focusControl == null) {\r
+                new Exception(\r
+                        "Could not determine, if equation needs to be saved before action. focusControl == null")\r
+                .printStackTrace();\r
+                return;\r
+            }\r
+            Composite parent = focusControl.getParent();\r
+            \r
+            /* Scan bottom-up if we come across an EquationTab. \r
+             * If so, ask it to save the expression.*/\r
+            while (parent != null) {\r
+                if (parent instanceof ExpressionComposite) {\r
+                    ExpressionComposite expressionComposite = (ExpressionComposite)parent;\r
+                    expressionComposite.saveExpression();\r
+                    break;\r
+                } else if(parent instanceof RemoveFocusBeforeExperimentComposite) {\r
+                    focusControl.getParent().forceFocus();\r
+                    break;\r
+                }\r
+                parent = parent.getParent();\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ModelNameValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ModelNameValidator.java
new file mode 100644 (file)
index 0000000..ec53c88
--- /dev/null
@@ -0,0 +1,56 @@
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+\r
+/**\r
+ * Name validator for model.\r
+ * @author Tuomas Miettinen\r
+ * \r
+ */\r
+public class ModelNameValidator extends NameValidator {\r
+\r
+    @Override\r
+    protected boolean nameIsTaken(ReadGraph graph, Resource model, String name) throws DatabaseException {\r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        \r
+        if(model == null)\r
+            return false;\r
+\r
+        if (nameTakenByFunctionFunctionLibraryOrModuleType(graph, model, name)) return true;\r
+        \r
+        Resource configurationResource = graph.getPossibleObject(model, SIMU.HasConfiguration);\r
+        if(configurationResource == null)\r
+            return true;\r
+        SysdynModel sysdynModel = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configurationResource);\r
+        sysdynModel.update(graph);\r
+        \r
+        if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, null, name)) return true;\r
+        \r
+        if (nameTakenByBuiltInFunction(graph, name)) return true;\r
+\r
+        if (nameTakenBySharedFunctionLibrary(graph, model, null, name)) return true;\r
+\r
+        if (nameTakenBySheet(sysdynModel, name)) return true;\r
+\r
+        return false;\r
+    }\r
+\r
+    @Override\r
+    public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName)\r
+            throws DatabaseException {\r
+\r
+    }\r
+\r
+    @Override\r
+    public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName)\r
+            throws DatabaseException {\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ModuleTypeNameValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ModuleTypeNameValidator.java
new file mode 100644 (file)
index 0000000..8a3c851
--- /dev/null
@@ -0,0 +1,84 @@
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+\r
+/**\r
+ * Name validator for module types.\r
+ * @author Tuomas Miettinen\r
+ * \r
+ */\r
+public class ModuleTypeNameValidator extends NameValidator {\r
+\r
+    @Override\r
+    protected boolean nameIsTaken(ReadGraph graph, Resource moduleTypeSymbol, String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        ModelingResources mr = ModelingResources.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+        if(moduleTypeSymbol == null)\r
+            return false;\r
+\r
+        Resource moduleType;\r
+        if (graph.isInheritedFrom(moduleTypeSymbol, sr.Module)) {\r
+            // Renamed in model browser\r
+            moduleType = moduleTypeSymbol;\r
+        } else {\r
+            // Renamed in ModuleTypeTab\r
+            moduleType = graph.getPossibleObject(moduleTypeSymbol, mr.SymbolToComponentType);\r
+        }\r
+        if(moduleType == null)\r
+            return true;\r
+        \r
+        // All ModuleTypes are under the top level model\r
+        Resource model = graph.getPossibleObject(moduleType, l0.PartOf);\r
+        if(model == null)\r
+            return true;\r
+\r
+        Resource configurationResource = graph.getPossibleObject(model, SIMU.HasConfiguration);\r
+        if(configurationResource == null)\r
+            return true;\r
+        SysdynModel sysdynModel = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configurationResource);\r
+        sysdynModel.update(graph);\r
+        \r
+        if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, null, name)) return true;\r
+        \r
+        // Check that the module name != model name\r
+        if (NameUtils.getSafeName(graph, model).equals(name)) return true;\r
+        \r
+        if (nameTakenByBuiltInFunction(graph, name)) return true;\r
+\r
+        if (nameTakenBySharedFunctionLibrary(graph, model, null, name)) return true;\r
+        \r
+        if (nameTakenBySheet(sysdynModel, name)) return true;\r
+\r
+        if (nameTakenByItemUnderLibrary(graph, model, moduleType, name)) return true;\r
+\r
+        return false;\r
+    }\r
+\r
+    @Override\r
+    public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName)\r
+            throws DatabaseException {\r
+        // TODO Auto-generated method stub\r
+\r
+    }\r
+\r
+    @Override\r
+    public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName)\r
+            throws DatabaseException {\r
+        // TODO Auto-generated method stub\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/NameValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/NameValidator.java
new file mode 100644 (file)
index 0000000..25d7090
--- /dev/null
@@ -0,0 +1,378 @@
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import java.util.Collection;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.Shadow;\r
+import org.simantics.sysdyn.representation.Sheet;\r
+import org.simantics.sysdyn.representation.Variable;\r
+import org.simantics.sysdyn.ui.modelica.ModelicaSourceViewerConfiguration;\r
+import org.simantics.sysdyn.utils.Function;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+\r
+/**\r
+ * This class is used when renaming an element to check that there\r
+ * are no elements in the database that would cause a conflict. There\r
+ * are two kinds of different conflicts:\r
+ * 1) There is an element in the database which has the same URI.\r
+ *    Adding another causes damage or even a fatal corruption in the \r
+ *    database.\r
+ * 2) Multiple different elements in the database are accessed with\r
+ *    identical identifiers in the generated Modelica model. This will\r
+ *    prevent the simulation from running. \r
+ * \r
+ * @author Tuomas Miettinen\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public abstract class NameValidator {\r
+\r
+    /**\r
+     * This method tells the validator whether the proposed name is taken. To be more precise,\r
+     * it tells if the proposed name should not be used for any reason. E.g. similarly named\r
+     * resources cause problems in some occasions and are fine in others. In addition, there\r
+     * (at least )are two reasons to decline a name proposition: firstly, the data base might\r
+     * have a similarly named entity, and secondly, accepting a proposed name would lead in\r
+     * naming conflicts in the generated OpenModelica model.\r
+     * \r
+     * @param graph\r
+     * @param resource the Resource which is being renamed\r
+     * @param name the proposed name\r
+     * @return true iff the name proposition is denied\r
+     * @throws DatabaseException\r
+     */\r
+    protected abstract boolean nameIsTaken(ReadGraph graph, Resource resource, String name) throws DatabaseException;\r
+\r
+    /**\r
+     * Replaces variable names in all the expressions in the defined configuration. \r
+     * Replace doesn't have to replace words in other configurations than the configuration where the renamed variable is\r
+     * because input variables handle the transitions between configurations (modules).\r
+     * \r
+     * @param graph WriteGraph\r
+     * @param configuration The configuration where the renamed variable is located\r
+     * @param originalName The original name of the variable\r
+     * @param newName New name of the variable\r
+     */\r
+    public abstract void renameInEquations(WriteGraph graph, Resource resource, String originalName, String newName) throws DatabaseException;\r
+\r
+    public abstract void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName) throws DatabaseException;\r
+\r
+    /**\r
+     * Checks that the syntax of the given name is valid and there \r
+     * are no other functions that have the same name in neither the \r
+     * configuration nor among built in functions\r
+     *  \r
+     * @param graph ReadGraph\r
+     * @param resource The variable that is being renamed\r
+     * @param name The new name of the variable\r
+     * @return true iff the new name is valid\r
+     * @throws DatabaseException\r
+     */\r
+    public boolean isValid(ReadGraph graph, Resource resource, String name) throws DatabaseException {\r
+        // Decline empty string\r
+        if(name.length() < 1) return false;\r
+        \r
+        // Decline names based on the type of the resource\r
+        if(nameIsTaken(graph, resource, name)) return false;\r
+        \r
+        // Decline names which are against Modelica naming rules\r
+        boolean allowSpaces = doesResourceAllowSpacedName(graph, resource);\r
+        if(!isValidModelica(name, allowSpaces)) return false;\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Determine whether a Sysdyn Variable can have whitespace in its name (based on its type).\r
+     * @param graph\r
+     * @param resource Resource of the variable\r
+     * @return true iff spaces are allowed in the name\r
+     */\r
+    protected boolean doesResourceAllowSpacedName(ReadGraph graph,\r
+                       Resource resource) {\r
+           SysdynResource sr = SysdynResource.getInstance(graph);\r
+           SpreadsheetResource sheet = SpreadsheetResource.getInstance(graph);\r
+       try {\r
+               if (resource == null)\r
+                       return false;\r
+               // Function, FunctionLibrary, and SharedFunctionLibrary are not\r
+               // allowed to have whitespace.\r
+               if (graph.isInstanceOf(resource, sr.Variable)\r
+//                                     || graph.isInstanceOf(resource, sr.Module)\r
+//                                     || graph.isInstanceOf(resource, sr.ModuleType)\r
+                                       || graph.isInstanceOf(resource, sr.Enumeration)\r
+                                       || graph.isInstanceOf(resource, sr.EnumerationIndex)\r
+                                       || graph.isInstanceOf(resource, sheet.Spreadsheet)\r
+                                       || graph.isInstanceOf(resource, sr.SysdynModel)) {\r
+                               return true;\r
+                       }\r
+               } catch (ServiceException e) {\r
+                       // TODO Auto-generated catch block\r
+                       e.printStackTrace();\r
+               }\r
+       return false;\r
+       }\r
+\r
+       /**\r
+     * Checks that the syntax of the given name is valid and there \r
+     * are no other variables that have the same name in the configuration\r
+     *  \r
+     * @param variable The variable that is being renamed\r
+     * @param name The new name of the variable\r
+     * @return true iff the new name is valid\r
+     * @throws DatabaseException\r
+     */\r
+    public boolean isValid(final Resource resource, final String name) {\r
+        boolean result = false;\r
+\r
+        try {\r
+            result = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
+\r
+                @Override\r
+                public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                    return isValid(graph, resource, name);\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * Checks that the syntax of the given name is valid \r
+     * and that it is not a keyword in Modelica.\r
+     * \r
+     * @param name name that is validated\r
+     * @return true iff the syntax of the name is valid\r
+     */\r
+    public boolean isValidModelica(String name, boolean allowSpaces) {\r
+        String lowerCase = name.toLowerCase();\r
+        String pattern = "[a-zA-Z][a-zA-Z0-9]*" + (allowSpaces ? "( [a-zA-Z][a-zA-Z0-9]*)*" : "");\r
+        Pattern p = Pattern.compile(pattern);\r
+        Matcher m = p.matcher(lowerCase);\r
+        if (!m.matches()) {\r
+            return false;\r
+        } else {\r
+               String[] splitNames= name.split("\\s+");\r
+               for (String splitName : splitNames) {\r
+                       // Do not allow Modelica keywords to be a part of a whitespaced name\r
+                       if (ModelicaSourceViewerConfiguration.keywords.contains(splitName)) {\r
+                               return false;\r
+                       }\r
+               }\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Checks that there is no similarly named spread sheet in the top level model.\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param configurationResource Resource of the configuration of the model\r
+     * @param resource Resource being validated\r
+     * @param name proposed new name for resource\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    protected boolean nameTakenBySheet(\r
+            ReadGraph graph, \r
+            Resource configurationResource, \r
+            Resource resource, \r
+            String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);\r
+        for (Resource r : graph.getObjects(configurationResource, l0.ConsistsOf)) {\r
+            if (graph.isInstanceOf(r, SHEET.Book)) {\r
+                for (Resource s : graph.getObjects(r, l0.ConsistsOf)) {\r
+                    if (NameUtils.getSafeName(graph, s).equals(name) && !s.equals(resource)) {\r
+                        return true;\r
+                    }\r
+                }\r
+                // Assume only one book\r
+                break;\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    /**\r
+     * Checks that there is no similarly named spread sheet in the top level model.\r
+     * \r
+     * @param sysdynModel the model\r
+     * @param name proposed new name for resource\r
+     * @return\r
+     */\r
+    public boolean nameTakenBySheet(\r
+            SysdynModel sysdynModel, \r
+            String name) {\r
+       Configuration configuration = sysdynModel.getConfiguration();\r
+        if (configuration == null)\r
+            return true;\r
+        for (IElement e : configuration.getElements()) {\r
+            if (e instanceof Sheet) {\r
+                if (((Sheet)e).getName().equals(name)) {\r
+                    return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * Check that there are no similarly named functions, module types, or any\r
+     * other items in the same library. There are actually plenty of items that have\r
+     * to be avoided, probably all of them, they are all included in this test. \r
+     * \r
+     * @param graph ReadGraph\r
+     * @param library Resource which is studied\r
+     * @param resource Resource being validated\r
+     * @param name proposed new name for resource\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    protected boolean nameTakenByItemUnderLibrary(\r
+            ReadGraph graph,\r
+            Resource library,\r
+            Resource resource,\r
+            String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        for (Resource r : graph.getObjects(library, l0.ConsistsOf)) {\r
+            if (NameUtils.getSafeName(graph, r).equals(name) && !r.equals(resource)) {\r
+                return true;\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    /**\r
+     * Check that there is no similarly named function library among shared function libraries.\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param model resource of the top level model under which the resource is\r
+     * @param resource Resource being validated\r
+     * @param name proposed new name for resource\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    protected boolean nameTakenBySharedFunctionLibrary(\r
+            ReadGraph graph,\r
+            Resource model, \r
+            Resource resource,\r
+            String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Collection<Resource> linkedResources = graph.getObjects(model, l0.IsLinkedTo);\r
+        for (Resource r : linkedResources) {\r
+            // Find the "Shared functions" library \r
+            if (graph.isInstanceOf(r, sr.SharedFunctionOntology)) {\r
+                if (NameUtils.getSafeName(graph, r).equals(name) && !r.equals(resource)) {\r
+                    return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    /**\r
+     * Check that there is no similarly named function among built-in functions\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param name name that is checked\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    protected boolean nameTakenByBuiltInFunction(\r
+            ReadGraph graph, \r
+            String name) throws DatabaseException {\r
+        for (Function f : Function.getAllBuiltInFunctions(graph)) {\r
+            if (f.getName().equals(name)) {\r
+                return true;\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    /**\r
+     * Check that the top level of the model doesn't contain \r
+     * a variable or module with the same name.\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param sysdynModel the model\r
+     * @param resource Resource being validated\r
+     * @param name proposed new name for resource\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    protected boolean nameTakenByTopLevelVariableOrModule(\r
+            ReadGraph graph,\r
+            SysdynModel sysdynModel,\r
+            Resource resource,\r
+            String name) throws DatabaseException {\r
+        Configuration configuration = sysdynModel.getConfiguration();\r
+        if(configuration == null)\r
+            return true;\r
+        IElement current = sysdynModel.getElement(resource);\r
+        for(IElement e : configuration.getElements()) {\r
+            if(e instanceof Variable && !(e instanceof Shadow)) {\r
+                Variable v = (Variable) e;\r
+                if(!v.equals(current) && v.getName() != null && v.getName().equals(name)) {\r
+                    return true;\r
+                }\r
+            } else if (e instanceof Module) {\r
+                Module m = (Module)e;\r
+                if(!m.equals(current) && m.getName() != null && m.getName().equals(name)) {\r
+                    return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    /**\r
+     * Check that there is no similarly named function, function library,\r
+     * or module type directly under a library\r
+     * \r
+     * This function should not be used by functions, function libraries, or module types\r
+     *\r
+     * @param graph ReadGraph\r
+     * @param library Resource which is studied\r
+     * @param name proposed new name for resource\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    protected boolean nameTakenByFunctionFunctionLibraryOrModuleType(\r
+            ReadGraph graph,\r
+            Resource library,\r
+            String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        for (Resource r : graph.getObjects(library, l0.ConsistsOf)) {\r
+            if (graph.isInstanceOf(r, sr.SysdynModelicaFunctionLibrary)\r
+                    || graph.isInstanceOf(r, sr.SysdynModelicaFunction)\r
+                    || graph.isInheritedFrom(r, sr.Module)) {\r
+                if (NameUtils.getSafeName(graph, r).equals(name)) {\r
+                    return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/OldTransferableGraph1.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/OldTransferableGraph1.java
new file mode 100644 (file)
index 0000000..558f5a3
--- /dev/null
@@ -0,0 +1,76 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.Binding;\r
+import org.simantics.databoard.serialization.Serializer;\r
+import org.simantics.graph.representation.External;\r
+import org.simantics.graph.representation.Identity;\r
+import org.simantics.graph.representation.Internal;\r
+import org.simantics.graph.representation.Root;\r
+import org.simantics.graph.representation.TransferableGraph1;\r
+import org.simantics.graph.representation.Value;\r
+\r
+\r
+/**\r
+ * Transferable graph datatype. \r
+ * See <a href="https://www.simantics.org/wiki/index.php/Graph_exchange_format">specification</a>. \r
+ * @author Hannu Niemistö\r
+ */\r
+public class OldTransferableGraph1 {\r
+       public static Binding BINDING = Bindings.getBindingUnchecked(TransferableGraph1.class);\r
+       public static Serializer SERIALIZER = Bindings.getSerializerUnchecked(BINDING);\r
+       \r
+       public int resourceCount;\r
+       public Identity[] identities;   \r
+       public int[] statements;\r
+       public Value[] values;  \r
+       \r
+       public OldTransferableGraph1() {\r
+       }\r
+       \r
+       public OldTransferableGraph1(int resourceCount, Identity[] identities,\r
+                       int[] statements, Value[] values) {\r
+               this.resourceCount = resourceCount;\r
+               this.identities = identities;\r
+               this.statements = statements;\r
+               this.values = values;\r
+       }\r
+\r
+       public void print() {\r
+               System.out.println("Identities");\r
+               for(Identity id : identities) {\r
+                       System.out.print("    " + id.resource + " = ");\r
+                       if(id.definition instanceof Root) {\r
+                               Root def = (Root)id.definition;\r
+                               System.out.println("ROOT(" + def.name + ")");\r
+                       }\r
+                       else if(id.definition instanceof External) {\r
+                               External def = (External)id.definition;\r
+                               System.out.println("EXTERNAL(" + def.parent + ", " + def.name + ")");\r
+                       }\r
+                       else if(id.definition instanceof Internal) {\r
+                               Internal def = (Internal)id.definition;\r
+                               System.out.println("INTERNAL(" + def.parent + ", " + def.name + ")");\r
+                       }\r
+               }\r
+               System.out.println("Statements:");\r
+               for(int i=0;i<statements.length;i+=4)\r
+                       System.out.println("    " + \r
+                                       statements[i] + " " +\r
+                                       statements[i+1] + " " +\r
+                                       statements[i+2] + " " +\r
+                                       statements[i+3]\r
+                                       );\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SharedFunctionLibraryNameValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SharedFunctionLibraryNameValidator.java
new file mode 100644 (file)
index 0000000..d48e025
--- /dev/null
@@ -0,0 +1,70 @@
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+\r
+/**\r
+ * Name validator for shared function libraries.\r
+ * @author Tuomas Miettinen\r
+ * \r
+ */\r
+public class SharedFunctionLibraryNameValidator extends NameValidator {\r
+\r
+    @Override\r
+    protected boolean nameIsTaken(ReadGraph graph, Resource functionLibrary, String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        \r
+        if(functionLibrary == null)\r
+            return false;\r
+        \r
+        // Do the checking for all models that are linked to that shared function library\r
+        for (Resource model : graph.getObjects(functionLibrary, l0.IsLinkedTo_Inverse)) {\r
+            if(model == null)\r
+                return true;\r
+\r
+            Resource configurationResource = graph.getPossibleObject(model, SIMU.HasConfiguration);\r
+            if(configurationResource == null)\r
+                return true;\r
+            SysdynModel sysdynModel = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configurationResource);\r
+            sysdynModel.update(graph);\r
+            \r
+            if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, null, name)) return true;\r
+\r
+            // Check that the functionLibrary name != model name\r
+            if (NameUtils.getSafeName(graph, model).equals(name)) return true;\r
+            \r
+            if (nameTakenByBuiltInFunction(graph, name)) return true;\r
+\r
+            if (nameTakenBySharedFunctionLibrary(graph, model, functionLibrary, name)) return true;\r
+            \r
+            if (nameTakenBySheet(sysdynModel, name)) return true;\r
+            \r
+            if (nameTakenByItemUnderLibrary(graph, model, null, name)) return true;\r
+        }\r
+        \r
+        return false;\r
+    }\r
+\r
+    @Override\r
+    public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName)\r
+            throws DatabaseException {\r
+        // TODO Auto-generated method stub\r
+\r
+    }\r
+\r
+    @Override\r
+    public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName)\r
+            throws DatabaseException {\r
+        // TODO Auto-generated method stub\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SheetNameValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SheetNameValidator.java
new file mode 100644 (file)
index 0000000..115f58e
--- /dev/null
@@ -0,0 +1,70 @@
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+\r
+/**\r
+ * Name validator for spread sheets.\r
+ * @author Tuomas Miettinen\r
+ * \r
+ */\r
+public class SheetNameValidator extends NameValidator {\r
+\r
+    @Override\r
+    protected boolean nameIsTaken(ReadGraph graph, Resource sheet, String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        \r
+        if(sheet == null)\r
+            return false;\r
+        \r
+        Resource book = graph.getPossibleObject(sheet, l0.PartOf);\r
+        if(book == null)\r
+            return true;\r
+        \r
+        Resource configurationResource = graph.getPossibleObject(book, l0.PartOf);\r
+        if(configurationResource == null)\r
+            return true;\r
+        SysdynModel sysdynModel = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configurationResource);\r
+        sysdynModel.update(graph);\r
+        \r
+        Resource model = graph.getPossibleObject(configurationResource, l0.PartOf);\r
+        if(model == null)\r
+            return true;\r
+\r
+        if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, sheet, name)) return true;\r
+        \r
+        // Check that the sheet name != model name\r
+        if (NameUtils.getSafeName(graph, model).equals(name)) return true;\r
+        \r
+        if (nameTakenByBuiltInFunction(graph, name)) return true;\r
+\r
+        if (nameTakenBySharedFunctionLibrary(graph, model, null, name)) return true;\r
+        \r
+        if (nameTakenBySheet(graph, configurationResource, sheet, name)) return true;\r
+\r
+        if (nameTakenByItemUnderLibrary(graph, model, null, name)) return true;\r
+\r
+        return false;\r
+    }\r
+\r
+    @Override\r
+    public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName)\r
+            throws DatabaseException {\r
+        // TODO Auto-generated method stub\r
+\r
+    }\r
+\r
+    @Override\r
+    public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName)\r
+            throws DatabaseException {\r
+        // TODO Auto-generated method stub\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SyntaxError.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SyntaxError.java
new file mode 100644 (file)
index 0000000..9497924
--- /dev/null
@@ -0,0 +1,224 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.eclipse.jface.text.BadLocationException;\r
+import org.eclipse.jface.text.IDocument;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;\r
+\r
+/**\r
+ * Class for containing errors caught in expression validation\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SyntaxError {\r
+    \r
+    private String type, message, image;\r
+    private int beginLine, beginColumn, endLine, endColumn;\r
+    private Integer start, offset;\r
+    \r
+    /**\r
+     * A syntax error without any info. Remember to assign location, \r
+     * type and message information.\r
+     */\r
+    public SyntaxError() {\r
+        \r
+    }\r
+    \r
+    /**\r
+     * Creates an error from expression parser token\r
+     * @param token expressionParser token\r
+     * @param message Error message\r
+     */\r
+    public SyntaxError(Token token, String message){\r
+        this(token.image, message, token.beginLine, token.beginColumn, token.endLine, token.endColumn);\r
+    }\r
+    \r
+    /**\r
+     * Creates an error from table parser token\r
+     * @param token tableParser token\r
+     * @param message Error message\r
+     */\r
+    public SyntaxError(org.simantics.sysdyn.tableParser.Token token, String message){\r
+        this(token.image, message, token.beginLine, token.beginColumn, token.endLine, token.endColumn);\r
+    }\r
+    \r
+    /**\r
+     * Create syntax error with full data\r
+     * @param image\r
+     * @param message\r
+     * @param beginLine\r
+     * @param beginColumn\r
+     * @param endLine\r
+     * @param endColumn\r
+     */\r
+    public SyntaxError(String image, String message, int beginLine, int beginColumn, int endLine, int endColumn) {\r
+        this.image = image;\r
+        this.message = message;\r
+        this.beginLine = beginLine;\r
+        this.beginColumn = beginColumn;\r
+        this.endLine = endLine;\r
+        this.endColumn = endColumn;\r
+        this.type = ExpressionField.SYNTAX_ERROR;\r
+    }\r
+    \r
+    /**\r
+     * Create syntax error with location, message and type data\r
+     * @param start\r
+     * @param offset\r
+     * @param type\r
+     * @param message\r
+     */\r
+    public SyntaxError(int start, int offset, String type, String message) {\r
+        this(start, offset, type, message, null);\r
+    }\r
+    \r
+    /**\r
+     * Create syntax error with location, message and type data\r
+     * @param start\r
+     * @param offset\r
+     * @param type\r
+     * @param message\r
+     */\r
+    public SyntaxError(int start, int offset, String type, String message, String image) {\r
+        this.image = image;\r
+        this.start = start;\r
+        this.offset = offset;\r
+        this.type = type;\r
+        this.message = message;\r
+    }\r
+    \r
+    /**\r
+     * Get start location of the issue. If start has not been set,\r
+     * document is used to calculate it.\r
+     * @param document\r
+     * @return\r
+     */\r
+    public int getStart(IDocument document) {\r
+        if(this.start != null)\r
+            return this.start;\r
+        else if(document != null){\r
+            int start = 0;\r
+            if(document.getLength() > 0) {\r
+                try {\r
+                    start = document.getLineOffset(beginLine - 1) + beginColumn - 1;\r
+                } catch (BadLocationException e) {\r
+                    //e.printStackTrace();\r
+                }\r
+            }\r
+            return start;\r
+        } else {\r
+            return 0;\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Get offset data of the issue. If offset has not been set,\r
+     * document is used to calculate it.\r
+     * \r
+     * @param document\r
+     * @return\r
+     */\r
+    public int getOffset(IDocument document) {\r
+        if(this.offset != null) \r
+            return this.offset;\r
+        else if(document != null){\r
+            int start = getStart(document);\r
+            int offset = document.getLength();\r
+            if(document.getLength() > 0) {\r
+                try {\r
+                    offset = document.getLineOffset(endLine - 1) + endColumn - start;\r
+                } catch (BadLocationException e) {\r
+                    //e.printStackTrace();\r
+                }\r
+            }\r
+            return offset;\r
+        } else {\r
+            return 0;\r
+        }\r
+    }\r
+    \r
+    public void setToken(Token token){\r
+       this.image = token.image;\r
+       this.beginLine = token.beginLine;\r
+       this.beginColumn = token.beginColumn;\r
+       this.endLine = token.endLine;\r
+       this.endColumn = token.endColumn;\r
+    }\r
+    \r
+    public void setToken(org.simantics.sysdyn.tableParser.Token token){\r
+        this.image = token.image;\r
+        this.beginLine = token.beginLine;\r
+        this.beginColumn = token.beginColumn;\r
+        this.endLine = token.endLine;\r
+        this.endColumn = token.endColumn;\r
+    }\r
+    \r
+    public String getType() {\r
+        return type;\r
+    }\r
+\r
+    public void setType(String type) {\r
+        this.type = type;\r
+    }\r
+\r
+    public String getMessage() {\r
+        return message;\r
+    }\r
+\r
+    public void setMessage(String message) {\r
+        this.message = message;\r
+    }\r
+\r
+    public String getImage() {\r
+        return image;\r
+    }\r
+\r
+    public void setImage(String image) {\r
+        this.image = image;\r
+    }\r
+\r
+    public int getBeginLine() {\r
+        return beginLine;\r
+    }\r
+\r
+    public void setBeginLine(int beginLine) {\r
+        this.beginLine = beginLine;\r
+    }\r
+\r
+    public int getBeginColumn() {\r
+        return beginColumn;\r
+    }\r
+\r
+    public void setBeginColumn(int beginColumn) {\r
+        this.beginColumn = beginColumn;\r
+    }\r
+\r
+    public int getEndLine() {\r
+        return endLine;\r
+    }\r
+\r
+    public void setEndLine(int endLine) {\r
+        this.endLine = endLine;\r
+    }\r
+\r
+    public int getEndColumn() {\r
+        return endColumn;\r
+    }\r
+\r
+    public void setEndColumn(int endColumn) {\r
+        this.endColumn = endColumn;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SysdynWorkbenchUtils.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/SysdynWorkbenchUtils.java
new file mode 100644 (file)
index 0000000..987fce9
--- /dev/null
@@ -0,0 +1,95 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+\r
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import org.eclipse.ui.IEditorPart;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.eclipse.ui.IWorkbenchPage;\r
+import org.eclipse.ui.IWorkbenchWindow;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.g2d.canvas.ICanvasContext;\r
+import org.simantics.g2d.canvas.IToolMode;\r
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
+import org.simantics.sysdyn.ui.elements.SysdynElementHints;\r
+import org.simantics.utils.datastructures.hints.IHintContext;\r
+import org.simantics.utils.threads.ThreadUtils;\r
+\r
+/**\r
+ * Workbench utilities.\r
+ * \r
+ * @author Tuomas Miettinen\r
+ */\r
+public class SysdynWorkbenchUtils {\r
+\r
+       /**\r
+        * Get the active page of the diagram editor.\r
+        * \r
+        * @return active page of the diagram editor.\r
+        */\r
+       public static IWorkbenchPage getActivePageOfEditor() {\r
+               DiagramEditor editor = null;\r
+               IWorkbench workbench = PlatformUI.getWorkbench();\r
+               IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();\r
+               IWorkbenchPage page = null;\r
+               // To ask for the active window doesn't work, so browse through all\r
+               // windows and when an active editor is found, use that\r
+               for (IWorkbenchWindow window : windows) {\r
+                       page = window.getActivePage();\r
+                       if (page != null) {\r
+                               try {\r
+                           editor = (DiagramEditor)page.getActiveEditor();\r
+                           if (editor != null)\r
+                                       // Found one\r
+                                       break;\r
+                               } catch (ClassCastException e) {\r
+                                       continue;\r
+                   }\r
+                       }\r
+               }\r
+               return page;\r
+       }\r
+       \r
+       public static IToolMode getSysdynToolMode() {\r
+               IWorkbenchPage p = SysdynWorkbenchUtils.getActivePageOfEditor();\r
+               IEditorPart editor = p.getActiveEditor();\r
+               final ICanvasContext context = (ICanvasContext)(editor.getAdapter(ICanvasContext.class));\r
+               ToolQuery toolQuery = new ToolQuery(context);\r
+               ThreadUtils.syncExec(context.getThreadAccess(), toolQuery);\r
+               return toolQuery.getSysdynToolMode();\r
+       }\r
+\r
+       static class ToolQuery implements Runnable {\r
+\r
+               private IToolMode mode;\r
+               private ICanvasContext context;\r
+               \r
+               ToolQuery(ICanvasContext context) {\r
+                       this.context = context;\r
+                       this.mode = null;\r
+               }\r
+               \r
+               @Override\r
+               public void run() {\r
+                       IHintContext hc = context.getDefaultHintContext();\r
+                       if (hc == null)\r
+                               return;\r
+                       IToolMode sysdynMode = hc.getHint(SysdynElementHints.SYSDYN_KEY_TOOL);\r
+                       mode = sysdynMode;\r
+               }\r
+               \r
+               public IToolMode getSysdynToolMode() {\r
+                       return mode;\r
+               }\r
+               \r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/VariableNameValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/VariableNameValidator.java
new file mode 100644 (file)
index 0000000..b818a50
--- /dev/null
@@ -0,0 +1,267 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils;\r
+\r
+import java.io.StringReader;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.StringTokenizer;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.Model;\r
+import org.simantics.sysdyn.representation.ModuleType;\r
+import org.simantics.sysdyn.utils.ModelUtils;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Name validator for variables, modules, and enumerations.\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ * \r
+ */\r
+public class VariableNameValidator extends NameValidator {\r
+\r
+       @Override\r
+    public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName) throws DatabaseException {\r
+               /*FIXME: \r
+                * How this works when range used in equations has the same string as\r
+                * the renamed variable? Should it be possible? \r
+                */ \r
+        if(originalName.equals(newName))\r
+            return; // Do nothing\r
+               \r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+        Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);\r
+        if(expressions  != null) {\r
+            List<Resource> expressionList = ListUtils.toList(graph, expressions);\r
+            for(Resource s : expressionList) {\r
+                for(Resource p : graph.getPredicates(s)) {\r
+                    Resource o = graph.getPossibleObject(s, p);\r
+                    if(o != null && graph.isInstanceOf(o, l0.String) && !p.equals(sr.Expression_arrayRange)) {\r
+                        String string = graph.getRelatedValue(s, p);\r
+                        String replaced  = replaceAllWords(string, originalName, newName);\r
+                        if(!string.equals(replaced))\r
+                               graph.claimLiteral(s, p, replaced);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+       }\r
+       \r
+       @Override\r
+    public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName) throws DatabaseException {\r
+           if(originalName.equals(newName))\r
+               return; // Do nothing\r
+\r
+           Layer0 l0 = Layer0.getInstance(graph);\r
+           SysdynResource sr = SysdynResource.getInstance(graph);\r
+           for(Resource r : graph.getObjects(configuration, l0.ConsistsOf)) {\r
+               if(graph.isInstanceOf(r, sr.IndependentVariable)) {\r
+                   renameInEquations(graph, r, originalName, newName);\r
+               }\r
+           }\r
+       }\r
+\r
+       private static String replaceAllWords(String original, String find, String replacement) {\r
+               // Test if the new name (String find) is found in the original \r
+               // string in some format.\r
+               String pattern = "(.|\r|\n)*" + find.replace(" ", "\\s+") + "(.|\r|\n)*";\r
+               if(!original.matches(pattern)) return original;\r
+               if (find.equals(replacement)) return original;\r
+\r
+        ExpressionParser parser = new ExpressionParser(new StringReader(original));\r
+        try {\r
+                       parser.expr();\r
+               } catch (ParseException e) {\r
+                       // Best effort; if there are syntax errors, the replace may fail.\r
+               }\r
+        \r
+        // Collect all references\r
+        HashMap<String, List<Token>> allReferences = new HashMap<String, List<Token>>();\r
+        allReferences.putAll(parser.getReferences());\r
+        allReferences.putAll(parser.getFunctionCallReferences());\r
+        allReferences.putAll(parser.getEnumerationReferences());\r
+               \r
+        List<Token> replacedTokens = allReferences.get(find);\r
+        if (replacedTokens == null)\r
+               return original;\r
+        \r
+        // Sort the tokens so that they are in the reversed order based on\r
+        // their location in the expression.\r
+        Collections.sort(replacedTokens);\r
+        Collections.reverse(replacedTokens);\r
+        \r
+        // Go through the tokens in the reversed order\r
+        String result = new String(original);\r
+               for (Token token : replacedTokens) {\r
+               // Find the place where the last token points to in the original string\r
+               // First find where the correct line starts:\r
+               int startingPoint = 0;\r
+               for (int i = 0; i < token.beginLine - 1; ++i)\r
+                       startingPoint = result.indexOf('\n', startingPoint) + 1;\r
+               // Then where the replaced string starts: \r
+               startingPoint += token.beginColumn - 1;\r
+               \r
+               // Cut the string\r
+               String begin = result.substring(0, startingPoint);\r
+               String end = result.substring(startingPoint);\r
+               \r
+               // Replace the string\r
+               String regex = find.replaceAll(" ", "\\\\s+");\r
+               end = end.replaceFirst(regex, replacement);\r
+               result = begin + end;\r
+        }\r
+               \r
+               return result;\r
+       }\r
+\r
+\r
+       @Override\r
+    protected boolean nameIsTaken(ReadGraph graph, Resource variable, String name) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+        if(variable == null)\r
+                       return false;\r
+        \r
+               SysdynModel sysdynModel = ModelUtils.getModel(graph, variable);\r
+               if(sysdynModel == null)\r
+                       return true;\r
+               sysdynModel.update(graph);\r
+        \r
+               Configuration configuration = sysdynModel.getConfiguration();\r
+               if(configuration == null)\r
+                   return true;\r
+               \r
+               // Get the top level model\r
+        Model rootModel = null;\r
+        ModuleType moduleType = configuration.getModuleType();\r
+        if (moduleType != null) {\r
+            Object o = moduleType.getParent();\r
+            if (o instanceof Model) {\r
+                rootModel = (Model)o;\r
+            }\r
+        } else {\r
+            rootModel = configuration.getModel();\r
+        }\r
+        \r
+        // Get the top level model (SysdynModel)\r
+        // Resource library should be used with care if it is not instance of sr.SysdynModel\r
+        Resource library = graph.getPossibleObject(variable, l0.PartOf);\r
+        if(library == null) {\r
+            return true;\r
+        } else {\r
+            library = graph.getPossibleObject(library, l0.PartOf);\r
+            if(library == null) {\r
+                return true;\r
+            }\r
+        }\r
+\r
+               // Check if the function is right under the model.\r
+        if (graph.isInstanceOf(library, sr.SysdynModel)) {\r
+            // Check that the function name != model name (== library name)\r
+            if (NameUtils.getSafeName(graph, library).equals(name)) return true;\r
+            \r
+            if (nameTakenByBuiltInFunction(graph, name)) return true;\r
+\r
+            if (nameTakenBySharedFunctionLibrary(graph, library, null, name)) return true;\r
+            \r
+            if (nameTakenBySheet(sysdynModel, name)) return true;\r
+        }\r
+\r
+               if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, variable, name)) return true;\r
+\r
+               if (rootModel != null) {\r
+                   // Browse through all ModuleTypes within the whole model\r
+               if (rootModel.containsModuleType(name))\r
+                       return true;\r
+               }\r
+               \r
+               if (nameTakenByFunctionFunctionLibraryOrModuleType(graph, library, name)) return true;\r
+               \r
+               return false;\r
+       }\r
+\r
+       /**\r
+        * Checks that the syntax of the given name is valid and there \r
+        * are no other variables that have the same name in the configuration\r
+        *  \r
+        * @param graph ReadGraph\r
+        * @param variable The variable that is being renamed\r
+        * @param name The new name of the variable\r
+        * @return\r
+        * @throws DatabaseException\r
+        */\r
+       public boolean isValid(ReadGraph graph, Resource variable, String name, boolean hasRange) throws DatabaseException {\r
+           if(hasRange) {\r
+                       String range = null;\r
+                       if(name.contains("[")) {\r
+                               StringTokenizer st = new StringTokenizer(name, "[]", true);\r
+                               if(st.countTokens() != 4)\r
+                                       return false;\r
+                               name = st.nextToken();\r
+                               if(!st.nextToken().equals("[")) return false;\r
+                               range = st.nextToken();\r
+                               if(!st.nextToken().equals("]")) return false;\r
+                       }\r
+                       if(range != null && !ArrayVariableUtils.isRangeValid(graph, variable, range)) return false;\r
+               }\r
+               return isValid(graph, variable, name);\r
+       }\r
+\r
+       \r
+       /**\r
+        * Checks that the syntax of the given name is valid and there \r
+        * are no other variables that have the same name in the configuration\r
+        *  \r
+        * @param variable The variable that is being renamed\r
+        * @param name The new name of the variable\r
+        * @return\r
+        * @throws DatabaseException\r
+        */\r
+       public boolean isValid(final Resource variable, final String name, final boolean hasRange) {\r
+               if (variable == null || name == null)\r
+                       return false;\r
+               \r
+               boolean result = false;\r
+               try {\r
+                       result = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
+\r
+                               @Override\r
+                               public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                                       return isValid(graph, variable, name, hasRange);\r
+                               }\r
+\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               return result;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/ImportUtilsUI.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/ImportUtilsUI.java
new file mode 100644 (file)
index 0000000..9aa85f8
--- /dev/null
@@ -0,0 +1,63 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4192\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils.imports;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.utils.imports.ImportUtils;\r
+\r
+/**\r
+ * Utilities for importing tg files: Models, Modules and Function libraries\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ImportUtilsUI {\r
+\r
+    public static String IMPORTMODELTPATH = "IMPORT_MODEL_PATH";\r
+    public static String IMPORTMODULETPATH = "IMPORT_MODULE_PATH";\r
+    public static String IMPORTFUNCTIONLIBRARYPATH = "IMPORT_FUNCTION_LIBRARY_PATH";\r
+\r
+\r
+    /* ********************************* */\r
+    /* *******   IMPORT MODEL  ********* */\r
+    /* ********************************* */\r
+    public static IStatus importModelFile(String path, IProgressMonitor monitor) throws Exception {\r
+        Activator.getDefault().getPreferenceStore().setValue(IMPORTMODELTPATH, (new File(path)).getParent());\r
+        return ImportUtils.importModelFile(path, monitor);\r
+    }\r
+\r
+\r
+    /* ********************************* */\r
+    /* *******  IMPORT MODULE  ********* */\r
+    /* ********************************* */\r
+    public static IStatus importModuleFile(Resource model, String path, IProgressMonitor monitor) {\r
+        Activator.getDefault().getPreferenceStore().setValue(IMPORTMODULETPATH, (new File(path)).getParent());\r
+        return ImportUtils.importModuleFile(model, path, monitor);\r
+    }\r
+\r
+\r
+\r
+    /* ********************************* */\r
+    /* ***  IMPORT FUNCTION LIBRARY  *** */\r
+    /* ********************************* */\r
+\r
+    public static IStatus importFunctionLibrary(Resource functionLibrary, String path, IProgressMonitor monitor) {\r
+        Activator.getDefault().getPreferenceStore().setValue(IMPORTFUNCTIONLIBRARYPATH, (new File(path)).getParent());\r
+        return ImportUtils.importFunctionLibrary(functionLibrary, path, monitor);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/DependencyFunction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/DependencyFunction.java
new file mode 100644 (file)
index 0000000..99865d0
--- /dev/null
@@ -0,0 +1,350 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.Issue;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.scl.reflection.annotations.SCLValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;\r
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
+import org.simantics.sysdyn.ui.utils.ExpressionUtils.ReferenceOption;\r
+import org.simantics.sysdyn.ui.utils.SyntaxError;\r
+import org.simantics.utils.datastructures.collections.CollectionUtils;\r
+\r
+/**\r
+ * Evaluates issues related to Dependencies (arrows)\r
+ * \r
+ * @author Teemu Lempinen\r
+ * \r
+ */\r
+public class DependencyFunction {\r
+       \r
+       // Set containing the names of variables that can be used everywhere, like "time"\r
+       private static Set<String> GLOBAL_VARIABLES = CollectionUtils.toSet("time");\r
+\r
+    /**\r
+     * Evaluates dependency-related issues for a component.\r
+     * \r
+     * Issues include: Unused dependency\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param component Evaluated component (Variable)\r
+     * @return list of issues related to component\r
+     * @throws DatabaseException\r
+     */\r
+    @SCLValue(type = "ReadGraph -> Resource -> [Issue]")\r
+    public static List<Issue> dependencyValidator(ReadGraph graph, Resource component) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+        if (!graph.isInstanceOf(component, sr.IndependentVariable))\r
+            return Collections.emptyList();\r
+\r
+        if (!graph.hasStatement(component) || !graph.hasStatement(component, l0.PartOf))\r
+            return Collections.emptyList();\r
+        \r
+        ArrayList<Issue> result = new ArrayList<Issue>();\r
+        Set<String> references = null;\r
+        \r
+        // Find all references in equations of component\r
+        try {\r
+            references = ValidationUtils.getAllReferences(graph, component).getVariableReferences();\r
+        } catch (Exception e) {\r
+            return result;\r
+        } \r
+\r
+        // Find all variables that are linked to component with arrows\r
+        Set<String> dependencies = ValidationUtils.getDependencies(graph, component);\r
+\r
+        // Check that all arrow dependencies are used in equations\r
+        if (dependencies != null) {\r
+            for (String dependency : dependencies) {\r
+                if (references == null || !references.contains(dependency)) {\r
+                    result.add(new IssueWithStringContext(sr.Validations_UnusedDependencyIssue, component, dependency));\r
+                }\r
+            }\r
+        }\r
+\r
+        return result;\r
+    }\r
+    \r
+\r
+    private static Configuration getConfiguration(ReadGraph graph, Resource component) throws DatabaseException {\r
+        Resource configuration = graph.getPossibleObject(component, Layer0.getInstance(graph).PartOf);\r
+        \r
+        if(configuration == null)\r
+            return null;\r
+        \r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        SysdynModel sm = smm.getModel(graph, configuration);\r
+        if(sm == null)\r
+            return null;\r
+\r
+        sm.update(graph);\r
+        return sm.getConfiguration();\r
+    }\r
+\r
+    /**\r
+     * Evaluates dependency-related issues for a component.\r
+     * \r
+     * Issues include: Missing link No such variable\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param component Evaluated component (Variable)\r
+     * @return list of issues related to component\r
+     * @throws DatabaseException\r
+     */\r
+    @SCLValue(type = "ReadGraph -> Resource -> [Issue]")\r
+    public static List<Issue> missingDependencyValidator(ReadGraph graph, Resource component) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+        if (!graph.isInstanceOf(component, sr.IndependentVariable))\r
+            return Collections.emptyList();\r
+\r
+        if (!graph.hasStatement(component) || !graph.hasStatement(component, l0.PartOf))\r
+            return Collections.emptyList();\r
+\r
+        // Find all references in equations of component\r
+        References references = null;\r
+        try {\r
+            references = ValidationUtils.getAllReferences(graph, component);\r
+        } catch (Exception e) {\r
+            return Collections.emptyList();\r
+        }\r
+        \r
+        Configuration configuration = getConfiguration(graph, component);\r
+        ArrayList<Issue> result = new ArrayList<Issue>();\r
+        \r
+        // Examine possible for-index references. Remove if found\r
+        for(Resource expressionResource : references.forIndices.keySet()) {\r
+            if(references.forIndices.containsKey(expressionResource)) {\r
+                for(Token token : references.forIndices.get(expressionResource).keySet()) {\r
+                    if(references.references.containsKey(expressionResource) && \r
+                            references.references.get(expressionResource).containsKey(token.image)) {\r
+                        references.references.get(expressionResource).remove(token.image);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        \r
+        // Examine Sheet references\r
+        for(Resource expressionResource : references.functionReferences.keySet()) {\r
+            for(String functionKey : references.functionReferences.get(expressionResource).keySet()) {\r
+                List<SyntaxError> sheetErrors = ExpressionUtils.examineSheetReferences(\r
+                        configuration, \r
+                        functionKey, \r
+                        references.functionReferences.get(expressionResource).get(functionKey), \r
+                        references.expressions.get(expressionResource), \r
+                        references.references.get(expressionResource));\r
+                if(sheetErrors != null) {\r
+                    for(SyntaxError error : sheetErrors)\r
+                        result.add(new IssueWithStringContext(sr.Validations_InvalidSheetReferenceIssue, component, error.getMessage(), error.getImage()));\r
+                }\r
+            }\r
+        }\r
+        \r
+        \r
+        // Examine dependencies\r
+        Set<String> variablesReferences = references.getVariableReferences();\r
+        if(variablesReferences == null || variablesReferences.isEmpty())\r
+            return result;\r
+        \r
+        // Remove references to self\r
+        String name = NameUtils.getSafeName(graph, component);\r
+        if(name != null && variablesReferences.contains(name))\r
+            variablesReferences.remove(name);\r
+        \r
+        // Find all variables that are linked to component with arrows\r
+        Set<String> dependencies = ValidationUtils.getDependencies(graph, component);\r
+        dependencies.addAll(GLOBAL_VARIABLES);\r
+        \r
+        // Remove all dependency variables from reference maps \r
+        for(String dependency : dependencies)\r
+            variablesReferences.remove(dependency);\r
+\r
+        boolean isStock = isStock(graph, component);\r
+        ReferenceOption option;\r
+\r
+        for(String reference : variablesReferences) {\r
+            option = ExpressionUtils.getReferenceOption(configuration, reference);\r
+            switch(option) {\r
+                case DOES_NOT_EXIST:\r
+                    result.add(new IssueWithStringContext(sr.Validations_NoSuchVariableIssue, component, reference));\r
+                case CAN_BE_CONNECTED:\r
+                    if(isStock) {\r
+                        /* Stocks do not get incoming dependencies. They are allowed\r
+                        to have references without arrows */\r
+                    } else {\r
+                        result.add(new IssueWithStringContext(sr.Validations_MissingLinkIssue, component, reference));\r
+                    }\r
+                    break;\r
+                case CANNOT_BE_CONNECTED:\r
+            }\r
+        }\r
+        \r
+        \r
+        for(Resource expression : references.ranges.keySet()) {\r
+            List<SyntaxError> errors = new ArrayList<SyntaxError>();\r
+            // RANGES\r
+            errors.addAll(ExpressionUtils.examineArrayRanges(graph, configuration, references.ranges.get(expression), references.forIndices.get(expression)));\r
+            \r
+            // ENUMERATION REFERENCES IN FOR-LOOPS\r
+            errors.addAll(ExpressionUtils.examineEnumerationReferences(configuration, references.enumerationReferences.get(expression)));\r
+\r
+            for(SyntaxError error : errors) {\r
+                Resource type = sr.Validations_RangeIssue;\r
+                if(ExpressionField.SYNTAX_WARNING.equals(error.getType())) {\r
+                    type = sr.Validations_RangeWarning;\r
+                }\r
+                result.add(new IssueWithStringContext(type, component, error.getMessage()));\r
+\r
+            }\r
+        }   \r
+        \r
+        return result;\r
+\r
+    }\r
+    \r
+    private static boolean isStock(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        List<Resource> expressionList = ValidationUtils.getExpressions(graph, variable);\r
+        if(expressionList == null || expressionList.isEmpty()) {\r
+            return false;\r
+        } else {\r
+            for(Resource expression : expressionList) {\r
+                if(!graph.isInstanceOf(expression, SysdynResource.getInstance(graph).StockExpression))\r
+                    return false;\r
+            }\r
+            return true;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Missing link description\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param converter\r
+     * @param issue Issue\r
+     * @return issue description\r
+     * @throws DatabaseException\r
+     */\r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String missingLinkIssueDescription(ReadGraph graph, Resource converter, Variable property)\r
+            throws DatabaseException {\r
+       \r
+        List<String> contexts = IssueWithStringContext.getStringContexts(graph, property);\r
+        String result = "Missing a link to ";\r
+        if (contexts.size() > 0) {\r
+            result = result + contexts.get(0);\r
+        }\r
+\r
+        return result;\r
+        \r
+    }\r
+\r
+    /**\r
+     * Unused dependency description\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param converter\r
+     * @param issue Issue\r
+     * @return issue description\r
+     * @throws DatabaseException\r
+     */\r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String unusedDependencyIssueDescription(ReadGraph graph, Resource converter, Variable property)\r
+            throws DatabaseException {\r
+        \r
+        List<String> contexts = IssueWithStringContext.getStringContexts(graph, property);\r
+        String result = "Unused dependency: ";\r
+        if (contexts.size() > 0) {\r
+            result = result + contexts.get(0);\r
+        }\r
+\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * No such variable description. Finds all variables that the component\r
+     * refers to and adds their names to the issue description.\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param converter\r
+     * @param issue Issue\r
+     * @return issue description\r
+     * @throws DatabaseException\r
+     */\r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String noSuchVariableIssueDescription(ReadGraph graph, Resource converter, Variable property)\r
+            throws DatabaseException {\r
+        \r
+        List<String> contexts = IssueWithStringContext.getStringContexts(graph, property);\r
+        String result = "Refers to unexisting variable ";\r
+        if (contexts.size() > 0) {\r
+            result = result + contexts.get(0);\r
+        }\r
+        \r
+        return result;\r
+    }\r
+    \r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String invalidSheetReferenceIssueDescription(ReadGraph graph, Resource converter, Variable property)\r
+            throws DatabaseException {\r
+        \r
+        List<String> contexts = IssueWithStringContext.getStringContexts(graph, property);\r
+        String result = "";\r
+        \r
+        if(contexts.size() == 2)\r
+            result = contexts.get(0) + ": " + contexts.get(1);\r
+        else\r
+            result = "Spreadsheet reference error";\r
+\r
+        return result;\r
+    }\r
+    \r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String rangeIssueDescription(ReadGraph graph, Resource converter, Variable property)\r
+            throws DatabaseException {\r
+        \r
+        List<String> contexts = IssueWithStringContext.getStringContexts(graph, property);\r
+        if (contexts.size() > 0) {\r
+            return contexts.get(0);\r
+        } else {\r
+            return "Range Issue";\r
+        }\r
+    }\r
+    \r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String rangeWarningDescription(ReadGraph graph, Resource converter, Variable property)\r
+            throws DatabaseException {\r
+        return rangeIssueDescription(graph, converter, property);\r
+    }\r
+    \r
+    \r
+    \r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/EnumerationFunction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/EnumerationFunction.java
new file mode 100644 (file)
index 0000000..96b687c
--- /dev/null
@@ -0,0 +1,66 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.simantics.db.Issue;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.issue.StandardIssue;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.scl.reflection.annotations.SCLValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Functions for checking issues in Enumerations\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class EnumerationFunction  {\r
+\r
+    private static String NO_INDEXES = "Enumeration does not contain indexes.";\r
+\r
+    @SCLValue(type = "ReadGraph -> Resource -> [Issue]")\r
+    public static List<Issue> enumerationIndexValidator(ReadGraph graph, Resource component) throws DatabaseException {\r
+\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+        if(!graph.isInstanceOf(component, sr.Enumeration)) {\r
+            return Collections.emptyList();\r
+        }\r
+\r
+        boolean noIndexes = false;\r
+\r
+        try {\r
+            Resource indexList = graph.getPossibleObject(component, sr.Enumeration_enumerationIndexList);\r
+            List<Resource> indexes = ListUtils.toList(graph, indexList);\r
+            if(indexes.size() == 0)\r
+                noIndexes = true;\r
+        } catch (DatabaseException e) {\r
+            noIndexes = true;\r
+        }\r
+\r
+        if(noIndexes)\r
+            return Collections.<Issue>singletonList(new StandardIssue(sr.Validations_EmptyEnumerationIssue, component));\r
+        else\r
+            return Collections.emptyList();\r
+    }\r
+\r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String emptyEnumerationIssueDescription(ReadGraph graph, Resource converter, Variable property) throws DatabaseException {\r
+        return NO_INDEXES;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ExpressionIssueFunction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ExpressionIssueFunction.java
new file mode 100644 (file)
index 0000000..8a55a52
--- /dev/null
@@ -0,0 +1,76 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.simantics.db.Issue;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.issue.StandardIssue;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.issues.common.IssueUtils;\r
+import org.simantics.scl.reflection.annotations.SCLValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Detects syntax errors, unsupported characters and undefined expressions from variables.\r
+ * \r
+ * @author tlteemu\r
+ *\r
+ */\r
+public class ExpressionIssueFunction {\r
+    \r
+    private static String SYNTAX_ERROR = "Syntax error";\r
+    private static String UNSUPPORTED_CHARACTERS = "Unsupported characters";\r
+    private static String UNDEFINED_EXPRESSION = "Undefined expression";\r
+    \r
+    @SCLValue(type = "ReadGraph -> Resource -> [Issue]")\r
+    public static List<Issue> expressionValidator(ReadGraph graph, Resource component) throws DatabaseException {\r
+        \r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+        if(!graph.isInstanceOf(component, sr.IndependentVariable)) {\r
+            return Collections.emptyList();\r
+        }\r
+        \r
+        // Try if there are any errors while parsing the expressions\r
+        try {\r
+            ValidationUtils.getAllReferences(graph, component);\r
+        } catch (Exception e) {\r
+            return Collections.<Issue>singletonList(new StandardIssue(sr.Validations_ExpressionIssue, component));\r
+        }\r
+        return Collections.emptyList();\r
+    }\r
+    \r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String expressionIssueDescription(ReadGraph graph, Resource converter, Variable property) throws DatabaseException {\r
+       \r
+       List<Resource> contexts = IssueUtils.getContextsForProperty(graph, property);\r
+        Resource component = contexts.get(0);\r
+        \r
+        // There should be an error\r
+        try {\r
+            ValidationUtils.getAllReferences(graph, component);\r
+        } catch (SyntaxErrorException e) {\r
+            return SYNTAX_ERROR;\r
+        } catch (UnsupportedCharactersException e) {\r
+            return UNSUPPORTED_CHARACTERS;\r
+        } catch (UndefinedExpressionException e) {\r
+            return UNDEFINED_EXPRESSION;\r
+        }   \r
+        return "Erroneus error";\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/Functions.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/Functions.java
new file mode 100644 (file)
index 0000000..eca0810
--- /dev/null
@@ -0,0 +1,70 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.issues.common.IssueUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.project.ontology.ProjectResource;\r
+import org.simantics.scl.reflection.annotations.SCLValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Generic functions for validations\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class Functions {\r
+\r
+    @SCLValue(type = "ReadGraph -> Resource -> Resource")\r
+    public static Resource baseRealizationFunction(ReadGraph graph, Resource model) throws DatabaseException {\r
+        return model;\r
+    }\r
+\r
+\r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String path(ReadGraph graph, Resource source, Variable property) throws DatabaseException {\r
+        List<Resource> contexts = IssueUtils.getContextsForProperty(graph, property);\r
+        if (contexts.size() > 0) {\r
+            Resource component = contexts.get(0);\r
+            Layer0 L0 = Layer0.getInstance(graph);\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            ProjectResource PROJECT = ProjectResource.getInstance(graph);\r
+            StringBuilder sb = new StringBuilder("");\r
+            Resource parent = graph.getPossibleObject(component, L0.PartOf);\r
+            boolean first = true;\r
+            while(parent != null && !graph.isInstanceOf(parent, PROJECT.Project)) {\r
+                if(!graph.isInstanceOf(parent, sr.Configuration)) {\r
+                    String name = NameUtils.getSafeName(graph, parent);\r
+                    if(first) {\r
+                        sb.append(name);\r
+                        first = false;\r
+                    } else {\r
+                        sb.insert(0, "/");\r
+                        sb.insert(0, name);\r
+                    }\r
+                }\r
+                parent = graph.getPossibleObject(parent, L0.PartOf);\r
+            }\r
+            return sb.toString();\r
+        } else {\r
+            return "";\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/IssueWithStringContext.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/IssueWithStringContext.java
new file mode 100644 (file)
index 0000000..906124f
--- /dev/null
@@ -0,0 +1,107 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.issue.StandardIssue;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Issue that can have string contexts.\r
+ * \r
+ * String contexts are written to a graph like resource contexts and can be accessed \r
+ * in issue description functions. This eliminates the need for making complex calculations \r
+ * for obtaining values that have already been calculated in the issue source function. \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class IssueWithStringContext extends StandardIssue {\r
+\r
+    String[] stringContexts;\r
+\r
+    /**\r
+     * Creates an issue with one resource context and an arbitrary number of string contexts\r
+     * @param type\r
+     * @param context\r
+     * @param stringContexts\r
+     */\r
+    public IssueWithStringContext(Resource type, Resource context, String... stringContexts) {\r
+        super(type, context);\r
+        this.stringContexts = stringContexts;\r
+    }\r
+    \r
+    /**\r
+     * Get the string contexts of this issue\r
+     * @return string contexts\r
+     */\r
+    public String[] getStringContexts() {\r
+        return stringContexts;\r
+    }\r
+    \r
+    /**\r
+     * Overridden function from StandardResource. This writes a list of string contexts to the database.\r
+     */\r
+    public void writeAdditionalContext(WriteGraph graph, Resource issue) throws DatabaseException {\r
+        super.writeAdditionalContext(graph, issue);\r
+        \r
+        // Add possible string contexts to the contexts array\r
+        if(stringContexts != null && stringContexts.length > 0) {\r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+            Layer0 L0 = Layer0.getInstance(graph);\r
+            List<Resource> contexts = new ArrayList<Resource>();\r
+            for(String s : stringContexts) {\r
+                Resource r = graph.newResource();\r
+                graph.claim(r, L0.InstanceOf, L0.String);\r
+                graph.claimValue(r, s, Bindings.STRING);\r
+                contexts.add(r);\r
+            }\r
+            graph.claim(issue, SR.Validations_Issue_stringContexts, ListUtils.create(graph, L0.List, contexts));\r
+        }\r
+        \r
+    }\r
+    \r
+    /**\r
+     * Gets string contexts from IssueWithStringContexts\r
+     * @param graph ReadGraph\r
+     * @param property issue property\r
+     * @return String contexts of issue or empty list if none is found\r
+     * @throws DatabaseException\r
+     */\r
+    public static List<String> getStringContexts(ReadGraph graph, Variable property) throws DatabaseException {\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        Variable issueVariable = property.getParent(graph);\r
+        Resource issueResource = issueVariable.getRepresents(graph);\r
+        Resource list = graph.getPossibleObject(issueResource, SR.Validations_Issue_stringContexts);\r
+        if(list == null) {\r
+            return Collections.emptyList();\r
+        } else {\r
+            List<Resource> stringResources = ListUtils.toList(graph, list);\r
+            ArrayList<String> result = new ArrayList<String>(stringResources.size());\r
+            for(Resource r : stringResources) {\r
+                result.add((String)graph.getValue(r, Bindings.STRING));\r
+            }\r
+            return result;\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ModuleStandardIssue.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ModuleStandardIssue.java
new file mode 100644 (file)
index 0000000..4cbdf73
--- /dev/null
@@ -0,0 +1,37 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.issue.StandardIssue;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.issues.ontology.IssueResource;\r
+\r
+public class ModuleStandardIssue extends StandardIssue {\r
+\r
+    public ModuleStandardIssue(Resource type, Resource ... contexts) {\r
+        super(type, contexts);\r
+    }\r
+    \r
+    @Override\r
+    public void writeAdditionalContext(WriteGraph graph, Resource issue) throws DatabaseException {\r
+        super.writeAdditionalContext(graph, issue);\r
+\r
+        if(contexts.length >= 2) {\r
+            IssueResource IR = IssueResource.getInstance(graph);\r
+            // Input / output context\r
+            graph.claim(issue, IR.Issue_HasContext, IR.Issue_HasContext_Inverse, contexts[1]);\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/NoSuchVariableException.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/NoSuchVariableException.java
new file mode 100644 (file)
index 0000000..4ec1176
--- /dev/null
@@ -0,0 +1,17 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+public class NoSuchVariableException extends RuntimeException {\r
+    private static final long serialVersionUID = -5766352512554068379L;\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ParameterExistsValidator.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ParameterExistsValidator.java
new file mode 100644 (file)
index 0000000..0fb44b6
--- /dev/null
@@ -0,0 +1,50 @@
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.jfreechart.chart.properties.AllVariablesOfModel;\r
+import org.simantics.jfreechart.chart.properties.ChartVariable;\r
+import org.simantics.jfreechart.chart.properties.VariableExistsValidator;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+public class ParameterExistsValidator extends VariableExistsValidator {\r
+\r
+       public ParameterExistsValidator(WidgetSupport support, TrackedText text) {\r
+               super(support, text);\r
+       }\r
+\r
+    @Override\r
+    public void setInput(ISessionContext context, Object input) {\r
+        final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
+        if(resource == null)\r
+            return;\r
+        \r
+        SimanticsUI.getSession().asyncRequest(\r
+                new AllVariablesOfModel(resource)\r
+        , new Listener<Collection<ChartVariable>>() {\r
+\r
+            @Override\r
+            public void execute(Collection<ChartVariable> variables) {\r
+                ParameterExistsValidator.this.variables = variables;\r
+            }\r
+\r
+            @Override\r
+            public void exception(Throwable t) {\r
+                t.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                return ParameterExistsValidator.this.text.isDisposed();\r
+            }\r
+\r
+        }); \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/References.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/References.java
new file mode 100644 (file)
index 0000000..0d9ed3d
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+\r
+/**\r
+ * Container for different types of references got from expression parser\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class References {\r
+    public HashMap<Resource, String> expressions = new HashMap<Resource, String>();\r
+    public HashMap<Resource, HashMap<String, List<Token>>> references = new HashMap<Resource, HashMap<String, List<Token>>>();\r
+    public HashMap<Resource, HashMap<String, List<List<Token>>>> ranges = new HashMap<Resource, HashMap<String, List<List<Token>>>>();\r
+    public HashMap<Resource, HashMap<Token, List<Token>>> forIndices = new HashMap<Resource, HashMap<Token, List<Token>>>();\r
+    public HashMap<Resource, HashMap<String, List<Token>>> enumerationReferences = new HashMap<Resource, HashMap<String, List<Token>>>();\r
+    public HashMap<Resource, HashMap<String, List<Token>>> functionReferences = new HashMap<Resource, HashMap<String, List<Token>>>();\r
+    \r
+    \r
+    /**\r
+     * Get all variable references from all expressions of the variable in a single set\r
+     * @return All variable references\r
+     */\r
+    public Set<String> getVariableReferences() {\r
+        HashSet<String> result = new HashSet<String>();\r
+        for(HashMap<String, List<Token>> map : references.values()) {\r
+            for(String key : map.keySet()) {\r
+                if(!map.get(key).isEmpty())\r
+                    result.add(key);\r
+            }\r
+        }\r
+        \r
+        return result;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/SyntaxErrorException.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/SyntaxErrorException.java
new file mode 100644 (file)
index 0000000..0592a5d
--- /dev/null
@@ -0,0 +1,18 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+public class SyntaxErrorException extends RuntimeException {\r
+    private static final long serialVersionUID = -6466653179001958636L;\r
+    \r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UndefinedExpressionException.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UndefinedExpressionException.java
new file mode 100644 (file)
index 0000000..1c53cd8
--- /dev/null
@@ -0,0 +1,17 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+public class UndefinedExpressionException extends RuntimeException {\r
+    private static final long serialVersionUID = 7352486116119189105L;\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UnitFunction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UnitFunction.java
new file mode 100644 (file)
index 0000000..2eeadea
--- /dev/null
@@ -0,0 +1,300 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.db.Issue;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.issue.StandardIssue;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.issues.common.IssueUtils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.scl.reflection.annotations.SCLValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.expressions.IExpression;\r
+import org.simantics.sysdyn.representation.utils.UnitUtils;\r
+import org.simantics.sysdyn.utils.Function;\r
+import org.simantics.sysdyn.utils.ModelUtils;\r
+\r
+public class UnitFunction {\r
+\r
+    @SCLValue(type = "ReadGraph -> Resource -> [Issue]")\r
+    public static List<Issue> unitValidator(ReadGraph graph, Resource component) throws DatabaseException {\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        if(graph.isInstanceOf(component, SR.Variable) && !graph.isInstanceOf(component, SR.Cloud))\r
+            return variableValidator(graph, component);\r
+        else if(graph.isInstanceOf(component, SR.Module))\r
+            return moduleValidator(graph, component);\r
+        else\r
+            return Collections.emptyList();\r
+    }\r
+    \r
+    private static List<Issue> variableValidator(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph); \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+        Resource configuration = graph.getPossibleObject(variable, L0.PartOf);\r
+        if(configuration == null)\r
+            return Collections.emptyList();\r
+\r
+        // Make sure unit updates are listened to\r
+        String unit = null;\r
+        if (graph.isInstanceOf(variable, SR.Shadow)) {\r
+               Resource original = graph.getPossibleObject(variable, SR.Shadow_original);\r
+               if (original == null)\r
+                       return Collections.emptyList();\r
+               unit = graph.getPossibleRelatedValue(original, SR.Variable_unit);\r
+        } else {\r
+               unit = graph.getPossibleRelatedValue(variable, SR.Variable_unit);\r
+        }\r
+        if(unit == null || unit.trim().length() == 0)\r
+            return Collections.<Issue>singletonList(new StandardIssue(SR.Validations_UnitWarning, variable));\r
+\r
+        if(!graph.isInstanceOf(variable, SR.IndependentVariable))\r
+            return Collections.emptyList();\r
+        \r
+        Resource expressionList = graph.getPossibleObject(variable, SR.Variable_expressionList);\r
+\r
+        if(expressionList == null)\r
+            return Collections.emptyList();\r
+\r
+\r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        SysdynModel sm = smm.getModel(graph, configuration);\r
+        sm.getMapping().domainModified(variable);\r
+\r
+        sm.update(graph);\r
+        Object var = sm.getMapping().get(variable);\r
+\r
+        ArrayList<Issue> issues = new ArrayList<Issue>();\r
+\r
+        for(Resource expression : ListUtils.toList(graph, expressionList)) {\r
+            for(Resource r : graph.getObjects(expression, SR.Expression_equation)) {\r
+                graph.getValue(r);\r
+            }\r
+\r
+            sm.getMapping().domainModified(expression);\r
+            sm.update(graph);\r
+\r
+            Object expr = sm.getMapping().get(expression);\r
+\r
+            if(expr != null && var != null && expr instanceof IExpression && var instanceof IndependentVariable) {\r
+                String result = ((IExpression)expr).validateUnits(graph, sm);\r
+                if(result != null) {\r
+                    Issue issue = new StandardIssue(SR.Validations_UnitWarning, variable, expression, graph.getPossibleObject(variable, SR.Variable_unit));\r
+                    issues.add(issue);\r
+                }\r
+            }\r
+        }\r
+        return issues;\r
+    }\r
+    \r
+    private static List<Issue> moduleValidator(ReadGraph graph, Resource module) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+        if(module == null)\r
+            return Collections.emptyList();\r
+\r
+        Resource configuration = graph.getPossibleObject(module, L0.PartOf);\r
+        if(configuration == null)\r
+            return Collections.emptyList();\r
+\r
+        SysdynModel model = ModelUtils.getModel(graph, module);\r
+        String result = null;\r
+        ArrayList<Issue> issues = new ArrayList<Issue>();\r
+        for(Resource outputRelation : graph.getObjects(module, SR.Variable_isTailOf)) {\r
+            Resource reference = graph.getPossibleObject(outputRelation, SR.Dependency_refersTo);\r
+            if(reference != null) {\r
+                Resource output = graph.getPossibleObject(outputRelation, SR.Variable_HasHead);\r
+                if(output == null)\r
+                    continue;\r
+                String left = graph.getPossibleRelatedValue(output, SR.Variable_unit);\r
+                String right = graph.getPossibleRelatedValue(reference, SR.Variable_unit);\r
+                ArrayList<Function> functions = Function.getAllBuiltInFunctions(graph);\r
+                result = UnitUtils.matchUnits(left, right, functions, UnitUtils.allowEquivalents(graph, model));\r
+                if(result != null)\r
+                    issues.add(new ModuleStandardIssue(SR.Validations_ModuleOutputUnitWarning, module, output, reference));\r
+            }\r
+        }\r
+        for(Resource inputRelation : graph.getObjects(module, SR.Variable_isHeadOf)) {\r
+            Resource reference = graph.getPossibleObject(inputRelation, SR.Dependency_refersTo);\r
+            if(reference != null) {\r
+                Resource variable = graph.getPossibleObject(inputRelation, SR.Variable_HasTail);\r
+                if(variable == null)\r
+                    continue;\r
+                String left = graph.getPossibleRelatedValue(variable, SR.Variable_unit);\r
+                String right = graph.getPossibleRelatedValue(reference, SR.Variable_unit);\r
+                ArrayList<Function> functions = Function.getAllBuiltInFunctions(graph);\r
+               result = UnitUtils.matchUnits(left, right, functions, UnitUtils.allowEquivalents(graph, model));\r
+                if(result != null)\r
+                    issues.add(new ModuleStandardIssue(SR.Validations_ModuleInputUnitWarning, module, variable, reference));\r
+            }\r
+        }\r
+        return issues;\r
+    }\r
+\r
+\r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String unitWarningDescription(ReadGraph graph, Resource converter, Variable property) throws DatabaseException {\r
+        List<Resource> contexts = IssueUtils.getContextsForProperty(graph, property);\r
+\r
+        if(contexts.size() == 0)\r
+            return "Error, No contexts";\r
+\r
+        Resource variable = contexts.get(0);\r
+        String unit = graph.getPossibleRelatedValue(variable, SysdynResource.getInstance(graph).Variable_unit);\r
+\r
+        if(unit == null || unit.length() == 0)\r
+            return "No unit defined";\r
+        \r
+        if(contexts.size() < 2)\r
+            return "Error, not enough contexts";\r
+\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Resource configuration = graph.getPossibleObject(variable, L0.PartOf);\r
+        if(configuration == null)\r
+            return "Error, No Confiugration";\r
+\r
+\r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        SysdynModel sm = smm.getModel(graph, configuration);\r
+\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        for(Resource r : graph.getObjects(contexts.get(1), SR.Expression_equation)) {\r
+            graph.getValue(r);\r
+        }\r
+\r
+        Object expr = sm.getMapping().get(contexts.get(1));\r
+        String result = ((IExpression)expr).validateUnits(graph, sm);\r
+        \r
+        return result;\r
+    }\r
+\r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String moduleOutputUnitWarningDescription(ReadGraph graph, Resource converter, Variable property) throws DatabaseException {\r
+        List<Resource> contexts = IssueUtils.getContextsForProperty(graph, property);\r
+\r
+        if(contexts.size() < 3)\r
+            return "Error, No contexts";\r
+\r
+        Resource output = contexts.get(1);\r
+        Resource reference = contexts.get(2);\r
+\r
+        return moduleInterfaceDescription(graph, output, reference, "Module output has different unit. (", ")");\r
+\r
+    }\r
+    \r
+    @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")\r
+    public static String moduleInputUnitWarningDescription(ReadGraph graph, Resource converter, Variable property) throws DatabaseException {\r
+        List<Resource> contexts = IssueUtils.getContextsForProperty(graph, property);\r
+\r
+        if(contexts.size() < 3)\r
+            return "Error, No contexts";\r
+\r
+        Resource output = contexts.get(1);\r
+        Resource reference = contexts.get(2);\r
+\r
+        return moduleInterfaceDescription(graph, output, reference, "Module input has different unit. (", ")");\r
+\r
+    }\r
+    \r
+    private static String moduleInterfaceDescription(ReadGraph graph, Resource leftResource, Resource rightResource, String prefix, String suffix) throws DatabaseException {\r
+        if(leftResource == null)\r
+            return "Erroneus error: left == null";\r
+        \r
+        if(rightResource == null)\r
+            return "Erroneus error: right == null";\r
+        \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        String left = graph.getPossibleRelatedValue(leftResource, SR.Variable_unit);\r
+        if(left == null || left.isEmpty())\r
+            return "No unit defined for " + NameUtils.getSafeName(graph, leftResource);\r
+        \r
+        String right = graph.getPossibleRelatedValue(rightResource, SR.Variable_unit);\r
+        if(right == null || right.isEmpty())\r
+            return "No unit defined for " + NameUtils.getSafeName(graph, rightResource);\r
+        \r
+        SysdynModel model = ModelUtils.getModel(graph, leftResource);\r
+        ArrayList<Function> functions = Function.getAllBuiltInFunctions(graph);\r
+       String result = UnitUtils.matchUnits(left, right, functions, UnitUtils.allowEquivalents(graph, model));\r
+        \r
+        if(result != null)\r
+            result = prefix + result + suffix;\r
+        \r
+        return result;\r
+    }\r
+    \r
+    \r
+    \r
+    \r
+    @SCLValue(type = "ReadGraph -> [Resource] -> [Resource]")\r
+    public static List<Resource> moduleInterfaceExtension(ReadGraph graph, List<Resource> rs) throws DatabaseException {\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        HashSet<Resource> components = new HashSet<Resource>();\r
+        HashSet<Resource> searchedModuleTypes = new HashSet<Resource>();\r
+        for(Resource r : rs) {\r
+            if(!graph.isInstanceOf(r, SR.Variable))\r
+                continue;\r
+            \r
+            if(graph.isInstanceOf(r, SR.Input)) {\r
+                Resource connection = graph.getPossibleObject(r, SR.Variable_isHeadOf);\r
+                if(connection != null)\r
+                    components.add(graph.getPossibleObject(connection, SR.Variable_HasTail));\r
+            }\r
+            \r
+            for(Resource connection :  graph.getObjects(r, SR.Variable_isTailOf)) {\r
+                Resource head = graph.getPossibleObject(connection, SR.Variable_HasHead);\r
+                if(head != null && graph.isInstanceOf(head, SR.Module)) {\r
+                    components.add(head);\r
+                }\r
+            }\r
+            \r
+            Layer0 L0 = Layer0.getInstance(graph);\r
+            Resource configuration = graph.getPossibleObject(r, L0.PartOf);\r
+            Resource possibleModule = graph.getPossibleObject(configuration, L0.PartOf);\r
+            if(graph.isInheritedFrom(possibleModule, SR.Module) && !searchedModuleTypes.contains(possibleModule)) {\r
+                searchedModuleTypes.add(possibleModule);\r
+                for(Resource model : graph.syncRequest(new ObjectsWithType(Simantics.getProject().get(), L0.ConsistsOf, SR.SysdynModel))) {\r
+                    Collection<Resource> found = org.simantics.db.indexing.IndexUtils.findByType(graph, model, possibleModule);\r
+                    components.addAll(found);\r
+                }\r
+            }\r
+\r
+        }\r
+        \r
+        if(!components.isEmpty()) {\r
+            rs.addAll(components);\r
+        }\r
+        \r
+        return rs;\r
+        \r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UnsupportedCharactersException.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/UnsupportedCharactersException.java
new file mode 100644 (file)
index 0000000..b2aa82f
--- /dev/null
@@ -0,0 +1,17 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+public class UnsupportedCharactersException extends RuntimeException {\r
+    private static final long serialVersionUID = 8210873686720503188L;\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ValidationUtils.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ValidationUtils.java
new file mode 100644 (file)
index 0000000..d90fd96
--- /dev/null
@@ -0,0 +1,166 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.validation;\r
+\r
+import java.io.StringReader;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Statement;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+import org.simantics.sysdyn.expressionParser.TokenMgrError;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ValidationUtils {\r
+    \r
+    /**\r
+     * Find all variables that are referred to in the expressions of variable r\r
+     * @param graph ReadGraph\r
+     * @param r Variable resource\r
+     * @return All names of the variables that are referred to in the expressions of r\r
+     * @throws DatabaseException\r
+     * @throws SyntaxErrorException\r
+     * @throws UnsupportedCharactersException\r
+     * @throws UndefinedExpressionException\r
+     */\r
+    public static References getAllReferences(ReadGraph graph, Resource r) throws DatabaseException, SyntaxErrorException, UnsupportedCharactersException, UndefinedExpressionException {\r
+        References result = new References();\r
+\r
+        ExpressionParser parser = new ExpressionParser(new StringReader(""));\r
+\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        List<Resource> expressionList = getExpressions(graph, r);\r
+        if(expressionList == null || expressionList.isEmpty())\r
+            throw new UndefinedExpressionException();\r
+        for(Resource expression : expressionList) {\r
+            \r
+            Collection<Statement> statements = graph.getStatements(expression, sr.Expression_equation);\r
+            if(statements.isEmpty())\r
+                throw new UndefinedExpressionException();\r
+\r
+            for(Statement statement : statements) {\r
+                Object v = graph.getValue(statement.getObject());\r
+                String value = v.toString();\r
+                \r
+                if(value.length() == 0) {\r
+                    // Empty might be allowed\r
+                    if(!graph.isSubrelationOf(statement.getPredicate(), sr.HasEquationOrEmpty))\r
+                        throw new UndefinedExpressionException();\r
+                }\r
+\r
+                parser.ReInit(new StringReader(value));\r
+                try {\r
+                    parser.expr();\r
+                    \r
+                    HashMap<String, List<Token>> refs = parser.getReferences();\r
+                    result.references.put(expression, refs);\r
+                    result.ranges.put(expression, parser.getRanges());\r
+                    result.forIndices.put(expression,  parser.getForIndices());\r
+                    result.enumerationReferences.put(expression, parser.getEnumerationReferences());\r
+                    result.functionReferences.put(expression, parser.getFunctionCallReferences());\r
+                    result.expressions.put(expression, value);\r
+                    \r
+                } catch (ParseException e1) {\r
+                    throw new SyntaxErrorException();\r
+                } catch (TokenMgrError err) {\r
+                    throw new UnsupportedCharactersException();\r
+                }\r
+            }\r
+        }\r
+        return result;\r
+    }\r
+    \r
+    /**\r
+     * Get all expressions of a variable r\r
+     * @param graph ReadGraph\r
+     * @param r Variable with expressions\r
+     * @return List of expression (resources)\r
+     * @throws DatabaseException\r
+     */\r
+    public static List<Resource> getExpressions(ReadGraph graph, Resource r) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Resource hasExpressions = graph.getPossibleObject(r, sr.Variable_expressionList);\r
+        if(hasExpressions != null)\r
+            return ListUtils.toList(graph, hasExpressions);\r
+        else\r
+            return null;\r
+    }\r
+\r
+\r
+    /**\r
+     * Returns the names of the related variables (dependencies)\r
+     * For stocks, find also both the incoming and outgoing flows\r
+     * \r
+     * @param graph\r
+     * @param r\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    public static HashSet<String> getDependencies(ReadGraph graph, Resource r) throws DatabaseException {\r
+        HashSet<String> variables = new HashSet<String>();\r
+        if(graph != null && r != null) {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+            // Add incoming dependencies and flows\r
+            Collection<Resource> dependencies = graph.getObjects(r, sr.Variable_isHeadOf);\r
+            for(Resource d : dependencies) {\r
+                if(graph.isInstanceOf(d, sr.Dependency)\r
+                               || (graph.isInstanceOf(d, sr.Flow) && graph.isInstanceOf(r, sr.Stock))) {\r
+                    Resource tail = graph.getPossibleObject(d, sr.Variable_HasTail);\r
+                    if(tail != null) {\r
+                        \r
+                        if(graph.isInstanceOf(tail, sr.Shadow)) {\r
+                            tail = graph.getPossibleObject(tail, sr.Shadow_original);\r
+                            if(tail == null)\r
+                                continue;\r
+                        }\r
+                        \r
+                        Object name = graph.getPossibleRelatedValue(tail, l0.HasName);\r
+                        if(name != null)\r
+                            variables.add((String)name);\r
+                    }\r
+                }\r
+            }\r
+            \r
+            // Add also the outgoing flows \r
+            Collection<Resource> outgoingFlows = graph.getObjects(r, sr.Variable_isTailOf);\r
+            for(Resource f : outgoingFlows) {\r
+                if(graph.isInstanceOf(f, sr.Flow) && graph.isInstanceOf(r, sr.Stock)) {\r
+                    Resource head = graph.getPossibleObject(f, sr.Variable_HasHead);\r
+                    if(head != null) {\r
+\r
+                        Object name = graph.getPossibleRelatedValue(head, l0.HasName);\r
+                        if(name != null)\r
+                            variables.add((String)name);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        return variables;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/values/ValueView.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/values/ValueView.java
new file mode 100644 (file)
index 0000000..6908c0e
--- /dev/null
@@ -0,0 +1,349 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.values;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.dnd.Clipboard;\r
+import org.eclipse.swt.dnd.TextTransfer;\r
+import org.eclipse.swt.dnd.Transfer;\r
+import org.eclipse.swt.events.KeyEvent;\r
+import org.eclipse.swt.events.KeyListener;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Event;\r
+import org.eclipse.swt.widgets.Listener;\r
+import org.eclipse.swt.widgets.Table;\r
+import org.eclipse.swt.widgets.TableColumn;\r
+import org.eclipse.swt.widgets.TableItem;\r
+import org.eclipse.ui.ISelectionListener;\r
+import org.eclipse.ui.part.ViewPart;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.ui.viewUtils.SysdynDatasetSelectionListener;\r
+\r
+/**\r
+ * A view that shows the values of currently selected variables in a table. \r
+ * One column (first by default) is always time values.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ValueView  extends ViewPart {\r
+\r
+       private boolean disposed;\r
+       private Composite baseComposite;\r
+       private ISelectionListener selectionListener;\r
+       private Table table;\r
+\r
+       @Override\r
+       public void createPartControl(Composite parent) {\r
+\r
+               disposed = false;\r
+               GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(parent);\r
+               baseComposite = new Composite(parent, \r
+                               SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
+               GridLayoutFactory.fillDefaults().applyTo(baseComposite);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(baseComposite);\r
+\r
+               // Result table\r
+               table = new Table (baseComposite, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);\r
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(table);\r
+               table.setLinesVisible (true);\r
+               table.setHeaderVisible (true);\r
+               GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);\r
+               data.heightHint = 200;\r
+               table.setLayoutData(data);\r
+\r
+\r
+               // Add selectionListener for updating the table\r
+               selectionListener = new SysdynDatasetSelectionListener() {\r
+\r
+                       @Override\r
+                       protected void selectionChanged(final Collection<SysdynDataSet> activeDatasets) {\r
+                               if(disposed) return;\r
+                               table.getDisplay().asyncExec(new Runnable() {\r
+\r
+                                       @Override\r
+                                       public void run() {\r
+                                               updateTable(activeDatasets);\r
+                                       }\r
+                               });\r
+                       }\r
+\r
+            @Override\r
+            protected void selectionChanged(ReadGraph graph, Resource resource) {\r
+                // Do nothing\r
+            }\r
+\r
+               }; \r
+               getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(selectionListener);\r
+               \r
+               // Refreshes the table. There might be a selection already before the table is shown.\r
+               ISelection selection = getSite().getWorkbenchWindow().getSelectionService().getSelection();\r
+               if(selection != null)\r
+                   selectionListener.selectionChanged(getSite().getPart(), selection);\r
+               \r
+               \r
+               /*\r
+                * A primitive copy paste to support exporting data from table to excel\r
+                * \r
+                * columnName\tcolumnName\tcolumnName\n\r
+                * value\tvalue\tvalue\n\r
+                * ...\r
+                * value\tvalue\tvalue\n\r
+                * \r
+                */\r
+               KeyListener kl = new KeyListener() {\r
+            \r
+            @Override\r
+            public void keyReleased(KeyEvent e) {\r
+                \r
+            }\r
+            \r
+            @Override\r
+            public void keyPressed(KeyEvent e) {\r
+                if (e.stateMask == SWT.CTRL && e.keyCode == 99)\r
+                {\r
+                    \r
+                    Clipboard cb = new Clipboard(e.display);\r
+                    \r
+                    TextTransfer textTransfer = TextTransfer.getInstance();\r
+                    \r
+                    // Add names of the columns first. Selection is always full, print all columns\r
+                    StringBuilder sb = new StringBuilder();\r
+                    int columnCount = table.getColumnCount();\r
+                    for(int i = 0; i < columnCount; i++) {\r
+                        TableColumn tc = table.getColumn(i);\r
+                        sb.append(tc.getText());\r
+                        if(i < columnCount - 1)\r
+                            sb.append("\t");\r
+                        else\r
+                            sb.append("\n");\r
+                    }\r
+                    \r
+                    // Print all selected rows. \r
+                    for(TableItem ti : table.getSelection())\r
+                        for(int i = 0; i < columnCount; i++) {\r
+                            sb.append(ti.getText(i));\r
+                            if(i < columnCount - 1)\r
+                                sb.append("\t");\r
+                            else\r
+                                sb.append("\n");\r
+                        }\r
+                    \r
+                    cb.setContents(new Object[]{sb.toString()}, new Transfer[]{textTransfer});\r
+                }\r
+            }\r
+        };\r
+        \r
+        table.addKeyListener(kl);\r
+        \r
+\r
+       }\r
+\r
+       /**\r
+        * Updates the table after selection has been changed\r
+        * \r
+        * @param activeDatasets\r
+        */\r
+       private void updateTable(Collection<SysdynDataSet> activeDatasets) {\r
+\r
+               if(activeDatasets.isEmpty() || !(activeDatasets instanceof ArrayList)) return;\r
+               \r
+               // Clear the old table\r
+               table.removeAll();\r
+               if(table.getColumnCount() > 0) {\r
+                       for(int i = table.getColumnCount() - 1; i>=0; i--) {\r
+                               table.getColumn(i).dispose();\r
+                       }\r
+               }\r
+               \r
+               // Create new columns\r
+               ArrayList<SysdynDataSet> datasets = (ArrayList<SysdynDataSet>) activeDatasets;\r
+               \r
+               ArrayList<String> titleList = new ArrayList<String>();\r
+               titleList.add("Time");\r
+               double[] times = new double[0];\r
+               for (int i=0; i<datasets.size(); i++) {\r
+                       String name = datasets.get(i).name;\r
+            if (datasets.get(i).resultIndex != null) {\r
+               name += "(" + datasets.get(i).resultIndex + ")"; \r
+            }\r
+                       if(datasets.get(i).result != null)\r
+                               name += " : " + datasets.get(i).result;\r
+                       titleList.add(name);\r
+                       if(times == null || datasets.get(i).values.length > times.length) {\r
+                               times = datasets.get(i).times;\r
+                       }\r
+               }\r
+\r
+               \r
+           Listener sortListener = new Listener() {\r
+               public void handleEvent(Event e) {\r
+                   TableItem[] items = table.getItems();\r
+                   TableColumn column = (TableColumn)e.widget;\r
+                   \r
+                               TableColumn sortColumn = table.getSortColumn();\r
+                               int dir = table.getSortDirection();\r
+                               if (sortColumn == column) {\r
+                                       dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;\r
+                               } else {\r
+                                       table.setSortColumn(column);\r
+                                       dir = SWT.UP;\r
+                               }\r
+                   \r
+                               int index = 0;\r
+                               while(index < table.getColumnCount()) {\r
+                                       if(table.getColumn(index) == column)\r
+                                               break;\r
+                                       index++;\r
+                               }\r
+                   for (int i = 1; i < items.length; i++) {\r
+                       String v1 = items[i].getText(index);\r
+                       if(v1.contains("*"))\r
+                               v1 = v1.substring(0, v1.indexOf("*"));\r
+                       Double value1;\r
+                       try {\r
+                               value1 = Double.parseDouble(v1);\r
+                       } catch(NumberFormatException ne) {\r
+                               continue;\r
+                       }\r
+                       for (int j = 0; j < i; j++){\r
+                               String v2 = items[j].getText(index);\r
+                               if(v2.contains("*"))\r
+                                       v2 = v2.substring(0, v2.indexOf("*"));\r
+                           Double value2;\r
+                               try {\r
+                                       value2 = Double.parseDouble(v2);\r
+                               } catch(NumberFormatException ne) {\r
+                                       continue;\r
+                               }\r
+                           int result = value1.compareTo(value2);\r
+                           if (dir == SWT.UP && result < 0 || dir == SWT.DOWN && result > 0) {\r
+                               int columns = table.getColumnCount();\r
+                               String[] values = new String[columns];\r
+                               for(int k = 0; k < columns; k++) {\r
+                                       values[k] = items[i].getText(k);\r
+                               }\r
+                               items[i].dispose();\r
+                               TableItem item = new TableItem(table, SWT.NONE, j);\r
+                               item.setText(values);\r
+                               items = table.getItems();\r
+                               break;\r
+                           }\r
+                       }\r
+                   }\r
+                   table.setSortColumn(column);\r
+                   table.setSortDirection(dir);\r
+               }\r
+           };\r
+\r
+\r
+               \r
+               String[] titles = titleList.toArray(new String[titleList.size()]);\r
+               \r
+               for (int i=0; i<titles.length; i++) {\r
+                       TableColumn column = new TableColumn (table, SWT.NONE);\r
+                       column.setText (titles [i]);\r
+                       column.addListener(SWT.Selection, sortListener);\r
+                       column.setMoveable(true);\r
+               }       \r
+               \r
+           table.setSortColumn(table.getColumn(0));\r
+           table.setSortDirection(SWT.UP);\r
+           \r
+               // add results\r
+               \r
+               for (int i=0; i<times.length; i++) {\r
+                       TableItem item = new TableItem (table, SWT.NONE);\r
+                       item.setText(0, String.valueOf(times[i]));\r
+                       for(int j=0; j<datasets.size(); j++) {\r
+                               String approximation = approximate(times[i], i, datasets.get(j));\r
+                               item.setText (j + 1 /* time is at column 0 */, approximation);\r
+                       }\r
+               }\r
+               \r
+               for (int i=0; i<titles.length; i++) {\r
+                       table.getColumn (i).pack ();\r
+               }       \r
+\r
+       }\r
+\r
+       \r
+       /**\r
+        * Approximate a value for a table cell. There might not be a value for some specific time step\r
+        * due to different result sets. Approximation uses linear interpolation to calculate an approximate\r
+        * value for the desired time step. \r
+        * \r
+        * @param time Time step that is displayed\r
+        * @param index Index of the displayed time on its dataset\r
+        * @param dataset The dataset that contains the values that are displayed\r
+        * @return The exact value of an approximate if an exat value is not found\r
+        */\r
+       private String approximate(Double time, int index, SysdynDataSet dataset) {\r
+               \r
+               // time out of datasets range\r
+               if(dataset.times.length == 0 || time > dataset.times[dataset.times.length - 1] ||\r
+                               time < dataset.times[0]) {\r
+                       return "---";\r
+               }\r
+               \r
+               // Make sure the index is within times array\r
+               if(index >= dataset.times.length)\r
+                       index = dataset.times.length - 1;\r
+\r
+               // times match, no approximation needed\r
+               double t;\r
+               for(int i = 0; i < dataset.times.length; i++) {\r
+                   t = dataset.times[i];\r
+                   if(t == time)\r
+                       return String.valueOf(dataset.values[i]);\r
+               }\r
+\r
+               // Search the position on datasets' timeline\r
+               int dir = table.getSortDirection();\r
+               while(dataset.times[index] > time) {\r
+                       index = dir == SWT.UP ? index - 1 : index + 1;\r
+               }\r
+               while(dataset.times[index] <= time)\r
+                       index = dir == SWT.UP ? index + 1 : index - 1;\r
+               \r
+               int a = dir == SWT.UP ? index - 1 : index;\r
+               int b = dir == SWT.UP ? index : index - 1;\r
+               \r
+               // Calculate and return approximation\r
+               return dataset.values[a] + \r
+               (dataset.values[b] - dataset.values[a]) * \r
+               (time - dataset.times[a]) /\r
+               (dataset.times[b] - dataset.times[a]) + "*"; \r
+       }\r
+\r
+       @Override\r
+       public void setFocus() {\r
+           \r
+       }\r
+\r
+       @Override\r
+       public void dispose() {\r
+               super.dispose();\r
+               getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(selectionListener);\r
+               disposed = true;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/viewUtils/SysdynDatasetSelectionListener.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/viewUtils/SysdynDatasetSelectionListener.java
new file mode 100644 (file)
index 0000000..688ba1f
--- /dev/null
@@ -0,0 +1,225 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.viewUtils;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.ui.ISelectionListener;\r
+import org.eclipse.ui.IWorkbenchPart;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.common.procedure.adapter.DisposableListener;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.SelectionHints;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.request.PossibleActiveVariableFromVariable;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.modeling.ModelingUtils;\r
+import org.simantics.sysdyn.Functions;\r
+import org.simantics.sysdyn.JFreeChartResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.ui.trend.PinTrend;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.ui.ISelectionUtils;\r
+\r
+/**\r
+ * Selection listener for listening datasets of the selected variables. Selections can come \r
+ * from both diagram and model browser. Listener provides the active datasets\r
+ * of the selected variable(s) or the JFreeChart of a selected chart definition. \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public abstract class SysdynDatasetSelectionListener implements ISelectionListener {\r
+\r
+    /**\r
+     * Triggered after a variable is selected from diagram or model browser\r
+     * Subclasses implement.\r
+     * @param activeDatasets Active dataset(s) of the selected variable(s)\r
+     */\r
+    protected abstract void selectionChanged(Collection<SysdynDataSet> activeDatasets);\r
+\r
+    /**\r
+     * Triggered after a chart definition is selected from model browser\r
+     * Subclasses implement\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param resource Chart definition resource\r
+     */\r
+    protected abstract void selectionChanged(ReadGraph graph, Resource resource);\r
+\r
+\r
+\r
+    public void dispose() {\r
+        if(listener != null)\r
+            listener.dispose();\r
+    }\r
+    \r
+    DisposableListener<ArrayList<SysdynDataSet>> listener;\r
+\r
+    @Override\r
+    public void selectionChanged(IWorkbenchPart part, final ISelection selection) {\r
+        // Empty selection or pinned trend -> Do nothing\r
+        if(selection.isEmpty() || Boolean.TRUE.equals(PinTrend.getState()))\r
+            return;\r
+\r
+        if(selection instanceof IStructuredSelection) {\r
+            Session session = SimanticsUI.peekSession();\r
+            if (session == null)\r
+                return;\r
+            \r
+            if(listener != null)\r
+                listener.dispose();\r
+            \r
+            listener = new DisposableListener<ArrayList<SysdynDataSet>>() {\r
+\r
+                @Override\r
+                public void execute(ArrayList<SysdynDataSet> vars) {\r
+                    if(vars != null)\r
+                        selectionChanged(vars);\r
+                }\r
+\r
+                @Override\r
+                public void exception(Throwable t) {\r
+                    t.printStackTrace();\r
+                }\r
+            };\r
+\r
+            try {\r
+                session.syncRequest(new Read<ArrayList<SysdynDataSet>>() {\r
+                    @Override\r
+                    public ArrayList<SysdynDataSet> perform(ReadGraph graph) throws DatabaseException {\r
+\r
+                        // Model browser provides variables\r
+                        Collection<Variable> vars = ISelectionUtils.filterSetSelection(selection, Variable.class);\r
+\r
+                        if(vars.isEmpty()) {\r
+                            // Selection did not contain variables\r
+                            Set<Resource> ress = ISelectionUtils.filterSetSelection(selection, Resource.class);\r
+                            List<Resource> runtimes = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_VARIABLE_RESOURCE, Resource.class);\r
+                            if(!runtimes.isEmpty()) {\r
+                                // Selection is most probably in a diagram\r
+                                Resource runtime = runtimes.get(0);\r
+\r
+                                // Get variables for selected resources\r
+                                for(Resource resource : ress) {\r
+                                    Variable variable = getVariable(graph, resource, runtime);\r
+                                    if(variable != null)\r
+                                        vars.add(variable);\r
+                                }\r
+\r
+                                // If there is no vars and only one selection, it can be a chart\r
+                                if(vars.isEmpty() && ress.size() == 1) {\r
+                                    Resource r = ress.iterator().next();\r
+                                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                                    if(graph.isInstanceOf(r, jfree.ChartElement)) {\r
+                                        if(graph.hasStatement(r, jfree.ChartElement_component)) {\r
+                                            r = graph.getSingleObject(r, jfree.ChartElement_component);\r
+                                            selectionChanged(graph, r);\r
+                                            return null;\r
+                                        }\r
+                                    }\r
+                                }\r
+\r
+                            } else {\r
+                                // Selection is a jfreechart\r
+                                if(ress.size() == 1) {\r
+                                    Resource r = ress.iterator().next();\r
+                                    JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
+                                    if(graph.isInstanceOf(r, jfree.Chart)) {\r
+                                        selectionChanged(graph, r);\r
+                                        return null;\r
+                                    }\r
+                                }\r
+                            }\r
+                        }\r
+\r
+                        // Update datasets and add result listeners to models\r
+                        return getDatasets(graph, vars);\r
+\r
+                    }\r
+                }, listener);\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();   \r
+            }\r
+        }\r
+    }\r
+\r
+\r
+\r
+    /**\r
+     * Updates datasets for the selected variables\r
+     * @param graph ReadGraph\r
+     * @param variables Selected variables\r
+     * @throws DatabaseException\r
+     */\r
+    private ArrayList<SysdynDataSet> getDatasets(ReadGraph graph, Collection<Variable> variables) throws DatabaseException {\r
+\r
+        ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
+        for(Variable variable : variables) {\r
+            Variable v = graph.syncRequest(new PossibleActiveVariableFromVariable(variable));\r
+            if(v == null)\r
+                continue;\r
+            // Get all active datasets for the variable and add them to the result\r
+            Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
+            Object object = null;\r
+            if(dsVariable != null)\r
+                 object = dsVariable.getValue(graph);\r
+\r
+            if(object != null && object instanceof ArrayList<?>)\r
+                for(Object o : (ArrayList<?>)object) {\r
+                    if(o instanceof SysdynDataSet)\r
+                        datasets.add((SysdynDataSet)o);\r
+                }\r
+        }\r
+\r
+        return datasets;\r
+    }\r
+\r
+\r
+    /**\r
+     * Find a variable representing element\r
+     * \r
+     * @param g ReadGraph\r
+     * @param element Element resource\r
+     * @param runtime runtime resource\r
+     * @return Variable representing element\r
+     * @throws DatabaseException\r
+     */\r
+    private Variable getVariable(ReadGraph g, Resource element, Resource runtime) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(g);\r
+        DiagramResource dr = DiagramResource.getInstance(g);\r
+        if(runtime == null) return null;\r
+        Resource resource = ModelingUtils.getPossibleElementCorrespondendence(g, element);\r
+        if(resource != null && g.isInstanceOf(resource, sr.Shadow)) resource = g.getPossibleObject(resource, sr.Shadow_original);\r
+        if(resource == null || !g.isInstanceOf(resource, sr.Variable)) return null;\r
+        String variableURI = g.getPossibleRelatedValue(runtime, dr.RuntimeDiagram_HasVariable);\r
+        if(variableURI != null) {\r
+            try {\r
+                Variable compositeVariable = Variables.getVariable(g, variableURI);\r
+                return compositeVariable.browsePossible(g, resource);\r
+            } catch (MissingVariableException e) {}\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/Preferences.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/Preferences.java
new file mode 100644 (file)
index 0000000..f75c970
--- /dev/null
@@ -0,0 +1,55 @@
+package org.simantics.sysdyn.ui.wizards;\r
+\r
+import java.util.Deque;\r
+import java.util.Iterator;\r
+import java.util.LinkedList;\r
+import java.util.Set;\r
+import java.util.TreeSet;\r
+\r
+import org.eclipse.ui.IMemento;\r
+import org.simantics.utils.ui.workbench.StringMemento;\r
+\r
+public final class Preferences {\r
+\r
+    public static final String  RECENT_MODEL_IMPORT_LOCATIONS = "RECENT_MODEL_IMPORT_LOCATIONS";\r
+    public static final String  RECENT_MODEL_EXPORT_LOCATIONS = "RECENT_MODEL_EXPORT_LOCATIONS";\r
+    public static final String  MODEL_EXPORT_OVERWRITE = "MODEL_EXPORT_OVERWRITE";\r
+\r
+    private static final String TAG_PATH                = "path";\r
+    private static final String ATTR_NAME               = "name";\r
+\r
+    public static Deque<String> decodePaths(String recentPathsPref) {\r
+        Deque<String> result = new LinkedList<String>();\r
+        try {\r
+            StringMemento sm = new StringMemento(recentPathsPref);\r
+            for (IMemento m : sm.getChildren(TAG_PATH)) {\r
+                String name = m.getString(ATTR_NAME);\r
+                if (name != null && !name.isEmpty())\r
+                    result.add(name);\r
+            }\r
+        } catch (IllegalArgumentException e) {\r
+        }\r
+        return result;\r
+    }\r
+\r
+    public static String encodePaths(Deque<String> recentPaths) {\r
+        StringMemento sm = new StringMemento();\r
+        for (String path : recentPaths) {\r
+            IMemento m = sm.createChild(TAG_PATH);\r
+            m.putString(ATTR_NAME, path);\r
+        }\r
+        return sm.toString();\r
+    }\r
+\r
+    public static <T> void removeDuplicates(Iterable<String> iter) {\r
+        // Remove duplicates\r
+        Set<String> dups = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);\r
+        for (Iterator<String> it = iter.iterator(); it.hasNext();) {\r
+            String path = it.next();\r
+            if (!dups.add(path)) {\r
+                it.remove();\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/ExportWizardFunction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/ExportWizardFunction.java
new file mode 100644 (file)
index 0000000..5b5667b
--- /dev/null
@@ -0,0 +1,53 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.ui.IImportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.simantics.db.Resource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+\r
+public class ExportWizardFunction extends Wizard implements IImportWizard {\r
+       \r
+       private WizardFunctionsExportPage mainPage;\r
+       private IStructuredSelection currentSelection = null;\r
+       private String initialPath = null;\r
+       public Resource selection;\r
+\r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ExportWizardFunction() {\r
+       this(null);\r
+    }\r
+    \r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ExportWizardFunction(String initialPath)\r
+    {\r
+        super();\r
+        this.initialPath = initialPath;\r
+    }\r
\r
+    public void init(IWorkbench workbench, IStructuredSelection currentSelection) {\r
+        setWindowTitle("Export");\r
+        this.currentSelection = currentSelection;\r
+        selection = (Resource)AdaptionUtils.adaptToSingle(currentSelection, org.simantics.db.Resource.class);\r
+    }\r
+    \r
+    public void addPages() {\r
+        super.addPages();\r
+               mainPage = new WizardFunctionsExportPage(\r
+                               "wizardFunctionsExportPage", initialPath, currentSelection); //$NON-NLS-1$\r
+        addPage(mainPage);\r
+    }\r
+\r
+       @Override\r
+       public boolean performFinish() {\r
+               return mainPage.createProjects(selection);\r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeFunctionLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeFunctionLabeler.java
new file mode 100644 (file)
index 0000000..37d85e0
--- /dev/null
@@ -0,0 +1,20 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.labeler.LabelerContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
+\r
+public class FunctionTreeFunctionLabeler extends LabelerContributor<FunctionLibraryNode<Resource>>{\r
+\r
+       @Override\r
+       public String getLabel(ReadGraph graph, FunctionLibraryNode<Resource> input)\r
+                       throws DatabaseException {\r
+               String name = NameUtils.getSafeName(graph, input.data);\r
+               return name;\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeLibraries.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeLibraries.java
new file mode 100644 (file)
index 0000000..f234424
--- /dev/null
@@ -0,0 +1,37 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+\r
+public class FunctionTreeLibraries extends ViewpointContributor<ModelNode> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, ModelNode model)\r
+    throws DatabaseException {\r
+       ArrayList<FunctionLibraryNode<Resource>> result = new ArrayList<FunctionLibraryNode<Resource>>();\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+               for (Resource r : graph.syncRequest(new ObjectsWithType(model.data, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))){\r
+                       result.add(new FunctionLibraryNode<Resource>(r));\r
+               }\r
+\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeModelLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeModelLabeler.java
new file mode 100644 (file)
index 0000000..1a2003a
--- /dev/null
@@ -0,0 +1,17 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.labeler.LabelerContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+\r
+public class FunctionTreeModelLabeler extends LabelerContributorImpl<ModelNode>{\r
+\r
+       @Override\r
+       public String getLabel(ReadGraph graph, ModelNode input)\r
+                       throws DatabaseException {\r
+               return NameUtils.getSafeName(graph, input.data);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeModels.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeModels.java
new file mode 100644 (file)
index 0000000..623f1a3
--- /dev/null
@@ -0,0 +1,43 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.impl.contributor.viewpoint.ViewpointContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+\r
+public class FunctionTreeModels extends ViewpointContributorImpl<Resource> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, Resource input)\r
+                       throws DatabaseException {\r
+               \r
+\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(input, l0.ConsistsOf, sr.SysdynModel))) {\r
+                       result.add(new ModelNode(r));\r
+               }\r
+               Resource sharedlibrary = graph.getPossibleResource("http://SharedOntologies");\r
+               if (sharedlibrary != null)\r
+               result.add(new SharedFunctionsFolderNode(sharedlibrary));\r
+               \r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "Function Library Import";\r
+       }\r
+       \r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedFolderLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedFolderLabeler.java
new file mode 100644 (file)
index 0000000..17f5368
--- /dev/null
@@ -0,0 +1,15 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.labeler.LabelerContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public class FunctionTreeSharedFolderLabeler extends LabelerContributorImpl<SharedFunctionsFolderNode>{\r
+\r
+       @Override\r
+       public String getLabel(ReadGraph graph, SharedFunctionsFolderNode input)\r
+                       throws DatabaseException {\r
+               return "Shared Functions";\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedLibraries.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedLibraries.java
new file mode 100644 (file)
index 0000000..e9003a1
--- /dev/null
@@ -0,0 +1,35 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;\r
+\r
+public class FunctionTreeSharedLibraries extends ViewpointContributor<SharedFunctionsFolderNode> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, SharedFunctionsFolderNode folder)\r
+    throws DatabaseException {\r
+       ArrayList<SharedFunctionLibraryNode> result = new ArrayList<SharedFunctionLibraryNode>();\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Resource sharedlibrary = graph.getPossibleResource("http://SharedOntologies");\r
+               for (Resource r : graph.syncRequest(new ObjectsWithType(sharedlibrary, l0.ConsistsOf, sr.SharedFunctionOntology))){\r
+                       result.add(new SharedFunctionLibraryNode(r));\r
+               }\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedLibraryLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSharedLibraryLabeler.java
new file mode 100644 (file)
index 0000000..e054cf6
--- /dev/null
@@ -0,0 +1,17 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.labeler.LabelerContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;\r
+\r
+public class FunctionTreeSharedLibraryLabeler extends LabelerContributorImpl<SharedFunctionLibraryNode>{\r
+\r
+       @Override\r
+       public String getLabel(ReadGraph graph, SharedFunctionLibraryNode input)\r
+                       throws DatabaseException {\r
+               return NameUtils.getSafeName(graph, input.data);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSubLibraries.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/FunctionTreeSubLibraries.java
new file mode 100644 (file)
index 0000000..c88421a
--- /dev/null
@@ -0,0 +1,36 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
+\r
+public class FunctionTreeSubLibraries extends ViewpointContributor<FunctionLibraryNode<Resource>> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, FunctionLibraryNode<Resource> library)\r
+    throws DatabaseException {\r
+       ArrayList<FunctionLibraryNode<Resource>> result = new ArrayList<FunctionLibraryNode<Resource>>();\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+               for (Resource r : graph.syncRequest(new ObjectsWithType(library.data, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))){\r
+                       result.add(new FunctionLibraryNode<Resource>(r));\r
+               }\r
+\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/ImportWizardFunction.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/ImportWizardFunction.java
new file mode 100644 (file)
index 0000000..b51a322
--- /dev/null
@@ -0,0 +1,54 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.ui.IImportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.simantics.db.Resource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+\r
+public class ImportWizardFunction extends Wizard implements IImportWizard {\r
+       \r
+       private WizardFunctionsImportPage mainPage;\r
+       private IStructuredSelection currentSelection = null;\r
+       private String initialPath = null;\r
+       public Resource selection;\r
+\r
+    /**\r
+     * Constructor for ImportWizardFunction.\r
+     */\r
+    public ImportWizardFunction() {\r
+       this(null);\r
+    }\r
+    \r
+    /**\r
+     * Constructor for ImportWizardFunction.\r
+     */\r
+    public ImportWizardFunction(String initialPath)\r
+    {\r
+        super();\r
+        this.initialPath = initialPath;\r
+    }\r
\r
+    public void init(IWorkbench workbench, IStructuredSelection currentSelection) {\r
+        setWindowTitle("Import");\r
+        this.currentSelection = currentSelection;\r
+        selection = (Resource)AdaptionUtils.adaptToSingle(currentSelection, org.simantics.db.Resource.class);\r
+    }\r
+    \r
+    public void addPages() {\r
+        super.addPages();\r
+               mainPage = new WizardFunctionsImportPage(\r
+                               "wizardFunctionsImportPage", initialPath, currentSelection); //$NON-NLS-1$\r
+        addPage(mainPage);\r
+    }\r
+\r
+       @Override\r
+       public boolean performFinish() {\r
+               return mainPage.createProjects();\r
+               \r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/SharedFunctionsFolderNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/SharedFunctionsFolderNode.java
new file mode 100644 (file)
index 0000000..2658fb6
--- /dev/null
@@ -0,0 +1,60 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+public class SharedFunctionsFolderNode extends FunctionLibraryNode<Resource> implements IDropTargetNode {\r
+\r
+    public SharedFunctionsFolderNode(Resource resource) {\r
+        super(resource);\r
+    }\r
+\r
+       @Override\r
+       public void delete() throws DeleteException {\r
+               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               \r
+                               graph.deny(data, l0.PartOf);\r
+                               graph.deny(data, l0.IsLinkedTo_Inverse);\r
+\r
+                               // TODO: remove file\r
+                       }\r
+               });\r
+       }\r
+       \r
+       @Override\r
+       public void drop(Object data) {\r
+               final Resource[] resources = ResourceAdaptionUtils.toResources(data);\r
+               final Resource library = this.data;\r
+               if(resources.length > 0) {\r
+                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                               \r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       for(Resource tobeMoved : resources) {\r
+                                               if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||\r
+                                                               graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {\r
+                                                       graph.deny(tobeMoved, l0.PartOf);\r
+                                                       graph.claim(tobeMoved, l0.PartOf, library);\r
+                                               }\r
+                                       }\r
+                               }\r
+                       });\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java
new file mode 100644 (file)
index 0000000..785df45
--- /dev/null
@@ -0,0 +1,366 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+\r
+import org.eclipse.core.runtime.Path;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.PixelConverter;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.Files;\r
+import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.TransferableGraphRequest2;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.graph.representation.TransferableGraph1;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class WizardFunctionsExportPage extends WizardPage {\r
+       \r
+       // dialog store id constants\r
+       private Text filePathField;\r
+       \r
+       // Keep track of the archive that we browsed to last time\r
+       // the wizard was invoked.\r
+       private static String previouslyBrowsedFile = "";\r
+\r
+       private Button browseDirectoriesButton;\r
+       \r
+       //private IStructuredSelection currentSelection;\r
+       \r
+       GraphExplorerComposite functionLibraryExplorer;\r
+       \r
+       private boolean selectionMade = false;\r
+       \r
+       /**\r
+        * Creates a new project creation wizard page.\r
+        * \r
+        */\r
+       public WizardFunctionsExportPage() {\r
+               this("wizardFunctionsExportPage", null, null); //$NON-NLS-1$\r
+       }\r
+\r
+       /**\r
+        * Create a new instance of the receiver.\r
+        * \r
+        * @param pageName\r
+        */\r
+       public WizardFunctionsExportPage(String pageName) {\r
+               this(pageName,null, null);\r
+       }\r
+                       \r
+       /**\r
+        * More (many more) parameters.\r
+        * \r
+        * @param pageName\r
+        * @param initialPath\r
+        * @param currentSelection\r
+        * @since 3.5\r
+        */\r
+       public WizardFunctionsExportPage(String pageName,String initialPath,\r
+                       IStructuredSelection currentSelection) {\r
+               super(pageName);\r
+               //this.currentSelection = currentSelection;\r
+               setPageComplete(false);\r
+               setTitle("Export Function Library");\r
+               setDescription("Choose the Function Library and the export location, then press Finish.");\r
+       }\r
+       \r
+       public void createControl(Composite parent) {\r
+               \r
+               initializeDialogUnits(parent);\r
+\r
+               Composite workArea = new Composite(parent, SWT.NONE);\r
+               setControl(workArea);\r
+\r
+               workArea.setLayout(new GridLayout());\r
+               workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
+                               | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
+\r
+               createProjectsRoot(workArea);\r
+               createTree(workArea);\r
+               \r
+       }\r
+       \r
+       private void createProjectsRoot(Composite workArea) {\r
+               \r
+               // set label for field\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select the export location for Function Library:");\r
+               \r
+               Composite projectGroup = new Composite(workArea, SWT.NONE);\r
+               GridLayout layout = new GridLayout();\r
+               layout.numColumns = 2;\r
+               layout.makeColumnsEqualWidth = false;\r
+               layout.marginWidth = 0;\r
+\r
+               projectGroup.setLayout(layout);\r
+               projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
+               \r
+               // function library location entry field\r
+               this.filePathField = new Text(projectGroup, SWT.BORDER);\r
+\r
+               GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
+               directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
+               filePathField.setLayoutData(directoryPathData);\r
+               \r
+               filePathField.addModifyListener(new ModifyListener(){\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+               previouslyBrowsedFile = filePathField.getText();        \r
+            }\r
+               });\r
+               if (previouslyBrowsedFile != null){\r
+                       filePathField.setText(previouslyBrowsedFile);\r
+                       validatePage();\r
+               }\r
+               \r
+               // browse button\r
+               browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
+               browseDirectoriesButton.setText("Browse");\r
+               setButtonLayoutData(browseDirectoriesButton);\r
+               \r
+               browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
+                       /*\r
+                        * (non-Javadoc)\r
+                        * \r
+                        * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
+                        * elected(org.eclipse.swt.events.SelectionEvent)\r
+                        */\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               handleLocationDirectoryButtonPressed();\r
+                       }\r
+               });\r
+               \r
+       }\r
+       \r
+       private void createTree(Composite workArea){\r
+               \r
+               //set label for tree\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select Function Library to export:");\r
+\r
+               try {\r
+                       Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph)\r
+                                               throws DatabaseException {\r
+                                       Resource model = SimanticsUI.getProject().get();\r
+                                       return model;\r
+                               }\r
+\r
+                       });\r
+\r
+                       functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                                       "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
+\r
+                       functionLibraryExplorer\r
+                       .setBrowseContexts(SysdynResource.URIs.FunctionTree);\r
+\r
+                       functionLibraryExplorer.finish();\r
+\r
+                       functionLibraryExplorer.setInput(null, input);\r
+\r
+                       GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                                       functionLibraryExplorer);\r
+                       \r
+                       ((Tree)functionLibraryExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
+                               \r
+                               @Override\r
+                               public void widgetSelected(SelectionEvent e) {\r
+                                       setMessage(null);\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                               @Override\r
+                               public void widgetDefaultSelected(SelectionEvent e) {\r
+                                       setMessage(null);\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                       });\r
+\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+\r
+       }\r
+    \r
+       //Set filePathField active\r
+       public void setVisible(boolean visible) {\r
+               super.setVisible(visible);\r
+               this.filePathField.setFocus();\r
+       }\r
+       \r
+       \r
+       //Open dialog for choosing the file\r
+       protected void handleLocationDirectoryButtonPressed() {\r
+               \r
+               final Shell shell = filePathField.getShell();\r
+               \r
+               FileDialog dialog = new FileDialog(shell, SWT.SAVE);\r
+               \r
+               String[] ext = {"*.sysdynFunctions"};\r
+               dialog.setFilterExtensions(ext);\r
+               \r
+               dialog.setText("Export Function Library");\r
+\r
+               String dirName = filePathField.getText().trim();\r
+               \r
+               File path = new File(dirName);\r
+               if (path.exists()) {\r
+                       dialog.setFilterPath(new Path(dirName).toOSString());   \r
+               }\r
+               \r
+               String selectedFile = dialog.open();\r
+               if (selectedFile != null) {\r
+                       filePathField.setText(selectedFile);\r
+                       validatePage();\r
+               }               \r
+\r
+       }\r
+       \r
+       //Get selection from the tree\r
+       @SuppressWarnings("unchecked")\r
+       public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
+                       Class<T> clazz) {\r
+               if(explorer == null)\r
+                       return null;\r
+               ISelection selection = ((ISelectionProvider) explorer\r
+                               .getAdapter(ISelectionProvider.class)).getSelection();\r
+               if (selection == null)\r
+                       return null;\r
+               IStructuredSelection iss = (IStructuredSelection) selection;\r
+               AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
+               if (inc == null)\r
+                       return null;\r
+               final T resource = (T) inc.getAdapter(clazz);\r
+\r
+               return resource;\r
+       }\r
+       \r
+       public boolean createProjects(Resource selection) {\r
+               \r
+               final String selected = previouslyBrowsedFile;\r
+               if(selected == null) return false;\r
+               \r
+        final Resource functionLibrary = getExplorerResource(functionLibraryExplorer, Resource.class);\r
+        if(functionLibrary == null) return false;\r
+        \r
+               String name = null;\r
+               try {\r
+                       name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf))\r
+                                               return null;\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       String name = graph.syncRequest(new PossibleRelatedValue<String>(functionLibrary, l0.HasName, Bindings.STRING ));\r
+                                       return name;\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+               } catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               if(name == null) return false;\r
+       \r
+               SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               String name = graph.syncRequest(new PossibleRelatedValue<String>(functionLibrary, l0.HasName, Bindings.STRING ));\r
+                               ArrayList<Pair<Resource, String>> roots = new ArrayList<Pair<Resource, String>>();\r
+                               roots.add(Pair.make(functionLibrary, name));\r
+                               TransferableGraph1 tg = graph.syncRequest(new TransferableGraphRequest2(roots, functionLibrary));\r
+\r
+                               try {\r
+                                       Files.createFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class), tg);\r
+                               } catch (RuntimeBindingConstructionException e) {\r
+                                       e.printStackTrace();\r
+                               } catch (IOException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+\r
+                               \r
+                       }\r
+               });\r
+        \r
+        return true;\r
+       }\r
+       \r
+       void validatePage() {\r
+               \r
+               if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
+                       setPageComplete(false);\r
+                       return;\r
+               }\r
+               \r
+               if (functionLibraryExplorer != null){\r
+                       final Resource selectedResource = getExplorerResource(functionLibraryExplorer, Resource.class);\r
+\r
+                       String root = null;\r
+                       try {\r
+                               root = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                                       @Override\r
+                                       public String perform(ReadGraph graph) throws DatabaseException {\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               Resource model = graph.getPossibleObject(selectedResource, l0.PartOf);\r
+                                               String rootName = NameUtils.getSafeName(graph, model);\r
+\r
+                                               return rootName;\r
+                                       }\r
+\r
+                               });\r
+                               if (root != null && root.equalsIgnoreCase("Development Project")){\r
+                                       setPageComplete(false);\r
+                                       setMessage("Select Function Library folder under the Model or from the Shared Functions folder.");\r
+                                       return;\r
+                               }\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+               }\r
+               \r
+               setPageComplete(true);\r
+               \r
+       }\r
+       \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java
new file mode 100644 (file)
index 0000000..702a96c
--- /dev/null
@@ -0,0 +1,441 @@
+package org.simantics.sysdyn.ui.wizards.functions;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Path;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.PixelConverter;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+\r
+public class WizardFunctionsImportPage extends WizardPage{\r
+\r
+       // dialog store id constants\r
+       private Text filePathField;\r
+\r
+       // Keep track of the archive that we browsed to last time\r
+       // the wizard was invoked.\r
+       private static String previouslyBrowsedFile = "";\r
+\r
+       private Button browseDirectoriesButton;\r
+\r
+       private Shell shell;\r
+\r
+       //private IStructuredSelection currentSelection;\r
+\r
+       private Resource selectedModel;\r
+\r
+       GraphExplorerComposite functionLibraryExplorer;\r
+       \r
+       private boolean selectionMade = false;\r
+       \r
+       /**\r
+        * Creates a new project creation wizard page.\r
+        * \r
+        */\r
+       public WizardFunctionsImportPage() {\r
+               this("wizardFunctionsImportPage", null, null); //$NON-NLS-1$\r
+       }\r
+\r
+       /**\r
+        * Create a new instance of the receiver.\r
+        * \r
+        * @param pageName\r
+        */\r
+       public WizardFunctionsImportPage(String pageName) {\r
+               this(pageName,null, null);\r
+       }\r
+\r
+       /**\r
+        * More (many more) parameters.\r
+        * \r
+        * @param pageName\r
+        * @param initialPath\r
+        * @param currentSelection\r
+        * @since 3.5\r
+        */\r
+       public WizardFunctionsImportPage(String pageName,String initialPath,\r
+                       IStructuredSelection currentSelection) {\r
+               super(pageName);\r
+               setPageComplete(false);\r
+               //this.currentSelection = currentSelection;\r
+               setTitle("Import Function Library");\r
+               setDescription("Choose the Function Library file and the import location, then press Finish.");\r
+       }\r
+\r
+       public void createControl(Composite parent) {\r
+\r
+               initializeDialogUnits(parent);\r
+\r
+               Composite workArea = new Composite(parent, SWT.NONE);\r
+               setControl(workArea);\r
+\r
+               workArea.setLayout(new GridLayout());\r
+               workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
+                               | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
+\r
+               createProjectsRoot(workArea);\r
+\r
+               createTree(workArea);\r
+               \r
+               \r
+       }\r
+\r
+       private void createProjectsRoot(Composite workArea) {\r
+\r
+               //set label for field\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select Function Library source:");\r
+\r
+               Composite projectGroup = new Composite(workArea, SWT.NONE);\r
+               GridLayout layout = new GridLayout();\r
+               layout.numColumns = 2;\r
+               layout.makeColumnsEqualWidth = false;\r
+               layout.marginWidth = 0;\r
+\r
+               projectGroup.setLayout(layout);\r
+               projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
+\r
+               // module location entry field\r
+               this.filePathField = new Text(projectGroup, SWT.BORDER);\r
+\r
+               GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
+               directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
+               filePathField.setLayoutData(directoryPathData);\r
+               \r
+\r
+               filePathField.addModifyListener(new ModifyListener(){\r
+                       @Override\r
+                       public void modifyText(ModifyEvent e) {\r
+                               previouslyBrowsedFile = filePathField.getText();        \r
+                       }\r
+               });\r
+               if (previouslyBrowsedFile != null){\r
+                       filePathField.setText(previouslyBrowsedFile);\r
+                       validatePage();\r
+               }\r
+\r
+               // browse button\r
+               browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
+               browseDirectoriesButton.setText("Browse");\r
+               setButtonLayoutData(browseDirectoriesButton);\r
+\r
+               browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
+                       /*\r
+                        * (non-Javadoc)\r
+                        * \r
+                        * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
+                        * elected(org.eclipse.swt.events.SelectionEvent)\r
+                        */\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               handleLocationDirectoryButtonPressed();\r
+                       }\r
+               });\r
+\r
+       }\r
+\r
+       private void createTree(Composite workArea){\r
+               \r
+               //set label for tree\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select import location:");\r
+\r
+               try {\r
+                       Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph)\r
+                                               throws DatabaseException {\r
+                                       Resource model = SimanticsUI.getProject().get();\r
+                                       return model;\r
+                               }\r
+\r
+                       });\r
+\r
+                       functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                                       "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
+\r
+                       functionLibraryExplorer\r
+                       .setBrowseContexts(SysdynResource.URIs.FunctionTree);\r
+\r
+                       functionLibraryExplorer.finish();\r
+\r
+                       functionLibraryExplorer.setInput(null, input);\r
+\r
+                       GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                                       functionLibraryExplorer);\r
+                       \r
+                       ((Tree)functionLibraryExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
+                               \r
+                               @Override\r
+                               public void widgetSelected(SelectionEvent e) {\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                               @Override\r
+                               public void widgetDefaultSelected(SelectionEvent e) {\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                       });\r
+\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+       }\r
+\r
+       //Set filePathField active\r
+       public void setVisible(boolean visible) {\r
+               super.setVisible(visible);\r
+               this.filePathField.setFocus();\r
+       }\r
+\r
+       //Open dialog for choosing the file\r
+       protected void handleLocationDirectoryButtonPressed() {\r
+\r
+               shell = filePathField.getShell();\r
+\r
+               FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
+\r
+               String[] ext = {"*.sysdynFunctions; *.tg", "*.*"};\r
+               dialog.setFilterExtensions(ext);\r
+\r
+               dialog.setText("Import Function Library");\r
+\r
+               String dirName = filePathField.getText().trim();\r
+\r
+               File path = new File(dirName);\r
+               if (path.exists()) {\r
+                       dialog.setFilterPath(new Path(dirName).toOSString());   \r
+               }\r
+\r
+               String selectedFile = dialog.open();\r
+               if (selectedFile != null) {\r
+                       filePathField.setText(selectedFile);\r
+                       validatePage();\r
+               }       \r
+       }\r
+\r
+       //Get selection from the tree\r
+       @SuppressWarnings("unchecked")\r
+       public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
+                       Class<T> clazz) {\r
+               \r
+               if(explorer == null)\r
+                       return null;\r
+               ISelection selection = ((ISelectionProvider) explorer\r
+                               .getAdapter(ISelectionProvider.class)).getSelection();\r
+               if (selection == null)\r
+                       return null;\r
+               IStructuredSelection iss = (IStructuredSelection) selection;\r
+               AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
+               if (inc == null)\r
+                       return null;\r
+               final T resource = (T) inc.getAdapter(clazz);\r
+\r
+               return resource;\r
+       }\r
+\r
+       //Create project after finish is pressed.\r
+       public boolean createProjects() {\r
+               \r
+               selectedModel= getExplorerResource(functionLibraryExplorer, Resource.class);\r
+               if(selectedModel == null){\r
+                       setErrorMessage("Error when retrieving resource");\r
+                       return false;\r
+               }\r
+                       \r
+               String selected = previouslyBrowsedFile;\r
+               if(selected == null){\r
+                       setErrorMessage("No file selected");\r
+                       return false;\r
+               }\r
+               \r
+               IStatus status = ImportUtilsUI.importFunctionLibrary(selectedModel, selected, null);\r
+\r
+               /*\r
+               TransferableGraph1 tg = null;\r
+               try {\r
+                       tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
+               } catch (RuntimeBindingConstructionException e) {\r
+                       e.printStackTrace();\r
+                       return false;\r
+               } catch (IOException e) {\r
+                       setErrorMessage("The imported file is not of type: Function Library");\r
+                       return false;\r
+               } \r
+               if(tg == null){\r
+                       setErrorMessage("The imported file is not of type: Function Library");\r
+                       return false;\r
+               }\r
+\r
+\r
+               try {\r
+                       Boolean hasSharedOntologies;\r
+                       hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
+\r
+                               @Override\r
+                               public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                                       try {\r
+                                               graph.getResource("http://SharedOntologies");\r
+                                       } catch (ResourceNotFoundException e) {\r
+                                               return false;\r
+                                       }               \r
+                                       return true;\r
+                               }\r
+                       });\r
+\r
+                       if(!hasSharedOntologies) {\r
+                               SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               GraphUtils.create2(graph, l0.Library, \r
+                                                               l0.HasName, "SharedOntologies",\r
+                                                               l0.PartOf, graph.getResource("http:/"));\r
+                                       }\r
+                               });\r
+\r
+                       }\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+                       return false;\r
+               }\r
+\r
+\r
+               SysdynFunctionLibraryImportAdvisor ia = new SysdynFunctionLibraryImportAdvisor(selectedModel);\r
+               try {\r
+                       DefaultPasteHandler.defaultExecute(tg, selectedModel, ia);\r
+               } catch (Exception e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+               final Resource root = ia.getRoot();\r
+\r
+               try {\r
+                       SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       if(graph.isInstanceOf(root, SysdynResource.getInstance(graph).SharedFunctionOntology)) {\r
+                                               Resource library = graph.getResource("http://SharedOntologies");\r
+                                               if(!graph.hasStatement(library, l0.ConsistsOf, root)) {\r
+                                                       graph.claim(library, l0.ConsistsOf, root);\r
+                                               }\r
+\r
+                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                               Resource model = selectedModel;\r
+                                               while(!graph.isInstanceOf(model, sr.SysdynModel) && graph.isInstanceOf(model, l0.Ontology))\r
+                                                       model = graph.getSingleObject(model, l0.PartOf);\r
+                                               if(graph.isInstanceOf(model, sr.SysdynModel)) {\r
+                                                       graph.claim(model, l0.IsLinkedTo, l0.IsLinkedTo_Inverse, root);\r
+                                               }\r
+\r
+                                       } else if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary)) {\r
+                                               Resource instanceOf = graph.getPossibleObject(root,l0.InstanceOf);\r
+                                               String type = "...";\r
+                                               if(instanceOf != null)\r
+                                                       type = NameUtils.getSafeName(graph, instanceOf);\r
+                                               else {\r
+                                                       Resource inheritedFrom = graph.getPossibleObject(root, l0.Inherits);\r
+                                                       if(inheritedFrom != null)\r
+                                                               type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                                               } \r
+                                               graph.deny(root, l0.PartOf);\r
+                                               error = type;\r
+                                       }\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               if (!error.isEmpty()){\r
+                       setErrorMessage("The imported file is not of type: Function Library (" + error +")");\r
+                       error = "";\r
+                       return false;\r
+               }\r
+                */\r
+               if(status == null || !status.equals(Status.OK_STATUS)) {\r
+                   setErrorMessage(status.getMessage());\r
+                   return false;\r
+               }\r
+               return true;\r
+       }\r
+       /*\r
+\r
+       private class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {\r
+\r
+               public SysdynFunctionLibraryImportAdvisor(Resource library) {\r
+                       super(library);\r
+               }\r
+\r
+               @Override\r
+               public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {\r
+                       if(root.type.equals(SysdynResource.URIs.SharedFunctionOntology)) {\r
+                               try {\r
+                                       library = graph.getResource("http://SharedOntologies");\r
+                               } catch (ResourceNotFoundException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+                       }\r
+               }\r
+\r
+               @Override\r
+               public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {\r
+                       Layer0 l0 = graph.getService(Layer0.class);\r
+                       this.root = graph.newResource();\r
+                       graph.claim(library, l0.ConsistsOf, l0.PartOf, this.root);\r
+                       String name = root.name;\r
+                       String newName = nameMappings.get(name);\r
+                       graph.addLiteral(this.root, l0.HasName, l0.NameOf, l0.String, newName, Bindings.STRING);\r
+                       return this.root;\r
+\r
+               }\r
+\r
+       }\r
+       */\r
+       \r
+       void validatePage() {\r
+\r
+               if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
+                       setPageComplete(false);\r
+                       return;\r
+               }\r
+               setErrorMessage(null);\r
+               setPageComplete(true);\r
+\r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/ImportWizardMdl.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/ImportWizardMdl.java
new file mode 100644 (file)
index 0000000..9142284
--- /dev/null
@@ -0,0 +1,47 @@
+package org.simantics.sysdyn.ui.wizards.mdl;\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.ui.IImportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+\r
+public class ImportWizardMdl extends Wizard implements IImportWizard {\r
+       \r
+       private WizardMdlImportPage mainPage;\r
+       private IStructuredSelection currentSelection = null;\r
+       private String initialPath = null;\r
+       \r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ImportWizardMdl() {\r
+       this(null);\r
+    }\r
+    \r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ImportWizardMdl(String initialPath)\r
+    {\r
+        super();\r
+        this.initialPath = initialPath;\r
+    }\r
+\r
+    public void addPages() {\r
+        super.addPages();\r
+               mainPage = new WizardMdlImportPage(\r
+                               "wizardMdlImportPage", initialPath, currentSelection); //$NON-NLS-1$\r
+        addPage(mainPage);\r
+    }\r
+    \r
+    public void init(IWorkbench workbench, IStructuredSelection currentSelection) {\r
+        setWindowTitle("Import");\r
+        this.currentSelection = currentSelection;\r
+    }\r
+    \r
+       @Override\r
+       public boolean performFinish() {\r
+               return mainPage.createProjects();\r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/WizardMdlImportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/WizardMdlImportPage.java
new file mode 100644 (file)
index 0000000..93766ed
--- /dev/null
@@ -0,0 +1,213 @@
+package org.simantics.sysdyn.ui.wizards.mdl;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.runtime.Path;\r
+import org.eclipse.jface.layout.PixelConverter;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.modelImport.MdlParser;\r
+import org.simantics.sysdyn.modelImport.model.Model;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class WizardMdlImportPage extends WizardPage{\r
+       \r
+       // dialog store id constants\r
+       private Text filePathField;\r
+       \r
+       // Keep track of the archive that we browsed to last time\r
+       // the wizard was invoked.\r
+       private static String previouslyBrowsedFile = "";\r
+\r
+       private Button browseDirectoriesButton;\r
+       \r
+       /**\r
+        * Creates a new project creation wizard page.\r
+        * \r
+        */\r
+       public WizardMdlImportPage() {\r
+               this("wizardMdlImportPage", null, null); //$NON-NLS-1$\r
+       }\r
+\r
+       /**\r
+        * Create a new instance of the receiver.\r
+        * \r
+        * @param pageName\r
+        */\r
+       public WizardMdlImportPage(String pageName) {\r
+               this(pageName,null, null);\r
+       }\r
+                       \r
+       /**\r
+        * More (many more) parameters.\r
+        * \r
+        * @param pageName\r
+        * @param initialPath\r
+        * @param currentSelection\r
+        * @since 3.5\r
+        */\r
+       public WizardMdlImportPage(String pageName,String initialPath,\r
+                       IStructuredSelection currentSelection) {\r
+               super(pageName);\r
+               setPageComplete(false);\r
+               setTitle("Import Vensim model");\r
+               setDescription("Choose the Vensim model file (.mdl), then press Finish.");\r
+       }\r
+\r
+       public void createControl(Composite parent) {\r
+       \r
+               initializeDialogUnits(parent);\r
+\r
+               Composite workArea = new Composite(parent, SWT.NONE);\r
+               setControl(workArea);\r
+\r
+               workArea.setLayout(new GridLayout());\r
+               workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
+                               | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
+\r
+               createProjectsRoot(workArea);   \r
+       }\r
+       \r
+       private void createProjectsRoot(Composite workArea) {\r
+\r
+               // set label for field\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select Vensim model source:");\r
+               \r
+               Composite projectGroup = new Composite(workArea, SWT.NONE);\r
+               GridLayout layout = new GridLayout();\r
+               layout.numColumns = 2;\r
+               layout.makeColumnsEqualWidth = false;\r
+               layout.marginWidth = 0;\r
+\r
+               projectGroup.setLayout(layout);\r
+               projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
+\r
+               // model location entry field\r
+               this.filePathField = new Text(projectGroup, SWT.BORDER);\r
+               \r
+               GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
+               directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
+               filePathField.setLayoutData(directoryPathData);\r
+               filePathField.addModifyListener(new ModifyListener(){\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+               previouslyBrowsedFile = filePathField.getText();        \r
+            }\r
+               });\r
+               if (previouslyBrowsedFile != null){\r
+                       filePathField.setText(previouslyBrowsedFile);\r
+                       validatePage();\r
+               }\r
+               \r
+               // browse button\r
+               browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
+               browseDirectoriesButton.setText("Browse");\r
+               setButtonLayoutData(browseDirectoriesButton);\r
+               \r
+               browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
+                       /*\r
+                        * (non-Javadoc)\r
+                        * \r
+                        * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
+                        * elected(org.eclipse.swt.events.SelectionEvent)\r
+                        */\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               handleLocationDirectoryButtonPressed();\r
+                       }\r
+               });\r
+               \r
+       }\r
+       \r
+       //Set filePathField active\r
+       public void setVisible(boolean visible) {\r
+               super.setVisible(visible);\r
+               this.filePathField.setFocus();\r
+       }\r
+       \r
+       //Open dialog for choosing the file\r
+       protected void handleLocationDirectoryButtonPressed() {\r
+               \r
+               final Shell shell = filePathField.getShell();\r
+\r
+               FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
+               String[] ext = {"*.mdl"};\r
+               dialog.setFilterExtensions(ext);\r
+               dialog.setText("Import Vensim model (.mdl)");\r
+\r
+               String dirName = filePathField.getText().trim();\r
+               \r
+               File path = new File(dirName);\r
+               if (path.exists()) {\r
+                       dialog.setFilterPath(new Path(dirName).toOSString());   \r
+               }\r
+               \r
+               String selectedFile = dialog.open();\r
+               if (selectedFile != null) {\r
+                       filePathField.setText(selectedFile);\r
+                       validatePage();\r
+               }\r
+\r
+       }\r
+       \r
+       //Create project after finish is pressed.\r
+       public boolean createProjects() {\r
+               \r
+               final Resource project = SimanticsUI.getProject().get();\r
+               if(project == null) return false;\r
+\r
+               String selected = previouslyBrowsedFile;\r
+               if(selected == null) return false;\r
+               \r
+               File file = new File(selected);\r
+               \r
+               // TODO: is this wizard actually used anywhere?\r
+               final Model model;\r
+               \r
+               try {\r
+                       model = MdlParser.parse(file);\r
+               }\r
+               catch (Exception e) {\r
+                       e.printStackTrace();\r
+                       return false;\r
+               }\r
+               \r
+               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               model.write(graph, project, new WriteContext());\r
+                       }\r
+               });\r
+               \r
+               return true;\r
+               \r
+       }\r
+    void validatePage(){\r
+       \r
+               if (previouslyBrowsedFile.isEmpty()){\r
+                       setPageComplete(false);\r
+                       return;\r
+               }\r
+               \r
+               setPageComplete(true);\r
+    }\r
+}\r
+       
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynExportModel.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynExportModel.java
new file mode 100644 (file)
index 0000000..593bec5
--- /dev/null
@@ -0,0 +1,100 @@
+package org.simantics.sysdyn.ui.wizards.model;\r
+\r
+import java.io.File;\r
+\r
+import org.simantics.db.common.NamedResource;\r
+\r
+public class SysdynExportModel {\r
+    \r
+    private Object              selection;\r
+    private File                exportLocation;\r
+    private String              description;\r
+    private boolean             overwrite;\r
+    private NamedResource       model;\r
+    private boolean             dependencies;\r
+    \r
+    public SysdynExportModel(Object selection, boolean overwrite) {\r
+        this.selection = selection;\r
+        this.description = "";\r
+        this.overwrite = overwrite;\r
+    }\r
+\r
+    /**\r
+     * @return the overwrite\r
+     */\r
+    public boolean getOverwrite() {\r
+        return overwrite;\r
+    }\r
+\r
+    /**\r
+     * @param overwrite the overwrite to set\r
+     */\r
+    public void setOverwrite(boolean overwrite) {\r
+        this.overwrite = overwrite;\r
+    }\r
+\r
+    /**\r
+     * @return the selection\r
+     */\r
+    public Object getSelection() {\r
+        return selection;\r
+    }\r
+\r
+    /**\r
+     * @param selection the selection to set\r
+     */\r
+    public void setSelection(Object selection) {\r
+        this.selection = selection;\r
+    }\r
+\r
+    /**\r
+     * @return the description\r
+     */\r
+    public String getDescription() {\r
+        return description;\r
+    }\r
+\r
+    /**\r
+     * @param description the description to set\r
+     */\r
+    public void setDescription(String description) {\r
+        this.description = description;\r
+    }\r
+\r
+    /**\r
+     * @return the exportLocation\r
+     */\r
+    public File getExportLocation() {\r
+        return exportLocation;\r
+    }\r
+\r
+    /**\r
+     * @param exportLocation the exportLocation to set\r
+     */\r
+    public void setExportLocation(File exportLocation) {\r
+        this.exportLocation = exportLocation;\r
+    }\r
+\r
+    public void setModel(NamedResource model) {\r
+        this.model = model;\r
+    }\r
+    \r
+    public NamedResource getModel() {\r
+        return this.model;\r
+    }\r
+\r
+    /**\r
+     * @return the dependencies\r
+     */\r
+    public boolean getDependencies() {\r
+        return dependencies;\r
+    }\r
+\r
+    /**\r
+     * @param dependencies the dependencies to set\r
+     */\r
+    public void setDependencies(boolean dependencies) {\r
+        this.dependencies = dependencies;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynImportModel.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynImportModel.java
new file mode 100644 (file)
index 0000000..b6e8ee9
--- /dev/null
@@ -0,0 +1,58 @@
+package org.simantics.sysdyn.ui.wizards.model;\r
+\r
+import java.io.File;\r
+import java.util.Deque;\r
+\r
+public class SysdynImportModel {\r
+\r
+    private Object          selection;\r
+    private Deque<String>   recentLocations;\r
+    private File            importLocation;\r
+\r
+    public SysdynImportModel(Deque<String> recentImportPaths) {\r
+        this.recentLocations = recentImportPaths;\r
+    }\r
+\r
+    /**\r
+     * @return the selection\r
+     */\r
+    public Object getSelection() {\r
+        return selection;\r
+    }\r
+\r
+    /**\r
+     * @param selection the selection to set\r
+     */\r
+    public void setSelection(Object selection) {\r
+        this.selection = selection;\r
+    }\r
+\r
+    /**\r
+     * @return the recentLocations\r
+     */\r
+    public Deque<String> getRecentLocations() {\r
+        return recentLocations;\r
+    }\r
+\r
+    /**\r
+     * @param recentLocations the recentLocations to set\r
+     */\r
+    public void setRecentLocations(Deque<String> recentLocations) {\r
+        this.recentLocations = recentLocations;\r
+    }\r
+\r
+    /**\r
+     * @return the importLocation\r
+     */\r
+    public File getImportLocation() {\r
+        return importLocation;\r
+    }\r
+\r
+    /**\r
+     * @param importLocation the importLocation to set\r
+     */\r
+    public void setImportLocation(File importLocation) {\r
+        this.importLocation = importLocation;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelExportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelExportPage.java
new file mode 100644 (file)
index 0000000..27b196d
--- /dev/null
@@ -0,0 +1,257 @@
+package org.simantics.sysdyn.ui.wizards.model;\r
+\r
+import java.io.File;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.CCombo;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.NamedResource;\r
+import org.simantics.db.common.request.UniqueRead;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelExport.ExportConstants;\r
+import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+\r
+public class SysdynModelExportPage extends WizardPage {\r
+\r
+    private SysdynExportModel           exportModel;\r
+    private CCombo                      exportLocation;\r
+    private CCombo                      model;\r
+    //private Composite                   draft;\r
+    private Text                        description;\r
+    private Button                      overwrite;\r
+    private List<NamedResource>         models;\r
+    private Button                      dependencies;\r
+    private Button                      browseFileButton;\r
+    \r
+    protected SysdynModelExportPage(SysdynExportModel exportModel) {\r
+        super("Export Sysdyn Model", "Define Export location", null);\r
+        this.exportModel = exportModel;\r
+    }\r
+\r
+    @Override\r
+    public void createControl(Composite parent) {\r
+        Composite container = new Composite(parent, SWT.NONE);\r
+        GridLayout layout = new GridLayout();\r
+        layout.horizontalSpacing = 20;\r
+        layout.verticalSpacing = 10;\r
+        layout.numColumns = 3;\r
+        container.setLayout(layout);\r
+        \r
+//        draft = new Composite(container, SWT.NONE);\r
+//        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(draft);\r
+//        draft.setBackground(draft.getDisplay().getSystemColor(SWT.COLOR_RED));\r
+//        GridLayoutFactory.swtDefaults().spacing(5, 5).applyTo(draft);\r
+//        \r
+//        Composite draft2 = new Composite(draft, SWT.NONE);\r
+//        GridLayoutFactory.swtDefaults().applyTo(draft2);\r
+//        GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(draft2);\r
+//        new Label(draft2, SWT.NONE).setText("The model contains unpublished dependencies. The model can only be saved with draft status.");\r
+//        \r
+        new Label(container, SWT.NONE).setText("Exported model:");\r
+        model = new CCombo(container, SWT.BORDER);\r
+        model.setEditable(false);\r
+        model.setText("");\r
+        model.setToolTipText("Selects the model to export a state from.");\r
+        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(model);\r
+        model.addModifyListener(new ModifyListener(){\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                \r
+                for (NamedResource nr : models) {\r
+                    if (model.getText().equals(nr.getName())) {\r
+                            exportModel.setModel(nr);\r
+                            break;\r
+                    }\r
+                }\r
+                browseFileButton.setFocus();\r
+                validatePage();\r
+            }\r
+        });\r
+        \r
+        new Label(container, SWT.NONE).setText("&Target file:");\r
+        exportLocation = new CCombo(container, SWT.BORDER);\r
+        exportLocation.setText("");\r
+        GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(exportLocation);\r
+        exportLocation.addModifyListener(new ModifyListener() {\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                validatePage();\r
+            }\r
+        });\r
+        browseFileButton = new Button(container, SWT.PUSH);\r
+        browseFileButton.setText("Brows&e...");\r
+        browseFileButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));\r
+        browseFileButton.addSelectionListener(new SelectionAdapter() {\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);\r
+                dialog.setText("Choose Export Target File");\r
+                String loc = exportLocation.getText();\r
+                //if (exportModel.model != null)\r
+                 //   dialog.setFileName(exportModel.model.get().getName());\r
+                dialog.setFilterPath(loc);\r
+                dialog.setFilterExtensions(new String[] { "*" + ExportConstants.MODEL_FILE_EXTENSION });\r
+                dialog.setFilterNames(new String[] { "Sysdyn Model (*" + ExportConstants.MODEL_FILE_EXTENSION + ")" });\r
+                dialog.setOverwrite(false);\r
+                String file = dialog.open();\r
+                if (file == null)\r
+                    return;\r
+                exportLocation.setText(file);\r
+                validatePage();\r
+            }\r
+        });\r
+        \r
+        new Label(container, SWT.NONE).setText("Notes:");\r
+\r
+        description = new Text(container, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 150).grab(true, true).span(3, 1).applyTo(description);\r
+        description.addModifyListener(new ModifyListener() {\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                exportModel.setDescription(description.getText());\r
+            }\r
+        });\r
+        \r
+        Label horizRule = new Label(container, SWT.BORDER);\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 0).grab(true, false).span(3, 1).applyTo(horizRule);\r
+\r
+        overwrite = new Button(container, SWT.CHECK);\r
+        overwrite.setText("&Overwrite existing files without warning");\r
+        overwrite.setSelection(exportModel.getOverwrite());\r
+        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(overwrite);\r
+        overwrite.addSelectionListener(new SelectionAdapter() {\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                validatePage();\r
+            }\r
+        });\r
+        \r
+        dependencies = new Button(container, SWT.CHECK);\r
+        dependencies.setText("&Include Shared Libraries in exported file");\r
+        dependencies.setSelection(exportModel.getDependencies());\r
+        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(dependencies);\r
+        dependencies.addSelectionListener(new SelectionAdapter() {\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                validatePage();\r
+            }\r
+        });\r
+        \r
+        try {\r
+            initializeData();\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        setControl(container);\r
+        browseFileButton.setFocus();\r
+        validatePage();\r
+    }\r
+\r
+    private void initializeData() throws DatabaseException {\r
+        final Resource selection = ResourceAdaptionUtils.toSingleResource(exportModel.getSelection());\r
+\r
+        models = getModels();\r
+        Collections.sort(models);\r
+        int i = 0;\r
+        for (NamedResource namedResource : models) {\r
+            model.add(namedResource.getName());\r
+            if (selection != null && selection.equals(namedResource.getResource())) {\r
+                model.select(i);\r
+                exportModel.setModel(namedResource);\r
+            } else {\r
+                model.select(0);\r
+                for (NamedResource nr : models) {\r
+                    if (model.getItem(0).equals(nr.getName()))\r
+                        exportModel.setModel(nr);\r
+                }\r
+                \r
+            }\r
+            i++;\r
+        }\r
+    }\r
+\r
+    private List<NamedResource> getModels() throws DatabaseException {\r
+        return Simantics.getSession().sync(new UniqueRead<List<NamedResource>>() {\r
+\r
+            @Override\r
+            public List<NamedResource> perform(ReadGraph graph) throws DatabaseException {\r
+                Layer0 L0 = Layer0.getInstance(graph);\r
+                SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+                ArrayList<NamedResource> models = new ArrayList<NamedResource>();\r
+                Resource currentProject = Simantics.getProjectResource();\r
+                Collection<Resource> consistsOfs = graph.getObjects(currentProject, L0.ConsistsOf);\r
+                for (Resource resource : consistsOfs) {\r
+                    if (graph.isInstanceOf(resource, SYSDYN.SysdynModel)) {\r
+                        String modelName = graph.getRelatedValue2(resource, L0.HasName, Bindings.STRING);\r
+                        models.add(new NamedResource(modelName, resource));\r
+                    }\r
+                }\r
+                return models;\r
+            }\r
+        });\r
+    }\r
+\r
+    protected void validatePage() {\r
+        if (model.getItemCount() == 0){\r
+            setErrorMessage("There are no exportable Sysdyn models in your workspace.");\r
+            setPageComplete(false);\r
+            return;\r
+        }\r
+        String exportLoc = exportLocation.getText();\r
+        if (exportLoc.isEmpty()) {\r
+            setMessage("Select target file.");\r
+            setErrorMessage(null);\r
+            setPageComplete(false);\r
+            return;\r
+        }\r
+        if (!exportLoc.endsWith(ExportConstants.MODEL_FILE_EXTENSION)) {\r
+            setErrorMessage("Wrong file extension! Correct is " + ExportConstants.MODEL_FILE_EXTENSION);\r
+            setPageComplete(false);\r
+            return;\r
+        }\r
+        File file = new File(exportLoc);\r
+        if (file.isDirectory()) {\r
+            setErrorMessage("The target must be a file, an existing directory was given.");\r
+            setPageComplete(false);\r
+            return;\r
+        }\r
+        File parent = file.getParentFile();\r
+        if (parent == null || !parent.isDirectory()) {\r
+            setErrorMessage("The target directory does not exist.");\r
+            setPageComplete(false);\r
+            return;\r
+        }\r
+        \r
+        exportModel.setExportLocation(file);\r
+        exportModel.setOverwrite(overwrite.getSelection());\r
+        exportModel.setDependencies(dependencies.getSelection());\r
+        exportModel.setDescription(description.getText());\r
+        \r
+        setErrorMessage(null);\r
+        setMessage("Export selected model.");\r
+        setPageComplete(true);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelExportWizard.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelExportWizard.java
new file mode 100644 (file)
index 0000000..baaea7f
--- /dev/null
@@ -0,0 +1,123 @@
+package org.simantics.sysdyn.ui.wizards.model;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.util.Deque;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.preferences.InstanceScope;\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.jface.operation.IRunnableWithProgress;\r
+import org.eclipse.jface.preference.IPersistentPreferenceStore;\r
+import org.eclipse.jface.preference.IPreferenceStore;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.ui.IExportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.eclipse.ui.preferences.ScopedPreferenceStore;\r
+import org.simantics.modeling.ui.utils.NoProjectPage;\r
+import org.simantics.sysdyn.modelExport.SysdynModelExporter;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.wizards.Preferences;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class SysdynModelExportWizard extends Wizard implements IExportWizard {\r
+\r
+    private static final int MAX_RECENT_EXPORT_PATHS = 10;\r
+    \r
+    private SysdynExportModel   exportModel;\r
+    private Deque<String>       recentExportPaths;\r
+    private boolean             overwrite;\r
+    \r
+    public SysdynModelExportWizard() {\r
+        setWindowTitle("Export Sysdyn Model");\r
+        setNeedsProgressMonitor(true);\r
+    }\r
+\r
+    @Override\r
+    public void init(IWorkbench workbench, IStructuredSelection selection) {\r
+        readPreferences();\r
+        exportModel = new SysdynExportModel(selection.getFirstElement(), overwrite);\r
+    }\r
+    \r
+    @Override\r
+    public void addPages() {\r
+        super.addPages();\r
+        if (exportModel != null)\r
+            addPage(new SysdynModelExportPage(exportModel));\r
+        else\r
+            addPage(new NoProjectPage("Export Sysdyn Model"));\r
+    }\r
+\r
+    @Override\r
+    public boolean performFinish() {\r
+        try {\r
+            recentExportPaths.addFirst(exportModel.getExportLocation().getAbsolutePath());\r
+            Preferences.removeDuplicates(recentExportPaths);\r
+            if (recentExportPaths.size() > MAX_RECENT_EXPORT_PATHS)\r
+                recentExportPaths.pollLast();\r
+\r
+            writePreferences();\r
+        } catch (IOException e) {\r
+            ErrorLogger.defaultLogError("Failed to write preferences", e);\r
+        }\r
+\r
+        final File output = exportModel.getExportLocation();\r
+        if (output.exists()) {\r
+            if (!exportModel.getOverwrite()) {\r
+                boolean ok = MessageDialog.openConfirm(getShell(), "Overwrite", "A file by the name " + output.getAbsolutePath() + " already exists.\n\nDo you want to overwrite?");\r
+                if (!ok) {\r
+                    return false;\r
+                }\r
+            }\r
+            if (!output.delete()) {\r
+                MessageDialog.openError(getShell(), "Delete Problem", "Could not overwrite previously existing file " + output);\r
+                return false;\r
+            }\r
+        }\r
+        try {\r
+            getContainer().run(true, true, new IRunnableWithProgress() {\r
+                @Override\r
+                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {\r
+                    SysdynModelExporter.exportModel(monitor, exportModel.getModel().getResource(), exportModel.getExportLocation(), exportModel.getDescription(), exportModel.getDependencies());\r
+                }\r
+            });\r
+        } catch (InvocationTargetException e) {\r
+            Throwable t = e.getTargetException();\r
+            WizardPage cp = (WizardPage) getContainer().getCurrentPage();\r
+            if (t instanceof IOException) {\r
+                ErrorLogger.defaultLogError("An I/O problem occurred while exporting the model. See exception for details.", t);\r
+                cp.setErrorMessage("An I/O problem occurred while exporting the model.\nMessage: " + t.getMessage());\r
+            } else {\r
+                ErrorLogger.defaultLogError("Unexpected exception while exporting the model. See exception for details.", t);\r
+                cp.setErrorMessage("Unexpected exception while exporting the model. See error log for details.\nMessage: " + t.getMessage());\r
+            }\r
+            return false;\r
+        } catch (InterruptedException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+            return false;\r
+        }\r
+\r
+        return true;\r
+    }\r
+\r
+    private void readPreferences() {\r
+        \r
+        IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);\r
+        String recentPathsPref = store.getString(Preferences.RECENT_MODEL_EXPORT_LOCATIONS);\r
+        recentExportPaths = Preferences.decodePaths(recentPathsPref);\r
+        overwrite = store.getBoolean(Preferences.MODEL_EXPORT_OVERWRITE);\r
+    }\r
+    \r
+    private void writePreferences() throws IOException {\r
+        \r
+        IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);\r
+        store.putValue(Preferences.RECENT_MODEL_EXPORT_LOCATIONS, Preferences.encodePaths(recentExportPaths));\r
+        store.setValue(Preferences.MODEL_EXPORT_OVERWRITE, exportModel.getOverwrite());\r
+        if (store.needsSaving())\r
+            store.save();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelImportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelImportPage.java
new file mode 100644 (file)
index 0000000..3ab66cd
--- /dev/null
@@ -0,0 +1,219 @@
+package org.simantics.sysdyn.ui.wizards.model;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.concurrent.atomic.AtomicReference;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.CCombo;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.databoard.container.DataContainer;\r
+import org.simantics.databoard.container.DataContainers;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.modelExport.ExportConstants;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+\r
+public class SysdynModelImportPage extends WizardPage {\r
+\r
+    private SysdynImportModel       importModel;\r
+    private Text                    importTarget;\r
+    private CCombo                  importLocation;\r
+    private Label                   creation;\r
+    //private Label                   version;\r
+    private Text                    description;\r
+    private Text                    status;\r
+\r
+    protected SysdynModelImportPage(SysdynImportModel importModel) {\r
+        super("Import Sysdyn Model", "Define import location", null);\r
+        this.importModel = importModel;\r
+    }\r
+\r
+    @Override\r
+    public void createControl(Composite parent) {\r
+        Composite container = new Composite(parent, SWT.NONE);\r
+        GridLayoutFactory.swtDefaults().spacing(20, 10).numColumns(3).applyTo(container);\r
+\r
+//        draft = new Composite(container, SWT.NONE);\r
+//        draft.setBackground(draft.getDisplay().getSystemColor(SWT.COLOR_RED));\r
+//        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(draft);\r
+//        GridLayoutFactory.swtDefaults().numColumns(0).margins(0, 0).applyTo(draft);\r
+//        \r
+//        Composite draft2 = new Composite(draft, SWT.NONE);\r
+//        GridLayoutFactory.swtDefaults().applyTo(draft2);\r
+//        GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(draft2);\r
+//        new Label(draft2, SWT.NONE).setText("This model draft was exported with unpublished dependencies.");\r
+        \r
+        new Label(container, SWT.NONE).setText("Import target:");\r
+        importTarget = new Text(container, SWT.BORDER);\r
+        importTarget.setEditable(false);\r
+        importTarget.setText("");\r
+        importTarget.setToolTipText("Shows the target of the import.");\r
+        importTarget.setEnabled(false);\r
+        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(importTarget);\r
+\r
+        new Label(container, SWT.NONE).setText("&Model file:");\r
+        importLocation = new CCombo(container, SWT.BORDER);\r
+        importLocation.setText("");\r
+        GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(importLocation);\r
+        importLocation.addModifyListener(new ModifyListener(){\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+                validatePage();\r
+            }\r
+        });\r
+        Button browseFileButton = new Button(container, SWT.PUSH);\r
+        browseFileButton.setText("Br&owse...");\r
+        browseFileButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));\r
+        browseFileButton.addSelectionListener(new SelectionAdapter() {\r
+            @Override\r
+            public void widgetSelected(SelectionEvent e) {\r
+                FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);\r
+                dialog.setText("Choose Model to Import");\r
+                File lastFile = new File(importLocation.getText());\r
+                dialog.setFilterPath(lastFile.getParent());\r
+                dialog.setFilterExtensions(new String[] { "*.sysdyn" });\r
+                dialog.setFilterNames(new String[] { "Sysdyn Model (*.sysdyn)" });\r
+                String file = dialog.open();\r
+                if (file == null)\r
+                    return;\r
+                importLocation.setText(file);\r
+                //setDump(false, false);\r
+                validatePage();\r
+            }\r
+        });\r
+\r
+        Label horizRule = new Label(container, SWT.BORDER);\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 0).grab(true, false).span(3, 1).applyTo(horizRule);\r
+\r
+        creation = new Label(container, SWT.NONE);\r
+        creation.setText("");\r
+        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(creation);\r
+//        version = new Label(container, SWT.NONE);\r
+//        version.setText("");\r
+//        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(version);\r
+\r
+        Label notes = new Label(container, SWT.NONE);\r
+        notes.setText("Notes:");\r
+        GridDataFactory.fillDefaults().grab(false, false).span(3, 1).applyTo(notes);\r
+\r
+        description = new Text(container, SWT.MULTI | SWT.READ_ONLY | SWT.V_SCROLL | SWT.BORDER | SWT.FLAT);\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 150).grab(true, true).span(3, 1).applyTo(description);\r
+\r
+        status = new Text(container, SWT.MULTI | SWT.READ_ONLY);\r
+        status.setText("");\r
+        GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(status);\r
+\r
+        Label horizRule2 = new Label(container, SWT.BORDER);\r
+        GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 0).grab(true, false).span(3, 1).applyTo(horizRule2);\r
+        \r
+        try {\r
+            initializeData();\r
+        } catch (DatabaseException e) {\r
+            ErrorLogger.defaultLogError(e);\r
+        }\r
+        \r
+        setControl(container);\r
+        validatePage();\r
+    }\r
+\r
+    private void initializeData() throws DatabaseException {\r
+        final AtomicReference<String> projectName = new AtomicReference<String>();\r
+\r
+        Simantics.getSession().syncRequest(new ReadRequest() {\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                projectName.set( NameUtils.getSafeName(graph, Simantics.getProjectResource()) );\r
+            }\r
+        });\r
+\r
+        importTarget.setText(projectName.get());\r
+\r
+        for (String path : importModel.getRecentLocations()) {\r
+            importLocation.add(path);\r
+        }\r
+        if (importLocation.getItemCount() > 0)\r
+            importLocation.select(0);\r
+        \r
+    }\r
+\r
+    protected void validatePage() {\r
+        String importLoc = importLocation.getText();\r
+        if (importLoc.isEmpty()) {\r
+            setMessage("Select file to import.");\r
+            setErrorMessage(null);\r
+            setPageComplete(false);\r
+            return;\r
+        }\r
+        File file = new File(importLoc);\r
+        if (!file.exists() || !file.isFile()) {\r
+            setErrorMessage("Selected file is invalid.");\r
+            setPageComplete(false);\r
+            return;\r
+        }\r
+        \r
+        try {\r
+            importModel.setImportLocation(file);\r
+            \r
+            DataContainer container = DataContainers.readHeader(file);\r
+            \r
+            Variant dateVariant = container.metadata.get("date");\r
+            String dateText = dateVariant != null ? dateVariant.getValue().toString() : "Unknown date";\r
+            \r
+            Variant authorVariant = container.metadata.get("author");\r
+            String authorText = authorVariant != null ? authorVariant.getValue().toString() : "Unknown author";\r
+            \r
+            Variant descriptionVariant = container.metadata.get("description");\r
+            String descriptionText = descriptionVariant != null ? descriptionVariant.getValue().toString() : "";\r
+            \r
+            String creationText = "Created by " + authorText + " on " + dateText; \r
+            \r
+            creation.setText(creationText);\r
+            description.setText(descriptionText);\r
+            \r
+            \r
+            String statusText = "This model can be imported.";\r
+            if (container.version == ExportConstants.CURRENT_MODEL_EXPORT_VERSION) {\r
+//            } else if(container.version >= ExportConstants.SMALLEST_MIGRATED_MODEL_EXPORT_VERSION) {\r
+//                statusText = "This model can be migrated.";\r
+            } else {\r
+                status.setText("This model cannot be imported.");\r
+                setErrorMessage("This model cannot be imported");\r
+                setPageComplete(false);\r
+                return;\r
+            }\r
+            status.setText(statusText);\r
+            creation.getParent().layout();\r
+            \r
+        } catch (IOException e) {\r
+            e.printStackTrace();\r
+            creation.setText("");\r
+//            version.setText("");\r
+            description.setText("");\r
+            status.setText("This model cannot be imported.");\r
+            setErrorMessage("Could not read header information from " + file.getAbsolutePath());\r
+            setPageComplete(false);\r
+            return;\r
+        }\r
+        setErrorMessage(null);\r
+        setMessage("Import " + file.getName() + "");\r
+        setPageComplete(true);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelImportWizard.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/model/SysdynModelImportWizard.java
new file mode 100644 (file)
index 0000000..fad9cf9
--- /dev/null
@@ -0,0 +1,130 @@
+package org.simantics.sysdyn.ui.wizards.model;\r
+\r
+import java.io.IOException;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.util.Deque;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.OperationCanceledException;\r
+import org.eclipse.core.runtime.preferences.InstanceScope;\r
+import org.eclipse.jface.operation.IRunnableWithProgress;\r
+import org.eclipse.jface.preference.IPersistentPreferenceStore;\r
+import org.eclipse.jface.preference.IPreferenceStore;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.ui.IImportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.eclipse.ui.preferences.ScopedPreferenceStore;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.graph.db.MissingDependencyException;\r
+import org.simantics.modeling.ui.utils.NoProjectPage;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.sysdyn.ui.wizards.Preferences;\r
+import org.simantics.utils.ui.ErrorLogger;\r
+import org.simantics.utils.ui.ExceptionUtils;\r
+\r
+public class SysdynModelImportWizard extends Wizard implements IImportWizard {\r
+\r
+    private static final int MAX_RECENT_IMPORT_PATHS = 10;\r
+    \r
+    private SysdynImportModel importModel;\r
+\r
+    public SysdynModelImportWizard() {\r
+        setWindowTitle("Import Sysdyn Model");\r
+        setNeedsProgressMonitor(true);\r
+    }\r
+    \r
+    @Override\r
+    public void init(IWorkbench workbench, IStructuredSelection selection) {\r
+        readPreferences(selection);\r
+        \r
+\r
+    }\r
+    \r
+    @Override\r
+    public void addPages() {\r
+        super.addPages();\r
+        if (importModel != null)\r
+            addPage(new SysdynModelImportPage(importModel));\r
+        else\r
+            addPage(new NoProjectPage("Import Sysdyn Model"));\r
+    }\r
+\r
+    @Override\r
+    public boolean performFinish() {\r
+        try {\r
+            importModel.getRecentLocations().addFirst(importModel.getImportLocation().getAbsolutePath());\r
+            Preferences.removeDuplicates(importModel.getRecentLocations());\r
+            if (importModel.getRecentLocations().size() > MAX_RECENT_IMPORT_PATHS)\r
+                importModel.getRecentLocations().pollLast();\r
+\r
+            writePreferences();\r
+        } catch (IOException e) {\r
+            ErrorLogger.defaultLogError("Failed to write preferences", e);\r
+        }\r
+        \r
+        try {\r
+            getContainer().run(true, true, new IRunnableWithProgress() {\r
+                @Override\r
+                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {\r
+                    try {\r
+                        ImportUtilsUI.importModelFile(importModel.getImportLocation().getAbsolutePath(), monitor);\r
+                        //SysdynModelImporter.importModel(monitor, importModel.getImportLocation());\r
+                    } catch (Exception e) {\r
+                        throw new InvocationTargetException(e);\r
+                    } finally {\r
+                        monitor.done();\r
+                    }\r
+                }\r
+            });\r
+        } catch (InvocationTargetException e) {\r
+            Throwable t = e.getTargetException();\r
+            if (t instanceof OperationCanceledException)\r
+                return false;\r
+\r
+            WizardPage cp = (WizardPage) getContainer().getCurrentPage();\r
+            ErrorLogger.defaultLogError(t);\r
+            if (t instanceof IOException) {\r
+                cp.setErrorMessage("An I/O problem occurred while importing Sysdyn model.\n\nMessage: " + e.getMessage());\r
+            } else if (t instanceof MissingDependencyException) {\r
+                cp.setErrorMessage("The import target project is missing required dependencies from database.");\r
+                ExceptionUtils.logAndShowError(t.getMessage(), t);\r
+            } else {\r
+                cp.setErrorMessage("An unknown problem occurred while importing Sysdyn model.\n\nMessage: " + e.getMessage());\r
+            }\r
+            return false;\r
+        } catch (InterruptedException e) {\r
+            ExceptionUtils.logAndShowError(e);\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
+    \r
+    private void readPreferences(IStructuredSelection selection) {\r
+        IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);\r
+\r
+        String recentPathsPref = store.getString(Preferences.RECENT_MODEL_IMPORT_LOCATIONS);\r
+        Deque<String> recentImportPaths = Preferences.decodePaths(recentPathsPref);\r
+\r
+        ISessionContext ctx = Simantics.getSessionContext();\r
+        if (ctx == null)\r
+            return;\r
+//        IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);\r
+//        if (project == null)\r
+//            return;\r
+//        \r
+        importModel = new SysdynImportModel(recentImportPaths);\r
+        //importModel.project = project;\r
+        importModel.setSelection(selection.getFirstElement());\r
+    }\r
+\r
+    private void writePreferences() throws IOException {\r
+        IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);\r
+        store.putValue(Preferences.RECENT_MODEL_IMPORT_LOCATIONS, Preferences.encodePaths(importModel.getRecentLocations()));\r
+        if (store.needsSaving())\r
+            store.save();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/ExportWizardModel.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/ExportWizardModel.java
new file mode 100644 (file)
index 0000000..5288762
--- /dev/null
@@ -0,0 +1,53 @@
+package org.simantics.sysdyn.ui.wizards.models;\r
+\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.ui.IImportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.simantics.db.Resource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+@Deprecated\r
+public class ExportWizardModel extends Wizard implements IImportWizard {\r
+       \r
+       private WizardModelsExportPage mainPage;\r
+       private IStructuredSelection currentSelection = null;\r
+       private String initialPath = null;\r
+       public Resource selection;\r
+\r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ExportWizardModel() {\r
+       this(null);\r
+    }\r
+    \r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ExportWizardModel(String initialPath)\r
+    {\r
+        super();\r
+        this.initialPath = initialPath;\r
+    }\r
\r
+    public void init(IWorkbench workbench, IStructuredSelection currentSelection) {\r
+        setWindowTitle("Export");\r
+        this.currentSelection = currentSelection;\r
+        selection = (Resource)AdaptionUtils.adaptToSingle(currentSelection, org.simantics.db.Resource.class);\r
+    }\r
+    \r
+    public void addPages() {\r
+        super.addPages();\r
+               mainPage = new WizardModelsExportPage(\r
+                               "wizardModelsExportPage", initialPath, currentSelection); //$NON-NLS-1$\r
+        addPage(mainPage);\r
+    }\r
+\r
+       @Override\r
+       public boolean performFinish() {\r
+               return mainPage.createProjects();\r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/ImportWizardModel.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/ImportWizardModel.java
new file mode 100644 (file)
index 0000000..c1a8726
--- /dev/null
@@ -0,0 +1,48 @@
+package org.simantics.sysdyn.ui.wizards.models;\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.ui.IImportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+\r
+@Deprecated\r
+public class ImportWizardModel extends Wizard implements IImportWizard {\r
+       \r
+       private WizardModelsImportPage mainPage;\r
+       private IStructuredSelection currentSelection = null;\r
+       private String initialPath = null;\r
+       \r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ImportWizardModel() {\r
+       this(null);\r
+    }\r
+    \r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ImportWizardModel(String initialPath)\r
+    {\r
+        super();\r
+        this.initialPath = initialPath;      \r
+    }\r
+\r
+    public void addPages() {\r
+        super.addPages();\r
+               mainPage = new WizardModelsImportPage(\r
+                               "wizardModelsImportPage", initialPath, currentSelection); //$NON-NLS-1$\r
+        addPage(mainPage);\r
+    }\r
+    \r
+    public void init(IWorkbench workbench, IStructuredSelection currentSelection) {\r
+        setWindowTitle("Import");\r
+        this.currentSelection = currentSelection;\r
+    }\r
+\r
+       @Override\r
+       public boolean performFinish() {\r
+               return mainPage.createProjects();\r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java
new file mode 100644 (file)
index 0000000..ae1f0e8
--- /dev/null
@@ -0,0 +1,320 @@
+package org.simantics.sysdyn.ui.wizards.models;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+\r
+import org.eclipse.core.runtime.Path;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.PixelConverter;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.Files;\r
+import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.TransferableGraphRequest2;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.graph.representation.TransferableGraph1;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class WizardModelsExportPage extends WizardPage {\r
+       \r
+       // dialog store id constants\r
+       private Text filePathField;\r
+       \r
+       // Keep track of the archive that we browsed to last time\r
+       // the wizard was invoked.\r
+\r
+       private static String previouslyBrowsedFile = "";\r
+\r
+       private Button browseDirectoriesButton;\r
+       \r
+       //private IStructuredSelection currentSelection;\r
+       \r
+       private Resource selectedModel;\r
+       \r
+       GraphExplorerComposite modelExplorer;\r
+       \r
+       private boolean selectionMade = false;\r
+       \r
+       \r
+       \r
+       /**\r
+        * Creates a new project creation wizard page.\r
+        * \r
+        */\r
+       public WizardModelsExportPage() {\r
+               this("wizardModelsExportPage", null, null); //$NON-NLS-1$\r
+       }\r
+\r
+       /**\r
+        * Create a new instance of the receiver.\r
+        * \r
+        * @param pageName\r
+        */\r
+       public WizardModelsExportPage(String pageName) {\r
+               this(pageName,null, null);\r
+       }\r
+                       \r
+       /**\r
+        * More (many more) parameters.\r
+        * \r
+        * @param pageName\r
+        * @param initialPath\r
+        * @param currentSelection\r
+        * @since 3.5\r
+        */\r
+       public WizardModelsExportPage(String pageName,String initialPath,\r
+                       IStructuredSelection currentSelection) {\r
+               super(pageName);\r
+               //this.currentSelection = currentSelection;\r
+               setPageComplete(false);\r
+               setTitle("Export Model");\r
+               setDescription("Choose the Model and the export location, then press Finish.");\r
+       }\r
+       \r
+       public void createControl(Composite parent) {\r
+               \r
+               initializeDialogUnits(parent);\r
+\r
+               Composite workArea = new Composite(parent, SWT.NONE);\r
+               setControl(workArea);\r
+\r
+               workArea.setLayout(new GridLayout());\r
+               workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
+                               | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
+               \r
+               createProjectsRoot(workArea);\r
+               createTree (workArea);\r
+       }\r
+       \r
+       private void createProjectsRoot(Composite workArea) {\r
+               \r
+               // set label for field\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select the export location for Model:");\r
+               \r
+               Composite projectGroup = new Composite(workArea, SWT.NONE);\r
+               GridLayout layout = new GridLayout();\r
+               layout.numColumns = 2;\r
+               layout.makeColumnsEqualWidth = false;\r
+               layout.marginWidth = 0;\r
+\r
+               projectGroup.setLayout(layout);\r
+               projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
+               \r
+               // model location entry field\r
+               this.filePathField = new Text(projectGroup, SWT.BORDER);\r
+\r
+               GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
+               directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
+               filePathField.setLayoutData(directoryPathData);\r
+               \r
+               filePathField.addModifyListener(new ModifyListener(){\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+               previouslyBrowsedFile = filePathField.getText();        \r
+            }\r
+               });\r
+               if (previouslyBrowsedFile != null){\r
+                       filePathField.setText(previouslyBrowsedFile);\r
+                       validatePage();\r
+               }\r
+\r
+               // browse button\r
+               browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
+               browseDirectoriesButton.setText("Browse");\r
+               setButtonLayoutData(browseDirectoriesButton);\r
+               \r
+               browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
+                       /*\r
+                        * (non-Javadoc)\r
+                        * \r
+                        * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
+                        * elected(org.eclipse.swt.events.SelectionEvent)\r
+                        */\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               handleLocationDirectoryButtonPressed();\r
+                       }\r
+               });\r
+               \r
+       }\r
+       \r
+       private void createTree(Composite workArea){\r
+               \r
+               //set label for tree\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select Model to export:");\r
+\r
+               try {\r
+                       Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph)\r
+                                               throws DatabaseException {\r
+                                       Resource model = SimanticsUI.getProject().get();\r
+                                       return model;\r
+                               }\r
+\r
+                       });\r
+\r
+                       modelExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                                       "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
+\r
+                       modelExplorer\r
+                       .setBrowseContexts(SysdynResource.URIs.ImportModuleTree);\r
+\r
+                       modelExplorer.finish();\r
+\r
+                       modelExplorer.setInput(null, input);\r
+\r
+                       GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                                       modelExplorer);\r
+                       \r
+                       ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
+                               \r
+                               @Override\r
+                               public void widgetSelected(SelectionEvent e) {\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                               @Override\r
+                               public void widgetDefaultSelected(SelectionEvent e) {\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                       });\r
+                       \r
+\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+       }\r
+       \r
+       //Set filePathField active\r
+       public void setVisible(boolean visible) {\r
+               super.setVisible(visible);\r
+               this.filePathField.setFocus();\r
+       }\r
+       \r
+       //Open dialog for choosing the file\r
+       protected void handleLocationDirectoryButtonPressed() {\r
+               final Shell shell = filePathField.getShell();\r
+               \r
+               FileDialog dialog = new FileDialog(shell, SWT.SAVE);\r
+               \r
+               String[] ext = {"*.sysdyn"};\r
+               dialog.setFilterExtensions(ext);\r
+               \r
+               dialog.setText("Export Model");\r
+\r
+               String dirName = filePathField.getText().trim();\r
+               \r
+               File path = new File(dirName);\r
+               if (path.exists()) {\r
+                       dialog.setFilterPath(new Path(dirName).toOSString());   \r
+               }\r
+               \r
+               String selectedFile = dialog.open();\r
+               if (selectedFile != null) {\r
+                       filePathField.setText(selectedFile);\r
+                       validatePage();\r
+               }               \r
+\r
+       }\r
+       //Get selection from the tree\r
+       @SuppressWarnings("unchecked")\r
+       public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
+                       Class<T> clazz) {\r
+               \r
+               if(explorer == null)\r
+                       return null;\r
+               ISelection selection = ((ISelectionProvider) explorer\r
+                               .getAdapter(ISelectionProvider.class)).getSelection();\r
+               if (selection == null)\r
+                       return null;\r
+               IStructuredSelection iss = (IStructuredSelection) selection;\r
+               AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
+               if (inc == null)\r
+                       return null;\r
+               final T resource = (T) inc.getAdapter(clazz);\r
+\r
+               return resource;\r
+       }\r
+       \r
+       public boolean createProjects() {\r
+               \r
+               final String selected = previouslyBrowsedFile;\r
+               if(selected == null) return false;\r
+               \r
+               selectedModel= getExplorerResource(modelExplorer, Resource.class);\r
+               if(selectedModel == null)\r
+                       return false;\r
+        \r
+        // FIXME: Model browser doesn't change its selection even if the selected object is removed,\r
+        // so you can try to export a removed model \r
+               \r
+               SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               String name = graph.syncRequest(new PossibleRelatedValue<String>(selectedModel, l0.HasName, Bindings.STRING ));\r
+                               ArrayList<Pair<Resource, String>> roots = new ArrayList<Pair<Resource, String>>();\r
+                               roots.add(Pair.make(selectedModel, name));\r
+                               TransferableGraph1 tg = graph.syncRequest(new TransferableGraphRequest2(roots, selectedModel));\r
+\r
+                               try {\r
+                                       Files.createFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class), tg);\r
+                               } catch (RuntimeBindingConstructionException e) {\r
+                                       e.printStackTrace();\r
+                               } catch (IOException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+                               \r
+                       }\r
+               });\r
+\r
+               return true;\r
+       }\r
+       \r
+       void validatePage() {\r
+               \r
+               if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
+                       setPageComplete(false);\r
+                       return;\r
+               }\r
+               \r
+               setPageComplete(true);\r
+               \r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsImportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsImportPage.java
new file mode 100644 (file)
index 0000000..a4c69b9
--- /dev/null
@@ -0,0 +1,456 @@
+package org.simantics.sysdyn.ui.wizards.models;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.jface.layout.PixelConverter;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class WizardModelsImportPage extends WizardPage{\r
+       \r
+       private Text filePathField;\r
+       \r
+       // Keep track of the archive that we browsed to last time\r
+       // the wizard was invoked.\r
+       private static String previouslyBrowsedFile = "";\r
+\r
+       private Button browseDirectoriesButton;\r
+\r
+       private Shell shell;\r
+       \r
+       /**\r
+        * Creates a new project creation wizard page.\r
+        * \r
+        */\r
+       public WizardModelsImportPage() {\r
+               this("wizardModelsImportPage", null, null); //$NON-NLS-1$\r
+       }\r
+\r
+       /**\r
+        * Create a new instance of the receiver.\r
+        * \r
+        * @param pageName\r
+        */\r
+       public WizardModelsImportPage(String pageName) {\r
+               this(pageName,null, null);\r
+       }\r
+                       \r
+       /**\r
+        * More (many more) parameters.\r
+        * \r
+        * @param pageName\r
+        * @param initialPath\r
+        * @param currentSelection\r
+        * @since 3.5\r
+        */\r
+       public WizardModelsImportPage(String pageName,String initialPath,\r
+                       IStructuredSelection currentSelection) {\r
+               super(pageName);\r
+               //this.initialPath = initialPath;\r
+               //this.currentSelection = currentSelection;\r
+               setPageComplete(false);\r
+               setTitle("Import Model");\r
+               setDescription("Choose the Model file, then press Finish.");\r
+       }\r
+\r
+       \r
+       public void createControl(Composite parent) {\r
+\r
+               initializeDialogUnits(parent);\r
+\r
+               Composite workArea = new Composite(parent, SWT.NONE);\r
+               setControl(workArea);\r
+\r
+               workArea.setLayout(new GridLayout());\r
+               workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
+                               | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
+\r
+               createProjectsRoot(workArea);\r
+       }\r
+       \r
+       private void createProjectsRoot(Composite workArea) {\r
+\r
+               // set label for field\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select Model source:");\r
+               \r
+               Composite projectGroup = new Composite(workArea, SWT.NONE);\r
+               GridLayout layout = new GridLayout();\r
+               layout.numColumns = 2;\r
+               layout.makeColumnsEqualWidth = false;\r
+               layout.marginWidth = 0;\r
+\r
+               projectGroup.setLayout(layout);\r
+               projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
+\r
+               // model location entry field\r
+               this.filePathField = new Text(projectGroup, SWT.BORDER);\r
+               \r
+               GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
+               directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
+               filePathField.setLayoutData(directoryPathData);\r
+               filePathField.addModifyListener(new ModifyListener(){\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+               previouslyBrowsedFile = filePathField.getText();\r
+            }\r
+               });\r
+               if (previouslyBrowsedFile != null){\r
+                       filePathField.setText(previouslyBrowsedFile);\r
+                       validatePage();\r
+               }\r
+               \r
+               // browse button\r
+               browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
+               browseDirectoriesButton.setText("Browse");\r
+               setButtonLayoutData(browseDirectoriesButton);\r
+                       \r
+               browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
+                       /*\r
+                        * (non-Javadoc)\r
+                        * \r
+                        * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
+                        * elected(org.eclipse.swt.events.SelectionEvent)\r
+                        */\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               setErrorMessage(null);\r
+                               handleLocationDirectoryButtonPressed();\r
+                       }\r
+               });     \r
+       }\r
+\r
+       \r
+       //Set filePathField active\r
+       public void setVisible(boolean visible) {\r
+               super.setVisible(visible);\r
+               this.filePathField.setFocus();\r
+       }\r
+       \r
+       \r
+       //Open dialog for choosing the file\r
+       protected void handleLocationDirectoryButtonPressed() {\r
+               \r
+               shell = filePathField.getShell();\r
+               \r
+               FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
+               \r
+               String[] ext = {"*.sysdyn; *.tg", "*.*"};\r
+               dialog.setFilterExtensions(ext);\r
+               \r
+               dialog.setText("Import Model");\r
+\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);\r
+               if(path.isEmpty() || !(new File(path).exists()))\r
+                       path = Platform.getLocation().toOSString();\r
+               dialog.setFilterPath(path);\r
+               \r
+               String selectedFile = dialog.open();\r
+               if (selectedFile != null) {\r
+                       filePathField.setText(selectedFile);\r
+                       validatePage();\r
+               }\r
+               \r
+       }\r
+\r
+       //Create project after finish is pressed.\r
+       public boolean createProjects() {\r
+               \r
+               Resource project = SimanticsUI.getProject().get();\r
+               if(project == null){\r
+                       setErrorMessage("Error when retrieving resource");\r
+                       return false;\r
+               }\r
+               \r
+               final String selected = previouslyBrowsedFile;\r
+               if(selected == null){\r
+                       setErrorMessage("No file selected");\r
+                       return false;\r
+               }\r
+\r
+               try {\r
+                       IStatus status = ImportUtilsUI.importModelFile(selected, null);\r
+                       if(status == null || !status.equals(Status.OK_STATUS)) {\r
+                           setErrorMessage(status.getMessage());\r
+                           return false;\r
+                       }\r
+                       return true;\r
+               } catch (Exception e) {\r
+                       e.printStackTrace();\r
+                       return false;\r
+               }\r
+               \r
+        /*\r
+               TransferableGraph1 tg = null;\r
+               try {\r
+                       tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
+               } catch (RuntimeBindingConstructionException e) {\r
+                       e.printStackTrace();\r
+               } catch (IOException e) {       \r
+                       try {\r
+                               OldTransferableGraph1 otg = (OldTransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(OldTransferableGraph1.class));\r
+                               tg = new TransferableGraph1(otg.resourceCount, otg.identities, otg.statements, otg.values);\r
+                       } catch (RuntimeBindingConstructionException e1) {\r
+                               e1.printStackTrace();\r
+                       } catch (IOException e1) {\r
+                               setErrorMessage("The imported file is not of type: System Dynamics Model");\r
+                               return false;\r
+                       }\r
+               }\r
+               if(tg == null){ \r
+                       setErrorMessage("The imported file is not of type: System Dynamics Model");\r
+                       return false;\r
+               }\r
+               \r
+               try {\r
+                       \r
+                       DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(project);\r
+                       DefaultPasteHandler.defaultExecute(tg, SimanticsUI.getProject().get(), ia);\r
+                       \r
+                       // Check that imported resource was actually a model \r
+                       //and fix changes made to old ontology versions\r
+                       final Resource root = ia.getRoot();\r
+                       SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                               \r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       \r
+                                       if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModel)) {\r
+                                               Resource instanceOf = graph.getPossibleObject(root, Layer0.getInstance(graph).InstanceOf);\r
+                                               String type = "...";\r
+                                               if(instanceOf != null)\r
+                                                       type = NameUtils.getSafeName(graph, instanceOf);\r
+                                               else {\r
+                                                       Resource inheritedFrom = graph.getPossibleObject(root, Layer0.getInstance(graph).Inherits);\r
+                                                       if(inheritedFrom != null)\r
+                                                               type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                                               }\r
+                                               graph.deny(root, Layer0.getInstance(graph).PartOf);\r
+                                               error = type;\r
+                                       } else {\r
+                                               updateOldConfigurationToBaseRealization(graph, root);\r
+                                               addDefaultOntologyLinks(graph, root);\r
+                                               addURIsToDiagrams(graph, root);\r
+                                               addSpreadSheetBook(graph, root);\r
+                                       }\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               } catch (Exception e) {\r
+                       e.printStackTrace();\r
+               }\r
+    \r
+               if (!error.isEmpty()){\r
+                       setErrorMessage("The imported file is not of type: System Dynamics Model (" + error +")");\r
+                       error = "";\r
+                       return false;\r
+               }\r
+               */\r
+//             if(status == null || !status.equals(Status.OK_STATUS)) {\r
+//                 setErrorMessage(status.getMessage());\r
+//                 return false;\r
+//             }\r
+//             return true;            \r
+       }\r
+       \r
+       /**\r
+        * In old versions base realization was separate. Newer versions use configuration as base realization. \r
+        * @param graph WriteGraph\r
+        * @param model Imported model\r
+        */\r
+       /*\r
+       private static void updateOldConfigurationToBaseRealization(WriteGraph graph, Resource model) {\r
+               Layer0X L0X = Layer0X.getInstance(graph);\r
+               try {\r
+                       Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+                       if(configuration != null && !graph.hasStatement(configuration, L0X.IsBaseRealizationOf, model))\r
+                               graph.claim(configuration, L0X.IsBaseRealizationOf, model);\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+       }\r
+       */\r
+       \r
+       /**\r
+        * Links should be exported and imported automatically. If it has failed, the \r
+        * default ontology links sysdyn and layer0 are added.\r
+        * \r
+        * @param graph WriteGraph\r
+        * @param model Imported model\r
+        */\r
+        /*\r
+       private static void addDefaultOntologyLinks(WriteGraph graph, Resource model) {\r
+               try {\r
+                       Layer0 l0 = Layer0.getInstance(graph);\r
+                       // The links should be exported and imported automatically\r
+                       Resource sysdyn = graph.getResource("http://www.simantics.org/Sysdyn-1.1");\r
+                       Resource layer0 = graph.getResource("http://www.simantics.org/Layer0-1.1");\r
+                       if(!graph.hasStatement(model, l0.IsLinkedTo, sysdyn))\r
+                               graph.claim(model, l0.IsLinkedTo, sysdyn);\r
+                       if(!graph.hasStatement(model, l0.IsLinkedTo, layer0))\r
+                               graph.claim(model, l0.IsLinkedTo, layer0);\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+               \r
+       private static void addURIsToDiagrams(WriteGraph graph, Resource model) {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SimulationResource simu = SimulationResource.getInstance(graph);\r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+               try {\r
+                       HashSet<Resource> configurations = new HashSet<Resource>();\r
+               \r
+                       Resource configuration = graph.getPossibleObject(model, simu.HasConfiguration);\r
+                       if(configuration != null) \r
+                               configurations.add(configuration);\r
+                       \r
+                       for(Resource r : graph.getObjects(model, l0.ConsistsOf)) {\r
+                               if(graph.isInheritedFrom(r, sr.Module)) {\r
+                                       Resource moduleConfiguration = graph.getPossibleObject(r, sr2.IsDefinedBy);\r
+                                       if(moduleConfiguration != null)\r
+                                               configurations.add(moduleConfiguration);\r
+                               }\r
+                       }\r
+                       \r
+                       for(Resource conf : configurations) {\r
+                               Resource configurationDiagram = graph.getPossibleObject(conf, mr.CompositeToDiagram);\r
+                               if(configurationDiagram != null && !graph.hasStatement(configurationDiagram, l0.PartOf)) {\r
+                                       GraphUtils.create2(graph, l0.Library, \r
+                                                       l0.HasName, "__CONTAINER__",\r
+                                                       l0.PartOf, conf,\r
+                                                       l0.ConsistsOf, configurationDiagram);\r
+                               }\r
+                       }\r
+                       \r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+*/     \r
+       \r
+       /**\r
+        * Add a missing spreadsheet book to the model\r
+        * \r
+        * @param graph\r
+        * @param model\r
+        */\r
+       /*\r
+       private static void addSpreadSheetBook(WriteGraph graph, Resource model) {\r
+           try {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SpreadsheetResource ssr = SpreadsheetResource.getInstance(graph);\r
+               SimulationResource simu = SimulationResource.getInstance(graph);\r
+               Resource conf = graph.getPossibleObject(model, simu.HasConfiguration);\r
+               if(conf != null && graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, ssr.Book)).isEmpty()) {\r
+                   Resource book = graph.newResource();\r
+                   graph.claim(book, l0.InstanceOf, null, ssr.Book);\r
+                   graph.addLiteral(book, l0.HasName, l0.NameOf, l0.String, "Book" + UUID.randomUUID().toString(), Bindings.STRING);\r
+                   graph.claim(conf, l0.ConsistsOf, l0.PartOf, book);\r
+\r
+                   createSheet(graph, book, "Sheet1", new String[] { }, new int[] { 50 });\r
+               }\r
+           } catch (DatabaseException e) {\r
+               e.printStackTrace();\r
+           }\r
+       }\r
+       */\r
+       /**\r
+        * Create a sheet (Copied from SysdynProject)\r
+        * \r
+        * @param graph\r
+        * @param book\r
+        * @param name\r
+        * @param colNames\r
+        * @param colWidths\r
+        * @return\r
+        * @throws DatabaseException\r
+        */\r
+       /*\r
+    private static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException {\r
+\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Layer0X L0X = Layer0X.getInstance(graph);\r
+        SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);\r
+\r
+        Resource result = graph.newResource();\r
+        graph.claim(result, L0.InstanceOf, null, sr.Spreadsheet);\r
+\r
+        if(name == null) {\r
+            name = NameUtils.findFreshEscapedName(graph, "Sheet", book, sr.HasSheet);\r
+        }\r
+        graph.claimLiteral(result, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);\r
+        graph.claim(book, L0.ConsistsOf, L0.PartOf, result);\r
+\r
+        {\r
+            Resource newCell = graph.newResource();\r
+            graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
+            graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Dimensions", Bindings.STRING);\r
+            graph.addLiteral(newCell, sr.Dimensions_fitColumns, sr.Dimensions_fitColumns_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
+            graph.addLiteral(newCell, sr.Dimensions_fitRows, sr.Dimensions_fitRows_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
+            graph.addLiteral(newCell, sr.Dimensions_columnCount, sr.Dimensions_columnCount_Inverse, L0.Integer, 128, Bindings.INTEGER);\r
+            graph.addLiteral(newCell, sr.Dimensions_rowCount, sr.Dimensions_rowCount_Inverse, L0.Integer, 256, Bindings.INTEGER);\r
+            graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
+        }\r
+\r
+        {\r
+            Resource newCell = graph.newResource();\r
+            graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
+            graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Headers", Bindings.STRING);\r
+            graph.addLiteral(newCell, sr.Headers_columnLabels, sr.Headers_columnLabels_Inverse, L0.StringArray, colNames, Bindings.STRING_ARRAY);\r
+            graph.addLiteral(newCell, sr.Headers_columnWidths, sr.Headers_columnWidths_Inverse, L0.IntegerArray, colWidths, Bindings.INT_ARRAY);\r
+            graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
+        }\r
+\r
+        {\r
+            \r
+            double[] doubles = new double[10*2];\r
+            for(int i=0;i<10*2;i++) doubles[i] = i;\r
+            \r
+            Resource newCell = graph.newResource();\r
+            graph.claim(newCell, L0.InstanceOf, null, sr.DoubleArrayCell);\r
+            graph.addLiteral(newCell, sr.DoubleArrayCell_HasWidth, sr.DoubleArrayCell_HasWidth_Inverse, L0.Integer, 10, Bindings.INTEGER);\r
+            graph.addLiteral(newCell, sr.HasLocation, sr.HasLocation_Inverse, L0.String, "B2", Bindings.STRING);\r
+            graph.addLiteral(newCell, sr.DoubleArrayCell_HasDoubleArray, sr.DoubleArrayCell_HasDoubleArray_Inverse, L0.DoubleArray, doubles, Bindings.DOUBLE_ARRAY);\r
+            graph.claim(result, L0X.HasChildVariables, L0X.HasChildVariables_Inverse, newCell);\r
+            \r
+        }\r
+        \r
+        return result;\r
+\r
+    }\r
+    */\r
+    void validatePage(){\r
+       \r
+               if (previouslyBrowsedFile.isEmpty()){\r
+                       setPageComplete(false);\r
+                       return;\r
+               }\r
+               setErrorMessage(null);\r
+               setPageComplete(true);\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ExportWizardModule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ExportWizardModule.java
new file mode 100644 (file)
index 0000000..a808443
--- /dev/null
@@ -0,0 +1,54 @@
+package org.simantics.sysdyn.ui.wizards.modules;\r
+\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.ui.IImportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.simantics.db.Resource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+\r
+public class ExportWizardModule extends Wizard implements IImportWizard {\r
+       \r
+       private WizardModulesExportPage mainPage;\r
+       private IStructuredSelection currentSelection = null;\r
+       private String initialPath = null;\r
+       public Resource selection;\r
+\r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ExportWizardModule() {\r
+       this(null);\r
+    }\r
+    \r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ExportWizardModule(String initialPath)\r
+    {\r
+        super();\r
+        this.initialPath = initialPath;\r
+    }\r
\r
+    public void init(IWorkbench workbench, IStructuredSelection currentSelection) {\r
+        setWindowTitle("Export");\r
+        this.currentSelection = currentSelection;\r
+        selection = (Resource)AdaptionUtils.adaptToSingle(currentSelection, org.simantics.db.Resource.class);\r
+    }\r
+    \r
+    public void addPages() {\r
+        super.addPages();\r
+               mainPage = new WizardModulesExportPage(\r
+                               "wizardModulesExportPage", initialPath, currentSelection); //$NON-NLS-1$\r
+        addPage(mainPage);\r
+    }\r
+\r
+       @Override\r
+       public boolean performFinish() {\r
+               return mainPage.createProjects();\r
+               \r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ImportWizardModule.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ImportWizardModule.java
new file mode 100644 (file)
index 0000000..a389366
--- /dev/null
@@ -0,0 +1,54 @@
+package org.simantics.sysdyn.ui.wizards.modules;\r
+\r
+\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.Wizard;\r
+import org.eclipse.ui.IImportWizard;\r
+import org.eclipse.ui.IWorkbench;\r
+import org.simantics.db.Resource;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
+\r
+\r
+public class ImportWizardModule extends Wizard implements IImportWizard {\r
+       \r
+       private WizardModulesImportPage mainPage;\r
+       private IStructuredSelection currentSelection = null;\r
+       private String initialPath = null;\r
+       public Resource selection;\r
+\r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ImportWizardModule() {\r
+       this(null);\r
+    }\r
+    \r
+    /**\r
+     * Constructor for ExternalProjectImportWizard.\r
+     */\r
+    public ImportWizardModule(String initialPath)\r
+    {\r
+        super();\r
+        this.initialPath = initialPath;\r
+    }\r
\r
+    public void init(IWorkbench workbench, IStructuredSelection currentSelection) {\r
+        setWindowTitle("Import");\r
+        this.currentSelection = currentSelection;\r
+        selection = (Resource)AdaptionUtils.adaptToSingle(currentSelection, org.simantics.db.Resource.class);\r
+    }\r
+    \r
+    public void addPages() {\r
+        super.addPages();\r
+               mainPage = new WizardModulesImportPage(\r
+                               "wizardModulesImportPage", initialPath, currentSelection); //$NON-NLS-1$\r
+        addPage(mainPage);\r
+    }\r
+\r
+       @Override\r
+       public boolean performFinish() {\r
+               return mainPage.createProjects();\r
+               \r
+       }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleComponentTypeNode.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleComponentTypeNode.java
new file mode 100644 (file)
index 0000000..7b50181
--- /dev/null
@@ -0,0 +1,161 @@
+package org.simantics.sysdyn.ui.wizards.modules;\r
+\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.common.node.DeleteException;\r
+import org.simantics.browsing.ui.common.node.IDeletableNode;\r
+import org.simantics.browsing.ui.common.node.IModifiableNode;\r
+import org.simantics.browsing.ui.content.Labeler.Modifier;\r
+import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.layer0.adapter.PasteHandler;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+public class ModuleComponentTypeNode extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
+\r
+       \r
+       Listener<String> configurationNameSynchronizer;\r
+       private boolean disposed = false;\r
+       private Resource configuration;\r
+       \r
+    public ModuleComponentTypeNode(Resource resource) {\r
+        super(resource);\r
+\r
+        SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                       StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+                       configuration = graph.getPossibleObject(data, sr2.IsDefinedBy);                         \r
+                       }\r
+               });\r
+        \r
+        // Not the best solution for name sync\r
+        configurationNameSynchronizer = new Listener<String>() {\r
+\r
+               @Override\r
+                       public void execute(final String result) {\r
+                               SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
+                                       \r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               if(configuration != null)\r
+                                                       graph.claimLiteral(configuration, Layer0.getInstance(graph).HasLabel, result);\r
+                                       }\r
+                               });\r
+                       }\r
+\r
+                       @Override\r
+                       public void exception(Throwable t) {\r
+                               t.printStackTrace();\r
+                       }\r
+\r
+                       @Override\r
+                       public boolean isDisposed() {\r
+                               return disposed;\r
+                       }\r
+               };\r
+               \r
+        SimanticsUI.getSession().asyncRequest(new Read<String>() {\r
+\r
+                       @Override\r
+                       public String perform(ReadGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               return graph.getRelatedValue(data, l0.HasName);\r
+                       }\r
+               \r
+        }, configurationNameSynchronizer);\r
+        \r
+    }\r
+\r
+    @Override\r
+    public Modifier getModifier(String columnId) {\r
+        Modifier modifier = null;\r
+        try {\r
+            modifier = SimanticsUI.getSession().syncRequest(new Read<Modifier>() {\r
+\r
+                @Override\r
+                public Modifier perform(ReadGraph graph) throws ManyObjectsForFunctionalRelationException, ServiceException {\r
+                    ModelingResources mr = ModelingResources.getInstance(graph);\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    Resource type =  graph.getPossibleObject(data, mr.SymbolToComponentType);\r
+\r
+                    LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), type, l0.HasName) {\r
+                        @Override\r
+                        public String isValid(String label) {\r
+                            if (label.isEmpty())\r
+                                return "Empty name not allowed";\r
+                            return null;\r
+                        }\r
+                    };\r
+\r
+\r
+                    return modifier;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        return modifier;\r
+    }\r
+\r
+    @Override\r
+    public void delete() throws DeleteException {\r
+       disposed = true;\r
+        try {\r
+            SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                       Layer0 l0 = Layer0.getInstance(graph);\r
+                    StructuralResource2 st = StructuralResource2.getInstance(graph);\r
+                    ModelingResources mr = ModelingResources.getInstance(graph);\r
+\r
+                    Resource type =  graph.getPossibleObject(data, mr.SymbolToComponentType);\r
+                    Resource model = graph.getSingleObject(type, l0.PartOf);\r
+                    Resource modelConfiguration = graph.getSingleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+                    if (!graph.syncRequest(new ObjectsWithType(modelConfiguration, l0.ConsistsOf, type)).isEmpty()) {\r
+                        System.out.println("The module is used at the model configuration");\r
+                        return;\r
+                    }\r
+                    Collection<Resource> moduleTypes = graph.syncRequest(new ObjectsWithType(model, l0.ConsistsOf, st.ComponentType));\r
+                    for(Resource r : moduleTypes) {\r
+                        Resource configuration = graph.getSingleObject(r, st.IsDefinedBy);\r
+                        if(!graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, type)).isEmpty()) {\r
+                            System.out.println("The module is used at another module: " + graph.getRelatedValue(r, l0.HasName));\r
+                            return;\r
+                        }\r
+                    }\r
+                    graph.deny(model, l0.ConsistsOf, type);\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    @SuppressWarnings("rawtypes")\r
+    @Override\r
+    public Object getAdapter(Class adapter) {\r
+        if(PasteHandler.class == adapter && configuration != null) \r
+            return new DefaultPasteHandler(configuration);\r
+        return super.getAdapter(adapter);\r
+    }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModels.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModels.java
new file mode 100644 (file)
index 0000000..272a2af
--- /dev/null
@@ -0,0 +1,40 @@
+package org.simantics.sysdyn.ui.wizards.modules;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.common.node.AbstractNode;\r
+import org.simantics.browsing.ui.graph.impl.contributor.viewpoint.ViewpointContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+\r
+public class ModuleTreeModels extends ViewpointContributorImpl<Resource> {\r
+\r
+       @Override\r
+       public Collection<?> getContribution(ReadGraph graph, Resource input)\r
+                       throws DatabaseException {\r
+               \r
+\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ArrayList<AbstractNode<Resource>> result = new ArrayList<AbstractNode<Resource>>();\r
+               for(Resource r : graph.syncRequest(new ObjectsWithType(input, l0.ConsistsOf, sr.SysdynModel))) {\r
+                       result.add(new ModelNode(r));\r
+               }\r
+               \r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public String getViewpointId() {\r
+               return "Module Import";\r
+       }\r
+       \r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModules.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModules.java
new file mode 100644 (file)
index 0000000..76f76f8
--- /dev/null
@@ -0,0 +1,35 @@
+package org.simantics.sysdyn.ui.wizards.modules;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.browsing.ui.graph.contributor.viewpoint.ViewpointContributor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.ui.browser.nodes.ModelNode;\r
+\r
+public class ModuleTreeModules extends ViewpointContributor<ModelNode> {\r
+\r
+    @Override\r
+    public Collection<?> getContribution(ReadGraph graph, ModelNode model)\r
+    throws DatabaseException {\r
+       ArrayList<ModuleComponentTypeNode> result = new ArrayList<ModuleComponentTypeNode>();\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+               for (Resource r : graph.syncRequest(new ObjectsWithType(model.data, l0.ConsistsOf, sr2.ComponentType))){\r
+                       result.add(new ModuleComponentTypeNode(r));\r
+               }\r
+\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public String getViewpointId() {\r
+        return "Standard";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModulesLabeler.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleTreeModulesLabeler.java
new file mode 100644 (file)
index 0000000..0aa030a
--- /dev/null
@@ -0,0 +1,16 @@
+package org.simantics.sysdyn.ui.wizards.modules;\r
+\r
+import org.simantics.browsing.ui.graph.impl.contributor.labeler.LabelerContributorImpl;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public class ModuleTreeModulesLabeler extends LabelerContributorImpl<ModuleComponentTypeNode>{\r
+\r
+       @Override\r
+       public String getLabel(ReadGraph graph, ModuleComponentTypeNode input)\r
+                       throws DatabaseException {\r
+               return NameUtils.getSafeName(graph, input.data);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java
new file mode 100644 (file)
index 0000000..3625dd9
--- /dev/null
@@ -0,0 +1,475 @@
+package org.simantics.sysdyn.ui.wizards.modules;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.eclipse.core.runtime.Path;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.PixelConverter;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.Files;\r
+import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.TransferableGraphRequest2;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.graph.representation.TransferableGraph1;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class WizardModulesExportPage extends WizardPage {\r
+       \r
+       // dialog store id constants\r
+       private Text filePathField;\r
+       \r
+       // Keep track of the archive that we browsed to last time\r
+       // the wizard was invoked.\r
+       private static String previouslyBrowsedFile = "";\r
+\r
+       private Button browseDirectoriesButton;\r
+       \r
+       private Resource selectedModule;\r
+       \r
+       GraphExplorerComposite modelExplorer;\r
+\r
+       private boolean selectionMade = false;\r
+       \r
+       /**\r
+        * Creates a new project creation wizard page.\r
+        * \r
+        */\r
+       public WizardModulesExportPage() {\r
+               this("wizardModulesExportPage", null, null); //$NON-NLS-1$\r
+       }\r
+\r
+       /**\r
+        * Create a new instance of the receiver.\r
+        * \r
+        * @param pageName\r
+        */\r
+       public WizardModulesExportPage(String pageName) {\r
+               this(pageName,null, null);\r
+       }\r
+                       \r
+       /**\r
+        * More (many more) parameters.\r
+        * \r
+        * @param pageName\r
+        * @param initialPath\r
+        * @param currentSelection\r
+        * @since 3.5\r
+        */\r
+       public WizardModulesExportPage(String pageName,String initialPath,\r
+                       IStructuredSelection currentSelection) {\r
+               super(pageName);\r
+               //this.currentSelection = currentSelection;\r
+               setPageComplete(false);\r
+               setTitle("Export Module");\r
+               setDescription("Choose the Module and the export location, then press Finish.");\r
+       }\r
+       \r
+       public void createControl(Composite parent) {\r
+               \r
+               initializeDialogUnits(parent);\r
+\r
+               Composite workArea = new Composite(parent, SWT.NONE);\r
+               setControl(workArea);\r
+\r
+               workArea.setLayout(new GridLayout());\r
+               workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
+                               | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
+\r
+               createProjectsRoot(workArea);\r
+               createTree(workArea);\r
+       }\r
+       \r
+       private void createProjectsRoot(Composite workArea) {\r
+               \r
+               // set label for field\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select the export location for Module:");\r
+               \r
+               Composite projectGroup = new Composite(workArea, SWT.NONE);\r
+               GridLayout layout = new GridLayout();\r
+               layout.numColumns = 2;\r
+               layout.makeColumnsEqualWidth = false;\r
+               layout.marginWidth = 0;\r
+\r
+               projectGroup.setLayout(layout);\r
+               projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
+               \r
+               // module location entry field\r
+               this.filePathField = new Text(projectGroup, SWT.BORDER);\r
+\r
+               GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
+               directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
+               filePathField.setLayoutData(directoryPathData);\r
+               \r
+               filePathField.addModifyListener(new ModifyListener(){\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+               previouslyBrowsedFile = filePathField.getText();        \r
+            }\r
+               });\r
+               if (previouslyBrowsedFile != null){\r
+                       filePathField.setText(previouslyBrowsedFile);\r
+                       validatePage();\r
+               }\r
+               \r
+               // browse button\r
+               browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
+               browseDirectoriesButton.setText("Browse");\r
+               setButtonLayoutData(browseDirectoriesButton);\r
+               \r
+               browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
+                       /*\r
+                        * (non-Javadoc)\r
+                        * \r
+                        * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
+                        * elected(org.eclipse.swt.events.SelectionEvent)\r
+                        */\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               handleLocationDirectoryButtonPressed();\r
+                       }\r
+               });\r
+               \r
+       }\r
+\r
+       private void createTree(Composite workArea){\r
+               \r
+               //set label for tree\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select Module to export:");\r
+\r
+               try {\r
+                       Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph)\r
+                                               throws DatabaseException {\r
+                                       Resource model = SimanticsUI.getProject().get();\r
+                                       return model;\r
+                               }\r
+\r
+                       });\r
+\r
+                       modelExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                                       "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
+\r
+                       modelExplorer\r
+                       .setBrowseContexts(SysdynResource.URIs.ExportModuleTree);\r
+\r
+                       modelExplorer.finish();\r
+                       \r
+                       modelExplorer.setInput(null, input);\r
+\r
+                       GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                                       modelExplorer);\r
+                       \r
+                       ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
+                               \r
+                               @Override\r
+                               public void widgetSelected(SelectionEvent e) {\r
+                                       setMessage(null);\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                               @Override\r
+                               public void widgetDefaultSelected(SelectionEvent e) {\r
+                                       setMessage(null);\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                       });\r
+\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+       }\r
+    \r
+       //Set filePathField active\r
+       public void setVisible(boolean visible) {\r
+               super.setVisible(visible);\r
+               this.filePathField.setFocus();\r
+       }\r
+       \r
+       //Open dialog for choosing the file\r
+       protected void handleLocationDirectoryButtonPressed() {\r
+               \r
+               final Shell shell = filePathField.getShell();\r
+               \r
+               FileDialog dialog = new FileDialog(shell, SWT.SAVE);\r
+               \r
+               String[] ext = {"*.sysdynModule"};\r
+               dialog.setFilterExtensions(ext);\r
+               \r
+               dialog.setText("Export Module");\r
+\r
+               String dirName = filePathField.getText().trim();\r
+               \r
+               File path = new File(dirName);\r
+               if (path.exists()) {\r
+                       dialog.setFilterPath(new Path(dirName).toOSString());   \r
+               }\r
+               \r
+               String selectedFile = dialog.open();\r
+               if (selectedFile != null) {\r
+                       filePathField.setText(selectedFile);\r
+                       validatePage();\r
+               }               \r
+\r
+       }\r
+       \r
+       //Get selection from the tree\r
+       @SuppressWarnings("unchecked")\r
+       public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
+                       Class<T> clazz) {\r
+               \r
+               if(explorer == null)\r
+                       return null;\r
+               ISelection selection = ((ISelectionProvider) explorer\r
+                               .getAdapter(ISelectionProvider.class)).getSelection();\r
+               if (selection == null)\r
+                       return null;\r
+               IStructuredSelection iss = (IStructuredSelection) selection;\r
+               AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
+               if (inc == null)\r
+                       return null;\r
+               final T resource = (T) inc.getAdapter(clazz);\r
+\r
+               return resource;\r
+       }\r
+       \r
+       //Create export file when finish is pressed\r
+       public boolean createProjects() {\r
+               \r
+               final String selected = previouslyBrowsedFile;\r
+               if(selected == null) return false;\r
+\r
+               selectedModule= getExplorerResource(modelExplorer, Resource.class);\r
+               if(selectedModule == null)\r
+                       return false;\r
+               \r
+               String name = null;\r
+               try {\r
+                       name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                               @Override\r
+                               public String perform(ReadGraph graph) throws DatabaseException {\r
+                                       StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       \r
+                                       Resource component = selectedModule;\r
+                                       if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))\r
+                                               return null;\r
+                                       \r
+                                       Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
+                                       if (configuration == null)\r
+                                               return null;\r
+                                       \r
+                                       ArrayList<String> dependencies = null;\r
+                                       for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {\r
+                                               if(dependencies == null)\r
+                                                       dependencies = new ArrayList<String>();\r
+                                               String name = NameUtils.getSafeName(graph, r);\r
+                                               String instanceOf = NameUtils.getSafeName(graph, graph.getSingleObject(r, l0.InstanceOf));\r
+                                               dependencies.add(name + " : " + instanceOf);\r
+                                       }\r
+                                       if(dependencies != null && !dependencies.isEmpty())\r
+                                               throw new ContainsDependenciesException(dependencies);\r
+                                       \r
+                                       String name = graph.getPossibleRelatedValue(component, l0.HasName, Bindings.STRING);\r
+                                       return name;\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+               } \r
+               catch (DatabaseException e1) {\r
+                       e1.printStackTrace();\r
+               }\r
+               if(name == null) return false;\r
+               \r
+               SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
+                       \r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               \r
+                               final Resource component = selectedModule;\r
+                               //final Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);\r
+                               if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))\r
+                                       return;\r
+                               String name = graph.syncRequest(new PossibleRelatedValue<String>(component, l0.HasName, Bindings.STRING ));\r
+                               final ArrayList<Pair<Resource, String>> roots = new ArrayList<Pair<Resource, String>>();\r
+                               roots.add(Pair.make(component, name));\r
+\r
+                               graph.asyncRequest(new WriteRequest() {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+                                               ModelingResources mr = ModelingResources.getInstance(graph);\r
+                                               final Resource modulesymbol = graph.getPossibleObject(component, mr.ComponentTypeToSymbol);\r
+                                               Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
+                                               if (!graph.hasStatement(configuration, l0.PartOf, component)&& \r
+                                                               !graph.hasStatement(modulesymbol, l0.PartOf, component)) {\r
+                                                       // Make sure that configuration and symbol are included.\r
+                                                       // In old versions, they were attached to model, not to module.\r
+                                                       Resource previousPartof = graph.getSingleObject(configuration, l0.PartOf);\r
+\r
+                                                       graph.deny(configuration, l0.PartOf);\r
+                                                       graph.deny(modulesymbol, l0.PartOf);\r
+                                                       graph.claim(configuration, l0.PartOf, l0.ConsistsOf, component);\r
+                                                       graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, component);\r
+\r
+                                                       export(graph, selected, roots, component);\r
+\r
+                                                       graph.deny(configuration, l0.PartOf);\r
+                                                       graph.deny(modulesymbol, l0.PartOf);\r
+                                                       graph.claim(configuration, l0.PartOf, l0.ConsistsOf, previousPartof);\r
+                                                       graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, previousPartof);\r
+                                               } else {\r
+                                                       // Normal export\r
+                                                       export(graph, selected, roots, component);\r
+                                               }\r
+                                       }\r
+                               });\r
+\r
+                       }\r
+               });\r
+\r
+               return true;\r
+       }\r
+       \r
+       private void export(WriteGraph graph, String path, ArrayList<Pair<Resource, String>> roots, Resource component) {\r
+               \r
+               // FIXME: Enumeration replacement handling like this is not suitable.\r
+               try {\r
+                       Layer0 l0 = Layer0.getInstance(graph);\r
+                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                       StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+\r
+                       Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
+                       ArrayList<Pair<Resource, Resource>> replacements = new ArrayList<Pair<Resource, Resource>>();\r
+\r
+                       for(Resource enumeration : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {\r
+                               if(graph.hasStatement(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
+                                       for(Resource replacement : graph.getObjects(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
+                                               replacements.add(new Pair<Resource, Resource>(enumeration, replacement));\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       for(Pair<Resource,Resource> replacement : replacements)\r
+                               graph.deny(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);\r
+                       \r
+                       TransferableGraph1 tg = graph.syncRequest(new TransferableGraphRequest2(roots, component));\r
+                       Files.createFile(new File(path), Bindings.getBindingUnchecked(TransferableGraph1.class), tg);\r
+                       \r
+                       for(Pair<Resource,Resource> replacement : replacements)\r
+                               graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);\r
+\r
+               } catch (RuntimeBindingConstructionException e) {\r
+                       e.printStackTrace();\r
+               } catch (IOException e) {\r
+                       e.printStackTrace();\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+       \r
+       class ContainsDependenciesException extends DatabaseException {\r
+               private static final long serialVersionUID = -1533706136673146020L;\r
+               \r
+               private Collection<String> dependencies;\r
+               \r
+               ContainsDependenciesException(Collection<String> dependencies) {\r
+                       this.dependencies = dependencies;\r
+               }\r
+               \r
+               public Collection<String> getDependencies() {\r
+                       return this.dependencies;\r
+               }\r
+               \r
+       }\r
+       \r
+       void validatePage() {\r
+               \r
+               if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
+                       setPageComplete(false);\r
+                       return;\r
+               }\r
+               \r
+               if (modelExplorer != null){\r
+                       final Resource selectedResource = getExplorerResource(modelExplorer, Resource.class);\r
+\r
+                       String root = null;\r
+                       try {\r
+                               root = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
+\r
+                                       @Override\r
+                                       public String perform(ReadGraph graph) throws DatabaseException {\r
+                                               Layer0 l0 = Layer0.getInstance(graph);\r
+                                               Resource model = graph.getPossibleObject(selectedResource, l0.PartOf);\r
+                                               String rootName = NameUtils.getSafeName(graph, model);\r
+\r
+                                               return rootName;\r
+                                       }\r
+\r
+                               });\r
+                               if (root != null && root.equalsIgnoreCase("Development Project")){\r
+                                       setPageComplete(false);\r
+                                       setMessage("Select Module under the Model.");\r
+                                       return;\r
+                               }\r
+                       } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+               }\r
+               \r
+               setPageComplete(true);\r
+               \r
+       }\r
+        \r
+\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java b/1.8/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java
new file mode 100644 (file)
index 0000000..415d02c
--- /dev/null
@@ -0,0 +1,365 @@
+package org.simantics.sysdyn.ui.wizards.modules;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Path;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.PixelConverter;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.ISelectionProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.wizard.WizardPage;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.events.ModifyEvent;\r
+import org.eclipse.swt.events.ModifyListener;\r
+import org.eclipse.swt.events.SelectionAdapter;\r
+import org.eclipse.swt.events.SelectionEvent;\r
+import org.eclipse.swt.events.SelectionListener;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Button;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.FileDialog;\r
+import org.eclipse.swt.widgets.Label;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.eclipse.swt.widgets.Text;\r
+import org.eclipse.swt.widgets.Tree;\r
+import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+\r
+\r
+public class WizardModulesImportPage extends WizardPage{\r
+       \r
+       public static String IMPORTMODULETPATH = "IMPORT_MODULE_PATH";\r
+       \r
+       // dialog store id constants\r
+       \r
+       private Text filePathField;\r
+       \r
+       // Keep track of the archive that we browsed to last time\r
+       // the wizard was invoked.\r
+       private static String previouslyBrowsedFile = "";\r
+\r
+       private Button browseDirectoriesButton;\r
+\r
+       private Shell shell;\r
+       \r
+       //private IStructuredSelection currentSelection;\r
+       \r
+       private Resource selectedModel;\r
+       \r
+       GraphExplorerComposite modelExplorer;\r
+       \r
+       private boolean selectionMade = false;\r
+       \r
+       /**\r
+        * Creates a new project creation wizard page.\r
+        * \r
+        */\r
+       public WizardModulesImportPage() {\r
+               this("wizardModulesImportPage", null, null); //$NON-NLS-1$\r
+       }\r
+\r
+       /**\r
+        * Create a new instance of the receiver.\r
+        * \r
+        * @param pageName\r
+        */\r
+       public WizardModulesImportPage(String pageName) {\r
+               this(pageName,null, null);\r
+       }\r
+                       \r
+       /**\r
+        * More (many more) parameters.\r
+        * \r
+        * @param pageName\r
+        * @param initialPath\r
+        * @param currentSelection\r
+        * @since 3.5\r
+        */\r
+       public WizardModulesImportPage(String pageName,String initialPath,\r
+                       IStructuredSelection currentSelection) {\r
+               super(pageName);\r
+               setPageComplete(false);\r
+               //this.currentSelection = currentSelection;\r
+               setTitle("Import Module");\r
+               setDescription("Choose the Module file and the import location, then press Finish.");\r
+       }\r
+       \r
+       public void createControl(Composite parent) {\r
+       \r
+               initializeDialogUnits(parent);\r
+\r
+               Composite workArea = new Composite(parent, SWT.NONE);\r
+               setControl(workArea);\r
+\r
+               workArea.setLayout(new GridLayout());\r
+               workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
+                               | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
+\r
+               createProjectsRoot(workArea);\r
+               \r
+               createTree(workArea);\r
+       }\r
+       \r
+       private void createProjectsRoot(Composite workArea) {\r
+               \r
+               // set label for field\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select Module source:");\r
+               \r
+               Composite projectGroup = new Composite(workArea, SWT.NONE);\r
+               GridLayout layout = new GridLayout();\r
+               layout.numColumns = 2;\r
+               layout.makeColumnsEqualWidth = false;\r
+               layout.marginWidth = 0;\r
+               \r
+               projectGroup.setLayout(layout);\r
+               projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
+               \r
+               // module location entry field\r
+               this.filePathField = new Text(projectGroup, SWT.BORDER);\r
+\r
+               GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
+               directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
+               filePathField.setLayoutData(directoryPathData);\r
+               \r
+               filePathField.addModifyListener(new ModifyListener(){\r
+            @Override\r
+            public void modifyText(ModifyEvent e) {\r
+               previouslyBrowsedFile = filePathField.getText();        \r
+            }\r
+               });\r
+               if (previouslyBrowsedFile != null){\r
+                       filePathField.setText(previouslyBrowsedFile);\r
+                       validatePage();\r
+               }\r
+               \r
+               // browse button\r
+               browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
+               browseDirectoriesButton.setText("Browse");\r
+               setButtonLayoutData(browseDirectoriesButton);\r
+               \r
+               browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
+                       /*\r
+                        * (non-Javadoc)\r
+                        * \r
+                        * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
+                        * elected(org.eclipse.swt.events.SelectionEvent)\r
+                        */\r
+                       public void widgetSelected(SelectionEvent e) {\r
+                               handleLocationDirectoryButtonPressed();\r
+                       }\r
+               });\r
+               \r
+       }\r
+\r
+       private void createTree(Composite workArea){\r
+               \r
+               //set label for tree\r
+               Label title = new Label(workArea, SWT.NONE);\r
+               title.setText("Select import location:");\r
+\r
+               try {\r
+                       Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
+\r
+                               @Override\r
+                               public Resource perform(ReadGraph graph)\r
+                                               throws DatabaseException {\r
+                                       Resource model = SimanticsUI.getProject().get();\r
+                                       return model;\r
+                               }\r
+\r
+                       });\r
+\r
+                       modelExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
+                                       "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
+\r
+                       modelExplorer\r
+                       .setBrowseContexts(SysdynResource.URIs.ImportModuleTree);\r
+\r
+                       modelExplorer.finish();\r
+\r
+                       modelExplorer.setInput(null, input);\r
+                       \r
+                       GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
+                                       modelExplorer);\r
+                       \r
+                       ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
+                               \r
+                               @Override\r
+                               public void widgetSelected(SelectionEvent e) {\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                               @Override\r
+                               public void widgetDefaultSelected(SelectionEvent e) {\r
+                                       selectionMade = true;\r
+                                       validatePage();\r
+                               }\r
+                       });\r
+                       \r
+\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+\r
+       }\r
+       \r
+       //Set filePathField active\r
+       public void setVisible(boolean visible) {\r
+               super.setVisible(visible);\r
+               this.filePathField.setFocus();\r
+       }\r
+       \r
+       //Open dialog for choosing the file\r
+       protected void handleLocationDirectoryButtonPressed() {\r
+               \r
+               shell = filePathField.getShell();\r
+               \r
+               FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
+               \r
+               String[] ext = {"*.sysdynModule; *.tg", "*.*"};\r
+               dialog.setFilterExtensions(ext);\r
+               \r
+               dialog.setText("Import Module");\r
+\r
+               String dirName = filePathField.getText().trim();\r
+               \r
+               File path = new File(dirName);\r
+               if (path.exists()) {\r
+                       dialog.setFilterPath(new Path(dirName).toOSString());   \r
+               }\r
+               \r
+               String selectedFile = dialog.open();\r
+               if (selectedFile != null) {\r
+                       filePathField.setText(selectedFile);\r
+                       validatePage();\r
+               }               \r
+       }\r
+       \r
+       //Get selection from the tree\r
+       @SuppressWarnings("unchecked")\r
+       public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
+                       Class<T> clazz) {\r
+               \r
+               if(explorer == null)\r
+                       return null;\r
+               ISelection selection = ((ISelectionProvider) explorer\r
+                               .getAdapter(ISelectionProvider.class)).getSelection();\r
+               if (selection == null)\r
+                       return null;\r
+               IStructuredSelection iss = (IStructuredSelection) selection;\r
+               AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
+               if (inc == null)\r
+                       return null;\r
+               final T resource = (T) inc.getAdapter(clazz);\r
+\r
+               return resource;\r
+       }\r
+       \r
+       //Create project after finish is pressed.\r
+       public boolean createProjects() {\r
+               \r
+               String selected = previouslyBrowsedFile;\r
+               if(selected == null){ \r
+                       setErrorMessage("Error when retrieving resource");\r
+                       return false;\r
+               }\r
+               \r
+               selectedModel= getExplorerResource(modelExplorer, Resource.class);\r
+               if(selectedModel == null){\r
+                       setErrorMessage("No file selected");\r
+                       return false;\r
+               }\r
+               \r
+               IStatus status = ImportUtilsUI.importModuleFile(selectedModel, selected, null);\r
+               \r
+               /*\r
+               TransferableGraph1 tg = null;\r
+               try {\r
+                       tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
+               } catch (RuntimeBindingConstructionException e) {\r
+                       e.printStackTrace();\r
+               } catch (IOException e) {\r
+                       setErrorMessage("The imported file is not of type: Module Type");\r
+                       return false;\r
+               }\r
+               if(tg == null){\r
+                       setErrorMessage("The imported file is not of type: Module Type");\r
+                       return false;\r
+               }\r
+\r
+               \r
+               DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(selectedModel);\r
+               try {\r
+                       DefaultPasteHandler.defaultExecute(tg, selectedModel, ia);\r
+               } catch (MissingDependencyException e) {\r
+                       e.printStackTrace();\r
+               } catch (Exception e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+               final Resource root = ia.getRoot();\r
+               \r
+               try {\r
+                       SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+                               \r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       if(!graph.isInheritedFrom(root, SysdynResource.getInstance(graph).Module)) {\r
+                                               Resource instanceOf = graph.getPossibleObject(root, Layer0.getInstance(graph).InstanceOf);\r
+                                               String type = "...";\r
+                                               if(instanceOf != null)\r
+                                                       type = NameUtils.getSafeName(graph, instanceOf);\r
+                                               else {\r
+                                                       Resource inheritedFrom = graph.getPossibleObject(root, Layer0.getInstance(graph).Inherits);\r
+                                                       if(inheritedFrom != null)\r
+                                                               type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                                               }\r
+                                               graph.deny(root, Layer0.getInstance(graph).PartOf);\r
+                                               error = type;\r
+                                       }\r
+                               }\r
+                               });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+               if (!error.isEmpty()){\r
+                       setErrorMessage("The imported file is not of type: Module Type (" + error +")");\r
+                       error = "";\r
+                       return false;\r
+               }\r
+               */\r
+               if(status == null || !status.equals(Status.OK_STATUS)) {\r
+                   setErrorMessage(status.getMessage());\r
+                   return false;\r
+               }\r
+\r
+               return true;\r
+       }\r
+       \r
+       void validatePage() {\r
+               \r
+               if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
+                       setPageComplete(false);\r
+                       return;\r
+               }\r
+               \r
+               setErrorMessage(null);\r
+               setPageComplete(true);\r
+               \r
+       }\r
+       \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn.ui/sysdyn.product b/1.8/org.simantics.sysdyn.ui/sysdyn.product
new file mode 100644 (file)
index 0000000..422e885
--- /dev/null
@@ -0,0 +1,125 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<?pde version="3.5"?>\r
+\r
+<product name="Simantics System Dynamic Tool" uid="org.simantics.sysdyn.product.Sysdyn" id="org.simantics.sysdyn.ui.product" application="org.simantics.workbench.application" version="1.8" useFeatures="true" includeLaunchers="false">\r
+\r
+   <aboutInfo>\r
+      <image path="/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.png"/>\r
+      <text>\r
+         %about.text\r
+      </text>\r
+   </aboutInfo>\r
+\r
+   <configIni use="default">\r
+   </configIni>\r
+\r
+   <launcherArgs>\r
+      <programArgs>-fixerrors
+--launcher.XXMaxPermSize 192m
+-data @noDefault</programArgs>\r
+      <vmArgs>-ea  -Xmx768M -XX:MaxPermSize=192m -Xshare:off -Dorg.simantics.undo.enabled=true</vmArgs>\r
+      <vmArgsMac>-XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts</vmArgsMac>\r
+      <vmArgsWin>-Dorg.osgi.framework.os.name=win32</vmArgsWin>\r
+   </launcherArgs>\r
+\r
+   <windowImages i16="/org.simantics.sysdyn.ui/icons/simantics_sysdyn16.png" i32="/org.simantics.sysdyn.ui/icons/simantics_sysdyn32.png" i48="/org.simantics.sysdyn.ui/icons/simantics_sysdyn48.png" i64="/org.simantics.sysdyn.ui/icons/simantics_sysdyn64.png" i128="/org.simantics.sysdyn.ui/icons/simantics_sysdyn128.png"/>\r
+\r
+   <splash\r
+      location="org.simantics.sysdyn.ui" />\r
+   <launcher name="Simantics-Sysdyn">\r
+      <solaris/>\r
+      <win useIco="false">\r
+         <bmp/>\r
+      </win>\r
+   </launcher>\r
+\r
+\r
+   <vm>\r
+      <windows include="true">org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6</windows>\r
+   </vm>\r
+\r
+   <license>\r
+        <url>http://www.eclipse.org/legal/epl-v10.html</url>\r
+        <text>\r
+   Eclipse Public License - v 1.0
+
+THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT&apos;S ACCEPTANCE OF THIS AGREEMENT.
+
+1. DEFINITIONS
+
+&quot;Contribution&quot; means:
+
+a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
+b) in the case of each subsequent Contributor:
+i) changes to the Program, and
+ii) additions to the Program;
+where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution &apos;originates&apos; from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor&apos;s behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
+&quot;Contributor&quot; means any person or entity that distributes the Program.
+
+&quot;Licensed Patents&quot; mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
+
+&quot;Program&quot; means the Contributions distributed in accordance with this Agreement.
+
+&quot;Recipient&quot; means anyone who receives the Program under this Agreement, including all Contributors.
+
+2. GRANT OF RIGHTS
+
+a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
+b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
+c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient&apos;s responsibility to acquire that license before distributing the Program.
+d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
+3. REQUIREMENTS
+
+A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
+
+a) it complies with the terms and conditions of this Agreement; and
+b) its license agreement:
+i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
+ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
+iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
+iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
+When the Program is made available in source code form:
+
+a) it must be made available under this Agreement; and
+b) a copy of this Agreement must be included with each copy of the Program.
+Contributors may not remove or alter any copyright notices contained within the Program.
+
+Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
+
+4. COMMERCIAL DISTRIBUTION
+
+Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (&quot;Commercial Contributor&quot;) hereby agrees to defend and indemnify every other Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
+
+For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor&apos;s responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
+
+5. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
+
+6. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+7. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
+
+If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient&apos;s patent(s), then such Recipient&apos;s rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
+
+All Recipient&apos;s rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient&apos;s rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient&apos;s obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
+
+Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
+
+This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.\r
+         </text>\r
+   </license>\r
+\r
+   <plugins>\r
+   </plugins>\r
+\r
+   <features>\r
+      <feature id="org.simantics.sysdyn" version="1.8.0.qualifier"/>\r
+   </features>\r
+\r
+\r
+</product>\r
diff --git a/1.8/org.simantics.sysdyn/.classpath b/1.8/org.simantics.sysdyn/.classpath
new file mode 100644 (file)
index 0000000..8a8f166
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>\r
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="output" path="bin"/>\r
+</classpath>\r
diff --git a/1.8/org.simantics.sysdyn/.hgignore b/1.8/org.simantics.sysdyn/.hgignore
new file mode 100644 (file)
index 0000000..73df90f
--- /dev/null
@@ -0,0 +1,5 @@
+syntax: regexp\r
+^bin/\r
+\r
+syntax: glob\r
+*.svn/*
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/.project b/1.8/org.simantics.sysdyn/.project
new file mode 100644 (file)
index 0000000..05d4439
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>org.simantics.sysdyn</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.ManifestBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.pde.SchemaBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>org.eclipse.pde.PluginNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/1.8/org.simantics.sysdyn/.settings/org.eclipse.jdt.core.prefs b/1.8/org.simantics.sysdyn/.settings/org.eclipse.jdt.core.prefs
new file mode 100644 (file)
index 0000000..785aae6
--- /dev/null
@@ -0,0 +1,8 @@
+#Mon Nov 16 15:37:44 EET 2009\r
+eclipse.preferences.version=1\r
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\r
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6\r
+org.eclipse.jdt.core.compiler.compliance=1.6\r
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error\r
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error\r
+org.eclipse.jdt.core.compiler.source=1.6\r
diff --git a/1.8/org.simantics.sysdyn/META-INF/MANIFEST.MF b/1.8/org.simantics.sysdyn/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..886074f
--- /dev/null
@@ -0,0 +1,62 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Simantics System Dynamics
+Bundle-SymbolicName: org.simantics.sysdyn;singleton:=true
+Bundle-Version: 1.8.0.qualifier
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: org.simantics.objmap;bundle-version="0.1.0",
+ org.simantics.db;bundle-version="0.6.2",
+ org.simantics.modelica;bundle-version="1.0.0",
+ org.simantics.db.common;bundle-version="0.8.0",
+ org.simantics.simulation;bundle-version="1.0.0",
+ org.eclipse.ui.console;bundle-version="3.4.0",
+ org.eclipse.core.runtime;bundle-version="3.5.0",
+ org.eclipse.jface;bundle-version="3.5.2",
+ org.simantics.project;bundle-version="1.0.0",
+ org.simantics.layer0.utils;bundle-version="0.8.0",
+ org.simantics.layer0;bundle-version="1.0.0",
+ org.simantics.structural.ontology;bundle-version="1.0.0",
+ org.simantics.sysdyn.ontology;bundle-version="1.0.0",
+ org.simantics.modeling;bundle-version="1.1.1",
+ org.simantics.diagram;bundle-version="1.1.1",
+ org.simantics.diagram.ontology;bundle-version="1.1.1",
+ org.simantics.scl.runtime;bundle-version="0.1.3",
+ org.simantics.db.layer0;bundle-version="1.1.0",
+ org.simantics.spreadsheet.common;bundle-version="1.1.0",
+ org.simantics.spreadsheet;bundle-version="1.1.0",
+ org.eclipse.jface.text;bundle-version="3.6.1",
+ org.simantics.spreadsheet.ontology;bundle-version="1.2.0",
+ org.simantics.fmu;bundle-version="1.0.0",
+ org.simantics.fmu.me.win32;bundle-version="1.0.0",
+ org.simantics.issues;bundle-version="1.1.0",
+ org.simantics.issues.common;bundle-version="1.1.0",
+ org.simantics.jfreechart;bundle-version="1.0.0",
+ org.jfree.jchart;bundle-version="1.0.13",
+ org.jfree.jcommon;bundle-version="1.0.16",
+ org.simantics.spreadsheet.graph;bundle-version="1.1.0",
+ fi.semantum.sysdyn.solver;bundle-version="0.1.0"
+Export-Package: org.simantics.sysdyn,
+ org.simantics.sysdyn.adapter,
+ org.simantics.sysdyn.elementaryCycles,
+ org.simantics.sysdyn.expressionParser,
+ org.simantics.sysdyn.manager,
+ org.simantics.sysdyn.modelExport,
+ org.simantics.sysdyn.modelImport,
+ org.simantics.sysdyn.modelImport.model,
+ org.simantics.sysdyn.modelParser,
+ org.simantics.sysdyn.modelica,
+ org.simantics.sysdyn.representation,
+ org.simantics.sysdyn.representation.expressions,
+ org.simantics.sysdyn.representation.utils,
+ org.simantics.sysdyn.representation.visitors,
+ org.simantics.sysdyn.simulation,
+ org.simantics.sysdyn.solver,
+ org.simantics.sysdyn.tableParser,
+ org.simantics.sysdyn.utils,
+ org.simantics.sysdyn.utils.imports
+Bundle-Activator: org.simantics.sysdyn.Activator
+Bundle-ActivationPolicy: lazy
+Import-Package: org.eclipse.ui,
+ org.simantics.sysdyn.utils,
+ org.simantics.ui
+Bundle-Vendor: VTT Technical Reserarch Centre of Finland
diff --git a/1.8/org.simantics.sysdyn/ModelicaParser.html b/1.8/org.simantics.sysdyn/ModelicaParser.html
new file mode 100644 (file)
index 0000000..157b944
--- /dev/null
@@ -0,0 +1,727 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
+<HTML>
+<HEAD>
+<TITLE>BNF for ModelicaParser.jj </TITLE>
+</HEAD>
+<BODY>
+<H1 ALIGN=CENTER>BNF for ModelicaParser.jj </H1>
+<H2 ALIGN=CENTER>TOKENS</H2>
+<TABLE>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Lexer *********************************************************/</PRE>
+  </TD>
+ </TR>
+ <!-- Token -->
+ <TR>
+  <TD>
+   <PRE>
+&lt;DEFAULT&gt; SKIP : {
+&lt;WHITESPACE: " " | "\n" | "\r" | "\t"&gt;
+| &lt;COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/"&gt;
+| &lt;COMMENT2: "//" (~["\n"])*&gt;
+}
+
+   </PRE>
+  </TD>
+ </TR>
+ <!-- Token -->
+ <TR>
+  <TD>
+   <PRE>
+&lt;DEFAULT&gt; TOKEN : {
+"algorithm"
+| "discrete"
+| "false"
+| "model"
+| "redeclare"
+| "and"
+| "each"
+| "final"
+| "not"
+| "replaceable"
+| "annotation"
+| "else"
+| "flow"
+| "operator"
+| "return"
+| "assert"
+| "elseif"
+| "for"
+| "or"
+| "stream"
+| "block"
+| "elsewhen"
+| "function"
+| "outer"
+| "then"
+| "break"
+| "encapsulated"
+| "if"
+| "output"
+| "true"
+| "class"
+| "end"
+| "import"
+| "package"
+| "type"
+| "connect"
+| "enumeration"
+| "in"
+| "parameter"
+| "when"
+| "connector"
+| "equation"
+| "initial"
+| "partial"
+| "while"
+| "constant"
+| "expandable"
+| "inner"
+| "protected"
+| "within"
+| "constrainedby"
+| "extends"
+| "input"
+| "public"
+| "der"
+| "external"
+| "loop"
+| "record"
+| "("
+| ")"
+| "{"
+| "}"
+| "["
+| "]"
+| "."
+| ":"
+| ";"
+| ","
+| "&lt;"
+| "&lt;="
+| "&gt;"
+| "&gt;="
+| "=="
+| "&lt;&gt;"
+| "+"
+| "-"
+| ".+"
+| ".-"
+| "*"
+| "/"
+| ".*"
+| "./"
+| "^"
+| ".^"
+| "="
+| ":="
+| &lt;IDENT: ["a"-"z","A"-"Z","_"] (["a"-"z","A"-"Z","_","0"-"9"])*&gt;
+| &lt;STRING: "\"" (~["\"","\\","\n"] | "\\" ~["\n"])* "\""&gt; : {
+| &lt;UNSIGNED_INTEGER: (["0"-"9"])+&gt;
+| &lt;UNSIGNED_NUMBER: &lt;UNSIGNED_INTEGER&gt; "." (&lt;UNSIGNED_INTEGER&gt;)? (["e","E"] &lt;UNSIGNED_INTEGER&gt;)? | "." &lt;UNSIGNED_INTEGER&gt; (["e","E"] &lt;UNSIGNED_INTEGER&gt;)? | &lt;UNSIGNED_INTEGER&gt; ["e","E"] &lt;UNSIGNED_INTEGER&gt;&gt;
+}
+
+   </PRE>
+  </TD>
+ </TR>
+</TABLE>
+<H2 ALIGN=CENTER>NON-TERMINALS</H2>
+<TABLE>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Parser ********************************************************/
+
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+</PRE>
+  </TD>
+ </TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod1">parse</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod2">stored_definition</A> &lt;EOF&gt;</TD>
+</TR>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Stored Definition - Within ************************************/</PRE>
+  </TD>
+ </TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod2">stored_definition</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "within" ( <A HREF="#prod3">name</A> )? ";" )? ( ( "final" )? <A HREF="#prod4">class_definition</A> ";" )*</TD>
+</TR>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Class Definition **********************************************/</PRE>
+  </TD>
+ </TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod4">class_definition</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "encapsulated" )? ( "partial" )? ( "class" | "model" | "record" | "block" | ( "expandable" )? "connector" | "type" | "package" | "function" | "operator" | "operator function" | "operator record" ) <A HREF="#prod5">class_specifier</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod5">class_specifier</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;IDENT&gt; <A HREF="#prod6">string_comment</A> <A HREF="#prod7">composition</A> "end" &lt;IDENT&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;IDENT&gt; "=" <A HREF="#prod8">base_prefix</A> <A HREF="#prod3">name</A> ( <A HREF="#prod9">array_subscripts</A> )? ( <A HREF="#prod10">class_modification</A> )? <A HREF="#prod11">comment</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;IDENT&gt; "=" "enumeration" "(" ( ( <A HREF="#prod12">enum_list</A> )? | ":" ) ")" <A HREF="#prod11">comment</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;IDENT&gt; "=" "der" "(" <A HREF="#prod3">name</A> "," &lt;IDENT&gt; ( "," &lt;IDENT&gt; )* ")" <A HREF="#prod11">comment</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"extends" &lt;IDENT&gt; ( <A HREF="#prod10">class_modification</A> )? <A HREF="#prod6">string_comment</A> <A HREF="#prod7">composition</A> "end" &lt;IDENT&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod8">base_prefix</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod13">type_prefix</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod12">enum_list</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod14">enumeration_literal</A> ( "," <A HREF="#prod14">enumeration_literal</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod14">enumeration_literal</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;IDENT&gt; <A HREF="#prod11">comment</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod15">parse_composition</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod7">composition</A> &lt;EOF&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod7">composition</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod16">element_list</A> ( "public" <A HREF="#prod16">element_list</A> | "protected" <A HREF="#prod16">element_list</A> | <A HREF="#prod17">equation_section</A> | <A HREF="#prod18">algorithm_section</A> )* ( "external" ( <A HREF="#prod19">language_specification</A> )? ( <A HREF="#prod20">external_function_call</A> )? ( <A HREF="#prod21">annotation</A> )? ";" )? ( <A HREF="#prod21">annotation</A> ";" )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod19">language_specification</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;STRING&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod20">external_function_call</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod22">component_reference</A> "=" )? &lt;IDENT&gt; "(" ( <A HREF="#prod23">expression_list</A> )? ")"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod16">element_list</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod24">element</A> ";" )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod24">element</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod25">import_clause</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod26">extends_clause</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "redeclare" )? ( "final" )? ( "inner" )? ( "outer" )? ( ( <A HREF="#prod4">class_definition</A> | <A HREF="#prod27">component_clause</A> ) | "replaceable" ( <A HREF="#prod4">class_definition</A> | <A HREF="#prod27">component_clause</A> ) ( <A HREF="#prod28">constraining_clause</A> <A HREF="#prod11">comment</A> )? )</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod25">import_clause</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"import" ( &lt;IDENT&gt; "=" <A HREF="#prod3">name</A> | <A HREF="#prod3">name</A> ( "." "*" )? ) <A HREF="#prod11">comment</A></TD>
+</TR>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Extends *******************************************************/</PRE>
+  </TD>
+ </TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod26">extends_clause</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"extends" <A HREF="#prod3">name</A> ( <A HREF="#prod10">class_modification</A> )? ( <A HREF="#prod21">annotation</A> )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod28">constraining_clause</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"constrainedby" <A HREF="#prod3">name</A> ( <A HREF="#prod10">class_modification</A> )?</TD>
+</TR>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Component Clause **********************************************/</PRE>
+  </TD>
+ </TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod27">component_clause</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod13">type_prefix</A> ) ( <A HREF="#prod29">type_specifier</A> ) ( <A HREF="#prod9">array_subscripts</A> )? ( <A HREF="#prod30">component_list</A> )</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod13">type_prefix</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "flow" | "stream" )? ( "discrete" | "parameter" | "constant" )? ( "output" | "input" )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod29">type_specifier</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod3">name</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod30">component_list</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod31">component_declaration</A> ( "," <A HREF="#prod31">component_declaration</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod31">component_declaration</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod32">declaration</A> ( <A HREF="#prod33">conditional_attribute</A> )? <A HREF="#prod11">comment</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod33">conditional_attribute</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"if" <A HREF="#prod34">expression</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod32">declaration</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;IDENT&gt; ( <A HREF="#prod9">array_subscripts</A> )? ( <A HREF="#prod35">modification</A> )?</TD>
+</TR>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Modification **********************************************/</PRE>
+  </TD>
+ </TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod35">modification</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod10">class_modification</A> ( "=" <A HREF="#prod34">expression</A> )? | "=" <A HREF="#prod34">expression</A> | ":=" <A HREF="#prod34">expression</A> )</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod10">class_modification</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"(" ( <A HREF="#prod36">argument_list</A> )? ")"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod36">argument_list</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod37">argument</A> ( "," <A HREF="#prod37">argument</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod37">argument</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod38">element_modification_or_replaceable</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod39">element_redeclaration</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod38">element_modification_or_replaceable</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "each" )? ( "final" )? ( <A HREF="#prod40">element_modification</A> | <A HREF="#prod41">element_replaceable</A> )</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod40">element_modification</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod3">name</A> ( <A HREF="#prod35">modification</A> )? <A HREF="#prod6">string_comment</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod39">element_redeclaration</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"redeclare" ( "each" )? ( "final" )? ( ( <A HREF="#prod4">class_definition</A> | <A HREF="#prod42">component_clause1</A> ) | <A HREF="#prod41">element_replaceable</A> )</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod41">element_replaceable</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"replaceable" ( <A HREF="#prod4">class_definition</A> | <A HREF="#prod42">component_clause1</A> ) ( <A HREF="#prod28">constraining_clause</A> )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod42">component_clause1</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod13">type_prefix</A> <A HREF="#prod29">type_specifier</A> <A HREF="#prod43">component_declaration1</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod43">component_declaration1</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod32">declaration</A> <A HREF="#prod11">comment</A></TD>
+</TR>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Equations *************************************************/</PRE>
+  </TD>
+ </TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod17">equation_section</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "initial" )? "equation" ( <A HREF="#prod44">equation</A> ";" )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod18">algorithm_section</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "initial" )? "algorithm" ( <A HREF="#prod45">statement</A> ";" )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod44">equation</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod46">simple_expression</A> "=" <A HREF="#prod34">expression</A> | <A HREF="#prod47">if_equation</A> | <A HREF="#prod48">for_equation</A> | <A HREF="#prod49">connect_clause</A> | <A HREF="#prod50">when_equation</A> | &lt;IDENT&gt; <A HREF="#prod51">function_call_args</A> ) <A HREF="#prod11">comment</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod45">statement</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod22">component_reference</A> ( ":=" <A HREF="#prod34">expression</A> | <A HREF="#prod51">function_call_args</A> ) | "(" <A HREF="#prod52">output_expression_list</A> ")" ":=" <A HREF="#prod22">component_reference</A> <A HREF="#prod51">function_call_args</A> | "break" | "return" | <A HREF="#prod53">if_statement</A> | <A HREF="#prod54">for_statement</A> | <A HREF="#prod55">while_statement</A> | <A HREF="#prod56">when_statement</A> ) <A HREF="#prod11">comment</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod47">if_equation</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"if" <A HREF="#prod34">expression</A> "then" ( <A HREF="#prod44">equation</A> ";" )* ( "elseif" <A HREF="#prod34">expression</A> "then" ( <A HREF="#prod44">equation</A> ";" )* )* ( "else" ( <A HREF="#prod44">equation</A> ";" )* )? "end" "if"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod53">if_statement</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"if" <A HREF="#prod34">expression</A> "then" ( <A HREF="#prod45">statement</A> ";" )* ( "elseif" <A HREF="#prod34">expression</A> "then" ( <A HREF="#prod45">statement</A> ";" )* )* ( "else" ( <A HREF="#prod45">statement</A> ";" )* )? "end" "if"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod48">for_equation</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"for" <A HREF="#prod57">for_indices</A> "loop" ( <A HREF="#prod44">equation</A> ";" )* "end" "for"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod54">for_statement</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"for" <A HREF="#prod57">for_indices</A> "loop" ( <A HREF="#prod45">statement</A> ";" )* "end" "for"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod57">for_indices</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod58">for_index</A> ( "," <A HREF="#prod58">for_index</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod58">for_index</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;IDENT&gt; ( "in" <A HREF="#prod34">expression</A> )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod55">while_statement</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"while" <A HREF="#prod34">expression</A> "loop" ( <A HREF="#prod45">statement</A> ";" )* "end" "while"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod50">when_equation</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"when" <A HREF="#prod34">expression</A> "then" ( <A HREF="#prod44">equation</A> ";" )* ( "elsewhen" <A HREF="#prod34">expression</A> "then" ( <A HREF="#prod44">equation</A> ";" )* )* "end" "when"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod56">when_statement</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"when" <A HREF="#prod34">expression</A> "then" ( <A HREF="#prod45">statement</A> ";" )* ( "elsewhen" <A HREF="#prod34">expression</A> "then" ( <A HREF="#prod45">statement</A> ";" )* )* "end" "when"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod49">connect_clause</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"connect" "(" <A HREF="#prod22">component_reference</A> "," <A HREF="#prod22">component_reference</A> ")"</TD>
+</TR>
+ <!-- Special token -->
+ <TR>
+  <TD>
+<PRE>
+/*** Expressions ***************************************************/</PRE>
+  </TD>
+ </TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod59">expr</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod46">simple_expression</A> &lt;EOF&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"if" <A HREF="#prod34">expression</A> "then" <A HREF="#prod34">expression</A> ( "elseif" <A HREF="#prod34">expression</A> "then" <A HREF="#prod34">expression</A> )* "else" <A HREF="#prod34">expression</A> &lt;EOF&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod34">expression</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod46">simple_expression</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"if" <A HREF="#prod34">expression</A> "then" <A HREF="#prod34">expression</A> ( "elseif" <A HREF="#prod34">expression</A> "then" <A HREF="#prod34">expression</A> )* "else" <A HREF="#prod34">expression</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod46">simple_expression</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod60">logical_expression</A> ( ":" <A HREF="#prod60">logical_expression</A> ( ":" <A HREF="#prod60">logical_expression</A> )? )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod60">logical_expression</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod61">logical_term</A> ( "or" <A HREF="#prod61">logical_term</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod61">logical_term</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod62">logical_factor</A> ( "and" <A HREF="#prod62">logical_factor</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod62">logical_factor</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "not" )? <A HREF="#prod63">relation</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod63">relation</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod64">arithmetic_expression</A> ( <A HREF="#prod65">rel_op</A> <A HREF="#prod64">arithmetic_expression</A> )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod65">rel_op</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"&lt;"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"&lt;="</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"&gt;"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"&gt;="</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"=="</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"&lt;&gt;"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod64">arithmetic_expression</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod66">add_op</A> )? <A HREF="#prod67">term</A> ( <A HREF="#prod66">add_op</A> <A HREF="#prod67">term</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod66">add_op</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"+"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"-"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>".+"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>".-"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod67">term</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod68">factor</A> ( <A HREF="#prod69">mul_op</A> <A HREF="#prod68">factor</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod69">mul_op</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"*"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"/"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>".*"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"./"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod68">factor</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod70">primary</A> ( "^" | ".^" <A HREF="#prod70">primary</A> )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod70">primary</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;UNSIGNED_NUMBER&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;UNSIGNED_INTEGER&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;STRING&gt;</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"false"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"true"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod3">name</A> | "der" | "initial" ) <A HREF="#prod51">function_call_args</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod22">component_reference</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"(" <A HREF="#prod34">expression</A> ")"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"[" <A HREF="#prod23">expression_list</A> ( ";" <A HREF="#prod23">expression_list</A> )* "]"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"{" <A HREF="#prod71">function_arguments</A> "}"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"end"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod3">name</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "." )? &lt;IDENT&gt; ( "." &lt;IDENT&gt; )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod22">component_reference</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( "." )? &lt;IDENT&gt; ( <A HREF="#prod9">array_subscripts</A> )? ( "." &lt;IDENT&gt; ( <A HREF="#prod9">array_subscripts</A> )? )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod51">function_call_args</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"(" ( <A HREF="#prod71">function_arguments</A> )? ")"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod71">function_arguments</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod34">expression</A> ( "," <A HREF="#prod71">function_arguments</A> | "for" <A HREF="#prod57">for_indices</A> )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod72">named_arguments</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod72">named_arguments</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod73">named_argument</A> ( "," <A HREF="#prod72">named_arguments</A> )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod73">named_argument</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>&lt;IDENT&gt; "=" <A HREF="#prod34">expression</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod52">output_expression_list</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( <A HREF="#prod34">expression</A> )? ( "," ( <A HREF="#prod34">expression</A> )? )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod23">expression_list</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod34">expression</A> ( "," <A HREF="#prod34">expression</A> )*</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod9">array_subscripts</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"[" <A HREF="#prod74">subscript</A> ( "," <A HREF="#prod74">subscript</A> )* "]"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod74">subscript</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>":"</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>|</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod34">expression</A></TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod11">comment</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE><A HREF="#prod6">string_comment</A> ( <A HREF="#prod21">annotation</A> )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod6">string_comment</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>( &lt;STRING&gt; ( "+" &lt;STRING&gt; )* )?</TD>
+</TR>
+<TR>
+<TD ALIGN=RIGHT VALIGN=BASELINE><A NAME="prod21">annotation</A></TD>
+<TD ALIGN=CENTER VALIGN=BASELINE>::=</TD>
+<TD ALIGN=LEFT VALIGN=BASELINE>"annotation" <A HREF="#prod10">class_modification</A></TD>
+</TR>
+</TABLE>
+</BODY>
+</HTML>
diff --git a/1.8/org.simantics.sysdyn/adapters.xml b/1.8/org.simantics.sysdyn/adapters.xml
new file mode 100644 (file)
index 0000000..c01c1f8
--- /dev/null
@@ -0,0 +1,109 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<!--\r
+    Copyright (c) 2010 Association for Decentralized Information Management in\r
+    Industry THTH ry.\r
+    All rights reserved. This program and the accompanying materials\r
+    are made available under the terms of the Eclipse Public License v1.0\r
+    which accompanies this distribution, and is available at\r
+    http://www.eclipse.org/legal/epl-v10.html\r
+   \r
+    Contributors:\r
+        VTT Technical Research Centre of Finland - initial API and implementation\r
+ -->\r
+\r
+<adapters>    \r
+    <target\r
+        interface="org.simantics.simulation.model.IModel">\r
+        <type\r
+            uri="http://www.simantics.org/Sysdyn-0.0/SysdynModel"\r
+            class="org.simantics.sysdyn.manager.SysdynModel">\r
+            <this />\r
+        </type>\r
+    </target>\r
+    \r
+    <target\r
+        interface="org.simantics.sysdyn.adapter.distribution.IDistribution">\r
+        <type\r
+            uri="http://www.simantics.org/Sysdyn-0.0/NormalDistribution"\r
+            class="org.simantics.sysdyn.adapter.distribution.NormalDistribution">\r
+                       <graph/>           \r
+            <this />\r
+        </type>\r
+        <type\r
+            uri="http://www.simantics.org/Sysdyn-0.0/UniformDistribution"\r
+            class="org.simantics.sysdyn.adapter.distribution.UniformDistribution">\r
+                       <graph/>           \r
+            <this />\r
+        </type>   \r
+        <type\r
+            uri="http://www.simantics.org/Sysdyn-0.0/Interval"\r
+            class="org.simantics.sysdyn.adapter.distribution.Interval">\r
+                       <graph/>           \r
+            <this />\r
+        </type>\r
+    </target>\r
+    \r
+    <target\r
+        interface="org.simantics.sysdyn.adapter.generator.IGenerator">\r
+        <type\r
+            uri="http://www.simantics.org/Sysdyn-0.0/RandomGenerator"\r
+            class="org.simantics.sysdyn.adapter.generator.RandomGenerator">\r
+                       <graph/>           \r
+            <this />\r
+        </type>\r
+        <type\r
+            uri="http://www.simantics.org/Sysdyn-0.0/HaltonSequenceGenerator"\r
+            class="org.simantics.sysdyn.adapter.generator.HaltonSequenceGenerator">\r
+                       <graph/>           \r
+            <this />\r
+        </type>\r
+    </target>\r
+    \r
+   <target\r
+        interface="org.simantics.sysdyn.adapter.SensitivityExperimentParameter">\r
+        <type\r
+            uri="http://www.simantics.org/Sysdyn-0.0/SensitivityAnalysisExperiment/Parameter"\r
+            class="org.simantics.sysdyn.adapter.SensitivityExperimentParameter">\r
+                       <graph/>           \r
+            <this />\r
+        </type>\r
+       </target>        \r
+    \r
+<!--   <target interface="org.simantics.db.layer0.variable.Variable">\r
+               <type uri="http://www.simantics.org/Sysdyn-0.0/Configuration"\r
+                       class="org.simantics.sysdyn.adapter.ConfigurationVariable" >\r
+                       <this />\r
+               </type>\r
+               <type uri="http://www.simantics.org/Simulation-0.0/Run"\r
+                       class="org.simantics.sysdyn.adapter.RunVariable" >\r
+                       <this />\r
+               </type>\r
+       </target>-->\r
+    \r
+       <!-- \r
+       <target interface="org.simantics.db.layer0.variable.Variable">\r
+\r
+               <adapter uri="http://www.simantics.org/Sysdyn-0.0/Configuration"\r
+                       contextClass="org.simantics.db.layer0.variable.Variable"\r
+                       adapterClass="org.simantics.sysdyn.adapter.ConfigurationVariableAdapter"/>\r
+               <adapter uri="http://www.simantics.org/Sysdyn-0.0/Variable"\r
+                       contextClass="org.simantics.db.layer0.variable.Variable"\r
+                       adapterClass="org.simantics.sysdyn.adapter.ChildVariableAdapter"/>\r
+               <adapter uri="http://www.simantics.org/Sysdyn-0.0/Module"\r
+                       contextClass="org.simantics.db.layer0.variable.Variable"\r
+                       adapterClass="org.simantics.sysdyn.adapter.ChildVariableAdapter"/>\r
+               <adapter uri="http://www.simantics.org/Simulation-0.0/Run"\r
+                       contextClass="org.simantics.db.layer0.variable.Variable"\r
+                       adapterClass="org.simantics.sysdyn.adapter.RunVariableAdapter"/>\r
+       </target>\r
+       -->\r
+\r
+    <target\r
+        interface="org.simantics.db.layer0.migration.MigrationStep">\r
+        <resource\r
+            uri="http://www.simantics.org/Sysdyn-0.0/Migration/from1.6to1.7/Custom"\r
+            class="org.simantics.sysdyn.adapter.CustomMigrationStep">\r
+        </resource>\r
+    </target>\r
+    \r
+</adapters>
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/build.properties b/1.8/org.simantics.sysdyn/build.properties
new file mode 100644 (file)
index 0000000..26e468c
--- /dev/null
@@ -0,0 +1,18 @@
+###############################################################################\r
+# Copyright (c) 2010 Association for Decentralized Information Management in\r
+# Industry THTH ry.\r
+# All rights reserved. This program and the accompanying materials\r
+# are made available under the terms of the Eclipse Public License v1.0\r
+# which accompanies this distribution, and is available at\r
+# http://www.eclipse.org/legal/epl-v10.html\r
+#\r
+# Contributors:\r
+#     VTT Technical Research Centre of Finland - initial API and implementation\r
+###############################################################################\r
+source.. = src/\r
+output.. = bin/\r
+bin.includes = META-INF/,\\r
+               .,\\r
+               adapters.xml,\\r
+               plugin.xml,\\r
+               scl/\r
diff --git a/1.8/org.simantics.sysdyn/plugin.xml b/1.8/org.simantics.sysdyn/plugin.xml
new file mode 100644 (file)
index 0000000..e3c4447
--- /dev/null
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<?eclipse version="3.4"?>\r
+<plugin>\r
+\r
+   <extension point="org.simantics.scl.reflection.binding">\r
+      <namespace path="http://www.simantics.org/Sysdyn-1.1/Functions">\r
+         <externalClass className="org.simantics.db.Resource"/>\r
+         <externalClass className="org.simantics.db.ReadGraph"/>\r
+         <externalClass className="org.simantics.db.WriteGraph"/>\r
+         <externalClass className="org.simantics.db.Issue"/>\r
+         <externalClass className="org.simantics.databoard.binding.Binding"/>\r
+         <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
+         <externalClass className="org.simantics.db.layer0.variable.ValueAccessor"/>\r
+         <externalClass className="org.simantics.db.layer0.variable.VariableMap"/>\r
+         <class className="org.simantics.sysdyn.Functions"/>\r
+      </namespace>\r
+   </extension>\r
+   <extension\r
+         point="org.simantics.scl.runtime.package">\r
+      <package\r
+            URI="Simantics"\r
+            directory="scl">\r
+      </package>\r
+   </extension>\r
+\r
+</plugin>\r
diff --git a/1.8/org.simantics.sysdyn/scl/Sysdyn.scl b/1.8/org.simantics.sysdyn/scl/Sysdyn.scl
new file mode 100644 (file)
index 0000000..12e7ef7
--- /dev/null
@@ -0,0 +1,108 @@
+include "UI/Progress"\r
+include "Simantics/DB"\r
+include "Simantics/Variables"\r
+\r
+importJava "org.simantics.sysdyn.utils.DocumentationUtils" where\r
+\r
+    @JavaName getModules\r
+    getModules :: Variable -> <ReadGraph> [Resource]\r
+    \r
+    @JavaName getExperimentVariables\r
+    getExperimentVariables :: Variable -> <ReadGraph> [Variable]\r
+    \r
+    @JavaName getRoleVariables\r
+    getRoleVariables :: Variable -> <ReadGraph> [Variable]    \r
+\r
+    @JavaName getDocumentVariables\r
+    getDocumentVariables :: Variable -> <ReadGraph> [Variable]    \r
+\r
+    @JavaName getIndexDocuments\r
+    getIndexDocuments :: Variable -> <ReadGraph> [Variable]    \r
+    \r
+    @JavaName getResultVariables\r
+    getResultVariables :: Variable -> <ReadGraph> [Variable]  \r
+    \r
+    @JavaName getConfiguration\r
+    getConfiguration :: Resource -> <ReadGraph> Resource\r
+    \r
+    @JavaName getConfigurationVariables\r
+    getConfigurationVariables :: Resource -> <ReadGraph> [Resource]\r
+    \r
+    @JavaName getName\r
+    getName :: Resource -> <ReadGraph> String\r
+    \r
+    @JavaName getType\r
+    getType :: Resource -> <ReadGraph> String\r
+\r
+    @JavaName getUnit\r
+    getUnit :: Resource -> <ReadGraph> String\r
+\r
+    @JavaName getVariability\r
+    getVariability :: Resource -> <ReadGraph> String    \r
+    \r
+    @JavaName getDescription\r
+    getDescription :: Resource -> <ReadGraph> String\r
+    \r
+    @JavaName getDocumentationDefinition\r
+    getDocumentationDefinition :: Resource -> <ReadGraph> String\r
+    \r
+    \r
+    \r
+    @JavaName numberOfVariables\r
+    numberOfVariables :: Resource -> Boolean -> <ReadGraph> Integer\r
+\r
+    @JavaName totalNumberOfVariables\r
+    totalNumberOfVariables :: Resource -> Boolean -> <ReadGraph> Integer\r
+    \r
+    @JavaName numberOfStocks\r
+    numberOfStocks :: Resource -> Boolean -> <ReadGraph> Integer\r
+    \r
+    @JavaName numberOfValves\r
+    numberOfValves :: Resource -> Boolean -> <ReadGraph> Integer\r
+    \r
+    @JavaName numberOfInputs\r
+    numberOfInputs :: Resource -> Boolean -> <ReadGraph> Integer\r
+    \r
+    @JavaName numberOfShadows\r
+    numberOfShadows :: Resource -> Boolean -> <ReadGraph> Integer\r
+    \r
+    @JavaName numberOfAuxiliaries\r
+    numberOfAuxiliaries :: Resource -> Boolean -> <ReadGraph> Integer\r
+    \r
+    @JavaName numberOfModules\r
+    numberOfModules :: Resource -> Boolean -> <ReadGraph> Integer\r
+    \r
+    @JavaName numberOfSheets\r
+    numberOfSheets :: Resource -> Boolean -> <ReadGraph> Integer\r
+    \r
+    @JavaName numberOfModuleTypes\r
+    numberOfModuleTypes :: Variable -> <ReadGraph> Integer\r
+   \r
+    @JavaName base64Encode\r
+    base64Encode :: Variable -> String -> <ReadGraph> String \r
+    \r
+    @JavaName formatDate\r
+    formatDate :: Long -> <ReadGraph> String \r
+    \r
+    @JavaName importModel\r
+    importModel :: String -> <Proc> Resource\r
+    \r
+    @JavaName isParameter\r
+    isParameter :: Variable -> <ReadGraph> Boolean\r
+\r
+    lastValue :: Resource -> String -> String -> Double\r
+    lastValue2 :: Variable -> String -> <ReadGraph> Variable\r
+    lastValueIndexed :: Variable -> String -> <ReadGraph> Variable\r
+    equation :: Variable -> String -> <ReadGraph> Variable\r
+\r
+importJava "org.simantics.sysdyn.manager.SysdynExperiments" where\r
+    \r
+    activateExperiment :: Resource -> String\r
+    run :: String -> ()\r
+    saveIC :: Variable -> String -> <WriteGraph> Maybe Resource\r
+    assignIC :: Variable -> String -> <WriteGraph> ()\r
+    deassignIC :: Variable -> <WriteGraph> ()\r
+    applyIC :: Variable -> String -> <WriteGraph> ()\r
+    deleteIC :: Variable -> String -> <WriteGraph> ()\r
+\r
+    
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/Activator.java
new file mode 100644 (file)
index 0000000..640c85f
--- /dev/null
@@ -0,0 +1,64 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn;\r
+\r
+import java.io.File;\r
+\r
+import org.osgi.framework.BundleActivator;\r
+import org.osgi.framework.BundleContext;\r
+\r
+public class Activator implements BundleActivator {\r
+\r
+    private static BundleContext bundleContext;\r
+    \r
+    // The plug-in ID\r
+    public static final String PLUGIN_ID = "org.simantics.sysdyn";\r
+    \r
+    // The shared instance\r
+    private static Activator plugin;\r
+    \r
+    @Override\r
+    public void start(BundleContext context) throws Exception {\r
+        bundleContext = context;\r
+        File modelsDir = Activator.getBundleContext().getDataFile("models");\r
+        if (!modelsDir.exists()) {\r
+            modelsDir.mkdir();\r
+        }\r
+        plugin = this;\r
+    }\r
+\r
+    @Override\r
+    public void stop(BundleContext context) throws Exception {\r
+        File modelsDir = Activator.getBundleContext().getDataFile("models");\r
+        if (modelsDir.exists()) {\r
+            recursiveDelete(modelsDir);\r
+        }\r
+        plugin = null;\r
+\r
+    }\r
+\r
+    public static Activator getDefault() {\r
+        return plugin;\r
+    }\r
+\r
+    public static BundleContext getBundleContext() {\r
+        return bundleContext;\r
+    }\r
+    \r
+    private static boolean recursiveDelete(File fileOrDir) {\r
+        if(fileOrDir.isDirectory())\r
+            for(File innerFile: fileOrDir.listFiles())\r
+                if(!recursiveDelete(innerFile))\r
+                    return false;\r
+        return fileOrDir.delete();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/Functions.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/Functions.java
new file mode 100644 (file)
index 0000000..04c2b62
--- /dev/null
@@ -0,0 +1,269 @@
+package org.simantics.sysdyn;\r
+\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.Binding;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ResourceRead;\r
+import org.simantics.db.common.uri.UnescapedChildMapOfResource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.function.All;\r
+import org.simantics.db.layer0.variable.StandardGraphChildVariable;\r
+import org.simantics.db.layer0.variable.ValueAccessor;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.VariableMap;\r
+import org.simantics.db.layer0.variable.VariableMapImpl;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.scl.reflection.annotations.SCLValue;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.adapter.ActiveDatasetsIndexVariable;\r
+import org.simantics.sysdyn.adapter.NamesIndexVariable;\r
+import org.simantics.sysdyn.adapter.TimeIndexVariable;\r
+import org.simantics.sysdyn.adapter.TimesIndexVariable;\r
+import org.simantics.sysdyn.adapter.ValueIndexVariable;\r
+import org.simantics.sysdyn.adapter.ValueIndexVariableI;\r
+import org.simantics.sysdyn.adapter.ValuesIndexVariable;\r
+\r
+public class Functions {\r
+       \r
+       public static String VALUE = "value";\r
+       public static String VALUES = "values";\r
+       public static String TIME = "time";\r
+       public static String TIMES = "times";\r
+       public static String NAMES = "names";   \r
+       public static String ACTIVE_DATASETS = "activeDatasets";                \r
+       \r
+    @SCLValue(type = "ValueAccessor")\r
+       public static ValueAccessor valuePropertyValue = new ValueAccessor() {\r
+\r
+               @Override\r
+               public Object getValue(ReadGraph graph, Variable context)\r
+                               throws DatabaseException {\r
+                       // TODO Auto-generated method stub\r
+                       return null;\r
+               }\r
+\r
+               @Override\r
+               public Object getValue(ReadGraph graph, Variable context,\r
+                               Binding binding) throws DatabaseException {\r
+                       // TODO Auto-generated method stub\r
+                       return null;\r
+               }\r
+\r
+               @Override\r
+               public void setValue(WriteGraph graph, Variable context, Object value)\r
+                               throws DatabaseException {\r
+                       // TODO Auto-generated method stub\r
+                       \r
+               }\r
+\r
+               @Override\r
+               public void setValue(WriteGraph graph, Variable context, Object value,\r
+                               Binding binding) throws DatabaseException {\r
+                       // TODO Auto-generated method stub\r
+                       \r
+               }\r
+       \r
+       };\r
+\r
+    @SCLValue(type = "ValueAccessor")\r
+       public static ValueAccessor equationPropertyValue = new ValueAccessor() {\r
+\r
+               @Override\r
+               public Object getValue(ReadGraph graph, Variable context) throws DatabaseException {\r
+                       return getValue(graph, context, Bindings.STRING);\r
+               }\r
+\r
+               @Override\r
+               public Object getValue(ReadGraph graph, Variable context, Binding binding) throws DatabaseException {\r
+                       \r
+                       Variable v = context.getParent(graph);\r
+                       \r
+                       Resource represents = v.getPossibleRepresents(graph);\r
+                       if(represents != null) {\r
+                               SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+                               Collection<Resource> res = ListUtils.toList(graph, graph.getSingleObject(represents, SYSDYN.Variable_expressionList));\r
+                               if(res.size() == 1) {\r
+                                       Resource exp = res.iterator().next();\r
+                                       String text = graph.getRelatedValue(exp, SYSDYN.Expression_equation, Bindings.STRING);\r
+                                       return text;\r
+                               }\r
+                       }\r
+\r
+                       return null;\r
+                       \r
+               }\r
+\r
+               @Override\r
+               public void setValue(WriteGraph graph, Variable context, Object value) throws DatabaseException {\r
+                       \r
+                       if(value instanceof Variant) value = ((Variant)value).getValue();\r
+                       \r
+                       if(!(value instanceof String)) throw new DatabaseException("Unexpected value " + value + ", expected String");\r
+                       \r
+                       setValue(graph, context, value, Bindings.STRING);\r
+                       \r
+               }\r
+\r
+               @Override\r
+               public void setValue(WriteGraph graph, Variable context, Object value, Binding binding) throws DatabaseException {\r
+                       \r
+                       if(value instanceof Variant) value = ((Variant)value).getValue();\r
+                       \r
+                       if(!(value instanceof String)) throw new DatabaseException("Unexpected value " + value + ", expected String");\r
+\r
+                       Variable v = context.getParent(graph);\r
+                       \r
+                       Resource represents = v.getPossibleRepresents(graph);\r
+                       if(represents != null) {\r
+                               SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+                               Collection<Resource> res = ListUtils.toList(graph, graph.getSingleObject(represents, SYSDYN.Variable_expressionList));\r
+                               if(res.size() == 1) {\r
+                                       Resource exp = res.iterator().next();\r
+                                       graph.claimLiteral(exp, SYSDYN.Expression_equation, value, Bindings.STRING);\r
+                               }\r
+                       }\r
+                       \r
+               }\r
+       \r
+       };\r
+       \r
+\r
+       @SCLValue(type = "VariableMap")\r
+       public static VariableMap runProperties = new VariableMapImpl() {\r
+\r
+           @Override\r
+           public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {\r
+\r
+               String property = context.getName(graph);\r
+               if(TIME.equals(property))\r
+                   return new TimeIndexVariable(graph, context, name);\r
+               else\r
+                   return null;\r
+           }\r
+\r
+           @Override\r
+           public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {\r
+               return map;\r
+           }\r
+       };\r
+\r
+    @SCLValue(type = "VariableMap")\r
+       public static VariableMap valuePropertyProperties = new VariableMapImpl() {\r
+       \r
+               @Override\r
+               public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {\r
+                       \r
+                       String property = context.getName(graph);\r
+                       if(VALUE.equals(property))\r
+                               if(name.startsWith("$")) {\r
+                                       Integer index = Integer.parseInt(name.substring(1));\r
+                                       return new ValueIndexVariableI(graph, context, index);\r
+                               } else {\r
+                                       return new ValueIndexVariable(graph, context, name);\r
+                               }\r
+                       else if(VALUES.equals(property))\r
+                               return new ValuesIndexVariable(graph, context, name);\r
+                       else if(TIMES.equals(property))\r
+                               return new TimesIndexVariable(graph, context, name);\r
+            else if(TIME.equals(property))\r
+                return new TimeIndexVariable(graph, context, name);                    \r
+                       else if(NAMES.equals(property))\r
+                               return new NamesIndexVariable(graph, context, name);\r
+                       else if(ACTIVE_DATASETS.equals(property))\r
+                               return new ActiveDatasetsIndexVariable(graph, context, name);\r
+                       else\r
+                               return null;\r
+               }\r
+\r
+               @Override\r
+               public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {\r
+                   return map;\r
+//                     Collections.emptyList();\r
+//             StandardGraphChildVariable variable = (StandardGraphChildVariable)context;\r
+//             collectPropertiesFromContext(graph, variable, variable.resource, map);\r
+               }\r
+               \r
+       };\r
+       \r
+       \r
+       @SCLValue(type = "VariableMap")\r
+       public static VariableMap runChildren = new VariableMapImpl() {\r
+       \r
+               @Override\r
+               public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {\r
+                       StandardGraphChildVariable variable = (StandardGraphChildVariable)context;\r
+                       Map<String, Resource> children = graph.syncRequest(new StructuralChildMapOfResource(getConfiguration(graph, variable)));\r
+                       Resource child = children.get(name);\r
+                       if(child == null) return All.getStandardChildDomainChildVariable(graph, context, name);\r
+                       return graph.getPossibleContextualAdapter(child, variable, Variable.class, Variable.class);\r
+               }\r
+\r
+               @Override\r
+               public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {\r
+                   \r
+                       StandardGraphChildVariable variable = (StandardGraphChildVariable)context;\r
+                       \r
+                       map = All.getStandardChildDomainChildVariables(graph, context, map);\r
+                       \r
+                       for(Map.Entry<String, Resource> entry : graph.syncRequest(new StructuralChildMapOfResource(getConfiguration(graph, variable))).entrySet()) {\r
+                               String name = entry.getKey();\r
+                               Resource child = entry.getValue();\r
+                               Variable var = graph.getPossibleContextualAdapter(child, variable, Variable.class, Variable.class);\r
+                               if(var != null) {\r
+                           if(map == null) map = new HashMap<String,Variable>();\r
+                                       map.put(name, var);\r
+                               } else {\r
+                                       System.err.println("No adapter for " + child + " in " + variable.getURI(graph));\r
+                               }\r
+                       }\r
+                       \r
+                       return map;\r
+                       \r
+               }\r
+               \r
+               Resource getConfiguration(ReadGraph graph, Variable run) throws DatabaseException {\r
+                       Layer0 L0 = Layer0.getInstance(graph);\r
+                       Layer0X L0X = Layer0X.getInstance(graph);\r
+                       Resource experiment = graph.getPossibleObject(run.getRepresents(graph), L0.PartOf);\r
+                       Resource model = graph.getPossibleObject(experiment, L0.PartOf);\r
+                       return graph.getPossibleObject(model, L0X.HasBaseRealization);\r
+               }\r
+               \r
+       };\r
+       \r
+       \r
+       static class StructuralChildMapOfResource extends ResourceRead<Map<String, Resource>> {\r
+\r
+               public StructuralChildMapOfResource(Resource resource) {\r
+                       super(resource);\r
+               }\r
+\r
+               @Override\r
+               public Map<String, Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                       \r
+                       StructuralResource2 STR = StructuralResource2.getInstance(graph);\r
+                       Map<String, Resource> directChildren = graph.syncRequest(new UnescapedChildMapOfResource(resource));\r
+                       Resource type = graph.getPossibleType(resource, STR.Component);\r
+                       if(type != null) {\r
+                               Resource definition = graph.getPossibleObject(type, STR.IsDefinedBy);\r
+                               if(definition != null) {\r
+                                       return graph.syncRequest(new UnescapedChildMapOfResource(definition));\r
+                               }\r
+                       }\r
+\r
+                       return directChildren;\r
+                               \r
+               }\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/TestParser.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/TestParser.java
new file mode 100644 (file)
index 0000000..86b3245
--- /dev/null
@@ -0,0 +1,233 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn;\r
+\r
+import java.io.StringReader;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.ParseException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.UnitParser;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+public class TestParser {\r
+    \r
+    /**\r
+     * @param args\r
+     */\r
+    public static void main(String[] args) {\r
+\r
+        HashMap<String, String> units = new HashMap<String, String>();\r
+        boolean allowEquivalents = true;\r
+        \r
+        doScenario(scenario1(units), units, allowEquivalents);\r
+        doScenario(scenario2(units), units, allowEquivalents);\r
+        doScenario(scenario3(units), units, allowEquivalents);\r
+        doScenario(scenario4(units), units, allowEquivalents);\r
+        doScenario(scenario5(units), units, allowEquivalents);\r
+        doScenario(scenario6(units), units, allowEquivalents);\r
+        doScenario(scenario7(units), units, allowEquivalents);\r
+        doScenario(scenario8(units), units, allowEquivalents);\r
+        doScenario(scenario9(units), units, allowEquivalents);\r
+        doScenario(scenario10(units), units, allowEquivalents);\r
+        doScenario(scenario11(units), units, allowEquivalents);\r
+        doScenario(scenario12(units), units, allowEquivalents);\r
+        doScenario(scenario13(units), units, allowEquivalents);\r
+\r
+    }\r
+    \r
+    private static void doScenario(String expression, HashMap<String, String> units, boolean allowEquivalents) {\r
+        System.out.println("-----------------------------------");\r
+        System.out.println("Expression: " + expression);\r
+        System.out.println("Units: ");\r
+        for(String key : units.keySet()) {\r
+            System.out.println("   " + key + " -> " + units.get(key));\r
+        }\r
+        StringReader sr = new StringReader(expression);\r
+        UnitParser parser = new UnitParser(sr);\r
+        try {\r
+            UnitCheckingNode node = (UnitCheckingNode) parser.expr();\r
+            \r
+            try {\r
+                UnitResult u = node.getUnits(units, Function.getAllBuiltInFunctions(), allowEquivalents);\r
+                System.out.println("Result: " + u.getCleanFullUnit());\r
+            } catch (UnitCheckingException e) {\r
+                e.printStackTrace();\r
+            }\r
+            \r
+//            node.dump("");\r
+        } catch (ParseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    private static String scenario1(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m");\r
+        units.put("b", "m");\r
+        units.put("c", "m");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("a*b*c");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario2(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m");\r
+        units.put("b", "m");\r
+        units.put("c", "m");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("a+b+c");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario3(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m");\r
+        units.put("b", "m");\r
+        units.put("c", "m");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("a/b+b/c");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario4(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m");\r
+        units.put("b", "m");\r
+        units.put("c", "m");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("if a == b then a+b else b + c + a");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario5(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m");\r
+        units.put("b", "s");\r
+        units.put("c", "m");\r
+        units.put("d", "s");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+//        sb.append("a / b + (c*a)/(b*a)");\r
+        sb.append("c/(b*a)");\r
+\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario6(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m");\r
+        units.put("b", "s");\r
+        units.put("c", "m");\r
+        units.put("d", "m/s");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("if a > c then c*a/b else a*d");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario7(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m/s");\r
+        units.put("b.e", "s");\r
+        units.put("c", "m");\r
+        units.put("d", "s");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("a[1] + c[1] / b.e[1]");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario8(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m");\r
+        units.put("b", "s");\r
+        units.put("c", "s*m");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("c + {a[i] * b[i] for i in 1:3}");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario9(HashMap<String, String> units) {\r
+        units.clear();\r
+        units.put("a", "m");\r
+        units.put("b", "m");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("1+a+1+b");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario10(HashMap<String, String> units) {\r
+        units.clear();\r
+        units.put("a", "m");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("1*a*1*a");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario11(HashMap<String, String> units) {\r
+        units.clear();\r
+        units.put("a", "m");\r
+        units.put("b", "m");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("-a+b");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario12(HashMap<String, String> units) {\r
+        units.clear();\r
+        units.put("a", "m");\r
+        units.put("b", "s");\r
+        units.put("c", "m/s");\r
+\r
+\r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("1/a/b + 1/c");\r
+        return sb.toString();\r
+    }\r
+    \r
+    private static String scenario13(HashMap<String, String> units) {\r
+        units.clear();\r
+        \r
+        units.put("a", "m");\r
+        units.put("b", "m");\r
+        units.put("c", "m");\r
+        units.put("d", "s");\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("(a/b+b/c)/d");\r
+        return sb.toString();\r
+    }\r
+    \r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ActiveDatasetsIndexVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ActiveDatasetsIndexVariable.java
new file mode 100644 (file)
index 0000000..4b57b97
--- /dev/null
@@ -0,0 +1,56 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.modelica.data.DataSet;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.manager.SysdynResult;\r
+\r
+public class ActiveDatasetsIndexVariable extends IndexVariable< ArrayList<DataSet>> {\r
+\r
+       public ActiveDatasetsIndexVariable(ReadGraph graph, Variable parent, String indexes)\r
+                       throws DatabaseException {\r
+               super(graph, parent, indexes);\r
+       }\r
+\r
+       @Override\r
+       public  ArrayList<DataSet> getValue() {\r
+               ArrayList<DataSet> datasets = new ArrayList<DataSet>();\r
+\r
+               if(experiment == null)\r
+                       return datasets;\r
+\r
+               Collection<SysdynResult> results = experiment.getActiveResults();\r
+               ArrayList<String> variableNamesWithIndexes = getVariableNamesWithIndexNumbers();\r
+               ArrayList<String> variableNames = getVariableNames();\r
+\r
+               for(int i = 0; i < variableNamesWithIndexes.size(); i++) {\r
+                       for(SysdynResult result : results) {\r
+                               SysdynDataSet ds = result.getDataSet(variableNamesWithIndexes.get(i));\r
+                               if(ds != null) {\r
+                                       // NOTE: this method was changed to no longer remove\r
+                                       // remove enumeration indices from variable names as it\r
+                                       // seems unnecessary and makes different instances of the\r
+                                       // same variable with different enumeration indices\r
+                                       // indistinguishable from each other in simulation results\r
+                                       ds.name = variableNames.get(i);\r
+\r
+                                       datasets.add(ds);\r
+                               }\r
+                       }\r
+               }\r
+               return datasets;\r
+       }\r
+\r
+       @Override\r
+       public void setIndexedValue(WriteGraph graph, Object value)\r
+                       throws DatabaseException {\r
+\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/CustomMigrationStep.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/CustomMigrationStep.java
new file mode 100644 (file)
index 0000000..dce49fa
--- /dev/null
@@ -0,0 +1,58 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.migration.MigrationState;\r
+import org.simantics.db.layer0.migration.MigrationStateKeys;\r
+import org.simantics.db.layer0.migration.MigrationStep;\r
+import org.simantics.db.layer0.util.Layer0Utils;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+\r
+public class CustomMigrationStep implements MigrationStep {\r
+\r
+       @Override\r
+       public void applyTo(IProgressMonitor monitor, Session session, MigrationState state) throws DatabaseException {\r
+               \r
+               final Resource res = state.getProperty(MigrationStateKeys.CURRENT_RESOURCE);\r
+               \r
+               session.syncRequest(new WriteRequest() {\r
+\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+\r
+                               for(Resource model : graph.syncRequest(new ObjectsWithType(res, l0.ConsistsOf, SIMU.Model))) {\r
+\r
+                                       Resource sheetExperiment = Layer0Utils.getPossibleChild(graph, model, "SheetExperiment");\r
+                                       if(sheetExperiment != null) return;\r
+       \r
+                                       SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);\r
+                                       sheetExperiment = GraphUtils.create2(graph, SHEET.Experiment,\r
+                                                       l0.HasName, "SheetExperiment",\r
+                                                       l0.HasLabel, "Sheet Experiment",\r
+                                                       l0.PartOf, model);\r
+       \r
+                                       Resource sheetRun = GraphUtils.create2(graph, SHEET.Run,\r
+                                                       l0.HasName, "Default",\r
+                                                       l0.PartOf, sheetExperiment);\r
+                                                       \r
+\r
+                               }\r
+                               \r
+                       }\r
+                       \r
+               });\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/IndexVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/IndexVariable.java
new file mode 100644 (file)
index 0000000..cfd243e
--- /dev/null
@@ -0,0 +1,272 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.Binding;\r
+import org.simantics.databoard.type.Datatype;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ParametrizedPrimitiveRead;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.AbstractPropertyVariable;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.ExternalRead;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.manager.VariableSubscriptionManager;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public abstract class IndexVariable<T> extends AbstractPropertyVariable {\r
+\r
+       protected Variable parent;\r
+       protected SysdynModel model;\r
+       protected SysdynExperiment experiment;\r
+       protected String rvi;\r
+       protected HashMap<String, String> rvis;\r
+       protected String indexes;\r
+       protected VariableSubscriptionManager subscriptionManager;\r
+       \r
+       public IndexVariable(ReadGraph graph, Variable parent, String indexes) throws DatabaseException {\r
+               this.parent = parent;\r
+               this.indexes = indexes;\r
+       }\r
+       \r
+       \r
+       protected VariableSubscriptionManager getSubscriptionManager() {\r
+               return this.experiment;\r
+       }\r
+\r
+       public String getIndexes() {\r
+               return this.indexes;\r
+       }\r
+\r
+    /**\r
+     * Register a property subscription\r
+     * \r
+     * @param request PropertyRequest\r
+     * @param procedure \r
+     * @return\r
+     */\r
+       protected VariableValueSubscription<T> registerSubscription(ExternalRead<?> request, Listener<T> procedure) {\r
+           // Other properties are requested from model (they listen to new simulation results)\r
+           VariableValueSubscription<T> subscription = new VariableValueSubscription<T>(request, this, procedure);\r
+           if(subscriptionManager != null) {\r
+               subscriptionManager.addVariableValueSubscription(subscription);\r
+           }\r
+        subscription.update();\r
+           return subscription;\r
+       }\r
+\r
+    /**\r
+     * Unregisters a subscription\r
+     * @param subscription\r
+     */\r
+       protected void unregisterSubscription(VariableValueSubscription<T> subscription) {\r
+               subscription.setListener(null);\r
+               if(subscriptionManager != null)\r
+                   subscriptionManager.removeVariableValueSubscription(subscription);\r
+       }\r
+       \r
+       \r
+\r
+    /**\r
+     * Class for supporting requests with different property parameters. Equals-method has been modified \r
+     * from ParametrizedPrivimiteRead to check also the property value.\r
+     * \r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    class PropertyRequest extends ParametrizedPrimitiveRead<Variable, T> {\r
+\r
+\r
+        public PropertyRequest(Variable indexVariable) {\r
+            super(indexVariable);\r
+        }\r
+\r
+        VariableValueSubscription<T> subscription;\r
+\r
+        @Override\r
+        public void register(ReadGraph graph, Listener<T> procedure) {\r
+            subscription = registerSubscription(this, procedure);\r
+        }\r
+        @Override\r
+        public void unregistered() {\r
+            if(subscription != null) {\r
+                unregisterSubscription(subscription);\r
+                subscription = null;\r
+            }\r
+        }\r
+\r
+        @SuppressWarnings("unchecked")\r
+               @Override\r
+        public boolean equals(Object object) {\r
+            if(object instanceof IndexVariable.PropertyRequest && super.equals(object)) {\r
+                return this.parameter.equals(((PropertyRequest)object).parameter);\r
+            } else {\r
+                return super.equals(object);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+       @Override\r
+       public Resource getPropertyResource(ReadGraph graph) throws DatabaseException {\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public Resource getContainerResource(ReadGraph graph) throws DatabaseException {\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public Datatype getDatatype(ReadGraph graph) throws DatabaseException {\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public Variable getPredicate(ReadGraph graph) throws DatabaseException {\r
+               return null;\r
+       }\r
+\r
+       @SuppressWarnings("unchecked")\r
+       @Override\r
+       public <U> U getValue(ReadGraph graph) throws DatabaseException {\r
+               return (U) getValue(graph, Bindings.DOUBLE);\r
+       }\r
+\r
+       @SuppressWarnings("unchecked")\r
+       @Override\r
+       public <U> U getValue(ReadGraph graph, Binding binding) throws DatabaseException {\r
+        ensureInformationAvailable(graph);\r
+               // Do something before request, e.g. calculate some variables used in the request\r
+               beforeRequest(graph);\r
+        \r
+        return (U) graph.syncRequest(new PropertyRequest(this));\r
+        \r
+       }\r
+       \r
+       protected void beforeRequest(ReadGraph graph) throws DatabaseException {\r
+\r
+       }\r
+       \r
+       protected void ensureInformationAvailable(ReadGraph graph) throws DatabaseException {\r
+               SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+               ModelingResources MOD = ModelingResources.getInstance(graph);\r
+               \r
+        if(model == null) {\r
+            Resource modelResource = Variables.getModel(graph, parent);\r
+            Resource configuration = graph.getPossibleObject(modelResource, SIMU.HasConfiguration);\r
+            model = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, configuration);\r
+        }\r
+        \r
+        Variable var = parent.getParent(graph);\r
+        Resource represents = var.getRepresents(graph);\r
+        \r
+        Resource activeRun = null;\r
+        if(represents != null) {\r
+            do {\r
+                if(graph.isInstanceOf(represents, SIMU.Run)) {\r
+                    activeRun = represents;\r
+                    break;\r
+                }\r
+                var = var.getParent(graph);\r
+                represents = var.getRepresents(graph);\r
+            } while(represents != null && !graph.isInstanceOf(represents, MOD.StructuralModel));\r
+        }\r
+\r
+        IProject project = Simantics.peekProject();\r
+        if(activeRun != null && project != null) {\r
+            IExperimentManager expMan = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+               IExperiment e = expMan.getExperiment(NameUtils.getSafeName(graph, activeRun));\r
+               if(e instanceof SysdynExperiment)\r
+                       this.experiment = (SysdynExperiment)e;\r
+        }\r
+        \r
+        this.subscriptionManager = getSubscriptionManager();\r
+               rvi =  Variables.getPossibleRVI(graph, this);\r
+               if(rvi != null)\r
+                   rvis = VariableRVIUtils.getActiveRVIs(graph, parent.getParent(graph));      \r
+       }\r
+       \r
+       private Pair<ArrayList<String>,ArrayList<String>> getVariableNameArrays() {\r
+               Pair<ArrayList<String>,ArrayList<String>> result = new Pair<ArrayList<String>,ArrayList<String>>(new ArrayList<String>(), new ArrayList<String>());\r
+               if(rvi == null || rvis == null)\r
+                   return result;\r
+               \r
+        if(rvi.indexOf('#') > 0)\r
+               rvi = rvi.substring(0, rvi.indexOf('#'));\r
+        \r
+        String test = rvi;\r
+        if(indexes != null && !indexes.isEmpty()) {\r
+               String regexIndexes = indexes.trim().replaceAll("\\b_\\b", "[a-zA-Z0-9_]*"); // Why was there was ".replace('.', ',')" ? - Removed by Teemu 2.9.2012\r
+               test = rvi + "\\[" + regexIndexes + "\\]";\r
+        } else {\r
+               test = rvi + "(\\[.*\\])?";\r
+        }\r
+        for(String k : rvis.keySet()) {\r
+               String value = rvis.get(k);\r
+               if(k.matches(test) || value.matches(test)) {\r
+                       result.first.add(k.substring(1).replace("/", ".").replace("%20", "_"));\r
+                       result.second.add(value.substring(1).replace("/", ".").replace("%20", " "));\r
+               }\r
+        }\r
+        \r
+        return result;\r
+               \r
+       }\r
+       \r
+       protected ArrayList<String> getVariableNames() {\r
+               return getVariableNameArrays().second;\r
+       }\r
+       \r
+       protected ArrayList<String> getVariableNamesWithIndexNumbers() {\r
+               return getVariableNameArrays().first;\r
+       }\r
+       \r
+       abstract public T getValue();\r
+\r
+       @Override\r
+       public void setValue(WriteGraph graph, Object value, Binding binding) throws DatabaseException {\r
+           setValue(graph, value);\r
+       }\r
+       \r
+       @Override\r
+       public void setValue(WriteGraph graph, Object value) throws DatabaseException {\r
+           ensureInformationAvailable(graph);\r
+               setIndexedValue(graph, value);\r
+       }\r
+\r
+       abstract protected void setIndexedValue(WriteGraph graph, Object value) throws DatabaseException;\r
+       \r
+\r
+\r
+       @Override\r
+       public String getName(ReadGraph graph) throws DatabaseException {\r
+               return indexes;\r
+       }\r
+\r
+       @Override\r
+       public Object getSerialized(ReadGraph graph) throws DatabaseException {\r
+               return indexes;\r
+       }\r
+\r
+       @Override\r
+       public Variable getParent(ReadGraph graph) throws DatabaseException {\r
+               return parent;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/NamesIndexVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/NamesIndexVariable.java
new file mode 100644 (file)
index 0000000..7e32bba
--- /dev/null
@@ -0,0 +1,29 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+\r
+public class NamesIndexVariable extends IndexVariable<String[]> {\r
+\r
+       public NamesIndexVariable(ReadGraph graph, Variable parent, String indexes)\r
+                       throws DatabaseException {\r
+               super(graph, parent, indexes);\r
+       }\r
+\r
+       @Override\r
+       public String[] getValue() {\r
+               ArrayList<String> names = getVariableNames();\r
+               return names.toArray(new String[names.size()]);\r
+       }\r
+\r
+       @Override\r
+       public void setIndexedValue(WriteGraph graph, Object value)\r
+                       throws DatabaseException {\r
+               // TODO Auto-generated method stub\r
+               \r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/SensitivityExperimentParameter.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/SensitivityExperimentParameter.java
new file mode 100644 (file)
index 0000000..7309898
--- /dev/null
@@ -0,0 +1,105 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.adapter.distribution.IDistribution;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.Variable;\r
+import org.simantics.sysdyn.representation.utils.IndexUtils;\r
+import org.simantics.sysdyn.representation.utils.RepresentationUtils;\r
+\r
+public class SensitivityExperimentParameter {\r
+    \r
+    private String variableName;\r
+    private String[] indexes;\r
+    private String fullName;\r
+    private IDistribution distribution;\r
+    \r
+    public SensitivityExperimentParameter(ReadGraph graph, Resource parameter) {\r
+        \r
+        try {\r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+            Resource distributionResource = graph.getPossibleObject(parameter, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution);\r
+            distribution = graph.adapt(distributionResource, IDistribution.class);\r
+            variableName = graph.getPossibleRelatedValue(parameter, SR.SensitivityAnalysisExperiment_Parameter_variable, Bindings.STRING);\r
+            indexes = graph.getPossibleRelatedValue(parameter, SR.SensitivityAnalysisExperiment_Parameter_indexes, Bindings.STRING_ARRAY);\r
+            \r
+            Resource model = graph.syncRequest(new PossibleModel(parameter));\r
+            SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+            SysdynModel sm = smm.getModel(graph, graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration));\r
+            \r
+            Variable variable = RepresentationUtils.getVariable(sm.getConfiguration(), variableName);\r
+                   \r
+            if (variable != null) {\r
+                   if(indexes == null && (variable.getArrayIndexes() != null & variable.getArrayIndexes().size() > 0)) {\r
+                       indexes = new String[variable.getArrayIndexes().size()];\r
+                       \r
+                       for(int i = 0; i < variable.getArrayIndexes().size(); i++) {\r
+                           Enumeration e = variable.getArrayIndexes().get(i);\r
+                           indexes[i] = e.getEnumerationIndexes().get(0).getName();\r
+                       }\r
+                   }\r
+                   \r
+                   if(indexes != null) {\r
+                       StringBuilder sb = new StringBuilder();\r
+                       sb.append("[");\r
+                       for(int i = 0; i < indexes.length; i++) {\r
+                           if(i > 0)\r
+                               sb.append(",");\r
+       \r
+                           String index = indexes[i];\r
+                           sb.append(index);\r
+                       }\r
+                       sb.append("]");\r
+                       String result = IndexUtils.rangeToIndexes(variable, sb.toString());\r
+                       fullName = variableName + result;\r
+                   } else {\r
+                       fullName = variableName;\r
+                   }\r
+            }\r
+        } catch (DatabaseException e) {\r
+\r
+        }\r
+    }\r
+\r
+    public String getVariableName() {\r
+        return variableName;\r
+    }\r
+    \r
+    public String[] getIndexes() {\r
+        return indexes;\r
+    }\r
+\r
+    public String getFullName() {\r
+        return fullName;\r
+    }\r
+\r
+    public IDistribution getDistribution() {\r
+        return distribution;\r
+    }\r
+\r
+       public String getFullModelicaName() {\r
+       if (this.fullName == null)\r
+               return null;\r
+        return this.fullName.replace(' ', '_');\r
+       }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimeIndexVariable.java
new file mode 100644 (file)
index 0000000..9a44eac
--- /dev/null
@@ -0,0 +1,32 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
+\r
+public class TimeIndexVariable extends IndexVariable<Double> {\r
+\r
+       public TimeIndexVariable(ReadGraph graph, Variable parent, String indexes)\r
+                       throws DatabaseException {\r
+               super(graph, parent, indexes);\r
+       }\r
+\r
+       @Override\r
+       public Double getValue() {\r
+           if(experiment != null && experiment instanceof SysdynPlaybackExperiment)\r
+               return ((SysdynPlaybackExperiment)experiment).getTime();\r
+           if(experiment != null && experiment instanceof SysdynGameExperimentBase)\r
+               return ((SysdynGameExperimentBase)experiment).getSolver().getTime();\r
+           return null;\r
+       }\r
+\r
+       @Override\r
+       public void setIndexedValue(WriteGraph graph, Object value)\r
+                       throws DatabaseException {\r
+               \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimesIndexVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/TimesIndexVariable.java
new file mode 100644 (file)
index 0000000..329e4cd
--- /dev/null
@@ -0,0 +1,52 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.manager.SysdynResult;\r
+\r
+public class TimesIndexVariable extends IndexVariable<double[][]> {\r
+\r
+       public TimesIndexVariable(ReadGraph graph, Variable parent, String indexes)\r
+                       throws DatabaseException {\r
+               super(graph, parent, indexes);\r
+               // TODO Auto-generated constructor stub\r
+       }\r
+\r
+       @Override\r
+       public double[][] getValue() {\r
+           if(experiment == null)\r
+               return new double[0][0];\r
+           \r
+           Collection<SysdynResult> results = experiment.getActiveResults();\r
+           ArrayList<String> variableNames = getVariableNamesWithIndexNumbers();\r
+\r
+           double[][] result = new double[variableNames.size()][];\r
+           for(int i = 0; i < variableNames.size(); i++) {\r
+               for(SysdynResult r : results) {\r
+                   SysdynDataSet ds = r.getDataSet(variableNames.get(i));\r
+                   if(ds != null && ds.times != null) {\r
+                       result[i] =  new double[ds.times.length];\r
+                       for(int j = 0; j < ds.times.length; j++) {\r
+                           result[i][j] = ds.times[j];\r
+                       }\r
+                       break; // Show the first result found. (i.e. do not show history datasets)\r
+                   }\r
+               }\r
+               if(result[i] == null)\r
+                result[i] = new double[0];\r
+           }\r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public void setIndexedValue(WriteGraph graph, Object value)\r
+                       throws DatabaseException {\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariable.java
new file mode 100644 (file)
index 0000000..3b05dd7
--- /dev/null
@@ -0,0 +1,19 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+\r
+public class ValueIndexVariable extends ValueIndexVariableBase<double[]> {\r
+\r
+       public ValueIndexVariable(ReadGraph graph, Variable parent, String indexes)\r
+                       throws DatabaseException {\r
+           super(graph, parent, indexes);\r
+       }\r
+       \r
+       @Override\r
+       public double[] getValue() {\r
+               return getValueFull();\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableBase.java
new file mode 100644 (file)
index 0000000..1e7bf51
--- /dev/null
@@ -0,0 +1,119 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.manager.SysdynResult;\r
+import org.simantics.sysdyn.solver.ISolver;\r
+\r
+abstract public class ValueIndexVariableBase<T> extends IndexVariable<T> {\r
+\r
+       public ValueIndexVariableBase(ReadGraph graph, Variable parent, String indexes)\r
+                       throws DatabaseException {\r
+           super(graph, parent, indexes);\r
+       }\r
+\r
+       public static double[] UNRESOLVED = new double[0];\r
+       \r
+       public double[] getValueFull() {\r
+           if(experiment == null)\r
+               return UNRESOLVED;\r
+\r
+        Collection<SysdynResult> results = experiment.getActiveResults();\r
+               ArrayList<String> variableNames = getVariableNamesWithIndexNumbers();\r
+\r
+               double[] result = new double[variableNames.size()];\r
+               for(int i = 0; i < variableNames.size(); i++) {\r
+                   for(SysdynResult r : results) {            \r
+                       if(experiment instanceof SysdynGameExperimentBase) {\r
+                           Double d = ((SysdynGameExperimentBase)experiment).getCurrentValue(variableNames.get(i)); \r
+                           result[i] = d != null ? d : 0;\r
+                       } else {\r
+                           SysdynDataSet ds = r.getDataSet(variableNames.get(i));\r
+                           if(ds != null && ds.values != null && ds.values.length > 0) {\r
+                               result[i] =  ds.values[ds.values.length-1];\r
+                           } else {\r
+                               return UNRESOLVED;\r
+                           }\r
+                       }\r
+                   }\r
+               }\r
+               return result;\r
+       }\r
+\r
+       @Override\r
+       public void setIndexedValue(WriteGraph graph, Object value)\r
+                       throws DatabaseException {\r
+               Variable var = parent.getParent(graph);\r
+               Resource resource = var.getRepresents(graph);\r
+               \r
+               if(!(value instanceof double[]) || resource == null)\r
+                       return;\r
+               \r
+               double[] values = (double[]) value;\r
+               \r
+//             FMUControlJNI control = null;\r
+               if(experiment instanceof SysdynGameExperimentBase) { // Support only game experiments for now..\r
+                   \r
+                       SysdynGameExperimentBase exp = (SysdynGameExperimentBase)experiment;\r
+                   ExperimentState state = exp.getSysdynExperimentState();\r
+                   // Set value to control only if the simulation is running or stopped, not before initialization\r
+                   if(!(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)))\r
+                       return;\r
+                   \r
+//                 control = ((SysdynGameExperimentBase)this.experiment).getFMUControl();\r
+//                 if(control == null) \r
+//                     return;\r
+                       \r
+                       ISolver solver = exp.getSolver();\r
+\r
+                       try {\r
+                       \r
+                               ArrayList<String> variableNames = getVariableNamesWithIndexNumbers();\r
+                               for(int i = 0; i < variableNames.size() && i < values.length; i++) {\r
+\r
+                                       if(values[i] == Double.NaN)\r
+                                               continue;\r
+\r
+                                       String name = variableNames.get(i);\r
+                                       solver.setRealValue(name, values[i]);\r
+\r
+                                       // Set value for all referred variables in modules\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       for(Resource dependency : graph.getObjects(resource, sr.Variable_isTailOf)) {\r
+                                               Resource head = graph.getPossibleObject(dependency, sr.Variable_HasHead);\r
+                                               Resource ref = graph.getPossibleObject(dependency, sr.Dependency_refersTo);\r
+                                               if(ref != null && head != null) {\r
+                                                       String module = "";\r
+                                                       if(name.indexOf(".") > 0)\r
+                                                               module = name.substring(0, name.lastIndexOf(".") + 1);\r
+                                                       String refName = module + NameUtils.getSafeName(graph, head) + "." + NameUtils.getSafeName(graph, ref);\r
+                                                       solver.setRealValue(refName, values[i]);\r
+                                               } \r
+                                       }\r
+\r
+                               }\r
+                               exp.refresh();\r
+                               exp.updateSubscriptions();\r
+                       \r
+                       } catch (Exception e) {\r
+                               \r
+                               Logger.defaultLogError(e);\r
+                               \r
+                       }\r
+                       \r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableI.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValueIndexVariableI.java
new file mode 100644 (file)
index 0000000..c414f3d
--- /dev/null
@@ -0,0 +1,51 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.Arrays;\r
+\r
+import org.simantics.databoard.binding.Binding;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+\r
+public class  ValueIndexVariableI extends ValueIndexVariableBase<Double> {\r
+\r
+       final int index;\r
+       \r
+       public ValueIndexVariableI(ReadGraph graph, Variable parent, int index) throws DatabaseException {\r
+           super(graph, parent, "");\r
+           this.index = index;\r
+       }\r
+       \r
+       @Override\r
+       public Double getValue() {\r
+               double[] array = getValueFull();\r
+               if(array == null || index < 0 || array.length < index+1) return Double.NaN;\r
+               return array[index];\r
+       }\r
+       \r
+       @Override\r
+       public void setValue(WriteGraph graph, Object value) throws DatabaseException {\r
+               ensureInformationAvailable(graph);\r
+               double[] existing = getValueFull();\r
+               double[] newValue = Arrays.copyOf(existing, existing.length);\r
+               newValue[index] = (Double)value;\r
+               super.setValue(graph, newValue);\r
+       }\r
+       \r
+       @Override\r
+       public void setValue(WriteGraph graph, Object value, Binding binding) throws DatabaseException {\r
+               setValue(graph, value);\r
+       }\r
+       \r
+       @Override\r
+       public String getName(ReadGraph graph) throws DatabaseException {\r
+               return "$" + index;\r
+       }\r
+       \r
+       @Override\r
+       public Object getSerialized(ReadGraph graph) throws DatabaseException {\r
+               return "$" + index;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/ValuesIndexVariable.java
new file mode 100644 (file)
index 0000000..d0eb203
--- /dev/null
@@ -0,0 +1,62 @@
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.manager.SysdynResult;\r
+\r
+public class ValuesIndexVariable extends IndexVariable<double[][]> {\r
+\r
+       public ValuesIndexVariable(ReadGraph graph, Variable parent, String indexes)\r
+                       throws DatabaseException {\r
+               super(graph, parent, indexes);\r
+       }\r
+\r
+       @Override\r
+       public double[][] getValue() {\r
+        ArrayList<String> variableNames = getVariableNamesWithIndexNumbers();\r
+        double[][] result = new double[variableNames.size()][];\r
+\r
+        if (experiment != null) {\r
+               Collection<SysdynResult> results = experiment.getActiveResults();\r
+               for(int i = 0; i < variableNames.size(); i++) {\r
+                   for(SysdynResult r : results) {            \r
+                       SysdynDataSet ds = r.getDataSet(variableNames.get(i));\r
+                       if(ds != null && ds.values != null) {\r
+                           result[i] =  new double[ds.values.length];\r
+                           for(int j = 0; j < ds.values.length; j++) {\r
+                               result[i][j] = ds.values[j];\r
+                           }\r
+                           \r
+                           /*\r
+                            * If this is the actual simulation result and experiment is game experiment, \r
+                            * get the last value from experiment. It might be different from the result\r
+                            * file, if it has been modified in current time step \r
+                            */\r
+                           if(experiment instanceof SysdynGameExperimentBase && ds.result == null) {\r
+                               double d = ((SysdynGameExperimentBase)experiment).getCurrentValue(variableNames.get(i));\r
+                               result[i][ds.values.length - 1] = d;\r
+                           }\r
+                           break; // Show the first result found. (i.e. do not show history datasets)\r
+                       }\r
+                       \r
+                       if(result[i] == null)\r
+                           result[i] = new double[0];\r
+                   }\r
+               }\r
+        }\r
+        return result;\r
+       }\r
+\r
+       @Override\r
+       public void setIndexedValue(WriteGraph graph, Object value)\r
+                       throws DatabaseException {\r
+               \r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableRVIUtils.java
new file mode 100644 (file)
index 0000000..0f24cc5
--- /dev/null
@@ -0,0 +1,335 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.LinkedHashMap;\r
+import java.util.List;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+\r
+/**\r
+ * Utils for finding all active rvis for a single variable. A variable can have multiple \r
+ * rvis, if it is an array variable. Active rvis can be limited using a boolean value sr.ShowEnumerationIndexInCharts\r
+ * \r
+ * Example rvis for a variable with two enumerations (/ModuleInstance1/ModuleInstance2/Variable[Enumeration, Enumeration2]): \r
+ * \r
+ * /ModuleInstance1/ModuleInstance2/Variable[index1, index1]\r
+ * /ModuleInstance1/ModuleInstance2/Variable[index1, index2]\r
+ * /ModuleInstance1/ModuleInstance2/Variable[index2, index1]\r
+ * /ModuleInstance1/ModuleInstance2/Variable[index2, index2]\r
+ * \r
+ * \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class VariableRVIUtils {\r
+\r
+    /**\r
+     * Recursive function for finding number format and label for the set of rvis. (rvis.put("Variable[1]", "Variable[index1]");\r
+     * At the end of the recursive calls, rvis contains all possible combinations of enumeration indexes that are\r
+     * set to be shown in charts\r
+     * \r
+     * @param g ReadGraph\r
+     * @param rvi RVI of the variable\r
+     * @param rvis RVI map containing the full rvi with enumerations. Key contains numerical \r
+     * value of the enumeration and value contains the name of the enumeration (e.g. ["Variable[1]", "Variable[index1]"])\r
+     * @param arrayIndexes ArrayIndex resources, Enumerations.\r
+     * @throws DatabaseException\r
+     */\r
+    private static void traverseIndexes(ReadGraph g, String rvi, HashMap<String, String> rvis, List<Resource> arrayIndexes) throws DatabaseException {\r
+        traverseIndexes(g, rvi, rvis, arrayIndexes, 0, "", "");\r
+    }\r
+\r
+    /**\r
+     * Recursive function for finding number format and label for the set of rvis. (rvis.put("Variable[1]", "Variable[index1]"); \r
+     * At the end of the recursive calls, rvis contains all possible combinations of enumeration indexes that are\r
+     * set to be shown in charts\r
+     * \r
+     * @param g ReadGraph\r
+     * @param rvi RVI of the variable\r
+     * @param rvis RVI map containing the full rvi with enumerations. Key contains numerical \r
+     * @param arrayIndexes ArrayIndex resources, Enumerations.\r
+     * @param currentEnumeration Currently evaluated enumeration index (in arrayIndexes list)\r
+     * @param indexesSoFar String representation of the indexes so far in numerical format\r
+     * @param indexNamesSoFar String representation of the indexes so far in name format\r
+     * @throws DatabaseException\r
+     */\r
+    private static void traverseIndexes(ReadGraph g, String rvi, HashMap<String, String> rvis, List<Resource> arrayIndexes, int currentIndex, String indexesSoFar, String indexNamesSoFar) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(g);\r
+        // Enumeration indexes of the current enumeration (e.g. the first EnumIndexes in Var[EnumIndexes, EnumIndexes, EnumIndexes])\r
+        Resource enumerationIndexes = g.getPossibleObject(arrayIndexes.get(currentIndex), sr.Enumeration_enumerationIndexList);\r
+        if(enumerationIndexes == null)\r
+            return;\r
+        List<Resource> indexes = ListUtils.toList(g, enumerationIndexes);\r
+        for(int i = 0; i < indexes.size(); i++) {\r
+            Boolean b = g.getPossibleRelatedValue(indexes.get(i), sr.EnumerationIndex_showEnumerationIndexInCharts, Bindings.BOOLEAN);\r
+            // If this index is not wanted to be shown in charts, the recursion does not go any further and rvis.put() is not called for this enumeration\r
+            if(Boolean.TRUE.equals(b)) {\r
+                // Get the name of the index\r
+                String name = g.getRelatedValue(indexes.get(i), Layer0.getInstance(g).HasName);\r
+                if(currentIndex < arrayIndexes.size() - 1)\r
+                    // If there are still more EnumIndexes, recursively call the function and add current index to indexesSoFar and indexNamesSoFar\r
+                    traverseIndexes(g, rvi, rvis, arrayIndexes, currentIndex + 1, \r
+                            indexesSoFar + (i + 1) +",", indexNamesSoFar + (name) +",");\r
+                else {\r
+                    // The last enumeration. Add [rvi[1, 1, 1] = rvi[index1, index1, index1]}and so on to the rvis map\r
+                    rvis.put(\r
+                            rvi + "[" + indexesSoFar + (i + 1) + "]", \r
+                            rvi + "[" + indexNamesSoFar + (name) + "]");\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Resolves and replaces all overridden enumerations in enumerations -list\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param variable Selected variable\r
+     * @param enumerations List of array indexes of the variable\r
+     * @return\r
+     */\r
+    private static List<Resource> resolveActiveArrayIndexes(ReadGraph graph, Variable variable, List<Resource> enumerations) {\r
+        try {\r
+            Layer0 l0 = Layer0.getInstance(graph);\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            String uri = variable.getURI(graph);\r
+            uri = uri.substring(0, uri.lastIndexOf("/"));\r
+            // The parent configuration or module\r
+            Variable v = Variables.getPossibleVariable(graph, uri);\r
+            if(v != null) {\r
+                Resource module = v.getRepresents(graph);\r
+                if(module != null && graph.isInheritedFrom(graph.getSingleObject(module, l0.InstanceOf), sr.Module)) {\r
+                    // If the variable is located in a module, it might have overridden (redeclared) enumerations\r
+                    boolean somethingIsReplaced = false;\r
+                    // Find all redeclarations\r
+                    for(Resource redeclaration : graph.syncRequest(new ObjectsWithType(module, sr.Module_redeclaration, sr.Redeclaration))) {\r
+                        Resource replaced = graph.getSingleObject(redeclaration, sr.Redeclaration_replacedEnumeration);\r
+                        while(enumerations.contains(replaced)) {\r
+                            // Replace the redelcared enumeration in enumerations -list with the replacing enumeration\r
+                            enumerations.add(enumerations.indexOf(replaced), graph.getSingleObject(redeclaration, sr.Redeclaration_replacingEnumeration));\r
+                            enumerations.remove(replaced);\r
+                            somethingIsReplaced = true;\r
+                        }\r
+                    }\r
+\r
+                    if(somethingIsReplaced) {\r
+                        // If something was replaced, do the same again for the parent configuration. The\r
+                        // enumerations may be replaced throughout the whole model hierarchy\r
+                        resolveActiveArrayIndexes(graph, v, enumerations);\r
+                    }\r
+                }\r
+            }\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+\r
+        }\r
+        return enumerations;\r
+    }\r
+\r
+\r
+    /**\r
+     * Returns rvis in a map in format /ModuleInstance/Variable[1] = /ModuleInstance/Variable[index1]\r
+     * @param graph ReadGraph\r
+     * @param variable Variable for the rvis\r
+     * @return rvis in a map. Keys are numerical formatted array indexes and values are textual.\r
+     * @throws DatabaseException\r
+     */\r
+    public static HashMap<String, String> getActiveRVIs(ReadGraph graph, Variable variable) throws DatabaseException {\r
+        HashMap<String, String> rvis = new LinkedHashMap<String, String>();\r
+\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+        String rvi = Variables.getRVI(graph, variable);\r
+\r
+        Resource r = variable.getRepresents(graph);\r
+\r
+        Resource arrayIndexes = graph.getPossibleObject(r, sr.Variable_arrayIndexesList);\r
+        if(arrayIndexes == null) {\r
+            // If variable is single-dimensional, use the same rvi\r
+            rvis.put(rvi, rvi);\r
+        } else {\r
+            // If variable is multidimensional, get all indexes that are active and add them to rvis-map\r
+            List<Resource> arrayIndexList = ListUtils.toList(graph, arrayIndexes);\r
+            resolveActiveArrayIndexes(graph, variable, arrayIndexList);\r
+\r
+            if(arrayIndexList.size() > 0)\r
+                traverseIndexes(graph, rvi, rvis, arrayIndexList);\r
+            else\r
+                rvis.put(rvi, rvi);\r
+        }\r
+\r
+        return rvis;\r
+    }\r
+\r
+    \r
+    /**\r
+     * Filters a list of datasets of a single variable with a given filter. Filter should contain \r
+     * as many entries as the variable has enumerations. If the variable is Var[Enum1, Enum2, Enum3]\r
+     * the filter length should be 3.\r
+     * \r
+     * Allowed filter entries are All, Sum and a name of an index.\r
+     * \r
+     * Example filtering for variable Var[Enum1, Enum2, Enum3] where all enumerations have indexes {1, 2}\r
+     * \r
+     * filter: {All, Sum, 1}\r
+     * \r
+     * Filters are applied from back to front\r
+     * \r
+     * 1 1 1\r
+     * 1 1 2    \r
+     * 1 2 1    1 1 1    \r
+     * 1 2 2 => 1 2 1 => 1 SUM(1 1, 2 1)\r
+     * 2 1 1    2 1 1    2 SUM(1 1, 2 1)\r
+     * 2 1 2    2 2 1    \r
+     * 2 2 1    \r
+     * 2 2 2    \r
+     * \r
+     * @param datasets List of SysdynDatasets for a single multidimensional variable\r
+     * @param filter filter for the datasets\r
+     * @return filtered list of SysdynDatasets\r
+     */\r
+    public static ArrayList<SysdynDataSet> getDataset(ArrayList<SysdynDataSet> datasets, String[] filter) {\r
+        // If all filters are "All", no filtering is required.\r
+        boolean doFiltering = false;\r
+        for(String f : filter) {\r
+            if(!f.equalsIgnoreCase("All")) {\r
+                // One of the filters is not All -> do filtering\r
+                doFiltering = true;\r
+                break;\r
+            }\r
+        }\r
+        \r
+        if(doFiltering == false)\r
+            return datasets;\r
+                \r
+        // Start filtering with the complete set of datasets\r
+        ArrayList<SysdynDataSet> result = datasets;\r
+        \r
+        // Go through the filter from end to start\r
+        for(int i = filter.length - 1; i >= 0; i--) {\r
+            // Get the current filter\r
+            String currentFilter = filter[i].trim();\r
+            \r
+            ArrayList<SysdynDataSet> tempResult = new ArrayList<SysdynDataSet>();\r
+            HashMap<String, SysdynDataSet> sums = new HashMap<String, SysdynDataSet>();\r
+            for(SysdynDataSet dataset : result) {\r
+                String tempIndexes = dataset.name.substring(dataset.name.indexOf('[') + 1, dataset.name.indexOf(']'));\r
+                String[] indexes = tempIndexes.split(",");\r
+                if(currentFilter.equals("All")) {\r
+                    /*\r
+                     *  If the filter is "All", all datasets \r
+                     *  are kept for the next filtering\r
+                     */\r
+                    tempResult.add(dataset);\r
+                } else if(currentFilter.equals(indexes[i].trim())) {\r
+                    /*\r
+                     *  If the filter equals the index of the dataset\r
+                     *  at the same location, the dataset is kept for the next filtering\r
+                     *  \r
+                     *  e.g. \r
+                     *  dataset = Var[index3, index1, index2]\r
+                     *  filter = {All, index1, ALL}\r
+                     *  i = 1 (from 0 to 2)\r
+                     *  \r
+                     *  dataset's index and filter match at location 1 (the middle index)\r
+                     */\r
+                    tempResult.add(dataset);\r
+                }  else if(currentFilter.equals("Sum")) {\r
+                    /*\r
+                     * Whenever Sum is used as the filter, all datasets having the\r
+                     * same indexes before the sum filter location are summed. \r
+                     * \r
+                     * e.g.\r
+                     * filter = {1, 1, SUM}\r
+                     * 1, 1, 1    \r
+                     * 1, 1, 2 => 1, 1, SUM(1, 1, 1; 1, 1, 2)\r
+                     * 1, 2, 1    1, 2, SUM(1, 2, 1; 1, 2, 2)\r
+                     * 1, 2, 2    \r
+                     */\r
+                    \r
+                    // Find the preceding range (e.g. index1index2index2)\r
+                    String rangeBefore = "";\r
+                    for(int j = 0; j < i; j++)\r
+                        rangeBefore += indexes[j].trim();\r
+                    \r
+                    // Find if there are any datasets for that preceding range in sums\r
+                    SysdynDataSet sum = sums.get(rangeBefore);\r
+                    if(sum != null) {\r
+                        // A sum dataset was found. Add values from this dataset to the sum dataset\r
+                        for(int j = 0; j < sum.values.length; j++)\r
+                            sum.values[j] = sum.values[j] + dataset.values[j];\r
+                    } else {\r
+                        // The first occurence of this preceding range, create a new dataset for the sum\r
+                        \r
+                        // Copy times and values\r
+                        double[] times = new double[dataset.times.length];\r
+                        for(int j = 0; j < dataset.times.length; j++)\r
+                            times[j] = dataset.times[j];\r
+                        double[] values = new double[dataset.values.length];\r
+                        for(int j = 0; j < dataset.values.length; j++)\r
+                            values[j] = dataset.values[j];\r
+                        \r
+                        // Create the dataset and add it to both tempResult and sums map\r
+                        SysdynDataSet newDataset = new SysdynDataSet(dataset.name, dataset.result, times, values);\r
+                        tempResult.add(newDataset);\r
+                        sums.put(rangeBefore, newDataset);\r
+                        \r
+                        // Modify the name of the dataset by adding "Sum" to the current index location.\r
+                        String name = newDataset.name.substring(0, newDataset.name.indexOf('[') + 1);\r
+                        for(int j = 0; j < indexes.length; j++) {\r
+                            if(j < i)\r
+                                // Indexes before "Sum" stay the same\r
+                                name += indexes[j].trim();\r
+                            else if(j >= i)\r
+                                // Current "Sum" index  and indexes after "Sum" are copied from filter\r
+                                name += filter[j].trim();\r
+\r
+                            if(j < indexes.length - 1)\r
+                                name += ", ";\r
+                        }\r
+                        name += "]";\r
+                        \r
+                        // Replace the sum dataset's name\r
+                        newDataset.name = name;\r
+                    }\r
+                        \r
+                } else {\r
+                    // Discard the series\r
+                }\r
+            }\r
+            \r
+            /*\r
+             *  Replace result list with the filtered results and move on to next\r
+             *  filter index or return the list \r
+             */\r
+            result.clear();\r
+            for(SysdynDataSet dataset : tempResult)\r
+                result.add(dataset);\r
+        }\r
+        return result;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableValueSubscription.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/VariableValueSubscription.java
new file mode 100644 (file)
index 0000000..716fd58
--- /dev/null
@@ -0,0 +1,111 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.concurrent.atomic.AtomicBoolean;\r
+\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.ExternalRead;\r
+import org.simantics.db.service.QueryControl;\r
+import org.simantics.utils.datastructures.Callback;\r
+\r
+public class VariableValueSubscription<T> {\r
+    \r
+       public static final long SUBSCRIPTION_COLLECTION_INTERVAL = 2000L;\r
+\r
+       protected ExternalRead<?>  request;\r
+       protected IndexVariable<T>         variable;\r
+       protected Listener<T> listener;\r
+\r
+       /**\r
+        * To protect against invoking listener.exception multiple times which is\r
+        * forbidden.\r
+        */\r
+       protected AtomicBoolean    excepted = new AtomicBoolean(false);\r
+\r
+       public VariableValueSubscription(ExternalRead<?> request, IndexVariable<T> variable, Listener<T> listener) {\r
+               this.request = request;\r
+               this.variable = variable;\r
+               this.listener = listener;\r
+       }\r
+\r
+       public ExternalRead<?> getRequest() {\r
+               return request;\r
+       }\r
+\r
+    public void update() {\r
+        try {\r
+            T value = variable.getValue();\r
+            fireValue(value);\r
+        } catch (Throwable e) {\r
+            fireException(e);\r
+        }\r
+    }\r
+\r
+       void fireValue(T value) {\r
+               if (listener != null)\r
+                       listener.execute(value);\r
+       }\r
+\r
+       void fireException(Throwable t) {\r
+               if (listener != null && excepted.compareAndSet(false, true))\r
+                       listener.exception(t);\r
+        else\r
+            // Can't invoke listener.exception multiple times, but logging\r
+            // further exceptions anyway.\r
+            Logger.defaultLogError(t);\r
+       }\r
+       \r
+       public void setListener(Listener<T> listener) {\r
+               this.listener = listener;\r
+       }\r
+\r
+       /**\r
+        * This makes sure that subscriptions regarding performed DB external reads\r
+        * are abolished from DB client caches when no longer needed.\r
+        * \r
+        * @param session \r
+        * @param subscriptions\r
+        */\r
+       @SuppressWarnings("rawtypes") \r
+       public static void collectSubscriptions(Session session, final VariableValueSubscription[] subscriptions, final ExternalRead<?>... extraReads) {\r
+               if (subscriptions.length == 0 && extraReads.length == 0)\r
+                       return;\r
+\r
+               session.asyncRequest(new WriteRequest() {\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               Collection<ExternalRead<?>> requests = new ArrayList<ExternalRead<?>>(subscriptions.length + extraReads.length);\r
+                               for (VariableValueSubscription subscription : subscriptions)\r
+                                       requests.add(subscription.getRequest());\r
+                               for (ExternalRead<?> read : extraReads)\r
+                                       requests.add(read);\r
+                               graph.getService(QueryControl.class).gc(graph, requests);\r
+                       }\r
+               }, new Callback<DatabaseException>() {\r
+                       @Override\r
+                       public void run(DatabaseException e) {\r
+                               if (e != null)\r
+                                       e.printStackTrace();\r
+                       }\r
+               });\r
+       }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/IDistribution.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/IDistribution.java
new file mode 100644 (file)
index 0000000..a094985
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter.distribution;\r
+\r
+public interface IDistribution {\r
+\r
+    /**\r
+     * Map a probability to the random variable.\r
+     * When random numbers are used to generate the Monte Carlo simulation parameters, the probability\r
+     * is itself selected randomly (between (0,1); at the domain endpoints the value is undefined).\r
+     * \r
+     * @param probability\r
+     * @return Inverse cumulative distribution function at probability, i.e. the random variable at the\r
+     * point where the cumulative distribution function yields probability.\r
+     */\r
+    public double inverseCDF(double probability);\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/Interval.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/Interval.java
new file mode 100644 (file)
index 0000000..39fd876
--- /dev/null
@@ -0,0 +1,84 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter.distribution;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class Interval implements IDistribution {\r
+    \r
+    private double min = 0;\r
+    private double max = 10;\r
+    private double intervalLength = 1;\r
+    private int numberOfValues = 10;\r
+    private int index = 0;\r
+    \r
+    public Interval(ReadGraph graph, Resource distribution) {\r
+\r
+        try {\r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+            Double minValue = graph.getPossibleRelatedValue(distribution, SR.Interval_minValue, Bindings.DOUBLE);\r
+            if(minValue != null)\r
+                this.min = minValue;\r
+            \r
+            Double maxValue = graph.getPossibleRelatedValue(distribution, SR.Interval_maxValue, Bindings.DOUBLE);\r
+            if(maxValue != null)\r
+                this.max = maxValue;\r
+                        \r
+            Resource parameter = graph.getPossibleObject(distribution, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse);\r
+           \r
+            Resource experiment = graph.getPossibleObject(parameter, Layer0.getInstance(graph).PartOf);\r
+\r
+            Integer numberOfValues = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_numberOfValues, Bindings.INTEGER);\r
+            if(numberOfValues != null)\r
+                this.numberOfValues = numberOfValues;\r
+            \r
+            intervalLength = (maxValue - minValue) / (this.numberOfValues - 1);\r
+            \r
+        } catch (DatabaseException e) {\r
+\r
+        }\r
+    }\r
+\r
+    public double getMin() {\r
+        return min;\r
+    }\r
+\r
+    public double getMax() {\r
+        return max;\r
+    }\r
+\r
+    public int getNumberOfValues() {\r
+        return numberOfValues;\r
+    }\r
+\r
+    public double getIntervalLength() {\r
+        return intervalLength;\r
+    }\r
+\r
+       @Override\r
+       public double inverseCDF(double probability) {\r
+               // This is a bit awkward...\r
+           double value = min + (intervalLength * index);\r
+           index++;\r
+           if (index >= numberOfValues)\r
+               index = 0;\r
+           return value;\r
+       }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/NormalDistribution.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/NormalDistribution.java
new file mode 100644 (file)
index 0000000..7887a62
--- /dev/null
@@ -0,0 +1,404 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter.distribution;\r
+\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class NormalDistribution implements IDistribution {\r
+\r
+    private Double min = null;\r
+    private Double max = null;\r
+    private double minProbability = 0;\r
+    private double maxProbability = 1;\r
+    private double mean;\r
+    private double stdDeviation;  \r
+    \r
+    public NormalDistribution(ReadGraph graph, Resource distribution) {\r
+\r
+        try {\r
+\r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+            min = graph.getPossibleRelatedValue(distribution, SR.NormalDistribution_minValue, Bindings.DOUBLE);\r
+            max = graph.getPossibleRelatedValue(distribution, SR.NormalDistribution_maxValue, Bindings.DOUBLE);\r
+            stdDeviation = graph.getPossibleRelatedValue(distribution, SR.NormalDistribution_stdDeviation, Bindings.DOUBLE);\r
+            mean = graph.getPossibleRelatedValue(distribution, SR.NormalDistribution_mean, Bindings.DOUBLE);\r
+            \r
+               // Determine the max and min probabilities.\r
+            if (min != null)\r
+               minProbability = cdf(min, mean, stdDeviation, false);\r
+            if (max != null)\r
+               maxProbability = cdf(max, mean, stdDeviation, false);\r
+\r
+        } catch (DatabaseException e) {\r
+\r
+        }\r
+    }\r
+    \r
+    public double getMin() {\r
+        return min;\r
+    }\r
+\r
+    public double getMax() {\r
+        return max;\r
+    }\r
+    \r
+       @Override\r
+       public double inverseCDF(double probability) {\r
+               // Map probability to [min,max]\r
+               double mappedProbability = minProbability + (maxProbability - minProbability) * probability;\r
+               // Calculate the inverse CDF\r
+               return quantile(mappedProbability, mean, stdDeviation);\r
+       }\r
+\r
+    //The following is from BEAST-MCMC (https://code.google.com/p/beast-mcmc/)\r
+    \r
+    /*\r
+     * NormalDistribution.java\r
+     *\r
+     * Copyright (c) 2002-2011 Alexei Drummond, Andrew Rambaut and Marc Suchard\r
+     *\r
+     * This file is part of BEAST.\r
+     * See the NOTICE file distributed with this work for additional\r
+     * information regarding copyright ownership and licensing.\r
+     *\r
+     * BEAST is free software; you can redistribute it and/or modify\r
+     * it under the terms of the GNU Lesser General Public License as\r
+     * published by the Free Software Foundation; either version 2\r
+     * of the License, or (at your option) any later version.\r
+     *\r
+     *  BEAST is distributed in the hope that it will be useful,\r
+     *  but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+     *  GNU Lesser General Public License for more details.\r
+     *\r
+     * You should have received a copy of the GNU Lesser General Public\r
+     * License along with BEAST; if not, write to the\r
+     * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,\r
+     * Boston, MA  02110-1301  USA\r
+     */\r
+    \r
+    /**\r
+     * quantiles (=inverse cumulative density function)\r
+     *\r
+     * @param z  argument\r
+     * @param m  mean\r
+     * @param sd standard deviation\r
+     * @return icdf at z\r
+     */\r
+    public static double quantile(double z, double m, double sd) {\r
+        return m + Math.sqrt(2.0) * sd * inverseErf(2.0 * z - 1.0);\r
+    }\r
+    \r
+    /** A more accurate and faster implementation of the cdf (taken from function pnorm in the R statistical language)\r
+     * This implementation has discrepancies depending on the programming language and system architecture\r
+     * In Java, returned values become zero once z reaches -37.5193 exactly on the machine tested\r
+     * In the other implementation, the returned value 0 at about z = -8\r
+     * In C, this 0 value is reached approximately z = -37.51938\r
+     *\r
+     * Will later need to be optimised for BEAST\r
+     *\r
+     * @param x     argument\r
+     * @param mu    mean\r
+     * @param sigma standard deviation\r
+     * @param log_p is p logged\r
+     * @return cdf at x\r
+     */\r
+    public static double cdf(double x, double mu, double sigma, boolean log_p) {\r
+        boolean i_tail=false;\r
+        double p, cp = Double.NaN;\r
+\r
+        if(Double.isNaN(x) || Double.isNaN(mu) || Double.isNaN(sigma)) {\r
+            return Double.NaN;\r
+        }\r
+        if(Double.isInfinite(x) && mu == x) { /* x-mu is NaN */\r
+            return Double.NaN;\r
+        }\r
+        if (sigma <= 0) {\r
+            if(sigma < 0) {\r
+                return Double.NaN;\r
+            }\r
+            return (x < mu) ? 0.0 : 1.0;\r
+        }\r
+        p = (x - mu) / sigma;\r
+        if(Double.isInfinite(p)) {\r
+            return (x < mu) ? 0.0 : 1.0;\r
+        }\r
+        x = p;\r
+        if(Double.isNaN(x)) {\r
+            return Double.NaN;\r
+        }\r
+\r
+        double xden, xnum, temp, del, eps, xsq, y;\r
+        int i;\r
+        boolean lower, upper;\r
+        eps = DBL_EPSILON * 0.5;\r
+        lower = !i_tail;\r
+        upper = i_tail;\r
+\r
+        y = Math.abs(x);\r
+        if (y <= 0.67448975) { /* Normal.quantile(3/4, 1, 0) = 0.67448975 */\r
+            if (y > eps) {\r
+                xsq = x * x;\r
+                xnum = a[4] * xsq;\r
+                xden = xsq;\r
+                for (i = 0; i < 3; i++) {\r
+                    xnum = (xnum + a[i]) * xsq;\r
+                    xden = (xden + b[i]) * xsq;\r
+                }\r
+            }\r
+            else {\r
+                xnum = xden = 0.0;\r
+            }\r
+            temp = x * (xnum + a[3]) / (xden + b[3]);\r
+            if(lower) {\r
+                p = 0.5 + temp;\r
+            }\r
+            if(upper) {\r
+                cp = 0.5 - temp;\r
+            }\r
+            if(log_p) {\r
+                if(lower) {\r
+                    p = Math.log(p);\r
+                }\r
+                if(upper) {\r
+                    cp = Math.log(cp);\r
+                }\r
+            }\r
+        }\r
+\r
+\r
+        else if (y <= M_SQRT_32) {\r
+            /* Evaluate pnorm for 0.67448975 = Normal.quantile(3/4, 1, 0) < |x| <= sqrt(32) ~= 5.657 */\r
+\r
+            xnum = c[8] * y;\r
+            xden = y;\r
+            for (i = 0; i < 7; i++) {\r
+                xnum = (xnum + c[i]) * y;\r
+                xden = (xden + d[i]) * y;\r
+            }\r
+            temp = (xnum + c[7]) / (xden + d[7]);\r
+\r
+            //do_del(y);\r
+            //swap_tail;\r
+            //#define do_del(X)                                                 \\r
+            xsq = ((int) (y * CUTOFF)) * 1.0 / CUTOFF;\r
+            del = (y - xsq) * (y + xsq);\r
+            if(log_p) {\r
+                p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp);\r
+                if((lower && x > 0.0) || (upper && x <= 0.0)) {\r
+                    cp = Math.log(1.0-Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp);\r
+                }\r
+            }\r
+            else {\r
+                p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp;\r
+                cp = 1.0 - p;\r
+            }\r
+            //#define swap_tail                                         \\r
+            if (x > 0.0) {\r
+                temp = p;\r
+                if(lower) {\r
+                    p = cp;\r
+                }\r
+                cp = temp;\r
+            }\r
+        }\r
+        /* else   |x| > sqrt(32) = 5.657 :\r
+         * the next two case differentiations were really for lower=T, log=F\r
+         * Particularly  *not*  for  log_p !\r
+         * Cody had (-37.5193 < x  &&  x < 8.2924) ; R originally had y < 50\r
+         * Note that we do want symmetry(0), lower/upper -> hence use y\r
+         */\r
+        else if(log_p || (lower && -37.5193 < x  &&  x < 8.2924)\r
+                || (upper && -8.2924  < x  &&  x < 37.5193)) {\r
+\r
+            /* Evaluate pnorm for x in (-37.5, -5.657) union (5.657, 37.5) */\r
+            xsq = 1.0 / (x * x);\r
+            xnum = p_[5] * xsq;\r
+            xden = xsq;\r
+            for (i = 0; i < 4; i++) {\r
+                xnum = (xnum + p_[i]) * xsq;\r
+                xden = (xden + q[i]) * xsq;\r
+            }\r
+            temp = xsq * (xnum + p_[4]) / (xden + q[4]);\r
+            temp = (M_1_SQRT_2PI - temp) / y;\r
+\r
+            //do_del(x);\r
+            xsq = ((int) (x * CUTOFF)) * 1.0 / CUTOFF;\r
+            del = (x - xsq) * (x + xsq);\r
+            if(log_p) {\r
+                p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp);\r
+                if((lower && x > 0.0) || (upper && x <= 0.0)) {\r
+                    cp = Math.log(1.0-Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp);\r
+                }\r
+            }\r
+            else {\r
+                p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp;\r
+                cp = 1.0 - p;\r
+            }\r
+            //swap_tail;\r
+            if (x > 0.0) {\r
+                temp = p;\r
+                if(lower) {\r
+                    p = cp;\r
+                }\r
+                cp = temp;\r
+            }\r
+        }\r
+        else { /* no log_p , large x such that probs are 0 or 1 */\r
+            if(x > 0) {\r
+                p = 1.0;\r
+                cp = 0.0;\r
+            }\r
+            else {\r
+                p = 0.0;\r
+                cp = 1.0;\r
+            }\r
+        }\r
+        return p;\r
+\r
+    }\r
+\r
+    // Private\r
+\r
+    protected double m, sd;\r
+\r
+    private static final double[] a = {\r
+            2.2352520354606839287,\r
+            161.02823106855587881,\r
+            1067.6894854603709582,\r
+            18154.981253343561249,\r
+            0.065682337918207449113\r
+    };\r
+    private static final double[] b = {\r
+            47.20258190468824187,\r
+            976.09855173777669322,\r
+            10260.932208618978205,\r
+            45507.789335026729956\r
+    };\r
+    private static final double[] c = {\r
+            0.39894151208813466764,\r
+            8.8831497943883759412,\r
+            93.506656132177855979,\r
+            597.27027639480026226,\r
+            2494.5375852903726711,\r
+            6848.1904505362823326,\r
+            11602.651437647350124,\r
+            9842.7148383839780218,\r
+            1.0765576773720192317e-8\r
+    };\r
+    private static final double[] d = {\r
+            22.266688044328115691,\r
+            235.38790178262499861,\r
+            1519.377599407554805,\r
+            6485.558298266760755,\r
+            18615.571640885098091,\r
+            34900.952721145977266,\r
+            38912.003286093271411,\r
+            19685.429676859990727\r
+    };\r
+    private static final double[] p_ = {\r
+            0.21589853405795699,\r
+            0.1274011611602473639,\r
+            0.022235277870649807,\r
+            0.001421619193227893466,\r
+            2.9112874951168792e-5,\r
+            0.02307344176494017303\r
+    };\r
+    private static final double[] q = {\r
+            1.28426009614491121,\r
+            0.468238212480865118,\r
+            0.0659881378689285515,\r
+            0.00378239633202758244,\r
+            7.29751555083966205e-5\r
+    };\r
+\r
+    private static final int CUTOFF = 16; /* Cutoff allowing exact "*" and "/" */\r
+\r
+    private static final double M_SQRT_32 = 5.656854249492380195206754896838; /* The square root of 32 */\r
+    private static final double M_1_SQRT_2PI =  0.398942280401432677939946059934;\r
+    private static final double DBL_EPSILON = 2.2204460492503131e-016;\r
+    \r
+    /*\r
+     * ErrorFunction.java\r
+     *\r
+     * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut\r
+     *\r
+     * This file is part of BEAST.\r
+     * See the NOTICE file distributed with this work for additional\r
+     * information regarding copyright ownership and licensing.\r
+     *\r
+     * BEAST is free software; you can redistribute it and/or modify\r
+     * it under the terms of the GNU Lesser General Public License as\r
+     * published by the Free Software Foundation; either version 2\r
+     * of the License, or (at your option) any later version.\r
+     *\r
+     *  BEAST is distributed in the hope that it will be useful,\r
+     *  but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+     *  GNU Lesser General Public License for more details.\r
+     *\r
+     * You should have received a copy of the GNU Lesser General Public\r
+     * License along with BEAST; if not, write to the\r
+     * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,\r
+     * Boston, MA  02110-1301  USA\r
+     */\r
+       \r
+       /**\r
+        * inverse error function\r
+        *\r
+        * @param z argument\r
+        *\r
+        * @return function value\r
+        */\r
+       public static double inverseErf(double z)\r
+       {\r
+               return pointNormal(0.5*z+0.5)/Math.sqrt(2.0);\r
+       }\r
+               \r
+       // Private\r
+       \r
+       // Returns z so that Prob{x<z}=prob where x ~ N(0,1) and (1e-12) < prob<1-(1e-12)\r
+       private static double pointNormal(double prob)\r
+       {\r
+               // Odeh RE & Evans JO (1974) The percentage points of the normal distribution.\r
+               // Applied Statistics 22: 96-97 (AS70)\r
+       \r
+               // Newer methods:\r
+               // Wichura MJ (1988) Algorithm AS 241: the percentage points of the\r
+               // normal distribution.  37: 477-484.\r
+               // Beasley JD & Springer SG  (1977).  Algorithm AS 111: the percentage \r
+               // points of the normal distribution.  26: 118-121.\r
+       \r
+               double a0 = -0.322232431088, a1 = -1, a2 = -0.342242088547, a3 = -0.0204231210245;\r
+               double a4 = -0.453642210148e-4, b0 = 0.0993484626060, b1 = 0.588581570495;\r
+               double b2 = 0.531103462366, b3 = 0.103537752850, b4 = 0.0038560700634;\r
+               double y, z = 0, p = prob, p1;\r
+       \r
+               p1 = (p < 0.5 ? p : 1-p);\r
+               if (p1 < 1e-20)\r
+               {\r
+                       new IllegalArgumentException("Argument prob out of range");\r
+               }\r
+       \r
+               y = Math.sqrt(Math.log(1/(p1*p1)));   \r
+               z = y + ((((y*a4+a3)*y+a2)*y+a1)*y+a0)/((((y*b4+b3)*y+b2)*y+b1)*y+b0);\r
+               return (p < 0.5 ? -z : z);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/UniformDistribution.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/distribution/UniformDistribution.java
new file mode 100644 (file)
index 0000000..fe6d475
--- /dev/null
@@ -0,0 +1,57 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter.distribution;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class UniformDistribution implements IDistribution {\r
+    \r
+    private double min;\r
+    private double max;\r
+    \r
+    public UniformDistribution(ReadGraph graph, Resource distribution) {\r
+\r
+        try {\r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+\r
+            Double minValue = graph.getPossibleRelatedValue(distribution, SR.UniformDistribution_minValue, Bindings.DOUBLE);\r
+            if(minValue != null)\r
+                this.min = minValue;\r
+            \r
+            Double maxValue = graph.getPossibleRelatedValue(distribution, SR.UniformDistribution_maxValue, Bindings.DOUBLE);\r
+            if(maxValue != null)\r
+                this.max = maxValue;\r
+            \r
+        } catch (DatabaseException e) {\r
+\r
+        }\r
+    }\r
+\r
+    public double getMin() {\r
+        return min;\r
+    }\r
+\r
+    public double getMax() {\r
+        return max;\r
+    }\r
+\r
+    @Override\r
+       public double inverseCDF(double probability) {\r
+               return min + probability * (max - min); \r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/HaltonSequenceGenerator.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/HaltonSequenceGenerator.java
new file mode 100644 (file)
index 0000000..15363fd
--- /dev/null
@@ -0,0 +1,95 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter.generator;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Halton sequence generator that creates ArrayLists of Doubles between 0 and 1.\r
+ * \r
+ * @author Tuomas Miettinen\r
+ */\r
+public class HaltonSequenceGenerator implements IGenerator {\r
+       \r
+    private int dimension;\r
+    private int index = 0;\r
+    private ArrayList<Integer> primes;\r
+    \r
+    private void getPrimes() {\r
+       int newPrime = 2;\r
+               while (primes.size() < dimension) {\r
+                       boolean isPrime = true;\r
+               for (int p : primes) {\r
+                       if (newPrime % p == 0) {\r
+                               ++newPrime;\r
+                               isPrime = false;\r
+                               break;\r
+                       }\r
+               }\r
+               if (isPrime) {\r
+                       primes.add(newPrime); \r
+               }\r
+       }\r
+    }\r
+    \r
+    public HaltonSequenceGenerator(ReadGraph graph, Resource method) {\r
+       \r
+        try {\r
+               SysdynResource SR = SysdynResource.getInstance(graph);\r
+               Resource experiment = graph.getPossibleObject(method, SR.SensitivityAnalysisExperiment_method_Inverse);\r
+               Resource parameterListResource = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_parameterList);\r
+               dimension = ListUtils.getListNodes(graph, parameterListResource).size();\r
+\r
+               primes = new ArrayList<Integer>();\r
+               getPrimes();\r
+               \r
+               initialize();\r
+           } catch (DatabaseException e) {\r
+       \r
+           }\r
+    }\r
+\r
+    public static double getHalton(int index, int base) {\r
+       ++index; // Map indexes to start from 1;\r
+        double result = 0;\r
+        double f = 1.0 / base;\r
+        while (index > 0) {\r
+               result = result + f * (index % base);\r
+            index = index / base;\r
+            f = f / base;\r
+        }\r
+        return result;\r
+    }\r
+    \r
+       public List<Double> next() {\r
+               ArrayList<Double> retval = new ArrayList<Double>();\r
+               for (int i = 0; i < dimension; ++i) {\r
+                       int base = primes.get(i);\r
+                       double halton = getHalton(index, base);\r
+                       retval.add(halton);\r
+               }\r
+               ++index;\r
+               return retval;\r
+       }\r
+       \r
+    public void initialize() {\r
+       index = 0;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/IGenerator.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/IGenerator.java
new file mode 100644 (file)
index 0000000..5979264
--- /dev/null
@@ -0,0 +1,34 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter.generator;\r
+\r
+import java.util.List;\r
+\r
+/**\r
+ * Interface for parameter value generators. \r
+ * \r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public interface IGenerator {\r
+\r
+       /**\r
+        * Get the next parameter combination.\r
+        * @return list of generated parameter values \r
+        */\r
+       public List<Double> next();\r
+       \r
+       /**\r
+        * Initialize the generator.\r
+        */\r
+       public void initialize();\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/RandomGenerator.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/adapter/generator/RandomGenerator.java
new file mode 100644 (file)
index 0000000..e4a920f
--- /dev/null
@@ -0,0 +1,64 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.adapter.generator;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.Random;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Random generator that creates ArrayLists of random Doubles between 0 and 1.\r
+ * \r
+ * @author Tuomas Miettinen\r
+ */\r
+\r
+public class RandomGenerator implements IGenerator {\r
+       \r
+    private int seed;\r
+    private int dimension;\r
+    private Random random;\r
+    \r
+    public RandomGenerator(ReadGraph graph, Resource method) {\r
+       \r
+        try {\r
+               SysdynResource SR = SysdynResource.getInstance(graph);\r
+               Resource experiment = graph.getPossibleObject(method, SR.SensitivityAnalysisExperiment_method_Inverse);\r
+               seed = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_randomSeed, Bindings.INTEGER);\r
+               \r
+               Resource parameterListResource = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_parameterList);\r
+               dimension = ListUtils.getListNodes(graph, parameterListResource).size();\r
+\r
+               initialize();\r
+           } catch (DatabaseException e) {\r
+       \r
+           }\r
+    }\r
+\r
+       public List<Double> next() {\r
+               ArrayList<Double> randoms = new ArrayList<Double>();\r
+               for (int i = 0; i < dimension; ++i)\r
+                       randoms.add(random.nextDouble());\r
+               return randoms;\r
+       }\r
+       \r
+    public void initialize() {\r
+       random = new Random(this.seed);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/AdjacencyList.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/AdjacencyList.java
new file mode 100644 (file)
index 0000000..47c784c
--- /dev/null
@@ -0,0 +1,46 @@
+package org.simantics.sysdyn.elementaryCycles;
+
+import java.util.Vector;
+
+
+/**
+ * Calculates the adjacency-list for a given adjacency-matrix.
+ * 
+ * 
+ * @author Frank Meyer, web@normalisiert.de
+ * @version 1.0, 26.08.2006
+ *
+ */
+public class AdjacencyList {
+       /**
+        * Calculates a adjacency-list for a given array of an adjacency-matrix.
+        *
+        * @param adjacencyMatrix array with the adjacency-matrix that represents
+        * the graph
+        * @return int[][]-array of the adjacency-list of given nodes. The first
+        * dimension in the array represents the same node as in the given
+        * adjacency, the second dimension represents the indicies of those nodes,
+        * that are direct successornodes of the node.
+        */
+       @SuppressWarnings({ "rawtypes", "unchecked" })
+       public static int[][] getAdjacencyList(boolean[][] adjacencyMatrix) {
+               int[][] list = new int[adjacencyMatrix.length][];
+
+               for (int i = 0; i < adjacencyMatrix.length; i++) {
+                       Vector v = new Vector();
+                       for (int j = 0; j < adjacencyMatrix[i].length; j++) {
+                               if (adjacencyMatrix[i][j]) {
+                                       v.add(new Integer(j));
+                               }
+                       }
+
+                       list[i] = new int[v.size()];
+                       for (int j = 0; j < v.size(); j++) {
+                               Integer in = (Integer) v.get(j);
+                               list[i][j] = in.intValue();
+                       }
+               }
+               
+               return list;
+       }
+}
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/ElementaryCyclesSearch.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/ElementaryCyclesSearch.java
new file mode 100644 (file)
index 0000000..641682f
--- /dev/null
@@ -0,0 +1,167 @@
+package org.simantics.sysdyn.elementaryCycles;
+
+import java.util.List;
+import java.util.Vector;
+
+
+
+/**
+ * Searchs all elementary cycles in a given directed graph. The implementation
+ * is independent from the concrete objects that represent the graphnodes, it
+ * just needs an array of the objects representing the nodes the graph
+ * and an adjacency-matrix of type boolean, representing the edges of the
+ * graph. It then calculates based on the adjacency-matrix the elementary
+ * cycles and returns a list, which contains lists itself with the objects of the 
+ * concrete graphnodes-implementation. Each of these lists represents an
+ * elementary cycle.<br><br>
+ *
+ * The implementation uses the algorithm of Donald B. Johnson for the search of
+ * the elementary cycles. For a description of the algorithm see:<br>
+ * Donald B. Johnson: Finding All the Elementary Circuits of a Directed Graph.
+ * SIAM Journal on Computing. Volumne 4, Nr. 1 (1975), pp. 77-84.<br><br>
+ *
+ * The algorithm of Johnson is based on the search for strong connected
+ * components in a graph. For a description of this part see:<br>
+ * Robert Tarjan: Depth-first search and linear graph algorithms. In: SIAM
+ * Journal on Computing. Volume 1, Nr. 2 (1972), pp. 146-160.<br>
+ * 
+ * @author Frank Meyer, web_at_normalisiert_dot_de
+ * @version 1.2, 22.03.2009
+ *
+ */
+@SuppressWarnings("rawtypes")
+public class ElementaryCyclesSearch {
+       /** List of cycles */
+       private List cycles = null;
+
+       /** Adjacency-list of graph */
+       private int[][] adjList = null;
+
+       /** Graphnodes */
+       private Object[] graphNodes = null;
+
+       /** Blocked nodes, used by the algorithm of Johnson */
+       private boolean[] blocked = null;
+
+       /** B-Lists, used by the algorithm of Johnson */
+       private Vector[] B = null;
+
+       /** Stack for nodes, used by the algorithm of Johnson */
+       private Vector stack = null;
+
+       /**
+        * Constructor.
+        *
+        * @param matrix adjacency-matrix of the graph
+        * @param graphNodes array of the graphnodes of the graph; this is used to
+        * build sets of the elementary cycles containing the objects of the original
+        * graph-representation
+        */
+       public ElementaryCyclesSearch(boolean[][] matrix, Object[] graphNodes) {
+               this.graphNodes = graphNodes;
+               this.adjList = AdjacencyList.getAdjacencyList(matrix);
+       }
+
+       /**
+        * Returns List::List::Object with the Lists of nodes of all elementary
+        * cycles in the graph.
+        *
+        * @return List::List::Object with the Lists of the elementary cycles.
+        */
+       public List getElementaryCycles() {
+               this.cycles = new Vector();
+               this.blocked = new boolean[this.adjList.length];
+               this.B = new Vector[this.adjList.length];
+               this.stack = new Vector();
+               StrongConnectedComponents sccs = new StrongConnectedComponents(this.adjList);
+               int s = 0;
+
+               while (true) {
+                       SCCResult sccResult = sccs.getAdjacencyList(s);
+                       if (sccResult != null && sccResult.getAdjList() != null) {
+                               Vector[] scc = sccResult.getAdjList();
+                               s = sccResult.getLowestNodeId();
+                               for (int j = 0; j < scc.length; j++) {
+                                       if ((scc[j] != null) && (scc[j].size() > 0)) {
+                                               this.blocked[j] = false;
+                                               this.B[j] = new Vector();
+                                       }
+                               }
+
+                               this.findCycles(s, s, scc);
+                               s++;
+                       } else {
+                               break;
+                       }
+               }
+
+               return this.cycles;
+       }
+
+       /**
+        * Calculates the cycles containing a given node in a strongly connected
+        * component. The method calls itself recursivly.
+        *
+        * @param v
+        * @param s
+        * @param adjList adjacency-list with the subgraph of the strongly
+        * connected component s is part of.
+        * @return true, if cycle found; false otherwise
+        */
+       @SuppressWarnings("unchecked")
+       private boolean findCycles(int v, int s, Vector[] adjList) {
+               boolean f = false;
+               this.stack.add(new Integer(v));
+               this.blocked[v] = true;
+
+               for (int i = 0; i < adjList[v].size(); i++) {
+                       int w = ((Integer) adjList[v].get(i)).intValue();
+                       // found cycle
+                       if (w == s) {
+                               Vector cycle = new Vector();
+                               for (int j = 0; j < this.stack.size(); j++) {
+                                       int index = ((Integer) this.stack.get(j)).intValue();
+                                       cycle.add(this.graphNodes[index]);
+                               }
+                               this.cycles.add(cycle);
+                               f = true;
+                       } else if (!this.blocked[w]) {
+                               if (this.findCycles(w, s, adjList)) {
+                                       f = true;
+                               }
+                       }
+               }
+
+               if (f) {
+                       this.unblock(v);
+               } else {
+                       for (int i = 0; i < adjList[v].size(); i++) {
+                               int w = ((Integer) adjList[v].get(i)).intValue();
+                               if (!this.B[w].contains(new Integer(v))) {
+                                       this.B[w].add(new Integer(v));
+                               }
+                       }
+               }
+
+               this.stack.remove(new Integer(v));
+               return f;
+       }
+
+       /**
+        * Unblocks recursivly all blocked nodes, starting with a given node.
+        *
+        * @param node node to unblock
+        */
+       private void unblock(int node) {
+               this.blocked[node] = false;
+               Vector Bnode = this.B[node];
+               while (Bnode.size() > 0) {
+                       Integer w = (Integer) Bnode.get(0);
+                       Bnode.remove(0);
+                       if (this.blocked[w.intValue()]) {
+                               this.unblock(w.intValue());
+                       }
+               }
+       }
+}
+
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/SCCResult.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/SCCResult.java
new file mode 100644 (file)
index 0000000..c8787cd
--- /dev/null
@@ -0,0 +1,34 @@
+package org.simantics.sysdyn.elementaryCycles;\r
+\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+import java.util.Vector;\r
+\r
+@SuppressWarnings("rawtypes")\r
+public class SCCResult {\r
+       private Set nodeIDsOfSCC = null;\r
+       private Vector[] adjList = null;\r
+       private int lowestNodeId = -1;\r
+       \r
+       @SuppressWarnings("unchecked")\r
+       public SCCResult(Vector[] adjList, int lowestNodeId) {\r
+               this.adjList = adjList;\r
+               this.lowestNodeId = lowestNodeId;\r
+               this.nodeIDsOfSCC = new HashSet();\r
+               if (this.adjList != null) {\r
+                       for (int i = this.lowestNodeId; i < this.adjList.length; i++) {\r
+                               if (this.adjList[i].size() > 0) {\r
+                                       this.nodeIDsOfSCC.add(new Integer(i));\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+\r
+       public Vector[] getAdjList() {\r
+               return adjList;\r
+       }\r
+\r
+       public int getLowestNodeId() {\r
+               return lowestNodeId;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/StrongConnectedComponents.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/StrongConnectedComponents.java
new file mode 100644 (file)
index 0000000..8c966d3
--- /dev/null
@@ -0,0 +1,280 @@
+package org.simantics.sysdyn.elementaryCycles;
+
+
+import java.util.Vector;
+
+/**
+ * This is a helpclass for the search of all elementary cycles in a graph 
+ * with the algorithm of Johnson. For this it searches for strong connected
+ * components, using the algorithm of Tarjan. The constructor gets an 
+ * adjacency-list of a graph. Based on this graph, it gets a nodenumber s,
+ * for which it calculates the subgraph, containing all nodes
+ * {s, s + 1, ..., n}, where n is the highest nodenumber in the original
+ * graph (e.g. it builds a subgraph with all nodes with higher or same
+ * nodenumbers like the given node s). It returns the strong connected
+ * component of this subgraph which contains the lowest nodenumber of all
+ * nodes in the subgraph.<br><br>
+ *
+ * For a description of the algorithm for calculating the strong connected
+ * components see:<br>
+ * Robert Tarjan: Depth-first search and linear graph algorithms. In: SIAM
+ * Journal on Computing. Volume 1, Nr. 2 (1972), pp. 146-160.<br>
+ * For a description of the algorithm for searching all elementary cycles in
+ * a directed graph see:<br>
+ * Donald B. Johnson: Finding All the Elementary Circuits of a Directed Graph.
+ * SIAM Journal on Computing. Volumne 4, Nr. 1 (1975), pp. 77-84.<br><br>
+ *
+ * @author Frank Meyer, web_at_normalisiert_dot_de
+ * @version 1.1, 22.03.2009
+ *
+ */
+@SuppressWarnings({"rawtypes", "unchecked"})
+public class StrongConnectedComponents {
+       /** Adjacency-list of original graph */
+       private int[][] adjListOriginal = null;
+
+       /** Adjacency-list of currently viewed subgraph */
+       private int[][] adjList = null;
+       
+       /** Helpattribute for finding scc's */
+       private boolean[] visited = null;
+
+       /** Helpattribute for finding scc's */
+       private Vector stack = null;
+
+       /** Helpattribute for finding scc's */
+       private int[] lowlink = null;
+
+       /** Helpattribute for finding scc's */
+       private int[] number = null;
+
+       /** Helpattribute for finding scc's */
+       private int sccCounter = 0;
+
+       /** Helpattribute for finding scc's */
+       private Vector currentSCCs = null;
+
+       /**
+        * Constructor.
+        *
+        * @param adjList adjacency-list of the graph
+        */
+       public StrongConnectedComponents(int[][] adjList) {
+               this.adjListOriginal = adjList;
+       }
+
+       /**
+        * This method returns the adjacency-structure of the strong connected
+        * component with the least vertex in a subgraph of the original graph
+        * induced by the nodes {s, s + 1, ..., n}, where s is a given node. Note
+        * that trivial strong connected components with just one node will not
+        * be returned.
+        *
+        * @param node node s
+        * @return SCCResult with adjacency-structure of the strong
+        * connected component; null, if no such component exists
+        */
+       public SCCResult getAdjacencyList(int node) {
+               this.visited = new boolean[this.adjListOriginal.length];
+               this.lowlink = new int[this.adjListOriginal.length];
+               this.number = new int[this.adjListOriginal.length];
+               this.visited = new boolean[this.adjListOriginal.length];
+               this.stack = new Vector();
+               this.currentSCCs = new Vector();
+
+               this.makeAdjListSubgraph(node);
+
+               for (int i = node; i < this.adjListOriginal.length; i++) {
+                       if (!this.visited[i]) {
+                               this.getStrongConnectedComponents(i);
+                               Vector nodes = this.getLowestIdComponent();
+                               if (nodes != null && !nodes.contains(new Integer(node)) && !nodes.contains(new Integer(node + 1))) {
+                                       return this.getAdjacencyList(node + 1);
+                               } else {
+                                       Vector[] adjacencyList = this.getAdjList(nodes);
+                                       if (adjacencyList != null) {
+                                               for (int j = 0; j < this.adjListOriginal.length; j++) {
+                                                       if (adjacencyList[j].size() > 0) {
+                                                               return new SCCResult(adjacencyList, j);
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               return null;
+       }
+
+       /**
+        * Builds the adjacency-list for a subgraph containing just nodes
+        * >= a given index.
+        *
+        * @param node Node with lowest index in the subgraph
+        */
+       private void makeAdjListSubgraph(int node) {
+               this.adjList = new int[this.adjListOriginal.length][0];
+
+               for (int i = node; i < this.adjList.length; i++) {
+                       Vector successors = new Vector();
+                       for (int j = 0; j < this.adjListOriginal[i].length; j++) {
+                               if (this.adjListOriginal[i][j] >= node) {
+                                       successors.add(new Integer(this.adjListOriginal[i][j]));
+                               }
+                       }
+                       if (successors.size() > 0) {
+                               this.adjList[i] = new int[successors.size()];
+                               for (int j = 0; j < successors.size(); j++) {
+                                       Integer succ = (Integer) successors.get(j);
+                                       this.adjList[i][j] = succ.intValue();
+                               }
+                       }
+               }
+       }
+
+       /**
+        * Calculates the strong connected component out of a set of scc's, that
+        * contains the node with the lowest index.
+        *
+        * @return Vector::Integer of the scc containing the lowest nodenumber
+        */
+       private Vector getLowestIdComponent() {
+               int min = this.adjList.length;
+               Vector currScc = null;
+
+               for (int i = 0; i < this.currentSCCs.size(); i++) {
+                       Vector scc = (Vector) this.currentSCCs.get(i);
+                       for (int j = 0; j < scc.size(); j++) {
+                               Integer node = (Integer) scc.get(j);
+                               if (node.intValue() < min) {
+                                       currScc = scc;
+                                       min = node.intValue();
+                               }
+                       }
+               }
+
+               return currScc;
+       }
+
+       /**
+        * @return Vector[]::Integer representing the adjacency-structure of the
+        * strong connected component with least vertex in the currently viewed
+        * subgraph
+        */
+       private Vector[] getAdjList(Vector nodes) {
+               Vector[] lowestIdAdjacencyList = null;
+
+               if (nodes != null) {
+                       lowestIdAdjacencyList = new Vector[this.adjList.length];
+                       for (int i = 0; i < lowestIdAdjacencyList.length; i++) {
+                               lowestIdAdjacencyList[i] = new Vector();
+                       }
+                       for (int i = 0; i < nodes.size(); i++) {
+                               int node = ((Integer) nodes.get(i)).intValue();
+                               for (int j = 0; j < this.adjList[node].length; j++) {
+                                       int succ = this.adjList[node][j];
+                                       if (nodes.contains(new Integer(succ))) {
+                                               lowestIdAdjacencyList[node].add(new Integer(succ));
+                                       }
+                               }
+                       }
+               }
+
+               return lowestIdAdjacencyList;
+       }
+
+       /**
+        * Searchs for strong connected components reachable from a given node.
+        *
+        * @param root node to start from.
+        */
+       private void getStrongConnectedComponents(int root) {
+               this.sccCounter++;
+               this.lowlink[root] = this.sccCounter;
+               this.number[root] = this.sccCounter;
+               this.visited[root] = true;
+               this.stack.add(new Integer(root));
+
+               for (int i = 0; i < this.adjList[root].length; i++) {
+                       int w = this.adjList[root][i];
+                       if (!this.visited[w]) {
+                               this.getStrongConnectedComponents(w);
+                               this.lowlink[root] = Math.min(lowlink[root], lowlink[w]);
+                       } else if (this.number[w] < this.number[root]) {
+                               if (this.stack.contains(new Integer(w))) {
+                                       lowlink[root] = Math.min(this.lowlink[root], this.number[w]);
+                               }
+                       }
+               }
+
+               // found scc
+               if ((lowlink[root] == number[root]) && (stack.size() > 0)) {
+                       int next = -1;
+                       Vector scc = new Vector();
+
+                       do {
+                               next = ((Integer) this.stack.get(stack.size() - 1)).intValue();
+                               this.stack.remove(stack.size() - 1);
+                               scc.add(new Integer(next));
+                       } while (this.number[next] > this.number[root]);
+
+                       // simple scc's with just one node will not be added
+                       if (scc.size() > 1) {
+                               this.currentSCCs.add(scc);
+                       }
+               }
+       }
+
+       public static void main(String[] args) {
+               boolean[][] adjMatrix = new boolean[10][];
+
+               for (int i = 0; i < 10; i++) {
+                       adjMatrix[i] = new boolean[10];
+               }
+
+               /*adjMatrix[0][1] = true;
+               adjMatrix[1][2] = true;
+               adjMatrix[2][0] = true;
+               adjMatrix[2][4] = true;
+               adjMatrix[1][3] = true;
+               adjMatrix[3][6] = true;
+               adjMatrix[6][5] = true;
+               adjMatrix[5][3] = true;
+               adjMatrix[6][7] = true;
+               adjMatrix[7][8] = true;
+               adjMatrix[7][9] = true;
+               adjMatrix[9][6] = true;*/
+               
+        adjMatrix[0][1] = true;
+        adjMatrix[1][2] = true;
+        adjMatrix[2][0] = true; adjMatrix[2][6] = true;
+        adjMatrix[3][4] = true;
+        adjMatrix[4][5] = true; adjMatrix[4][6] = true;
+        adjMatrix[5][3] = true;
+        adjMatrix[6][7] = true;
+        adjMatrix[7][8] = true;
+        adjMatrix[8][6] = true;
+        
+        adjMatrix[6][1] = true;
+
+               int[][] adjList = AdjacencyList.getAdjacencyList(adjMatrix);
+               StrongConnectedComponents scc = new StrongConnectedComponents(adjList);
+               for (int i = 0; i < adjList.length; i++) {
+                       System.out.print("i: " + i + "\n");
+                       SCCResult r = scc.getAdjacencyList(i);
+                       if (r != null) {
+                               Vector[] al = scc.getAdjacencyList(i).getAdjList();
+                               for (int j = i; j < al.length; j++) {
+                                       if (al[j].size() > 0) {
+                                               System.out.print("j: " + j);
+                                               for (int k = 0; k < al[j].size(); k++) {
+                                                       System.out.print(" _" + al[j].get(k).toString());
+                                               }
+                                               System.out.print("\n");
+                                       }
+                               }
+                               System.out.print("\n");
+                       }
+               }
+       }
+}
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/TestCycles.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/TestCycles.java
new file mode 100644 (file)
index 0000000..e846272
--- /dev/null
@@ -0,0 +1,68 @@
+package org.simantics.sysdyn.elementaryCycles;\r
+\r
+\r
+import java.util.List;\r
+\r
+\r
+/**\r
+ * Testfile for elementary cycle search.\r
+ *\r
+ * @author Frank Meyer\r
+ *\r
+ */\r
+public class TestCycles {\r
+\r
+       /**\r
+        * @param args\r
+        */\r
+       @SuppressWarnings("rawtypes")\r
+       public static void main(String[] args) {\r
+               String nodes[] = new String[10];\r
+               boolean adjMatrix[][] = new boolean[10][10];\r
+\r
+               for (int i = 0; i < 10; i++) {\r
+                       nodes[i] = "Node " + i;\r
+               }\r
+\r
+               adjMatrix[0][1] = true;\r
+               adjMatrix[1][2] = true;\r
+               adjMatrix[2][0] = true;\r
+               adjMatrix[2][4] = true;\r
+               adjMatrix[1][3] = true;\r
+               adjMatrix[3][6] = true;\r
+               adjMatrix[6][5] = true;\r
+               adjMatrix[5][3] = true;\r
+               adjMatrix[6][7] = true;\r
+               adjMatrix[7][8] = true;\r
+               adjMatrix[7][9] = true;\r
+               adjMatrix[9][6] = true;\r
+               /*\r
+        adjMatrix[0][1] = true;\r
+        adjMatrix[1][2] = true;\r
+        adjMatrix[2][0] = true; adjMatrix[2][6] = true;\r
+        adjMatrix[3][4] = true;\r
+        adjMatrix[4][5] = true; adjMatrix[4][6] = true;\r
+        adjMatrix[5][3] = true;\r
+        adjMatrix[6][7] = true;\r
+        adjMatrix[7][8] = true;\r
+        adjMatrix[8][6] = true;\r
+        \r
+        adjMatrix[6][1] = true;\r
+*/\r
+               ElementaryCyclesSearch ecs = new ElementaryCyclesSearch(adjMatrix, nodes);\r
+               List cycles = ecs.getElementaryCycles();\r
+               for (int i = 0; i < cycles.size(); i++) {\r
+                       List cycle = (List) cycles.get(i);\r
+                       for (int j = 0; j < cycle.size(); j++) {\r
+                               String node = (String) cycle.get(j);\r
+                               if (j < cycle.size() - 1) {\r
+                                       System.out.print(node + " -> ");\r
+                               } else {\r
+                                       System.out.print(node);\r
+                               }\r
+                       }\r
+                       System.out.print("\n");\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/license.txt b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/elementaryCycles/license.txt
new file mode 100644 (file)
index 0000000..0ed76f9
--- /dev/null
@@ -0,0 +1,11 @@
+(BSD-2 license)\r
+\r
+Copyright (c) 2012, Frank Meyer\r
+All rights reserved.\r
+\r
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r
+\r
+    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r
+    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\r
+\r
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.java
new file mode 100644 (file)
index 0000000..5b37fb6
--- /dev/null
@@ -0,0 +1,1862 @@
+/* Generated By:JavaCC: Do not edit this line. ExpressionParser.java */\r
+package org.simantics.sysdyn.expressionParser;\r
+\r
+import java.util.Set;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+@SuppressWarnings({"unused", "serial"})\r
+public class ExpressionParser implements ExpressionParserConstants {\r
+\r
+    public class ForRange {\r
+                public Token start;\r
+                public Token end;\r
+    }\r
+\r
+    boolean forIndex = false;\r
+    Token firstToken;\r
+\r
+    public Token getFirstToken() {\r
+        return firstToken;\r
+     }\r
+\r
+        List<ForRange> forRanges = new ArrayList<ForRange>();\r
+\r
+    public List<ForRange> getForRanges() {\r
+        return forRanges;\r
+    }\r
+\r
+        HashMap<String, List<Token>> references = new HashMap<String, List<Token>>();\r
+\r
+    public HashMap<String, List<Token>> getReferences() {\r
+        return references;\r
+    }\r
+\r
+    HashMap<String, List<List<Token>>> ranges = new HashMap<String, List<List<Token>>>();\r
+\r
+    public HashMap<String, List<List<Token>>> getRanges() {\r
+        return ranges;\r
+    }\r
+\r
+        List<Token> currentRange = null;\r
+\r
+        HashMap<Token, List<Token>> forIndices = new HashMap<Token, List<Token>>();\r
+\r
+    public HashMap<Token, List<Token>> getForIndices() {\r
+        return forIndices;\r
+    }\r
+\r
+    HashMap<String, List<Token>> enumerationReferences = new HashMap<String, List<Token>>();\r
+\r
+    public HashMap<String, List<Token>> getEnumerationReferences() {\r
+        return enumerationReferences;\r
+    }\r
+\r
+/*\r
+    Collect EACH function call and all references that are inside the call brackets.\r
+    These are later used to exclude spread sheet references out of the normal functions.\r
+*/\r
+    String functionCall = null;\r
+    HashMap<String, List<Token>> functionCallReferences = new HashMap<String, List<Token>>();\r
+\r
+    public HashMap<String, List<Token>> getFunctionCallReferences() {\r
+        return functionCallReferences;\r
+    }\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+  final public void expr() throws ParseException {\r
+        jj_input_stream.setTabSize(1);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 33:\r
+    case 35:\r
+    case 60:\r
+    case 62:\r
+    case 64:\r
+    case 76:\r
+    case 77:\r
+    case 78:\r
+    case 79:\r
+    case IDENT:\r
+    case QIDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+                firstToken = token;\r
+      simple_expression();\r
+      jj_consume_token(0);\r
+      break;\r
+    case 31:\r
+                firstToken = token;\r
+      jj_consume_token(31);\r
+      expression();\r
+      jj_consume_token(28);\r
+      expression();\r
+      label_1:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 20:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[0] = jj_gen;\r
+          break label_1;\r
+        }\r
+        jj_consume_token(20);\r
+        expression();\r
+        jj_consume_token(28);\r
+        expression();\r
+      }\r
+      jj_consume_token(15);\r
+      expression();\r
+      jj_consume_token(0);\r
+      break;\r
+    default:\r
+      jj_la1[1] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void expression() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 33:\r
+    case 35:\r
+    case 60:\r
+    case 62:\r
+    case 64:\r
+    case 76:\r
+    case 77:\r
+    case 78:\r
+    case 79:\r
+    case IDENT:\r
+    case QIDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      simple_expression();\r
+      break;\r
+    case 31:\r
+      jj_consume_token(31);\r
+      expression();\r
+      jj_consume_token(28);\r
+      expression();\r
+      label_2:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 20:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[2] = jj_gen;\r
+          break label_2;\r
+        }\r
+        jj_consume_token(20);\r
+        expression();\r
+        jj_consume_token(28);\r
+        expression();\r
+      }\r
+      jj_consume_token(15);\r
+      expression();\r
+      break;\r
+    default:\r
+      jj_la1[3] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void simple_expression() throws ParseException {\r
+    logical_expression();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 67:\r
+      jj_consume_token(67);\r
+      logical_expression();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 67:\r
+        jj_consume_token(67);\r
+        logical_expression();\r
+        break;\r
+      default:\r
+        jj_la1[4] = jj_gen;\r
+        ;\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[5] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void logical_expression() throws ParseException {\r
+    logical_term();\r
+    label_3:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 22:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[6] = jj_gen;\r
+        break label_3;\r
+      }\r
+      jj_consume_token(22);\r
+      logical_term();\r
+    }\r
+  }\r
+\r
+  final public void logical_term() throws ParseException {\r
+    logical_factor();\r
+    label_4:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 9:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[7] = jj_gen;\r
+        break label_4;\r
+      }\r
+      jj_consume_token(9);\r
+      logical_factor();\r
+    }\r
+  }\r
+\r
+  final public void logical_factor() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 12:\r
+      jj_consume_token(12);\r
+      break;\r
+    default:\r
+      jj_la1[8] = jj_gen;\r
+      ;\r
+    }\r
+    relation();\r
+  }\r
+\r
+  final public void relation() throws ParseException {\r
+    arithmetic_expression();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 70:\r
+    case 71:\r
+    case 72:\r
+    case 73:\r
+    case 74:\r
+    case 75:\r
+      rel_op();\r
+      arithmetic_expression();\r
+      break;\r
+    default:\r
+      jj_la1[9] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void rel_op() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 70:\r
+      jj_consume_token(70);\r
+      break;\r
+    case 71:\r
+      jj_consume_token(71);\r
+      break;\r
+    case 72:\r
+      jj_consume_token(72);\r
+      break;\r
+    case 73:\r
+      jj_consume_token(73);\r
+      break;\r
+    case 74:\r
+      jj_consume_token(74);\r
+      break;\r
+    case 75:\r
+      jj_consume_token(75);\r
+      break;\r
+    default:\r
+      jj_la1[10] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void arithmetic_expression() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 76:\r
+    case 77:\r
+    case 78:\r
+    case 79:\r
+      add_op();\r
+      break;\r
+    default:\r
+      jj_la1[11] = jj_gen;\r
+      ;\r
+    }\r
+    term();\r
+    label_5:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 76:\r
+      case 77:\r
+      case 78:\r
+      case 79:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[12] = jj_gen;\r
+        break label_5;\r
+      }\r
+      add_op();\r
+      term();\r
+    }\r
+  }\r
+\r
+  final public void add_op() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 76:\r
+      jj_consume_token(76);\r
+      break;\r
+    case 77:\r
+      jj_consume_token(77);\r
+      break;\r
+    case 78:\r
+      jj_consume_token(78);\r
+      break;\r
+    case 79:\r
+      jj_consume_token(79);\r
+      break;\r
+    default:\r
+      jj_la1[13] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void term() throws ParseException {\r
+    factor();\r
+    label_6:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 80:\r
+      case 81:\r
+      case 82:\r
+      case 83:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[14] = jj_gen;\r
+        break label_6;\r
+      }\r
+      mul_op();\r
+      factor();\r
+    }\r
+  }\r
+\r
+  final public void factor() throws ParseException {\r
+    primary();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 84:\r
+    case 85:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 84:\r
+        jj_consume_token(84);\r
+        break;\r
+      case 85:\r
+        jj_consume_token(85);\r
+        break;\r
+      default:\r
+        jj_la1[15] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      primary();\r
+      break;\r
+    default:\r
+      jj_la1[16] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void mul_op() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 80:\r
+      jj_consume_token(80);\r
+      break;\r
+    case 81:\r
+      jj_consume_token(81);\r
+      break;\r
+    case 82:\r
+      jj_consume_token(82);\r
+      break;\r
+    case 83:\r
+      jj_consume_token(83);\r
+      break;\r
+    default:\r
+      jj_la1[17] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void primary() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case UNSIGNED_NUMBER:\r
+      jj_consume_token(UNSIGNED_NUMBER);\r
+      break;\r
+    case UNSIGNED_INTEGER:\r
+      jj_consume_token(UNSIGNED_INTEGER);\r
+      break;\r
+    case STRING:\r
+      jj_consume_token(STRING);\r
+      break;\r
+    case 6:\r
+      jj_consume_token(6);\r
+      break;\r
+    case 33:\r
+      jj_consume_token(33);\r
+      break;\r
+    default:\r
+      jj_la1[19] = jj_gen;\r
+      if (jj_2_1(2147483647)) {\r
+    functionCall = null;\r
+        name();\r
+        function_call_args();\r
+    functionCall = null;\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case IDENT:\r
+        case QIDENT:\r
+          component_reference(null);\r
+          break;\r
+        case 60:\r
+          jj_consume_token(60);\r
+          expression();\r
+          jj_consume_token(61);\r
+          break;\r
+        case 64:\r
+          jj_consume_token(64);\r
+          expression_list();\r
+          label_7:\r
+          while (true) {\r
+            switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+            case 68:\r
+              ;\r
+              break;\r
+            default:\r
+              jj_la1[18] = jj_gen;\r
+              break label_7;\r
+            }\r
+            jj_consume_token(68);\r
+            expression_list();\r
+          }\r
+          jj_consume_token(65);\r
+          break;\r
+        case 62:\r
+          jj_consume_token(62);\r
+          function_arguments();\r
+          jj_consume_token(63);\r
+          break;\r
+        case 35:\r
+          jj_consume_token(35);\r
+          break;\r
+        default:\r
+          jj_la1[20] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  final public Token ident() throws ParseException {\r
+  Token concatToken = null;\r
+  Token continuationToken = null;\r
+  String fullStr = null;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case IDENT:\r
+      jj_consume_token(IDENT);\r
+    concatToken = token;\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case IDENT:\r
+      case QIDENT:\r
+        continuationToken = ident();\r
+    fullStr = new String("");\r
+    // Replace whitespace sequence with a single space character.\r
+    fullStr += concatToken.image + " " + continuationToken.image;\r
+\r
+    Token tempToken = new Token(concatToken.kind, fullStr);\r
+    tempToken.beginLine = concatToken.beginLine;\r
+    tempToken.beginColumn = concatToken.beginColumn;\r
+    tempToken.endLine = token.endLine;\r
+    tempToken.endColumn = token.endColumn;\r
+        concatToken = tempToken;\r
+        break;\r
+      default:\r
+        jj_la1[21] = jj_gen;\r
+        ;\r
+      }\r
+    {if (true) return concatToken;}\r
+      break;\r
+    case QIDENT:\r
+      jj_consume_token(QIDENT);\r
+    {if (true) return token;}\r
+      break;\r
+    default:\r
+      jj_la1[22] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void name() throws ParseException {\r
+  Token identToken = null;\r
+    identToken = ident();\r
+    if (functionCall == null)\r
+        functionCall = identToken.image;\r
+    else\r
+        functionCall += "." + identToken.image;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 66:\r
+      jj_consume_token(66);\r
+      name();\r
+      break;\r
+    default:\r
+      jj_la1[23] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void component_reference(String prevToken) throws ParseException {\r
+    Token identToken = null;\r
+    //IDENT [ array_subscripts ] [ "." component_reference ]\r
+            identToken = ident();\r
+    String name = identToken.image;\r
+        // forIndex == true and prevToken != null => this is the second part of an enumeration in for-index\r
+        if(forIndex == true) {\r
+           if(prevToken != null) {\r
+                        if(enumerationReferences.get(prevToken) == null) {\r
+                                enumerationReferences.put(prevToken, new ArrayList<Token>());\r
+                        }\r
+                        List<Token> list = enumerationReferences.get(prevToken);\r
+                        list.add(identToken);\r
+\r
+                // forIndex == true and prevToken == null => this is the enumeration in for-index\r
+                } else {\r
+                        if(enumerationReferences.get(name) == null) {\r
+                                enumerationReferences.put(name, new ArrayList<Token>());\r
+                        }\r
+                        List<Token> list = enumerationReferences.get(name);\r
+                        list.add(identToken);\r
+        }\r
+        } else {\r
+            if(prevToken != null)\r
+                name = prevToken + "." + name;\r
+                if(references.get(name) == null) {\r
+                        references.put(name, new ArrayList<Token>());\r
+                }\r
+                List<Token> list = references.get(name);\r
+                list.add(identToken);\r
+\r
+                if(functionCall != null) {\r
+                  if(!functionCallReferences.containsKey(functionCall))\r
+                      functionCallReferences.put(functionCall, new ArrayList<Token>());\r
+            List<Token> functionReferencelist = getFunctionCallReferences().get(functionCall);\r
+            functionReferencelist.add(identToken);\r
+                }\r
+        }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 64:\r
+      array_subscripts(identToken);\r
+      break;\r
+    default:\r
+      jj_la1[24] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 66:\r
+      jj_consume_token(66);\r
+      component_reference(name);\r
+      break;\r
+    default:\r
+      jj_la1[25] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void function_call_args() throws ParseException {\r
+    jj_consume_token(60);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 31:\r
+    case 33:\r
+    case 35:\r
+    case 60:\r
+    case 62:\r
+    case 64:\r
+    case 76:\r
+    case 77:\r
+    case 78:\r
+    case 79:\r
+    case IDENT:\r
+    case QIDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      function_arguments();\r
+      break;\r
+    default:\r
+      jj_la1[26] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(61);\r
+        if(functionCall != null) {\r
+          if(!functionCallReferences.containsKey(functionCall))\r
+              functionCallReferences.put(functionCall, new ArrayList<Token>());\r
+            }\r
+  }\r
+\r
+  final public void function_arguments() throws ParseException {\r
+    if (jj_2_2(2147483647)) {\r
+      named_argument();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        jj_consume_token(69);\r
+        function_arguments();\r
+        break;\r
+      default:\r
+        jj_la1[27] = jj_gen;\r
+        ;\r
+      }\r
+    } else {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 60:\r
+      case 62:\r
+      case 64:\r
+      case 76:\r
+      case 77:\r
+      case 78:\r
+      case 79:\r
+      case IDENT:\r
+      case QIDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        expression();\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 21:\r
+        case 69:\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 69:\r
+            jj_consume_token(69);\r
+            function_arguments();\r
+            break;\r
+          case 21:\r
+            jj_consume_token(21);\r
+            for_indices();\r
+            break;\r
+          default:\r
+            jj_la1[28] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+          break;\r
+        default:\r
+          jj_la1[29] = jj_gen;\r
+          ;\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[30] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void for_indices() throws ParseException {\r
+    for_index();\r
+    label_8:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[31] = jj_gen;\r
+        break label_8;\r
+      }\r
+      jj_consume_token(69);\r
+      for_index();\r
+    }\r
+  }\r
+\r
+  final public void for_index() throws ParseException {\r
+    Token identToken = null;\r
+    //IDENT [ in expression ]\r
+            identToken = ident();\r
+                forIndices.put(identToken, currentRange);\r
+                forIndex = true;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 41:\r
+      jj_consume_token(41);\r
+                  ForRange forRange = new ForRange();\r
+                  forRange.start = token;\r
+      expression();\r
+                  forRange.start = forRange.start.next;\r
+                  forRange.end = token;\r
+                  forRanges.add(forRange);\r
+      break;\r
+    default:\r
+      jj_la1[32] = jj_gen;\r
+      ;\r
+    }\r
+                forIndex = false;\r
+  }\r
+\r
+/* Removed by Teemu. Refactored in function_arguments)\r
+void named_arguments() : {\r
+} {\r
+       named_argument() ( "," named_arguments() )?\r
+}\r
+*/\r
+  final public void named_argument() throws ParseException {\r
+    ident();\r
+    jj_consume_token(86);\r
+    expression();\r
+  }\r
+\r
+  final public void output_expression_list() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 31:\r
+    case 33:\r
+    case 35:\r
+    case 60:\r
+    case 62:\r
+    case 64:\r
+    case 76:\r
+    case 77:\r
+    case 78:\r
+    case 79:\r
+    case IDENT:\r
+    case QIDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      expression();\r
+      break;\r
+    default:\r
+      jj_la1[33] = jj_gen;\r
+      ;\r
+    }\r
+    label_9:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[34] = jj_gen;\r
+        break label_9;\r
+      }\r
+      jj_consume_token(69);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 60:\r
+      case 62:\r
+      case 64:\r
+      case 76:\r
+      case 77:\r
+      case 78:\r
+      case 79:\r
+      case IDENT:\r
+      case QIDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        expression();\r
+        break;\r
+      default:\r
+        jj_la1[35] = jj_gen;\r
+        ;\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void expression_list() throws ParseException {\r
+    expression();\r
+    label_10:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[36] = jj_gen;\r
+        break label_10;\r
+      }\r
+      jj_consume_token(69);\r
+      expression();\r
+    }\r
+  }\r
+\r
+  final public void array_subscripts(Token prevToken) throws ParseException {\r
+        if(ranges.get(prevToken.image) == null) {\r
+                ranges.put(prevToken.image, new ArrayList<List<Token>>());\r
+        }\r
+        List<List<Token>> rangesList = ranges.get(prevToken.image);\r
+        currentRange = new ArrayList<Token>();\r
+    jj_consume_token(64);\r
+    subscript(currentRange);\r
+    label_11:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[37] = jj_gen;\r
+        break label_11;\r
+      }\r
+      jj_consume_token(69);\r
+      subscript(currentRange);\r
+    }\r
+    jj_consume_token(65);\r
+        rangesList.add(currentRange);\r
+  }\r
+\r
+  final public void subscript(List<Token> currentRange) throws ParseException {\r
+  Token rangeToken = new Token(token.kind, "");\r
+  rangeToken.beginColumn = token.beginColumn + 1;\r
+  rangeToken.beginLine = token.beginLine;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 67:\r
+      jj_consume_token(67);\r
+            currentRange.add(token);\r
+      break;\r
+    default:\r
+      jj_la1[40] = jj_gen;\r
+      if (jj_2_3(2147483647)) {\r
+        functionCall = null;\r
+        name();\r
+        function_call_args();\r
+        functionCall = null;\r
+        rangeToken.image = "";\r
+            rangeToken.endColumn = token.endColumn;\r
+            rangeToken.endLine = token.endLine;\r
+            currentRange.add(rangeToken);\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case IDENT:\r
+        case QIDENT:\r
+        case UNSIGNED_INTEGER:\r
+          rangeIndex(rangeToken, true, ":");\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 67:\r
+            jj_consume_token(67);\r
+            rangeIndex(rangeToken, false, ":");\r
+            break;\r
+          default:\r
+            jj_la1[38] = jj_gen;\r
+            ;\r
+          }\r
+            rangeToken.endColumn = token.endColumn;\r
+            rangeToken.endLine = token.endLine;\r
+                currentRange.add(rangeToken);\r
+          break;\r
+        case 62:\r
+          jj_consume_token(62);\r
+            rangeToken.image = rangeToken.image + token.image;\r
+          rangeIndex(rangeToken, true, ",");\r
+          label_12:\r
+          while (true) {\r
+            switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+            case 69:\r
+              ;\r
+              break;\r
+            default:\r
+              jj_la1[39] = jj_gen;\r
+              break label_12;\r
+            }\r
+            jj_consume_token(69);\r
+            rangeIndex(rangeToken, false, ",");\r
+          }\r
+            rangeToken.endColumn = token.endColumn;\r
+            rangeToken.endLine = token.endLine;\r
+                currentRange.add(rangeToken);\r
+          jj_consume_token(63);\r
+                rangeToken.image = rangeToken.image + token.image;\r
+          break;\r
+        default:\r
+          jj_la1[41] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void rangeIndex(Token rangeToken, boolean first, String delim) throws ParseException {\r
+  Token identToken = null;\r
+  if(!first)\r
+        rangeToken.image = rangeToken.image + delim;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case UNSIGNED_INTEGER:\r
+      jj_consume_token(UNSIGNED_INTEGER);\r
+                rangeToken.image = rangeToken.image + token.image;\r
+      break;\r
+    case IDENT:\r
+    case QIDENT:\r
+      identToken = ident();\r
+                rangeToken.image = rangeToken.image + identToken;\r
+      break;\r
+    default:\r
+      jj_la1[42] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  private boolean jj_2_1(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_1(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(0, xla); }\r
+  }\r
+\r
+  private boolean jj_2_2(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_2(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(1, xla); }\r
+  }\r
+\r
+  private boolean jj_2_3(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_3(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(2, xla); }\r
+  }\r
+\r
+  private boolean jj_3R_74() {\r
+    if (jj_scan_token(67)) return true;\r
+    if (jj_3R_73()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_35() {\r
+    if (jj_3R_39()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_33() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_35()) jj_scanpos = xsp;\r
+    if (jj_3R_36()) return true;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_37()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_38() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(70)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(71)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(72)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(73)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(74)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(75)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_16() {\r
+    if (jj_scan_token(66)) return true;\r
+    if (jj_3R_13()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_26() {\r
+    if (jj_scan_token(67)) return true;\r
+    if (jj_3R_25()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_29()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_79() {\r
+    if (jj_3R_15()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_28() {\r
+    if (jj_scan_token(22)) return true;\r
+    if (jj_3R_27()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_80() {\r
+    if (jj_scan_token(41)) return true;\r
+    if (jj_3R_17()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_32() {\r
+    if (jj_3R_33()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_34()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_78() {\r
+    if (jj_scan_token(UNSIGNED_INTEGER)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_73() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_78()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_79()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_30() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(12)) jj_scanpos = xsp;\r
+    if (jj_3R_32()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_13() {\r
+    if (jj_3R_15()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_16()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_77() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_76()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_27() {\r
+    if (jj_3R_30()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_31()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_66() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_54()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_63() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_66()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_67()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_57() {\r
+    if (jj_scan_token(66)) return true;\r
+    if (jj_3R_51()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_76() {\r
+    if (jj_3R_15()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_80()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_25() {\r
+    if (jj_3R_27()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_28()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_2() {\r
+    if (jj_3R_14()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_23() {\r
+    if (jj_3R_25()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_26()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_19() {\r
+    if (jj_scan_token(QIDENT)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_72() {\r
+    if (jj_3R_76()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_77()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_71() {\r
+    if (jj_scan_token(62)) return true;\r
+    if (jj_3R_73()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_75()) { jj_scanpos = xsp; break; }\r
+    }\r
+    if (jj_scan_token(63)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_53() {\r
+    if (jj_scan_token(68)) return true;\r
+    if (jj_3R_52()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_21() {\r
+    if (jj_scan_token(31)) return true;\r
+    if (jj_3R_17()) return true;\r
+    if (jj_scan_token(28)) return true;\r
+    if (jj_3R_17()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_24()) { jj_scanpos = xsp; break; }\r
+    }\r
+    if (jj_scan_token(15)) return true;\r
+    if (jj_3R_17()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_60() {\r
+    if (jj_3R_17()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_63()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_65() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_64()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_20() {\r
+    if (jj_3R_23()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_17() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_20()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_21()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_3() {\r
+    if (jj_3R_13()) return true;\r
+    if (jj_scan_token(60)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_70() {\r
+    if (jj_3R_73()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_74()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_59() {\r
+    if (jj_3R_14()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_62()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_54() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_59()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_60()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_55() {\r
+    if (jj_3R_54()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_22() {\r
+    if (jj_3R_15()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_69() {\r
+    if (jj_3R_13()) return true;\r
+    if (jj_3R_50()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_18() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_22()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_15() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_18()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_19()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_50() {\r
+    if (jj_scan_token(60)) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_55()) jj_scanpos = xsp;\r
+    if (jj_scan_token(61)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_56() {\r
+    if (jj_3R_61()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_68() {\r
+    if (jj_scan_token(67)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_64() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_68()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_69()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_70()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_71()) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_1() {\r
+    if (jj_3R_13()) return true;\r
+    if (jj_scan_token(60)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_49() {\r
+    if (jj_scan_token(62)) return true;\r
+    if (jj_3R_54()) return true;\r
+    if (jj_scan_token(63)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_48() {\r
+    if (jj_scan_token(64)) return true;\r
+    if (jj_3R_52()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_53()) { jj_scanpos = xsp; break; }\r
+    }\r
+    if (jj_scan_token(65)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_47() {\r
+    if (jj_scan_token(60)) return true;\r
+    if (jj_3R_17()) return true;\r
+    if (jj_scan_token(61)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_46() {\r
+    if (jj_3R_51()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_58() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_17()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_61() {\r
+    if (jj_scan_token(64)) return true;\r
+    if (jj_3R_64()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_65()) { jj_scanpos = xsp; break; }\r
+    }\r
+    if (jj_scan_token(65)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_45() {\r
+    if (jj_3R_13()) return true;\r
+    if (jj_3R_50()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_43() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(84)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(85)) return true;\r
+    }\r
+    if (jj_3R_42()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_42() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(92)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(91)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(90)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(6)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(33)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_45()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_46()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_47()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_48()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_49()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(35)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_29() {\r
+    if (jj_scan_token(67)) return true;\r
+    if (jj_3R_25()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_41() {\r
+    if (jj_3R_44()) return true;\r
+    if (jj_3R_40()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_34() {\r
+    if (jj_3R_38()) return true;\r
+    if (jj_3R_33()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_37() {\r
+    if (jj_3R_39()) return true;\r
+    if (jj_3R_36()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_44() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(80)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(81)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(82)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(83)) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_40() {\r
+    if (jj_3R_42()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_43()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_52() {\r
+    if (jj_3R_17()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_58()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_75() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_73()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_62() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_54()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_14() {\r
+    if (jj_3R_15()) return true;\r
+    if (jj_scan_token(86)) return true;\r
+    if (jj_3R_17()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_67() {\r
+    if (jj_scan_token(21)) return true;\r
+    if (jj_3R_72()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_24() {\r
+    if (jj_scan_token(20)) return true;\r
+    if (jj_3R_17()) return true;\r
+    if (jj_scan_token(28)) return true;\r
+    if (jj_3R_17()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_36() {\r
+    if (jj_3R_40()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_41()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_39() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(76)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(77)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(78)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(79)) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_51() {\r
+    if (jj_3R_15()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_56()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_57()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_31() {\r
+    if (jj_scan_token(9)) return true;\r
+    if (jj_3R_30()) return true;\r
+    return false;\r
+  }\r
+\r
+  /** Generated Token Manager. */\r
+  public ExpressionParserTokenManager token_source;\r
+  SimpleCharStream jj_input_stream;\r
+  /** Current token. */\r
+  public Token token;\r
+  /** Next token. */\r
+  public Token jj_nt;\r
+  private int jj_ntk;\r
+  private Token jj_scanpos, jj_lastpos;\r
+  private int jj_la;\r
+  private int jj_gen;\r
+  final private int[] jj_la1 = new int[43];\r
+  static private int[] jj_la1_0;\r
+  static private int[] jj_la1_1;\r
+  static private int[] jj_la1_2;\r
+  static {\r
+      jj_la1_init_0();\r
+      jj_la1_init_1();\r
+      jj_la1_init_2();\r
+   }\r
+   private static void jj_la1_init_0() {\r
+      jj_la1_0 = new int[] {0x100000,0x80001040,0x100000,0x80001040,0x0,0x0,0x400000,0x200,0x1000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x0,0x80001040,0x0,0x200000,0x200000,0x80001040,0x0,0x0,0x80001040,0x0,0x80001040,0x0,0x0,0x0,0x0,0x0,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_1() {\r
+      jj_la1_1 = new int[] {0x0,0x5000000a,0x0,0x5000000a,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x50000008,0x0,0x0,0x0,0x0,0x0,0x5000000a,0x0,0x0,0x0,0x5000000a,0x0,0x200,0x5000000a,0x0,0x5000000a,0x0,0x0,0x0,0x0,0x0,0x40000000,0x0,};\r
+   }\r
+   private static void jj_la1_init_2() {\r
+      jj_la1_2 = new int[] {0x0,0x1f00f001,0x0,0x1f00f001,0x8,0x8,0x0,0x0,0x0,0xfc0,0xfc0,0xf000,0xf000,0xf000,0xf0000,0x300000,0x300000,0xf0000,0x10,0x1c000000,0x3000001,0x3000000,0x3000000,0x4,0x1,0x4,0x1f00f001,0x20,0x20,0x20,0x1f00f001,0x20,0x0,0x1f00f001,0x20,0x1f00f001,0x20,0x20,0x8,0x20,0x8,0xb000000,0xb000000,};\r
+   }\r
+  final private JJCalls[] jj_2_rtns = new JJCalls[3];\r
+  private boolean jj_rescan = false;\r
+  private int jj_gc = 0;\r
+\r
+  /** Constructor with InputStream. */\r
+  public ExpressionParser(java.io.InputStream stream) {\r
+     this(stream, null);\r
+  }\r
+  /** Constructor with InputStream and supplied encoding */\r
+  public ExpressionParser(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source = new ExpressionParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 43; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream) {\r
+     ReInit(stream, null);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 43; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Constructor. */\r
+  public ExpressionParser(java.io.Reader stream) {\r
+    jj_input_stream = new SimpleCharStream(stream, 1, 1);\r
+    token_source = new ExpressionParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 43; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader stream) {\r
+    jj_input_stream.ReInit(stream, 1, 1);\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 43; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Constructor with generated Token Manager. */\r
+  public ExpressionParser(ExpressionParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 43; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(ExpressionParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 43; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  private Token jj_consume_token(int kind) throws ParseException {\r
+    Token oldToken;\r
+    if ((oldToken = token).next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    if (token.kind == kind) {\r
+      jj_gen++;\r
+      if (++jj_gc > 100) {\r
+        jj_gc = 0;\r
+        for (int i = 0; i < jj_2_rtns.length; i++) {\r
+          JJCalls c = jj_2_rtns[i];\r
+          while (c != null) {\r
+            if (c.gen < jj_gen) c.first = null;\r
+            c = c.next;\r
+          }\r
+        }\r
+      }\r
+      return token;\r
+    }\r
+    token = oldToken;\r
+    jj_kind = kind;\r
+    throw generateParseException();\r
+  }\r
+\r
+  static private final class LookaheadSuccess extends java.lang.Error { }\r
+  final private LookaheadSuccess jj_ls = new LookaheadSuccess();\r
+  private boolean jj_scan_token(int kind) {\r
+    if (jj_scanpos == jj_lastpos) {\r
+      jj_la--;\r
+      if (jj_scanpos.next == null) {\r
+        jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();\r
+      } else {\r
+        jj_lastpos = jj_scanpos = jj_scanpos.next;\r
+      }\r
+    } else {\r
+      jj_scanpos = jj_scanpos.next;\r
+    }\r
+    if (jj_rescan) {\r
+      int i = 0; Token tok = token;\r
+      while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }\r
+      if (tok != null) jj_add_error_token(kind, i);\r
+    }\r
+    if (jj_scanpos.kind != kind) return true;\r
+    if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;\r
+    return false;\r
+  }\r
+\r
+\r
+/** Get the next Token. */\r
+  final public Token getNextToken() {\r
+    if (token.next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    jj_gen++;\r
+    return token;\r
+  }\r
+\r
+/** Get the specific Token. */\r
+  final public Token getToken(int index) {\r
+    Token t = token;\r
+    for (int i = 0; i < index; i++) {\r
+      if (t.next != null) t = t.next;\r
+      else t = t.next = token_source.getNextToken();\r
+    }\r
+    return t;\r
+  }\r
+\r
+  private int jj_ntk() {\r
+    if ((jj_nt=token.next) == null)\r
+      return (jj_ntk = (token.next=token_source.getNextToken()).kind);\r
+    else\r
+      return (jj_ntk = jj_nt.kind);\r
+  }\r
+\r
+  private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();\r
+  private int[] jj_expentry;\r
+  private int jj_kind = -1;\r
+  private int[] jj_lasttokens = new int[100];\r
+  private int jj_endpos;\r
+\r
+  private void jj_add_error_token(int kind, int pos) {\r
+    if (pos >= 100) return;\r
+    if (pos == jj_endpos + 1) {\r
+      jj_lasttokens[jj_endpos++] = kind;\r
+    } else if (jj_endpos != 0) {\r
+      jj_expentry = new int[jj_endpos];\r
+      for (int i = 0; i < jj_endpos; i++) {\r
+        jj_expentry[i] = jj_lasttokens[i];\r
+      }\r
+      jj_entries_loop: for (java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();) {\r
+        int[] oldentry = (int[])(it.next());\r
+        if (oldentry.length == jj_expentry.length) {\r
+          for (int i = 0; i < jj_expentry.length; i++) {\r
+            if (oldentry[i] != jj_expentry[i]) {\r
+              continue jj_entries_loop;\r
+            }\r
+          }\r
+          jj_expentries.add(jj_expentry);\r
+          break jj_entries_loop;\r
+        }\r
+      }\r
+      if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;\r
+    }\r
+  }\r
+\r
+  /** Generate ParseException. */\r
+  public ParseException generateParseException() {\r
+    jj_expentries.clear();\r
+    boolean[] la1tokens = new boolean[93];\r
+    if (jj_kind >= 0) {\r
+      la1tokens[jj_kind] = true;\r
+      jj_kind = -1;\r
+    }\r
+    for (int i = 0; i < 43; i++) {\r
+      if (jj_la1[i] == jj_gen) {\r
+        for (int j = 0; j < 32; j++) {\r
+          if ((jj_la1_0[i] & (1<<j)) != 0) {\r
+            la1tokens[j] = true;\r
+          }\r
+          if ((jj_la1_1[i] & (1<<j)) != 0) {\r
+            la1tokens[32+j] = true;\r
+          }\r
+          if ((jj_la1_2[i] & (1<<j)) != 0) {\r
+            la1tokens[64+j] = true;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    for (int i = 0; i < 93; i++) {\r
+      if (la1tokens[i]) {\r
+        jj_expentry = new int[1];\r
+        jj_expentry[0] = i;\r
+        jj_expentries.add(jj_expentry);\r
+      }\r
+    }\r
+    jj_endpos = 0;\r
+    jj_rescan_token();\r
+    jj_add_error_token(0, 0);\r
+    int[][] exptokseq = new int[jj_expentries.size()][];\r
+    for (int i = 0; i < jj_expentries.size(); i++) {\r
+      exptokseq[i] = jj_expentries.get(i);\r
+    }\r
+    return new ParseException(token, exptokseq, tokenImage);\r
+  }\r
+\r
+  /** Enable tracing. */\r
+  final public void enable_tracing() {\r
+  }\r
+\r
+  /** Disable tracing. */\r
+  final public void disable_tracing() {\r
+  }\r
+\r
+  private void jj_rescan_token() {\r
+    jj_rescan = true;\r
+    for (int i = 0; i < 3; i++) {\r
+    try {\r
+      JJCalls p = jj_2_rtns[i];\r
+      do {\r
+        if (p.gen > jj_gen) {\r
+          jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;\r
+          switch (i) {\r
+            case 0: jj_3_1(); break;\r
+            case 1: jj_3_2(); break;\r
+            case 2: jj_3_3(); break;\r
+          }\r
+        }\r
+        p = p.next;\r
+      } while (p != null);\r
+      } catch(LookaheadSuccess ls) { }\r
+    }\r
+    jj_rescan = false;\r
+  }\r
+\r
+  private void jj_save(int index, int xla) {\r
+    JJCalls p = jj_2_rtns[index];\r
+    while (p.gen > jj_gen) {\r
+      if (p.next == null) { p = p.next = new JJCalls(); break; }\r
+      p = p.next;\r
+    }\r
+    p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;\r
+  }\r
+\r
+  static final class JJCalls {\r
+    int gen;\r
+    Token first;\r
+    int arg;\r
+    JJCalls next;\r
+  }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.jj b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParser.jj
new file mode 100644 (file)
index 0000000..ce3aa44
--- /dev/null
@@ -0,0 +1,430 @@
+options {\r
+  JDK_VERSION = "1.6";\r
+  STATIC = false;\r
+}\r
+\r
+PARSER_BEGIN(ExpressionParser)\r
+package org.simantics.sysdyn.expressionParser;\r
+\r
+import java.util.Set;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+@SuppressWarnings({"unused", "serial"})\r
+public class ExpressionParser {\r
+\r
+    public class ForRange {\r           public Token start;\r
+               public Token end;\r
+    }\r
+\r
+    boolean forIndex = false;\r
+    Token firstToken;\r
+\r
+    public Token getFirstToken() {\r            return firstToken;\r
+     }\r\r
+       List<ForRange> forRanges = new ArrayList<ForRange>();\r
+    \r
+    public List<ForRange> getForRanges() {\r
+        return forRanges;\r
+    }\r
+    \r
+       HashMap<String, List<Token>> references = new HashMap<String, List<Token>>();\r
+    \r
+    public HashMap<String, List<Token>> getReferences() {\r
+        return references;\r
+    }\r
+\r
+    HashMap<String, List<List<Token>>> ranges = new HashMap<String, List<List<Token>>>();\r
+    \r
+    public HashMap<String, List<List<Token>>> getRanges() {\r
+        return ranges;\r
+    }\r
+\r
+       List<Token> currentRange = null;\r
+\r
+       HashMap<Token, List<Token>> forIndices = new HashMap<Token, List<Token>>();\r
+\r
+    public HashMap<Token, List<Token>> getForIndices() {\r
+        return forIndices;\r
+    }\r
+\r
+    HashMap<String, List<Token>> enumerationReferences = new HashMap<String, List<Token>>();\r
+    \r
+    public HashMap<String, List<Token>> getEnumerationReferences() {\r
+        return enumerationReferences;\r
+    }\r
+\r
+/*\r
+    Collect EACH function call and all references that are inside the call brackets.\r
+    These are later used to exclude spread sheet references out of the normal functions.\r
+*/\r
+    String functionCall = null;\r
+    HashMap<String, List<Token>> functionCallReferences = new HashMap<String, List<Token>>();\r
+    \r
+    public HashMap<String, List<Token>> getFunctionCallReferences() {\r
+        return functionCallReferences;\r
+    }    \r
+    \r
+    \r
+}\r
+PARSER_END(ExpressionParser)\r
+\r
+/*** Lexer *********************************************************/\r
+\r
+SKIP:\r
+{ <WHITESPACE: " " | "\n" | "\r" | "\t" > \r
+| <COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/" >  \r
+| <COMMENT2: "//" (~["\n"])* >\r
+}\r
+\r
+TOKEN:\r
+{\r
+"algorithm"    | "discrete"    | "false"       | "model"       | "redeclare"\r
+| "and"                | "each"                | "final"       | "not"         | "replaceable"\r
+| "annotation" | "else"                | "flow"        | "operator" | "return"\r
+|"assert"              | "elseif"              | "for"         | "or"          | "stream"\r
+| "block"              | "elsewhen"    | "function" | "outer"  | "then"\r
+| "break"              | "encapsulated" | "if"         | "output"      | "true"\r
+| "class"              | "end"                 | "import"      | "package" | "type"\r
+| "connect"    | "enumeration" | "in"          | "parameter" | "when"\r
+| "connector"  | "equation"    | /*"initial" |*/ "partial" | "while"\r
+| "constant"   | "expandable"  | "inner"       | "protected" | "within"\r
+| "constrainedby" | "extends"  | "input"       | "public"\r
+| /*"der"              |*/ "external"  | "loop"        | "record"\r
+| "(" | ")" | "{" | "}" | "[" | "]" | "." | ":" | ";" | ","\r
+| "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+| "+" | "-" | ".+" | ".-"\r
+| "*" | "/" | ".*" | "./"\r
+| "^" | ".^"\r
+| "=" | ":=" \r
+| <IDENT: ["a"-"z","A"-"Z","_"] (["a"-"z","A"-"Z","_","0"-"9"])* >\r
+| <QIDENT: "'" (["a"-"z","A"-"Z","_","0"-"9","!","*","+",",",\r
+ "-",".","/",":",";","=","?","@","^","~"," ","\'","\\","\b","\f"])* "'" >\r
+ /* Excluded "#","$","%","&","(",")","<",">","[","]","{","}","|", and "\"" because of Sysdyn */\r
+ /* Excluded "\?", "\a", and "\v" because of JavaCC */\r
+ /* Excluded "\n","\r", and "\t" just in case */\r
+| <STRING: "\"" (~["\"", "\\", "\n"] | "\\" ~["\n"])* "\"">\r
+    { matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); }\r
+| <UNSIGNED_INTEGER: (["0"-"9"])+ >\r
+| <UNSIGNED_NUMBER:  \r
+    ( <UNSIGNED_INTEGER> "." (<UNSIGNED_INTEGER>)? (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | "." <UNSIGNED_INTEGER> (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | <UNSIGNED_INTEGER> ["e","E"] (["+","-"])? <UNSIGNED_INTEGER>\r
+    ) >\r
+}\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+\r
+void expr() : {\r
+       jj_input_stream.setTabSize(1);\r
+} {\r
+       {\r
+               firstToken = token;\r
+       }\r
+       simple_expression() <EOF>\r
+       |\r
+       {\r
+               firstToken = token;\r
+       }\r
+       "if" expression() "then" expression() ( "elseif" expression() "then" expression() )*\r
+       "else" expression() <EOF>\r
+}\r
+\r
+void expression() : {\r
+} {\r
+       simple_expression()\r
+       | "if" expression() "then" expression() ( "elseif" expression() "then" expression() )*\r
+       "else" expression()\r
+}\r
+\r
+void simple_expression() : {\r
+} {\r
+       logical_expression() ( ":" logical_expression() ( ":" logical_expression() )? )?\r
+}      \r
+\r
+void logical_expression() : {\r
+} {\r
+       logical_term() ( "or" logical_term() )*\r
+}      \r
+\r
+void logical_term() : {\r
+} {\r
+       logical_factor() ( "and" logical_factor() )*\r
+}\r
+\r
+void logical_factor() : {\r
+} {\r
+       ( "not" )? relation()\r
+}\r
+\r
+void relation() : {\r
+} {\r
+       arithmetic_expression() ( rel_op() arithmetic_expression() )?\r
+}\r
+\r
+void rel_op() : {\r
+} {\r
+       "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+}\r
+\r
+void arithmetic_expression() : {\r
+} {\r
+    (add_op())? term() (add_op() term())*\r
+}\r
+\r
+void add_op() : {\r
+} {\r
+    "+" | "-" | ".+" | ".-"\r
+}\r
+\r
+void term() : {\r
+} {\r
+    factor() ( mul_op() factor() )*\r
+}\r
+\r
+void factor() : {\r
+} {\r
+       primary() ( ( "^" | ".^" ) primary() )?\r
+}\r
+\r
+void mul_op() : {\r
+} {\r
+    "*" | "/" | ".*" | "./"\r
+}\r
+\r
+void primary() : {\r
+} {\r
+       <UNSIGNED_NUMBER>\r
+  | <UNSIGNED_INTEGER>\r
+  | <STRING>\r
+  | "false"\r
+  | "true"\r
+  |   LOOKAHEAD( name() "(" )\r  {\r    functionCall = null;\r
+  }\r
+    name() function_call_args()\r  {\r    functionCall = null;\r
+  }    \r
+  | component_reference(null)\r
+  /*| "(" output_expression_list() ")"*/ // Not needed, replaced with following:\r
+  | "(" expression() ")"\r
+  | "[" expression_list() ( ";" expression_list() )* "]"\r
+  | "{" function_arguments() "}"\r
+  | "end"\r
+}\r
+\r
+Token ident() : {\r
+  Token concatToken = null;\r
+  Token continuationToken = null;\r
+  String fullStr = null;\r
+} {\r
+  <IDENT>\r
+  { concatToken = token; }\r
+  ( continuationToken = ident()\r
+  {\r
+    fullStr = new String("");\r
+    // Replace whitespace sequence with a single space character.\r
+    fullStr += concatToken.image + " " + continuationToken.image;\r
+    \r
+    Token tempToken = new Token(concatToken.kind, fullStr);\r
+    tempToken.beginLine = concatToken.beginLine;\r
+    tempToken.beginColumn = concatToken.beginColumn;\r
+    tempToken.endLine = token.endLine;\r
+    tempToken.endColumn = token.endColumn;\r
+       concatToken = tempToken;\r
+  }\r
+  )?\r
+  {\r    return concatToken;\r
+  }\r
+  |\r
+  <QIDENT>\r
+  {\r
+    return token;\r
+  }\r
+}\r\r
+void name() : {\r
+  Token identToken = null;\r
+} {\r
+       identToken = ident()\r
+       {\r    if (functionCall == null)\r
+        functionCall = identToken.image;\r
+    else\r
+        functionCall += "." + identToken.image;\r
+       }\r
+       ( "." name() )?\r
+}\r
+\r
+void component_reference(String prevToken) : {\r
+    Token identToken = null;\r
+} {\r
+    //IDENT [ array_subscripts ] [ "." component_reference ]\r
+       identToken = ident()\r
+       {\r
+    String name = identToken.image;\r
+       // forIndex == true and prevToken != null => this is the second part of an enumeration in for-index\r
+       if(forIndex == true) {\r    if(prevToken != null) {\r
+                       if(enumerationReferences.get(prevToken) == null) {\r                             enumerationReferences.put(prevToken, new ArrayList<Token>());\r
+                       }\r
+                       List<Token> list = enumerationReferences.get(prevToken);\r
+                       list.add(identToken);           \r
+       \r
+               // forIndex == true and prevToken == null => this is the enumeration in for-index\r
+               } else {\r
+                       if(enumerationReferences.get(name) == null) {\r
+                               enumerationReferences.put(name, new ArrayList<Token>());\r
+                       }\r
+                       List<Token> list = enumerationReferences.get(name);\r
+                       list.add(identToken);\r
+        }\r
+       } else {\r
+           if(prevToken != null)\r
+               name = prevToken + "." + name; \r                if(references.get(name) == null) {\r
+                       references.put(name, new ArrayList<Token>());\r
+               }\r
+               List<Token> list = references.get(name);\r
+               list.add(identToken);\r
+\r
+               if(functionCall != null) {\r
+                 if(!functionCallReferences.containsKey(functionCall))\r
+                     functionCallReferences.put(functionCall, new ArrayList<Token>());\r
+            List<Token> functionReferencelist = getFunctionCallReferences().get(functionCall);\r
+            functionReferencelist.add(identToken);\r            }\r
+       }\r
+\r
+       }\r
+       \r
+       ( array_subscripts(identToken) )? ( "." component_reference(name) )?\r
+}\r
+\r
+void function_call_args() : {\r
+} {\r
+       "(" ( function_arguments() )? ")"\r      {\r        if(functionCall != null) {\r
+          if(!functionCallReferences.containsKey(functionCall))\r
+              functionCallReferences.put(functionCall, new ArrayList<Token>());\r
+            }\r
+       }\r
+}\r
+\r
+void function_arguments() : {\r
+} {\r
+       //expression [ "," function_arguments | for for_indices ]\r
+       //| named_arguments\r
+       LOOKAHEAD(named_argument()) named_argument()  ( "," function_arguments() )?\r
+       | expression() ( "," function_arguments() | "for" for_indices() )?\r
+       \r
+}\r
+\r
+void for_indices() : {\r
+} {\r
+       //for_index {"," for_index}\r
+       for_index() ("," for_index())*\r
+}\r
+\r
+void for_index() : {\r
+    Token identToken = null;\r
+} {\r
+       //IDENT [ in expression ]\r
+       identToken = ident()\r
+       {\r
+               forIndices.put(identToken, currentRange);\r
+               forIndex = true;\r       }\r
+               ( "in"\r         {\r
+                 ForRange forRange = new ForRange();\r
+                 forRange.start = token;\r              }\r
+               expression()\r           {\r
+                 forRange.start = forRange.start.next;\r
+                 forRange.end = token;\r
+                 forRanges.add(forRange);\r             }\r
+               )?\r
+       {\r              forIndex = false;\r
+       }\r
+}\r
+\r
+/* Removed by Teemu. Refactored in function_arguments)\r
+void named_arguments() : {\r
+} {\r
+       named_argument() ( "," named_arguments() )?\r
+}\r
+*/\r
+\r
+void named_argument() : {\r
+} {    \r
+       ident() "=" expression()\r
+}\r
+\r
+void output_expression_list() : {\r
+} {\r
+       ( expression() )? ( "," ( expression() )? )*\r
+}\r
+\r
+\r
+void expression_list() : {\r
+} {\r
+    expression() ( "," expression() )*\r
+}\r
+\r
+void array_subscripts(Token prevToken) : {\r    if(ranges.get(prevToken.image) == null) {\r
+               ranges.put(prevToken.image, new ArrayList<List<Token>>());\r
+       }\r
+       List<List<Token>> rangesList = ranges.get(prevToken.image);\r
+       currentRange = new ArrayList<Token>(); \r
+} {\r
+       "[" subscript(currentRange) ( "," subscript(currentRange) )* "]"\r
+       {\r
+       rangesList.add(currentRange);\r
+       }\r
+}\r
+\r
+void subscript(List<Token> currentRange) : {\r
+  Token rangeToken = new Token(token.kind, "");\r
+  rangeToken.beginColumn = token.beginColumn + 1;\r
+  rangeToken.beginLine = token.beginLine;\r
+} {\r   ":"\r    {\r          currentRange.add(token);\r
+       }\r
+       |   LOOKAHEAD( name() "(" )\r
+    {\r
+        functionCall = null;\r
+    }\r
+        name() function_call_args()\r
+    {\r
+        functionCall = null;\r
+        rangeToken.image = "";\r
+           rangeToken.endColumn = token.endColumn;\r
+           rangeToken.endLine = token.endLine;\r
+           currentRange.add(rangeToken);\r
+    }\r
+       | rangeIndex(rangeToken, true, ":") ( ":" rangeIndex(rangeToken, false, ":"))?  {\r
+           rangeToken.endColumn = token.endColumn;\r
+           rangeToken.endLine = token.endLine;\r
+               currentRange.add(rangeToken);\r
+       }\r
+       | "{"\r
+       {\r          rangeToken.image = rangeToken.image + token.image;\r
+       }\r
+               rangeIndex(rangeToken, true, ",") ( "," rangeIndex(rangeToken, false, ","))*\r
+       {\r
+           rangeToken.endColumn = token.endColumn;\r
+           rangeToken.endLine = token.endLine;\r
+               currentRange.add(rangeToken);\r
+       }\r
+               "}"\r
+       {\r              rangeToken.image = rangeToken.image + token.image;\r
+       }\r
+}\r
+\r
+void rangeIndex(Token rangeToken, boolean first, String delim) : {\r
+  Token identToken = null;\r
+  if(!first)\r
+       rangeToken.image = rangeToken.image + delim;\r
+} {\r   <UNSIGNED_INTEGER>\r     {\r
+               rangeToken.image = rangeToken.image + token.image;  \r   }\r
+       | identToken = ident()\r
+       {\r              rangeToken.image = rangeToken.image + identToken;\r
+       }\r
+}\r  \r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserConstants.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserConstants.java
new file mode 100644 (file)
index 0000000..62dfa36
--- /dev/null
@@ -0,0 +1,130 @@
+/* Generated By:JavaCC: Do not edit this line. ExpressionParserConstants.java */\r
+package org.simantics.sysdyn.expressionParser;\r
+\r
+\r
+/**\r
+ * Token literal values and constants.\r
+ * Generated by org.javacc.parser.OtherFilesGen#start()\r
+ */\r
+public interface ExpressionParserConstants {\r
+\r
+  /** End of File. */\r
+  int EOF = 0;\r
+  /** RegularExpression Id. */\r
+  int WHITESPACE = 1;\r
+  /** RegularExpression Id. */\r
+  int COMMENT1 = 2;\r
+  /** RegularExpression Id. */\r
+  int COMMENT2 = 3;\r
+  /** RegularExpression Id. */\r
+  int IDENT = 88;\r
+  /** RegularExpression Id. */\r
+  int QIDENT = 89;\r
+  /** RegularExpression Id. */\r
+  int STRING = 90;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_INTEGER = 91;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_NUMBER = 92;\r
+\r
+  /** Lexical state. */\r
+  int DEFAULT = 0;\r
+\r
+  /** Literal token values. */\r
+  String[] tokenImage = {\r
+    "<EOF>",\r
+    "<WHITESPACE>",\r
+    "<COMMENT1>",\r
+    "<COMMENT2>",\r
+    "\"algorithm\"",\r
+    "\"discrete\"",\r
+    "\"false\"",\r
+    "\"model\"",\r
+    "\"redeclare\"",\r
+    "\"and\"",\r
+    "\"each\"",\r
+    "\"final\"",\r
+    "\"not\"",\r
+    "\"replaceable\"",\r
+    "\"annotation\"",\r
+    "\"else\"",\r
+    "\"flow\"",\r
+    "\"operator\"",\r
+    "\"return\"",\r
+    "\"assert\"",\r
+    "\"elseif\"",\r
+    "\"for\"",\r
+    "\"or\"",\r
+    "\"stream\"",\r
+    "\"block\"",\r
+    "\"elsewhen\"",\r
+    "\"function\"",\r
+    "\"outer\"",\r
+    "\"then\"",\r
+    "\"break\"",\r
+    "\"encapsulated\"",\r
+    "\"if\"",\r
+    "\"output\"",\r
+    "\"true\"",\r
+    "\"class\"",\r
+    "\"end\"",\r
+    "\"import\"",\r
+    "\"package\"",\r
+    "\"type\"",\r
+    "\"connect\"",\r
+    "\"enumeration\"",\r
+    "\"in\"",\r
+    "\"parameter\"",\r
+    "\"when\"",\r
+    "\"connector\"",\r
+    "\"equation\"",\r
+    "\"partial\"",\r
+    "\"while\"",\r
+    "\"constant\"",\r
+    "\"expandable\"",\r
+    "\"inner\"",\r
+    "\"protected\"",\r
+    "\"within\"",\r
+    "\"constrainedby\"",\r
+    "\"extends\"",\r
+    "\"input\"",\r
+    "\"public\"",\r
+    "\"external\"",\r
+    "\"loop\"",\r
+    "\"record\"",\r
+    "\"(\"",\r
+    "\")\"",\r
+    "\"{\"",\r
+    "\"}\"",\r
+    "\"[\"",\r
+    "\"]\"",\r
+    "\".\"",\r
+    "\":\"",\r
+    "\";\"",\r
+    "\",\"",\r
+    "\"<\"",\r
+    "\"<=\"",\r
+    "\">\"",\r
+    "\">=\"",\r
+    "\"==\"",\r
+    "\"<>\"",\r
+    "\"+\"",\r
+    "\"-\"",\r
+    "\".+\"",\r
+    "\".-\"",\r
+    "\"*\"",\r
+    "\"/\"",\r
+    "\".*\"",\r
+    "\"./\"",\r
+    "\"^\"",\r
+    "\".^\"",\r
+    "\"=\"",\r
+    "\":=\"",\r
+    "<IDENT>",\r
+    "<QIDENT>",\r
+    "<STRING>",\r
+    "<UNSIGNED_INTEGER>",\r
+    "<UNSIGNED_NUMBER>",\r
+  };\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserTokenManager.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ExpressionParserTokenManager.java
new file mode 100644 (file)
index 0000000..85adbb7
--- /dev/null
@@ -0,0 +1,1361 @@
+/* Generated By:JavaCC: Do not edit this line. ExpressionParserTokenManager.java */\r
+package org.simantics.sysdyn.expressionParser;\r
+import java.util.Set;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+/** Token Manager. */\r
+public class ExpressionParserTokenManager implements ExpressionParserConstants\r
+{\r
+\r
+  /** Debug output. */\r
+  public  java.io.PrintStream debugStream = System.out;\r
+  /** Set debug output. */\r
+  public  void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }\r
+private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1)
+{\r
+   switch (pos)
+   {\r
+      case 0:\r
+         if ((active1 & 0x2cc004L) != 0L)\r
+            return 12;\r
+         if ((active0 & 0xffffffffffffff0L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            return 2;\r
+         }\r
+         if ((active1 & 0x20000L) != 0L)\r
+            return 17;\r
+         return -1;\r
+      case 1:\r
+         if ((active0 & 0x84020080400000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0xf7bfdff7fbffff0L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 1)\r
+            {\r
+               jjmatchedKind = 88;\r
+               jjmatchedPos = 1;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 2:\r
+         if ((active0 & 0x800201200L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0xffffdf77f9fedf0L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 2;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 3:\r
+         if ((active0 & 0x400084212118400L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0xbfff5b56d8e69f0L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 3)\r
+            {\r
+               jjmatchedKind = 88;\r
+               jjmatchedPos = 3;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 4:\r
+         if ((active0 & 0x848004290008c0L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0xb7b75b1469e6130L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 4;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 5:\r
+         if ((active0 & 0x9100011009c0000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x26b75a046026130L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 5;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 6:\r
+         if ((active0 & 0x4050a000000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x22b250046026130L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 6)\r
+            {\r
+               jjmatchedKind = 88;\r
+               jjmatchedPos = 6;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 7:\r
+         if ((active0 & 0x201200006020020L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x2a150040006110L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 7;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 8:\r
+         if ((active0 & 0x22010040006000L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 8;\r
+            return 2;\r
+         }\r
+         if ((active0 & 0x8140000000110L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      case 9:\r
+         if ((active0 & 0x2000000004000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x20010040002000L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 9;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 10:\r
+         if ((active0 & 0x10000002000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x20000040000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 10;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 11:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x20000000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 11;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      default :\r
+         return -1;\r
+   }\r
+}\r
+private final int jjStartNfa_0(int pos, long active0, long active1)
+{\r
+   return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1);\r
+}\r
+private int jjStopAtPos(int pos, int kind)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   return pos + 1;\r
+}\r
+private int jjMoveStringLiteralDfa0_0()\r
+{\r
+   switch(curChar)\r
+   {\r
+      case 40:\r
+         return jjStopAtPos(0, 60);\r
+      case 41:\r
+         return jjStopAtPos(0, 61);\r
+      case 42:\r
+         return jjStopAtPos(0, 80);\r
+      case 43:\r
+         return jjStopAtPos(0, 76);\r
+      case 44:\r
+         return jjStopAtPos(0, 69);\r
+      case 45:\r
+         return jjStopAtPos(0, 77);\r
+      case 46:\r
+         jjmatchedKind = 66;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x2cc000L);\r
+      case 47:\r
+         return jjStartNfaWithStates_0(0, 81, 17);\r
+      case 58:\r
+         jjmatchedKind = 67;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x800000L);\r
+      case 59:\r
+         return jjStopAtPos(0, 68);\r
+      case 60:\r
+         jjmatchedKind = 70;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x880L);\r
+      case 61:\r
+         jjmatchedKind = 86;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x400L);\r
+      case 62:\r
+         jjmatchedKind = 72;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x200L);\r
+      case 91:\r
+         return jjStopAtPos(0, 64);\r
+      case 93:\r
+         return jjStopAtPos(0, 65);\r
+      case 94:\r
+         return jjStopAtPos(0, 84);\r
+      case 97:\r
+         return jjMoveStringLiteralDfa1_0(0x84210L, 0x0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa1_0(0x21000000L, 0x0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa1_0(0x21108400000000L, 0x0L);\r
+      case 100:\r
+         return jjMoveStringLiteralDfa1_0(0x20L, 0x0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa1_0(0x242210842108400L, 0x0L);\r
+      case 102:\r
+         return jjMoveStringLiteralDfa1_0(0x4210840L, 0x0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa1_0(0x84021080000000L, 0x0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa1_0(0x400000000000000L, 0x0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa1_0(0x80L, 0x0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa1_0(0x1000L, 0x0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa1_0(0x108420000L, 0x0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa1_0(0x108442000000000L, 0x0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa1_0(0x800000000042100L, 0x0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa1_0(0x800000L, 0x0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa1_0(0x4210000000L, 0x0L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa1_0(0x10880000000000L, 0x0L);\r
+      case 123:\r
+         return jjStopAtPos(0, 62);\r
+      case 125:\r
+         return jjStopAtPos(0, 63);\r
+      default :\r
+         return jjMoveNfa_0(0, 0);\r
+   }\r
+}\r
+private int jjMoveStringLiteralDfa1_0(long active0, long active1)\r
+{\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(0, active0, active1);\r
+      return 1;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 42:\r
+         if ((active1 & 0x40000L) != 0L)\r
+            return jjStopAtPos(1, 82);\r
+         break;\r
+      case 43:\r
+         if ((active1 & 0x4000L) != 0L)\r
+            return jjStopAtPos(1, 78);\r
+         break;\r
+      case 45:\r
+         if ((active1 & 0x8000L) != 0L)\r
+            return jjStopAtPos(1, 79);\r
+         break;\r
+      case 47:\r
+         if ((active1 & 0x80000L) != 0L)\r
+            return jjStopAtPos(1, 83);\r
+         break;\r
+      case 61:\r
+         if ((active1 & 0x80L) != 0L)\r
+            return jjStopAtPos(1, 71);\r
+         else if ((active1 & 0x200L) != 0L)\r
+            return jjStopAtPos(1, 73);\r
+         else if ((active1 & 0x400L) != 0L)\r
+            return jjStopAtPos(1, 74);\r
+         else if ((active1 & 0x800000L) != 0L)\r
+            return jjStopAtPos(1, 87);\r
+         break;\r
+      case 62:\r
+         if ((active1 & 0x800L) != 0L)\r
+            return jjStopAtPos(1, 75);\r
+         break;\r
+      case 94:\r
+         if ((active1 & 0x200000L) != 0L)\r
+            return jjStopAtPos(1, 85);\r
+         break;\r
+      case 97:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x442000000440L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x800000000042100L, active1, 0L);\r
+      case 102:\r
+         if ((active0 & 0x80000000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 31, 2);\r
+         break;\r
+      case 104:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x880010000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x10000000000820L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x403118010L, active1, 0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1000000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x20000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 41;\r
+            jjmatchedPos = 1;\r
+         }\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x84010840004200L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x421108000201080L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000L, active1, 0L);\r
+      case 113:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x200000000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x400000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 22, 2);\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x8000220000000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x80000L, active1, 0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x800000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x10000010c000000L, active1, 0L);\r
+      case 120:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x242000000000000L, active1, 0L);\r
+      case 121:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x4000000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(0, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(0, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(1, active0, 0L);\r
+      return 2;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x400000000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x100000000000000L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x800002040000400L);\r
+      case 100:\r
+         if ((active0 & 0x200L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 9, 2);\r
+         else if ((active0 & 0x800000000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 35, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x180L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x80030020000L);\r
+      case 103:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x10L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x800000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x40L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x25108004004800L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x408000001010000L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x82005000002000L);\r
+      case 114:\r
+         if ((active0 & 0x200000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 21, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x440000800000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x2188020L);\r
+      case 116:\r
+         if ((active0 & 0x1000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 12, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x250000108040000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x210200000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(1, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa3_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(1, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(2, active0, 0L);\r
+      return 3;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2240060000800L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x5000020L);\r
+      case 101:\r
+         if ((active0 & 0x8000L) != 0L)\r
+         {\r
+            jjmatchedKind = 15;\r
+            jjmatchedPos = 3;\r
+         }\r
+         else if ((active0 & 0x200000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 33, 2);\r
+         else if ((active0 & 0x4000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 38, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x24400000a980180L);\r
+      case 104:\r
+         if ((active0 & 0x400L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 10, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10000000000000L);\r
+      case 107:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100800000002000L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10000000000L);\r
+      case 110:\r
+         if ((active0 & 0x10000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 28, 2);\r
+         else if ((active0 & 0x80000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 43, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x108000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x800001000004010L);\r
+      case 112:\r
+         if ((active0 & 0x400000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 58, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100000000L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x20000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x21000400000040L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x8400000000000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x80000000040000L);\r
+      case 119:\r
+         if ((active0 & 0x10000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 16, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(2, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa4_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(2, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(3, active0, 0L);\r
+      return 4;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000822000L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100L);\r
+      case 101:\r
+         if ((active0 & 0x40L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 6, 2);\r
+         else if ((active0 & 0x800000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 47, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x8118000000000L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x110400000100000L);\r
+      case 107:\r
+         if ((active0 & 0x1000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 24, 2);\r
+         else if ((active0 & 0x20000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 29, 2);\r
+         break;\r
+      case 108:\r
+         if ((active0 & 0x80L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 7, 2);\r
+         else if ((active0 & 0x800L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 11, 2);\r
+         break;\r
+      case 109:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x42000000000000L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000L);\r
+      case 114:\r
+         if ((active0 & 0x8000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 27, 2);\r
+         else if ((active0 & 0x4000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 50, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0xa000010000c0030L);\r
+      case 115:\r
+         if ((active0 & 0x400000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 34, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x80000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 55, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x21200004004000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100000000L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(3, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa5_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(3, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(4, active0, 0L);\r
+      return 5;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x1400000004000L);\r
+      case 99:\r
+         if ((active0 & 0x100000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 56, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x8108000002000L);\r
+      case 100:\r
+         if ((active0 & 0x800000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 59, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x42000000000000L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000020L);\r
+      case 102:\r
+         if ((active0 & 0x100000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 20, 2);\r
+         break;\r
+      case 103:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000000L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x200004000010L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x100L);\r
+      case 109:\r
+         if ((active0 & 0x800000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 23, 2);\r
+         break;\r
+      case 110:\r
+         if ((active0 & 0x40000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 18, 2);\r
+         else if ((active0 & 0x10000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 52, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x200000000000000L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x20010000000000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000L);\r
+      case 116:\r
+         if ((active0 & 0x80000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 19, 2);\r
+         else if ((active0 & 0x100000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 32, 2);\r
+         else if ((active0 & 0x1000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 36, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x20000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(4, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa6_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(4, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(5, active0, 0L);\r
+      return 6;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x222010000000100L);\r
+      case 101:\r
+         if ((active0 & 0x2000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 37, 2);\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x2002000L);\r
+      case 108:\r
+         if ((active0 & 0x400000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 46, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x1000000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x200004020000L);\r
+      case 115:\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 54, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x8000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 39;\r
+            jjmatchedPos = 6;\r
+         }\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x8140000004030L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(5, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa7_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(5, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(6, active0, 0L);\r
+      return 7;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x2000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x2000000000000L);\r
+      case 101:\r
+         if ((active0 & 0x20L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 5, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x8040000000000L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x20000000004000L);\r
+      case 108:\r
+         if ((active0 & 0x200000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 57, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x40000000L);\r
+      case 110:\r
+         if ((active0 & 0x2000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 25, 2);\r
+         else if ((active0 & 0x4000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 26, 2);\r
+         else if ((active0 & 0x200000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 45, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100000000000L);\r
+      case 114:\r
+         if ((active0 & 0x20000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 17, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100L);\r
+      case 116:\r
+         if ((active0 & 0x1000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 48, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10000000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(6, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa8_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(6, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(7, active0, 0L);\r
+      return 8;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x40000000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x2000L);\r
+      case 100:\r
+         if ((active0 & 0x8000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 51, 2);\r
+         break;\r
+      case 101:\r
+         if ((active0 & 0x100L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 8, 2);\r
+         break;\r
+      case 105:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x10000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x2000000000000L);\r
+      case 109:\r
+         if ((active0 & 0x10L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 4, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x20000000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x4000L);\r
+      case 114:\r
+         if ((active0 & 0x40000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 42, 2);\r
+         else if ((active0 & 0x100000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 44, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(7, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa9_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(7, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(8, active0, 0L);\r
+      return 9;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 101:\r
+         if ((active0 & 0x2000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 49, 2);\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x20000000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x2000L);\r
+      case 110:\r
+         if ((active0 & 0x4000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 14, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x10000000000L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(8, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa10_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(8, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(9, active0, 0L);\r
+      return 10;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 100:\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x20000000000000L);\r
+      case 101:\r
+         if ((active0 & 0x2000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 13, 2);\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x40000000L);\r
+      case 110:\r
+         if ((active0 & 0x10000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 40, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(9, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa11_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(9, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(10, active0, 0L);\r
+      return 11;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 98:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0x20000000000000L);\r
+      case 100:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return jjStartNfaWithStates_0(11, 30, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(10, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa12_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(10, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(11, active0, 0L);\r
+      return 12;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 121:\r
+         if ((active0 & 0x20000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(12, 53, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(11, active0, 0L);\r
+}\r
+private int jjStartNfaWithStates_0(int pos, int kind, int state)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) { return pos + 1; }\r
+   return jjMoveNfa_0(state, pos + 1);\r
+}\r
+static final long[] jjbitVec0 = {
+   0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+};\r
+private int jjMoveNfa_0(int startState, int curPos)\r
+{\r
+   int startsAt = 0;\r
+   jjnewStateCnt = 37;\r
+   int i = 1;\r
+   jjstateSet[0] = startState;\r
+   int kind = 0x7fffffff;\r
+   for (;;)\r
+   {\r
+      if (++jjround == 0x7fffffff)\r
+         ReInitRounds();\r
+      if (curChar < 64)\r
+      {\r
+         long l = 1L << curChar;\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 0:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 91)\r
+                        kind = 91;\r
+                     jjCheckNAddStates(0, 4);\r
+                  }\r
+                  else if ((0x100002600L & l) != 0L)\r
+                  {\r
+                     if (kind > 1)\r
+                        kind = 1;\r
+                  }\r
+                  else if (curChar == 47)\r
+                     jjAddStates(5, 6);\r
+                  else if (curChar == 46)\r
+                     jjCheckNAdd(12);\r
+                  else if (curChar == 34)\r
+                     jjCheckNAddStates(7, 9);\r
+                  else if (curChar == 39)\r
+                     jjCheckNAddTwoStates(4, 5);\r
+                  break;\r
+               case 17:\r
+                  if (curChar == 47)\r
+                  {\r
+                     if (kind > 3)\r
+                        kind = 3;\r
+                     jjCheckNAdd(24);\r
+                  }\r
+                  else if (curChar == 42)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 2:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 88)\r
+                     kind = 88;\r
+                  jjstateSet[jjnewStateCnt++] = 2;\r
+                  break;\r
+               case 3:\r
+                  if (curChar == 39)\r
+                     jjCheckNAddTwoStates(4, 5);\r
+                  break;\r
+               case 4:\r
+                  if ((0xaffffc8300001100L & l) != 0L)\r
+                     jjCheckNAddTwoStates(4, 5);\r
+                  break;\r
+               case 5:\r
+                  if (curChar == 39 && kind > 89)\r
+                     kind = 89;\r
+                  break;\r
+               case 6:\r
+                  if (curChar == 34)\r
+                     jjCheckNAddStates(7, 9);\r
+                  break;\r
+               case 7:\r
+                  if ((0xfffffffbfffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(7, 9);\r
+                  break;\r
+               case 9:\r
+                  if ((0xfffffffffffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(7, 9);\r
+                  break;\r
+               case 10:\r
+                  if (curChar == 34 && kind > 90)\r
+                     kind = 90;\r
+                  break;\r
+               case 11:\r
+                  if (curChar == 46)\r
+                     jjCheckNAdd(12);\r
+                  break;\r
+               case 12:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAddTwoStates(12, 13);\r
+                  break;\r
+               case 14:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(15);\r
+                  break;\r
+               case 15:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAdd(15);\r
+                  break;\r
+               case 16:\r
+                  if (curChar == 47)\r
+                     jjAddStates(5, 6);\r
+                  break;\r
+               case 18:\r
+                  if ((0xfffffbffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 19:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 20;\r
+                  break;\r
+               case 20:\r
+                  if ((0xffff7fffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 21:\r
+                  if (curChar == 47 && kind > 2)\r
+                     kind = 2;\r
+                  break;\r
+               case 22:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 21;\r
+                  break;\r
+               case 23:\r
+                  if (curChar != 47)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(24);\r
+                  break;\r
+               case 24:\r
+                  if ((0xfffffffffffffbffL & l) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(24);\r
+                  break;\r
+               case 25:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 91)\r
+                     kind = 91;\r
+                  jjCheckNAddStates(0, 4);\r
+                  break;\r
+               case 26:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 91)\r
+                     kind = 91;\r
+                  jjCheckNAdd(26);\r
+                  break;\r
+               case 27:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(27, 28);\r
+                  break;\r
+               case 28:\r
+                  if (curChar != 46)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAddTwoStates(29, 30);\r
+                  break;\r
+               case 29:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAddTwoStates(29, 30);\r
+                  break;\r
+               case 31:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(32);\r
+                  break;\r
+               case 32:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAdd(32);\r
+                  break;\r
+               case 33:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(33, 34);\r
+                  break;\r
+               case 35:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(36);\r
+                  break;\r
+               case 36:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAdd(36);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else if (curChar < 128)\r
+      {\r
+         long l = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 0:\r
+               case 2:\r
+                  if ((0x7fffffe87fffffeL & l) == 0L)\r
+                     break;\r
+                  if (kind > 88)\r
+                     kind = 88;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 4:\r
+                  if ((0x47fffffed7ffffffL & l) != 0L)\r
+                     jjAddStates(13, 14);\r
+                  break;\r
+               case 7:\r
+                  if ((0xffffffffefffffffL & l) != 0L)\r
+                     jjCheckNAddStates(7, 9);\r
+                  break;\r
+               case 8:\r
+                  if (curChar == 92)\r
+                     jjstateSet[jjnewStateCnt++] = 9;\r
+                  break;\r
+               case 9:\r
+                  jjCheckNAddStates(7, 9);\r
+                  break;\r
+               case 13:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(15, 16);\r
+                  break;\r
+               case 18:\r
+               case 20:\r
+                  jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 24:\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 24;\r
+                  break;\r
+               case 30:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(17, 18);\r
+                  break;\r
+               case 34:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(19, 20);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else\r
+      {\r
+         int i2 = (curChar & 0xff) >> 6;\r
+         long l2 = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 7:\r
+               case 9:\r
+                  if ((jjbitVec0[i2] & l2) != 0L)\r
+                     jjCheckNAddStates(7, 9);\r
+                  break;\r
+               case 18:\r
+               case 20:\r
+                  if ((jjbitVec0[i2] & l2) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 24:\r
+                  if ((jjbitVec0[i2] & l2) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 24;\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      if (kind != 0x7fffffff)\r
+      {\r
+         jjmatchedKind = kind;\r
+         jjmatchedPos = curPos;\r
+         kind = 0x7fffffff;\r
+      }\r
+      ++curPos;\r
+      if ((i = jjnewStateCnt) == (startsAt = 37 - (jjnewStateCnt = startsAt)))\r
+         return curPos;\r
+      try { curChar = input_stream.readChar(); }\r
+      catch(java.io.IOException e) { return curPos; }\r
+   }\r
+}\r
+static final int[] jjnextStates = {
+   26, 27, 28, 33, 34, 17, 23, 7, 8, 10, 18, 19, 22, 4, 5, 14, 
+   15, 31, 32, 35, 36, 
+};\r
+\r
+/** Token literal values. */\r
+public static final String[] jjstrLiteralImages = {\r
+"", null, null, null, "\141\154\147\157\162\151\164\150\155", \r
+"\144\151\163\143\162\145\164\145", "\146\141\154\163\145", "\155\157\144\145\154", \r
+"\162\145\144\145\143\154\141\162\145", "\141\156\144", "\145\141\143\150", "\146\151\156\141\154", "\156\157\164", \r
+"\162\145\160\154\141\143\145\141\142\154\145", "\141\156\156\157\164\141\164\151\157\156", "\145\154\163\145", \r
+"\146\154\157\167", "\157\160\145\162\141\164\157\162", "\162\145\164\165\162\156", \r
+"\141\163\163\145\162\164", "\145\154\163\145\151\146", "\146\157\162", "\157\162", \r
+"\163\164\162\145\141\155", "\142\154\157\143\153", "\145\154\163\145\167\150\145\156", \r
+"\146\165\156\143\164\151\157\156", "\157\165\164\145\162", "\164\150\145\156", "\142\162\145\141\153", \r
+"\145\156\143\141\160\163\165\154\141\164\145\144", "\151\146", "\157\165\164\160\165\164", "\164\162\165\145", \r
+"\143\154\141\163\163", "\145\156\144", "\151\155\160\157\162\164", "\160\141\143\153\141\147\145", \r
+"\164\171\160\145", "\143\157\156\156\145\143\164", \r
+"\145\156\165\155\145\162\141\164\151\157\156", "\151\156", "\160\141\162\141\155\145\164\145\162", "\167\150\145\156", \r
+"\143\157\156\156\145\143\164\157\162", "\145\161\165\141\164\151\157\156", "\160\141\162\164\151\141\154", \r
+"\167\150\151\154\145", "\143\157\156\163\164\141\156\164", \r
+"\145\170\160\141\156\144\141\142\154\145", "\151\156\156\145\162", "\160\162\157\164\145\143\164\145\144", \r
+"\167\151\164\150\151\156", "\143\157\156\163\164\162\141\151\156\145\144\142\171", \r
+"\145\170\164\145\156\144\163", "\151\156\160\165\164", "\160\165\142\154\151\143", \r
+"\145\170\164\145\162\156\141\154", "\154\157\157\160", "\162\145\143\157\162\144", "\50", "\51", "\173", "\175", \r
+"\133", "\135", "\56", "\72", "\73", "\54", "\74", "\74\75", "\76", "\76\75", \r
+"\75\75", "\74\76", "\53", "\55", "\56\53", "\56\55", "\52", "\57", "\56\52", "\56\57", \r
+"\136", "\56\136", "\75", "\72\75", null, null, null, null, null, };\r
+\r
+/** Lexer state names. */\r
+public static final String[] lexStateNames = {\r
+   "DEFAULT",\r
+};\r
+static final long[] jjtoToken = {
+   0xfffffffffffffff1L, 0x1fffffffL, 
+};\r
+static final long[] jjtoSkip = {
+   0xeL, 0x0L, 
+};\r
+protected SimpleCharStream input_stream;\r
+private final int[] jjrounds = new int[37];\r
+private final int[] jjstateSet = new int[74];\r
+private final StringBuilder jjimage = new StringBuilder();\r
+private StringBuilder image = jjimage;\r
+private int jjimageLen;\r
+private int lengthOfMatch;\r
+protected char curChar;\r
+/** Constructor. */\r
+public ExpressionParserTokenManager(SimpleCharStream stream){\r
+   if (SimpleCharStream.staticFlag)\r
+      throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");\r
+   input_stream = stream;\r
+}\r
+\r
+/** Constructor. */\r
+public ExpressionParserTokenManager(SimpleCharStream stream, int lexState){\r
+   this(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream)\r
+{\r
+   jjmatchedPos = jjnewStateCnt = 0;\r
+   curLexState = defaultLexState;\r
+   input_stream = stream;\r
+   ReInitRounds();\r
+}\r
+private void ReInitRounds()\r
+{\r
+   int i;\r
+   jjround = 0x80000001;\r
+   for (i = 37; i-- > 0;)\r
+      jjrounds[i] = 0x80000000;\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream, int lexState)\r
+{\r
+   ReInit(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Switch to specified lex state. */\r
+public void SwitchTo(int lexState)\r
+{\r
+   if (lexState >= 1 || lexState < 0)\r
+      throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);\r
+   else\r
+      curLexState = lexState;\r
+}\r
+\r
+protected Token jjFillToken()\r
+{\r
+   final Token t;\r
+   final String curTokenImage;\r
+   final int beginLine;\r
+   final int endLine;\r
+   final int beginColumn;\r
+   final int endColumn;\r
+   String im = jjstrLiteralImages[jjmatchedKind];\r
+   curTokenImage = (im == null) ? input_stream.GetImage() : im;\r
+   beginLine = input_stream.getBeginLine();\r
+   beginColumn = input_stream.getBeginColumn();\r
+   endLine = input_stream.getEndLine();\r
+   endColumn = input_stream.getEndColumn();\r
+   t = Token.newToken(jjmatchedKind);\r
+   t.kind = jjmatchedKind;\r
+   t.image = curTokenImage;\r
+\r
+   t.beginLine = beginLine;\r
+   t.endLine = endLine;\r
+   t.beginColumn = beginColumn;\r
+   t.endColumn = endColumn;\r
+\r
+   return t;\r
+}\r
+\r
+int curLexState = 0;\r
+int defaultLexState = 0;\r
+int jjnewStateCnt;\r
+int jjround;\r
+int jjmatchedPos;\r
+int jjmatchedKind;\r
+\r
+/** Get the next Token. */\r
+public Token getNextToken() \r
+{\r
+  Token matchedToken;\r
+  int curPos = 0;\r
+\r
+  EOFLoop :
+  for (;;)\r
+  {\r
+   try\r
+   {\r
+      curChar = input_stream.BeginToken();\r
+   }\r
+   catch(java.io.IOException e)\r
+   {\r
+      jjmatchedKind = 0;\r
+      matchedToken = jjFillToken();\r
+      return matchedToken;\r
+   }\r
+   image = jjimage;\r
+   image.setLength(0);\r
+   jjimageLen = 0;\r
+\r
+   jjmatchedKind = 0x7fffffff;\r
+   jjmatchedPos = 0;\r
+   curPos = jjMoveStringLiteralDfa0_0();\r
+   if (jjmatchedKind != 0x7fffffff)\r
+   {\r
+      if (jjmatchedPos + 1 < curPos)\r
+         input_stream.backup(curPos - jjmatchedPos - 1);\r
+      if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)\r
+      {\r
+         matchedToken = jjFillToken();\r
+         TokenLexicalActions(matchedToken);\r
+         return matchedToken;\r
+      }\r
+      else\r
+      {\r
+         continue EOFLoop;\r
+      }\r
+   }\r
+   int error_line = input_stream.getEndLine();\r
+   int error_column = input_stream.getEndColumn();\r
+   String error_after = null;\r
+   boolean EOFSeen = false;\r
+   try { input_stream.readChar(); input_stream.backup(1); }\r
+   catch (java.io.IOException e1) {\r
+      EOFSeen = true;\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+      if (curChar == '\n' || curChar == '\r') {\r
+         error_line++;\r
+         error_column = 0;\r
+      }\r
+      else\r
+         error_column++;\r
+   }\r
+   if (!EOFSeen) {\r
+      input_stream.backup(1);\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+   }\r
+   throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);\r
+  }\r
+}\r
+\r
+void TokenLexicalActions(Token matchedToken)\r
+{\r
+   switch(jjmatchedKind)\r
+   {\r
+      case 90 :\r
+        image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)));\r
+      matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+}\r
+private void jjCheckNAdd(int state)\r
+{\r
+   if (jjrounds[state] != jjround)\r
+   {\r
+      jjstateSet[jjnewStateCnt++] = state;\r
+      jjrounds[state] = jjround;\r
+   }\r
+}\r
+private void jjAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjstateSet[jjnewStateCnt++] = jjnextStates[start];\r
+   } while (start++ != end);\r
+}\r
+private void jjCheckNAddTwoStates(int state1, int state2)\r
+{\r
+   jjCheckNAdd(state1);\r
+   jjCheckNAdd(state2);\r
+}\r
+\r
+private void jjCheckNAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjCheckNAdd(jjnextStates[start]);\r
+   } while (start++ != end);\r
+}\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ParseException.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/ParseException.java
new file mode 100644 (file)
index 0000000..c5c3b5f
--- /dev/null
@@ -0,0 +1,196 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.expressionParser;\r
+\r
+/**\r
+ * This exception is thrown when parse errors are encountered.\r
+ * You can explicitly create objects of this exception type by\r
+ * calling the method generateParseException in the generated\r
+ * parser.\r
+ *\r
+ * You can modify this class to customize your error reporting\r
+ * mechanisms so long as you retain the public fields.\r
+ */\r
+public class ParseException extends Exception {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * This constructor is used by the method "generateParseException"\r
+   * in the generated parser.  Calling this constructor generates\r
+   * a new object of this type with the fields "currentToken",\r
+   * "expectedTokenSequences", and "tokenImage" set.\r
+   */\r
+  public ParseException(Token currentTokenVal,\r
+                        int[][] expectedTokenSequencesVal,\r
+                        String[] tokenImageVal\r
+                       )\r
+  {\r
+    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));\r
+    currentToken = currentTokenVal;\r
+    expectedTokenSequences = expectedTokenSequencesVal;\r
+    tokenImage = tokenImageVal;\r
+  }\r
+\r
+  /**\r
+   * The following constructors are for use by you for whatever\r
+   * purpose you can think of.  Constructing the exception in this\r
+   * manner makes the exception behave in the normal way - i.e., as\r
+   * documented in the class "Throwable".  The fields "errorToken",\r
+   * "expectedTokenSequences", and "tokenImage" do not contain\r
+   * relevant information.  The JavaCC generated code does not use\r
+   * these constructors.\r
+   */\r
+\r
+  public ParseException() {\r
+    super();\r
+  }\r
+\r
+  /** Constructor with message. */\r
+  public ParseException(String message) {\r
+    super(message);\r
+  }\r
+\r
+\r
+  /**\r
+   * This is the last token that has been consumed successfully.  If\r
+   * this object has been created due to a parse error, the token\r
+   * followng this token will (therefore) be the first error token.\r
+   */\r
+  public Token currentToken;\r
+\r
+  /**\r
+   * Each entry in this array is an array of integers.  Each array\r
+   * of integers represents a sequence of tokens (by their ordinal\r
+   * values) that is expected at this point of the parse.\r
+   */\r
+  public int[][] expectedTokenSequences;\r
+\r
+  /**\r
+   * This is a reference to the "tokenImage" array of the generated\r
+   * parser within which the parse error occurred.  This array is\r
+   * defined in the generated ...Constants interface.\r
+   */\r
+  public String[] tokenImage;\r
+\r
+  /**\r
+   * It uses "currentToken" and "expectedTokenSequences" to generate a parse\r
+   * error message and returns it.  If this object has been created\r
+   * due to a parse error, and you do not catch it (it gets thrown\r
+   * from the parser) the correct error message\r
+   * gets displayed.\r
+   */\r
+  private static String initialise(Token currentToken,\r
+                           int[][] expectedTokenSequences,\r
+                           String[] tokenImage) {\r
+    String eol = System.getProperty("line.separator", "\n");\r
+    StringBuffer expected = new StringBuffer();\r
+    int maxSize = 0;\r
+    for (int i = 0; i < expectedTokenSequences.length; i++) {\r
+      if (maxSize < expectedTokenSequences[i].length) {\r
+        maxSize = expectedTokenSequences[i].length;\r
+      }\r
+      for (int j = 0; j < expectedTokenSequences[i].length; j++) {\r
+        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');\r
+      }\r
+      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {\r
+        expected.append("...");\r
+      }\r
+      expected.append(eol).append("    ");\r
+    }\r
+    String retval = "Encountered \"";\r
+    Token tok = currentToken.next;\r
+    for (int i = 0; i < maxSize; i++) {\r
+      if (i != 0) retval += " ";\r
+      if (tok.kind == 0) {\r
+        retval += tokenImage[0];\r
+        break;\r
+      }\r
+      retval += " " + tokenImage[tok.kind];\r
+      retval += " \"";\r
+      retval += add_escapes(tok.image);\r
+      retval += " \"";\r
+      tok = tok.next;\r
+    }\r
+    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;\r
+    retval += "." + eol;\r
+    if (expectedTokenSequences.length == 1) {\r
+      retval += "Was expecting:" + eol + "    ";\r
+    } else {\r
+      retval += "Was expecting one of:" + eol + "    ";\r
+    }\r
+    retval += expected.toString();\r
+    return retval;\r
+  }\r
+\r
+  /**\r
+   * The end of line string for this machine.\r
+   */\r
+  protected String eol = System.getProperty("line.separator", "\n");\r
+\r
+  /**\r
+   * Used to convert raw characters to their escaped version\r
+   * when these raw version cannot be used as part of an ASCII\r
+   * string literal.\r
+   */\r
+  static String add_escapes(String str) {\r
+      StringBuffer retval = new StringBuffer();\r
+      char ch;\r
+      for (int i = 0; i < str.length(); i++) {\r
+        switch (str.charAt(i))\r
+        {\r
+           case 0 :\r
+              continue;\r
+           case '\b':\r
+              retval.append("\\b");\r
+              continue;\r
+           case '\t':\r
+              retval.append("\\t");\r
+              continue;\r
+           case '\n':\r
+              retval.append("\\n");\r
+              continue;\r
+           case '\f':\r
+              retval.append("\\f");\r
+              continue;\r
+           case '\r':\r
+              retval.append("\\r");\r
+              continue;\r
+           case '\"':\r
+              retval.append("\\\"");\r
+              continue;\r
+           case '\'':\r
+              retval.append("\\\'");\r
+              continue;\r
+           case '\\':\r
+              retval.append("\\\\");\r
+              continue;\r
+           default:\r
+              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+                 String s = "0000" + Integer.toString(ch, 16);\r
+                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+              } else {\r
+                 retval.append(ch);\r
+              }\r
+              continue;\r
+        }\r
+      }\r
+      return retval.toString();\r
+   }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=65dcbd31a9e7a053287ebf70e24f8b8f (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/SimpleCharStream.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/SimpleCharStream.java
new file mode 100644 (file)
index 0000000..ae8e144
--- /dev/null
@@ -0,0 +1,480 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.expressionParser;\r
+\r
+/**\r
+ * An implementation of interface CharStream, where the stream is assumed to\r
+ * contain only ASCII characters (without unicode processing).\r
+ */\r
+\r
+public class SimpleCharStream\r
+{\r
+/** Whether parser is static. */\r
+  public static final boolean staticFlag = false;\r
+  int bufsize;\r
+  int available;\r
+  int tokenBegin;\r
+/** Position in buffer. */\r
+  public int bufpos = -1;\r
+  protected int bufline[];\r
+  protected int bufcolumn[];\r
+\r
+  protected int column = 0;\r
+  protected int line = 1;\r
+\r
+  protected boolean prevCharIsCR = false;\r
+  protected boolean prevCharIsLF = false;\r
+\r
+  protected java.io.Reader inputStream;\r
+\r
+  protected char[] buffer;\r
+  protected int maxNextCharInd = 0;\r
+  protected int inBuf = 0;\r
+  protected int tabSize = 8;\r
+\r
+  protected void setTabSize(int i) { tabSize = i; }\r
+  protected int getTabSize(int i) { return tabSize; }\r
+\r
+\r
+  protected void ExpandBuff(boolean wrapAround)\r
+  {\r
+    char[] newbuffer = new char[bufsize + 2048];\r
+    int newbufline[] = new int[bufsize + 2048];\r
+    int newbufcolumn[] = new int[bufsize + 2048];\r
+\r
+    try\r
+    {\r
+      if (wrapAround)\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos += (bufsize - tokenBegin));\r
+      }\r
+      else\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos -= tokenBegin);\r
+      }\r
+    }\r
+    catch (Throwable t)\r
+    {\r
+      throw new Error(t.getMessage());\r
+    }\r
+\r
+\r
+    bufsize += 2048;\r
+    available = bufsize;\r
+    tokenBegin = 0;\r
+  }\r
+\r
+  protected void FillBuff() throws java.io.IOException\r
+  {\r
+    if (maxNextCharInd == available)\r
+    {\r
+      if (available == bufsize)\r
+      {\r
+        if (tokenBegin > 2048)\r
+        {\r
+          bufpos = maxNextCharInd = 0;\r
+          available = tokenBegin;\r
+        }\r
+        else if (tokenBegin < 0)\r
+          bufpos = maxNextCharInd = 0;\r
+        else\r
+          ExpandBuff(false);\r
+      }\r
+      else if (available > tokenBegin)\r
+        available = bufsize;\r
+      else if ((tokenBegin - available) < 2048)\r
+        ExpandBuff(true);\r
+      else\r
+        available = tokenBegin;\r
+    }\r
+\r
+    int i;\r
+    try {\r
+      if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)\r
+      {\r
+        inputStream.close();\r
+        throw new java.io.IOException();\r
+      }\r
+      else\r
+        maxNextCharInd += i;\r
+      return;\r
+    }\r
+    catch(java.io.IOException e) {\r
+      --bufpos;\r
+      backup(0);\r
+      if (tokenBegin == -1)\r
+        tokenBegin = bufpos;\r
+      throw e;\r
+    }\r
+  }\r
+\r
+/** Start. */\r
+  public char BeginToken() throws java.io.IOException\r
+  {\r
+    tokenBegin = -1;\r
+    char c = readChar();\r
+    tokenBegin = bufpos;\r
+\r
+    return c;\r
+  }\r
+\r
+  protected void UpdateLineColumn(char c)\r
+  {\r
+    column++;\r
+\r
+    if (prevCharIsLF)\r
+    {\r
+      prevCharIsLF = false;\r
+      line += (column = 1);\r
+    }\r
+    else if (prevCharIsCR)\r
+    {\r
+      prevCharIsCR = false;\r
+      if (c == '\n')\r
+      {\r
+        prevCharIsLF = true;\r
+      }\r
+      else\r
+        line += (column = 1);\r
+    }\r
+\r
+    switch (c)\r
+    {\r
+      case '\r' :\r
+        prevCharIsCR = true;\r
+        break;\r
+      case '\n' :\r
+        prevCharIsLF = true;\r
+        break;\r
+      case '\t' :\r
+        column--;\r
+        column += (tabSize - (column % tabSize));\r
+        break;\r
+      default :\r
+        break;\r
+    }\r
+\r
+    bufline[bufpos] = line;\r
+    bufcolumn[bufpos] = column;\r
+  }\r
+\r
+/** Read a character. */\r
+  public char readChar() throws java.io.IOException\r
+  {\r
+    if (inBuf > 0)\r
+    {\r
+      --inBuf;\r
+\r
+      if (++bufpos == bufsize)\r
+        bufpos = 0;\r
+\r
+      return buffer[bufpos];\r
+    }\r
+\r
+    if (++bufpos >= maxNextCharInd)\r
+      FillBuff();\r
+\r
+    char c = buffer[bufpos];\r
+\r
+    UpdateLineColumn(c);\r
+    return c;\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndColumn\r
+   */\r
+\r
+  public int getColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndLine\r
+   */\r
+\r
+  public int getLine() {\r
+    return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token end column number. */\r
+  public int getEndColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  /** Get token end line number. */\r
+  public int getEndLine() {\r
+     return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token beginning column number. */\r
+  public int getBeginColumn() {\r
+    return bufcolumn[tokenBegin];\r
+  }\r
+\r
+  /** Get token beginning line number. */\r
+  public int getBeginLine() {\r
+    return bufline[tokenBegin];\r
+  }\r
+\r
+/** Backup a number of characters. */\r
+  public void backup(int amount) {\r
+\r
+    inBuf += amount;\r
+    if ((bufpos -= amount) < 0)\r
+      bufpos += bufsize;\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    available = bufsize = buffersize;\r
+    buffer = new char[buffersize];\r
+    bufline = new int[buffersize];\r
+    bufcolumn = new int[buffersize];\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    if (buffer == null || buffersize != buffer.length)\r
+    {\r
+      available = bufsize = buffersize;\r
+      buffer = new char[buffersize];\r
+      bufline = new int[buffersize];\r
+      bufcolumn = new int[buffersize];\r
+    }\r
+    prevCharIsLF = prevCharIsCR = false;\r
+    tokenBegin = inBuf = maxNextCharInd = 0;\r
+    bufpos = -1;\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+  int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                          int startcolumn, int buffersize)\r
+  {\r
+    ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                     int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+  /** Get token literal value. */\r
+  public String GetImage()\r
+  {\r
+    if (bufpos >= tokenBegin)\r
+      return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);\r
+    else\r
+      return new String(buffer, tokenBegin, bufsize - tokenBegin) +\r
+                            new String(buffer, 0, bufpos + 1);\r
+  }\r
+\r
+  /** Get the suffix. */\r
+  public char[] GetSuffix(int len)\r
+  {\r
+    char[] ret = new char[len];\r
+\r
+    if ((bufpos + 1) >= len)\r
+      System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);\r
+    else\r
+    {\r
+      System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,\r
+                                                        len - bufpos - 1);\r
+      System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);\r
+    }\r
+\r
+    return ret;\r
+  }\r
+\r
+  /** Reset buffer when finished. */\r
+  public void Done()\r
+  {\r
+    buffer = null;\r
+    bufline = null;\r
+    bufcolumn = null;\r
+  }\r
+\r
+  /**\r
+   * Method to adjust line and column numbers for the start of a token.\r
+   */\r
+  public void adjustBeginLineColumn(int newLine, int newCol)\r
+  {\r
+    int start = tokenBegin;\r
+    int len;\r
+\r
+    if (bufpos >= tokenBegin)\r
+    {\r
+      len = bufpos - tokenBegin + inBuf + 1;\r
+    }\r
+    else\r
+    {\r
+      len = bufsize - tokenBegin + bufpos + 1 + inBuf;\r
+    }\r
+\r
+    int i = 0, j = 0, k = 0;\r
+    int nextColDiff = 0, columnDiff = 0;\r
+\r
+    while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])\r
+    {\r
+      bufline[j] = newLine;\r
+      nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];\r
+      bufcolumn[j] = newCol + columnDiff;\r
+      columnDiff = nextColDiff;\r
+      i++;\r
+    }\r
+\r
+    if (i < len)\r
+    {\r
+      bufline[j] = newLine++;\r
+      bufcolumn[j] = newCol + columnDiff;\r
+\r
+      while (i++ < len)\r
+      {\r
+        if (bufline[j = start % bufsize] != bufline[++start % bufsize])\r
+          bufline[j] = newLine++;\r
+        else\r
+          bufline[j] = newLine;\r
+      }\r
+    }\r
+\r
+    line = bufline[j];\r
+    column = bufcolumn[j];\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=c766a5138ab7879b8b98d46681a242b8 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TestExpressionParser.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TestExpressionParser.java
new file mode 100644 (file)
index 0000000..35225c2
--- /dev/null
@@ -0,0 +1,47 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.expressionParser;\r
+\r
+import java.io.StringReader;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+\r
+public class TestExpressionParser {\r
+    \r
+    static private ExpressionParser parser;\r
+    \r
+    public static void parse(String string) {\r
+        parser.ReInit(new StringReader(string));\r
+        try {\r
+            parser.expr();\r
+            HashMap<String, List<Token>> references = parser.getReferences();\r
+            for(String ref : references.keySet()) {\r
+                System.out.println(ref);\r
+            }\r
+        } catch (ParseException e) {\r
+            System.out.println("While parsing " + string + ":");\r
+            // TODO Auto-generated catch block\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    public static void main(String[] args) {\r
+        parser = new ExpressionParser(\r
+                new StringReader("")\r
+        );\r
+        parse("1 + m2ma");\r
+        System.out.println("##");\r
+        parse("ter2e + moro");\r
+        System.out.println("##");\r
+        parse("moro * sqr(4.0) + min(m2ma, moi)");\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/Token.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/Token.java
new file mode 100644 (file)
index 0000000..9cce569
--- /dev/null
@@ -0,0 +1,155 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.expressionParser;\r
+\r
+/**\r
+ * Describes the input token stream.\r
+ */\r
+\r
+public class Token implements java.io.Serializable, Comparable<Token> {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * An integer that describes the kind of this token.  This numbering\r
+   * system is determined by JavaCCParser, and a table of these numbers is\r
+   * stored in the file ...Constants.java.\r
+   */\r
+  public int kind;\r
+\r
+  /** The line number of the first character of this Token. */\r
+  public int beginLine;\r
+  /** The column number of the first character of this Token. */\r
+  public int beginColumn;\r
+  /** The line number of the last character of this Token. */\r
+  public int endLine;\r
+  /** The column number of the last character of this Token. */\r
+  public int endColumn;\r
+\r
+  /**\r
+   * The string image of the token.\r
+   */\r
+  public String image;\r
+\r
+  /**\r
+   * A reference to the next regular (non-special) token from the input\r
+   * stream.  If this is the last token from the input stream, or if the\r
+   * token manager has not read tokens beyond this one, this field is\r
+   * set to null.  This is true only if this token is also a regular\r
+   * token.  Otherwise, see below for a description of the contents of\r
+   * this field.\r
+   */\r
+  public Token next;\r
+\r
+  /**\r
+   * This field is used to access special tokens that occur prior to this\r
+   * token, but after the immediately preceding regular (non-special) token.\r
+   * If there are no such special tokens, this field is set to null.\r
+   * When there are more than one such special token, this field refers\r
+   * to the last of these special tokens, which in turn refers to the next\r
+   * previous special token through its specialToken field, and so on\r
+   * until the first special token (whose specialToken field is null).\r
+   * The next fields of special tokens refer to other special tokens that\r
+   * immediately follow it (without an intervening regular token).  If there\r
+   * is no such token, this field is null.\r
+   */\r
+  public Token specialToken;\r
+\r
+  /**\r
+   * An optional attribute value of the Token.\r
+   * Tokens which are not used as syntactic sugar will often contain\r
+   * meaningful values that will be used later on by the compiler or\r
+   * interpreter. This attribute value is often different from the image.\r
+   * Any subclass of Token that actually wants to return a non-null value can\r
+   * override this method as appropriate.\r
+   */\r
+  public Object getValue() {\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * No-argument constructor\r
+   */\r
+  public Token() {}\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image.\r
+   */\r
+  public Token(int kind)\r
+  {\r
+    this(kind, null);\r
+  }\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image and Kind.\r
+   */\r
+  public Token(int kind, String image)\r
+  {\r
+    this.kind = kind;\r
+    this.image = image;\r
+  }\r
+\r
+  /**\r
+   * Returns the image.\r
+   */\r
+  public String toString()\r
+  {\r
+    return image;\r
+  }\r
+\r
+  /**\r
+   * Returns a new Token object, by default. However, if you want, you\r
+   * can create and return subclass objects based on the value of ofKind.\r
+   * Simply add the cases to the switch for all those special cases.\r
+   * For example, if you have a subclass of Token called IDToken that\r
+   * you want to create if ofKind is ID, simply add something like :\r
+   *\r
+   *    case MyParserConstants.ID : return new IDToken(ofKind, image);\r
+   *\r
+   * to the following switch statement. Then you can cast matchedToken\r
+   * variable to the appropriate type and use sit in your lexical actions.\r
+   */\r
+  public static Token newToken(int ofKind, String image)\r
+  {\r
+    switch(ofKind)\r
+    {\r
+      default : return new Token(ofKind, image);\r
+    }\r
+  }\r
+\r
+  public static Token newToken(int ofKind)\r
+  {\r
+    return newToken(ofKind, null);\r
+  }\r
+\r
+       @Override\r
+       public int compareTo(Token o) {\r
+               if (this.beginLine < o.beginLine)\r
+                       return -1;\r
+               if (this.beginLine > o.beginLine)\r
+                       return 1;\r
+               else {\r
+                       if (this.beginColumn < o.beginColumn)\r
+                               return -1;\r
+                       if (this.beginColumn > o.beginColumn)\r
+                               return 1;\r
+                       return 0;\r
+               }\r
+       }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=ed7a6d865f7fbc2c64e008e34bd824b0 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TokenMgrError.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/expressionParser/TokenMgrError.java
new file mode 100644 (file)
index 0000000..db38041
--- /dev/null
@@ -0,0 +1,156 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.expressionParser;\r
+\r
+/** Token Manager Error. */\r
+public class TokenMgrError extends Error\r
+{\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /*\r
+   * Ordinals for various reasons why an Error of this type can be thrown.\r
+   */\r
+\r
+  /**\r
+   * Lexical error occurred.\r
+   */\r
+  static final int LEXICAL_ERROR = 0;\r
+\r
+  /**\r
+   * An attempt was made to create a second instance of a static token manager.\r
+   */\r
+  static final int STATIC_LEXER_ERROR = 1;\r
+\r
+  /**\r
+   * Tried to change to an invalid lexical state.\r
+   */\r
+  static final int INVALID_LEXICAL_STATE = 2;\r
+\r
+  /**\r
+   * Detected (and bailed out of) an infinite loop in the token manager.\r
+   */\r
+  static final int LOOP_DETECTED = 3;\r
+\r
+  /**\r
+   * Indicates the reason why the exception is thrown. It will have\r
+   * one of the above 4 values.\r
+   */\r
+  int errorCode;\r
+\r
+  /**\r
+   * Replaces unprintable characters by their escaped (or unicode escaped)\r
+   * equivalents in the given string\r
+   */\r
+  protected static final String addEscapes(String str) {\r
+    StringBuffer retval = new StringBuffer();\r
+    char ch;\r
+    for (int i = 0; i < str.length(); i++) {\r
+      switch (str.charAt(i))\r
+      {\r
+        case 0 :\r
+          continue;\r
+        case '\b':\r
+          retval.append("\\b");\r
+          continue;\r
+        case '\t':\r
+          retval.append("\\t");\r
+          continue;\r
+        case '\n':\r
+          retval.append("\\n");\r
+          continue;\r
+        case '\f':\r
+          retval.append("\\f");\r
+          continue;\r
+        case '\r':\r
+          retval.append("\\r");\r
+          continue;\r
+        case '\"':\r
+          retval.append("\\\"");\r
+          continue;\r
+        case '\'':\r
+          retval.append("\\\'");\r
+          continue;\r
+        case '\\':\r
+          retval.append("\\\\");\r
+          continue;\r
+        default:\r
+          if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+            String s = "0000" + Integer.toString(ch, 16);\r
+            retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+          } else {\r
+            retval.append(ch);\r
+          }\r
+          continue;\r
+      }\r
+    }\r
+    return retval.toString();\r
+  }\r
+\r
+  /**\r
+   * Returns a detailed message for the Error when it is thrown by the\r
+   * token manager to indicate a lexical error.\r
+   * Parameters :\r
+   *    EOFSeen     : indicates if EOF caused the lexical error\r
+   *    curLexState : lexical state in which this error occurred\r
+   *    errorLine   : line number when the error occurred\r
+   *    errorColumn : column number when the error occurred\r
+   *    errorAfter  : prefix that was seen before this error occurred\r
+   *    curchar     : the offending character\r
+   * Note: You can customize the lexical error message by modifying this method.\r
+   */\r
+  protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {\r
+    return("Lexical error at line " +\r
+          errorLine + ", column " +\r
+          errorColumn + ".  Encountered: " +\r
+          (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +\r
+          "after : \"" + addEscapes(errorAfter) + "\"");\r
+  }\r
+\r
+  /**\r
+   * You can also modify the body of this method to customize your error messages.\r
+   * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not\r
+   * of end-users concern, so you can return something like :\r
+   *\r
+   *     "Internal Error : Please file a bug report .... "\r
+   *\r
+   * from this method for such cases in the release version of your parser.\r
+   */\r
+  public String getMessage() {\r
+    return super.getMessage();\r
+  }\r
+\r
+  /*\r
+   * Constructors of various flavors follow.\r
+   */\r
+\r
+  /** No arg constructor. */\r
+  public TokenMgrError() {\r
+  }\r
+\r
+  /** Constructor with message and reason. */\r
+  public TokenMgrError(String message, int reason) {\r
+    super(message);\r
+    errorCode = reason;\r
+  }\r
+\r
+  /** Full Constructor. */\r
+  public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {\r
+    this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);\r
+  }\r
+}\r
+/* JavaCC - OriginalChecksum=24b6b4792f62099f85bde9ed73a49451 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/ActiveResults.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/ActiveResults.java
new file mode 100644 (file)
index 0000000..6ae1b03
--- /dev/null
@@ -0,0 +1,71 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ActiveResults implements Read<Collection<Resource>>{\r
+    \r
+    private Resource resource;\r
+    \r
+    public ActiveResults(Resource resource) {\r
+        this.resource = resource;\r
+    }\r
+\r
+    @Override\r
+    public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        ModelingResources MR = ModelingResources.getInstance(graph);\r
+        \r
+        Collection<Resource> result = new ArrayList<Resource>();\r
+        \r
+        Collection<Resource> experiments;\r
+        if(graph.isInstanceOf(resource, MR.StructuralModel))\r
+            experiments = graph.syncRequest(new ObjectsWithType(resource, L0.ConsistsOf, SR.Experiment));\r
+        else {\r
+            experiments = new ArrayList<Resource>();\r
+            experiments.add(resource);\r
+        }\r
+            \r
+        for(Resource experiment : experiments) {\r
+            Collection<Resource> experimentResults = graph.getObjects(experiment, SR.Experiment_result);\r
+            for(Resource r : experimentResults) {\r
+                if(graph.hasStatement(r, SR.Result_showResult)) {\r
+                   result.add(r);\r
+                }\r
+            }\r
+            Collection<Resource> experimentResultSets = graph.getObjects(experiment, SR.Experiment_resultSet);\r
+            for(Resource resultSet : experimentResultSets) {\r
+               experimentResults = graph.getObjects(resultSet, SR.Experiment_result);\r
+                for(Resource r : experimentResults) {\r
+                    if(graph.hasStatement(r, SR.Result_showResult)) {\r
+                       result.add(r);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        \r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FileResult.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FileResult.java
new file mode 100644 (file)
index 0000000..e685e8d
--- /dev/null
@@ -0,0 +1,116 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.simantics.databoard.Accessors;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.accessor.Accessor;\r
+import org.simantics.databoard.accessor.MapAccessor;\r
+import org.simantics.databoard.accessor.RecordAccessor;\r
+import org.simantics.databoard.accessor.binary.BinaryRecord;\r
+import org.simantics.databoard.accessor.binary.BinaryVariant;\r
+import org.simantics.databoard.accessor.error.AccessorConstructionException;\r
+import org.simantics.databoard.accessor.error.AccessorException;\r
+import org.simantics.databoard.accessor.reference.ChildReference;\r
+import org.simantics.databoard.accessor.reference.ComponentReference;\r
+import org.simantics.databoard.accessor.reference.IndexReference;\r
+import org.simantics.databoard.accessor.reference.KeyReference;\r
+import org.simantics.databoard.accessor.reference.NameReference;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+\r
+public class FileResult extends SysdynResult {\r
+    \r
+    private RecordAccessor accessor;\r
+\r
+    /**\r
+     * Open result from a file\r
+     * \r
+     * @param result Name of the result (seen in visualization)\r
+     * @param path file path\r
+     */\r
+    public FileResult(String resultName, String path) {\r
+        super(resultName);\r
+        File file = new File(path);\r
+        try {\r
+            BinaryVariant bv = (BinaryVariant)Accessors.openAccessor(file);\r
+            BinaryRecord br = bv.getContentAccessor();\r
+            accessor = br;\r
+        } catch (AccessorConstructionException e) {\r
+            e.printStackTrace();\r
+        } \r
+    }\r
+    \r
+    /**\r
+     * Get the {@link RecordAccessor} of this result\r
+     * @return {@link RecordAccessor} for this result\r
+     */\r
+    public Accessor getAccessor() {\r
+        return accessor;\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Get dataset for a named variable from accessor\r
+     * @param variable The name of the variable\r
+     * @return {@link SysdynDataSet}\r
+     */\r
+    @Override\r
+    public SysdynDataSet getDataSet(String variable) {\r
+        if(accessor != null) {\r
+            synchronized(accessor) {\r
+                ChildReference ref = ChildReference.compile(\r
+                        new NameReference("recordings"),\r
+                        new KeyReference( Bindings.VARIANT, Variant.ofInstance(variable) ),\r
+                        new ComponentReference(),\r
+                        new NameReference("segments"),\r
+                        new IndexReference(0)\r
+                        );\r
+                MapAccessor ma;\r
+                try {\r
+                     ma = accessor.getComponent( ref );\r
+                } catch (AccessorConstructionException e) {\r
+                        return null;\r
+                } \r
+                \r
+                try {\r
+                    int size = ma.size();\r
+                    Double[] times = new Double[size];\r
+                    Double[] values = new Double[size];\r
+    \r
+                    ma.getAll(Bindings.DOUBLE, Bindings.DOUBLE, times, values);\r
+    \r
+                    double[] times_ = new double[size];\r
+                    double[] values_ = new double[size];\r
+                    for (int i=0; i<size; i++) {\r
+                        times_[i] = (times[i]!=null ? times[i] : 0);\r
+                        values_[i] = (values[i]!=null ? values[i] : 0);\r
+                    }\r
+    \r
+                    return new SysdynDataSet(variable, getResultName(), times_, values_);\r
+                } catch (AccessorException e) {\r
+                    // Unable to read data from file\r
+                    e.printStackTrace();\r
+                }\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void saveToFile(File file, IProgressMonitor progressMonitor) {\r
+        // Already a saved result. No need for action.\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FunctionUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/FunctionUtils.java
new file mode 100644 (file)
index 0000000..2d86001
--- /dev/null
@@ -0,0 +1,260 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.io.PrintStream;\r
+import java.util.ArrayList;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.Activator;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class FunctionUtils {\r
+       \r
+       // SOMETHING WRONG HERE\r
+       \r
+       public static List<String> getLibraryPathsForModelica(final SysdynExperiment experiment) {\r
+               try {\r
+                       return Simantics.getSession().syncRequest(new Read<List<String>>() {\r
+                               @Override\r
+                               public List<String> perform(ReadGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                                       List<String> paths = new ArrayList<String>();\r
+                                   for(Resource parent : getParents(graph, experiment.getModel(), true)) {\r
+                                       if(graph.isInstanceOf(parent, sr.SysdynModel)) {\r
+                                           String modelName = NameUtils.getSafeName(graph, parent);\r
+                                           paths.add(modelName + "_functions.mo");\r
+                                       } else {\r
+                                           String libraryName = NameUtils.getSafeName(graph, parent);\r
+                                           paths.add("..\\\\\\\\..\\\\\\\\libraries\\\\\\\\functions\\\\\\\\" + libraryName + ".mo");\r
+                                       }\r
+                                   }\r
+                                   return paths;\r
+                               }\r
+                       });\r
+               }\r
+               catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+                       return null;\r
+               }\r
+       }\r
+       \r
+       public static void updateFunctionFilesForExperiment(final SysdynExperiment experiment) {\r
+               try {\r
+                       Simantics.getSession().syncRequest(new ReadRequest() {\r
+                               @Override\r
+                               public void run(ReadGraph graph) throws DatabaseException {\r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       \r
+                                       for (Resource parent : getParents(graph, experiment.getModel(), false)) {\r
+                                               if(graph.isInstanceOf(parent, sr.SysdynModel)) {\r
+                                                       String parentName = NameUtils.getSafeName(graph, parent);\r
+                                                       File scriptFile = new File(experiment.getExperimentDir(), parentName + "_functions.mo");\r
+                                                       updateFunctionFile(graph, parent, scriptFile, false);\r
+                                               } else {\r
+                                                       updateFunctionFileForLibrary(graph, parent);\r
+                                               }\r
+                                       }\r
+                                       \r
+                               }\r
+                       });\r
+               }\r
+               catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+       \r
+       private static Set<Resource> getParents(ReadGraph graph, Resource model, boolean ignoreEmpty) \r
+                       throws DatabaseException{\r
+               Layer0         l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+               Set<Resource> parents = new HashSet<Resource>();\r
+\r
+        if(model == null) {\r
+            return parents;\r
+        }\r
+        \r
+               parents.add(model);\r
+               \r
+               for(Resource r : graph.getObjects(model, l0.IsLinkedTo)) {\r
+                       if(graph.isInstanceOf(r, sr.SharedFunctionOntology)) {\r
+                               parents.add(r);\r
+                       } else {\r
+                               if(!graph.syncRequest(new ObjectsWithType(r, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary)).isEmpty()) {\r
+                                       parents.add(r);\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               if(ignoreEmpty) {\r
+                       Set<Resource> nonEmptyParents = new HashSet<Resource>();\r
+                       for(Resource parent : parents) {\r
+                               if(isNonEmpty(graph, parent)) {\r
+                                       nonEmptyParents.add(parent);\r
+                               }\r
+                       }\r
+                       parents = nonEmptyParents;\r
+               }\r
+               \r
+               return parents;\r
+       }\r
+       \r
+       private static boolean isNonEmpty(ReadGraph graph, Resource library) \r
+                       throws DatabaseException {\r
+               Layer0         l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               if(!graph.syncRequest(new ObjectsWithType(library, l0.ConsistsOf, sr.SysdynModelicaFunction)).isEmpty()) {\r
+                       return true;\r
+               } else {\r
+                       for(Resource l : graph.syncRequest(new ObjectsWithType(library, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) {\r
+                               if(isNonEmpty(graph, l)) {\r
+                                       return true;\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               return false;\r
+       }\r
+       \r
+       private static void updateFunctionFile(ReadGraph graph, Resource library, File scriptFile, boolean builtIn) \r
+                       throws DatabaseException {\r
+               PrintStream s;\r
+               try {\r
+                       s = new PrintStream(scriptFile);\r
+               } catch (FileNotFoundException e) {\r
+                       e.printStackTrace();\r
+                       return;\r
+               }\r
+               \r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               String name = NameUtils.getSafeName(graph, library);\r
+               \r
+               if(!builtIn && !graph.isInstanceOf(library, sr.SysdynModel)) {\r
+                       s.println("package " + name);\r
+               }\r
+               writeLibrary(graph, library, scriptFile, s, builtIn);\r
+               if(!builtIn && !graph.isInstanceOf(library, sr.SysdynModel)) {\r
+                       s.println("end " + name + ";\n");\r
+               }\r
+               \r
+               s.close();\r
+       }\r
+       \r
+       private static void updateFunctionFileForLibrary(ReadGraph graph, Resource library) \r
+                       throws DatabaseException {\r
+           Layer0 l0 = Layer0.getInstance(graph);\r
+\r
+           while(!graph.isInstanceOf(library, l0.Ontology)) {\r
+               library = graph.getSingleObject(library, l0.PartOf);\r
+           }\r
+\r
+           File librariesDir = Activator.getBundleContext().getDataFile("libraries");\r
+           if (!librariesDir.exists()) {\r
+               librariesDir.mkdir();\r
+           }\r
+           File dir = new File(librariesDir, "functions");\r
+           if (!dir.exists()) {\r
+               dir.mkdir();\r
+           }\r
+           \r
+           String parentName = NameUtils.getSafeName(graph, library);\r
+           File scriptFile = new File(dir, parentName + ".mo");\r
+\r
+           Resource sysdyn = graph.getResource("http://www.simantics.org/Sysdyn-1.1");\r
+\r
+           if(library.equals(sysdyn)) {\r
+               updateFunctionFile(graph, library, scriptFile, true);\r
+           } else {\r
+               updateFunctionFile(graph, library, scriptFile, false);\r
+           }\r
+\r
+       }\r
+       \r
+       private static void writeLibrary(ReadGraph graph, Resource library, File scriptFile, PrintStream stream, boolean builtIn) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               writeLibraryFunctions(graph, library, scriptFile, stream);\r
+               for(Resource sublibrary : graph.syncRequest(new ObjectsWithType(library, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary))) {\r
+                       String name = NameUtils.getSafeName(graph, sublibrary);\r
+                       if(!builtIn)\r
+                               stream.println("encapsulated package " + name);\r
+                       writeLibrary(graph, sublibrary, scriptFile, stream, builtIn);\r
+                       if(!builtIn)\r
+                               stream.println("end " + name + ";\n");\r
+               }\r
+       }\r
+       \r
+       private static void writeLibraryFunctions(ReadGraph graph, Resource library, File scriptFile, PrintStream stream) \r
+                       throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               for(Resource function : graph.syncRequest(new ObjectsWithType(library, l0.ConsistsOf, sr.SysdynModelicaFunction))) {\r
+                       String name = NameUtils.getSafeName(graph, function);\r
+                       // Built-in Modelica (array) functions have no function code and they don't need to be added explicitly.\r
+                       String functionCode = graph.getPossibleRelatedValue(function, sr.SysdynModelicaFunction_modelicaFunctionCode);\r
+                       if (functionCode == null) {\r
+                           continue;\r
+                       }\r
+                       stream.println("function " + name);\r
+                       stream.println(functionCode);\r
+                       stream.println("end " + name + ";\n");\r
+                       for(Resource externalFunction : graph.syncRequest(new ObjectsWithType(function, l0.ConsistsOf, sr.ExternalFunctionFile))) {\r
+                               createExternalFunctionFile(graph, externalFunction, scriptFile);\r
+                       }\r
+               }\r
+       }\r
+       \r
+       private static void createExternalFunctionFile(ReadGraph graph, Resource externalFunction, File scriptFile) \r
+                       throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+               File dir = scriptFile.getParentFile();\r
+               \r
+               if(!dir.exists())\r
+                   dir.mkdir();\r
+               \r
+               if(!dir.isDirectory())\r
+                   return;\r
+\r
+               try {\r
+                       String name = NameUtils.getSafeName(graph, externalFunction);\r
+                       if(name.endsWith(".o") || name.endsWith(".a")) {\r
+                               FileOutputStream fos = new FileOutputStream(dir + File.separator + name);\r
+                               byte[] fileBArray = graph.getPossibleRelatedValue(externalFunction, sr.ExternalFunctionFile_externalFile, Bindings.BYTE_ARRAY);\r
+                               fos.write(fileBArray);\r
+                               fos.close();\r
+                       }\r
+               } catch (IOException e) {\r
+                       e.printStackTrace();\r
+               }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/GameResult.java
new file mode 100644 (file)
index 0000000..8997ca0
--- /dev/null
@@ -0,0 +1,33 @@
+package org.simantics.sysdyn.manager;\r
+\r
+import gnu.trove.list.array.TDoubleArrayList;\r
+import gnu.trove.map.hash.THashMap;\r
+\r
+import org.simantics.modelica.data.DataSet;\r
+import org.simantics.modelica.data.SimulationResult;\r
+\r
+/**\r
+ * Game results\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class GameResult extends SimulationResult {\r
+       \r
+       public GameResult(SysdynGameExperimentBase sysdynGameExperiment, THashMap<String, TDoubleArrayList> results, String[] subscription) {\r
+               \r
+               // Get times\r
+               TDoubleArrayList timeList = results.get("time");\r
+               double[] times = timeList.toArray();\r
+               \r
+               String name;\r
+               for(int k = 0; k < subscription.length; k++) {\r
+                       name = subscription[k];\r
+                       TDoubleArrayList valueList = results.get(name);\r
+                       if(valueList.size() ==  timeList.size()) {\r
+                               this.variables.add(new DataSet(name, times, valueList.toArray()));\r
+                       } else {\r
+                               System.err.println("wrong amount of values " + name);\r
+                       }\r
+               }\r
+       }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetResult.java
new file mode 100644 (file)
index 0000000..9805a7c
--- /dev/null
@@ -0,0 +1,324 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4180\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.io.File;\r
+import java.io.InputStream;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modelica.data.DataSet;\r
+import org.simantics.modelica.data.SimulationResult;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.spreadsheet.SheetVariables;\r
+import org.simantics.spreadsheet.common.matrix.VariantMatrix;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.utils.IndexUtils;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * A result built from a spreadsheet table. Imitates a normal simulation result for \r
+ * easy display on charts and tables.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class HistoryDatasetResult extends SimulationResult {\r
+    @Override\r
+    public void read(File file, int interval) {} // Do nothing\r
+    @Override\r
+    public void read(InputStream stream, int interval) {} // Do nothing\r
+\r
+    private boolean disposed;\r
+\r
+    /**\r
+     * Dispose listeners of this result. It is important to dispose all listeners \r
+     * when they are not needed anymore.\r
+     */\r
+    public void disposeListeners() {\r
+        this.disposed = true;\r
+    }\r
+\r
+    /**\r
+     * Reads history data to this result. Location of the data is described in historyData resource.\r
+     * \r
+     * @param sysdynResult MemoryResult to which this simulation result is read\r
+     * @param historyData Resource describing the history data to be read from a spreadsheet\r
+     */\r
+    public void read(final MemoryResult sysdynResult, final Resource historyData) {\r
+\r
+        Simantics.getSession().asyncRequest(new Read<Pair<SysdynModel, List<DataSet>>>() {\r
+\r
+            @Override\r
+            public Pair<SysdynModel, List<DataSet>> perform(ReadGraph graph) throws DatabaseException {\r
+                ArrayList<DataSet> variables = new ArrayList<DataSet>();\r
+\r
+                SysdynResource sr = SysdynResource.getInstance(graph);\r
+                Layer0 l0 = Layer0.getInstance(graph);\r
+                SimulationResource simu = SimulationResource.getInstance(graph);\r
+\r
+                String datasetName = "History Dataset";\r
+                VariantMatrix vm = null;\r
+                SysdynModel sdmodel = null;\r
+                String timeVariable = "time";\r
+                boolean columns = true;\r
+                try {\r
+                    Pair<SysdynModel, List<DataSet>> emptyResult = new Pair<SysdynModel, List<DataSet>>(sdmodel, variables);\r
+\r
+                    \r
+                    // Find the SysdynModel of this historyData\r
+                    Resource model = graph.getPossibleObject(historyData, l0.PartOf);\r
+                    Resource config = graph.getPossibleObject(model, simu.HasConfiguration);\r
+                    sdmodel = SysdynModelManager.getInstance(graph.getSession()).getModel(graph, config);\r
+                    sdmodel.update(graph);\r
+                    \r
+                    // Find properties of the result: name, sheet, range, time variable, orientation\r
+                    datasetName = NameUtils.getSafeLabel(graph, historyData);\r
+                    \r
+\r
+                    Resource sheet = graph.getPossibleObject(historyData, sr.HistoryDataset_sheet);\r
+                    if(sheet == null)\r
+                        return emptyResult;\r
+                    \r
+                    String start = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_start);\r
+                    String end = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_end);\r
+                    if(start == null || start.isEmpty() || end == null || end.isEmpty())\r
+                        return emptyResult;\r
+                    String r = start + ":" + end;\r
+                    \r
+                    String time = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_timeName);\r
+                    if(time != null && !time.isEmpty())\r
+                        timeVariable = time;\r
+                    \r
+                    if(graph.hasStatement(historyData, sr.HistoryDataset_columns))\r
+                        columns = graph.getRelatedValue(historyData, sr.HistoryDataset_columns, Bindings.BOOLEAN);\r
+                        \r
+                    // Find the sheet variable\r
+                    Variable v = graph.adapt(sheet, Variable.class);\r
+                    Variable range = v.getChild(graph, r);\r
+                    if(range == null)\r
+                        return emptyResult;\r
+                    \r
+                    // Find the content of the range\r
+                    Variant content = range.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT);\r
+                    Object matrixValue = content.getValue();\r
+                    if(matrixValue instanceof VariantMatrix) {\r
+                        vm = (VariantMatrix)matrixValue;\r
+                    }\r
+\r
+                } catch(DatabaseException e) {\r
+                    return new Pair<SysdynModel, List<DataSet>>(sdmodel, variables);\r
+                } catch(NegativeArraySizeException e) {\r
+                    // Negative array size may be result of mofifying start and end variables\r
+                    return new Pair<SysdynModel, List<DataSet>>(sdmodel, variables);\r
+                }\r
+\r
+                \r
+                // Orientation\r
+                int x = columns ? vm.getColumnCount() : vm.getRowCount();\r
+                int y = columns ? vm.getRowCount() : vm.getColumnCount();\r
+                \r
+                /*\r
+                 * The table needs at least:\r
+                 * \r
+                 * headers for variables + one value\r
+                 * two variables (of which one is time-variable)\r
+                 * \r
+                 * => minimum of 2x2 matrix\r
+                 */\r
+                if(vm == null || x < 2 || y < 2)\r
+                    return new Pair<SysdynModel, List<DataSet>>(sdmodel, variables);\r
+\r
+                String[] names = new String[x];\r
+                HashMap<String, ArrayList<Pair<Double, Double>>> values = new HashMap<String, ArrayList<Pair<Double,Double>>>();\r
+                Integer timeIndex = null;\r
+                \r
+                // Find variable names\r
+                for(int i = 0; i < x ; i++) {\r
+                    Variant cell = columns ? vm.get(0, i) : vm.get(i, 0);\r
+                    if(cell != null && cell.getValue() != null) {\r
+                        String name = cell.getValue().toString();\r
+                        if(!values.containsKey(name)) {\r
+                            names[i] = name;\r
+                            values.put(names[i], new ArrayList<Pair<Double,Double>>());\r
+\r
+                            // Time column index\r
+                            if(names[i].equals(timeVariable))\r
+                                timeIndex = i;\r
+                        }\r
+                    } else {\r
+                        names[i] = null;\r
+                    }\r
+                }\r
+\r
+                // If times were not found, return empty\r
+                if(timeIndex == null || names[timeIndex] == null)\r
+                    return new Pair<SysdynModel, List<DataSet>>(sdmodel, variables);\r
+\r
+                // Get time column ready first\r
+                for(int i = 1; i < y; i++) {\r
+                    Variant cell = columns ? vm.get(i, timeIndex) : vm.get(timeIndex, i);\r
+                    Double value = null;\r
+                    if(cell != null)\r
+                        value = getDoubleValue(cell);\r
+                    values.get(names[timeIndex]).add(new Pair<Double, Double>(value, value)); // add also null-values\r
+                }\r
+\r
+                // Get variable values column by column (or row by row\r
+                for(int i = 0; i < x; i++) {\r
+                    if(i == timeIndex || names[i] == null) \r
+                        continue;\r
+\r
+                    for(int j = 1; j < y; j++) {\r
+                        Variant cell = columns ? vm.get(j, i) : vm.get(i, j);\r
+                        if(cell != null && cell.getValue() != null) {\r
+                            Double value = getDoubleValue(cell);\r
+                            if(value != null) {\r
+                                Pair<Double, Double> time = values.get(names[timeIndex]).get(j - 1);\r
+                                if(time != null && time.first != null) {\r
+                                    values.get(names[i]).add(\r
+                                            new Pair<Double, Double>(\r
+                                                    time.first, \r
+                                                    value)\r
+                                            );\r
+                                }\r
+                            }\r
+                        }\r
+                    }\r
+\r
+                    ArrayList<Pair<Double, Double>> doubles = values.get(names[i]);\r
+                    \r
+                    String name = names[i];\r
+                    // If the variable has array indexes, they need to be converted to numbers\r
+                    if(name.contains("[")) {\r
+                        org.simantics.sysdyn.representation.Variable variable = getVariable(name, sdmodel.getConfiguration());\r
+                        if(variable != null)\r
+                            name = IndexUtils.equationRangesToIndexes(variable, name);\r
+                    }\r
+                    \r
+                    // Replace spaces with '_'. That is how they are stored elsewhere\r
+                    name = name.replace(" ", "_");\r
+\r
+                    // Read values to SysdynDataSet\r
+                    SysdynDataSet ds = new SysdynDataSet(name, datasetName, new double[doubles.size()], new double[doubles.size()]);\r
+                    variables.add(ds);\r
+                    for(int d = 0; d < doubles.size(); d++) {\r
+                        Pair<Double, Double> pair = doubles.get(d);\r
+                        ds.times[d] = pair.first;\r
+                        ds.values[d] = pair.second;\r
+                    }\r
+                }\r
+                return new Pair<SysdynModel, List<DataSet>>(sdmodel, variables);\r
+            }\r
+\r
+        }, new Listener<Pair<SysdynModel, List<DataSet>>>() {\r
+\r
+            @Override\r
+            public void execute(Pair<SysdynModel, List<DataSet>> result) {\r
+                // Update result set and send message to model that results have been changed\r
+                HistoryDatasetResult.this.variables = result.second;\r
+                sysdynResult.setResult(HistoryDatasetResult.this);\r
+                if(result.first != null)\r
+                    result.first.resultChanged();\r
+            }\r
+\r
+            @Override\r
+            public void exception(Throwable t) {\r
+                t.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                return disposed;\r
+            }\r
+        });\r
+\r
+\r
+    }\r
+    \r
+    /**\r
+     * Finds a variable defined by path starting from configuration \r
+     * @param path Path of the variable\r
+     * @param configuration Configuration where to look for the variable\r
+     * @return Variable\r
+     */\r
+    private org.simantics.sysdyn.representation.Variable getVariable(String path, Configuration configuration) {\r
+        String next = path;\r
+        int index = next.indexOf(".");\r
+\r
+        // If path has commas, we are looking for a module\r
+        if(index > 0) {\r
+            path = path.substring(index + 1);\r
+            next = next.substring(0, index);\r
+        } else {\r
+            // No commas, we are looking for a variable\r
+            if(next.contains("["))\r
+                // Variable has array indexes, remove the array indexes\r
+                next = next.substring(0, next.indexOf("["));\r
+        }\r
+\r
+        for(IElement e : configuration.getElements()) {\r
+            if(e instanceof org.simantics.sysdyn.representation.Variable) {\r
+                org.simantics.sysdyn.representation.Variable v = (org.simantics.sysdyn.representation.Variable) e;\r
+                if(v.getName().equals(next)) {\r
+                    return v; // found the variable\r
+                }\r
+            } else if(e instanceof Module && ((Module)e).getName().equals(next)) {\r
+                return getVariable(path, ((Module)e).getType().getConfiguration()); // Recursive call with a shorter path\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+\r
+    /**\r
+     * Finds the double value from a spreadsheet cell. \r
+     * @param cell Cell where to look for\r
+     * @return Double value of the cell or null if not double or if empty\r
+     */\r
+    private Double getDoubleValue(Variant cell) {\r
+        if(cell.getValue() == null)\r
+            return null;\r
+\r
+        Double value = null;\r
+        try {\r
+            value = Double.parseDouble(cell.getValue().toString());\r
+        } catch (NumberFormatException e) {\r
+        }\r
+        return value;\r
+    }\r
+\r
+    @Override\r
+    public DataSet getDataSet(String name) {\r
+        DataSet ds = super.getDataSet(name);\r
+        if(ds == null && name.contains(".")) {\r
+            ds = super.getDataSet(name.substring(name.lastIndexOf(".") + 1));\r
+        }\r
+        return ds;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/HistoryDatasetUtils.java
new file mode 100644 (file)
index 0000000..e164c81
--- /dev/null
@@ -0,0 +1,92 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.spreadsheet.SheetVariables;\r
+import org.simantics.spreadsheet.common.matrix.VariantMatrix;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class HistoryDatasetUtils {\r
+    \r
+    public static List<String> getVariableNamesInRange(ReadGraph graph, Resource historyData) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        \r
+        ArrayList<String> values = new ArrayList<String>();\r
+\r
+\r
+        Resource sheet = graph.getPossibleObject(historyData, sr.HistoryDataset_sheet);\r
+        if(sheet == null)\r
+            return values;\r
+        \r
+        String start = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_start);\r
+        String end = graph.getPossibleRelatedValue(historyData, sr.HistoryDataset_end);\r
+        if(start == null || start.isEmpty() || end == null || end.isEmpty())\r
+            return values;\r
+        String r = start + ":" + end;\r
+        \r
+        if(!graph.hasStatement(historyData, sr.HistoryDataset_columns))\r
+            return values;\r
+            \r
+        boolean columns = graph.getRelatedValue(historyData, sr.HistoryDataset_columns, Bindings.BOOLEAN);\r
+            \r
+        Variable v = graph.adapt(sheet, Variable.class);\r
+        Variable range = v.getChild(graph, r);\r
+        if(range == null)\r
+            return values;\r
+        \r
+        Variant content = range.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT);\r
+        Object matrixValue = content.getValue();\r
+        if(!(matrixValue instanceof VariantMatrix))\r
+            return values;\r
+        \r
+        VariantMatrix vm = (VariantMatrix)matrixValue;\r
+        \r
+        /*\r
+         * The table needs at least:\r
+         * \r
+         * headers for variables + one value\r
+         * two variables (of which one is time-variable)\r
+         * \r
+         * => minimum of 2x2 matrix\r
+         */\r
+        \r
+        int x = columns ? vm.getColumnCount() : vm.getRowCount();\r
+        int y = columns ? vm.getRowCount() : vm.getColumnCount();\r
+        \r
+        if(vm == null || x < 2 || y < 2)\r
+            return values;\r
+\r
+        \r
+        // Names\r
+        for(int i = 0; i < x ; i++) {\r
+            Variant cell = columns ? vm.get(0, i) : vm.get(i, 0);\r
+            if(cell != null && cell.getValue() != null) {\r
+                String name = cell.getValue().toString();\r
+                if(!values.contains(name)) {\r
+                    values.add(name);\r
+                }\r
+            }\r
+        }\r
+        \r
+        return values;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/MemoryResult.java
new file mode 100644 (file)
index 0000000..f6ef5bb
--- /dev/null
@@ -0,0 +1,249 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import gnu.trove.map.hash.THashMap;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.util.List;\r
+import java.util.TreeMap;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.simantics.databoard.Accessors;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.Datatypes;\r
+import org.simantics.databoard.Files;\r
+import org.simantics.databoard.accessor.MapAccessor;\r
+import org.simantics.databoard.accessor.RecordAccessor;\r
+import org.simantics.databoard.accessor.error.AccessorConstructionException;\r
+import org.simantics.databoard.accessor.java.JavaRecord;\r
+import org.simantics.databoard.annotations.Arguments;\r
+import org.simantics.databoard.binding.Binding;\r
+import org.simantics.databoard.binding.RecordBinding;\r
+import org.simantics.databoard.binding.error.BindingException;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.databoard.type.Datatype;\r
+import org.simantics.modelica.data.DataSet;\r
+import org.simantics.modelica.data.SimulationResult;\r
+\r
+// TODO: rename to OpenModelicaResult or something as this is very specific?\r
+public class MemoryResult extends SysdynResult {\r
+    \r
+    private THashMap<String, SysdynDataSet> results;\r
+    private File resultFile;\r
+    private Integer resultIndex = null;\r
+    private SimulationResult simulationResult;\r
+\r
+\r
+    /**\r
+     * Create a sysdynresult accessor using a {@link SimulationResult}\r
+     * @param result\r
+     */\r
+    public MemoryResult(SimulationResult result, String resultName) {\r
+        super(resultName);\r
+        \r
+        results = new THashMap<String, SysdynDataSet>();\r
+\r
+        if(result != null)\r
+            setResult(result);\r
+        \r
+    }\r
+    \r
+    @Override\r
+    public SysdynDataSet getDataSet(String variable) {\r
+        // Try to get cached result\r
+        SysdynDataSet result = results.get(variable);\r
+        if(result != null)\r
+            return result;\r
+        \r
+        // if not found, try to read it\r
+        SimulationResult simulationResult = getSimulationResult();\r
+        try {\r
+            if (simulationResult != null) {\r
+                DataSet ds = simulationResult.getDataSet(variable);\r
+                if(ds == null)\r
+                    ds = simulationResult.readVariable(variable, resultFile);\r
+\r
+                if(ds != null) {\r
+                    SysdynDataSet sds = new SysdynDataSet(ds.name, getResultName(), ds.times, ds.values, resultIndex);\r
+                    results.put(variable, sds);\r
+                    return sds;\r
+                }\r
+            }\r
+        } catch (FileNotFoundException e1) {\r
+            // Unable to read data from OpenModelica result file\r
+            System.err.println("Variable " + variable + " not found in OpenModelica result file");\r
+            return null;\r
+        } catch (IOException e1) {\r
+            // IoFail\r
+            e1.printStackTrace();\r
+        }\r
+        \r
+        return null;\r
+    }\r
+\r
+    public void setResultFile(File resFile) {\r
+        this.resultFile = resFile;\r
+    }\r
+    \r
+    public int numberOfVariables() {\r
+        return simulationResult.getVariableDataSets().size();\r
+    }\r
+    \r
+    public void setResult(SimulationResult result) {\r
+        this.simulationResult = result;\r
+        this.results.clear();\r
+        if(result != null)\r
+            addAllInitialValues(result); // For legacy reasons\r
+    }\r
+    \r
+    public SimulationResult getSimulationResult() {\r
+        return this.simulationResult;\r
+    }\r
+\r
+    \r
+    \r
+    /**\r
+     * Read all results from their DataSets. --- Legacy init file support. Not needed with mat files.\r
+     */\r
+    private void addAllInitialValues(SimulationResult result) {\r
+        // Add initial values\r
+        for(DataSet ds : result.getInitialValueDataSets()){\r
+            SysdynDataSet sds = new SysdynDataSet(ds.name, getResultName(), ds.times, ds.values);\r
+            results.put(ds.name, sds);\r
+        }\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Save current {@link RecordAccessor} to a {@link File}\r
+     * \r
+     * @param file {@link File} where the {@link RecordAccessor} is saved\r
+     */\r
+    @Override\r
+    public void saveToFile(File file, IProgressMonitor progressMonitor) {\r
+        try {\r
+            // Create Memory Historian\r
+            Datatype recordingSessionType = Datatypes.getDatatype("RecordingSession");\r
+            RecordBinding sessionBinding = (RecordBinding) Bindings.getBinding( recordingSessionType );\r
+            Object session = sessionBinding.createDefault();  \r
+            JavaRecord accessor = (JavaRecord) Accessors.getAccessor( sessionBinding, session );\r
+\r
+            // Get binding and value from memory\r
+            JavaRecord jr = (JavaRecord) accessor;\r
+            Binding binding = jr.getBinding();\r
+            Object value = jr.getObject();\r
+                \r
+            // Read the missing variables one by one.\r
+            getSimulationResult().readMissingVariables(this.resultFile);\r
+\r
+            addAllDataSetsToAccessor(accessor, progressMonitor);\r
+            // Write to file\r
+            if (progressMonitor != null) {\r
+                progressMonitor.subTask("Save results");\r
+            }\r
+            Files.createFile(file, binding, value);\r
+            \r
+            // The division is made so that 1 unit per variable and their sum for saving them.\r
+            progressMonitor.worked(numberOfVariables());\r
+        } catch (IOException e) {\r
+            e.printStackTrace();\r
+        } catch (BindingException e) {\r
+            e.printStackTrace();\r
+        } catch (AccessorConstructionException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Read all results from their DataSets.\r
+     * @param progressMonitor \r
+     */\r
+    private void addAllDataSetsToAccessor(JavaRecord accessor, IProgressMonitor progressMonitor) {\r
+        try {\r
+            MapAccessor recordings = accessor.getFieldAccessor("recordings");\r
+    \r
+            // There is a recording for each variable\r
+            List<DataSet> datasets = getSimulationResult().getVariableDataSets();\r
+            RecordBinding recordingBinding = (RecordBinding) Bindings.getBinding( Recording.class );\r
+            if (progressMonitor != null) {\r
+                progressMonitor.subTask("Prepare saving");\r
+            }\r
+            // Add variables\r
+            for(DataSet ds : datasets){\r
+                if (progressMonitor != null) {\r
+                    progressMonitor.worked(1);\r
+                }\r
+                // Add recording to session, if not already added\r
+                Variant dsNodeId = Variant.ofInstance( ds.name );\r
+                if (recordings.containsKey(Bindings.VARIANT, dsNodeId)) \r
+                    continue;\r
+                \r
+                Recording recording = createRecording(ds);\r
+                recordings.put(Bindings.VARIANT, recording.nodeId, Bindings.VARIANT, new Variant(recordingBinding, recording));\r
+            }\r
+        } catch (Exception e) {\r
+            e.printStackTrace();\r
+        } \r
+    }\r
+    \r
+    /**\r
+     * Create a recording for a variable to this result's {@link RecordAccessor} \r
+     * @param ds {@link DataSet} for the variable\r
+     * @return {@link Recording}\r
+     * @throws BindingException\r
+     */\r
+    @SuppressWarnings("unchecked")\r
+    Recording createRecording(DataSet ds) throws BindingException {\r
+        RecordBinding recordingBinding = (RecordBinding) Bindings.getBindingUnchecked( Recording.class );\r
+        Recording recording = (Recording) recordingBinding.createDefault();                 \r
+        recording.nodeId = Variant.ofInstance( ds.name );\r
+        recording.labels.put("en", ds.name);\r
+\r
+        // Create one segment\r
+        TreeMap<Double, Double> segment = new TreeMap<Double, Double>();\r
+        recording.segments = new TreeMap[] { segment };\r
+\r
+        int length = ds.values.length;\r
+        for (int i=0; i<length; i++) {\r
+            double time = ds.times[i];\r
+            double value = ds.values[i];\r
+            segment.put(time, value);                      \r
+        }\r
+        return recording;\r
+    }\r
+    \r
+    /**\r
+     * Class representing a recording for a variable\r
+     * @author Teemu Lempinen\r
+     *\r
+     */\r
+    public static class Recording {\r
+        public Variant nodeId;\r
+        public @Arguments({String.class, String.class}) TreeMap<String, String> labels;\r
+        public @Arguments({TreeMap.class, Double.class, Double.class}) TreeMap<Double, Double>[] segments;\r
+    }\r
+\r
+    /**\r
+     * Set the index of the run; used when the individual time series of a variable are shown in\r
+     * the same JFreeChart.\r
+     * @param currentRun The index of the run \r
+     */\r
+       public void setResultIndex(int resultIndex) {\r
+               this.resultIndex = resultIndex;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java
new file mode 100644 (file)
index 0000000..326e8cb
--- /dev/null
@@ -0,0 +1,885 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4180\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import gnu.trove.set.hash.THashSet;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.concurrent.locks.Lock;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.preferences.DefaultScope;\r
+import org.eclipse.core.runtime.preferences.IScopeContext;\r
+import org.osgi.service.prefs.Preferences;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.RequestProcessor;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.VirtualGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modelica.IModelicaMonitor;\r
+import org.simantics.modelica.ModelicaException;\r
+import org.simantics.modelica.ModelicaKeys;\r
+import org.simantics.modelica.ModelicaManager;\r
+import org.simantics.modelica.SimulationLocation;\r
+import org.simantics.modelica.data.CSVSimulationResult;\r
+import org.simantics.modelica.data.MatSimulationResult;\r
+import org.simantics.modelica.data.SimulationResult;\r
+import org.simantics.modelica.preferences.OpenModelicaPreferences;\r
+import org.simantics.simulation.data.Datasource;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IExperimentListener;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.Activator;\r
+import org.simantics.sysdyn.adapter.VariableValueSubscription;\r
+import org.simantics.sysdyn.modelica.ModelicaWriter;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.Model;\r
+import org.simantics.sysdyn.simulation.SimulationScheduler;\r
+\r
+public class OldSysdynExperiment extends SysdynExperiment {\r
+\r
+    protected Session                                                          session;\r
+    protected Runnable                                                                 modificationListener;\r
+    protected SysdynModel                                                      sysdynModel;\r
+    protected boolean                                                          toggled = false;\r
+    @SuppressWarnings("rawtypes")\r
+    protected THashSet<VariableValueSubscription>      variableValueSubscriptions = new THashSet<VariableValueSubscription>();\r
+    @SuppressWarnings("rawtypes")\r
+    protected volatile VariableValueSubscription[]     variableValueSubscriptionsSnapshot = null;\r
+\r
+    protected String                                                           previousModelStructure;\r
+    protected HashMap<String, String>               previousParameters;\r
+    protected Process                                                          process;\r
+    protected boolean                                                          canceled = false;\r
+    protected ExperimentState                       sysdynExperimentState;\r
+\r
+    private SysdynResult                            result;\r
+    private File                                    simulationDir;\r
+\r
+    protected String                                experimentName;\r
+    protected static String                         omcVersion = null;\r
+    protected static String                         omcHome = null;\r
+\r
+    public static OldSysdynExperiment                                  INSTANCE;\r
+\r
+    public OldSysdynExperiment(Resource experiment, Resource model) {\r
+        super(experiment, model);\r
+        INSTANCE = this;\r
+    }\r
+\r
+    public static OldSysdynExperiment getInstance() {\r
+        return INSTANCE;\r
+    }\r
+\r
+    public SysdynResult getCurrentResult() {\r
+        if(this.result == null)\r
+            this.result = new MemoryResult(null, null);\r
+        return this.result;\r
+    }\r
+\r
+    public Collection<SysdynResult> getActiveResults() {\r
+        ArrayList<SysdynResult> result = new ArrayList<SysdynResult>();\r
+        if(getCurrentResult() != null)\r
+            result.add(getCurrentResult());\r
+        result.addAll(sysdynModel.getDisplayedResults());\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * Initialize this experiment\r
+     * @param g ReadGraph\r
+     */\r
+    public void init(ReadGraph g) {\r
+        try {\r
+            this.experimentName = NameUtils.getSafeName(g, experiment);\r
+        } catch (DatabaseException e) {\r
+            this.experimentName = "Experiment";\r
+        }\r
+\r
+        this.session = g.getSession();\r
+        state = ExperimentState.STOPPED;\r
+        for(IExperimentListener listener : listeners.getListeners())\r
+            listener.stateChanged(state);\r
+\r
+        try {\r
+                       g.syncRequest(new ReadRequest() {\r
+\r
+                           @Override\r
+                           public void run(ReadGraph graph) throws DatabaseException {\r
+                               final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+                               sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration);\r
+                               toggleActivation(graph, true);\r
+                           }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       Logger.defaultLogError(e);\r
+               }\r
+\r
+        setSysdynExperimentState(ExperimentState.INITIALIZING);\r
+    }\r
+\r
+    @Override\r
+    public void saveState() {\r
+        if(result == null || !(result instanceof MemoryResult)) \r
+            return;\r
+        // TODO: temporary fix\r
+        SaveResultJob saveResultJob = new SaveResultJob(OldSysdynExperiment.this, session, (MemoryResult)result);\r
+        saveResultJob.schedule();\r
+    }\r
+\r
+    protected Thread getSaveThread(final SysdynResult result, final File file, final IProgressMonitor progressMonitor) {\r
+        return new Thread() {\r
+            @Override\r
+            public void run() {\r
+                if(!canceled) {\r
+                    // Get and store results\r                    result.saveToFile(file, progressMonitor);\r
+                }\r            }\r
+        };\r
+    }\r
+    \r
+    /**\r
+     * Starts a simulation job. Use this method to start a simulation.\r
+     */\r
+    @Override\r
+    public void simulate(boolean enabled) {\r
+        if(enabled && sysdynModel != null) {\r
+            if(!ExperimentState.RUNNING.equals(getState())) {\r
+                changeState(ExperimentState.RUNNING);\r
+                startSimulationJob();\r
+            }\r
+        } else if (!toggled){\r
+            changeState(ExperimentState.STOPPED);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Starts a simulation job\r
+     */\r
+    protected void startSimulationJob() {\r
+        session.asyncRequest(new ReadRequest() {\r
+\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                SimulationScheduler.start(sysdynModel, OldSysdynExperiment.this);\r
+            }\r
+        });\r
+    }\r
+\r
+\r
+    /**\r
+     * Write model configuration to a single Modelica code\r
+     * @param monitor\r
+     * @param isGame is the experiment a "game experiment". This is needed for modifying the code to work with FMU simulation\r
+     * @return Modelica code\r
+     */\r
+    protected String getModelicaCode(IModelicaMonitor monitor, boolean isGame, String modelicaVersion) {\r
+        String modelText = null;\r
+        try {\r
+            // Write all configurations once\r
+            modelText = ModelicaWriter.write(sysdynModel.getModules(), sysdynModel.getConfiguration().getModel().getStartTime(), isGame, modelicaVersion);\r
+        } catch (Exception e) {\r
+            // Stop experiment and show console\r
+            /*setExperimentStopped(experiment); =>*/ simulate(false);\r
+            monitor.showConsole();\r
+            monitor.message("Error when writing Modelica code.");\r
+        }\r
+        return modelText;\r
+    }\r
+\r
+    /**\r
+     * Get all inits and parameter values required for the inits -file\r
+     * @param monitor\r
+     * @return All inits in a map\r
+     */\r
+    protected HashMap<String, String> getExperimentParameters(IModelicaMonitor monitor) {\r
+        Configuration configuration = sysdynModel.getConfiguration();\r
+//        HashMap<String, String> inits = sysdynModel.getInits(configuration, ""); Not needed anymore, whole xml content is replaced\r
+        HashMap<String, String> parameters = new HashMap<String, String>();\r
+        Model model = configuration.getModel();\r
+        Double startTime = model.getStartTime();\r
+        Double stopTime = model.getStopTime();\r
+        parameters.put(ModelicaKeys.START_VALUE, startTime.toString());\r
+        parameters.put(ModelicaKeys.STOP_VALUE, stopTime.toString());\r
+        String outputFormat = "mat";\r
+        parameters.put(ModelicaKeys.OUTPUT_FORMAT, outputFormat);\r
+\r
+        Double simulationStepLength = model.getSimulationStepLength();\r
+        if(simulationStepLength != null) {\r
+            parameters.put(ModelicaKeys.STEP_VALUE, simulationStepLength.toString());\r
+            parameters.put(ModelicaKeys.NUMBER_OF_INTERVALS, "" + ((int)((stopTime - startTime) / simulationStepLength)));\r
+        } else {\r
+            parameters.put(ModelicaKeys.STEP_VALUE, "" + (stopTime - startTime) / 500);\r
+        }\r
+\r
+        Double outputInterval = model.getOutputInterval();\r
+        parameters.put(ModelicaKeys.OUTPUT_INTERVAL, outputInterval != null ? outputInterval.toString() : parameters.get(ModelicaKeys.STEP_VALUE));\r
+\r
+        String method = "\"" + model.getSolver() + "\"";\r
+        parameters.put(ModelicaKeys.METHOD, method);\r
+        if(model.getTolerance() != null)\r
+            parameters.put(ModelicaKeys.TOLERANCE, model.getTolerance().toString());\r
+        String variableFilter = model.getVariableFilter();\r
+        if(variableFilter != null && !variableFilter.isEmpty())\r
+            parameters.put(ModelicaKeys.VARIABLE_FILTER, variableFilter);\r
+        return parameters;\r
+    }\r
+\r
+    /**\r
+     * Builds a model\r
+     * @param simulationLocation\r
+     * @param inits\r
+     * @param modelText\r
+     * @param monitor\r
+     */\r
+    protected void buildModel(SimulationLocation simulationLocation, IModelicaMonitor monitor) {\r
+\r
+        try {\r
+            simulationLocation.executableFile.delete();\r
+            ModelicaManager.buildModel(simulationLocation, monitor);\r
+        } catch (ModelicaException e) {\r
+            if(e.getMessage() != null)\r
+                monitor.message(e.getMessage());\r
+            monitor.showConsole();\r
+            canceled = true;\r
+            previousModelStructure = "";\r
+            previousParameters = null;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Run a built model\r
+     * @param structureChanged \r
+     * @throws IOException\r
+     */\r
+    protected void runModelica(SimulationLocation simulationLocation, IModelicaMonitor monitor, IProgressMonitor progressMonitor, HashMap<String, String> experimentParameters, HashMap<String, String> changes) throws IOException {\r
+        progressMonitor.subTask("Simulate model");\r
+        process = ModelicaManager.runModelica(\r
+                simulationLocation,\r
+                monitor,\r
+                experimentParameters, \r
+                changes\r
+                );\r
+        ModelicaManager.printProcessOutput(process, monitor);\r
+\r
+        Thread resultThread = getResultThread(simulationLocation, experimentParameters, monitor, progressMonitor);\r
+        resultThread.run();\r
+\r
+        process = null;\r
+    }\r
+\r
+    /**\r
+     * Get a thread for reading and saving reuslts from a normal simulation\r
+     * @param simulationLocation\r
+     * @param inits\r
+     * @param monitor\r
+     * @param progressMonitor\r
+     * @return\r
+     */\r
+    protected Thread getResultThread(final SimulationLocation simulationLocation, final HashMap<String, String> experimentParameters, final IModelicaMonitor monitor, final IProgressMonitor progressMonitor) {\r
+        return new Thread() {\r
+            @Override\r
+            public void run() {\r
+                try {\r
+                    process.waitFor();\r
+\r
+                    if(!canceled) {\r
+                        // Get and store results\r
+                        progressMonitor.worked(1);\r
+                        progressMonitor.subTask("Read results");\r
+                        SimulationResult result;\r
+                        if(simulationLocation.resultFile.getName().endsWith(".csv"))\r
+                            result = new CSVSimulationResult();\r
+                        else if(simulationLocation.resultFile.getName().endsWith(".plt"))\r
+                            result = new SimulationResult();\r
+                        else\r
+                            result = new MatSimulationResult(); // The latest format\r
+\r
+                        // The interval of results saved. Every result? Every other result? etc...\r
+                        int outIntervalInt = 1;\r
+                        String outputInterval = experimentParameters.get(ModelicaKeys.OUTPUT_INTERVAL);\r
+                        if(outputInterval != null) {\r
+                            String stepTime = experimentParameters.get(ModelicaKeys.STEP_VALUE);\r
+                            String stopTime = experimentParameters.get(ModelicaKeys.STOP_VALUE);\r
+                            \r
+                            Double step = Double.parseDouble(stepTime);\r
+                            Double stop = Double.parseDouble(stopTime);\r
+                            Double outInterval = Double.parseDouble(outputInterval);\r
+\r
+                            outIntervalInt = (int)getInterval(outInterval, step);\r
+                            // Actually you might be able to use an outInterval one or two longer. \r
+                            int maxIntervalInt = (int)Math.round(stop / step);\r
+                            if (outIntervalInt > maxIntervalInt)\r
+                                outIntervalInt = maxIntervalInt;\r
+                        }\r
+\r
+                        result.initRead(simulationLocation.resultFile);\r
+                        result.readTime(simulationLocation.resultFile, outIntervalInt);\r
+                        //result.readInits(simulationLocation.initFile); // Parameter values are read from .mat\r
+                        result.filter();\r
+                        ((MemoryResult)getCurrentResult()).setResult(result);\r
+                        ((MemoryResult)getCurrentResult()).setResultFile(simulationLocation.resultFile);\r
+                        progressMonitor.worked(1);\r
+                        resultsChanged();\r
+\r
+                        simulate(false);\r
+\r
+                        String errorString = result.getResultReadErrors();\r
+                        if(errorString != null && !errorString.isEmpty())\r
+                            monitor.message(errorString);\r
+                    }\r
+                } catch (FileNotFoundException e) {\r
+                    e.printStackTrace();\r
+                } catch (IOException e) {\r
+                    e.printStackTrace();\r
+                } catch (InterruptedException e) {\r
+                    e.printStackTrace();\r
+                }\r
+            }\r
+        };\r
+    }\r
+\r
+    protected static long getInterval(double outputLength, double stepLength) {\r
+        double interval = outputLength / stepLength;\r
+        if (interval <= 1)\r
+            return 1;\r
+        return Math.round(interval);\r
+    }\r
+\r
+\r
+    /**\r
+     * \r
+     * @param sysdynModel\r
+     * @param modelText\r
+     * @param inits\r
+     * @param additionalScript\r
+     * @return\r
+     * @throws IOException\r
+     */\r
+    protected SimulationLocation createSimulationFiles(SysdynModel sysdynModel, String modelText, HashMap<String, String> inits, String additionalScript, boolean fmu) throws IOException {\r
+        File simulationDir = getExperimentDir();\r
+\r
+        // update all function files. both the model's and built-in\r
+        FunctionUtils.updateFunctionFilesForExperiment(this);\r
+\r
+\r
+        SimulationLocation location = ModelicaManager.createSimulationLocation(simulationDir, sysdynModel.getConfiguration().getLabel(), modelText, ModelicaManager.getOMHome(), ModelicaManager.isOldOMVersion());\r
+        if (fmu) {\r
+               ModelicaManager.createFMUSimulationScripts(location, inits, additionalScript);\r
+        }\r
+        else {\r
+               ModelicaManager.createSimulationScripts(location, inits, additionalScript);\r
+        }\r
+        return location;\r
+    }\r
+\r
+    /**\r
+     * Get a simulation directory for this model\r
+     * @return File directory\r
+     */\r
+    public File getExperimentDir() {\r
+        if(simulationDir == null) {\r
+            File modelsDir = Activator.getBundleContext().getDataFile("models");\r
+            String experimentName = this.experimentName;\r
+            List<String> files = Arrays.asList(modelsDir.list());\r
+            if (files.contains(experimentName)) {\r
+                int i = 2;\r
+                while (files.contains(experimentName + "_" + i)){\r
+                    i++;\r
+                }\r
+                experimentName += "_" + i;\r
+            }\r
+\r
+            simulationDir  = Activator.getBundleContext().getDataFile("models/" + experimentName);\r
+            if (!simulationDir.exists()) {\r
+                simulationDir.mkdir();\r
+            }\r
+        }\r
+        return simulationDir;\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @return\r
+     */\r
+    protected String getAdditionalScripts() {\r
+        StringBuilder functionscript = new StringBuilder();\r
+        for(String path : FunctionUtils.getLibraryPathsForModelica(this)) {\r
+            functionscript.append("loadFile(\"" + path + "\");\n");\r
+        }\r
+        return functionscript.toString();\r
+    }\r
+\r
+    /**\r
+     * Starts simulating a model. Call only from inside simulation job! Start simulation using simulate(true).\r
+     * @param monitor\r
+     * @param progressMonitor\r
+     * @throws IOException\r
+     */\r
+    public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException {\r
+        canceled = false;\r
+        progressMonitor.subTask("Write modelica classes");\r
+\r
+        omcVersion = ModelicaManager.getDefaultOMVersion();\r
+        \r
+        monitor.message("Simulate " + modelName + " using OpenModelica " + omcVersion);\r
+        \r
+        // Get Modelica code\r
+        String modelText = getModelicaCode(monitor, false, omcVersion);\r
+        if(modelText == null)\r
+            return;\r
+        progressMonitor.worked(1);\r
+\r
+        // Write initial files and add init-parameters\r
+        progressMonitor.subTask("Write simulation files");\r
+        HashMap<String, String> experimentParameters = getExperimentParameters(monitor);\r
+        \r
+        // add loadFile script to load all related functions and function libraries\r
+        String additionalScript = getAdditionalScripts();\r
+        \r
+        // Create simulation files\r
+        SimulationLocation simulationLocation = createSimulationFiles(sysdynModel, modelText, experimentParameters, additionalScript, false);\r
+        progressMonitor.worked(1);\r
+        \r
+        // Build the model and store previous model structure and inits that affect the building\r
+        // If there is no exe file OR the model structure has not changed, no need to build\r
+        String flatModelText = ModelicaManager.getFlatModelText(simulationLocation, monitor, FunctionUtils.getLibraryPathsForModelica(this));\r
+        boolean structureChanged = sysdynModel.isStructureModified();\r
+        \r
+        if (!simulationLocation.executableFile.isFile() || structureChanged) {\r
+            progressMonitor.subTask("Build model");\r
+            previousModelStructure = flatModelText;\r
+            previousParameters = ModelicaManager.getModelParameters(previousModelStructure);\r
+            \r
+            buildModel(simulationLocation, monitor);\r
+        }\r
+        \r
+        // Add changed parameters in case that structure has not changed\r
+        HashMap<String, String> changes = structureChanged ? null : new HashMap<String, String>();\r
+        if(!structureChanged && previousParameters != null && omcVersion.startsWith("1.9")) {\r
+                HashMap<String, String> newParameters = ModelicaManager.getModelParameters(flatModelText);\r
+                for(String key : previousParameters.keySet()) {\r
+                    if(!previousParameters.get(key).equals(newParameters.get(key))) {\r
+                        changes.put(key, newParameters.get(key));\r
+                    }\r
+                }\r
+                previousParameters = newParameters;\r
+        }\r
+        progressMonitor.worked(1);\r
+        \r
+        if(simulationLocation != null && !canceled) {\r
+            // Simulate the model\r
+            runModelica(simulationLocation, monitor, progressMonitor, experimentParameters, changes);\r
+        }\r
+        \r
+        if(canceled)\r
+            simulate(false);\r
+        process = null;\r
+    }\r
+\r
+    /**\r
+     * Get the version of the OpenModelica compiler that is defined to be used\r
+     * in Preferences\r
+     * @return OpenModelica version\r
+     */\r
+    protected String getOpenModelicaVersion() {\r
+        String omVersion = null;\r
+\r
+        IScopeContext context = DefaultScope.INSTANCE;\r
+        Preferences node = context.getNode(org.simantics.modelica.Activator.PLUGIN_ID);\r
+        String omHome = node.get(OpenModelicaPreferences.OM_HOME, null);\r
+        if(omHome != null) {\r
+               File omHomeDir = new File(omHome);\r
+               if(omHomeDir != null && omHomeDir.isDirectory())\r
+                       omVersion = ModelicaManager.getOMVersion(omHomeDir);\r
+        }\r
+\r
+        if(omVersion == null) {\r
+               omVersion = ModelicaManager.getDefaultOMVersion();\r
+        }\r
+        \r
+        return omVersion;\r
+    }\r
+\r
+\r
+    /**\r
+     * Method that compares given modelText and inits to previous model and inits\r
+     * @param modelText Textual representation of a model (Modelica code)\r
+     * @param inits map of init parameters\r
+     * @return true if the model has changed, false otherwise\r
+     */\r
+//    protected boolean hasStructureChanged(String modelText) {\r
+//\r
+//        if(previousModelStructure == null)\r
+//            return true;\r
+//\r
+//        // Then compare the actual model structure\r
+//        BufferedReader current = new BufferedReader(\r
+//                new StringReader(modelText));\r
+//        BufferedReader previous = new BufferedReader(\r
+//                new StringReader(previousModelStructure));\r
+//\r
+//        String c, p;\r
+//        try {\r
+//            // Read both current and previous model texts at the same time\r
+//            c = current.readLine();\r
+//            p = previous.readLine();\r
+//\r
+//            while (c != null && p != null) {\r
+//                // if the lines are the same, no need for further examination\r
+//                if(!c.equals(p)) {\r
+//                    if(c.contains("parameter") && p.contains("parameter")) {\r
+//                        /*\r
+//                         *  The line is a parameter definition.\r
+//                         *  In this case only what is before '=' matters\r
+//                         * \r
+//                         *  parameter Real Var = 1;\r
+//                         *     is structurally same as\r
+//                         *  parameter Real Var = 2;\r
+//                         */\r
+//                        int i = c.indexOf("=");\r
+//                        if(!c.substring(0, i).equals(p.substring(0, i))) {\r
+//                            // different parameter definition\r
+//                            return true;\r
+//                        }\r
+//                    } else {\r
+//                        // other than a line containing parameters differs\r
+//                        return true;\r
+//                    }\r
+//                }\r
+//                c = current.readLine();\r
+//                p = previous.readLine();\r
+//            }\r
+//\r
+//            if((c == null && p != null) || (c != null && p == null)) {\r
+//                // different lengths\r
+//                return true;\r
+//            }\r
+//\r
+//        } catch(IOException e) {\r
+//            // Something went wrong in the comparison, it is safer to say that the structure has changed\r
+//            return true;\r
+//        }\r
+//        return false;\r
+//    }\r
+\r
+    /**\r
+     * Destroy an ongoing simulation process\r
+     */\r
+    public void cancelSimulation() {\r
+        canceled = true;\r
+        if(process != null) {\r
+            process.destroy();\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Toggle simulation state\r
+     * @param enabled true == RUNNING, false == STOPPED\r
+     */\r
+    public void toggleSimulation(boolean enabled) {\r
+        if(enabled) {\r
+            this.toggled = true;\r
+            changeState(ExperimentState.RUNNING);\r
+            if(modificationListener == null) {\r
+\r
+                modificationListener = new Runnable() {\r
+\r
+                    @Override\r
+                    public void run() {\r
+                        session.asyncRequest(new ReadRequest() {\r
+\r
+                            @Override\r
+                            public void run(ReadGraph graph) throws DatabaseException {\r
+                                if(getState() == ExperimentState.RUNNING) {\r
+                                    SimulationScheduler.start(sysdynModel, OldSysdynExperiment.this);\r
+                                }\r
+\r
+                            }\r
+                        });\r
+\r
+                    };\r
+                };\r
+                sysdynModel.addModificationListener(modificationListener);\r
+            }\r
+        }\r
+        else {\r
+            changeState(ExperimentState.STOPPED);\r
+            this.toggled = false;\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    public void refresh(RequestProcessor session) {\r
+        session.asyncRequest(new ReadRequest() {\r
+\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                init(graph);\r
+            }\r
+\r
+        });\r
+    }\r
+    \r
+    @Override\r
+    public void refresh(Session session) {\r
+        refresh((RequestProcessor)session);\r
+    }\r
+\r
+    @Override\r
+    protected void localStateChange() {\r
+        setSysdynExperimentState(getState());\r
+        switch(state) {\r
+            case DISPOSED:\r
+                onExperimentDisposed();\r
+                break;\r
+            default:\r
+                break;\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Returns sysdyn experiment state. It is usually the same as ordinary experiment state.\r
+     * Initializing phase takes longer than normally in game experiments.\r
+     * @return\r
+     */\r
+    public ExperimentState getSysdynExperimentState() {\r
+        return sysdynExperimentState;\r
+    }\r
+\r
+    protected void setSysdynExperimentState(final ExperimentState state) {\r
+        sysdynExperimentState = state;\r
+        session.asyncRequest(new ReadRequest() {\r
+\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
+                final Session session = graph.getSession();\r
+                session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 L0 = Layer0.getInstance(graph);\r
+                        SimulationResource SR = SimulationResource.getInstance(graph);\r
+                        graph.deny(model, SR.HasExperimentState);\r
+                        graph.deny(experiment, SR.HasExperimentState);\r
+\r
+                        Resource st = graph.newResource();\r
+                        switch(state) {\r
+                            case INITIALIZING:\r
+                                graph.claim(st, L0.InstanceOf, SR.ExperimentState_Initializing);\r
+                                break;\r
+                            case RUNNING:\r
+                                graph.claim(st, L0.InstanceOf, SR.ExperimentState_Running);\r
+                                break;\r
+                            case STOPPED:\r
+                                graph.claim(st, L0.InstanceOf, SR.ExperimentState_Stopped);\r
+                                break;\r
+                            case DISPOSED:\r
+                                graph.claim(st, L0.InstanceOf, SR.ExperimentState_Disposed);\r
+                                break;\r
+                        }\r
+\r
+                        graph.claim(model, SR.HasExperimentState, st);\r
+                        graph.claim(experiment, SR.HasExperimentState, st);\r
+                    }});\r
+            }\r
+        });\r
+    }\r
+\r
+    /**\r
+     * Actions performed when experiment is disposed\r
+     * @param graph\r
+     */\r
+    protected void onExperimentDisposed() {\r
+        cancelSimulation();\r
+        sysdynModel.removeModificationListener(modificationListener);\r
+        modificationListener = null;\r
+\r
+        session.asyncRequest(new ReadRequest() {\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                toggleActivation(graph, false);\r
+            }\r
+        });\r
+    }\r
+\r
+\r
+    /**\r
+     * Toggles the active-state of this experiment on or off\r
+     * @param graph ReadGraph\r
+     * @param activate The active-state of this experiment\r
+     */\r
+    protected void toggleActivation(ReadGraph graph, final boolean activate) {\r
+        VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
+        final Session session = graph.getSession();\r
+        session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {\r
+            @Override\r
+            public void perform(WriteGraph graph) throws DatabaseException {\r
+                VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
+\r
+                session.asyncRequest(new WriteRequest(runtime) {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+                        if(activate)\r
+                            graph.claim(experiment, SIMU.IsActive, experiment);\r
+                        else\r
+                            graph.denyStatement(experiment, SIMU.IsActive, experiment);\r
+                    }\r
+\r
+                });\r
+            }\r
+        });\r
+    }\r
+\r
+\r
+    /* Result subscriptions */\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    /**\r
+     * Copy from AprosExperiment\r
+     * @param subscription\r
+     */\r
+    @Override\r
+    public void addVariableValueSubscription(VariableValueSubscription subscription) {\r
+        assert subscription != null;\r
+        synchronized (variableValueSubscriptions) {\r
+            //System.out.println("ADD listener " + subscription);\r
+            variableValueSubscriptions.add(subscription);\r
+            variableValueSubscriptionsSnapshot = null;\r
+        }\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    /**\r
+     * Copy from AprosExperiment\r
+     * @param subscription\r
+     */\r
+    @Override\r
+    public void removeVariableValueSubscription(VariableValueSubscription subscription) {\r
+        assert subscription != null;\r
+        synchronized (variableValueSubscriptions) {\r
+            //System.out.println("REMOVE listener " + subscription);\r
+            variableValueSubscriptions.remove(subscription);\r
+            variableValueSubscriptionsSnapshot = null;\r
+        }\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    /**\r
+     * Copy from AprosExperiment\r
+     * @return\r
+     */\r
+    @Override\r
+    public VariableValueSubscription[] getListenerSnapshot() {\r
+        VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot;\r
+        if (snapshot == null) {\r
+            synchronized (variableValueSubscriptions) {\r
+                snapshot = variableValueSubscriptionsSnapshot;\r
+                if (snapshot == null) {\r
+                    snapshot = variableValueSubscriptionsSnapshot = variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]);\r
+                }\r
+            }\r
+            //System.out.println("listener count: " + snapshot.length);\r
+        }\r
+        return snapshot;\r
+    }\r
+\r
+    volatile long previousVariableUpdateTime = 0;\r
+    volatile boolean skippedVariableUpdate = true;\r
+\r
+\r
+    /**\r
+     * Modified copy from AprosExperiment\r
+     */\r
+    public void resultsChanged() {\r
+       resultsChanged(false);\r
+    }\r
+\r
+    public void resultsChanged(boolean force) {\r
+        long time = System.nanoTime();\r
+        long sinceLast = time - previousVariableUpdateTime;\r
+//        System.err.println("sinceLast " + 1e-9*sinceLast);\r
+        if(sinceLast > 100000000 || force) {\r
+            updateSubscriptions();\r
+            previousVariableUpdateTime = time;\r
+        }\r
+        else\r
+            skippedVariableUpdate = true;\r
+    }\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    /**\r
+     * Modified copy from AporsExperiment\r
+     */\r
+    @Override\r
+    public void updateSubscriptions() {\r
+        for(VariableValueSubscription subscription : getListenerSnapshot())\r
+            subscription.update();\r
+        skippedVariableUpdate = false;\r
+    }\r
+    \r
+    public int numberOfSimulationRunSteps() {\r
+        /*\r
+         * 1. Write modelica files\r
+         * 2. Write other simulation files\r
+         * 3. Build model OR update parameters\r
+         * 4. Run modelica\r
+         * 5. Read results \r
+         */\r
+        return 5; \r
+    }\r
+\r
+\r
+    /* Experiment methods that are not used in this experiment */\r
+\r
+    @Override\r
+    public Lock getDatasourceLock() {\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public Datasource getDatasource() {\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public void simulateDuration(double duration) {\r
+        System.out.println("simulateDuartion");\r
+    }\r
+\r
+\r
+    @Override\r
+    public void rewindTo(double time) {\r
+        System.out.println("rewindTo");\r
+    }\r
+\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultJob.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultJob.java
new file mode 100644 (file)
index 0000000..38a87e6
--- /dev/null
@@ -0,0 +1,126 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4180\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.io.File;\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Class for saving simulation results.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SaveResultJob extends Job {\r
+\r
+    private final MemoryResult sysdynResult;\r
+    private final OldSysdynExperiment experiment;\r
+    private final Session session;\r
+    private IProgressMonitor monitor;\r
+    private File file;\r
+    \r
+    public SaveResultJob(final OldSysdynExperiment experiment, Session session, final MemoryResult result) {\r
+        super("Save Result");\r
+        this.experiment = experiment;\r
+        this.sysdynResult = result;\r
+        this.session = session;\r
+    }\r
+\r
+    @Override\r
+    protected IStatus run(IProgressMonitor monitor) {\r
+        this.monitor = monitor;\r
+        int resultItemsNumber = sysdynResult.numberOfVariables();\r
+        monitor.beginTask("Save result", resultItemsNumber * 2 + 1);        \r
+        try {\r
+            // Create result file\r
+            file = session.syncRequest(new Read<File>() {\r
+\r
+                @Override\r
+                public File perform(ReadGraph graph) throws DatabaseException {\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    Resource model = graph.getSingleObject(experiment.getResource(), l0.PartOf);\r
+                    Resource project = graph.getSingleObject(model, l0.PartOf);\r
+                    String projectName = graph.getPossibleRelatedValue(project, l0.HasName);\r
+                    File root = new File(Platform.getLocation().toOSString(), "www.simantics.org");\r
+                    if(!root.isDirectory()) root.mkdir();\r
+                    File projectRoot = new File(root, projectName);\r
+                    if(!projectRoot.isDirectory()) projectRoot.mkdir();\r
+                    File file = new File(projectRoot, UUID.randomUUID().toString() + ".dbb");\r
+                    return file;\r
+                }\r
+            });\r
+        \r
+            // Start the saving operation\r
+            Thread saveThread = experiment.getSaveThread(sysdynResult, file, SaveResultJob.this.monitor);\r
+            saveThread.run();\r
+                    \r
+            // Add the result under the experiment within the model browser. \r
+            session.syncRequest(new WriteRequest() {\r
+\r
+                @Override\r
+                public void perform(WriteGraph graph) throws DatabaseException {\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    Resource model = graph.getSingleObject(experiment.getResource(), l0.PartOf);\r
+                    String name = NameUtils.findFreshName(graph, "Result", model, l0.ConsistsOf, "%s%d");\r
+        \r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    Resource res = GraphUtils.create2(graph, sr.Result,\r
+                            l0.HasLabel, name,\r
+                            l0.HasName, name,\r
+                            l0.PartOf, model,\r
+                            sr.Result_resultFile, file.getAbsolutePath(),\r
+                            sr.Result_time, System.currentTimeMillis());\r
+                    graph.claim(experiment.getResource(), sr.Experiment_result, res);\r
+                }\r
+            });\r
+\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        } catch (Exception e) {\r
+            e.printStackTrace();\r
+            return new Status(\r
+                    Status.ERROR, \r
+                    "org.simantics.sysdyn.ui", \r
+                    "Save results failed: \n" + e.getMessage());\r
+        } \r
+        monitor.done(); \r
+        return Status.OK_STATUS;\r
+    }\r
+\r
+    @Override\r
+    public boolean belongsTo(Object family) {\r
+        return "SaveResultJob".equals(family);\r
+    }\r
+\r
+    @Override\r
+    protected void canceling() {\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultSetJob.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SaveResultSetJob.java
new file mode 100644 (file)
index 0000000..ea2f9e6
--- /dev/null
@@ -0,0 +1,153 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.io.File;\r
+import java.util.ArrayList;\r
+import java.util.UUID;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.request.WriteResultRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Class for saving simulation result sets.\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SaveResultSetJob extends Job {\r
+\r
+       private final ArrayList<MemoryResult> sysdynResults;\r
+    private final OldSysdynExperiment experiment;\r
+    private final Session session;\r
+    private IProgressMonitor monitor;\r
+    private File file;\r
+\r
+    public SaveResultSetJob(final OldSysdynExperiment experiment, Session session, final ArrayList<MemoryResult> results) {\r
+        super("Save Results");\r
+        this.experiment = experiment;\r
+        this.sysdynResults = results;\r
+        this.session = session;\r
+    }\r
+\r
+    @Override\r
+    protected IStatus run(IProgressMonitor monitor) {\r
+        this.monitor = monitor;\r
+        if (sysdynResults == null || sysdynResults.size() == 0)\r
+            return Status.CANCEL_STATUS;\r
+        int resultItemsNumber = sysdynResults.get(0).numberOfVariables() * sysdynResults.size();\r
+        monitor.beginTask("Save results", resultItemsNumber * 2 + 2);     \r
+        \r
+        try {\r
+               // Create a ResultSet, under which the individual results are stored, and\r
+               // add it under the experiment within the model browser. \r
+\r
+               final Resource resultSetResource = session.syncRequest(new WriteResultRequest<Resource>() {\r
+\r
+                       @Override\r
+                       public Resource perform(WriteGraph graph) throws DatabaseException {\r
+                               Layer0 l0 = Layer0.getInstance(graph);\r
+                               Resource model = graph.getSingleObject(experiment.getResource(), l0.PartOf);\r
+                               String name = NameUtils.findFreshName(graph, "ResultSet", model, l0.ConsistsOf, "%s%d");\r
+\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               Resource res = GraphUtils.create2(graph, sr.ResultSet,\r
+                                               l0.HasLabel, name,\r
+                                               l0.HasName, name,\r
+                                               l0.PartOf, model,\r
+                                               sr.Result_time, System.currentTimeMillis());\r
+                               graph.claim(experiment.getResource(), sr.Experiment_resultSet, res);\r
+                                       return res;\r
+                       }\r
+               });\r
+               monitor.worked(1);\r
+               \r
+               // Save the individual results\r
+               for (int i = 0; i < sysdynResults.size(); ++i) {\r
+                       MemoryResult result = sysdynResults.get(i);\r
+                       final String name = new Integer(i+1).toString();\r
+                       // Create result file\r
+                       file = session.syncRequest(new Read<File>() {\r
+\r
+                               @Override\r
+                               public File perform(ReadGraph graph) throws DatabaseException {\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       Resource model = graph.getSingleObject(experiment.getResource(), l0.PartOf);\r
+                                       Resource project = graph.getSingleObject(model, l0.PartOf);\r
+                                       String projectName = graph.getPossibleRelatedValue(project, l0.HasName);\r
+                                       File root = new File(Platform.getLocation().toOSString(), "www.simantics.org");\r
+                                       if(!root.isDirectory()) root.mkdir();\r
+                                       File projectRoot = new File(root, projectName);\r
+                                       if(!projectRoot.isDirectory()) projectRoot.mkdir();\r
+                                       File file = new File( projectRoot, UUID.randomUUID().toString() + ".dbb");\r
+                                       return file;\r
+                               }\r
+                       });\r
+\r
+                       // Start the saving operation\r
+                       Thread saveThread = experiment.getSaveThread(result, file, SaveResultSetJob.this.monitor);\r
+                       saveThread.run();\r
+\r
+                       // Add the result under the ResultSet within the model browser. \r
+                       session.syncRequest(new WriteRequest() {\r
+\r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+                                       Layer0 l0 = Layer0.getInstance(graph);\r
+                                       String resultSetName = graph.getRelatedValue(resultSetResource, l0.HasName);\r
+                                       \r
+                                       SysdynResource sr = SysdynResource.getInstance(graph);\r
+                                       Resource res = GraphUtils.create2(graph, sr.Result,\r
+                                                       l0.HasLabel, name,\r
+                                                       l0.HasName, resultSetName + "#" + name,\r
+                                                       sr.Result_resultFile, file.getAbsolutePath(),\r
+                                                       sr.Result_time, System.currentTimeMillis());\r
+                                       graph.claim(resultSetResource, sr.Experiment_result, res);\r
+                               }\r
+                       });\r
+\r
+               }\r
+\r
+               } catch (DatabaseException e1) {\r
+                       // TODO Auto-generated catch block\r
+                       e1.printStackTrace();\r
+               }\r
+\r
+        monitor.done(); \r
+        return Status.OK_STATUS;\r
+    }\r
+\r
+    @Override\r
+    public boolean belongsTo(Object family) {\r
+        return "SaveResultSetJob".equals(family);\r
+    }\r
+\r
+    @Override\r
+    protected void canceling() {\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SimulateDurationJob.java
new file mode 100644 (file)
index 0000000..9ff4912
--- /dev/null
@@ -0,0 +1,102 @@
+package org.simantics.sysdyn.manager;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.sysdyn.solver.ISolver;\r
+\r
+class SimulateDurationJob extends Job {\r
+\r
+       private boolean canceled = false;\r
+       private double duration;\r
+       private final SysdynGameExperimentBase base;\r
+       private final ISolver solver;\r
+       \r
+       public SimulateDurationJob(SysdynGameExperimentBase base, String name, double duration) {\r
+               super(name);\r
+               this.base = base;\r
+               this.solver = base.getSolver();\r
+               this.duration = duration;\r
+       }\r
+\r
+       @Override\r
+       protected void canceling() {\r
+               canceled = true;\r
+       }\r
+\r
+       @Override\r
+       protected IStatus run(IProgressMonitor monitor) {\r
+               if(base == null || base.getState() != ExperimentState.STOPPED)\r
+                       return Status.OK_STATUS;\r
+\r
+               long start = System.nanoTime();\r
+               \r
+               base.changeState(ExperimentState.RUNNING);\r
+               int nSteps = (int)(duration / base.stepLength); \r
+               int work = 1 + nSteps * 3 + 2; // initialization + number of steps * number of phases per step + set result + call result listeners \r
+\r
+               monitor.beginTask("Simulating " + duration + " time steps", work);\r
+               monitor.subTask("Initialize step simulation");\r
+\r
+               if(base.subscription == null || base.results == null)\r
+                       return Status.OK_STATUS;\r
+\r
+               if(duration <= 0.0)\r
+                       duration = base.stepDuration;\r
+\r
+\r
+               try {\r
+\r
+                       solver.prepareToStep();\r
+\r
+                       double time = solver.getTime();\r
+                       double eTime = time + duration;\r
+\r
+                       monitor.worked(1);\r
+\r
+                       base.setSubscribedResults(monitor, time);\r
+\r
+                       int stepNumber = 1;\r
+                       while((eTime - time > base.stepLength * 1e-6) && !canceled) {\r
+                               \r
+                               if(eTime - time < base.stepLength)\r
+                                       solver.setStepLength(eTime - time);\r
+\r
+                               monitor.subTask("Simulate step (time = " + time + ")");\r
+                               solver.simulateStep();\r
+                               monitor.worked(1);\r
+\r
+                               time = solver.getTime();\r
+\r
+                               if(stepNumber % base.savePer == 0) {\r
+                                       base.setSubscribedResults(monitor, time);\r
+                               } else {\r
+                                       monitor.worked(1);\r
+                               }\r
+                               stepNumber++;\r
+                               monitor.worked(1);\r
+\r
+                       }\r
+\r
+                       monitor.subTask("Display results");\r
+                       ((MemoryResult)base.getCurrentResult()).setResult(new GameResult(base, base.results, base.subscription));\r
+                       monitor.worked(1);\r
+\r
+                       base.resultsChanged(true);\r
+                       monitor.worked(1);\r
+                       base.changeState(ExperimentState.STOPPED);\r
+\r
+               } catch (Exception e) {\r
+                       e.printStackTrace();\r
+                       System.err.println("SysdynGameExperiment simulateDuration failed: \n\t" + e.getMessage());\r
+               }\r
+               \r
+               long end = System.nanoTime();\r
+               System.err.println("simulate duration took " + 1e-6*(end-start) + "ms.");\r
+\r
+               return Status.OK_STATUS;\r
+               \r
+       }\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynConsole.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynConsole.java
new file mode 100644 (file)
index 0000000..3d20128
--- /dev/null
@@ -0,0 +1,205 @@
+package org.simantics.sysdyn.manager;\r
+\r
+import java.text.SimpleDateFormat;\r
+import java.util.Calendar;\r
+\r
+import org.eclipse.jface.text.BadLocationException;\r
+import org.eclipse.ui.PartInitException;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.console.ConsolePlugin;\r
+import org.eclipse.ui.console.IConsole;\r
+import org.eclipse.ui.console.IConsoleManager;\r
+import org.eclipse.ui.console.IHyperlink;\r
+import org.eclipse.ui.console.IPatternMatchListener;\r
+import org.eclipse.ui.console.MessageConsole;\r
+import org.eclipse.ui.console.MessageConsoleStream;\r
+import org.eclipse.ui.console.PatternMatchEvent;\r
+import org.eclipse.ui.console.TextConsole;\r
+import org.simantics.sysdyn.solver.ISolverMonitor;\r
+\r
+public class SysdynConsole implements ISolverMonitor {\r
+\r
+    private static String SYSDYN_CONSOLE = "Sysdyn modelica console";\r
+    private MessageConsole console;\r
+\r
+    public static SysdynConsole INSTANCE = new SysdynConsole();\r
+    \r
+    public SysdynConsole() {\r
+        ConsolePlugin plugin = ConsolePlugin.getDefault();\r
+        IConsoleManager conMan = plugin.getConsoleManager();\r
+        IConsole[] existing = conMan.getConsoles();\r
+        for (int i = 0; i < existing.length; i++)\r
+            if (existing[i].getName().equals(SYSDYN_CONSOLE))\r
+                console =  (MessageConsole) existing[i];\r
+        if(console == null) {\r
+            MessageConsole myConsole = new MessageConsole(SYSDYN_CONSOLE, null);\r
+            conMan.addConsoles(new IConsole[]{myConsole});\r
+            console = myConsole;\r
+            console.addPatternMatchListener(new IPatternMatchListener() {\r
+\r
+                @Override\r
+                public void matchFound(PatternMatchEvent event) {\r
+                    try {\r
+                        console.addHyperlink(new IssueLink(), event.getOffset(), event.getLength());\r
+                    } catch (BadLocationException e) {\r
+                        e.printStackTrace();\r
+                    }\r
+                }\r
+\r
+                @Override\r
+                public void disconnect() {\r
+                }\r
+\r
+                @Override\r
+                public void connect(TextConsole console) {\r
+                }\r
+\r
+                @Override\r
+                public String getPattern() {\r
+                    \r
+                    return "Issues view";\r
+                }\r
+\r
+                @Override\r
+                public String getLineQualifier() {\r
+                    return null;\r
+                }\r
+\r
+                @Override\r
+                public int getCompilerFlags() {\r
+                    return 0;\r
+                }\r
+            });\r
+            \r
+            /* Link to the modelica document: to be opened to a modelica code viewer.\r
+            console.addPatternMatchListener(new IPatternMatchListener() {\r
+\r
+                @Override\r
+                public void matchFound(PatternMatchEvent event) {\r
+                    try {\r
+                        if(event.getSource() instanceof MessageConsole) {\r
+                            MessageConsole console = (MessageConsole) event.getSource();\r
+                            IDocument document = console.getDocument();\r
+                            String s = document.get(event.getOffset(), event.getLength());\r
+                            s = s.substring(s.indexOf(":") + 1, s.lastIndexOf(":"));\r
+                            String[] split = s.split(":|-");\r
+                            \r
+                            //TODO: Find the modelica document and its locations\r
+                            int startOffset = modelicaDocument.getLineOffset(Integer.parseInt(split[0])) + Integer.parseInt(split[1]);\r
+                            int endOffset = modelicaDocument.getLineOffset(Integer.parseInt(split[2])) + Integer.parseInt(split[3]);\r
+                            System.out.println("Open modelica editor for model at: " + startOffset + ", " + (endOffset - startOffset));\r
+                            \r
+                        }\r
+                        \r
+                        console.addHyperlink(new ModelicaLink(), event.getOffset(), event.getLength());\r
+                    } catch (BadLocationException e) {\r
+                        e.printStackTrace();\r
+                    }\r
+                }\r
+\r
+                @Override\r
+                public void disconnect() {\r
+                }\r
+\r
+                @Override\r
+                public void connect(TextConsole console) {\r
+                }\r
+\r
+                @Override\r
+                public String getPattern() {\r
+                    return "\\[[^\\[]*:[\\d]*:[\\d]*\\-[\\d]*:[\\d]*:writable\\]";\r
+\r
+                }\r
+\r
+                @Override\r
+                public String getLineQualifier() {\r
+                    return null;\r
+                }\r
+\r
+                @Override\r
+                public int getCompilerFlags() {\r
+                    return 0;\r
+                }\r
+            });\r
+            */\r
+\r
+\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void message(String message) {\r
+        message(message, "hh:mm:ss");\r
+    }\r
+\r
+    /**\r
+     * Print message to a console with a specified time stamp format\r
+     * \r
+     * @param message the message to be printed\r
+     * @param timeStampFormat simpledateformat timestamp format. null if no timestamp wanted\r
+     */\r
+    public void message(String message, String timeStampFormat) {\r
+        Calendar cal = Calendar.getInstance();\r
+        SimpleDateFormat sdf = new SimpleDateFormat(timeStampFormat);\r
+        String time = sdf.format(cal.getTime());\r
+\r
+        MessageConsoleStream out = this.console.newMessageStream();\r
+        if(message.length() > 1)\r
+            out.println("[" + time +"] " + message);\r
+\r
+\r
+\r
+        if(message.contains("Error")) {\r
+            showConsole();\r
+            out.println("See Issues view");\r
+        }\r
+    }\r
+\r
+    public void clearConsole() {\r
+        this.console.clearConsole();\r
+    }\r
+\r
+    public void showConsole() {\r
+        ConsolePlugin plugin = ConsolePlugin.getDefault();\r
+        IConsoleManager conMan = plugin.getConsoleManager();\r
+        conMan.showConsoleView(console);\r
+    }\r
+\r
+    class IssueLink implements IHyperlink {\r
+\r
+        @Override\r
+        public void linkEntered() {\r
+        }\r
+\r
+        @Override\r
+        public void linkExited() {\r
+        }\r
+\r
+        @Override\r
+        public void linkActivated() {\r
+            try {\r
+                PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.simantics.issues.ui.issueview2");\r
+            } catch (PartInitException e) {\r
+                e.printStackTrace();\r
+            }            \r
+        }\r
+    }\r
+    \r
+    class ModelicaLink implements IHyperlink {\r
+\r
+        @Override\r
+        public void linkEntered() {\r
+        }\r
+\r
+        @Override\r
+        public void linkExited() {\r
+        }\r
+\r
+        @Override\r
+        public void linkActivated() {\r
+            System.err.println("MODELICA LINK");           \r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynDataSet.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynDataSet.java
new file mode 100644 (file)
index 0000000..a98ad67
--- /dev/null
@@ -0,0 +1,38 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import org.simantics.modelica.data.DataSet;\r
+\r
+/**\r
+ * Extension for the basic Modelica result {@link DataSet} containing also an optional result name.\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynDataSet extends DataSet {\r
+\r
+    public String result; // Name of the result file if this is not the result of the current simulation\r
+       public Integer resultIndex = null;\r
+\r
+    public SysdynDataSet(String name, String result, double[] times, double[] values, Integer resultIndex) {\r
+        super(name, times, values);\r
+        this.result = result;\r
+        this.resultIndex = resultIndex;\r
+    }\r
+    \r
+    public SysdynDataSet(String name, String result, double[] times, double[] values) {\r
+        super(name, times, values);\r
+        this.result = result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java
new file mode 100644 (file)
index 0000000..54f8aa2
--- /dev/null
@@ -0,0 +1,451 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4180\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import gnu.trove.set.hash.THashSet;\r
+\r
+import java.io.File;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.Collection;\r
+import java.util.List;\r
+import java.util.concurrent.locks.Lock;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.RequestProcessor;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.VirtualGraph;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.data.Datasource;\r
+import org.simantics.simulation.experiment.Experiment;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IDynamicExperiment;\r
+import org.simantics.simulation.experiment.IExperimentListener;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.Activator;\r
+import org.simantics.sysdyn.adapter.VariableValueSubscription;\r
+import org.simantics.sysdyn.solver.SysdynSimulationJob;\r
+import org.simantics.sysdyn.solver.SolverSettings;\r
+import org.simantics.sysdyn.solver.SolverSettings.SolverType;\r
+\r
+public class SysdynExperiment extends Experiment implements IDynamicExperiment, VariableSubscriptionManager {\r
+       \r
+       // TODO: change to protected as necessary when oldSysdynExperiment is removed\r
+       \r
+       private Session                                                                 session;\r
+       private Runnable                                                                modificationListener;\r
+       public SysdynModel                                                      sysdynModel;\r
+       private boolean                                                                 toggled = false;\r
+\r
+       @SuppressWarnings("rawtypes")\r
+       private THashSet<VariableValueSubscription> variableValueSubscriptions = new THashSet<VariableValueSubscription>();\r
+       @SuppressWarnings("rawtypes")\r
+       private VariableValueSubscription[] variableValueSubscriptionsSnapshot = null;\r
+\r
+       private Process                                                                 process;\r
+       private boolean                                                                 canceled = false;\r
+       private ExperimentState                       sysdynExperimentState;\r
+\r
+       private SysdynResult                            result;\r
+       \r
+       private String experimentName;\r
+       private File experimentDir;\r
+\r
+       public SysdynExperiment(Resource experiment, Resource model) {\r
+               super(experiment, model);\r
+               this.experimentName = "Experiment";\r
+               this.experimentDir = null;\r
+       }\r
+\r
+       public SysdynResult getCurrentResult() {\r
+               if(this.result == null)\r
+                       this.result = new MemoryResult(null, null);\r
+               return this.result;\r
+       }\r
+       \r
+    public void setCurrentResult(SysdynResult result) {\r
+       this.result = result;\r
+    }\r
+\r
+       public Collection<SysdynResult> getActiveResults() {\r
+               ArrayList<SysdynResult> result = new ArrayList<SysdynResult>();\r
+               if(getCurrentResult() != null)\r
+                       result.add(getCurrentResult());\r
+               result.addAll(sysdynModel.getDisplayedResults());\r
+               return result;\r
+       }\r
+\r
+       /**\r
+        * Initialize this experiment\r
+        * @param g ReadGraph\r
+        */\r
+       public void init(ReadGraph g) {\r
+               try {\r
+                       this.experimentName = NameUtils.getSafeName(g, experiment);\r
+               } catch (DatabaseException e) {\r
+                       this.experimentName = "Experiment";\r
+               }\r
+\r
+               this.session = g.getSession();\r
+               state = ExperimentState.STOPPED;\r
+               for(IExperimentListener listener : listeners.getListeners())\r
+                       listener.stateChanged(state);\r
+\r
+               session.asyncRequest(new ReadRequest() {\r
+\r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+                               sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration);\r
+                               toggleActivation(graph, true);\r
+                       }\r
+               });\r
+\r
+               setSysdynExperimentState(ExperimentState.INITIALIZING);\r
+       }\r
+\r
+       @Override\r
+       public void saveState() {\r
+               if(result == null || !(result instanceof MemoryResult)) \r
+                       return;\r
+               // TODO: fix this\r
+               //SaveResultJob saveResultJob = new SaveResultJob(AltSysdynExperiment.this, session, result);\r
+               //saveResultJob.schedule();\r
+       }\r
+\r
+       protected Thread getSaveThread(final SysdynResult result, final File file, final IProgressMonitor progressMonitor) {\r
+               return new Thread() {\r
+                       @Override\r
+                       public void run() {\r
+                               if(!canceled) {\r
+                                       // Get and store results\r                                       result.saveToFile(file, progressMonitor);\r
+                               }\r                      }\r
+               };\r
+       }\r
+\r
+       @Override\r
+       public void simulate(boolean enabled) {\r
+               // TODO: add state checks\r
+               if (enabled) {\r
+                       SysdynSimulationJob job = new SysdynSimulationJob(sysdynModel.getConfiguration().getLabel(), this);\r
+                       job.schedule();\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Destroy an ongoing simulation process\r
+        */\r
+       public void cancelSimulation() {\r
+               canceled = true;\r
+               if(process != null) {\r
+                       process.destroy();\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Toggle simulation state\r
+        * @param enabled true == RUNNING, false == STOPPED\r
+        */\r
+       public void toggleSimulation(boolean enabled) {\r
+               if(enabled) {\r
+                       this.toggled = true;\r
+                       changeState(ExperimentState.RUNNING);\r
+                       if(modificationListener == null) {\r
+\r
+                               modificationListener = new Runnable() {\r
+\r
+                                       @Override\r
+                                       public void run() {\r
+                                               session.asyncRequest(new ReadRequest() {\r
+\r
+                                                       @Override\r
+                                                       public void run(ReadGraph graph) throws DatabaseException {\r
+                                                               if(getState() == ExperimentState.RUNNING) {\r
+                                                                       // TODO: fix this\r
+                                                                       //SimulationScheduler.start(sysdynModel, this);\r
+                                                               }\r
+\r
+                                                       }\r
+                                               });\r
+\r
+                                       };\r
+                               };\r
+                               sysdynModel.addModificationListener(modificationListener);\r
+                       }\r
+               }\r
+               else {\r
+                       changeState(ExperimentState.STOPPED);\r
+                       this.toggled = false;\r
+               }\r
+\r
+       }\r
+\r
+       @Override\r
+       public void refresh(RequestProcessor session) {\r
+               session.asyncRequest(new ReadRequest() {\r
+\r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               init(graph);\r
+                       }\r
+\r
+               });\r
+       }\r
+\r
+       @Override\r
+       public void refresh(Session session) {\r
+               refresh((RequestProcessor)session);\r
+       }\r
+\r
+       @Override\r
+       protected void localStateChange() {\r
+               setSysdynExperimentState(getState());\r
+               switch(state) {\r
+               case DISPOSED:\r
+                       onExperimentDisposed();\r
+                       break;\r
+               default:\r
+                       break;\r
+               }\r
+\r
+       }\r
+\r
+       /**\r
+        * Returns sysdyn experiment state. It is usually the same as ordinary experiment state.\r
+        * Initializing phase takes longer than normally in game experiments.\r
+        * @return\r
+        */\r
+       public ExperimentState getSysdynExperimentState() {\r
+               return sysdynExperimentState;\r
+       }\r
+\r
+       protected void setSysdynExperimentState(final ExperimentState state) {\r
+               sysdynExperimentState = state;\r
+               session.asyncRequest(new ReadRequest() {\r
+\r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
+                               final Session session = graph.getSession();\r
+                               session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               Layer0 L0 = Layer0.getInstance(graph);\r
+                                               SimulationResource SR = SimulationResource.getInstance(graph);\r
+                                               graph.deny(model, SR.HasExperimentState);\r
+                                               graph.deny(experiment, SR.HasExperimentState);\r
+\r
+                                               Resource st = graph.newResource();\r
+                                               switch(state) {\r
+                                               case INITIALIZING:\r
+                                                       graph.claim(st, L0.InstanceOf, SR.ExperimentState_Initializing);\r
+                                                       break;\r
+                                               case RUNNING:\r
+                                                       graph.claim(st, L0.InstanceOf, SR.ExperimentState_Running);\r
+                                                       break;\r
+                                               case STOPPED:\r
+                                                       graph.claim(st, L0.InstanceOf, SR.ExperimentState_Stopped);\r
+                                                       break;\r
+                                               case DISPOSED:\r
+                                                       graph.claim(st, L0.InstanceOf, SR.ExperimentState_Disposed);\r
+                                                       break;\r
+                                               }\r
+\r
+                                               graph.claim(model, SR.HasExperimentState, st);\r
+                                               graph.claim(experiment, SR.HasExperimentState, st);\r
+                                       }});\r
+                       }\r
+               });\r
+       }\r
+\r
+       /**\r
+        * Actions performed when experiment is disposed\r
+        * @param graph\r
+        */\r
+       protected void onExperimentDisposed() {\r
+               cancelSimulation();\r
+               sysdynModel.removeModificationListener(modificationListener);\r
+               modificationListener = null;\r
+\r
+               session.asyncRequest(new ReadRequest() {\r
+                       @Override\r
+                       public void run(ReadGraph graph) throws DatabaseException {\r
+                               toggleActivation(graph, false);\r
+                       }\r
+               });\r
+       }\r
+\r
+\r
+       /**\r
+        * Toggles the active-state of this experiment on or off\r
+        * @param graph ReadGraph\r
+        * @param activate The active-state of this experiment\r
+        */\r
+       protected void toggleActivation(ReadGraph graph, final boolean activate) {\r
+               // TODO: does not work correctly, the experiment can appear inactive even when it is actually active\r
+               VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
+               final Session session = graph.getSession();\r
+               session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {\r
+                       @Override\r
+                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                               VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
+\r
+                               session.asyncRequest(new WriteRequest(runtime) {\r
+\r
+                                       @Override\r
+                                       public void perform(WriteGraph graph) throws DatabaseException {\r
+                                               SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+                                               if(activate)\r
+                                                       graph.claim(experiment, SIMU.IsActive, experiment);\r
+                                               else\r
+                                                       graph.denyStatement(experiment, SIMU.IsActive, experiment);\r
+                                       }\r
+\r
+                               });\r
+                       }\r
+               });\r
+       }\r
+\r
+\r
+       /* Result subscriptions */\r
+\r
+       @SuppressWarnings("rawtypes")\r
+       /**\r
+        * Copy from AprosExperiment\r
+        * @param subscription\r
+        */\r
+       @Override\r
+       public void addVariableValueSubscription(VariableValueSubscription subscription) {\r
+               assert subscription != null;\r
+               synchronized (variableValueSubscriptions) {\r
+                       variableValueSubscriptions.add(subscription);\r
+                       variableValueSubscriptionsSnapshot = null;\r
+               }\r
+       }\r
+\r
+       @SuppressWarnings("rawtypes")\r
+       /**\r
+        * Copy from AprosExperiment\r
+        * @param subscription\r
+        */\r
+       @Override\r
+       public void removeVariableValueSubscription(VariableValueSubscription subscription) {\r
+               assert subscription != null;\r
+               synchronized (variableValueSubscriptions) {\r
+                       variableValueSubscriptions.remove(subscription);\r
+                       variableValueSubscriptionsSnapshot = null;\r
+               }\r
+       }\r
+\r
+       @SuppressWarnings("rawtypes")\r
+       /**\r
+        * Copy from AprosExperiment\r
+        * @return\r
+        */\r
+       @Override\r
+       public VariableValueSubscription[] getListenerSnapshot() {\r
+               VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot;\r
+               if (snapshot == null) {\r
+                       synchronized (variableValueSubscriptions) {\r
+                               snapshot = variableValueSubscriptionsSnapshot;\r
+                               if (snapshot == null) {\r
+                                       snapshot = variableValueSubscriptionsSnapshot = \r
+                                                       variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]);\r
+                               }\r
+                       }\r
+               }\r
+               return snapshot;\r
+       }\r
+\r
+       volatile long previousVariableUpdateTime = 0;\r
+\r
+       /**\r
+        * Modified copy from AprosExperiment\r
+        */\r
+       public void resultsChanged() {\r
+               long time = System.nanoTime();\r
+               if (time - previousVariableUpdateTime > 10000000) {\r
+                       updateSubscriptions();\r
+                       previousVariableUpdateTime = time;\r
+               }\r
+       }\r
+\r
+       @SuppressWarnings("rawtypes")\r
+       /**\r
+        * Modified copy from AporsExperiment\r
+        */\r
+       @Override\r
+       public void updateSubscriptions() {\r
+               for(VariableValueSubscription subscription : getListenerSnapshot())\r
+                       subscription.update();\r
+       }\r
+\r
+       /* Experiment methods that are not used in this experiment */\r
+\r
+       @Override\r
+       public Lock getDatasourceLock() {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+\r
+       @Override\r
+       public Datasource getDatasource() {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+\r
+       @Override\r
+       public void simulateDuration(double duration) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+\r
+       @Override\r
+       public void rewindTo(double time) {\r
+               throw new UnsupportedOperationException();\r
+       }\r
+       \r
+       \r
+       \r
+       // TODO: clean this up a bit maybe?\r
+       public File getExperimentDir() {\r
+               if (experimentDir == null) {\r
+            File modelsDir = Activator.getBundleContext().getDataFile("models");\r
+            String name = experimentName;\r
+            List<String> files = Arrays.asList(modelsDir.list());\r
+            if (files.contains(name)) {\r
+                int i = 2;\r
+                while (files.contains(name + "_" + i)){\r
+                    i++;\r
+                }\r
+                name += "_" + i;\r
+            }\r
+            experimentDir = new File(modelsDir, name);\r
+            experimentDir.mkdir();\r
+        }\r
+               \r
+        return experimentDir;\r
+       }\r
+       \r
+       public SolverType getSolverType() {\r
+               // should be defined in experiment properties (similarly to other experiment types)\r
+               return SolverSettings.getSelectedSolverType();\r
+       }\r
+\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiments.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiments.java
new file mode 100644 (file)
index 0000000..78d7902
--- /dev/null
@@ -0,0 +1,275 @@
+package org.simantics.sysdyn.manager;\r
+\r
+import java.util.Collection;\r
+import java.util.concurrent.Semaphore;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.NullProgressMonitor;\r
+import org.eclipse.core.runtime.SubMonitor;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.Layer0Utils;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.layer0.variable.RVI;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.PartialIC;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.experiment.IDynamicExperiment;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.model.ExperimentLoadingFailed;\r
+import org.simantics.simulation.project.IExperimentActivationListener;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.utils.DataContainer;\r
+\r
+public class SysdynExperiments {\r
+\r
+    public static String activateExperiment(IProgressMonitor monitor, final IProject project, final IExperimentManager manager, final Resource experimentResource) {\r
+       \r
+       if(monitor == null) monitor = new NullProgressMonitor();\r
+       \r
+        final SubMonitor mon = SubMonitor.convert(monitor, "Activating experiment", 100000);\r
+\r
+//        SysdynExperimentManagerListener.listenManager(manager);\r
+        IExperiment[] experiments = manager.getExperiments();\r
+        SubMonitor shutdownMon = mon.newChild(10000);\r
+        int workPerExperiment;\r
+        if (experiments.length > 0)\r
+               workPerExperiment = 10000 / experiments.length;\r
+        else\r
+               workPerExperiment = 10000;\r
+        for(IExperiment e : experiments)\r
+            if(e.getState() != ExperimentState.DISPOSED)\r
+                e.shutdown(shutdownMon.newChild(workPerExperiment));\r
+        mon.setWorkRemaining(90000);\r
+\r
+        final Semaphore activated = new Semaphore(0);\r
+        final DataContainer<Throwable> problem = new DataContainer<Throwable>();\r
+        final DataContainer<IExperiment> run = new DataContainer<IExperiment>();\r
+        manager.startExperiment(experimentResource, new IExperimentActivationListener() {\r
+\r
+            @Override\r
+            public void onExperimentActivated(final IExperiment experiment) {\r
+//                MessageService.defaultLog(new org.eclipse.core.runtime.Status(IStatus.INFO, "org.simantics.simulation.ui", 0, "Activated experiment " + experiment.getIdentifier() , null));\r
+                activated.release();\r
+                run.set(experiment);\r
+            }\r
+            @Override\r
+            public void onFailure(Throwable e) {\r
+                problem.set(e);\r
+                activated.release();\r
+            }\r
+            @Override\r
+            public void onMessage(IStatus message) {\r
+//                MessageService.getDefault().log(message);\r
+            }\r
+            @Override\r
+            public IProgressMonitor getProgressMonitor() {\r
+                return mon;\r
+            }\r
+        }, true);\r
+        try {\r
+            activated.acquire();\r
+            Throwable t = problem.get();\r
+            if (t != null) {\r
+                if (t instanceof ExperimentLoadingFailed) {\r
+//                    ErrorLogger.defaultLogError(t);\r
+//                    ShowMessage.showError("Experiment Activation Failed", t.getMessage());\r
+                } else {\r
+//                    ExceptionUtils.logAndShowError(t);\r
+                }\r
+            }\r
+\r
+            return run.get().getIdentifier();\r
+            //return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Experiment activation failed, see exception for details.", problem.get());\r
+        } catch (InterruptedException e) {\r
+            return null;\r
+        }\r
+    }\r
+       \r
+    \r
+    public static String activateExperiment(Resource experiment) throws DatabaseException {\r
+\r
+//     Resource experiment = Layer0Utils.getPossibleChild(graph, model, name);\r
+//     if( experiment == null) return false;\r
+\r
+//     SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+//        if (!graph.isInstanceOf(experiment, SIMU.Experiment)) return false;\r
+        \r
+        final IProject project = Simantics.getProject();\r
+        if (project == null) return null;\r
\r
+        final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        if(experimentManager == null) return null;\r
+        \r
+       return SysdynExperiments.activateExperiment(null, project, experimentManager, experiment);\r
+               \r
+       }\r
+    \r
+    public static void run(String experimentId) throws DatabaseException {\r
+\r
+        final IProject project = Simantics.getProject();\r
+        if (project == null) return;\r
\r
+        final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        if(experimentManager == null) return;\r
+        \r
+        IExperiment experiment = experimentManager.getExperiment(experimentId);\r
+        if(experiment instanceof IDynamicExperiment)\r
+               ((IDynamicExperiment)experiment).simulate(true);\r
+        \r
+    }\r
+\r
+       private static void processChild(ReadGraph graph, Variable child, PartialIC IC) throws DatabaseException {\r
+               \r
+               System.err.println("processChild " + child.getURI(graph));\r
+               \r
+               for(Variable c : child.getChildren(graph)) {\r
+                       processChild(graph, c, IC);\r
+               }\r
+               Variable values = child.getPossibleProperty(graph, "values");\r
+               if(values == null) return;\r
+                       \r
+               Resource represents = child.getPossibleRepresents(graph);\r
+               if(represents == null) return;\r
+                       \r
+               Layer0 L0 = Layer0.getInstance(graph);\r
+               SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+               \r
+               Collection<Resource> exprs = graph.syncRequest(new ObjectsWithType(represents, L0.ConsistsOf, SYSDYN.ParameterExpression));\r
+               if(exprs.size() == 0) return;\r
+                       \r
+               Variable v = values.getPossibleProperty(graph, "");\r
+               if(v == null) return;\r
+               double[][] vs = v.getValue(graph);\r
+               Variable value = child.getPossibleProperty(graph, "value");\r
+               if(value == null) return;\r
+               for(int i=0;i<vs.length;i++) {\r
+                       double[] ds = vs[i];\r
+                       if(ds == null) continue;\r
+                       Variable target = value.getPossibleProperty(graph, "$" + i);\r
+                       if(target != null && ds.length > 0) {\r
+                               RVI rvi = target.getRVI(graph);\r
+                               double initial = ds[0];\r
+                               System.err.println("rvi=" + rvi + " value=" + initial);\r
+                               IC.add(rvi, Variant.ofInstance(initial));\r
+                       }\r
+               }\r
+       }\r
+\r
+    public static Resource saveIC(WriteGraph graph, Variable input, String name) throws DatabaseException {\r
+       \r
+               Resource model = Variables.getModel(graph, input);\r
+       Resource child = Layer0Utils.getPossibleChild(graph, model, name);\r
+       SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+       \r
+       if(child != null) {\r
+               if(graph.isInstanceOf(child, SYSDYN.InitialCondition)) {\r
+                       RemoverUtil.remove(graph, child);\r
+               } else {\r
+                       return null;\r
+               }\r
+       }\r
+       \r
+               PartialIC IC = new PartialIC();\r
+               processChild(graph, input, IC);\r
+\r
+               Layer0 L0 = Layer0.getInstance(graph);\r
+               ModelingResources MOD = ModelingResources.getInstance(graph);\r
+               Resource ic = graph.newResource();\r
+               graph.claim(ic, L0.InstanceOf, SYSDYN.InitialCondition);\r
+               graph.addLiteral(ic, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);\r
+               graph.addLiteral(ic, SYSDYN.InitialCondition_HasInitialValues, SYSDYN.InitialCondition_HasInitialValues_Inverse, MOD.PartialIC, IC, PartialIC.BINDING);\r
+               graph.claim(model, L0.ConsistsOf, ic);\r
+               \r
+               return ic;\r
+       \r
+    }\r
+\r
+    public static void assignIC(WriteGraph graph, Variable experiment, String name) throws DatabaseException {\r
+\r
+       System.err.println("assignIC " + experiment.getURI(graph));\r
+\r
+               Layer0 L0 = Layer0.getInstance(graph);\r
+               SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+\r
+       Resource run = experiment.getPossibleRepresents(graph);\r
+       if(run == null) return;\r
+       Resource exp = graph.getPossibleObject(run, L0.PartOf);\r
+       if(exp == null) return;\r
+\r
+       Resource model = Variables.getModel(graph, experiment);\r
+       Resource ic = Layer0Utils.getPossibleChild(graph, model, name);\r
+       if(ic == null) return;\r
+       \r
+       if(!graph.isInstanceOf(ic, SYSDYN.InitialCondition)) return;\r
+       \r
+               graph.deny(exp, SYSDYN.Experiment_ic);\r
+               graph.claim(exp, SYSDYN.Experiment_ic, ic);\r
+       \r
+    }\r
+    \r
+    public static void deassignIC(WriteGraph graph, Variable experiment) throws DatabaseException {\r
+\r
+       System.err.println("deassignIC " + experiment.getURI(graph));\r
+\r
+               Layer0 L0 = Layer0.getInstance(graph);\r
+               SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+\r
+       Resource run = experiment.getPossibleRepresents(graph);\r
+       if(run == null) return;\r
+       Resource exp = graph.getPossibleObject(run, L0.PartOf);\r
+       if(exp == null) return;\r
+       \r
+               graph.deny(exp, SYSDYN.Experiment_ic);\r
+       \r
+    }\r
+\r
+    public static void applyIC(WriteGraph graph, Variable experiment, String name) throws DatabaseException {\r
+\r
+       System.err.println("applyIC " + experiment.getURI(graph));\r
+\r
+               Layer0 L0 = Layer0.getInstance(graph);\r
+               SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+\r
+       Resource run = experiment.getPossibleRepresents(graph);\r
+       if(run == null) return;\r
+       Resource exp = graph.getPossibleObject(run, L0.PartOf);\r
+       if(exp == null) return;\r
+\r
+       Resource model = Variables.getModel(graph, experiment);\r
+       Resource ic = Layer0Utils.getPossibleChild(graph, model, name);\r
+       if(ic == null) return;\r
+       \r
+       if(!graph.isInstanceOf(ic, SYSDYN.InitialCondition)) return;\r
+       \r
+               Variable base = Variables.getVariable(graph, run);\r
+               \r
+               PartialIC data = graph.getPossibleRelatedValue(ic, SYSDYN.InitialCondition_HasInitialValues, PartialIC.BINDING);\r
+               data.apply(graph, base);\r
+       \r
+    }\r
+    \r
+    public static void deleteIC(WriteGraph graph, Variable input, String name) throws DatabaseException {\r
+\r
+       Resource model = Variables.getModel(graph, input);\r
+       Resource child = Layer0Utils.getPossibleChild(graph, model, name);\r
+       SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+\r
+       if((child != null) && graph.isInstanceOf(child, SYSDYN.InitialCondition))\r
+               RemoverUtil.remove(graph, child);\r
+       \r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperiment.java
new file mode 100644 (file)
index 0000000..6d8d4a9
--- /dev/null
@@ -0,0 +1,415 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import gnu.trove.list.array.TDoubleArrayList;\r
+import gnu.trove.map.hash.THashMap;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.lang.reflect.Field;\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.NullProgressMonitor;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.Layer0Utils;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.fmu.FMUControlJNI;\r
+import org.simantics.fmu.FMUJNIException;\r
+import org.simantics.modelica.IModelicaMonitor;\r
+import org.simantics.modelica.ModelicaManager;\r
+import org.simantics.modelica.SimulationLocation;\r
+import org.simantics.modeling.PartialIC;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.simulation.SimulationJob.HeadlessModelicaMonitor;\r
+import org.simantics.sysdyn.solver.ISolver;\r
+import org.simantics.sysdyn.solver.ModelicaSolver;\r
+\r
+/**\r
+ * Game experiment\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynGameExperiment extends SysdynGameExperimentBase {\r
+\r
+       private ModelicaSolver solver;\r
+       public FMUControlJNI control;\r
+       private boolean loaded = false;\r
+       \r
+       private static boolean fortranLibrariesLoaded = false;\r
+       \r
+       public SysdynGameExperiment(Resource experiment, Resource model) {\r
+               super(experiment, model);\r
+               this.solver = new ModelicaSolver(this);\r
+       }\r
+       \r
+       public FMUControlJNI getFMUControl() {\r
+               return control;\r
+       }\r
+       \r
+       @Override\r
+       public void init(ReadGraph g) {\r
+               super.init(g);\r
+\r
+               if(control == null)\r
+                       control = new FMUControlJNI();\r
+               \r
+               results = new THashMap<String, TDoubleArrayList>();\r
+               \r
+       }\r
+       \r
+       @Override\r
+       protected void onExperimentDisposed() {\r
+               super.onExperimentDisposed();\r
+               if(control!=null) {\r
+                       try {\r
+                               control.unloadFMU();\r
+                               loaded = false;\r
+                       } catch (FMUJNIException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+               }\r
+       }\r
+\r
+       private boolean isValidFMU(File file) {\r
+               if(!file.exists()) return false;\r
+               if(!file.isFile()) return false;\r
+               if(file.length() == 0) return false;\r
+               return true;\r
+       }\r
+       \r
+\r
+       @Override\r
+       public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException {\r
+               canceled = false;\r
+\r
+               progressMonitor.subTask("Write modelica classes");\r
+\r
+               // Write Modelica files       \r
+               String modelText = getModelicaCode(monitor, true, getOpenModelicaVersion());\r
+               if(modelText == null)\r
+                       return;\r
+               \r
+        omcVersion = ModelicaManager.getDefaultOMVersion();\r
+        \r
+        monitor.message("Simulate " + modelName + " using OpenModelica " + omcVersion);\r
+        \r
+               progressMonitor.worked(1);\r
+\r
+               // Write initial files and add init-parameters\r
+               progressMonitor.subTask("Write simulation files");\r
+               HashMap<String, String> inits = getExperimentParameters(monitor);\r
+\r
+\r
+               // add loadFile script to load all related functions and function libraries \r
+               String additionalScript = getAdditionalScripts();\r
+\r
+               // Create simulation files\r
+               SimulationLocation simulationLocation = createSimulationFiles(sysdynModel, modelText, inits, additionalScript, true);\r
+               progressMonitor.worked(1);\r
+\r
+               // Load precompiled fmu if structure has not changed and it has not yet been loaded\r
+               File fmu = null;\r
+               if(!sysdynModel.isStructureModified()) {\r
+                   if(!simulationLocation.executableFile.isFile()) {\r
+                       fmu = loadModelFmu(simulationLocation);\r
+                   } else {\r
+                       fmu = simulationLocation.executableFile;\r
+                   }\r
+               }\r
+               // Build the model and store previous model structure and inits that affect the building\r
+               // If there is no exe file OR the model structure has not changed, no need to build\r
+               if (fmu == null && (!isValidFMU(simulationLocation.executableFile) || sysdynModel.isStructureModified())) {\r
+                       progressMonitor.subTask("Build model");\r
+                       buildModel(simulationLocation, monitor);\r
+                       previousModelStructure = modelText;\r
+                       \r
+                       saveModelFmu(simulationLocation);\r
+               }\r
+\r
+               progressMonitor.worked(1);\r
+\r
+               if(simulationLocation != null && !canceled) {\r
+                       // Load fmu and initialize it for simulation\r
+                       try {\r
+                               if (false && !fortranLibrariesLoaded) { // Enable this when we update from OpenModelica 1.9.0beta4!\r
+                                       File omDir = ModelicaManager.getOMHome();\r
+                                       File mingw = new File(omDir, "MinGW");\r
+                                       File mbin = new File(mingw, "bin");\r
+                                       \r
+                                       // Add MinGW path to java.library.path. This is a bit of a hack because \r
+                                       // java.library.path isn't intended to be set programmatically.\r
+                                       String newLibPath = System.getProperty("java.library.path") + File.pathSeparator + mbin.getAbsolutePath();\r
+                                       System.setProperty("java.library.path", newLibPath);\r
+                                       Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");\r
+                                       fieldSysPath.setAccessible(true);\r
+                                       if (fieldSysPath != null) {\r
+                                               fieldSysPath.set(System.class.getClassLoader(), null);\r
+                                       }\r
+                                       \r
+                                       System.loadLibrary("libgfortran-3");\r
+                                       System.out.println("Loaded libgfortran-3.dll");\r
+                                       System.loadLibrary("pthreadGC2");\r
+                                       System.out.println("Loaded pthreadGC2.dll");\r
+                                       fortranLibrariesLoaded = true;\r
+                               }\r
+                \r
+                               control.loadFMUFile(simulationLocation.executableFile.getAbsolutePath()); // unzip and load fmu\r
+                               loaded = true;\r
+                               instantiate();\r
+                               \r
+                       } catch (FMUJNIException e) {\r
+                               System.err.println("SysdynGameExperiment initialization failed:\n\t" + e.getMessage());\r
+                       } catch (SecurityException e) {\r
+                               // TODO Auto-generated catch block\r
+                               e.printStackTrace();\r
+                       } catch (NoSuchFieldException e) {\r
+                               // TODO Auto-generated catch block\r
+                               e.printStackTrace();\r
+                       } catch (IllegalArgumentException e) {\r
+                               // TODO Auto-generated catch block\r
+                               e.printStackTrace();\r
+                       } catch (IllegalAccessException e) {\r
+                               // TODO Auto-generated catch block\r
+                               e.printStackTrace();\r
+                       }\r
+\r
+               }\r
+               process = null;\r
+               simulate(false); \r
+       }\r
+\r
+       /**\r
+        * Load fmu file from database, if it exists for the model of this experiment\r
+        * \r
+        * @param simulationLocation SimulationLocation indicating where the fmu should be loaded\r
+        * @return Loaded fmu or null if it was not loaded from database\r
+        */\r
+       private File loadModelFmu(SimulationLocation simulationLocation) {\r
+           File fmu = null;\r
+           try {\r
+               final String fmuLocation = simulationLocation.executableFile.getAbsolutePath();\r
+            fmu = session.syncRequest(new Read<File>() {\r
+                @Override\r
+                public File perform(ReadGraph graph) throws DatabaseException {\r
+                    File result = null;\r
+                    FileOutputStream fos;\r
+                    try {\r
+                        fos = new FileOutputStream(fmuLocation);\r
+                        byte[] fileBArray = graph.getPossibleRelatedValue(\r
+                                getModel(), SysdynResource.getInstance(graph).SysdynModel_fmuFile, Bindings.BYTE_ARRAY);\r
+                        \r
+                        if(fileBArray != null) {\r
+                            fos.write(fileBArray);\r
+                            fos.close();\r
+                            result = new File(fmuLocation);\r
+                        } else {\r
+                            fos.close();\r
+                            return null;\r
+                        }\r
+                        \r
+                    } catch (FileNotFoundException e) {\r
+                        e.printStackTrace();\r
+                    } catch (IOException e) {\r
+                        e.printStackTrace();\r
+                    }\r
+                    return result;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+           \r
+           return fmu;\r
+       }\r
+       \r
+       /**\r
+        * Save fmu file from simulationLocation to database\r
+        * @param simulationLocation Location for finding fmu\r
+        */\r
+       private void saveModelFmu(SimulationLocation simulationLocation) {\r
+           final String fmuLocation = simulationLocation.executableFile.getAbsolutePath();\r
+           session.asyncRequest(new WriteRequest() {\r
+\r
+               @Override\r
+               public void perform(WriteGraph graph) throws DatabaseException {\r
+                   File file = new File(fmuLocation);\r
+                   byte[] fileBArray = new byte[(int)file.length()];\r
+                   FileInputStream fis;\r
+                   try {\r
+                       fis = new FileInputStream(file);\r
+\r
+                       fis.read(fileBArray);\r
+                       graph.claimLiteral(\r
+                               getModel(), \r
+                               SysdynResource.getInstance(graph).SysdynModel_fmuFile, \r
+                               fileBArray, Bindings.BYTE_ARRAY);\r
+                       fis.close();\r
+                   } catch (FileNotFoundException e) {\r
+                       e.printStackTrace();\r
+                   } catch (IOException e) {\r
+                       e.printStackTrace();\r
+                   }\r
+            }\r
+        });\r
+       }\r
+\r
+\r
+       @Override\r
+    public void rewindTo(double time) {\r
+       \r
+        if(control == null)\r
+            return;\r
+        \r
+        if(time >-0.001 && time < 0.001) {\r
+               try {\r
+                               simulate(new HeadlessModelicaMonitor(), new NullProgressMonitor(), sysdynModel.getConfiguration().getLabel());\r
+                   //instantiate();\r
+                       } catch (IOException e) {\r
+                               Logger.defaultLogError(e);\r
+                       }\r
+        } else {\r
+            System.out.println("rewindTo");\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public void refresh(Session session) {\r
+        try {\r
+            control.initializeSimulation();\r
+            clearResults();\r
+            //getInitialResultValues();\r
+            \r
+        } catch (FMUJNIException e) {\r
+            System.err.println("SysdynGameExperiment instantiate failed: " + e.getMessage());\r
+        }\r
+    }\r
+    \r
+    private synchronized void instantiate() {\r
+        try {\r
+            HashMap<String, String> inits = getExperimentParameters(null);\r
+\r
+            control.setStepLength(stepLength); // FIXME: fixed step lenghth\r
+            control.setTime(startTime);\r
+            control.instantiateSimulation(); // instantiate simulation\r
+\r
+            if(!control.isInitialized()) {\r
+                       control.initializeSimulation();\r
+                   }\r
+\r
+            if(inits.get("variableFilter") == null || inits.get("variableFilter").equals(".*"))\r
+                subscription = control.getAllVariables();\r
+            else\r
+                subscription = control.filterVariables(inits.get("variableFilter"));\r
+            \r
+            // Initialize subscription indexes map for fast result reading in getValue()\r
+            if(subscriptionIndexes == null)\r
+                subscriptionIndexes = new HashMap<String, Integer>();\r
+            \r
+            subscriptionIndexes.clear();\r
+            for(int i = 0; i < subscription.length; i++) {\r
+                subscriptionIndexes.put(subscription[i], i);\r
+            }\r
+\r
+            // Initialize container for current simulation results\r
+            currentValues = new double[subscription.length];\r
+            \r
+            // subscribe all variables\r
+            control.subscribe(subscription); \r
+\r
+            clearResults();\r
+            //getInitialResultValues();\r
+            \r
+                       Simantics.getSession().syncRequest(new WriteRequest() {\r
+\r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+\r
+                                       Resource run = Layer0Utils.getPossibleChild(graph, SysdynGameExperiment.this.experiment, getIdentifier());\r
+                                       if(run == null) {\r
+                                               System.err.println("No run");\r
+                                               return;\r
+                                       }\r
+                                       \r
+                                       Variable base = Variables.getVariable(graph, run);\r
+                                       \r
+                                       SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+                                       \r
+                                       Resource ic = graph.getPossibleObject(SysdynGameExperiment.this.experiment, SYSDYN.Experiment_ic);\r
+                                       if(ic == null) return;\r
+                                       \r
+                                       PartialIC data = graph.getPossibleRelatedValue(ic, SYSDYN.InitialCondition_HasInitialValues, PartialIC.BINDING);\r
+                                       data.apply(graph, base);\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+            \r
+        } catch (FMUJNIException e) {\r
+            System.err.println("SysdynGameExperiment instantiate failed: " + e.getMessage());\r
+        } catch (DatabaseException e) {\r
+            System.err.println("SysdynGameExperiment instantiate failed: " + e.getMessage());\r
+               }\r
+    }\r
+\r
+//    private synchronized void getInitialResultValues() {\r
+//        try {\r
+//            // Initialize results\r
+//            results.clear();\r
+//\r
+//            currentValues = control.getSubscribedResults(currentValues);\r
+//            for(int k = 0; k < subscription.length; k++) {\r
+//                results.put(subscription[k], new ArrayList<Double>());\r
+//                results.get(subscription[k]).add(currentValues[k]);\r
+//            }\r
+//\r
+//            ((MemoryResult)getCurrentResult()).setResult(new GameResult(this.results, this.subscription));\r
+//            resultsChanged();  \r
+//        } catch (FMUJNIException e) {\r
+//            System.err.println("SysdynGameExperiment getInitialResultValues failed: " + e.getMessage());\r
+//        }\r
+//    }\r
+    \r
+    @Override\r
+    public void updateSubscriptions() {\r
+       \r
+       if(!loaded) return;\r
+       \r
+        try {\r
+            if(control.isInitialized())\r
+                currentValues = control.getSubscribedResults(currentValues);\r
+        } catch (FMUJNIException e) {\r
+            e.printStackTrace();\r
+        }\r
+        super.updateSubscriptions();\r
+    }\r
+\r
+       @Override\r
+       public ISolver getSolver() {\r
+               return solver;\r
+       }\r
+    \r
+ }\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentBase.java
new file mode 100644 (file)
index 0000000..421e75d
--- /dev/null
@@ -0,0 +1,198 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import gnu.trove.list.array.TDoubleArrayList;\r
+import gnu.trove.map.hash.THashMap;\r
+\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.procedure.AsyncListener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.fmu.FMUJNIException;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.solver.ISolver;\r
+import org.simantics.utils.datastructures.Quad;\r
+\r
+/**\r
+ * Game experiment\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+abstract public class SysdynGameExperimentBase extends OldSysdynExperiment {\r
+\r
+       public double stepLength = DEFAULT_STEP_LENGTH;\r
+       public double startTime = DEFAULT_START_TIME;\r
+       protected double stepDuration = DEFAULT_STEP_DURATION;\r
+       protected int savePer = 1;\r
+\r
+       protected HashMap<String, Integer> subscriptionIndexes;\r
+       protected double[] currentValues; // Current values from FMU. Updated with updateSubscriptions\r
+       \r
+       THashMap<String, TDoubleArrayList> results;\r
+\r
+       protected String[] subscription;\r
+       \r
+       public static double DEFAULT_STEP_DURATION = 1.0;\r
+       public static double DEFAULT_STEP_LENGTH        = 0.1;\r
+       public static double DEFAULT_START_TIME         = 0.0;\r
+       public static int DEFAULT_OUTPUT_INTERVAL       = 1;\r
+       \r
+       public SysdynGameExperimentBase(Resource experiment, Resource model) {\r
+               super(experiment, model);\r
+       }\r
+\r
+       public double getStepDuration() {\r
+               return stepDuration;\r
+       }\r
+       \r
+       public void setStepDuration(double duration) {\r
+               this.stepDuration = duration;\r
+       }\r
+       \r
+       public double getStepLength() {\r
+               return stepLength;\r
+       }\r
+       \r
+       public void setStepLength(double stepLength) {\r
+               this.stepLength = stepLength;\r
+       }\r
+       \r
+       public void setStartTime(double startTime) {\r
+               this.startTime = startTime;\r
+       }\r
+\r
+       public void setOutputInterval(int interval) {\r
+               this.savePer = interval;\r
+       }\r
+       \r
+    public Double getCurrentValue(String name) {\r
+        if(subscriptionIndexes != null && name != null) {\r
+            Integer index = subscriptionIndexes.get(name);\r
+            if(index != null) {\r
+                return currentValues[index];\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+\r
+       public void setSubscribedResults(IProgressMonitor monitor, double time) throws FMUJNIException {\r
+\r
+               monitor.subTask("Get results (time = " + time + ")");\r
+               currentValues = getSolver().getSubscribedResults(currentValues);\r
+               monitor.worked(1);\r
+\r
+               monitor.subTask("Save results (time = " + time + ")");\r
+               for(int k = 0; k < subscription.length; k++) {\r
+                       setResults(time, subscription[k], currentValues[k]);\r
+               }\r
+               \r
+               lastResultTime = time;\r
+               \r
+       }\r
+    \r
+       private double lastResultTime = Double.NaN;\r
+\r
+       public void setResults(double time, String key, Double value) {\r
+               TDoubleArrayList list = results.get(key);\r
+               if(list == null) {\r
+                       list = new TDoubleArrayList();\r
+                       results.put(key, list);\r
+               }\r
+               if(time == lastResultTime) {\r
+                       list.set(list.size()-1, value);\r
+               } else {\r
+                       list.add(value);\r
+               }\r
+//             System.err.println("setResults " + time + " " + key + " = " + list);\r
+       }\r
+       \r
+       public void clearResults() {\r
+               lastResultTime = Double.NaN;\r
+               results.clear();\r
+       }\r
+       \r
+       @Override\r
+       public void simulateDuration(double duration) {\r
+               Job job = new SimulateDurationJob(this, "Simulate steps", duration);\r
+               // Start the Job\r
+               job.schedule();\r
+       }\r
+       \r
+       public void refresh() {\r
+       }\r
+       \r
+    public abstract ISolver getSolver();\r
+    \r
+    @Override\r
+    public void init(ReadGraph g) {\r
+       \r
+       super.init(g);\r
+       \r
+       try {\r
+               g.syncRequest(new Read<Quad<Double, Double, Double, Double>>() {\r
+\r
+                       @Override\r
+                       public Quad<Double, Double, Double, Double> perform(ReadGraph graph)\r
+                                       throws DatabaseException {\r
+                               SysdynResource sr = SysdynResource.getInstance(graph);\r
+                               Double stepDuration = graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepDuration);\r
+                               Double stepLength = graph.getPossibleRelatedValue(experiment, sr.GameExperiment_stepLength);\r
+                               Double outputInterval = graph.getPossibleRelatedValue(model, sr.SysdynModel_outputInterval);\r
+                               Double startTime = graph.getPossibleRelatedValue(model, sr.SysdynModel_startTime);\r
+                               return new Quad<Double, Double, Double, Double>(stepDuration, stepLength, outputInterval, startTime);\r
+                       }\r
+               }, new AsyncListener<Quad<Double, Double, Double, Double>>() {\r
+\r
+                       @Override\r
+                       public void execute(AsyncReadGraph graph,\r
+                                       Quad<Double, Double, Double, Double> result) {\r
+                               setStepDuration(result.first != null ? result.first : DEFAULT_STEP_DURATION);\r
+                               setStepLength(result.second != null ? result.second : DEFAULT_STEP_LENGTH);\r
+                               setStartTime(result.fourth != null ? result.fourth : DEFAULT_START_TIME);\r
+\r
+                               if(result.third == null) {\r
+                                       setOutputInterval(DEFAULT_OUTPUT_INTERVAL);\r
+                               } else {\r
+                                       int interval = (int)getInterval(result.third, getStepLength());\r
+                                       setOutputInterval(interval);\r
+                               }\r
+                       }\r
+\r
+                       @Override\r
+                       public void exception(AsyncReadGraph graph, Throwable throwable) {\r
+                               throwable.printStackTrace();\r
+                               setStepDuration(DEFAULT_STEP_DURATION);\r
+                               setStepLength(DEFAULT_STEP_LENGTH);\r
+                               setStartTime(DEFAULT_START_TIME);\r
+                               setOutputInterval(DEFAULT_OUTPUT_INTERVAL);\r
+                       }\r
+\r
+                       @Override\r
+                       public boolean isDisposed() {\r
+                               return getState().equals(ExperimentState.DISPOSED);\r
+                       }\r
+               });\r
+       } catch (DatabaseException e) {\r
+               e.printStackTrace();\r
+       }\r
+       \r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynGameExperimentInternal.java
new file mode 100644 (file)
index 0000000..1dfc9a8
--- /dev/null
@@ -0,0 +1,181 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import gnu.trove.list.array.TDoubleArrayList;\r
+import gnu.trove.map.hash.THashMap;\r
+\r
+import java.io.IOException;\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.NullProgressMonitor;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.Layer0Utils;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.modelica.IModelicaMonitor;\r
+import org.simantics.modeling.PartialIC;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.simulation.SimulationJob.HeadlessModelicaMonitor;\r
+import org.simantics.sysdyn.solver.ISolver;\r
+import org.simantics.sysdyn.solver.ISolverMonitor;\r
+import org.simantics.sysdyn.solver.InternalSolver;\r
+\r
+\r
+public class SysdynGameExperimentInternal extends SysdynGameExperimentBase {\r
+\r
+       public InternalSolver solver;\r
+       \r
+       public SysdynGameExperimentInternal(Resource experiment, Resource model) {\r
+               super(experiment, model);\r
+       }\r
+\r
+       @Override\r
+       public ISolver getSolver() {\r
+               return solver;\r
+       }\r
+       \r
+       @Override\r
+       public void init(ReadGraph g) {\r
+               \r
+               super.init(g);\r
+               \r
+               results = new THashMap<String, TDoubleArrayList>();\r
+\r
+               solver = new InternalSolver(this, sysdynModel, true, new ISolverMonitor() {\r
+                       \r
+                       @Override\r
+                       public void showConsole() {\r
+                               // TODO Auto-generated method stub\r
+                               \r
+                       }\r
+                       \r
+                       @Override\r
+                       public void message(String message) {\r
+                               System.err.println("Internal solver:" + message);\r
+                       }\r
+                       \r
+                       @Override\r
+                       public void clearConsole() {\r
+                               // TODO Auto-generated method stub\r
+                               \r
+                       }\r
+               });\r
+\r
+       }\r
+\r
+       @Override\r
+    public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException {\r
+               \r
+       try {\r
+\r
+               solver.initialize();\r
+               solver.buildModel();\r
+\r
+            //solver.setTime(startTime);\r
+\r
+            subscription = solver.solver.keys();\r
+            \r
+            // Initialize subscription indexes map for fast result reading in getValue()\r
+            if(subscriptionIndexes == null)\r
+                subscriptionIndexes = new HashMap<String, Integer>();\r
+            \r
+            subscriptionIndexes.clear();\r
+            for(int i = 0; i < subscription.length; i++) {\r
+                subscriptionIndexes.put(subscription[i], i);\r
+            }\r
+\r
+            // Initialize container for current simulation results\r
+            currentValues = new double[subscription.length];\r
+            \r
+            // subscribe all variables\r
+            //solver.subscribe(subscription); \r
+\r
+            clearResults();\r
+            //getInitialResultValues();\r
+            \r
+                       Simantics.getSession().syncRequest(new WriteRequest() {\r
+\r
+                               @Override\r
+                               public void perform(WriteGraph graph) throws DatabaseException {\r
+\r
+                                       Resource run = Layer0Utils.getPossibleChild(graph, SysdynGameExperimentInternal.this.experiment, getIdentifier());\r
+                                       if(run == null) {\r
+                                               System.err.println("No run");\r
+                                               return;\r
+                                       }\r
+                                       \r
+                                       Variable base = Variables.getVariable(graph, run);\r
+                                       \r
+                                       SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
+                                       \r
+                                       Resource ic = graph.getPossibleObject(SysdynGameExperimentInternal.this.experiment, SYSDYN.Experiment_ic);\r
+                                       if(ic == null) return;\r
+                                       \r
+                                       PartialIC data = graph.getPossibleRelatedValue(ic, SYSDYN.InitialCondition_HasInitialValues, PartialIC.BINDING);\r
+                                       data.apply(graph, base);\r
+                                       \r
+                               }\r
+                               \r
+                       });\r
+                       \r
+                       \r
+                       setSubscribedResults(new NullProgressMonitor(), solver.getTime());\r
+\r
+                       ((MemoryResult)getCurrentResult()).setResult(new GameResult(this, this.results, this.subscription));\r
+\r
+                       resultsChanged(true);\r
+                       \r
+               changeState(ExperimentState.STOPPED);\r
+               \r
+               } catch (Exception e) {\r
+                       Logger.defaultLogError(e);\r
+               }\r
+    }\r
+       \r
+       @Override\r
+       public void refresh() {\r
+               try {\r
+                       setSubscribedResults(new NullProgressMonitor(), solver.getTime());\r
+       \r
+                       ((MemoryResult)getCurrentResult()).setResult(new GameResult(this, this.results, this.subscription));\r
+       \r
+                       resultsChanged(true);\r
+               } catch (Exception e) {\r
+                       Logger.defaultLogError(e);\r
+               }                       \r
+       }\r
+       \r
+       @Override\r
+    public void rewindTo(double time) {\r
+        \r
+        if(time >-0.001 && time < 0.001) {\r
+               try {\r
+                               simulate(new HeadlessModelicaMonitor(), new NullProgressMonitor(), sysdynModel.getConfiguration().getLabel());\r
+                   //instantiate();\r
+                       } catch (IOException e) {\r
+                               Logger.defaultLogError(e);\r
+                       }\r
+        } else {\r
+            System.out.println("rewindTo");\r
+        }\r
+    }\r
+\r
+ }\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java
new file mode 100644 (file)
index 0000000..ab04055
--- /dev/null
@@ -0,0 +1,589 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4180\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import gnu.trove.set.hash.THashSet;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import java.util.concurrent.CopyOnWriteArrayList;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.procedure.Listener;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.db.service.VirtualGraphSupport;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.IMapping;\r
+import org.simantics.objmap.IMappingListener;\r
+import org.simantics.objmap.MappingException;\r
+import org.simantics.objmap.Mappings;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.model.IModel;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.simulation.project.ExperimentRuns;\r
+import org.simantics.simulation.project.IExperimentActivationListener;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.adapter.VariableValueSubscription;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Model;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.ParameterOverride;\r
+import org.simantics.sysdyn.representation.Sheet;\r
+import org.simantics.sysdyn.representation.SysdynSchema;\r
+import org.simantics.sysdyn.representation.Variability;\r
+import org.simantics.sysdyn.representation.expressions.Expression;\r
+import org.simantics.sysdyn.representation.expressions.IExpression;\r
+import org.simantics.sysdyn.representation.expressions.ParameterExpression;\r
+import org.simantics.sysdyn.representation.expressions.StockExpression;\r
+import org.simantics.sysdyn.solver.SolverSettings;\r
+import org.simantics.sysdyn.solver.SolverSettings.SolverType;\r
+\r
+/**\r
+ * Maintains a Java representation of system dynamic model.\r
+ * @author Hannu Niemistö, Teemu Lempinen\r
+ */\r
+public class SysdynModel implements IModel, IMappingListener, VariableSubscriptionManager {\r
+\r
+    private Session session;\r
+\r
+    private IMapping mapping;\r
+\r
+    private Resource configurationResource;\r
+    private Resource modelResource;\r
+\r
+    private Configuration configuration;\r
+\r
+    private final Set<Configuration> modules = new HashSet<Configuration>();\r
+\r
+    private ArrayList<SysdynResult> displayedResults;\r
+    private final ArrayList<HistoryDatasetResult> listeningHistories = new ArrayList<HistoryDatasetResult>();\r
+\r
+    private final CopyOnWriteArrayList<Runnable> modificationListeners =\r
+            new CopyOnWriteArrayList<Runnable>();\r
+    \r
+    @SuppressWarnings("rawtypes")\r
+    protected THashSet<VariableValueSubscription> variableValueSubscriptions = new THashSet<VariableValueSubscription>();\r
+    @SuppressWarnings("rawtypes")\r
+    protected volatile VariableValueSubscription[] variableValueSubscriptionsSnapshot = null;\r
+\r
+    @SuppressWarnings("rawtypes")\r
+    private final Map<Class, Object> services = new HashMap<Class, Object>();\r
+    \r
+    private boolean structureModified = false;\r
+\r
+    /**\r
+     * Recursively read all module configurations that are used in \r
+     * configResource and its components children\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param configResource Configuration\r
+     * @param result set containing all encountered configurations\r
+     * @throws DatabaseException\r
+     */\r
+    void readModules(ReadGraph graph, Resource configResource, Set<Resource> result) throws DatabaseException {\r
+\r
+        // if result does not contain this resource, add it to the result\r
+        if(!result.add(configResource)) return;\r
+\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        StructuralResource2 str = StructuralResource2.getInstance(graph);\r
+\r
+        for(Resource part : graph.getObjects(configResource, l0.ConsistsOf)) {\r
+            if(graph.isInstanceOf(part, sr.Module)) {\r
+                Resource type = graph.getPossibleType(part, sr.Module);\r
+                Resource config = graph.getPossibleObject(type, str.IsDefinedBy);\r
+                // Recursively readModules\r
+                readModules(graph, config, result);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Get all modules that have been used in configResource and its children\r
+     * @param graph ReadGraph\r
+     * @param configResource Configuration\r
+     * @return All modules (configuration resources) that have been used in configResource  \r
+     * @throws DatabaseException\r
+     */\r
+    Set<Resource> readModules(ReadGraph graph, Resource configResource) throws DatabaseException {\r
+        HashSet<Resource> result = new HashSet<Resource>();\r
+        readModules(graph, configResource, result);\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * Create an ObjMapping\r
+     * @param g ReadGraph\r
+     * @throws DatabaseException\r
+     */\r
+    private void createMapping(ReadGraph g) throws DatabaseException {\r
+        SysdynSchema schema = new SysdynSchema(g);\r
+        mapping = Mappings.createWithListening(schema);\r
+        mapping.addMappingListener(SysdynModel.this);\r
+        try {\r
+            configuration = (Configuration)mapping.map(g, configurationResource);                \r
+        } catch (MappingException e) {\r
+            SysdynConsole.INSTANCE.message(\r
+                    "Error: Mapping is broken! Find the problem, " +\r
+                    "fix it and restart the program." +\r
+                    "\nJava error message:\n" + \r
+                            e.getMessage());\r
+            throw e;\r
+        }\r
+        for(Resource config : readModules(g, configurationResource)) {\r
+            modules.add((Configuration)mapping.map(g, config));\r
+        }\r
+    }\r
+\r
+    /**\r
+     * New Sysdyn model\r
+     * @param g ReadGraph\r
+     * @param configurationResource Configration resource of the model\r
+     */\r
+    public SysdynModel(ReadGraph g, Resource configurationResource) {\r
+        this.session = g.getSession();\r
+        this.configurationResource = configurationResource;\r
+\r
+        try {\r
+            createMapping(g);\r
+        } catch(DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        g.asyncRequest(new Read<ArrayList<SysdynResult>> () {\r
+            @Override\r
+            public ArrayList<SysdynResult> perform(ReadGraph graph) throws DatabaseException {\r
+                ArrayList<SysdynResult> displayedResults = new ArrayList<SysdynResult>();\r
+                // TODO: this can be done automatically with a listener\r
+                \r
+                for(HistoryDatasetResult hs : listeningHistories)\r
+                    hs.disposeListeners(); // dispose old histories listening to spreadsheets\r
+                \r
+                try {\r
+                    // Find all active saved results\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+                    Resource model = graph.getPossibleObject(getConfigurationResource(), SIMU.IsConfigurationOf);\r
+                    if(model == null)\r
+                        return null;\r
+                    \r
+                    Collection<Resource> results = graph.syncRequest(new ActiveResults(model));\r
+                    for(Resource result : results) {\r
+                        if(graph.hasStatement(result, sr.Result_showResult)) {\r
+                            SysdynResult sysdynResult = null;\r
+                            if(graph.isInstanceOf(result, sr.HistoryDataset)) {\r
+                                HistoryDatasetResult r = new HistoryDatasetResult();\r
+                                listeningHistories.add(r);\r
+                                sysdynResult = new MemoryResult(r, NameUtils.getSafeLabel(graph, result));\r
+                                r.read((MemoryResult)sysdynResult, result);\r
+                            } else {\r
+                                sysdynResult = new FileResult(\r
+                                        (String) graph.getPossibleRelatedValue(result, l0.HasLabel),\r
+                                        (String) graph.getPossibleRelatedValue(result, sr.Result_resultFile));\r
+                            }\r
+\r
+                            if(sysdynResult != null)\r
+                                displayedResults.add(sysdynResult);\r
+                        }\r
+                    }\r
+                } catch (Exception e) {\r
+                    e.printStackTrace();\r
+                }\r
+\r
+                return displayedResults;\r
+            }\r
+\r
+        }, new Listener<ArrayList<SysdynResult>> () {\r
+\r
+            @Override\r
+            public void execute(ArrayList<SysdynResult> result) {\r
+                // Add the current result if there is one\r
+                displayedResults = result;\r
+                resultChanged();\r
+            }\r
+\r
+            @Override\r
+            public void exception(Throwable t) {\r
+                t.printStackTrace();\r
+            }\r
+\r
+            @Override\r
+            public boolean isDisposed() {\r
+                return false;\r
+            }\r
+\r
+        });\r
+    }\r
+\r
+    // A dummy call for experiments\r
+    public SysdynModel(Resource modelResource) {\r
+        this.modelResource = modelResource;\r
+    }\r
+    \r
+    /**\r
+     * Get modules\r
+     * @return modules\r
+     */\r
+    public Set<Configuration> getModules() {\r
+       return modules;\r
+    }\r
+\r
+    /**\r
+     * Update mapping.\r
+     * \r
+     * Use this if inside a transaction.\r
+     * \r
+     * @param graph ReadGraph\r
+     * @return has the range been modified\r
+     * @throws DatabaseException\r
+     */\r
+    public synchronized boolean update(ReadGraph graph) throws DatabaseException {\r
+        if(mapping.isDomainModified()) {\r
+            try {\r
+                Collection<Object> updated = mapping.updateRange(graph);\r
+\r
+                for(Object o : updated) {\r
+                    if(o instanceof Model) {\r
+                        continue;\r
+                    } else if(o instanceof Expression && !(o instanceof StockExpression)) {\r
+                        IndependentVariable variable = ((Expression)o).getParent();\r
+                        Variability variability = Variability.getVariability(variable, false, configuration);\r
+                        if(variability == Variability.PARAMETER)\r
+                            continue;\r
+                    }\r
+                    \r
+                    // if continue has not been called, the structure has changed\r
+                    setStructureModified(true);\r
+                    break;\r
+\r
+                }\r
+                \r
+            } catch (MappingException e) {\r
+                SysdynConsole.INSTANCE.message(\r
+                        "Error: Mapping is broken! Find the problem, " +\r
+                        "fix it and restart the program." +\r
+                        "\nJava error message:\n" + \r
+                                e.getMessage());\r
+                throw e;\r
+            }\r
+\r
+            // Remove all unnecessary module configurations from modules \r
+            Set<Resource> configs = readModules(graph, configurationResource); \r
+            for(Resource config : configs) {\r
+                if(!modules.contains(config))\r
+                    modules.add((Configuration)mapping.map(graph, config));\r
+            }\r
+\r
+            HashSet<Configuration> toBeRemoved = null;\r
+            for(Configuration module : modules) {\r
+                if(!configs.contains(mapping.inverseGet(module))) {\r
+                    if(toBeRemoved == null)\r
+                        toBeRemoved = new HashSet<Configuration>();\r
+                    toBeRemoved.add(module);\r
+                }\r
+            }\r
+            if(toBeRemoved != null)\r
+                modules.removeAll(toBeRemoved);\r
+            return true;\r
+        }\r
+        else\r
+            return false;\r
+    }        \r
+\r
+    /**\r
+     * Update mapping.\r
+     * \r
+     * Use only if not inside a transaction\r
+     * @return has range been updated\r
+     * @throws DatabaseException\r
+     */\r
+    public boolean update() throws DatabaseException {\r
+        return session.syncRequest(new Read<Boolean>() {\r
+            @Override\r
+            public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                return update(graph);\r
+            }\r
+        });\r
+    }\r
+    \r
+    /**\r
+     * Fires an update to all result listeners and subscriptions\r
+     * after results have changed\r
+     */\r
+    public void resultChanged() {\r
+        IProject project = Simantics.peekProject();\r
+        IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+        IExperiment active = manager.getActiveExperiment();   \r
+        if(active != null && active instanceof SysdynExperiment) {\r
+            ((SysdynExperiment)active).resultsChanged();\r
+        }\r
+        \r
+        updateSubscriptions();\r
+    }\r
+\r
+    public void addModificationListener(Runnable listener) {\r
+        synchronized(modificationListeners) {\r
+            modificationListeners.add(listener);\r
+        }\r
+    }\r
+\r
+    public void removeModificationListener(Runnable listener) {\r
+        synchronized(modificationListeners) {\r
+            modificationListeners.remove(listener);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Fires all modification listeners after a change in the domain\r
+     */\r
+    @Override\r
+    public void domainModified() {\r
+        synchronized(modificationListeners) {\r
+            for(Runnable listener : modificationListeners)\r
+                listener.run();\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public void rangeModified() {\r
+    }\r
+\r
+    public Configuration getConfiguration() {\r
+        return configuration;\r
+    }\r
+\r
+    public Resource getConfigurationResource() {\r
+        return configurationResource;\r
+    }\r
+\r
+    public IMapping getMapping() {\r
+        return mapping;\r
+    }\r
+\r
+    public synchronized IElement getElement(Resource resource) {\r
+        return (IElement)mapping.get(resource);\r
+    }\r
+\r
+    public <T> T getService(Class<T> clazz) {\r
+        synchronized(services) {\r
+            return clazz.cast(services.get(clazz));\r
+        }\r
+    }\r
+\r
+    public <T> void addService(Class<T> clazz, T service) {\r
+        synchronized(services) {\r
+            services.put(clazz, service);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    public IExperiment loadExperiment(ReadGraph g, Resource experiment, IExperimentActivationListener listener) {\r
+        // Make sure that configurationResource exists\r
+        if(configurationResource == null && modelResource != null) {\r
+            SimulationResource simu = SimulationResource.getInstance(g);\r
+            try {\r
+                configurationResource = g.getPossibleObject(modelResource, simu.HasConfiguration);\r
+            } catch (ManyObjectsForFunctionalRelationException e) {\r
+                e.printStackTrace();\r
+            } catch (ServiceException e) {\r
+                e.printStackTrace();\r
+            } \r
+        }\r
+\r
+        try {\r
+            // Create a new experiment based on the experiment resource type\r
+            SysdynResource sr = SysdynResource.getInstance(g);\r
+            SysdynExperiment exp;\r
+            \r
+            if(g.isInstanceOf(experiment, sr.PlaybackExperiment)) {\r
+                exp = new SysdynPlaybackExperiment(experiment, modelResource);\r
+            } else if(g.isInstanceOf(experiment, sr.GameExperiment)) {\r
+               if (SolverType.INTERNAL.equals(SolverSettings.getSelectedSolverType())) {\r
+                       exp = new SysdynGameExperimentInternal(experiment, modelResource);\r
+               }\r
+               else {\r
+                    exp = new SysdynGameExperiment(experiment, modelResource);\r
+               }\r
+            } else if(g.isInstanceOf(experiment, sr.SensitivityAnalysisExperiment)) {\r
+                exp = new SysdynSensitivityAnalysisExperiment(experiment, modelResource);\r
+            } else if(g.isInstanceOf(experiment, sr.BasicExperiment)) {\r
+               // TODO: this is a temporary hack to make sure at least one \r
+               // working implementation is available even if the new solver \r
+               // architecture is completely broken\r
+               if (SolverType.INTERNAL.equals(SolverSettings.getSelectedSolverType())) {\r
+                       exp = new SysdynExperiment(experiment, modelResource);\r
+               }\r
+               else {\r
+                       exp = new OldSysdynExperiment(experiment, modelResource);\r
+               }\r
+            } else {\r
+                return null;\r
+            }\r
+            \r
+            // TODO: should maybe get the model from model manager?\r
+            \r
+            exp.init(g);\r
+            \r
+            VirtualGraphSupport support = g.getSession().getService(VirtualGraphSupport.class);\r
+            ExperimentRuns.createRun(g.getSession(), support.getWorkspacePersistent("experiments"), experiment, exp, SysdynResource.URIs.Experiment_Run, listener, null);\r
+            if(listener != null)\r
+                listener.onExperimentActivated(exp);\r
+            return exp;\r
+        } catch(Exception e) {\r
+            if(listener != null)\r
+                listener.onFailure(e);\r
+            return null;\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * Get active results. To update the active results, use getAndUpdateActiveResults()\r
+     * \r
+     * @param graph ReadGraph\r
+     * @return all active SysdynResults (last update with getAndUpdateActiveResults())\r
+     */\r
+    public Collection<SysdynResult> getDisplayedResults() {\r
+       // TODO: displayedResults are always empty?\r
+        if(displayedResults == null)\r
+            return new ArrayList<SysdynResult>();\r
+        else\r
+            return displayedResults;\r
+    }\r
+\r
+    /**\r
+     * Get all parameters for Configuration\r
+     * \r
+     * @param configuration Configuration\r
+     * @param prefix String prefix of configuration in this model (Module1.Module2...)\r
+     * @return\r
+     */\r
+    public HashMap<String, String> getInits(Configuration configuration, String prefix) {\r
+        HashMap<String, String> inits = new HashMap<String, String>();\r
+        for (IElement element : configuration.getElements()) {\r
+            if (element instanceof Module) {\r
+                Module module = (Module) element;\r
+                Configuration conf = module.getType().getConfiguration();\r
+                String prfx = prefix + module.getName() + ".";\r
+                inits.putAll(getInits(conf, prfx));\r
+                for(ParameterOverride po : module.getParameterOverrides()) {\r
+                       inits.put(prfx + po.getVariable().getName(), po.getExpression());\r
+                }\r
+            } else if (element instanceof IndependentVariable) {\r
+               IndependentVariable variable = (IndependentVariable) element;\r
+               //FIXME: more general solution for finding out if the variable is a parameter\r
+               if(variable != null && variable.getExpressions() != null && variable.getExpressions().get(0) != null) {\r
+                       IExpression expression = variable.getExpressions().get(0);\r
+                       if (expression instanceof ParameterExpression) {\r
+                               Double value = ((ParameterExpression)expression).getValue();\r
+                               if(value != null)\r
+                                       inits.put(prefix + variable.getName(), "" + value);\r
+                       }\r
+               }\r
+            } else if(element instanceof Sheet) {\r
+                Sheet sheet = (Sheet) element;\r
+                for(String cell : sheet.getCells().keySet()) {\r
+                    inits.put(sheet.getName() + "." + cell, sheet.getCells().get(cell).toString());\r
+                }\r
+            }\r
+        }\r
+        return inits;\r
+    }\r
+\r
+\r
+       @SuppressWarnings("rawtypes")\r
+    /**\r
+     * Copy from AprosExperiment\r
+     * @param subscription\r
+     */\r
+    @Override\r
+    public void addVariableValueSubscription(VariableValueSubscription subscription) {\r
+        assert subscription != null;\r
+        synchronized (variableValueSubscriptions) {\r
+            variableValueSubscriptions.add(subscription);\r
+            variableValueSubscriptionsSnapshot = null;\r
+        }\r
+    }\r
+\r
+       @SuppressWarnings("rawtypes")\r
+    /**\r
+     * Copy from AprosExperiment\r
+     * @param subscription\r
+     */\r
+   @Override\r
+   public void removeVariableValueSubscription(VariableValueSubscription subscription) {\r
+        assert subscription != null;\r
+        synchronized (variableValueSubscriptions) {\r
+            variableValueSubscriptions.remove(subscription);\r
+            variableValueSubscriptionsSnapshot = null;\r
+        }\r
+    }\r
+\r
+       @SuppressWarnings("rawtypes")\r
+    /**\r
+     * Copy from AprosExperiment\r
+     * @return\r
+     */\r
+    @Override\r
+    public VariableValueSubscription[] getListenerSnapshot() {\r
+        VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot;\r
+        if (snapshot == null) {\r
+            synchronized (variableValueSubscriptions) {\r
+                snapshot = variableValueSubscriptionsSnapshot;\r
+                if (snapshot == null) {\r
+                    snapshot = variableValueSubscriptionsSnapshot = variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]);\r
+                }\r
+            }\r
+        }\r
+        return snapshot;\r
+    }\r
+\r
+       @SuppressWarnings("rawtypes")\r
+    /**\r
+     * Modified copy from AporsExperiment\r
+     */\r
+    @Override\r
+    public void updateSubscriptions() {\r
+        VariableValueSubscription[] snapShot = getListenerSnapshot();\r
+        for(VariableValueSubscription subscription : snapShot)\r
+            subscription.update();\r
+    }\r
+       \r
+       \r
+       public boolean isStructureModified() {\r
+           return structureModified;\r
+       }\r
+\r
+       public void setStructureModified(boolean structureModified) {\r
+           this.structureModified = structureModified;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java
new file mode 100644 (file)
index 0000000..c902f9c
--- /dev/null
@@ -0,0 +1,84 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.util.WeakHashMap;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+/**\r
+ * Manages system dynamic models.\r
+ * @author Hannu Niemist&ouml;\r
+ */\r
+public class SysdynModelManager {\r
+    WeakHashMap<Resource, SysdynModel> models =\r
+        new WeakHashMap<Resource, SysdynModel>(); // FIXME: Resources are weak, there is no guarantee that model exists in this map as long as needed.\r
+                                                                                         //        HashTable with a disposal procedure could be better solution..\r
+    Session session;\r
+\r
+    public SysdynModelManager(Session session) {\r
+        this.session = session;\r
+    }\r
+\r
+    /**\r
+     * Use only if not inside a transaction\r
+     */\r
+    public SysdynModel getModel(final Resource resource) {\r
+       synchronized(models) {\r
+               SysdynModel model = models.get(resource);\r
+               if(model == null) {\r
+                   try {\r
+                       session.syncRequest(new ReadRequest() {\r
+                               @Override\r
+                               public void run(ReadGraph graph) throws DatabaseException {\r
+                                       SysdynModel model = new SysdynModel(graph, resource);\r
+                                   models.put(resource, model);\r
+                               }\r
+                           });\r
+                   } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+                   }\r
+                   \r
+                   model = models.get(resource);\r
+               }\r
+               return model;\r
+       }\r
+    }\r
+    \r
+    /**\r
+     * Should be used if called inside a transaction\r
+     */\r
+    public SysdynModel getModel(ReadGraph g, Resource resource) {\r
+       synchronized(models) {\r
+               SysdynModel model = models.get(resource);\r
+               if(model == null) {\r
+                   model = new SysdynModel(g, resource);\r
+                   models.put(resource, model);\r
+               }\r
+               return model;\r
+       }\r
+    }\r
+\r
+    public synchronized static SysdynModelManager getInstance(Session session) {\r
+        SysdynModelManager manager =\r
+            session.peekService(SysdynModelManager.class);\r
+        if(manager == null) {\r
+            manager = new SysdynModelManager(session);\r
+            session.registerService(SysdynModelManager.class, manager);\r
+        }\r
+        return manager;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java
new file mode 100644 (file)
index 0000000..38ae038
--- /dev/null
@@ -0,0 +1,285 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.concurrent.Executors;\r
+import java.util.concurrent.ScheduledExecutorService;\r
+import java.util.concurrent.ScheduledFuture;\r
+import java.util.concurrent.TimeUnit;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.Simantics;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.simulation.experiment.ExperimentState;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class SysdynPlaybackExperiment extends OldSysdynExperiment {\r
+\r
+    public static long DURATION_SLOW = 20000;\r
+    public static long DURATION_NORMAL = 10000;\r
+    public static long DURATION_FAST = 5000;\r
+\r
+    double time, startTime, endTime;\r
+    public static final long VARIABLE_UPDATE_INTERVAL = 500000000;\r
+    private static final double UPDATES_PER_TIME_UNIT = 0.015;\r
+    private long playbackDuration = DURATION_NORMAL;\r
+    private Collection<Runnable> timeListeners = new ArrayList<Runnable>();\r
+\r
+    ScheduledExecutorService playbackExecutionService;\r
+    PlaybackConfiguration playbackConfiguration;\r
+\r
+    public SysdynPlaybackExperiment(Resource experiment, Resource model) {\r
+        super(experiment, model);\r
+        this.time = 0;\r
+    }\r
+\r
+\r
+    /**\r
+     * Interrupts a possible ongoing playback\r
+     * \r
+     * @param time\r
+     */\r
+    public void setTimeInterrupting(double time) {\r
+        stopPlayback();\r
+        setTime(time);\r
+    }\r
+\r
+    /**\r
+     * Sets a new time and continues playback from that point if \r
+     * playback was running  \r
+     * @param time\r
+     */\r
+    public void setTimeAndContinue(double time) {\r
+        if(isPlaybackRunning()) {\r
+            stopPlayback();\r
+            setTime(time);\r
+            startPlayback(500);\r
+        } else {\r
+            setTime(time);\r
+        }\r
+    }\r
+\r
+    private void setTime(double time) {\r
+        this.time = time;\r
+        resultsChanged(); \r
+    }\r
+\r
+    public double getTime() {\r
+        return this.time;\r
+    }\r
+\r
+    public double getStartTime() {\r
+        return this.startTime;\r
+    }\r
+\r
+    public double getEndTime() {\r
+        return this.endTime;\r
+    }\r
+\r
+    public void setPlaybackDuration(long duration) {\r
+        this.playbackDuration = duration;\r
+        if(isPlaybackRunning()) {\r
+            //Restart playback with different time settings\r
+            startPlayback();\r
+        }\r
+    }\r
+\r
+    public long getPlaybackDuration() {\r
+        return this.playbackDuration;\r
+    }\r
+\r
+    @Override\r
+    public void init(ReadGraph g) {\r
+        this.session = g.getSession();\r
+        session.asyncRequest(new ReadRequest() {\r
+\r
+            @Override\r
+            public void run(ReadGraph graph) throws DatabaseException {\r
+                changeState(ExperimentState.RUNNING);\r
+                final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+                sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration);\r
+                toggleActivation(graph, true);\r
+                getPlaybackConfiguration(graph);\r
+                startSimulationJob();\r
+            }\r
+        });\r
+    }\r
+\r
+\r
+    // PLAYBACK CONTROLS\r
+    public void startPlayback() {\r
+        startPlayback(0);\r
+    }\r
+    public void startPlayback(long initialDelay) {\r
+        if(isPlaybackRunning()) {\r
+            stopPlayback();\r
+        }\r
+        playbackConfiguration = getPlaybackConfiguration();\r
+        playbackExecutionService = Executors.newScheduledThreadPool(1); \r
+\r
+        if(time >= playbackConfiguration.endTime) {\r
+            setTime(playbackConfiguration.startTime);\r
+            playbackConfiguration = getPlaybackConfiguration();\r
+        }\r
+\r
+        Runnable playbackSimulationTask = new PlaybackSimulationTask(time, playbackConfiguration.simulationStepLength);\r
+\r
+        long delay = (long) (playbackConfiguration.playbackDuration / playbackConfiguration.intervals);\r
+        ScheduledFuture<?> stepper = playbackExecutionService.scheduleWithFixedDelay(\r
+                playbackSimulationTask, initialDelay, delay, TimeUnit.MILLISECONDS\r
+                );\r
+\r
+        Runnable stopSimulationTask = new StopSimulationTask(stepper, playbackConfiguration.endTime);\r
+        playbackExecutionService.schedule(stopSimulationTask, playbackConfiguration.playbackDuration + initialDelay, TimeUnit.MILLISECONDS);\r
+\r
+        changeState(ExperimentState.RUNNING);\r
+    }\r
+\r
+    public boolean isPlaybackRunning() {\r
+        return playbackExecutionService != null && !playbackExecutionService.isShutdown();\r
+    }\r
+\r
+    public void resetPlayback() {\r
+        double startTime = 0.0;\r
+        if(isPlaybackRunning() && playbackConfiguration != null) {\r
+            startTime = playbackConfiguration.startTime;\r
+        } else {\r
+            startTime = getPlaybackConfiguration().startTime;\r
+        }\r
+        setTimeInterrupting(startTime);\r
+    }\r
+\r
+    public void stopPlayback() {\r
+        if(isPlaybackRunning()) {\r
+            playbackExecutionService.shutdownNow();\r
+            playbackExecutionService.shutdown();\r
+            if(playbackConfiguration != null)\r
+                playbackConfiguration = null;\r
+            changeState(ExperimentState.STOPPED);\r
+        }\r
+    }\r
+\r
+\r
+    private class PlaybackSimulationTask implements Runnable {\r
+        private int stepCount;\r
+        private double startTime, stepLength;\r
+\r
+        public PlaybackSimulationTask(double startTime, double stepLength) {\r
+            this.startTime = startTime;\r
+            this.stepLength = stepLength;\r
+        }\r
+\r
+        public void run() {\r
+            ++stepCount;\r
+            setTime(startTime + stepCount * stepLength);\r
+//          System.out.println("Playback step at time: " + (startTime + stepCount * stepLength) + " (step: " + stepCount + ")");\r
+        }\r
+    }\r
+\r
+    private class StopSimulationTask implements Runnable {\r
+\r
+        private ScheduledFuture<?> scheduledFuture;\r
+        private double endTime;\r
+\r
+        public StopSimulationTask(ScheduledFuture<?> aSchedFuture, double endTime){\r
+            scheduledFuture = aSchedFuture;\r
+            this.endTime = endTime;\r
+        }\r
+        public void run() {\r
+//            System.out.println("Stopping playback");\r
+            scheduledFuture.cancel(false);\r
+            stopPlayback();\r
+            setTime(endTime);\r
+        }\r
+\r
+    }\r
+\r
+    private PlaybackConfiguration getPlaybackConfiguration() {\r
+        PlaybackConfiguration config = null;\r
+        try {\r
+            config = Simantics.getSession().syncRequest(new Read<PlaybackConfiguration>() {\r
+\r
+                @Override\r
+                public PlaybackConfiguration perform(ReadGraph graph) throws DatabaseException {\r
+                    return getPlaybackConfiguration(graph);\r
+                }\r
+\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return config;\r
+    }\r
+    private PlaybackConfiguration getPlaybackConfiguration(ReadGraph graph) throws DatabaseException {\r
+        Double[] numbers = new Double[3];\r
+        Resource model = getModel();\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime);\r
+        numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime);\r
+\r
+        PlaybackConfiguration config = new PlaybackConfiguration();\r
+        config.simulationDuration = numbers[1] - numbers[0] - time;\r
+        config.playbackDuration = (long) (config.simulationDuration / (config.simulationDuration + time) * playbackDuration);\r
+        config.intervals = config.playbackDuration * UPDATES_PER_TIME_UNIT;\r
+        config.simulationStepLength = config.simulationDuration / config.intervals;\r
+        config.endTime = numbers[1];\r
+        config.startTime = numbers[0];\r
+\r
+        this.startTime = config.startTime;\r
+        this.endTime = config.endTime;\r
+        return config;\r
+    }\r
+\r
+    private class PlaybackConfiguration {\r
+        public double simulationDuration, simulationStepLength, intervals, endTime, startTime;\r
+        public long playbackDuration;\r
+    }\r
+\r
+    protected void localStateChange() {\r
+        super.localStateChange();\r
+\r
+        ExperimentState state = getState();\r
+        if(ExperimentState.DISPOSED.equals(state)) {\r
+            stopPlayback();\r
+        }\r
+    }\r
+\r
+    // TIME LISTENERS\r
+    public void addTimeListener(Runnable timeListener) {\r
+        if(!this.timeListeners.contains(timeListener))\r
+            this.timeListeners.add(timeListener);\r
+    }\r
+\r
+    public Collection<Runnable> getTimeListeners() {\r
+        return this.timeListeners;\r
+    }\r
+\r
+    public void removeTimeListener(Runnable timeListener) {\r
+        this.timeListeners.remove(timeListener);\r
+    }\r
+\r
+    @Override\r
+    public void resultsChanged() {\r
+        for(Runnable listener : timeListeners) {\r
+            listener.run();\r
+        }\r
+        super.resultsChanged();\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynResult.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynResult.java
new file mode 100644 (file)
index 0000000..e564d59
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4180\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+\r
+import java.io.File;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+\r
+/**\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public abstract class SysdynResult {\r
+\r
+    private String resultName;\r
+\r
+    public SysdynResult(String resultName) {\r
+        this.resultName = resultName;\r
+    }\r
+\r
+    public String getResultName() {\r
+        return this.resultName;\r
+    }\r
+\r
+    public abstract SysdynDataSet getDataSet(String variable);\r
+\r
+    public abstract void saveToFile(File file, IProgressMonitor progressMonitor);\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynSensitivityAnalysisExperiment.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynSensitivityAnalysisExperiment.java
new file mode 100644 (file)
index 0000000..063c386
--- /dev/null
@@ -0,0 +1,378 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.manager;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modelica.IModelicaMonitor;\r
+import org.simantics.modelica.ModelicaKeys;\r
+import org.simantics.modelica.ModelicaManager;\r
+import org.simantics.modelica.SimulationLocation;\r
+import org.simantics.modelica.data.CSVSimulationResult;\r
+import org.simantics.modelica.data.MatSimulationResult;\r
+import org.simantics.modelica.data.SimulationResult;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.adapter.SensitivityExperimentParameter;\r
+import org.simantics.sysdyn.adapter.generator.IGenerator;\r
+\r
+/**\r
+ * Sensitivity analysis experiment\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class SysdynSensitivityAnalysisExperiment extends OldSysdynExperiment {\r
+\r
+    private ArrayList<MemoryResult> results = null;\r
+       private int numberOfRuns = 0;\r
+       private IGenerator valueGenerator = null;\r
+       \r
+    public SysdynSensitivityAnalysisExperiment(Resource experiment, Resource model) {\r
+        super(experiment, model);\r
+    }\r
+    \r
+    private void findValuesAndRun(List<SensitivityExperimentParameter> parameters, HashMap<String, String> values, HashMap<String, String> experimentParameters) {\r
+       ArrayList<HashMap<String, String>> parameterMaps = new ArrayList<HashMap<String, String>>();\r
+       int parametersSize = parameters.size();\r
+\r
+       // Get method and number of runs\r
+        try {\r
+                       session.syncRequest(new WriteRequest() {\r
+                           @Override\r
+                           public void perform(WriteGraph graph) throws DatabaseException {\r
+                               SysdynResource SR = SysdynResource.getInstance(graph);\r
+                               numberOfRuns = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_numberOfValues, Bindings.INTEGER);\r
+                               Resource methodResource = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_method);\r
+                               if (methodResource == null) {\r
+                                   methodResource = GraphUtils.create2(graph, SR.RandomGenerator);\r
+                                   graph.claim(experiment, SR.SensitivityAnalysisExperiment_method, methodResource);\r
+                               }\r
+                               valueGenerator = graph.adapt(methodResource, IGenerator.class);\r
+                           }\r
+\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+        \r
+        // Refresh rate for charts\r
+        refreshRate = numberOfRuns / 20 + 1;\r
+        \r
+        // Initialize the random generator\r
+       valueGenerator.initialize();\r
+       \r
+       // Determine the changed parameters and their values for each individual run\r
+       for (int i = 0; i < numberOfRuns; ++i) {\r
+               List<Double> randoms = valueGenerator.next();// multi-dimensional random\r
+               HashMap<String, String> parameterMap = new HashMap<String, String>(parametersSize);\r
+               for (int j = 0; j < parametersSize; ++j) {\r
+                       SensitivityExperimentParameter p = parameters.get(j);\r
+                       // Get the random value\r
+                       double value = p.getDistribution().inverseCDF(randoms.get(j));\r
+                       // Add the new parameter-value-pair \r
+                       parameterMap.put(p.getFullModelicaName(), Double.toString(value));\r
+               }\r
+               // Add the complete list of one individual run parameter-value-pairs.\r
+               parameterMaps.add(parameterMap);\r
+       }\r
+               \r
+       // Set the parameters for each individual experiment and run them.\r
+       for (HashMap<String, String> parameterSet : parameterMaps) {\r
+               values.putAll(parameterSet);\r
+               runSensitivityRun(values, experimentParameters);\r
+       }\r
+    }\r
+    \r
+    private void runSensitivityRun(HashMap<String, String> values, HashMap<String, String> experimentParameters) {\r
+        int indexOfDot = simulationLocation.resultFile.toString().lastIndexOf('.');\r
+        if (indexOfDot > 1) {\r
+            String resFile = simulationLocation.resultFile.toString();\r
+            String newResFile = resFile.substring(0, indexOfDot) + currentRun + resFile.substring(indexOfDot);\r
+            experimentParameters.put(ModelicaManager.RESULT_FILE_NAME, newResFile);\r
+        }                \r
+        // Simulate the model for one parameter set\r
+        progressMonitor.subTask("Simulation iteration " + (currentRun+1) + "/" + numberOfRuns);\r
+\r
+        \r
+        try {\r
+            process = ModelicaManager.runModelica(\r
+                    simulationLocation,\r
+                    monitor,\r
+                    experimentParameters, \r
+                    values\r
+                    );\r
+        } catch (IOException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        ModelicaManager.printProcessOutput(process, monitor);\r
+\r
+        File resFile = new File(experimentParameters.get(ModelicaManager.RESULT_FILE_NAME));\r
+        boolean updateMonitors = currentRun % refreshRate == 0 || currentRun == numberOfRuns - 1;\r
+        Thread resultThread = getResultThread(resFile, experimentParameters, monitor, progressMonitor, updateMonitors, currentRun);\r
+        resultThread.run();\r
+\r
+        process = null;\r
+        \r
+        progressMonitor.worked(1);\r
+        currentRun++;\r
+\r
+    }\r
+    \r
+    private SimulationLocation simulationLocation;\r
+    private IModelicaMonitor monitor;\r
+    private IProgressMonitor progressMonitor;\r
+//    private HashMap<String, String> experimentParameters;\r
+    private int currentRun = 0;\r
+    private int refreshRate = 1;\r
+    private List<SensitivityExperimentParameter> parameters = new ArrayList<SensitivityExperimentParameter>();\r
+    \r
+    @Override\r
+    protected void runModelica(SimulationLocation simulationLocation, IModelicaMonitor monitor, IProgressMonitor progressMonitor, HashMap<String, String> experimentParameters, HashMap<String, String> changes) throws IOException {\r
+        results = null;\r
+        \r
+        this.simulationLocation = simulationLocation;\r
+        this.monitor = monitor;\r
+        this.progressMonitor = progressMonitor;\r
+        \r
+        if (changes == null) {\r
+            changes = new HashMap<String, String>();\r
+        }\r
+        \r
+        String version = ModelicaManager.getOMVersion(simulationLocation.omHome);\r
+        experimentParameters.put(ModelicaManager.OMC_VERSION, version);\r
+        \r
+        \r
+        loadConfiguration();\r
+        \r
+        currentRun = 0;\r
+        \r
+        \r
+        findValuesAndRun(parameters, changes, experimentParameters);\r
+    }\r
+\r
+    private void loadConfiguration(){\r
+        try {\r
+            session.syncRequest(new ReadRequest() {\r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                    \r
+                    SysdynResource SR = SysdynResource.getInstance(graph);\r
+                    \r
+                    Integer rRate = graph.getPossibleRelatedValue(experiment,  SR.SensitivityAnalysisExperiment_resultRefreshRate, Bindings.INTEGER);\r
+                    if(rRate != null)\r
+                        refreshRate = rRate;\r
+                    \r
+                    Resource parameterListResource = graph.getPossibleObject(experiment, SR.SensitivityAnalysisExperiment_parameterList);\r
+                    List<Resource> parameterResources = ListUtils.toList(graph, parameterListResource);\r
+                    \r
+                    if(parameters != null) {\r
+                        parameters.clear();\r
+                        for(Resource p : parameterResources) {\r
+                                       SensitivityExperimentParameter parameter = graph.adapt(p, SensitivityExperimentParameter.class);\r
+                               if (parameter.getFullName() != null)\r
+                                       parameters.add(parameter);\r
+                        }\r
+                    }\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Get a thread for reading and saving reuslts from a normal simulation\r
+     * @param simulationLocation\r
+     * @param inits\r
+     * @param monitor\r
+     * @param progressMonitor\r
+     * @param currentRun\r
+     * @return\r
+     */\r
+    protected Thread getResultThread(final File resFile, \r
+            final HashMap<String, String> experimentParameters, \r
+            final IModelicaMonitor monitor, \r
+            final IProgressMonitor progressMonitor,\r
+            final boolean updateMonitors,\r
+            final int currentRun) {\r
+        return new Thread() {\r
+            @Override\r
+            public void run() {\r
+                try {\r
+                    process.waitFor();\r
+\r
+                    if(!canceled) {\r
+                        // Get and store results\r
+                        SimulationResult result;\r
+                        if(resFile.getName().endsWith(".csv"))\r
+                            result = new CSVSimulationResult();\r
+                        else if(resFile.getName().endsWith(".plt"))\r
+                            result = new SimulationResult();\r
+                        else\r
+                            result = new MatSimulationResult(); // The latest format\r
+\r
+                        // The interval of results saved. Every result? Every other result? etc...\r
+                        int outIntervalInt = 1;\r
+                        String outputInterval = experimentParameters.get(ModelicaKeys.OUTPUT_INTERVAL);\r
+                        if(outputInterval != null) {\r
+                            String stepTime = experimentParameters.get(ModelicaKeys.STEP_VALUE);\r
+                            String stopTime = experimentParameters.get(ModelicaKeys.STOP_VALUE);\r
+                            \r
+                            Double step = Double.parseDouble(stepTime);\r
+                            Double stop = Double.parseDouble(stopTime);\r
+                            Double outInterval = Double.parseDouble(outputInterval);\r
+\r
+                            outIntervalInt = (int)getInterval(outInterval, step);\r
+                            // Actually you might be able to use an outInterval one or two longer. \r
+                            int maxIntervalInt = (int)Math.round(stop / step);\r
+                            if (outIntervalInt > maxIntervalInt)\r
+                                outIntervalInt = maxIntervalInt;\r
+                        }\r
+\r
+                        result.initRead(resFile);\r
+                        result.readTime(resFile, outIntervalInt);\r
+                        //result.readInits(simulationLocation.initFile); // Parameter values are read from .mat\r
+                        result.filter();\r
+                        \r
+                        MemoryResult currentResult = new MemoryResult(null, null);\r
+                        getCurrentResults().add(currentResult);\r
+                        currentResult.setResult(result);\r
+                        currentResult.setResultFile(resFile);\r
+                        currentResult.setResultIndex(currentRun);\r
+                        \r
+                        if(updateMonitors)\r
+                            resultsChanged();\r
+\r
+                        simulate(false);\r
+\r
+                        String errorString = result.getResultReadErrors();\r
+                        if(errorString != null && !errorString.isEmpty())\r
+                            monitor.message(errorString);\r
+                    }\r
+                } catch (FileNotFoundException e) {\r
+                    e.printStackTrace();\r
+                } catch (IOException e) {\r
+                    e.printStackTrace();\r
+                } catch (InterruptedException e) {\r
+                    e.printStackTrace();\r
+                }\r
+            }\r
+        };\r
+    }\r
+    \r
+    public ArrayList<MemoryResult> getCurrentResults() {\r
+        if(this.results == null) {\r
+            this.results = new ArrayList<MemoryResult>();\r
+        }\r
+        return this.results;\r
+    }\r
+    \r
+    @Override\r
+    public Collection<SysdynResult> getActiveResults() {\r
+        ArrayList<SysdynResult> result = new ArrayList<SysdynResult>();\r
+        result.addAll(getCurrentResults());\r
+        result.addAll(sysdynModel.getDisplayedResults());\r
+        return result;\r
+    }\r
+    \r
+    @Override\r
+    public MemoryResult getCurrentResult() {\r
+        if (this.results == null || this.results.size() < 1)\r
+            return null;\r
+        /* There should be a better alternative solution for this. Currently\r
+         * the return value is next to nonsense.\r
+         */\r
+        return this.results.get(0);\r
+    }\r
+    \r
+    @Override\r
+    public void resultsChanged() {\r
+        long time = System.nanoTime();\r
+        updateSubscriptions();\r
+        previousVariableUpdateTime = time;\r
+    }\r
+    \r
+    @Override\r
+    public void saveState() {\r
+        if(results == null || !(results instanceof ArrayList<?>)) \r
+            return;\r
+        SaveResultSetJob saveResultSetJob = new SaveResultSetJob((OldSysdynExperiment)this, session, results);\r
+        saveResultSetJob.schedule();\r
+    }\r
+    \r
+    @Override\r
+    public int numberOfSimulationRunSteps() {\r
+        try {\r
+            Integer numberOfIterations = session.syncRequest(new Read<Integer>() {\r
+                @Override\r
+                public Integer perform(ReadGraph graph) throws DatabaseException {\r
+                    SysdynResource SR = SysdynResource.getInstance(graph);\r
+                    Integer numberOfIterations = graph.getPossibleRelatedValue(experiment, SR.SensitivityAnalysisExperiment_numberOfValues, Bindings.INTEGER);\r
+                    \r
+                    return numberOfIterations;\r
+                }\r
+            });\r
+            \r
+            if(numberOfIterations == null)\r
+                numberOfIterations = 0;\r
+            \r
+            // 3 steps before sensitivity iterations\r
+            return 3 + numberOfIterations; \r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        return super.numberOfSimulationRunSteps();\r
+\r
+    }\r
+    \r
+    \r
+    @Override\r
+    public synchronized void simulate(IModelicaMonitor monitor, IProgressMonitor progressMonitor, String modelName) throws IOException {\r
+        \r
+        omcVersion = ModelicaManager.getDefaultOMVersion();\r
+\r
+        // Make sure that omc version is 1.9 or higher. \r
+        // Builtin version during this change is 1.9 beta 4\r
+        if(omcVersion != null) {\r
+            try {\r
+                double v = Double.parseDouble(omcVersion.substring(0, 3));\r
+                if(v < 1.9) {\r
+                    monitor.message("Error: Sensitivity analysis requires OMC version >= 1.9 \n" +\r
+                               "Current version is " + omcVersion +"\n" +\r
+                                               "Change version from Window->Preferences->Modelica");\r
+                    simulate(false);\r
+                    return;\r
+                }\r
+            } catch (NumberFormatException e) {}\r
+        }\r
+        \r
+        super.simulate(monitor, progressMonitor, modelName);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/VariableSubscriptionManager.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/VariableSubscriptionManager.java
new file mode 100644 (file)
index 0000000..d55010c
--- /dev/null
@@ -0,0 +1,16 @@
+package org.simantics.sysdyn.manager;\r
+\r
+import org.simantics.sysdyn.adapter.VariableValueSubscription;\r
+\r
+@SuppressWarnings("rawtypes") \r
+public interface VariableSubscriptionManager {\r
+       \r
+    public void addVariableValueSubscription(VariableValueSubscription subscription);\r
+    \r
+    public void removeVariableValueSubscription(VariableValueSubscription subscription);\r
+    \r
+    public VariableValueSubscription[] getListenerSnapshot();\r
+    \r
+    public void updateSubscriptions();\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/ExportConstants.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/ExportConstants.java
new file mode 100644 (file)
index 0000000..19695ff
--- /dev/null
@@ -0,0 +1,10 @@
+package org.simantics.sysdyn.modelExport;\r
+\r
+public class ExportConstants {\r
+\r
+    public static final String MODEL_FILE_EXTENSION = ".sysdyn";\r
+    public static final String CURRENT_MODEL_EXPORT_FORMAT = ".sysdyn";\r
+    public static final int CURRENT_MODEL_EXPORT_VERSION = 1;\r
+    //public static final int SMALLEST_MIGRATED_MODEL_EXPORT_VERSION = 0;\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/SysdynModelExporter.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelExport/SysdynModelExporter.java
new file mode 100644 (file)
index 0000000..333a654
--- /dev/null
@@ -0,0 +1,133 @@
+package org.simantics.sysdyn.modelExport;\r
+\r
+import gnu.trove.map.hash.THashMap;\r
+\r
+import java.io.File;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.text.DateFormat;\r
+import java.util.Date;\r
+import java.util.LinkedList;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import java.util.TreeMap;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.SubMonitor;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.UniqueRead;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.CopyHandler;\r
+import org.simantics.db.layer0.util.ClipboardUtils;\r
+import org.simantics.db.layer0.util.ModelDependenciesBean;\r
+import org.simantics.db.layer0.util.ModelDependency;\r
+import org.simantics.db.layer0.util.ModelTransferableGraphSource;\r
+import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
+import org.simantics.db.layer0.util.SimanticsClipboard.Representation;\r
+import org.simantics.db.layer0.util.SimanticsClipboardImpl;\r
+import org.simantics.db.layer0.util.SimanticsKeys;\r
+import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
+import org.simantics.graph.db.TransferableGraphs;\r
+import org.simantics.graph.representation.TransferableGraph1;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+\r
+public class SysdynModelExporter {\r
+\r
+    private SysdynModelExporter() {\r
+    }\r
+    \r
+    \r
+    public static void exportModel(IProgressMonitor monitor, final Resource model, File exportLocation, String description, boolean dependencies) throws InvocationTargetException {\r
+        try {\r
+            final SubMonitor mon = SubMonitor.convert(monitor, 100);\r
+            mon.beginTask("Exporting Sysdyn Model...", 100);\r
+            final Map<String, Variant> tgExtensions = new THashMap<String, Variant>();\r
+            Session session = Simantics.getSession();\r
+            if (dependencies) {\r
+                session.syncRequest(new ReadRequest() {\r
+                    \r
+                    @Override\r
+                    public void run(ReadGraph graph) throws DatabaseException {\r
+                        mon.setTaskName("Scanning model dependencies..");\r
+                        mon.worked(10);\r
+                        LinkedList<ModelDependency> modelDependencies = new LinkedList<ModelDependency>();\r
+                        scanDependencies(graph, model, modelDependencies);\r
+                        if (!modelDependencies.isEmpty())\r
+                            tgExtensions.put(ModelDependenciesBean.EXTENSION_KEY, new Variant(ModelDependenciesBean.BINDING, new ModelDependenciesBean(modelDependencies.toArray(new ModelDependency[modelDependencies.size()]))));\r
+                    }\r
+\r
+                    private void scanDependencies(ReadGraph graph, Resource resource, LinkedList<ModelDependency> modelDependencies) throws DatabaseException {\r
+                        Layer0 L0 = Layer0.getInstance(graph);\r
+                        ModelingResources MOD = ModelingResources.getInstance(graph);\r
+                        for(Resource library : graph.syncRequest(new ObjectsWithType(resource, L0.IsLinkedTo, MOD.SharedOntology))) {\r
+                            String uri = graph.getPossibleURI(library);\r
+                            if(uri == null) continue;\r
+                            CopyHandler ch = graph.adapt(library, CopyHandler.class);\r
+                            SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl();\r
+                            ch.copyToClipboard(graph, clipboard);\r
+                            for (Set<Representation> object : clipboard.getContents()) {\r
+                                TransferableGraph1 tg = ClipboardUtils.accept(graph, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH);\r
+                                if(tg != null) modelDependencies.addFirst(new ModelDependency(uri, tg));\r
+                            }\r
+                            scanDependencies(graph, library, modelDependencies);\r
+                        }\r
+                    }\r
+                });\r
+            }\r
+            \r
+            mon.setTaskName("Creating transferable graph source...");\r
+            mon.worked(10);\r
+            ModelTransferableGraphSource source = session.sync(new UniqueRead<ModelTransferableGraphSource>() {\r
+                @Override\r
+                public ModelTransferableGraphSource perform(ReadGraph graph) throws DatabaseException {\r
+                    mon.worked(10);\r
+                    TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model);\r
+                    mon.worked(10);\r
+                    if (!tgExtensions.isEmpty())\r
+                        conf.baseExtensions.putAll(tgExtensions);\r
+                    mon.worked(10);\r
+                    return new ModelTransferableGraphSourceRequest(conf).perform(graph);\r
+                }\r
+            });\r
+            \r
+            mon.worked(10);\r
+            mon.setTaskName("Writing metadata...");\r
+            TreeMap<String,Variant> metadata = getModelExportMetadata(description);\r
+            mon.worked(10);\r
+            mon.setTaskName("Writing transferable graph...");\r
+            \r
+            try {\r
+                TransferableGraphs.writeTransferableGraph(session, \r
+                        ExportConstants.CURRENT_MODEL_EXPORT_FORMAT, ExportConstants.CURRENT_MODEL_EXPORT_VERSION, metadata, source, exportLocation);\r
+                mon.worked(20);\r
+                source.closeStreams();\r
+            } catch (Exception e) {\r
+                throw new InvocationTargetException(e);\r
+            }\r
+\r
+            for(File f : source.getFiles())\r
+                f.delete();\r
+            \r
+            mon.worked(10);\r
+            mon.setTaskName("Done!");\r
+        } catch (DatabaseException e) {\r
+            throw new InvocationTargetException(e);\r
+        }\r
+    }\r
+\r
+\r
+    private static TreeMap<String, Variant> getModelExportMetadata(String description) {\r
+        TreeMap<String,Variant> metadata = new TreeMap<String,Variant>();\r
+        metadata.put("date", Variant.ofInstance(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())));\r
+        metadata.put("author", Variant.ofInstance(System.getProperty("user.name", "")));\r
+        metadata.put("description", Variant.ofInstance(description));\r
+        \r
+        return metadata;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlParser.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlParser.java
new file mode 100644 (file)
index 0000000..25c77c0
--- /dev/null
@@ -0,0 +1,324 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.modelImport;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.InputStreamReader;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.mdl.Declaration;\r
+import org.simantics.sysdyn.modelImport.mdl.Lookup;\r
+import org.simantics.sysdyn.modelImport.mdl.MdlModel;\r
+import org.simantics.sysdyn.modelImport.mdl.Sketch;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchComment;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchConnection;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchObject;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchValve;\r
+import org.simantics.sysdyn.modelImport.mdl.SketchVariable;\r
+import org.simantics.sysdyn.modelImport.mdl.Subscript;\r
+import org.simantics.sysdyn.modelImport.mdl.SubscriptVariable;\r
+import org.simantics.sysdyn.modelImport.mdl.MdlVariable;\r
+import org.simantics.sysdyn.modelImport.model.Comment;\r
+import org.simantics.sysdyn.modelImport.model.Connection;\r
+import org.simantics.sysdyn.modelImport.model.Model;\r
+import org.simantics.sysdyn.modelImport.model.Variable;\r
+import org.simantics.sysdyn.modelImport.model.Shadow;\r
+import org.simantics.sysdyn.modelImport.model.Symbol;\r
+import org.simantics.sysdyn.modelImport.model.Valve;\r
+\r
+public class MdlParser {\r
+       \r
+       private static final String UTF_8 = "{UTF-8}";\r
+       private static final String SKETCH_VERSION = "V300";\r
+       private static final String SKETCH_START = "\\\\\\---///";\r
+       private static final String SKETCH_END = "///---\\\\\\";\r
+       \r
+       private static final String PARAMETER_START = "INITIAL TIME";\r
+       private static final String PARAMETER_STOP = "FINAL TIME";\r
+       private static final String PARAMETER_STEP = "TIME STEP";\r
+\r
+       public static Model parse(File file) throws Exception {\r
+               // generate a mdl model based on the contents of the file\r
+               MdlModel mdl = parseFile(file);\r
+               \r
+               // generate a sysdyn model from the mdl model\r
+               Model model = new Model(mdl.getName());\r
+\r
+               // add (necessary) enumerations\r
+               for (Subscript subscript : mdl.getAllSubscripts()) {\r
+                       if (!subscript.isEquivalent())\r
+                               model.addEnumeration(subscript.getEnumeration());\r
+               }\r
+               \r
+               // add lookup functions\r
+               for (Lookup lookup : mdl.getAllLookups()) {\r
+                       model.addFunction(lookup.getFunction());\r
+               }\r
+               \r
+               int offset = 0;\r
+               \r
+               // add sketch labels and independent elements\r
+               for (Sketch sketch : mdl.getSketches()) {\r
+                       \r
+                       // add the sketch label to the diagram for the sake of clarity\r
+                       model.addSymbol(new Comment(\r
+                                       MdlUtil.getSysdynDimensions(offset, 0, -1, -1), \r
+                                       "=== VENSIM SKETCH: "+sketch.getName()+" ======>"));\r
+                       sketch.setLocation(offset, 20);\r
+                       \r
+                       for (SketchComment comment : sketch.getComments()) {\r
+                               Symbol symbol = comment.getSymbol();\r
+                               if (symbol != null) {\r
+                                       comment.setModelObject(symbol);\r
+                                       model.addSymbol(symbol);\r
+                               }\r
+                       }\r
+                       \r
+                       for (SketchValve valve : sketch.getValves()) {\r
+                               Valve symbol = valve.getSymbol();\r
+                               if (symbol != null) {\r
+                                       valve.setModelObject(symbol);\r
+                                       model.addVariable(symbol);\r
+                               }\r
+                       }\r
+                       \r
+                       for (SketchVariable variable : sketch.getNonShadowVariables()) {\r
+                               Variable symbol = variable.getSymbol();\r
+                               if (symbol != null) {\r
+                                       variable.setModelObject(symbol);\r
+                                       model.addVariable(symbol);\r
+                               }\r
+                       }\r
+                       \r
+                       offset += sketch.getWidth();\r
+               }\r
+               \r
+               // add dependent elements\r
+               for (Sketch sketch : mdl.getSketches()) {\r
+                       for (SketchVariable variable : sketch.getShadowVariables()) {\r
+                               Variable original = model.getVariable(variable.getName());\r
+                               if (original != null) {\r
+                                       // create a shadow variable if the original variable exists\r
+                                       Shadow symbol = new Shadow(variable.getDimensions(), original);\r
+                                       variable.setModelObject(symbol);\r
+                                       model.addShadow(symbol);\r
+                               }\r
+                               else {\r
+                                       // create a new original variable instead of a shadow variable if\r
+                                       // the original variable does not exist\r
+                                       Variable symbol = variable.getSymbol();\r
+                                       if (symbol != null) {\r
+                                               variable.setModelObject(symbol);\r
+                                               model.addVariable(symbol);\r
+                                       }\r
+                               }\r
+                       }\r
+\r
+                       for (SketchConnection connection : sketch.getConnections()) {\r
+                               Connection conn = connection.getConnection();\r
+                               if (conn != null) {\r
+                                       connection.setModelObject(conn);\r
+                                       model.addConnection(conn);\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               // Set simulation parameters\r
+               MdlVariable start = mdl.getVariable(PARAMETER_START);\r
+               if (start != null && Pattern.matches(MdlUtil.DBL, start.getExpressionString()))\r
+                       model.setStartTime(Double.parseDouble(start.getExpressionString()));\r
+               \r
+               MdlVariable stop = mdl.getVariable(PARAMETER_STOP);\r
+               if (stop != null && Pattern.matches(MdlUtil.DBL, stop.getExpressionString()))\r
+                       model.setStopTime(Double.parseDouble(stop.getExpressionString()));\r
+               \r
+               MdlVariable step = mdl.getVariable(PARAMETER_STEP);\r
+               if (step != null && Pattern.matches(MdlUtil.DBL, step.getExpressionString())) {\r
+                       model.setTimeStep(Double.parseDouble(step.getExpressionString()));\r
+                       // TODO: for some reason sysdyn only accepts certain time units\r
+                       // so this most definitely does not work in all cases\r
+                       String unit = step.getUnit();\r
+                       if (unit.contains("[")) {\r
+                               unit = unit.substring(0, unit.indexOf('[')).trim();\r
+                       }\r
+                       model.setTimeUnit(unit.toLowerCase());\r
+               }\r
+               \r
+               \r
+               // TODO: unit and result step thingamajig\r
+               \r
+               return model;\r
+       }\r
+       \r
+       private static MdlModel parseFile(File file) throws Exception {\r
+               // strip the file suffix from file name\r
+               String name = file.getName();\r
+               if (file.getName().contains(".")) {\r
+                       name = name.substring(0, name.indexOf('.'));\r
+               }\r
+               \r
+               MdlModel mdl = new MdlModel(name);\r
+               \r
+               // peek at the first line to see if we need to use UTF-8\r
+               BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));\r
+               String line = reader.readLine();\r
+\r
+               if (line == null) {\r
+                       // file is empty, nothing to do here\r
+                       reader.close();\r
+                       return null;\r
+               }\r
+\r
+               if (line.startsWith(UTF_8)) {\r
+                       reader.close();\r
+                       reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));\r
+                       // skip the first line\r
+                       reader.readLine();\r
+                       line = reader.readLine();\r
+               }\r
+\r
+               // START READING VARIABLE DATA\r
+\r
+               // keep track of the current category\r
+               String category = null;\r
+\r
+               do {\r
+                       // skip empty lines\r
+                       if (line.isEmpty()) \r
+                               continue;\r
+\r
+                       // combine the (possible) variable declaration into one line    \r
+                       StringBuilder buffer = new StringBuilder();\r
+                       do {\r
+                               // strip leading whitespace if present\r
+                               line = line.replaceFirst("^\\s*", "");\r
+                               // strip trailing '\' if present\r
+                               line = line.replaceFirst("\\\\$", "");\r
+                               \r
+                               buffer.append(line);\r
+                               \r
+                               // each variable declaration ends with '|'\r
+                               if (line.endsWith("|"))\r
+                                       break;\r
+                       } while ((line = reader.readLine()) != null);\r
+                       String str = buffer.toString();\r
+\r
+                       String cat;\r
+                       Declaration decl;\r
+                       \r
+                       // parse the (possible) variable declaration\r
+                       if ((cat = Declaration.parseCategory(str)) != null) {\r
+                               category = cat;\r
+                       }\r
+                       else if ((decl = MdlVariable.getPossible(str, mdl)) != null) {\r
+                               mdl.addVariable((MdlVariable)decl, category);\r
+                       }\r
+                       else if ((decl = SubscriptVariable.getPossible(str, mdl)) != null) {\r
+                               mdl.addSubscriptVariable((SubscriptVariable)decl, category);\r
+                       }\r
+                       else if ((decl = Lookup.getPossible(str, mdl)) != null) {\r
+                               mdl.addLookup((Lookup)decl);\r
+                       }\r
+                       else if ((decl = Subscript.getPossible(str, mdl)) != null) {\r
+                               mdl.addSubscript((Subscript)decl);\r
+                       }\r
+                       else {\r
+                               // if we got this far, the variable could not be parsed\r
+                               throw new Exception("unrecognized variable "+str);\r
+                       }\r
+\r
+               } while ((line = reader.readLine()) != null && !line.startsWith(SKETCH_START));\r
+\r
+               // END READING VARIABLE DATA\r
+\r
+               if (line == null) {\r
+                       throw new Exception("unexpected end of file");\r
+               }\r
+\r
+               // START READING SKETCH DATA\r
+\r
+               // keep track of the current sketch\r
+               Sketch sketch = null;\r
+\r
+               do {\r
+                       // skip empty lines\r
+                       if (line.isEmpty())\r
+                               continue;\r
+                       \r
+                       SketchObject so;\r
+\r
+                       if (line.startsWith(SKETCH_START)) {\r
+                               sketch = new Sketch(mdl);\r
+                               mdl.addSketch(sketch);\r
+                       }\r
+                       else if (line.startsWith(SKETCH_VERSION)) {\r
+                               // version declaration, nothing to do here\r
+                       }\r
+                       else if (line.startsWith("*")) {\r
+                               sketch.setName(line.substring(1));\r
+                       }\r
+                       else if (line.startsWith("$")) {\r
+                               // font declaration, nothing to do here\r
+                       }\r
+                       else if ((so = SketchConnection.getPossible(line, sketch)) != null) {\r
+                               sketch.addConnection((SketchConnection)so);\r
+                       }\r
+                       else if ((so = SketchVariable.getPossible(line, sketch)) != null) {\r
+                               sketch.addVariable((SketchVariable)so);\r
+                       }\r
+                       else if ((so = SketchValve.getPossible(line, sketch)) != null) {\r
+                               SketchValve valve = (SketchValve)so;\r
+                               // the next row after a valve should always the variable associated with the valve\r
+                               SketchVariable attached = SketchVariable.getPossible(reader.readLine(), sketch);\r
+                               if (attached == null || !attached.isAttached()) {\r
+                                       throw new Exception("attached variable not found for valve");\r
+                               }\r
+                               valve.setAttached(attached);\r
+                               sketch.addValve(valve);\r
+                       }\r
+                       else if ((so = SketchComment.getPossible(line, sketch)) != null) {\r
+                               SketchComment comment = (SketchComment)so;\r
+                               if (comment.hasTextLine()) {\r
+                                       comment.setText(reader.readLine());\r
+                               }\r
+                               // do not add i/o objects to the sketch currently\r
+                               if (!comment.isInputOutput())\r
+                                       sketch.addComment(comment);\r
+                       }\r
+                       else {\r
+                               // if we got this far, the element could not be parsed\r
+                               throw new Exception("unrecognized element "+line);\r
+                       }\r
+\r
+               } while ((line = reader.readLine()) != null && !line.startsWith(SKETCH_END));\r
+\r
+               // END READING SKETCH DATA\r
+\r
+               if (line == null) {\r
+                       throw new Exception("unexpected end of file");\r
+               }\r
+\r
+               // START READING OTHER DATA\r
+\r
+               do {\r
+                       // TODO: is there anything relevant here?\r
+               } while ((line = reader.readLine()) != null);\r
+\r
+               // END READING OTHER DATA\r
+\r
+               reader.close();\r
+               return mdl;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlUtil.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/MdlUtil.java
new file mode 100644 (file)
index 0000000..980948d
--- /dev/null
@@ -0,0 +1,310 @@
+package org.simantics.sysdyn.modelImport;\r
+\r
+import java.util.List;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.mdl.Lookup;\r
+import org.simantics.sysdyn.modelImport.mdl.MdlModel;\r
+\r
+public class MdlUtil {\r
+       \r
+       // multiplier for dimension conversion between vensim and sysdyn\r
+       private static final double SCALE_MULTIPLIER = 0.45;\r
+\r
+       // most of this is based on the documentation of the .mdl file format \r
+       // available in http://www.vensim.com/documentation/24305.htm\r
+\r
+       // some regular expressions that are used commonly in the parser\r
+       public static final String DBL = "[+-]?(?:NaN|Infinity|\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)";\r
+       public static final String DBL_G = "("+DBL+")";\r
+       public static final String INT = "[+-]?\\d+";\r
+       public static final String INT_G = "("+INT+")";\r
+\r
+       // matches a basic vensim name (starts with a letter, may contain any word \r
+       // characters and white space)\r
+       public static final String BASIC_NAME =\r
+                       "[A-Za-z]\\w*(?:\\s+\\w+)*";\r
+       // matches a special vensim name (starts and ends with a quotation mark, \r
+       // may contain escaped special characters)\r
+       public static final String SPECIAL_NAME =\r
+                       "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"";\r
+\r
+       // matches a vensim variable (either basic name or special name)\r
+       public static final String VARIABLE =\r
+                       "("+BASIC_NAME+"|"+SPECIAL_NAME+")";\r
+       // matches a vensim variable inside an expression (basic name not followed \r
+       // by an open parenthesis or a special name)\r
+       public static final String VARIABLE_EXPRESSION =\r
+                       "([A-Za-z](?![\\s\\w]*\\()\\w*(?:\\s+\\w+)*|"+SPECIAL_NAME+")";\r
+       // matches a vensim subscript variable (basic name with a list of indices)\r
+       public static final String SUBSCRIPT =\r
+                       "("+BASIC_NAME+")\\[("+BASIC_NAME+"\\!?(?:,"+BASIC_NAME+"\\!?)*)\\]";\r
+       // matches a vensim function (basic name followed by an open parenthesis)\r
+       public static final String FUNCTION =\r
+                       "("+BASIC_NAME+")\\s*\\(";\r
+\r
+       public static String normalize(String str) {\r
+               // start by removing all tabs from the string, not really necessary \r
+               // but does make the equation cleaner\r
+               str = str.replaceAll("\t", "");\r
+\r
+               // normalize functions\r
+               str = normalizeFunctions(str);\r
+               // normalize variables\r
+               str = normalizeVariables(str);\r
+\r
+               // replace inline operations\r
+               str = str.replaceAll(":AND:", " and ");\r
+               str = str.replaceAll(":OR:", " or ");\r
+               \r
+               // foo^-bar does not work in Modelica, it needs to be changed to foo^(-bar)\r
+               str = addParenthesesToExponents(str);\r
+               \r
+               // NOTE: something like this must be done to replace Vensim comparison \r
+               // "=" with Modelica comparison "==" but this solution breaks geq and leq\r
+               //str = str.replaceAll("=", "==");\r
+\r
+               return str;\r
+       }\r
+\r
+       private static String normalizeVariables(String expression) {\r
+               StringBuilder result = new StringBuilder();\r
+               int offset = 0;\r
+\r
+               Matcher matcher = Pattern.compile(VARIABLE_EXPRESSION).matcher(expression);\r
+               while (matcher.find()) {\r
+                       result.append(expression.substring(offset, matcher.start()));\r
+\r
+                       String variable = matcher.group(1);\r
+\r
+                       // TODO: fix this after proper support for quoted variable names\r
+                       // is implemented\r
+                       \r
+                       if (variable.equalsIgnoreCase("time")) {\r
+                               // replace all references to simulation time with references\r
+                               // to the special purpose time variable\r
+                               result.append("time");\r
+                       }\r
+                       else if (variable.startsWith("\"") && variable.endsWith("\"")) {\r
+                               // replace double quotes with single quotes in quoted variable\r
+                               // names as per modelica syntax (currently useless and might \r
+                               // actually break something)\r
+                               result.append('\'');\r
+                               result.append(variable.substring(1, variable.length() - 1));\r
+                               result.append('\'');\r
+                       }\r
+                       else {\r
+                               // in all other cases, manipulate variable names slightly to \r
+                               // make them conform to Modelica syntax (the proper way to do \r
+                               // this would be to simply quote problematic variable names \r
+                               // but quoted variable names are currently broken in sysdyn so \r
+                               // that is not an option)\r
+                               \r
+                               // capitalize each part of the variable name to prevent \r
+                               // collisions with reserved keywords (e.g. "public")\r
+                               String[] parts = variable.split("\\s+");\r
+                               for (int i = 0; i < parts.length; i++) {\r
+                                       // a part of a variable name can not start with a number so\r
+                                       // concatenate the parts if this is the case\r
+                                       if (i > 0 && !Character.isDigit(parts[i].charAt(0)))\r
+                                               result.append(' ');\r
+                                       result.append(parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1));\r
+                               }\r
+                       }\r
+\r
+                       offset = matcher.end();\r
+               }\r
+               if (offset < expression.length()) {\r
+                       result.append(expression.substring(offset));\r
+               }\r
+\r
+               return result.toString();\r
+       }\r
+\r
+       private static String normalizeFunctions(String expression) {\r
+               StringBuilder result = new StringBuilder();\r
+               int offset = 0;\r
+\r
+               Matcher matcher = Pattern.compile(FUNCTION).matcher(expression);\r
+               while (matcher.find()) {\r
+                       result.append(expression.substring(offset, matcher.start()));\r
+\r
+                       String function = matcher.group(1);\r
+\r
+                       if (function.equalsIgnoreCase("sum")) {\r
+                               // vensim "sum" is similar to modelica "sum" if operations \r
+                               // are replaced with dot-operations (e.g. * with .*) inside\r
+                               // the parameters\r
+                               result.append("sum(");\r
+                               int closing = expression.indexOf(')', matcher.end());\r
+                               String parameters = expression.substring(matcher.end(), closing);\r
+                               parameters = parameters.replaceAll("\\*", ".*");\r
+                               parameters = parameters.replaceAll("/", "./");\r
+                               parameters = parameters.replaceAll("\\+", ".+");\r
+                               parameters = parameters.replaceAll("-", ".-");\r
+                               result.append(parameters);\r
+                               offset = closing;\r
+                       }\r
+                       else if (function.equalsIgnoreCase("if then else")) {\r
+                               result.append("IFTHENELSE(");\r
+                               offset = matcher.end();\r
+                       }\r
+                       else {\r
+                               // this will also capitalize lookups, is this ok?\r
+                               result.append(function.toUpperCase()+"(");\r
+                               offset = matcher.end();\r
+                       }\r
+               }\r
+               if (offset < expression.length()) {\r
+                       result.append(expression.substring(offset));\r
+               }\r
+\r
+               return result.toString();\r
+       }\r
+       \r
+       private static String addParenthesesToExponents(String expression) {\r
+               if (!expression.contains("^")) {\r
+                       return expression;\r
+               }\r
+               \r
+               StringBuilder result = new StringBuilder();\r
+               int offset = 0;\r
+               \r
+               Matcher matcher = Pattern.compile("\\^\\s*-\\s*"+VARIABLE_EXPRESSION).matcher(expression);\r
+               while (matcher.find()) {\r
+                       result.append(expression.substring(offset, matcher.start()));\r
+                       \r
+                       result.append("^(-").append(matcher.group(1)).append(")");\r
+                       \r
+                       offset = matcher.end();\r
+               }\r
+               if (offset < expression.length()) {\r
+                       result.append(expression.substring(offset));\r
+               }\r
+\r
+               return result.toString();\r
+       }\r
+\r
+       public static String finalize(String expression, MdlModel mdl) {\r
+               expression = expandIterations(expression, mdl);\r
+               expression = renameLookups(expression, mdl);\r
+\r
+               return expression;\r
+       }\r
+\r
+       private static String expandIterations(String expression, MdlModel mdl) {\r
+               StringBuilder result = new StringBuilder();\r
+               int offset = 0;\r
+\r
+               Matcher matcher = Pattern.compile(SUBSCRIPT).matcher(expression);\r
+               while (matcher.find()) {\r
+                       result.append(expression.substring(offset, matcher.start()));\r
+\r
+                       String name = matcher.group(1);\r
+                       String[] indices = matcher.group(2).split(",");\r
+\r
+                       result.append(name);\r
+\r
+                       result.append('[');\r
+                       for (int i = 0; i < indices.length; i++) {\r
+                               if (i > 0)\r
+                                       result.append(',');\r
+\r
+                               if (indices[i].endsWith("!")) {\r
+                                       String subscript = indices[i].substring(0, indices[i].length() - 1);\r
+                                       List<String> values = mdl.getSubscript(subscript).getValues();\r
+                                       result.append('{');\r
+                                       for (int j = 0; j < values.size(); j++) {\r
+                                               if (j > 0)\r
+                                                       result.append(',');\r
+                                               result.append(values.get(j));\r
+                                       }\r
+                                       result.append('}');\r
+                               }\r
+                               else {\r
+                                       result.append(indices[i]);\r
+                               }\r
+                       }\r
+                       result.append(']');\r
+\r
+                       offset = matcher.end();\r
+               }\r
+               if (offset < expression.length()) {\r
+                       result.append(expression.substring(offset));\r
+               }\r
+\r
+               return result.toString();\r
+       }\r
+\r
+       private static String renameLookups(String expression, MdlModel mdl) {\r
+               StringBuilder result = new StringBuilder();\r
+               int offset = 0;\r
+\r
+               Matcher matcher = Pattern.compile(FUNCTION).matcher(expression);\r
+               while (matcher.find()) {\r
+                       result.append(expression.substring(offset, matcher.start()));\r
+\r
+                       String name = matcher.group(1);\r
+\r
+                       Lookup potential = mdl.getLookup(name);\r
+\r
+                       if (potential != null) {\r
+                               name = name.replaceAll("\\s+", "");\r
+                       }\r
+\r
+                       result.append(name+"(");\r
+                       offset = matcher.end();\r
+               }\r
+               if (offset < expression.length()) {\r
+                       result.append(expression.substring(offset));\r
+               }\r
+\r
+               return result.toString();\r
+       }\r
+\r
+       public static String replaceSubscripts(String expression, String subscript, String replacement) {\r
+               StringBuilder result = new StringBuilder();\r
+               int offset = 0;\r
+\r
+               Matcher matcher = Pattern.compile(SUBSCRIPT).matcher(expression);\r
+               while (matcher.find()) {\r
+                       result.append(expression.substring(offset, matcher.start()));\r
+\r
+                       String name = matcher.group(1);\r
+                       String[] indices = matcher.group(2).split(",");\r
+\r
+                       result.append(name);\r
+\r
+                       result.append('[');\r
+                       for (int i = 0; i < indices.length; i++) {\r
+                               if (i > 0)\r
+                                       result.append(',');\r
+\r
+                               if (indices[i].equals(subscript)) {\r
+                                       result.append(replacement);\r
+                               }\r
+                               else {\r
+                                       result.append(indices[i]);\r
+                               }\r
+                       }\r
+                       result.append(']');\r
+\r
+                       offset = matcher.end();\r
+               }\r
+               if (offset < expression.length()) {\r
+                       result.append(expression.substring(offset));\r
+               }\r
+\r
+               return result.toString();\r
+       }\r
+       \r
+       public static double[] getSysdynDimensions(int x, int y, int width, int height) {\r
+               return new double[] {\r
+                               x * SCALE_MULTIPLIER,\r
+                               y * SCALE_MULTIPLIER,\r
+                               width * SCALE_MULTIPLIER,\r
+                               height * SCALE_MULTIPLIER\r
+               };\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Declaration.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Declaration.java
new file mode 100644 (file)
index 0000000..4282a6d
--- /dev/null
@@ -0,0 +1,65 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+public abstract class Declaration {\r
+\r
+       private static final String CATEGORY = "\\*{56}\\s*\\.(.+)\\s*\\*{56}.*";\r
+       \r
+       protected static final String DECL_DELIM = "\\s*~\\s*";\r
+       protected static final String DECL_END = "\\s*\\|";\r
+       protected static final String DECL_UNIT = "([^~]*?)";\r
+       protected static final String DECL_DESC = "([^\\|]*?)";\r
+\r
+       protected static final String DECL_SUFFIX = \r
+                       DECL_DELIM + DECL_UNIT + DECL_DELIM + DECL_DESC + DECL_END;\r
+       protected static final int declarationUnit = 1;\r
+       protected static final int declarationDescription = 2;\r
+       \r
+       private String name;\r
+       private MdlModel mdl;\r
+       \r
+       private String unit;\r
+       private String description;\r
+       \r
+       protected Declaration(String name, MdlModel mdl) {\r
+               this.name = name;\r
+               this.mdl = mdl;\r
+       }\r
+       \r
+       protected void parseSuffix(String suffix) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(DECL_SUFFIX).matcher(suffix);\r
+               if (!matcher.matches()) {\r
+                       // this should not happen unless subclasses fail to construct their\r
+                       // regular expressions properly\r
+                       throw new Exception("could not parse declaration suffix "+suffix);\r
+               }\r
+               \r
+               unit = matcher.group(declarationUnit);\r
+               description = matcher.group(declarationDescription);\r
+       }\r
+       \r
+       public String getName() {\r
+               return name;\r
+       }\r
+       \r
+       public MdlModel getMdl() {\r
+               return mdl;\r
+       }\r
+       \r
+       public String getUnit() {\r
+               return unit;\r
+       }\r
+       \r
+       public String getDescription() {\r
+               return description;\r
+       }\r
+\r
+       public static String parseCategory(String line) {\r
+               Matcher matcher = Pattern.compile(CATEGORY).matcher(line);\r
+               return matcher.matches() ? matcher.group(1).trim() : null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Lookup.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Lookup.java
new file mode 100644 (file)
index 0000000..cf0ff89
--- /dev/null
@@ -0,0 +1,125 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.support.Function;\r
+\r
+public class Lookup extends Declaration {\r
+       \r
+       private static final String LOOKUP_RANGE =\r
+                       "\\[\\("+MdlUtil.DBL_G+","+MdlUtil.DBL_G+"\\)-\\("+MdlUtil.DBL_G+","+MdlUtil.DBL_G+"\\)\\]";\r
+       private static final String LOOKUP_POINTS =\r
+                       "(\\("+MdlUtil.DBL+","+MdlUtil.DBL+"\\)(?:,\\("+MdlUtil.DBL+","+MdlUtil.DBL+"\\))*)";\r
+       private static final String LOOKUP =\r
+                       "("+MdlUtil.BASIC_NAME+")\\s*\\(\\s*"+LOOKUP_RANGE+","+LOOKUP_POINTS+"\\s*\\)";\r
+       \r
+       private static final String LOOKUP_DECL = \r
+                       LOOKUP+"("+DECL_SUFFIX+")";\r
+       private static final int lookupName = 1;\r
+       private static final int lookupRangeXMin = 2;\r
+       private static final int lookupRangeYMin = 3;\r
+       private static final int lookupRangeXMax = 4;\r
+       private static final int lookupRangeYMax = 5;\r
+       private static final int lookupPoints = 6;\r
+       private static final int lookupSuffix = 7;\r
+       \r
+       private double xMin;\r
+       private double yMin;\r
+       private double xMax;\r
+       private double yMax;\r
+       private double[] points;\r
+       \r
+       private Function function;\r
+       \r
+       protected Lookup(String name, MdlModel mdl, \r
+                       double xMin, double yMin, double xMax, double yMax, \r
+                       double[] points) {\r
+               super(name, mdl);\r
+               this.xMin = xMin;\r
+               this.yMin = yMin;\r
+               this.xMax = xMax;\r
+               this.yMax = yMax;\r
+               this.points = points;\r
+       }\r
+       \r
+       public static Lookup getPossible(String line, MdlModel mdl) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(LOOKUP_DECL).matcher(line);\r
+               if (!matcher.matches()) {\r
+                       return null;\r
+               }\r
+               \r
+               String name = matcher.group(lookupName).toUpperCase();\r
+               double xMin = Double.parseDouble(matcher.group(lookupRangeXMin));\r
+               double yMin = Double.parseDouble(matcher.group(lookupRangeYMin));\r
+               double xMax = Double.parseDouble(matcher.group(lookupRangeXMax));\r
+               double yMax = Double.parseDouble(matcher.group(lookupRangeYMax));\r
+               double[] points = parsePoints(matcher.group(lookupPoints));\r
+               \r
+               Lookup lookup = new Lookup(name, mdl, xMin, yMin, xMax, yMax, points);\r
+               lookup.parseSuffix(matcher.group(lookupSuffix));\r
+               return lookup;\r
+       }\r
+       \r
+       private static double[] parsePoints(String str) {\r
+               // a hack to remove the leading empty string otherwise produced by split()\r
+               str = str.replaceFirst("[(),]+", "");\r
+               String[] parts = str.split("[(),]+");\r
+               double[] points = new double[parts.length];\r
+               for (int i = 0; i < parts.length; i++) {\r
+                       points[i] = Double.parseDouble(parts[i]);\r
+               }\r
+               return points;\r
+       }\r
+\r
+       public double getxMin() {\r
+               return xMin;\r
+       }\r
+\r
+       public double getyMin() {\r
+               return yMin;\r
+       }\r
+\r
+       public double getxMax() {\r
+               return xMax;\r
+       }\r
+\r
+       public double getyMax() {\r
+               return yMax;\r
+       }\r
+       \r
+       public double[] getPoints() {\r
+               return points;\r
+       }\r
+       \r
+       public Function getFunction() {\r
+               if (function != null) {\r
+                       return function;\r
+               }\r
+               \r
+               StringBuilder body = new StringBuilder();\r
+               \r
+               // one input, one output\r
+               body.append("input Real i;\n");\r
+               body.append("output Real o;\n");\r
+               \r
+               // interpolate over the set of points\r
+               body.append("algorithm\n");\r
+               \r
+               body.append("o := interpolate(i, {");\r
+               for (int i = 0; i < points.length/2; i++) {\r
+                       if (i > 0) {\r
+                               body.append(',');\r
+                       }\r
+                       body.append('{').append(points[2*i]).append(',').append(points[2*i+1]).append('}');\r
+               }\r
+               body.append("});\n");\r
+               \r
+               function = new Function(getName().replaceAll("\\s+", ""), body.toString());\r
+               \r
+               return function;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/MdlModel.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/MdlModel.java
new file mode 100644 (file)
index 0000000..fba97c5
--- /dev/null
@@ -0,0 +1,141 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+public class MdlModel {\r
+       \r
+       private String name;\r
+       \r
+       private Map<String, MdlVariable> variables;\r
+       private Map<String, ArrayList<MdlVariable>> groups;\r
+       private Map<String, Lookup> lookups;\r
+       private Map<String, Subscript> subscripts;\r
+       private List<Sketch> sketches;\r
+       \r
+       public MdlModel(String name) {\r
+               this.name = name;\r
+               \r
+               this.variables = new HashMap<String, MdlVariable>();\r
+               this.groups = new HashMap<String, ArrayList<MdlVariable>>();\r
+               this.lookups = new HashMap<String, Lookup>();\r
+               this.subscripts = new HashMap<String, Subscript>();\r
+               this.sketches = new ArrayList<Sketch>();\r
+       }\r
+       \r
+       public String getName() {\r
+               return name;\r
+       }\r
+       \r
+       public void addVariable(MdlVariable variable, String group) \r
+                       throws Exception {\r
+               if (variables.get(variable.getName()) != null) {\r
+                       throw new Exception("duplicate variable "+variable.getName());\r
+               }\r
+               \r
+               variables.put(variable.getName(), variable);\r
+               \r
+               if (group != null) {\r
+                       if (groups.get(group) == null) {\r
+                               groups.put(group, new ArrayList<MdlVariable>());\r
+                       }\r
+                       groups.get(group).add(variable);\r
+               }\r
+       }\r
+       \r
+       public void addSubscriptVariable(SubscriptVariable variable, String group) \r
+                       throws Exception {\r
+               MdlVariable original = variables.get(variable.getName());\r
+               if (original != null) {\r
+                       if (!(original instanceof SubscriptVariable)) {\r
+                               throw new Exception("incompatible type for variable "+variable.getName());\r
+                       }\r
+                       ((SubscriptVariable)original).addSubscriptVariable(variable);\r
+               }\r
+               else {\r
+                       addVariable(variable, group);\r
+               }\r
+       }\r
+       \r
+       public MdlVariable getVariable(String name) {\r
+               return variables.get(name);\r
+       }\r
+       \r
+       public Set<MdlVariable> getAllVariables() {\r
+               return new HashSet<MdlVariable>(variables.values());\r
+       }\r
+       \r
+       public void addLookup(Lookup lookup) \r
+                       throws Exception {\r
+               if (lookups.get(lookup.getName()) != null) {\r
+                       throw new Exception("duplicate lookup "+lookup.getName());\r
+               }\r
+               \r
+               lookups.put(lookup.getName(), lookup);\r
+       }\r
+       \r
+       public Lookup getLookup(String name) {\r
+               return lookups.get(name);\r
+       }\r
+       \r
+       public Set<Lookup> getAllLookups() {\r
+               return new HashSet<Lookup>(lookups.values());\r
+       }\r
+       \r
+       public void addSubscript(Subscript subscript) \r
+                       throws Exception {\r
+               if (subscripts.get(subscript.getName()) != null) {\r
+                       throw new Exception("duplicate subscript "+subscript.getName());\r
+               }\r
+               \r
+               subscripts.put(subscript.getName(), subscript);\r
+       }\r
+       \r
+       public Subscript getSubscript(String name) {\r
+               return subscripts.get(name);\r
+       }\r
+       \r
+       public Set<Subscript> getAllSubscripts() {\r
+               return new HashSet<Subscript>(subscripts.values());\r
+       }\r
+       \r
+       public Subscript resolveSubscript(Set<String> values) {\r
+               // if a value is actually a subscript, expand it to its values\r
+               Set<String> all = new HashSet<String>();\r
+               for (String value : values) {\r
+                       Subscript potential = subscripts.get(value);\r
+                       if (potential != null) {\r
+                               all.addAll(potential.getValues());\r
+                       }\r
+                       else {\r
+                               all.add(value);\r
+                       }\r
+               }\r
+               \r
+               // find the subscript that contains exactly the given set of values.\r
+               // only consider original subscripts (ignore equivalent subscripts)\r
+               for (Subscript subscript : getAllSubscripts()) {\r
+                       if (!subscript.isEquivalent() && \r
+                                       subscript.getValues().containsAll(all) && \r
+                                       all.containsAll(subscript.getValues())) {\r
+                               return subscript;\r
+                       }\r
+               }\r
+               \r
+               // if an exact match could not be found, return null\r
+               return null;\r
+       }\r
+       \r
+       public void addSketch(Sketch sketch) {\r
+               sketches.add(sketch);\r
+       }\r
+       \r
+       public List<Sketch> getSketches() {\r
+               return sketches;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/MdlVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/MdlVariable.java
new file mode 100644 (file)
index 0000000..ad63d00
--- /dev/null
@@ -0,0 +1,218 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.ArrayList;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.Variable;\r
+import org.simantics.sysdyn.modelImport.model.expression.DelayExpression;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+import org.simantics.sysdyn.modelImport.model.expression.IntegralExpression;\r
+import org.simantics.sysdyn.modelImport.model.expression.NormalExpression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public class MdlVariable extends Declaration {\r
+       \r
+       protected static final String EXPRESSION =\r
+                       "(?:\\s*=\\s*([^~]*?(?:"+MdlUtil.SPECIAL_NAME+"[^~]*?)*))?";\r
+       \r
+       private static final String VARIABLE_DECL =\r
+                       MdlUtil.VARIABLE+EXPRESSION+"("+DECL_SUFFIX+")";\r
+       private static final int variableName = 1;\r
+       private static final int variableExpression = 2;\r
+       private static final int variableSuffix = 3;\r
+       \r
+       private String expression;\r
+       \r
+       protected MdlVariable(String name, MdlModel mdl, String expression) {\r
+               super(name, mdl);\r
+               this.expression = expression;\r
+       }\r
+       \r
+       public static MdlVariable getPossible(String line, MdlModel mdl) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(VARIABLE_DECL).matcher(line);\r
+               if (!matcher.matches()) {\r
+                       return null;\r
+               }\r
+               \r
+               String name = MdlUtil.normalize(matcher.group(variableName));\r
+               String expression = matcher.group(variableExpression);\r
+               if (expression != null)\r
+                       expression = MdlUtil.normalize(expression);\r
+               \r
+               MdlVariable var = new MdlVariable(name, mdl, expression);\r
+               var.parseSuffix(matcher.group(variableSuffix));\r
+               return var;\r
+       }\r
+       \r
+       public String getExpressionString() {\r
+               return expression;\r
+       }\r
+       \r
+       public <T extends Variable> T initVariable(T variable) {\r
+               variable.setName(getName());\r
+               if (expression != null)\r
+                       variable.setExpression(getExpression());\r
+               \r
+               String unit = getUnit();\r
+               Range range = parseRange(unit);\r
+               if (range != null)\r
+                       unit = unit.substring(0, unit.indexOf('[')).trim();\r
+               \r
+               variable.setUnit(unit);\r
+               if (range != null)\r
+                       variable.setRange(range);\r
+               variable.setDescription(getDescription());\r
+               \r
+               return variable;\r
+       }\r
+       \r
+       public Expression getExpression() {\r
+               if (expression == null) {\r
+                       return null;\r
+               }\r
+               else {\r
+                       return parseExpression(MdlUtil.finalize(expression, getMdl()));\r
+               }\r
+       }\r
+       \r
+       protected static Expression parseExpression(String expression) {\r
+               Matcher matcher = Pattern.compile(\r
+                       MdlUtil.FUNCTION+"(.*)\\)"\r
+                               ).matcher(expression);\r
+               if (!matcher.matches()) {\r
+                       // the expression is not one of the special function calls\r
+                       return new NormalExpression(expression);\r
+               }\r
+               \r
+               String function = matcher.group(1).toUpperCase();\r
+               String[] parameters = splitFunctionParameters(matcher.group(2));\r
+               \r
+               if (function.equals("INTEG")) {\r
+                       // an integral expression\r
+                       if (parameters.length != 2) {\r
+                               System.err.println("malformed integral expression: "+expression);\r
+                               return null;\r
+                       }\r
+                       return new IntegralExpression(parameters[0], parameters[1]);\r
+               }\r
+               else if (function.equals("INITIAL")) {\r
+                       // as we do not have a proper replacement for Vensim "initial" \r
+                       // function in sysdyn, replace it with a stock with no flows\r
+                       if (parameters.length != 1) {\r
+                               System.err.println("malformed initial expression: "+expression);\r
+                               return null;\r
+                       }\r
+                       return new IntegralExpression("0", parameters[0]);\r
+               }\r
+               else if (function.equals("DELAY N")) {\r
+                       // a delay expression\r
+                       if (parameters.length != 4) {\r
+                               System.err.println("malformed delay expression: "+expression);\r
+                               return null;\r
+                       }\r
+                       return new DelayExpression(parameters[0], parameters[1], parameters[2], Integer.parseInt(parameters[3]));\r
+               }\r
+               else if (function.equals("SMOOTH3I")) {\r
+                       if (parameters.length != 3) {\r
+                               System.err.println("malformed smoothi expression: "+expression);\r
+                       }\r
+                       // what is the correct degree for smooth?\r
+                       return new DelayExpression(parameters[0], parameters[1], parameters[2], 3);\r
+               }\r
+               else if (function.equals("SMOOTH3")) {\r
+                       if (parameters.length != 2) {\r
+                               System.err.println("malformed smooth expression: "+expression);\r
+                       }\r
+                       // what is the correct degree and initial value for smooth?\r
+                       return new DelayExpression(parameters[0], parameters[1], parameters[0], 3);\r
+               }\r
+               else if (function.equals("SMOOTHI")) {\r
+                       if (parameters.length != 3) {\r
+                               System.err.println("malformed smoothi expression: "+expression);\r
+                       }\r
+                       // what is the correct degree for smooth?\r
+                       return new DelayExpression(parameters[0], parameters[1], parameters[2], 1);\r
+               }\r
+               else if (function.equals("SMOOTH")) {\r
+                       if (parameters.length != 2) {\r
+                               System.err.println("malformed smooth expression: "+expression);\r
+                       }\r
+                       // what is the correct degree and initial value for smooth?\r
+                       return new DelayExpression(parameters[0], parameters[1], parameters[0], 1);\r
+               }\r
+               else if (function.equals("GAME")) {\r
+                       // a game expression, currently treated as a normal expression\r
+                       if (parameters.length != 1) {\r
+                               System.err.println("malformed game expression: "+expression);\r
+                               return null;\r
+                       }\r
+                       return new NormalExpression(parameters[0]);\r
+               }\r
+               else {\r
+                       return new NormalExpression(expression);\r
+               }\r
+       }\r
+       \r
+       private static Range parseRange(String unit) {\r
+               Matcher matcher = Pattern.compile(\r
+                       "\\["+MdlUtil.DBL_G+",(\\?|"+MdlUtil.DBL_G+"|"+MdlUtil.DBL_G+","+MdlUtil.DBL_G+")\\]"\r
+                               ).matcher(unit);\r
+               if (matcher.find()) {\r
+                       Double start, end, step;\r
+                       start = Double.parseDouble(matcher.group(1));\r
+                       if (matcher.group(2).equals("?")) {\r
+                               end = null;\r
+                               step = null;\r
+                       }\r
+                       else if (matcher.group(2).contains(",")){\r
+                               end = Double.parseDouble(matcher.group(4));\r
+                               step = Double.parseDouble(matcher.group(5));\r
+                       }\r
+                       else {\r
+                               end = Double.parseDouble(matcher.group(3));\r
+                               step = null;    \r
+                       }\r
+                       return new Range(start, end, step);\r
+               }\r
+               else {\r
+                       return null;\r
+               }\r
+       }\r
+       \r
+       private static String[] splitFunctionParameters(String str) {\r
+               ArrayList<String> list = new ArrayList<String>();\r
+\r
+               int i;\r
+               int last = 0;\r
+               int level = 0;\r
+               boolean comment = false;\r
+               boolean brackets = false;\r
+\r
+               for (i = 0; i < str.length(); i++) {\r
+                       char current = str.charAt(i);\r
+                       if (current == '"')\r
+                               // note that this does not currently support escaped quotation marks inside quoted variable names\r
+                               comment = !comment;\r
+                       else if (current == '[' && !comment)\r
+                               brackets = true;\r
+                       else if (current == ']' && !comment)\r
+                               brackets = false;\r
+                       else if (current == '(' && !comment && !brackets)\r
+                               level++;\r
+                       else if (current == ')' && !comment && !brackets)\r
+                               level--;\r
+                       else if (current == ',' && !comment && !brackets && level == 0) {\r
+                               list.add(str.substring(last, i).trim());\r
+                               last = i + 1;\r
+                       }\r
+               }\r
+               if (last < i) {\r
+                       list.add(str.substring(last, i).trim());\r
+               }\r
+\r
+               return list.toArray(new String[list.size()]);\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Sketch.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Sketch.java
new file mode 100644 (file)
index 0000000..89f40f8
--- /dev/null
@@ -0,0 +1,164 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+\r
+public class Sketch {\r
+       \r
+       private MdlModel mdl;\r
+       private String name;\r
+       \r
+       private int xOffset = 0;\r
+       private int yOffset = 0;\r
+       \r
+       private boolean updateEdges;\r
+       private int topEdge = 0;\r
+       private int bottomEdge = 0;\r
+       private int leftEdge = 0;\r
+       private int rightEdge = 0;\r
+\r
+       private List<SketchComment> comments;\r
+       private List<SketchConnection> connections;\r
+       private List<SketchValve> valves;\r
+       private List<SketchVariable> variables;\r
+       \r
+       private HashMap<Integer, SketchObject> objects;\r
+       \r
+       public Sketch(MdlModel mdl) {\r
+               this.mdl = mdl;\r
+               \r
+               updateEdges = true;\r
+               \r
+               comments = new ArrayList<SketchComment>();\r
+               connections = new ArrayList<SketchConnection>();\r
+               valves = new ArrayList<SketchValve>();\r
+               variables = new ArrayList<SketchVariable>();\r
+               \r
+               objects = new HashMap<Integer, SketchObject>();\r
+       }\r
+       \r
+       public MdlModel getMdl() {\r
+               return mdl;\r
+       }\r
+       \r
+       public String getName() {\r
+               return name;\r
+       }\r
+\r
+       public void setName(String name) {\r
+               this.name = name;\r
+       }\r
+       \r
+       private void updateEdges() {\r
+               if (updateEdges) {\r
+                       boolean first = true;\r
+                       for (SketchElement e : getAllElements()) {\r
+                               topEdge    = first ? e.getTop()    : Math.min(topEdge, e.getTop() );\r
+                               bottomEdge = first ? e.getBottom() : Math.max(bottomEdge, e.getBottom());\r
+                               leftEdge   = first ? e.getLeft()   : Math.min(leftEdge, e.getLeft());\r
+                               rightEdge  = first ? e.getRight()  : Math.max(rightEdge, e.getRight());\r
+                               first = false;\r
+                       }\r
+                       updateEdges = false;\r
+               }\r
+       }\r
+       \r
+       public int getWidth() {\r
+               updateEdges();\r
+               return rightEdge - leftEdge;\r
+       }\r
+       \r
+       public int getHeight() {\r
+               updateEdges();\r
+               return bottomEdge - topEdge;\r
+       }\r
+       \r
+       // sets the relative location of this sketch in the diagram \r
+       public void setLocation(int x, int y) {\r
+               xOffset = x;\r
+               yOffset = y;\r
+       }\r
+       \r
+       public int getElementXOffset() {\r
+               updateEdges();\r
+               return -leftEdge + xOffset;\r
+       }\r
+       \r
+       public int getElementYOffset() {\r
+               updateEdges();\r
+               return -topEdge + yOffset;\r
+       }\r
+       \r
+       public void addComment(SketchComment comment) {\r
+               comments.add(comment);\r
+               objects.put(comment.getId(), comment);\r
+               updateEdges = true;\r
+       }\r
+       \r
+       public List<SketchComment> getComments() {\r
+               return comments;\r
+       }\r
+       \r
+       public void addConnection(SketchConnection connection) {\r
+               connections.add(connection);\r
+               objects.put(connection.getId(), connection);\r
+       }\r
+       \r
+       public List<SketchConnection> getConnections() {\r
+               return connections;\r
+       }\r
+       \r
+       public void addValve(SketchValve valve) {\r
+               valves.add(valve);\r
+               objects.put(valve.getId(), valve);\r
+               // replace the attached variable with the valve in order to redirect \r
+               // possible connections to the variable to the valve\r
+               objects.put(valve.getAttached().getId(), valve);\r
+               updateEdges = true;\r
+       }\r
+       \r
+       public List<SketchValve> getValves() {\r
+               return valves;\r
+       }\r
+       \r
+       public void addVariable(SketchVariable variable) {\r
+               variables.add(variable);\r
+               objects.put(variable.getId(), variable);\r
+               updateEdges = true;\r
+       }\r
+       \r
+       public List<SketchVariable> getVariables() {\r
+               return variables;\r
+       }\r
+       \r
+       public SketchObject getObject(int id) {\r
+               return objects.get(id);\r
+       }\r
+       \r
+       public List<SketchElement> getAllElements() {\r
+               ArrayList<SketchElement> list = new ArrayList<SketchElement>();\r
+               list.addAll(getComments());\r
+               list.addAll(getValves());\r
+               list.addAll(getVariables());\r
+               return list;\r
+       }\r
+       \r
+       public List<SketchVariable> getShadowVariables() {\r
+               List<SketchVariable> variables = new ArrayList<SketchVariable>();\r
+               for (SketchVariable var : getVariables()) {\r
+                       if (!var.allowsIn()) {\r
+                               variables.add(var);\r
+                       }\r
+               }\r
+               return variables;\r
+       }\r
+       \r
+       public List<SketchVariable> getNonShadowVariables() {\r
+               List<SketchVariable> variables = new ArrayList<SketchVariable>();\r
+               variables.addAll(getVariables());\r
+               variables.removeAll(getShadowVariables());\r
+               return variables;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchComment.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchComment.java
new file mode 100644 (file)
index 0000000..3c4b238
--- /dev/null
@@ -0,0 +1,74 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.model.Cloud;\r
+import org.simantics.sysdyn.modelImport.model.Comment;\r
+import org.simantics.sysdyn.modelImport.model.Symbol;\r
+\r
+public class SketchComment extends SketchElement {\r
+       \r
+       private static final String SKETCH_COMMENT =\r
+                       "12,"+KEEP_I+KEEP_I+"("+ELEMENT_SUFFIX+")";\r
+       private static final int commentId = 1;\r
+       private static final int commentIcon = 2;\r
+       private static final int commentSuffix = 3;\r
+       \r
+       public enum CommentIcon {\r
+               CLOUD, OTHER\r
+       }\r
+       \r
+       private String text;\r
+       private CommentIcon icon;\r
+\r
+       protected SketchComment(int id, Sketch sketch, CommentIcon icon) {\r
+               super(id, sketch);\r
+               this.icon = icon;\r
+       }\r
+       \r
+       public static SketchComment getPossible(String line, Sketch sketch) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(SKETCH_COMMENT).matcher(line);\r
+               if (!matcher.matches()) {\r
+                       return null;\r
+               }\r
+               \r
+               int id = Integer.parseInt(matcher.group(commentId));\r
+               \r
+               CommentIcon icon;\r
+               switch (Integer.parseInt(matcher.group(commentIcon))) {\r
+               case 48: icon = CommentIcon.CLOUD; break;\r
+               default: icon = CommentIcon.OTHER; break;\r
+               }\r
+               \r
+               SketchComment element = new SketchComment(id, sketch, icon);\r
+               element.parseSuffix(matcher.group(commentSuffix));\r
+               return element;\r
+       }\r
+\r
+       public String getText() {\r
+               return text;\r
+       }\r
+       \r
+       public void setText(String text) {\r
+               this.text = text;\r
+       }\r
+       \r
+       public CommentIcon getIcon() {\r
+               return icon;\r
+       }\r
+       \r
+       @Override\r
+       public Symbol getSymbol() {\r
+               if (isInputOutput())\r
+                       return new Comment(getDimensions(), "I/O objects are not supported");\r
+               \r
+               switch(icon) {\r
+               case CLOUD: return new Cloud(getDimensions());\r
+               case OTHER: return new Comment(getDimensions(), text);\r
+               default: return null;\r
+               }\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchConnection.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchConnection.java
new file mode 100644 (file)
index 0000000..e1fe384
--- /dev/null
@@ -0,0 +1,173 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.model.Connection;\r
+import org.simantics.sysdyn.modelImport.model.Dependency;\r
+import org.simantics.sysdyn.modelImport.model.Flow;\r
+import org.simantics.sysdyn.modelImport.model.Symbol;\r
+\r
+public class SketchConnection extends SketchObject {\r
+       \r
+       public enum ConnectionType {\r
+               ARROW, LINE_ARROW, LINE_SEGMENT, OTHER\r
+       }\r
+       \r
+       private static final String POINTS = "(\\d+\\|(?:\\(-?\\d+,-?\\d+\\)\\|)+)";\r
+       \r
+       // each sketch connection is declared with a string:\r
+       // 1,id,from,to,shape,hid,pol,thick,hasf,dtype,res,color,font,np|plist\r
+       \r
+       // the following regular expression matches a connection declaration and \r
+       // extracts the useful information from it\r
+       private static final String SKETCH_CONNECTION = \r
+                       "1,"+KEEP_I+KEEP_I+KEEP_I+KEEP_I+SKIP_I+SKIP_I+SKIP_I+SKIP_I+SKIP_I+SKIP_I+SKIP_ANY+SKIP_ANY+POINTS;\r
+       // corresponding group indices\r
+       private static final int connectionId = 1;\r
+       private static final int connectionFrom = 2;\r
+       private static final int connectionTo = 3;\r
+       private static final int connectionShape = 4;\r
+       private static final int connectionPoints = 5;\r
+       \r
+       private static final String SAVE = "(-?\\d+),";\r
+       private static final String SKIP = "-?\\d+,";\r
+       \r
+       public static final String sketchConnection =\r
+               //   1,  id,  from,to,  shape,hid, pol, thick,hasf,dtype,res, color,font,np|plist\r
+                       "1,"+SAVE+SAVE+SAVE+SAVE+ SKIP+SKIP+SKIP+ SKIP+SKIP+ SKIP+"[^,]*,[^,]*,"+POINTS;\r
+\r
+       private int from;\r
+       private int to;\r
+       private ConnectionType type;\r
+       int[] points;\r
+\r
+       protected SketchConnection(int id, Sketch sketch, int from, int to, ConnectionType type, int[] points) {\r
+               super(id, sketch);\r
+               this.from = from;\r
+               this.to = to;\r
+               this.type = type;\r
+               this.points = points;\r
+       }\r
+       \r
+       public static SketchConnection getPossible(String line, Sketch sketch) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(SKETCH_CONNECTION).matcher(line);\r
+               if (!matcher.matches()) {\r
+                       return null;\r
+               }\r
+               \r
+               int id = Integer.parseInt(matcher.group(connectionId));\r
+               int from = Integer.parseInt(matcher.group(connectionFrom));\r
+               int to = Integer.parseInt(matcher.group(connectionTo));\r
+               int connType = Integer.parseInt(matcher.group(connectionShape));\r
+               \r
+               ConnectionType type;\r
+               switch (Integer.parseInt(matcher.group(connectionShape))) {\r
+               case 0: \r
+               case 1: type = ConnectionType.ARROW; break;\r
+               case 4: type = ConnectionType.LINE_ARROW; break;\r
+               case 100: type = ConnectionType.LINE_SEGMENT; break;\r
+               default: \r
+                       System.err.println("connection type "+connType+" not recognized"); \r
+                       type = ConnectionType.OTHER; break;\r
+               }\r
+               \r
+               int[] points = parsePoints(matcher.group(connectionPoints));\r
+               \r
+               return new SketchConnection(id, sketch, from, to, type, points);\r
+       }\r
+       \r
+       private static int[] parsePoints(String str) {\r
+               int sep = str.indexOf('|');\r
+               int count = Integer.parseInt(str.substring(0, sep));\r
+               int[] points = new int[count*2];\r
+               for (int i = 0; i < count; i++) {\r
+                       int start = sep + 1;\r
+                       sep = str.indexOf('|', start);\r
+                       String[] pair = str.substring(start+1, sep-1).split(",");\r
+                       points[i*2] = Integer.parseInt(pair[0]);\r
+                       points[i*2+1] = Integer.parseInt(pair[1]);\r
+               }\r
+               return points;\r
+       }\r
+\r
+       public int getFrom() {\r
+               return from;\r
+       }\r
+\r
+       public int getTo() {\r
+               return to;\r
+       }\r
+\r
+       public ConnectionType getType() {\r
+               return type;\r
+       }\r
+       \r
+       public int[] getPoints() {\r
+               return points;\r
+       }\r
+\r
+       public Connection getConnection() {\r
+               Symbol tail = (Symbol)getSketch().getObject(from).getModelObject();\r
+               if (tail == null) {\r
+                       return null;\r
+               }\r
+               Symbol head = (Symbol)getSketch().getObject(to).getModelObject();\r
+               if (head == null) {\r
+                       return null;\r
+               }\r
+               \r
+               switch (type) {\r
+               case ARROW:        return new Dependency(tail, head, true, false, getAngle(getSketch()));\r
+               case LINE_ARROW:   return new Flow(tail, head);\r
+               case LINE_SEGMENT: return new Flow(head, tail);\r
+               default: return null;\r
+               }\r
+       }\r
+\r
+       private double getAngle(Sketch sketch) {\r
+               if (points == null || points.length < 2) {\r
+                       return 0;\r
+               }\r
+               \r
+               SketchElement tail = (SketchElement)sketch.getObject(from);\r
+               SketchElement head = (SketchElement)sketch.getObject(to);\r
+               \r
+               // 'from' element is in (x0, y0) and 'to' element is in (x2, y2)\r
+               double x0 = tail.getX();\r
+               double y0 = tail.getY();\r
+               double x2 = head.getX();\r
+               double y2 = head.getY();\r
+               \r
+               // treat the first points in points as the control point (x1, y1)\r
+               double x1 = (double)points[0];\r
+               double y1 = (double)points[1];\r
+               \r
+               //System.err.println("("+x0+","+y0+") -> ("+x1+","+y1+") -> ("+x2+","+y2+")");\r
+\r
+               double dx0 = x1 - x0;\r
+               double dy0 = y1 - y0;\r
+               double dx1 = x1 - x2;\r
+               double dy1 = y1 - y2;\r
+               double dx  = x2 - x0;\r
+               double dy  = y2 - y0;\r
+\r
+               // length of (p1-p0) x (p2-p0)\r
+               double dd = dx0*dy - dy0*dx; \r
+\r
+               if (Math.abs(dd) < 0.01) {\r
+                       // Points are (almost) collinear\r
+                       return 0;\r
+               }\r
+               else {\r
+                       // (p1-p0) * (p1-p2) / dd\r
+                       double offset = (dx0*dx1 + dy0*dy1) / dd;\r
+                       double angle = Math.PI/2 - Math.atan(offset);\r
+                       if (dd > 0)\r
+                               angle = angle - Math.PI;\r
+                       return angle;\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchElement.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchElement.java
new file mode 100644 (file)
index 0000000..ab4eae9
--- /dev/null
@@ -0,0 +1,144 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.Symbol;\r
+import org.simantics.sysdyn.modelImport.model.Valve.TextPosition;\r
+\r
+public abstract class SketchElement extends SketchObject {\r
+       \r
+       // each sketch element is declared with a string:\r
+       // n,id,name,x,y,w,h,sh,bits,hid,hasf,tpos,bw,nav1,nav2(,box,fill,font)\r
+       \r
+       // n, id and name depend on the type of the sketch element, and some\r
+       // of the fields in the suffix do not contain useful information\r
+       \r
+       // the following regular expression matches the suffix of an element\r
+       // declaration and extracts the useful information from it\r
+       protected static final String ELEMENT_SUFFIX =\r
+                       KEEP_I+KEEP_I+KEEP_I+KEEP_I+KEEP_I+KEEP_I+SKIP_I+SKIP_I+KEEP_I+".*";\r
+       // corresponding group indices\r
+       private static final int elementX = 1;\r
+       private static final int elementY = 2;\r
+       private static final int elementWidth = 3;\r
+       private static final int elementHeight = 4;\r
+       private static final int elementShape = 5;\r
+       private static final int elementBits = 6;\r
+       private static final int elementTextPos = 7;\r
+\r
+       private int x;\r
+       private int y;\r
+       private int width;\r
+       private int height;\r
+       private boolean attached;\r
+       private boolean allowsIn;\r
+       private boolean allowsOut;\r
+       private boolean inputOutput;\r
+       private boolean textLine;\r
+       private TextPosition textPosition;\r
+\r
+       protected SketchElement(int id, Sketch sketch) {\r
+               super(id, sketch);\r
+       }\r
+       \r
+       protected void parseSuffix(String suffix) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(ELEMENT_SUFFIX).matcher(suffix);\r
+               if (!matcher.matches()) {\r
+                       // this should not happen unless subclasses fail to construct their\r
+                       // regular expressions properly\r
+                       throw new Exception("could not parse element suffix "+suffix);\r
+               }\r
+               \r
+               x = Integer.parseInt(matcher.group(elementX));\r
+               y = Integer.parseInt(matcher.group(elementY));\r
+               width = Integer.parseInt(matcher.group(elementWidth));\r
+               height = Integer.parseInt(matcher.group(elementHeight));\r
+               attached = (Integer.parseInt(matcher.group(elementShape)) & 1<<5) != 0;\r
+               allowsIn = (Integer.parseInt(matcher.group(elementBits)) & 1) != 0;\r
+               allowsOut = (Integer.parseInt(matcher.group(elementBits)) & 1<<1) != 0;\r
+               inputOutput = (Integer.parseInt(matcher.group(elementBits)) & 1<<3) != 0;\r
+               textLine = (Integer.parseInt(matcher.group(elementBits)) & 1<<2) != 0;\r
+               \r
+               switch (Integer.parseInt(matcher.group(elementTextPos))) {\r
+               case 0: textPosition = TextPosition.INSIDE; break;\r
+               case 1: textPosition = TextPosition.BELOW; break;\r
+               case 2: textPosition = TextPosition.LEFT; break;\r
+               case 3: textPosition = TextPosition.ABOVE; break;\r
+               case 4: textPosition = TextPosition.RIGHT; break;\r
+               default: textPosition = TextPosition.UNSET; break;\r
+               }\r
+               \r
+       }\r
+\r
+       public int getX() {\r
+               return x;\r
+       }\r
+       \r
+       public int getY() {\r
+               return y;\r
+       }\r
+       \r
+       public int getWidth() {\r
+               return width;\r
+       }\r
+\r
+       public int getHeight() {\r
+               return height;\r
+       }\r
+       \r
+       public int getTop() {\r
+               return getY() - getHeight();\r
+       }\r
+       \r
+       public int getBottom() {\r
+               return getY() + getHeight();\r
+       }\r
+       \r
+       public int getLeft() {\r
+               return getX() - getWidth();\r
+       }\r
+       \r
+       public int getRight() {\r
+               return getX() + getWidth();\r
+       }\r
+       \r
+       public boolean isAttached() {\r
+               return attached;\r
+       }\r
+\r
+       public boolean allowsIn() {\r
+               return allowsIn;\r
+       }\r
+\r
+       public boolean allowsOut() {\r
+               return allowsOut;\r
+       }\r
+\r
+       public boolean isInputOutput() {\r
+               return inputOutput;\r
+       }\r
+\r
+       public boolean hasTextLine() {\r
+               return textLine;\r
+       }\r
+       \r
+       public TextPosition getTextPosition() {\r
+               return textPosition;\r
+       }\r
+\r
+       public abstract Symbol getSymbol();\r
+       \r
+       // get sysdyn dimensions for element [x, y, width, height]\r
+       public double[] getDimensions() {\r
+               return MdlUtil.getSysdynDimensions(\r
+                               getLeft() + getSketch().getElementXOffset(),\r
+                               getTop() + getSketch().getElementYOffset(),\r
+                               getWidth() * 2,\r
+                               getHeight() * 2\r
+                               );\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchObject.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchObject.java
new file mode 100644 (file)
index 0000000..a4c2ac4
--- /dev/null
@@ -0,0 +1,39 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+\r
+public abstract class SketchObject {\r
+       \r
+       // some shorthands\r
+       protected static final String KEEP_I = MdlUtil.INT_G+",";\r
+       protected static final String SKIP_I = MdlUtil.INT+",";\r
+       protected static final String SKIP_ANY = "[^,]*,";\r
+\r
+       private int id;\r
+       private Sketch sketch;\r
+       \r
+       private IWriteableObject modelObject;\r
+       \r
+       protected SketchObject(int id, Sketch sketch) {\r
+               this.id = id;\r
+               this.sketch = sketch;\r
+       }\r
+       \r
+       public int getId() {\r
+               return id;\r
+       }\r
+       \r
+       public Sketch getSketch() {\r
+               return sketch;\r
+       }\r
+       \r
+       public void setModelObject(IWriteableObject modelObject) {\r
+               this.modelObject = modelObject;\r
+       }\r
+       \r
+       public IWriteableObject getModelObject() {\r
+               return modelObject;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchValve.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchValve.java
new file mode 100644 (file)
index 0000000..7f38531
--- /dev/null
@@ -0,0 +1,57 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.model.Valve;\r
+import org.simantics.sysdyn.modelImport.model.Valve.Orientation;\r
+\r
+public class SketchValve extends SketchElement {\r
+       \r
+       private static final String SKETCH_VALVE =\r
+                       "11,"+KEEP_I+SKIP_I+"("+ELEMENT_SUFFIX+")";\r
+       private static final int valveId = 1;\r
+       private static final int valveSuffix = 2;\r
+       \r
+       private SketchVariable attached;\r
+       \r
+       protected SketchValve(int id, Sketch sketch) {\r
+               super(id, sketch);\r
+       }\r
+       \r
+       public static SketchValve getPossible(String line, Sketch sketch) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(SKETCH_VALVE).matcher(line);\r
+               if (!matcher.matches()) {\r
+                       return null;\r
+               }\r
+               \r
+               int id = Integer.parseInt(matcher.group(valveId));\r
+               \r
+               SketchValve element = new SketchValve(id, sketch);\r
+               element.parseSuffix(matcher.group(valveSuffix));\r
+               return element;\r
+       }\r
+\r
+       public SketchVariable getAttached() {\r
+               return attached;\r
+       }\r
+\r
+       public void setAttached(SketchVariable attached) {\r
+               this.attached = attached;\r
+       }\r
+       \r
+       @Override\r
+       public Valve getSymbol() {\r
+               MdlVariable variable = getSketch().getMdl().getVariable(attached.getName());\r
+               if (variable == null) {\r
+                       return null;\r
+               }\r
+               \r
+               Valve valve = new Valve(Orientation.HORIZONTAL, getTextPosition());\r
+               valve.setDimensions(getDimensions());\r
+               \r
+               return variable.initVariable(valve);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SketchVariable.java
new file mode 100644 (file)
index 0000000..031611d
--- /dev/null
@@ -0,0 +1,66 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.Auxiliary;\r
+import org.simantics.sysdyn.modelImport.model.Variable;\r
+import org.simantics.sysdyn.modelImport.model.Stock;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+\r
+public class SketchVariable extends SketchElement {\r
+       \r
+       private static final String SKETCH_VARIABLE =\r
+                       "10,"+KEEP_I+MdlUtil.VARIABLE+",("+ELEMENT_SUFFIX+")";\r
+       private static final int variableId = 1;\r
+       private static final int variableName = 2;\r
+       private static final int variableSuffix = 3;\r
+       \r
+       private String name;\r
+\r
+       protected SketchVariable(int id, Sketch sketch, String name) {\r
+               super(id, sketch);\r
+               this.name = name;\r
+       }\r
+       \r
+       public static SketchVariable getPossible(String line, Sketch sketch) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(SKETCH_VARIABLE).matcher(line);\r
+               if (!matcher.matches()) {\r
+                       return null;\r
+               }\r
+               \r
+               int id = Integer.parseInt(matcher.group(variableId));\r
+               String name = MdlUtil.normalize(matcher.group(variableName));\r
+               \r
+               SketchVariable element = new SketchVariable(id, sketch, name);\r
+               element.parseSuffix(matcher.group(variableSuffix));\r
+               return element;\r
+       }\r
+       \r
+       public String getName() {\r
+               return name;\r
+       }\r
+       \r
+       @Override\r
+       public Variable getSymbol() {\r
+               MdlVariable variable = getSketch().getMdl().getVariable(name);\r
+               if (variable == null) {\r
+                       return null;\r
+               }\r
+               \r
+               Variable var;\r
+               \r
+               Expression expr = variable.getExpression();\r
+               if (expr != null && expr.getExpressionTypeString().equals("StockExpression"))\r
+                       var = new Stock();\r
+               else\r
+                       var = new Auxiliary();\r
+               \r
+               var.setDimensions(getDimensions());\r
+               \r
+               return variable.initVariable(var);\r
+       }\r
+       \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Subscript.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/Subscript.java
new file mode 100644 (file)
index 0000000..c6b4a94
--- /dev/null
@@ -0,0 +1,79 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+\r
+public class Subscript extends Declaration {\r
+       \r
+       private static final String SUBSCRIPT_DECL = \r
+                       "("+MdlUtil.BASIC_NAME+")\\s*(:|<->)\\s*([^~]*?)("+DECL_SUFFIX+")";\r
+       private static final int subscriptName = 1;\r
+       private static final int subscriptType = 2;\r
+       private static final int subscriptExpression = 3;\r
+       private static final int subscriptSuffix = 4;\r
+       \r
+       private String original;\r
+       private List<String> values;\r
+       \r
+       private Enumeration enumeration;\r
+       \r
+       protected Subscript(String name, MdlModel mdl, List<String> values) {\r
+               super(name, mdl);\r
+               this.original = null;\r
+               this.values = values;\r
+       }\r
+       \r
+       protected Subscript(String name, MdlModel mdl, String original) {\r
+               super(name, mdl);\r
+               this.original = original;\r
+               this.values = null;\r
+       }\r
+       \r
+       public static Subscript getPossible(String line, MdlModel mdl) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(SUBSCRIPT_DECL).matcher(line);                \r
+               if (!matcher.matches())\r
+                       return null;\r
+               \r
+               String name = MdlUtil.normalize(matcher.group(subscriptName));\r
+               boolean equivalent = matcher.group(subscriptType).equals("<->");\r
+               String expression = MdlUtil.normalize(matcher.group(subscriptExpression));\r
+               \r
+               Subscript subscript;\r
+               if (equivalent)\r
+                       subscript = new Subscript(name, mdl, expression);\r
+               else\r
+                       subscript = new Subscript(name, mdl, Arrays.asList(expression.split(",")));\r
+               subscript.parseSuffix(matcher.group(subscriptSuffix));\r
+               return subscript;\r
+       }\r
+       \r
+       public String getOriginal() {\r
+               return original;\r
+       }\r
+       \r
+       public List<String> getValues() {\r
+               if (values != null)\r
+                       return values;\r
+               else\r
+                       return getMdl().getSubscript(original).getValues();\r
+       }\r
+       \r
+       public boolean isEquivalent() {\r
+               return original != null;\r
+       }\r
+       \r
+       public Enumeration getEnumeration() {\r
+               if (enumeration == null) {\r
+                       enumeration = new Enumeration(getName(), getValues());\r
+               }\r
+               \r
+               return enumeration;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SubscriptVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/mdl/SubscriptVariable.java
new file mode 100644 (file)
index 0000000..ef397f4
--- /dev/null
@@ -0,0 +1,289 @@
+package org.simantics.sysdyn.modelImport.mdl;\r
+\r
+import java.util.ArrayDeque;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.Deque;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.modelImport.MdlUtil;\r
+import org.simantics.sysdyn.modelImport.model.expression.EnumerationExpression;\r
+import org.simantics.sysdyn.modelImport.model.expression.NormalExpression;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+\r
+public class SubscriptVariable extends MdlVariable {\r
+       \r
+       // a subscript variable is a variable that has a different equation\r
+       // depending on the value of the subscript it references\r
+       private static final String SUBSCRIPT_VARIABLE_DECL = \r
+                       MdlUtil.SUBSCRIPT+EXPRESSION+"("+DECL_SUFFIX+")";;\r
+       private static final int subscriptVariableName = 1;\r
+       private static final int subscriptVariableIndices = 2;\r
+       private static final int subscriptVariableExpression = 3;\r
+       private static final int subscriptVariableSuffix = 4;\r
+\r
+       private String[] indices;\r
+       private SubscriptVariable next;\r
+       \r
+       protected SubscriptVariable(String name, MdlModel mdl, String expression, String[] indices) {\r
+               super(name, mdl, expression);\r
+               this.indices = indices;\r
+               this.next = null;\r
+       }\r
+       \r
+       public static SubscriptVariable getPossible(String line, MdlModel mdl) \r
+                       throws Exception {\r
+               Matcher matcher = Pattern.compile(SUBSCRIPT_VARIABLE_DECL).matcher(line);\r
+               if (!matcher.matches()) {\r
+                       return null;\r
+               }\r
+               \r
+               String name = MdlUtil.normalize(matcher.group(subscriptVariableName));\r
+               String[] indices = MdlUtil.normalize(matcher.group(subscriptVariableIndices)).split(",");\r
+               String expression = matcher.group(subscriptVariableExpression);\r
+               if (expression != null)\r
+                       expression = MdlUtil.normalize(expression);\r
+               \r
+               SubscriptVariable subVar = new SubscriptVariable(name, mdl, expression, indices);\r
+               subVar.parseSuffix(matcher.group(subscriptVariableSuffix));\r
+               return subVar;\r
+       }\r
+       \r
+       public String[] getIndices() {\r
+               return indices;\r
+       }\r
+       \r
+       private SubscriptVariable getNext() {\r
+               return next;\r
+       }\r
+       \r
+       private void setNext(SubscriptVariable next) {\r
+               this.next = next;\r
+       }\r
+       \r
+       public void addSubscriptVariable(SubscriptVariable variable) {\r
+               // find the last variable in the list and add the new variable after it\r
+               SubscriptVariable last = this;\r
+               while (last.getNext() != null)\r
+                       last = last.getNext();\r
+               last.setNext(variable);\r
+       }\r
+       \r
+       @Override\r
+       public EnumerationExpression getExpression() {\r
+               SubscriptVariable var;\r
+               \r
+               // find out what subscripts the combined expression uses by collecting\r
+               // all subscript indices from individual expressions into a list of\r
+               // sets (one set for each "position" in the indices)\r
+               \r
+               List<Set<String>> subscripts = new ArrayList<Set<String>>();\r
+               for (int i = 0; i < indices.length; i++) {\r
+                       subscripts.add(new HashSet<String>());\r
+               }\r
+               \r
+               var = this;\r
+               while (var != null) {\r
+                       for (int i = 0; i < var.getIndices().length; i++) {\r
+                               subscripts.get(i).add(var.getIndices()[i]);\r
+                       }\r
+                       \r
+                       var = var.getNext();\r
+               }\r
+               \r
+               // turn the aforementioned list of sets into a list of enumeration\r
+               // by finding the enumerations that correspond to the sets of subscript\r
+               // indices\r
+               \r
+               List<Enumeration> enumerations = new ArrayList<Enumeration>();\r
+               for (Set<String> values : subscripts) {\r
+                       Subscript potential = getMdl().resolveSubscript(values);\r
+                       if (potential == null) {\r
+                               System.err.println("subscript indices could not be resolved ");\r
+                               return null;\r
+                       }\r
+                       enumerations.add(potential.getEnumeration());\r
+               }\r
+               \r
+               // first check if the expression is just a (either one or two \r
+               // dimensional) list of values and just parse it if this is\r
+               // the case (should only happen if there is only one expression)\r
+               \r
+               // let enum x = {a,b,c}\r
+               //\r
+               // expand subscript expression over x with equations defined as\r
+               //\r
+               // foo[x] = 1,2,3\r
+               // \r
+               // into\r
+               //\r
+               // bar[a] = 1\r
+               // bar[b] = 2\r
+               // bar[c] = 3\r
+               \r
+               valuearray:\r
+               if (next == null) {\r
+                       // number(,number)*\r
+                       if (enumerations.size() == 1 && \r
+                                       Pattern.matches(MdlUtil.DBL+"(,"+MdlUtil.DBL+")*", getExpressionString())) {\r
+                               EnumerationExpression expr = new EnumerationExpression(enumerations);\r
+                               \r
+                               String[] values = getExpressionString().split(",");\r
+                               if (enumerations.get(0).getValues().size() != values.length) {\r
+                                       // could not find a value for each enumeration index, \r
+                                       // attempt to parse the equation normally\r
+                                       break valuearray;\r
+                               }\r
+                               for (int i = 0; i < values.length; i++) {\r
+                                       expr.addExpression(new NormalExpression(values[i]),\r
+                                                       enumerations.get(0).getValues().get(i));\r
+                               \r
+                               }\r
+                               \r
+                               return expr;\r
+                       }\r
+                       // (number(,number)*;)*\r
+                       else if (enumerations.size() == 2 && \r
+                                       Pattern.matches("("+MdlUtil.DBL+"(,"+MdlUtil.DBL+")*;)+", getExpressionString())) {\r
+                               EnumerationExpression expr = new EnumerationExpression(enumerations);\r
+                               \r
+                               String[] rows = getExpressionString().split(";");\r
+                               if (enumerations.get(0).getValues().size() != rows.length) {\r
+                                       // could not find a value for each enumeration index \r
+                                       // in the first enumeration, attempt to parse the equation \r
+                                       // normally\r
+                                       break valuearray;\r
+                               }\r
+                               for (int i = 0; i < rows.length; i++) {\r
+                                       String[] values = rows[i].split(",");\r
+                                       if (enumerations.get(1).getValues().size() != values.length) {\r
+                                               // could not find a value for each enumeration index\r
+                                               // in the second enumeration, attempt to parse the \r
+                                               // equation normally\r
+                                               break valuearray;\r
+                                       }\r
+                                       for (int j = 0; j < values.length; j++) {\r
+                                               expr.addExpression(new NormalExpression(values[j]),\r
+                                                               enumerations.get(0).getValues().get(i),\r
+                                                               enumerations.get(1).getValues().get(j));\r
+                                       }\r
+                               }\r
+                               \r
+                               return expr;\r
+                       }\r
+               }\r
+               \r
+               // expand the expressions to one expression for each combination of \r
+               // enumeration indices; this process must take into account the \r
+               // fact that some enumerations can be subsets of other enumerations \r
+               // and must be expanded accordingly\r
+               \r
+               // let enum x = {a,b,c} and enum y = {a,b}\r
+               //\r
+               // expand subscript expression over x with equations defined as\r
+               //\r
+               // foo[y] = bar[y]\r
+               // foo[c] = 10\r
+               //\r
+               // into:\r
+               //\r
+               // foo[a] = bar[a]\r
+               // foo[b] = bar[b]\r
+               // foo[c] = 10\r
+               \r
+               EnumerationExpression expr = new EnumerationExpression(enumerations);\r
+               \r
+               var = this;\r
+               while (var != null) {\r
+                       \r
+                       Deque<WorkExpression> workqueue = new ArrayDeque<WorkExpression>();\r
+                       workqueue.add(new WorkExpression(var.getIndices(), var.getExpressionString()));\r
+                       \r
+                       for (int i = 0; i < var.getIndices().length; i++) {\r
+                               int limit = workqueue.size();\r
+                               for (int j = 0; j < limit; j++) {\r
+                                       WorkExpression current = workqueue.pollFirst();\r
+                                       Subscript potential = getMdl().getSubscript(current.indices[i]);\r
+                                       if (potential != null) {\r
+                                               for (String value : potential.getValues()) {\r
+                                                       String[] newindices = Arrays.copyOf(current.indices, current.indices.length);\r
+                                                       newindices[i] = value;\r
+                                                       String newexpression = current.expression;\r
+                                                       newexpression = MdlUtil.replaceSubscripts(newexpression, potential.getName(), value);\r
+                                                       workqueue.addLast(new WorkExpression(newindices, newexpression));\r
+                                               }\r
+                                       }\r
+                                       else {\r
+                                               workqueue.addLast(current);\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       for (WorkExpression we : workqueue) {\r
+                               String expression = MdlUtil.finalize(we.expression, getMdl());\r
+                               // TODO: is this check correct?\r
+                               if (next == null) {\r
+                                       // Vensim allows comparison of subscript indices which\r
+                                       // is not a meaningful operation in sysdyn, so attempt\r
+                                       // to resolve and remove them here\r
+                                       expression = removeComparisons(expression, indices, we.indices);\r
+                               }\r
+                               expr.addExpression(parseExpression(expression), we.indices);\r
+                       }\r
+                       \r
+                       var = var.getNext();\r
+               }\r
+               \r
+               return expr;\r
+       }\r
+       \r
+       private class WorkExpression {\r
+               String[] indices;\r
+               String expression;\r
+               \r
+               private WorkExpression(String[] indices, String expression) {\r
+                       this.indices = indices;\r
+                       this.expression = expression;\r
+               }\r
+       }\r
+       \r
+       private static String removeComparisons(String expression, String[] subscripts, String[] values) {\r
+               \r
+               if (!expression.contains("=")) {\r
+                       return expression;\r
+               }\r
+                               \r
+               for (int i = 0; i < subscripts.length; i++) {\r
+                       for (int j = 0; j < subscripts.length; j++) {\r
+                               StringBuilder result = new StringBuilder();\r
+                               int offset = 0;\r
+                               \r
+                               Matcher matcher = Pattern.compile(subscripts[i]+"\\s*=\\s*"+subscripts[j]).matcher(expression);\r
+                               while (matcher.find()) {\r
+                                       result.append(expression.substring(offset, matcher.start()));\r
+                                       \r
+                                       if (values[i].equals(values[j])) {\r
+                                               result.append("true");\r
+                                       }\r
+                                       else {\r
+                                               result.append("false");\r
+                                       }\r
+                                       \r
+                                       offset = matcher.end();\r
+                               }\r
+                               if (offset < expression.length()) {\r
+                                       result.append(expression.substring(offset));\r
+                               }\r
+                               \r
+                               expression = result.toString();\r
+                       }\r
+               }\r
+               \r
+               return expression;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Auxiliary.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Auxiliary.java
new file mode 100644 (file)
index 0000000..73d2e28
--- /dev/null
@@ -0,0 +1,29 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public class Auxiliary extends Variable {\r
+       \r
+       public Auxiliary() {\r
+               \r
+       }\r
+       \r
+       public Auxiliary(double[] dim, String name, Expression expression, Range range, String unit, String description) {\r
+               super(dim, name, expression, range, unit, description);\r
+       }\r
+       \r
+       @Override\r
+       public Resource getVariableType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).Auxiliary;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getSymbolType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).AuxiliarySymbol;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Cloud.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Cloud.java
new file mode 100644 (file)
index 0000000..c93d003
--- /dev/null
@@ -0,0 +1,50 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class Cloud extends Symbol {\r
+       \r
+       private Resource cloud;\r
+       \r
+       public Cloud() {\r
+               \r
+       }\r
+       \r
+       public Cloud(double[] dim) {\r
+               super(dim);\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               cloud = GraphUtils.create2(graph, sr.Cloud,\r
+                               l0.HasName, context.getNextCloud(),\r
+                               l0.PartOf, parent);\r
+               \r
+               Resource symbol = super.write(graph, parent, context);\r
+               graph.claim(symbol, mr.ElementToComponent, cloud);\r
+               \r
+               return cloud;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getSymbolType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).CloudSymbol;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getResource() {\r
+               return cloud;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Comment.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Comment.java
new file mode 100644 (file)
index 0000000..06c651c
--- /dev/null
@@ -0,0 +1,57 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class Comment extends Symbol {\r
+       \r
+       private String text;\r
+       \r
+       public Comment() {\r
+               \r
+       }\r
+       \r
+       public Comment(String text) {\r
+               this.text = text;\r
+       }\r
+       \r
+       public Comment(double[] dim, String text) {\r
+               super(dim);\r
+               this.text = text;\r
+       }\r
+\r
+       public String getText() {\r
+               return text;\r
+       }\r
+\r
+       public void setText(String text) {\r
+               this.text = text;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               DiagramResource dr = DiagramResource.getInstance(graph);\r
+               \r
+               Resource symbol = super.write(graph, parent, context);\r
+               \r
+               graph.claimLiteral(symbol, dr.HasText, text, Bindings.STRING);\r
+               \r
+               return symbol;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getSymbolType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).AdditionalSymbols_MultilineText;\r
+       }\r
+\r
+       @Override\r
+       public Resource getResource() {\r
+               // comments only have diagram resources\r
+               return getDiagramResource();\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Connection.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Connection.java
new file mode 100644 (file)
index 0000000..acd124c
--- /dev/null
@@ -0,0 +1,96 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public abstract class Connection implements IWriteableObject {\r
+\r
+       private Symbol head;\r
+       private Symbol tail;\r
+       \r
+       private Resource connection;\r
+       private Resource diagramConnection;\r
+       \r
+       public Connection() {\r
+               \r
+       }\r
+\r
+       public Connection(Symbol tail, Symbol head) {\r
+               this.tail = tail;\r
+               this.head = head;\r
+       }\r
+       \r
+       public Symbol getHead() {\r
+               return head;\r
+       }\r
+\r
+       public void setHead(Symbol head) {\r
+               this.head = head;\r
+       }\r
+\r
+       public Symbol getTail() {\r
+               return tail;\r
+       }\r
+\r
+       public void setTail(Symbol tail) {\r
+               this.tail = tail;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               DiagramResource dr = DiagramResource.getInstance(graph);\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               connection = GraphUtils.create2(graph, getConnectionType(graph),\r
+                               sr.Variable_HasHead, head.getResource(),\r
+                               sr.Variable_HasTail, tail.getResource(),\r
+                               l0.PartOf, parent);\r
+               graph.claim(connection, mr.Mapped, connection);\r
+               \r
+               Resource diagram = graph.getSingleObject(parent, mr.CompositeToDiagram);\r
+               \r
+               Resource tailConnector = GraphUtils.create2(graph, dr.Connector,\r
+                               sr.HasTailTerminal, tail.getDiagramResource());\r
+\r
+               Resource headConnector = GraphUtils.create2(graph, dr.Connector,\r
+                               sr.HasHeadTerminal, head.getDiagramResource(),\r
+                               dr.AreConnected, tailConnector);\r
+\r
+               diagramConnection = GraphUtils.create2(graph, getDiagramConnectionType(graph),\r
+                               l0.HasName, context.getNextObject(),\r
+                               l0.PartOf, diagram,\r
+                               sr2.HasConnectionType, sr.SysdynConnectionType,\r
+                               mr.DiagramConnectionToConnection, connection,\r
+                               dr.HasArrowConnector, headConnector,\r
+                               dr.HasPlainConnector, tailConnector);\r
+\r
+               OrderedSetUtils.add(graph, diagram, diagramConnection);\r
+               \r
+               return connection;\r
+       }\r
+       \r
+       public abstract Resource getConnectionType(ReadGraph graph);\r
+       public abstract Resource getDiagramConnectionType(ReadGraph graph);\r
+       \r
+       @Override\r
+       public Resource getResource() {\r
+               return connection;\r
+       }\r
+       \r
+       public Resource getDiagramResource() {\r
+               return diagramConnection;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Dependency.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Dependency.java
new file mode 100644 (file)
index 0000000..a09c3e8
--- /dev/null
@@ -0,0 +1,87 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class Dependency extends Connection {\r
+       \r
+       private boolean showArrow;\r
+       private boolean showDelay;\r
+       private double angle;\r
+       \r
+       public Dependency() {\r
+               \r
+       }\r
+       \r
+       public Dependency(boolean showArrow, boolean showDelay, double angle) {\r
+               this.showArrow = showArrow;\r
+               this.showDelay = showDelay;\r
+               this.angle = angle;\r
+       }\r
+       \r
+       public Dependency(Symbol tail, Symbol head, boolean showArrow, boolean showDelay, double angle) {\r
+               super(tail, head);\r
+               this.showArrow = showArrow;\r
+               this.showDelay = showDelay;\r
+               this.angle = angle;\r
+       }\r
+\r
+       public boolean isShowArrow() {\r
+               return showArrow;\r
+       }\r
+\r
+       public void setShowArrow(boolean showArrow) {\r
+               this.showArrow = showArrow;\r
+       }\r
+\r
+       public boolean isShowDelay() {\r
+               return showDelay;\r
+       }\r
+\r
+       public void setShowDelay(boolean showDelay) {\r
+               this.showDelay = showDelay;\r
+       }\r
+\r
+       public double getAngle() {\r
+               return angle;\r
+       }\r
+\r
+       public void setAngle(double angle) {\r
+               this.angle = angle;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               if (getHead() == null || getTail() == null) {\r
+                       System.err.println("dependency missing head or tail");\r
+                       return null;\r
+               }\r
+               \r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               Resource dependency = super.write(graph, parent, context);\r
+               graph.claimLiteral(dependency, l0.HasName, context.getNextDependency(), Bindings.STRING);\r
+               \r
+               graph.claimLiteral(getDiagramResource(), sr.Dependency_angle, angle, Bindings.DOUBLE);\r
+               \r
+               return dependency;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getConnectionType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).Dependency;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getDiagramConnectionType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).DependencyConnection;\r
+       }\r
+       \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Flow.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Flow.java
new file mode 100644 (file)
index 0000000..6fb0d8d
--- /dev/null
@@ -0,0 +1,46 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class Flow extends Connection {\r
+       \r
+       public Flow() {\r
+               \r
+       }\r
+       \r
+       public Flow(Symbol tail, Symbol head) {\r
+               super(tail, head);\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               if (getHead() == null || getTail() == null) {\r
+                       System.err.println("flow missing head or tail");\r
+                       return null;\r
+               }\r
+               \r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               \r
+               Resource flow = super.write(graph, parent, context);\r
+               graph.claimLiteral(flow, l0.HasName, context.getNextFlow(), Bindings.STRING);\r
+               \r
+               return flow;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getConnectionType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).Flow;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getDiagramConnectionType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).FlowConnection;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/IWriteableObject.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/IWriteableObject.java
new file mode 100644 (file)
index 0000000..0d327b0
--- /dev/null
@@ -0,0 +1,37 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+\r
+public interface IWriteableObject {\r
+       \r
+       /**\r
+        * Write this object to the graph and return the corresponding resource.\r
+        * \r
+        * @param graph \r
+        * @param parent \r
+        * @param context\r
+        * @return Resource\r
+        * @throws DatabaseException \r
+        */\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException;\r
+       \r
+       /**\r
+        * Return the resource corresponding to this object or null if this object has not been written yet.\r
+        * \r
+        * @return Resource\r
+        */\r
+       public Resource getResource();\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Model.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Model.java
new file mode 100644 (file)
index 0000000..14a82c8
--- /dev/null
@@ -0,0 +1,219 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+import org.simantics.sysdyn.modelImport.model.support.Function;\r
+import org.simantics.sysdyn.utils.ModelUtils;\r
+\r
+public class Model implements IWriteableObject {\r
+       \r
+       private String name;\r
+       // necessary simulation parameters\r
+       private Double start, stop, step;\r
+       private String unit;\r
+       \r
+       // the structure of the model\r
+       private Map<String, Variable> variables;\r
+       private Map<String, Enumeration> enumerations;\r
+       private Map<String, Function> functions;\r
+       \r
+       private List<Symbol> symbols;\r
+       private List<Shadow> shadows;\r
+       private List<Connection> connections;\r
+       \r
+       private Resource model;\r
+       \r
+       public Model(String name) {\r
+               this.name = name;\r
+               \r
+               variables = new HashMap<String, Variable>();\r
+               enumerations = new HashMap<String, Enumeration>();\r
+               functions = new HashMap<String, Function>();\r
+               \r
+               symbols = new ArrayList<Symbol>();\r
+               shadows = new ArrayList<Shadow>();\r
+               connections = new ArrayList<Connection>();\r
+       }\r
+\r
+       public double getStartTime() {\r
+               return start;\r
+       }\r
+\r
+       public void setStartTime(double start) {\r
+               this.start = start;\r
+       }\r
+\r
+       public double getStopTime() {\r
+               return stop;\r
+       }\r
+\r
+       public void setStopTime(double stop) {\r
+               this.stop = stop;\r
+       }\r
+\r
+       public double getTimeStep() {\r
+               return step;\r
+       }\r
+\r
+       public void setTimeStep(double step) {\r
+               this.step = step;\r
+       }\r
+       \r
+       public String getTimeUnit() {\r
+               return unit;\r
+       }\r
+       \r
+       public void setTimeUnit(String unit) {\r
+               this.unit = unit;\r
+       }\r
+       \r
+       public void addVariable(Variable variable) {\r
+               if (variables.get(variable.getName()) != null) {\r
+                       System.err.println("variable "+variable.getName()+" already defined");\r
+                       return;\r
+               }\r
+               \r
+               variables.put(variable.getName(), variable);\r
+               \r
+               symbols.add(variable);\r
+       }\r
+       \r
+       public Variable getVariable(String name) {\r
+               return variables.get(name);\r
+       }\r
+       \r
+       public Collection<Variable> getVariables() {\r
+               return variables.values();\r
+       }\r
+       \r
+       public void addShadow(Shadow shadow) {\r
+               shadows.add(shadow);\r
+       }\r
+               \r
+       public void addSymbol(Symbol element) {\r
+               symbols.add(element);\r
+       }\r
+       \r
+       public void addConnection(Connection connection) {\r
+               // TODO: make sure connection head and tail exist\r
+               connections.add(connection);\r
+       }\r
+       \r
+       public void addEnumeration(Enumeration enumeration) {\r
+               if (enumerations.get(enumeration.getName()) != null) {\r
+                       System.err.println("enumeration "+enumeration.getName()+" already defined");\r
+                       return;\r
+               }\r
+               enumerations.put(enumeration.getName(), enumeration);\r
+       }\r
+       \r
+       public Enumeration getEnumeration(String name) {\r
+               return enumerations.get(name);\r
+       }\r
+       \r
+       public Collection<Enumeration> getEnumerations() {\r
+               return enumerations.values();\r
+       }\r
+       \r
+       public void addFunction(Function function) {\r
+               if (functions.get(function.getName()) != null) {\r
+                       System.err.println("function "+function.getName()+" already defined");\r
+                       return;\r
+               }\r
+               functions.put(function.getName(), function);\r
+       }\r
+       \r
+       public Function getEFunction(String name) {\r
+               return functions.get(name);\r
+       }\r
+       \r
+       public Collection<Function> getFunctions() {\r
+               return functions.values();\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               DiagramResource dr = DiagramResource.getInstance(graph);\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               SimulationResource sim = SimulationResource.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               model = ModelUtils.createModel(graph);\r
+               \r
+               Resource container = graph.getSingleObject(model, l0.PartOf);\r
+               String freshName = NameUtils.findFreshName(graph, name, container, l0.ConsistsOf, "%s%d");\r
+               graph.claimLiteral(model, l0.HasName, freshName, Bindings.STRING);\r
+               graph.claimLiteral(model, l0.HasLabel, freshName, Bindings.STRING);\r
+               \r
+               // TODO: this must be updated if/when simulation parameters are moved \r
+               // from model to experiment\r
+               if (start != null)\r
+                       graph.claimLiteral(model, sr.SysdynModel_startTime, start, Bindings.DOUBLE);\r
+               if (stop != null)\r
+                       graph.claimLiteral(model, sr.SysdynModel_stopTime, stop, Bindings.DOUBLE);\r
+               if (step != null)\r
+                       graph.claimLiteral(model, sr.SysdynModel_simulationStepLength, step, Bindings.DOUBLE);\r
+               if (unit != null)\r
+                       graph.claimLiteral(model, sr.SysdynModel_timeUnit, unit, Bindings.STRING);\r
+               \r
+               Resource configuration = graph.getSingleObject(model, sim.HasConfiguration);\r
+               \r
+               for (Enumeration e : getEnumerations()) {\r
+                       e.write(graph, configuration, context);\r
+               }\r
+               \r
+               for (Function f : getFunctions()) {\r
+                       f.write(graph, model, context);\r
+               }\r
+               \r
+               for (Symbol e : symbols) {\r
+                       e.write(graph, configuration, context);\r
+               }\r
+               \r
+               for (Shadow s : shadows) {\r
+                       s.write(graph, configuration, context);\r
+               }\r
+               \r
+               for (Connection c : connections) {\r
+                       c.write(graph, configuration, context);\r
+               }\r
+               \r
+               Resource diagram = graph.getSingleObject(configuration, mr.CompositeToDiagram);\r
+               graph.claimLiteral(diagram, dr.HasModCount, context.getObjectCount(), Bindings.LONG);\r
+               \r
+               return model;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getResource() {\r
+               return model;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Shadow.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Shadow.java
new file mode 100644 (file)
index 0000000..228b509
--- /dev/null
@@ -0,0 +1,67 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class Shadow extends Symbol {\r
+\r
+       private Variable original;\r
+       \r
+       private Resource shadow;\r
+       \r
+       public Shadow() {\r
+               \r
+       }\r
+       \r
+       public Shadow(Variable original) {\r
+               this.original = original;\r
+       }\r
+       \r
+       public Shadow(double[] dim, Variable original) {\r
+               super(dim);\r
+               this.original = original;\r
+       }\r
+\r
+       public Variable getOriginal() {\r
+               return original;\r
+       }\r
+\r
+       public void setOriginal(Variable original) {\r
+               this.original = original;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               shadow = GraphUtils.create2(graph, sr.Shadow,\r
+                               l0.HasName, context.getNextShadow(),\r
+                               l0.PartOf, parent);\r
+               \r
+               graph.claim(shadow, sr.Shadow_original, original.getResource());\r
+               \r
+               Resource symbol = super.write(graph, parent, context);\r
+               graph.claim(symbol, mr.ElementToComponent, shadow);\r
+               \r
+               return shadow;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getSymbolType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).ShadowSymbol;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getResource() {\r
+               return shadow;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Stock.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Stock.java
new file mode 100644 (file)
index 0000000..1e658ed
--- /dev/null
@@ -0,0 +1,29 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.expression.IntegralExpression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public class Stock extends Variable {\r
+       \r
+       public Stock() {\r
+               \r
+       }\r
+       \r
+       public Stock(double[] dim, String name, IntegralExpression expression, Range range, String unit, String description) {\r
+               super(dim, name, expression, range, unit, description);\r
+       }\r
+       \r
+       @Override\r
+       public Resource getVariableType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).Stock;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getSymbolType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).StockSymbol;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Symbol.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Symbol.java
new file mode 100644 (file)
index 0000000..18e76cf
--- /dev/null
@@ -0,0 +1,101 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.OrderedSetUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+\r
+public abstract class Symbol implements IWriteableObject {\r
+       \r
+       private double x;\r
+       private double y;\r
+       private double width;\r
+       private double height;\r
+\r
+       private Resource symbol;\r
+       \r
+       public Symbol() {\r
+               \r
+       }\r
+\r
+       public Symbol(double[] dim) {\r
+               x = dim[0];\r
+               y = dim[1];\r
+               width = dim[2];\r
+               height = dim[3];\r
+       }\r
+       \r
+       public void setDimensions(double[] dim) {\r
+               x = dim[0];\r
+               y = dim[1];\r
+               width = dim[2];\r
+               height = dim[3];\r
+       }\r
+\r
+       public double getX() {\r
+               return x;\r
+       }\r
+\r
+       public void setX(double x) {\r
+               this.x = x;\r
+       }\r
+\r
+       public double getY() {\r
+               return y;\r
+       }\r
+\r
+       public void setY(double y) {\r
+               this.y = y;\r
+       }\r
+\r
+       public double getWidth() {\r
+               return width;\r
+       }\r
+\r
+       public void setWidth(double width) {\r
+               this.width = width;\r
+       }\r
+\r
+       public double getHeight() {\r
+               return height;\r
+       }\r
+\r
+       public void setHeight(double height) {\r
+               this.height = height;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               DiagramResource dr = DiagramResource.getInstance(graph);\r
+               G2DResource g2d = G2DResource.getInstance(graph);\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+\r
+               Resource diagram = graph.getSingleObject(parent, mr.CompositeToDiagram);\r
+               \r
+               symbol = GraphUtils.create2(graph, getSymbolType(graph),\r
+                               l0.HasName, context.getNextObject(),\r
+                               l0.PartOf, diagram);\r
+\r
+               double[] transform = { 1.0, 0.0, 0.0, 1.0, x, y };\r
+               graph.claimLiteral(symbol, dr.HasTransform, g2d.Transform, transform, Bindings.DOUBLE_ARRAY);\r
+\r
+               OrderedSetUtils.add(graph, diagram, symbol);\r
+               \r
+               return symbol;\r
+       }\r
+       \r
+       public abstract Resource getSymbolType(ReadGraph graph);\r
+       \r
+       public Resource getDiagramResource() {\r
+               return symbol;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Valve.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Valve.java
new file mode 100644 (file)
index 0000000..011b3c1
--- /dev/null
@@ -0,0 +1,87 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public class Valve extends Variable {\r
+       \r
+       public enum Orientation {\r
+               HORIZONTAL, VERTICAL\r
+       }\r
+       \r
+       public enum TextPosition {\r
+               INSIDE, BELOW, LEFT, ABOVE, RIGHT, UNSET\r
+       }\r
+       \r
+       private Orientation orientation;\r
+       private TextPosition position;\r
+       \r
+       public Valve() {\r
+               \r
+       }\r
+       \r
+       public Valve(Orientation orientation, TextPosition position) {\r
+               this.orientation = orientation;\r
+               this.position = position;\r
+       }\r
+       \r
+       public Valve(double[] dim, String name, Expression expression, Range range, String unit, String description, \r
+                       Orientation orientation, TextPosition position) {\r
+               super(dim, name, expression, range, unit, description);\r
+               this.orientation = orientation;\r
+               this.position = position;\r
+       }\r
+\r
+       public Orientation getOrientation() {\r
+               return orientation;\r
+       }\r
+\r
+       public void setOrientation(Orientation orientation) {\r
+               this.orientation = orientation;\r
+       }\r
+\r
+       public TextPosition getPosition() {\r
+               return position;\r
+       }\r
+\r
+       public void setPosition(TextPosition position) {\r
+               this.position = position;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+               Resource location = null;\r
+               switch (position) {\r
+               case BELOW: location = sr.Bottom; break;\r
+               case LEFT: location = sr.Left; break;\r
+               case ABOVE: location = sr.Top; break;\r
+               case RIGHT: location = sr.Right; break;\r
+               case UNSET:\r
+               default: System.err.println("valve text location not set"); location = sr.Bottom; break;\r
+               }\r
+               \r
+               Resource valve = super.write(graph, parent, context);\r
+               \r
+               graph.claim(getDiagramResource(), sr.ValveSymbol_textLocation, location);\r
+               \r
+               return valve;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getVariableType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).Valve;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getSymbolType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).ValveSymbol;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Variable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/Variable.java
new file mode 100644 (file)
index 0000000..c29b46b
--- /dev/null
@@ -0,0 +1,125 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.expression.Expression;\r
+import org.simantics.sysdyn.modelImport.model.support.Range;\r
+\r
+public abstract class Variable extends Symbol {\r
+\r
+       private String name;\r
+       private Expression expression;\r
+       private Range range;\r
+       private String unit;\r
+       private String description;\r
+       \r
+       private Resource variable;\r
+       \r
+       public Variable() {\r
+               \r
+       }\r
+       \r
+       public Variable(String name, Expression expression, Range range, String unit, String description) {\r
+               this.name = name;\r
+               this.expression = expression;\r
+               this.range = range;\r
+               this.unit = unit;\r
+               this.description = description;\r
+       }\r
+\r
+       public Variable(double[] dim, String name, Expression expression, Range range, String unit, String description) {\r
+               super(dim);\r
+               this.name = name;\r
+               this.expression = expression;\r
+               this.range = range;\r
+               this.unit = unit;\r
+               this.description = description;\r
+       }\r
+\r
+       public String getName() {\r
+               return name;\r
+       }\r
+\r
+       public void setName(String name) {\r
+               this.name = name;\r
+       }\r
+\r
+       public Expression getExpression() {\r
+               return expression;\r
+       }\r
+\r
+       public void setExpression(Expression expression) {\r
+               this.expression = expression;\r
+       }\r
+\r
+       public Range getRange() {\r
+               return range;\r
+       }\r
+\r
+       public void setRange(Range range) {\r
+               this.range = range;\r
+       }\r
+\r
+       public String getUnit() {\r
+               return unit;\r
+       }\r
+\r
+       public void setUnit(String unit) {\r
+               this.unit = unit;\r
+       }\r
+\r
+       public String getDescription() {\r
+               return description;\r
+       }\r
+\r
+       public void setDescription(String description) {\r
+               this.description = description;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               ModelingResources mr = ModelingResources.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+               variable = GraphUtils.create2(graph, getVariableType(graph), \r
+                               l0.HasName, name,\r
+                               l0.PartOf, parent);\r
+               graph.claim(variable, mr.Mapped, variable);\r
+               \r
+               // TODO: write references to enumerations here?\r
+               \r
+               if (expression != null) {\r
+                       expression.write(graph, variable, context);\r
+               }\r
+               if (range != null) {\r
+                       range.write(graph, variable, context);\r
+               }\r
+               if (unit != null && !unit.isEmpty()) {\r
+                       graph.claimLiteral(variable, sr.Variable_unit, unit, Bindings.STRING);\r
+               }\r
+               if (description != null && !description.isEmpty()) {\r
+                       graph.claimLiteral(variable, l0.HasDescription, description, Bindings.STRING);\r
+               }\r
+               \r
+               Resource symbol = super.write(graph, parent, context);\r
+               graph.claim(symbol, mr.ElementToComponent, variable);\r
+\r
+               return variable;\r
+       }\r
+       \r
+       public abstract Resource getVariableType(ReadGraph graph);\r
+       \r
+       @Override\r
+       public Resource getResource() {\r
+               return variable;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/WriteContext.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/WriteContext.java
new file mode 100644 (file)
index 0000000..4a00b01
--- /dev/null
@@ -0,0 +1,45 @@
+package org.simantics.sysdyn.modelImport.model;\r
+\r
+public class WriteContext {\r
+       \r
+       private long objectCount;\r
+       \r
+       private long cloudCount;\r
+       private long shadowCount;\r
+       private long dependencyCount;\r
+       private long flowCount;\r
+       \r
+       public WriteContext() {\r
+               objectCount = 0;\r
+               \r
+               cloudCount = 0;\r
+               shadowCount = 0;\r
+               dependencyCount = 0;\r
+               flowCount = 0;\r
+       }\r
+       \r
+       public String getNextObject() {\r
+               return Long.toString(objectCount++);\r
+       }\r
+       \r
+       public long getObjectCount() {\r
+               return objectCount;\r
+       }\r
+       \r
+       public String getNextCloud() {\r
+               return "Cloud" + cloudCount++;\r
+       }\r
+       \r
+       public String getNextShadow() {\r
+               return "Shadow" + shadowCount++;\r
+       }\r
+       \r
+       public String getNextDependency() {\r
+               return "Dependency" + dependencyCount++;\r
+       }\r
+       \r
+       public String getNextFlow() {\r
+               return "Flow" + flowCount++;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/DelayExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/DelayExpression.java
new file mode 100644 (file)
index 0000000..95e88ef
--- /dev/null
@@ -0,0 +1,48 @@
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class DelayExpression extends Expression {\r
+       \r
+       private String expression;\r
+       private String time;\r
+       private String initial;\r
+       private int order;\r
+       \r
+       public DelayExpression(String expression, String time, String initial, int order) {\r
+               this.expression = expression;\r
+               this.time = time;\r
+               this.initial = initial;\r
+               this.order = order;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               Resource expr = super.write(graph, parent, context);\r
+               \r
+               graph.claimLiteral(expr, sr.DelayExpression_expression, expression, Bindings.STRING);\r
+               graph.claimLiteral(expr, sr.DelayExpression_delayTime, time, Bindings.STRING);\r
+               graph.claimLiteral(expr, sr.DelayExpression_initialValue, initial, Bindings.STRING);\r
+               graph.claimLiteral(expr, sr.DelayExpression_order, order, Bindings.INTEGER);\r
+               \r
+               return expr;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getExpressionType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).DelayExpression;\r
+       }\r
+       \r
+       @Override\r
+       public String getExpressionTypeString() {\r
+               return "DelayExpression";\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/EnumerationExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/EnumerationExpression.java
new file mode 100644 (file)
index 0000000..5cad2cf
--- /dev/null
@@ -0,0 +1,87 @@
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+import org.simantics.sysdyn.modelImport.model.support.Enumeration;\r
+\r
+public class EnumerationExpression extends Expression {\r
+       \r
+       private List<Enumeration> enumerations;\r
+       private List<EnumerationSubExpression> subExpressions;\r
+       \r
+       public EnumerationExpression(List<Enumeration> enumerations) {\r
+               this.enumerations = enumerations;\r
+               this.subExpressions = new ArrayList<EnumerationSubExpression>();\r
+       }\r
+       \r
+       public void addExpression(Expression expression, String...indices) {\r
+               subExpressions.add(new EnumerationSubExpression(expression, indices));\r
+       }\r
+       \r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               for (EnumerationSubExpression subexpr : subExpressions) {\r
+                       StringBuilder range = new StringBuilder();\r
+                       range.append('[');\r
+                       for (int i = 0; i < subexpr.indices.length; i++) {\r
+                               if (i > 0)\r
+                                       range.append(',');\r
+                               range.append(subexpr.indices[i]);\r
+                       }\r
+                       range.append(']');\r
+                       \r
+                       Resource res = subexpr.expression.write(graph, parent, context);\r
+                       \r
+                       graph.claimLiteral(res, sr.Expression_arrayRange, range.toString(), Bindings.STRING);\r
+               }\r
+               \r
+               ArrayList<Resource> indexlist = new ArrayList<Resource>();\r
+               for (Enumeration enumeration : enumerations) {\r
+                       indexlist.add(enumeration.getResource());\r
+               }\r
+               \r
+               // write array index list\r
+               graph.claim(parent, sr.Variable_arrayIndexesList, ListUtils.create(graph, indexlist));\r
+               \r
+               // TODO: set active expression?\r
+               \r
+               return getResource();\r
+       }\r
+\r
+       @Override\r
+       public Resource getExpressionType(ReadGraph graph) {\r
+               return subExpressions.get(0).expression.getExpressionType(graph);\r
+       }\r
+       \r
+       @Override\r
+       public String getExpressionTypeString() {\r
+               return subExpressions.get(0).expression.getExpressionTypeString();\r
+       }\r
+       \r
+       @Override\r
+       public Resource getResource() {\r
+               return subExpressions.get(0).expression.getResource();\r
+       }\r
+       \r
+       private class EnumerationSubExpression {\r
+               \r
+               Expression expression;\r
+               String[] indices;\r
+               \r
+               public EnumerationSubExpression(Expression expression, String...indices) {\r
+                       this.expression = expression;\r
+                       this.indices = indices;\r
+               }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/Expression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/Expression.java
new file mode 100644 (file)
index 0000000..c930084
--- /dev/null
@@ -0,0 +1,49 @@
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import java.util.Arrays;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public abstract class Expression implements IWriteableObject {\r
+\r
+       private Resource expr;\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               expr = GraphUtils.create2(graph, getExpressionType(graph),\r
+                               l0.PartOf, parent);\r
+\r
+               // insert the expression into the expression list of the variable \r
+               // (necessary because of enumeration expressions)\r
+               Resource list = graph.getPossibleObject(parent, sr.Variable_expressionList);\r
+               if (list != null) {\r
+                       ListUtils.insertBack(graph, list, Arrays.asList(expr));\r
+               }\r
+               else {\r
+                       graph.claim(parent, sr.Variable_expressionList, ListUtils.create(graph, Arrays.asList(expr)));\r
+               }\r
+               \r
+               return expr;\r
+       }\r
+       \r
+       public abstract Resource getExpressionType(ReadGraph graph);\r
+       \r
+       public abstract String getExpressionTypeString();\r
+\r
+       @Override\r
+       public Resource getResource() {\r
+               return expr;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/IntegralExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/IntegralExpression.java
new file mode 100644 (file)
index 0000000..3ca709f
--- /dev/null
@@ -0,0 +1,43 @@
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class IntegralExpression extends Expression {\r
+       \r
+       private String integral;\r
+       private String initial;\r
+       \r
+       public IntegralExpression(String integral, String initial) {\r
+               this.integral = integral;\r
+               this.initial = initial;\r
+       }\r
+       \r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               Resource expr = super.write(graph, parent, context);\r
+               \r
+               graph.claimLiteral(expr, sr.StockExpression_integralEquation, integral, Bindings.STRING);\r
+               graph.claimLiteral(expr, sr.StockExpression_initialEquation, initial, Bindings.STRING);\r
+               graph.claim(expr, sr.StockExpression_useCustomIntegral, expr);\r
+               \r
+               return expr;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getExpressionType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).StockExpression;\r
+       }\r
+       \r
+       @Override\r
+       public String getExpressionTypeString() {\r
+               return "StockExpression";\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/LookupExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/LookupExpression.java
new file mode 100644 (file)
index 0000000..efcd9b2
--- /dev/null
@@ -0,0 +1,66 @@
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class LookupExpression extends Expression {\r
+       \r
+       private String expression;\r
+       private double xMin;\r
+       private double yMin;\r
+       private double xMax;\r
+       private double yMax;\r
+       private double[] points;\r
+       \r
+       public LookupExpression(String expression, double xMin, double yMin, double xMax, double yMax, double[] points) {\r
+               this.expression = expression;\r
+               this.xMin = xMin;\r
+               this.yMin = yMin;\r
+               this.xMax = xMax;\r
+               this.yMax = yMax;\r
+               this.points = points;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               StringBuilder lookup = new StringBuilder();\r
+               lookup.append('{');\r
+               for (int i = 0; i < points.length / 2; i++) {\r
+                       if (i > 0) {\r
+                               lookup.append(',');\r
+                       }\r
+                       lookup.append('{').append(points[2*i]).append(',').append(points[2*i+1]).append('}');\r
+               }\r
+               lookup.append('}');\r
+               \r
+               Resource expr = super.write(graph, parent, context);\r
+               \r
+               // TODO: fix this\r
+               graph.claimLiteral(expr, sr.WithLookupExpression_expression, expression, Bindings.STRING);\r
+               graph.claimLiteral(expr, sr.WithLookupExpression_lookup, lookup.toString(), Bindings.STRING);\r
+               graph.claimLiteral(expr, sr.WithLookupExpression_minX, xMin, Bindings.DOUBLE);\r
+               graph.claimLiteral(expr, sr.WithLookupExpression_minY, yMin, Bindings.DOUBLE);\r
+               graph.claimLiteral(expr, sr.WithLookupExpression_maxX, xMax, Bindings.DOUBLE);\r
+               graph.claimLiteral(expr, sr.WithLookupExpression_maxY, yMax, Bindings.DOUBLE);\r
+               \r
+               return expr;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getExpressionType(ReadGraph graph) {\r
+               return SysdynResource.getInstance(graph).WithLookupExpression;\r
+       }\r
+       \r
+       @Override\r
+       public String getExpressionTypeString() {\r
+               return "WithLookupExpression";\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/NormalExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/expression/NormalExpression.java
new file mode 100644 (file)
index 0000000..b1efa51
--- /dev/null
@@ -0,0 +1,51 @@
+package org.simantics.sysdyn.modelImport.model.expression;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class NormalExpression extends Expression {\r
+\r
+       private String expression;\r
+       \r
+       public NormalExpression(String expression) {\r
+               this.expression = expression;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               Resource expr = super.write(graph, parent, context);\r
+               \r
+               graph.claimLiteral(expr, sr.Expression_equation, expression, Bindings.STRING);\r
+               \r
+               return expr;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getExpressionType(ReadGraph graph) {\r
+               try {\r
+                       Double.parseDouble(expression);\r
+                       return SysdynResource.getInstance(graph).ParameterExpression;\r
+               }\r
+               catch (NumberFormatException e) {\r
+                       return SysdynResource.getInstance(graph).NormalExpression;\r
+               }\r
+       }\r
+       \r
+       @Override\r
+       public String getExpressionTypeString() {\r
+               try {\r
+                       Double.parseDouble(expression);\r
+                       return "ParameterExpression";\r
+               }\r
+               catch (NumberFormatException e) {\r
+                       return "NormalExpression";\r
+               }\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Enumeration.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Enumeration.java
new file mode 100644 (file)
index 0000000..2a6e8e9
--- /dev/null
@@ -0,0 +1,62 @@
+package org.simantics.sysdyn.modelImport.model.support;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Enumeration implements IWriteableObject {\r
+       \r
+       private String name;\r
+       private List<String> values;\r
+       \r
+       private Resource enumeration;\r
+       \r
+       public Enumeration(String name, List<String> values) {\r
+               this.name = name;\r
+               this.values = values;\r
+       }\r
+       \r
+       public String getName() {\r
+               return name;\r
+       }\r
+       \r
+       public List<String> getValues() {\r
+               return values;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context)\r
+                       throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               enumeration = GraphUtils.create2(graph, sr.Enumeration,\r
+                               l0.HasName, name,\r
+                               l0.PartOf, parent);\r
+               \r
+               List<Resource> indices = new ArrayList<Resource>();\r
+               for (String index : values) {\r
+                       indices.add(GraphUtils.create2(graph, sr.EnumerationIndex,\r
+                                       l0.HasName, index));\r
+               }\r
+               \r
+               graph.claim(enumeration, sr.Enumeration_enumerationIndexList, ListUtils.create(graph, indices));\r
+               \r
+               return enumeration;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getResource() {\r
+               return enumeration;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Function.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Function.java
new file mode 100644 (file)
index 0000000..9f17087
--- /dev/null
@@ -0,0 +1,65 @@
+package org.simantics.sysdyn.modelImport.model.support;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Function implements IWriteableObject {\r
+\r
+       private String name;\r
+       private String body;\r
+       private String description;\r
+       \r
+       private Resource function;\r
+       \r
+       public Function(String name, String body) {\r
+               this(name, body, null);\r
+       }\r
+       \r
+       public Function(String name, String body, String description) {\r
+               this.name = name;\r
+               this.body = body;\r
+               this.description = description;\r
+       }\r
+       \r
+       public String getName() {\r
+               return name;\r
+       }\r
+       \r
+       public String getBody() {\r
+               return body;\r
+       }\r
+       \r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource parent, WriteContext context) \r
+                       throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(graph);\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+               \r
+               function = GraphUtils.create2(graph, sr.SysdynModelicaFunction, \r
+                               l0.HasName, name,\r
+                               l0.PartOf, parent);\r
+               \r
+               graph.claimLiteral(function, sr.SysdynModelicaFunction_modelicaFunctionCode, body, Bindings.STRING);\r
+               \r
+               if (description != null) {\r
+                       graph.claimLiteral(function, l0.HasDescription, body, Bindings.STRING);\r
+               }\r
+               \r
+               // TODO: should alco handle inputs and outputs somehow\r
+               \r
+               return function;\r
+       }\r
+\r
+       @Override\r
+       public Resource getResource() {\r
+               return function;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Range.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelImport/model/support/Range.java
new file mode 100644 (file)
index 0000000..bfcf236
--- /dev/null
@@ -0,0 +1,46 @@
+package org.simantics.sysdyn.modelImport.model.support;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.modelImport.model.IWriteableObject;\r
+import org.simantics.sysdyn.modelImport.model.WriteContext;\r
+\r
+public class Range implements IWriteableObject {\r
+       \r
+       private Double start;\r
+       private Double end;\r
+       private Double step;\r
+       \r
+       private Resource resource;\r
+       \r
+       public Range(Double start, Double end, Double step) {\r
+               this.start = start;\r
+               this.end = end;\r
+               this.step = step;\r
+       }\r
+       \r
+       public Double getStart() {\r
+               return start;\r
+       }\r
+\r
+       public Double getEnd() {\r
+               return end;\r
+       }\r
+\r
+       public Double getStep() {\r
+               return step;\r
+       }\r
+\r
+       @Override\r
+       public Resource write(WriteGraph graph, Resource variable, WriteContext context) throws DatabaseException {\r
+               // TODO: implementation\r
+               return null;\r
+       }\r
+       \r
+       @Override\r
+       public Resource getResource() {\r
+               return resource;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParser.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParser.java
new file mode 100644 (file)
index 0000000..5f89fce
--- /dev/null
@@ -0,0 +1,3880 @@
+/* Generated By:JavaCC: Do not edit this line. ModelParser.java */\r
+package org.simantics.sysdyn.modelParser;\r
+\r
+import java.util.ArrayList;\r
+\r
+@SuppressWarnings({"unused", "serial"})\r
+public class ModelParser implements ModelParserConstants {\r
+\r
+  private ArrayList<Parameter> inputs = new ArrayList<Parameter>();\r
+  private ArrayList<Parameter> outputs = new ArrayList<Parameter>();\r
+\r
+  private enum InterfaceVariableType\r
+  {\r
+    INPUT, OUTPUT, OTHER\r
+  }\r
+\r
+  public class Parameter\r
+  {\r
+    public String name;\r
+    public boolean optional;\r
+    public String description;\r
+    public String type;\r
+\r
+    public Parameter()\r
+    {\r
+      name = new String("");\r
+      optional = false;\r
+      description = null;\r
+      type = null;\r
+    }\r
+  }\r
+\r
+  public ArrayList<Parameter> getInputs()\r
+  {\r
+    return inputs;\r
+  }\r
+\r
+  public ArrayList<Parameter> getOutputs()\r
+  {\r
+    return outputs;\r
+  }\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+  final public void parse() throws ParseException {\r
+        jj_input_stream.setTabSize(1);\r
+    stored_definition();\r
+    jj_consume_token(0);\r
+  }\r
+\r
+/*** Stored Definition - Within ************************************/\r
+  final public void stored_definition() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 53:\r
+      jj_consume_token(53);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+      case IDENT:\r
+        name();\r
+        break;\r
+      default:\r
+        jj_la1[0] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(70);\r
+      break;\r
+    default:\r
+      jj_la1[1] = jj_gen;\r
+      ;\r
+    }\r
+    label_1:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 7:\r
+      case 11:\r
+      case 17:\r
+      case 24:\r
+      case 26:\r
+      case 30:\r
+      case 34:\r
+      case 37:\r
+      case 38:\r
+      case 44:\r
+      case 47:\r
+      case 50:\r
+      case 61:\r
+      case 94:\r
+      case 95:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[2] = jj_gen;\r
+        break label_1;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 11:\r
+        jj_consume_token(11);\r
+        break;\r
+      default:\r
+        jj_la1[3] = jj_gen;\r
+        ;\r
+      }\r
+      class_definition();\r
+      jj_consume_token(70);\r
+    }\r
+  }\r
+\r
+/*** Class Definition **********************************************/\r
+  final public void class_definition() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 30:\r
+      jj_consume_token(30);\r
+      break;\r
+    default:\r
+      jj_la1[4] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 47:\r
+      jj_consume_token(47);\r
+      break;\r
+    default:\r
+      jj_la1[5] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 34:\r
+      jj_consume_token(34);\r
+      break;\r
+    case 7:\r
+      jj_consume_token(7);\r
+      break;\r
+    case 61:\r
+      jj_consume_token(61);\r
+      break;\r
+    case 24:\r
+      jj_consume_token(24);\r
+      break;\r
+    case 44:\r
+    case 50:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 50:\r
+        jj_consume_token(50);\r
+        break;\r
+      default:\r
+        jj_la1[6] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(44);\r
+      break;\r
+    case 38:\r
+      jj_consume_token(38);\r
+      break;\r
+    case 37:\r
+      jj_consume_token(37);\r
+      break;\r
+    case 26:\r
+      jj_consume_token(26);\r
+      break;\r
+    case 17:\r
+      jj_consume_token(17);\r
+      break;\r
+    case 94:\r
+      jj_consume_token(94);\r
+      break;\r
+    case 95:\r
+      jj_consume_token(95);\r
+      break;\r
+    default:\r
+      jj_la1[7] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+    class_specifier();\r
+  }\r
+\r
+  final public void class_specifier() throws ParseException {\r
+    if (jj_2_1(2)) {\r
+      jj_consume_token(IDENT);\r
+      string_comment();\r
+      composition();\r
+      jj_consume_token(35);\r
+      jj_consume_token(IDENT);\r
+    } else if (jj_2_2(2)) {\r
+      jj_consume_token(IDENT);\r
+      jj_consume_token(88);\r
+      base_prefix();\r
+      name();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 66:\r
+        array_subscripts();\r
+        break;\r
+      default:\r
+        jj_la1[8] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 62:\r
+        class_modification();\r
+        break;\r
+      default:\r
+        jj_la1[9] = jj_gen;\r
+        ;\r
+      }\r
+      comment();\r
+    } else if (jj_2_3(3)) {\r
+      jj_consume_token(IDENT);\r
+      jj_consume_token(88);\r
+      jj_consume_token(40);\r
+      jj_consume_token(62);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case IDENT:\r
+        enum_list();\r
+        break;\r
+      default:\r
+        jj_la1[10] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(63);\r
+      comment();\r
+    } else if (jj_2_4(3)) {\r
+      jj_consume_token(IDENT);\r
+      jj_consume_token(88);\r
+      jj_consume_token(58);\r
+      jj_consume_token(62);\r
+      name();\r
+      jj_consume_token(71);\r
+      jj_consume_token(IDENT);\r
+      label_2:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[11] = jj_gen;\r
+          break label_2;\r
+        }\r
+        jj_consume_token(71);\r
+        jj_consume_token(IDENT);\r
+      }\r
+      jj_consume_token(63);\r
+      comment();\r
+    } else {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 55:\r
+        jj_consume_token(55);\r
+        jj_consume_token(IDENT);\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 62:\r
+          class_modification();\r
+          break;\r
+        default:\r
+          jj_la1[12] = jj_gen;\r
+          ;\r
+        }\r
+        string_comment();\r
+        composition();\r
+        jj_consume_token(35);\r
+        jj_consume_token(IDENT);\r
+        break;\r
+      default:\r
+        jj_la1[13] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void base_prefix() throws ParseException {\r
+    type_prefix();\r
+  }\r
+\r
+  final public void enum_list() throws ParseException {\r
+    enumeration_literal();\r
+    label_3:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[14] = jj_gen;\r
+        break label_3;\r
+      }\r
+      jj_consume_token(71);\r
+      enumeration_literal();\r
+    }\r
+  }\r
+\r
+  final public void enumeration_literal() throws ParseException {\r
+    jj_consume_token(IDENT);\r
+    comment();\r
+  }\r
+\r
+  final public void parse_composition() throws ParseException {\r
+    composition();\r
+    jj_consume_token(0);\r
+  }\r
+\r
+  final public void composition() throws ParseException {\r
+    element_list();\r
+    label_4:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 4:\r
+      case 45:\r
+      case 46:\r
+      case 52:\r
+      case 57:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[15] = jj_gen;\r
+        break label_4;\r
+      }\r
+      if (jj_2_5(2)) {\r
+        jj_consume_token(57);\r
+        element_list();\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 52:\r
+          jj_consume_token(52);\r
+          element_list();\r
+          break;\r
+        case 45:\r
+        case 46:\r
+          equation_section();\r
+          break;\r
+        case 4:\r
+          algorithm_section();\r
+          break;\r
+        default:\r
+          jj_la1[16] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 59:\r
+      jj_consume_token(59);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case STRING:\r
+        language_specification();\r
+        break;\r
+      default:\r
+        jj_la1[17] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+      case IDENT:\r
+        external_function_call();\r
+        break;\r
+      default:\r
+        jj_la1[18] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 14:\r
+        annotation();\r
+        break;\r
+      default:\r
+        jj_la1[19] = jj_gen;\r
+        ;\r
+      }\r
+      jj_consume_token(70);\r
+      break;\r
+    default:\r
+      jj_la1[20] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 14:\r
+      annotation();\r
+      jj_consume_token(70);\r
+      break;\r
+    default:\r
+      jj_la1[21] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void language_specification() throws ParseException {\r
+    jj_consume_token(STRING);\r
+  }\r
+\r
+  final public void external_function_call() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 68:\r
+    case IDENT:\r
+      component_reference();\r
+      jj_consume_token(88);\r
+      break;\r
+    default:\r
+      jj_la1[22] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(IDENT);\r
+    jj_consume_token(62);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 31:\r
+    case 33:\r
+    case 35:\r
+    case 46:\r
+    case 58:\r
+    case 62:\r
+    case 64:\r
+    case 66:\r
+    case 68:\r
+    case 78:\r
+    case 79:\r
+    case 80:\r
+    case 81:\r
+    case IDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      expression_list();\r
+      break;\r
+    default:\r
+      jj_la1[23] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(63);\r
+  }\r
+\r
+  final public void element_list() throws ParseException {\r
+    label_5:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 5:\r
+      case 7:\r
+      case 8:\r
+      case 11:\r
+      case 13:\r
+      case 16:\r
+      case 17:\r
+      case 23:\r
+      case 24:\r
+      case 26:\r
+      case 27:\r
+      case 30:\r
+      case 32:\r
+      case 34:\r
+      case 36:\r
+      case 37:\r
+      case 38:\r
+      case 42:\r
+      case 44:\r
+      case 47:\r
+      case 49:\r
+      case 50:\r
+      case 51:\r
+      case 55:\r
+      case 56:\r
+      case 61:\r
+      case 68:\r
+      case IDENT:\r
+      case 94:\r
+      case 95:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[24] = jj_gen;\r
+        break label_5;\r
+      }\r
+      element();\r
+      jj_consume_token(70);\r
+    }\r
+  }\r
+\r
+  final public void element() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 36:\r
+      import_clause();\r
+      break;\r
+    case 55:\r
+      extends_clause();\r
+      break;\r
+    case 5:\r
+    case 7:\r
+    case 8:\r
+    case 11:\r
+    case 13:\r
+    case 16:\r
+    case 17:\r
+    case 23:\r
+    case 24:\r
+    case 26:\r
+    case 27:\r
+    case 30:\r
+    case 32:\r
+    case 34:\r
+    case 37:\r
+    case 38:\r
+    case 42:\r
+    case 44:\r
+    case 47:\r
+    case 49:\r
+    case 50:\r
+    case 51:\r
+    case 56:\r
+    case 61:\r
+    case 68:\r
+    case IDENT:\r
+    case 94:\r
+    case 95:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 8:\r
+        jj_consume_token(8);\r
+        break;\r
+      default:\r
+        jj_la1[25] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 11:\r
+        jj_consume_token(11);\r
+        break;\r
+      default:\r
+        jj_la1[26] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 51:\r
+        jj_consume_token(51);\r
+        break;\r
+      default:\r
+        jj_la1[27] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 27:\r
+        jj_consume_token(27);\r
+        break;\r
+      default:\r
+        jj_la1[28] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 5:\r
+      case 7:\r
+      case 16:\r
+      case 17:\r
+      case 23:\r
+      case 24:\r
+      case 26:\r
+      case 30:\r
+      case 32:\r
+      case 34:\r
+      case 37:\r
+      case 38:\r
+      case 42:\r
+      case 44:\r
+      case 47:\r
+      case 49:\r
+      case 50:\r
+      case 56:\r
+      case 61:\r
+      case 68:\r
+      case IDENT:\r
+      case 94:\r
+      case 95:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 7:\r
+        case 17:\r
+        case 24:\r
+        case 26:\r
+        case 30:\r
+        case 34:\r
+        case 37:\r
+        case 38:\r
+        case 44:\r
+        case 47:\r
+        case 50:\r
+        case 61:\r
+        case 94:\r
+        case 95:\r
+          class_definition();\r
+          break;\r
+        case 5:\r
+        case 16:\r
+        case 23:\r
+        case 32:\r
+        case 42:\r
+        case 49:\r
+        case 56:\r
+        case 68:\r
+        case IDENT:\r
+          component_clause();\r
+          break;\r
+        default:\r
+          jj_la1[29] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        break;\r
+      case 13:\r
+        jj_consume_token(13);\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 7:\r
+        case 17:\r
+        case 24:\r
+        case 26:\r
+        case 30:\r
+        case 34:\r
+        case 37:\r
+        case 38:\r
+        case 44:\r
+        case 47:\r
+        case 50:\r
+        case 61:\r
+        case 94:\r
+        case 95:\r
+          class_definition();\r
+          break;\r
+        case 5:\r
+        case 16:\r
+        case 23:\r
+        case 32:\r
+        case 42:\r
+        case 49:\r
+        case 56:\r
+        case 68:\r
+        case IDENT:\r
+          component_clause();\r
+          break;\r
+        default:\r
+          jj_la1[30] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 54:\r
+          constraining_clause();\r
+          comment();\r
+          break;\r
+        default:\r
+          jj_la1[31] = jj_gen;\r
+          ;\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[32] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[33] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void import_clause() throws ParseException {\r
+    jj_consume_token(36);\r
+    if (jj_2_6(2)) {\r
+      jj_consume_token(IDENT);\r
+      jj_consume_token(88);\r
+      name();\r
+    } else {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+      case IDENT:\r
+        name();\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 68:\r
+          jj_consume_token(68);\r
+          jj_consume_token(82);\r
+          break;\r
+        default:\r
+          jj_la1[34] = jj_gen;\r
+          ;\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[35] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    }\r
+    comment();\r
+  }\r
+\r
+/*** Extends *******************************************************/\r
+  final public void extends_clause() throws ParseException {\r
+    jj_consume_token(55);\r
+    name();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 62:\r
+      class_modification();\r
+      break;\r
+    default:\r
+      jj_la1[36] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 14:\r
+      annotation();\r
+      break;\r
+    default:\r
+      jj_la1[37] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void constraining_clause() throws ParseException {\r
+    jj_consume_token(54);\r
+    name();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 62:\r
+      class_modification();\r
+      break;\r
+    default:\r
+      jj_la1[38] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+/*** Component Clause **********************************************/\r
+  final public void component_clause() throws ParseException {\r
+    InterfaceVariableType ioType = InterfaceVariableType.OTHER;\r
+    String typeSpecifier = "";\r
+    //String arraySubscripts = null;\r
+    ArrayList<Parameter> componentList = new ArrayList<Parameter>();\r
+    ioType = type_prefix();\r
+    typeSpecifier = type_specifier();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 66:\r
+      array_subscripts();\r
+      break;\r
+    default:\r
+      jj_la1[39] = jj_gen;\r
+      ;\r
+    }\r
+    componentList = component_list();\r
+        if (ioType == InterfaceVariableType.INPUT) {\r
+            for (Parameter input : componentList) {\r
+                input.type = typeSpecifier;\r
+                inputs.add(input);\r
+            }\r
+        } else if (ioType == InterfaceVariableType.OUTPUT) {\r
+            for (Parameter output : componentList) {\r
+                output.type = typeSpecifier;\r
+                outputs.add(output);\r
+            }\r
+        }\r
+  }\r
+\r
+  final public InterfaceVariableType type_prefix() throws ParseException {\r
+    InterfaceVariableType type = InterfaceVariableType.OTHER;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 16:\r
+    case 23:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 16:\r
+        jj_consume_token(16);\r
+        break;\r
+      case 23:\r
+        jj_consume_token(23);\r
+        break;\r
+      default:\r
+        jj_la1[40] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[41] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 5:\r
+    case 42:\r
+    case 49:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 5:\r
+        jj_consume_token(5);\r
+        break;\r
+      case 42:\r
+        jj_consume_token(42);\r
+        break;\r
+      case 49:\r
+        jj_consume_token(49);\r
+        break;\r
+      default:\r
+        jj_la1[42] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[43] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 32:\r
+    case 56:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 32:\r
+        jj_consume_token(32);\r
+                 type = InterfaceVariableType.OUTPUT;\r
+        break;\r
+      case 56:\r
+        jj_consume_token(56);\r
+                    type = InterfaceVariableType.INPUT;\r
+        break;\r
+      default:\r
+        jj_la1[44] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[45] = jj_gen;\r
+      ;\r
+    }\r
+        {if (true) return type;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public String type_specifier() throws ParseException {\r
+    String ret = new String("");\r
+    ret = name();\r
+        {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public ArrayList<Parameter> component_list() throws ParseException {\r
+    ArrayList<Parameter> ret = new ArrayList<Parameter>();\r
+    Parameter temp;\r
+    // component_declaration { "," component_declaration }\r
+            temp = component_declaration();\r
+                                         ret.add(temp);\r
+    label_6:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[46] = jj_gen;\r
+        break label_6;\r
+      }\r
+      jj_consume_token(71);\r
+      temp = component_declaration();\r
+                                           ret.add(temp);\r
+    }\r
+            {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public Parameter component_declaration() throws ParseException {\r
+    Parameter ret;\r
+    String temp = "";\r
+    // declaration [ conditional_attribute ] comment\r
+            ret = declaration();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 31:\r
+      conditional_attribute();\r
+      break;\r
+    default:\r
+      jj_la1[47] = jj_gen;\r
+      ;\r
+    }\r
+    ret.description = comment();\r
+        {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void conditional_attribute() throws ParseException {\r
+    jj_consume_token(31);\r
+    expression();\r
+  }\r
+\r
+  final public Parameter declaration() throws ParseException {\r
+    // Parameter here without comment yet.\r
+    Parameter ret = new Parameter();\r
+    jj_consume_token(IDENT);\r
+                  ret.name = new String(token.image);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 66:\r
+      array_subscripts();\r
+      break;\r
+    default:\r
+      jj_la1[48] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 62:\r
+    case 88:\r
+    case 89:\r
+      ret.optional = modification();\r
+      break;\r
+    default:\r
+      jj_la1[49] = jj_gen;\r
+      ;\r
+    }\r
+                {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+/*** Modification **********************************************/\r
+  final public boolean modification() throws ParseException {\r
+    boolean optional = false;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 62:\r
+      class_modification();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 88:\r
+        jj_consume_token(88);\r
+        expression();\r
+        break;\r
+      default:\r
+        jj_la1[50] = jj_gen;\r
+        ;\r
+      }\r
+      break;\r
+    case 88:\r
+      jj_consume_token(88);\r
+      expression();\r
+                             optional = true;\r
+      break;\r
+    case 89:\r
+      jj_consume_token(89);\r
+      expression();\r
+                              optional = true;\r
+      break;\r
+    default:\r
+      jj_la1[51] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+            {if (true) return optional;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void class_modification() throws ParseException {\r
+    jj_consume_token(62);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 8:\r
+    case 10:\r
+    case 11:\r
+    case 13:\r
+    case 68:\r
+    case IDENT:\r
+      argument_list();\r
+      break;\r
+    default:\r
+      jj_la1[52] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(63);\r
+  }\r
+\r
+  final public void argument_list() throws ParseException {\r
+    argument();\r
+    label_7:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[53] = jj_gen;\r
+        break label_7;\r
+      }\r
+      jj_consume_token(71);\r
+      argument();\r
+    }\r
+  }\r
+\r
+  final public void argument() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 10:\r
+    case 11:\r
+    case 13:\r
+    case 68:\r
+    case IDENT:\r
+      element_modification_or_replaceable();\r
+      break;\r
+    case 8:\r
+      element_redeclaration();\r
+      break;\r
+    default:\r
+      jj_la1[54] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void element_modification_or_replaceable() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 10:\r
+      jj_consume_token(10);\r
+      break;\r
+    default:\r
+      jj_la1[55] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 11:\r
+      jj_consume_token(11);\r
+      break;\r
+    default:\r
+      jj_la1[56] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 68:\r
+    case IDENT:\r
+      element_modification();\r
+      break;\r
+    case 13:\r
+      element_replaceable();\r
+      break;\r
+    default:\r
+      jj_la1[57] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void element_modification() throws ParseException {\r
+    name();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 62:\r
+    case 88:\r
+    case 89:\r
+      modification();\r
+      break;\r
+    default:\r
+      jj_la1[58] = jj_gen;\r
+      ;\r
+    }\r
+    string_comment();\r
+  }\r
+\r
+  final public void element_redeclaration() throws ParseException {\r
+    jj_consume_token(8);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 10:\r
+      jj_consume_token(10);\r
+      break;\r
+    default:\r
+      jj_la1[59] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 11:\r
+      jj_consume_token(11);\r
+      break;\r
+    default:\r
+      jj_la1[60] = jj_gen;\r
+      ;\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 5:\r
+    case 7:\r
+    case 16:\r
+    case 17:\r
+    case 23:\r
+    case 24:\r
+    case 26:\r
+    case 30:\r
+    case 32:\r
+    case 34:\r
+    case 37:\r
+    case 38:\r
+    case 42:\r
+    case 44:\r
+    case 47:\r
+    case 49:\r
+    case 50:\r
+    case 56:\r
+    case 61:\r
+    case 68:\r
+    case IDENT:\r
+    case 94:\r
+    case 95:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 7:\r
+      case 17:\r
+      case 24:\r
+      case 26:\r
+      case 30:\r
+      case 34:\r
+      case 37:\r
+      case 38:\r
+      case 44:\r
+      case 47:\r
+      case 50:\r
+      case 61:\r
+      case 94:\r
+      case 95:\r
+        class_definition();\r
+        break;\r
+      case 5:\r
+      case 16:\r
+      case 23:\r
+      case 32:\r
+      case 42:\r
+      case 49:\r
+      case 56:\r
+      case 68:\r
+      case IDENT:\r
+        component_clause1();\r
+        break;\r
+      default:\r
+        jj_la1[61] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      break;\r
+    case 13:\r
+      element_replaceable();\r
+      break;\r
+    default:\r
+      jj_la1[62] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void element_replaceable() throws ParseException {\r
+    jj_consume_token(13);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 7:\r
+    case 17:\r
+    case 24:\r
+    case 26:\r
+    case 30:\r
+    case 34:\r
+    case 37:\r
+    case 38:\r
+    case 44:\r
+    case 47:\r
+    case 50:\r
+    case 61:\r
+    case 94:\r
+    case 95:\r
+      class_definition();\r
+      break;\r
+    case 5:\r
+    case 16:\r
+    case 23:\r
+    case 32:\r
+    case 42:\r
+    case 49:\r
+    case 56:\r
+    case 68:\r
+    case IDENT:\r
+      component_clause1();\r
+      break;\r
+    default:\r
+      jj_la1[63] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 54:\r
+      constraining_clause();\r
+      break;\r
+    default:\r
+      jj_la1[64] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void component_clause1() throws ParseException {\r
+    type_prefix();\r
+    type_specifier();\r
+    component_declaration1();\r
+  }\r
+\r
+  final public void component_declaration1() throws ParseException {\r
+    declaration();\r
+    comment();\r
+  }\r
+\r
+/*** Equations *************************************************/\r
+  final public void equation_section() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 46:\r
+      jj_consume_token(46);\r
+      break;\r
+    default:\r
+      jj_la1[65] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(45);\r
+    label_8:\r
+    while (true) {\r
+      if (jj_2_7(2)) {\r
+        ;\r
+      } else {\r
+        break label_8;\r
+      }\r
+      equation();\r
+      jj_consume_token(70);\r
+    }\r
+  }\r
+\r
+  final public void algorithm_section() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 46:\r
+      jj_consume_token(46);\r
+      break;\r
+    default:\r
+      jj_la1[66] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(4);\r
+    label_9:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 18:\r
+      case 21:\r
+      case 29:\r
+      case 31:\r
+      case 43:\r
+      case 48:\r
+      case 62:\r
+      case 68:\r
+      case IDENT:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[67] = jj_gen;\r
+        break label_9;\r
+      }\r
+      statement();\r
+      jj_consume_token(70);\r
+    }\r
+  }\r
+\r
+  final public void equation() throws ParseException {\r
+    if (jj_2_8(3)) {\r
+      simple_expression();\r
+      jj_consume_token(88);\r
+      expression();\r
+    } else {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 31:\r
+        if_equation();\r
+        break;\r
+      case 21:\r
+        for_equation();\r
+        break;\r
+      case 39:\r
+        connect_clause();\r
+        break;\r
+      case 43:\r
+        when_equation();\r
+        break;\r
+      case IDENT:\r
+        jj_consume_token(IDENT);\r
+        function_call_args();\r
+        break;\r
+      default:\r
+        jj_la1[68] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    }\r
+    comment();\r
+  }\r
+\r
+  final public void statement() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 68:\r
+    case IDENT:\r
+      component_reference();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 89:\r
+        jj_consume_token(89);\r
+        expression();\r
+        break;\r
+      case 62:\r
+        function_call_args();\r
+        break;\r
+      default:\r
+        jj_la1[69] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      break;\r
+    case 62:\r
+      jj_consume_token(62);\r
+      output_expression_list();\r
+      jj_consume_token(63);\r
+      jj_consume_token(89);\r
+      component_reference();\r
+      function_call_args();\r
+      break;\r
+    case 29:\r
+      jj_consume_token(29);\r
+      break;\r
+    case 18:\r
+      jj_consume_token(18);\r
+      break;\r
+    case 31:\r
+      if_statement();\r
+      break;\r
+    case 21:\r
+      for_statement();\r
+      break;\r
+    case 48:\r
+      while_statement();\r
+      break;\r
+    case 43:\r
+      when_statement();\r
+      break;\r
+    default:\r
+      jj_la1[70] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+    comment();\r
+  }\r
+\r
+  final public void if_equation() throws ParseException {\r
+    jj_consume_token(31);\r
+    expression();\r
+    jj_consume_token(28);\r
+    label_10:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 21:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 39:\r
+      case 43:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[71] = jj_gen;\r
+        break label_10;\r
+      }\r
+      equation();\r
+      jj_consume_token(70);\r
+    }\r
+    label_11:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 20:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[72] = jj_gen;\r
+        break label_11;\r
+      }\r
+      jj_consume_token(20);\r
+      expression();\r
+      jj_consume_token(28);\r
+      label_12:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 21:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 39:\r
+        case 43:\r
+        case 46:\r
+        case 58:\r
+        case 62:\r
+        case 64:\r
+        case 66:\r
+        case 68:\r
+        case 78:\r
+        case 79:\r
+        case 80:\r
+        case 81:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[73] = jj_gen;\r
+          break label_12;\r
+        }\r
+        equation();\r
+        jj_consume_token(70);\r
+      }\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 15:\r
+      jj_consume_token(15);\r
+      label_13:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 21:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 39:\r
+        case 43:\r
+        case 46:\r
+        case 58:\r
+        case 62:\r
+        case 64:\r
+        case 66:\r
+        case 68:\r
+        case 78:\r
+        case 79:\r
+        case 80:\r
+        case 81:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[74] = jj_gen;\r
+          break label_13;\r
+        }\r
+        equation();\r
+        jj_consume_token(70);\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[75] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(35);\r
+    jj_consume_token(31);\r
+  }\r
+\r
+  final public void if_statement() throws ParseException {\r
+    jj_consume_token(31);\r
+    expression();\r
+    jj_consume_token(28);\r
+    label_14:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 18:\r
+      case 21:\r
+      case 29:\r
+      case 31:\r
+      case 43:\r
+      case 48:\r
+      case 62:\r
+      case 68:\r
+      case IDENT:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[76] = jj_gen;\r
+        break label_14;\r
+      }\r
+      statement();\r
+      jj_consume_token(70);\r
+    }\r
+    label_15:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 20:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[77] = jj_gen;\r
+        break label_15;\r
+      }\r
+      jj_consume_token(20);\r
+      expression();\r
+      jj_consume_token(28);\r
+      label_16:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 18:\r
+        case 21:\r
+        case 29:\r
+        case 31:\r
+        case 43:\r
+        case 48:\r
+        case 62:\r
+        case 68:\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[78] = jj_gen;\r
+          break label_16;\r
+        }\r
+        statement();\r
+        jj_consume_token(70);\r
+      }\r
+    }\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 15:\r
+      jj_consume_token(15);\r
+      label_17:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 18:\r
+        case 21:\r
+        case 29:\r
+        case 31:\r
+        case 43:\r
+        case 48:\r
+        case 62:\r
+        case 68:\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[79] = jj_gen;\r
+          break label_17;\r
+        }\r
+        statement();\r
+        jj_consume_token(70);\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[80] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(35);\r
+    jj_consume_token(31);\r
+  }\r
+\r
+  final public void for_equation() throws ParseException {\r
+    jj_consume_token(21);\r
+    for_indices();\r
+    jj_consume_token(60);\r
+    label_18:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 21:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 39:\r
+      case 43:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[81] = jj_gen;\r
+        break label_18;\r
+      }\r
+      equation();\r
+      jj_consume_token(70);\r
+    }\r
+    jj_consume_token(35);\r
+    jj_consume_token(21);\r
+  }\r
+\r
+  final public void for_statement() throws ParseException {\r
+    jj_consume_token(21);\r
+    for_indices();\r
+    jj_consume_token(60);\r
+    label_19:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 18:\r
+      case 21:\r
+      case 29:\r
+      case 31:\r
+      case 43:\r
+      case 48:\r
+      case 62:\r
+      case 68:\r
+      case IDENT:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[82] = jj_gen;\r
+        break label_19;\r
+      }\r
+      statement();\r
+      jj_consume_token(70);\r
+    }\r
+    jj_consume_token(35);\r
+    jj_consume_token(21);\r
+  }\r
+\r
+  final public void for_indices() throws ParseException {\r
+    for_index();\r
+    label_20:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[83] = jj_gen;\r
+        break label_20;\r
+      }\r
+      jj_consume_token(71);\r
+      for_index();\r
+    }\r
+  }\r
+\r
+  final public void for_index() throws ParseException {\r
+    jj_consume_token(IDENT);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 41:\r
+      jj_consume_token(41);\r
+      expression();\r
+      break;\r
+    default:\r
+      jj_la1[84] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void while_statement() throws ParseException {\r
+    jj_consume_token(48);\r
+    expression();\r
+    jj_consume_token(60);\r
+    label_21:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 18:\r
+      case 21:\r
+      case 29:\r
+      case 31:\r
+      case 43:\r
+      case 48:\r
+      case 62:\r
+      case 68:\r
+      case IDENT:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[85] = jj_gen;\r
+        break label_21;\r
+      }\r
+      statement();\r
+      jj_consume_token(70);\r
+    }\r
+    jj_consume_token(35);\r
+    jj_consume_token(48);\r
+  }\r
+\r
+  final public void when_equation() throws ParseException {\r
+    jj_consume_token(43);\r
+    expression();\r
+    jj_consume_token(28);\r
+    label_22:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 21:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 39:\r
+      case 43:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[86] = jj_gen;\r
+        break label_22;\r
+      }\r
+      equation();\r
+      jj_consume_token(70);\r
+    }\r
+    label_23:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 25:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[87] = jj_gen;\r
+        break label_23;\r
+      }\r
+      jj_consume_token(25);\r
+      expression();\r
+      jj_consume_token(28);\r
+      label_24:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 21:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 39:\r
+        case 43:\r
+        case 46:\r
+        case 58:\r
+        case 62:\r
+        case 64:\r
+        case 66:\r
+        case 68:\r
+        case 78:\r
+        case 79:\r
+        case 80:\r
+        case 81:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[88] = jj_gen;\r
+          break label_24;\r
+        }\r
+        equation();\r
+        jj_consume_token(70);\r
+      }\r
+    }\r
+    jj_consume_token(35);\r
+    jj_consume_token(43);\r
+  }\r
+\r
+  final public void when_statement() throws ParseException {\r
+    jj_consume_token(43);\r
+    expression();\r
+    jj_consume_token(28);\r
+    label_25:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 18:\r
+      case 21:\r
+      case 29:\r
+      case 31:\r
+      case 43:\r
+      case 48:\r
+      case 62:\r
+      case 68:\r
+      case IDENT:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[89] = jj_gen;\r
+        break label_25;\r
+      }\r
+      statement();\r
+      jj_consume_token(70);\r
+    }\r
+    label_26:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 25:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[90] = jj_gen;\r
+        break label_26;\r
+      }\r
+      jj_consume_token(25);\r
+      expression();\r
+      jj_consume_token(28);\r
+      label_27:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 18:\r
+        case 21:\r
+        case 29:\r
+        case 31:\r
+        case 43:\r
+        case 48:\r
+        case 62:\r
+        case 68:\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[91] = jj_gen;\r
+          break label_27;\r
+        }\r
+        statement();\r
+        jj_consume_token(70);\r
+      }\r
+    }\r
+    jj_consume_token(35);\r
+    jj_consume_token(43);\r
+  }\r
+\r
+  final public void connect_clause() throws ParseException {\r
+    jj_consume_token(39);\r
+    jj_consume_token(62);\r
+    component_reference();\r
+    jj_consume_token(71);\r
+    component_reference();\r
+    jj_consume_token(63);\r
+  }\r
+\r
+/*** Expressions ***************************************************/\r
+  final public void expr() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 33:\r
+    case 35:\r
+    case 46:\r
+    case 58:\r
+    case 62:\r
+    case 64:\r
+    case 66:\r
+    case 68:\r
+    case 78:\r
+    case 79:\r
+    case 80:\r
+    case 81:\r
+    case IDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      simple_expression();\r
+      jj_consume_token(0);\r
+      break;\r
+    case 31:\r
+      jj_consume_token(31);\r
+      expression();\r
+      jj_consume_token(28);\r
+      expression();\r
+      label_28:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 20:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[92] = jj_gen;\r
+          break label_28;\r
+        }\r
+        jj_consume_token(20);\r
+        expression();\r
+        jj_consume_token(28);\r
+        expression();\r
+      }\r
+      jj_consume_token(15);\r
+      expression();\r
+      jj_consume_token(0);\r
+      break;\r
+    default:\r
+      jj_la1[93] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void expression() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 33:\r
+    case 35:\r
+    case 46:\r
+    case 58:\r
+    case 62:\r
+    case 64:\r
+    case 66:\r
+    case 68:\r
+    case 78:\r
+    case 79:\r
+    case 80:\r
+    case 81:\r
+    case IDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      simple_expression();\r
+      break;\r
+    case 31:\r
+      jj_consume_token(31);\r
+      expression();\r
+      jj_consume_token(28);\r
+      expression();\r
+      label_29:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 20:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[94] = jj_gen;\r
+          break label_29;\r
+        }\r
+        jj_consume_token(20);\r
+        expression();\r
+        jj_consume_token(28);\r
+        expression();\r
+      }\r
+      jj_consume_token(15);\r
+      expression();\r
+      break;\r
+    default:\r
+      jj_la1[95] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void simple_expression() throws ParseException {\r
+    logical_expression();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 69:\r
+      jj_consume_token(69);\r
+      logical_expression();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        jj_consume_token(69);\r
+        logical_expression();\r
+        break;\r
+      default:\r
+        jj_la1[96] = jj_gen;\r
+        ;\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[97] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void logical_expression() throws ParseException {\r
+    logical_term();\r
+    label_30:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 22:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[98] = jj_gen;\r
+        break label_30;\r
+      }\r
+      jj_consume_token(22);\r
+      logical_term();\r
+    }\r
+  }\r
+\r
+  final public void logical_term() throws ParseException {\r
+    logical_factor();\r
+    label_31:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 9:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[99] = jj_gen;\r
+        break label_31;\r
+      }\r
+      jj_consume_token(9);\r
+      logical_factor();\r
+    }\r
+  }\r
+\r
+  final public void logical_factor() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 12:\r
+      jj_consume_token(12);\r
+      break;\r
+    default:\r
+      jj_la1[100] = jj_gen;\r
+      ;\r
+    }\r
+    relation();\r
+  }\r
+\r
+  final public void relation() throws ParseException {\r
+    arithmetic_expression();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 72:\r
+    case 73:\r
+    case 74:\r
+    case 75:\r
+    case 76:\r
+    case 77:\r
+      rel_op();\r
+      arithmetic_expression();\r
+      break;\r
+    default:\r
+      jj_la1[101] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void rel_op() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 72:\r
+      jj_consume_token(72);\r
+      break;\r
+    case 73:\r
+      jj_consume_token(73);\r
+      break;\r
+    case 74:\r
+      jj_consume_token(74);\r
+      break;\r
+    case 75:\r
+      jj_consume_token(75);\r
+      break;\r
+    case 76:\r
+      jj_consume_token(76);\r
+      break;\r
+    case 77:\r
+      jj_consume_token(77);\r
+      break;\r
+    default:\r
+      jj_la1[102] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void arithmetic_expression() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 78:\r
+    case 79:\r
+    case 80:\r
+    case 81:\r
+      add_op();\r
+      break;\r
+    default:\r
+      jj_la1[103] = jj_gen;\r
+      ;\r
+    }\r
+    term();\r
+    label_32:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[104] = jj_gen;\r
+        break label_32;\r
+      }\r
+      add_op();\r
+      term();\r
+    }\r
+  }\r
+\r
+  final public void add_op() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 78:\r
+      jj_consume_token(78);\r
+      break;\r
+    case 79:\r
+      jj_consume_token(79);\r
+      break;\r
+    case 80:\r
+      jj_consume_token(80);\r
+      break;\r
+    case 81:\r
+      jj_consume_token(81);\r
+      break;\r
+    default:\r
+      jj_la1[105] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void term() throws ParseException {\r
+    factor();\r
+    label_33:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 82:\r
+      case 83:\r
+      case 84:\r
+      case 85:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[106] = jj_gen;\r
+        break label_33;\r
+      }\r
+      mul_op();\r
+      factor();\r
+    }\r
+  }\r
+\r
+  final public void mul_op() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 82:\r
+      jj_consume_token(82);\r
+      break;\r
+    case 83:\r
+      jj_consume_token(83);\r
+      break;\r
+    case 84:\r
+      jj_consume_token(84);\r
+      break;\r
+    case 85:\r
+      jj_consume_token(85);\r
+      break;\r
+    default:\r
+      jj_la1[107] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public void factor() throws ParseException {\r
+    primary();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 86:\r
+    case 87:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 86:\r
+        jj_consume_token(86);\r
+        break;\r
+      case 87:\r
+        jj_consume_token(87);\r
+        break;\r
+      default:\r
+        jj_la1[108] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      primary();\r
+      break;\r
+    default:\r
+      jj_la1[109] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void primary() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case UNSIGNED_NUMBER:\r
+      jj_consume_token(UNSIGNED_NUMBER);\r
+      break;\r
+    case UNSIGNED_INTEGER:\r
+      jj_consume_token(UNSIGNED_INTEGER);\r
+      break;\r
+    case STRING:\r
+      jj_consume_token(STRING);\r
+      break;\r
+    case 6:\r
+      jj_consume_token(6);\r
+      break;\r
+    case 33:\r
+      jj_consume_token(33);\r
+      break;\r
+    default:\r
+      jj_la1[112] = jj_gen;\r
+      if (jj_2_9(2147483647)) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 68:\r
+        case IDENT:\r
+          name();\r
+          break;\r
+        case 58:\r
+          jj_consume_token(58);\r
+          break;\r
+        case 46:\r
+          jj_consume_token(46);\r
+          break;\r
+        default:\r
+          jj_la1[110] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        function_call_args();\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 68:\r
+        case IDENT:\r
+          component_reference();\r
+          break;\r
+        case 62:\r
+          jj_consume_token(62);\r
+          expression();\r
+          jj_consume_token(63);\r
+          break;\r
+        case 66:\r
+          jj_consume_token(66);\r
+          expression_list();\r
+          label_34:\r
+          while (true) {\r
+            switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+            case 70:\r
+              ;\r
+              break;\r
+            default:\r
+              jj_la1[111] = jj_gen;\r
+              break label_34;\r
+            }\r
+            jj_consume_token(70);\r
+            expression_list();\r
+          }\r
+          jj_consume_token(67);\r
+          break;\r
+        case 64:\r
+          jj_consume_token(64);\r
+          function_arguments();\r
+          jj_consume_token(65);\r
+          break;\r
+        case 35:\r
+          jj_consume_token(35);\r
+          break;\r
+        default:\r
+          jj_la1[113] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  final public String name() throws ParseException {\r
+    String ret = new String("");\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 68:\r
+      jj_consume_token(68);\r
+                ret += ".";\r
+      break;\r
+    default:\r
+      jj_la1[114] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(IDENT);\r
+                     ret += token.image;\r
+    label_35:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[115] = jj_gen;\r
+        break label_35;\r
+      }\r
+      jj_consume_token(68);\r
+                   ret += ".";\r
+      jj_consume_token(IDENT);\r
+                     ret += token.image;\r
+    }\r
+        {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void component_reference() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 68:\r
+      jj_consume_token(68);\r
+      break;\r
+    default:\r
+      jj_la1[116] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(IDENT);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 66:\r
+      array_subscripts();\r
+      break;\r
+    default:\r
+      jj_la1[117] = jj_gen;\r
+      ;\r
+    }\r
+    label_36:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 68:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[118] = jj_gen;\r
+        break label_36;\r
+      }\r
+      jj_consume_token(68);\r
+      jj_consume_token(IDENT);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 66:\r
+        array_subscripts();\r
+        break;\r
+      default:\r
+        jj_la1[119] = jj_gen;\r
+        ;\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void function_call_args() throws ParseException {\r
+    jj_consume_token(62);\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 31:\r
+    case 33:\r
+    case 35:\r
+    case 46:\r
+    case 58:\r
+    case 62:\r
+    case 64:\r
+    case 66:\r
+    case 68:\r
+    case 78:\r
+    case 79:\r
+    case 80:\r
+    case 81:\r
+    case IDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      function_arguments();\r
+      break;\r
+    default:\r
+      jj_la1[120] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(63);\r
+  }\r
+\r
+  final public void function_arguments() throws ParseException {\r
+    if (jj_2_10(2)) {\r
+      expression();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 21:\r
+      case 71:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 71:\r
+          jj_consume_token(71);\r
+          function_arguments();\r
+          break;\r
+        case 21:\r
+          jj_consume_token(21);\r
+          for_indices();\r
+          break;\r
+        default:\r
+          jj_la1[121] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[122] = jj_gen;\r
+        ;\r
+      }\r
+    } else {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case IDENT:\r
+        named_arguments();\r
+        break;\r
+      default:\r
+        jj_la1[123] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void named_arguments() throws ParseException {\r
+    named_argument();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 71:\r
+      jj_consume_token(71);\r
+      named_arguments();\r
+      break;\r
+    default:\r
+      jj_la1[124] = jj_gen;\r
+      ;\r
+    }\r
+  }\r
+\r
+  final public void named_argument() throws ParseException {\r
+    jj_consume_token(IDENT);\r
+    jj_consume_token(88);\r
+    expression();\r
+  }\r
+\r
+  final public void output_expression_list() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 6:\r
+    case 12:\r
+    case 31:\r
+    case 33:\r
+    case 35:\r
+    case 46:\r
+    case 58:\r
+    case 62:\r
+    case 64:\r
+    case 66:\r
+    case 68:\r
+    case 78:\r
+    case 79:\r
+    case 80:\r
+    case 81:\r
+    case IDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      expression();\r
+      break;\r
+    default:\r
+      jj_la1[125] = jj_gen;\r
+      ;\r
+    }\r
+    label_37:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[126] = jj_gen;\r
+        break label_37;\r
+      }\r
+      jj_consume_token(71);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 46:\r
+      case 58:\r
+      case 62:\r
+      case 64:\r
+      case 66:\r
+      case 68:\r
+      case 78:\r
+      case 79:\r
+      case 80:\r
+      case 81:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        expression();\r
+        break;\r
+      default:\r
+        jj_la1[127] = jj_gen;\r
+        ;\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void expression_list() throws ParseException {\r
+    expression();\r
+    label_38:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[128] = jj_gen;\r
+        break label_38;\r
+      }\r
+      jj_consume_token(71);\r
+      expression();\r
+    }\r
+  }\r
+\r
+  final public void array_subscripts() throws ParseException {\r
+    jj_consume_token(66);\r
+    subscript();\r
+    label_39:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[129] = jj_gen;\r
+        break label_39;\r
+      }\r
+      jj_consume_token(71);\r
+      subscript();\r
+    }\r
+    jj_consume_token(67);\r
+  }\r
+\r
+  final public void subscript() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 69:\r
+      jj_consume_token(69);\r
+      break;\r
+    case 6:\r
+    case 12:\r
+    case 31:\r
+    case 33:\r
+    case 35:\r
+    case 46:\r
+    case 58:\r
+    case 62:\r
+    case 64:\r
+    case 66:\r
+    case 68:\r
+    case 78:\r
+    case 79:\r
+    case 80:\r
+    case 81:\r
+    case IDENT:\r
+    case STRING:\r
+    case UNSIGNED_INTEGER:\r
+    case UNSIGNED_NUMBER:\r
+      expression();\r
+      break;\r
+    default:\r
+      jj_la1[130] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  final public String comment() throws ParseException {\r
+    String ret;\r
+    // string_comment [ annotation ]\r
+            ret = string_comment();\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 14:\r
+      annotation();\r
+      break;\r
+    default:\r
+      jj_la1[131] = jj_gen;\r
+      ;\r
+    }\r
+            {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public String string_comment() throws ParseException {\r
+    String ret = null;\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case STRING:\r
+      jj_consume_token(STRING);\r
+                     ret = new String(token.image);\r
+      label_40:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 78:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[132] = jj_gen;\r
+          break label_40;\r
+        }\r
+        jj_consume_token(78);\r
+                    ret += "+";\r
+        jj_consume_token(STRING);\r
+                           ret += token.image;\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[133] = jj_gen;\r
+      ;\r
+    }\r
+            {if (true) return ret;}\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void annotation() throws ParseException {\r
+    jj_consume_token(14);\r
+    class_modification();\r
+  }\r
+\r
+  private boolean jj_2_1(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_1(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(0, xla); }\r
+  }\r
+\r
+  private boolean jj_2_2(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_2(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(1, xla); }\r
+  }\r
+\r
+  private boolean jj_2_3(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_3(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(2, xla); }\r
+  }\r
+\r
+  private boolean jj_2_4(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_4(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(3, xla); }\r
+  }\r
+\r
+  private boolean jj_2_5(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_5(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(4, xla); }\r
+  }\r
+\r
+  private boolean jj_2_6(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_6(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(5, xla); }\r
+  }\r
+\r
+  private boolean jj_2_7(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_7(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(6, xla); }\r
+  }\r
+\r
+  private boolean jj_2_8(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_8(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(7, xla); }\r
+  }\r
+\r
+  private boolean jj_2_9(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_9(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(8, xla); }\r
+  }\r
+\r
+  private boolean jj_2_10(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_10(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(9, xla); }\r
+  }\r
+\r
+  private boolean jj_3R_50() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3_5()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_66()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_67()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_68()) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_5() {\r
+    if (jj_scan_token(57)) return true;\r
+    if (jj_3R_43()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_42() {\r
+    if (jj_3R_43()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_50()) { jj_scanpos = xsp; break; }\r
+    }\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_51()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_52()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_74() {\r
+    if (jj_scan_token(43)) return true;\r
+    if (jj_3R_46()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_137() {\r
+    if (jj_3R_46()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_135() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(69)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_137()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_131() {\r
+    if (jj_scan_token(71)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_104() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(50)) jj_scanpos = xsp;\r
+    if (jj_scan_token(44)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_133() {\r
+    if (jj_scan_token(66)) return true;\r
+    if (jj_3R_135()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_130() {\r
+    if (jj_scan_token(68)) return true;\r
+    if (jj_scan_token(IDENT)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_64() {\r
+    if (jj_scan_token(71)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_48() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_64()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_65()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_92() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_125() {\r
+    if (jj_3R_46()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_131()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_85() {\r
+    if (jj_3R_92()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_136() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_4() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    if (jj_scan_token(58)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_3() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    if (jj_scan_token(40)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_2() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_1() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_3R_41()) return true;\r
+    if (jj_3R_42()) return true;\r
+    if (jj_scan_token(35)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_134() {\r
+    if (jj_3R_136()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_129() {\r
+    if (jj_3R_133()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_132() {\r
+    if (jj_3R_134()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_123() {\r
+    if (jj_3R_63()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_127() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3_10()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_132()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_72() {\r
+    if (jj_scan_token(21)) return true;\r
+    if (jj_3R_85()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_10() {\r
+    if (jj_3R_46()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_48()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_128() {\r
+    if (jj_3R_127()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_75() {\r
+    if (jj_scan_token(62)) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_128()) jj_scanpos = xsp;\r
+    if (jj_scan_token(63)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_98() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(30)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(47)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(34)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(7)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(61)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(24)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_104()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(38)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(37)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(26)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(17)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(94)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(95)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_124() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(68)) jj_scanpos = xsp;\r
+    if (jj_scan_token(IDENT)) return true;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_129()) jj_scanpos = xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_130()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_126() {\r
+    if (jj_scan_token(70)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_79() {\r
+    if (jj_scan_token(68)) return true;\r
+    if (jj_scan_token(IDENT)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_78() {\r
+    if (jj_scan_token(68)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_63() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_78()) jj_scanpos = xsp;\r
+    if (jj_scan_token(IDENT)) return true;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_79()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_47() {\r
+    if (jj_3R_63()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_9() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_47()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(58)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(46)) return true;\r
+    }\r
+    }\r
+    if (jj_scan_token(62)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_106() {\r
+    if (jj_3R_63()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_114() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(86)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(87)) return true;\r
+    }\r
+    if (jj_3R_113()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_71() {\r
+    if (jj_scan_token(31)) return true;\r
+    if (jj_3R_46()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_122() {\r
+    if (jj_scan_token(64)) return true;\r
+    if (jj_3R_127()) return true;\r
+    if (jj_scan_token(65)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_121() {\r
+    if (jj_scan_token(66)) return true;\r
+    if (jj_3R_125()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_126()) { jj_scanpos = xsp; break; }\r
+    }\r
+    if (jj_scan_token(67)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_117() {\r
+    if (jj_scan_token(56)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_120() {\r
+    if (jj_scan_token(62)) return true;\r
+    if (jj_3R_46()) return true;\r
+    if (jj_scan_token(63)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_118() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_123()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(58)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(46)) return true;\r
+    }\r
+    }\r
+    if (jj_3R_75()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_119() {\r
+    if (jj_3R_124()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_116() {\r
+    if (jj_scan_token(32)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_113() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(93)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(92)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(91)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(6)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(33)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_118()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_119()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_120()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_121()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_122()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(35)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_112() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_116()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_117()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_111() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(5)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(42)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(49)) return true;\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_110() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(16)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(23)) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_105() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_110()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_111()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_112()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_108() {\r
+    if (jj_3R_113()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_114()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_109() {\r
+    if (jj_3R_115()) return true;\r
+    if (jj_3R_108()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_68() {\r
+    if (jj_3R_81()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_102() {\r
+    if (jj_3R_107()) return true;\r
+    if (jj_3R_101()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_97() {\r
+    if (jj_3R_103()) return true;\r
+    if (jj_3R_96()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_115() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(82)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(83)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(84)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(85)) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_101() {\r
+    if (jj_3R_108()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_109()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_58() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_3R_75()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_57() {\r
+    if (jj_3R_74()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_56() {\r
+    if (jj_3R_73()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_107() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(78)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(79)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(80)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(81)) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_55() {\r
+    if (jj_3R_72()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_54() {\r
+    if (jj_3R_71()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_7() {\r
+    if (jj_3R_44()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_87() {\r
+    if (jj_scan_token(9)) return true;\r
+    if (jj_3R_86()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_99() {\r
+    if (jj_3R_105()) return true;\r
+    if (jj_3R_106()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_100() {\r
+    if (jj_3R_107()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_67() {\r
+    if (jj_3R_80()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_96() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_100()) jj_scanpos = xsp;\r
+    if (jj_3R_101()) return true;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_102()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_103() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(72)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(73)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(74)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(75)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(76)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(77)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_60() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_59()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_77() {\r
+    if (jj_scan_token(22)) return true;\r
+    if (jj_3R_76()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_8() {\r
+    if (jj_3R_45()) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    if (jj_3R_46()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_93() {\r
+    if (jj_3R_96()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_97()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_44() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3_8()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_54()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_55()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_56()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_57()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_58()) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_95() {\r
+    if (jj_3R_99()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_86() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(12)) jj_scanpos = xsp;\r
+    if (jj_3R_93()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_6() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(88)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_76() {\r
+    if (jj_3R_86()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_87()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_89() {\r
+    if (jj_scan_token(55)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_81() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(46)) jj_scanpos = xsp;\r
+    if (jj_scan_token(4)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_59() {\r
+    if (jj_3R_76()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_77()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_88() {\r
+    if (jj_scan_token(36)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_80() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(46)) jj_scanpos = xsp;\r
+    if (jj_scan_token(45)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_45() {\r
+    if (jj_3R_59()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_60()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_91() {\r
+    if (jj_scan_token(13)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_66() {\r
+    if (jj_scan_token(52)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_94() {\r
+    if (jj_3R_98()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_90() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_94()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_95()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_62() {\r
+    if (jj_scan_token(31)) return true;\r
+    if (jj_3R_46()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_61() {\r
+    if (jj_3R_45()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_46() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_61()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_62()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_84() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(8)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(11)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(51)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(27)) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_90()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_91()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_83() {\r
+    if (jj_3R_89()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_70() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_82()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_83()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_84()) return true;\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_82() {\r
+    if (jj_3R_88()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_73() {\r
+    if (jj_scan_token(39)) return true;\r
+    if (jj_scan_token(62)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_53() {\r
+    if (jj_3R_70()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_43() {\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_53()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_69() {\r
+    if (jj_scan_token(14)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_65() {\r
+    if (jj_scan_token(21)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_49() {\r
+    if (jj_scan_token(STRING)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_41() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_49()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_52() {\r
+    if (jj_3R_69()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_51() {\r
+    if (jj_scan_token(59)) return true;\r
+    return false;\r
+  }\r
+\r
+  /** Generated Token Manager. */\r
+  public ModelParserTokenManager token_source;\r
+  SimpleCharStream jj_input_stream;\r
+  /** Current token. */\r
+  public Token token;\r
+  /** Next token. */\r
+  public Token jj_nt;\r
+  private int jj_ntk;\r
+  private Token jj_scanpos, jj_lastpos;\r
+  private int jj_la;\r
+  private int jj_gen;\r
+  final private int[] jj_la1 = new int[134];\r
+  static private int[] jj_la1_0;\r
+  static private int[] jj_la1_1;\r
+  static private int[] jj_la1_2;\r
+  static {\r
+      jj_la1_init_0();\r
+      jj_la1_init_1();\r
+      jj_la1_init_2();\r
+   }\r
+   private static void jj_la1_init_0() {\r
+      jj_la1_0 = new int[] {0x0,0x0,0x45020880,0x800,0x40000000,0x0,0x0,0x5020080,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10,0x10,0x0,0x0,0x4000,0x0,0x4000,0x0,0x80001040,0x4d8329a0,0x100,0x800,0x0,0x8000000,0x458300a0,0x458300a0,0x0,0x458320a0,0x4d8329a0,0x0,0x0,0x0,0x4000,0x0,0x0,0x810000,0x810000,0x20,0x20,0x0,0x0,0x0,0x80000000,0x0,0x0,0x0,0x0,0x2d00,0x0,0x2d00,0x400,0x800,0x2000,0x0,0x400,0x800,0x458300a0,0x458320a0,0x458300a0,0x0,0x0,0x0,0xa0240000,0x80200000,0x0,0xa0240000,0x80201040,0x100000,0x80201040,0x80201040,0x8000,0xa0240000,0x100000,0xa0240000,0xa0240000,0x8000,0x80201040,0xa0240000,0x0,0x0,0xa0240000,0x80201040,0x2000000,0x80201040,0xa0240000,0x2000000,0xa0240000,0x100000,0x80001040,0x100000,0x80001040,0x0,0x0,0x400000,0x200,0x1000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80001040,0x200000,0x200000,0x0,0x0,0x80001040,0x0,0x80001040,0x0,0x0,0x80001040,0x4000,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_1() {\r
+      jj_la1_1 = new int[] {0x0,0x200000,0x20049064,0x0,0x0,0x8000,0x40000,0x20041064,0x0,0x40000000,0x0,0x0,0x40000000,0x800000,0x0,0x2106000,0x106000,0x0,0x0,0x0,0x8000000,0x0,0x0,0x4400400a,0x218e9475,0x0,0x0,0x80000,0x0,0x21069465,0x21069465,0x400000,0x21069465,0x218e9475,0x0,0x0,0x40000000,0x0,0x40000000,0x0,0x0,0x0,0x20400,0x20400,0x1000001,0x1000001,0x0,0x0,0x0,0x40000000,0x0,0x40000000,0x0,0x0,0x0,0x0,0x0,0x0,0x40000000,0x0,0x0,0x21069465,0x21069465,0x21069465,0x400000,0x4000,0x4000,0x40010800,0x880,0x40000000,0x40010800,0x4400488a,0x0,0x4400488a,0x4400488a,0x0,0x40010800,0x0,0x40010800,0x40010800,0x0,0x4400488a,0x40010800,0x0,0x200,0x40010800,0x4400488a,0x0,0x4400488a,0x40010800,0x0,0x40010800,0x0,0x4400400a,0x0,0x4400400a,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4004000,0x0,0x2,0x40000008,0x0,0x0,0x0,0x0,0x0,0x0,0x4400400a,0x0,0x0,0x0,0x0,0x4400400a,0x0,0x4400400a,0x0,0x0,0x4400400a,0x0,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_2() {\r
+      jj_la1_2 = new int[] {0x4000010,0x0,0xc0000000,0x0,0x0,0x0,0x0,0xc0000000,0x4,0x0,0x4000000,0x80,0x0,0x0,0x80,0x0,0x0,0x8000000,0x4000010,0x0,0x0,0x0,0x4000010,0x3c03c015,0xc4000010,0x0,0x0,0x0,0x0,0xc4000010,0xc4000010,0x0,0xc4000010,0xc4000010,0x10,0x4000010,0x0,0x0,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x80,0x0,0x4,0x3000000,0x1000000,0x3000000,0x4000010,0x80,0x4000010,0x0,0x0,0x4000010,0x3000000,0x0,0x0,0xc4000010,0xc4000010,0xc4000010,0x0,0x0,0x0,0x4000010,0x4000000,0x2000000,0x4000010,0x3c03c015,0x0,0x3c03c015,0x3c03c015,0x0,0x4000010,0x0,0x4000010,0x4000010,0x0,0x3c03c015,0x4000010,0x80,0x0,0x4000010,0x3c03c015,0x0,0x3c03c015,0x4000010,0x0,0x4000010,0x0,0x3c03c015,0x0,0x3c03c015,0x20,0x20,0x0,0x0,0x0,0x3f00,0x3f00,0x3c000,0x3c000,0x3c000,0x3c0000,0x3c0000,0xc00000,0xc00000,0x4000010,0x40,0x38000000,0x4000015,0x10,0x10,0x10,0x4,0x10,0x4,0x3c03c015,0x80,0x80,0x4000000,0x80,0x3c03c015,0x80,0x3c03c015,0x80,0x80,0x3c03c035,0x0,0x4000,0x8000000,};\r
+   }\r
+  final private JJCalls[] jj_2_rtns = new JJCalls[10];\r
+  private boolean jj_rescan = false;\r
+  private int jj_gc = 0;\r
+\r
+  /** Constructor with InputStream. */\r
+  public ModelParser(java.io.InputStream stream) {\r
+     this(stream, null);\r
+  }\r
+  /** Constructor with InputStream and supplied encoding */\r
+  public ModelParser(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source = new ModelParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 134; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream) {\r
+     ReInit(stream, null);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 134; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Constructor. */\r
+  public ModelParser(java.io.Reader stream) {\r
+    jj_input_stream = new SimpleCharStream(stream, 1, 1);\r
+    token_source = new ModelParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 134; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader stream) {\r
+    jj_input_stream.ReInit(stream, 1, 1);\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 134; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Constructor with generated Token Manager. */\r
+  public ModelParser(ModelParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 134; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(ModelParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 134; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  private Token jj_consume_token(int kind) throws ParseException {\r
+    Token oldToken;\r
+    if ((oldToken = token).next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    if (token.kind == kind) {\r
+      jj_gen++;\r
+      if (++jj_gc > 100) {\r
+        jj_gc = 0;\r
+        for (int i = 0; i < jj_2_rtns.length; i++) {\r
+          JJCalls c = jj_2_rtns[i];\r
+          while (c != null) {\r
+            if (c.gen < jj_gen) c.first = null;\r
+            c = c.next;\r
+          }\r
+        }\r
+      }\r
+      return token;\r
+    }\r
+    token = oldToken;\r
+    jj_kind = kind;\r
+    throw generateParseException();\r
+  }\r
+\r
+  static private final class LookaheadSuccess extends java.lang.Error { }\r
+  final private LookaheadSuccess jj_ls = new LookaheadSuccess();\r
+  private boolean jj_scan_token(int kind) {\r
+    if (jj_scanpos == jj_lastpos) {\r
+      jj_la--;\r
+      if (jj_scanpos.next == null) {\r
+        jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();\r
+      } else {\r
+        jj_lastpos = jj_scanpos = jj_scanpos.next;\r
+      }\r
+    } else {\r
+      jj_scanpos = jj_scanpos.next;\r
+    }\r
+    if (jj_rescan) {\r
+      int i = 0; Token tok = token;\r
+      while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }\r
+      if (tok != null) jj_add_error_token(kind, i);\r
+    }\r
+    if (jj_scanpos.kind != kind) return true;\r
+    if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;\r
+    return false;\r
+  }\r
+\r
+\r
+/** Get the next Token. */\r
+  final public Token getNextToken() {\r
+    if (token.next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    jj_gen++;\r
+    return token;\r
+  }\r
+\r
+/** Get the specific Token. */\r
+  final public Token getToken(int index) {\r
+    Token t = token;\r
+    for (int i = 0; i < index; i++) {\r
+      if (t.next != null) t = t.next;\r
+      else t = t.next = token_source.getNextToken();\r
+    }\r
+    return t;\r
+  }\r
+\r
+  private int jj_ntk() {\r
+    if ((jj_nt=token.next) == null)\r
+      return (jj_ntk = (token.next=token_source.getNextToken()).kind);\r
+    else\r
+      return (jj_ntk = jj_nt.kind);\r
+  }\r
+\r
+  private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();\r
+  private int[] jj_expentry;\r
+  private int jj_kind = -1;\r
+  private int[] jj_lasttokens = new int[100];\r
+  private int jj_endpos;\r
+\r
+  private void jj_add_error_token(int kind, int pos) {\r
+    if (pos >= 100) return;\r
+    if (pos == jj_endpos + 1) {\r
+      jj_lasttokens[jj_endpos++] = kind;\r
+    } else if (jj_endpos != 0) {\r
+      jj_expentry = new int[jj_endpos];\r
+      for (int i = 0; i < jj_endpos; i++) {\r
+        jj_expentry[i] = jj_lasttokens[i];\r
+      }\r
+      jj_entries_loop: for (java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();) {\r
+        int[] oldentry = (int[])(it.next());\r
+        if (oldentry.length == jj_expentry.length) {\r
+          for (int i = 0; i < jj_expentry.length; i++) {\r
+            if (oldentry[i] != jj_expentry[i]) {\r
+              continue jj_entries_loop;\r
+            }\r
+          }\r
+          jj_expentries.add(jj_expentry);\r
+          break jj_entries_loop;\r
+        }\r
+      }\r
+      if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;\r
+    }\r
+  }\r
+\r
+  /** Generate ParseException. */\r
+  public ParseException generateParseException() {\r
+    jj_expentries.clear();\r
+    boolean[] la1tokens = new boolean[96];\r
+    if (jj_kind >= 0) {\r
+      la1tokens[jj_kind] = true;\r
+      jj_kind = -1;\r
+    }\r
+    for (int i = 0; i < 134; i++) {\r
+      if (jj_la1[i] == jj_gen) {\r
+        for (int j = 0; j < 32; j++) {\r
+          if ((jj_la1_0[i] & (1<<j)) != 0) {\r
+            la1tokens[j] = true;\r
+          }\r
+          if ((jj_la1_1[i] & (1<<j)) != 0) {\r
+            la1tokens[32+j] = true;\r
+          }\r
+          if ((jj_la1_2[i] & (1<<j)) != 0) {\r
+            la1tokens[64+j] = true;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    for (int i = 0; i < 96; i++) {\r
+      if (la1tokens[i]) {\r
+        jj_expentry = new int[1];\r
+        jj_expentry[0] = i;\r
+        jj_expentries.add(jj_expentry);\r
+      }\r
+    }\r
+    jj_endpos = 0;\r
+    jj_rescan_token();\r
+    jj_add_error_token(0, 0);\r
+    int[][] exptokseq = new int[jj_expentries.size()][];\r
+    for (int i = 0; i < jj_expentries.size(); i++) {\r
+      exptokseq[i] = jj_expentries.get(i);\r
+    }\r
+    return new ParseException(token, exptokseq, tokenImage);\r
+  }\r
+\r
+  /** Enable tracing. */\r
+  final public void enable_tracing() {\r
+  }\r
+\r
+  /** Disable tracing. */\r
+  final public void disable_tracing() {\r
+  }\r
+\r
+  private void jj_rescan_token() {\r
+    jj_rescan = true;\r
+    for (int i = 0; i < 10; i++) {\r
+    try {\r
+      JJCalls p = jj_2_rtns[i];\r
+      do {\r
+        if (p.gen > jj_gen) {\r
+          jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;\r
+          switch (i) {\r
+            case 0: jj_3_1(); break;\r
+            case 1: jj_3_2(); break;\r
+            case 2: jj_3_3(); break;\r
+            case 3: jj_3_4(); break;\r
+            case 4: jj_3_5(); break;\r
+            case 5: jj_3_6(); break;\r
+            case 6: jj_3_7(); break;\r
+            case 7: jj_3_8(); break;\r
+            case 8: jj_3_9(); break;\r
+            case 9: jj_3_10(); break;\r
+          }\r
+        }\r
+        p = p.next;\r
+      } while (p != null);\r
+      } catch(LookaheadSuccess ls) { }\r
+    }\r
+    jj_rescan = false;\r
+  }\r
+\r
+  private void jj_save(int index, int xla) {\r
+    JJCalls p = jj_2_rtns[index];\r
+    while (p.gen > jj_gen) {\r
+      if (p.next == null) { p = p.next = new JJCalls(); break; }\r
+      p = p.next;\r
+    }\r
+    p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;\r
+  }\r
+\r
+  static final class JJCalls {\r
+    int gen;\r
+    Token first;\r
+    int arg;\r
+    JJCalls next;\r
+  }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParserConstants.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParserConstants.java
new file mode 100644 (file)
index 0000000..b307d24
--- /dev/null
@@ -0,0 +1,131 @@
+/* Generated By:JavaCC: Do not edit this line. ModelParserConstants.java */\r
+package org.simantics.sysdyn.modelParser;\r
+\r
+\r
+/**\r
+ * Token literal values and constants.\r
+ * Generated by org.javacc.parser.OtherFilesGen#start()\r
+ */\r
+public interface ModelParserConstants {\r
+\r
+  /** End of File. */\r
+  int EOF = 0;\r
+  /** RegularExpression Id. */\r
+  int WHITESPACE = 1;\r
+  /** RegularExpression Id. */\r
+  int COMMENT1 = 2;\r
+  /** RegularExpression Id. */\r
+  int COMMENT2 = 3;\r
+  /** RegularExpression Id. */\r
+  int IDENT = 90;\r
+  /** RegularExpression Id. */\r
+  int STRING = 91;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_INTEGER = 92;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_NUMBER = 93;\r
+\r
+  /** Lexical state. */\r
+  int DEFAULT = 0;\r
+\r
+  /** Literal token values. */\r
+  String[] tokenImage = {\r
+    "<EOF>",\r
+    "<WHITESPACE>",\r
+    "<COMMENT1>",\r
+    "<COMMENT2>",\r
+    "\"algorithm\"",\r
+    "\"discrete\"",\r
+    "\"false\"",\r
+    "\"model\"",\r
+    "\"redeclare\"",\r
+    "\"and\"",\r
+    "\"each\"",\r
+    "\"final\"",\r
+    "\"not\"",\r
+    "\"replaceable\"",\r
+    "\"annotation\"",\r
+    "\"else\"",\r
+    "\"flow\"",\r
+    "\"operator\"",\r
+    "\"return\"",\r
+    "\"assert\"",\r
+    "\"elseif\"",\r
+    "\"for\"",\r
+    "\"or\"",\r
+    "\"stream\"",\r
+    "\"block\"",\r
+    "\"elsewhen\"",\r
+    "\"function\"",\r
+    "\"outer\"",\r
+    "\"then\"",\r
+    "\"break\"",\r
+    "\"encapsulated\"",\r
+    "\"if\"",\r
+    "\"output\"",\r
+    "\"true\"",\r
+    "\"class\"",\r
+    "\"end\"",\r
+    "\"import\"",\r
+    "\"package\"",\r
+    "\"type\"",\r
+    "\"connect\"",\r
+    "\"enumeration\"",\r
+    "\"in\"",\r
+    "\"parameter\"",\r
+    "\"when\"",\r
+    "\"connector\"",\r
+    "\"equation\"",\r
+    "\"initial\"",\r
+    "\"partial\"",\r
+    "\"while\"",\r
+    "\"constant\"",\r
+    "\"expandable\"",\r
+    "\"inner\"",\r
+    "\"protected\"",\r
+    "\"within\"",\r
+    "\"constrainedby\"",\r
+    "\"extends\"",\r
+    "\"input\"",\r
+    "\"public\"",\r
+    "\"der\"",\r
+    "\"external\"",\r
+    "\"loop\"",\r
+    "\"record\"",\r
+    "\"(\"",\r
+    "\")\"",\r
+    "\"{\"",\r
+    "\"}\"",\r
+    "\"[\"",\r
+    "\"]\"",\r
+    "\".\"",\r
+    "\":\"",\r
+    "\";\"",\r
+    "\",\"",\r
+    "\"<\"",\r
+    "\"<=\"",\r
+    "\">\"",\r
+    "\">=\"",\r
+    "\"==\"",\r
+    "\"<>\"",\r
+    "\"+\"",\r
+    "\"-\"",\r
+    "\".+\"",\r
+    "\".-\"",\r
+    "\"*\"",\r
+    "\"/\"",\r
+    "\".*\"",\r
+    "\"./\"",\r
+    "\"^\"",\r
+    "\".^\"",\r
+    "\"=\"",\r
+    "\":=\"",\r
+    "<IDENT>",\r
+    "<STRING>",\r
+    "<UNSIGNED_INTEGER>",\r
+    "<UNSIGNED_NUMBER>",\r
+    "\"operator function\"",\r
+    "\"operator record\"",\r
+  };\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParserTokenManager.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelParserTokenManager.java
new file mode 100644 (file)
index 0000000..ab57915
--- /dev/null
@@ -0,0 +1,1448 @@
+/* Generated By:JavaCC: Do not edit this line. ModelParserTokenManager.java */\r
+package org.simantics.sysdyn.modelParser;\r
+import java.util.ArrayList;\r
+\r
+/** Token Manager. */\r
+public class ModelParserTokenManager implements ModelParserConstants\r
+{\r
+\r
+  /** Debug output. */\r
+  public  java.io.PrintStream debugStream = System.out;\r
+  /** Set debug output. */\r
+  public  void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }\r
+private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1)
+{\r
+   switch (pos)
+   {\r
+      case 0:\r
+         if ((active1 & 0x80000L) != 0L)\r
+            return 14;\r
+         if ((active0 & 0x3ffffffffffffff0L) != 0L || (active1 & 0xc0000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            return 2;\r
+         }\r
+         if ((active1 & 0xb30010L) != 0L)\r
+            return 9;\r
+         return -1;\r
+      case 1:\r
+         if ((active0 & 0x108420080400000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x3ef7bdff7fbffff0L) != 0L || (active1 & 0xc0000000L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 1)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 1;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 2:\r
+         if ((active0 & 0x400000800201200L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x3bfffdf77f9fedf0L) != 0L || (active1 & 0xc0000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 2;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 3:\r
+         if ((active0 & 0x1000084212118400L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x2bfff5b56d8e69f0L) != 0L || (active1 & 0xc0000000L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 3)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 3;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 4:\r
+         if ((active0 & 0x1090004290008c0L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x2af6f5b1469e6130L) != 0L || (active1 & 0xc0000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 4;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 5:\r
+         if ((active0 & 0x22200011009c0000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x8d6f5a046026130L) != 0L || (active1 & 0xc0000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 5;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 6:\r
+         if ((active0 & 0x80d0a000000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x856250046026130L) != 0L || (active1 & 0xc0000000L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 6)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 6;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 7:\r
+         if ((active0 & 0x54150040006110L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 7)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 7;\r
+            }\r
+            return 2;\r
+         }\r
+         if ((active0 & 0x802200006020020L) != 0L || (active1 & 0xc0000000L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      case 8:\r
+         if ((active0 & 0x10140000000110L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x44010040006000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 8;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 9:\r
+         if ((active0 & 0x40010040002000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 9;\r
+            return 2;\r
+         }\r
+         if ((active0 & 0x4000000004000L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      case 10:\r
+         if ((active0 & 0x10000002000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x40000040000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 10;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 11:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 11;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 12:\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      default :\r
+         return -1;\r
+   }\r
+}\r
+private final int jjStartNfa_0(int pos, long active0, long active1)
+{\r
+   return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1);\r
+}\r
+private int jjStopAtPos(int pos, int kind)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   return pos + 1;\r
+}\r
+private int jjMoveStringLiteralDfa0_0()\r
+{\r
+   switch(curChar)\r
+   {\r
+      case 40:\r
+         return jjStopAtPos(0, 62);\r
+      case 41:\r
+         return jjStopAtPos(0, 63);\r
+      case 42:\r
+         return jjStopAtPos(0, 82);\r
+      case 43:\r
+         return jjStopAtPos(0, 78);\r
+      case 44:\r
+         return jjStopAtPos(0, 71);\r
+      case 45:\r
+         return jjStopAtPos(0, 79);\r
+      case 46:\r
+         jjmatchedKind = 68;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0xb30000L);\r
+      case 47:\r
+         return jjStartNfaWithStates_0(0, 83, 14);\r
+      case 58:\r
+         jjmatchedKind = 69;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x2000000L);\r
+      case 59:\r
+         return jjStopAtPos(0, 70);\r
+      case 60:\r
+         jjmatchedKind = 72;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x2200L);\r
+      case 61:\r
+         jjmatchedKind = 88;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x1000L);\r
+      case 62:\r
+         jjmatchedKind = 74;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x800L);\r
+      case 91:\r
+         return jjStopAtPos(0, 66);\r
+      case 93:\r
+         return jjStopAtPos(0, 67);\r
+      case 94:\r
+         return jjStopAtPos(0, 86);\r
+      case 97:\r
+         return jjMoveStringLiteralDfa1_0(0x84210L, 0x0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa1_0(0x21000000L, 0x0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa1_0(0x42108400000000L, 0x0L);\r
+      case 100:\r
+         return jjMoveStringLiteralDfa1_0(0x400000000000020L, 0x0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa1_0(0x884210842108400L, 0x0L);\r
+      case 102:\r
+         return jjMoveStringLiteralDfa1_0(0x4210840L, 0x0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa1_0(0x108421080000000L, 0x0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa1_0(0x1000000000000000L, 0x0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa1_0(0x80L, 0x0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa1_0(0x1000L, 0x0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa1_0(0x108420000L, 0xc0000000L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa1_0(0x210842000000000L, 0x0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa1_0(0x2000000000042100L, 0x0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa1_0(0x800000L, 0x0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa1_0(0x4210000000L, 0x0L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa1_0(0x21080000000000L, 0x0L);\r
+      case 123:\r
+         return jjStopAtPos(0, 64);\r
+      case 125:\r
+         return jjStopAtPos(0, 65);\r
+      default :\r
+         return jjMoveNfa_0(0, 0);\r
+   }\r
+}\r
+private int jjMoveStringLiteralDfa1_0(long active0, long active1)\r
+{\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(0, active0, active1);\r
+      return 1;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 42:\r
+         if ((active1 & 0x100000L) != 0L)\r
+            return jjStopAtPos(1, 84);\r
+         break;\r
+      case 43:\r
+         if ((active1 & 0x10000L) != 0L)\r
+            return jjStopAtPos(1, 80);\r
+         break;\r
+      case 45:\r
+         if ((active1 & 0x20000L) != 0L)\r
+            return jjStopAtPos(1, 81);\r
+         break;\r
+      case 47:\r
+         if ((active1 & 0x200000L) != 0L)\r
+            return jjStopAtPos(1, 85);\r
+         break;\r
+      case 61:\r
+         if ((active1 & 0x200L) != 0L)\r
+            return jjStopAtPos(1, 73);\r
+         else if ((active1 & 0x800L) != 0L)\r
+            return jjStopAtPos(1, 75);\r
+         else if ((active1 & 0x1000L) != 0L)\r
+            return jjStopAtPos(1, 76);\r
+         else if ((active1 & 0x2000000L) != 0L)\r
+            return jjStopAtPos(1, 89);\r
+         break;\r
+      case 62:\r
+         if ((active1 & 0x2000L) != 0L)\r
+            return jjStopAtPos(1, 77);\r
+         break;\r
+      case 94:\r
+         if ((active1 & 0x800000L) != 0L)\r
+            return jjStopAtPos(1, 87);\r
+         break;\r
+      case 97:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x842000000440L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x2400000000042100L, active1, 0L);\r
+      case 102:\r
+         if ((active0 & 0x80000000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 31, 2);\r
+         break;\r
+      case 104:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1080010000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000000000820L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x403118010L, active1, 0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1000000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x20000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 41;\r
+            jjmatchedPos = 1;\r
+         }\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x108410840004200L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1042108000201080L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000L, active1, 0xc0000000L);\r
+      case 113:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x200000000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x400000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 22, 2);\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x10000220000000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x80000L, active1, 0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x800000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000010c000000L, active1, 0L);\r
+      case 120:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x884000000000000L, active1, 0L);\r
+      case 121:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x4000000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(0, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(0, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(1, active0, active1);\r
+      return 2;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x400000000L, active1, 0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x200000000000000L, active1, 0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x2000002040000400L, active1, 0L);\r
+      case 100:\r
+         if ((active0 & 0x200L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 9, 2);\r
+         else if ((active0 & 0x800000000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 35, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x180L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x80030020000L, active1, 0xc0000000L);\r
+      case 103:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x10L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x1400000000000L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x40L, active1, 0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x4a108004004800L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x1010000001010000L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x104005000002000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x200000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 21, 2);\r
+         else if ((active0 & 0x400000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 58, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x840000800000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x2188020L, active1, 0L);\r
+      case 116:\r
+         if ((active0 & 0x1000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 12, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x8a0000108040000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x210200000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(1, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa3_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(1, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(2, active0, active1);\r
+      return 3;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x4240060000800L, active1, 0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x5000020L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x8000L) != 0L)\r
+         {\r
+            jjmatchedKind = 15;\r
+            jjmatchedPos = 3;\r
+         }\r
+         else if ((active0 & 0x200000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 33, 2);\r
+         else if ((active0 & 0x4000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 38, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x88800000a980180L, active1, 0L);\r
+      case 104:\r
+         if ((active0 & 0x400L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 10, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x20000000000000L, active1, 0L);\r
+      case 107:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2000000000L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x201000000002000L, active1, 0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10000000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x10000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 28, 2);\r
+         else if ((active0 & 0x80000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 43, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x108000000000L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2000001000004010L, active1, 0L);\r
+      case 112:\r
+         if ((active0 & 0x1000000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 60, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100000000L, active1, 0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x20000L, active1, 0xc0000000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x42000400000040L, active1, 0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10c00000000000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100000000040000L, active1, 0L);\r
+      case 119:\r
+         if ((active0 & 0x10000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 16, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(2, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa4_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(2, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(3, active0, active1);\r
+      return 4;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000822000L, active1, 0xc0000000L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x40L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 6, 2);\r
+         else if ((active0 & 0x1000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 48, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x10118000000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x220c00000100000L, active1, 0L);\r
+      case 107:\r
+         if ((active0 & 0x1000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 24, 2);\r
+         else if ((active0 & 0x20000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 29, 2);\r
+         break;\r
+      case 108:\r
+         if ((active0 & 0x80L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 7, 2);\r
+         else if ((active0 & 0x800L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 11, 2);\r
+         break;\r
+      case 109:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L, active1, 0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x84000000000000L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x8000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 27, 2);\r
+         else if ((active0 & 0x8000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 51, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x28000010000c0030L, active1, 0L);\r
+      case 115:\r
+         if ((active0 & 0x400000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 34, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x100000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 56, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x42200004004000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100000000L, active1, 0L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(3, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa5_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(3, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(4, active0, active1);\r
+      return 5;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2c00000004000L, active1, 0L);\r
+      case 99:\r
+         if ((active0 & 0x200000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 57, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x10108000002000L, active1, 0L);\r
+      case 100:\r
+         if ((active0 & 0x2000000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 61, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x84000000000000L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000020L, active1, 0L);\r
+      case 102:\r
+         if ((active0 & 0x100000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 20, 2);\r
+         break;\r
+      case 103:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000000L, active1, 0L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x200004000010L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x100L, active1, 0L);\r
+      case 109:\r
+         if ((active0 & 0x800000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 23, 2);\r
+         break;\r
+      case 110:\r
+         if ((active0 & 0x40000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 18, 2);\r
+         else if ((active0 & 0x20000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 53, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x800000000000000L, active1, 0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40010000000000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000L, active1, 0L);\r
+      case 116:\r
+         if ((active0 & 0x80000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 19, 2);\r
+         else if ((active0 & 0x100000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 32, 2);\r
+         else if ((active0 & 0x1000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 36, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x20000L, active1, 0xc0000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(4, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa6_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(4, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(5, active0, active1);\r
+      return 6;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x844010000000100L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x2000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 37, 2);\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x2002000L, active1, 0L);\r
+      case 108:\r
+         if ((active0 & 0x400000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 46, 2);\r
+         else if ((active0 & 0x800000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 47, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x2000000000000L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x200004020000L, active1, 0xc0000000L);\r
+      case 115:\r
+         if ((active0 & 0x80000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 55, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x8000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 39;\r
+            jjmatchedPos = 6;\r
+         }\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x10140000004030L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x40000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(5, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa7_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(5, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(6, active0, active1);\r
+      return 7;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x2000L, active1, 0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x4000000000000L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x20L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 5, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10040000000000L, active1, 0L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x40000000004000L, active1, 0L);\r
+      case 108:\r
+         if ((active0 & 0x800000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 59, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x40000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x2000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 25, 2);\r
+         else if ((active0 & 0x4000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 26, 2);\r
+         else if ((active0 & 0x200000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 45, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100000000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x20000L) != 0L)\r
+         {\r
+            jjmatchedKind = 17;\r
+            jjmatchedPos = 7;\r
+         }\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100L, active1, 0xc0000000L);\r
+      case 116:\r
+         if ((active0 & 0x2000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 49, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10000000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(6, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa8_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(6, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(7, active0, active1);\r
+      return 8;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 32:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0xc0000000L);\r
+      case 97:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x40000000L, active1, 0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x2000L, active1, 0L);\r
+      case 100:\r
+         if ((active0 & 0x10000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 52, 2);\r
+         break;\r
+      case 101:\r
+         if ((active0 & 0x100L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 8, 2);\r
+         break;\r
+      case 105:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x10000000000L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x4000000000000L, active1, 0L);\r
+      case 109:\r
+         if ((active0 & 0x10L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 4, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x40000000000000L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x4000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x40000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 42, 2);\r
+         else if ((active0 & 0x100000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 44, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(7, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa9_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(7, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(8, active0, active1);\r
+      return 9;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 101:\r
+         if ((active0 & 0x4000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 50, 2);\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x40000000000000L, active1, 0L);\r
+      case 102:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x40000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x2000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x4000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 14, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x10000000000L, active1, 0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x80000000L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x40000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(8, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa10_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(8, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(9, active0, active1);\r
+      return 10;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 100:\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x40000000000000L, active1, 0L);\r
+      case 101:\r
+         if ((active0 & 0x2000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 13, 2);\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x40000000L, active1, 0x80000000L);\r
+      case 110:\r
+         if ((active0 & 0x10000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 40, 2);\r
+         break;\r
+      case 117:\r
+         return jjMoveStringLiteralDfa11_0(active0, 0L, active1, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(9, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa11_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(9, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(10, active0, active1);\r
+      return 11;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 98:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0x40000000000000L, active1, 0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0L, active1, 0x80000000L);\r
+      case 100:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return jjStartNfaWithStates_0(11, 30, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0L, active1, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(10, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa12_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(10, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(11, active0, active1);\r
+      return 12;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 99:\r
+         return jjMoveStringLiteralDfa13_0(active0, 0L, active1, 0x40000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa13_0(active0, 0L, active1, 0x80000000L);\r
+      case 121:\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(12, 54, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(11, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa13_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(11, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(12, 0L, active1);\r
+      return 13;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 114:\r
+         return jjMoveStringLiteralDfa14_0(active1, 0x80000000L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa14_0(active1, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(12, 0L, active1);\r
+}\r
+private int jjMoveStringLiteralDfa14_0(long old1, long active1)\r
+{\r
+   if (((active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(12, 0L, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(13, 0L, active1);\r
+      return 14;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 100:\r
+         if ((active1 & 0x80000000L) != 0L)\r
+            return jjStopAtPos(14, 95);\r
+         break;\r
+      case 105:\r
+         return jjMoveStringLiteralDfa15_0(active1, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(13, 0L, active1);\r
+}\r
+private int jjMoveStringLiteralDfa15_0(long old1, long active1)\r
+{\r
+   if (((active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(13, 0L, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(14, 0L, active1);\r
+      return 15;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 111:\r
+         return jjMoveStringLiteralDfa16_0(active1, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(14, 0L, active1);\r
+}\r
+private int jjMoveStringLiteralDfa16_0(long old1, long active1)\r
+{\r
+   if (((active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(14, 0L, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(15, 0L, active1);\r
+      return 16;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 110:\r
+         if ((active1 & 0x40000000L) != 0L)\r
+            return jjStopAtPos(16, 94);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(15, 0L, active1);\r
+}\r
+private int jjStartNfaWithStates_0(int pos, int kind, int state)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) { return pos + 1; }\r
+   return jjMoveNfa_0(state, pos + 1);\r
+}\r
+static final long[] jjbitVec0 = {
+   0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+};\r
+private int jjMoveNfa_0(int startState, int curPos)\r
+{\r
+   int startsAt = 0;\r
+   jjnewStateCnt = 34;\r
+   int i = 1;\r
+   jjstateSet[0] = startState;\r
+   int kind = 0x7fffffff;\r
+   for (;;)\r
+   {\r
+      if (++jjround == 0x7fffffff)\r
+         ReInitRounds();\r
+      if (curChar < 64)\r
+      {\r
+         long l = 1L << curChar;\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 14:\r
+                  if (curChar == 47)\r
+                  {\r
+                     if (kind > 3)\r
+                        kind = 3;\r
+                     jjCheckNAdd(21);\r
+                  }\r
+                  else if (curChar == 42)\r
+                     jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 0:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 92)\r
+                        kind = 92;\r
+                     jjCheckNAddStates(3, 7);\r
+                  }\r
+                  else if ((0x100002600L & l) != 0L)\r
+                  {\r
+                     if (kind > 1)\r
+                        kind = 1;\r
+                  }\r
+                  else if (curChar == 47)\r
+                     jjAddStates(8, 9);\r
+                  else if (curChar == 46)\r
+                     jjCheckNAdd(9);\r
+                  else if (curChar == 34)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 2:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjstateSet[jjnewStateCnt++] = 2;\r
+                  break;\r
+               case 3:\r
+                  if (curChar == 34)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 4:\r
+                  if ((0xfffffffbfffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 6:\r
+                  if ((0xfffffffffffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 7:\r
+                  if (curChar == 34 && kind > 91)\r
+                     kind = 91;\r
+                  break;\r
+               case 8:\r
+                  if (curChar == 46)\r
+                     jjCheckNAdd(9);\r
+                  break;\r
+               case 9:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAddTwoStates(9, 10);\r
+                  break;\r
+               case 11:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(12);\r
+                  break;\r
+               case 12:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAdd(12);\r
+                  break;\r
+               case 13:\r
+                  if (curChar == 47)\r
+                     jjAddStates(8, 9);\r
+                  break;\r
+               case 15:\r
+                  if ((0xfffffbffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 16:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 17;\r
+                  break;\r
+               case 17:\r
+                  if ((0xffff7fffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 18:\r
+                  if (curChar == 47 && kind > 2)\r
+                     kind = 2;\r
+                  break;\r
+               case 19:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 18;\r
+                  break;\r
+               case 20:\r
+                  if (curChar != 47)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(21);\r
+                  break;\r
+               case 21:\r
+                  if ((0xfffffffffffffbffL & l) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(21);\r
+                  break;\r
+               case 22:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAddStates(3, 7);\r
+                  break;\r
+               case 23:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAdd(23);\r
+                  break;\r
+               case 24:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(24, 25);\r
+                  break;\r
+               case 25:\r
+                  if (curChar != 46)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAddTwoStates(26, 27);\r
+                  break;\r
+               case 26:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAddTwoStates(26, 27);\r
+                  break;\r
+               case 28:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(29);\r
+                  break;\r
+               case 29:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAdd(29);\r
+                  break;\r
+               case 30:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(30, 31);\r
+                  break;\r
+               case 32:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(33);\r
+                  break;\r
+               case 33:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAdd(33);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else if (curChar < 128)\r
+      {\r
+         long l = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 0:\r
+               case 2:\r
+                  if ((0x7fffffe87fffffeL & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 4:\r
+                  if ((0xffffffffefffffffL & l) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 5:\r
+                  if (curChar == 92)\r
+                     jjstateSet[jjnewStateCnt++] = 6;\r
+                  break;\r
+               case 6:\r
+                  jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 10:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(13, 14);\r
+                  break;\r
+               case 15:\r
+               case 17:\r
+                  jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 21:\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 21;\r
+                  break;\r
+               case 27:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(15, 16);\r
+                  break;\r
+               case 31:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(17, 18);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else\r
+      {\r
+         int i2 = (curChar & 0xff) >> 6;\r
+         long l2 = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 4:\r
+               case 6:\r
+                  if ((jjbitVec0[i2] & l2) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 15:\r
+               case 17:\r
+                  if ((jjbitVec0[i2] & l2) != 0L)\r
+                     jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 21:\r
+                  if ((jjbitVec0[i2] & l2) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 21;\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      if (kind != 0x7fffffff)\r
+      {\r
+         jjmatchedKind = kind;\r
+         jjmatchedPos = curPos;\r
+         kind = 0x7fffffff;\r
+      }\r
+      ++curPos;\r
+      if ((i = jjnewStateCnt) == (startsAt = 34 - (jjnewStateCnt = startsAt)))\r
+         return curPos;\r
+      try { curChar = input_stream.readChar(); }\r
+      catch(java.io.IOException e) { return curPos; }\r
+   }\r
+}\r
+static final int[] jjnextStates = {
+   15, 16, 19, 23, 24, 25, 30, 31, 14, 20, 4, 5, 7, 11, 12, 28, 
+   29, 32, 33, 
+};\r
+\r
+/** Token literal values. */\r
+public static final String[] jjstrLiteralImages = {\r
+"", null, null, null, "\141\154\147\157\162\151\164\150\155", \r
+"\144\151\163\143\162\145\164\145", "\146\141\154\163\145", "\155\157\144\145\154", \r
+"\162\145\144\145\143\154\141\162\145", "\141\156\144", "\145\141\143\150", "\146\151\156\141\154", "\156\157\164", \r
+"\162\145\160\154\141\143\145\141\142\154\145", "\141\156\156\157\164\141\164\151\157\156", "\145\154\163\145", \r
+"\146\154\157\167", "\157\160\145\162\141\164\157\162", "\162\145\164\165\162\156", \r
+"\141\163\163\145\162\164", "\145\154\163\145\151\146", "\146\157\162", "\157\162", \r
+"\163\164\162\145\141\155", "\142\154\157\143\153", "\145\154\163\145\167\150\145\156", \r
+"\146\165\156\143\164\151\157\156", "\157\165\164\145\162", "\164\150\145\156", "\142\162\145\141\153", \r
+"\145\156\143\141\160\163\165\154\141\164\145\144", "\151\146", "\157\165\164\160\165\164", "\164\162\165\145", \r
+"\143\154\141\163\163", "\145\156\144", "\151\155\160\157\162\164", "\160\141\143\153\141\147\145", \r
+"\164\171\160\145", "\143\157\156\156\145\143\164", \r
+"\145\156\165\155\145\162\141\164\151\157\156", "\151\156", "\160\141\162\141\155\145\164\145\162", "\167\150\145\156", \r
+"\143\157\156\156\145\143\164\157\162", "\145\161\165\141\164\151\157\156", "\151\156\151\164\151\141\154", \r
+"\160\141\162\164\151\141\154", "\167\150\151\154\145", "\143\157\156\163\164\141\156\164", \r
+"\145\170\160\141\156\144\141\142\154\145", "\151\156\156\145\162", "\160\162\157\164\145\143\164\145\144", \r
+"\167\151\164\150\151\156", "\143\157\156\163\164\162\141\151\156\145\144\142\171", \r
+"\145\170\164\145\156\144\163", "\151\156\160\165\164", "\160\165\142\154\151\143", "\144\145\162", \r
+"\145\170\164\145\162\156\141\154", "\154\157\157\160", "\162\145\143\157\162\144", "\50", "\51", "\173", "\175", \r
+"\133", "\135", "\56", "\72", "\73", "\54", "\74", "\74\75", "\76", "\76\75", \r
+"\75\75", "\74\76", "\53", "\55", "\56\53", "\56\55", "\52", "\57", "\56\52", "\56\57", \r
+"\136", "\56\136", "\75", "\72\75", null, null, null, null, \r
+"\157\160\145\162\141\164\157\162\40\146\165\156\143\164\151\157\156", "\157\160\145\162\141\164\157\162\40\162\145\143\157\162\144", };\r
+\r
+/** Lexer state names. */\r
+public static final String[] lexStateNames = {\r
+   "DEFAULT",\r
+};\r
+static final long[] jjtoToken = {
+   0xfffffffffffffff1L, 0xffffffffL, 
+};\r
+static final long[] jjtoSkip = {
+   0xeL, 0x0L, 
+};\r
+protected SimpleCharStream input_stream;\r
+private final int[] jjrounds = new int[34];\r
+private final int[] jjstateSet = new int[68];\r
+private final StringBuilder jjimage = new StringBuilder();\r
+private StringBuilder image = jjimage;\r
+private int jjimageLen;\r
+private int lengthOfMatch;\r
+protected char curChar;\r
+/** Constructor. */\r
+public ModelParserTokenManager(SimpleCharStream stream){\r
+   if (SimpleCharStream.staticFlag)\r
+      throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");\r
+   input_stream = stream;\r
+}\r
+\r
+/** Constructor. */\r
+public ModelParserTokenManager(SimpleCharStream stream, int lexState){\r
+   this(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream)\r
+{\r
+   jjmatchedPos = jjnewStateCnt = 0;\r
+   curLexState = defaultLexState;\r
+   input_stream = stream;\r
+   ReInitRounds();\r
+}\r
+private void ReInitRounds()\r
+{\r
+   int i;\r
+   jjround = 0x80000001;\r
+   for (i = 34; i-- > 0;)\r
+      jjrounds[i] = 0x80000000;\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream, int lexState)\r
+{\r
+   ReInit(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Switch to specified lex state. */\r
+public void SwitchTo(int lexState)\r
+{\r
+   if (lexState >= 1 || lexState < 0)\r
+      throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);\r
+   else\r
+      curLexState = lexState;\r
+}\r
+\r
+protected Token jjFillToken()\r
+{\r
+   final Token t;\r
+   final String curTokenImage;\r
+   final int beginLine;\r
+   final int endLine;\r
+   final int beginColumn;\r
+   final int endColumn;\r
+   String im = jjstrLiteralImages[jjmatchedKind];\r
+   curTokenImage = (im == null) ? input_stream.GetImage() : im;\r
+   beginLine = input_stream.getBeginLine();\r
+   beginColumn = input_stream.getBeginColumn();\r
+   endLine = input_stream.getEndLine();\r
+   endColumn = input_stream.getEndColumn();\r
+   t = Token.newToken(jjmatchedKind, curTokenImage);\r
+\r
+   t.beginLine = beginLine;\r
+   t.endLine = endLine;\r
+   t.beginColumn = beginColumn;\r
+   t.endColumn = endColumn;\r
+\r
+   return t;\r
+}\r
+\r
+int curLexState = 0;\r
+int defaultLexState = 0;\r
+int jjnewStateCnt;\r
+int jjround;\r
+int jjmatchedPos;\r
+int jjmatchedKind;\r
+\r
+/** Get the next Token. */\r
+public Token getNextToken() \r
+{\r
+  Token matchedToken;\r
+  int curPos = 0;\r
+\r
+  EOFLoop :
+  for (;;)\r
+  {\r
+   try\r
+   {\r
+      curChar = input_stream.BeginToken();\r
+   }\r
+   catch(java.io.IOException e)\r
+   {\r
+      jjmatchedKind = 0;\r
+      matchedToken = jjFillToken();\r
+      return matchedToken;\r
+   }\r
+   image = jjimage;\r
+   image.setLength(0);\r
+   jjimageLen = 0;\r
+\r
+   jjmatchedKind = 0x7fffffff;\r
+   jjmatchedPos = 0;\r
+   curPos = jjMoveStringLiteralDfa0_0();\r
+   if (jjmatchedKind != 0x7fffffff)\r
+   {\r
+      if (jjmatchedPos + 1 < curPos)\r
+         input_stream.backup(curPos - jjmatchedPos - 1);\r
+      if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)\r
+      {\r
+         matchedToken = jjFillToken();\r
+         TokenLexicalActions(matchedToken);\r
+         return matchedToken;\r
+      }\r
+      else\r
+      {\r
+         continue EOFLoop;\r
+      }\r
+   }\r
+   int error_line = input_stream.getEndLine();\r
+   int error_column = input_stream.getEndColumn();\r
+   String error_after = null;\r
+   boolean EOFSeen = false;\r
+   try { input_stream.readChar(); input_stream.backup(1); }\r
+   catch (java.io.IOException e1) {\r
+      EOFSeen = true;\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+      if (curChar == '\n' || curChar == '\r') {\r
+         error_line++;\r
+         error_column = 0;\r
+      }\r
+      else\r
+         error_column++;\r
+   }\r
+   if (!EOFSeen) {\r
+      input_stream.backup(1);\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+   }\r
+   throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);\r
+  }\r
+}\r
+\r
+void TokenLexicalActions(Token matchedToken)\r
+{\r
+   switch(jjmatchedKind)\r
+   {\r
+      case 91 :\r
+        image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)));\r
+      matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+}\r
+private void jjCheckNAdd(int state)\r
+{\r
+   if (jjrounds[state] != jjround)\r
+   {\r
+      jjstateSet[jjnewStateCnt++] = state;\r
+      jjrounds[state] = jjround;\r
+   }\r
+}\r
+private void jjAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjstateSet[jjnewStateCnt++] = jjnextStates[start];\r
+   } while (start++ != end);\r
+}\r
+private void jjCheckNAddTwoStates(int state1, int state2)\r
+{\r
+   jjCheckNAdd(state1);\r
+   jjCheckNAdd(state2);\r
+}\r
+\r
+private void jjCheckNAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjCheckNAdd(jjnextStates[start]);\r
+   } while (start++ != end);\r
+}\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelicaParser.jj b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ModelicaParser.jj
new file mode 100644 (file)
index 0000000..e780b8a
--- /dev/null
@@ -0,0 +1,741 @@
+options {\r
+  JDK_VERSION = "1.6";\r
+  STATIC = false;\r
+}\r
+\r
+PARSER_BEGIN(ModelParser)\r
+package org.simantics.sysdyn.modelParser;\r
+\r
+import java.util.ArrayList;\r
+\r
+@SuppressWarnings({"unused", "serial"})\r
+public class ModelParser {\r
+\r
+  private ArrayList<Parameter> inputs = new ArrayList<Parameter>();\r
+  private ArrayList<Parameter> outputs = new ArrayList<Parameter>();\r
+  \r
+  private enum InterfaceVariableType\r  {\r    INPUT, OUTPUT, OTHER\r
+  }\r
+\r
+  public class Parameter\r  {\r
+    public String name;\r
+    public boolean optional;\r
+    public String description;\r
+    public String type;\r
+    \r
+    public Parameter()\r    {\r
+      name = new String("");\r
+      optional = false;\r
+      description = null;\r
+      type = null;\r
+    }\r  }\r
+\r
+  public ArrayList<Parameter> getInputs()\r
+  {\r
+    return inputs;\r
+  }\r
+    \r
+  public ArrayList<Parameter> getOutputs()\r
+  {\r
+    return outputs;\r
+  }\r
+    \r
+}\r
+\r
+PARSER_END(ModelParser)\r
+\r
+/*** Lexer *********************************************************/\r
+\r
+SKIP:\r
+{ <WHITESPACE: " " | "\n" | "\r" | "\t" > \r
+| <COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/" >  \r
+| <COMMENT2: "//" (~["\n"])* >\r
+}\r
+\r
+TOKEN:\r
+{\r
+"algorithm"     | "discrete"    | "false"   | "model"   | "redeclare"\r
+| "and"         | "each"        | "final"   | "not"     | "replaceable"\r
+| "annotation" | "else"         | "flow"    | "operator" | "return"\r
+|"assert"       | "elseif"      | "for"     | "or"      | "stream"\r
+| "block"       | "elsewhen"    | "function" | "outer"  | "then"\r
+| "break"       | "encapsulated" | "if"     | "output"  | "true"\r
+| "class"       | "end"         | "import"  | "package" | "type"\r
+| "connect"     | "enumeration" | "in"      | "parameter" | "when"\r
+| "connector"   | "equation"    | "initial" | "partial" | "while"\r
+| "constant"    | "expandable"  | "inner"   | "protected" | "within"\r
+| "constrainedby" | "extends"   | "input"   | "public"\r
+| "der"         | "external"    | "loop"    | "record"\r
+| "(" | ")" | "{" | "}" | "[" | "]" | "." | ":" | ";" | ","\r
+| "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+| "+" | "-" | ".+" | ".-"\r
+| "*" | "/" | ".*" | "./"\r
+| "^" | ".^"\r
+| "=" | ":=" \r
+| <IDENT: ["a"-"z","A"-"Z","_"] (["a"-"z","A"-"Z","_","0"-"9"])* >\r
+| <STRING: "\"" (~["\"", "\\", "\n"] | "\\" ~["\n"])* "\"">\r
+    { matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); }\r
+| <UNSIGNED_INTEGER: (["0"-"9"])+ >\r
+| <UNSIGNED_NUMBER:  \r
+    ( <UNSIGNED_INTEGER> "." (<UNSIGNED_INTEGER>)? (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | "." <UNSIGNED_INTEGER> (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | <UNSIGNED_INTEGER> ["e","E"] (["+","-"])? <UNSIGNED_INTEGER>\r
+    ) >\r
+}\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+\r
+void parse() : {\r
+       jj_input_stream.setTabSize(1);\r
+} {\r
+    stored_definition() <EOF>\r
+}\r
+\r
+/*** Stored Definition - Within ************************************/\r
+\r
+void stored_definition() : {\r
+} {\r
+//  stored_definition:\r
+//  [ within [ name ] ";" ]\r
+//  { [ final ] class_definition ";" }\r
+    ( "within" ( name() )? ";" )?\r
+    ( ( "final" )? class_definition() ";" )*\r
+}\r
+\r
+/*** Class Definition **********************************************/\r
+  \r
+void class_definition() : {\r
+} {\r
+//  class_definition :\r
+//  [ encapsulated ]\r
+//  [ partial\r
+//  ] ( class modelrecordblock expandableconnectortype\r
+//  | | | | [ ] | | package | function | operator | operator function | operator record )\r
+//  class_specifier\r
+    ( "encapsulated" )?\r
+    ( "partial" )?\r
+    ( "class" | "model" | "record" | "block" | ( "expandable" )? "connector" | "type" |\r
+    "package" | "function" | "operator" | "operator function" | "operator record" )\r
+    class_specifier()\r
+}\r
+\r
+\r
+void class_specifier() : {\r
+} {\r
+//  class_specifier :\r
+//  IDENT string_comment composition end IDENT\r
+//  | IDENT "=" base_prefix name [ array_subscripts ]\r
+//  [ class_modification ] comment\r
+//  | IDENT "=" enumeration "(" ( [enum_list] | ":" ) ")" comment\r
+//  | IDENT "=" der "(" name "," IDENT { "," IDENT } ")" comment\r
+//  | extends IDENT [ class_modification ] string_comment composition\r
+//  end IDENT  \r
+    LOOKAHEAD(2) <IDENT> string_comment() composition() "end" <IDENT>\r
+    | LOOKAHEAD(2) <IDENT> "=" base_prefix() name() ( array_subscripts() )? ( class_modification() )? comment()\r
+    | LOOKAHEAD(3) <IDENT> "=" "enumeration" "(" ( ( enum_list() )? | ":" ) ")" comment()\r
+    |LOOKAHEAD(3)  <IDENT> "=" "der" "(" name() "," <IDENT> ( "," <IDENT> )* ")" comment()\r
+    | "extends" <IDENT> ( class_modification() )? string_comment() composition() "end" <IDENT> \r
+}\r
+\r
+void base_prefix() : {\r
+} {\r
+    type_prefix()\r
+}\r
+\r
+void enum_list() : {\r
+} {\r
+//  enumeration_literal { "," enumeration_literal}\r
+    enumeration_literal() ( "," enumeration_literal() )* \r
+}\r
+\r
+void enumeration_literal() : {\r
+} {\r
+    <IDENT> comment()\r
+}\r
+\r
+void parse_composition() : {\r
+} {\r
+    composition() <EOF>\r
+}\r
+\r
+void composition() : {\r
+} {\r
+//  element_list\r
+//  { public element_list |\r
+//  protected element_list |\r
+//  equation_section |\r
+//  algorithm_section\r
+//  }\r
+//  [ external [ language_specification ]\r
+//  [ external_function_call ] [ annotation ] ";" ]\r
+//  [ annotation ";" ]\r
+    element_list()\r
+    ( LOOKAHEAD(2) "public" element_list() | "protected" element_list() | equation_section() | algorithm_section() )*\r
+    ( "external" ( language_specification() )? ( external_function_call() )? ( annotation() )? ";" )?\r
+    ( annotation() ";" )?\r
+}\r
+\r
+void language_specification() : {\r
+} {\r
+    <STRING>\r
+}\r
+\r
+void external_function_call() : {\r
+} {\r
+//  [ component_reference "=" ]\r
+//  IDENT "(" [ expression_list ] ")"\r
+    ( component_reference() "=" )?\r
+    <IDENT> "(" ( expression_list() )? ")"\r
+}\r
+\r
+void element_list() : {\r
+} {\r
+    ( element() ";" )*\r
+}\r
+\r
+void element() : {\r
+} {\r
+//  import_clause |\r
+//  extends_clause |\r
+//  [ redeclare ]\r
+//  [ final ]\r
+//  [ inner ] [ outer ]\r
+//  ( ( class_definition | component_clause) |\r
+//  replaceable ( class_definition | component_clause)\r
+//  [constraining_clause comment])\r
+    import_clause() |\r
+    extends_clause() |\r
+    ( "redeclare" )?\r
+    ( "final" )?\r
+    ( "inner" )? ( "outer" )?\r
+    ( (class_definition() | component_clause()) |\r
+        "replaceable" (class_definition() | component_clause())\r
+        (constraining_clause() comment())?)\r
+}\r
+\r
+void import_clause() : {\r
+} {\r
+//  import ( IDENT "=" name | name ["." "*"] ) comment\r
+    "import" (LOOKAHEAD(2) <IDENT> "=" name() | name() ("." "*")? ) comment()\r
+}\r
+\r
+/*** Extends *******************************************************/\r
+void extends_clause() : {\r
+} {\r
+//  extends name [ class_modification ] [annotation]\r
+    "extends" name() ( class_modification() )? ( annotation() )?\r
+}\r
+\r
+void constraining_clause() : {\r
+} {\r
+//  constrainedby name [ class_modification ]\r
+    "constrainedby" name() ( class_modification() )?\r
+}\r
+\r
+/*** Component Clause **********************************************/\r
+void component_clause() : {\r
+    InterfaceVariableType ioType = InterfaceVariableType.OTHER;\r
+    String typeSpecifier = "";\r
+    //String arraySubscripts = null;\r
+    ArrayList<Parameter> componentList = new ArrayList<Parameter>();\r
+} {\r
+  \r
+//  type_prefix type_specifier [ array_subscripts ] component_list\r
+    ( ioType = type_prefix() )\r
+    ( typeSpecifier = type_specifier() )\r
+    ( /*arraySubscripts =*/ array_subscripts() )?\r
+    ( componentList = component_list() )\r
+    {\r
+        if (ioType == InterfaceVariableType.INPUT) {\r
+            for (Parameter input : componentList) {\r
+                input.type = typeSpecifier;\r
+                inputs.add(input);\r            }\r
+        } else if (ioType == InterfaceVariableType.OUTPUT) {\r
+            for (Parameter output : componentList) {\r
+                output.type = typeSpecifier;          \r
+                outputs.add(output);\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+InterfaceVariableType type_prefix() : {\r
+    InterfaceVariableType type = InterfaceVariableType.OTHER;\r
+} {\r
+//  [ flow | stream ]\r
+//  [ discrete | parameter | constant ] [ input | output ]\r
+    ( "flow" | "stream" )?\r
+    ( "discrete" | "parameter" | "constant" )?\r
+    ( "output" { type = InterfaceVariableType.OUTPUT; }\r
+        | "input" { type = InterfaceVariableType.INPUT; }\r
+    )?\r
+    {\r
+        return type;\r
+    }\r
+}\r
+String type_specifier() : {\r
+    String ret = new String("");\r
+} {\r
+       ret = name()\r
+       {\r        return ret;\r
+    }\r
+}\r
+\r
+ArrayList<Parameter> component_list() : {\r
+    ArrayList<Parameter> ret = new ArrayList<Parameter>();\r
+    Parameter temp;\r
+} {\r
+//     component_declaration { "," component_declaration }\r
+       temp = component_declaration() { ret.add(temp); }\r    ( "," temp = component_declaration() { ret.add(temp); } )*\r
+       {\r          return ret;\r
+       }\r
+}\r
+\r
+Parameter component_declaration() : {\r
+    Parameter ret;\r
+    String temp = "";\r
+} {\r
+//     declaration [ conditional_attribute ] comment\r
+       ret = declaration() ( conditional_attribute() )? ret.description = comment()\r
+    {\r
+        return ret;\r
+    }\r
+}\r
+\r
+void conditional_attribute() : {\r
+} {\r
+       "if" expression()\r
+}\r
+\r
+Parameter declaration() : {\r
+    // Parameter here without comment yet.\r
+    Parameter ret = new Parameter();\r
+} {\r
+//     IDENT [ array_subscripts ] [ modification ]\r
+       <IDENT> { ret.name = new String(token.image); }\r
+       ( array_subscripts() )?\r
+       ( ret.optional = modification() )?\r
+       {\r              return ret;\r    }\r
+}\r
+\r
+/*** Modification **********************************************/\r
+boolean modification() : {\r
+    boolean optional = false;\r
+} {\r
+//     class_modification [ "=" expression ]\r
+//     | "=" expression\r
+//     | ":=" expression\r
+       ( class_modification() ( "=" expression() )?\r
+       | "=" expression() { optional = true; }\r
+       | ":=" expression() { optional = true; } )\r
+       {\r          return optional;\r
+       } \r
+}\r
+\r
+void class_modification() : {\r
+} {\r
+//     "(" [ argument_list ] ")"\r
+       "(" ( argument_list() )? ")"\r
+}\r
+\r
+void argument_list() : {\r
+} {\r
+// argument { "," argument }\r
+       argument() ( "," argument() )*\r
+}\r
+\r
+void argument() : {\r
+} {\r
+//     element_modification_or_replaceable\r
+//     | element_redeclaration\r
+       element_modification_or_replaceable() |\r
+       element_redeclaration()\r
+}\r
+\r
+void element_modification_or_replaceable() : {\r
+} {\r
+//     [ each ] [ final ] ( element_modification | element_replaceable)\r
+       ( "each" )? ( "final" )? ( element_modification() | element_replaceable() )\r}\r
+\r
+void element_modification() : {\r
+} {\r
+//     name [ modification ] string_comment\r
+       name() ( modification() )? string_comment()\r
+}\r
+\r
+void element_redeclaration() : {\r
+} {\r
+//     redeclare [ each ] [ final ]\r
+//     ( ( class_definition | component_clause1) | element_replaceable )\r
+       "redeclare" ( "each" )? ( "final" )?\r
+       ( ( class_definition() | component_clause1() ) | element_replaceable() )\r}\r
+\r
+void element_replaceable() : {\r
+} {\r
+//     replaceable ( class_definition | component_clause1)\r
+//     [constraining_clause]\r
+       "replaceable" ( class_definition() | component_clause1() ) ( constraining_clause() )?\r
+}\r
+\r
+void component_clause1() : {\r
+} {\r
+//     type_prefix type_specifier component_declaration1\r
+       type_prefix() type_specifier() component_declaration1()\r
+}\r
+\r
+void component_declaration1() : {\r
+} {\r
+       declaration() comment()\r
+}\r
+\r
+\r
+/*** Equations *************************************************/\r
+void equation_section() : {\r
+} {\r
+//     [ initial ] equation { equation ";" }\r
+       ( "initial" )? "equation" ( LOOKAHEAD(2) equation() ";" )*\r
+}\r
+\r
+void algorithm_section() : {\r
+} {\r
+//     [ initial ] algorithm { statement ";" }\r
+       ( "initial" )? "algorithm" ( statement() ";" )*\r}\r
+\r
+void equation() : {\r
+} {\r
+//     ( simple_expression "=" expression\r
+//     | if_equation\r
+//     | for_equation\r
+//     | connect_clause\r
+//     | when_equation\r
+//     | IDENT function_call_args )\r
+//     comment\r
+       ( LOOKAHEAD(3) simple_expression() "=" expression()\r
+               | if_equation()\r
+               | for_equation()\r
+               | connect_clause()\r
+               | when_equation()\r
+               | <IDENT> function_call_args() )\r
+       comment()\r}\r
+\r
+void statement() : {\r
+} {\r
+//     ( component_reference ( ":=" expression | function_call_args )\r
+//     | "(" output_expression_list ")" ":=" component_reference function_call_args\r
+//     | break\r
+//     | return\r
+//     | if_statement\r
+//     | for_statement\r
+//     | while_statement\r
+//     | when_statement )\r
+//     comment\r
+       ( component_reference() ( ":=" expression() | function_call_args() )\r
+               | "(" output_expression_list() ")" ":=" component_reference() function_call_args()\r
+               | "break"\r
+               | "return"\r
+               | if_statement()\r
+               | for_statement()\r
+               | while_statement()\r
+               | when_statement() )\r
+       comment() \r       \r
+}\r
+\r
+void if_equation() : {\r
+} {\r
+//     if expression then\r
+//     { equation ";" }\r
+//     { elseif expression then\r
+//     { equation ";" }\r
+//     }\r
+//     [ else\r
+//     { equation ";" }\r
+//     ]\r
+//     end if\r
+       "if" expression() "then"\r
+               ( equation() ";" )*\r
+       ( "elseif" expression() "then"\r
+               ( equation() ";" )*\r
+       )*\r
+       ( "else"\r
+               ( equation() ";" )*\r
+       )?\r
+       "end" "if"\r}\r
+\r
+void if_statement() : {\r
+} {\r
+//     if expression then\r
+//     { statement ";" }\r
+//     { elseif expression then\r
+//     { statement ";" }\r
+//     }\r
+//     [ else\r
+//     { statement ";" }\r
+//     ]\r
+//     end if\r
+       "if" expression() "then"\r
+               ( statement() ";" )*\r
+       ( "elseif" expression() "then"\r
+               ( statement() ";" )*\r
+       )*\r
+       ( "else"\r
+               ( statement() ";" )*\r
+       )?\r
+       "end" "if"\r}\r
+\r
+void for_equation() : {\r
+} {\r
+//     for for_indices loop\r
+//     { equation ";" }\r
+//     end for\r
+       "for" for_indices() "loop"\r
+               ( equation() ";" )*\r
+       "end" "for"\r}\r
+\r
+void for_statement() : {\r
+} {\r
+//     for for_indices loop\r
+//     { equation ";" }\r
+//     end for\r
+       "for" for_indices() "loop"\r
+               ( statement() ";" )*\r
+       "end" "for"\r}\r
+\r
+void for_indices() : {\r
+} {\r
+       //for_index {"," for_index}\r
+       for_index() ("," for_index())*\r
+}\r
+\r
+void for_index() : {\r
+} {\r
+       //IDENT [ in expression ]\r
+       <IDENT> ( "in" expression()     )?\r
+}\r
+\r
+void while_statement() : {\r
+} {\r
+//     while expression loop\r
+//     { statement ";" }\r
+//     end while\r
+       "while" expression() "loop"\r
+               ( statement() ";" )*\r
+       "end" "while"\r}\r
+\r
+void when_equation() : {\r
+} {\r
+//     when expression then\r
+//     { equation ";" }\r
+//     { elsewhen expression then\r
+//     { equation ";" } }\r
+//     end when\r
+       "when" expression() "then"\r
+               ( equation() ";" )*\r
+       ( "elsewhen" expression() "then"\r
+               ( equation() ";" )*\r
+       )*\r
+       "end" "when"\r}\r
+\r
+void when_statement() : {\r
+} {\r
+//     when expression then\r
+//     { statement ";" }\r
+//     { elsewhen expression then\r
+//     { statement ";" } }\r
+//     end when\r
+       "when" expression() "then"\r
+               ( statement() ";" )*\r
+       ( "elsewhen" expression() "then"\r
+               ( statement() ";" )*\r
+       )*\r
+       "end" "when"\r}\r
+\r
+void connect_clause() : {\r
+} {\r
+//     connect "(" component_reference "," component_reference ")"\r
+       "connect" "(" component_reference() "," component_reference() ")"\r
+}\r
+\r
+/*** Expressions ***************************************************/\r
+void expr() : {\r
+} {\r
+       simple_expression() <EOF>\r
+       |\r
+       "if" expression() "then" expression() ( "elseif" expression() "then" expression() )*\r
+       "else" expression() <EOF>\r
+}\r
+\r
+void expression() : {\r
+} {\r
+       simple_expression()\r
+       | "if" expression() "then" expression() ( "elseif" expression() "then" expression() )*\r
+       "else" expression()\r
+}\r
+\r
+void simple_expression() : {\r
+} {\r
+       logical_expression() ( ":" logical_expression() ( ":" logical_expression() )? )?\r
+}      \r
+\r
+void logical_expression() : {\r
+} {\r
+       logical_term() ( "or" logical_term() )*\r
+}      \r
+\r
+void logical_term() : {\r
+} {\r
+       logical_factor() ( "and" logical_factor() )*\r
+}\r
+\r
+void logical_factor() : {\r
+} {\r
+       ( "not" )? relation()\r
+}\r
+\r
+void relation() : {\r
+} {\r
+       arithmetic_expression() ( rel_op() arithmetic_expression() )?\r
+}\r
+\r
+void rel_op() : {\r
+} {\r
+       "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+}\r
+\r
+void arithmetic_expression() : {\r
+} {\r
+    (add_op())? term() (add_op() term())*\r
+}\r
+\r
+void add_op() : {\r
+} {\r
+    "+" | "-" | ".+" | ".-"\r
+}\r
+\r
+void term() : {\r
+} {\r
+    factor() ( mul_op() factor() )*\r
+}\r
+\r
+void mul_op() : {\r
+} {\r
+    "*" | "/" | ".*" | "./"\r
+}\r
+\r
+void factor() : {\r
+} {\r
+       primary() ( ( "^" | ".^" ) primary() )?\r
+}\r
+\r
+void primary() : {\r
+} {\r
+       <UNSIGNED_NUMBER>\r
+  | <UNSIGNED_INTEGER>\r
+  | <STRING>\r
+  | "false"\r
+  | "true"\r
+  |   LOOKAHEAD( (name()|"der"|"initial") "(" ) (name()|"der"|"initial") function_call_args()\r
+  | component_reference()\r
+  /* | "(" output_expression_list() ")" */ // Not needed, replaced with following:\r
+  | "(" expression() ")"\r
+  | "[" expression_list() ( ";" expression_list() )* "]"\r
+  | "{" function_arguments() "}"\r
+  | "end"\r
+}\r
+\r
+String name() : {\r
+    String ret = new String("");\r
+} {\r
+//     [ "." ] IDENT { "." IDENT }\r
+       ( "." { ret += "."; } )?\r
+          <IDENT> { ret += token.image; }\r
+          ( "." { ret += "."; }\r
+          <IDENT> { ret += token.image; }\r
+       )*\r
+       {\r        return ret;\r
+    }\r
+}\r
+\r
+void component_reference() : {\r
+} {\r
+//     [ "." ] IDENT [ array_subscripts ] { "." IDENT [ array_subscripts ] }\r
+       ( "." )? <IDENT> ( array_subscripts() )? ( "." <IDENT> ( array_subscripts() )? )*\r
+}\r
+\r
+void function_call_args() : {\r
+} {\r
+//     "(" [ function_arguments ] ")"\r
+       "(" ( function_arguments() )? ")"\r
+}\r
+\r
+void function_arguments() : {\r
+} {\r
+       //expression [ "," function_arguments | for for_indices ]\r
+       //| named_arguments\r
+        LOOKAHEAD(2) expression() ( "," function_arguments() | "for" for_indices() )?\r
+       | named_arguments()\r
+}\r
+\r
+void named_arguments() : {\r
+} {\r
+//     named_argument [ "," named_arguments ]  \r
+       named_argument() ( "," named_arguments() )?\r
+}\r
+\r
+void named_argument() : {\r
+} {    \r
+       <IDENT> "=" expression()\r
+}\r
+\r
+void output_expression_list() : {\r
+} {\r
+//     [ expression ] { "," [ expression ] }  \r
+       ( expression() )? ( "," ( expression() )? )*\r
+}\r
+\r
+void expression_list() : {\r
+} {\r
+//     expression { "," expression }\r
+    expression() ( "," expression() )*\r
+}\r
+\r
+void array_subscripts() : {\r
+} {\r
+//     "[" subscript { "," subscript } "]" \r
+       "["     subscript()     ( "," subscript() )* "]"\r
+}\r
+\r
+void subscript() : {\r
+} {\r
+//     ":" | expression  \r     ":" | expression() \r
+}\r
+\r
+String comment() : {\r
+    String ret;\r} {\r// string_comment [ annotation ]\r
+       ret = string_comment() ( annotation() )?\r
+       {\r          return ret;\r
+       }\r
+}\r
+\r
+String string_comment() : {\r
+    String ret = null;\r
+} {\r
+//     [ STRING { "+" STRING } ]  \r
+       ( <STRING> { ret = new String(token.image); }\r
+           ( "+" { ret += "+"; }\r
+               <STRING> { ret += token.image; }\r
+           )*\r
+       )?\r
+       {\r          return ret;\r
+       } \r}\r
+\r
+void annotation() : {\r
+} {\r
+//     annotation class_modification\r
+       "annotation" class_modification()  \r
+}\r  \r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ParseException.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/ParseException.java
new file mode 100644 (file)
index 0000000..86734a7
--- /dev/null
@@ -0,0 +1,187 @@
+/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */\r
+/* JavaCCOptions:KEEP_LINE_COL=null */\r
+package org.simantics.sysdyn.modelParser;\r
+\r
+/**\r
+ * This exception is thrown when parse errors are encountered.\r
+ * You can explicitly create objects of this exception type by\r
+ * calling the method generateParseException in the generated\r
+ * parser.\r
+ *\r
+ * You can modify this class to customize your error reporting\r
+ * mechanisms so long as you retain the public fields.\r
+ */\r
+public class ParseException extends Exception {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * This constructor is used by the method "generateParseException"\r
+   * in the generated parser.  Calling this constructor generates\r
+   * a new object of this type with the fields "currentToken",\r
+   * "expectedTokenSequences", and "tokenImage" set.\r
+   */\r
+  public ParseException(Token currentTokenVal,\r
+                        int[][] expectedTokenSequencesVal,\r
+                        String[] tokenImageVal\r
+                       )\r
+  {\r
+    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));\r
+    currentToken = currentTokenVal;\r
+    expectedTokenSequences = expectedTokenSequencesVal;\r
+    tokenImage = tokenImageVal;\r
+  }\r
+\r
+  /**\r
+   * The following constructors are for use by you for whatever\r
+   * purpose you can think of.  Constructing the exception in this\r
+   * manner makes the exception behave in the normal way - i.e., as\r
+   * documented in the class "Throwable".  The fields "errorToken",\r
+   * "expectedTokenSequences", and "tokenImage" do not contain\r
+   * relevant information.  The JavaCC generated code does not use\r
+   * these constructors.\r
+   */\r
+\r
+  public ParseException() {\r
+    super();\r
+  }\r
+\r
+  /** Constructor with message. */\r
+  public ParseException(String message) {\r
+    super(message);\r
+  }\r
+\r
+\r
+  /**\r
+   * This is the last token that has been consumed successfully.  If\r
+   * this object has been created due to a parse error, the token\r
+   * followng this token will (therefore) be the first error token.\r
+   */\r
+  public Token currentToken;\r
+\r
+  /**\r
+   * Each entry in this array is an array of integers.  Each array\r
+   * of integers represents a sequence of tokens (by their ordinal\r
+   * values) that is expected at this point of the parse.\r
+   */\r
+  public int[][] expectedTokenSequences;\r
+\r
+  /**\r
+   * This is a reference to the "tokenImage" array of the generated\r
+   * parser within which the parse error occurred.  This array is\r
+   * defined in the generated ...Constants interface.\r
+   */\r
+  public String[] tokenImage;\r
+\r
+  /**\r
+   * It uses "currentToken" and "expectedTokenSequences" to generate a parse\r
+   * error message and returns it.  If this object has been created\r
+   * due to a parse error, and you do not catch it (it gets thrown\r
+   * from the parser) the correct error message\r
+   * gets displayed.\r
+   */\r
+  private static String initialise(Token currentToken,\r
+                           int[][] expectedTokenSequences,\r
+                           String[] tokenImage) {\r
+    String eol = System.getProperty("line.separator", "\n");\r
+    StringBuffer expected = new StringBuffer();\r
+    int maxSize = 0;\r
+    for (int i = 0; i < expectedTokenSequences.length; i++) {\r
+      if (maxSize < expectedTokenSequences[i].length) {\r
+        maxSize = expectedTokenSequences[i].length;\r
+      }\r
+      for (int j = 0; j < expectedTokenSequences[i].length; j++) {\r
+        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');\r
+      }\r
+      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {\r
+        expected.append("...");\r
+      }\r
+      expected.append(eol).append("    ");\r
+    }\r
+    String retval = "Encountered \"";\r
+    Token tok = currentToken.next;\r
+    for (int i = 0; i < maxSize; i++) {\r
+      if (i != 0) retval += " ";\r
+      if (tok.kind == 0) {\r
+        retval += tokenImage[0];\r
+        break;\r
+      }\r
+      retval += " " + tokenImage[tok.kind];\r
+      retval += " \"";\r
+      retval += add_escapes(tok.image);\r
+      retval += " \"";\r
+      tok = tok.next;\r
+    }\r
+    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;\r
+    retval += "." + eol;\r
+    if (expectedTokenSequences.length == 1) {\r
+      retval += "Was expecting:" + eol + "    ";\r
+    } else {\r
+      retval += "Was expecting one of:" + eol + "    ";\r
+    }\r
+    retval += expected.toString();\r
+    return retval;\r
+  }\r
+\r
+  /**\r
+   * The end of line string for this machine.\r
+   */\r
+  protected String eol = System.getProperty("line.separator", "\n");\r
+\r
+  /**\r
+   * Used to convert raw characters to their escaped version\r
+   * when these raw version cannot be used as part of an ASCII\r
+   * string literal.\r
+   */\r
+  static String add_escapes(String str) {\r
+      StringBuffer retval = new StringBuffer();\r
+      char ch;\r
+      for (int i = 0; i < str.length(); i++) {\r
+        switch (str.charAt(i))\r
+        {\r
+           case 0 :\r
+              continue;\r
+           case '\b':\r
+              retval.append("\\b");\r
+              continue;\r
+           case '\t':\r
+              retval.append("\\t");\r
+              continue;\r
+           case '\n':\r
+              retval.append("\\n");\r
+              continue;\r
+           case '\f':\r
+              retval.append("\\f");\r
+              continue;\r
+           case '\r':\r
+              retval.append("\\r");\r
+              continue;\r
+           case '\"':\r
+              retval.append("\\\"");\r
+              continue;\r
+           case '\'':\r
+              retval.append("\\\'");\r
+              continue;\r
+           case '\\':\r
+              retval.append("\\\\");\r
+              continue;\r
+           default:\r
+              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+                 String s = "0000" + Integer.toString(ch, 16);\r
+                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+              } else {\r
+                 retval.append(ch);\r
+              }\r
+              continue;\r
+        }\r
+      }\r
+      return retval.toString();\r
+   }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=e46c56bfa832359193465f81e8a2147e (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/SimpleCharStream.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/SimpleCharStream.java
new file mode 100644 (file)
index 0000000..102b285
--- /dev/null
@@ -0,0 +1,471 @@
+/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */\r
+/* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package org.simantics.sysdyn.modelParser;\r
+\r
+/**\r
+ * An implementation of interface CharStream, where the stream is assumed to\r
+ * contain only ASCII characters (without unicode processing).\r
+ */\r
+\r
+public class SimpleCharStream\r
+{\r
+/** Whether parser is static. */\r
+  public static final boolean staticFlag = false;\r
+  int bufsize;\r
+  int available;\r
+  int tokenBegin;\r
+/** Position in buffer. */\r
+  public int bufpos = -1;\r
+  protected int bufline[];\r
+  protected int bufcolumn[];\r
+\r
+  protected int column = 0;\r
+  protected int line = 1;\r
+\r
+  protected boolean prevCharIsCR = false;\r
+  protected boolean prevCharIsLF = false;\r
+\r
+  protected java.io.Reader inputStream;\r
+\r
+  protected char[] buffer;\r
+  protected int maxNextCharInd = 0;\r
+  protected int inBuf = 0;\r
+  protected int tabSize = 8;\r
+\r
+  protected void setTabSize(int i) { tabSize = i; }\r
+  protected int getTabSize(int i) { return tabSize; }\r
+\r
+\r
+  protected void ExpandBuff(boolean wrapAround)\r
+  {\r
+    char[] newbuffer = new char[bufsize + 2048];\r
+    int newbufline[] = new int[bufsize + 2048];\r
+    int newbufcolumn[] = new int[bufsize + 2048];\r
+\r
+    try\r
+    {\r
+      if (wrapAround)\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos += (bufsize - tokenBegin));\r
+      }\r
+      else\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos -= tokenBegin);\r
+      }\r
+    }\r
+    catch (Throwable t)\r
+    {\r
+      throw new Error(t.getMessage());\r
+    }\r
+\r
+\r
+    bufsize += 2048;\r
+    available = bufsize;\r
+    tokenBegin = 0;\r
+  }\r
+\r
+  protected void FillBuff() throws java.io.IOException\r
+  {\r
+    if (maxNextCharInd == available)\r
+    {\r
+      if (available == bufsize)\r
+      {\r
+        if (tokenBegin > 2048)\r
+        {\r
+          bufpos = maxNextCharInd = 0;\r
+          available = tokenBegin;\r
+        }\r
+        else if (tokenBegin < 0)\r
+          bufpos = maxNextCharInd = 0;\r
+        else\r
+          ExpandBuff(false);\r
+      }\r
+      else if (available > tokenBegin)\r
+        available = bufsize;\r
+      else if ((tokenBegin - available) < 2048)\r
+        ExpandBuff(true);\r
+      else\r
+        available = tokenBegin;\r
+    }\r
+\r
+    int i;\r
+    try {\r
+      if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)\r
+      {\r
+        inputStream.close();\r
+        throw new java.io.IOException();\r
+      }\r
+      else\r
+        maxNextCharInd += i;\r
+      return;\r
+    }\r
+    catch(java.io.IOException e) {\r
+      --bufpos;\r
+      backup(0);\r
+      if (tokenBegin == -1)\r
+        tokenBegin = bufpos;\r
+      throw e;\r
+    }\r
+  }\r
+\r
+/** Start. */\r
+  public char BeginToken() throws java.io.IOException\r
+  {\r
+    tokenBegin = -1;\r
+    char c = readChar();\r
+    tokenBegin = bufpos;\r
+\r
+    return c;\r
+  }\r
+\r
+  protected void UpdateLineColumn(char c)\r
+  {\r
+    column++;\r
+\r
+    if (prevCharIsLF)\r
+    {\r
+      prevCharIsLF = false;\r
+      line += (column = 1);\r
+    }\r
+    else if (prevCharIsCR)\r
+    {\r
+      prevCharIsCR = false;\r
+      if (c == '\n')\r
+      {\r
+        prevCharIsLF = true;\r
+      }\r
+      else\r
+        line += (column = 1);\r
+    }\r
+\r
+    switch (c)\r
+    {\r
+      case '\r' :\r
+        prevCharIsCR = true;\r
+        break;\r
+      case '\n' :\r
+        prevCharIsLF = true;\r
+        break;\r
+      case '\t' :\r
+        column--;\r
+        column += (tabSize - (column % tabSize));\r
+        break;\r
+      default :\r
+        break;\r
+    }\r
+\r
+    bufline[bufpos] = line;\r
+    bufcolumn[bufpos] = column;\r
+  }\r
+\r
+/** Read a character. */\r
+  public char readChar() throws java.io.IOException\r
+  {\r
+    if (inBuf > 0)\r
+    {\r
+      --inBuf;\r
+\r
+      if (++bufpos == bufsize)\r
+        bufpos = 0;\r
+\r
+      return buffer[bufpos];\r
+    }\r
+\r
+    if (++bufpos >= maxNextCharInd)\r
+      FillBuff();\r
+\r
+    char c = buffer[bufpos];\r
+\r
+    UpdateLineColumn(c);\r
+    return c;\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndColumn\r
+   */\r
+\r
+  public int getColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndLine\r
+   */\r
+\r
+  public int getLine() {\r
+    return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token end column number. */\r
+  public int getEndColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  /** Get token end line number. */\r
+  public int getEndLine() {\r
+     return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token beginning column number. */\r
+  public int getBeginColumn() {\r
+    return bufcolumn[tokenBegin];\r
+  }\r
+\r
+  /** Get token beginning line number. */\r
+  public int getBeginLine() {\r
+    return bufline[tokenBegin];\r
+  }\r
+\r
+/** Backup a number of characters. */\r
+  public void backup(int amount) {\r
+\r
+    inBuf += amount;\r
+    if ((bufpos -= amount) < 0)\r
+      bufpos += bufsize;\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    available = bufsize = buffersize;\r
+    buffer = new char[buffersize];\r
+    bufline = new int[buffersize];\r
+    bufcolumn = new int[buffersize];\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    if (buffer == null || buffersize != buffer.length)\r
+    {\r
+      available = bufsize = buffersize;\r
+      buffer = new char[buffersize];\r
+      bufline = new int[buffersize];\r
+      bufcolumn = new int[buffersize];\r
+    }\r
+    prevCharIsLF = prevCharIsCR = false;\r
+    tokenBegin = inBuf = maxNextCharInd = 0;\r
+    bufpos = -1;\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+  int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                          int startcolumn, int buffersize)\r
+  {\r
+    ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                     int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+  /** Get token literal value. */\r
+  public String GetImage()\r
+  {\r
+    if (bufpos >= tokenBegin)\r
+      return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);\r
+    else\r
+      return new String(buffer, tokenBegin, bufsize - tokenBegin) +\r
+                            new String(buffer, 0, bufpos + 1);\r
+  }\r
+\r
+  /** Get the suffix. */\r
+  public char[] GetSuffix(int len)\r
+  {\r
+    char[] ret = new char[len];\r
+\r
+    if ((bufpos + 1) >= len)\r
+      System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);\r
+    else\r
+    {\r
+      System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,\r
+                                                        len - bufpos - 1);\r
+      System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);\r
+    }\r
+\r
+    return ret;\r
+  }\r
+\r
+  /** Reset buffer when finished. */\r
+  public void Done()\r
+  {\r
+    buffer = null;\r
+    bufline = null;\r
+    bufcolumn = null;\r
+  }\r
+\r
+  /**\r
+   * Method to adjust line and column numbers for the start of a token.\r
+   */\r
+  public void adjustBeginLineColumn(int newLine, int newCol)\r
+  {\r
+    int start = tokenBegin;\r
+    int len;\r
+\r
+    if (bufpos >= tokenBegin)\r
+    {\r
+      len = bufpos - tokenBegin + inBuf + 1;\r
+    }\r
+    else\r
+    {\r
+      len = bufsize - tokenBegin + bufpos + 1 + inBuf;\r
+    }\r
+\r
+    int i = 0, j = 0, k = 0;\r
+    int nextColDiff = 0, columnDiff = 0;\r
+\r
+    while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])\r
+    {\r
+      bufline[j] = newLine;\r
+      nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];\r
+      bufcolumn[j] = newCol + columnDiff;\r
+      columnDiff = nextColDiff;\r
+      i++;\r
+    }\r
+\r
+    if (i < len)\r
+    {\r
+      bufline[j] = newLine++;\r
+      bufcolumn[j] = newCol + columnDiff;\r
+\r
+      while (i++ < len)\r
+      {\r
+        if (bufline[j = start % bufsize] != bufline[++start % bufsize])\r
+          bufline[j] = newLine++;\r
+        else\r
+          bufline[j] = newLine;\r
+      }\r
+    }\r
+\r
+    line = bufline[j];\r
+    column = bufcolumn[j];\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=7ab7faca15b64bda32c7a4effb209066 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/Token.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/Token.java
new file mode 100644 (file)
index 0000000..25d3618
--- /dev/null
@@ -0,0 +1,131 @@
+/* Generated By:JavaCC: Do not edit this line. Token.java Version 5.0 */\r
+/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package org.simantics.sysdyn.modelParser;\r
+\r
+/**\r
+ * Describes the input token stream.\r
+ */\r
+\r
+public class Token implements java.io.Serializable {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * An integer that describes the kind of this token.  This numbering\r
+   * system is determined by JavaCCParser, and a table of these numbers is\r
+   * stored in the file ...Constants.java.\r
+   */\r
+  public int kind;\r
+\r
+  /** The line number of the first character of this Token. */\r
+  public int beginLine;\r
+  /** The column number of the first character of this Token. */\r
+  public int beginColumn;\r
+  /** The line number of the last character of this Token. */\r
+  public int endLine;\r
+  /** The column number of the last character of this Token. */\r
+  public int endColumn;\r
+\r
+  /**\r
+   * The string image of the token.\r
+   */\r
+  public String image;\r
+\r
+  /**\r
+   * A reference to the next regular (non-special) token from the input\r
+   * stream.  If this is the last token from the input stream, or if the\r
+   * token manager has not read tokens beyond this one, this field is\r
+   * set to null.  This is true only if this token is also a regular\r
+   * token.  Otherwise, see below for a description of the contents of\r
+   * this field.\r
+   */\r
+  public Token next;\r
+\r
+  /**\r
+   * This field is used to access special tokens that occur prior to this\r
+   * token, but after the immediately preceding regular (non-special) token.\r
+   * If there are no such special tokens, this field is set to null.\r
+   * When there are more than one such special token, this field refers\r
+   * to the last of these special tokens, which in turn refers to the next\r
+   * previous special token through its specialToken field, and so on\r
+   * until the first special token (whose specialToken field is null).\r
+   * The next fields of special tokens refer to other special tokens that\r
+   * immediately follow it (without an intervening regular token).  If there\r
+   * is no such token, this field is null.\r
+   */\r
+  public Token specialToken;\r
+\r
+  /**\r
+   * An optional attribute value of the Token.\r
+   * Tokens which are not used as syntactic sugar will often contain\r
+   * meaningful values that will be used later on by the compiler or\r
+   * interpreter. This attribute value is often different from the image.\r
+   * Any subclass of Token that actually wants to return a non-null value can\r
+   * override this method as appropriate.\r
+   */\r
+  public Object getValue() {\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * No-argument constructor\r
+   */\r
+  public Token() {}\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image.\r
+   */\r
+  public Token(int kind)\r
+  {\r
+    this(kind, null);\r
+  }\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image and Kind.\r
+   */\r
+  public Token(int kind, String image)\r
+  {\r
+    this.kind = kind;\r
+    this.image = image;\r
+  }\r
+\r
+  /**\r
+   * Returns the image.\r
+   */\r
+  public String toString()\r
+  {\r
+    return image;\r
+  }\r
+\r
+  /**\r
+   * Returns a new Token object, by default. However, if you want, you\r
+   * can create and return subclass objects based on the value of ofKind.\r
+   * Simply add the cases to the switch for all those special cases.\r
+   * For example, if you have a subclass of Token called IDToken that\r
+   * you want to create if ofKind is ID, simply add something like :\r
+   *\r
+   *    case MyParserConstants.ID : return new IDToken(ofKind, image);\r
+   *\r
+   * to the following switch statement. Then you can cast matchedToken\r
+   * variable to the appropriate type and use sit in your lexical actions.\r
+   */\r
+  public static Token newToken(int ofKind, String image)\r
+  {\r
+    switch(ofKind)\r
+    {\r
+      default : return new Token(ofKind, image);\r
+    }\r
+  }\r
+\r
+  public static Token newToken(int ofKind)\r
+  {\r
+    return newToken(ofKind, null);\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=8584b8a0988c627589640a007dbfe0bb (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/TokenMgrError.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelParser/TokenMgrError.java
new file mode 100644 (file)
index 0000000..60c6745
--- /dev/null
@@ -0,0 +1,147 @@
+/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 5.0 */\r
+/* JavaCCOptions: */\r
+package org.simantics.sysdyn.modelParser;\r
+\r
+/** Token Manager Error. */\r
+public class TokenMgrError extends Error\r
+{\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /*\r
+   * Ordinals for various reasons why an Error of this type can be thrown.\r
+   */\r
+\r
+  /**\r
+   * Lexical error occurred.\r
+   */\r
+  static final int LEXICAL_ERROR = 0;\r
+\r
+  /**\r
+   * An attempt was made to create a second instance of a static token manager.\r
+   */\r
+  static final int STATIC_LEXER_ERROR = 1;\r
+\r
+  /**\r
+   * Tried to change to an invalid lexical state.\r
+   */\r
+  static final int INVALID_LEXICAL_STATE = 2;\r
+\r
+  /**\r
+   * Detected (and bailed out of) an infinite loop in the token manager.\r
+   */\r
+  static final int LOOP_DETECTED = 3;\r
+\r
+  /**\r
+   * Indicates the reason why the exception is thrown. It will have\r
+   * one of the above 4 values.\r
+   */\r
+  int errorCode;\r
+\r
+  /**\r
+   * Replaces unprintable characters by their escaped (or unicode escaped)\r
+   * equivalents in the given string\r
+   */\r
+  protected static final String addEscapes(String str) {\r
+    StringBuffer retval = new StringBuffer();\r
+    char ch;\r
+    for (int i = 0; i < str.length(); i++) {\r
+      switch (str.charAt(i))\r
+      {\r
+        case 0 :\r
+          continue;\r
+        case '\b':\r
+          retval.append("\\b");\r
+          continue;\r
+        case '\t':\r
+          retval.append("\\t");\r
+          continue;\r
+        case '\n':\r
+          retval.append("\\n");\r
+          continue;\r
+        case '\f':\r
+          retval.append("\\f");\r
+          continue;\r
+        case '\r':\r
+          retval.append("\\r");\r
+          continue;\r
+        case '\"':\r
+          retval.append("\\\"");\r
+          continue;\r
+        case '\'':\r
+          retval.append("\\\'");\r
+          continue;\r
+        case '\\':\r
+          retval.append("\\\\");\r
+          continue;\r
+        default:\r
+          if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+            String s = "0000" + Integer.toString(ch, 16);\r
+            retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+          } else {\r
+            retval.append(ch);\r
+          }\r
+          continue;\r
+      }\r
+    }\r
+    return retval.toString();\r
+  }\r
+\r
+  /**\r
+   * Returns a detailed message for the Error when it is thrown by the\r
+   * token manager to indicate a lexical error.\r
+   * Parameters :\r
+   *    EOFSeen     : indicates if EOF caused the lexical error\r
+   *    curLexState : lexical state in which this error occurred\r
+   *    errorLine   : line number when the error occurred\r
+   *    errorColumn : column number when the error occurred\r
+   *    errorAfter  : prefix that was seen before this error occurred\r
+   *    curchar     : the offending character\r
+   * Note: You can customize the lexical error message by modifying this method.\r
+   */\r
+  protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {\r
+    return("Lexical error at line " +\r
+          errorLine + ", column " +\r
+          errorColumn + ".  Encountered: " +\r
+          (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +\r
+          "after : \"" + addEscapes(errorAfter) + "\"");\r
+  }\r
+\r
+  /**\r
+   * You can also modify the body of this method to customize your error messages.\r
+   * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not\r
+   * of end-users concern, so you can return something like :\r
+   *\r
+   *     "Internal Error : Please file a bug report .... "\r
+   *\r
+   * from this method for such cases in the release version of your parser.\r
+   */\r
+  public String getMessage() {\r
+    return super.getMessage();\r
+  }\r
+\r
+  /*\r
+   * Constructors of various flavors follow.\r
+   */\r
+\r
+  /** No arg constructor. */\r
+  public TokenMgrError() {\r
+  }\r
+\r
+  /** Constructor with message and reason. */\r
+  public TokenMgrError(String message, int reason) {\r
+    super(message);\r
+    errorCode = reason;\r
+  }\r
+\r
+  /** Full Constructor. */\r
+  public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {\r
+    this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);\r
+  }\r
+}\r
+/* JavaCC - OriginalChecksum=d047fc9c0c00c40e4d34a354929bb60c (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelica/ModelicaWriter.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/modelica/ModelicaWriter.java
new file mode 100644 (file)
index 0000000..f2c0a1b
--- /dev/null
@@ -0,0 +1,506 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.modelica;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.Comparator;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+\r
+import org.simantics.sysdyn.representation.Book;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.Dependency;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Input;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.ModuleType;\r
+import org.simantics.sysdyn.representation.Sheet;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Variable;\r
+import org.simantics.sysdyn.representation.expressions.DelayExpression;\r
+import org.simantics.sysdyn.representation.expressions.IExpression;\r
+\r
+/**\r
+ * ModelicaWriter writes Sysdyn model representations (objmap) into Modelica code.\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ModelicaWriter {\r
+\r
+       /**\r
+        * Write a collection of configurations into a single Modelica code\r
+        * @param isGame \r
+        * \r
+        * @param Configurations Configurations, one main configuration and possible modules\r
+        * @return Complete Modelica code of a model\r
+        */\r
+       public static String write(Collection<Configuration> _configurations, double startTime, boolean isGame, String omVersion) {\r
+\r
+               ArrayList<Configuration> configurations = new ArrayList<Configuration>(_configurations);\r
+               Collections.sort(configurations, new Comparator<Configuration>() {\r
+\r
+                       boolean uses(Configuration o1, Configuration o2) {\r
+                               ModuleType type = o2.getModuleType();\r
+                               if(type == null) return false;\r
+                               for(IElement e : o1.getElements()) {\r
+                                       if(e instanceof Module) {\r
+                                               Module m = (Module)e;\r
+                                               if(m.getType().equals(type)) {\r
+                                                       return true;\r
+                                               }\r
+                                       }\r
+                               }\r
+                               return false;\r
+                       }\r
+\r
+                       @Override\r
+                       public int compare(Configuration o1, Configuration o2) {\r
+                               if(uses(o1, o2)) return 1;\r
+                               else if(uses(o2, o1)) return -1;\r
+                               else return 0;\r
+                       }\r
+\r
+               });\r
+\r
+               Configuration modelConf = null;\r
+               for(Configuration conf : configurations) {\r
+                       if(conf.getModel() != null) {\r
+                               modelConf = conf;\r
+                       }\r
+               }\r
+               StringBuilder b = new StringBuilder();\r
+\r
+               int spreadsheetlocation = b.length();\r
+\r
+               String modelName = modelConf.getLabel().replace(" ", "");\r
+               b.append("model " + modelName + "\n");\r
+\r
+               // Super class for enumerations\r
+               b.append("partial class Enumeration_class\n");\r
+               b.append("    parameter Integer size;\n");\r
+               b.append("    parameter Integer elements[:];\n");\r
+               b.append("end Enumeration_class;\n\n");\r
+\r
+               // find out which delays are used in the model and create the\r
+               // necessary classes\r
+               HashSet<Integer> delays = new HashSet<Integer>();\r
+               for (Configuration configuration : configurations) {\r
+                       for (IElement element : configuration.getElements()) {\r
+                               if (element instanceof IndependentVariable) {\r
+                                       for (IExpression expression : ((IndependentVariable)element).getExpressions()) {\r
+                                               if (expression instanceof DelayExpression) {\r
+                                                       delays.add(((DelayExpression)expression).getOrder());\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+\r
+               for (Integer i : delays) {\r
+                       b.append(getDelayClass(i));\r
+                       b.append("\n");\r
+               }\r
+\r
+               HashSet<String> sheetNames = new HashSet<String>();\r
+               for(Sheet sheet : getSpreadSheets(configurations))\r
+                       sheetNames.add(sheet.getModelicaName());\r
+\r
+               // Write all module configurations to the declarations part (first)\r
+               for(Configuration conf : configurations) {\r
+                       conf.setIsGameConfiguration(isGame);\r
+                       if(!conf.equals(modelConf))\r
+                               writeConfiguration(conf, sheetNames, startTime, b);\r
+               }\r
+\r
+               // Write model configuration last, so that equations-part does not contain module definitions\r
+               modelConf.setIsGameConfiguration(isGame);\r
+               writeConfiguration(modelConf, sheetNames, startTime, b);\r
+\r
+               b.append("end " + modelName + ";\n\n");\r
+\r
+               // Insert spreadsheets\r
+               if(omVersion != null && omVersion.startsWith("1.9")) {\r
+                       b.insert(spreadsheetlocation, getGlobalSpreadSheets(configurations));\r
+               } else {\r
+                       b.append(getGlobalSpreadSheets(configurations));\r
+               }\r
+\r
+               return b.toString();\r
+       }\r
+\r
+       /**\r
+        * Get all spreadsheets that are found in the model\r
+        * @param configurations\r
+        * @return\r
+        */\r
+       private static List<Sheet> getSpreadSheets(Collection<Configuration> configurations) {\r
+               for(Configuration conf : configurations) {\r
+                       if(conf.getModel() != null) {\r
+                               for(IElement e : conf.getElements()) {\r
+                                       if(e instanceof Book) {\r
+                                               return ((Book)e).getSheets();\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               return Collections.emptyList();\r
+       }\r
+\r
+       /**\r
+        * \r
+        */\r
+       private static String getGlobalSpreadSheets(Collection<Configuration> configurations) {\r
+               StringBuilder sheets = new StringBuilder();\r
+               for(Configuration conf : configurations) {\r
+                       if(conf.getModel() != null) {\r
+                               for(IElement e : conf.getElements()) {\r
+                                       if(e instanceof Book) {\r
+                                               return ((Book)e).getBook();\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+\r
+               return sheets.toString();\r
+       }\r
+\r
+       /**\r
+        * Write a single configuration to a given string builder\r
+        * \r
+        * @param configuration Model or module configuration\r
+        * @param b String builder\r
+        */\r
+       private static void writeConfiguration(Configuration configuration, HashSet<String> sheetNames, double startTime, StringBuilder b) {\r
+               boolean defTime = true;\r
+               String app;\r
+\r
+               // Lists for storing different configuration elements\r
+               ArrayList<IndependentVariable> variables = new ArrayList<IndependentVariable>();\r
+               ArrayList<Input> inputs = new ArrayList<Input>();\r
+               ArrayList<Module> modules = new ArrayList<Module>();\r
+               ArrayList<Stock> stocks = new ArrayList<Stock>();\r
+               ArrayList<Enumeration> enumerations = new ArrayList<Enumeration>();\r
+               ArrayList<Dependency> inputDependencies = new ArrayList<Dependency>();\r
+               ArrayList<Dependency> outputDependencies = new ArrayList<Dependency>();\r
+               HashMap<String, ArrayList<Input>> moduleInputs = new HashMap<String, ArrayList<Input>>();\r
+\r
+               // Initialize lists\r
+               for(IElement element : configuration.getElements()) {\r
+                       if(element instanceof IndependentVariable) {\r
+                               // Normal variable\r
+                               variables.add((IndependentVariable)element);\r
+                               if(element instanceof Stock)\r
+                                       // Stock\r
+                                       stocks.add((Stock)element);\r
+                       } else if (element instanceof Module) {\r
+                               // Module\r
+                               Module m = (Module)element; \r
+                               modules.add(m);\r
+                               moduleInputs.put(m.getName(), new ArrayList<Input>());\r
+                               for(IElement e : m.getType().getConfiguration().getElements())\r
+                                       // Inputs inside the module\r
+                                       if(e instanceof Input && !((Input)e).isHeadOfDependency()) {\r
+                                               moduleInputs.get(m.getName()).add((Input)e);\r
+                                       }\r
+                       } else if (element instanceof Input) {\r
+                               // Input variables\r
+                               inputs.add((Input)element);\r
+                       } else if (element instanceof Enumeration) {\r
+                               // Enumerations\r
+                               enumerations.add((Enumeration)element);\r
+                       } else if (element instanceof Dependency) {\r
+                               Dependency dependency = (Dependency)element;\r
+                               if(dependency.getHead() instanceof Module) {\r
+                                       // References given to child modules\r
+                                       outputDependencies.add(dependency);\r
+                               } else if(dependency.getTail() instanceof Module){\r
+                                       // References from child modules\r
+                                       inputDependencies.add(dependency);\r
+                               }\r
+                       }\r
+               }\r
+\r
+               // Setup input references. (Input, String reference to another variable)\r
+               HashMap<Input, String> inputReferences = new HashMap<Input, String>();\r
+               setupInputReferences(inputReferences, inputDependencies);\r
+\r
+\r
+               // If the configuration is model configuration, use model name. Otherwise, use configuration name.\r
+               ModuleType mt = configuration.getModuleType();\r
+\r
+               // className == null, if this is a model configuration. model configuration start and end are written in ModelicaWriter.write\r
+               String className = mt != null ? (mt.getName().replace(" ", "")) : null;\r
+\r
+               if(className != null)\r
+                       b.append("class "+className+"\n");\r
+\r
+               // Add spreadsheets to all modules and model. Model is "inner" and modules "outer"\r
+               String globalStatus = mt != null ? "outer" : "inner";\r
+               for(String sheetName : sheetNames)\r
+                       b.append("    " + globalStatus + " " + sheetName + "_class" + " "+ sheetName + ";\n");\r
+\r
+               if(!enumerations.isEmpty()) {\r
+                       b.append("// Enumeration definitions\n");\r
+                       for(Enumeration e : enumerations) {\r
+                               b.append(e.getDeclaration());\r
+                       }\r
+               }\r
+\r
+               b.append("// Variable definitions\n");\r
+               for(IndependentVariable variable : variables) {\r
+                       app = variable.getDeclaration();\r
+                       if (app != null) {\r
+                               b.append(app);\r
+                       }\r
+               }\r
+\r
+               if(defTime) {\r
+                       // Time variable for FMU (game) simulations\r
+                       if(configuration.isGameConfiguration()) {\r
+                               if(configuration.getModel() != null)\r
+                                       // Parameter for model root. Values changed in FMU simulator\r
+                                       b.append("    parameter Real time = " + startTime + ";\n");\r
+                               else\r
+                                       // Continuous variable for module instances\r
+                                       b.append("    Real time;\n");\r
+\r
+                       }\r
+               }\r
+\r
+               if(!modules.isEmpty()) {\r
+                       b.append("// Module definitions\n");\r
+                       for(Module m : modules) {\r
+                               b.append(m.getDeclaration());\r
+                       }\r
+               }\r
+\r
+\r
+               // Input definitions\r
+               inputDefinitions(b, configuration, inputs, inputReferences);\r
+\r
+               boolean initialEquations = false;\r
+               for(Stock stock : stocks) {\r
+                       app = stock.getInitialEquation();\r
+                       if (app != null) {\r
+                               if(initialEquations == false) {\r
+                                       initialEquations = true;\r
+                                       b.append("// Initial Equations\n");\r
+                                       b.append("initial equation\n");\r
+                               }\r
+                               b.append(app);\r
+                       }\r
+               }\r
+\r
+               boolean equation = false;\r
+               b.append("// Equations\n");\r
+               for(IndependentVariable variable : variables) {\r
+                       app = variable.getEquation();\r
+                       if (app != null) {\r
+                               if(!equation) {\r
+                                       b.append("equation\n");\r
+                                       equation = true;\r
+                               }\r
+\r
+                               b.append(app);\r
+                       }\r
+               }\r
+\r
+               // If "equation" has not been added but there are still equations to be defined, add "equation"\r
+               if(!equation && (!inputReferences.isEmpty() || !outputDependencies.isEmpty() ||\r
+                               !moduleInputs.isEmpty() || !modules.isEmpty()))\r
+                       b.append("equation\n");\r
+\r
+               // Continuous input references\r
+               continuousInputReferences(b, inputReferences);\r
+\r
+               b.append("// Outputs\n");\r
+               for(Dependency dependency : outputDependencies) {\r
+                       Variable variable = (Variable)dependency.getTail();\r
+                       Module module = (Module)dependency.getHead();\r
+                       Input reference = (Input)dependency.refersTo();\r
+                       if(reference != null && reference.getName() != null && (reference.getVariability() == null || reference.getVariability().isEmpty())) {\r
+                               b.append("    " + module.getName() + "." + reference.getModelicaName() + " = " + variable.getModelicaName() + ";\n");\r
+                               moduleInputs.get(module.getName()).remove(reference);\r
+                       }\r
+               }\r
+\r
+               b.append("// Default values for inputs in modules\n");\r
+               for(String moduleLabel : moduleInputs.keySet()) {\r
+                       for(Input input : moduleInputs.get(moduleLabel)) {\r
+                               if(input.getVariability() == null || input.getVariability().isEmpty())\r
+                                       b.append("    " + moduleLabel + "." + input.getModelicaName() + " = " + input.getDefaultInputValue(moduleLabel) + ";\n");\r
+                       }\r
+               }\r
+\r
+               if(defTime) {\r
+                       if(configuration.isGameConfiguration() && !modules.isEmpty()) {\r
+                               b.append("// Time values for module\n");\r
+                               for(Module m : modules) {\r
+                                       b.append("    " + m.getName() + ".time = time;\n");\r
+                               }\r
+                       }\r
+               }\r
+\r
+               if(className != null)\r
+                       b.append("end ").append(className).append(";\n\n");\r
+\r
+       }\r
+\r
+       /**\r
+        * Define continuous input references\r
+        * @param b String builder\r
+        * @param inputReferences Input references\r
+        */\r
+       private static void continuousInputReferences(StringBuilder b, HashMap<Input, String> inputReferences) {\r
+               b.append("// Inputs\n");\r
+               for(Input i : inputReferences.keySet()) {\r
+                       if(i.getVariability() == null || i.getVariability().isEmpty()) {\r
+                               // Define only continuous variables here\r
+                               b.append("    " + i.getModelicaName() + " = " + inputReferences.get(i));\r
+                       }\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Setup input references for all inputs that are defined in child modules\r
+        * \r
+        * @param inputReferences Map containing the references\r
+        * @param inputDependencies List of input dependencies\r
+        */\r
+       private static void setupInputReferences(HashMap<Input, String> inputReferences, ArrayList<Dependency> inputDependencies) {\r
+               for(Dependency dependency : inputDependencies) {\r
+                       Input input = (Input)dependency.getHead();\r
+                       Module module = (Module)dependency.getTail();\r
+                       Variable reference = (Variable)dependency.refersTo();\r
+                       String expression;\r
+                       // If reference exists, use reference name. Otherwise, use default value.\r
+                       if(reference != null && reference.getName() != null)\r
+                               expression = module.getName() + "." + reference.getModelicaName() + ";\n";\r
+\r
+                       else\r
+                               expression = input.getDefaultInputValue() + ";\n";\r
+\r
+                       inputReferences.put(input, expression);\r
+               }\r
+       }\r
+\r
+       /**\r
+        *  Build input definitions\r
+        * \r
+        * @param b String builder\r
+        * @param configuration Module configuration\r
+        * @param inputs All inputs of this module\r
+        * @param inputReferences \r
+        */\r
+       private static void inputDefinitions(StringBuilder b, Configuration configuration, ArrayList<Input> inputs, HashMap<Input, String> inputReferences) {\r
+               if(inputs.isEmpty())\r
+                       return;\r
+\r
+               b.append("// Input definitions\n");\r
+               for(Input i : inputs) {\r
+                       if(i.getVariability() != null && !i.getVariability().isEmpty()) {\r
+                               // Input is NOT continuous\r
+                               if(inputReferences.containsKey(i)) {\r
+                                       // Input is defined in a child module\r
+                                       String declaration = i.getDeclaration();\r
+                                       declaration = declaration.substring(0, declaration.length() - 2); // remove ";\n" from the end\r
+                                       b.append(declaration + " = " + inputReferences.get(i));\r
+                               } else {\r
+                                       // Input is not defined in a child module, use default value\r
+                                       b.append(i.getDeclarationWithValue());\r
+                               }\r
+                       } else if(configuration.getModel() != null && !i.isHeadOfDependency()) {\r
+                               /*\r
+                                *  Input is in the top of the hierarchy, \r
+                                *  and it does not get value from anywhere else.\r
+                                *  => Declare it wit its default value \r
+                                */\r
+                               b.append(i.getDeclarationWithValue());\r
+                       } else {\r
+                               // Continuous => Parent module takes care of declaring a value for the input\r
+                               b.append(i.getDeclaration());\r
+                       }\r
+               }\r
+       }\r
+\r
+       public String escape(String name) {\r
+               return name.replace(' ', '_');\r
+       }\r
+       \r
+       public static final String DELAY_TIME = "delayTime";\r
+       public static final String DELAY_INITIAL = "initialValue";\r
+\r
+       private static String getDelayClass(int order) {\r
+               StringBuilder buffer = new StringBuilder();\r
+\r
+               buffer.append("class " + getDelayName(order) + "\n");\r
+\r
+               // variable block\r
+\r
+               // (possibly) continuous auxiliary variable\r
+               buffer.append("\tReal DL;\n");\r
+               // (possibly) continuous delay time\r
+               buffer.append("\tReal " + DELAY_TIME + ";\n");\r
+               // (possibly) continuous initial value\r
+               buffer.append("\tReal " + DELAY_INITIAL + ";\n");\r
+\r
+               // first valve\r
+               buffer.append("\tReal " + getDelayValve(0) + ";\n");\r
+\r
+               // stocks and valves, valves are delayed values of the variable\r
+               for (int i = 1; i <= order; i++) {\r
+                       buffer.append("\tReal LV"+i + "(fixed=false);\n");\r
+                       buffer.append("\tReal "+ getDelayValve(i) + ";\n");\r
+               }\r
+\r
+               // initial equation block\r
+               buffer.append("initial equation\n");\r
+\r
+               // Each stock gets the same initial value\r
+               for (int i = 1; i <= order; i++) {\r
+                       buffer.append("\tLV"+i + " = DL * " + DELAY_INITIAL + ";\n");\r
+               }\r
+\r
+               // equation block\r
+               buffer.append("equation\n");\r
+               \r
+               buffer.append("\tDL = " + DELAY_TIME + " / "+order+";\n");\r
+\r
+               // valves and stocks\r
+               for (int i = 1; i <= order; i++) {\r
+                       buffer.append("\tder(LV"+i + ") = - " + getDelayValve(i) + " + " + getDelayValve(i-1) + ";\n");\r
+                       buffer.append("\t"+ getDelayValve(i) + " = LV"+i + " / DL;\n");\r
+               }\r
+\r
+               buffer.append("end ");\r
+               buffer.append(getDelayName(order));\r
+               buffer.append(";\n");\r
+\r
+               return buffer.toString();\r
+       }\r
+\r
+       public static String getDelayName(int order) {\r
+               return "order_"+order+"_delay";\r
+       }\r
+       \r
+       public static String getDelayValve(int order) {\r
+               return "delay"+order;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/refactoring/TGRefactoring.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/refactoring/TGRefactoring.java
new file mode 100644 (file)
index 0000000..3e19f43
--- /dev/null
@@ -0,0 +1,91 @@
+package org.simantics.sysdyn.refactoring;\r
+\r
+import gnu.trove.set.hash.TIntHashSet;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.File;\r
+import java.io.FileReader;\r
+import java.io.IOException;\r
+import java.net.URLDecoder;\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.databoard.container.DataContainer;\r
+import org.simantics.databoard.container.DataContainers;\r
+import org.simantics.graph.query.Path;\r
+import org.simantics.graph.query.TransferableGraphConversion;\r
+import org.simantics.graph.query.UriUtils;\r
+import org.simantics.graph.refactoring.GraphRefactoringUtils;\r
+import org.simantics.graph.refactoring.MappingSpecification;\r
+import org.simantics.graph.refactoring.MappingSpecification.MappingRule;\r
+import org.simantics.graph.representation.TransferableGraph1;\r
+import org.simantics.graph.store.IdentityStore;\r
+\r
+public class TGRefactoring {\r
+    \r
+    public static void main(String[] args) throws Exception {\r
+        // Select the directory where this file is\r
+        File dir = new File(URLDecoder.decode(TGRefactoring.class.getResource(".").getPath(), "UTF-8")).getAbsoluteFile();\r
+        System.out.println(dir);\r
+        \r
+        // Choose input and output files for refactoring. Files are relative to the selected directory.\r
+        File input = new File(dir, "ServiceModel_2012-08-28b.tg"); // use your own file names\r
+        File mappingSpec = new File(dir, "mappingSpec.txt");\r
+        File output = new File(dir, "ServiceModel_2012-08-28b-refactored.tg");\r
+\r
+        // Get a map containing the changed names \r
+        \r
+        // Read input file \r
+        DataContainer dc = DataContainers.readFile(input);\r
+        \r
+        // Get transferable graph from the input file\r
+        TransferableGraph1 tg1 = (TransferableGraph1) dc.content.getValue(TransferableGraph1.BINDING);\r
+        \r
+        MappingSpecification spec = readMappingSpec(mappingSpec);\r
+        boolean fixed = GraphRefactoringUtils.fixIncorrectRoot(tg1.identities);\r
+        IdentityStore idStore = TransferableGraphConversion.extractIdentities(tg1);\r
+        TIntHashSet parentsAffected = new TIntHashSet(); \r
+        GraphRefactoringUtils.refactor(tg1, idStore, spec, parentsAffected);\r
+        tg1.resourceCount = idStore.getResourceCount();\r
+        tg1.identities = idStore.toArray();\r
+//        GraphRefactoringUtils.compactify(tg1, parentsAffected);\r
+        if(fixed)\r
+            GraphRefactoringUtils.unfixIncorrectRoot(tg1.identities);\r
+        \r
+        // Rewrite DataContainer content\r
+        dc.content = new Variant(TransferableGraph1.BINDING, tg1);\r
+        \r
+        // Write the refactored graph to output file\r
+        DataContainers.writeFile(output, dc);\r
+    }\r
+    \r
+    private static MappingSpecification readMappingSpec(File mappingSpec) throws IOException {\r
+        BufferedReader reader = new BufferedReader(new FileReader(mappingSpec));\r
+        ArrayList<MappingRule> rules = new ArrayList<MappingRule>();\r
+        while(true) {\r
+            String line = reader.readLine();\r
+            if(line == null)\r
+                break;\r
+            line = line.trim();\r
+            if(line.isEmpty())\r
+                continue;\r
+            String[] parts = line.trim().split(" ");\r
+            if(parts.length == 2) {\r
+                Path from = UriUtils.uriToPath(parts[0]);\r
+                Path to = UriUtils.uriToPath(parts[1]);\r
+                rules.add(new MappingRule(from, to));\r
+            } else {\r
+                if(line.trim().startsWith("//") || (line.trim().startsWith("/*") && line.trim().endsWith("/*"))) {\r
+                    // Comment \r
+                } else {\r
+                    reader.close();\r
+                    throw new IOException("Invalid mapping spec format. Every non-empty line should contain two URIs or comment");\r
+                }\r
+            }\r
+        }\r
+        reader.close();\r
+        \r
+        return new MappingSpecification(rules);\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/refactoring/mappingSpec.txt b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/refactoring/mappingSpec.txt
new file mode 100644 (file)
index 0000000..5183521
--- /dev/null
@@ -0,0 +1,38 @@
+\r
+// 4.9.2012 ontology changes\r
+http://www.simantics.org/Layer0-1.0 http://www.simantics.org/Layer0-1.1\r
+http://www.simantics.org/Layer0X-1.0 http://www.simantics.org/Layer0X-1.1\r
+http://www.simantics.org/G2D-1.0 http://www.simantics.org/G2D-1.1\r
+http://www.simantics.org/Structural-1.0 http://www.simantics.org/Structural-1.2\r
+http://www.simantics.org/Diagram-2.1 http://www.simantics.org/Diagram-2.2\r
+http://www.simantics.org/Simulation-1.0 http://www.simantics.org/Simulation-1.1\r
+http://www.simantics.org/Modeling-1.1 http://www.simantics.org/Modeling-1.2\r
+http://www.simantics.org/Project-1.1 http://www.simantics.org/Project-1.2\r
+http://www.simantics.org/Spreadsheet-1.1 http://www.simantics.org/Spreadsheet-1.2\r
+http://www.simantics.org/Viewpoint-1.1 http://www.simantics.org/Viewpoint-1.2\r
+http://www.simantics.org/Image2-1.1 http://www.simantics.org/Image2-1.2\r
+http://www.simantics.org/Color-1.0 http://www.simantics.org/Color-1.1\r
+http://www.simantics.org/Action-1.0 http://www.simantics.org/Action-1.1\r
+http://www.simantics.org/Silk-1.0 http://www.simantics.org/Silk-1.1\r
+http://www.simantics.org/Issue-1.1 http://www.simantics.org/Issue-1.2\r
+http://www.simantics.org/User-1.0 http://www.simantics.org/User-1.1\r
+http://www.simantics.org/Documentation-1.0 http://www.simantics.org/Documentation-1.1\r
+http://www.simantics.org/Document-1.1 http://www.simantics.org/Document-1.2\r
+http://www.simantics.org/SelectionView-1.1 http://www.simantics.org/SelectionView-1.2\r
+\r
+// Spreadsheet changes\r
+http://www.simantics.org/Spreadsheet-1.2/HasContent http://www.simantics.org/Spreadsheet-1.2/Cell/content\r
+http://www.simantics.org/Spreadsheet-1.2/FitRows http://www.simantics.org/Spreadsheet-1.2/Dimensions/fitRows\r
+http://www.simantics.org/Spreadsheet-1.2/FitColumns http://www.simantics.org/Spreadsheet-1.2/Dimensions/fitColumns\r
+http://www.simantics.org/Spreadsheet-1.2/ColumnCount http://www.simantics.org/Spreadsheet-1.2/Dimensions/columnCount\r
+http://www.simantics.org/Spreadsheet-1.2/ColumnLabels http://www.simantics.org/Spreadsheet-1.2/Headers/columnLabels\r
+http://www.simantics.org/Spreadsheet-1.2/RowCount http://www.simantics.org/Spreadsheet-1.2/Dimensions/rowCount\r
+http://www.simantics.org/Spreadsheet-1.2/ColumnWidths http://www.simantics.org/Spreadsheet-1.2/Headers/columnWidths\r
+\r
+http://www.simantics.org/Spreadsheet-1.2/ContentOf http://www.simantics.org/Spreadsheet-1.2/Cell/content/Inverse    \r
+http://www.simantics.org/Spreadsheet-1.2/FitRowsOf http://www.simantics.org/Spreadsheet-1.2/Dimensions/fitRows/Inverse\r
+http://www.simantics.org/Spreadsheet-1.2/FitColumnsOf http://www.simantics.org/Spreadsheet-1.2/Dimensions/fitColumns/Inverse\r
+http://www.simantics.org/Spreadsheet-1.2/ColumnCountOf http://www.simantics.org/Spreadsheet-1.2/Dimensions/columnCount/Inverse\r
+http://www.simantics.org/Spreadsheet-1.2/ColumnLabelsOf http://www.simantics.org/Spreadsheet-1.2/Headers/columnLabels/Inverse\r
+http://www.simantics.org/Spreadsheet-1.2/RowCountOf http://www.simantics.org/Spreadsheet-1.2/Dimensions/rowCount/Inverse\r
+http://www.simantics.org/Spreadsheet-1.2/ColumnWidthsOf http://www.simantics.org/Spreadsheet-1.2/Headers/columnWidths/Inverse
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Auxiliary.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Auxiliary.java
new file mode 100644 (file)
index 0000000..bf68a9d
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SysdynResource.URIs.Auxiliary)\r
+public class Auxiliary extends IndependentVariable {\r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Book.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Book.java
new file mode 100644 (file)
index 0000000..da0feb3
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SpreadsheetResource.URIs.Book)\r
+public class Book extends Variable {\r
+    \r
+    @RelatedElements(\r
+            value = Layer0.URIs.ConsistsOf,\r
+            composition = true)\r
+            private ArrayList<Sheet> sheets = new ArrayList<Sheet>();\r
+\r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);                \r
+    }\r
+    \r
+    public List<Sheet> getSheets() {\r
+        return sheets;\r
+    }\r
+    \r
+    public String markBook() {\r
+        return "BOOK " + this.getName();\r
+    }\r
+    \r
+    public String getBook() {\r
+        StringBuilder book = new StringBuilder();\r
+        \r
+//        book.append("partial class SpreadSheetBook\n");\r
+        \r
+        for(Sheet sheet : sheets) \r
+            book.append(sheet.getStringRepresentation());\r
+        \r
+//        book.append("end SpreadSheetBook;");\r
+        \r
+        return book.toString();\r
+        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Cloud.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Cloud.java
new file mode 100644 (file)
index 0000000..1244dcf
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SysdynResource.URIs.Cloud)\r
+public class Cloud implements IElement {\r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Configuration.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Configuration.java
new file mode 100644 (file)
index 0000000..e5d8d05
--- /dev/null
@@ -0,0 +1,98 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Representation of a model or module configuration \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.Configuration)\r
+public class Configuration {\r
+    \r
+    @RelatedValue(Layer0.URIs.HasName)\r
+    private String name;\r
+\r
+    @RelatedValue(Layer0.URIs.HasLabel)\r
+    private String label;\r
+    \r
+    /**\r
+     * Not null if configuration of a module\r
+     */\r
+    @RelatedElement(StructuralResource2.URIs.Defines)\r
+    private ModuleType moduleType;\r
+\r
+    /**\r
+     * Not null if is configuration of a model\r
+     */\r
+    @RelatedElement(SimulationResource.URIs.IsConfigurationOf)\r
+    private Model model;\r
+    \r
+    @RelatedElements(\r
+            value = Layer0.URIs.ConsistsOf,\r
+            composition = true)\r
+            private ArrayList<IElement> elements = new ArrayList<IElement>();\r
+\r
+    private boolean isGameConfiguration = false;\r
+    \r
+    public void setIsGameConfiguration(boolean isGame) {\r
+        this.isGameConfiguration = isGame;\r
+    }\r
+    \r
+    public boolean isGameConfiguration() {\r
+        return this.isGameConfiguration;\r
+    }\r
+\r
+    /**\r
+     * Get all elements of this configuration. Also all sheets from books are included.\r
+     * @return\r
+     */\r
+    public ArrayList<IElement> getElements() {\r
+        ArrayList<IElement> elements = new ArrayList<IElement>();\r
+        elements.addAll(this.elements);\r
+        for(IElement e : this.elements) {\r
+            if(e instanceof Book) {\r
+                elements.addAll(((Book)e).getSheets());\r
+            }\r
+        }\r
+        return elements;\r
+    }\r
+\r
+    public String getName() {\r
+        return name;\r
+    }\r
+\r
+    public String getLabel() {\r
+        return label != null ? label : name;\r
+    }\r
+    \r
+    public ModuleType getModuleType() {\r
+       return moduleType;\r
+    }\r
+    \r
+    public Model getModel() {\r
+        return model;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Dependency.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Dependency.java
new file mode 100644 (file)
index 0000000..f41c201
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SysdynResource.URIs.Dependency)\r
+public class Dependency implements IElement {\r
+    @RelatedElement(SysdynResource.URIs.Variable_HasTail)\r
+    private IElement tail;\r
+    @RelatedElement(SysdynResource.URIs.Variable_HasHead)\r
+    private IElement head;\r
+    @RelatedElement(SysdynResource.URIs.Dependency_refersTo)\r
+    private IElement refersTo;\r
+    \r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);        \r
+    }\r
+    \r
+    public IElement getTail() {\r
+        return this.tail;\r
+    }\r
+    \r
+    public IElement getHead() {\r
+        return this.head;\r
+    }\r
+    \r
+    public IElement refersTo() {\r
+        return this.refersTo;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/DiagramContainerDummy.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/DiagramContainerDummy.java
new file mode 100644 (file)
index 0000000..3ad1464
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(DiagramResource.URIs.DiagramContainer)\r
+public class DiagramContainerDummy implements IElement {\r
+    \r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);        \r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Entity.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Entity.java
new file mode 100644 (file)
index 0000000..ec61ed0
--- /dev/null
@@ -0,0 +1,30 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+/**\r
+ * Dummy class representing any entity.\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@GraphType(Layer0.URIs.Entity)\r
+public class Entity implements IElement {\r
+\r
+       @Override\r
+       public void accept(IElementVisitorVoid v) {\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Enumeration.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Enumeration.java
new file mode 100644 (file)
index 0000000..c87889c
--- /dev/null
@@ -0,0 +1,112 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.objmap.annotations.RelatedListElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SysdynResource.URIs.Enumeration)\r
+public class Enumeration extends Variable {\r
+       \r
+    @RelatedListElements(SysdynResource.URIs.Enumeration_enumerationIndexList)\r
+    private ArrayList<EnumerationIndex> enumerationIndexes = new ArrayList<EnumerationIndex>();\r
+    \r
+    @RelatedValue(SysdynResource.URIs.Enumeration_isReplaceable)\r
+    private Boolean isReplaceable;\r
+    \r
+    @RelatedElements(\r
+            value = SysdynResource.URIs.Redeclaration_replacedEnumeration_Inverse,\r
+            composition = true)\r
+            private ArrayList<Redeclaration> redeclarations = new ArrayList<Redeclaration>();\r
+\r
+       @Override\r
+       public void accept(IElementVisitorVoid v) {\r
+               v.visit(this);  \r
+       }\r
+       \r
+       public String getDeclaration() {\r
+               StringBuilder sb = new StringBuilder();\r
+               sb.append(getEnumerationClassDefinition());\r
+               sb.append("    ");\r
+               sb.append(getModelicaName() + "_class");\r
+               sb.append(" " + getModelicaName());\r
+               sb.append(";\n");\r
+               \r
+               sb.append("    parameter Integer " + getModelicaName() + "_size = " + getModelicaName() + ".size;\n");\r
+               sb.append("    parameter Integer " + getModelicaName() + "_elements[:] = " + getModelicaName() + ".elements;\n");\r
+               return sb.toString();\r
+       }\r
+       \r
+       public ArrayList<EnumerationIndex> getEnumerationIndexes() {\r
+       return enumerationIndexes;\r
+       }\r
+       \r
+       public boolean isReplaceable() {\r
+               return Boolean.TRUE.equals(isReplaceable);\r
+       }\r
+       \r
+       public String getEnumerationClassDefinition() {\r
+               \r
+               // Build indexes (one = 1, two = 2, etc..) and elements {1,2,3,..,size}\r
+               ArrayList<EnumerationIndex> indexes = getEnumerationIndexes();\r
+               StringBuilder elementsBuilder = new StringBuilder();\r
+               elementsBuilder.append("{");\r
+               StringBuilder indexesBuilder = new StringBuilder();\r
+               for(int i = 1; i <= indexes.size(); i++) {\r
+                       indexesBuilder.append("        constant Integer ");\r
+                       indexesBuilder.append(indexes.get(i - 1).getModelicaName());\r
+                       indexesBuilder.append(" = " + i + ";\n");\r
+                       \r
+                       elementsBuilder.append(i);\r
+                       if(i < indexes.size())\r
+                               elementsBuilder.append(",");\r
+               }\r
+               elementsBuilder.append("}");\r
+               \r
+               /*\r
+                * class E_class\r
+                *     extends Enumeration_class(size = n, elements = {1,2,3,..n});\r
+                *     constant Integer index1 = 1;\r
+                *     constant Integer index2 = 2;\r
+                *     ....\r
+                *     constant Integer indexn = n;\r
+                * end E_class;\r
+                */\r
+               \r
+               StringBuilder sb = new StringBuilder();\r
+               sb.append("    class ");\r
+               sb.append(getModelicaName());\r
+               sb.append("_class\n");\r
+               sb.append("        extends Enumeration_class(size=");\r
+               sb.append(indexes.size());\r
+               sb.append(", elements=");\r
+               sb.append(elementsBuilder);\r
+               sb.append(");\n");\r
+               sb.append(indexesBuilder);\r
+               sb.append("    end ");\r
+               sb.append(getModelicaName());\r
+               sb.append("_class;\n");\r
+               \r
+               return sb.toString();\r
+       }\r
+       \r
+       public ArrayList<Redeclaration> getRedeclarations() {\r
+               return redeclarations;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/EnumerationIndex.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/EnumerationIndex.java
new file mode 100644 (file)
index 0000000..7e7e836
--- /dev/null
@@ -0,0 +1,29 @@
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+@GraphType(SysdynResource.URIs.EnumerationIndex)\r
+public class EnumerationIndex {\r
+\r
+    @RelatedValue(Layer0.URIs.HasName)\r
+    protected String name;\r
+    \r
+    public String getName() {\r
+        return this.name;\r
+    }\r
+    \r
+    /**\r
+     * Get Modelica compliant name\r
+     * @return The name of this variable with spaces (' ') replaced with \r
+     * underscore characters ('_')\r
+     */\r
+    public String getModelicaName() {\r
+       if (this.name == null)\r
+               return null;\r
+        return this.name.replace(' ', '_');\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Flow.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Flow.java
new file mode 100644 (file)
index 0000000..43a31d0
--- /dev/null
@@ -0,0 +1,38 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SysdynResource.URIs.Flow)\r
+public class Flow implements IElement {\r
+    @RelatedElement(SysdynResource.URIs.Variable_HasTail)\r
+    private IElement tail;\r
+    @RelatedElement(SysdynResource.URIs.Variable_HasHead)\r
+    private IElement head;\r
+    \r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);        \r
+    }\r
+    \r
+    public IElement getTail() {\r
+        return this.tail;\r
+    }\r
+    \r
+    public IElement getHead() {\r
+        return this.head;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Function.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Function.java
new file mode 100644 (file)
index 0000000..7210ddc
--- /dev/null
@@ -0,0 +1,82 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.objmap.annotations.UpdateMethod;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Representation of a function\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.SysdynModelicaFunction)\r
+public class Function {\r
+\r
+    @RelatedValue(Layer0.URIs.HasName)\r
+    private String name;\r
+\r
+    @RelatedValue(SysdynResource.URIs.SysdynModelicaFunction_modelicaFunctionCode)\r
+    private String code;\r
+\r
+    private boolean hasTimeReference = false;\r
+\r
+    public String getCode() {\r
+        return \r
+                "function " + name + "\n" +\r
+                code +\r
+                "end " + name + ";\n";\r
+    }\r
+\r
+    public String getName() {\r
+        return name;\r
+    }\r
+\r
+    /**\r
+     * Keep track if the function contains references to time. If there is a reference to time, \r
+     * the variables calling this function cannot be parameters or constants.\r
+     * \r
+     * @param g ReadGraph\r
+     * @param r Function resource\r
+     * @return\r
+     * @throws DatabaseException\r
+     */\r
+    @UpdateMethod\r
+    public boolean update(ReadGraph g, Resource r) throws DatabaseException {\r
+        hasTimeReference = false;\r
+\r
+        String code = g.getPossibleRelatedValue(r, SysdynResource.getInstance(g).SysdynModelicaFunction_modelicaFunctionCode);\r
+        if(code == null)\r
+               return true;\r
+        \r
+        String[] elements = code.split("[\\+\\-\\*\\/\\(\\)\\[\\]\\{\\}=;\\s]");\r
+        for(String element : elements) {\r
+            if("time".equals(element)) {\r
+                hasTimeReference = true;\r
+                break;\r
+            }\r
+        }\r
+        return true;\r
+    }\r
+\r
+    public boolean hasTimeReference() {\r
+        return hasTimeReference;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/FunctionLibrary.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/FunctionLibrary.java
new file mode 100644 (file)
index 0000000..5300a34
--- /dev/null
@@ -0,0 +1,78 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+/**\r
+ * Representation of a function library\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.SysdynModelicaFunctionLibrary)\r
+public class FunctionLibrary {\r
+    \r
+    @RelatedValue(Layer0.URIs.HasName)\r
+    private String name;\r
+\r
+    @RelatedElements(\r
+            value = Layer0.URIs.ConsistsOf,\r
+            composition = true)\r
+    private ArrayList<Object> elements = new ArrayList<Object>();\r
+\r
+    /**\r
+     * Get all functions inside this library. (sub-libraries excluded)\r
+     * @return\r
+     */\r
+    public ArrayList<Function> getFunctions() {\r
+        ArrayList<Function> functions = new ArrayList<Function>();\r
+        if(elements != null) {\r
+            for(Object element : elements) {\r
+                if(element instanceof Function)\r
+                    functions.add((Function)element);\r
+            }\r
+        }\r
+        return functions;\r
+    }\r
+    \r
+    /**\r
+     * Get all function libraries included in this library\r
+     * @return All function libraries included in this library\r
+     */\r
+    public ArrayList<FunctionLibrary> getLibraries() {\r
+        ArrayList<FunctionLibrary> libraries = new ArrayList<FunctionLibrary>();\r
+        if(elements != null) {\r
+            for(Object element : elements) {\r
+                if(element instanceof FunctionLibrary)\r
+                    libraries.add((FunctionLibrary)element);\r
+            }\r
+        }\r
+        return libraries;\r
+    }\r
+    \r
+    /**\r
+     * Get the name of this library\r
+     * @return The name of this library\r
+     */\r
+    public String getName() {\r
+        return name;\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/IElement.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/IElement.java
new file mode 100644 (file)
index 0000000..a44aafa
--- /dev/null
@@ -0,0 +1,18 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+public interface IElement {\r
+    void accept(IElementVisitorVoid v);\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/IndependentVariable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/IndependentVariable.java
new file mode 100644 (file)
index 0000000..4245299
--- /dev/null
@@ -0,0 +1,214 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Iterator;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.expressions.IExpression;\r
+import org.simantics.sysdyn.representation.expressions.ParameterExpression;\r
+import org.simantics.sysdyn.representation.expressions.StockExpression;\r
+import org.simantics.sysdyn.representation.utils.FormatUtils;\r
+\r
+/**\r
+ * Representation of an independent variable\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public abstract class IndependentVariable extends Variable {\r
+       \r
+    @RelatedElements(\r
+            value = SysdynResource.URIs.Variable_isHeadOf,\r
+            composition = true)\r
+            private ArrayList<IElement> isHeadOf = new ArrayList<IElement>();\r
+\r
+    /**\r
+     * Get the declaration of this variable\r
+     * @return Declaration of this variable\r
+     */\r
+    public String getDeclaration() {\r
+        Variability variability = Variability.getVariability(this);\r
+\r
+        // [variability] type name[range]\r
+        StringBuilder sb = new StringBuilder();\r
+        sb.append("    ");\r
+        sb.append(variability.getText().isEmpty() ? "" : variability.getText() + " ");\r
+        sb.append(getType() + " ");\r
+        sb.append(getModelicaName());\r
+        sb.append(getRange());\r
+\r
+        // [= expression]\r
+        if(variability == Variability.PARAMETER || variability == Variability.CONSTANT) {\r
+            // parameters and constants are guaranteed to have only one expression\r
+               String expression = getExpressions().get(0).getExpression();\r
+               expression = FormatUtils.replaceWhitespace(expression);\r
+            String equation = FormatUtils.formatExpressionForModelica(this, expression);\r
+            sb.append(" = " + equation);\r
+        }\r
+\r
+        // ;\n\r
+        sb.append(";\n");\r
+        \r
+        // Possible additions to expressions. e.g. helper classes and variables\r
+        if(getExpressions() != null) {\r
+            for(IExpression e : getExpressions()) {\r
+                String addition = e.getDeclarationAddition();\r
+                if(addition != null)\r
+                    sb.append(addition);\r
+            }\r
+        }\r
+        \r
+        return sb.toString();\r
+    }\r
+\r
+       /**\r
+     * Get the range of this variable, if it is an array variable. \r
+     * <p>\r
+     * Format: [EnumerationName.size (, Enumeration2Name.size)*] \r
+     * @return Range of this variable, if it is an array variable. Empty string otherwise.\r
+     */\r
+    public String getRange() {\r
+        ArrayList<Enumeration> enumerations = getArrayIndexes();\r
+        String range = "";\r
+        if(enumerations != null && enumerations.size() > 0) {\r
+            StringBuilder sb = new StringBuilder();\r
+            sb.append("[");\r
+            Iterator<Enumeration> iterator = enumerations.iterator();\r
+            while(iterator.hasNext()) {\r
+                sb.append(iterator.next().getModelicaName() + ".size");\r
+                if(iterator.hasNext()) {\r
+                    sb.append(", ");\r
+                }\r
+            }\r
+            sb.append("]");\r
+            range = sb.toString();\r
+        }\r
+        return range;\r
+    }\r
+\r
+    /**\r
+     * Get all initial equations or null, if there are no initial equations.\r
+     * @return Initial equations as string or null.\r
+     */\r
+    public String getInitialEquation() {\r
+        StringBuilder sb = new StringBuilder();                \r
+\r
+        for(IExpression expression : getExpressions()) {\r
+            String initialEquation = expression.getInitialEquation();\r
+            if(initialEquation != null)\r
+                sb.append(initialEquation);\r
+        }\r
+        \r
+        String result = sb.toString();\r
+        return result.length() > 0 ? result : null;\r
+    }\r
+\r
+    /**\r
+     * Get the equation of this variable for equation block. Null is returned if this variable is not continuous.\r
+     * @return Equation or null\r
+     */\r
+    public String getEquation() {\r
+        if(Variability.getVariability(this) == Variability.CONTINUOUS) {\r
+            return getVariableEquation();\r
+        } else {\r
+            return null;\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Combines all possible equations for this variable. Array variables can have multiple equations.\r
+     * @return equations or null\r
+     */\r
+    protected String getVariableEquation() {\r
+        if(this.expressions == null || this.expressions.isEmpty())\r
+            return null;\r
+        \r
+        ArrayList<IExpression> expressions = getExpressions();\r
+        ArrayList<Enumeration> enumerations = getArrayIndexes();\r
+        IExpression firstExpression = expressions.get(0);\r
+        if(enumerations == null || enumerations.size() < 1) {\r
+            if(firstExpression == null)\r
+                return null;\r
+            else\r
+                return firstExpression.getEquation();\r
+        } else {\r
+            // ARRAY variable. Create all equations for the variable\r
+            StringBuilder sb = new StringBuilder();         \r
+            for(IExpression expression : expressions) {\r
+                sb.append(expression.getEquation());\r
+            }\r
+            return sb.toString();\r
+        }\r
+    }\r
+    \r
+    public ArrayList<IElement> getIncomingDependencies() {\r
+       return isHeadOf;\r
+    }\r
+    \r
+    @Override\r
+    public String getDocumentationDefinition(ReadGraph graph) throws DatabaseException {\r
+        String declaration = getDeclaration();\r
+        String initialEquation = getInitialEquation();\r
+        \r
+        StringBuilder result = new StringBuilder();\r
+        \r
+        if(declaration != null && declaration.length() > 0 && declaration.contains("=")) {\r
+        result.append("<p>");\r
+        if(getExpressions().size() > 1)\r
+            result.append(formatForHTML(declaration));\r
+        if(this instanceof Stock)\r
+            result.append(formatForHTML(declaration.substring(declaration.indexOf("(") + 1, declaration.lastIndexOf(")"))));\r
+        else\r
+            result.append(formatForHTML(declaration.substring(declaration.indexOf("=") + 1)));\r
+        result.append("</p>");\r
+        }\r
+        \r
+        result.append("<p>");\r
+        for(IExpression exp : getExpressions()) {\r
+            String expression = exp.getDocumentationExpression(graph);\r
+            if(!(exp instanceof StockExpression))\r
+                expression = expression.substring(expression.indexOf("=") + 1);\r
+            if(!(exp instanceof ParameterExpression))\r
+                result.append(formatForHTML(expression));\r
+        }\r
+        result.append("</p>");\r
+        \r
+        if(initialEquation != null && initialEquation.length() > 0) {\r
+            result.append("<p><b>Initial value:</b></p><p>");\r
+            if(getExpressions().size() > 1)\r
+                result.append(formatForHTML(initialEquation));\r
+            else\r
+                result.append(formatForHTML(initialEquation.substring(initialEquation.indexOf("=") + 1)));\r
+            result.append("</p>");\r
+        }\r
+        \r
+        result.append(super.getDocumentationDefinition(graph));\r
+        \r
+        return result.toString();\r
+    }\r
+    \r
+    private String formatForHTML(String text) {\r
+        text= text.trim();\r
+        text = text.replaceAll("\\r\\n|\\r|\\n", "<br/>");\r
+        if(text.endsWith(";"))\r
+            text = text.substring(0, text.length() - 1);\r
+        text = text.replace("/* Actual value read from init file */", "");\r
+        return text;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Input.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Input.java
new file mode 100644 (file)
index 0000000..fe89920
--- /dev/null
@@ -0,0 +1,142 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+/**\r
+ * Representation of an input variable \r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.Input)\r
+public class Input extends Variable {\r
+\r
+    @RelatedValue(SysdynResource.URIs.Input_defaultInputValue)\r
+    private Double defaultInputValue;\r
+    @RelatedElements(SysdynResource.URIs.Variable_isHeadOf)\r
+    private List<IElement> isHeadOf;\r
+    \r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);\r
+    }\r
+\r
+    /**\r
+     * Get the default value for this input. Default values may be set in either \r
+     * inside input's own module or in its parent module. If the value is set in a \r
+     * parent module, give input module's instance name as inModule.\r
+     * \r
+     * @param inModule The name of the instance in which this variable is. \r
+     * Can be null, if default value is set inside the variable's own module.\r
+     * @return Default input value.\r
+     */\r
+    public String getDefaultInputValue(String inModule) {\r
+        if( getArrayIndexes() == null || getArrayIndexes().isEmpty()) {\r
+            return defaultInputValue.toString();\r
+        } else {\r
+            StringBuilder sb = new StringBuilder();\r
+            sb.append("fill(");\r
+            sb.append(defaultInputValue);\r
+            sb.append(", ");\r
+            Iterator<Enumeration> i = getArrayIndexes().iterator();\r
+            while(i.hasNext()) {\r
+                Enumeration e = i.next();\r
+                sb.append((inModule != null && !inModule.isEmpty() ? inModule + "." : "") + e.getModelicaName() + ".size");\r
+                if(i.hasNext())\r
+                    sb.append(", ");\r
+            }\r
+            sb.append(")");\r
+            return sb.toString();\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Get the default value for this input inside it's own module.\r
+     * @return Default value\r
+     */\r
+    public String getDefaultInputValue() {\r
+        return getDefaultInputValue(null);\r
+    }\r
+\r
+    /**\r
+     * Is there a connection to this input variable from a module. (i.e. does this input variable possibly get its value from a child module)\r
+     * @return\r
+     */\r
+    public boolean isHeadOfDependency() {\r
+        return !isHeadOf.isEmpty();\r
+    }\r
+    \r
+    /**\r
+     * Get the declaration of this input variable with its default value\r
+     * @return declaration of this input variable with its default value\r
+     */\r
+    public String getDeclarationWithValue() {\r
+        String declaration = getDeclaration();\r
+        declaration = declaration.substring(0, declaration.length() - 2); // remove ";\n"\r
+        declaration += " = " + getDefaultInputValue() + ";\n";\r
+        return declaration;\r
+    }\r
+    \r
+    /**\r
+     * Get the declaration of this input variable without a default value\r
+     * @return declaration of this input variable without a default value\r
+     */\r
+    public String getDeclaration() {\r
+       ArrayList<Enumeration> enumerations = getArrayIndexes();\r
+       String range = "";\r
+       if(enumerations != null && enumerations.size() > 0) {\r
+               StringBuilder sb = new StringBuilder();\r
+               sb.append("[");\r
+               Iterator<Enumeration> iterator = enumerations.iterator();\r
+               while(iterator.hasNext()) {\r
+                       sb.append(iterator.next().getModelicaName() + ".size");\r
+                       if(iterator.hasNext()) {\r
+                               sb.append(", ");\r
+                       }\r
+               }\r
+               sb.append("]");\r
+               range = sb.toString();\r
+       }\r
+       \r
+       boolean continuous = variability == null || variability.isEmpty();\r
+        return "    " + (continuous ? "" : variability + " ") + getType() + " " + getModelicaName() + range + ";\n";\r
+    }\r
+    \r
+    @Override\r
+    public String getDocumentationDefinition(ReadGraph graph) throws DatabaseException {\r
+        String expression = getDefaultInputValue() + "   // Default value";\r
+\r
+        if(isHeadOf.size() > 0 && isHeadOf.get(0) instanceof Dependency) {\r
+            Dependency dependency = (Dependency) isHeadOf.get(0);\r
+            Module module = (Module)dependency.getTail();\r
+            Variable reference = (Variable)dependency.refersTo();\r
+            // If reference exists, use reference name. Otherwise, use default value.\r
+            if(reference != null && reference.getModelicaName() != null)\r
+                expression = "<b>Reference:</b><br/>" + module.getName() + "." + reference.getModelicaName() + ";\n";\r
+        }\r
+        \r
+        return expression + super.getDocumentationDefinition(graph);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/LibraryDummy.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/LibraryDummy.java
new file mode 100644 (file)
index 0000000..6abe502
--- /dev/null
@@ -0,0 +1,43 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+/**\r
+ * A dummy variable representing any possible library\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@GraphType(Layer0.URIs.Library)\r
+public class LibraryDummy implements IElement {\r
+    \r
+    @RelatedValue(Layer0.URIs.HasName)\r
+    private String name;\r
+       \r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);        \r
+    }\r
+    \r
+    /**\r
+     * Name of the library\r
+     * @return Name of the library\r
+     */\r
+    public String getName() {\r
+        return name;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/LoadRepresentation.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/LoadRepresentation.java
new file mode 100644 (file)
index 0000000..fd5aac5
--- /dev/null
@@ -0,0 +1,102 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.objmap.IMapping;\r
+import org.simantics.objmap.MappingException;\r
+import org.simantics.objmap.Mappings;\r
+import org.simantics.sysdyn.manager.SysdynConsole;\r
+\r
+public class LoadRepresentation {\r
+    \r
+    public static IMapping loadMappedMapping(Session session, final Resource configuration) throws DatabaseException {\r
+        return session.syncRequest(new Read<IMapping>() {\r
+\r
+            @Override\r
+            public IMapping perform(ReadGraph graph)\r
+                    throws DatabaseException {\r
+                SysdynSchema schema = new SysdynSchema(graph);\r
+                IMapping mapping = Mappings.createWithoutListening(schema);\r
+                \r
+                try {\r
+                    mapping.map(graph, configuration);\r
+                } catch (MappingException e) {\r
+                    SysdynConsole.INSTANCE.message(\r
+                            "Error: Mapping is broken! Find the problem, " +\r
+                            "fix it and restart the program." +\r
+                            "\nJava error message:\n" + \r
+                                    e.getMessage());\r
+                    throw e;\r
+                }\r
+                \r
+                return mapping;\r
+            }\r
+            \r
+        });\r
+    }\r
+\r
+    public static Configuration loadConfiguration(Session session, final Resource configuration) throws DatabaseException {\r
+        return session.syncRequest(new Read<Configuration>() {\r
+\r
+            @Override\r
+            public Configuration perform(ReadGraph graph)\r
+                    throws DatabaseException {\r
+                SysdynSchema schema = new SysdynSchema(graph);\r
+                IMapping mapping = Mappings.createWithoutListening(schema);\r
+                \r
+                try {\r
+                    return (Configuration)mapping.map(graph, configuration);                \r
+                } catch (MappingException e) {\r
+                    SysdynConsole.INSTANCE.message(\r
+                            "Error: Mapping is broken! Find the problem, " +\r
+                            "fix it and restart the program." +\r
+                            "\nJava error message:\n" + \r
+                                    e.getMessage());\r
+                    throw e;\r
+                }\r
+                \r
+            }\r
+            \r
+        });\r
+    }\r
+    \r
+    public static IElement loadElement(Session session, final Resource element) throws DatabaseException {\r
+        return session.syncRequest(new Read<IElement>() {\r
+\r
+            @Override\r
+            public IElement perform(ReadGraph graph)\r
+                    throws DatabaseException {\r
+                SysdynSchema schema = new SysdynSchema(graph);\r
+                IMapping mapping = Mappings.createWithoutListening(schema);\r
+                \r
+                try {\r
+                    return (IElement)mapping.map(graph, element);                \r
+                } catch (MappingException e) {\r
+                    SysdynConsole.INSTANCE.message(\r
+                            "Error: Mapping is broken! Find the problem, " +\r
+                            "fix it and restart the program." +\r
+                            "\nJava error message:\n" + \r
+                                    e.getMessage());\r
+                    throw e;\r
+                }\r
+                \r
+            }\r
+            \r
+        });\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Loop.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Loop.java
new file mode 100644 (file)
index 0000000..f81e535
--- /dev/null
@@ -0,0 +1,92 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedListElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+\r
+@GraphType(SysdynResource.URIs.Loop)\r
+public class Loop implements IElement {\r
+\r
+    @RelatedValue(Layer0.URIs.HasName)\r
+    protected String name;\r
+    \r
+    @RelatedElement(Layer0.URIs.PartOf)\r
+    protected Object parent;\r
+    \r
+    @RelatedValue(SysdynResource.URIs.LoopSymbol_Clockwise)\r
+    protected Boolean clockwise;\r
+    \r
+    @RelatedValue(SysdynResource.URIs.Loop_Comment)\r
+    protected String comment;\r
+    \r
+    @RelatedListElements(SysdynResource.URIs.Loop_Items)\r
+    protected ArrayList<Object> items = new ArrayList<Object>();\r
+    \r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);        \r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return The name of this loop\r
+     */\r
+    public String getName() {\r
+        return this.name;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return The comment of this loop\r
+     */\r
+    public String getComment() {\r
+        return this.comment;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return The variables and dependencies of this loop\r
+     */\r
+    public ArrayList<Object> getItems() {\r
+        return this.items;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return true iff loop rotates clockwise.\r
+     */\r
+    public boolean isClockwise() {\r
+       return this.clockwise;\r
+    }\r
+    \r
+    /**\r
+     *\r
+     * @return Parent configuration of this loop (or null if something is wrong)\r
+     */\r
+    public Configuration getParentConfiguration() {\r
+        if(parent instanceof Configuration) {\r
+            return (Configuration)parent;\r
+        } else {\r
+            return null;\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Model.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Model.java
new file mode 100644 (file)
index 0000000..76f28a4
--- /dev/null
@@ -0,0 +1,254 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.annotations.BuiltinFunctions;\r
+\r
+/**\r
+ * Representation of a system dynamics model\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.SysdynModel)\r
+public class Model {\r
+\r
+    @RelatedValue(SysdynResource.URIs.SysdynModel_startTime)\r
+    private final Double startTime = 0.0;\r
+\r
+    @RelatedValue(SysdynResource.URIs.SysdynModel_stopTime)\r
+    private final Double stopTime = 10.0;\r
+\r
+    @RelatedValue(SysdynResource.URIs.SysdynModel_outputInterval)\r
+    private Double outputInterval;\r
+    \r
+    @RelatedValue(SysdynResource.URIs.SysdynModel_simulationStepLength)\r
+    private Double stepLength;\r
+\r
+    @RelatedValue(SysdynResource.URIs.SysdynModel_tolerance)\r
+    private Double tolerance;\r
+\r
+    @RelatedValue(SysdynResource.URIs.SysdynModel_solver)\r
+    private String solver;\r
+    \r
+    @RelatedValue(SysdynResource.URIs.SysdynModel_variableFilter)\r
+    private String variableFilter;\r
+    \r
+    @RelatedElement(SimulationResource.URIs.HasConfiguration)\r
+    private Configuration configuration;\r
+    \r
+    @RelatedValue(SysdynResource.URIs.SysdynModel_timeUnit)\r
+    private String timeUnit;\r
+    \r
+    @RelatedElements(\r
+            value = Layer0.URIs.ConsistsOf,\r
+            composition = true)\r
+    private final ArrayList<Object> consistsOf = new ArrayList<Object>();\r
+    \r
+    @RelatedElements(\r
+            value = Layer0.URIs.IsLinkedTo,\r
+            composition = true)\r
+    private final ArrayList<Object> linkedTo = new ArrayList<Object>();\r
+    \r
+    \r
+    @BuiltinFunctions\r
+    private FunctionLibrary builtins;\r
+\r
+    /**\r
+     * \r
+     * @return Simulation start time\r
+     */\r
+    public Double getStartTime() {\r
+        return startTime;\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @return Simulation end time\r
+     */\r
+    public Double getStopTime() {\r
+        return stopTime;\r
+    }\r
+\r
+    /**\r
+     * Simulation output interval\r
+     * @return\r
+     */\r
+    public Double getOutputInterval() {\r
+        return outputInterval;\r
+    }\r
+\r
+    /**\r
+     * Simulation step length\r
+     * @return\r
+     */\r
+    public Double getSimulationStepLength() {\r
+       return stepLength;\r
+    }\r
+    /**\r
+     * \r
+     * @return Tolerance for simulation engine\r
+     */\r
+    public Double getTolerance() {\r
+        return tolerance;\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @return Solver name\r
+     */\r
+    public String getSolver() {\r
+        return solver;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return variableFilter or ".*" if null\r
+     */\r
+    public String getVariableFilter() {\r
+        if(variableFilter == null || variableFilter.isEmpty())\r
+            return ".*";\r
+        else\r
+            return variableFilter;\r
+    }\r
+\r
+    /**\r
+     * Get all functions that are linked to this model: built-in functions, model's own functions and shared function libraries\r
+     * @return all functions liked to this model\r
+     */\r
+    public HashMap<String, Function> getFunctions() {\r
+        HashMap<String, Function> functions = new HashMap<String, Function>();\r
+        if(consistsOf != null ) {\r
+            for(Object o : consistsOf) {\r
+                if(o instanceof Function) {\r
+                    Function f = (Function) o;\r
+                    functions.put(f.getName(), f);\r
+                } else if (o instanceof FunctionLibrary) {\r
+                    addFunctions("", (FunctionLibrary)o, functions);\r
+                }\r
+            }\r
+        }\r
+        \r
+        if(linkedTo != null) {\r
+            for(Object o : linkedTo) {\r
+                if(o instanceof SharedFunctionLibrary) {\r
+                    SharedFunctionLibrary fl = (SharedFunctionLibrary)o;\r
+                    addFunctions(fl.getName(), fl, functions);\r
+                }\r
+            }\r
+        }\r
+        \r
+        if(builtins != null)\r
+            addBuiltinFunctions(builtins, functions);\r
+        \r
+        return functions;\r
+    }\r
+    \r
+    /**\r
+     * Determine if this Model consists of a certain ModuleType.\r
+     * @param moduleType The name of the ModuleType that is sought \r
+     * @return true iff this consists of moduleType\r
+     */\r
+    public boolean containsModuleType(String moduleType) {\r
+        if(consistsOf != null ) {\r
+            for(Object o : consistsOf) {\r
+                if(o instanceof ModuleType) {\r
+                    ModuleType mt = (ModuleType)o;\r
+                    if (mt.getName().equals(moduleType)) \r
+                        return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    /**\r
+     * Determine if this Model consists of a certain Function or \r
+     * FunctionLibrary ON THE TOP LEVEL.\r
+     * @param elementName The name of the element that is sought \r
+     * @return true iff this consists of element\r
+     */\r
+    public boolean containsFunctionOrLibrary(String elementName) {\r
+        if(consistsOf != null ) {\r
+            for(Object o : consistsOf) {\r
+                if(o instanceof Function) {\r
+                    Function f = (Function)o;\r
+                    if (f.getName().equals(elementName)) \r
+                        return true;\r
+                }\r
+                else if(o instanceof FunctionLibrary) {\r
+                    FunctionLibrary fl = (FunctionLibrary)o;\r
+                    if (fl.getName().equals(elementName)) \r
+                        return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * Add built-in functions to functions map. Built-in functions do not have any library path.\r
+     * @param library Built-in function library\r
+     * @param functions Function map containing all functions\r
+     */\r
+    private void addBuiltinFunctions(FunctionLibrary library, HashMap<String, Function> functions) {\r
+        for(Function f : library.getFunctions())\r
+            functions.put(f.getName(), f);\r
+        for(FunctionLibrary fl : library.getLibraries())\r
+            addBuiltinFunctions(fl, functions);\r
+    }\r
+    \r
+    /**\r
+     * Add functions from a library to a library map\r
+     * @param path Path to the library\r
+     * @param library Function library\r
+     * @param functions Function map containing all functions\r
+     */\r
+    private void addFunctions(String path, FunctionLibrary library, HashMap<String, Function> functions) {\r
+        for(Function f : library.getFunctions())\r
+            functions.put(path + (path.isEmpty() ? "" : ".") + f.getName(), f);\r
+        for(FunctionLibrary fl : library.getLibraries())\r
+            addFunctions((path.isEmpty() ? "" : path + ".") + fl.getName(), fl, functions);\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return Built-in functions library\r
+     */\r
+    public FunctionLibrary getBuiltins() {\r
+        return builtins;\r
+    }\r
+    \r
+    \r
+    /**\r
+     * \r
+     * @return Configuration of this model\r
+     */\r
+    public Configuration getModelConfiguration() {\r
+       return configuration;\r
+    }\r
+    \r
+    \r
+    public String getTimeUnit() {\r
+        return timeUnit;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Module.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Module.java
new file mode 100644 (file)
index 0000000..3938f20
--- /dev/null
@@ -0,0 +1,352 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashSet;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * Representation of a module instance\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.Module)\r
+public class Module implements IElement {\r
+\r
+       @RelatedValue(Layer0.URIs.HasName)\r
+       private String name;\r
+\r
+       @RelatedElement(Layer0.URIs.PartOf)\r
+       private Configuration parentConfiguration;\r
+\r
+       @RelatedElement(Layer0.URIs.InstanceOf)\r
+       private ModuleType type;\r
+\r
+       @RelatedElements(SysdynResource.URIs.Module_redeclaration)\r
+       private List<Redeclaration> redeclarations;\r
+\r
+       @RelatedElements(Layer0.URIs.ConsistsOf)\r
+       private List<Entity> consistsOf;\r
+\r
+       @Override\r
+       public void accept(IElementVisitorVoid v) {\r
+               v.visit(this);\r
+       }\r
+\r
+       public String getName() {\r
+               return name;\r
+       }\r
+\r
+       public ModuleType getType() {\r
+               return type;\r
+       }\r
+\r
+       /**\r
+        * Returns the declaration of a module with possible redeclared enumerations and parameter assignments\r
+        *\r
+        * <p>\r
+        * Enumeration redeclaration:\r
+        * parameter Integer Enum__size = Enum.size; <br>\r
+        * parameter Integer Enum__elements[:] = Enum.elements; <br>\r
+        * ModuleType ModuleType1(Enum.size = Enum__size, Enum.elements = Enum__elements); <br>\r
+        * \r
+        * <p>\r
+        * Temporary parameter variables are needed to avoid name conflicts when redeclaring an \r
+        * enumeration with the same name.\r
+        * \r
+        * @return Declaration of a module instance\r
+        */\r
+       public String getDeclaration() {\r
+\r
+\r
+               String enumerationRedeclarations = getEnumerationRedeclarations();\r
+               Pair<String, String> inputRedeclarations = getInputRedeclarations();\r
+               String parameterOverrides = getParameterOverrideString();\r
+\r
+               StringBuilder redeclarations = new StringBuilder();\r
+\r
+               if(!enumerationRedeclarations.isEmpty() || !inputRedeclarations.first.isEmpty() || !parameterOverrides.isEmpty()) {\r
+                       redeclarations.append("(");\r
+                       redeclarations.append(enumerationRedeclarations);\r
+\r
+                       String ir = inputRedeclarations.first;\r
+                       if(enumerationRedeclarations.isEmpty() && !inputRedeclarations.first.isEmpty())\r
+                               // remove first ", " if no enumeration redeclarations\r
+                               ir = inputRedeclarations.first.substring(2); \r
+                       redeclarations.append(ir);\r
+\r
+                       if(!parameterOverrides.isEmpty()) {\r
+                               if(redeclarations.length() > 1)\r
+                                       redeclarations.append(", ");\r
+                               redeclarations.append(parameterOverrides);\r
+                       }\r
+\r
+                       redeclarations.append(")");\r
+               }\r
+\r
+               StringBuilder sb = new StringBuilder();\r
+\r
+               // Possible reference variables\r
+               if(inputRedeclarations.second != null && !inputRedeclarations.second.isEmpty()) {\r
+                       sb.append(inputRedeclarations.second);\r
+               }\r
+\r
+               sb.append("    ");\r
+               sb.append(getType().getName());\r
+               sb.append(" ");\r
+               sb.append(getName());\r
+               sb.append(redeclarations.toString()); // possible redeclarations\r
+               sb.append(";\n");\r
+               return sb.toString();\r
+       }\r
+\r
+       /**\r
+        * Get possible enumeration redeclarations.\r
+        * @return enumeration redeclarations or empty string\r
+        */\r
+       private String getEnumerationRedeclarations() {\r
+               StringBuilder redeclarations = new StringBuilder();\r
+               if(!getRedeclarations().isEmpty()) {\r
+\r
+                   boolean first = true;\r
+                       Iterator<Redeclaration> i = getRedeclarations().iterator();\r
+                       while(i.hasNext()) {\r
+                               Redeclaration rd = i.next();\r
+                               String redeclaration = rd.getRedeclaration();\r
+                               if(redeclaration != null && !redeclaration.isEmpty()) {\r
+                    if(!first) {\r
+                        redeclarations.append(",");\r
+                    } else {\r
+                        first = false;\r
+                    }\r
+                                   redeclarations.append(redeclaration);\r
+                               }\r
+                       }\r
+               }\r
+               return redeclarations.toString();\r
+       }\r
+\r
+       /**\r
+        * Get possible input redeclarations\r
+        * @return input redeclarations or empty string\r
+        */\r
+       private Pair<String, String> getInputRedeclarations() {\r
+               StringBuilder declarations = new StringBuilder();\r
+               StringBuilder references = new StringBuilder();\r
+\r
+               for(IElement element : parentConfiguration.getElements()) {\r
+                       if (element instanceof Dependency) {\r
+                               Dependency dependency = (Dependency)element;\r
+                               if(dependency.getHead().equals(this)){\r
+                                       Input reference = (Input)dependency.refersTo();\r
+                                       Variable outputVariable = (Variable)dependency.getTail();\r
+                                       if(outputVariable instanceof Shadow)\r
+                                           outputVariable = ((Shadow) outputVariable).getOriginal();\r
+                                       \r
+                                       String name = outputVariable.getModelicaName();\r
+\r
+                                       Module module = (Module)dependency.getHead();\r
+\r
+                                       if(reference != null && reference.getName() != null) {\r
+                                               if(reference.getVariability() == null || reference.getVariability().isEmpty())\r
+                                                       continue; // Only parameters and constants are redeclared\r
+\r
+                                                       for(IElement e : module.getType().getConfiguration().getElements()) {\r
+                                                               if(e instanceof Variable) {\r
+                                                                       Variable v = (Variable)e;\r
+\r
+                                                                       if(v.getName() != null && outputVariable.getName().equals(v.getName())) {\r
+                                                                               /*\r
+                                                                                *  The target module contains a variable with the same name. Need to\r
+                                                                                *  avoid Module(variable = variable) situations \r
+                                                                                */\r
+                                                                               String declaration;\r
+                                                                               if(outputVariable instanceof Input)\r
+                                                                                       declaration = ((Input)outputVariable).getDeclaration();\r
+                                                                               else\r
+                                                                                       declaration = ((IndependentVariable)outputVariable).getDeclaration();\r
+\r
+                                                                               if(declaration.contains("="))\r
+                                                                                       declaration = declaration.substring(0, declaration.indexOf("=") - 1); // Break to "="\r
+                                                                               else\r
+                                                                                       declaration = declaration.substring(0, declaration.length() - 2); // Remove ending ";\n" \r
+\r
+                                                                               name = outputVariable.getModelicaName() + "_reference";\r
+                                                                               declaration = declaration.replace(outputVariable.getModelicaName(), name);\r
+                                                                               declaration += " = " + outputVariable.getModelicaName() + " /* Reference value to avoid name conflicts in module instantiation */ ;\n";\r
+                                                                               references.append(declaration);\r
+                                                                               break;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+\r
+                                                       declarations.append(", " + reference.getModelicaName() + " = " + name);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               return new Pair<String, String>(declarations.toString(), references.toString());\r
+       }\r
+\r
+       public Configuration getParentConfiguration() {\r
+               return this.parentConfiguration;\r
+       }\r
+\r
+       /**\r
+        * Return the list of the defined redeclarations for this module instance.\r
+        * \r
+        * @return List of the defined redeclarations or an empty list if redeclarations have not been set \r
+        */\r
+       public List<Redeclaration> getRedeclarations() {\r
+               if(redeclarations == null) {\r
+                       redeclarations = new ArrayList<Redeclaration>();\r
+               }\r
+               return redeclarations;\r
+       }\r
+\r
+\r
+       /**\r
+        * Get all parameter override elements for this module instance as a string "param = value, param2 = value2, ..."\r
+        * @return parameter overrides\r
+        */\r
+       public String getParameterOverrideString() {\r
+           String result = "";\r
+\r
+           for(ParameterOverride po : getParameterOverrides()) {\r
+               IndependentVariable var = po.getVariable();\r
+               if(!Variability.CONTINUOUS.equals(Variability.getVariability(var, false, parentConfiguration))) {\r
+                   if(!result.isEmpty())\r
+                       result += ", ";\r
+\r
+                   result += po.getOverride();\r
+               }\r
+           }\r
+\r
+               return result;\r
+       }\r
+\r
+\r
+       /**\r
+        * Get all parameter overrides of this module instance\r
+        * @return\r
+        */\r
+       public Set<ParameterOverride> getParameterOverrides() {\r
+               HashSet<ParameterOverride> result = new HashSet<ParameterOverride>();\r
+               if(consistsOf != null) {\r
+                       for(Entity e : consistsOf) {\r
+                               if(e instanceof ParameterOverride) {\r
+                                       result.add( (ParameterOverride) e);\r
+                               }\r
+                       }\r
+               }\r
+               return result; \r
+       }\r
+\r
+\r
+       \r
+    public String getDocumentationDefinition() {\r
+        String enumerationRedeclarations = getEnumerationRedeclarations();\r
+        String parameterOverrides = getParameterOverrideString();\r
+        \r
+        StringBuilder result = new StringBuilder();\r
+        \r
+        String[] erecs = enumerationRedeclarations.split(",");\r
+        boolean first = true;\r
+        result.append("<p>");\r
+        for(String s : erecs) {\r
+            if(s.length() == 0)\r
+                continue;\r
+            \r
+            if(first) {\r
+                result.append("<b>Enumeration redeclarations:</b><br/>");\r
+            }\r
+            first = false;\r
+            result.append(s.trim());\r
+            result.append("<br/>");\r
+        }\r
+        result.append("</p>");\r
+\r
+        \r
+        \r
+        first = true;\r
+        result.append("<p>");\r
+\r
+        String[] poverrds = parameterOverrides.split(",");\r
+        for(String s : poverrds) {\r
+            if(s.length() == 0)\r
+                continue;\r
+\r
+            if(first) {\r
+                result.append("<b>Parameter overrides:</b><br/>");\r
+            }\r
+            first = false;\r
+            result.append(s.trim());\r
+            result.append("<br/>");\r
+        }\r
+        result.append("</p>");\r
+\r
+        ArrayList<Dependency> inputs = new ArrayList<Dependency>();\r
+        ArrayList<Dependency> outputs = new ArrayList<Dependency>();\r
+        for(IElement e : parentConfiguration.getElements()) {\r
+            if(e instanceof Dependency) {\r
+                Dependency d = (Dependency)e;\r
+                if(this.equals(d.getHead()) && d.refersTo() != null) {\r
+                    inputs.add(d);\r
+                } else if(this.equals(d.getTail()) && d.refersTo() != null) {\r
+                    outputs.add(d);\r
+                }\r
+            }\r
+        }\r
+        \r
+        first = true;\r
+        result.append("<p>");\r
+        for(Dependency d : inputs) {\r
+            if(first) {\r
+                result.append("<b>Inputs:</b><br/>");\r
+            }\r
+            first = false;\r
+            \r
+            result.append(getName() + "." + ((Variable)d.refersTo()).getModelicaName() + " = " + ((Variable)d.getTail()).getModelicaName());\r
+            result.append("<br/>");\r
+        }\r
+        result.append("</p>");\r
+        \r
+        first = true;\r
+        result.append("<p>");\r
+        for(Dependency d : outputs) {\r
+            if(first) {\r
+                result.append("<b>Outputs:</b><br/>");\r
+            }\r
+            first = false;\r
+            \r
+            result.append(((Variable)d.getHead()).getModelicaName() + " = " + getName() + "." + ((Variable)d.refersTo()).getModelicaName());\r
+            result.append("<br/>");\r
+        }\r
+        result.append("</p>");\r
+\r
+        \r
+        return result.toString();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/ModuleType.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/ModuleType.java
new file mode 100644 (file)
index 0000000..bf7b84a
--- /dev/null
@@ -0,0 +1,55 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+/**\r
+ * Representation of a module type\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@GraphType(StructuralResource2.URIs.ComponentType)\r
+public class ModuleType implements IElement {\r
+\r
+    @RelatedValue(Layer0.URIs.HasName)\r
+    private String name;\r
+    \r
+    @RelatedElement(StructuralResource2.URIs.IsDefinedBy)\r
+    private Object configuration;\r
+    \r
+    @RelatedElement(Layer0.URIs.PartOf)\r
+    protected Object parent;\r
+\r
+    public String getName() {\r
+       return name;\r
+    }\r
+\r
+    public Configuration getConfiguration() {\r
+        return configuration instanceof Configuration ? (Configuration)configuration : null;\r
+    }\r
+    \r
+       @Override\r
+       public void accept(IElementVisitorVoid v) {\r
+       }\r
+       \r
+       public Object getParent() {\r
+           return parent;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/ParameterOverride.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/ParameterOverride.java
new file mode 100644 (file)
index 0000000..713f7ee
--- /dev/null
@@ -0,0 +1,59 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+\r
+/**\r
+ * Representation of a parameter override\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.Module_ParameterOverride)\r
+public class ParameterOverride extends Entity {\r
+    \r
+    @RelatedElement(SysdynResource.URIs.Module_ParameterOverride_overriddenParameter)\r
+    private IndependentVariable variable;\r
+    \r
+    @RelatedValue(SysdynResource.URIs.Module_ParameterOverride_overrideExpression)\r
+    private String expression;\r
+    \r
+    /**\r
+     * Get the parameter variable to be overridden\r
+     * @return parameter variable to be overridden\r
+     */\r
+    public IndependentVariable getVariable() {\r
+        return variable;\r
+    }\r
+    \r
+    /**\r
+     * Get the overriding expression\r
+     * @return overriding expression\r
+     */\r
+    public String getExpression() {\r
+        return expression;\r
+    }\r
+    \r
+    /**\r
+     * Get the complete override equation: "variable = overridingExpression"\r
+     * @return override equation\r
+     */\r
+    public String getOverride() {\r
+        return variable.getModelicaName() + " = " + expression;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Redeclaration.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Redeclaration.java
new file mode 100644 (file)
index 0000000..0d2efc9
--- /dev/null
@@ -0,0 +1,54 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+@GraphType(SysdynResource.URIs.Redeclaration)\r
+public class Redeclaration {\r
+       \r
+    @RelatedElement(SysdynResource.URIs.Redeclaration_replacedEnumeration)\r
+    private Enumeration replacedEnumeration;\r
+    \r
+    @RelatedElement(SysdynResource.URIs.Redeclaration_replacingEnumeration)\r
+    private Enumeration replacingEnumeration;\r
+    \r
+    public String getRedeclaration() {\r
+       if(replacedEnumeration == null || replacingEnumeration == null) {\r
+               return "";\r
+       }\r
+       StringBuilder sb = new StringBuilder();\r
+       sb.append(replacedEnumeration.getModelicaName());\r
+       sb.append(".size = ");\r
+       sb.append(replacingEnumeration.getModelicaName());\r
+       sb.append("_size, ");\r
+       sb.append(replacedEnumeration.getModelicaName());\r
+       sb.append(".elements = ");\r
+       sb.append(replacingEnumeration.getModelicaName());\r
+       sb.append("_elements");\r
+       \r
+       return sb.toString();\r
+    }\r
+\r
+       public Enumeration getReplacedEnumeration() {\r
+               return replacedEnumeration;\r
+       }\r
+\r
+       public Enumeration getReplacingEnumeration() {\r
+               return replacingEnumeration;\r
+       }\r
+    \r
+    \r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Shadow.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Shadow.java
new file mode 100644 (file)
index 0000000..3842234
--- /dev/null
@@ -0,0 +1,102 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.expressions.IExpression;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SysdynResource.URIs.Shadow)\r
+public class Shadow extends Variable {\r
+\r
+    @RelatedElement(SysdynResource.URIs.Shadow_original)\r
+    private Variable original;\r
+\r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        if(getOriginal() != null)\r
+            original.accept(v);\r
+    }\r
+\r
+    public Variable getOriginal() {\r
+        return original;\r
+    }\r
+\r
+    @Override\r
+    public String getName() {\r
+        if(getOriginal() != null)\r
+            return getOriginal().getName();\r
+        else\r
+            return super.getName();\r
+    }\r
+\r
+    @Override\r
+    public ArrayList<Enumeration> getArrayIndexes() {\r
+        if(getOriginal() != null)\r
+            return getOriginal().getArrayIndexes();\r
+        else\r
+            return super.getArrayIndexes();\r
+    }\r
+\r
+    @Override\r
+    public ArrayList<IExpression> getExpressions() {\r
+        if(getOriginal() != null)\r
+            return getOriginal().getExpressions();\r
+        else\r
+            return super.getExpressions();\r
+    }\r
+\r
+    @Override\r
+    public String getVariability() {\r
+        if(getOriginal() != null)\r
+            return getOriginal().getVariability();\r
+        else\r
+            return super.getVariability();\r
+    }\r
+\r
+    @Override\r
+    public String getType() {\r
+        if(getOriginal() != null)\r
+            return getOriginal().getType();\r
+        else\r
+            return super.getType();\r
+    }\r
+\r
+    @Override\r
+    public String getUnit() {\r
+        if(getOriginal() != null)\r
+            return getOriginal().getUnit();\r
+        else\r
+            return super.getUnit();\r
+    }\r
+\r
+    @Override\r
+    public String getDocumentationDefinition(ReadGraph graph) throws DatabaseException {\r
+        return null;\r
+    }\r
+    \r
+    @Override\r
+    public String getModelicaName() {\r
+        if(getOriginal() != null)\r
+            return getOriginal().getModelicaName();\r
+        else\r
+            return super.getModelicaName();\r
+    }\r
+    \r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/SharedFunctionLibrary.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/SharedFunctionLibrary.java
new file mode 100644 (file)
index 0000000..357f9d0
--- /dev/null
@@ -0,0 +1,26 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Representation of a shared function library. See {@link FunctionLibrary} \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.SharedFunctionOntology)\r
+public class SharedFunctionLibrary extends FunctionLibrary {\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Sheet.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Sheet.java
new file mode 100644 (file)
index 0000000..7a27fd2
--- /dev/null
@@ -0,0 +1,329 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import gnu.trove.map.hash.THashMap;\r
+import gnu.trove.set.hash.THashSet;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.databoard.primitives.MutableString;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.UpdateMethod;\r
+import org.simantics.spreadsheet.Range;\r
+import org.simantics.spreadsheet.SheetVariables;\r
+import org.simantics.spreadsheet.common.exception.CellParseException;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.spreadsheet.util.SpreadsheetUtils;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SpreadsheetResource.URIs.Spreadsheet)\r
+public class Sheet extends org.simantics.sysdyn.representation.Variable {\r
+    \r
+    @RelatedElement(Layer0.URIs.PartOf)\r
+    protected Book book;\r
+    \r
+    THashMap<String, Object> cells = new THashMap<String, Object>();\r
+    THashSet<String> usedRanges = new THashSet<String>();\r
+    \r
+    Resource resource;\r
+\r
+    public String getSheet() {\r
+        return "Sheet";\r
+    }\r
+    \r
+    @UpdateMethod\r
+    public boolean updateCells(ReadGraph g, Resource r) throws DatabaseException {\r
+        if(g.hasStatement(r)) {\r
+            this.resource = r;\r
+            THashMap<String, Object> newCells = new THashMap<String, Object>();\r
+            \r
+            g.getObjects(r, Layer0.getInstance(g).ConsistsOf);\r
+            Variable v = g.adapt(r, Variable.class);\r
+            for(Variable child : v.getChildren(g)) {\r
+                String name = child.getName(g);\r
+                try {\r
+                    SpreadsheetUtils.decodeCellAbsolute(name);\r
+                    Object value = child.getPropertyValue(g, SheetVariables.CONTENT);\r
+                    if(value instanceof Variant) {\r
+                        newCells.put(name, ((Variant)value).getValue());\r
+                    }\r
+                } catch (CellParseException e) {\r
+                } catch (MissingVariableException e) {\r
+                    System.out.println("missing content for: " + name);\r
+                }\r
+            }\r
+            \r
+            boolean update = false;\r
+            if(newCells.size() == this.cells.size()) {\r
+                // Cells are the same size. There might not be changes. Next up: content\r
+                for(String key : this.cells.keySet()) {\r
+                    if(!this.cells.get(key).equals(newCells.get(key))) {\r
+                        update = true;\r
+                        break;\r
+                    }\r
+                }\r
+            } else {\r
+                update = true;\r
+            }\r
+            \r
+            if(update) {\r
+                this.cells = newCells;\r
+                this.usedRanges.clear();\r
+                return true;\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
+    public String getStringRepresentation() {\r
+        final StringBuilder clazz = new StringBuilder();\r
+        clazz.append("class " + getModelicaName() + "_class\n");\r
+        \r
+        try {\r
+            Simantics.getSession().syncRequest(new ReadRequest() {\r
+\r
+                @Override\r
+                public void run(ReadGraph graph) throws DatabaseException {\r
+                    HashSet<String> possibleRanges = new HashSet<String>();\r
+                    \r
+                    // Write all doubles that have been used in expressions\r
+                    final HashSet<String> usedCells = new HashSet<String>();\r
+                    for(String key : usedRanges) {\r
+                        if(cells.containsKey(key)) {\r
+                            addRange(key, usedCells, clazz);\r
+                        } else {\r
+                            for(String range : getChildRanges(graph, key)) {\r
+                                if(cells.containsKey(range))\r
+                                    addRange(range, usedCells, clazz);\r
+                            }\r
+                            possibleRanges.add(key);\r
+                        }\r
+                    }\r
+\r
+                    // Get cell ranges. Add cell names that have not been used individually to usedCells set\r
+                    // and use those names in ranges\r
+\r
+                    Variable v = graph.adapt(resource, Variable.class);\r
+                    for(String possibleRange : possibleRanges) {\r
+                        String[] parts = possibleRange.split(":");\r
+                        if(parts.length != 2 || !cells.containsKey(parts[0]) || !cells.containsKey(parts[1]))\r
+                            continue;\r
+                        Variable range = v.getChild(graph, possibleRange);\r
+                        if(range == null)\r
+                            continue;\r
+                        String[][] rangeCells = range.getPropertyValue(graph, SheetVariables.RANGE_CELL_NAMES);\r
+                        if(rangeCells == null)\r
+                            continue;\r
+\r
+                        if(rangeCells[0].length > 1) {\r
+                            // Has two dimensions     \r
+                            clazz.append("    parameter Real[" + rangeCells.length + ", " + rangeCells[0].length + "] ");\r
+                            clazz.append(possibleRange.replace(":", "_") + " = {");\r
+                            for(int i = 0; i < rangeCells.length; i++) {\r
+                                clazz.append("{");\r
+                                for(int j = 0; j < rangeCells[i].length; j++) {\r
+                                    clazz.append(rangeCells[i][j]);\r
+                                    usedCells.add(rangeCells[i][j]); // Add the cell name to used cells\r
+                                    if(j < rangeCells[i].length - 1)\r
+                                        clazz.append(", ");\r
+                                }\r
+                                clazz.append("}");\r
+                                if(i < rangeCells.length - 1)\r
+                                    clazz.append(", ");\r
+                            }\r
+                            clazz.append("};\n");\r
+                        } else {\r
+                            // Has one dimension\r
+                            clazz.append("    parameter Real[" + rangeCells.length + "] ");\r
+                            clazz.append(possibleRange.replace(":", "_") + " = {");\r
+                            for(int i = 0; i < rangeCells.length; i++) {\r
+                                clazz.append(rangeCells[i][0]);\r
+                                usedCells.add(rangeCells[i][0]); // Add the cell name to used cells\r
+                                if(i < rangeCells.length - 1)\r
+                                    clazz.append(", ");\r
+                            }\r
+                            clazz.append("};\n");\r
+                        }\r
+                    }\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        clazz.append("end " + getModelicaName() + "_class;\n");\r
+//        clazz.append("    " + name + "_class " + name + ";\n");\r
+        return clazz.toString();\r
+    }\r
+    \r
+    private void addRange(String key, HashSet<String> usedCells, StringBuilder clazz) {\r
+        if(usedCells.add(key)) {\r
+            Object value = cells.get(key);\r
+            if(value instanceof String || value instanceof MutableString) {\r
+                try {\r
+                    Double d = Double.parseDouble(value.toString());\r
+                    value = d;\r
+                } catch (NumberFormatException e) {\r
+                }\r
+            } \r
+\r
+            if(value instanceof Double) {\r
+                Double d = (Double)value;\r
+                clazz.append("    parameter Real " + key + " = " + d + " /* Actual value read from init file */;\n");\r
+            }\r
+        }\r
+    }\r
+    \r
+    private ArrayList<String> getChildRanges(ReadGraph graph, String range) throws DatabaseException {\r
+        ArrayList<String> ranges = new ArrayList<String>();\r
+        if(range.contains(":")) {\r
+            // Get cell ranges. Add cell names that have not been used individually to usedCells set\r
+            // and use those names in ranges\r
+            Variable v = graph.adapt(resource, Variable.class);\r
+            String[] parts = range.split(":");\r
+            if(parts.length != 2 || !cells.containsKey(parts[0]) || !cells.containsKey(parts[1]))\r
+                return ranges;\r
+            Variable rangeVariable = v.getChild(graph, range);\r
+            if(rangeVariable == null)\r
+                return ranges;\r
+            String[][] rangeCells = rangeVariable.getPropertyValue(graph, SheetVariables.RANGE_CELL_NAMES);\r
+            if(rangeCells == null)\r
+                return ranges;\r
+\r
+            for(int i = 0; i < rangeCells.length; i++) {\r
+                for(int j = 0; j < rangeCells[i].length; j++) {\r
+                    ranges.add(rangeCells[i][j]);\r
+                }\r
+            }\r
+        }\r
+        return ranges;\r
+    }\r
+\r
+    \r
+    public THashMap<String, Object> getCells() {\r
+        return cells;\r
+    }\r
+    \r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        \r
+    }\r
+    \r
+    /**\r
+     * Add a range that has been used for this sheet. \r
+     * \r
+     * Used ranges help to reduce code sent to Modelica.\r
+     * \r
+     * @param range range of cell/cells. (e.g. B2 or B4:B6)\r
+     */\r
+    public void use(final String usedRange) {\r
+        usedRanges.add(usedRange);\r
+    }\r
+\r
+    \r
+    @Override\r
+    public String getDocumentationDefinition(ReadGraph graph) throws DatabaseException {\r
+        Variable v = Variables.getVariable(graph, resource);\r
+        Collection<Variable> children = v.getChildren(graph);\r
+        HashMap<Variable, Range> map = new HashMap<Variable, Range>();\r
+        int minColumn = -1;\r
+        int maxColumn = -1;\r
+        int minRow = -1;\r
+        int maxRow = -1;\r
+        for(Variable child : children) {\r
+            Range range = SpreadsheetUtils.decodePossibleCellAbsolute(child.getName(graph));\r
+            if(range != null) {\r
+                Variant valueVariant = child.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT);\r
+                Object valueObject = valueVariant.getValue();\r
+                if(valueObject instanceof String) {\r
+                    String value = (String) valueObject;\r
+                    if(!value.isEmpty()) {\r
+                        map.put(child, range);\r
+                        if(minColumn < 0 || range.startColumn < minColumn)\r
+                            minColumn = range.startColumn;\r
+                        if(range.startColumn > maxColumn)\r
+                            maxColumn = range.startColumn;\r
+                        if(minRow < 0 || range.startRow < minRow)\r
+                            minRow = range.startRow;\r
+                        if(range.startRow > maxRow)\r
+                            maxRow = range.startRow;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        int nColumns = maxColumn - minColumn + 1;\r
+        int nRows = maxRow - minRow + 1;\r
+        String[][] table = new String[nRows][nColumns];\r
+        for(int i = 0; i < nRows; i++) \r
+            for(int j = 0; j < nColumns; j++)\r
+                table[i][j] = "";\r
+        \r
+        for(Variable cell : map.keySet()) {\r
+            Range range = map.get(cell);\r
+            Variant valueVariant = cell.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT);\r
+            Object valueObject = valueVariant.getValue();\r
+            table[range.startRow - minRow][range.startColumn - minColumn] = valueObject.toString(); \r
+        }\r
+        \r
+        StringBuilder result = new StringBuilder();\r
+        result.append("<table style='border-collapse:collapse;'>");\r
+        for(int i = -1; i < nRows; i++) {\r
+            result.append("<tr>");\r
+            for(int j = -1; j < nColumns; j++) {\r
+                result.append("<td style='border: 1px solid black;'>");\r
+                if(i == -1 || j == -1)\r
+                    result.insert(result.length() - 2, "background-color:#D3D3D3; text-align:center;");\r
+                if(i == -1 && j == -1) {\r
+                    // Do nothing\r
+                } else if(i == -1) {\r
+                    // First row, make column headers\r
+                    result.append(SpreadsheetUtils.columnName(j + minColumn));\r
+                } else if(j == -1){\r
+                    // First column, make row numbers. Rows start from 1\r
+                    result.append(i + minRow + 1);\r
+                } else {\r
+                    // Actual content\r
+                    result.append(table[i][j]);\r
+                }\r
+                result.append("</td>");\r
+            }\r
+            result.append("</tr>");\r
+        }\r
+        result.append("</table>");\r
+\r
+        return result.toString();\r
+    }\r
+    \r
+    \r
+    public Resource getResource() {\r
+        return resource;\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Stock.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Stock.java
new file mode 100644 (file)
index 0000000..e706bc2
--- /dev/null
@@ -0,0 +1,117 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedElements;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.expressions.StockExpression;\r
+import org.simantics.sysdyn.representation.utils.SheetFormatUtils;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+/**\r
+ * Representation of a Stock variable\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.Stock)\r
+public class Stock extends IndependentVariable {\r
+\r
+    @RelatedElements(\r
+            value = SysdynResource.URIs.Variable_isHeadOf,\r
+            composition = true)\r
+    private ArrayList<IElement> incomingConnections = new ArrayList<IElement>();\r
+\r
+\r
+    @RelatedElements(\r
+            value = SysdynResource.URIs.Variable_isTailOf,\r
+            composition = true)\r
+    private ArrayList<IElement> outgoingConnections = new ArrayList<IElement>();\r
+\r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);        \r
+    }\r
+\r
+    @Override\r
+    public String getInitialEquation() {\r
+        if (Variability.getVariability(this) == Variability.CONTINUOUS) {\r
+            return super.getInitialEquation();\r
+        } else {\r
+            return null;\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public String getDeclaration() {\r
+       // is it really guaranteed that variability is the only necessary \r
+       // parameter to consider when deciding whether to use start=value \r
+       // notation or initial equations?\r
+        String each = (getArrayIndexes() != null && !getArrayIndexes().isEmpty()) ? "each " : "";\r
+        // each is required when a single value is used for all dimensions e.g. Stock[30](each start = 0)  \r
+        if (Variability.getVariability(this) == Variability.CONTINUOUS) {\r
+            // start parameter is not used, everything needs to be fixed=false\r
+            return "    " + getType() + " " + getModelicaName() + getRange() + "(" + each + "fixed=false);\n";\r
+        } else {\r
+            // Start parameter is used. Parameter guarantees that there is only one expression.\r
+            StockExpression e = (StockExpression)getExpressions().get(0);\r
+            String initialEquation = e.getModelicaExpression();\r
+            initialEquation = SheetFormatUtils.reformatSheetReferences(this, initialEquation);\r
+\r
+            return "    " + \r
+            getType() + \r
+            " " + \r
+            getModelicaName() + \r
+            getRange() + \r
+            "(" + \r
+            "start=" + \r
+            initialEquation + \r
+            ", " + \r
+            each + \r
+            "fixed=true);\n";\r
+        }\r
+    }\r
+\r
+    public String getEquation() {\r
+        return getVariableEquation();\r
+    }\r
+\r
+\r
+    public ArrayList<Valve> getIncomingValves() {\r
+        ArrayList<Valve> valves = new ArrayList<Valve>();\r
+        for(IElement element : incomingConnections) {\r
+            if(element instanceof Flow) {\r
+                Flow flow = (Flow)element;\r
+                valves.add((Valve)flow.getTail());\r
+            }\r
+        }\r
+        return valves;\r
+    }\r
+\r
+    public ArrayList<Valve> getOutgoingValves() {\r
+        ArrayList<Valve> valves = new ArrayList<Valve>();\r
+        for(IElement element : outgoingConnections) {\r
+            if(element instanceof Flow) {\r
+                Flow flow = (Flow)element;\r
+                valves.add((Valve)flow.getHead());\r
+            }\r
+        }\r
+        return valves;\r
+    }\r
+\r
+\r
+}\r
+\r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/SysdynSchema.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/SysdynSchema.java
new file mode 100644 (file)
index 0000000..1cd9a72
--- /dev/null
@@ -0,0 +1,71 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.objmap.schema.MappingSchemas;\r
+import org.simantics.objmap.schema.SimpleSchema;\r
+import org.simantics.sysdyn.representation.expressions.ConstantExpression;\r
+import org.simantics.sysdyn.representation.expressions.DelayExpression;\r
+import org.simantics.sysdyn.representation.expressions.LookupExpression;\r
+import org.simantics.sysdyn.representation.expressions.NormalExpression;\r
+import org.simantics.sysdyn.representation.expressions.ParameterExpression;\r
+import org.simantics.sysdyn.representation.expressions.StockExpression;\r
+import org.simantics.sysdyn.representation.expressions.WithLookupExpression;\r
+\r
+public class SysdynSchema extends SimpleSchema {\r
+    \r
+    public SysdynSchema(ReadGraph g) {        \r
+        try {\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Auxiliary.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Cloud.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Configuration.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Dependency.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Flow.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Stock.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Valve.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Module.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Input.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, ModuleType.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Model.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Enumeration.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, EnumerationIndex.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, NormalExpression.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, ParameterExpression.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, StockExpression.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, ConstantExpression.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, WithLookupExpression.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, LookupExpression.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Redeclaration.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, LibraryDummy.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Book.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Sheet.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, DiagramContainerDummy.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, DelayExpression.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, FunctionLibrary.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, SharedFunctionLibrary.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Function.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Entity.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, ParameterOverride.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Shadow.class));\r
+            addLinkType(MappingSchemas.fromAnnotations(g, Loop.class));\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        } catch (InstantiationException e) {\r
+            e.printStackTrace();\r
+        } catch (IllegalAccessException e) {\r
+            e.printStackTrace();\r
+        }        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Valve.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Valve.java
new file mode 100644 (file)
index 0000000..aa3d012
--- /dev/null
@@ -0,0 +1,24 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.visitors.IElementVisitorVoid;\r
+\r
+@GraphType(SysdynResource.URIs.Valve)\r
+public class Valve extends IndependentVariable {\r
+    @Override\r
+    public void accept(IElementVisitorVoid v) {\r
+        v.visit(this);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variability.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variability.java
new file mode 100644 (file)
index 0000000..27f33a6
--- /dev/null
@@ -0,0 +1,292 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+import org.simantics.sysdyn.representation.utils.FormatUtils;\r
+import org.simantics.sysdyn.representation.utils.RepresentationUtils;\r
+\r
+/**\r
+ * Variability of a variable in system dynamics models. \r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public enum Variability {\r
+\r
+    PARAMETER("parameter"),\r
+    CONSTANT("constant"),\r
+    CONTINUOUS("");\r
+    \r
+    \r
+    private static List<String> timeDependentFunctions = Arrays.asList(\r
+        "pre",\r
+        "delay"\r
+    );\r
+\r
+    private String text;\r
+\r
+    Variability(String text) {\r
+        this.text = text;\r
+    }\r
+\r
+    public String getText() {\r
+        return this.text;\r
+    }\r
+\r
+    /**\r
+     * Convert a textual representation to a Variability object. \r
+     * \r
+     * @param text Variability as text (parameter / constant / continuous)\r
+     * @return Variability or null\r
+     */\r
+    public static Variability fromString(String text) {\r
+        if (text != null) {\r
+            for (Variability v : Variability.values()) {\r
+                if (text.equalsIgnoreCase(v.text)) {\r
+                    return v;\r
+                }\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+\r
+    /**\r
+     * Check if reference in a configuration is a parameter.\r
+     * @param variable \r
+     * @param configuration Configuration\r
+     * @param reference String reference to a variable\r
+     * @return is the reference a parameter\r
+     */\r
+    private static boolean isParameter(IndependentVariable variable, Configuration configuration, String reference, boolean allowVariables) {\r
+        // Check if references are references to sheets or enumerations. \r
+        // Sheet and Enumeration references are allowed, since sheets contain only constants / parameters\r
+        String r = reference.split("\\.")[0]; \r
+        for(IElement element : configuration.getElements()) {\r
+            if(element instanceof Module) {\r
+                Module m = (Module)element;\r
+                if(r.equals(m.getName())) {\r
+                    if(!reference.contains(".")) {\r
+                        // The reference contains only modules, implementation feature for the expression parser\r
+                        return true;\r
+                    }\r
+                    Configuration moduleConfiguration = m.getType().getConfiguration();\r
+                    return isParameter(variable, moduleConfiguration, reference.substring(reference.indexOf(".") + 1), allowVariables);\r
+                }\r
+            } else if(element instanceof Book) {\r
+                for(Sheet sheet : ((Book)element).getSheets()) {\r
+                    if(r.equals(sheet.getName())) {\r
+                        return true;\r
+                    }\r
+                }\r
+            } else if(element instanceof Enumeration) {\r
+                Enumeration e = (Enumeration)element;\r
+                if(r.equals(e.getName())) {\r
+                    String[] split = reference.split("\\.");\r
+                    if(split.length == 1)\r
+                        return true;\r
+                    if(split.length == 2) {\r
+                        if(split[1].equals("size") || split[1].equals("elements"))\r
+                            return true;\r
+\r
+                        for(EnumerationIndex ei : e.getEnumerationIndexes()) {\r
+                            if(split[1].equals(ei.getName()))\r
+                                return true;\r
+                        }\r
+                    }\r
+                }\r
+            } else if(allowVariables) {\r
+                // Only if variable references are allowed\r
+                if(element instanceof IndependentVariable && !(element instanceof Stock)) {\r
+                    IndependentVariable v = (IndependentVariable)element;\r
+                    if(r.equals(v.getName())) { \r
+                       if(v.getName().equals(variable.getName())) // Reference to self. Can be used in pre(self)\r
+                               return false;\r
+                       else\r
+                               return getVariability(v) != Variability.CONTINUOUS;\r
+                    }\r
+                } else if(element instanceof Input) {\r
+                    Input i = (Input)element;\r
+                    if(r.equals(i.getName())) {\r
+                        return i.getVariability() != null && !i.getVariability().equals(Variability.CONTINUOUS.getText());\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        \r
+        // Try to find sheet in another way: this might be a module type configuration. Find the model configuration and its sheet\r
+        if(configuration.getModuleType() != null) {\r
+               Object parent = configuration.getModuleType().getParent();\r
+               if(parent != null && parent instanceof Model) {\r
+                       configuration = ((Model)parent).getModelConfiguration();\r
+                for(IElement element : configuration.getElements()) {\r
+                       if(element instanceof Book) {\r
+                        for(Sheet sheet : ((Book)element).getSheets()) {\r
+                            if(r.equals(sheet.getName())) {\r
+                                return true;\r
+                            }\r
+                        }\r
+                        break;\r
+                       }\r
+                }\r
+               }\r
+        }\r
+        \r
+        \r
+        \r
+        // If there was no sheet for this reference name, or there was some other problem, return false\r
+        return false;\r
+    }\r
+    \r
+\r
+    /**\r
+     * Get variability of a variable. Allows references to other parameter variables in parameter expressions \r
+     * if game experiment is not active.\r
+     * @param variable Variable\r
+     * @return Variabilty of a variable\r
+     */\r
+    static public Variability getVariability(IndependentVariable variable) {\r
+       if(RepresentationUtils.isPartOfGameExperiment(variable) && !(variable instanceof Stock)) {\r
+               \r
+               /* \r
+                * Game experiments cannot use as many parameter variables as normal experiments.\r
+                * If a parameter variable is changed, other parameter values depending on that \r
+                * parameter value are not automatically changed.\r
+                * \r
+                * Something of a hack: \r
+                * Allow variable references, if there are not incoming dependencies to the variable.\r
+                * This enables the use of derived variables for initial values of stocks.\r
+                */\r
+               if(variable.getIncomingDependencies() == null || variable.getIncomingDependencies().isEmpty())\r
+                       return getVariability(variable, true, null);\r
+               else\r
+                       return getVariability(variable, false, null);\r
+       } else {\r
+               return getVariability(variable, true, null);\r
+       }\r
+    }\r
+\r
+    /**\r
+     * Get variability of a variable\r
+     * @param variable Variable\r
+     * @param allowVariableReferences Allow references to other (parameter) variables in parameter expressions.\r
+     * @param configuration Configuration of the location for references. (null => variable.getParentConfiguration()) \r
+     * @return Variabilty of a variable\r
+     */\r
+    static public Variability getVariability(IndependentVariable variable, boolean allowVariableReferences, Configuration configuration) {\r
+        if(variable == null || variable.getExpressions() == null)\r
+            return Variability.CONTINUOUS;\r
+        \r
+        ArrayList<org.simantics.sysdyn.representation.expressions.IExpression> expressions = variable.getExpressions();\r
+\r
+        if(expressions.size() != 1)\r
+            return Variability.CONTINUOUS; // Cannot handle multiple expressions as parameters\r
+\r
+        org.simantics.sysdyn.representation.expressions.IExpression ie  = expressions.get(0);\r
+\r
+        String expression = ie.getExpression();\r
+\r
+        return getVariability(variable, expression, allowVariableReferences, configuration);\r
+    }\r
+\r
+    /**\r
+     * Get the variability of an expression in a variable. Variables may have multiple expressions.\r
+     * Allows references to other (parameter) variables in parameter expressions.\r
+     * \r
+     * @param variable Variable\r
+     * @param expression Expression\r
+     * @return Variability of the expression\r
+     */\r
+    static public Variability getVariability(IndependentVariable variable, String expression) {\r
+        return getVariability(variable, expression, true, null);\r
+    }\r
+\r
+    /**\r
+     * Get the variability of an expression in a variable. Variables may have multiple expressions.\r
+     * \r
+     * @param variable Variable\r
+     * @param expression Expression\r
+     * @param allowVariableReferences Allow references to other (parameter) variables in parameter expressions\r
+     * @param configuration Configuration of the location for references. (null => variable.getParentConfiguration()) \r
+     * @return Variability of the expression\r
+     */\r
+    static public Variability getVariability(IndependentVariable variable, String expression, boolean allowVariableReferences, Configuration configuration) {\r
+        Configuration conf = configuration == null ? variable.getParentConfiguration() : configuration;\r
+        // If no variables are used in the equation, start value is used\r
+\r
+        HashMap<String, Function> functions = new HashMap<String, Function>();\r
+        if(conf != null) {\r
+            Model model = null;\r
+            if(conf.getModuleType() != null) {\r
+                ModuleType moduleType = conf.getModuleType();\r
+                if (moduleType.getParent() instanceof Model) {\r
+                    model = (Model) moduleType.getParent();\r
+                }\r
+            } else {\r
+                model = conf.getModel();\r
+            }\r
+\r
+            if(model != null)\r
+                functions = model.getFunctions();\r
+        }\r
+\r
+        // First the equation is formatted and parsed\r
+        String equation = FormatUtils.formatExpressionForModelica(variable, expression, false);\r
+        ExpressionParser parser = new ExpressionParser(new StringReader(equation));\r
+        try {\r
+            parser.expr();\r
+            if(parser.getReferences().isEmpty() && parser.getFunctionCallReferences().isEmpty()) {\r
+                // if equation did not contain any references, start value is used\r
+                return Variability.PARAMETER;\r
+            } else {\r
+                Set<String> references = parser.getReferences().keySet();\r
+                \r
+                if(parser.getForIndices()!=null) {\r
+                       for(Token t : parser.getForIndices().keySet()) {\r
+                               references.remove(t.image);\r
+                       }\r
+                }\r
+                \r
+                // Check used functions\r
+                for(String function : parser.getFunctionCallReferences().keySet()) {\r
+                    if(functions.containsKey(function) && functions.get(function).hasTimeReference())\r
+                        return Variability.CONTINUOUS;\r
+                    else if (timeDependentFunctions.contains(function)) {\r
+                        return Variability.CONTINUOUS;\r
+                    }\r
+                }\r
+\r
+                // Go through each reference\r
+                for(String reference : references) {\r
+                    if(!isParameter(variable, conf, reference, allowVariableReferences)) {\r
+                        return Variability.CONTINUOUS;\r
+                    }\r
+                }\r
+\r
+                // All found variables were sheets or non-continuous\r
+                return Variability.PARAMETER;\r
+            }\r
+        } catch (ParseException e) {\r
+        }\r
+\r
+        return Variability.CONTINUOUS;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variable.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/Variable.java
new file mode 100644 (file)
index 0000000..997e61d
--- /dev/null
@@ -0,0 +1,163 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedListElements;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.expressions.IExpression;\r
+\r
+/**\r
+ * Abstract class for representing a variable in system dynamics models \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public abstract class Variable implements IElement {\r
+    \r
+    @RelatedValue(SysdynResource.URIs.Variable_type)\r
+    protected String type;\r
+    \r
+    @RelatedValue(Layer0.URIs.HasName)\r
+    protected String name;\r
+    \r
+    @RelatedElement(Layer0.URIs.PartOf)\r
+    protected Object parent;\r
+    \r
+    @RelatedListElements(SysdynResource.URIs.Variable_arrayIndexesList)\r
+    protected ArrayList<Enumeration> arrayIndexes = new ArrayList<Enumeration>();\r
+    \r
+    @RelatedListElements(SysdynResource.URIs.Variable_expressionList)\r
+    protected ArrayList<IExpression> expressions = new ArrayList<IExpression>();\r
+    \r
+    @RelatedValue(SysdynResource.URIs.Variable_variability)\r
+    protected String variability;\r
+    \r
+    @RelatedValue(SysdynResource.URIs.Variable_unit)\r
+    protected String unit;\r
+    \r
+    @RelatedValue(Layer0.URIs.HasDescription)\r
+    protected String description;\r
+    \r
+    @RelatedElement(SysdynResource.URIs.IsOutput)\r
+    protected IElement isOutput;    \r
+    \r
+    /**\r
+     * Return the variability of this variable (Used in practice only with Input variables)\r
+     * @return Variability\r
+     */\r
+    public String getVariability() {\r
+        return variability;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return The name of this variable\r
+     */\r
+    public String getName() {\r
+        return this.name;\r
+    }\r
+    \r
+    /**\r
+     * Get Modelica compliant name\r
+     * @return The name of this variable with spaces (' ') replaced with \r
+     * underscore characters ('_')\r
+     */\r
+    public String getModelicaName() {\r
+       if (this.name == null)\r
+               return null;\r
+        return this.name.replace(' ', '_');\r
+    }\r
+    \r
+    /**\r
+     *\r
+     * @return Parent configuration of this variable (or null if something is wrong)\r
+     */\r
+    public Configuration getParentConfiguration() {\r
+        if(parent instanceof Configuration) {\r
+            return (Configuration)parent;\r
+        } else if(parent instanceof Book) {\r
+            return (Configuration)((Book)parent).getParentConfiguration();\r
+        } else {\r
+            return null;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * \r
+     * @return The type of this variable (<u>Real</u> / Boolean / ...) \r
+     */\r
+    public String getType() {\r
+        return this.type;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return Array indexes for this variable\r
+     */\r
+    public ArrayList<Enumeration> getArrayIndexes() {\r
+       return this.arrayIndexes;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return Expressions of this variable\r
+     */\r
+    public ArrayList<IExpression> getExpressions() {\r
+        return this.expressions;\r
+    }\r
+    \r
+    /**\r
+     * \r
+     * @return Units of this variable\r
+     */\r
+    public String getUnit() {\r
+        return this.unit;\r
+    }\r
+    \r
+    /**\r
+     * Get description\r
+     * @return description\r
+     */\r
+    public String getDescription() {\r
+        if(description == null)\r
+            return "";\r
+        else \r
+            return description;\r
+    }\r
+    \r
+    public boolean isOutput() {\r
+        return !(isOutput == null);\r
+    }\r
+    \r
+    /**\r
+     * Get definition for documentation.\r
+     * \r
+     * For independent variables this is the equations\r
+     * For enumerations this is the indexes\r
+     * etc.\r
+     * @return\r
+     */\r
+    public String getDocumentationDefinition(ReadGraph graph) throws DatabaseException {\r
+        if(isOutput())\r
+            return "<br />Is output";\r
+        else\r
+            return "";\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctions.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctions.java
new file mode 100644 (file)
index 0000000..173db2c
--- /dev/null
@@ -0,0 +1,31 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.annotations;\r
+\r
+import java.lang.annotation.ElementType;\r
+import java.lang.annotation.Retention;\r
+import java.lang.annotation.RetentionPolicy;\r
+import java.lang.annotation.Target;\r
+\r
+import org.simantics.objmap.annotations.meta.HasFieldRuleFactory;\r
+\r
+/**\r
+ * BuiltinFunctions -annotation returns the built-in functions function library \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+@Retention(RetentionPolicy.RUNTIME)\r
+@Target(ElementType.FIELD)\r
+@HasFieldRuleFactory(BuiltinFunctionsFactory.class)\r
+public @interface BuiltinFunctions {\r
+}\r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctionsAccessor.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctionsAccessor.java
new file mode 100644 (file)
index 0000000..c010706
--- /dev/null
@@ -0,0 +1,57 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+\r
+package org.simantics.sysdyn.representation.annotations;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.MappingException;\r
+import org.simantics.objmap.rules.domain.IDomainAccessor;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Accesses the built-in functions in Sysdyn ontology\r
+ * \r
+ * @author Teemu Lempinen\r
+ */\r
+public class BuiltinFunctionsAccessor implements IDomainAccessor<Resource> {\r
+\r
+    \r
+    public BuiltinFunctionsAccessor() {\r
+    }\r
+\r
+    @Override\r
+    public Resource get(ReadGraph graph, Resource element) throws MappingException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        Resource builtinFunctions = null;\r
+        try {\r
+            Resource sysdyn = graph.getResource("http://www.simantics.org/Sysdyn-1.1");\r
+            builtinFunctions = graph.syncRequest(new PossibleObjectWithType(sysdyn, l0.ConsistsOf, sr.SysdynModelicaFunctionLibrary));\r
+        } catch (DatabaseException e) {\r
+            throw new MappingException(e);\r
+        }\r
+        return builtinFunctions;\r
+    }\r
+    \r
+    @Override\r
+    public boolean set(WriteGraph g, Resource element, Resource value)\r
+            throws MappingException {\r
+        // Built-in functions should not be set programmatically\r
+        return true;        \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctionsFactory.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/annotations/BuiltinFunctionsFactory.java
new file mode 100644 (file)
index 0000000..f6800db
--- /dev/null
@@ -0,0 +1,36 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.annotations;\r
+\r
+import java.lang.annotation.Annotation;\r
+import java.lang.reflect.Field;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.exception.ValidationException;\r
+import org.simantics.objmap.IMappingRule;\r
+import org.simantics.objmap.rules.MappedElementRule;\r
+import org.simantics.objmap.rules.factory.IFieldRuleFactory;\r
+import org.simantics.objmap.rules.range.FieldAccessor;\r
+\r
+public class BuiltinFunctionsFactory implements IFieldRuleFactory {\r
+\r
+    @Override\r
+    public IMappingRule create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException, ValidationException, ServiceException {\r
+        return new MappedElementRule(\r
+                new BuiltinFunctionsAccessor(),\r
+                new FieldAccessor<Object>(field)\r
+                );\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ConstantExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ConstantExpression.java
new file mode 100644 (file)
index 0000000..3b4036f
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.utils.FormatUtils;\r
+\r
+/**\r
+ * Represents a constant expression\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.ConstantExpression)\r
+public class ConstantExpression extends Expression {\r
+\r
+    @RelatedValue(SysdynResource.URIs.Expression_equation)\r
+    private String equation;\r
+\r
+    @Override\r
+    public String getExpression() {\r
+        return equation;\r
+    }    \r
+    \r
+    @Override\r
+    public String getModelicaExpression() {\r
+        return FormatUtils.replaceWhitespace(equation);\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/DelayExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/DelayExpression.java
new file mode 100644 (file)
index 0000000..4edf308
--- /dev/null
@@ -0,0 +1,146 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.modelica.ModelicaWriter;\r
+import org.simantics.sysdyn.representation.utils.FormatUtils;\r
+import org.simantics.sysdyn.representation.utils.IndexUtils;\r
+import org.simantics.sysdyn.representation.utils.UnitUtils;\r
+\r
+/**\r
+ * Representation of a delay expression. The order of the \r
+ * delay can be 1-n.\r
+ * \r
+ * Delay with n = 3:\r
+ * \r
+ * DELAY3=LV3/DL\r
+ * LV3=INTEG(RT2-DELAY3,DL*input)\r
+ * RT2=LV2/DL\r
+ * LV2=INTEG(RT1-RT2,LV3)\r
+ * RT1=LV1/DL\r
+ * LV1=INTEG(input-RT1,LV3)\r
+ * DL=delay time/3\r
+ * \r
+ * DELAY3I=LV3/DL\r
+ * LV3=INTEG(RT2-DELAY3I,initial value*DL) \r
+ * RT2=LV2/DL\r
+ * LV2=INTEG(RT1-RT2,LV3)\r
+ * RT1=LV1/DL\r
+ * LV1=INTEG(input-RT1,LV3)\r
+ * DL=delay time/3\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.DelayExpression)\r
+public class DelayExpression extends Expression {\r
+\r
+       @RelatedValue(SysdynResource.URIs.DelayExpression_initialValue)\r
+       private String initialValue;\r
+\r
+       @RelatedValue(SysdynResource.URIs.DelayExpression_delayTime)\r
+       private String delayTime;\r
+\r
+       @RelatedValue(SysdynResource.URIs.DelayExpression_order)\r
+       private Integer order;\r
+\r
+       @RelatedValue(SysdynResource.URIs.DelayExpression_expression)\r
+       private String equation;\r
+\r
+       @Override\r
+       public String getDeclarationAddition() {\r
+               // instantiate the correct delay class for this expression\r
+               return "\t" + ModelicaWriter.getDelayName(order) + " " + instance() + ";\n";\r
+       }\r
+\r
+       @Override\r
+       public String getEquation() {\r
+               StringBuilder sb = new StringBuilder();\r
+\r
+               String equation = FormatUtils.replaceWhitespace(this.equation);\r
+               equation = FormatUtils.formatExpressionForModelica(parent, equation);\r
+               String delayTime = FormatUtils.replaceWhitespace(this.delayTime);\r
+               delayTime = FormatUtils.formatExpressionForModelica(parent, delayTime);\r
+               String initialValue = FormatUtils.replaceWhitespace(this.initialValue);\r
+               initialValue = FormatUtils.formatExpressionForModelica(parent, initialValue);\r
+\r
+               sb.append("\t" + instance() + "." + ModelicaWriter.getDelayValve(0) + " = " + equation + ";\n");\r
+\r
+               sb.append("\t" + instance() + "." + ModelicaWriter.DELAY_TIME + " = " + delayTime + ";\n");\r
+\r
+               sb.append("\t" + instance() + "." + ModelicaWriter.DELAY_INITIAL + " = ");\r
+               if (initialValue != null && !initialValue.isEmpty()) {\r
+                       sb.append(initialValue);\r
+               } \r
+               else {\r
+                       // if an initial value is not set, use the value of the first valve\r
+                       sb.append(instance() + "." + ModelicaWriter.getDelayValve(0));\r
+               }\r
+               sb.append(";\n");\r
+\r
+               // set the value of the variable\r
+               String range = IndexUtils.rangeToIndexes(parent, getArrayRange());\r
+               // TODO: this variable name thing here (and in other expressions) is a hack and should be fixed\r
+               sb.append("\t" + parent.getModelicaName() + (range.equals("[:]") ? "" : range) + " = " + \r
+                               instance() + "." + ModelicaWriter.getDelayValve(order) + ";\n");\r
+               \r
+               return sb.toString();\r
+       }\r
+\r
+       @Override\r
+       public String getExpression() {\r
+               return "This + is + not + a + parameter + at + any + time";\r
+       }\r
+\r
+       @Override\r
+       public String getModelicaExpression() {\r
+               return getExpression();\r
+       }\r
+\r
+       @Override\r
+       public String validateUnits(ReadGraph graph, SysdynModel model) {\r
+               if(parent.getUnit() == null)\r
+                       return "Unit not defined for " + parent.getName();\r
+\r
+               String result =  UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), equation);\r
+               if(result == null)\r
+                       result =  UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), initialValue);\r
+               if(result == null)\r
+                       result =  UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), UnitUtils.getTimeUnit(graph, model), delayTime);\r
+\r
+               return result;\r
+       }\r
+\r
+       public int getOrder() {\r
+               return order;\r
+       }\r
+\r
+       private String instance() {\r
+               // construct an identifier for this expression based on the array \r
+               // indices if necessary\r
+               String identifier;\r
+               if (getArrayRange() != null && !getArrayRange().isEmpty()) {\r
+                       identifier = IndexUtils.rangeToIndexes(parent, getArrayRange()).replaceAll("[\\[\\]{},]", "_");\r
+               }\r
+               else {\r
+                       identifier = "_";\r
+               }\r
+               return parent.getModelicaName() + identifier + "instance";\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/Expression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/Expression.java
new file mode 100644 (file)
index 0000000..7463bfc
--- /dev/null
@@ -0,0 +1,95 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.objmap.annotations.RelatedElement;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.utils.UnitUtils;\r
+\r
+/**\r
+ * Abstract class for any expression\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public abstract class Expression implements IExpression {\r
+        \r
+    @RelatedValue(SysdynResource.URIs.Expression_arrayRange)\r
+    private String range;\r
+    \r
+    @RelatedElement(Layer0.URIs.PartOf)\r
+    protected IndependentVariable parent;\r
+\r
+    @Override\r
+    public String getEquation() {\r
+        return null;\r
+    }\r
+    \r
+    @Override\r
+    public String getInitialEquation() {\r
+        return null;\r
+    }\r
+    \r
+    @Override\r
+    public String getDeclarationAddition() {\r
+        return null;\r
+    }\r
+\r
+    @Override\r
+    public String getExpression() {\r
+        return null;\r
+    }\r
+    \r
+    /**\r
+     * Get Modelica compliant expression\r
+     * @return The expression with spaces (' ') replaced with \r
+     * underscore characters ('_')\r
+     */\r
+    public String getModelicaExpression() {\r
+        return null;\r
+    }\r
+    \r
+    @Override\r
+    public String getArrayRange() {\r
+       if(range == null)\r
+               return "";\r
+       else\r
+               return range;\r
+    }\r
+\r
+    @Override\r
+    public String validateUnits() {\r
+        return validateUnits(null, null);\r
+    }\r
+    \r
+    @Override\r
+    public String validateUnits(ReadGraph graph, SysdynModel model) {\r
+        return UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), getExpression());\r
+    }\r
+    \r
+    @Override\r
+    public IndependentVariable getParent() {\r
+        return parent;\r
+    }\r
+    \r
+    @Override\r
+    public String getDocumentationExpression(ReadGraph graph) throws DatabaseException {\r
+        return getEquation();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/IExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/IExpression.java
new file mode 100644 (file)
index 0000000..58de03c
--- /dev/null
@@ -0,0 +1,87 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+\r
+\r
+/**\r
+ * Interface for all expressions in System Dynamics models\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public interface IExpression {\r
+\r
+    /**\r
+     * Get any possible additions to variable declaration.\r
+     * @return additions or null\r
+     */\r
+    String getDeclarationAddition();\r
+    \r
+    /**\r
+     * Initial value for this variable and expression\r
+     * @return initial value or null\r
+     */\r
+    String getInitialEquation();\r
+    \r
+    /**\r
+     * Get the actual equation of this expression\r
+     * @return equation or null\r
+     */\r
+    String getEquation();\r
+    \r
+    /**\r
+     * Get the range of this expression\r
+     * @return Range or null if not multidimensional\r
+     */\r
+    String getArrayRange();\r
+    \r
+    /**\r
+     * Get the plain (possibly unformatted) expression from this expression. (type variable = EXPRESSION ;\n)\r
+     * @return \r
+     */\r
+    String getExpression();\r
+    \r
+    \r
+    /**\r
+     * Match the units of this expression to units of its variable\r
+     * @return null if match, Error message otherwise\r
+     */\r
+    String validateUnits();\r
+    \r
+    /**\r
+     * Match the units of this expression to units of its variable. \r
+     * \r
+     * Requests units of referred variables for request listening\r
+     * @param graph ReadGraph\r
+     * @param model SysdynModel (with mapping)\r
+     * @return null if match, ERror message otherwise\r
+     */\r
+    String validateUnits(ReadGraph graph, SysdynModel model);\r
+    \r
+    /**\r
+     * Get the owner of this expression\r
+     * @return owner of this expression\r
+     */\r
+    IndependentVariable getParent();\r
+    \r
+    \r
+    /**\r
+     * Get the representation of this expression to web documentation\r
+     * @return\r
+     */\r
+    String getDocumentationExpression(ReadGraph graph) throws DatabaseException;\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/LookupExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/LookupExpression.java
new file mode 100644 (file)
index 0000000..5d5b4d8
--- /dev/null
@@ -0,0 +1,20 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+@GraphType(SysdynResource.URIs.LookupExpression)\r
+public class LookupExpression extends Expression {\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/NormalExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/NormalExpression.java
new file mode 100644 (file)
index 0000000..696854e
--- /dev/null
@@ -0,0 +1,51 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.utils.FormatUtils;\r
+import org.simantics.sysdyn.representation.utils.IndexUtils;\r
+\r
+/**\r
+ * Representation of a normal (auxiliary) expression\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.NormalExpression)\r
+public class NormalExpression extends Expression {\r
+\r
+    @RelatedValue(SysdynResource.URIs.Expression_equation)\r
+    private String equation;\r
+    \r
+    @Override\r
+    public String getExpression() {\r
+        return equation;\r
+    }\r
+    \r
+    @Override\r
+    public String getModelicaExpression() {\r
+        return FormatUtils.replaceWhitespace(getExpression());\r
+    }\r
+    \r
+    @Override\r
+    public String getEquation() {\r
+       String equation = FormatUtils.replaceWhitespace(this.equation);\r
+       equation = FormatUtils.formatExpressionForModelica(parent, equation);\r
+       String range = IndexUtils.rangeToIndexes(parent, this.getArrayRange());\r
+        return "    " + parent.getModelicaName() + (range.equals("[:]") ? "" : range) + " = " + equation + ";\n";\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ParameterExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/ParameterExpression.java
new file mode 100644 (file)
index 0000000..5385212
--- /dev/null
@@ -0,0 +1,62 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.representation.utils.FormatUtils;\r
+import org.simantics.sysdyn.representation.utils.IndexUtils;\r
+\r
+/**\r
+ * Representation of a parameter expression\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.ParameterExpression)\r
+public class ParameterExpression extends Expression {\r
+    \r
+    @RelatedValue(SysdynResource.URIs.Expression_equation)\r
+    private String equation;\r
+    \r
+    @Override\r
+    public String getExpression() {\r
+        return equation + " /* Actual value read from init file */";\r
+    }\r
+    \r
+    @Override\r
+    public String getModelicaExpression() {\r
+       String equation = FormatUtils.replaceWhitespace(this.equation);\r
+        return equation + " /* Actual value read from init file */";\r
+    }\r
+\r
+    \r
+    /**\r
+     * Used when the expression is a part of an array variable. Then it is like a normal auxiliary.\r
+     */\r
+    @Override\r
+    public String getEquation() {\r
+       String equation = FormatUtils.replaceWhitespace(this.equation);\r
+       String range = IndexUtils.rangeToIndexes(parent, this.getArrayRange());\r
+       return "    " + parent.getModelicaName() + (range.equals("[:]") ? "" : range) + " = " + equation + ";\n";\r
+    };\r
+    \r
+    public Double getValue() {\r
+       try {\r
+               return Double.parseDouble(equation);\r
+       } catch(NumberFormatException e) {\r
+               return null;\r
+       }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/StockExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/StockExpression.java
new file mode 100644 (file)
index 0000000..3fb5f59
--- /dev/null
@@ -0,0 +1,157 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Valve;\r
+import org.simantics.sysdyn.representation.utils.FormatUtils;\r
+import org.simantics.sysdyn.representation.utils.IndexUtils;\r
+import org.simantics.sysdyn.representation.utils.UnitUtils;\r
+\r
+/**\r
+ * Class representing a stock expression in a variable\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.StockExpression)\r
+public class StockExpression extends Expression {\r
+\r
+       @RelatedValue(SysdynResource.URIs.StockExpression_initialEquation)\r
+    private String initialEquation;\r
+\r
+       @RelatedValue(SysdynResource.URIs.StockExpression_integralEquation)\r
+    private String integralEquation;\r
+\r
+    @Override\r
+    public String getExpression() {\r
+       return initialEquation;\r
+    }\r
+\r
+    @Override\r
+    public String getModelicaExpression() {\r
+        return FormatUtils.replaceWhitespace(initialEquation);\r
+    }\r
+    \r
+    @Override\r
+    public String getEquation() {\r
+        return getEquation(true);\r
+    }\r
+    \r
+    private String getEquation(boolean modelicaEquation) {\r
+        \r
+        // Build range e.g. Stock[2,3]\r
+       String range = IndexUtils.rangeToIndexes(parent, this.getArrayRange());\r
+       \r
+       // Stock equation is always der(Stock)\r
+        StringBuilder b = new StringBuilder();\r
+        b.append("    der(")\r
+        .append(parent.getModelicaName() + (range.equals("[:]") ? "" : range))\r
+        .append(") = ");\r
+        \r
+        if (integralEquation != null) {\r
+               if (modelicaEquation) {\r
+                       String equation = FormatUtils.replaceWhitespace(this.integralEquation);\r
+                       equation = FormatUtils.formatExpressionForModelica(parent, equation);\r
+               b.append(equation).append(";\n");\r
+               } else {\r
+                       b.append(integralEquation).append(";\n");\r
+               }\r
+        } else {\r
+               // Stock equation is formed automatically using incoming and outgoing flows (actually the nearest valves in those flows)\r
+                   ArrayList<Valve> incoming = ((Stock)parent).getIncomingValves();\r
+                   ArrayList<Valve> outgoing = ((Stock)parent).getOutgoingValves();\r
+                   if(incoming.isEmpty() && outgoing.isEmpty()) {\r
+                       // No connections, add 0 for each array index if any.\r
+                       ArrayList<Enumeration> enumerations = parent.getArrayIndexes();\r
+                       if(enumerations == null || enumerations.isEmpty()) {\r
+                           b.append(" 0.0");\r
+                       } else {\r
+                           b.append(" zeros(");\r
+                           for(int i = 0; i < enumerations.size(); i++) {\r
+                               b.append(modelicaEquation ? enumerations.get(i).getModelicaName() : enumerations.get(i).getName() + ".size");\r
+                               if(i != enumerations.size() - 1)\r
+                                   b.append(", ");\r
+                           }\r
+                           b.append(")");\r
+                       }\r
+               \r
+                   } else {\r
+                       // incoming valves add and outgoing valves reduce the stock\r
+                       for(Valve valve : outgoing)\r
+                           b.append("\n        - ").append(modelicaEquation ? valve.getModelicaName() : valve.getName() + range);\r
+                       for(Valve valve : incoming)\r
+                           b.append("\n        + ").append(modelicaEquation ? valve.getModelicaName() : valve.getName() + range);\r
+                   }\r
+                   b.append(";\n");\r
+        }\r
+           return b.toString();\r
+    }\r
+    @Override\r
+    public String getInitialEquation() {\r
+       String initialEquation = FormatUtils.replaceWhitespace(this.initialEquation);\r
+        // format the initial equation for modelica execution \r
+        String equation = FormatUtils.formatExpressionForModelica(parent, initialEquation, false);\r
+       String range = IndexUtils.rangeToIndexes(parent, this.getArrayRange());\r
+       return "    " + parent.getModelicaName() + (range != null ? range : "") + " = " + equation + ";\n";\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Return Double representation of the initial equation for given variable\r
+     * \r
+     * @param variable\r
+     * @return Double representing the initial equation or null if initial equation is not a double\r
+     */\r
+    public Double getStartValue() {\r
+       Double value = null;\r
+       ArrayList<IExpression> expressions = parent.getExpressions();\r
+       if(expressions.size() == 1) {\r
+               IExpression e = expressions.get(0);\r
+            if(e.getInitialEquation() == null) {\r
+                try {\r
+                    value = Double.parseDouble(initialEquation);\r
+                } catch(NumberFormatException e1) {\r
+                    return null;\r
+                }\r
+            }\r
+       }\r
+       return value;\r
+    }\r
+\r
+    \r
+    @Override\r
+    public String validateUnits(ReadGraph graph, SysdynModel model) {\r
+        String result = UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), initialEquation);\r
+        if(result == null) {\r
+               String integralEquation = getEquation(false);\r
+            if(integralEquation.contains("="))\r
+                result = UnitUtils.matchUnits(\r
+                        graph, \r
+                        model, \r
+                        parent.getParentConfiguration(), \r
+                        parent.getUnit(), \r
+                        "(" + integralEquation.substring(integralEquation.indexOf("=") + 1, integralEquation.lastIndexOf(";")) +") * time");\r
+        }\r
+        \r
+        return result;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/WithLookupExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/WithLookupExpression.java
new file mode 100644 (file)
index 0000000..82acd99
--- /dev/null
@@ -0,0 +1,192 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.expressions;\r
+\r
+import java.awt.geom.Rectangle2D;\r
+import java.io.IOException;\r
+import java.io.StringWriter;\r
+\r
+import org.jfree.chart.ChartFactory;\r
+import org.jfree.chart.JFreeChart;\r
+import org.jfree.chart.plot.PlotOrientation;\r
+import org.jfree.data.xy.DefaultXYDataset;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.jfreechart.chart.ChartUtils;\r
+import org.simantics.objmap.annotations.GraphType;\r
+import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.spreadsheet.Range;\r
+import org.simantics.spreadsheet.SheetVariables;\r
+import org.simantics.spreadsheet.util.SpreadsheetUtils;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Model;\r
+import org.simantics.sysdyn.representation.Sheet;\r
+import org.simantics.sysdyn.representation.utils.FormatUtils;\r
+import org.simantics.sysdyn.representation.utils.IndexUtils;\r
+import org.simantics.sysdyn.representation.utils.SheetFormatUtils;\r
+import org.simantics.sysdyn.representation.utils.UnitUtils;\r
+\r
+/**\r
+ * Representation of a withlookup expression\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+@GraphType(SysdynResource.URIs.WithLookupExpression)\r
+public class WithLookupExpression extends Expression {\r
+\r
+    @RelatedValue(SysdynResource.URIs.WithLookupExpression_lookup)\r
+    private String lookupTable;\r
+    @RelatedValue(SysdynResource.URIs.WithLookupExpression_expression)\r
+    private String equation;\r
+\r
+    @Override\r
+    public String getEquation() {\r
+       String equation = FormatUtils.replaceWhitespace(this.equation);\r
+       equation = FormatUtils.formatExpressionForModelica(parent, equation);\r
+        String range = IndexUtils.rangeToIndexes(parent, this.getArrayRange());\r
+\r
+        return \r
+                "    " + parent.getModelicaName() + (range.equals("[:]") ? "" : range) + " = interpolate(" + equation + ", " + SheetFormatUtils.reformatSheetReferences(parent, lookupTable) + ");\n";\r
+    }\r
+\r
+    @Override\r
+    public String getModelicaExpression() {\r
+       return "interpolate(" + FormatUtils.replaceWhitespace(equation) + ", " + lookupTable + ")";\r
+    }\r
+    \r
+    @Override\r
+    public String getExpression() {\r
+        return "interpolate(" + equation + ", " + lookupTable + ")";\r
+    }\r
+\r
+    @Override\r
+    public String validateUnits(ReadGraph graph, SysdynModel model) {\r
+        if(parent.getUnit() == null)\r
+            return "Unit not defined for " + parent.getName();\r
+\r
+        String result = UnitUtils.expressionUnitsValid(graph, model, parent.getParentConfiguration(), equation);\r
+        if(result == null) {\r
+            result = UnitUtils.matchUnits(graph, model, parent.getParentConfiguration(), parent.getUnit(), lookupTable);\r
+        }\r
+\r
+        return result;\r
+    }\r
+\r
+    @Override\r
+    public String getDocumentationExpression(ReadGraph graph) throws DatabaseException {\r
+        String expression = super.getDocumentationExpression(graph);\r
+\r
+        // assume lookup table has format: {{1,2},{3,4}}\r
+        String table = lookupTable;\r
+\r
+        Sheet sheet = null;\r
+        if(table.matches("[a-zA-Z0-9]*\\([a-zA-Z0-9:]*\\)")) {\r
+            // try if it is a sheet reference\r
+            String name = table.substring(0, table.indexOf("("));\r
+            String range = table.substring(table.indexOf("(") + 1, table.indexOf(")"));\r
+            IndependentVariable independentVariable = getParent();\r
+            Configuration conf = independentVariable.getParentConfiguration();\r
+            Model model = conf.getModel();\r
+\r
+            if(model == null) {\r
+                Object parent = conf.getModuleType().getParent();\r
+                if(parent instanceof Model) {\r
+                    model = (Model)parent;\r
+                }\r
+            }\r
+            \r
+            if(model != null) {\r
+                for(IElement e : model.getModelConfiguration().getElements()) {\r
+                    if(e instanceof Sheet && name.equals(((Sheet)e).getName())) {\r
+                        sheet = (Sheet)e;\r
+                        Variable v = Variables.getVariable(graph, sheet.getResource());\r
+                        Variable rangeVariable = v.getChild(graph, range);\r
+                        Range r = SpreadsheetUtils.decodeRange(range);\r
+                        if(r.endColumn - r.startColumn == 1) {\r
+                            String[][] rangeCells = rangeVariable.getPropertyValue(graph, SheetVariables.RANGE_CELL_NAMES);\r
+                            StringBuilder sb = new StringBuilder();\r
+                            boolean firstRow = true;\r
+                            for(int i = 0; i < rangeCells.length; i++) {\r
+                                if(!firstRow)\r
+                                    sb.append(",");\r
+                                firstRow = false;\r
+\r
+                                boolean firstColumn = true;\r
+                                for(int j = 0; j < rangeCells[i].length; j++) {\r
+                                    if(!firstColumn)\r
+                                        sb.append(",");\r
+                                    firstColumn = false;\r
+                                    sb.append(sheet.getCells().get(rangeCells[i][j]));\r
+                                }\r
+                            }\r
+                            table = sb.toString();\r
+\r
+                        }\r
+                        break;\r
+                    }\r
+                }\r
+            }\r
+\r
+            if(sheet != null) {\r
+\r
+            }\r
+        }\r
+\r
+        table = table.replace("{", "");\r
+        table = table.replace("}", "");\r
+        String[] split = table.split(",");\r
+        double[] x = new double[split.length / 2];\r
+        double[] y = new double[split.length / 2];\r
+\r
+        try {\r
+            for(int i = 0; i < split.length / 2; i++) {\r
+                x[i] = Double.parseDouble(split[i*2]);\r
+                y[i] = Double.parseDouble(split[i*2+1]);\r
+            }\r
+\r
+            DefaultXYDataset dataset = new DefaultXYDataset();\r
+            dataset.addSeries("lookup", new double[][] {y, x});\r
+            JFreeChart chart = ChartFactory.createXYLineChart(\r
+                    "",                         // chart title\r
+                    "",                         // domain axis label\r
+                    "",                         // range axis label\r
+                    dataset,                    // data\r
+                    PlotOrientation.HORIZONTAL, // Orientation\r
+                    false,                      // include legend\r
+                    false,                      // tooltips\r
+                    false                       // urls\r
+                    );\r
+\r
+            StringWriter writer = new StringWriter();\r
+            ChartUtils.writeSVG(chart, new Rectangle2D.Double(0, 0, 200, 100), writer);\r
+            writer.flush();\r
+            String svg = writer.toString();\r
+            writer.close();\r
+            svg = svg.substring(svg.indexOf("<svg"));\r
+            svg = svg.replaceAll("[\r\n]+", "");\r
+            expression = expression + "<div>" + svg + "</div>";\r
+        } catch (NumberFormatException e) {\r
+\r
+        } catch (IOException e) {\r
+        }\r
+\r
+        return expression;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/FormatUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/FormatUtils.java
new file mode 100644 (file)
index 0000000..d05d954
--- /dev/null
@@ -0,0 +1,157 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.utils;\r
+\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Variability;\r
+import org.simantics.sysdyn.representation.Variable;\r
+\r
+public class FormatUtils {\r
+\r
+       /**\r
+        * Formats expressions for OpenModelica. Indexes are changed into numbers.\r
+        * @param variable Variable\r
+        * @param expression Expression\r
+        * @return Formatted expression\r
+        */\r
+       public static String formatExpressionForModelica(Variable variable, String expression) {\r
+               return formatExpressionForModelica(variable, expression, true);\r
+       }\r
+\r
+       /**\r
+        * Formats expressions for OpenModelica. Indexes are changed into numbers.\r
+        * \r
+        * @param variable Variable\r
+        * @param expression Expression\r
+        * @param gameAdditions Add game hacks?\r
+        * @return Formatted expression\r
+        */\r
+       public static String formatExpressionForModelica(Variable variable, String expression, boolean gameAdditions) {\r
+               String modified = expression;\r
+               if(gameAdditions) \r
+                       // FIXME: A hack. This is needed for fmu simulation to notice changes in parameters.\r
+                       // OpenModelica supports FMI 1.0, which does not support tunable variables. Problem should be fixed with FMI 2.0\r
+                       modified = addGameExperimentAdditions(variable, modified);\r
+               modified = IndexUtils.equationRangesToIndexes(variable, modified);\r
+               modified = SheetFormatUtils.reformatSheetReferences(variable, modified);\r
+               return modified;\r
+       }\r
+\r
+\r
+       /**\r
+        * Adds hacks for variables to work with game experiments.\r
+        * <p>\r
+        * The hack is as follows. If the expression contains a reference to a parameter, add the following around the \r
+        * expression: \r
+        * <p><b>\r
+        * if initial() or parameter < 0 or parameter >= 0 then EXPRESSION else pre(variable)\r
+        * </b><p>\r
+        * The hack is added only if there is a reference to a parameter.\r
+        * \r
+        * @param variable Variable\r
+        * @param expression Expression\r
+        * @return Expression with added hacks for game experiments\r
+        */\r
+       private static String addGameExperimentAdditions(Variable variable, String expression) {\r
+               if(variable == null || !(variable instanceof IndependentVariable))\r
+                       return expression;\r
+               if(!RepresentationUtils.isPartOfGameExperiment(variable))\r
+                       return expression;\r
+\r
+               if(Variability.getVariability((IndependentVariable)variable).equals(Variability.CONTINUOUS)) {\r
+                       Variable reference = RepresentationUtils.getFirstGameVariableReference(variable, expression);\r
+                       if(reference != null) {\r
+                               String condition;\r
+                               \r
+                               boolean array = reference.getArrayIndexes() != null && \r
+                                       reference.getArrayIndexes() != null &&\r
+                                               !reference.getArrayIndexes().isEmpty();\r
+                               \r
+                               String refName = reference.getModelicaName();\r
+                               if(reference.getType().equals("Boolean")) {\r
+                                       condition= "if initial() or " + refName + " or not " +\r
+                                               refName + " then (";\r
+                               } else {\r
+                       if(array)\r
+                           refName = "sum(" + refName + ")";\r
+                                       condition= "if " + refName + " < 0 or " +\r
+                                               refName + " >= 0 then (";\r
+                               }\r
+                               \r
+                               String conditionEnd = ") else " + getZeros(variable);\r
+                               expression = condition + expression + conditionEnd;\r
+                       }\r
+\r
+               }\r
+               return expression;\r
+       }       \r
+\r
+       private static String getZeros(Variable variable) {\r
+           ArrayList<Enumeration> enumerations = variable.getArrayIndexes();\r
+           if(enumerations == null || enumerations.size() == 0)\r
+               return "0";\r
+           else {\r
+               StringBuilder sb = new StringBuilder();\r
+               sb.append("zeros(");\r
+               boolean first = true;\r
+               for(Enumeration e : enumerations) {\r
+                   if(!first)\r
+                       sb.append(", ");\r
+                   first = false;\r
+                   sb.append(e.getModelicaName() + ".size");\r
+               }\r
+               sb.append(")");\r
+               return sb.toString();\r
+           }\r
+       }\r
+       \r
+       /**\r
+        * Replaces each whitespace sequence with a single underscore character ('_').\r
+        * @param app String of which whitespace are replaced\r
+        * @return a new String with whitespace replaced\r
+        */\r
+    public static String replaceWhitespace(String app) {\r
+       String equation = app;\r
+       //String equation = FormatUtils.formatExpressionForModelica(variable, app, false);\r
+        ExpressionParser parser = new ExpressionParser(new StringReader(equation));\r
+       String modifiedEquation = new String(equation);\r
+\r
+        try {\r
+                       parser.expr();\r
+               } catch (ParseException e) {\r
+                       // TODO Auto-generated catch block\r
+                       e.printStackTrace();\r
+               }\r
+\r
+        // Collect all references\r
+        ArrayList<String> allReferences = new ArrayList<String>();\r
+        allReferences.addAll(parser.getReferences().keySet());\r
+        allReferences.addAll(parser.getFunctionCallReferences().keySet());\r
+        allReferences.addAll(parser.getEnumerationReferences().keySet());\r
+        \r
+        // Replace whitespace sequences with underscore characters\r
+        for (String reference : allReferences) {\r
+               String regex = reference.replaceAll(" ", "(_|\\\\s+)");\r
+               String replacement = reference.replaceAll(" ", "_");\r
+               modifiedEquation = modifiedEquation.replaceAll(regex, replacement);\r
+        }\r
+        \r
+               return modifiedEquation;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/IndexUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/IndexUtils.java
new file mode 100644 (file)
index 0000000..360ffe1
--- /dev/null
@@ -0,0 +1,144 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.utils;\r
+\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.StringTokenizer;\r
+\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser.ForRange;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.EnumerationIndex;\r
+import org.simantics.sysdyn.representation.Variable;\r
+\r
+public class IndexUtils {\r
+\r
+       public static int indexOf(Enumeration enumeration, String index) {\r
+               int result = -1;\r
+               ArrayList<EnumerationIndex> indexes = enumeration.getEnumerationIndexes();\r
+               for(int i = 0; i < indexes.size(); i++) {\r
+                       if(indexes.get(i).getName().equals(index)) {\r
+                               result = i  +1;\r
+                               break;\r
+                       }\r
+               }\r
+               return result;\r
+       }\r
+\r
+\r
+       public static String rangeToIndexes(Variable variable, String range) {\r
+               if(variable == null)\r
+                       return range;\r
+               StringBuilder sb = new StringBuilder();\r
+               if(variable.getArrayIndexes() == null || range == null)\r
+                       return "";\r
+               ArrayList<Enumeration> enumerations = variable.getArrayIndexes();\r
+               StringTokenizer st = new StringTokenizer(range, "{}[]:,", true);\r
+               int index = 0;\r
+               boolean insideCurlyBrackets = false;\r
+               while(st.hasMoreTokens()) {\r
+                       String rangeToken = st.nextToken().trim();\r
+                       if(rangeToken.matches("[\\[\\]:]")) {\r
+                               sb.append(rangeToken);\r
+                       } else if(rangeToken.matches("[\\{]")) {\r
+                               sb.append(rangeToken);\r
+                               insideCurlyBrackets = true;\r
+                       } else if(rangeToken.matches("[\\}]")) {\r
+                               sb.append(rangeToken);\r
+                               insideCurlyBrackets = false;\r
+                       } else if (rangeToken.equals(",")) {\r
+                           sb.append(rangeToken);\r
+                           if (!insideCurlyBrackets) {\r
+                               index++;\r
+                           }\r
+                       } else if(index < enumerations.size()) {\r
+                           if(rangeToken.equals(enumerations.get(index).getName())) {\r
+                               sb.append(":");\r
+                           } else {\r
+                               int i = indexOf(enumerations.get(index), rangeToken);\r
+                               if(i >= 0)\r
+                                   sb.append(i);\r
+                               else\r
+                                   sb.append(rangeToken);\r
+                           }\r
+                       } else {\r
+                           sb.append(rangeToken);\r
+                       }\r
+               }\r
+               return sb.toString();\r
+       }\r
+\r
+       private static String fixForRangeEnumerations(Variable variable, String equation) {\r
+               ExpressionParser parser = new ExpressionParser(new StringReader(equation));\r
+               try {\r
+                       parser.expr();\r
+                       for(ForRange forRange : parser.getForRanges()) {\r
+                               // Concat the tokens that form the range, this is\r
+                               // necessary for names that have whitespace.\r
+                               String rangeString = new String(forRange.start.image);\r
+                               Token temp = forRange.start;\r
+                               while (!temp.equals(forRange.end)) {\r
+                                       temp = temp.next;\r
+                                       rangeString += " " + temp.image;\r
+                               }\r
+                               Variable v = RepresentationUtils.getVariable(variable.getParentConfiguration(), rangeString);\r
+                               if(v instanceof Enumeration) {\r
+                                       equation = equation.replaceAll("in[\\s]*" + rangeString + "($|[^\\.])", \r
+                                                                                                  "in " + rangeString.replaceAll(" ", "_") + ".elements$1");\r
+                               }\r
+                       }\r
+               } catch (ParseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               return equation;\r
+       }\r
+\r
+       public static String equationRangesToIndexes(Variable variable, String equation) {\r
+               if(equation == null) return equation;\r
+\r
+               if(equation.contains("[")) {\r
+                       StringBuilder result = new StringBuilder();\r
+                       String delimiters = "+-*/(){}[],. ";\r
+                       StringTokenizer st = new StringTokenizer(equation, delimiters, true);\r
+                       String prevToken = st.nextToken();\r
+                       result.append(prevToken);\r
+                       while (st.hasMoreTokens()) {\r
+                               String nextToken = st.nextToken();\r
+                               if (nextToken.equals("[")) {\r
+                                       StringBuilder range = new StringBuilder();\r
+                                       range.append("[");\r
+                                       String rangeToken = st.nextToken();\r
+                                       while(!rangeToken.equals("]")) {\r
+                                               range.append(rangeToken);\r
+                                               rangeToken = st.nextToken();\r
+                                       }\r
+                                       range.append("]");\r
+\r
+                                       Variable prevVar = RepresentationUtils.getVariable(variable.getParentConfiguration(), prevToken.trim());\r
+                                       result.append(rangeToIndexes(prevVar, range.toString()));\r
+                               } else {\r
+                                       result.append(nextToken);\r
+                               }\r
+                               prevToken = nextToken;\r
+                       }\r
+                       equation = fixForRangeEnumerations(variable, result.toString());\r
+               } else if(equation.contains("{")){\r
+                       // Cases where there are {something for i in Enum} without [] brackets\r
+                       equation = fixForRangeEnumerations(variable, equation);\r
+               }\r
+\r
+               return equation;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/RepresentationUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/RepresentationUtils.java
new file mode 100644 (file)
index 0000000..cac1aea
--- /dev/null
@@ -0,0 +1,196 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.utils;\r
+\r
+import java.io.StringReader;\r
+import java.util.Set;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.project.IProject;\r
+import org.simantics.simulation.experiment.IExperiment;\r
+import org.simantics.simulation.project.IExperimentManager;\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Variability;\r
+import org.simantics.sysdyn.representation.Variable;\r
+\r
+public class RepresentationUtils {\r
+\r
+       /**\r
+        * Returns true, if there is an active experiment and the active experiment\r
+        * is a game experiment\r
+        * @return true, if there is an active experiment and the active experiment\r
+        * is a game experiment\r
+        */\r
+       public static boolean isGameExperimentActive() {\r
+               // Find active experiment\r
+               IProject project = Simantics.peekProject();\r
+               if (project == null)\r
+                       return false;\r
+\r
+               IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
+\r
+               IExperiment active = manager.getActiveExperiment();\r
+               if (active instanceof SysdynGameExperimentBase)\r
+                       return true;\r
+               else\r
+                       return false;\r
+       }\r
+\r
+       /**\r
+        * Find out if a variable is part of a game configuration. (This means that the variable is a \r
+        * part of a game experiment)\r
+        * @param variable\r
+        * @return\r
+        */\r
+       public static boolean isPartOfGameExperiment(Variable variable) {\r
+               Configuration conf = variable.getParentConfiguration();\r
+               if(conf != null)\r
+                       return conf.isGameConfiguration();\r
+               else\r
+                       return false;\r
+       }\r
+\r
+       /**\r
+        * Find out if a module is part of a game configuration. (This means that the module is a \r
+        * part of a game experiment)\r
+        * @param variable\r
+        * @return\r
+        */\r
+       public static boolean isPartOfGameExperiment(Module module) {\r
+               Configuration conf = module.getParentConfiguration();\r
+               if(conf != null)\r
+                       return conf.isGameConfiguration();\r
+               else\r
+                       return false;\r
+       }\r
+\r
+\r
+       /**\r
+        * Retrieves the first reference to a game variable (parameter variable) in the given\r
+        * expression or null if there is no reference to a game variable.\r
+        * <p>\r
+        * Current requirements for a game variable: Variable contains only one parameter expression.\r
+        * @param variable Variable that has the expression\r
+        * @param expression Expression\r
+        * @return The name of the first referred game variable or null if there is no such reference\r
+        */\r
+       public static Variable getFirstGameVariableReference(Variable variable, String expression) {\r
+               String equation = FormatUtils.formatExpressionForModelica(variable, expression, false);\r
+               ExpressionParser parser = new ExpressionParser(new StringReader(equation));\r
+               Variable result = null;\r
+               try {\r
+                       parser.expr();\r
+                       if(!parser.getReferences().isEmpty()) {\r
+                               Set<String> references = parser.getReferences().keySet();\r
+                               // Go through each reference\r
+                               for(String reference : references) {\r
+                                       if((result = getGameVariableReference(variable, variable.getParentConfiguration(), reference)) != null) {\r
+                                               break;\r
+                                       }\r
+                               }\r
+                       }\r
+               } catch (ParseException e) {\r
+               }\r
+               return result;\r
+       }\r
+\r
+       /**\r
+        * Test if a given reference is a game variable\r
+        * @param variable Variable that contains the reference\r
+        * @param configuration Configuration where the reference is searched in\r
+        * @param reference Reference variable name\r
+        * @return true if reference is a game variable, false otherwise\r
+        */\r
+       private static Variable getGameVariableReference(Variable variable, Configuration configuration, String reference) {\r
+\r
+               String r = reference.split("\\.")[0]; \r
+               for(IElement element : configuration.getElements()) {\r
+                       if(element instanceof Module) {\r
+                               Module m = (Module)element;\r
+                               if(r.equals(m.getName())) {\r
+                                       if(!reference.contains(".")) {\r
+                                               // The reference contains only modules, implementation feature for the expression parser\r
+                                               return null;\r
+                                       }\r
+                                       Configuration moduleConfiguration = m.getType().getConfiguration();\r
+                                       return getGameVariableReference(variable, moduleConfiguration, reference.substring(reference.indexOf(".") + 1));\r
+                               }\r
+                       } else if(element instanceof IndependentVariable && !(element instanceof Stock)) {\r
+                               IndependentVariable v = (IndependentVariable)element;\r
+                               if(r.equals(v.getName())) { \r
+                                       if(v.getName().equals(variable.getName())) {\r
+                                               return null;// Reference to self.\r
+                                       } else {\r
+                                               if(Variability.PARAMETER.equals(Variability.getVariability(v, false, null))) {\r
+                                                       return v;\r
+                                               } else {\r
+                                                       return null;\r
+                                               }\r
+\r
+                                               /*\r
+                                               if(v.getExpressions() == null || v.getExpressions().getExpressions().size() > 1)\r
+                                                       return null;\r
+\r
+                                               IExpression e = v.getExpressions().getExpressions().get(0);\r
+\r
+                                               if(e instanceof ParameterExpression)\r
+                                                       return v;\r
+                                               */\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               return null;\r
+       }\r
+\r
+\r
+       public static Variable getVariable(Configuration configuration, String name) {\r
+               Configuration conf = configuration;\r
+               // This function seems to be used with both whitespaced and\r
+               // underscored versions of the variable name.\r
+               String whitespacedName = name.replace('_', ' ');\r
+               String[] components = whitespacedName.split("\\.");\r
+\r
+               for(String component : components) {\r
+\r
+                       Configuration newConf = null;\r
+\r
+                       for(IElement element : conf.getElements()) {\r
+                               if(element instanceof Variable) {\r
+                                       Variable variable = (Variable) element;\r
+                                       if(variable.getName().equals(component)) {\r
+                                               return variable;\r
+                                       }\r
+                               } else if(element instanceof Module) {\r
+                                       Module m = (Module)element;\r
+                                       if(m.getName().equals(component)) {\r
+                                               newConf = m.getType().getConfiguration();\r
+                                       }\r
+                               }\r
+                       }\r
+\r
+                       // If variable or configuration has not been found, return null\r
+                       if(newConf == null)\r
+                               return null;\r
+               }\r
+\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/SheetFormatUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/SheetFormatUtils.java
new file mode 100644 (file)
index 0000000..19b14ce
--- /dev/null
@@ -0,0 +1,113 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.utils;\r
+\r
+import java.io.StringReader;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
+import org.simantics.sysdyn.expressionParser.Token;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Model;\r
+import org.simantics.sysdyn.representation.ModuleType;\r
+import org.simantics.sysdyn.representation.Sheet;\r
+import org.simantics.sysdyn.representation.Variable;\r
+\r
+public class SheetFormatUtils {\r
+    \r
+    public static String reformatSheetReferences(Variable v, String expression) {\r
+        if(expression == null || !expression.contains("("))\r
+            return expression;\r
+        ExpressionParser parser = new ExpressionParser(new StringReader(expression));\r
+        try {\r
+            parser.expr();\r
+\r
+            HashMap<String, List<Token>> functionCalls = parser.getFunctionCallReferences();\r
+            for(String key : functionCalls.keySet()) {\r
+                String[] parts = key.split("\\.");\r
+                Object current = v.getParentConfiguration();\r
+                \r
+                // Hack. Sheets can currently exist only in models, not in module types.\r
+                ModuleType moduleType= ((Configuration)current).getModuleType();\r
+                if(moduleType != null) {\r
+                       if(moduleType.getParent() != null && moduleType.getParent() instanceof Model)\r
+                               current = ((Model)moduleType.getParent()).getModelConfiguration();\r
+                }\r
+                // end Hack.\r
+                \r
+                Object found = null;\r
+                for(int i = 0; i < parts.length && current != null; i++) {\r
+                    found = null;\r
+                    if(current instanceof Configuration) {\r
+                        for(IElement e : ((Configuration)current).getElements()) {\r
+                            if(e instanceof Configuration &&\r
+                                    ((Variable)e).getName().equals(parts[i])) {\r
+                                found = e;\r
+                                break;\r
+                            } else if(e instanceof Variable &&\r
+                                    ((Variable)e).getName().equals(parts[i])) {\r
+                                found = e;\r
+                                break;\r
+                            } \r
+                        }\r
+                    }\r
+                    current = found;\r
+                }\r
+                \r
+                if(current != null && current instanceof Sheet) {\r
+                    \r
+                    String tmp = "";\r
+                    int start = 0, end = 0, call = 0;\r
+                    String cellOrRange = null;\r
+                    while((call = expression.indexOf(key + "(", end)) >= 0) {\r
+                        start = expression.indexOf("(", call);\r
+                        \r
+                        tmp += expression.substring(end, start);\r
+                        \r
+                        end = expression.indexOf(")", start) + 1;\r
+                        if(start < 0 || end < 0 || end < start) {\r
+                            break;\r
+                        }\r
+                        cellOrRange = expression.substring(start, end);\r
+                        cellOrRange = cellOrRange.substring(1, cellOrRange.length() - 1);\r
+                        cellOrRange = cellOrRange.trim();\r
+                        cellOrRange = cellOrRange.replace(" ", "");\r
+                        \r
+                        Pattern p = Pattern.compile("[-\\+\\*\\/\\(\\)\\{\\}\\[\\],\\.\\t\\n\\r\\f]");\r
+                        Matcher m = p.matcher(cellOrRange);\r
+                        if (m.find() || cellOrRange.split(":").length > 2 || cellOrRange.length() == 0) {\r
+                            continue;\r
+                        }\r
+                        \r
+                        // Use the cell or range in the sheet.\r
+                        ((Sheet)current).use(cellOrRange);\r
+                        \r
+                        cellOrRange = cellOrRange.replace(":", "_");\r
+                        \r
+                        tmp += "." + cellOrRange;\r
+                    }\r
+                    tmp += expression.substring(end, expression.length());\r
+                    expression = tmp;\r
+                }\r
+            }\r
+\r
+        } catch (ParseException e) {\r
+        }\r
+        return expression;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/UnitUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/utils/UnitUtils.java
new file mode 100644 (file)
index 0000000..5b63087
--- /dev/null
@@ -0,0 +1,262 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.utils;\r
+\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Set;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.layer0.request.PossibleModel;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.Shadow;\r
+import org.simantics.sysdyn.representation.Variable;\r
+import org.simantics.sysdyn.unitParser.ParseException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.UnitParser;\r
+import org.simantics.sysdyn.unitParser.nodes.ComponentReferenceFull;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+public class UnitUtils {\r
+    \r
+    public static String expressionUnitsValid(ReadGraph graph, SysdynModel model, Configuration configuration, String expression) {\r
+        try {\r
+            StringReader reader = new StringReader(expression);\r
+            UnitParser parser = new UnitParser(reader);\r
+            System.out.println("expression " + expression);\r
+            UnitCheckingNode node = (UnitCheckingNode) parser.expr();\r
+            reader.close();\r
+            Set<String> components = UnitUtils.findComponents(node);\r
+            HashMap<String, String> units = UnitUtils.findUnits(graph, model, configuration, components);\r
+            \r
+            try {\r
+                node.getUnits(units, Function.getAllBuiltInFunctions(graph), allowEquivalents(graph, model));\r
+            } catch (UnitCheckingException e) {\r
+                return e.getMessage();\r
+            } catch (DatabaseException e) {\r
+                               e.printStackTrace();\r
+                       }\r
+        } catch (ParseException e) {\r
+               return "Cannot validate units: Syntax error in expression.";\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    /**\r
+     * Determine if the Unit Equivalents checkbox is selected \r
+     * @param graph\r
+     * @param model SysdynModel of which configuration is queried\r
+     * @return true iff equivalent units are allowed\r
+     * @throws DatabaseException\r
+     */\r
+    public static boolean allowEquivalents(ReadGraph graph, SysdynModel model) throws DatabaseException {\r
+       Resource modelResource = graph.syncRequest(new PossibleModel(model.getConfigurationResource()));\r
+               SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Resource unitIssueSource = graph.syncRequest(\r
+                new PossibleObjectWithType(modelResource, \r
+                        Layer0X.getInstance(graph).Activates, \r
+                        sr.Validations_Units_UnitIssueSource));\r
+        if(unitIssueSource == null)\r
+            return false;\r
+        \r
+        Boolean result = graph.getPossibleRelatedValue(unitIssueSource, sr.Validations_Units_UnitIssueSource_allowEquivalents, Bindings.BOOLEAN);\r
+        if(result == null)\r
+            result = false;\r
+        \r
+        return result;\r
+    }\r
+    \r
+    public static String matchUnits(ReadGraph graph, SysdynModel model, Configuration configuration, String unit, String expression) {\r
+        if(unit == null)\r
+            return "Unit not defined";\r
+        \r
+        try {\r
+            StringReader rightReader = new StringReader(expression);\r
+            UnitParser rightParser = new UnitParser(rightReader);\r
+            UnitCheckingNode right = (UnitCheckingNode) rightParser.expr();\r
+            rightReader.close();\r
+            Set<String> components = findComponents(right);\r
+            HashMap<String, String> units = findUnits(graph, model, configuration, components);\r
+       \r
+            try {\r
+                StringReader leftReader = new StringReader(unit);\r
+                   UnitParser leftParser = new UnitParser(leftReader);\r
+                   UnitCheckingNode left = (UnitCheckingNode) leftParser.expr();\r
+                   leftReader.close();\r
+                   \r
+                   try {\r
+                       ArrayList<Function> functions = Function.getAllBuiltInFunctions(graph);\r
+                       boolean allowEquivalents = allowEquivalents(graph, model);\r
+                       UnitResult rightUnits = right.getUnits(units, functions, allowEquivalents);\r
+                       UnitResult leftUnits = left.getUnits(null, functions, allowEquivalents);\r
+                       \r
+                       if(!rightUnits.equals(leftUnits))\r
+                           return leftUnits.getCleanFullUnit() + " != " + rightUnits.getCleanFullUnit();\r
+                   } catch (UnitCheckingException e) {\r
+                       return e.getMessage();\r
+                   } catch (DatabaseException e) {\r
+                                       e.printStackTrace();\r
+                               }\r
+            } catch (ParseException e) {\r
+               return "Syntax error in defined unit.";\r
+            }\r
+        } catch (ParseException e) {\r
+               return "Cannot validate units: Syntax error in expression.";\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    \r
+    public static HashMap<String, String> findUnits(ReadGraph graph, SysdynModel model, Configuration configuration, Set<String> components) {\r
+        HashMap<String, String> units = new HashMap<String, String>();\r
+        for(String component : components) {\r
+            Variable var = getElement(configuration, component);\r
+            if(var != null) {\r
+                \r
+                // Support listening, if graph and mapping exists\r
+                if(graph != null && model != null) {\r
+                       if (var instanceof Shadow)\r
+                               var = ((Shadow)var).getOriginal();\r
+                    Resource varResource = model.getMapping().inverseGet(var);\r
+                    if(varResource != null) {\r
+                        try {\r
+                            String unit = graph.getPossibleRelatedValue(varResource, SysdynResource.getInstance(graph).Variable_unit);\r
+                            if(unit != null) {\r
+                                units.put(component, unit);\r
+                            }\r
+                        } catch (ManyObjectsForFunctionalRelationException e) {\r
+                            e.printStackTrace();\r
+                        } catch (ServiceException e) {\r
+                            e.printStackTrace();\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        \r
+        units.put("time", getTimeUnit(graph, model));\r
+        \r
+        return units;\r
+    }\r
+    \r
+    public static String getTimeUnit(ReadGraph graph, SysdynModel model) {\r
+        try {\r
+            Resource modelResource = graph.syncRequest(new PossibleModel(model.getConfigurationResource()));\r
+            if(modelResource != null) {\r
+                String timeUnit = graph.getPossibleRelatedValue(modelResource, SysdynResource.getInstance(graph).SysdynModel_timeUnit);\r
+                if(timeUnit == null)\r
+                    timeUnit = "month";\r
+                return timeUnit;\r
+            }\r
+        } catch (ManyObjectsForFunctionalRelationException e) {\r
+            e.printStackTrace();\r
+        } catch (ServiceException e) {\r
+            e.printStackTrace();\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        return null;\r
+    }\r
+    \r
+    private static Variable getElement(Configuration configuration, String name) {\r
+        String[] elements = name.split("\\.");\r
+        String element = elements[0];\r
+        for(IElement e : configuration.getElements()) {\r
+            if(e instanceof Variable) {\r
+                Variable var = (Variable)e;\r
+                try {\r
+                       if (element.equals(var.getName()))\r
+                               return var;\r
+                } catch (NullPointerException npe) {\r
+                       npe.printStackTrace();\r
+                       System.out.println("See UnitUtils");\r
+                       return null;\r
+                }\r
+            } else if(e instanceof Module && elements.length > 1) {\r
+                Module mod = (Module)e;\r
+                if(mod.getName().equals(element)) {\r
+                    return getElement(mod.getType().getConfiguration(), name.substring(name.indexOf(".") + 1));\r
+                }\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    public static Set<String> findComponents(UnitCheckingNode node) {\r
+        HashSet<String> components = new HashSet<String>();\r
+        addComponents(node, components);\r
+        return components;\r
+        \r
+    }\r
+    \r
+    private static void addComponents(UnitCheckingNode node, HashSet<String> components) {\r
+        if(node instanceof ComponentReferenceFull) {\r
+            components.add(node.printNode());\r
+        } else {\r
+            for(int i = 0; i < node.jjtGetNumChildren(); i++) {\r
+                addComponents((UnitCheckingNode)node.jjtGetChild(i), components);\r
+            }\r
+        }\r
+    }\r
+    \r
+    \r
+    public static String matchUnits(String left, String right, ArrayList<Function> functions, boolean allowEquivalents) throws DatabaseException {\r
+        if(left == null || right == null || left.isEmpty() || right.isEmpty())\r
+            return "No unit defined";\r
+        \r
+        try {\r
+            StringReader leftReader = new StringReader(left);\r
+            UnitParser leftParser = new UnitParser(leftReader);\r
+            UnitCheckingNode leftNode = (UnitCheckingNode) leftParser.expr();\r
+            leftReader.close();\r
+            try {\r
+                   StringReader rightReader = new StringReader(right);\r
+                   UnitParser rightParser = new UnitParser(rightReader);\r
+                   UnitCheckingNode rightNode = (UnitCheckingNode) rightParser.expr();\r
+                   rightReader.close();\r
+       \r
+                   try {\r
+                       UnitResult leftUnits = leftNode.getUnits(null, functions, allowEquivalents);\r
+                       UnitResult rightUnits = rightNode.getUnits(null, functions, allowEquivalents);\r
+       \r
+                       if(!rightUnits.equals(leftUnits))\r
+                           return leftUnits.getCleanFullUnit() + " != " + rightUnits.getCleanFullUnit();\r
+                   } catch (UnitCheckingException e) {\r
+                       return e.getMessage();\r
+                   }\r
+            } catch (ParseException e) {\r
+               return "Cannot validate units: Syntax error in expression.";\r
+            }\r
+        } catch (ParseException e) {\r
+               return "Syntax error in defined unit.";\r
+        }\r
+        return null;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/visitors/ElementVisitorVoidAdapter.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/visitors/ElementVisitorVoidAdapter.java
new file mode 100644 (file)
index 0000000..6b5465a
--- /dev/null
@@ -0,0 +1,91 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.visitors;\r
+\r
+import org.simantics.sysdyn.representation.Auxiliary;\r
+import org.simantics.sysdyn.representation.Book;\r
+import org.simantics.sysdyn.representation.Cloud;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.Dependency;\r
+import org.simantics.sysdyn.representation.DiagramContainerDummy;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.Flow;\r
+import org.simantics.sysdyn.representation.Input;\r
+import org.simantics.sysdyn.representation.LibraryDummy;\r
+import org.simantics.sysdyn.representation.Loop;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Valve;\r
+import org.simantics.sysdyn.representation.Variable;\r
+\r
+public class ElementVisitorVoidAdapter implements IElementVisitorVoid {\r
+\r
+    @Override\r
+    public void visit(Auxiliary auxiliary) {\r
+    }\r
+\r
+    @Override\r
+    public void visit(Stock stock) {\r
+    }\r
+\r
+    @Override\r
+    public void visit(Valve valve) {\r
+    }\r
+\r
+    @Override\r
+    public void visit(Cloud cloud) {\r
+    }\r
+\r
+    @Override\r
+    public void visit(Input input) {\r
+    }\r
+\r
+    @Override\r
+    public void visit(Dependency dependency) {\r
+    }\r
+\r
+    @Override\r
+    public void visit(Flow flow) {\r
+    }\r
+    \r
+    @Override\r
+    public void visit(Module module) {\r
+    }\r
+\r
+    @Override\r
+    public void visit(Configuration configuration) {\r
+    }\r
+    \r
+    @Override\r
+    public void visit(Enumeration enumeration) {\r
+    }\r
+    \r
+    @Override\r
+    public void visit(LibraryDummy libraryDummy) {\r
+    }\r
+    \r
+    @Override\r
+    public void visit(Book sheet) {\r
+    }\r
+    \r
+    @Override\r
+    public void visit(DiagramContainerDummy container) {\r
+    }\r
+    \r
+    @Override\r
+    public void visit(Variable variable) {\r
+    }\r
+    \r
+    @Override\r
+    public void visit(Loop loop) {\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/visitors/IElementVisitorVoid.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/representation/visitors/IElementVisitorVoid.java
new file mode 100644 (file)
index 0000000..3b28258
--- /dev/null
@@ -0,0 +1,48 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.representation.visitors;\r
+\r
+import org.simantics.sysdyn.representation.Auxiliary;\r
+import org.simantics.sysdyn.representation.Book;\r
+import org.simantics.sysdyn.representation.Cloud;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.Dependency;\r
+import org.simantics.sysdyn.representation.DiagramContainerDummy;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.Flow;\r
+import org.simantics.sysdyn.representation.Input;\r
+import org.simantics.sysdyn.representation.LibraryDummy;\r
+import org.simantics.sysdyn.representation.Loop;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Valve;\r
+import org.simantics.sysdyn.representation.Variable;\r
+\r
+public interface IElementVisitorVoid {\r
+\r
+    void visit(Auxiliary auxiliary);\r
+    void visit(Stock stock);\r
+    void visit(Valve valve);\r
+    void visit(Cloud cloud);\r
+    void visit(Input input);\r
+    void visit(Dependency dependency);\r
+    void visit(Flow flow);   \r
+    void visit(Module module);\r
+    void visit(Configuration configuration);\r
+    void visit(Enumeration enumeration);\r
+    void visit(LibraryDummy libraryDummy);\r
+    void visit(Book sheet);\r
+    void visit(DiagramContainerDummy container);\r
+    void visit(Variable variable);\r
+    void visit(Loop loop);\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationJob.java
new file mode 100644 (file)
index 0000000..75e177f
--- /dev/null
@@ -0,0 +1,108 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.simulation;\r
+\r
+import java.text.SimpleDateFormat;\r
+import java.util.Calendar;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.simantics.modelica.IModelicaMonitor;\r
+import org.simantics.sysdyn.manager.OldSysdynExperiment;\r
+import org.simantics.sysdyn.manager.SysdynConsole;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+\r
+public class SimulationJob extends Job {\r
+\r
+    private SysdynModel model;\r
+    private OldSysdynExperiment experiment;\r
+    private IModelicaMonitor monitor;\r
+    \r
+    public SimulationJob(SysdynModel model, OldSysdynExperiment experiment) {\r
+        super("Simulate " + model.getConfiguration().getLabel());\r
+        this.model = model;\r
+        this.experiment = experiment;\r
+        if(PlatformUI.isWorkbenchRunning()) {\r
+            this.monitor = SysdynConsole.INSTANCE;\r
+        } else {\r
+            // Fallback to headless\r
+            this.monitor = new HeadlessModelicaMonitor();\r
+        }\r
+    }\r
+\r
+    @Override\r
+    protected IStatus run(IProgressMonitor monitor) {\r
+        monitor.beginTask("Simulate " + model.getConfiguration().getLabel(), experiment.numberOfSimulationRunSteps());        \r
+        try {\r
+            model.update();\r
+            if(experiment instanceof OldSysdynExperiment) {\r
+               ((OldSysdynExperiment)experiment).simulate(this.monitor, monitor, model.getConfiguration().getLabel());\r
+               model.setStructureModified(false);\r
+            }\r
+        } catch (Exception e) {\r
+            e.printStackTrace();\r
+            this.monitor.showConsole();\r
+            return new Status(\r
+                    Status.ERROR, \r
+                    "org.simantics.sysdyn.ui", \r
+                    "Simulation failed: \n" + e.getMessage());\r
+        } \r
+        this.monitor.message("\n");\r
+        monitor.done(); \r
+        return Status.OK_STATUS;\r
+    }\r
+\r
+    @Override\r
+    public boolean belongsTo(Object family) {\r
+        return "SimulationJob".equals(family);\r
+    }\r
+\r
+    public static class HeadlessModelicaMonitor implements IModelicaMonitor {\r
+        public HeadlessModelicaMonitor() {\r
+        }\r
+\r
+        @Override\r
+        public void message(String message) {\r
+            message(message, "hh:mm:ss");\r
+        }\r
+\r
+        /**\r
+         * Print message to a console with a specified time stamp format\r
+         * \r
+         * @param message the message to be printed\r
+         * @param timeStampFormat simpledateformat timestamp format. null if no timestamp wanted\r
+         */\r
+        public void message(String message, String timeStampFormat) {\r
+            Calendar cal = Calendar.getInstance();\r
+            SimpleDateFormat sdf = new SimpleDateFormat(timeStampFormat);\r
+            String time = sdf.format(cal.getTime());\r
+\r
+            System.out.println("[" + time +"] " + message);\r
+        }\r
+\r
+        public void clearConsole() {\r
+        }\r
+\r
+        public void showConsole() {\r
+        }\r
+\r
+    }\r
+\r
+    @Override\r
+    protected void canceling() {\r
+\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationScheduler.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/simulation/SimulationScheduler.java
new file mode 100644 (file)
index 0000000..bd4d7d6
--- /dev/null
@@ -0,0 +1,44 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.simulation;\r
+\r
+import org.simantics.sysdyn.manager.OldSysdynExperiment;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+\r
+public class SimulationScheduler {\r
+    SysdynModel model;\r
+    OldSysdynExperiment experiment;\r
+    SimulationJob job;\r
+    \r
+    private SimulationScheduler(SysdynModel model, OldSysdynExperiment experiment) {    \r
+        this.model = model;\r
+        this.experiment = experiment;\r
+        this.job = new SimulationJob(model, experiment);\r
+    }\r
+    \r
+    private void start() {\r
+        job.schedule();\r
+    }\r
+\r
+    public static synchronized SimulationScheduler start(SysdynModel model, OldSysdynExperiment experiment) {\r
+        SimulationScheduler scheduler = model.getService(SimulationScheduler.class);\r
+        if(scheduler == null || !scheduler.experiment.equals(experiment)) {\r
+            scheduler = new SimulationScheduler(model, experiment);\r
+            model.addService(SimulationScheduler.class, scheduler);\r
+            scheduler.start();\r
+        } else {\r
+            scheduler.start();\r
+        }\r
+        return scheduler;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolver.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolver.java
new file mode 100644 (file)
index 0000000..a2a14fb
--- /dev/null
@@ -0,0 +1,23 @@
+package org.simantics.sysdyn.solver;\r
+\r
+import org.simantics.sysdyn.solver.SolverSettings.SolverType;\r
+\r
+public interface ISolver {\r
+       \r
+       public void initialize() throws Exception;\r
+       public void buildModel() throws Exception;\r
+       public void runSolver() throws Exception;\r
+       public void updateResults() throws Exception;\r
+       public SolverType getType();\r
+       \r
+       public double[] getSubscribedResults(double[] array);\r
+       \r
+       public void prepareToStep() throws Exception;\r
+       public void simulateStep() throws Exception ;\r
+       \r
+       public void setStepLength(double length) throws Exception ;\r
+       public double getTime();\r
+       \r
+       public void setRealValue(String name, double value) throws Exception ;\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolverMonitor.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ISolverMonitor.java
new file mode 100644 (file)
index 0000000..9df8735
--- /dev/null
@@ -0,0 +1,9 @@
+package org.simantics.sysdyn.solver;\r
+\r
+import org.simantics.modelica.IModelicaMonitor;\r
+\r
+public interface ISolverMonitor extends IModelicaMonitor {\r
+       public void message(String message);\r
+       public void clearConsole();\r
+       public void showConsole();\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolver.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolver.java
new file mode 100644 (file)
index 0000000..6835e19
--- /dev/null
@@ -0,0 +1,217 @@
+package org.simantics.sysdyn.solver;\r
+\r
+import java.io.File;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.modelica.ModelicaManager;\r
+import org.simantics.modelica.SimulationLocation;\r
+import org.simantics.sysdyn.manager.FunctionUtils;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.modelica.ModelicaWriter;\r
+import org.simantics.sysdyn.representation.Model;\r
+import org.simantics.sysdyn.solver.SolverSettings.SolverType;\r
+import org.simantics.utils.FileUtils;\r
+\r
+import fi.semantum.sysdyn.solver.Solver;\r
+\r
+public class InternalSolver implements ISolver {\r
+\r
+       public static final boolean PRINT_CODE = false;\r
+       \r
+       private SysdynExperiment experiment;\r
+       private SysdynModel model;\r
+       private ISolverMonitor monitor;\r
+       public Solver solver;\r
+       \r
+       private double start;\r
+       private double stop;\r
+       private double step;\r
+       private double interval;\r
+       \r
+       private final boolean isGame;\r
+       \r
+       private SimulationLocation location;\r
+\r
+       private HashMap<String, SysdynDataSet> results;\r
+\r
+       public InternalSolver(SysdynExperiment experiment, SysdynModel model, boolean isGame, ISolverMonitor monitor) {\r
+               this.experiment = experiment;\r
+               this.model = model;\r
+               this.monitor = monitor;\r
+               this.isGame = isGame;\r
+               \r
+               solver = new Solver();\r
+               \r
+               // default values\r
+               start = 0;\r
+               stop = 500;\r
+               step = 0.1;\r
+               interval = step;\r
+       }\r
+\r
+       @Override\r
+       public void initialize() throws Exception {\r
+               \r
+               // set solver parameters\r
+               Model representation = model.getConfiguration().getModel();\r
+               // TODO: should probably check that the values actually make sense\r
+               // i.e. start and stop >= 0, start <= stop, stop - start >= step\r
+               if (representation.getStartTime() != null)\r
+                       start = representation.getStartTime();\r
+               if (representation.getStopTime() != null)\r
+                       stop = representation.getStopTime();\r
+               \r
+//             String omVersion = ModelicaManager.getDefaultOMVersion();\r
+               String modelContent = ModelicaWriter.write(model.getModules(), start, isGame, "1.9");\r
+\r
+               // update some stuff\r
+               FunctionUtils.updateFunctionFilesForExperiment(experiment);\r
+\r
+               location = ModelicaManager.createSimulationLocation(experiment.getExperimentDir(), \r
+                               model.getConfiguration().getLabel(), modelContent, null, false);\r
+               \r
+               if (representation.getSimulationStepLength() != null)\r
+                       step = representation.getSimulationStepLength();\r
+               else\r
+                       step = (stop - start) / 500;\r
+                       \r
+               if (representation.getOutputInterval() != null)\r
+                       interval = representation.getOutputInterval();\r
+               else\r
+                       interval = step;\r
+               \r
+               solver.setStep(step);\r
+               solver.setStart(start);\r
+       }\r
+\r
+       @Override\r
+       public void buildModel() throws Exception {\r
+               \r
+//             String flat = ModelicaManager.getFlatModelText(location, monitor, FunctionUtils.getLibraryPathsForModelica(experiment));\r
+//             System.err.println("=== FLAT ===");\r
+//             System.err.println(flat);\r
+//             System.err.println("=== FLAT ENDS ===");\r
+               \r
+               StringBuilder code = new StringBuilder();\r
+               for(String path : FunctionUtils.getLibraryPathsForModelica(experiment)) {\r
+                       File f = new File(location.modelFile.getParentFile(), path);\r
+                       code.append(FileUtils.getContents(f));\r
+               }\r
+               code.append(FileUtils.getContents(location.modelFile));\r
+               \r
+               if(PRINT_CODE) {\r
+                       System.err.println("=== CODE === ");\r
+                       System.err.println(code.toString());\r
+                       System.err.println("=== CODE ENDS ===");\r
+               }\r
+\r
+               solver.prepare(code.toString());\r
+               \r
+       }\r
+\r
+       @Override\r
+       public void runSolver() throws Exception {\r
+               \r
+               long startTime = System.nanoTime();\r
+               \r
+               // the number of result intervals in the simulation (account for initial values)\r
+               int count = (int)((stop - start) / interval) + 1;\r
+               // the number of steps in one result interval\r
+               int steps = (int)(interval / step);\r
+               \r
+               // an array containing an accurate time stamp for each interval\r
+               double[] times = new double[count];\r
+               // a map containing values of all variables for each interval\r
+\r
+               String[] keys = solver.keys();\r
+\r
+               double[][] values = new double[keys.length][];\r
+               \r
+//             HashMap<String, double[]> values = new HashMap<String, double[]>();\r
+               // initialize the temporary data structures\r
+               times[0] = start;\r
+               \r
+               double[] valueArray = solver.values();\r
+//             HashMap<String, Double> tmp = solver.values();\r
+//             String[] keys = new ArrayList<String>(tmp.keySet()).toArray(new String[tmp.size()]);\r
+\r
+               for(int i=0;i<keys.length;i++) {\r
+                       values[i] = new double[count];\r
+                       values[i][0] = valueArray[i];\r
+               }\r
+               \r
+               // run the simulation\r
+               for (int interval = 1; interval < count; interval++) {\r
+                       for (int i = 0; i < steps; i++) {\r
+                               solver.step();\r
+                       }\r
+                       times[interval] = times[interval-1] + steps * step;\r
+\r
+                       valueArray = solver.values();\r
+                       for(int i=0;i<keys.length;i++) {\r
+                               values[i][interval] = valueArray[i];\r
+                       }\r
+                       \r
+               }\r
+\r
+               results = new HashMap<String, SysdynDataSet>();\r
+               for(int i=0;i<keys.length;i++) {\r
+                       String name = keys[i];\r
+                       double[] arr = values[i];\r
+                       results.put(name, new SysdynDataSet(name, null, times, arr));\r
+               }\r
+\r
+//             for (String name : values.keySet()) {\r
+//                     results.put(name, new SysdynDataSet(name, null, times, values.get(name)));\r
+//             }\r
+               \r
+               long endTime = System.nanoTime();\r
+               \r
+               System.err.println("ran simulation in " + 1e-6*(endTime-startTime) + "ms.");\r
+               \r
+       }\r
+\r
+       @Override\r
+       public void updateResults() throws Exception {\r
+               InternalSolverResult result = new InternalSolverResult(null, results);\r
+               experiment.setCurrentResult(result);\r
+               experiment.resultsChanged();\r
+       }\r
+\r
+       @Override\r
+       public SolverType getType() {\r
+               return SolverType.INTERNAL;\r
+       }\r
+       \r
+       @Override\r
+       public double[] getSubscribedResults(double[] array) {\r
+               return solver.values();\r
+       }\r
+       \r
+       @Override\r
+       public double getTime() {\r
+               return solver.getTime();\r
+       }\r
+       \r
+       @Override\r
+       public void prepareToStep() throws Exception {\r
+       }\r
+       \r
+       @Override\r
+       public void setRealValue(String name, double value) throws Exception {\r
+               solver.setValue(name, value);\r
+       }\r
+\r
+       @Override\r
+       public void simulateStep() throws Exception {\r
+               solver.step();\r
+       }\r
+\r
+       @Override\r
+       public void setStepLength(double length) throws Exception {\r
+               solver.setStep(length);\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolverResult.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/InternalSolverResult.java
new file mode 100644 (file)
index 0000000..b630012
--- /dev/null
@@ -0,0 +1,29 @@
+package org.simantics.sysdyn.solver;\r
+\r
+import java.io.File;\r
+import java.util.HashMap;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.simantics.sysdyn.manager.SysdynDataSet;\r
+import org.simantics.sysdyn.manager.SysdynResult;\r
+\r
+public class InternalSolverResult extends SysdynResult {\r
+       \r
+       private HashMap<String, SysdynDataSet> results;\r
+\r
+       public InternalSolverResult(String resultName, HashMap<String, SysdynDataSet> results) {\r
+               super(resultName);\r
+               this.results = results;\r
+       }\r
+\r
+       @Override\r
+       public SysdynDataSet getDataSet(String variable) {\r
+               return results.get(variable);\r
+       }\r
+\r
+       @Override\r
+       public void saveToFile(File file, IProgressMonitor progressMonitor) {\r
+               // not implemented\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ModelicaSolver.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/ModelicaSolver.java
new file mode 100644 (file)
index 0000000..2538068
--- /dev/null
@@ -0,0 +1,93 @@
+package org.simantics.sysdyn.solver;\r
+\r
+import org.simantics.fmu.FMUJNIException;\r
+import org.simantics.sysdyn.manager.SysdynGameExperiment;\r
+import org.simantics.sysdyn.solver.SolverSettings.SolverType;\r
+\r
+public class ModelicaSolver implements ISolver {\r
+       \r
+       SysdynGameExperiment exp;\r
+       \r
+       public ModelicaSolver(SysdynGameExperiment exp) {\r
+               this.exp = exp;\r
+       }\r
+       \r
+       @Override\r
+       public void initialize() throws Exception {\r
+               // TODO Auto-generated method stub\r
+               \r
+       }\r
+\r
+       @Override\r
+       public void buildModel() throws Exception {\r
+               // TODO Auto-generated method stub\r
+               \r
+       }\r
+\r
+       @Override\r
+       public void runSolver() throws Exception {\r
+               // TODO Auto-generated method stub\r
+               \r
+       }\r
+\r
+       @Override\r
+       public void updateResults() throws Exception {\r
+               // TODO Auto-generated method stub\r
+               \r
+       }\r
+\r
+       @Override\r
+       public SolverType getType() {\r
+               // TODO Auto-generated method stub\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public double[] getSubscribedResults(double[] array) {\r
+               // TODO Auto-generated method stub\r
+               return null;\r
+       }\r
+\r
+       @Override\r
+       public void prepareToStep() throws Exception {\r
+\r
+               // initialize if not initialized\r
+               if(!exp.control.isInitialized()) {\r
+                       exp.control.setTime(exp.startTime);\r
+                       exp.control.initializeSimulation();\r
+                       exp.clearResults();\r
+                       //                              getInitialResultValues();\r
+               }\r
+\r
+               exp.control.setStepLength(exp.stepLength); // Set step length each time in case there has been changes\r
+               \r
+       }\r
+\r
+       @Override\r
+       public void simulateStep() throws Exception {\r
+               exp.control.simulateStep();\r
+       }\r
+\r
+       @Override\r
+       public void setStepLength(double length) throws Exception {\r
+               exp.control.setStepLength(length);\r
+       }\r
+\r
+       @Override\r
+       public double getTime() {\r
+               if(exp.control != null) {\r
+                       try {\r
+                               return exp.control.getTime();\r
+                       } catch (FMUJNIException e) {\r
+                       }\r
+               }\r
+               return 0.0;\r
+       }\r
+\r
+       @Override\r
+       public void setRealValue(String name, double value) throws Exception {\r
+               exp.control.setRealValue(name, value);\r
+       }\r
+\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SolverParameters.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SolverParameters.java
new file mode 100644 (file)
index 0000000..ec32dab
--- /dev/null
@@ -0,0 +1,13 @@
+package org.simantics.sysdyn.solver;\r
+\r
+public class SolverParameters {\r
+       public static final String START_VALUE         = "startTime";\r
+    public static final String STOP_VALUE          = "stopTime";\r
+    public static final String OUTPUT_FORMAT       = "outputFormat";\r
+    public static final String STEP_VALUE          = "stepSize";\r
+    public static final String NUMBER_OF_INTERVALS = "numberOfIntervals";\r
+    public static final String METHOD              = "method";\r
+    public static final String TOLERANCE           = "tolerance";\r
+    public static final String VARIABLE_FILTER     = "variableFilter";\r
+    public static final String OUTPUT_INTERVAL     = "outputInterval";\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SolverSettings.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SolverSettings.java
new file mode 100644 (file)
index 0000000..b3e8fb0
--- /dev/null
@@ -0,0 +1,34 @@
+package org.simantics.sysdyn.solver;\r
+\r
+import org.eclipse.core.runtime.preferences.ConfigurationScope;\r
+import org.osgi.service.prefs.Preferences;\r
+\r
+public class SolverSettings {\r
+       \r
+       public enum SolverType {\r
+               INTERNAL, OPENMODELICA, UNKNOWN\r
+       }\r
+       \r
+       public static final String QUALIFIER = "org.simantics.sysdyn.solver.preferences";\r
+       \r
+       public static final String SOLVER_TYPE = "SOLVER_TYPE";\r
+       public static final String SOLVER_TYPE_INTERNAL = "INTERNAL";\r
+       public static final String SOLVER_TYPE_OPENMODELICA = "OPENMODELICA";\r
+       \r
+       public static SolverType getSelectedSolverType() {\r
+               Preferences preferences = ConfigurationScope.INSTANCE.getNode(SolverSettings.QUALIFIER);\r
+               // default to internal solver\r
+               String type = preferences.get(SolverSettings.SOLVER_TYPE, SolverSettings.SOLVER_TYPE_INTERNAL);\r
+               \r
+               if (SOLVER_TYPE_INTERNAL.equals(type)) {\r
+                       return SolverType.INTERNAL;\r
+               }\r
+               else if (SOLVER_TYPE_OPENMODELICA.equals(type)) {\r
+                       return SolverType.OPENMODELICA;\r
+               }\r
+               else {\r
+                       return SolverType.UNKNOWN;\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SysdynSimulationJob.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/solver/SysdynSimulationJob.java
new file mode 100644 (file)
index 0000000..eed1f06
--- /dev/null
@@ -0,0 +1,99 @@
+package org.simantics.sysdyn.solver;\r
+\r
+import gnu.trove.map.TObjectIntMap;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.Simantics;\r
+import org.simantics.issues.Severity;\r
+import org.simantics.issues.common.CountModelIssuesBySeverity;\r
+import org.simantics.sysdyn.manager.SysdynConsole;\r
+import org.simantics.sysdyn.manager.SysdynExperiment;\r
+import org.simantics.sysdyn.solver.SolverSettings.SolverType;\r
+\r
+public class SysdynSimulationJob extends Job {\r
+       \r
+       private static final String pluginId = "unknown";\r
+       \r
+       protected String name;\r
+       protected SysdynExperiment experiment;\r
+       protected ISolver solver;\r
+       protected ISolverMonitor solverMonitor;\r
+\r
+       public SysdynSimulationJob(String name, SysdynExperiment experiment) {\r
+               super(name);\r
+               this.name = name;\r
+               this.experiment = experiment;\r
+               this.solver = null;\r
+               this.solverMonitor = SysdynConsole.INSTANCE;\r
+       }\r
+\r
+       @Override\r
+       protected IStatus run(IProgressMonitor monitor) {\r
+               monitor.beginTask("Simulate " + name, 4);\r
+               \r
+               // model update is necessary as it upgrades the isStructureModifier \r
+               // flag, could possibly be done differently if avoiding the graph\r
+               // operation is desired\r
+               try {\r
+                       experiment.sysdynModel.update();\r
+               }\r
+               catch (DatabaseException e) {\r
+                       return new Status(Status.ERROR, pluginId, "Could not update model", e);\r
+               }\r
+               \r
+               // do not simulate if there are errors in the model\r
+               try {\r
+                       TObjectIntMap<Severity> severeties = \r
+                                       Simantics.sync(new CountModelIssuesBySeverity(experiment.getModel(), true, Severity.ERROR));\r
+                       if (severeties.get(Severity.ERROR) > 0) {\r
+                               return new Status(Status.ERROR, pluginId, "There are unresolved errors in the model");\r
+                       }\r
+               }\r
+               catch (DatabaseException e) {\r
+                       return new Status(Status.ERROR, pluginId, "Could not obtain issue count from model", e);\r
+               }\r
+               \r
+               SolverType type = experiment.getSolverType();\r
+               // if the solver has not been created yet or the type of the solver \r
+               // has changed, a new solver must be created\r
+               if (solver == null || !solver.getType().equals(type)) {\r
+                       if (SolverType.INTERNAL.equals(type)) {\r
+                               solver = new InternalSolver(experiment, experiment.sysdynModel, false, solverMonitor);\r
+                       }\r
+                       else if (SolverType.OPENMODELICA.equals(type)) {\r
+                               return new Status(Status.ERROR, pluginId, "The experiment should be reloaded");\r
+                       }\r
+               }\r
+               \r
+               // TODO: this should be broken down\r
+               \r
+               try {\r
+                       monitor.subTask("generating model...");\r
+                       solver.initialize();\r
+                       monitor.worked(1);\r
+                       \r
+                       monitor.subTask("building model...");\r
+                       solver.buildModel();\r
+                       monitor.worked(1);\r
+                       \r
+                       monitor.subTask("running solver...");\r
+                       solver.runSolver();\r
+                       monitor.worked(1);\r
+                       \r
+                       monitor.subTask("getting results...");\r
+                       solver.updateResults();\r
+                       monitor.worked(1);\r
+               }\r
+               catch (Exception e) {\r
+                       return new Status(Status.ERROR, pluginId, "Simulation failed", e);\r
+               }\r
+               \r
+               monitor.done();\r
+               return Status.OK_STATUS;\r
+       }\r
+       \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/ParseException.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/ParseException.java
new file mode 100644 (file)
index 0000000..57f889b
--- /dev/null
@@ -0,0 +1,198 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */\r
+/* JavaCCOptions:KEEP_LINE_COL=null */\r
+package org.simantics.sysdyn.tableParser;\r
+\r
+/**\r
+ * This exception is thrown when parse errors are encountered.\r
+ * You can explicitly create objects of this exception type by\r
+ * calling the method generateParseException in the generated\r
+ * parser.\r
+ *\r
+ * You can modify this class to customize your error reporting\r
+ * mechanisms so long as you retain the public fields.\r
+ */\r
+public class ParseException extends Exception {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * This constructor is used by the method "generateParseException"\r
+   * in the generated parser.  Calling this constructor generates\r
+   * a new object of this type with the fields "currentToken",\r
+   * "expectedTokenSequences", and "tokenImage" set.\r
+   */\r
+  public ParseException(Token currentTokenVal,\r
+                        int[][] expectedTokenSequencesVal,\r
+                        String[] tokenImageVal\r
+                       )\r
+  {\r
+    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));\r
+    currentToken = currentTokenVal;\r
+    expectedTokenSequences = expectedTokenSequencesVal;\r
+    tokenImage = tokenImageVal;\r
+  }\r
+\r
+  /**\r
+   * The following constructors are for use by you for whatever\r
+   * purpose you can think of.  Constructing the exception in this\r
+   * manner makes the exception behave in the normal way - i.e., as\r
+   * documented in the class "Throwable".  The fields "errorToken",\r
+   * "expectedTokenSequences", and "tokenImage" do not contain\r
+   * relevant information.  The JavaCC generated code does not use\r
+   * these constructors.\r
+   */\r
+\r
+  public ParseException() {\r
+    super();\r
+  }\r
+\r
+  /** Constructor with message. */\r
+  public ParseException(String message) {\r
+    super(message);\r
+  }\r
+\r
+\r
+  /**\r
+   * This is the last token that has been consumed successfully.  If\r
+   * this object has been created due to a parse error, the token\r
+   * followng this token will (therefore) be the first error token.\r
+   */\r
+  public Token currentToken;\r
+\r
+  /**\r
+   * Each entry in this array is an array of integers.  Each array\r
+   * of integers represents a sequence of tokens (by their ordinal\r
+   * values) that is expected at this point of the parse.\r
+   */\r
+  public int[][] expectedTokenSequences;\r
+\r
+  /**\r
+   * This is a reference to the "tokenImage" array of the generated\r
+   * parser within which the parse error occurred.  This array is\r
+   * defined in the generated ...Constants interface.\r
+   */\r
+  public String[] tokenImage;\r
+\r
+  /**\r
+   * It uses "currentToken" and "expectedTokenSequences" to generate a parse\r
+   * error message and returns it.  If this object has been created\r
+   * due to a parse error, and you do not catch it (it gets thrown\r
+   * from the parser) the correct error message\r
+   * gets displayed.\r
+   */\r
+  private static String initialise(Token currentToken,\r
+                           int[][] expectedTokenSequences,\r
+                           String[] tokenImage) {\r
+    String eol = System.getProperty("line.separator", "\n");\r
+    StringBuffer expected = new StringBuffer();\r
+    int maxSize = 0;\r
+    for (int i = 0; i < expectedTokenSequences.length; i++) {\r
+      if (maxSize < expectedTokenSequences[i].length) {\r
+        maxSize = expectedTokenSequences[i].length;\r
+      }\r
+      for (int j = 0; j < expectedTokenSequences[i].length; j++) {\r
+        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');\r
+      }\r
+      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {\r
+        expected.append("...");\r
+      }\r
+      expected.append(eol).append("    ");\r
+    }\r
+    String retval = "Encountered \"";\r
+    Token tok = currentToken.next;\r
+    for (int i = 0; i < maxSize; i++) {\r
+      if (i != 0) retval += " ";\r
+      if (tok.kind == 0) {\r
+        retval += tokenImage[0];\r
+        break;\r
+      }\r
+      retval += " " + tokenImage[tok.kind];\r
+      retval += " \"";\r
+      retval += add_escapes(tok.image);\r
+      retval += " \"";\r
+      tok = tok.next;\r
+    }\r
+    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;\r
+    retval += "." + eol;\r
+    if (expectedTokenSequences.length == 1) {\r
+      retval += "Was expecting:" + eol + "    ";\r
+    } else {\r
+      retval += "Was expecting one of:" + eol + "    ";\r
+    }\r
+    retval += expected.toString();\r
+    return retval;\r
+  }\r
+\r
+  /**\r
+   * The end of line string for this machine.\r
+   */\r
+  protected String eol = System.getProperty("line.separator", "\n");\r
+\r
+  /**\r
+   * Used to convert raw characters to their escaped version\r
+   * when these raw version cannot be used as part of an ASCII\r
+   * string literal.\r
+   */\r
+  static String add_escapes(String str) {\r
+      StringBuffer retval = new StringBuffer();\r
+      char ch;\r
+      for (int i = 0; i < str.length(); i++) {\r
+        switch (str.charAt(i))\r
+        {\r
+           case 0 :\r
+              continue;\r
+           case '\b':\r
+              retval.append("\\b");\r
+              continue;\r
+           case '\t':\r
+              retval.append("\\t");\r
+              continue;\r
+           case '\n':\r
+              retval.append("\\n");\r
+              continue;\r
+           case '\f':\r
+              retval.append("\\f");\r
+              continue;\r
+           case '\r':\r
+              retval.append("\\r");\r
+              continue;\r
+           case '\"':\r
+              retval.append("\\\"");\r
+              continue;\r
+           case '\'':\r
+              retval.append("\\\'");\r
+              continue;\r
+           case '\\':\r
+              retval.append("\\\\");\r
+              continue;\r
+           default:\r
+              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+                 String s = "0000" + Integer.toString(ch, 16);\r
+                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+              } else {\r
+                 retval.append(ch);\r
+              }\r
+              continue;\r
+        }\r
+      }\r
+      return retval.toString();\r
+   }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=812397ddfc370286eccefa2f873e20e3 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/SimpleCharStream.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/SimpleCharStream.java
new file mode 100644 (file)
index 0000000..70ba9d9
--- /dev/null
@@ -0,0 +1,482 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */\r
+/* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package org.simantics.sysdyn.tableParser;\r
+\r
+/**\r
+ * An implementation of interface CharStream, where the stream is assumed to\r
+ * contain only ASCII characters (without unicode processing).\r
+ */\r
+\r
+public class SimpleCharStream\r
+{\r
+/** Whether parser is static. */\r
+  public static final boolean staticFlag = false;\r
+  int bufsize;\r
+  int available;\r
+  int tokenBegin;\r
+/** Position in buffer. */\r
+  public int bufpos = -1;\r
+  protected int bufline[];\r
+  protected int bufcolumn[];\r
+\r
+  protected int column = 0;\r
+  protected int line = 1;\r
+\r
+  protected boolean prevCharIsCR = false;\r
+  protected boolean prevCharIsLF = false;\r
+\r
+  protected java.io.Reader inputStream;\r
+\r
+  protected char[] buffer;\r
+  protected int maxNextCharInd = 0;\r
+  protected int inBuf = 0;\r
+  protected int tabSize = 8;\r
+\r
+  protected void setTabSize(int i) { tabSize = i; }\r
+  protected int getTabSize(int i) { return tabSize; }\r
+\r
+\r
+  protected void ExpandBuff(boolean wrapAround)\r
+  {\r
+    char[] newbuffer = new char[bufsize + 2048];\r
+    int newbufline[] = new int[bufsize + 2048];\r
+    int newbufcolumn[] = new int[bufsize + 2048];\r
+\r
+    try\r
+    {\r
+      if (wrapAround)\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos += (bufsize - tokenBegin));\r
+      }\r
+      else\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos -= tokenBegin);\r
+      }\r
+    }\r
+    catch (Throwable t)\r
+    {\r
+      throw new Error(t.getMessage());\r
+    }\r
+\r
+\r
+    bufsize += 2048;\r
+    available = bufsize;\r
+    tokenBegin = 0;\r
+  }\r
+\r
+  protected void FillBuff() throws java.io.IOException\r
+  {\r
+    if (maxNextCharInd == available)\r
+    {\r
+      if (available == bufsize)\r
+      {\r
+        if (tokenBegin > 2048)\r
+        {\r
+          bufpos = maxNextCharInd = 0;\r
+          available = tokenBegin;\r
+        }\r
+        else if (tokenBegin < 0)\r
+          bufpos = maxNextCharInd = 0;\r
+        else\r
+          ExpandBuff(false);\r
+      }\r
+      else if (available > tokenBegin)\r
+        available = bufsize;\r
+      else if ((tokenBegin - available) < 2048)\r
+        ExpandBuff(true);\r
+      else\r
+        available = tokenBegin;\r
+    }\r
+\r
+    int i;\r
+    try {\r
+      if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)\r
+      {\r
+        inputStream.close();\r
+        throw new java.io.IOException();\r
+      }\r
+      else\r
+        maxNextCharInd += i;\r
+      return;\r
+    }\r
+    catch(java.io.IOException e) {\r
+      --bufpos;\r
+      backup(0);\r
+      if (tokenBegin == -1)\r
+        tokenBegin = bufpos;\r
+      throw e;\r
+    }\r
+  }\r
+\r
+/** Start. */\r
+  public char BeginToken() throws java.io.IOException\r
+  {\r
+    tokenBegin = -1;\r
+    char c = readChar();\r
+    tokenBegin = bufpos;\r
+\r
+    return c;\r
+  }\r
+\r
+  protected void UpdateLineColumn(char c)\r
+  {\r
+    column++;\r
+\r
+    if (prevCharIsLF)\r
+    {\r
+      prevCharIsLF = false;\r
+      line += (column = 1);\r
+    }\r
+    else if (prevCharIsCR)\r
+    {\r
+      prevCharIsCR = false;\r
+      if (c == '\n')\r
+      {\r
+        prevCharIsLF = true;\r
+      }\r
+      else\r
+        line += (column = 1);\r
+    }\r
+\r
+    switch (c)\r
+    {\r
+      case '\r' :\r
+        prevCharIsCR = true;\r
+        break;\r
+      case '\n' :\r
+        prevCharIsLF = true;\r
+        break;\r
+      case '\t' :\r
+        column--;\r
+        column += (tabSize - (column % tabSize));\r
+        break;\r
+      default :\r
+        break;\r
+    }\r
+\r
+    bufline[bufpos] = line;\r
+    bufcolumn[bufpos] = column;\r
+  }\r
+\r
+/** Read a character. */\r
+  public char readChar() throws java.io.IOException\r
+  {\r
+    if (inBuf > 0)\r
+    {\r
+      --inBuf;\r
+\r
+      if (++bufpos == bufsize)\r
+        bufpos = 0;\r
+\r
+      return buffer[bufpos];\r
+    }\r
+\r
+    if (++bufpos >= maxNextCharInd)\r
+      FillBuff();\r
+\r
+    char c = buffer[bufpos];\r
+\r
+    UpdateLineColumn(c);\r
+    return c;\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndColumn\r
+   */\r
+\r
+  public int getColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndLine\r
+   */\r
+\r
+  public int getLine() {\r
+    return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token end column number. */\r
+  public int getEndColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  /** Get token end line number. */\r
+  public int getEndLine() {\r
+     return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token beginning column number. */\r
+  public int getBeginColumn() {\r
+    return bufcolumn[tokenBegin];\r
+  }\r
+\r
+  /** Get token beginning line number. */\r
+  public int getBeginLine() {\r
+    return bufline[tokenBegin];\r
+  }\r
+\r
+/** Backup a number of characters. */\r
+  public void backup(int amount) {\r
+\r
+    inBuf += amount;\r
+    if ((bufpos -= amount) < 0)\r
+      bufpos += bufsize;\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    available = bufsize = buffersize;\r
+    buffer = new char[buffersize];\r
+    bufline = new int[buffersize];\r
+    bufcolumn = new int[buffersize];\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    if (buffer == null || buffersize != buffer.length)\r
+    {\r
+      available = bufsize = buffersize;\r
+      buffer = new char[buffersize];\r
+      bufline = new int[buffersize];\r
+      bufcolumn = new int[buffersize];\r
+    }\r
+    prevCharIsLF = prevCharIsCR = false;\r
+    tokenBegin = inBuf = maxNextCharInd = 0;\r
+    bufpos = -1;\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+  int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                          int startcolumn, int buffersize)\r
+  {\r
+    ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                     int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+  /** Get token literal value. */\r
+  public String GetImage()\r
+  {\r
+    if (bufpos >= tokenBegin)\r
+      return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);\r
+    else\r
+      return new String(buffer, tokenBegin, bufsize - tokenBegin) +\r
+                            new String(buffer, 0, bufpos + 1);\r
+  }\r
+\r
+  /** Get the suffix. */\r
+  public char[] GetSuffix(int len)\r
+  {\r
+    char[] ret = new char[len];\r
+\r
+    if ((bufpos + 1) >= len)\r
+      System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);\r
+    else\r
+    {\r
+      System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,\r
+                                                        len - bufpos - 1);\r
+      System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);\r
+    }\r
+\r
+    return ret;\r
+  }\r
+\r
+  /** Reset buffer when finished. */\r
+  public void Done()\r
+  {\r
+    buffer = null;\r
+    bufline = null;\r
+    bufcolumn = null;\r
+  }\r
+\r
+  /**\r
+   * Method to adjust line and column numbers for the start of a token.\r
+   */\r
+  public void adjustBeginLineColumn(int newLine, int newCol)\r
+  {\r
+    int start = tokenBegin;\r
+    int len;\r
+\r
+    if (bufpos >= tokenBegin)\r
+    {\r
+      len = bufpos - tokenBegin + inBuf + 1;\r
+    }\r
+    else\r
+    {\r
+      len = bufsize - tokenBegin + bufpos + 1 + inBuf;\r
+    }\r
+\r
+    int i = 0, j = 0, k = 0;\r
+    int nextColDiff = 0, columnDiff = 0;\r
+\r
+    while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])\r
+    {\r
+      bufline[j] = newLine;\r
+      nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];\r
+      bufcolumn[j] = newCol + columnDiff;\r
+      columnDiff = nextColDiff;\r
+      i++;\r
+    }\r
+\r
+    if (i < len)\r
+    {\r
+      bufline[j] = newLine++;\r
+      bufcolumn[j] = newCol + columnDiff;\r
+\r
+      while (i++ < len)\r
+      {\r
+        if (bufline[j = start % bufsize] != bufline[++start % bufsize])\r
+          bufline[j] = newLine++;\r
+        else\r
+          bufline[j] = newLine;\r
+      }\r
+    }\r
+\r
+    line = bufline[j];\r
+    column = bufcolumn[j];\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=6ae427b43f697d2e9732f56763450bf7 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParser.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParser.java
new file mode 100644 (file)
index 0000000..a8f1dd2
--- /dev/null
@@ -0,0 +1,303 @@
+/* Generated By:JavaCC: Do not edit this line. TableParser.java */\r
+package org.simantics.sysdyn.tableParser;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class TableParser implements TableParserConstants {\r
+        ArrayList<Token> xTokens = new ArrayList<Token>();\r
+        ArrayList<Token> yTokens = new ArrayList<Token>();\r
+\r
+    public ArrayList<Token> getXTokens() {\r
+        return xTokens;\r
+    }\r
+\r
+    public ArrayList<Token> getYTokens() {\r
+        return yTokens;\r
+    }\r
+\r
+/*** Parser ********************************************************/\r
+  final public void table() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case 64:\r
+    case 66:\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 64:\r
+        curlyTable();\r
+        break;\r
+      case 66:\r
+        bracketTable();\r
+        break;\r
+      default:\r
+        jj_la1[0] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+      break;\r
+    default:\r
+      jj_la1[1] = jj_gen;\r
+      ;\r
+    }\r
+    jj_consume_token(0);\r
+  }\r
+\r
+  final public void curlyTable() throws ParseException {\r
+    jj_consume_token(64);\r
+    jj_consume_token(64);\r
+    table_element();\r
+    jj_consume_token(65);\r
+    label_1:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 71:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[2] = jj_gen;\r
+        break label_1;\r
+      }\r
+      jj_consume_token(71);\r
+      jj_consume_token(64);\r
+      table_element();\r
+      jj_consume_token(65);\r
+    }\r
+    jj_consume_token(65);\r
+  }\r
+\r
+  final public void bracketTable() throws ParseException {\r
+    jj_consume_token(66);\r
+    table_element();\r
+    label_2:\r
+    while (true) {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 70:\r
+        ;\r
+        break;\r
+      default:\r
+        jj_la1[3] = jj_gen;\r
+        break label_2;\r
+      }\r
+      jj_consume_token(70);\r
+      table_element();\r
+    }\r
+    jj_consume_token(67);\r
+  }\r
+\r
+  final public void table_element() throws ParseException {\r
+    x_value();\r
+    jj_consume_token(71);\r
+    y_value();\r
+  }\r
+\r
+  final public void x_value() throws ParseException {\r
+    signed_number();\r
+        xTokens.add(token);\r
+  }\r
+\r
+  final public void y_value() throws ParseException {\r
+    signed_number();\r
+        yTokens.add(token);\r
+  }\r
+\r
+  final public void signed_number() throws ParseException {\r
+    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+    case UNSIGNED_INTEGER:\r
+      jj_consume_token(UNSIGNED_INTEGER);\r
+      break;\r
+    case UNSIGNED_NUMBER:\r
+      jj_consume_token(UNSIGNED_NUMBER);\r
+      break;\r
+    case SIGNED_NUMBER:\r
+      jj_consume_token(SIGNED_NUMBER);\r
+      break;\r
+    default:\r
+      jj_la1[4] = jj_gen;\r
+      jj_consume_token(-1);\r
+      throw new ParseException();\r
+    }\r
+  }\r
+\r
+  /** Generated Token Manager. */\r
+  public TableParserTokenManager token_source;\r
+  SimpleCharStream jj_input_stream;\r
+  /** Current token. */\r
+  public Token token;\r
+  /** Next token. */\r
+  public Token jj_nt;\r
+  private int jj_ntk;\r
+  private int jj_gen;\r
+  final private int[] jj_la1 = new int[5];\r
+  static private int[] jj_la1_0;\r
+  static private int[] jj_la1_1;\r
+  static private int[] jj_la1_2;\r
+  static {\r
+      jj_la1_init_0();\r
+      jj_la1_init_1();\r
+      jj_la1_init_2();\r
+   }\r
+   private static void jj_la1_init_0() {\r
+      jj_la1_0 = new int[] {0x0,0x0,0x0,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_1() {\r
+      jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_2() {\r
+      jj_la1_2 = new int[] {0x5,0x5,0x80,0x40,0x70000000,};\r
+   }\r
+\r
+  /** Constructor with InputStream. */\r
+  public TableParser(java.io.InputStream stream) {\r
+     this(stream, null);\r
+  }\r
+  /** Constructor with InputStream and supplied encoding */\r
+  public TableParser(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source = new TableParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 5; i++) jj_la1[i] = -1;\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream) {\r
+     ReInit(stream, null);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 5; i++) jj_la1[i] = -1;\r
+  }\r
+\r
+  /** Constructor. */\r
+  public TableParser(java.io.Reader stream) {\r
+    jj_input_stream = new SimpleCharStream(stream, 1, 1);\r
+    token_source = new TableParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 5; i++) jj_la1[i] = -1;\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader stream) {\r
+    jj_input_stream.ReInit(stream, 1, 1);\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 5; i++) jj_la1[i] = -1;\r
+  }\r
+\r
+  /** Constructor with generated Token Manager. */\r
+  public TableParser(TableParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 5; i++) jj_la1[i] = -1;\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(TableParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 5; i++) jj_la1[i] = -1;\r
+  }\r
+\r
+  private Token jj_consume_token(int kind) throws ParseException {\r
+    Token oldToken;\r
+    if ((oldToken = token).next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    if (token.kind == kind) {\r
+      jj_gen++;\r
+      return token;\r
+    }\r
+    token = oldToken;\r
+    jj_kind = kind;\r
+    throw generateParseException();\r
+  }\r
+\r
+\r
+/** Get the next Token. */\r
+  final public Token getNextToken() {\r
+    if (token.next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    jj_gen++;\r
+    return token;\r
+  }\r
+\r
+/** Get the specific Token. */\r
+  final public Token getToken(int index) {\r
+    Token t = token;\r
+    for (int i = 0; i < index; i++) {\r
+      if (t.next != null) t = t.next;\r
+      else t = t.next = token_source.getNextToken();\r
+    }\r
+    return t;\r
+  }\r
+\r
+  private int jj_ntk() {\r
+    if ((jj_nt=token.next) == null)\r
+      return (jj_ntk = (token.next=token_source.getNextToken()).kind);\r
+    else\r
+      return (jj_ntk = jj_nt.kind);\r
+  }\r
+\r
+  private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();\r
+  private int[] jj_expentry;\r
+  private int jj_kind = -1;\r
+\r
+  /** Generate ParseException. */\r
+  public ParseException generateParseException() {\r
+    jj_expentries.clear();\r
+    boolean[] la1tokens = new boolean[95];\r
+    if (jj_kind >= 0) {\r
+      la1tokens[jj_kind] = true;\r
+      jj_kind = -1;\r
+    }\r
+    for (int i = 0; i < 5; i++) {\r
+      if (jj_la1[i] == jj_gen) {\r
+        for (int j = 0; j < 32; j++) {\r
+          if ((jj_la1_0[i] & (1<<j)) != 0) {\r
+            la1tokens[j] = true;\r
+          }\r
+          if ((jj_la1_1[i] & (1<<j)) != 0) {\r
+            la1tokens[32+j] = true;\r
+          }\r
+          if ((jj_la1_2[i] & (1<<j)) != 0) {\r
+            la1tokens[64+j] = true;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    for (int i = 0; i < 95; i++) {\r
+      if (la1tokens[i]) {\r
+        jj_expentry = new int[1];\r
+        jj_expentry[0] = i;\r
+        jj_expentries.add(jj_expentry);\r
+      }\r
+    }\r
+    int[][] exptokseq = new int[jj_expentries.size()][];\r
+    for (int i = 0; i < jj_expentries.size(); i++) {\r
+      exptokseq[i] = jj_expentries.get(i);\r
+    }\r
+    return new ParseException(token, exptokseq, tokenImage);\r
+  }\r
+\r
+  /** Enable tracing. */\r
+  final public void enable_tracing() {\r
+  }\r
+\r
+  /** Disable tracing. */\r
+  final public void disable_tracing() {\r
+  }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParser.jj b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParser.jj
new file mode 100644 (file)
index 0000000..c7bd0bd
--- /dev/null
@@ -0,0 +1,104 @@
+options {\r
+  JDK_VERSION = "1.6";\r
+  STATIC = false;\r
+}\r
+\r
+PARSER_BEGIN(TableParser)\r
+package org.simantics.sysdyn.tableParser;\r
+\r
+import java.util.ArrayList;\r
+\r
+public class TableParser {\r
+       ArrayList<Token> xTokens = new ArrayList<Token>();\r
+       ArrayList<Token> yTokens = new ArrayList<Token>();\r
+    \r
+    public ArrayList<Token> getXTokens() {\r
+        return xTokens;\r
+    }\r
+    \r
+    public ArrayList<Token> getYTokens() {\r
+        return yTokens;\r
+    }\r
+    \r
+    \r
+}\r
+PARSER_END(TableParser)\r
+\r
+/*** Lexer *********************************************************/\r
+\r
+SKIP:\r
+{ <WHITESPACE: " " | "\n" | "\r" | "\t" > \r
+| <COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/" >  \r
+| <COMMENT2: "//" (~["\n"])* >\r
+}\r
+\r
+TOKEN:\r
+{\r
+"algorithm"    | "discrete"    | "false"       | "model"       | "redeclare"\r
+| "and"                | "each"                | "final"       | "not"         | "replaceable"\r
+| "annotation" | "else"                | "flow"        | "operator" | "return"\r
+|"assert"              | "elseif"              | "for"         | "or"          | "stream"\r
+| "block"              | "elsewhen"    | "function" | "outer"  | "then"\r
+| "break"              | "encapsulated" | "if"         | "output"      | "true"\r
+| "class"              | "end"                 | "import"      | "package" | "type"\r
+| "connect"    | "enumeration" | "in"          | "parameter" | "when"\r
+| "connector"  | "equation"    | "initial" | "partial" | "while"\r
+| "constant"   | "expandable"  | "inner"       | "protected" | "within"\r
+| "constrainedby" | "extends"  | "input"       | "public"\r
+| "der"                | "external"    | "loop"        | "record"\r
+| "(" | ")" | "{" | "}" | "[" | "]" | "." | ":" | ";" | ","\r
+| "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+| "+" | "-" | ".+" | ".-"\r
+| "*" | "/" | ".*" | "./"\r
+| "^" | ".^"\r
+| "=" | ":=" \r
+| <IDENT: ["a"-"z","A"-"Z","_"] (["a"-"z","A"-"Z","_","0"-"9"])* >\r
+| <STRING: "\"" (~["\"", "\\", "\n"] | "\\" ~["\n"])* "\"">\r
+    { matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); }\r
+| <UNSIGNED_INTEGER: (["0"-"9"])+ >\r
+| <UNSIGNED_NUMBER:  \r
+    ( <UNSIGNED_INTEGER> "." (<UNSIGNED_INTEGER>)? (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | "." <UNSIGNED_INTEGER> (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | <UNSIGNED_INTEGER> ["e","E"] (["+","-"])? <UNSIGNED_INTEGER>\r
+    ) >\r
+| <SIGNED_NUMBER : (("-")? ( <UNSIGNED_NUMBER> | <UNSIGNED_INTEGER> ))>\r
+}\r
+\r
+/*** Parser ********************************************************/\r
+\r
+void table() : {\r
+} {\r
+        ( curlyTable() | bracketTable())? <EOF>\r
+}\r
+\r
+void curlyTable() : {\r} {\r
+       ( "{" "{" table_element() "}" ( "," "{" table_element() "}" )* "}" )\r
+} \r\r
+void bracketTable() : {\r} {\r
+       ( "[" table_element() ( ";" table_element() )* "]" )\r
+}\r  \r
+\r
+void table_element() : {\r
+} {\r
+       (x_value() "," y_value())\r
+} \r
+\r
+void x_value() : {\r
+} { \r
+       \r
+       signed_number() {\r
+       xTokens.add(token);\r
+       }\r
+}\r
+\r
+void y_value() : {\r
+} { \r
+       signed_number() {\r
+       yTokens.add(token);\r
+       }\r
+}\r
+\r
+void signed_number() : {\r
+} {\r
+       ( <UNSIGNED_INTEGER> | <UNSIGNED_NUMBER> | <SIGNED_NUMBER> )\r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParserConstants.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParserConstants.java
new file mode 100644 (file)
index 0000000..6b5f083
--- /dev/null
@@ -0,0 +1,132 @@
+/* Generated By:JavaCC: Do not edit this line. TableParserConstants.java */\r
+package org.simantics.sysdyn.tableParser;\r
+\r
+\r
+/**\r
+ * Token literal values and constants.\r
+ * Generated by org.javacc.parser.OtherFilesGen#start()\r
+ */\r
+public interface TableParserConstants {\r
+\r
+  /** End of File. */\r
+  int EOF = 0;\r
+  /** RegularExpression Id. */\r
+  int WHITESPACE = 1;\r
+  /** RegularExpression Id. */\r
+  int COMMENT1 = 2;\r
+  /** RegularExpression Id. */\r
+  int COMMENT2 = 3;\r
+  /** RegularExpression Id. */\r
+  int IDENT = 90;\r
+  /** RegularExpression Id. */\r
+  int STRING = 91;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_INTEGER = 92;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_NUMBER = 93;\r
+  /** RegularExpression Id. */\r
+  int SIGNED_NUMBER = 94;\r
+\r
+  /** Lexical state. */\r
+  int DEFAULT = 0;\r
+\r
+  /** Literal token values. */\r
+  String[] tokenImage = {\r
+    "<EOF>",\r
+    "<WHITESPACE>",\r
+    "<COMMENT1>",\r
+    "<COMMENT2>",\r
+    "\"algorithm\"",\r
+    "\"discrete\"",\r
+    "\"false\"",\r
+    "\"model\"",\r
+    "\"redeclare\"",\r
+    "\"and\"",\r
+    "\"each\"",\r
+    "\"final\"",\r
+    "\"not\"",\r
+    "\"replaceable\"",\r
+    "\"annotation\"",\r
+    "\"else\"",\r
+    "\"flow\"",\r
+    "\"operator\"",\r
+    "\"return\"",\r
+    "\"assert\"",\r
+    "\"elseif\"",\r
+    "\"for\"",\r
+    "\"or\"",\r
+    "\"stream\"",\r
+    "\"block\"",\r
+    "\"elsewhen\"",\r
+    "\"function\"",\r
+    "\"outer\"",\r
+    "\"then\"",\r
+    "\"break\"",\r
+    "\"encapsulated\"",\r
+    "\"if\"",\r
+    "\"output\"",\r
+    "\"true\"",\r
+    "\"class\"",\r
+    "\"end\"",\r
+    "\"import\"",\r
+    "\"package\"",\r
+    "\"type\"",\r
+    "\"connect\"",\r
+    "\"enumeration\"",\r
+    "\"in\"",\r
+    "\"parameter\"",\r
+    "\"when\"",\r
+    "\"connector\"",\r
+    "\"equation\"",\r
+    "\"initial\"",\r
+    "\"partial\"",\r
+    "\"while\"",\r
+    "\"constant\"",\r
+    "\"expandable\"",\r
+    "\"inner\"",\r
+    "\"protected\"",\r
+    "\"within\"",\r
+    "\"constrainedby\"",\r
+    "\"extends\"",\r
+    "\"input\"",\r
+    "\"public\"",\r
+    "\"der\"",\r
+    "\"external\"",\r
+    "\"loop\"",\r
+    "\"record\"",\r
+    "\"(\"",\r
+    "\")\"",\r
+    "\"{\"",\r
+    "\"}\"",\r
+    "\"[\"",\r
+    "\"]\"",\r
+    "\".\"",\r
+    "\":\"",\r
+    "\";\"",\r
+    "\",\"",\r
+    "\"<\"",\r
+    "\"<=\"",\r
+    "\">\"",\r
+    "\">=\"",\r
+    "\"==\"",\r
+    "\"<>\"",\r
+    "\"+\"",\r
+    "\"-\"",\r
+    "\".+\"",\r
+    "\".-\"",\r
+    "\"*\"",\r
+    "\"/\"",\r
+    "\".*\"",\r
+    "\"./\"",\r
+    "\"^\"",\r
+    "\".^\"",\r
+    "\"=\"",\r
+    "\":=\"",\r
+    "<IDENT>",\r
+    "<STRING>",\r
+    "<UNSIGNED_INTEGER>",\r
+    "<UNSIGNED_NUMBER>",\r
+    "<SIGNED_NUMBER>",\r
+  };\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParserTokenManager.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TableParserTokenManager.java
new file mode 100644 (file)
index 0000000..d8eae25
--- /dev/null
@@ -0,0 +1,1462 @@
+/* Generated By:JavaCC: Do not edit this line. TableParserTokenManager.java */\r
+package org.simantics.sysdyn.tableParser;\r
+import java.util.ArrayList;\r
+\r
+/** Token Manager. */\r
+public class TableParserTokenManager implements TableParserConstants\r
+{\r
+\r
+  /** Debug output. */\r
+  public  java.io.PrintStream debugStream = System.out;\r
+  /** Set debug output. */\r
+  public  void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }\r
+private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1)
+{\r
+   switch (pos)
+   {\r
+      case 0:\r
+         if ((active0 & 0x3ffffffffffffff0L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            return 2;\r
+         }\r
+         if ((active1 & 0x8000L) != 0L)\r
+            return 9;\r
+         if ((active1 & 0xb30010L) != 0L)\r
+            return 52;\r
+         if ((active1 & 0x80000L) != 0L)\r
+            return 27;\r
+         return -1;\r
+      case 1:\r
+         if ((active0 & 0x108420080400000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x3ef7bdff7fbffff0L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 1)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 1;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 2:\r
+         if ((active0 & 0x400000800201200L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x3bfffdf77f9fedf0L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 2;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 3:\r
+         if ((active0 & 0x1000084212118400L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x2bfff5b56d8e69f0L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 3)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 3;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 4:\r
+         if ((active0 & 0x1090004290008c0L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x2af6f5b1469e6130L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 4;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 5:\r
+         if ((active0 & 0x22200011009c0000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x8d6f5a046026130L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 5;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 6:\r
+         if ((active0 & 0x80d0a000000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x856250046026130L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 6)\r
+            {\r
+               jjmatchedKind = 90;\r
+               jjmatchedPos = 6;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 7:\r
+         if ((active0 & 0x54150040006110L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 7;\r
+            return 2;\r
+         }\r
+         if ((active0 & 0x802200006020020L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      case 8:\r
+         if ((active0 & 0x10140000000110L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x44010040006000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 8;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 9:\r
+         if ((active0 & 0x40010040002000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 9;\r
+            return 2;\r
+         }\r
+         if ((active0 & 0x4000000004000L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      case 10:\r
+         if ((active0 & 0x10000002000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x40000040000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 10;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 11:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 90;\r
+            jjmatchedPos = 11;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      default :\r
+         return -1;\r
+   }\r
+}\r
+private final int jjStartNfa_0(int pos, long active0, long active1)
+{\r
+   return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1);\r
+}\r
+private int jjStopAtPos(int pos, int kind)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   return pos + 1;\r
+}\r
+private int jjMoveStringLiteralDfa0_0()\r
+{\r
+   switch(curChar)\r
+   {\r
+      case 40:\r
+         return jjStopAtPos(0, 62);\r
+      case 41:\r
+         return jjStopAtPos(0, 63);\r
+      case 42:\r
+         return jjStopAtPos(0, 82);\r
+      case 43:\r
+         return jjStopAtPos(0, 78);\r
+      case 44:\r
+         return jjStopAtPos(0, 71);\r
+      case 45:\r
+         return jjStartNfaWithStates_0(0, 79, 9);\r
+      case 46:\r
+         jjmatchedKind = 68;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0xb30000L);\r
+      case 47:\r
+         return jjStartNfaWithStates_0(0, 83, 27);\r
+      case 58:\r
+         jjmatchedKind = 69;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x2000000L);\r
+      case 59:\r
+         return jjStopAtPos(0, 70);\r
+      case 60:\r
+         jjmatchedKind = 72;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x2200L);\r
+      case 61:\r
+         jjmatchedKind = 88;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x1000L);\r
+      case 62:\r
+         jjmatchedKind = 74;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x800L);\r
+      case 91:\r
+         return jjStopAtPos(0, 66);\r
+      case 93:\r
+         return jjStopAtPos(0, 67);\r
+      case 94:\r
+         return jjStopAtPos(0, 86);\r
+      case 97:\r
+         return jjMoveStringLiteralDfa1_0(0x84210L, 0x0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa1_0(0x21000000L, 0x0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa1_0(0x42108400000000L, 0x0L);\r
+      case 100:\r
+         return jjMoveStringLiteralDfa1_0(0x400000000000020L, 0x0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa1_0(0x884210842108400L, 0x0L);\r
+      case 102:\r
+         return jjMoveStringLiteralDfa1_0(0x4210840L, 0x0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa1_0(0x108421080000000L, 0x0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa1_0(0x1000000000000000L, 0x0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa1_0(0x80L, 0x0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa1_0(0x1000L, 0x0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa1_0(0x108420000L, 0x0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa1_0(0x210842000000000L, 0x0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa1_0(0x2000000000042100L, 0x0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa1_0(0x800000L, 0x0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa1_0(0x4210000000L, 0x0L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa1_0(0x21080000000000L, 0x0L);\r
+      case 123:\r
+         return jjStopAtPos(0, 64);\r
+      case 125:\r
+         return jjStopAtPos(0, 65);\r
+      default :\r
+         return jjMoveNfa_0(0, 0);\r
+   }\r
+}\r
+private int jjMoveStringLiteralDfa1_0(long active0, long active1)\r
+{\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(0, active0, active1);\r
+      return 1;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 42:\r
+         if ((active1 & 0x100000L) != 0L)\r
+            return jjStopAtPos(1, 84);\r
+         break;\r
+      case 43:\r
+         if ((active1 & 0x10000L) != 0L)\r
+            return jjStopAtPos(1, 80);\r
+         break;\r
+      case 45:\r
+         if ((active1 & 0x20000L) != 0L)\r
+            return jjStopAtPos(1, 81);\r
+         break;\r
+      case 47:\r
+         if ((active1 & 0x200000L) != 0L)\r
+            return jjStopAtPos(1, 85);\r
+         break;\r
+      case 61:\r
+         if ((active1 & 0x200L) != 0L)\r
+            return jjStopAtPos(1, 73);\r
+         else if ((active1 & 0x800L) != 0L)\r
+            return jjStopAtPos(1, 75);\r
+         else if ((active1 & 0x1000L) != 0L)\r
+            return jjStopAtPos(1, 76);\r
+         else if ((active1 & 0x2000000L) != 0L)\r
+            return jjStopAtPos(1, 89);\r
+         break;\r
+      case 62:\r
+         if ((active1 & 0x2000L) != 0L)\r
+            return jjStopAtPos(1, 77);\r
+         break;\r
+      case 94:\r
+         if ((active1 & 0x800000L) != 0L)\r
+            return jjStopAtPos(1, 87);\r
+         break;\r
+      case 97:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x842000000440L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x2400000000042100L, active1, 0L);\r
+      case 102:\r
+         if ((active0 & 0x80000000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 31, 2);\r
+         break;\r
+      case 104:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1080010000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000000000820L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x403118010L, active1, 0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1000000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x20000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 41;\r
+            jjmatchedPos = 1;\r
+         }\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x108410840004200L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1042108000201080L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000L, active1, 0L);\r
+      case 113:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x200000000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x400000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 22, 2);\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x10000220000000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x80000L, active1, 0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x800000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000010c000000L, active1, 0L);\r
+      case 120:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x884000000000000L, active1, 0L);\r
+      case 121:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x4000000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(0, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(0, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(1, active0, 0L);\r
+      return 2;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x400000000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x200000000000000L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x2000002040000400L);\r
+      case 100:\r
+         if ((active0 & 0x200L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 9, 2);\r
+         else if ((active0 & 0x800000000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 35, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x180L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x80030020000L);\r
+      case 103:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x10L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x1400000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x40L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x4a108004004800L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x1010000001010000L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x104005000002000L);\r
+      case 114:\r
+         if ((active0 & 0x200000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 21, 2);\r
+         else if ((active0 & 0x400000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 58, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x840000800000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x2188020L);\r
+      case 116:\r
+         if ((active0 & 0x1000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 12, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x8a0000108040000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x210200000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(1, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa3_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(1, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(2, active0, 0L);\r
+      return 3;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x4240060000800L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x5000020L);\r
+      case 101:\r
+         if ((active0 & 0x8000L) != 0L)\r
+         {\r
+            jjmatchedKind = 15;\r
+            jjmatchedPos = 3;\r
+         }\r
+         else if ((active0 & 0x200000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 33, 2);\r
+         else if ((active0 & 0x4000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 38, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x88800000a980180L);\r
+      case 104:\r
+         if ((active0 & 0x400L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 10, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x20000000000000L);\r
+      case 107:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x201000000002000L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10000000000L);\r
+      case 110:\r
+         if ((active0 & 0x10000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 28, 2);\r
+         else if ((active0 & 0x80000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 43, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x108000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2000001000004010L);\r
+      case 112:\r
+         if ((active0 & 0x1000000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 60, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100000000L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x20000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x42000400000040L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10c00000000000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100000000040000L);\r
+      case 119:\r
+         if ((active0 & 0x10000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 16, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(2, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa4_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(2, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(3, active0, 0L);\r
+      return 4;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000822000L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100L);\r
+      case 101:\r
+         if ((active0 & 0x40L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 6, 2);\r
+         else if ((active0 & 0x1000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 48, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x10118000000000L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x220c00000100000L);\r
+      case 107:\r
+         if ((active0 & 0x1000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 24, 2);\r
+         else if ((active0 & 0x20000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 29, 2);\r
+         break;\r
+      case 108:\r
+         if ((active0 & 0x80L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 7, 2);\r
+         else if ((active0 & 0x800L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 11, 2);\r
+         break;\r
+      case 109:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x84000000000000L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000L);\r
+      case 114:\r
+         if ((active0 & 0x8000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 27, 2);\r
+         else if ((active0 & 0x8000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 51, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x28000010000c0030L);\r
+      case 115:\r
+         if ((active0 & 0x400000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 34, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x100000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 56, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x42200004004000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100000000L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(3, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa5_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(3, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(4, active0, 0L);\r
+      return 5;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2c00000004000L);\r
+      case 99:\r
+         if ((active0 & 0x200000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 57, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x10108000002000L);\r
+      case 100:\r
+         if ((active0 & 0x2000000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 61, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x84000000000000L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000020L);\r
+      case 102:\r
+         if ((active0 & 0x100000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 20, 2);\r
+         break;\r
+      case 103:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000000L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x200004000010L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x100L);\r
+      case 109:\r
+         if ((active0 & 0x800000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 23, 2);\r
+         break;\r
+      case 110:\r
+         if ((active0 & 0x40000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 18, 2);\r
+         else if ((active0 & 0x20000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 53, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x800000000000000L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40010000000000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000L);\r
+      case 116:\r
+         if ((active0 & 0x80000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 19, 2);\r
+         else if ((active0 & 0x100000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 32, 2);\r
+         else if ((active0 & 0x1000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 36, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x20000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(4, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa6_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(4, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(5, active0, 0L);\r
+      return 6;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x844010000000100L);\r
+      case 101:\r
+         if ((active0 & 0x2000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 37, 2);\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x2002000L);\r
+      case 108:\r
+         if ((active0 & 0x400000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 46, 2);\r
+         else if ((active0 & 0x800000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 47, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x2000000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x200004020000L);\r
+      case 115:\r
+         if ((active0 & 0x80000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 55, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x8000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 39;\r
+            jjmatchedPos = 6;\r
+         }\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x10140000004030L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(5, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa7_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(5, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(6, active0, 0L);\r
+      return 7;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x2000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x4000000000000L);\r
+      case 101:\r
+         if ((active0 & 0x20L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 5, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10040000000000L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x40000000004000L);\r
+      case 108:\r
+         if ((active0 & 0x800000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 59, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x40000000L);\r
+      case 110:\r
+         if ((active0 & 0x2000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 25, 2);\r
+         else if ((active0 & 0x4000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 26, 2);\r
+         else if ((active0 & 0x200000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 45, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100000000000L);\r
+      case 114:\r
+         if ((active0 & 0x20000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 17, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100L);\r
+      case 116:\r
+         if ((active0 & 0x2000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 49, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10000000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(6, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa8_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(6, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(7, active0, 0L);\r
+      return 8;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x40000000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x2000L);\r
+      case 100:\r
+         if ((active0 & 0x10000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 52, 2);\r
+         break;\r
+      case 101:\r
+         if ((active0 & 0x100L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 8, 2);\r
+         break;\r
+      case 105:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x10000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x4000000000000L);\r
+      case 109:\r
+         if ((active0 & 0x10L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 4, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x40000000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x4000L);\r
+      case 114:\r
+         if ((active0 & 0x40000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 42, 2);\r
+         else if ((active0 & 0x100000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 44, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(7, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa9_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(7, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(8, active0, 0L);\r
+      return 9;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 101:\r
+         if ((active0 & 0x4000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 50, 2);\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x40000000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x2000L);\r
+      case 110:\r
+         if ((active0 & 0x4000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 14, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x10000000000L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(8, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa10_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(8, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(9, active0, 0L);\r
+      return 10;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 100:\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x40000000000000L);\r
+      case 101:\r
+         if ((active0 & 0x2000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 13, 2);\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x40000000L);\r
+      case 110:\r
+         if ((active0 & 0x10000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 40, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(9, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa11_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(9, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(10, active0, 0L);\r
+      return 11;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 98:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0x40000000000000L);\r
+      case 100:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return jjStartNfaWithStates_0(11, 30, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(10, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa12_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(10, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(11, active0, 0L);\r
+      return 12;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 121:\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(12, 54, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(11, active0, 0L);\r
+}\r
+private int jjStartNfaWithStates_0(int pos, int kind, int state)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) { return pos + 1; }\r
+   return jjMoveNfa_0(state, pos + 1);\r
+}\r
+static final long[] jjbitVec0 = {
+   0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+};\r
+private int jjMoveNfa_0(int startState, int curPos)\r
+{\r
+   int startsAt = 0;\r
+   jjnewStateCnt = 52;\r
+   int i = 1;\r
+   jjstateSet[0] = startState;\r
+   int kind = 0x7fffffff;\r
+   for (;;)\r
+   {\r
+      if (++jjround == 0x7fffffff)\r
+         ReInitRounds();\r
+      if (curChar < 64)\r
+      {\r
+         long l = 1L << curChar;\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 52:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 94)\r
+                        kind = 94;\r
+                     jjCheckNAddTwoStates(10, 11);\r
+                  }\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 93)\r
+                        kind = 93;\r
+                     jjCheckNAddTwoStates(48, 49);\r
+                  }\r
+                  break;\r
+               case 9:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 94)\r
+                        kind = 94;\r
+                     jjCheckNAddStates(0, 4);\r
+                  }\r
+                  else if (curChar == 46)\r
+                     jjCheckNAdd(10);\r
+                  break;\r
+               case 0:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 92)\r
+                        kind = 92;\r
+                     jjCheckNAddStates(5, 14);\r
+                  }\r
+                  else if ((0x100002600L & l) != 0L)\r
+                  {\r
+                     if (kind > 1)\r
+                        kind = 1;\r
+                  }\r
+                  else if (curChar == 46)\r
+                     jjCheckNAddTwoStates(48, 10);\r
+                  else if (curChar == 47)\r
+                     jjAddStates(15, 16);\r
+                  else if (curChar == 45)\r
+                     jjAddStates(17, 18);\r
+                  else if (curChar == 34)\r
+                     jjCheckNAddStates(19, 21);\r
+                  break;\r
+               case 27:\r
+                  if (curChar == 47)\r
+                  {\r
+                     if (kind > 3)\r
+                        kind = 3;\r
+                     jjCheckNAdd(34);\r
+                  }\r
+                  else if (curChar == 42)\r
+                     jjCheckNAddStates(22, 24);\r
+                  break;\r
+               case 2:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjstateSet[jjnewStateCnt++] = 2;\r
+                  break;\r
+               case 3:\r
+                  if (curChar == 34)\r
+                     jjCheckNAddStates(19, 21);\r
+                  break;\r
+               case 4:\r
+                  if ((0xfffffffbfffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(19, 21);\r
+                  break;\r
+               case 6:\r
+                  if ((0xfffffffffffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(19, 21);\r
+                  break;\r
+               case 7:\r
+                  if (curChar == 34 && kind > 91)\r
+                     kind = 91;\r
+                  break;\r
+               case 8:\r
+                  if (curChar == 45)\r
+                     jjAddStates(17, 18);\r
+                  break;\r
+               case 10:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAddTwoStates(10, 11);\r
+                  break;\r
+               case 12:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(13);\r
+                  break;\r
+               case 13:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAdd(13);\r
+                  break;\r
+               case 14:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAddStates(0, 4);\r
+                  break;\r
+               case 15:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAdd(15);\r
+                  break;\r
+               case 16:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(16, 17);\r
+                  break;\r
+               case 18:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(19);\r
+                  break;\r
+               case 19:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAdd(19);\r
+                  break;\r
+               case 20:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(20, 21);\r
+                  break;\r
+               case 21:\r
+                  if (curChar != 46)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAddTwoStates(22, 23);\r
+                  break;\r
+               case 22:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAddTwoStates(22, 23);\r
+                  break;\r
+               case 24:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(25);\r
+                  break;\r
+               case 25:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 94)\r
+                     kind = 94;\r
+                  jjCheckNAdd(25);\r
+                  break;\r
+               case 26:\r
+                  if (curChar == 47)\r
+                     jjAddStates(15, 16);\r
+                  break;\r
+               case 28:\r
+                  if ((0xfffffbffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(22, 24);\r
+                  break;\r
+               case 29:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 30;\r
+                  break;\r
+               case 30:\r
+                  if ((0xffff7fffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(22, 24);\r
+                  break;\r
+               case 31:\r
+                  if (curChar == 47 && kind > 2)\r
+                     kind = 2;\r
+                  break;\r
+               case 32:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 31;\r
+                  break;\r
+               case 33:\r
+                  if (curChar != 47)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(34);\r
+                  break;\r
+               case 34:\r
+                  if ((0xfffffffffffffbffL & l) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(34);\r
+                  break;\r
+               case 35:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAddStates(5, 14);\r
+                  break;\r
+               case 36:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 92)\r
+                     kind = 92;\r
+                  jjCheckNAdd(36);\r
+                  break;\r
+               case 37:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(37, 38);\r
+                  break;\r
+               case 38:\r
+                  if (curChar != 46)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAddTwoStates(39, 40);\r
+                  break;\r
+               case 39:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAddTwoStates(39, 40);\r
+                  break;\r
+               case 41:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(42);\r
+                  break;\r
+               case 42:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAdd(42);\r
+                  break;\r
+               case 43:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(43, 44);\r
+                  break;\r
+               case 45:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(46);\r
+                  break;\r
+               case 46:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAdd(46);\r
+                  break;\r
+               case 47:\r
+                  if (curChar == 46)\r
+                     jjCheckNAddTwoStates(48, 10);\r
+                  break;\r
+               case 48:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAddTwoStates(48, 49);\r
+                  break;\r
+               case 50:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(51);\r
+                  break;\r
+               case 51:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 93)\r
+                     kind = 93;\r
+                  jjCheckNAdd(51);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else if (curChar < 128)\r
+      {\r
+         long l = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 0:\r
+               case 2:\r
+                  if ((0x7fffffe87fffffeL & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 4:\r
+                  if ((0xffffffffefffffffL & l) != 0L)\r
+                     jjCheckNAddStates(19, 21);\r
+                  break;\r
+               case 5:\r
+                  if (curChar == 92)\r
+                     jjstateSet[jjnewStateCnt++] = 6;\r
+                  break;\r
+               case 6:\r
+                  jjCheckNAddStates(19, 21);\r
+                  break;\r
+               case 11:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(25, 26);\r
+                  break;\r
+               case 17:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(27, 28);\r
+                  break;\r
+               case 23:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(29, 30);\r
+                  break;\r
+               case 28:\r
+               case 30:\r
+                  jjCheckNAddStates(22, 24);\r
+                  break;\r
+               case 34:\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 34;\r
+                  break;\r
+               case 40:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(31, 32);\r
+                  break;\r
+               case 44:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(33, 34);\r
+                  break;\r
+               case 49:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(35, 36);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else\r
+      {\r
+         int i2 = (curChar & 0xff) >> 6;\r
+         long l2 = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 4:\r
+               case 6:\r
+                  if ((jjbitVec0[i2] & l2) != 0L)\r
+                     jjCheckNAddStates(19, 21);\r
+                  break;\r
+               case 28:\r
+               case 30:\r
+                  if ((jjbitVec0[i2] & l2) != 0L)\r
+                     jjCheckNAddStates(22, 24);\r
+                  break;\r
+               case 34:\r
+                  if ((jjbitVec0[i2] & l2) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 34;\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      if (kind != 0x7fffffff)\r
+      {\r
+         jjmatchedKind = kind;\r
+         jjmatchedPos = curPos;\r
+         kind = 0x7fffffff;\r
+      }\r
+      ++curPos;\r
+      if ((i = jjnewStateCnt) == (startsAt = 52 - (jjnewStateCnt = startsAt)))\r
+         return curPos;\r
+      try { curChar = input_stream.readChar(); }\r
+      catch(java.io.IOException e) { return curPos; }\r
+   }\r
+}\r
+static final int[] jjnextStates = {
+   15, 16, 17, 20, 21, 36, 37, 38, 43, 44, 15, 16, 17, 20, 21, 27, 
+   33, 9, 14, 4, 5, 7, 28, 29, 32, 12, 13, 18, 19, 24, 25, 41, 
+   42, 45, 46, 50, 51, 
+};\r
+\r
+/** Token literal values. */\r
+public static final String[] jjstrLiteralImages = {\r
+"", null, null, null, "\141\154\147\157\162\151\164\150\155", \r
+"\144\151\163\143\162\145\164\145", "\146\141\154\163\145", "\155\157\144\145\154", \r
+"\162\145\144\145\143\154\141\162\145", "\141\156\144", "\145\141\143\150", "\146\151\156\141\154", "\156\157\164", \r
+"\162\145\160\154\141\143\145\141\142\154\145", "\141\156\156\157\164\141\164\151\157\156", "\145\154\163\145", \r
+"\146\154\157\167", "\157\160\145\162\141\164\157\162", "\162\145\164\165\162\156", \r
+"\141\163\163\145\162\164", "\145\154\163\145\151\146", "\146\157\162", "\157\162", \r
+"\163\164\162\145\141\155", "\142\154\157\143\153", "\145\154\163\145\167\150\145\156", \r
+"\146\165\156\143\164\151\157\156", "\157\165\164\145\162", "\164\150\145\156", "\142\162\145\141\153", \r
+"\145\156\143\141\160\163\165\154\141\164\145\144", "\151\146", "\157\165\164\160\165\164", "\164\162\165\145", \r
+"\143\154\141\163\163", "\145\156\144", "\151\155\160\157\162\164", "\160\141\143\153\141\147\145", \r
+"\164\171\160\145", "\143\157\156\156\145\143\164", \r
+"\145\156\165\155\145\162\141\164\151\157\156", "\151\156", "\160\141\162\141\155\145\164\145\162", "\167\150\145\156", \r
+"\143\157\156\156\145\143\164\157\162", "\145\161\165\141\164\151\157\156", "\151\156\151\164\151\141\154", \r
+"\160\141\162\164\151\141\154", "\167\150\151\154\145", "\143\157\156\163\164\141\156\164", \r
+"\145\170\160\141\156\144\141\142\154\145", "\151\156\156\145\162", "\160\162\157\164\145\143\164\145\144", \r
+"\167\151\164\150\151\156", "\143\157\156\163\164\162\141\151\156\145\144\142\171", \r
+"\145\170\164\145\156\144\163", "\151\156\160\165\164", "\160\165\142\154\151\143", "\144\145\162", \r
+"\145\170\164\145\162\156\141\154", "\154\157\157\160", "\162\145\143\157\162\144", "\50", "\51", "\173", "\175", \r
+"\133", "\135", "\56", "\72", "\73", "\54", "\74", "\74\75", "\76", "\76\75", \r
+"\75\75", "\74\76", "\53", "\55", "\56\53", "\56\55", "\52", "\57", "\56\52", "\56\57", \r
+"\136", "\56\136", "\75", "\72\75", null, null, null, null, null, };\r
+\r
+/** Lexer state names. */\r
+public static final String[] lexStateNames = {\r
+   "DEFAULT",\r
+};\r
+static final long[] jjtoToken = {
+   0xfffffffffffffff1L, 0x7fffffffL, 
+};\r
+static final long[] jjtoSkip = {
+   0xeL, 0x0L, 
+};\r
+protected SimpleCharStream input_stream;\r
+private final int[] jjrounds = new int[52];\r
+private final int[] jjstateSet = new int[104];\r
+private final StringBuilder jjimage = new StringBuilder();\r
+private StringBuilder image = jjimage;\r
+private int jjimageLen;\r
+private int lengthOfMatch;\r
+protected char curChar;\r
+/** Constructor. */\r
+public TableParserTokenManager(SimpleCharStream stream){\r
+   if (SimpleCharStream.staticFlag)\r
+      throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");\r
+   input_stream = stream;\r
+}\r
+\r
+/** Constructor. */\r
+public TableParserTokenManager(SimpleCharStream stream, int lexState){\r
+   this(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream)\r
+{\r
+   jjmatchedPos = jjnewStateCnt = 0;\r
+   curLexState = defaultLexState;\r
+   input_stream = stream;\r
+   ReInitRounds();\r
+}\r
+private void ReInitRounds()\r
+{\r
+   int i;\r
+   jjround = 0x80000001;\r
+   for (i = 52; i-- > 0;)\r
+      jjrounds[i] = 0x80000000;\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream, int lexState)\r
+{\r
+   ReInit(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Switch to specified lex state. */\r
+public void SwitchTo(int lexState)\r
+{\r
+   if (lexState >= 1 || lexState < 0)\r
+      throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);\r
+   else\r
+      curLexState = lexState;\r
+}\r
+\r
+protected Token jjFillToken()\r
+{\r
+   final Token t;\r
+   final String curTokenImage;\r
+   final int beginLine;\r
+   final int endLine;\r
+   final int beginColumn;\r
+   final int endColumn;\r
+   String im = jjstrLiteralImages[jjmatchedKind];\r
+   curTokenImage = (im == null) ? input_stream.GetImage() : im;\r
+   beginLine = input_stream.getBeginLine();\r
+   beginColumn = input_stream.getBeginColumn();\r
+   endLine = input_stream.getEndLine();\r
+   endColumn = input_stream.getEndColumn();\r
+   t = Token.newToken(jjmatchedKind, curTokenImage);\r
+\r
+   t.beginLine = beginLine;\r
+   t.endLine = endLine;\r
+   t.beginColumn = beginColumn;\r
+   t.endColumn = endColumn;\r
+\r
+   return t;\r
+}\r
+\r
+int curLexState = 0;\r
+int defaultLexState = 0;\r
+int jjnewStateCnt;\r
+int jjround;\r
+int jjmatchedPos;\r
+int jjmatchedKind;\r
+\r
+/** Get the next Token. */\r
+public Token getNextToken() \r
+{\r
+  Token matchedToken;\r
+  int curPos = 0;\r
+\r
+  EOFLoop :
+  for (;;)\r
+  {\r
+   try\r
+   {\r
+      curChar = input_stream.BeginToken();\r
+   }\r
+   catch(java.io.IOException e)\r
+   {\r
+      jjmatchedKind = 0;\r
+      matchedToken = jjFillToken();\r
+      return matchedToken;\r
+   }\r
+   image = jjimage;\r
+   image.setLength(0);\r
+   jjimageLen = 0;\r
+\r
+   jjmatchedKind = 0x7fffffff;\r
+   jjmatchedPos = 0;\r
+   curPos = jjMoveStringLiteralDfa0_0();\r
+   if (jjmatchedKind != 0x7fffffff)\r
+   {\r
+      if (jjmatchedPos + 1 < curPos)\r
+         input_stream.backup(curPos - jjmatchedPos - 1);\r
+      if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)\r
+      {\r
+         matchedToken = jjFillToken();\r
+         TokenLexicalActions(matchedToken);\r
+         return matchedToken;\r
+      }\r
+      else\r
+      {\r
+         continue EOFLoop;\r
+      }\r
+   }\r
+   int error_line = input_stream.getEndLine();\r
+   int error_column = input_stream.getEndColumn();\r
+   String error_after = null;\r
+   boolean EOFSeen = false;\r
+   try { input_stream.readChar(); input_stream.backup(1); }\r
+   catch (java.io.IOException e1) {\r
+      EOFSeen = true;\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+      if (curChar == '\n' || curChar == '\r') {\r
+         error_line++;\r
+         error_column = 0;\r
+      }\r
+      else\r
+         error_column++;\r
+   }\r
+   if (!EOFSeen) {\r
+      input_stream.backup(1);\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+   }\r
+   throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);\r
+  }\r
+}\r
+\r
+void TokenLexicalActions(Token matchedToken)\r
+{\r
+   switch(jjmatchedKind)\r
+   {\r
+      case 91 :\r
+        image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)));\r
+      matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+}\r
+private void jjCheckNAdd(int state)\r
+{\r
+   if (jjrounds[state] != jjround)\r
+   {\r
+      jjstateSet[jjnewStateCnt++] = state;\r
+      jjrounds[state] = jjround;\r
+   }\r
+}\r
+private void jjAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjstateSet[jjnewStateCnt++] = jjnextStates[start];\r
+   } while (start++ != end);\r
+}\r
+private void jjCheckNAddTwoStates(int state1, int state2)\r
+{\r
+   jjCheckNAdd(state1);\r
+   jjCheckNAdd(state2);\r
+}\r
+\r
+private void jjCheckNAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjCheckNAdd(jjnextStates[start]);\r
+   } while (start++ != end);\r
+}\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/Token.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/Token.java
new file mode 100644 (file)
index 0000000..e5636f3
--- /dev/null
@@ -0,0 +1,142 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+/* Generated By:JavaCC: Do not edit this line. Token.java Version 5.0 */\r
+/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package org.simantics.sysdyn.tableParser;\r
+\r
+/**\r
+ * Describes the input token stream.\r
+ */\r
+\r
+public class Token implements java.io.Serializable {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * An integer that describes the kind of this token.  This numbering\r
+   * system is determined by JavaCCParser, and a table of these numbers is\r
+   * stored in the file ...Constants.java.\r
+   */\r
+  public int kind;\r
+\r
+  /** The line number of the first character of this Token. */\r
+  public int beginLine;\r
+  /** The column number of the first character of this Token. */\r
+  public int beginColumn;\r
+  /** The line number of the last character of this Token. */\r
+  public int endLine;\r
+  /** The column number of the last character of this Token. */\r
+  public int endColumn;\r
+\r
+  /**\r
+   * The string image of the token.\r
+   */\r
+  public String image;\r
+\r
+  /**\r
+   * A reference to the next regular (non-special) token from the input\r
+   * stream.  If this is the last token from the input stream, or if the\r
+   * token manager has not read tokens beyond this one, this field is\r
+   * set to null.  This is true only if this token is also a regular\r
+   * token.  Otherwise, see below for a description of the contents of\r
+   * this field.\r
+   */\r
+  public Token next;\r
+\r
+  /**\r
+   * This field is used to access special tokens that occur prior to this\r
+   * token, but after the immediately preceding regular (non-special) token.\r
+   * If there are no such special tokens, this field is set to null.\r
+   * When there are more than one such special token, this field refers\r
+   * to the last of these special tokens, which in turn refers to the next\r
+   * previous special token through its specialToken field, and so on\r
+   * until the first special token (whose specialToken field is null).\r
+   * The next fields of special tokens refer to other special tokens that\r
+   * immediately follow it (without an intervening regular token).  If there\r
+   * is no such token, this field is null.\r
+   */\r
+  public Token specialToken;\r
+\r
+  /**\r
+   * An optional attribute value of the Token.\r
+   * Tokens which are not used as syntactic sugar will often contain\r
+   * meaningful values that will be used later on by the compiler or\r
+   * interpreter. This attribute value is often different from the image.\r
+   * Any subclass of Token that actually wants to return a non-null value can\r
+   * override this method as appropriate.\r
+   */\r
+  public Object getValue() {\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * No-argument constructor\r
+   */\r
+  public Token() {}\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image.\r
+   */\r
+  public Token(int kind)\r
+  {\r
+    this(kind, null);\r
+  }\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image and Kind.\r
+   */\r
+  public Token(int kind, String image)\r
+  {\r
+    this.kind = kind;\r
+    this.image = image;\r
+  }\r
+\r
+  /**\r
+   * Returns the image.\r
+   */\r
+  public String toString()\r
+  {\r
+    return image;\r
+  }\r
+\r
+  /**\r
+   * Returns a new Token object, by default. However, if you want, you\r
+   * can create and return subclass objects based on the value of ofKind.\r
+   * Simply add the cases to the switch for all those special cases.\r
+   * For example, if you have a subclass of Token called IDToken that\r
+   * you want to create if ofKind is ID, simply add something like :\r
+   *\r
+   *    case MyParserConstants.ID : return new IDToken(ofKind, image);\r
+   *\r
+   * to the following switch statement. Then you can cast matchedToken\r
+   * variable to the appropriate type and use sit in your lexical actions.\r
+   */\r
+  public static Token newToken(int ofKind, String image)\r
+  {\r
+    switch(ofKind)\r
+    {\r
+      default : return new Token(ofKind, image);\r
+    }\r
+  }\r
+\r
+  public static Token newToken(int ofKind)\r
+  {\r
+    return newToken(ofKind, null);\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=d63d0e2011f8ce7fbf4f8ee6fd4e3986 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TokenMgrError.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/tableParser/TokenMgrError.java
new file mode 100644 (file)
index 0000000..49dbdbf
--- /dev/null
@@ -0,0 +1,158 @@
+/*******************************************************************************\r
+ * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 5.0 */\r
+/* JavaCCOptions: */\r
+package org.simantics.sysdyn.tableParser;\r
+\r
+/** Token Manager Error. */\r
+public class TokenMgrError extends Error\r
+{\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /*\r
+   * Ordinals for various reasons why an Error of this type can be thrown.\r
+   */\r
+\r
+  /**\r
+   * Lexical error occurred.\r
+   */\r
+  static final int LEXICAL_ERROR = 0;\r
+\r
+  /**\r
+   * An attempt was made to create a second instance of a static token manager.\r
+   */\r
+  static final int STATIC_LEXER_ERROR = 1;\r
+\r
+  /**\r
+   * Tried to change to an invalid lexical state.\r
+   */\r
+  static final int INVALID_LEXICAL_STATE = 2;\r
+\r
+  /**\r
+   * Detected (and bailed out of) an infinite loop in the token manager.\r
+   */\r
+  static final int LOOP_DETECTED = 3;\r
+\r
+  /**\r
+   * Indicates the reason why the exception is thrown. It will have\r
+   * one of the above 4 values.\r
+   */\r
+  int errorCode;\r
+\r
+  /**\r
+   * Replaces unprintable characters by their escaped (or unicode escaped)\r
+   * equivalents in the given string\r
+   */\r
+  protected static final String addEscapes(String str) {\r
+    StringBuffer retval = new StringBuffer();\r
+    char ch;\r
+    for (int i = 0; i < str.length(); i++) {\r
+      switch (str.charAt(i))\r
+      {\r
+        case 0 :\r
+          continue;\r
+        case '\b':\r
+          retval.append("\\b");\r
+          continue;\r
+        case '\t':\r
+          retval.append("\\t");\r
+          continue;\r
+        case '\n':\r
+          retval.append("\\n");\r
+          continue;\r
+        case '\f':\r
+          retval.append("\\f");\r
+          continue;\r
+        case '\r':\r
+          retval.append("\\r");\r
+          continue;\r
+        case '\"':\r
+          retval.append("\\\"");\r
+          continue;\r
+        case '\'':\r
+          retval.append("\\\'");\r
+          continue;\r
+        case '\\':\r
+          retval.append("\\\\");\r
+          continue;\r
+        default:\r
+          if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+            String s = "0000" + Integer.toString(ch, 16);\r
+            retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+          } else {\r
+            retval.append(ch);\r
+          }\r
+          continue;\r
+      }\r
+    }\r
+    return retval.toString();\r
+  }\r
+\r
+  /**\r
+   * Returns a detailed message for the Error when it is thrown by the\r
+   * token manager to indicate a lexical error.\r
+   * Parameters :\r
+   *    EOFSeen     : indicates if EOF caused the lexical error\r
+   *    curLexState : lexical state in which this error occurred\r
+   *    errorLine   : line number when the error occurred\r
+   *    errorColumn : column number when the error occurred\r
+   *    errorAfter  : prefix that was seen before this error occurred\r
+   *    curchar     : the offending character\r
+   * Note: You can customize the lexical error message by modifying this method.\r
+   */\r
+  protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {\r
+    return("Lexical error at line " +\r
+          errorLine + ", column " +\r
+          errorColumn + ".  Encountered: " +\r
+          (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +\r
+          "after : \"" + addEscapes(errorAfter) + "\"");\r
+  }\r
+\r
+  /**\r
+   * You can also modify the body of this method to customize your error messages.\r
+   * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not\r
+   * of end-users concern, so you can return something like :\r
+   *\r
+   *     "Internal Error : Please file a bug report .... "\r
+   *\r
+   * from this method for such cases in the release version of your parser.\r
+   */\r
+  public String getMessage() {\r
+    return super.getMessage();\r
+  }\r
+\r
+  /*\r
+   * Constructors of various flavors follow.\r
+   */\r
+\r
+  /** No arg constructor. */\r
+  public TokenMgrError() {\r
+  }\r
+\r
+  /** Constructor with message and reason. */\r
+  public TokenMgrError(String message, int reason) {\r
+    super(message);\r
+    errorCode = reason;\r
+  }\r
+\r
+  /** Full Constructor. */\r
+  public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {\r
+    this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);\r
+  }\r
+}\r
+/* JavaCC - OriginalChecksum=abb0cd060e347479552118d1e61a7e46 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/JJTUnitParserState.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/JJTUnitParserState.java
new file mode 100644 (file)
index 0000000..9988da3
--- /dev/null
@@ -0,0 +1,123 @@
+/* Generated By:JavaCC: Do not edit this line. JJTUnitParserState.java Version 5.0 */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+public class JJTUnitParserState {\r
+  private java.util.List<Node> nodes;\r
+  private java.util.List<Integer> marks;\r
+\r
+  private int sp;        // number of nodes on stack\r
+  private int mk;        // current mark\r
+  private boolean node_created;\r
+\r
+  public JJTUnitParserState() {\r
+    nodes = new java.util.ArrayList<Node>();\r
+    marks = new java.util.ArrayList<Integer>();\r
+    sp = 0;\r
+    mk = 0;\r
+  }\r
+\r
+  /* Determines whether the current node was actually closed and\r
+     pushed.  This should only be called in the final user action of a\r
+     node scope.  */\r
+  public boolean nodeCreated() {\r
+    return node_created;\r
+  }\r
+\r
+  /* Call this to reinitialize the node stack.  It is called\r
+     automatically by the parser's ReInit() method. */\r
+  public void reset() {\r
+    nodes.clear();\r
+    marks.clear();\r
+    sp = 0;\r
+    mk = 0;\r
+  }\r
+\r
+  /* Returns the root node of the AST.  It only makes sense to call\r
+     this after a successful parse. */\r
+  public Node rootNode() {\r
+    return nodes.get(0);\r
+  }\r
+\r
+  /* Pushes a node on to the stack. */\r
+  public void pushNode(Node n) {\r
+    nodes.add(n);\r
+    ++sp;\r
+  }\r
+\r
+  /* Returns the node on the top of the stack, and remove it from the\r
+     stack.  */\r
+  public Node popNode() {\r
+    if (--sp < mk) {\r
+      mk = marks.remove(marks.size()-1);\r
+    }\r
+    return nodes.remove(nodes.size()-1);\r
+  }\r
+\r
+  /* Returns the node currently on the top of the stack. */\r
+  public Node peekNode() {\r
+    return nodes.get(nodes.size()-1);\r
+  }\r
+\r
+  /* Returns the number of children on the stack in the current node\r
+     scope. */\r
+  public int nodeArity() {\r
+    return sp - mk;\r
+  }\r
+\r
+\r
+  public void clearNodeScope(Node n) {\r
+    while (sp > mk) {\r
+      popNode();\r
+    }\r
+    mk = marks.remove(marks.size()-1);\r
+  }\r
+\r
+\r
+  public void openNodeScope(Node n) {\r
+    marks.add(mk);\r
+    mk = sp;\r
+    n.jjtOpen();\r
+  }\r
+\r
+\r
+  /* A definite node is constructed from a specified number of\r
+     children.  That number of nodes are popped from the stack and\r
+     made the children of the definite node.  Then the definite node\r
+     is pushed on to the stack. */\r
+  public void closeNodeScope(Node n, int num) {\r
+    mk = marks.remove(marks.size()-1);\r
+    while (num-- > 0) {\r
+      Node c = popNode();\r
+      c.jjtSetParent(n);\r
+      n.jjtAddChild(c, num);\r
+    }\r
+    n.jjtClose();\r
+    pushNode(n);\r
+    node_created = true;\r
+  }\r
+\r
+\r
+  /* A conditional node is constructed if its condition is true.  All\r
+     the nodes that have been pushed since the node was opened are\r
+     made children of the conditional node, which is then pushed\r
+     on to the stack.  If the condition is false the node is not\r
+     constructed and they are left on the stack. */\r
+  public void closeNodeScope(Node n, boolean condition) {\r
+    if (condition) {\r
+      int a = nodeArity();\r
+      mk = marks.remove(marks.size()-1);\r
+      while (a-- > 0) {\r
+        Node c = popNode();\r
+        c.jjtSetParent(n);\r
+        n.jjtAddChild(c, a);\r
+      }\r
+      n.jjtClose();\r
+      pushNode(n);\r
+      node_created = true;\r
+    } else {\r
+      mk = marks.remove(marks.size()-1);\r
+      node_created = false;\r
+    }\r
+  }\r
+}\r
+/* JavaCC - OriginalChecksum=d0c8ac05372006e3b61e33c0a234ef07 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/Node.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/Node.java
new file mode 100644 (file)
index 0000000..bb89e6a
--- /dev/null
@@ -0,0 +1,36 @@
+/* Generated By:JJTree: Do not edit this line. Node.java Version 4.3 */\r
+/* JavaCCOptions:MULTI=false,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=UnitCheckingNodeFactory,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+/* All AST nodes must implement this interface.  It provides basic\r
+   machinery for constructing the parent and child relationships\r
+   between nodes. */\r
+\r
+public\r
+interface Node {\r
+\r
+  /** This method is called after the node has been made the current\r
+    node.  It indicates that child nodes can now be added to it. */\r
+  public void jjtOpen();\r
+\r
+  /** This method is called after all the child nodes have been\r
+    added. */\r
+  public void jjtClose();\r
+\r
+  /** This pair of methods are used to inform the node of its\r
+    parent. */\r
+  public void jjtSetParent(Node n);\r
+  public Node jjtGetParent();\r
+\r
+  /** This method tells the node to add its argument to the node's\r
+    list of children.  */\r
+  public void jjtAddChild(Node n, int i);\r
+\r
+  /** This method returns a child node.  The children are numbered\r
+     from zero, left to right. */\r
+  public Node jjtGetChild(int i);\r
+\r
+  /** Return the number of children the node has. */\r
+  public int jjtGetNumChildren();\r
+}\r
+/* JavaCC - OriginalChecksum=851e4a7b403fad4367cc9f6859ec9c32 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/ParseException.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/ParseException.java
new file mode 100644 (file)
index 0000000..fa6de90
--- /dev/null
@@ -0,0 +1,187 @@
+/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */\r
+/* JavaCCOptions:KEEP_LINE_COL=null */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+/**\r
+ * This exception is thrown when parse errors are encountered.\r
+ * You can explicitly create objects of this exception type by\r
+ * calling the method generateParseException in the generated\r
+ * parser.\r
+ *\r
+ * You can modify this class to customize your error reporting\r
+ * mechanisms so long as you retain the public fields.\r
+ */\r
+public class ParseException extends Exception {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * This constructor is used by the method "generateParseException"\r
+   * in the generated parser.  Calling this constructor generates\r
+   * a new object of this type with the fields "currentToken",\r
+   * "expectedTokenSequences", and "tokenImage" set.\r
+   */\r
+  public ParseException(Token currentTokenVal,\r
+                        int[][] expectedTokenSequencesVal,\r
+                        String[] tokenImageVal\r
+                       )\r
+  {\r
+    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));\r
+    currentToken = currentTokenVal;\r
+    expectedTokenSequences = expectedTokenSequencesVal;\r
+    tokenImage = tokenImageVal;\r
+  }\r
+\r
+  /**\r
+   * The following constructors are for use by you for whatever\r
+   * purpose you can think of.  Constructing the exception in this\r
+   * manner makes the exception behave in the normal way - i.e., as\r
+   * documented in the class "Throwable".  The fields "errorToken",\r
+   * "expectedTokenSequences", and "tokenImage" do not contain\r
+   * relevant information.  The JavaCC generated code does not use\r
+   * these constructors.\r
+   */\r
+\r
+  public ParseException() {\r
+    super();\r
+  }\r
+\r
+  /** Constructor with message. */\r
+  public ParseException(String message) {\r
+    super(message);\r
+  }\r
+\r
+\r
+  /**\r
+   * This is the last token that has been consumed successfully.  If\r
+   * this object has been created due to a parse error, the token\r
+   * followng this token will (therefore) be the first error token.\r
+   */\r
+  public Token currentToken;\r
+\r
+  /**\r
+   * Each entry in this array is an array of integers.  Each array\r
+   * of integers represents a sequence of tokens (by their ordinal\r
+   * values) that is expected at this point of the parse.\r
+   */\r
+  public int[][] expectedTokenSequences;\r
+\r
+  /**\r
+   * This is a reference to the "tokenImage" array of the generated\r
+   * parser within which the parse error occurred.  This array is\r
+   * defined in the generated ...Constants interface.\r
+   */\r
+  public String[] tokenImage;\r
+\r
+  /**\r
+   * It uses "currentToken" and "expectedTokenSequences" to generate a parse\r
+   * error message and returns it.  If this object has been created\r
+   * due to a parse error, and you do not catch it (it gets thrown\r
+   * from the parser) the correct error message\r
+   * gets displayed.\r
+   */\r
+  private static String initialise(Token currentToken,\r
+                           int[][] expectedTokenSequences,\r
+                           String[] tokenImage) {\r
+    String eol = System.getProperty("line.separator", "\n");\r
+    StringBuffer expected = new StringBuffer();\r
+    int maxSize = 0;\r
+    for (int i = 0; i < expectedTokenSequences.length; i++) {\r
+      if (maxSize < expectedTokenSequences[i].length) {\r
+        maxSize = expectedTokenSequences[i].length;\r
+      }\r
+      for (int j = 0; j < expectedTokenSequences[i].length; j++) {\r
+        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');\r
+      }\r
+      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {\r
+        expected.append("...");\r
+      }\r
+      expected.append(eol).append("    ");\r
+    }\r
+    String retval = "Encountered \"";\r
+    Token tok = currentToken.next;\r
+    for (int i = 0; i < maxSize; i++) {\r
+      if (i != 0) retval += " ";\r
+      if (tok.kind == 0) {\r
+        retval += tokenImage[0];\r
+        break;\r
+      }\r
+      retval += " " + tokenImage[tok.kind];\r
+      retval += " \"";\r
+      retval += add_escapes(tok.image);\r
+      retval += " \"";\r
+      tok = tok.next;\r
+    }\r
+    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;\r
+    retval += "." + eol;\r
+    if (expectedTokenSequences.length == 1) {\r
+      retval += "Was expecting:" + eol + "    ";\r
+    } else {\r
+      retval += "Was expecting one of:" + eol + "    ";\r
+    }\r
+    retval += expected.toString();\r
+    return retval;\r
+  }\r
+\r
+  /**\r
+   * The end of line string for this machine.\r
+   */\r
+  protected String eol = System.getProperty("line.separator", "\n");\r
+\r
+  /**\r
+   * Used to convert raw characters to their escaped version\r
+   * when these raw version cannot be used as part of an ASCII\r
+   * string literal.\r
+   */\r
+  static String add_escapes(String str) {\r
+      StringBuffer retval = new StringBuffer();\r
+      char ch;\r
+      for (int i = 0; i < str.length(); i++) {\r
+        switch (str.charAt(i))\r
+        {\r
+           case 0 :\r
+              continue;\r
+           case '\b':\r
+              retval.append("\\b");\r
+              continue;\r
+           case '\t':\r
+              retval.append("\\t");\r
+              continue;\r
+           case '\n':\r
+              retval.append("\\n");\r
+              continue;\r
+           case '\f':\r
+              retval.append("\\f");\r
+              continue;\r
+           case '\r':\r
+              retval.append("\\r");\r
+              continue;\r
+           case '\"':\r
+              retval.append("\\\"");\r
+              continue;\r
+           case '\'':\r
+              retval.append("\\\'");\r
+              continue;\r
+           case '\\':\r
+              retval.append("\\\\");\r
+              continue;\r
+           default:\r
+              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+                 String s = "0000" + Integer.toString(ch, 16);\r
+                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+              } else {\r
+                 retval.append(ch);\r
+              }\r
+              continue;\r
+        }\r
+      }\r
+      return retval.toString();\r
+   }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=4af9901dc6c68e7e4e08ab85f10baa96 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/SimpleCharStream.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/SimpleCharStream.java
new file mode 100644 (file)
index 0000000..a7b4b80
--- /dev/null
@@ -0,0 +1,471 @@
+/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */\r
+/* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+/**\r
+ * An implementation of interface CharStream, where the stream is assumed to\r
+ * contain only ASCII characters (without unicode processing).\r
+ */\r
+\r
+public class SimpleCharStream\r
+{\r
+/** Whether parser is static. */\r
+  public static final boolean staticFlag = false;\r
+  int bufsize;\r
+  int available;\r
+  int tokenBegin;\r
+/** Position in buffer. */\r
+  public int bufpos = -1;\r
+  protected int bufline[];\r
+  protected int bufcolumn[];\r
+\r
+  protected int column = 0;\r
+  protected int line = 1;\r
+\r
+  protected boolean prevCharIsCR = false;\r
+  protected boolean prevCharIsLF = false;\r
+\r
+  protected java.io.Reader inputStream;\r
+\r
+  protected char[] buffer;\r
+  protected int maxNextCharInd = 0;\r
+  protected int inBuf = 0;\r
+  protected int tabSize = 8;\r
+\r
+  protected void setTabSize(int i) { tabSize = i; }\r
+  protected int getTabSize(int i) { return tabSize; }\r
+\r
+\r
+  protected void ExpandBuff(boolean wrapAround)\r
+  {\r
+    char[] newbuffer = new char[bufsize + 2048];\r
+    int newbufline[] = new int[bufsize + 2048];\r
+    int newbufcolumn[] = new int[bufsize + 2048];\r
+\r
+    try\r
+    {\r
+      if (wrapAround)\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos += (bufsize - tokenBegin));\r
+      }\r
+      else\r
+      {\r
+        System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);\r
+        buffer = newbuffer;\r
+\r
+        System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);\r
+        bufline = newbufline;\r
+\r
+        System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);\r
+        bufcolumn = newbufcolumn;\r
+\r
+        maxNextCharInd = (bufpos -= tokenBegin);\r
+      }\r
+    }\r
+    catch (Throwable t)\r
+    {\r
+      throw new Error(t.getMessage());\r
+    }\r
+\r
+\r
+    bufsize += 2048;\r
+    available = bufsize;\r
+    tokenBegin = 0;\r
+  }\r
+\r
+  protected void FillBuff() throws java.io.IOException\r
+  {\r
+    if (maxNextCharInd == available)\r
+    {\r
+      if (available == bufsize)\r
+      {\r
+        if (tokenBegin > 2048)\r
+        {\r
+          bufpos = maxNextCharInd = 0;\r
+          available = tokenBegin;\r
+        }\r
+        else if (tokenBegin < 0)\r
+          bufpos = maxNextCharInd = 0;\r
+        else\r
+          ExpandBuff(false);\r
+      }\r
+      else if (available > tokenBegin)\r
+        available = bufsize;\r
+      else if ((tokenBegin - available) < 2048)\r
+        ExpandBuff(true);\r
+      else\r
+        available = tokenBegin;\r
+    }\r
+\r
+    int i;\r
+    try {\r
+      if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)\r
+      {\r
+        inputStream.close();\r
+        throw new java.io.IOException();\r
+      }\r
+      else\r
+        maxNextCharInd += i;\r
+      return;\r
+    }\r
+    catch(java.io.IOException e) {\r
+      --bufpos;\r
+      backup(0);\r
+      if (tokenBegin == -1)\r
+        tokenBegin = bufpos;\r
+      throw e;\r
+    }\r
+  }\r
+\r
+/** Start. */\r
+  public char BeginToken() throws java.io.IOException\r
+  {\r
+    tokenBegin = -1;\r
+    char c = readChar();\r
+    tokenBegin = bufpos;\r
+\r
+    return c;\r
+  }\r
+\r
+  protected void UpdateLineColumn(char c)\r
+  {\r
+    column++;\r
+\r
+    if (prevCharIsLF)\r
+    {\r
+      prevCharIsLF = false;\r
+      line += (column = 1);\r
+    }\r
+    else if (prevCharIsCR)\r
+    {\r
+      prevCharIsCR = false;\r
+      if (c == '\n')\r
+      {\r
+        prevCharIsLF = true;\r
+      }\r
+      else\r
+        line += (column = 1);\r
+    }\r
+\r
+    switch (c)\r
+    {\r
+      case '\r' :\r
+        prevCharIsCR = true;\r
+        break;\r
+      case '\n' :\r
+        prevCharIsLF = true;\r
+        break;\r
+      case '\t' :\r
+        column--;\r
+        column += (tabSize - (column % tabSize));\r
+        break;\r
+      default :\r
+        break;\r
+    }\r
+\r
+    bufline[bufpos] = line;\r
+    bufcolumn[bufpos] = column;\r
+  }\r
+\r
+/** Read a character. */\r
+  public char readChar() throws java.io.IOException\r
+  {\r
+    if (inBuf > 0)\r
+    {\r
+      --inBuf;\r
+\r
+      if (++bufpos == bufsize)\r
+        bufpos = 0;\r
+\r
+      return buffer[bufpos];\r
+    }\r
+\r
+    if (++bufpos >= maxNextCharInd)\r
+      FillBuff();\r
+\r
+    char c = buffer[bufpos];\r
+\r
+    UpdateLineColumn(c);\r
+    return c;\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndColumn\r
+   */\r
+\r
+  public int getColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  @Deprecated\r
+  /**\r
+   * @deprecated\r
+   * @see #getEndLine\r
+   */\r
+\r
+  public int getLine() {\r
+    return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token end column number. */\r
+  public int getEndColumn() {\r
+    return bufcolumn[bufpos];\r
+  }\r
+\r
+  /** Get token end line number. */\r
+  public int getEndLine() {\r
+     return bufline[bufpos];\r
+  }\r
+\r
+  /** Get token beginning column number. */\r
+  public int getBeginColumn() {\r
+    return bufcolumn[tokenBegin];\r
+  }\r
+\r
+  /** Get token beginning line number. */\r
+  public int getBeginLine() {\r
+    return bufline[tokenBegin];\r
+  }\r
+\r
+/** Backup a number of characters. */\r
+  public void backup(int amount) {\r
+\r
+    inBuf += amount;\r
+    if ((bufpos -= amount) < 0)\r
+      bufpos += bufsize;\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    available = bufsize = buffersize;\r
+    buffer = new char[buffersize];\r
+    bufline = new int[buffersize];\r
+    bufcolumn = new int[buffersize];\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.Reader dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    inputStream = dstream;\r
+    line = startline;\r
+    column = startcolumn - 1;\r
+\r
+    if (buffer == null || buffersize != buffer.length)\r
+    {\r
+      available = bufsize = buffersize;\r
+      buffer = new char[buffersize];\r
+      bufline = new int[buffersize];\r
+      bufcolumn = new int[buffersize];\r
+    }\r
+    prevCharIsLF = prevCharIsCR = false;\r
+    tokenBegin = inBuf = maxNextCharInd = 0;\r
+    bufpos = -1;\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+  int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+  int startcolumn, int buffersize)\r
+  {\r
+    this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, int startline,\r
+                          int startcolumn)\r
+  {\r
+    this(dstream, startline, startcolumn, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    this(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Constructor. */\r
+  public SimpleCharStream(java.io.InputStream dstream)\r
+  {\r
+    this(dstream, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                          int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                          int startcolumn, int buffersize)\r
+  {\r
+    ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, 1, 1, 4096);\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream)\r
+  {\r
+    ReInit(dstream, 1, 1, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, String encoding, int startline,\r
+                     int startcolumn) throws java.io.UnsupportedEncodingException\r
+  {\r
+    ReInit(dstream, encoding, startline, startcolumn, 4096);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream dstream, int startline,\r
+                     int startcolumn)\r
+  {\r
+    ReInit(dstream, startline, startcolumn, 4096);\r
+  }\r
+  /** Get token literal value. */\r
+  public String GetImage()\r
+  {\r
+    if (bufpos >= tokenBegin)\r
+      return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);\r
+    else\r
+      return new String(buffer, tokenBegin, bufsize - tokenBegin) +\r
+                            new String(buffer, 0, bufpos + 1);\r
+  }\r
+\r
+  /** Get the suffix. */\r
+  public char[] GetSuffix(int len)\r
+  {\r
+    char[] ret = new char[len];\r
+\r
+    if ((bufpos + 1) >= len)\r
+      System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);\r
+    else\r
+    {\r
+      System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,\r
+                                                        len - bufpos - 1);\r
+      System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);\r
+    }\r
+\r
+    return ret;\r
+  }\r
+\r
+  /** Reset buffer when finished. */\r
+  public void Done()\r
+  {\r
+    buffer = null;\r
+    bufline = null;\r
+    bufcolumn = null;\r
+  }\r
+\r
+  /**\r
+   * Method to adjust line and column numbers for the start of a token.\r
+   */\r
+  public void adjustBeginLineColumn(int newLine, int newCol)\r
+  {\r
+    int start = tokenBegin;\r
+    int len;\r
+\r
+    if (bufpos >= tokenBegin)\r
+    {\r
+      len = bufpos - tokenBegin + inBuf + 1;\r
+    }\r
+    else\r
+    {\r
+      len = bufsize - tokenBegin + bufpos + 1 + inBuf;\r
+    }\r
+\r
+    int i = 0, j = 0, k = 0;\r
+    int nextColDiff = 0, columnDiff = 0;\r
+\r
+    while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])\r
+    {\r
+      bufline[j] = newLine;\r
+      nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];\r
+      bufcolumn[j] = newCol + columnDiff;\r
+      columnDiff = nextColDiff;\r
+      i++;\r
+    }\r
+\r
+    if (i < len)\r
+    {\r
+      bufline[j] = newLine++;\r
+      bufcolumn[j] = newCol + columnDiff;\r
+\r
+      while (i++ < len)\r
+      {\r
+        if (bufline[j = start % bufsize] != bufline[++start % bufsize])\r
+          bufline[j] = newLine++;\r
+        else\r
+          bufline[j] = newLine;\r
+      }\r
+    }\r
+\r
+    line = bufline[j];\r
+    column = bufcolumn[j];\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=e3053baa4fc0756909ee8daa9c548c97 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/SimpleNode.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/SimpleNode.java
new file mode 100644 (file)
index 0000000..0eab39a
--- /dev/null
@@ -0,0 +1,94 @@
+/* Generated By:JJTree: Do not edit this line. SimpleNode.java Version 4.3 */\r
+/* JavaCCOptions:MULTI=false,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=UnitCheckingNodeFactory,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+public\r
+class SimpleNode implements Node {\r
+\r
+  protected Node parent;\r
+  protected Node[] children;\r
+  protected int id;\r
+  protected Object value;\r
+  protected UnitParser parser;\r
+  protected Token firstToken;\r
+  protected Token lastToken;\r
+\r
+  public SimpleNode(int i) {\r
+    id = i;\r
+  }\r
+\r
+  public SimpleNode(UnitParser p, int i) {\r
+    this(i);\r
+    parser = p;\r
+  }\r
+\r
+  public static Node jjtCreate(int id) {\r
+    return new SimpleNode(id);\r
+  }\r
+\r
+  public static Node jjtCreate(UnitParser p, int id) {\r
+    return new SimpleNode(p, id);\r
+  }\r
+\r
+  public void jjtOpen() {\r
+  }\r
+\r
+  public void jjtClose() {\r
+  }\r
+\r
+  public void jjtSetParent(Node n) { parent = n; }\r
+  public Node jjtGetParent() { return parent; }\r
+\r
+  public void jjtAddChild(Node n, int i) {\r
+    if (children == null) {\r
+      children = new Node[i + 1];\r
+    } else if (i >= children.length) {\r
+      Node c[] = new Node[i + 1];\r
+      System.arraycopy(children, 0, c, 0, children.length);\r
+      children = c;\r
+    }\r
+    children[i] = n;\r
+  }\r
+\r
+  public Node jjtGetChild(int i) {\r
+    return children[i];\r
+  }\r
+\r
+  public int jjtGetNumChildren() {\r
+    return (children == null) ? 0 : children.length;\r
+  }\r
+\r
+  public void jjtSetValue(Object value) { this.value = value; }\r
+  public Object jjtGetValue() { return value; }\r
+\r
+  public Token jjtGetFirstToken() { return firstToken; }\r
+  public void jjtSetFirstToken(Token token) { this.firstToken = token; }\r
+  public Token jjtGetLastToken() { return lastToken; }\r
+  public void jjtSetLastToken(Token token) { this.lastToken = token; }\r
+\r
+  /* You can override these two methods in subclasses of SimpleNode to\r
+     customize the way the node appears when the tree is dumped.  If\r
+     your output uses more than one line you should override\r
+     toString(String), otherwise overriding toString() is probably all\r
+     you need to do. */\r
+\r
+  public String toString() { return UnitParserTreeConstants.jjtNodeName[id]; }\r
+  public String toString(String prefix) { return prefix + toString(); }\r
+\r
+  /* Override this method if you want to customize how the node dumps\r
+     out its children. */\r
+\r
+  public void dump(String prefix) {\r
+    System.out.println(toString(prefix));\r
+    if (children != null) {\r
+      for (int i = 0; i < children.length; ++i) {\r
+        SimpleNode n = (SimpleNode)children[i];\r
+        if (n != null) {\r
+          n.dump(prefix + " ");\r
+        }\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+/* JavaCC - OriginalChecksum=97c0294de1ef3976f0b09baf888d3564 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/Token.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/Token.java
new file mode 100644 (file)
index 0000000..7e6124e
--- /dev/null
@@ -0,0 +1,131 @@
+/* Generated By:JavaCC: Do not edit this line. Token.java Version 5.0 */\r
+/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+/**\r
+ * Describes the input token stream.\r
+ */\r
+\r
+public class Token implements java.io.Serializable {\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /**\r
+   * An integer that describes the kind of this token.  This numbering\r
+   * system is determined by JavaCCParser, and a table of these numbers is\r
+   * stored in the file ...Constants.java.\r
+   */\r
+  public int kind;\r
+\r
+  /** The line number of the first character of this Token. */\r
+  public int beginLine;\r
+  /** The column number of the first character of this Token. */\r
+  public int beginColumn;\r
+  /** The line number of the last character of this Token. */\r
+  public int endLine;\r
+  /** The column number of the last character of this Token. */\r
+  public int endColumn;\r
+\r
+  /**\r
+   * The string image of the token.\r
+   */\r
+  public String image;\r
+\r
+  /**\r
+   * A reference to the next regular (non-special) token from the input\r
+   * stream.  If this is the last token from the input stream, or if the\r
+   * token manager has not read tokens beyond this one, this field is\r
+   * set to null.  This is true only if this token is also a regular\r
+   * token.  Otherwise, see below for a description of the contents of\r
+   * this field.\r
+   */\r
+  public Token next;\r
+\r
+  /**\r
+   * This field is used to access special tokens that occur prior to this\r
+   * token, but after the immediately preceding regular (non-special) token.\r
+   * If there are no such special tokens, this field is set to null.\r
+   * When there are more than one such special token, this field refers\r
+   * to the last of these special tokens, which in turn refers to the next\r
+   * previous special token through its specialToken field, and so on\r
+   * until the first special token (whose specialToken field is null).\r
+   * The next fields of special tokens refer to other special tokens that\r
+   * immediately follow it (without an intervening regular token).  If there\r
+   * is no such token, this field is null.\r
+   */\r
+  public Token specialToken;\r
+\r
+  /**\r
+   * An optional attribute value of the Token.\r
+   * Tokens which are not used as syntactic sugar will often contain\r
+   * meaningful values that will be used later on by the compiler or\r
+   * interpreter. This attribute value is often different from the image.\r
+   * Any subclass of Token that actually wants to return a non-null value can\r
+   * override this method as appropriate.\r
+   */\r
+  public Object getValue() {\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * No-argument constructor\r
+   */\r
+  public Token() {}\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image.\r
+   */\r
+  public Token(int kind)\r
+  {\r
+    this(kind, null);\r
+  }\r
+\r
+  /**\r
+   * Constructs a new token for the specified Image and Kind.\r
+   */\r
+  public Token(int kind, String image)\r
+  {\r
+    this.kind = kind;\r
+    this.image = image;\r
+  }\r
+\r
+  /**\r
+   * Returns the image.\r
+   */\r
+  public String toString()\r
+  {\r
+    return image;\r
+  }\r
+\r
+  /**\r
+   * Returns a new Token object, by default. However, if you want, you\r
+   * can create and return subclass objects based on the value of ofKind.\r
+   * Simply add the cases to the switch for all those special cases.\r
+   * For example, if you have a subclass of Token called IDToken that\r
+   * you want to create if ofKind is ID, simply add something like :\r
+   *\r
+   *    case MyParserConstants.ID : return new IDToken(ofKind, image);\r
+   *\r
+   * to the following switch statement. Then you can cast matchedToken\r
+   * variable to the appropriate type and use sit in your lexical actions.\r
+   */\r
+  public static Token newToken(int ofKind, String image)\r
+  {\r
+    switch(ofKind)\r
+    {\r
+      default : return new Token(ofKind, image);\r
+    }\r
+  }\r
+\r
+  public static Token newToken(int ofKind)\r
+  {\r
+    return newToken(ofKind, null);\r
+  }\r
+\r
+}\r
+/* JavaCC - OriginalChecksum=61dd11be23a2b24c2ed31564a8c7855c (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/TokenMgrError.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/TokenMgrError.java
new file mode 100644 (file)
index 0000000..d9e2ec7
--- /dev/null
@@ -0,0 +1,147 @@
+/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 5.0 */\r
+/* JavaCCOptions: */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+/** Token Manager Error. */\r
+public class TokenMgrError extends Error\r
+{\r
+\r
+  /**\r
+   * The version identifier for this Serializable class.\r
+   * Increment only if the <i>serialized</i> form of the\r
+   * class changes.\r
+   */\r
+  private static final long serialVersionUID = 1L;\r
+\r
+  /*\r
+   * Ordinals for various reasons why an Error of this type can be thrown.\r
+   */\r
+\r
+  /**\r
+   * Lexical error occurred.\r
+   */\r
+  static final int LEXICAL_ERROR = 0;\r
+\r
+  /**\r
+   * An attempt was made to create a second instance of a static token manager.\r
+   */\r
+  static final int STATIC_LEXER_ERROR = 1;\r
+\r
+  /**\r
+   * Tried to change to an invalid lexical state.\r
+   */\r
+  static final int INVALID_LEXICAL_STATE = 2;\r
+\r
+  /**\r
+   * Detected (and bailed out of) an infinite loop in the token manager.\r
+   */\r
+  static final int LOOP_DETECTED = 3;\r
+\r
+  /**\r
+   * Indicates the reason why the exception is thrown. It will have\r
+   * one of the above 4 values.\r
+   */\r
+  int errorCode;\r
+\r
+  /**\r
+   * Replaces unprintable characters by their escaped (or unicode escaped)\r
+   * equivalents in the given string\r
+   */\r
+  protected static final String addEscapes(String str) {\r
+    StringBuffer retval = new StringBuffer();\r
+    char ch;\r
+    for (int i = 0; i < str.length(); i++) {\r
+      switch (str.charAt(i))\r
+      {\r
+        case 0 :\r
+          continue;\r
+        case '\b':\r
+          retval.append("\\b");\r
+          continue;\r
+        case '\t':\r
+          retval.append("\\t");\r
+          continue;\r
+        case '\n':\r
+          retval.append("\\n");\r
+          continue;\r
+        case '\f':\r
+          retval.append("\\f");\r
+          continue;\r
+        case '\r':\r
+          retval.append("\\r");\r
+          continue;\r
+        case '\"':\r
+          retval.append("\\\"");\r
+          continue;\r
+        case '\'':\r
+          retval.append("\\\'");\r
+          continue;\r
+        case '\\':\r
+          retval.append("\\\\");\r
+          continue;\r
+        default:\r
+          if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r
+            String s = "0000" + Integer.toString(ch, 16);\r
+            retval.append("\\u" + s.substring(s.length() - 4, s.length()));\r
+          } else {\r
+            retval.append(ch);\r
+          }\r
+          continue;\r
+      }\r
+    }\r
+    return retval.toString();\r
+  }\r
+\r
+  /**\r
+   * Returns a detailed message for the Error when it is thrown by the\r
+   * token manager to indicate a lexical error.\r
+   * Parameters :\r
+   *    EOFSeen     : indicates if EOF caused the lexical error\r
+   *    curLexState : lexical state in which this error occurred\r
+   *    errorLine   : line number when the error occurred\r
+   *    errorColumn : column number when the error occurred\r
+   *    errorAfter  : prefix that was seen before this error occurred\r
+   *    curchar     : the offending character\r
+   * Note: You can customize the lexical error message by modifying this method.\r
+   */\r
+  protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {\r
+    return("Lexical error at line " +\r
+          errorLine + ", column " +\r
+          errorColumn + ".  Encountered: " +\r
+          (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +\r
+          "after : \"" + addEscapes(errorAfter) + "\"");\r
+  }\r
+\r
+  /**\r
+   * You can also modify the body of this method to customize your error messages.\r
+   * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not\r
+   * of end-users concern, so you can return something like :\r
+   *\r
+   *     "Internal Error : Please file a bug report .... "\r
+   *\r
+   * from this method for such cases in the release version of your parser.\r
+   */\r
+  public String getMessage() {\r
+    return super.getMessage();\r
+  }\r
+\r
+  /*\r
+   * Constructors of various flavors follow.\r
+   */\r
+\r
+  /** No arg constructor. */\r
+  public TokenMgrError() {\r
+  }\r
+\r
+  /** Constructor with message and reason. */\r
+  public TokenMgrError(String message, int reason) {\r
+    super(message);\r
+    errorCode = reason;\r
+  }\r
+\r
+  /** Full Constructor. */\r
+  public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {\r
+    this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);\r
+  }\r
+}\r
+/* JavaCC - OriginalChecksum=1a840694e4f0cebfb591db26400a3167 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingException.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingException.java
new file mode 100644 (file)
index 0000000..481004c
--- /dev/null
@@ -0,0 +1,21 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+public class UnitCheckingException extends Exception {\r
+    public UnitCheckingException(String string) {\r
+        super(string);\r
+    }\r
+\r
+    private static final long serialVersionUID = -5828012051088095625L;\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingNode.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingNode.java
new file mode 100644 (file)
index 0000000..5a71125
--- /dev/null
@@ -0,0 +1,54 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+\r
+public class UnitCheckingNode extends SimpleNode {\r
+\r
+    public UnitCheckingNode(int id) {\r
+        super(id);\r
+    }\r
+\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException{\r
+        UnitResult result = new UnitResult(allowEquivalents);\r
+\r
+        if(jjtGetNumChildren() == 0){\r
+            String node = printNode();\r
+            result.append(node);\r
+        } else {\r
+            for(int i = 0; i < jjtGetNumChildren(); i++) {\r
+                result.appendResult(((UnitCheckingNode)jjtGetChild(i)).getUnits(units, functions, allowEquivalents));\r
+            }\r
+        }\r
+        return result; \r
+    }\r
+    \r
+    public String printNode() {\r
+        StringBuilder sb = new StringBuilder();\r
+        Token token = jjtGetFirstToken();\r
+        sb.append(token.image);\r
+\r
+        while(token != null && !token.equals(jjtGetLastToken())) {\r
+            token = token.next;\r
+            sb.append(token.image);\r
+        }\r
+\r
+        return sb.toString();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingNodeFactory.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitCheckingNodeFactory.java
new file mode 100644 (file)
index 0000000..35f22df
--- /dev/null
@@ -0,0 +1,103 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.nodes.AddOp;\r
+import org.simantics.sysdyn.unitParser.nodes.Arithmetic;\r
+import org.simantics.sysdyn.unitParser.nodes.ArrayDefinition;\r
+import org.simantics.sysdyn.unitParser.nodes.ComponentIdentity;\r
+import org.simantics.sysdyn.unitParser.nodes.ComponentReference;\r
+import org.simantics.sysdyn.unitParser.nodes.ComponentReferenceFull;\r
+import org.simantics.sysdyn.unitParser.nodes.Condition;\r
+import org.simantics.sysdyn.unitParser.nodes.Divide;\r
+import org.simantics.sysdyn.unitParser.nodes.Expression;\r
+import org.simantics.sysdyn.unitParser.nodes.Factor;\r
+import org.simantics.sysdyn.unitParser.nodes.ForIndex;\r
+import org.simantics.sysdyn.unitParser.nodes.FunctionArguments;\r
+import org.simantics.sysdyn.unitParser.nodes.FunctionCall;\r
+import org.simantics.sysdyn.unitParser.nodes.IfThenElse;\r
+import org.simantics.sysdyn.unitParser.nodes.Multiplication;\r
+import org.simantics.sysdyn.unitParser.nodes.NamedArguments;\r
+import org.simantics.sysdyn.unitParser.nodes.ParenthesisExpression;\r
+import org.simantics.sysdyn.unitParser.nodes.Power;\r
+import org.simantics.sysdyn.unitParser.nodes.RelOp;\r
+import org.simantics.sysdyn.unitParser.nodes.Relation;\r
+import org.simantics.sysdyn.unitParser.nodes.Term;\r
+import org.simantics.sysdyn.unitParser.nodes.Value;\r
+\r
+public class UnitCheckingNodeFactory {\r
+    \r
+    private static HashMap<String, Class<?>> constructors = new HashMap<String, Class<?>>();\r
+    \r
+    static {\r
+        constructors.put("relation", Relation.class);\r
+        constructors.put("term", Term.class);\r
+        constructors.put("factor", Factor.class);\r
+        constructors.put("arithmetic_expression", Arithmetic.class);\r
+        constructors.put("ifthenelse", IfThenElse.class);\r
+        constructors.put("array_definition", ArrayDefinition.class);\r
+        \r
+        constructors.put("component_reference_full", ComponentReferenceFull.class);\r
+        constructors.put("value", Value.class);\r
+\r
+\r
+        constructors.put("power", Power.class);\r
+        constructors.put("divide", Divide.class);\r
+        constructors.put("multiplication", Multiplication.class);\r
+        constructors.put("add_op", AddOp.class);\r
+        constructors.put("rel_op", RelOp.class);\r
+\r
+        \r
+        \r
+        constructors.put("component_reference", ComponentReference.class);\r
+        constructors.put("component_identity", ComponentIdentity.class);\r
+        constructors.put("condition", Condition.class);\r
+        constructors.put("for_index", ForIndex.class);\r
+        constructors.put("parenthesis_expression", ParenthesisExpression.class);\r
+        constructors.put("function_call", FunctionCall.class);\r
+        constructors.put("function_arguments", FunctionArguments.class);\r
+        constructors.put("named_arguments", NamedArguments.class);\r
+        constructors.put("expression", Expression.class);\r
+\r
+        \r
+    }\r
+    \r
+    private static Class<?> getConstructor(int id) {\r
+        String name = UnitParserTreeConstants.jjtNodeName[id];\r
+        Class<?> constructor = constructors.get(name);\r
+        if(constructor == null)\r
+            return UnitCheckingNode.class;\r
+        else\r
+            return constructor;\r
+    }\r
+    \r
+    public static Node jjtCreate(int id) {\r
+        try {\r
+            return (Node) getConstructor(id).getConstructors()[0].newInstance(id);\r
+        } catch (IllegalArgumentException e) {\r
+            e.printStackTrace();\r
+        } catch (SecurityException e) {\r
+            e.printStackTrace();\r
+        } catch (InstantiationException e) {\r
+            e.printStackTrace();\r
+        } catch (IllegalAccessException e) {\r
+            e.printStackTrace();\r
+        } catch (InvocationTargetException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return null;\r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.java
new file mode 100644 (file)
index 0000000..4e35398
--- /dev/null
@@ -0,0 +1,2723 @@
+/* Generated By:JJTree&JavaCC: Do not edit this line. UnitParser.java */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+public class UnitParser/*@bgen(jjtree)*/implements UnitParserTreeConstants, UnitParserConstants {/*@bgen(jjtree)*/\r
+  protected JJTUnitParserState jjtree = new JJTUnitParserState();\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+  final public SimpleNode expr() throws ParseException {\r
+                     /*@bgen(jjtree) expr */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTEXPR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 0:\r
+      case 6:\r
+      case 12:\r
+      case 33:\r
+      case 35:\r
+      case 60:\r
+      case 62:\r
+      case 64:\r
+      case 76:\r
+      case 77:\r
+      case 78:\r
+      case 79:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 33:\r
+        case 35:\r
+        case 60:\r
+        case 62:\r
+        case 64:\r
+        case 76:\r
+        case 77:\r
+        case 78:\r
+        case 79:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          simple_expression();\r
+          break;\r
+        default:\r
+          jj_la1[0] = jj_gen;\r
+          ;\r
+        }\r
+        jj_consume_token(0);\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+          jjtn000.jjtSetLastToken(getToken(0));\r
+        {if (true) return jjtn000;}\r
+        break;\r
+      case 31:\r
+        ifthenelse();\r
+        jj_consume_token(0);\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+          jjtn000.jjtSetLastToken(getToken(0));\r
+        {if (true) return jjtn000;}\r
+        break;\r
+      default:\r
+        jj_la1[1] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+    throw new Error("Missing return statement in function");\r
+  }\r
+\r
+  final public void expression() throws ParseException {\r
+                     /*@bgen(jjtree) expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTEXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 33:\r
+      case 35:\r
+      case 60:\r
+      case 62:\r
+      case 64:\r
+      case 76:\r
+      case 77:\r
+      case 78:\r
+      case 79:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        simple_expression();\r
+        break;\r
+      case 31:\r
+        ifthenelse();\r
+        break;\r
+      default:\r
+        jj_la1[2] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void ifthenelse() throws ParseException {\r
+                     /*@bgen(jjtree) ifthenelse */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTIFTHENELSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(31);\r
+      condition();\r
+      jj_consume_token(28);\r
+      expression();\r
+      label_1:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 20:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[3] = jj_gen;\r
+          break label_1;\r
+        }\r
+        jj_consume_token(20);\r
+        condition();\r
+        jj_consume_token(28);\r
+        expression();\r
+      }\r
+      jj_consume_token(15);\r
+      expression();\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void condition() throws ParseException {\r
+                    /*@bgen(jjtree) condition */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTCONDITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      expression();\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void simple_expression() throws ParseException {\r
+                            /*@bgen(jjtree) simple_expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTSIMPLE_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      logical_expression();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 67:\r
+        jj_consume_token(67);\r
+        logical_expression();\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 67:\r
+          jj_consume_token(67);\r
+          logical_expression();\r
+          break;\r
+        default:\r
+          jj_la1[4] = jj_gen;\r
+          ;\r
+        }\r
+        break;\r
+      default:\r
+        jj_la1[5] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void logical_expression() throws ParseException {\r
+                             /*@bgen(jjtree) logical_expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTLOGICAL_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      logical_term();\r
+      label_2:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 22:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[6] = jj_gen;\r
+          break label_2;\r
+        }\r
+        jj_consume_token(22);\r
+        logical_term();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void logical_term() throws ParseException {\r
+                       /*@bgen(jjtree) logical_term */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTLOGICAL_TERM);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      logical_factor();\r
+      label_3:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 9:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[7] = jj_gen;\r
+          break label_3;\r
+        }\r
+        jj_consume_token(9);\r
+        logical_factor();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void logical_factor() throws ParseException {\r
+                         /*@bgen(jjtree) logical_factor */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTLOGICAL_FACTOR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 12:\r
+        jj_consume_token(12);\r
+        break;\r
+      default:\r
+        jj_la1[8] = jj_gen;\r
+        ;\r
+      }\r
+      relation();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void relation() throws ParseException {\r
+                   /*@bgen(jjtree) relation */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTRELATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      arithmetic_expression();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 70:\r
+      case 71:\r
+      case 72:\r
+      case 73:\r
+      case 74:\r
+      case 75:\r
+        rel_op();\r
+        arithmetic_expression();\r
+        break;\r
+      default:\r
+        jj_la1[9] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void rel_op() throws ParseException {\r
+                 /*@bgen(jjtree) rel_op */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTREL_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 70:\r
+        jj_consume_token(70);\r
+        break;\r
+      case 71:\r
+        jj_consume_token(71);\r
+        break;\r
+      case 72:\r
+        jj_consume_token(72);\r
+        break;\r
+      case 73:\r
+        jj_consume_token(73);\r
+        break;\r
+      case 74:\r
+        jj_consume_token(74);\r
+        break;\r
+      case 75:\r
+        jj_consume_token(75);\r
+        break;\r
+      default:\r
+        jj_la1[10] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void arithmetic_expression() throws ParseException {\r
+                                /*@bgen(jjtree) arithmetic_expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTARITHMETIC_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 76:\r
+      case 77:\r
+      case 78:\r
+      case 79:\r
+        add_op();\r
+        break;\r
+      default:\r
+        jj_la1[11] = jj_gen;\r
+        ;\r
+      }\r
+      term();\r
+      label_4:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 76:\r
+        case 77:\r
+        case 78:\r
+        case 79:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[12] = jj_gen;\r
+          break label_4;\r
+        }\r
+        add_op();\r
+        term();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void add_op() throws ParseException {\r
+                 /*@bgen(jjtree) add_op */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTADD_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 76:\r
+        jj_consume_token(76);\r
+        break;\r
+      case 77:\r
+        jj_consume_token(77);\r
+        break;\r
+      case 78:\r
+        jj_consume_token(78);\r
+        break;\r
+      case 79:\r
+        jj_consume_token(79);\r
+        break;\r
+      default:\r
+        jj_la1[13] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void term() throws ParseException {\r
+               /*@bgen(jjtree) term */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTTERM);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      if (jj_2_1(2147483647)) {\r
+        factor();\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 33:\r
+        case 35:\r
+        case 60:\r
+        case 62:\r
+        case 64:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          primary();\r
+          break;\r
+        default:\r
+          jj_la1[14] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+      label_5:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 80:\r
+        case 81:\r
+        case 82:\r
+        case 83:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[15] = jj_gen;\r
+          break label_5;\r
+        }\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 80:\r
+        case 82:\r
+          multiplication();\r
+          break;\r
+        case 81:\r
+        case 83:\r
+          divide();\r
+          break;\r
+        default:\r
+          jj_la1[16] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+        if (jj_2_2(2147483647)) {\r
+          factor();\r
+        } else {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 6:\r
+          case 33:\r
+          case 35:\r
+          case 60:\r
+          case 62:\r
+          case 64:\r
+          case IDENT:\r
+          case STRING:\r
+          case UNSIGNED_INTEGER:\r
+          case UNSIGNED_NUMBER:\r
+            primary();\r
+            break;\r
+          default:\r
+            jj_la1[17] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void factor() throws ParseException {\r
+                 /*@bgen(jjtree) factor */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFACTOR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      primary();\r
+      power();\r
+      primary();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void power() throws ParseException {\r
+                /*@bgen(jjtree) power */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPOWER);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 84:\r
+        jj_consume_token(84);\r
+        break;\r
+      case 85:\r
+        jj_consume_token(85);\r
+        break;\r
+      default:\r
+        jj_la1[18] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void multiplication() throws ParseException {\r
+                         /*@bgen(jjtree) multiplication */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTMULTIPLICATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 80:\r
+        jj_consume_token(80);\r
+        break;\r
+      case 82:\r
+        jj_consume_token(82);\r
+        break;\r
+      default:\r
+        jj_la1[19] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void divide() throws ParseException {\r
+                 /*@bgen(jjtree) divide */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTDIVIDE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 81:\r
+        jj_consume_token(81);\r
+        break;\r
+      case 83:\r
+        jj_consume_token(83);\r
+        break;\r
+      default:\r
+        jj_la1[20] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void primary() throws ParseException {\r
+                  /*@bgen(jjtree) primary */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPRIMARY);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 33:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        value();\r
+        break;\r
+      default:\r
+        jj_la1[22] = jj_gen;\r
+        if (jj_2_3(2147483647)) {\r
+          function_call();\r
+        } else {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case IDENT:\r
+            component_reference_full();\r
+            break;\r
+          case 60:\r
+            parenthesis_expression();\r
+            break;\r
+          case 64:\r
+            jj_consume_token(64);\r
+            expression_list();\r
+            label_6:\r
+            while (true) {\r
+              switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+              case 68:\r
+                ;\r
+                break;\r
+              default:\r
+                jj_la1[21] = jj_gen;\r
+                break label_6;\r
+              }\r
+              jj_consume_token(68);\r
+              expression_list();\r
+            }\r
+            jj_consume_token(65);\r
+            break;\r
+          case 62:\r
+            array_definition();\r
+            break;\r
+          case 35:\r
+            jj_consume_token(35);\r
+            break;\r
+          default:\r
+            jj_la1[23] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void component_reference_full() throws ParseException {\r
+                                   /*@bgen(jjtree) component_reference_full */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTCOMPONENT_REFERENCE_FULL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      component_reference();\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void array_definition() throws ParseException {\r
+                           /*@bgen(jjtree) array_definition */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTARRAY_DEFINITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(62);\r
+      function_arguments();\r
+      jj_consume_token(63);\r
+    } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      {if (true) throw (RuntimeException)jjte000;}\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      {if (true) throw (ParseException)jjte000;}\r
+    }\r
+    {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void function_call() throws ParseException {\r
+                        /*@bgen(jjtree) function_call */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFUNCTION_CALL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      name();\r
+      function_call_args();\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void parenthesis_expression() throws ParseException {\r
+                                 /*@bgen(jjtree) parenthesis_expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPARENTHESIS_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      parenthesis_open();\r
+      expression();\r
+      parenthesis_close();\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void value() throws ParseException {\r
+                /*@bgen(jjtree) value */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTVALUE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case UNSIGNED_NUMBER:\r
+        jj_consume_token(UNSIGNED_NUMBER);\r
+        break;\r
+      case UNSIGNED_INTEGER:\r
+        jj_consume_token(UNSIGNED_INTEGER);\r
+        break;\r
+      case STRING:\r
+        jj_consume_token(STRING);\r
+        break;\r
+      case 6:\r
+        jj_consume_token(6);\r
+        break;\r
+      case 33:\r
+        jj_consume_token(33);\r
+        break;\r
+      default:\r
+        jj_la1[24] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void parenthesis_open() throws ParseException {\r
+                           /*@bgen(jjtree) parenthesis_open */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPARENTHESIS_OPEN);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(60);\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void parenthesis_close() throws ParseException {\r
+                            /*@bgen(jjtree) parenthesis_close */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPARENTHESIS_CLOSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(61);\r
+    } finally {\r
+     if (jjtc000) {\r
+       jjtree.closeNodeScope(jjtn000, true);\r
+       jjtn000.jjtSetLastToken(getToken(0));\r
+     }\r
+    }\r
+  }\r
+\r
+  final public void name() throws ParseException {\r
+               /*@bgen(jjtree) name */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTNAME);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(IDENT);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 66:\r
+        jj_consume_token(66);\r
+        name();\r
+        break;\r
+      default:\r
+        jj_la1[25] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void component_reference() throws ParseException {\r
+                              /*@bgen(jjtree) component_reference */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTCOMPONENT_REFERENCE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      component_identity();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 64:\r
+        array_subscripts();\r
+        break;\r
+      default:\r
+        jj_la1[26] = jj_gen;\r
+        ;\r
+      }\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 66:\r
+        jj_consume_token(66);\r
+        component_reference();\r
+        break;\r
+      default:\r
+        jj_la1[27] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void component_identity() throws ParseException {\r
+                             /*@bgen(jjtree) component_identity */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTCOMPONENT_IDENTITY);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(IDENT);\r
+      label_7:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case IDENT:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[28] = jj_gen;\r
+          break label_7;\r
+        }\r
+        jj_consume_token(IDENT);\r
+      }\r
+    } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+    }\r
+  }\r
+\r
+  final public void function_call_args() throws ParseException {\r
+                             /*@bgen(jjtree) function_call_args */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFUNCTION_CALL_ARGS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      parenthesis_open();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 60:\r
+      case 62:\r
+      case 64:\r
+      case 76:\r
+      case 77:\r
+      case 78:\r
+      case 79:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        function_arguments();\r
+        break;\r
+      default:\r
+        jj_la1[29] = jj_gen;\r
+        ;\r
+      }\r
+      parenthesis_close();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void function_arguments() throws ParseException {\r
+                             /*@bgen(jjtree) function_arguments */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFUNCTION_ARGUMENTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      if (jj_2_4(2)) {\r
+        named_arguments();\r
+      } else {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 60:\r
+        case 62:\r
+        case 64:\r
+        case 76:\r
+        case 77:\r
+        case 78:\r
+        case 79:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          expression();\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case 21:\r
+          case 69:\r
+            switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+            case 69:\r
+              jj_consume_token(69);\r
+              function_arguments();\r
+              break;\r
+            case 21:\r
+              jj_consume_token(21);\r
+              for_indices();\r
+              break;\r
+            default:\r
+              jj_la1[30] = jj_gen;\r
+              jj_consume_token(-1);\r
+              throw new ParseException();\r
+            }\r
+            break;\r
+          default:\r
+            jj_la1[31] = jj_gen;\r
+            ;\r
+          }\r
+          break;\r
+        default:\r
+          jj_la1[32] = jj_gen;\r
+          jj_consume_token(-1);\r
+          throw new ParseException();\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void for_indices() throws ParseException {\r
+                      /*@bgen(jjtree) for_indices */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFOR_INDICES);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      for_index();\r
+      label_8:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 69:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[33] = jj_gen;\r
+          break label_8;\r
+        }\r
+        jj_consume_token(69);\r
+        for_index();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void for_index() throws ParseException {\r
+                    /*@bgen(jjtree) for_index */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFOR_INDEX);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(IDENT);\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 41:\r
+        jj_consume_token(41);\r
+        expression();\r
+        break;\r
+      default:\r
+        jj_la1[34] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void named_arguments() throws ParseException {\r
+                          /*@bgen(jjtree) named_arguments */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTNAMED_ARGUMENTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      named_argument();\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 69:\r
+        jj_consume_token(69);\r
+        named_arguments();\r
+        break;\r
+      default:\r
+        jj_la1[35] = jj_gen;\r
+        ;\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void named_argument() throws ParseException {\r
+                         /*@bgen(jjtree) named_argument */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTNAMED_ARGUMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(IDENT);\r
+      jj_consume_token(86);\r
+      expression();\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void output_expression_list() throws ParseException {\r
+                                 /*@bgen(jjtree) output_expression_list */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTOUTPUT_EXPRESSION_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 6:\r
+      case 12:\r
+      case 31:\r
+      case 33:\r
+      case 35:\r
+      case 60:\r
+      case 62:\r
+      case 64:\r
+      case 76:\r
+      case 77:\r
+      case 78:\r
+      case 79:\r
+      case IDENT:\r
+      case STRING:\r
+      case UNSIGNED_INTEGER:\r
+      case UNSIGNED_NUMBER:\r
+        expression();\r
+        break;\r
+      default:\r
+        jj_la1[36] = jj_gen;\r
+        ;\r
+      }\r
+      label_9:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 69:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[37] = jj_gen;\r
+          break label_9;\r
+        }\r
+        jj_consume_token(69);\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 6:\r
+        case 12:\r
+        case 31:\r
+        case 33:\r
+        case 35:\r
+        case 60:\r
+        case 62:\r
+        case 64:\r
+        case 76:\r
+        case 77:\r
+        case 78:\r
+        case 79:\r
+        case IDENT:\r
+        case STRING:\r
+        case UNSIGNED_INTEGER:\r
+        case UNSIGNED_NUMBER:\r
+          expression();\r
+          break;\r
+        default:\r
+          jj_la1[38] = jj_gen;\r
+          ;\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void expression_list() throws ParseException {\r
+                          /*@bgen(jjtree) expression_list */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTEXPRESSION_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      expression();\r
+      label_10:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 69:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[39] = jj_gen;\r
+          break label_10;\r
+        }\r
+        jj_consume_token(69);\r
+        expression();\r
+      }\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        {if (true) throw (RuntimeException)jjte000;}\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        {if (true) throw (ParseException)jjte000;}\r
+      }\r
+      {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+  }\r
+\r
+  final public void array_subscripts() throws ParseException {\r
+                           /*@bgen(jjtree) array_subscripts */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTARRAY_SUBSCRIPTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      jj_consume_token(64);\r
+      subscript();\r
+      label_11:\r
+      while (true) {\r
+        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+        case 69:\r
+          ;\r
+          break;\r
+        default:\r
+          jj_la1[40] = jj_gen;\r
+          break label_11;\r
+        }\r
+        jj_consume_token(69);\r
+        subscript();\r
+      }\r
+      jj_consume_token(65);\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void subscript() throws ParseException {\r
+                    /*@bgen(jjtree) subscript */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTSUBSCRIPT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case 67:\r
+        jj_consume_token(67);\r
+        break;\r
+      default:\r
+        jj_la1[42] = jj_gen;\r
+        if (jj_2_5(2147483647)) {\r
+          function_call();\r
+        } else {\r
+          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+          case IDENT:\r
+          case UNSIGNED_INTEGER:\r
+            rangeIndex();\r
+            switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+            case 67:\r
+              jj_consume_token(67);\r
+              rangeIndex();\r
+              break;\r
+            default:\r
+              jj_la1[41] = jj_gen;\r
+              ;\r
+            }\r
+            break;\r
+          default:\r
+            jj_la1[43] = jj_gen;\r
+            jj_consume_token(-1);\r
+            throw new ParseException();\r
+          }\r
+        }\r
+      }\r
+    } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            {if (true) throw (RuntimeException)jjte000;}\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            {if (true) throw (ParseException)jjte000;}\r
+          }\r
+          {if (true) throw (Error)jjte000;}\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  final public void rangeIndex() throws ParseException {\r
+                     /*@bgen(jjtree) rangeIndex */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTRANGEINDEX);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+    try {\r
+      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {\r
+      case UNSIGNED_INTEGER:\r
+        jj_consume_token(UNSIGNED_INTEGER);\r
+        break;\r
+      case IDENT:\r
+        jj_consume_token(IDENT);\r
+        break;\r
+      default:\r
+        jj_la1[44] = jj_gen;\r
+        jj_consume_token(-1);\r
+        throw new ParseException();\r
+      }\r
+    } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+    }\r
+  }\r
+\r
+  private boolean jj_2_1(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_1(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(0, xla); }\r
+  }\r
+\r
+  private boolean jj_2_2(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_2(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(1, xla); }\r
+  }\r
+\r
+  private boolean jj_2_3(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_3(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(2, xla); }\r
+  }\r
+\r
+  private boolean jj_2_4(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_4(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(3, xla); }\r
+  }\r
+\r
+  private boolean jj_2_5(int xla) {\r
+    jj_la = xla; jj_lastpos = jj_scanpos = token;\r
+    try { return !jj_3_5(); }\r
+    catch(LookaheadSuccess ls) { return true; }\r
+    finally { jj_save(4, xla); }\r
+  }\r
+\r
+  private boolean jj_3R_80() {\r
+    if (jj_3R_12()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_31() {\r
+    if (jj_scan_token(62)) return true;\r
+    if (jj_3R_37()) return true;\r
+    if (jj_scan_token(63)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_27() {\r
+    if (jj_3R_33()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_3() {\r
+    if (jj_3R_14()) return true;\r
+    if (jj_3R_15()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_22() {\r
+    if (jj_3R_31()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_21() {\r
+    if (jj_scan_token(64)) return true;\r
+    if (jj_3R_29()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_30()) { jj_scanpos = xsp; break; }\r
+    }\r
+    if (jj_scan_token(65)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_20() {\r
+    if (jj_3R_28()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_19() {\r
+    if (jj_3R_27()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_18() {\r
+    if (jj_3R_26()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_12() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_17()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_18()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_19()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_20()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_21()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_22()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(35)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_17() {\r
+    if (jj_3R_25()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_88() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(81)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(83)) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_87() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(80)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(82)) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_13() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(84)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(85)) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_62() {\r
+    if (jj_scan_token(67)) return true;\r
+    if (jj_3R_51()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_1() {\r
+    if (jj_3R_12()) return true;\r
+    if (jj_3R_13()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_73() {\r
+    if (jj_3R_77()) return true;\r
+    if (jj_3R_72()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_76() {\r
+    if (jj_3R_78()) return true;\r
+    if (jj_3R_75()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_82() {\r
+    if (jj_3R_12()) return true;\r
+    if (jj_3R_13()) return true;\r
+    if (jj_3R_12()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_79() {\r
+    if (jj_3R_82()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_75() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_79()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_80()) return true;\r
+    }\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_81()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_78() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(76)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(77)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(78)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(79)) return true;\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_67() {\r
+    if (jj_scan_token(9)) return true;\r
+    if (jj_3R_66()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_74() {\r
+    if (jj_3R_78()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_72() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_74()) jj_scanpos = xsp;\r
+    if (jj_3R_75()) return true;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_76()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_77() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(70)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(71)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(72)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(73)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(74)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(75)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_52() {\r
+    if (jj_scan_token(67)) return true;\r
+    if (jj_3R_51()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_62()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_61() {\r
+    if (jj_scan_token(22)) return true;\r
+    if (jj_3R_60()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_54() {\r
+    if (jj_scan_token(20)) return true;\r
+    if (jj_3R_53()) return true;\r
+    if (jj_scan_token(28)) return true;\r
+    if (jj_3R_34()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_70() {\r
+    if (jj_3R_72()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_73()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_66() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(12)) jj_scanpos = xsp;\r
+    if (jj_3R_70()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_65() {\r
+    if (jj_scan_token(67)) return true;\r
+    if (jj_3R_64()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_5() {\r
+    if (jj_3R_14()) return true;\r
+    if (jj_3R_15()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_60() {\r
+    if (jj_3R_66()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_67()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_50() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_49()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_51() {\r
+    if (jj_3R_60()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_61()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_64() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(90)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(88)) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_46() {\r
+    if (jj_3R_51()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_52()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_58() {\r
+    if (jj_3R_26()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_59() {\r
+    if (jj_3R_64()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_65()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_36() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_34()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_49() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(67)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_58()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_59()) return true;\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_57() {\r
+    if (jj_scan_token(21)) return true;\r
+    if (jj_3R_63()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_45() {\r
+    if (jj_scan_token(64)) return true;\r
+    if (jj_3R_49()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_50()) { jj_scanpos = xsp; break; }\r
+    }\r
+    if (jj_scan_token(65)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_55() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_16()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_53() {\r
+    if (jj_3R_34()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_43() {\r
+    if (jj_3R_47()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_34() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_42()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_43()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_42() {\r
+    if (jj_3R_46()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_47() {\r
+    if (jj_scan_token(31)) return true;\r
+    if (jj_3R_53()) return true;\r
+    if (jj_scan_token(28)) return true;\r
+    if (jj_3R_34()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_54()) { jj_scanpos = xsp; break; }\r
+    }\r
+    if (jj_scan_token(15)) return true;\r
+    if (jj_3R_34()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_29() {\r
+    if (jj_3R_34()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_36()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_41() {\r
+    if (jj_scan_token(66)) return true;\r
+    if (jj_3R_33()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_24() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    if (jj_scan_token(86)) return true;\r
+    if (jj_3R_34()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_71() {\r
+    if (jj_scan_token(41)) return true;\r
+    if (jj_3R_34()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_86() {\r
+    if (jj_3R_12()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_69() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_68()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_16() {\r
+    if (jj_3R_24()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_55()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_48() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_56()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_57()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_56() {\r
+    if (jj_scan_token(69)) return true;\r
+    if (jj_3R_37()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_38() {\r
+    if (jj_3R_37()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_68() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_71()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_63() {\r
+    if (jj_3R_68()) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_3R_69()) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_40() {\r
+    if (jj_3R_45()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_44() {\r
+    if (jj_3R_34()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_48()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_4() {\r
+    if (jj_3R_16()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_37() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3_4()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_44()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_32() {\r
+    if (jj_3R_15()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_38()) jj_scanpos = xsp;\r
+    if (jj_3R_35()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3_2() {\r
+    if (jj_3R_12()) return true;\r
+    if (jj_3R_13()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_23() {\r
+    if (jj_scan_token(66)) return true;\r
+    if (jj_3R_14()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_85() {\r
+    if (jj_3R_82()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_39() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    Token xsp;\r
+    while (true) {\r
+      xsp = jj_scanpos;\r
+      if (jj_scan_token(88)) { jj_scanpos = xsp; break; }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_33() {\r
+    if (jj_3R_39()) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_40()) jj_scanpos = xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_41()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_14() {\r
+    if (jj_scan_token(IDENT)) return true;\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_23()) jj_scanpos = xsp;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_84() {\r
+    if (jj_3R_88()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_35() {\r
+    if (jj_scan_token(61)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_15() {\r
+    if (jj_scan_token(60)) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_25() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_scan_token(91)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(90)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(89)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(6)) {\r
+    jj_scanpos = xsp;\r
+    if (jj_scan_token(33)) return true;\r
+    }\r
+    }\r
+    }\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_83() {\r
+    if (jj_3R_87()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_81() {\r
+    Token xsp;\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_83()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_84()) return true;\r
+    }\r
+    xsp = jj_scanpos;\r
+    if (jj_3R_85()) {\r
+    jj_scanpos = xsp;\r
+    if (jj_3R_86()) return true;\r
+    }\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_30() {\r
+    if (jj_scan_token(68)) return true;\r
+    if (jj_3R_29()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_28() {\r
+    if (jj_3R_15()) return true;\r
+    if (jj_3R_34()) return true;\r
+    if (jj_3R_35()) return true;\r
+    return false;\r
+  }\r
+\r
+  private boolean jj_3R_26() {\r
+    if (jj_3R_14()) return true;\r
+    if (jj_3R_32()) return true;\r
+    return false;\r
+  }\r
+\r
+  /** Generated Token Manager. */\r
+  public UnitParserTokenManager token_source;\r
+  SimpleCharStream jj_input_stream;\r
+  /** Current token. */\r
+  public Token token;\r
+  /** Next token. */\r
+  public Token jj_nt;\r
+  private int jj_ntk;\r
+  private Token jj_scanpos, jj_lastpos;\r
+  private int jj_la;\r
+  private int jj_gen;\r
+  final private int[] jj_la1 = new int[45];\r
+  static private int[] jj_la1_0;\r
+  static private int[] jj_la1_1;\r
+  static private int[] jj_la1_2;\r
+  static {\r
+      jj_la1_init_0();\r
+      jj_la1_init_1();\r
+      jj_la1_init_2();\r
+   }\r
+   private static void jj_la1_init_0() {\r
+      jj_la1_0 = new int[] {0x1040,0x80001041,0x80001040,0x100000,0x0,0x0,0x400000,0x200,0x1000,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x40,0x0,0x40,0x0,0x0,0x0,0x0,0x80001040,0x200000,0x200000,0x80001040,0x0,0x0,0x0,0x80001040,0x0,0x80001040,0x0,0x0,0x0,0x0,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_1() {\r
+      jj_la1_1 = new int[] {0x5000000a,0x5000000a,0x5000000a,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x5000000a,0x0,0x0,0x5000000a,0x0,0x0,0x0,0x0,0x2,0x50000008,0x2,0x0,0x0,0x0,0x0,0x5000000a,0x0,0x0,0x5000000a,0x0,0x200,0x0,0x5000000a,0x0,0x5000000a,0x0,0x0,0x0,0x0,0x0,0x0,};\r
+   }\r
+   private static void jj_la1_init_2() {\r
+      jj_la1_2 = new int[] {0xf00f001,0xf00f001,0xf00f001,0x0,0x8,0x8,0x0,0x0,0x0,0xfc0,0xfc0,0xf000,0xf000,0xf000,0xf000001,0xf0000,0xf0000,0xf000001,0x300000,0x50000,0xa0000,0x10,0xe000000,0x1000001,0xe000000,0x4,0x1,0x4,0x1000000,0xf00f001,0x20,0x20,0xf00f001,0x20,0x0,0x20,0xf00f001,0x20,0xf00f001,0x20,0x20,0x8,0x8,0x5000000,0x5000000,};\r
+   }\r
+  final private JJCalls[] jj_2_rtns = new JJCalls[5];\r
+  private boolean jj_rescan = false;\r
+  private int jj_gc = 0;\r
+\r
+  /** Constructor with InputStream. */\r
+  public UnitParser(java.io.InputStream stream) {\r
+     this(stream, null);\r
+  }\r
+  /** Constructor with InputStream and supplied encoding */\r
+  public UnitParser(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source = new UnitParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 45; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream) {\r
+     ReInit(stream, null);\r
+  }\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.InputStream stream, String encoding) {\r
+    try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jjtree.reset();\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 45; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Constructor. */\r
+  public UnitParser(java.io.Reader stream) {\r
+    jj_input_stream = new SimpleCharStream(stream, 1, 1);\r
+    token_source = new UnitParserTokenManager(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 45; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(java.io.Reader stream) {\r
+    jj_input_stream.ReInit(stream, 1, 1);\r
+    token_source.ReInit(jj_input_stream);\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jjtree.reset();\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 45; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Constructor with generated Token Manager. */\r
+  public UnitParser(UnitParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 45; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  /** Reinitialise. */\r
+  public void ReInit(UnitParserTokenManager tm) {\r
+    token_source = tm;\r
+    token = new Token();\r
+    jj_ntk = -1;\r
+    jjtree.reset();\r
+    jj_gen = 0;\r
+    for (int i = 0; i < 45; i++) jj_la1[i] = -1;\r
+    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\r
+  }\r
+\r
+  private Token jj_consume_token(int kind) throws ParseException {\r
+    Token oldToken;\r
+    if ((oldToken = token).next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    if (token.kind == kind) {\r
+      jj_gen++;\r
+      if (++jj_gc > 100) {\r
+        jj_gc = 0;\r
+        for (int i = 0; i < jj_2_rtns.length; i++) {\r
+          JJCalls c = jj_2_rtns[i];\r
+          while (c != null) {\r
+            if (c.gen < jj_gen) c.first = null;\r
+            c = c.next;\r
+          }\r
+        }\r
+      }\r
+      return token;\r
+    }\r
+    token = oldToken;\r
+    jj_kind = kind;\r
+    throw generateParseException();\r
+  }\r
+\r
+  static private final class LookaheadSuccess extends java.lang.Error { }\r
+  final private LookaheadSuccess jj_ls = new LookaheadSuccess();\r
+  private boolean jj_scan_token(int kind) {\r
+    if (jj_scanpos == jj_lastpos) {\r
+      jj_la--;\r
+      if (jj_scanpos.next == null) {\r
+        jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();\r
+      } else {\r
+        jj_lastpos = jj_scanpos = jj_scanpos.next;\r
+      }\r
+    } else {\r
+      jj_scanpos = jj_scanpos.next;\r
+    }\r
+    if (jj_rescan) {\r
+      int i = 0; Token tok = token;\r
+      while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }\r
+      if (tok != null) jj_add_error_token(kind, i);\r
+    }\r
+    if (jj_scanpos.kind != kind) return true;\r
+    if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;\r
+    return false;\r
+  }\r
+\r
+\r
+/** Get the next Token. */\r
+  final public Token getNextToken() {\r
+    if (token.next != null) token = token.next;\r
+    else token = token.next = token_source.getNextToken();\r
+    jj_ntk = -1;\r
+    jj_gen++;\r
+    return token;\r
+  }\r
+\r
+/** Get the specific Token. */\r
+  final public Token getToken(int index) {\r
+    Token t = token;\r
+    for (int i = 0; i < index; i++) {\r
+      if (t.next != null) t = t.next;\r
+      else t = t.next = token_source.getNextToken();\r
+    }\r
+    return t;\r
+  }\r
+\r
+  private int jj_ntk() {\r
+    if ((jj_nt=token.next) == null)\r
+      return (jj_ntk = (token.next=token_source.getNextToken()).kind);\r
+    else\r
+      return (jj_ntk = jj_nt.kind);\r
+  }\r
+\r
+  private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();\r
+  private int[] jj_expentry;\r
+  private int jj_kind = -1;\r
+  private int[] jj_lasttokens = new int[100];\r
+  private int jj_endpos;\r
+\r
+  private void jj_add_error_token(int kind, int pos) {\r
+    if (pos >= 100) return;\r
+    if (pos == jj_endpos + 1) {\r
+      jj_lasttokens[jj_endpos++] = kind;\r
+    } else if (jj_endpos != 0) {\r
+      jj_expentry = new int[jj_endpos];\r
+      for (int i = 0; i < jj_endpos; i++) {\r
+        jj_expentry[i] = jj_lasttokens[i];\r
+      }\r
+      jj_entries_loop: for (java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();) {\r
+        int[] oldentry = (int[])(it.next());\r
+        if (oldentry.length == jj_expentry.length) {\r
+          for (int i = 0; i < jj_expentry.length; i++) {\r
+            if (oldentry[i] != jj_expentry[i]) {\r
+              continue jj_entries_loop;\r
+            }\r
+          }\r
+          jj_expentries.add(jj_expentry);\r
+          break jj_entries_loop;\r
+        }\r
+      }\r
+      if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;\r
+    }\r
+  }\r
+\r
+  /** Generate ParseException. */\r
+  public ParseException generateParseException() {\r
+    jj_expentries.clear();\r
+    boolean[] la1tokens = new boolean[92];\r
+    if (jj_kind >= 0) {\r
+      la1tokens[jj_kind] = true;\r
+      jj_kind = -1;\r
+    }\r
+    for (int i = 0; i < 45; i++) {\r
+      if (jj_la1[i] == jj_gen) {\r
+        for (int j = 0; j < 32; j++) {\r
+          if ((jj_la1_0[i] & (1<<j)) != 0) {\r
+            la1tokens[j] = true;\r
+          }\r
+          if ((jj_la1_1[i] & (1<<j)) != 0) {\r
+            la1tokens[32+j] = true;\r
+          }\r
+          if ((jj_la1_2[i] & (1<<j)) != 0) {\r
+            la1tokens[64+j] = true;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    for (int i = 0; i < 92; i++) {\r
+      if (la1tokens[i]) {\r
+        jj_expentry = new int[1];\r
+        jj_expentry[0] = i;\r
+        jj_expentries.add(jj_expentry);\r
+      }\r
+    }\r
+    jj_endpos = 0;\r
+    jj_rescan_token();\r
+    jj_add_error_token(0, 0);\r
+    int[][] exptokseq = new int[jj_expentries.size()][];\r
+    for (int i = 0; i < jj_expentries.size(); i++) {\r
+      exptokseq[i] = jj_expentries.get(i);\r
+    }\r
+    return new ParseException(token, exptokseq, tokenImage);\r
+  }\r
+\r
+  /** Enable tracing. */\r
+  final public void enable_tracing() {\r
+  }\r
+\r
+  /** Disable tracing. */\r
+  final public void disable_tracing() {\r
+  }\r
+\r
+  private void jj_rescan_token() {\r
+    jj_rescan = true;\r
+    for (int i = 0; i < 5; i++) {\r
+    try {\r
+      JJCalls p = jj_2_rtns[i];\r
+      do {\r
+        if (p.gen > jj_gen) {\r
+          jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;\r
+          switch (i) {\r
+            case 0: jj_3_1(); break;\r
+            case 1: jj_3_2(); break;\r
+            case 2: jj_3_3(); break;\r
+            case 3: jj_3_4(); break;\r
+            case 4: jj_3_5(); break;\r
+          }\r
+        }\r
+        p = p.next;\r
+      } while (p != null);\r
+      } catch(LookaheadSuccess ls) { }\r
+    }\r
+    jj_rescan = false;\r
+  }\r
+\r
+  private void jj_save(int index, int xla) {\r
+    JJCalls p = jj_2_rtns[index];\r
+    while (p.gen > jj_gen) {\r
+      if (p.next == null) { p = p.next = new JJCalls(); break; }\r
+      p = p.next;\r
+    }\r
+    p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;\r
+  }\r
+\r
+  static final class JJCalls {\r
+    int gen;\r
+    Token first;\r
+    int arg;\r
+    JJCalls next;\r
+  }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.jj b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.jj
new file mode 100644 (file)
index 0000000..35d321e
--- /dev/null
@@ -0,0 +1,1250 @@
+/*@bgen(jjtree) Generated By:JJTree: Do not edit this line. UnitParser.jj */\r
+/*@egen*/options {\r
+  JDK_VERSION = "1.6";\r
+  STATIC = false;\r
+                    \r
+                                \r
+                                         \r
+}\r
+\r
+PARSER_BEGIN(UnitParser)\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+public class UnitParser/*@bgen(jjtree)*/implements UnitParserTreeConstants/*@egen*/ {/*@bgen(jjtree)*/\r
+  protected JJTUnitParserState jjtree = new JJTUnitParserState();\r
+\r
+/*@egen*/\r
+\r
+  \r
+    \r
+}\r
+PARSER_END(UnitParser)\r
+\r
+/*** Lexer *********************************************************/\r
+\r
+SKIP:\r
+{ <WHITESPACE: " " | "\n" | "\r" | "\t" > \r
+| <COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/" >  \r
+| <COMMENT2: "//" (~["\n"])* >\r
+}\r
+\r
+TOKEN:\r
+{\r
+"algorithm"    | "discrete"    | "false"       | "model"       | "redeclare"\r
+| "and"                | "each"                | "final"       | "not"         | "replaceable"\r
+| "annotation" | "else"                | "flow"        | "operator" | "return"\r
+|"assert"              | "elseif"              | "for"         | "or"          | "stream"\r
+| "block"              | "elsewhen"    | "function" | "outer"  | "then"\r
+| "break"              | "encapsulated" | "if"         | "output"      | "true"\r
+| "class"              | "end"                 | "import"      | "package" | "type"\r
+| "connect"    | "enumeration" | "in"          | "parameter" | "when"\r
+| "connector"  | "equation"    | /*"initial" |*/ "partial" | "while"\r
+| "constant"   | "expandable"  | "inner"       | "protected" | "within"\r
+| "constrainedby" | "extends"  | "input"       | "public"\r
+| /*"der"              |*/ "external"  | "loop"        | "record"\r
+| "(" | ")" | "{" | "}" | "[" | "]" | "." | ":" | ";" | ","\r
+| "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+| "+" | "-" | ".+" | ".-"\r
+| "*" | "/" | ".*" | "./"\r
+| "^" | ".^"\r
+| "=" | ":=" \r
+| <IDENT: ["a"-"z","A"-"Z","_","\u20ac","$","\u00a3","%","\u0391"-"\u03c9","\u00b5"] (["a"-"z","A"-"Z","_","\u20ac","$","\u00a3","%","\u0391"-"\u03c9","\u00b5","0"-"9"])* >\r
+| <STRING: "\"" (~["\"", "\\", "\n"] | "\\" ~["\n"])* "\"">\r
+    { matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); }\r
+| <UNSIGNED_INTEGER: (["0"-"9"])+ >\r
+| <UNSIGNED_NUMBER:  \r
+    ( <UNSIGNED_INTEGER> "." (<UNSIGNED_INTEGER>)? (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | "." <UNSIGNED_INTEGER> (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | <UNSIGNED_INTEGER> ["e","E"] (["+","-"])? <UNSIGNED_INTEGER>\r
+    ) >\r
+}\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+\r
+SimpleNode expr() : {/*@bgen(jjtree) expr */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTEXPR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) expr */\r
+        try {\r
+/*@egen*/\r
+       (simple_expression())? <EOF>/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+          jjtn000.jjtSetLastToken(getToken(0));\r
+        }\r
+/*@egen*/\r
+       {\r
+       return jjtn000;\r
+    }\r
+       |\r
+       ifthenelse() <EOF>/*@bgen(jjtree)*/\r
+        {\r
+          jjtree.closeNodeScope(jjtn000, true);\r
+          jjtc000 = false;\r
+          jjtn000.jjtSetLastToken(getToken(0));\r
+        }\r
+/*@egen*/\r
+       {\r
+       return jjtn000;\r
+    }/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void expression() : {/*@bgen(jjtree) expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTEXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) expression */\r
+        try {\r
+/*@egen*/\r
+       simple_expression()\r
+       | ifthenelse()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void ifthenelse() : {/*@bgen(jjtree) ifthenelse */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTIFTHENELSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r} {/*@bgen(jjtree) ifthenelse */\r
+  try {\r
+/*@egen*/\r
+  "if" condition() "then" expression() ( "elseif" condition() "then" expression() )* "else" expression()/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r
+\r\r
+void condition() : {/*@bgen(jjtree) condition */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTCONDITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) condition */\r
+  try {\r
+/*@egen*/\r
+  expression()/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r  \r  \r
+\r
+void simple_expression() : {/*@bgen(jjtree) simple_expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTSIMPLE_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) simple_expression */\r
+        try {\r
+/*@egen*/\r
+       logical_expression() ( ":" logical_expression() ( ":" logical_expression() )? )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}      \r
+\r
+void logical_expression() : {/*@bgen(jjtree) logical_expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTLOGICAL_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) logical_expression */\r
+        try {\r
+/*@egen*/\r
+       logical_term() ( "or" logical_term() )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}      \r
+\r
+void logical_term() : {/*@bgen(jjtree) logical_term */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTLOGICAL_TERM);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) logical_term */\r
+        try {\r
+/*@egen*/\r
+       logical_factor() ( "and" logical_factor() )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void logical_factor() : {/*@bgen(jjtree) logical_factor */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTLOGICAL_FACTOR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) logical_factor */\r
+        try {\r
+/*@egen*/\r
+       ( "not" )? relation()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void relation() : {/*@bgen(jjtree) relation */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTRELATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) relation */\r
+        try {\r
+/*@egen*/\r
+       arithmetic_expression() ( rel_op() arithmetic_expression() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void rel_op() : {/*@bgen(jjtree) rel_op */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTREL_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) rel_op */\r
+        try {\r
+/*@egen*/\r
+       "<" | "<=" | ">" | ">=" | "==" | "<>"/*@bgen(jjtree)*/\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void arithmetic_expression() : {/*@bgen(jjtree) arithmetic_expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTARITHMETIC_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) arithmetic_expression */\r
+    try {\r
+/*@egen*/\r
+    (add_op())? term() (add_op() term())*/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void add_op() : {/*@bgen(jjtree) add_op */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTADD_OP);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) add_op */\r
+    try {\r
+/*@egen*/\r
+    "+" | "-" | ".+" | ".-"/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void term() : {/*@bgen(jjtree) term */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTTERM);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) term */\r
+    try {\r
+/*@egen*/\r
+    ( LOOKAHEAD(primary() power()) factor() | primary() ) ( (multiplication() | divide()) ( LOOKAHEAD(primary() power()) factor() | primary()) )*/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void factor() : {/*@bgen(jjtree) factor */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFACTOR);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) factor */\r
+        try {\r
+/*@egen*/\r
+       primary() power() primary()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void power() : {/*@bgen(jjtree) power */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPOWER);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) power */\r
+        try {\r
+/*@egen*/\r
+       "^" | ".^"/*@bgen(jjtree)*/\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r  \r
+void multiplication() : {/*@bgen(jjtree) multiplication */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTMULTIPLICATION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) multiplication */\r
+    try {\r
+/*@egen*/\r
+    "*" | ".*"/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void divide() : {/*@bgen(jjtree) divide */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTDIVIDE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) divide */\r
+    try {\r
+/*@egen*/\r
+    "/" | "./"/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void primary() : {/*@bgen(jjtree) primary */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPRIMARY);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) primary */\r
+  try {\r
+/*@egen*/\r
+  value()\r
+  | LOOKAHEAD( name() parenthesis_open() ) function_call()   \r
+  | component_reference_full()\r
+  /*| "(" output_expression_list() ")"*/ // Not needed, replaced with following:\r
+  | parenthesis_expression()\r
+  | "[" expression_list() ( ";" expression_list() )* "]"\r
+  | array_definition()\r
+  | "end"/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r
+\r
+void component_reference_full() : {/*@bgen(jjtree) component_reference_full */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTCOMPONENT_REFERENCE_FULL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) component_reference_full */\r
+    try {\r
+/*@egen*/\r
+    component_reference()/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void array_definition() : {/*@bgen(jjtree) array_definition */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTARRAY_DEFINITION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) array_definition */\r
+  try {\r
+/*@egen*/\r
+  "{" function_arguments() "}"/*@bgen(jjtree)*/\r
+  } catch (Throwable jjte000) {\r
+    if (jjtc000) {\r
+      jjtree.clearNodeScope(jjtn000);\r
+      jjtc000 = false;\r
+    } else {\r
+      jjtree.popNode();\r
+    }\r
+    if (jjte000 instanceof RuntimeException) {\r
+      throw (RuntimeException)jjte000;\r
+    }\r
+    if (jjte000 instanceof ParseException) {\r
+      throw (ParseException)jjte000;\r
+    }\r
+    throw (Error)jjte000;\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r
+\r
+void function_call() : {/*@bgen(jjtree) function_call */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFUNCTION_CALL);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) function_call */\r
+    try {\r
+/*@egen*/\r
+    name() function_call_args()/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void parenthesis_expression() : {/*@bgen(jjtree) parenthesis_expression */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPARENTHESIS_EXPRESSION);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r} {/*@bgen(jjtree) parenthesis_expression */\r
+    try {\r
+/*@egen*/\r    parenthesis_open() expression() parenthesis_close()/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void value() : {/*@bgen(jjtree) value */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTVALUE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r} {/*@bgen(jjtree) value */\r
+        try {\r
+/*@egen*/\r
+       <UNSIGNED_NUMBER>\r
+  | <UNSIGNED_INTEGER>\r
+  | <STRING>\r
+  | "false"\r
+  | "true"/*@bgen(jjtree)*/\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r  \r
+\r
+void parenthesis_open() : {/*@bgen(jjtree) parenthesis_open */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPARENTHESIS_OPEN);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) parenthesis_open */\r
+    try {\r
+/*@egen*/\r
+    "("/*@bgen(jjtree)*/\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void parenthesis_close() : {/*@bgen(jjtree) parenthesis_close */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTPARENTHESIS_CLOSE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) parenthesis_close */\r
+   try {\r
+/*@egen*/\r
+   ")"/*@bgen(jjtree)*/\r
+   } finally {\r
+     if (jjtc000) {\r
+       jjtree.closeNodeScope(jjtn000, true);\r
+       jjtn000.jjtSetLastToken(getToken(0));\r
+     }\r
+   }\r
+/*@egen*/\r
+}\r
+\r
+void name() : {/*@bgen(jjtree) name */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTNAME);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) name */\r
+        try {\r
+/*@egen*/\r
+       <IDENT> ( "." name() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void component_reference() : {/*@bgen(jjtree) component_reference */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTCOMPONENT_REFERENCE);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) component_reference */\r
+        try {\r
+/*@egen*/\r
+       //IDENT [ array_subscripts ] [ "." component_reference ]\r
+       component_identity() ( array_subscripts() )? ( "." component_reference() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void component_identity() : {/*@bgen(jjtree) component_identity */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTCOMPONENT_IDENTITY);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) component_identity */\r
+  try {\r
+/*@egen*/\r  <IDENT> (<IDENT>)*/*@bgen(jjtree)*/\r
+  } finally {\r
+    if (jjtc000) {\r
+      jjtree.closeNodeScope(jjtn000, true);\r
+      jjtn000.jjtSetLastToken(getToken(0));\r
+    }\r
+  }\r
+/*@egen*/\r
+}\r  \r
+\r
+void function_call_args() : {/*@bgen(jjtree) function_call_args */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFUNCTION_CALL_ARGS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) function_call_args */\r
+        try {\r
+/*@egen*/\r
+       parenthesis_open() ( function_arguments() )? parenthesis_close()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void function_arguments() : {/*@bgen(jjtree) function_arguments */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFUNCTION_ARGUMENTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) function_arguments */\r
+        try {\r
+/*@egen*/\r
+       //expression [ "," function_arguments | for for_indices ]\r
+       //| named_arguments\r
+       LOOKAHEAD(2) named_arguments()\r
+       | expression() ( "," function_arguments() | "for" for_indices() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+       \r
+}\r
+\r
+void for_indices() : {/*@bgen(jjtree) for_indices */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFOR_INDICES);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) for_indices */\r
+        try {\r
+/*@egen*/\r
+       //for_index {"," for_index}\r
+       for_index() ("," for_index())*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void for_index() : {/*@bgen(jjtree) for_index */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTFOR_INDEX);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) for_index */\r
+        try {\r
+/*@egen*/\r
+       //IDENT [ in expression ]\r
+       <IDENT> ( "in" expression() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void named_arguments() : {/*@bgen(jjtree) named_arguments */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTNAMED_ARGUMENTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) named_arguments */\r
+        try {\r
+/*@egen*/\r
+       named_argument() ( "," named_arguments() )?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void named_argument() : {/*@bgen(jjtree) named_argument */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTNAMED_ARGUMENT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) named_argument */\r
+        try {\r
+/*@egen*/      \r
+       <IDENT> "=" expression()/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void output_expression_list() : {/*@bgen(jjtree) output_expression_list */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTOUTPUT_EXPRESSION_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) output_expression_list */\r
+        try {\r
+/*@egen*/\r
+       ( expression() )? ( "," ( expression() )? )*/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+\r
+void expression_list() : {/*@bgen(jjtree) expression_list */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTEXPRESSION_LIST);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) expression_list */\r
+    try {\r
+/*@egen*/\r
+    expression() ( "," expression() )*/*@bgen(jjtree)*/\r
+    } catch (Throwable jjte000) {\r
+      if (jjtc000) {\r
+        jjtree.clearNodeScope(jjtn000);\r
+        jjtc000 = false;\r
+      } else {\r
+        jjtree.popNode();\r
+      }\r
+      if (jjte000 instanceof RuntimeException) {\r
+        throw (RuntimeException)jjte000;\r
+      }\r
+      if (jjte000 instanceof ParseException) {\r
+        throw (ParseException)jjte000;\r
+      }\r
+      throw (Error)jjte000;\r
+    } finally {\r
+      if (jjtc000) {\r
+        jjtree.closeNodeScope(jjtn000, true);\r
+        jjtn000.jjtSetLastToken(getToken(0));\r
+      }\r
+    }\r
+/*@egen*/\r
+}\r
+\r
+void array_subscripts() : {/*@bgen(jjtree) array_subscripts */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTARRAY_SUBSCRIPTS);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) array_subscripts */\r
+        try {\r
+/*@egen*/\r
+       "[" subscript() ( "," subscript() )* "]"/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void subscript() : {/*@bgen(jjtree) subscript */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTSUBSCRIPT);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) subscript */\r
+        try {\r
+/*@egen*/\r     ":"\r
+       |   LOOKAHEAD( name() parenthesis_open() ) function_call()\r
+       | rangeIndex() ( ":" rangeIndex())?/*@bgen(jjtree)*/\r
+        } catch (Throwable jjte000) {\r
+          if (jjtc000) {\r
+            jjtree.clearNodeScope(jjtn000);\r
+            jjtc000 = false;\r
+          } else {\r
+            jjtree.popNode();\r
+          }\r
+          if (jjte000 instanceof RuntimeException) {\r
+            throw (RuntimeException)jjte000;\r
+          }\r
+          if (jjte000 instanceof ParseException) {\r
+            throw (ParseException)jjte000;\r
+          }\r
+          throw (Error)jjte000;\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r
+\r
+void rangeIndex() : {/*@bgen(jjtree) rangeIndex */\r
+  UnitCheckingNode jjtn000 = (UnitCheckingNode)UnitCheckingNodeFactory.jjtCreate(JJTRANGEINDEX);\r
+  boolean jjtc000 = true;\r
+  jjtree.openNodeScope(jjtn000);\r
+  jjtn000.jjtSetFirstToken(getToken(1));\r
+/*@egen*/\r
+} {/*@bgen(jjtree) rangeIndex */\r
+        try {\r
+/*@egen*/\r     <UNSIGNED_INTEGER>\r
+               | <IDENT>/*@bgen(jjtree)*/\r
+        } finally {\r
+          if (jjtc000) {\r
+            jjtree.closeNodeScope(jjtn000, true);\r
+            jjtn000.jjtSetLastToken(getToken(0));\r
+          }\r
+        }\r
+/*@egen*/\r
+}\r  \r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.jjt b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParser.jjt
new file mode 100644 (file)
index 0000000..af0cd4b
--- /dev/null
@@ -0,0 +1,282 @@
+options {\r
+  JDK_VERSION = "1.6";\r
+  STATIC = false;\r
+  TRACK_TOKENS=true;\r
+  NODE_CLASS="UnitCheckingNode";\r
+  NODE_FACTORY="UnitCheckingNodeFactory";\r
+}\r
+\r
+PARSER_BEGIN(UnitParser)\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+public class UnitParser {\r
+\r
+  \r
+    \r
+}\r
+PARSER_END(UnitParser)\r
+\r
+/*** Lexer *********************************************************/\r
+\r
+SKIP:\r
+{ <WHITESPACE: " " | "\n" | "\r" | "\t" > \r
+| <COMMENT1: "/*" (~["*"] | "*" ~["/"])* "*/" >  \r
+| <COMMENT2: "//" (~["\n"])* >\r
+}\r
+\r
+TOKEN:\r
+{\r
+"algorithm"    | "discrete"    | "false"       | "model"       | "redeclare"\r
+| "and"                | "each"                | "final"       | "not"         | "replaceable"\r
+| "annotation" | "else"                | "flow"        | "operator" | "return"\r
+|"assert"              | "elseif"              | "for"         | "or"          | "stream"\r
+| "block"              | "elsewhen"    | "function" | "outer"  | "then"\r
+| "break"              | "encapsulated" | "if"         | "output"      | "true"\r
+| "class"              | "end"                 | "import"      | "package" | "type"\r
+| "connect"    | "enumeration" | "in"          | "parameter" | "when"\r
+| "connector"  | "equation"    | /*"initial" |*/ "partial" | "while"\r
+| "constant"   | "expandable"  | "inner"       | "protected" | "within"\r
+| "constrainedby" | "extends"  | "input"       | "public"\r
+| /*"der"              |*/ "external"  | "loop"        | "record"\r
+| "(" | ")" | "{" | "}" | "[" | "]" | "." | ":" | ";" | ","\r
+| "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+| "+" | "-" | ".+" | ".-"\r
+| "*" | "/" | ".*" | "./"\r
+| "^" | ".^"\r
+| "=" | ":=" \r
+| <IDENT: ["a"-"z","A"-"Z","_","\u20ac","$","£","%","\u0391"-"\u03c9","µ"] (["a"-"z","A"-"Z","_","\u20ac","$","£","%","\u0391"-"\u03c9","µ","0"-"9"])* >\r
+| <STRING: "\"" (~["\"", "\\", "\n"] | "\\" ~["\n"])* "\"">\r
+    { matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1); }\r
+| <UNSIGNED_INTEGER: (["0"-"9"])+ >\r
+| <UNSIGNED_NUMBER:  \r
+    ( <UNSIGNED_INTEGER> "." (<UNSIGNED_INTEGER>)? (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | "." <UNSIGNED_INTEGER> (["e","E"] (["+","-"])? <UNSIGNED_INTEGER>)?\r
+    | <UNSIGNED_INTEGER> ["e","E"] (["+","-"])? <UNSIGNED_INTEGER>\r
+    ) >\r
+}\r
+\r
+/*** Parser ********************************************************/\r
+\r
+// https://javacc.dev.java.net/doc/javaccgrm.html\r
+// add_op -> add_op()\r
+// [ add_op ] -> ( add_op() )?\r
+// { add_op term } -> ( add_op() term() )*\r
+\r
+SimpleNode expr() : {\r
+} {\r
+       (simple_expression())? <EOF>\r
+       {\r
+       return jjtThis;\r
+    }\r
+       |\r
+       ifthenelse() <EOF>\r
+       {\r
+       return jjtThis;\r
+    }\r
+}\r
+\r
+void expression() : {\r
+} {\r
+       simple_expression()\r
+       | ifthenelse()\r
+}\r
+\r
+void ifthenelse() : {\r} {\r
+  "if" condition() "then" expression() ( "elseif" condition() "then" expression() )* "else" expression()\r
+}\r
+\r\r
+void condition() : {\r
+} {\r
+  expression()\r
+}\r  \r  \r
+\r
+void simple_expression() : {\r
+} {\r
+       logical_expression() ( ":" logical_expression() ( ":" logical_expression() )? )?\r
+}      \r
+\r
+void logical_expression() : {\r
+} {\r
+       logical_term() ( "or" logical_term() )*\r
+}      \r
+\r
+void logical_term() : {\r
+} {\r
+       logical_factor() ( "and" logical_factor() )*\r
+}\r
+\r
+void logical_factor() : {\r
+} {\r
+       ( "not" )? relation()\r
+}\r
+\r
+void relation() : {\r
+} {\r
+       arithmetic_expression() ( rel_op() arithmetic_expression() )?\r
+}\r
+\r
+void rel_op() : {\r
+} {\r
+       "<" | "<=" | ">" | ">=" | "==" | "<>"\r
+}\r
+\r
+void arithmetic_expression() : {\r
+} {\r
+    (add_op())? term() (add_op() term())*\r
+}\r
+\r
+void add_op() : {\r
+} {\r
+    "+" | "-" | ".+" | ".-"\r
+}\r
+\r
+void term() : {\r
+} {\r
+    ( LOOKAHEAD(primary() power()) factor() | primary() ) ( (multiplication() | divide()) ( LOOKAHEAD(primary() power()) factor() | primary()) )*\r
+}\r
+\r
+void factor() : {\r
+} {\r
+       primary() power() primary()\r
+}\r
+\r
+void power() : {\r
+} {\r
+       "^" | ".^"\r
+}\r  \r
+void multiplication() : {\r
+} {\r
+    "*" | ".*"\r
+}\r
+\r
+void divide() : {\r
+} {\r
+    "/" | "./"\r
+}\r
+\r
+void primary() : {\r
+} {\r
+  value()\r
+  | LOOKAHEAD( name() parenthesis_open() ) function_call()   \r
+  | component_reference_full()\r
+  /*| "(" output_expression_list() ")"*/ // Not needed, replaced with following:\r
+  | parenthesis_expression()\r
+  | "[" expression_list() ( ";" expression_list() )* "]"\r
+  | array_definition()\r
+  | "end"\r
+}\r
+\r
+void component_reference_full() : {\r
+} {\r
+    component_reference()\r
+}\r
+\r
+void array_definition() : {\r
+} {\r
+  "{" function_arguments() "}"\r
+}\r
+\r
+void function_call() : {\r
+} {\r
+    name() function_call_args()\r
+}\r
+\r
+void parenthesis_expression() : {\r} {\r    parenthesis_open() expression() parenthesis_close()\r
+}\r
+\r
+void value() : {\r} {\r
+       <UNSIGNED_NUMBER>\r
+  | <UNSIGNED_INTEGER>\r
+  | <STRING>\r
+  | "false"\r
+  | "true"\r
+}\r  \r
+\r
+void parenthesis_open() : {\r
+} {\r
+    "("\r
+}\r
+\r
+void parenthesis_close() : {\r
+} {\r
+   ")"\r
+}\r
+\r
+void name() : {\r
+} {\r
+       <IDENT> ( "." name() )?\r
+}\r
+\r
+void component_reference() : {\r
+} {\r
+       //IDENT [ array_subscripts ] [ "." component_reference ]\r
+       component_identity() ( array_subscripts() )? ( "." component_reference() )?\r
+}\r
+\r
+void component_identity() : {\r
+} {\r  <IDENT> (<IDENT>)*\r
+}\r  \r
+\r
+void function_call_args() : {\r
+} {\r
+       parenthesis_open() ( function_arguments() )? parenthesis_close()\r
+}\r
+\r
+void function_arguments() : {\r
+} {\r
+       //expression [ "," function_arguments | for for_indices ]\r
+       //| named_arguments\r
+       LOOKAHEAD(2) named_arguments()\r
+       | expression() ( "," function_arguments() | "for" for_indices() )?\r
+       \r
+}\r
+\r
+void for_indices() : {\r
+} {\r
+       //for_index {"," for_index}\r
+       for_index() ("," for_index())*\r
+}\r
+\r
+void for_index() : {\r
+} {\r
+       //IDENT [ in expression ]\r
+       <IDENT> ( "in" expression() )?\r
+}\r
+\r
+void named_arguments() : {\r
+} {\r
+       named_argument() ( "," named_arguments() )?\r
+}\r
+\r
+void named_argument() : {\r
+} {    \r
+       <IDENT> "=" expression()\r
+}\r
+\r
+void output_expression_list() : {\r
+} {\r
+       ( expression() )? ( "," ( expression() )? )*\r
+}\r
+\r
+\r
+void expression_list() : {\r
+} {\r
+    expression() ( "," expression() )*\r
+}\r
+\r
+void array_subscripts() : {\r
+} {\r
+       "[" subscript() ( "," subscript() )* "]"\r
+}\r
+\r
+void subscript() : {\r
+} {\r   ":"\r
+       |   LOOKAHEAD( name() parenthesis_open() ) function_call()\r
+       | rangeIndex() ( ":" rangeIndex())?\r
+}\r
+\r
+void rangeIndex() : {\r
+} {\r   <UNSIGNED_INTEGER>\r
+               | <IDENT>\r
+}\r  \r
+\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserConstants.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserConstants.java
new file mode 100644 (file)
index 0000000..1cef5de
--- /dev/null
@@ -0,0 +1,127 @@
+/* Generated By:JJTree&JavaCC: Do not edit this line. UnitParserConstants.java */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+\r
+/**\r
+ * Token literal values and constants.\r
+ * Generated by org.javacc.parser.OtherFilesGen#start()\r
+ */\r
+public interface UnitParserConstants {\r
+\r
+  /** End of File. */\r
+  int EOF = 0;\r
+  /** RegularExpression Id. */\r
+  int WHITESPACE = 1;\r
+  /** RegularExpression Id. */\r
+  int COMMENT1 = 2;\r
+  /** RegularExpression Id. */\r
+  int COMMENT2 = 3;\r
+  /** RegularExpression Id. */\r
+  int IDENT = 88;\r
+  /** RegularExpression Id. */\r
+  int STRING = 89;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_INTEGER = 90;\r
+  /** RegularExpression Id. */\r
+  int UNSIGNED_NUMBER = 91;\r
+\r
+  /** Lexical state. */\r
+  int DEFAULT = 0;\r
+\r
+  /** Literal token values. */\r
+  String[] tokenImage = {\r
+    "<EOF>",\r
+    "<WHITESPACE>",\r
+    "<COMMENT1>",\r
+    "<COMMENT2>",\r
+    "\"algorithm\"",\r
+    "\"discrete\"",\r
+    "\"false\"",\r
+    "\"model\"",\r
+    "\"redeclare\"",\r
+    "\"and\"",\r
+    "\"each\"",\r
+    "\"final\"",\r
+    "\"not\"",\r
+    "\"replaceable\"",\r
+    "\"annotation\"",\r
+    "\"else\"",\r
+    "\"flow\"",\r
+    "\"operator\"",\r
+    "\"return\"",\r
+    "\"assert\"",\r
+    "\"elseif\"",\r
+    "\"for\"",\r
+    "\"or\"",\r
+    "\"stream\"",\r
+    "\"block\"",\r
+    "\"elsewhen\"",\r
+    "\"function\"",\r
+    "\"outer\"",\r
+    "\"then\"",\r
+    "\"break\"",\r
+    "\"encapsulated\"",\r
+    "\"if\"",\r
+    "\"output\"",\r
+    "\"true\"",\r
+    "\"class\"",\r
+    "\"end\"",\r
+    "\"import\"",\r
+    "\"package\"",\r
+    "\"type\"",\r
+    "\"connect\"",\r
+    "\"enumeration\"",\r
+    "\"in\"",\r
+    "\"parameter\"",\r
+    "\"when\"",\r
+    "\"connector\"",\r
+    "\"equation\"",\r
+    "\"partial\"",\r
+    "\"while\"",\r
+    "\"constant\"",\r
+    "\"expandable\"",\r
+    "\"inner\"",\r
+    "\"protected\"",\r
+    "\"within\"",\r
+    "\"constrainedby\"",\r
+    "\"extends\"",\r
+    "\"input\"",\r
+    "\"public\"",\r
+    "\"external\"",\r
+    "\"loop\"",\r
+    "\"record\"",\r
+    "\"(\"",\r
+    "\")\"",\r
+    "\"{\"",\r
+    "\"}\"",\r
+    "\"[\"",\r
+    "\"]\"",\r
+    "\".\"",\r
+    "\":\"",\r
+    "\";\"",\r
+    "\",\"",\r
+    "\"<\"",\r
+    "\"<=\"",\r
+    "\">\"",\r
+    "\">=\"",\r
+    "\"==\"",\r
+    "\"<>\"",\r
+    "\"+\"",\r
+    "\"-\"",\r
+    "\".+\"",\r
+    "\".-\"",\r
+    "\"*\"",\r
+    "\"/\"",\r
+    "\".*\"",\r
+    "\"./\"",\r
+    "\"^\"",\r
+    "\".^\"",\r
+    "\"=\"",\r
+    "\":=\"",\r
+    "<IDENT>",\r
+    "<STRING>",\r
+    "<UNSIGNED_INTEGER>",\r
+    "<UNSIGNED_NUMBER>",\r
+  };\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserTokenManager.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserTokenManager.java
new file mode 100644 (file)
index 0000000..1758bea
--- /dev/null
@@ -0,0 +1,1408 @@
+/* Generated By:JJTree&JavaCC: Do not edit this line. UnitParserTokenManager.java */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+/** Token Manager. */\r
+public class UnitParserTokenManager implements UnitParserConstants\r
+{\r
+\r
+  /** Debug output. */\r
+  public  java.io.PrintStream debugStream = System.out;\r
+  /** Set debug output. */\r
+  public  void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }\r
+private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1)
+{\r
+   switch (pos)
+   {\r
+      case 0:\r
+         if ((active0 & 0xffffffffffffff0L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            return 2;\r
+         }\r
+         if ((active1 & 0x20000L) != 0L)\r
+            return 14;\r
+         if ((active1 & 0x2cc004L) != 0L)\r
+            return 9;\r
+         return -1;\r
+      case 1:\r
+         if ((active0 & 0x84020080400000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0xf7bfdff7fbffff0L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 1)\r
+            {\r
+               jjmatchedKind = 88;\r
+               jjmatchedPos = 1;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 2:\r
+         if ((active0 & 0x800201200L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0xffffdf77f9fedf0L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 2;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 3:\r
+         if ((active0 & 0x400084212118400L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0xbfff5b56d8e69f0L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 3)\r
+            {\r
+               jjmatchedKind = 88;\r
+               jjmatchedPos = 3;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 4:\r
+         if ((active0 & 0x848004290008c0L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0xb7b75b1469e6130L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 4;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 5:\r
+         if ((active0 & 0x9100011009c0000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x26b75a046026130L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 5;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 6:\r
+         if ((active0 & 0x4050a000000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x22b250046026130L) != 0L)\r
+         {\r
+            if (jjmatchedPos != 6)\r
+            {\r
+               jjmatchedKind = 88;\r
+               jjmatchedPos = 6;\r
+            }\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 7:\r
+         if ((active0 & 0x201200006020020L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x2a150040006110L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 7;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 8:\r
+         if ((active0 & 0x22010040006000L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 8;\r
+            return 2;\r
+         }\r
+         if ((active0 & 0x8140000000110L) != 0L)\r
+            return 2;\r
+         return -1;\r
+      case 9:\r
+         if ((active0 & 0x2000000004000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x20010040002000L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 9;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 10:\r
+         if ((active0 & 0x10000002000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x20000040000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 10;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      case 11:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return 2;\r
+         if ((active0 & 0x20000000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 88;\r
+            jjmatchedPos = 11;\r
+            return 2;\r
+         }\r
+         return -1;\r
+      default :\r
+         return -1;\r
+   }\r
+}\r
+private final int jjStartNfa_0(int pos, long active0, long active1)
+{\r
+   return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1);\r
+}\r
+private int jjStopAtPos(int pos, int kind)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   return pos + 1;\r
+}\r
+private int jjMoveStringLiteralDfa0_0()\r
+{\r
+   switch(curChar)\r
+   {\r
+      case 40:\r
+         return jjStopAtPos(0, 60);\r
+      case 41:\r
+         return jjStopAtPos(0, 61);\r
+      case 42:\r
+         return jjStopAtPos(0, 80);\r
+      case 43:\r
+         return jjStopAtPos(0, 76);\r
+      case 44:\r
+         return jjStopAtPos(0, 69);\r
+      case 45:\r
+         return jjStopAtPos(0, 77);\r
+      case 46:\r
+         jjmatchedKind = 66;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x2cc000L);\r
+      case 47:\r
+         return jjStartNfaWithStates_0(0, 81, 14);\r
+      case 58:\r
+         jjmatchedKind = 67;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x800000L);\r
+      case 59:\r
+         return jjStopAtPos(0, 68);\r
+      case 60:\r
+         jjmatchedKind = 70;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x880L);\r
+      case 61:\r
+         jjmatchedKind = 86;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x400L);\r
+      case 62:\r
+         jjmatchedKind = 72;\r
+         return jjMoveStringLiteralDfa1_0(0x0L, 0x200L);\r
+      case 91:\r
+         return jjStopAtPos(0, 64);\r
+      case 93:\r
+         return jjStopAtPos(0, 65);\r
+      case 94:\r
+         return jjStopAtPos(0, 84);\r
+      case 97:\r
+         return jjMoveStringLiteralDfa1_0(0x84210L, 0x0L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa1_0(0x21000000L, 0x0L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa1_0(0x21108400000000L, 0x0L);\r
+      case 100:\r
+         return jjMoveStringLiteralDfa1_0(0x20L, 0x0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa1_0(0x242210842108400L, 0x0L);\r
+      case 102:\r
+         return jjMoveStringLiteralDfa1_0(0x4210840L, 0x0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa1_0(0x84021080000000L, 0x0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa1_0(0x400000000000000L, 0x0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa1_0(0x80L, 0x0L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa1_0(0x1000L, 0x0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa1_0(0x108420000L, 0x0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa1_0(0x108442000000000L, 0x0L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa1_0(0x800000000042100L, 0x0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa1_0(0x800000L, 0x0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa1_0(0x4210000000L, 0x0L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa1_0(0x10880000000000L, 0x0L);\r
+      case 123:\r
+         return jjStopAtPos(0, 62);\r
+      case 125:\r
+         return jjStopAtPos(0, 63);\r
+      default :\r
+         return jjMoveNfa_0(0, 0);\r
+   }\r
+}\r
+private int jjMoveStringLiteralDfa1_0(long active0, long active1)\r
+{\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(0, active0, active1);\r
+      return 1;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 42:\r
+         if ((active1 & 0x40000L) != 0L)\r
+            return jjStopAtPos(1, 82);\r
+         break;\r
+      case 43:\r
+         if ((active1 & 0x4000L) != 0L)\r
+            return jjStopAtPos(1, 78);\r
+         break;\r
+      case 45:\r
+         if ((active1 & 0x8000L) != 0L)\r
+            return jjStopAtPos(1, 79);\r
+         break;\r
+      case 47:\r
+         if ((active1 & 0x80000L) != 0L)\r
+            return jjStopAtPos(1, 83);\r
+         break;\r
+      case 61:\r
+         if ((active1 & 0x80L) != 0L)\r
+            return jjStopAtPos(1, 71);\r
+         else if ((active1 & 0x200L) != 0L)\r
+            return jjStopAtPos(1, 73);\r
+         else if ((active1 & 0x400L) != 0L)\r
+            return jjStopAtPos(1, 74);\r
+         else if ((active1 & 0x800000L) != 0L)\r
+            return jjStopAtPos(1, 87);\r
+         break;\r
+      case 62:\r
+         if ((active1 & 0x800L) != 0L)\r
+            return jjStopAtPos(1, 75);\r
+         break;\r
+      case 94:\r
+         if ((active1 & 0x200000L) != 0L)\r
+            return jjStopAtPos(1, 85);\r
+         break;\r
+      case 97:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x442000000440L, active1, 0L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x800000000042100L, active1, 0L);\r
+      case 102:\r
+         if ((active0 & 0x80000000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 31, 2);\r
+         break;\r
+      case 104:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x880010000000L, active1, 0L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x10000000000820L, active1, 0L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x403118010L, active1, 0L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x1000000000L, active1, 0L);\r
+      case 110:\r
+         if ((active0 & 0x20000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 41;\r
+            jjmatchedPos = 1;\r
+         }\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x84010840004200L, active1, 0L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x421108000201080L, active1, 0L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x20000L, active1, 0L);\r
+      case 113:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x200000000000L, active1, 0L);\r
+      case 114:\r
+         if ((active0 & 0x400000L) != 0L)\r
+            return jjStartNfaWithStates_0(1, 22, 2);\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x8000220000000L, active1, 0L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x80000L, active1, 0L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x800000L, active1, 0L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x10000010c000000L, active1, 0L);\r
+      case 120:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x242000000000000L, active1, 0L);\r
+      case 121:\r
+         return jjMoveStringLiteralDfa2_0(active0, 0x4000000000L, active1, 0L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(0, active0, active1);\r
+}\r
+private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1)\r
+{\r
+   if (((active0 &= old0) | (active1 &= old1)) == 0L)\r
+      return jjStartNfa_0(0, old0, old1);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(1, active0, 0L);\r
+      return 2;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x400000000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x100000000000000L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x800002040000400L);\r
+      case 100:\r
+         if ((active0 & 0x200L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 9, 2);\r
+         else if ((active0 & 0x800000000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 35, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x180L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x80030020000L);\r
+      case 103:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x10L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x800000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x40L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x25108004004800L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x408000001010000L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x82005000002000L);\r
+      case 114:\r
+         if ((active0 & 0x200000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 21, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x440000800000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x2188020L);\r
+      case 116:\r
+         if ((active0 & 0x1000L) != 0L)\r
+            return jjStartNfaWithStates_0(2, 12, 2);\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x250000108040000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa3_0(active0, 0x210200000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(1, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa3_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(1, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(2, active0, 0L);\r
+      return 3;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2240060000800L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x5000020L);\r
+      case 101:\r
+         if ((active0 & 0x8000L) != 0L)\r
+         {\r
+            jjmatchedKind = 15;\r
+            jjmatchedPos = 3;\r
+         }\r
+         else if ((active0 & 0x200000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 33, 2);\r
+         else if ((active0 & 0x4000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 38, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x24400000a980180L);\r
+      case 104:\r
+         if ((active0 & 0x400L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 10, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10000000000000L);\r
+      case 107:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x2000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100800000002000L);\r
+      case 109:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x10000000000L);\r
+      case 110:\r
+         if ((active0 & 0x10000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 28, 2);\r
+         else if ((active0 & 0x80000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 43, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x108000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x800001000004010L);\r
+      case 112:\r
+         if ((active0 & 0x400000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 58, 2);\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x100000000L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x20000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x21000400000040L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x8400000000000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa4_0(active0, 0x80000000040000L);\r
+      case 119:\r
+         if ((active0 & 0x10000L) != 0L)\r
+            return jjStartNfaWithStates_0(3, 16, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(2, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa4_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(2, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(3, active0, 0L);\r
+      return 4;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000822000L);\r
+      case 99:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100L);\r
+      case 101:\r
+         if ((active0 & 0x40L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 6, 2);\r
+         else if ((active0 & 0x800000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 47, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x8118000000000L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x110400000100000L);\r
+      case 107:\r
+         if ((active0 & 0x1000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 24, 2);\r
+         else if ((active0 & 0x20000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 29, 2);\r
+         break;\r
+      case 108:\r
+         if ((active0 & 0x80L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 7, 2);\r
+         else if ((active0 & 0x800L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 11, 2);\r
+         break;\r
+      case 109:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L);\r
+      case 110:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x42000000000000L);\r
+      case 112:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x40000000L);\r
+      case 114:\r
+         if ((active0 & 0x8000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 27, 2);\r
+         else if ((active0 & 0x4000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 50, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0xa000010000c0030L);\r
+      case 115:\r
+         if ((active0 & 0x400000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 34, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x80000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(4, 55, 2);\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x21200004004000L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x100000000L);\r
+      case 119:\r
+         return jjMoveStringLiteralDfa5_0(active0, 0x2000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(3, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa5_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(3, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(4, active0, 0L);\r
+      return 5;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x1400000004000L);\r
+      case 99:\r
+         if ((active0 & 0x100000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 56, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x8108000002000L);\r
+      case 100:\r
+         if ((active0 & 0x800000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 59, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x42000000000000L);\r
+      case 101:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000020L);\r
+      case 102:\r
+         if ((active0 & 0x100000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 20, 2);\r
+         break;\r
+      case 103:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000000L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x2000000L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x200004000010L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x100L);\r
+      case 109:\r
+         if ((active0 & 0x800000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 23, 2);\r
+         break;\r
+      case 110:\r
+         if ((active0 & 0x40000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 18, 2);\r
+         else if ((active0 & 0x10000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 52, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x200000000000000L);\r
+      case 114:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x20010000000000L);\r
+      case 115:\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x40000000L);\r
+      case 116:\r
+         if ((active0 & 0x80000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 19, 2);\r
+         else if ((active0 & 0x100000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 32, 2);\r
+         else if ((active0 & 0x1000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(5, 36, 2);\r
+         return jjMoveStringLiteralDfa6_0(active0, 0x20000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(4, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa6_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(4, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(5, active0, 0L);\r
+      return 6;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x222010000000100L);\r
+      case 101:\r
+         if ((active0 & 0x2000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 37, 2);\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x2002000L);\r
+      case 108:\r
+         if ((active0 & 0x400000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 46, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x1000000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x200004020000L);\r
+      case 115:\r
+         if ((active0 & 0x40000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(6, 54, 2);\r
+         break;\r
+      case 116:\r
+         if ((active0 & 0x8000000000L) != 0L)\r
+         {\r
+            jjmatchedKind = 39;\r
+            jjmatchedPos = 6;\r
+         }\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x8140000004030L);\r
+      case 117:\r
+         return jjMoveStringLiteralDfa7_0(active0, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(5, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa7_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(5, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(6, active0, 0L);\r
+      return 7;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x2000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x2000000000000L);\r
+      case 101:\r
+         if ((active0 & 0x20L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 5, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x8040000000000L);\r
+      case 104:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10L);\r
+      case 105:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x20000000004000L);\r
+      case 108:\r
+         if ((active0 & 0x200000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 57, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x40000000L);\r
+      case 110:\r
+         if ((active0 & 0x2000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 25, 2);\r
+         else if ((active0 & 0x4000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 26, 2);\r
+         else if ((active0 & 0x200000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 45, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100000000000L);\r
+      case 114:\r
+         if ((active0 & 0x20000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 17, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x100L);\r
+      case 116:\r
+         if ((active0 & 0x1000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(7, 48, 2);\r
+         return jjMoveStringLiteralDfa8_0(active0, 0x10000000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(6, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa8_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(6, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(7, active0, 0L);\r
+      return 8;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 97:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x40000000L);\r
+      case 98:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x2000L);\r
+      case 100:\r
+         if ((active0 & 0x8000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 51, 2);\r
+         break;\r
+      case 101:\r
+         if ((active0 & 0x100L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 8, 2);\r
+         break;\r
+      case 105:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x10000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x2000000000000L);\r
+      case 109:\r
+         if ((active0 & 0x10L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 4, 2);\r
+         break;\r
+      case 110:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x20000000000000L);\r
+      case 111:\r
+         return jjMoveStringLiteralDfa9_0(active0, 0x4000L);\r
+      case 114:\r
+         if ((active0 & 0x40000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 42, 2);\r
+         else if ((active0 & 0x100000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(8, 44, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(7, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa9_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(7, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(8, active0, 0L);\r
+      return 9;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 101:\r
+         if ((active0 & 0x2000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 49, 2);\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x20000000000000L);\r
+      case 108:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x2000L);\r
+      case 110:\r
+         if ((active0 & 0x4000L) != 0L)\r
+            return jjStartNfaWithStates_0(9, 14, 2);\r
+         break;\r
+      case 111:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x10000000000L);\r
+      case 116:\r
+         return jjMoveStringLiteralDfa10_0(active0, 0x40000000L);\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(8, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa10_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(8, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(9, active0, 0L);\r
+      return 10;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 100:\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x20000000000000L);\r
+      case 101:\r
+         if ((active0 & 0x2000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 13, 2);\r
+         return jjMoveStringLiteralDfa11_0(active0, 0x40000000L);\r
+      case 110:\r
+         if ((active0 & 0x10000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(10, 40, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(9, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa11_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(9, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(10, active0, 0L);\r
+      return 11;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 98:\r
+         return jjMoveStringLiteralDfa12_0(active0, 0x20000000000000L);\r
+      case 100:\r
+         if ((active0 & 0x40000000L) != 0L)\r
+            return jjStartNfaWithStates_0(11, 30, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(10, active0, 0L);\r
+}\r
+private int jjMoveStringLiteralDfa12_0(long old0, long active0)\r
+{\r
+   if (((active0 &= old0)) == 0L)\r
+      return jjStartNfa_0(10, old0, 0L);\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) {\r
+      jjStopStringLiteralDfa_0(11, active0, 0L);\r
+      return 12;\r
+   }\r
+   switch(curChar)\r
+   {\r
+      case 121:\r
+         if ((active0 & 0x20000000000000L) != 0L)\r
+            return jjStartNfaWithStates_0(12, 53, 2);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+   return jjStartNfa_0(11, active0, 0L);\r
+}\r
+private int jjStartNfaWithStates_0(int pos, int kind, int state)\r
+{\r
+   jjmatchedKind = kind;\r
+   jjmatchedPos = pos;\r
+   try { curChar = input_stream.readChar(); }\r
+   catch(java.io.IOException e) { return pos + 1; }\r
+   return jjMoveNfa_0(state, pos + 1);\r
+}\r
+static final long[] jjbitVec0 = {
+   0x0L, 0x0L, 0x20000800000000L, 0x0L
+};\r
+static final long[] jjbitVec1 = {
+   0x0L, 0x0L, 0xfffffffffffe0000L, 0x3ffL
+};\r
+static final long[] jjbitVec2 = {
+   0x0L, 0x0L, 0x100000000000L, 0x0L
+};\r
+static final long[] jjbitVec3 = {
+   0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
+};\r
+static final long[] jjbitVec5 = {
+   0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+};\r
+private int jjMoveNfa_0(int startState, int curPos)\r
+{\r
+   int startsAt = 0;\r
+   jjnewStateCnt = 34;\r
+   int i = 1;\r
+   jjstateSet[0] = startState;\r
+   int kind = 0x7fffffff;\r
+   for (;;)\r
+   {\r
+      if (++jjround == 0x7fffffff)\r
+         ReInitRounds();\r
+      if (curChar < 64)\r
+      {\r
+         long l = 1L << curChar;\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 14:\r
+                  if (curChar == 47)\r
+                  {\r
+                     if (kind > 3)\r
+                        kind = 3;\r
+                     jjCheckNAdd(21);\r
+                  }\r
+                  else if (curChar == 42)\r
+                     jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 0:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 90)\r
+                        kind = 90;\r
+                     jjCheckNAddStates(3, 7);\r
+                  }\r
+                  else if ((0x100002600L & l) != 0L)\r
+                  {\r
+                     if (kind > 1)\r
+                        kind = 1;\r
+                  }\r
+                  else if ((0x3000000000L & l) != 0L)\r
+                  {\r
+                     if (kind > 88)\r
+                        kind = 88;\r
+                     jjCheckNAdd(2);\r
+                  }\r
+                  else if (curChar == 47)\r
+                     jjAddStates(8, 9);\r
+                  else if (curChar == 46)\r
+                     jjCheckNAdd(9);\r
+                  else if (curChar == 34)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 1:\r
+                  if ((0x3000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 88)\r
+                     kind = 88;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 2:\r
+                  if ((0x3ff003000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 88)\r
+                     kind = 88;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 3:\r
+                  if (curChar == 34)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 4:\r
+                  if ((0xfffffffbfffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 6:\r
+                  if ((0xfffffffffffffbffL & l) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 7:\r
+                  if (curChar == 34 && kind > 89)\r
+                     kind = 89;\r
+                  break;\r
+               case 8:\r
+                  if (curChar == 46)\r
+                     jjCheckNAdd(9);\r
+                  break;\r
+               case 9:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 91)\r
+                     kind = 91;\r
+                  jjCheckNAddTwoStates(9, 10);\r
+                  break;\r
+               case 11:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(12);\r
+                  break;\r
+               case 12:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 91)\r
+                     kind = 91;\r
+                  jjCheckNAdd(12);\r
+                  break;\r
+               case 13:\r
+                  if (curChar == 47)\r
+                     jjAddStates(8, 9);\r
+                  break;\r
+               case 15:\r
+                  if ((0xfffffbffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 16:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 17;\r
+                  break;\r
+               case 17:\r
+                  if ((0xffff7fffffffffffL & l) != 0L)\r
+                     jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 18:\r
+                  if (curChar == 47 && kind > 2)\r
+                     kind = 2;\r
+                  break;\r
+               case 19:\r
+                  if (curChar == 42)\r
+                     jjstateSet[jjnewStateCnt++] = 18;\r
+                  break;\r
+               case 20:\r
+                  if (curChar != 47)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(21);\r
+                  break;\r
+               case 21:\r
+                  if ((0xfffffffffffffbffL & l) == 0L)\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjCheckNAdd(21);\r
+                  break;\r
+               case 22:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjCheckNAddStates(3, 7);\r
+                  break;\r
+               case 23:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 90)\r
+                     kind = 90;\r
+                  jjCheckNAdd(23);\r
+                  break;\r
+               case 24:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(24, 25);\r
+                  break;\r
+               case 25:\r
+                  if (curChar != 46)\r
+                     break;\r
+                  if (kind > 91)\r
+                     kind = 91;\r
+                  jjCheckNAddTwoStates(26, 27);\r
+                  break;\r
+               case 26:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 91)\r
+                     kind = 91;\r
+                  jjCheckNAddTwoStates(26, 27);\r
+                  break;\r
+               case 28:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(29);\r
+                  break;\r
+               case 29:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 91)\r
+                     kind = 91;\r
+                  jjCheckNAdd(29);\r
+                  break;\r
+               case 30:\r
+                  if ((0x3ff000000000000L & l) != 0L)\r
+                     jjCheckNAddTwoStates(30, 31);\r
+                  break;\r
+               case 32:\r
+                  if ((0x280000000000L & l) != 0L)\r
+                     jjCheckNAdd(33);\r
+                  break;\r
+               case 33:\r
+                  if ((0x3ff000000000000L & l) == 0L)\r
+                     break;\r
+                  if (kind > 91)\r
+                     kind = 91;\r
+                  jjCheckNAdd(33);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else if (curChar < 128)\r
+      {\r
+         long l = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 0:\r
+               case 2:\r
+                  if ((0x7fffffe87fffffeL & l) == 0L)\r
+                     break;\r
+                  if (kind > 88)\r
+                     kind = 88;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 4:\r
+                  if ((0xffffffffefffffffL & l) != 0L)\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 5:\r
+                  if (curChar == 92)\r
+                     jjstateSet[jjnewStateCnt++] = 6;\r
+                  break;\r
+               case 6:\r
+                  jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 10:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(13, 14);\r
+                  break;\r
+               case 15:\r
+               case 17:\r
+                  jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 21:\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 21;\r
+                  break;\r
+               case 27:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(15, 16);\r
+                  break;\r
+               case 31:\r
+                  if ((0x2000000020L & l) != 0L)\r
+                     jjAddStates(17, 18);\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      else\r
+      {\r
+         int hiByte = (int)(curChar >> 8);\r
+         int i1 = hiByte >> 6;\r
+         long l1 = 1L << (hiByte & 077);\r
+         int i2 = (curChar & 0xff) >> 6;\r
+         long l2 = 1L << (curChar & 077);\r
+         do\r
+         {\r
+            switch(jjstateSet[--i])\r
+            {\r
+               case 0:\r
+               case 2:\r
+                  if (!jjCanMove_0(hiByte, i1, i2, l1, l2))\r
+                     break;\r
+                  if (kind > 88)\r
+                     kind = 88;\r
+                  jjCheckNAdd(2);\r
+                  break;\r
+               case 4:\r
+               case 6:\r
+                  if (jjCanMove_1(hiByte, i1, i2, l1, l2))\r
+                     jjCheckNAddStates(10, 12);\r
+                  break;\r
+               case 15:\r
+               case 17:\r
+                  if (jjCanMove_2(hiByte, i1, i2, l1, l2))\r
+                     jjCheckNAddStates(0, 2);\r
+                  break;\r
+               case 21:\r
+                  if (!jjCanMove_2(hiByte, i1, i2, l1, l2))\r
+                     break;\r
+                  if (kind > 3)\r
+                     kind = 3;\r
+                  jjstateSet[jjnewStateCnt++] = 21;\r
+                  break;\r
+               default : break;\r
+            }\r
+         } while(i != startsAt);\r
+      }\r
+      if (kind != 0x7fffffff)\r
+      {\r
+         jjmatchedKind = kind;\r
+         jjmatchedPos = curPos;\r
+         kind = 0x7fffffff;\r
+      }\r
+      ++curPos;\r
+      if ((i = jjnewStateCnt) == (startsAt = 34 - (jjnewStateCnt = startsAt)))\r
+         return curPos;\r
+      try { curChar = input_stream.readChar(); }\r
+      catch(java.io.IOException e) { return curPos; }\r
+   }\r
+}\r
+static final int[] jjnextStates = {
+   15, 16, 19, 23, 24, 25, 30, 31, 14, 20, 4, 5, 7, 11, 12, 28, 
+   29, 32, 33, 
+};\r
+private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2)\r
+{\r
+   switch(hiByte)\r
+   {\r
+      case 0:\r
+         return ((jjbitVec0[i2] & l2) != 0L);\r
+      case 3:\r
+         return ((jjbitVec1[i2] & l2) != 0L);\r
+      case 32:\r
+         return ((jjbitVec2[i2] & l2) != 0L);\r
+      default :\r
+         return false;\r
+   }\r
+}\r
+private static final boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2)\r
+{\r
+   switch(hiByte)\r
+   {\r
+      case 0:\r
+         return ((jjbitVec5[i2] & l2) != 0L);\r
+      default :\r
+         if ((jjbitVec3[i1] & l1) != 0L)\r
+            return true;\r
+         return false;\r
+   }\r
+}\r
+private static final boolean jjCanMove_2(int hiByte, int i1, int i2, long l1, long l2)\r
+{\r
+   switch(hiByte)\r
+   {\r
+      case 0:\r
+         return ((jjbitVec5[i2] & l2) != 0L);\r
+      default :\r
+         return false;\r
+   }\r
+}\r
+\r
+/** Token literal values. */\r
+public static final String[] jjstrLiteralImages = {\r
+"", null, null, null, "\141\154\147\157\162\151\164\150\155", \r
+"\144\151\163\143\162\145\164\145", "\146\141\154\163\145", "\155\157\144\145\154", \r
+"\162\145\144\145\143\154\141\162\145", "\141\156\144", "\145\141\143\150", "\146\151\156\141\154", "\156\157\164", \r
+"\162\145\160\154\141\143\145\141\142\154\145", "\141\156\156\157\164\141\164\151\157\156", "\145\154\163\145", \r
+"\146\154\157\167", "\157\160\145\162\141\164\157\162", "\162\145\164\165\162\156", \r
+"\141\163\163\145\162\164", "\145\154\163\145\151\146", "\146\157\162", "\157\162", \r
+"\163\164\162\145\141\155", "\142\154\157\143\153", "\145\154\163\145\167\150\145\156", \r
+"\146\165\156\143\164\151\157\156", "\157\165\164\145\162", "\164\150\145\156", "\142\162\145\141\153", \r
+"\145\156\143\141\160\163\165\154\141\164\145\144", "\151\146", "\157\165\164\160\165\164", "\164\162\165\145", \r
+"\143\154\141\163\163", "\145\156\144", "\151\155\160\157\162\164", "\160\141\143\153\141\147\145", \r
+"\164\171\160\145", "\143\157\156\156\145\143\164", \r
+"\145\156\165\155\145\162\141\164\151\157\156", "\151\156", "\160\141\162\141\155\145\164\145\162", "\167\150\145\156", \r
+"\143\157\156\156\145\143\164\157\162", "\145\161\165\141\164\151\157\156", "\160\141\162\164\151\141\154", \r
+"\167\150\151\154\145", "\143\157\156\163\164\141\156\164", \r
+"\145\170\160\141\156\144\141\142\154\145", "\151\156\156\145\162", "\160\162\157\164\145\143\164\145\144", \r
+"\167\151\164\150\151\156", "\143\157\156\163\164\162\141\151\156\145\144\142\171", \r
+"\145\170\164\145\156\144\163", "\151\156\160\165\164", "\160\165\142\154\151\143", \r
+"\145\170\164\145\162\156\141\154", "\154\157\157\160", "\162\145\143\157\162\144", "\50", "\51", "\173", "\175", \r
+"\133", "\135", "\56", "\72", "\73", "\54", "\74", "\74\75", "\76", "\76\75", \r
+"\75\75", "\74\76", "\53", "\55", "\56\53", "\56\55", "\52", "\57", "\56\52", "\56\57", \r
+"\136", "\56\136", "\75", "\72\75", null, null, null, null, };\r
+\r
+/** Lexer state names. */\r
+public static final String[] lexStateNames = {\r
+   "DEFAULT",\r
+};\r
+static final long[] jjtoToken = {
+   0xfffffffffffffff1L, 0xfffffffL, 
+};\r
+static final long[] jjtoSkip = {
+   0xeL, 0x0L, 
+};\r
+protected SimpleCharStream input_stream;\r
+private final int[] jjrounds = new int[34];\r
+private final int[] jjstateSet = new int[68];\r
+private final StringBuilder jjimage = new StringBuilder();\r
+private StringBuilder image = jjimage;\r
+private int jjimageLen;\r
+private int lengthOfMatch;\r
+protected char curChar;\r
+/** Constructor. */\r
+public UnitParserTokenManager(SimpleCharStream stream){\r
+   if (SimpleCharStream.staticFlag)\r
+      throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");\r
+   input_stream = stream;\r
+}\r
+\r
+/** Constructor. */\r
+public UnitParserTokenManager(SimpleCharStream stream, int lexState){\r
+   this(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream)\r
+{\r
+   jjmatchedPos = jjnewStateCnt = 0;\r
+   curLexState = defaultLexState;\r
+   input_stream = stream;\r
+   ReInitRounds();\r
+}\r
+private void ReInitRounds()\r
+{\r
+   int i;\r
+   jjround = 0x80000001;\r
+   for (i = 34; i-- > 0;)\r
+      jjrounds[i] = 0x80000000;\r
+}\r
+\r
+/** Reinitialise parser. */\r
+public void ReInit(SimpleCharStream stream, int lexState)\r
+{\r
+   ReInit(stream);\r
+   SwitchTo(lexState);\r
+}\r
+\r
+/** Switch to specified lex state. */\r
+public void SwitchTo(int lexState)\r
+{\r
+   if (lexState >= 1 || lexState < 0)\r
+      throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);\r
+   else\r
+      curLexState = lexState;\r
+}\r
+\r
+protected Token jjFillToken()\r
+{\r
+   final Token t;\r
+   final String curTokenImage;\r
+   final int beginLine;\r
+   final int endLine;\r
+   final int beginColumn;\r
+   final int endColumn;\r
+   String im = jjstrLiteralImages[jjmatchedKind];\r
+   curTokenImage = (im == null) ? input_stream.GetImage() : im;\r
+   beginLine = input_stream.getBeginLine();\r
+   beginColumn = input_stream.getBeginColumn();\r
+   endLine = input_stream.getEndLine();\r
+   endColumn = input_stream.getEndColumn();\r
+   t = Token.newToken(jjmatchedKind, curTokenImage);\r
+\r
+   t.beginLine = beginLine;\r
+   t.endLine = endLine;\r
+   t.beginColumn = beginColumn;\r
+   t.endColumn = endColumn;\r
+\r
+   return t;\r
+}\r
+\r
+int curLexState = 0;\r
+int defaultLexState = 0;\r
+int jjnewStateCnt;\r
+int jjround;\r
+int jjmatchedPos;\r
+int jjmatchedKind;\r
+\r
+/** Get the next Token. */\r
+public Token getNextToken() \r
+{\r
+  Token matchedToken;\r
+  int curPos = 0;\r
+\r
+  EOFLoop :
+  for (;;)\r
+  {\r
+   try\r
+   {\r
+      curChar = input_stream.BeginToken();\r
+   }\r
+   catch(java.io.IOException e)\r
+   {\r
+      jjmatchedKind = 0;\r
+      matchedToken = jjFillToken();\r
+      return matchedToken;\r
+   }\r
+   image = jjimage;\r
+   image.setLength(0);\r
+   jjimageLen = 0;\r
+\r
+   jjmatchedKind = 0x7fffffff;\r
+   jjmatchedPos = 0;\r
+   curPos = jjMoveStringLiteralDfa0_0();\r
+   if (jjmatchedKind != 0x7fffffff)\r
+   {\r
+      if (jjmatchedPos + 1 < curPos)\r
+         input_stream.backup(curPos - jjmatchedPos - 1);\r
+      if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)\r
+      {\r
+         matchedToken = jjFillToken();\r
+         TokenLexicalActions(matchedToken);\r
+         return matchedToken;\r
+      }\r
+      else\r
+      {\r
+         continue EOFLoop;\r
+      }\r
+   }\r
+   int error_line = input_stream.getEndLine();\r
+   int error_column = input_stream.getEndColumn();\r
+   String error_after = null;\r
+   boolean EOFSeen = false;\r
+   try { input_stream.readChar(); input_stream.backup(1); }\r
+   catch (java.io.IOException e1) {\r
+      EOFSeen = true;\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+      if (curChar == '\n' || curChar == '\r') {\r
+         error_line++;\r
+         error_column = 0;\r
+      }\r
+      else\r
+         error_column++;\r
+   }\r
+   if (!EOFSeen) {\r
+      input_stream.backup(1);\r
+      error_after = curPos <= 1 ? "" : input_stream.GetImage();\r
+   }\r
+   throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);\r
+  }\r
+}\r
+\r
+void TokenLexicalActions(Token matchedToken)\r
+{\r
+   switch(jjmatchedKind)\r
+   {\r
+      case 89 :\r
+        image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)));\r
+      matchedToken.image = matchedToken.image.substring(1,matchedToken.image.length()-1);\r
+         break;\r
+      default :\r
+         break;\r
+   }\r
+}\r
+private void jjCheckNAdd(int state)\r
+{\r
+   if (jjrounds[state] != jjround)\r
+   {\r
+      jjstateSet[jjnewStateCnt++] = state;\r
+      jjrounds[state] = jjround;\r
+   }\r
+}\r
+private void jjAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjstateSet[jjnewStateCnt++] = jjnextStates[start];\r
+   } while (start++ != end);\r
+}\r
+private void jjCheckNAddTwoStates(int state1, int state2)\r
+{\r
+   jjCheckNAdd(state1);\r
+   jjCheckNAdd(state2);\r
+}\r
+\r
+private void jjCheckNAddStates(int start, int end)\r
+{\r
+   do {\r
+      jjCheckNAdd(jjnextStates[start]);\r
+   } while (start++ != end);\r
+}\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserTreeConstants.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/UnitParserTreeConstants.java
new file mode 100644 (file)
index 0000000..656c238
--- /dev/null
@@ -0,0 +1,89 @@
+/* Generated By:JavaCC: Do not edit this line. UnitParserTreeConstants.java Version 5.0 */\r
+package org.simantics.sysdyn.unitParser;\r
+\r
+public interface UnitParserTreeConstants\r
+{\r
+  public int JJTEXPR = 0;\r
+  public int JJTEXPRESSION = 1;\r
+  public int JJTIFTHENELSE = 2;\r
+  public int JJTCONDITION = 3;\r
+  public int JJTSIMPLE_EXPRESSION = 4;\r
+  public int JJTLOGICAL_EXPRESSION = 5;\r
+  public int JJTLOGICAL_TERM = 6;\r
+  public int JJTLOGICAL_FACTOR = 7;\r
+  public int JJTRELATION = 8;\r
+  public int JJTREL_OP = 9;\r
+  public int JJTARITHMETIC_EXPRESSION = 10;\r
+  public int JJTADD_OP = 11;\r
+  public int JJTTERM = 12;\r
+  public int JJTFACTOR = 13;\r
+  public int JJTPOWER = 14;\r
+  public int JJTMULTIPLICATION = 15;\r
+  public int JJTDIVIDE = 16;\r
+  public int JJTPRIMARY = 17;\r
+  public int JJTCOMPONENT_REFERENCE_FULL = 18;\r
+  public int JJTARRAY_DEFINITION = 19;\r
+  public int JJTFUNCTION_CALL = 20;\r
+  public int JJTPARENTHESIS_EXPRESSION = 21;\r
+  public int JJTVALUE = 22;\r
+  public int JJTPARENTHESIS_OPEN = 23;\r
+  public int JJTPARENTHESIS_CLOSE = 24;\r
+  public int JJTNAME = 25;\r
+  public int JJTCOMPONENT_REFERENCE = 26;\r
+  public int JJTCOMPONENT_IDENTITY = 27;\r
+  public int JJTFUNCTION_CALL_ARGS = 28;\r
+  public int JJTFUNCTION_ARGUMENTS = 29;\r
+  public int JJTFOR_INDICES = 30;\r
+  public int JJTFOR_INDEX = 31;\r
+  public int JJTNAMED_ARGUMENTS = 32;\r
+  public int JJTNAMED_ARGUMENT = 33;\r
+  public int JJTOUTPUT_EXPRESSION_LIST = 34;\r
+  public int JJTEXPRESSION_LIST = 35;\r
+  public int JJTARRAY_SUBSCRIPTS = 36;\r
+  public int JJTSUBSCRIPT = 37;\r
+  public int JJTRANGEINDEX = 38;\r
+\r
+\r
+  public String[] jjtNodeName = {\r
+    "expr",\r
+    "expression",\r
+    "ifthenelse",\r
+    "condition",\r
+    "simple_expression",\r
+    "logical_expression",\r
+    "logical_term",\r
+    "logical_factor",\r
+    "relation",\r
+    "rel_op",\r
+    "arithmetic_expression",\r
+    "add_op",\r
+    "term",\r
+    "factor",\r
+    "power",\r
+    "multiplication",\r
+    "divide",\r
+    "primary",\r
+    "component_reference_full",\r
+    "array_definition",\r
+    "function_call",\r
+    "parenthesis_expression",\r
+    "value",\r
+    "parenthesis_open",\r
+    "parenthesis_close",\r
+    "name",\r
+    "component_reference",\r
+    "component_identity",\r
+    "function_call_args",\r
+    "function_arguments",\r
+    "for_indices",\r
+    "for_index",\r
+    "named_arguments",\r
+    "named_argument",\r
+    "output_expression_list",\r
+    "expression_list",\r
+    "array_subscripts",\r
+    "subscript",\r
+    "rangeIndex",\r
+  };\r
+}\r
+/* JavaCC - OriginalChecksum=55cc0533e9e24a32b3fbe9bcd56ca148 (do not edit this line) */\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/AddOp.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/AddOp.java
new file mode 100644 (file)
index 0000000..6aafee9
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class AddOp extends UnitCheckingNode {\r
+\r
+    public AddOp(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = super.getUnits(units, functions, allowEquivalents);\r
+        result.setUnitType(UnitType.OPERATOR);\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Arithmetic.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Arithmetic.java
new file mode 100644 (file)
index 0000000..44bb2e2
--- /dev/null
@@ -0,0 +1,69 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Arithmetic extends UnitCheckingNode {\r
+\r
+    public Arithmetic(int id) {\r
+        super(id);\r
+    }\r
+\r
+\r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = new UnitResult(allowEquivalents);\r
+\r
+        UnitCheckingNode base = null;\r
+        UnitCheckingNode operator = null;\r
+        UnitCheckingNode candidateNode = null;\r
+\r
+        for(int i = 0; i < jjtGetNumChildren(); i++) {\r
+            candidateNode = ((UnitCheckingNode)jjtGetChild(i));\r
+            UnitResult candidateUnits = candidateNode.getUnits(units, functions, allowEquivalents);\r
+            if(candidateUnits.getUnitType() == UnitType.OPERATOR) {\r
+                continue;\r
+            } else if(base == null || result.getUnitType() == UnitType.SCALAR || result.getUnitType() == UnitType.ANY) {\r
+                base = ((UnitCheckingNode)jjtGetChild(i));\r
+                result.appendResult(base.getUnits(units, functions, allowEquivalents));\r
+                continue;\r
+            } else if(candidateUnits.getUnitType() == UnitType.SCALAR) {\r
+                continue;\r
+            } else {\r
+                operator = ((UnitCheckingNode)jjtGetChild(i-1));\r
+                if(!result.equals(candidateUnits)) {\r
+                    throw new UnitCheckingException("Not equals exception: " +\r
+                            base.printNode() + " [" + result.getCleanFullUnit() + "] " + operator.printNode() + " " +\r
+                            candidateNode.printNode() + " [" + candidateUnits.getCleanFullUnit() + "]"\r
+                            );\r
+                }\r
+            }\r
+        }\r
+//        System.out.println("Arithmetic: " + printNode() + " [" + result.getFullUnit() + " : " + result.getUnitType() + "]");\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ArrayDefinition.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ArrayDefinition.java
new file mode 100644 (file)
index 0000000..9754bd3
--- /dev/null
@@ -0,0 +1,105 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ArrayDefinition extends UnitCheckingNode {\r
+\r
+    public ArrayDefinition(int id) {\r
+        super(id);\r
+    }\r
+\r
+\r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = new UnitResult(allowEquivalents);\r
+        result.setUnitType(UnitType.SCALAR);\r
+\r
+        UnitCheckingNode base = null;\r
+\r
+        if(jjtGetNumChildren() > 0 && jjtGetChild(0) instanceof FunctionArguments) {\r
+            FunctionArguments functionArguments = (FunctionArguments) jjtGetChild(0);\r
+\r
+            for(UnitCheckingNode candidateNode : gatherExpressions(functionArguments, new ArrayList<UnitCheckingNode>())) {\r
+                UnitResult candidateUnits = candidateNode.getUnits(units, functions, allowEquivalents);\r
+                if(candidateUnits.getUnitType() == UnitType.SCALAR) {\r
+                    continue;\r
+                } else if(base == null) {\r
+                    base = candidateNode;\r
+                    UnitType oldUnitType = result.getUnitType();\r
+                    result.appendResult(base.getUnits(units, functions, allowEquivalents));\r
+\r
+                    /*\r
+                     * Make sure unit type persist\r
+                     *  {Var1, Var2, 1} would result in UnitType.SCALAR even though it should be UnitType.NORMAL \r
+                     *  because the last element has UnitType.SCALAR  \r
+                     */\r
+                    UnitType newUnitType = result.getUnitType();\r
+                    if(newUnitType == UnitType.SCALAR || newUnitType == UnitType.ANY || newUnitType == UnitType.DMNL)\r
+                        result.setUnitType(oldUnitType);\r
+                    continue;\r
+                } else {\r
+                    if(!result.equals(candidateUnits)) {\r
+                        throw new UnitCheckingException("Array elements do not have same units: " +\r
+                                base.printNode() + " [" + result.getCleanFullUnit() + "] =/= " +\r
+                                candidateNode.printNode() + " [" + candidateUnits.getCleanFullUnit() + "]"\r
+                                );\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        \r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * Gather all expressions of array definitions.\r
+     * \r
+     * void function_arguments() : {\r
+     * } {\r
+     *     LOOKAHEAD(2) named_argument()  ( "," function_arguments() )?\r
+     *     | expression() ( "," function_arguments() | "for" for_indices() )?\r
+     *     \r
+     * }\r
+     * @param functionArguments\r
+     * @param expressions\r
+     * @return\r
+     */\r
+    private ArrayList<UnitCheckingNode> gatherExpressions(UnitCheckingNode functionArguments, ArrayList<UnitCheckingNode> expressions) {\r
+        if(functionArguments.jjtGetNumChildren() > 0) {\r
+            if(functionArguments.jjtGetChild(0) instanceof Expression) {\r
+                expressions.add(((UnitCheckingNode)functionArguments.jjtGetChild(0)));\r
+            }\r
+        }\r
+\r
+        if(functionArguments.jjtGetNumChildren() > 1) {\r
+            gatherExpressions((UnitCheckingNode)functionArguments.jjtGetChild(1), expressions);\r
+        }\r
+\r
+        return expressions;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentIdentity.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentIdentity.java
new file mode 100644 (file)
index 0000000..8d90375
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import org.simantics.sysdyn.unitParser.Token;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ComponentIdentity extends UnitCheckingNode {\r
+\r
+    public ComponentIdentity(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public String printNode() {\r
+        StringBuilder sb = new StringBuilder();\r
+        Token token = jjtGetFirstToken();\r
+        sb.append(token.image);\r
+\r
+        while(token != null && !token.equals(jjtGetLastToken())) {\r
+            sb.append(" ");\r
+            token = token.next;\r
+            sb.append(token.image);\r
+        }\r
+        return sb.toString();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentReference.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentReference.java
new file mode 100644 (file)
index 0000000..b9541bb
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ComponentReference extends UnitCheckingNode {\r
+\r
+    public ComponentReference(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public String printNode() {\r
+        StringBuilder sb = new StringBuilder();\r
+        for(int i = 0; i < jjtGetNumChildren(); i++) {\r
+            UnitCheckingNode node = (UnitCheckingNode) jjtGetChild(i);\r
+            if(node instanceof ComponentIdentity || node instanceof ComponentReference) {\r
+                if(sb.length() > 0)\r
+                    sb.append(".");\r
+                sb.append(node.printNode());\r
+            }\r
+        }\r
+        return sb.toString();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentReferenceFull.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ComponentReferenceFull.java
new file mode 100644 (file)
index 0000000..fa8e959
--- /dev/null
@@ -0,0 +1,85 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.ParseException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.UnitParser;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ComponentReferenceFull extends UnitCheckingNode {\r
+\r
+    public ComponentReferenceFull(int id) {\r
+        super(id);\r
+    }\r
+\r
+    protected UnitResult parseUnits(String units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        StringReader sr = new StringReader(units);\r
+        UnitParser parser = new UnitParser(sr);\r
+        try {\r
+            UnitCheckingNode node = (UnitCheckingNode) parser.expr();\r
+            return node.getUnits(null, functions, allowEquivalents);\r
+        } catch (UnitCheckingException e) {\r
+            e.printStackTrace();\r
+        } catch (ParseException e) {\r
+            throw new UnitCheckingException("Cannot validate units: Syntax error in expression.");\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        String node = printNode();\r
+        \r
+        if("dmnl".equals(node)) {\r
+            UnitResult result = new UnitResult(allowEquivalents);\r
+            result.setUnitType(UnitType.DMNL);\r
+            return result;\r
+        }\r
+        \r
+        if(units != null) {\r
+            if(!units.containsKey(node) || units.get(node) == null)\r
+                throw new UnitCheckingException("No units defined for " + node);\r
+            else {\r
+                return parseUnits(units.get(node), functions, allowEquivalents);\r
+            }\r
+        } else {\r
+            UnitResult result = new UnitResult(allowEquivalents);\r
+            result.addDivident(node);\r
+            result.append(node);\r
+            return result; \r
+        }\r
+    }\r
+\r
+    @Override\r
+    public String printNode() {\r
+        StringBuilder sb = new StringBuilder();\r
+        for(int i = 0; i < jjtGetNumChildren(); i++) {\r
+            UnitCheckingNode node = (UnitCheckingNode) jjtGetChild(i);\r
+            sb.append(node.printNode());\r
+        }\r
+        return sb.toString();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Condition.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Condition.java
new file mode 100644 (file)
index 0000000..c382cda
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class Condition extends UnitCheckingNode {\r
+\r
+    public Condition(int id) {\r
+        super(id);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Divide.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Divide.java
new file mode 100644 (file)
index 0000000..c206105
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Divide extends UnitCheckingNode {\r
+\r
+    public Divide(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = super.getUnits(units, functions, allowEquivalents);\r
+        result.setUnitType(UnitType.OPERATOR);\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Expression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Expression.java
new file mode 100644 (file)
index 0000000..eb3ec7f
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class Expression extends UnitCheckingNode {\r
+\r
+    public Expression(int id) {\r
+        super(id);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Factor.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Factor.java
new file mode 100644 (file)
index 0000000..fc92f87
--- /dev/null
@@ -0,0 +1,121 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.Token;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Tuomas Miettinen\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class Factor extends UnitCheckingNode {\r
+\r
+    public Factor(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = new UnitResult(allowEquivalents);\r
+        \r
+        UnitCheckingNode current = null;\r
+        UnitCheckingNode operator = null;\r
+        UnitCheckingNode base = null;\r
+        \r
+        for(int i = 0; i < jjtGetNumChildren(); i++) {\r
+            current = ((UnitCheckingNode)jjtGetChild(i));\r
+            UnitResult currentUnits = current.getUnits(units, functions, allowEquivalents);\r
+\r
+            if(currentUnits.getUnitType() == UnitType.ANY) {\r
+                result = new UnitResult(allowEquivalents);\r
+                result.setUnitType(UnitType.ANY);\r
+                return result;\r
+            } else if(currentUnits.getUnitType() == UnitType.OPERATOR) {\r
+                continue;\r
+            } else if(base == null) {\r
+                base = current;\r
+                continue;\r
+            } else {\r
+                operator = ((UnitCheckingNode)jjtGetChild(i-1));\r
+\r
+                if(operator instanceof Power) {\r
+                    UnitType unitType = currentUnits.getUnitType();\r
+                    if(unitType == UnitType.SCALAR) {\r
+                       int exponent;\r
+                       UnitResult baseUnits = base.getUnits(units, functions, allowEquivalents);\r
+                       try {\r
+                               exponent = Integer.valueOf(currentUnits.getFullUnit());\r
+                       } catch (NumberFormatException e) {\r
+                               exponent = 1; /* It's a bit of a corner case if someone want's to use\r
+                               an arithmetic expression other than a constant in the exponent. */\r
+                       }\r
+                       \r
+                       if (exponent < 0) {\r
+                               for (int j = 0; j > exponent; --j) {\r
+                                       // Negative exponent turns the base number around.\r
+                                       result.addAllDividers(baseUnits.getDividents());\r
+                                       result.addAllDividents(baseUnits.getDividers());\r
+                                       result.append(operator.printNode());\r
+                                       result.append(baseUnits.getFullUnit());\r
+                               }\r
+                               result.setUnitType(baseUnits.getUnitType());\r
+                       } else if (exponent > 0) {\r
+                               result.appendResult(baseUnits);\r
+                            for (int j = 1; j < exponent; ++j) {\r
+                                       result.addAllDividents(baseUnits.getDividents());\r
+                                       result.addAllDividers(baseUnits.getDividers());\r
+                                       result.append(operator.printNode());\r
+                                       result.append(baseUnits.getFullUnit());\r
+                               }\r
+                               result.setUnitType(baseUnits.getUnitType());\r
+                       } // 0 is a corner case\r
+                    }\r
+                }\r
+            }\r
+        }\r
+//        System.out.println("Term: " + printNode() + " [" + result.getFullUnit() + " : " + result.getUnitType() + "]");\r
+        return result;\r
+    }\r
+    \r
+    @Override\r
+    public String printNode() {\r
+        StringBuilder sb = new StringBuilder();\r
+        Token token = jjtGetFirstToken();\r
+        sb.append(token.image);\r
+\r
+        Token prevToken = null;\r
+        while(token != null && !token.equals(jjtGetLastToken())) {\r
+            prevToken = token;\r
+            token = token.next;\r
+            if(!token.image.equals("[") \r
+                    && !token.image.equals("]")\r
+                    && !prevToken.image.equals("[")\r
+                    && !prevToken.image.equals("]")\r
+                    && !token.image.equals(".")\r
+                    && !prevToken.image.equals("."))\r
+                sb.append(" ");\r
+            sb.append(token.image);\r
+        }\r
+        return sb.toString();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ForIndex.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ForIndex.java
new file mode 100644 (file)
index 0000000..40889a1
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ForIndex extends UnitCheckingNode {\r
+\r
+    public ForIndex(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        return new UnitResult(allowEquivalents);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/FunctionArguments.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/FunctionArguments.java
new file mode 100644 (file)
index 0000000..3921d3c
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class FunctionArguments extends UnitCheckingNode {\r
+\r
+    public FunctionArguments(int id) {\r
+        super(id);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/FunctionCall.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/FunctionCall.java
new file mode 100644 (file)
index 0000000..0832b0d
--- /dev/null
@@ -0,0 +1,204 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+import org.simantics.sysdyn.utils.Function.Input;\r
+import org.simantics.sysdyn.utils.Function.Output;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class FunctionCall extends UnitCheckingNode {\r
+\r
+    public FunctionCall(int id) {\r
+        super(id);\r
+    }\r
+\r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitCheckingNode functionLabelNode = ((UnitCheckingNode)jjtGetChild(0));\r
+        String functionLabel = functionLabelNode.printNode();\r
+        \r
+        UnitCheckingNode functionArgumentsWithParenthesisNode = ((UnitCheckingNode)jjtGetChild(1));\r
+        UnitCheckingNode functionArgumentsNode = ((UnitCheckingNode)functionArgumentsWithParenthesisNode.jjtGetChild(1));\r
+        \r
+        UnitCheckingException u = null;\r
+        \r
+        for (Function f : functions) {\r
+               if (f.getName().equals(functionLabel)) {\r
+                       // Get the expected inputs\r
+                       ArrayList<Input> inputs = f.getInputList();\r
+                       // Get arguments from parser.\r
+                       ArrayList<Pair<UnitResult, String>> argumentUnits = getArgumentsOf(functionArgumentsNode, units, functions, allowEquivalents);\r
+                       // Get correspondent actual units for unit templates in inputs.\r
+                       HashMap<String, String> correspondences = getReplacementUnitCorrespondences(inputs, argumentUnits);\r
+\r
+                       try {\r
+                               // If the function input parameter units are OK, set the output unit accordingly.  \r
+                               if (f.areArgumentUnitsValid(argumentUnits, correspondences, functions, allowEquivalents, units)) {\r
+                                       Output o = f.getOutputList().get(0); // Support only single return value functions.\r
+                                       return o.getUnitResult(units, f, functions, allowEquivalents, correspondences);\r
+                               }\r
+                               \r
+                               // Create the exception when we first time arrive here, since the functions\r
+                               // are sorted so that scalar functions are before vector ones and there are\r
+                               // a few duplicates, so this way the exception message is more likely useful.\r
+                               if (u == null)\r
+                                       u = getException(functionLabelNode, inputs, argumentUnits);\r
+                               // There may be similarly named functions, so if one doesn't succeed, go through the rest of the list anyway.\r
+                       } catch (UnitCheckingException e) {\r
+                               u = e; // Override the general exception with a more specific one.\r
+                       }\r
+               }\r
+        }\r
+        \r
+        if (u == null) {\r
+               UnitResult result = new UnitResult(allowEquivalents);\r
+            result.setUnitType(UnitType.ANY); // The function was not found.\r
+               return result;\r
+        }\r
+        \r
+        throw u;\r
+    }\r
+\r
+       private static HashMap<String, String> getReplacementUnitCorrespondences(\r
+                       ArrayList<Input> inputs, ArrayList<Pair<UnitResult, String>> argumentUnits) {\r
+               // TODO: General case. Currently each 'p, 'q etc. must exist as an atomic unit.\r
+               HashMap<String, String> correspondences = new HashMap<String, String>();\r
+               for (int i = 0; i < argumentUnits.size(); ++i) {\r
+                       if (argumentUnits.get(i).second != null) { // named arguments\r
+                               for (Input input : inputs) {\r
+                                       if (input.name.equals(argumentUnits.get(i).second)) {\r
+                                               addPossibleCorrespondence(correspondences, input, argumentUnits.get(i).first);\r
+                                       }\r
+                               }\r
+                       } else if (inputs.size() > i) {\r
+                               addPossibleCorrespondence(correspondences, inputs.get(i), argumentUnits.get(i).first);\r
+                       }\r
+               }\r
+               // If there is no mapping between the actual and defined inputs (e.g. 'p refers to both m and s),\r
+               // then return the latest correspondence. The users of this functions currently assume such behavior.\r
+               return correspondences;\r
+       }\r
+\r
+       private static void addPossibleCorrespondence(HashMap<String, String> correspondences,\r
+                       Input input, UnitResult argumentUnit) {\r
+               if (correspondences.containsKey(input.unit)\r
+                               && argumentUnit.getUnitType() == UnitType.SCALAR) {\r
+                       // Don't overwrite if the correspondence already exists and the new argument is scalar. \r
+                       return;\r
+               }\r
+               if (input.unit.matches("'[a-zA-Z]")) {\r
+                       String fullUnit = argumentUnit.getCleanFullUnit();\r
+                       if ("".equals(fullUnit))\r
+                               fullUnit = "1";\r
+                       correspondences.put(input.unit, fullUnit);\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Get the exception (text) shown to user.\r
+        * @param functionLabelNode\r
+        * @param inputs\r
+        * @param argumentUnits\r
+        * @return\r
+        */\r
+       private static UnitCheckingException getException(UnitCheckingNode functionLabelNode, \r
+                       ArrayList<Input> inputs, \r
+                       ArrayList<Pair<UnitResult, String>> argumentUnits) {\r
+       String exception = new String("Function arguments do not have correct units. Expected " + functionLabelNode.printNode() + "(");\r
+               \r
+       for (int i = 0; i < inputs.size(); ++i) {\r
+                       Input input = inputs.get(i);\r
+                       if (i == 0)\r
+                               exception += " ";\r
+                       exception += "[" + input.unit + "]";\r
+                       if (input.variableLength) {\r
+                               exception += "... ";\r
+                       }\r
+                       \r
+                       if (i != inputs.size() - 1)\r
+                               exception += ", ";\r
+               }\r
+               exception += " ), got " + functionLabelNode.printNode() + "(";\r
+               for (int i = 0; i < argumentUnits.size(); ++i) {\r
+                       UnitResult argumentUnit = argumentUnits.get(i).first;\r
+                       if (i == 0)\r
+                               exception += " ";\r
+                       exception += "[" + argumentUnit.getCleanFullUnit() + "]";\r
+                       \r
+                       if (i != argumentUnits.size() - 1)\r
+                               exception += ", ";\r
+                       \r
+               }\r
+               exception += " ).";\r
+               \r
+               return new UnitCheckingException(exception);\r
+       }\r
+\r
+    private static ArrayList<Pair<UnitResult, String>> getArgumentsOf(\r
+                       UnitCheckingNode functionArgumentsNode, \r
+                       HashMap<String, String> units, \r
+                       ArrayList<Function> functions, \r
+                       boolean allowEquivalents) throws UnitCheckingException {\r
+       // Arguments are defined recursively in OpenModelica\r
+               ArrayList<Pair<UnitResult, String>> argumentUnits = new ArrayList<Pair<UnitResult, String>>();\r
+               if (functionArgumentsNode instanceof FunctionArguments) {\r
+               UnitCheckingNode firstArg = ((UnitCheckingNode) functionArgumentsNode.jjtGetChild(0));\r
+               if (firstArg instanceof NamedArguments) {\r
+                       // Found all position arguments, continue with named arguments\r
+                       argumentUnits.addAll(getNamedArgumentsOf(firstArg, units, functions, allowEquivalents));\r
+               } else {\r
+                       argumentUnits.add(new Pair<UnitResult, String>(firstArg.getUnits(units, functions, allowEquivalents), null));\r
+                       if (functionArgumentsNode.jjtGetNumChildren() > 1) {\r
+                               // Continue to the next argument (within the following function_arguments)\r
+                               UnitCheckingNode next = ((UnitCheckingNode) functionArgumentsNode.jjtGetChild(1));\r
+                               argumentUnits.addAll(getArgumentsOf(next, units, functions, allowEquivalents));\r
+                       }\r
+               }\r
+               }\r
+               return argumentUnits;\r
+       }\r
+\r
+       private static ArrayList<Pair<UnitResult, String>> getNamedArgumentsOf(\r
+                       UnitCheckingNode namedArgumentsNode, \r
+                       HashMap<String, String> units, \r
+                       ArrayList<Function> functions, \r
+                       boolean allowEquivalents) throws UnitCheckingException {\r
+               // Named arguments are defined recursively in OpenModelica\r
+               ArrayList<Pair<UnitResult, String>> argumentUnits = new ArrayList<Pair<UnitResult, String>>();\r
+               if (namedArgumentsNode instanceof NamedArguments) {\r
+               UnitCheckingNode firstArg = ((UnitCheckingNode) namedArgumentsNode.jjtGetChild(0));\r
+               String argumentName = firstArg.jjtGetFirstToken().image;\r
+               argumentUnits.add(new Pair<UnitResult, String>(firstArg.getUnits(units, functions, allowEquivalents), argumentName));\r
+               if (namedArgumentsNode.jjtGetNumChildren() > 1) {\r
+                       // Continue to the next argument (within the following function_arguments)\r
+                       UnitCheckingNode next = ((UnitCheckingNode) namedArgumentsNode.jjtGetChild(1));\r
+                       argumentUnits.addAll(getNamedArgumentsOf(next, units, functions, allowEquivalents));\r
+               }\r
+               }\r
+               return argumentUnits;\r
+       }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/IfThenElse.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/IfThenElse.java
new file mode 100644 (file)
index 0000000..05c36d9
--- /dev/null
@@ -0,0 +1,69 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class IfThenElse extends UnitCheckingNode {\r
+\r
+    public IfThenElse(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult base = null;\r
+        UnitCheckingNode baseNode = null;\r
+        UnitCheckingNode candidateNode = null;\r
+        \r
+        for(int i = 0; i < jjtGetNumChildren(); i++) {\r
+            candidateNode = ((UnitCheckingNode)jjtGetChild(i));\r
+            UnitResult candidateUnits = candidateNode.getUnits(units, functions, allowEquivalents);\r
+            \r
+            if(!(candidateNode instanceof Condition)) {\r
+                \r
+                if(base == null) {\r
+                    base = candidateUnits;\r
+                    baseNode = candidateNode;\r
+                } else {\r
+                    if(!base.equals(candidateUnits)) {\r
+                        base.equals(candidateUnits);\r
+                        throw new UnitCheckingException("Conditional results do not have same units: " +\r
+                        printNode() + " -> " + \r
+                                baseNode.printNode() + " [" + base.getFullUnit() + "] <-> " +\r
+                                candidateNode.printNode() + " [" + candidateUnits.getFullUnit() + "]"\r
+                                );\r
+                    }\r
+                }\r
+            }\r
+\r
+\r
+        }\r
+        \r
+        return base;\r
+    }\r
+\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Multiplication.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Multiplication.java
new file mode 100644 (file)
index 0000000..57f28f7
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Multiplication extends UnitCheckingNode {\r
+\r
+    public Multiplication(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = super.getUnits(units, functions, allowEquivalents);\r
+        result.setUnitType(UnitType.OPERATOR);\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/NamedArguments.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/NamedArguments.java
new file mode 100644 (file)
index 0000000..7afcf98
--- /dev/null
@@ -0,0 +1,27 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class NamedArguments extends UnitCheckingNode {\r
+\r
+    public NamedArguments(int id) {\r
+        super(id);\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ParenthesisExpression.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/ParenthesisExpression.java
new file mode 100644 (file)
index 0000000..93d2872
--- /dev/null
@@ -0,0 +1,39 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class ParenthesisExpression extends UnitCheckingNode {\r
+\r
+    public ParenthesisExpression(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException{\r
+        UnitResult result = new UnitResult(allowEquivalents);\r
+        // Get the Expression between the parenthesis.\r
+        result.appendResult(((UnitCheckingNode)jjtGetChild(1)).getUnits(units, functions, allowEquivalents));\r
+        return result; \r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Power.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Power.java
new file mode 100644 (file)
index 0000000..8d90de3
--- /dev/null
@@ -0,0 +1,40 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Power extends UnitCheckingNode {\r
+\r
+    public Power(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = super.getUnits(units, functions, allowEquivalents);\r
+        result.setUnitType(UnitType.OPERATOR);\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/RelOp.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/RelOp.java
new file mode 100644 (file)
index 0000000..56b4138
--- /dev/null
@@ -0,0 +1,42 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class RelOp extends UnitCheckingNode {\r
+\r
+    public RelOp(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = super.getUnits(units, functions, allowEquivalents);\r
+        result.setUnitType(UnitType.OPERATOR);\r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Relation.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Relation.java
new file mode 100644 (file)
index 0000000..5831092
--- /dev/null
@@ -0,0 +1,70 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Relation extends UnitCheckingNode {\r
+\r
+    public Relation(int id) {\r
+        super(id);\r
+    }\r
+\r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = new UnitResult(allowEquivalents);\r
+        \r
+        UnitCheckingNode base = null;\r
+        UnitCheckingNode operator = null;\r
+        UnitCheckingNode candidateNode = null;\r
+        \r
+        base = ((UnitCheckingNode)jjtGetChild(0));\r
+        if(!(base instanceof Arithmetic) && jjtGetNumChildren() > 1)\r
+            base = ((UnitCheckingNode)jjtGetChild(1));\r
+            \r
+        if(base instanceof Arithmetic) {\r
+            result.appendResult(base.getUnits(units, functions, allowEquivalents));\r
+\r
+            for(int i = 2; i < jjtGetNumChildren(); i = i + 2) {\r
+                candidateNode = ((UnitCheckingNode)jjtGetChild(i));\r
+\r
+                if(!(candidateNode instanceof Value)) {\r
+                    operator = ((UnitCheckingNode)jjtGetChild(i-1));\r
+                    UnitResult candidateUnits = candidateNode.getUnits(units, functions, allowEquivalents);\r
+                    if(!result.equals(candidateUnits)) {\r
+                        result.equals(candidateUnits);\r
+                        throw new UnitCheckingException("Not equals exception: " +\r
+                                base.printNode() + " [" + result.getFullUnit() + "] " + operator.printNode() + " " +\r
+                                candidateNode.printNode() + " [" + candidateUnits.getFullUnit() + "]"\r
+                                );\r
+                    }\r
+                }\r
+\r
+            }\r
+        }\r
+        \r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Term.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Term.java
new file mode 100644 (file)
index 0000000..baa4a1c
--- /dev/null
@@ -0,0 +1,107 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.Token;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Term extends UnitCheckingNode {\r
+\r
+    public Term(int id) {\r
+        super(id);\r
+    }\r
+    \r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = new UnitResult(allowEquivalents);\r
+        \r
+        UnitCheckingNode current = null;\r
+        UnitCheckingNode operator = null;\r
+        UnitCheckingNode base = null;\r
+        \r
+        for(int i = 0; i < jjtGetNumChildren(); i++) {\r
+            current = ((UnitCheckingNode)jjtGetChild(i));\r
+            UnitResult currentUnits = current.getUnits(units, functions, allowEquivalents);\r
+\r
+            if(currentUnits.getUnitType() == UnitType.ANY) {\r
+                result = new UnitResult(allowEquivalents);\r
+                result.setUnitType(UnitType.ANY);\r
+                return result;\r
+            } else if(currentUnits.getUnitType() == UnitType.OPERATOR) {\r
+                continue;\r
+            } else if(base == null) {\r
+                base = current;\r
+                result.appendResult(currentUnits);\r
+                continue;\r
+            } else {\r
+                operator = ((UnitCheckingNode)jjtGetChild(i-1));\r
+\r
+                if(operator instanceof Multiplication) {\r
+                    UnitType unitType = currentUnits.getUnitType();\r
+                    if(unitType != UnitType.SCALAR && unitType != UnitType.DMNL) {\r
+                        result.append(operator.printNode());\r
+                        result.appendResult(currentUnits);\r
+                    }\r
+                } else if(operator instanceof Divide) {\r
+                    result.append(operator.printNode());\r
+                    result.addAllDividents(currentUnits.getDividers());\r
+                    result.addAllDividers(currentUnits.getDividents());\r
+                    UnitType unitType = currentUnits.getUnitType();\r
+                    if(unitType == UnitType.SCALAR || unitType == UnitType.DMNL) {\r
+                        result.append("1");\r
+                    } else {\r
+                        result.append(currentUnits.getFullUnit());\r
+                        result.setUnitType(unitType);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+//        System.out.println("Term: " + printNode() + " [" + result.getFullUnit() + " : " + result.getUnitType() + "]");\r
+        return result;\r
+    }\r
+    \r
+    @Override\r
+    public String printNode() {\r
+        StringBuilder sb = new StringBuilder();\r
+        Token token = jjtGetFirstToken();\r
+        sb.append(token.image);\r
+\r
+        Token prevToken = null;\r
+        while(token != null && !token.equals(jjtGetLastToken())) {\r
+            prevToken = token;\r
+            token = token.next;\r
+            if(!token.image.equals("[") \r
+                    && !token.image.equals("]")\r
+                    && !prevToken.image.equals("[")\r
+                    && !prevToken.image.equals("]")\r
+                    && !token.image.equals(".")\r
+                    && !prevToken.image.equals("."))\r
+                sb.append(" ");\r
+            sb.append(token.image);\r
+        }\r
+        return sb.toString();\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/UnitResult.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/UnitResult.java
new file mode 100644 (file)
index 0000000..c5920af
--- /dev/null
@@ -0,0 +1,289 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ ********************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.Iterator;\r
+\r
+/**\r
+ * Result of getUnits() request for Unit Parser nodes. \r
+ * \r
+ * Result is built of dividers and dividents. ( divident / divider )\r
+ * \r
+ * UnitType may provide information for handling this unit result\r
+ * \r
+ * fullUnit is the print of this unit in the order it is created.\r
+ * \r
+ * getCleanFullUnit reduces all unnecessary units and provides the most\r
+ * clean representation of the unit. ( e.g. m * s / m  -> s )\r
+ * \r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class UnitResult {\r
+    \r
+    public enum UnitType {NORMAL, ANY, DMNL, OPERATOR, SCALAR};\r
+    \r
+    private ArrayList<String> dividers = new ArrayList<String>();\r
+    private ArrayList<String> dividents = new ArrayList<String>();\r
+    private StringBuilder fullUnit = new StringBuilder();\r
+    private UnitType unitType;\r
+    \r
+    // Equivalent forms of units:\r
+    private final Equivalent[] EQUIVALENTS = {\r
+               new Equivalent("$","$s","dollar","dollars","usd"),\r
+               new Equivalent("\u20ac","\u20acs","eur","euro","euros","e","ecu"),\r
+               new Equivalent("£","£s","pound","pounds","gbp"),\r
+               new Equivalent("unit","units"),\r
+               new Equivalent("person","people","persons"),\r
+               new Equivalent("second","seconds","sec","s"),\r
+               new Equivalent("minute","minutes","min"),\r
+               new Equivalent("hour","hours","h","hr"),\r
+               new Equivalent("day","days","d"),\r
+               new Equivalent("month","months","mon","mth","mo","mos"),\r
+               new Equivalent("year","years","a","y","yr")\r
+               };\r
+       private boolean allowEquivalents;\r
+    \r
+    private class Equivalent {\r
+       public ArrayList<String> forms;\r
+       \r
+       Equivalent(String ... forms) {\r
+               this.forms = new ArrayList<String>();\r
+               for (String f : forms)\r
+                       this.forms.add(f);\r
+       }\r
+       \r
+       public boolean contains(String form) {\r
+               for (String f : forms)\r
+                       if (f.equalsIgnoreCase(form))\r
+                               return true;\r
+               return false;\r
+       }\r
+       \r
+       public String getDefault() {\r
+               if (forms.size() > 0)\r
+                       return forms.get(0);\r
+               else return null;\r
+       }\r
+    }\r
+    \r
+    public UnitResult(boolean allowEquivalents) {\r
+       this.allowEquivalents = allowEquivalents;\r
+        setUnitType(UnitType.NORMAL);\r
+    }\r
+    \r
+    public void appendResult(UnitResult result) {\r
+        addAllDividents(result.getDividents());\r
+        addAllDividers(result.getDividers());\r
+        append(result.getFullUnit());\r
+        setUnitType(result.getUnitType());\r
+    }\r
+    \r
+    public void addDivider(String divider) {\r
+        this.dividers.add(divider);\r
+        Collections.sort(this.dividers);\r
+    }\r
+    \r
+    public void addAllDividers(ArrayList<String> dividers) {\r
+        this.dividers.addAll(dividers);\r
+        Collections.sort(this.dividers);\r
+    }\r
+    \r
+    public void addDivident(String divident) {\r
+        this.dividents.add(divident);\r
+        Collections.sort(this.dividents);\r
+    }\r
+    \r
+    public void addAllDividents(ArrayList<String> dividents) {\r
+        this.dividents.addAll(dividents);\r
+        Collections.sort(this.dividents);\r
+    }\r
+    \r
+    public void append(String text) {\r
+        this.fullUnit.append(text);\r
+    }\r
+    \r
+    public ArrayList<String> getDividers() {\r
+        return this.dividers;\r
+    }\r
+    \r
+    public ArrayList<String> getDividents() {\r
+        return this.dividents;\r
+    }\r
+    \r
+    public String getFullUnit() {\r
+        return fullUnit.toString();\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Get clean representation of this unit. All redundant \r
+     * units are cleanend out and the unit is represented\r
+     * with max one '/' character.\r
+     * @return\r
+     */\r
+    public String getCleanFullUnit() {\r
+        if(dividers.size() == 0 && dividents.size() == 0)\r
+            return "";\r
+        \r
+        if(dividers.size() > 0 && dividents.size() == 0)\r
+            dividents.add("1");\r
+        \r
+        ArrayList<String> copyDividers1 = new ArrayList<String>(dividers);\r
+        ArrayList<String> copyDividents1 = new ArrayList<String>(dividents);\r
+        reduceUnitLists(dividents, copyDividents1, copyDividers1, allowEquivalents);\r
+        \r
+        StringBuilder sb = new StringBuilder();\r
+        Iterator<String> iterator = copyDividents1.iterator();\r
+        while(iterator.hasNext()) {\r
+            String s = iterator.next();\r
+            sb.append(s);\r
+            if(iterator.hasNext())\r
+                sb.append("*");\r
+        }\r
+        \r
+        if(copyDividers1.size() > 0) {\r
+            sb.append("/");\r
+            if(copyDividers1.size() > 1)\r
+                sb.append("(");\r
+            \r
+            iterator = copyDividers1.iterator();\r
+            while(iterator.hasNext()) {\r
+                String s = iterator.next();\r
+                sb.append(s);\r
+                if(iterator.hasNext())\r
+                    sb.append("*");\r
+            }\r
+            \r
+            if(copyDividers1.size() > 1)\r
+                sb.append(")");\r
+        }\r
+        \r
+        return sb.toString();\r
+    }\r
+    \r
+    @Override\r
+    public boolean equals(Object obj) {\r
+        if(!(obj instanceof UnitResult))\r
+            return false;\r
+        \r
+        UnitResult other = (UnitResult)obj;\r
+        \r
+        if(getUnitType() == UnitType.ANY || other.getUnitType() == UnitType.ANY)\r
+            return true;\r
+        \r
+        if(getUnitType() != other.getUnitType())\r
+            return true;\r
+        \r
+        ArrayList<String> copyDividers1 = new ArrayList<String>(dividers);\r
+        ArrayList<String> copyDividents1 = new ArrayList<String>(dividents);\r
+        reduceUnitLists(dividents, copyDividents1, copyDividers1, allowEquivalents);\r
+\r
+        ArrayList<String> copyDividers2 = new ArrayList<String>(other.dividers);\r
+        ArrayList<String> copyDividents2 = new ArrayList<String>(other.dividents);    \r
+        reduceUnitLists(other.dividents, copyDividents2, copyDividers2, allowEquivalents);\r
+\r
+        if(copyDividents1.size() != copyDividents2.size())\r
+            return false;\r
+        if(copyDividers1.size() != copyDividers2.size())\r
+            return false;\r
+        \r
+        if (allowEquivalents) {\r
+                   // Replace and sort all once again.\r
+                   for(int i = 0; i < copyDividents1.size(); i++) {\r
+                       copyDividents1.set(i, getDefaultForm(copyDividents1.get(i)));\r
+                       copyDividents2.set(i, getDefaultForm(copyDividents2.get(i)));\r
+                       Collections.sort(copyDividents1);\r
+                       Collections.sort(copyDividents2);\r
+                   }\r
+                   for(int i = 0; i < copyDividers1.size(); i++) {\r
+                       copyDividers1.set(i, getDefaultForm(copyDividers1.get(i)));\r
+                       copyDividers2.set(i, getDefaultForm(copyDividers2.get(i)));\r
+                       Collections.sort(copyDividers1);\r
+                       Collections.sort(copyDividers2);\r
+                   }\r
+        }\r
+        \r
+        for(int i = 0; i < copyDividents1.size(); i++) {\r
+            String a = copyDividents1.get(i);\r
+            String b = copyDividents2.get(i);\r
+            if(!a.equals(b)) {\r
+                return false;\r
+            }\r
+        }\r
+        for(int i = 0; i < copyDividers1.size(); i++) {\r
+            String a = copyDividers1.get(i);\r
+            String b = copyDividers2.get(i);\r
+            if(!a.equals(b)) {\r
+                return false;\r
+            }\r
+        }\r
+        \r
+        return true;\r
+    }\r
+    \r
+    /**\r
+     * Get the default form of a unit (e.g. dollars -> $).\r
+     * @param unit\r
+     * @return default form of unit\r
+     */\r
+    private String getDefaultForm(String unit) {\r
+       for (Equivalent e : EQUIVALENTS)\r
+               if (e.contains(unit))\r
+                       return e.getDefault();\r
+       return unit;\r
+       }\r
+\r
+       public void reduceUnitLists(\r
+                       ArrayList<String> originalDividents, \r
+                       ArrayList<String> copyDividents,\r
+                       ArrayList<String> copyDividers,\r
+                       boolean allowEquivalents) {\r
+               if (allowEquivalents) {\r
+                   // Replace equivalents\r
+                   for(int i = 0; i < originalDividents.size(); i++) {\r
+                       copyDividents.set(i, getDefaultForm(copyDividents.get(i)));\r
+                   }\r
+                   for(int i = 0; i < copyDividers.size(); i++) {\r
+                       copyDividers.set(i, getDefaultForm(copyDividers.get(i)));\r
+                   }\r
+        }\r
+               \r
+        for(String s : originalDividents) {\r
+               String equiv = allowEquivalents ? getDefaultForm(s) : s;\r
+            if(copyDividers.contains(equiv)) {\r
+                copyDividers.remove(equiv);\r
+                copyDividents.remove(equiv);\r
+            }\r
+        }\r
+        \r
+        if(copyDividents.isEmpty())\r
+            copyDividents.add("1");\r
+    }\r
+\r
+    public UnitType getUnitType() {\r
+        return unitType;\r
+    }\r
+\r
+    public void setUnitType(UnitType unitType) {\r
+        this.unitType = unitType;\r
+    }\r
+    \r
+    @Override\r
+    public String toString() {\r
+        return getCleanFullUnit();\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Value.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/unitParser/nodes/Value.java
new file mode 100644 (file)
index 0000000..e0edb44
--- /dev/null
@@ -0,0 +1,41 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *     VTT Technical Research Centre of Finland\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.unitParser.nodes;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.sysdyn.utils.Function;\r
+\r
+/**\r
+ * See UnitCheckingNodeFactory for mapping\r
+ * @author Teemu Lempinen\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Value extends UnitCheckingNode {\r
+\r
+    public Value(int id) {\r
+        super(id);\r
+    }\r
+\r
+    @Override\r
+    public UnitResult getUnits(HashMap<String, String> units, ArrayList<Function> functions, boolean allowEquivalents) throws UnitCheckingException {\r
+        UnitResult result = super.getUnits(units, functions, allowEquivalents);\r
+        result.setUnitType(UnitType.SCALAR);\r
+        return result;\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/DocumentationUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/DocumentationUtils.java
new file mode 100644 (file)
index 0000000..28ec9bf
--- /dev/null
@@ -0,0 +1,620 @@
+package org.simantics.sysdyn.utils;\r
+\r
+import java.text.DateFormat;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.Comparator;\r
+import java.util.Date;\r
+import java.util.List;\r
+import java.util.concurrent.TimeUnit;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
+\r
+import org.eclipse.core.runtime.NullProgressMonitor;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.util.Base64;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithSupertype;\r
+import org.simantics.db.common.request.UniqueRead;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.exception.MissingVariableException;\r
+import org.simantics.db.layer0.util.EvaluatingListener;\r
+import org.simantics.db.layer0.util.EvaluatingListener.Criterion;\r
+import org.simantics.db.layer0.util.EvaluatingListener.Evaluation;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.scl.runtime.function.FunctionImpl1;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.adapter.ValueIndexVariable;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.Book;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.IndependentVariable;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.Shadow;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Variability;\r
+import org.simantics.sysdyn.representation.Variable;\r
+import org.simantics.sysdyn.utils.imports.ImportUtils;\r
+import org.simantics.utils.DataContainer;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+public class DocumentationUtils {\r
+    \r
+    public static List<Resource> getModules(ReadGraph graph, org.simantics.db.layer0.variable.Variable model) throws DatabaseException {\r
+        if(model == null)\r
+            return Collections.emptyList();\r
+        \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        Resource modelResource = model.getRepresents(graph);\r
+        \r
+        ArrayList<Resource> result = new ArrayList<Resource>();\r
+        \r
+        if(graph.isInstanceOf(modelResource, SR.SysdynModel)) {\r
+            result.add(modelResource);\r
+            result.addAll(graph.syncRequest(new ObjectsWithSupertype(modelResource, Layer0.getInstance(graph).ConsistsOf, SR.Module)));        \r
+        }\r
+        \r
+        return result;\r
+    }\r
+    \r
+    public static List<org.simantics.db.layer0.variable.Variable> getExperimentVariables(ReadGraph graph, org.simantics.db.layer0.variable.Variable model) throws DatabaseException {\r
+        if(model == null)\r
+            return Collections.emptyList();\r
+        \r
+        ModelingResources MR = ModelingResources.getInstance(graph);\r
+        if (model == null || !graph.isInstanceOf(model.getRepresents(graph), MR.StructuralModel)) {\r
+            return Collections.emptyList();\r
+        }\r
+\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        ArrayList<org.simantics.db.layer0.variable.Variable> result = new ArrayList<org.simantics.db.layer0.variable.Variable>();\r
+        for (Resource config : graph.getObjects(model.getRepresents(graph), L0.ConsistsOf)) {\r
+            if (graph.isInstanceOf(config, SIMU.Experiment)) {\r
+                for (Resource run : graph.getObjects(config, L0.ConsistsOf)) {\r
+                    if (graph.isInstanceOf(run, SIMU.Run)) {\r
+                        if (graph.hasStatement(run, SIMU.IsActive)) {\r
+                            org.simantics.db.layer0.variable.Variable runVar = Variables.getPossibleVariable(graph, run);\r
+                            if(runVar != null)\r
+                                result.add(runVar);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        \r
+        return result;\r
+    }\r
+    \r
+    public static List<org.simantics.db.layer0.variable.Variable> getRoleVariables(ReadGraph graph, org.simantics.db.layer0.variable.Variable experiment) throws DatabaseException {\r
+        if(experiment == null)\r
+            return Collections.emptyList();\r
+        \r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        \r
+        if(graph.isInstanceOf(experiment.getRepresents(graph), SIMU.Run))\r
+            experiment = experiment.getParent(graph);\r
+\r
+        if(!graph.isInstanceOf(experiment.getRepresents(graph), SIMU.Experiment))\r
+            return Collections.emptyList();\r
+\r
+        Resource roleType = graph.getPossibleResource("http://www.semantum.fi/Simupedia-1.0/Role");\r
+        if(roleType == null)\r
+            return Collections.emptyList();\r
+        \r
+        ArrayList<org.simantics.db.layer0.variable.Variable> result = new ArrayList<org.simantics.db.layer0.variable.Variable>();\r
+        for(org.simantics.db.layer0.variable.Variable part : experiment.getChildren(graph)) {\r
+            if(graph.isInstanceOf(part.getRepresents(graph), roleType)) {\r
+                result.add(part);\r
+            }\r
+        }\r
+\r
+        return result;\r
+    }\r
+    \r
+    public static List<org.simantics.db.layer0.variable.Variable> getDocumentVariables(ReadGraph graph, org.simantics.db.layer0.variable.Variable model) throws DatabaseException {\r
+        if(model == null)\r
+            return Collections.emptyList();\r
+        \r
+        Resource documentType = graph.getPossibleResource("http://www.simantics.org/Documentation-1.2/Document");\r
+        if(documentType == null)\r
+            return Collections.emptyList();\r
+        \r
+        ArrayList<org.simantics.db.layer0.variable.Variable> result = new ArrayList<org.simantics.db.layer0.variable.Variable>();\r
+        for(org.simantics.db.layer0.variable.Variable part : model.getChildren(graph)) {\r
+            if(graph.isInstanceOf(part.getRepresents(graph), documentType)) {\r
+                result.add(part);\r
+            }\r
+        }\r
+\r
+        return result;\r
+    }\r
+    \r
+    public static List<org.simantics.db.layer0.variable.Variable> getResultVariables(ReadGraph graph, org.simantics.db.layer0.variable.Variable model) throws DatabaseException {\r
+        if(model == null)\r
+            return Collections.emptyList();\r
+        \r
+        org.simantics.db.layer0.variable.Variable library = model.getPossibleChild(graph, "PDFLibrary");\r
+        if(library == null)\r
+            return Collections.emptyList();\r
+        \r
+        \r
+        return new ArrayList<org.simantics.db.layer0.variable.Variable>(library.getChildren(graph));\r
+    }\r
+    \r
+    public static List<org.simantics.db.layer0.variable.Variable> getIndexDocuments(ReadGraph graph, org.simantics.db.layer0.variable.Variable project) throws DatabaseException {\r
+        Resource indexRelation = graph.getPossibleResource("http://www.semantum.fi/Simupedia-1.0/indexDocument");\r
+\r
+        if(indexRelation == null)\r
+            return Collections.emptyList();\r
+        \r
+        ArrayList<org.simantics.db.layer0.variable.Variable> result = new ArrayList<org.simantics.db.layer0.variable.Variable>();\r
+        for(org.simantics.db.layer0.variable.Variable model : project.getChildren(graph)) {\r
+            Resource modelResource = model.getRepresents(graph);\r
+            if(modelResource == null)\r
+                continue;\r
+            \r
+            Resource indexDocumentResource = graph.getPossibleObject(modelResource, indexRelation);\r
+            if(indexDocumentResource != null) {\r
+                org.simantics.db.layer0.variable.Variable indexDoc = Variables.getVariable(graph, indexDocumentResource);\r
+                result.add(indexDoc);\r
+            } \r
+        }\r
+        return result;\r
+    }\r
+    \r
+    public static Resource getConfiguration(ReadGraph graph, Resource module) throws DatabaseException {\r
+        if(module == null)\r
+            return null;\r
+        \r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        \r
+        if(graph.isInstanceOf(module, SR.SysdynModel)) {\r
+            return graph.getSingleObject(module, SimulationResource.getInstance(graph).HasConfiguration);\r
+        } else if(graph.isInheritedFrom(module, SR.Module)) {\r
+            return graph.getSingleObject(module, StructuralResource2.getInstance(graph).IsDefinedBy);\r
+        } else {\r
+            return null;\r
+        }\r
+    }\r
+    \r
+    public static List<Resource> getConfigurationVariables(ReadGraph graph, Resource configuration) throws DatabaseException {\r
+        if(configuration == null)\r
+            return Collections.emptyList();\r
+        \r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        SysdynModel sm = smm.getModel(graph, configuration);\r
+        \r
+        ArrayList<IElement> elements = new ArrayList<IElement>();\r
+\r
+        for(IElement element : sm.getConfiguration().getElements()) {\r
+            if((element instanceof Variable || element instanceof Module) && !(element instanceof Book) && !(element instanceof Shadow)) {\r
+                elements.add(element);\r
+            }\r
+        }\r
+        \r
+        Collections.sort(elements, new Comparator<IElement>() {\r
+\r
+            @Override\r
+            public int compare(IElement o1, IElement o2) {\r
+                if(!isApplied(o1) || !isApplied(o2))\r
+                    return 0;\r
+                else {\r
+                    String name1 = getName(o1);\r
+                    String name2 = getName(o2);\r
+                    return name1.compareTo(name2);\r
+                }\r
+            }\r
+            \r
+            private boolean isApplied(IElement element) {\r
+                if((element instanceof Variable || element instanceof Module) && !(element instanceof Book)) {\r
+                    return true;\r
+                } else {\r
+                    return false;\r
+                }\r
+\r
+            }\r
+            \r
+            private String getName(IElement element) {\r
+                if(element instanceof Variable)\r
+                    return ((Variable)element).getName();\r
+                else if(element instanceof Module)\r
+                    return ((Module)element).getName();\r
+                else\r
+                    return "";\r
+            }\r
+            \r
+        });\r
+        \r
+        ArrayList<Resource> result = new ArrayList<Resource>();\r
+        for(IElement e : elements)\r
+            result.add(sm.getMapping().inverseGet(e));\r
+        \r
+        return result;\r
+    }\r
+    \r
+    public static String getName(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        if(variable == null)\r
+            return null;\r
+        \r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        Resource configuration = graph.syncRequest(new GetConfigurationRequest(variable));\r
+        SysdynModel sm = smm.getModel(graph,configuration);\r
+        \r
+        IElement element = sm.getElement(variable);\r
+        \r
+        if(element instanceof Variable) {\r
+            Variable v = (Variable) element;\r
+            \r
+            StringBuilder sb = new StringBuilder();\r
+            sb.append(v.getModelicaName());\r
+            \r
+            \r
+            if(v.getArrayIndexes() != null && v.getArrayIndexes().size() > 0) {\r
+                sb.append("[");\r
+                boolean first = true;\r
+                for(Enumeration e : v.getArrayIndexes()) {\r
+                   if(!first)\r
+                       sb.append(", ");\r
+                   first = false;\r
+                   sb.append(e.getModelicaName());\r
+                }\r
+                \r
+                sb.append("]");\r
+            }\r
+            \r
+            return sb.toString();\r
+        } \r
+        \r
+        if(element instanceof Module) {\r
+            Module m = (Module) element;\r
+            return m.getName();\r
+        }\r
+        \r
+        return "";\r
+    }\r
+    \r
+    public static String getType(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        if(variable == null)\r
+            return null;\r
+        \r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        Resource configuration = graph.syncRequest(new GetConfigurationRequest(variable));\r
+        SysdynModel sm = smm.getModel(graph,configuration);\r
+        \r
+        IElement element = sm.getElement(variable);\r
+        \r
+        if(element instanceof Variable) {\r
+            String result = ((Variable)element).getType();\r
+            if(result == null)\r
+                return "";\r
+            else\r
+                return element.getClass().getSimpleName() + " " + result;\r
+        }\r
+        \r
+        if(element instanceof Module) {\r
+            Module m = (Module) element;\r
+            return"Module " + m.getType().getName();\r
+        }\r
+        \r
+        return "";\r
+    }\r
+    \r
+    public static String getUnit(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        if(variable == null)\r
+            return null;\r
+        \r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        Resource configuration = graph.syncRequest(new GetConfigurationRequest(variable));\r
+        SysdynModel sm = smm.getModel(graph,configuration);\r
+        \r
+        IElement element = sm.getElement(variable);\r
+        \r
+        if(element instanceof Variable) {\r
+            String result = ((Variable)element).getUnit();\r
+            if(result == null)\r
+                return "";\r
+            else\r
+                return result;\r
+        }\r
+        \r
+        return "";\r
+    }\r
+    \r
+    \r
+    public static String getVariability(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        if(variable == null)\r
+            return null;\r
+        \r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        Resource configuration = graph.syncRequest(new GetConfigurationRequest(variable));\r
+        SysdynModel sm = smm.getModel(graph,configuration);\r
+        \r
+        IElement element = sm.getElement(variable);\r
+        \r
+        if(element instanceof Stock)\r
+            return "";\r
+        \r
+        if(element instanceof IndependentVariable) {\r
+            Variability variability = Variability.getVariability((IndependentVariable)element);\r
+            if(variability == Variability.CONTINUOUS)\r
+                return "";\r
+            return variability.toString().toLowerCase();\r
+        }\r
+        if(element instanceof Variable) {\r
+            String result = ((Variable)element).getVariability();\r
+            if(result == null)\r
+                return "";\r
+            else {\r
+                return result;\r
+            }\r
+        }\r
+        \r
+        return "";\r
+    }\r
+    \r
+    public static String getDescription(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        if(variable == null)\r
+            return null;\r
+        \r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        Resource configuration = graph.syncRequest(new GetConfigurationRequest(variable));\r
+        SysdynModel sm = smm.getModel(graph,configuration);\r
+        \r
+        IElement element = sm.getElement(variable);\r
+        \r
+        if(element instanceof Variable) {\r
+            String result = ((Variable)element).getDescription();\r
+            if(result == null)\r
+                return "";\r
+            else\r
+                return result;\r
+        }\r
+        \r
+        return "";\r
+    }\r
+    \r
+    \r
+    public static String getDocumentationDefinition(ReadGraph graph, Resource variable) throws DatabaseException {\r
+        if(variable == null)\r
+            return null;\r
+\r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        Resource configuration = graph.syncRequest(new GetConfigurationRequest(variable));\r
+        SysdynModel sm = smm.getModel(graph,configuration);\r
+        \r
+        IElement element = sm.getElement(variable);\r
+        \r
+        if(element instanceof Variable) {\r
+            Variable v = (Variable) element;\r
+            String result = v.getDocumentationDefinition(graph);\r
+            if(result == null)\r
+                return "";\r
+            else\r
+                return result;\r
+        }\r
+        \r
+        if(element instanceof Module) {\r
+            Module m = (Module) element;\r
+            return m.getDocumentationDefinition();\r
+            // Print interface variables and parameter overrides\r
+        }\r
+        \r
+        return "";\r
+        \r
+    }\r
+    \r
+    \r
+    public static int numberOfVariables(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getVariables();\r
+    }\r
+    \r
+    public static int totalNumberOfVariables(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getTotalVariables();\r
+    }    \r
+    \r
+    public static int numberOfStocks(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getStocks();\r
+    }\r
+    \r
+    public static int numberOfValves(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getValves();\r
+    }\r
+    \r
+    public static int numberOfInputs(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getInputs();\r
+    }\r
+    \r
+    public static int numberOfShadows(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getShadows();\r
+    }\r
+\r
+    public static int numberOfAuxiliaries(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getAuxiliaries();\r
+    }\r
+    \r
+    public static int numberOfModules(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getModules();\r
+    }\r
+    \r
+    public static int numberOfSheets(ReadGraph graph, Resource configuration, boolean recursive) throws DatabaseException {\r
+        return graph.syncRequest(new ModuleSummaryRequest(configuration, recursive)).getSheets();\r
+    }\r
+    \r
+    public static int numberOfModuleTypes(ReadGraph graph, org.simantics.db.layer0.variable.Variable model) throws DatabaseException {\r
+        if(model == null)\r
+            return 0;\r
+        \r
+        Resource modelResource = model.getRepresents(graph);\r
+        return graph.syncRequest(new ObjectsWithSupertype(\r
+                modelResource, \r
+                Layer0.getInstance(graph).ConsistsOf, \r
+                SysdynResource.getInstance(graph).Module))\r
+                .size();\r
+    }\r
+    \r
+    public static String base64Encode(ReadGraph graph, org.simantics.db.layer0.variable.Variable variable, String property) throws DatabaseException {\r
+        byte[] fileBArray = variable.getPossiblePropertyValue(graph, property, Bindings.BYTE_ARRAY);\r
+        if(fileBArray != null)\r
+            return Base64.encode(fileBArray);\r
+        else\r
+            return "";\r
+    }\r
+    \r
+    public static String formatDate(long timeMillis) {\r
+        Date date = new Date(timeMillis);\r
+        String result = DateFormat.getDateInstance().format(date);\r
+        return result;\r
+    }\r
+    \r
+    /**\r
+     * Supports importing Sysdyn models into the current project from TG files\r
+     * in SCL.\r
+     * \r
+     * @param path\r
+     */\r
+    public static Resource importModel(String path) {\r
+       final DataContainer<Resource> m = new DataContainer<Resource>();\r
+        try {\r
+                       ImportUtils.importModelFile(path, new NullProgressMonitor(), new FunctionImpl1<Resource,WriteRequest>() {\r
+\r
+                               @Override\r
+                               public WriteRequest apply(Resource model) {\r
+                                       m.set(model);\r
+                                       return null;\r
+                               }\r
+                               \r
+                       });\r
+               } catch (Exception e) {\r
+                       e.printStackTrace();\r
+               }\r
+        return m.get();\r
+    }\r
+\r
+    public static boolean isParameter(ReadGraph graph, org.simantics.db.layer0.variable.Variable variable) throws DatabaseException {\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        Resource represents = variable.getPossibleRepresents(graph);\r
+        System.out.println(graph.getURI(represents));\r
+        if(represents == null || !graph.isInstanceOf(represents, SR.IndependentVariable))\r
+            return false;\r
+        \r
+        Resource expressionList = graph.getPossibleObject(represents, SR.Variable_expressionList);\r
+        \r
+        if(expressionList == null)\r
+            return false;\r
+        \r
+        List<Resource> expressions = ListUtils.toList(graph, expressionList);\r
+        if(expressions == null || expressions.size() != 1)\r
+            return false;\r
+        \r
+        Resource expression = expressions.get(0);\r
+        return graph.isInstanceOf(expression, SR.ParameterExpression);\r
+    }\r
+    \r
+    public static double lastValue(final Resource experiment, final String runId, final String path) throws DatabaseException {\r
+       \r
+               try {\r
+                       double[] values = EvaluatingListener.<double[]>trySyncRequest(Simantics.getSession(),\r
+                                       \r
+                                       new UniqueRead<double[]>(){\r
+                                               @Override\r
+                                               public double[] perform(ReadGraph graph) throws DatabaseException{\r
+                                                       \r
+                                               org.simantics.db.layer0.variable.Variable var = Variables.getVariable(graph, experiment);\r
+                                               if(var == null) return null;\r
+                                               org.simantics.db.layer0.variable.Variable run = var.getPossibleChild(graph, runId);\r
+                                               if(run == null) return null;\r
+                                               org.simantics.db.layer0.variable.Variable v = run.browsePossible(graph, path + "#value#");\r
+                                               if(v == null) return null;\r
+                                               return  v.getPossibleValue(graph);\r
+                                                       \r
+                                               }               \r
+                                       }, \r
+                                       new Criterion<double[]>() {\r
+\r
+                                               @Override\r
+                                               public Evaluation evaluate(double[] result) {\r
+                                                       if(result == null) return Evaluation.DISCARD;\r
+                                                       return (result != ValueIndexVariable.UNRESOLVED) ? Evaluation.ACCEPT : Evaluation.IGNORE;\r
+                                               }\r
+                                               \r
+                                       },\r
+                                       15, TimeUnit.SECONDS);\r
+                       return values[0];\r
+               } catch (InterruptedException e) {\r
+                       e.printStackTrace();\r
+                       return Double.NaN;\r
+               }\r
+       \r
+    }\r
+\r
+    public static org.simantics.db.layer0.variable.Variable lastValue2(ReadGraph graph, org.simantics.db.layer0.variable.Variable run, String path) throws DatabaseException {\r
+       \r
+       if(run == null) return null;\r
+\r
+       org.simantics.db.layer0.variable.Variable v = run.browsePossible(graph, "/" + path);\r
+       if(v == null) return null;\r
+\r
+       org.simantics.db.layer0.variable.Variable p = v.browsePossible(graph, "#value#$0");\r
+       if(p == null) return null;\r
+       \r
+       return p;\r
+       \r
+    }\r
+\r
+    /**\r
+     * Splits indexed variable reference into name and indices part.\r
+     * \r
+     * @param path\r
+     */\r
+    public static Pair<String, String> splitToNameAndIndices(String reference) {\r
+       final Pattern indexPattern = Pattern.compile("^([^\\[]*)\\[([^\\]]*)]$");\r
+       Matcher m = indexPattern.matcher(reference);\r
+       \r
+       if (m.matches()) {\r
+               String name = m.group(1);\r
+               String indices = m.group(2).trim().replaceAll("\\s*,\\s*", ",");\r
+               return Pair.make(name, indices);\r
+       } else {\r
+               return Pair.make(reference, "");\r
+       }\r
+\r
+    }\r
+    \r
+    public static org.simantics.db.layer0.variable.Variable lastValueIndexed(ReadGraph graph, org.simantics.db.layer0.variable.Variable run, String path) throws DatabaseException {\r
+       \r
+       if(run == null) return null;\r
+\r
+       Pair<String, String> nameAndIndices = splitToNameAndIndices(path);\r
+\r
+       org.simantics.db.layer0.variable.Variable v = run.browsePossible(graph, "/" + nameAndIndices.first + "#value#" + nameAndIndices.second);\r
+       if(v == null) throw new MissingVariableException("No variable for SysDyn reference path: " + path);\r
+       \r
+       return v;\r
+    }    \r
+    \r
+    public static org.simantics.db.layer0.variable.Variable equation(ReadGraph graph, org.simantics.db.layer0.variable.Variable run, String path) throws DatabaseException {\r
+\r
+       if(run == null) return null;\r
+       \r
+       org.simantics.db.layer0.variable.Variable v = run.browsePossible(graph, "/" + path);\r
+       if(v == null) return null;\r
+\r
+       org.simantics.db.layer0.variable.Variable p = v.browsePossible(graph, "#equation");\r
+       if(p == null) return null;\r
+       \r
+       return p;\r
+       \r
+    }\r
+    \r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/Function.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/Function.java
new file mode 100644 (file)
index 0000000..21fce96
--- /dev/null
@@ -0,0 +1,562 @@
+package org.simantics.sysdyn.utils;\r
+\r
+import java.io.StringReader;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.unitParser.ParseException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
+import org.simantics.sysdyn.unitParser.UnitParser;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult;\r
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
+import org.simantics.ui.SimanticsUI;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+\r
+/**\r
+ * Class to store function name, type, and parameters. \r
+ * \r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class Function implements Comparable<Function>{\r
+\r
+    private final String name;\r
+    private final Type type;\r
+    private final ArrayList<Input> inputList;\r
+    private final ArrayList<Output> outputList;\r
+    private final String description;\r
+    \r
+    public static class Parameter {\r
+       public static final String ANY = "ANY";\r
+       public static final String TIME = "TIME";\r
+       public String name;\r
+       public String unit = ANY;\r
+       \r
+       public UnitResult getUnitResult(\r
+                       HashMap<String, String> units, \r
+                       Function f,\r
+                       ArrayList<Function> functions,\r
+                       boolean allowEquivalents,\r
+                       HashMap<String, String> correspondences) throws UnitCheckingException {\r
+               \r
+               UnitResult result = new UnitResult(allowEquivalents);\r
+                       if (Parameter.ANY.equals(this.unit)) {\r
+                       result.setUnitType(UnitType.ANY);\r
+               } else if ("1".equals(this.unit)) { // TODO: see if this should be changed to something else\r
+                       result.setUnitType(UnitType.SCALAR);\r
+               } else {\r
+                       // Replace TIME with actual time unit.\r
+                       String timeUnit = units.get("time");\r
+                       String timeReplaced = this.unit.replace(Parameter.TIME, timeUnit);\r
+\r
+                       // Replace 'p, 'q, etc. in output with units from actual inputs.\r
+                       String correspondencesReplaced = replaceCorrespondences(f, timeReplaced, correspondences);\r
+\r
+                       try {\r
+                               StringReader outputReader = new StringReader(correspondencesReplaced);\r
+                               UnitParser outputParser = new UnitParser(outputReader);\r
+                               UnitCheckingNode output;\r
+                               output = (UnitCheckingNode) outputParser.expr();\r
+                               outputReader.close();\r
+                   result.appendResult(output.getUnits(null, functions, allowEquivalents));\r
+                       } catch (UnitCheckingException e) {\r
+                               e.printStackTrace();\r
+                       } catch (ParseException e) {\r
+                               throw new UnitCheckingException("Cannot validate units: Syntax error in expression.");\r
+                       }\r
+               }\r
+               \r
+            return result;\r
+       }\r
+       \r
+       private static String replaceCorrespondences(Function f, String original,\r
+                       HashMap<String, String> correspondences) throws UnitCheckingException {\r
+               int index;\r
+               String ret = new String(original);\r
+               // Go through the unit as long as there are part of form 'p, 'q, etc. and replace them.\r
+               while ((index = ret.indexOf('\'')) >= 0) {\r
+                       String replaced = ret.substring(index, index + 2); // The replaced units are always of length 2.\r
+                       try {\r
+                               ret = ret.replace(replaced, "(" + correspondences.get(replaced) + ")");\r
+                       } catch (NullPointerException npe) {\r
+                               throw new UnitCheckingException("Function " + f.getName() + " output unit could not be determined. Replacement unit " \r
+                                               + replaced + " not found in input unit definitions.");\r
+                       }\r
+               }\r
+               return ret;\r
+       }\r
+    }\r
+\r
+    public static class Input extends Parameter {\r
+       public boolean variableLength = false;\r
+       public boolean optional = false;\r
+       public ArrayList<String> variableLengthLabels;\r
+    }\r
+    \r
+    public static class Output extends Parameter {\r
+    }\r
+    \r
+    public enum Type {\r
+        USER_DEFINED,\r
+        SHARED,\r
+        SYSDYN,\r
+        MODELICA, \r
+        MODELICA_ARRAY,\r
+        VENSIM\r
+    }\r
+    \r
+    public Function(\r
+               String name, \r
+               ArrayList<Input> inputList, \r
+               ArrayList<Output> outputList, \r
+               Type type, \r
+               String description){\r
+       \r
+        this.name = new String(name);\r
+        \r
+        this.type = type;\r
+        \r
+        if (inputList != null)\r
+            this.inputList = inputList;\r
+        else\r
+            this.inputList = new ArrayList<Input>();\r
+        \r
+        if (outputList != null)\r
+            this.outputList = outputList;\r
+        else\r
+            this.outputList = new ArrayList<Output>();\r
+        \r
+        if (description != null)\r
+            this.description = new String(description);\r
+        else\r
+            this.description = null;\r
+    }\r
+       \r
+    /**\r
+     * Convert list of Inputs to string\r
+     * @param inputList list of Inputs\r
+     * @return printable form of inputs (for function declaration)\r
+     */\r
+       public static String inputListToString(ArrayList<Input> inputList) {\r
+               String inputStr = null;\r
+               for (Input p : inputList) {\r
+                       String pName;\r
+                       // Variable length parameter list\r
+                       if (p.variableLength) {\r
+                               pName = "";\r
+                               for (String label : p.variableLengthLabels) {\r
+                                       pName += label + ", ";\r
+                }\r
+                               pName += "...";\r
+                       } else {\r
+                               pName = p.name;\r
+                       }\r
+                       \r
+            if (inputStr == null)\r
+                inputStr = new String(pName);\r
+            else\r
+                inputStr += ", " + pName;\r
+               }\r
+               return inputStr;\r
+       }\r
+    \r
+    public ArrayList<Input> getInputList() {\r
+        return inputList;\r
+    }\r
+    \r
+    public ArrayList<Output> getOutputList() {\r
+        return outputList;\r
+    }\r
+    \r
+    public String getName() {\r
+        return name;\r
+    }\r
+    \r
+    public Type getType() {\r
+        return type;\r
+    }\r
+    \r
+    public String getDescription() {\r
+        return description;\r
+    }\r
+    \r
+    @Override\r
+    public int compareTo(Function f) {\r
+        // Sorting is done first in the order of Types and then alphabetically.\r
+        int typeCompare = type.compareTo(f.getType());\r
+        return typeCompare != 0 ? typeCompare : name.compareTo(f.getName());\r
+    }\r
+    \r
+    /**\r
+     * Get Modelica function input parameters\r
+     * @param graph\r
+     * @param sr \r
+     * @param r Resource of the Modelica function\r
+     * @return ArrayList of Inputs\r
+     * @throws DatabaseException\r
+     */\r
+    public static ArrayList<Input> getFunctionInputs(ReadGraph graph, SysdynResource sr, Resource r) throws DatabaseException {\r
+        Resource inputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_inputs);\r
+        ArrayList<Input> inputParameters = new ArrayList<Input>();\r
+        if (inputs != null) {\r
+            for (Resource input : ListUtils.toList(graph, inputs)) {\r
+               // Convert the Resource into Parameter;\r
+                Input inputParameter = new Input();\r
+                inputParameter.name = NameUtils.getSafeName(graph, input);\r
+                inputParameter.optional = graph.getPossibleRelatedValue(\r
+                               input, \r
+                               sr.SysdynModelicaFunction_optional, \r
+                               Bindings.BOOLEAN);\r
+                inputParameter.unit = graph.getPossibleRelatedValue(\r
+                               input, \r
+                               sr.SysdynModelicaFunction_unit, \r
+                               Bindings.STRING);\r
+                if (graph.isInstanceOf(input, sr.SysdynModelicaFunction_VariableLengthInput)) {\r
+                       inputParameter.variableLength = true;\r
+                    Resource shownLabels = graph.getPossibleObject(\r
+                            input, \r
+                            sr.SysdynModelicaFunction_VariableLengthInput_shownLabels);\r
+                    inputParameter.variableLengthLabels = new ArrayList<String>();\r
+                    if (shownLabels != null) {\r
+                        for (Resource label : ListUtils.toList(graph, shownLabels)) {\r
+                               inputParameter.variableLengthLabels.add(NameUtils.getSafeName(graph, label));\r
+                        }\r
+                    }\r
+                }\r
+                \r
+                       inputParameters.add(inputParameter);\r
+            }\r
+        }\r
+        return inputParameters;\r
+    }\r
+    \r
+    /**\r
+     * Get Modelica function outputs\r
+     * @param graph\r
+     * @param sr \r
+     * @param r Resource of the Modelica function\r
+     * @return ArrayList of Outputs\r
+     * @throws DatabaseException\r
+     */\r
+    protected static ArrayList<Output> getFunctionOutputs(ReadGraph graph,\r
+                       SysdynResource sr, Resource r) throws DatabaseException {\r
+       Resource outputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_outputs);\r
+        ArrayList<Output> outputParameters = new ArrayList<Output>(1);\r
+        if (outputs != null) {\r
+            for (Resource output : ListUtils.toList(graph, outputs)) {\r
+               // Convert the Resource into Parameter;\r
+                Output outputParameter = new Output();\r
+                outputParameter.name = NameUtils.getSafeName(graph, output);\r
+                outputParameter.unit = graph.getPossibleRelatedValue(\r
+                               output, \r
+                               sr.SysdynModelicaFunction_unit, \r
+                               Bindings.STRING);\r
+                outputParameters.add(outputParameter);\r
+            }\r
+        }\r
+        return outputParameters;\r
+       }\r
+\r
+    public static String getFunctionDescription(ReadGraph graph, Resource r) throws DatabaseException {\r
+        String descriptionStr = null;\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        Resource description = graph.getPossibleObject(r, l0.HasDescription);\r
+        if (description != null) {\r
+            descriptionStr = graph.getPossibleRelatedValue(r, l0.HasDescription, Bindings.STRING);\r
+        }\r
+        \r
+        return descriptionStr;\r
+    }\r
+    \r
+    private static ArrayList<Function> getFunctionsOfType(ReadGraph graph, String functionTypeUri, Type functionType) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        ArrayList<Function> functions = new ArrayList<Function>();\r
+        \r
+        // Add functions\r
+        Resource functionLibrary = graph.getPossibleResource(functionTypeUri);\r
+        for(Resource r : graph.syncRequest(new ObjectsWithType(functionLibrary, l0.ConsistsOf, sr.SysdynModelicaFunction))) {\r
+            String name = NameUtils.getSafeName(graph, r);\r
+            ArrayList<Input> inputs = getFunctionInputs(graph, sr, r);\r
+            ArrayList<Output> outputs = getFunctionOutputs(graph, sr, r);\r
+            String description = getFunctionDescription(graph, r);\r
+            functions.add(new Function(name, inputs, outputs, functionType, description));\r
+        }\r
+        return functions;\r
+    }\r
+    \r
+    /**\r
+     * Get all built-in Modelica functions.\r
+     * Should be used if called inside a transaction\r
+     * @return ArrayList containing all built-in functions.\r
+     */\r
+    public static ArrayList<Function> getAllBuiltInFunctions(ReadGraph graph) throws DatabaseException {\r
+        ArrayList<Function> functions = new ArrayList<Function>();\r
+    \r
+        // Add different types of functions.\r
+        functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions, Type.SYSDYN));\r
+        functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Vensim_Functions, Type.VENSIM));\r
+        functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Modelica_Functions, Type.MODELICA));\r
+        functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Modelica_Array_Functions, Type.MODELICA_ARRAY));\r
+        \r
+        return functions;\r
+    }\r
+    \r
+    /**\r
+     * Get all built-in Modelica functions.\r
+     * @return ArrayList containing all built-in functions.\r
+     */\r
+    public static ArrayList<Function> getAllBuiltInFunctions() {\r
+        ArrayList<Function> result = null;\r
+        \r
+        //Finding functions\r
+        try {\r
+             result = SimanticsUI.getSession().syncRequest(new Read<ArrayList<Function>>() {\r
+                @Override\r
+                public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {\r
+                    return getAllBuiltInFunctions(graph);\r
+                }\r
+            });\r
+        }\r
+        catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        \r
+        return result;\r
+    }\r
+    \r
+    /**\r
+     * Get all shared Modelica functions.\r
+     * @param variable of which model is in question\r
+     * @return ArrayList containing all shared functions.\r
+     */\r
+    public static ArrayList<Function> getSharedFunctions(final Resource model) {\r
+        ArrayList<Function> functions = new ArrayList<Function>();\r
+        if (model == null) {\r
+            return functions;\r
+        }\r
+        \r
+        try {\r
+            functions = SimanticsUI.getSession().syncRequest(new Read<ArrayList<Function>>() {\r
+    \r
+                @Override\r
+                public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+                    \r
+                    // Full names of the collected functions\r
+                    ArrayList<Function> sharedFunctions = new ArrayList<Function>();\r
+\r
+                    Collection<Resource> linkedResources = graph.getObjects(model, l0.IsLinkedTo);\r
+                    for (Resource r : linkedResources) {\r
+                        // Find the "Shared functions" library \r
+                        if (graph.isInstanceOf(r, sr.SharedFunctionOntology)) {\r
+                            // Get all function resources under the Shared Functions "folder". \r
+                            Collection<Resource> userFunctionResources = getFunctionsInside(graph, r);\r
+                            for (Resource function : userFunctionResources) {\r
+                                // Construct the Modelica name of the function\r
+                                String fullName = NameUtils.getSafeName(graph, function);\r
+                                Resource parent = function; // Parent is updated properly in the loop\r
+                                do {\r
+                                    parent = graph.getPossibleObject(parent, l0.PartOf);\r
+                                    fullName = NameUtils.getSafeName(graph, parent) + "." + fullName;\r
+                                } while (!graph.isInstanceOf(parent, l0.Ontology));\r
+                                \r
+                                // Create a Function object out of the Resource\r
+                                Function sharedFunction = new Function(fullName, \r
+                                               Function.getFunctionInputs(graph, sr, function),\r
+                                               Function.getFunctionOutputs(graph, sr, function),\r
+                                        Type.SHARED, \r
+                                        Function.getFunctionDescription(graph, function));\r
+                                sharedFunctions.add(sharedFunction);\r
+                            }\r
+                        }\r
+                    }\r
+                    return sharedFunctions;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return functions;\r
+    }\r
+    \r
+   /**\r
+     * Get all user defined Modelica functions.\r
+     * @param variable of which model is in question\r
+     * @return ArrayList containing all user defined functions.\r
+     */\r
+    public static ArrayList<Function> getUserDefinedFunctions(final Resource model) {\r
+        ArrayList<Function> functions = new ArrayList<Function>();\r
+        if (model == null) {\r
+            return functions;\r
+        }\r
+        \r
+        try {\r
+            functions = SimanticsUI.getSession().syncRequest(new Read<ArrayList<Function>>() {\r
+    \r
+                @Override\r
+                public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {\r
+                    Layer0 l0 = Layer0.getInstance(graph);\r
+                    SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+                    // Full names of the collected functions\r
+                    ArrayList<Function> userFunctions = new ArrayList<Function>();\r
+                    \r
+                    // Get all function resources under model recursively\r
+                    Collection<Resource> userFunctionResources = getFunctionsInside(graph, model);\r
+                    for (Resource function : userFunctionResources) {\r
+                        // Construct the Modelica name of the function\r
+                        String fullName = NameUtils.getSafeName(graph, function);\r
+                        Resource parent = graph.getPossibleObject(function, l0.PartOf);\r
+                        while (!graph.isInstanceOf(parent, sr.SysdynModel)) {\r
+                            fullName = NameUtils.getSafeName(graph, parent) + "." + fullName;\r
+                            parent = graph.getPossibleObject(parent, l0.PartOf);\r
+                        }\r
+                        \r
+                        // Create a Function object out of the Resource\r
+                        Function userFunction = new Function(fullName, \r
+                                Function.getFunctionInputs(graph, sr, function),\r
+                                Function.getFunctionOutputs(graph, sr, function),\r
+                                Type.USER_DEFINED, \r
+                                Function.getFunctionDescription(graph, function));\r
+                        userFunctions.add(userFunction);\r
+                    }\r
+                    \r
+                    return userFunctions;\r
+                }\r
+            });\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+        return functions;\r
+    }\r
+    \r
+    /**\r
+     * Get functions inside a resource\r
+     * @param graph\r
+     * @param r Recource in which functions are sought\r
+     * @return found function Resources\r
+     * @throws DatabaseException\r
+     */\r
+    public static Collection<Resource> getFunctionsInside(ReadGraph graph, Resource r) throws DatabaseException {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        ArrayList<Resource> functions = new ArrayList<Resource>();\r
+        functions.addAll(graph.syncRequest(new ObjectsWithType(\r
+                r, \r
+                l0.ConsistsOf, \r
+                sr.SysdynModelicaFunction)));\r
+        Collection<Resource> functionLibraries;\r
+        functionLibraries = graph.syncRequest(new ObjectsWithType(\r
+                r, \r
+                l0.ConsistsOf,\r
+                sr.SysdynModelicaFunctionLibrary));\r
+        for (Resource library : functionLibraries) {\r
+            functions.addAll(getFunctionsInside(graph, library));\r
+        }\r
+        return functions;\r
+    }\r
+    \r
+    /**\r
+     * Converts the description string to HTML-format\r
+     * @return HMTL-formatted description.\r
+     */\r
+    public String getDescriptionHTML() {\r
+        if (description == null)\r
+            return null;\r
+        return description.replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<BR>");\r
+    }\r
+\r
+    /**\r
+     * Determine if the units of the given arguments are valid\r
+     * @param argumentUnits validated arguments\r
+     * @param correspondences mapping from templates to actual arguments\r
+     * @param functions all functions available\r
+     * @param allowEquivalents true iff equivalent units are used (e.g. $ == dollar)\r
+     * @param units evm\r
+     * @return true iff argument units are valid\r
+     * @throws UnitCheckingException if \r
+     */\r
+    public boolean areArgumentUnitsValid(ArrayList<Pair<UnitResult, String>> argumentUnits, \r
+                       HashMap<String, String> correspondences,\r
+                       ArrayList<Function> functions, \r
+                       boolean allowEquivalents, \r
+                       HashMap<String, \r
+                       String> units) throws UnitCheckingException {\r
+               ArrayList<Boolean> inputMatches = new ArrayList<Boolean>(); // Table for matching inputs.\r
+               for (int i = 0; i < inputList.size(); ++i)\r
+                       inputMatches.add(Boolean.FALSE);\r
+               \r
+               for (int i = 0; i < argumentUnits.size(); ++i) { // Go through all _arguments_\r
+                       if (inputList.size() == 0)\r
+                               return false; // No inputs expected but got at least one\r
+                       \r
+                       if (argumentUnits.get(i).second != null) { // Named argument\r
+                               boolean found = false;\r
+                               for (int j = 0; j < inputList.size(); ++j) {\r
+                                       Input namedInput = inputList.get(j);\r
+                                       if (namedInput.name.equals(argumentUnits.get(i).second)) {\r
+                                               // Match input unit to argument unit\r
+                                               UnitResult inputUnit = namedInput.getUnitResult(units, this, functions, allowEquivalents, correspondences);\r
+                                               if (!inputUnit.equals(argumentUnits.get(i).first))\r
+                                                       return false;\r
+                                               inputMatches.set(j, Boolean.TRUE);\r
+                                               found = true;\r
+                                               break;\r
+                                       }\r
+                               }\r
+                               if (!found) {\r
+                                       throw new UnitCheckingException("Undefined input argument " + argumentUnits.get(i).second \r
+                                                       + " used in function " + this.getName() + ".");\r
+                               }\r
+                       } else { // Position argument\r
+                               if (i >= inputList.size()) { // Test for variable length argument\r
+                                       // Assume there can be only one variable length input and its in the end.\r
+                                       // And that there cannot be any optional arguments before.\r
+                                       Input input = inputList.get(inputList.size() - 1);\r
+                                       if (input.variableLength) {\r
+                                               // Match input unit to argument unit\r
+                                               UnitResult inputUnit = input.getUnitResult(units, this, functions, allowEquivalents, correspondences);\r
+                                               if (!inputUnit.equals(argumentUnits.get(i).first))\r
+                                                       return false;\r
+                                               // The corresponding _input_ has already been gone through, no need to set true.\r
+                                       } else {\r
+                                               return false;\r
+                                       }\r
+                               } else {\r
+                                       // Match input unit to argument unit\r
+                                       UnitResult inputUnit = inputList.get(i).getUnitResult(units, this, functions, allowEquivalents, correspondences);\r
+                                       if (inputUnit.getUnitType() == UnitType.SCALAR\r
+                                                       && !(argumentUnits.get(i).first.getUnitType() == UnitType.SCALAR))\r
+                                               return false; // Here we don't accept a "1" replaced with a NORMAL expression, there's "ANY" for that.\r
+                                       if (!inputUnit.equals(argumentUnits.get(i).first))\r
+                                               return false;\r
+                                       inputMatches.set(i, Boolean.TRUE);\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               // See if some of the required inputs has not been defined. \r
+               for (int i = 0; i < inputList.size(); ++i) {\r
+                       if (!inputMatches.get(i) && !inputList.get(i).optional) {\r
+                               return false;\r
+                       }\r
+               }\r
+               \r
+               return true;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/GetConfigurationRequest.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/GetConfigurationRequest.java
new file mode 100644 (file)
index 0000000..4aa5155
--- /dev/null
@@ -0,0 +1,42 @@
+package org.simantics.sysdyn.utils;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class GetConfigurationRequest implements Read<Resource> {\r
+        \r
+        private Resource resource;\r
+        \r
+        public GetConfigurationRequest(Resource resource) {\r
+            this.resource = resource;\r
+        }\r
+\r
+        @Override\r
+        public Resource perform(ReadGraph graph) throws DatabaseException {\r
+            return getConfiguration(graph, resource);\r
+        }\r
+        \r
+        private Resource getConfiguration(ReadGraph graph, Resource resource) throws DatabaseException {\r
+            Layer0 L0 = Layer0.getInstance(graph);\r
+            Resource parent = graph.getPossibleObject(resource, L0.PartOf);\r
+            if(parent == null)\r
+                return null;\r
+           \r
+            SysdynResource SR = SysdynResource.getInstance(graph);\r
+            if(graph.isInstanceOf(parent, SR.SysdynModel)) {\r
+                parent = graph.getPossibleObject(parent, SimulationResource.getInstance(graph).HasConfiguration);\r
+            }\r
+            \r
+            if(graph.isInstanceOf(parent, SR.Configuration)) {\r
+                return parent;\r
+            }\r
+            \r
+            else\r
+                return getConfiguration(graph, parent);\r
+        }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/LoopUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/LoopUtils.java
new file mode 100644 (file)
index 0000000..731151f
--- /dev/null
@@ -0,0 +1,334 @@
+/*******************************************************************************\r
+ * Copyright (c) 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.utils;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.NoSingleResultException;\r
+import org.simantics.db.exception.ServiceException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.elementaryCycles.ElementaryCyclesSearch;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Utils for loops\r
+ * @author Tuomas Miettinen\r
+ *\r
+ */\r
+public class LoopUtils {\r
+\r
+       private static class ElementaryLoopItem {\r
+               public int mapping;\r
+               ArrayList<Resource> dependencies;\r
+               \r
+               public ElementaryLoopItem(int mapping, ArrayList<Resource> dependencies) {\r
+                       this.mapping = mapping;\r
+                       this.dependencies = dependencies;\r
+               }\r
+       }\r
+       \r
+       public enum LoopType {\r
+               REINFORCING,\r
+               BALANCING,\r
+               UNDEFINED\r
+       };\r
+       \r
+       /**\r
+        * Get all the loops within the diagram where the resource belongs to.\r
+        * @param r Resource that is studied\r
+        * @return List of loops; each loop is a list of resources in the same order in which\r
+        * they appear in the loop. The first item in the list can be any of the items in the\r
+        * loop. \r
+        */\r
+       public static List<List<Resource>> getLoops(final Resource r) {\r
+               List<List<Resource>> loops = Collections.emptyList();\r
+               try {\r
+                       loops = SimanticsUI.getSession().syncRequest(new Read<List<List<Resource>>>() {\r
+\r
+                               @Override\r
+                               public List<List<Resource>> perform(ReadGraph graph)\r
+                                               throws DatabaseException {\r
+                                       return getLoops(graph, r);\r
+                               }\r
+                       });\r
+               } catch (DatabaseException e) {\r
+                       e.printStackTrace();\r
+               }\r
+               return loops;\r
+       }\r
+       \r
+       @SuppressWarnings({ "rawtypes", "unchecked", "unused" })\r
+       public static List<List<Resource>> getLoops(ReadGraph g, Resource r) throws DatabaseException, ServiceException {\r
+               // Get all loops in the diagram.\r
+               List<List<Resource>> cycles = getAllLoopsInDiagram(g, r);\r
+               \r
+               // Collect all those loops in which the original resource exists.\r
+               List<List<Resource>> loops = new ArrayList<List<Resource>>();\r
+               for (Object o : cycles) {\r
+                       if (o instanceof List) {\r
+                               List loop = (List)o;\r
+                               if (loop.contains(r))\r
+                                       loops.add(loop);\r
+                       }\r
+               }\r
+               \r
+               // Debug print the result\r
+               if (false) {\r
+                       System.out.println(cyclesToString(g, cycles));\r
+               }\r
+               \r
+               return loops;\r
+       }\r
+       \r
+       @SuppressWarnings({ "rawtypes", "unchecked" })\r
+       public static List<List<Resource>> getAllLoopsInDiagram(ReadGraph g, Resource r) throws DatabaseException, ServiceException {\r
+               Layer0 l0 = Layer0.getInstance(g);\r
+               SysdynResource sr = SysdynResource.getInstance(g);\r
+               Resource configuration = g.getPossibleObject(r, l0.PartOf);\r
+               if (configuration == null)\r
+                       return Collections.emptyList();\r
+               \r
+               Collection<Resource> variables = g.getObjects(configuration, l0.ConsistsOf);\r
+               ArrayList<Resource> shadows = new ArrayList<Resource>();\r
+               \r
+               // Leave only independent variables and shadows (and modules)\r
+               Iterator<Resource> it = variables.iterator();\r
+               while (it.hasNext()) {\r
+                       Resource v = it.next();\r
+                       if (g.isInstanceOf(v, sr.IndependentVariable)) {\r
+                       } else if (g.isInstanceOf(v, sr.Shadow)) {\r
+                               shadows.add(v);\r
+                               it.remove();\r
+                       /*} else if (|| g.isInstanceOf(v, sr.Module)) {\r
+                               */\r
+                       } else {\r
+                               it.remove();\r
+                       }\r
+               }\r
+                               \r
+               int variableCount = variables.size();\r
+               Resource nodes[] = new Resource[variableCount];\r
+               \r
+               // Add independent variables to map and array\r
+               int k = 0;\r
+               HashMap<Resource, ElementaryLoopItem> elementaryLoopItems = new HashMap<Resource, ElementaryLoopItem>();\r
+               for (Resource variable : variables) {\r
+                       ArrayList<Resource> dependingVariables = new ArrayList<Resource>();\r
+                       // Add forward dependencies and flows from valves.\r
+                       Collection<Resource> dependencies = g.getObjects(variable, sr.Variable_isTailOf);\r
+                       for (Resource dependency : dependencies) {\r
+                               Resource head = g.getPossibleObject(dependency, sr.Variable_HasHead);\r
+                               // Skip dependencies and flows to modules and clouds.\r
+                               if (head == null \r
+                                               || g.isInstanceOf(head, sr.Module)\r
+                                               || g.isInstanceOf(head, sr.Cloud))\r
+                                       continue;\r
+                               \r
+                               if ((g.isInstanceOf(dependency, sr.Flow) && g.isInstanceOf(variable, sr.Valve))\r
+                                               || g.isInstanceOf(dependency, sr.Dependency)) {\r
+                                       // Add all dependencies\r
+                                       // Add (only) such flows that start from a valve.\r
+                                       dependingVariables.add(head);\r
+                               }\r
+                       }\r
+                       // Add backward flows from stocks.\r
+                       Collection<Resource> backwardFlows = g.getObjects(variable, sr.Variable_isHeadOf);\r
+                       for (Resource flow : backwardFlows) {\r
+                               if (g.isInstanceOf(flow, sr.Flow)) {\r
+                                       Resource tail = g.getPossibleObject(flow, sr.Variable_HasTail);\r
+                                       if (tail != null && g.isInstanceOf(tail, sr.Stock)) {\r
+                                               // Add (only) such flows that start from a stock.\r
+                                               dependingVariables.add(tail);\r
+                                       }\r
+                               }\r
+                       }\r
+                       // Put the variable in the hash map.\r
+                       elementaryLoopItems.put(variable, new ElementaryLoopItem(k, dependingVariables));\r
+                       nodes[k++] = variable;\r
+               }\r
+               \r
+               // Add dependencies of shadow variables for their original variables\r
+               for (Resource shadow : shadows) {\r
+                       Resource original = g.getPossibleObject(shadow, sr.Shadow_original);\r
+                       ArrayList<Resource> dependingVariables = new ArrayList<Resource>();\r
+                       Collection<Resource> dependencies = g.getObjects(shadow, sr.Variable_isTailOf);\r
+                       for (Resource dependency : dependencies) {\r
+                               Resource head = g.getPossibleObject(dependency, sr.Variable_HasHead);\r
+                               if (!g.isInstanceOf(head, sr.Module)) {\r
+                                       dependingVariables.add(head);\r
+                               }\r
+                       }\r
+                       elementaryLoopItems.get(original).dependencies.addAll(dependingVariables);\r
+               }\r
+               \r
+               // Fill the adjacent matrix\r
+               boolean adjMatrix[][] = new boolean[variableCount][variableCount];\r
+               for (int j = 0; j < nodes.length; ++j) {\r
+                       ArrayList<Resource> dependingVariables = elementaryLoopItems.get(nodes[j]).dependencies;\r
+                       for (Resource v : dependingVariables) {\r
+                               adjMatrix[j][elementaryLoopItems.get(v).mapping] = true;\r
+                       }\r
+               }\r
+               \r
+               // Get ALL nodes in the diagram.\r
+               ElementaryCyclesSearch ecs = new ElementaryCyclesSearch(adjMatrix, nodes);\r
+               List cycles = ecs.getElementaryCycles();\r
+               \r
+               return cycles;\r
+       }\r
+       \r
+       /**\r
+        * Get the String representation of cycles. \r
+        * @param g\r
+        * @param cycles List of Resource Lists of which names are returned.\r
+        * @return the String representation of cycles\r
+        * @throws DatabaseException\r
+        */\r
+       public static String cyclesToString(ReadGraph g, List<List<Resource>> cycles) throws DatabaseException {\r
+               StringBuilder sb = new StringBuilder("");\r
+               for (int i = 0; i < cycles.size(); i++) {\r
+                       sb.append(cycleToString(g, cycles.get(i)));\r
+                       sb.append("\n");\r
+               }\r
+               return sb.toString();\r
+       }\r
+       \r
+       /**\r
+        * Get the String representation of a cycle. \r
+        * @param g\r
+        * @param cycle List of Resources of which names are returned.\r
+        * @return the String representation of a cycle\r
+        * @throws DatabaseException\r
+        */\r
+       public static String cycleToString(ReadGraph g, List<Resource> cycle) throws DatabaseException {\r
+               Layer0 l0 = Layer0.getInstance(g);\r
+               StringBuilder sb = new StringBuilder("");\r
+               for (int j = 0; j < cycle.size(); j++) {\r
+                       Resource node = (Resource) cycle.get(j);\r
+                       if (j < cycle.size() - 1) {\r
+                               sb.append(g.getPossibleRelatedValue(node, l0.HasName, Bindings.STRING) + " -> ");\r
+                       } else {\r
+                               sb.append(g.getPossibleRelatedValue(node, l0.HasName, Bindings.STRING));\r
+                       }\r
+               }\r
+               return sb.toString();\r
+       }\r
+       \r
+       /**\r
+        * Get the type of the loop, i.e. whether the loop is reinforcing or balancing.\r
+        * The type is determined based on the dependency arrows and flows on the diagram;\r
+        * the loop is balancing if there is odd number of dependencies with negative\r
+        * polarity (Polarity = "-"). Note:\r
+        * 1) each flow of which tail is a valve is considered a dependency with positive \r
+        *    (+) polarity.\r
+        * 2) each flow of which tail is a stock is considered a dependency with negative \r
+        *    (-) polarity which GOES TO THE OPPOSITE DIRECTION.\r
+        * 3) the polarity of a supplementary dependency arrow overrides a flow.\r
+        * 4) the loops are defined as a list of Resources. If the set of dependencies\r
+        *    between is ambiguous, the implementation may choose any possible dependency. \r
+        * 5) empty and null polarity are considered positive (+) polarities. \r
+        * @param graph\r
+        * @param resource The loop component\r
+        * @return the type of the loop. If the type cannot be determined,\r
+        * LoopType.UNDEFINED is returned\r
+        * @throws DatabaseException\r
+        */\r
+       public static LoopType getLoopType(ReadGraph graph, Resource resource) throws DatabaseException {\r
+               SysdynResource sr = SysdynResource.getInstance(graph); \r
+               ModelingResources mod = ModelingResources.getInstance(graph);\r
+               Resource loopResource = graph.getPossibleObject(resource, sr.Loop_Items);\r
+        \r
+               if (loopResource == null)\r
+                       return LoopType.UNDEFINED;\r
+\r
+               boolean oddNumberOfNegativeCausalities = false;\r
+               List<Resource> loop = ListUtils.toPossibleList(graph, loopResource);\r
+        for (int i = 0; i < loop.size(); ++i) {\r
+               boolean skipBackwardFlows = false;\r
+               \r
+               // Go through forward dependencies and flows\r
+               Collection<Resource> forwardDependencies = graph.getObjects(loop.get(i), sr.Variable_isTailOf);\r
+               \r
+               // And also through the forward dependencies of possible shadows.\r
+               Collection<Resource> shadows = graph.getObjects(loop.get(i), sr.Shadow_original_Inverse);\r
+               for (Resource shadow : shadows)\r
+                       forwardDependencies.addAll(graph.getObjects(shadow, sr.Variable_isTailOf));\r
+               \r
+               for (Resource dependency : forwardDependencies) {\r
+                       Resource dependingVariable = graph.getSingleObject(dependency, sr.Variable_HasHead);\r
+                       if (dependingVariable.equals(loop.get((i + 1) % loop.size()))) {\r
+                               if (graph.isInstanceOf(dependency, sr.Flow)) {\r
+                                       /*\r
+                                        * Forward flows never affect the loop type. Allow dependency arrows \r
+                                        * override flows; thus don't touch skipBackwardFlows and continue.\r
+                                        * continue also because we may have a flow from stock, which\r
+                                        * is the wrong dependency and we need to keep searching.\r
+                                        */\r
+                                       continue;\r
+                               }\r
+                               skipBackwardFlows = true;\r
+                               \r
+                               Resource dependencyConnection;\r
+                               try {\r
+                                       dependencyConnection = graph.getSingleObject(dependency, mod.ConnectionToDiagramConnection);\r
+                               } catch (NoSingleResultException e) {\r
+                                       return LoopType.UNDEFINED;\r
+                               }\r
+                           String polarity = (String)graph.getPossibleRelatedValue(dependencyConnection, sr.DependencyConnection_polarity, Bindings.STRING);\r
+                               if ("-".equals(polarity)) {\r
+                                       oddNumberOfNegativeCausalities = !oddNumberOfNegativeCausalities;\r
+                               } else if (polarity != null \r
+                                               && !"".equals(polarity)\r
+                                               && !"+".equals(polarity)) {\r
+                                       // There's something other than + in one of the dependencies\r
+                                       return LoopType.UNDEFINED;\r
+                               }\r
+                               // "+" doesn't affect loop type, consider null and "" as a "+".\r
+                               break;\r
+                       }\r
+               }\r
+               \r
+               if (skipBackwardFlows)\r
+                       continue;\r
+               \r
+               // Backward flows from stocks.\r
+               Collection<Resource> backwardFlows = graph.getObjects(loop.get(i), sr.Variable_isHeadOf);\r
+                       for (Resource flow : backwardFlows) {\r
+                               if (graph.isInstanceOf(flow, sr.Flow)) {\r
+                                       Resource dependingVariable = graph.getSingleObject(flow, sr.Variable_HasTail);\r
+                                       if (dependingVariable.equals(loop.get((i + 1) % loop.size()))) {\r
+                                               if (graph.isInstanceOf(dependingVariable, sr.Stock)) {\r
+                                                       // Basically, we should always end up here since all other\r
+                                                       // possibilities have already been gone through.\r
+                                                       oddNumberOfNegativeCausalities = !oddNumberOfNegativeCausalities;\r
+                                                       break;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+        }\r
+               return oddNumberOfNegativeCausalities ? LoopType.BALANCING : LoopType.REINFORCING;\r
+       }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModelUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModelUtils.java
new file mode 100644 (file)
index 0000000..e3212ab
--- /dev/null
@@ -0,0 +1,211 @@
+package org.simantics.sysdyn.utils;\r
+\r
+import java.util.UUID;\r
+\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.utils.Logger;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.adapter.Template;\r
+import org.simantics.document.DocumentResource;\r
+import org.simantics.issues.ontology.IssueResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.ModelingResources;\r
+import org.simantics.modeling.ModelingUtils;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.project.ontology.ProjectResource;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.utils.datastructures.ArrayMap;\r
+\r
+public class ModelUtils {\r
+\r
+    /**\r
+     * Returns the SysdynModel where the given variable is located\r
+     * \r
+     * @param graph ReadGraph\r
+     * @param variable Variable whose model is wanted\r
+     * @return SysdynModel where variable is located\r
+     * @throws DatabaseException\r
+     */\r
+    public static SysdynModel getModel(ReadGraph graph, Resource variable) throws DatabaseException  {\r
+        Layer0 l0 = Layer0.getInstance(graph);\r
+        Resource configuration = graph.getPossibleObject(variable, l0.PartOf);\r
+        if(configuration == null)\r
+            return null;\r
+        SysdynModelManager sdm = SysdynModelManager.getInstance(Simantics.getSession());\r
+        SysdynModel model = sdm.getModel(graph, configuration);\r
+        try {\r
+            model.update(graph);\r
+        } catch (DatabaseException e1) {\r
+            e1.printStackTrace();\r
+        }\r
+        return model;\r
+    }\r
+\r
+    public static Resource createModel(WriteGraph graph) {\r
+        return createModelAt(graph, Simantics.getProject().get());\r
+    }\r
+\r
+    // TODO: remove this\r
+    public static Resource createModelAt(WriteGraph g, Resource library) {\r
+        try {\r
+            Layer0 l0 = Layer0.getInstance(g);\r
+            Layer0X L0X = Layer0X.getInstance(g);\r
+            SysdynResource sr = SysdynResource.getInstance(g);\r
+            SpreadsheetResource SHEET = SpreadsheetResource.getInstance(g);\r
+            ModelingUtils mu = new ModelingUtils(g);\r
+            DocumentResource DOC = DocumentResource.getInstance(g);\r
+\r
+            String modelName = NameUtils.findFreshName(g, "Model", library, l0.ConsistsOf, "%s%d");\r
+\r
+            Resource project = Simantics.getProject().get();\r
+            Resource model = GraphUtils.create2(g,\r
+                    sr.SysdynModel,\r
+                    l0.PartOf, project,\r
+                    l0.HasName, modelName,\r
+                    l0.HasLabel, modelName,\r
+                    L0X.IsActivatedBy, project\r
+                    );\r
+\r
+            GraphUtils.create2(g,\r
+                    sr.Validations_Dependencies_MissingDependencyConnectionsIssueSource,\r
+                    L0X.IsActivatedBy, model,\r
+                    l0.PartOf, model\r
+                    );\r
+\r
+            GraphUtils.create2(g,\r
+                    sr.Validations_Dependencies_DependencyConnectionsIssueSource,\r
+                    L0X.IsActivatedBy, model,\r
+                    l0.PartOf, model\r
+                    );\r
+            \r
+            GraphUtils.create2(g,\r
+                    sr.Validations_Expressions_ExpressionIssueSource,\r
+                    L0X.IsActivatedBy, model,\r
+                    l0.PartOf, model\r
+                    );\r
+            \r
+            GraphUtils.create2(g,\r
+                    sr.Validations_Enumerations_EnumerationIssueSource,\r
+                    L0X.IsActivatedBy, model,\r
+                    l0.PartOf, model\r
+                    );     \r
+            \r
+            GraphUtils.create2(g,\r
+                    sr.Validations_Units_UnitIssueSource,\r
+                    L0X.IsActivatedBy, model,\r
+                    l0.PartOf, model,\r
+                    IssueResource.getInstance(g).IssueSource_active, false\r
+                    );        \r
+            \r
+            Resource conf = GraphUtils.create2(g,\r
+                    sr.Configuration,\r
+                    l0.PartOf, model,\r
+                    L0X.IsBaseRealizationOf, model,\r
+                    l0.HasName, modelName\r
+                    );\r
+\r
+            Resource diagram = g.newResource();\r
+            g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,\r
+                    ArrayMap\r
+                    .keys("", "diagram", "name")\r
+                    .values(conf, diagram, "Diagrammi")\r
+                    );\r
+\r
+            g.claim(model, mu.SIMU.HasConfiguration, conf);\r
+\r
+            Resource book = g.newResource();\r
+            g.claim(book, l0.InstanceOf, null, SHEET.Book);\r
+            g.addLiteral(book, l0.HasName, l0.NameOf, l0.String, "Book" + UUID.randomUUID().toString(), Bindings.STRING);\r
+            g.claim(conf, l0.ConsistsOf, l0.PartOf, book);\r
+\r
+            SheetUtils.createSheet(g, book, "Sheet1", new String[] { }, new int[] { 50 });\r
+\r
+\r
+\r
+            ModelingResources mr = ModelingResources.getInstance(g);\r
+            // Remove default mapping and add sysdyn mapping\r
+            for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {\r
+                if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {\r
+                    g.deny(diagram, L0X.HasTrigger, trigger);\r
+                }\r
+            }\r
+            Resource mapping = g.newResource();\r
+            g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);\r
+            g.claim(diagram, L0X.HasTrigger, mapping);\r
+\r
+            Resource report = GraphUtils.create2(g, DOC.Report,  DOC.HasDocumentation, "===Report===");\r
+\r
+            GraphUtils.create2(g, sr.BasicExperiment,\r
+                    l0.HasName, "Experiment",\r
+                    l0.HasLabel, "Experiment",\r
+                    DOC.HasReportFactory, report,\r
+                    l0.PartOf, model);\r
+\r
+            Resource sheetExperiment = GraphUtils.create2(g, SHEET.Experiment,\r
+                    l0.HasName, "SheetExperiment",\r
+                    l0.HasLabel, "Sheet Experiment",\r
+                    l0.PartOf, model);\r
+\r
+            Resource sheetRun = GraphUtils.create2(g, SHEET.Run,\r
+                    l0.HasName, "Default",\r
+                    l0.PartOf, sheetExperiment);\r
+\r
+            ProjectResource PROJ = ProjectResource.getInstance(g);\r
+            for(Resource dep : g.getObjects(library, l0.IsLinkedTo)) {\r
+                if(g.isInstanceOf(dep, PROJ.NamespaceRequirement)) {\r
+                    for(Resource req : g.getObjects(dep, PROJ.RequiresNamespace)) {\r
+                        String uri = g.getPossibleValue(req, Bindings.STRING);\r
+                        if(uri != null) {\r
+                            Resource target = g.getResource(uri);\r
+                            if(target != null) {\r
+                                g.claim(model, l0.IsLinkedTo, null, target);\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            \r
+            createSCLMain(g, model);\r
+            \r
+            ProfileEntries.createStandardProfiles(g, model);\r
+            \r
+            return model;\r
+            \r
+        } catch (DatabaseException e ) {\r
+               Logger.defaultLogError(e);\r
+        }\r
+        \r
+        return null;\r
+    }\r
+    \r
+    public static void createSCLMain(WriteGraph graph, Resource model) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Resource SCLModule = GraphUtils.create2(graph,\r
+                L0.SCLModule,\r
+                L0.PartOf, model,\r
+                L0.HasName, "SCLMain"\r
+                );\r
+\r
+        if(graph.hasStatement(SCLModule, L0.SCLModule_definition))\r
+            graph.deny(SCLModule, L0.SCLModule_definition);\r
+\r
+        graph.claimLiteral(SCLModule, L0.SCLModule_definition, "include \"Simantics/DB\"\n" +\r
+                "include \"Simantics/Variables\"\n" +\r
+                "include \"Simantics/Sysdyn\"\n" +\r
+                "include \"Simupedia/Sysdyn\" as SD\n" +\r
+                "include \"http://www.simantics.org/Documentation-1.2/Components\"\n" +\r
+                "include \"http://www.simantics.org/Documentation-1.2/Properties\" as Properties\n" +\r
+                "include \"http://www.simantics.org/Documentation-1.2/Relations\" as Relations\n" +\r
+                "include \"Simupedia/simupedia\"", Bindings.STRING);\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModuleSummary.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModuleSummary.java
new file mode 100644 (file)
index 0000000..ed0f25b
--- /dev/null
@@ -0,0 +1,103 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.utils;\r
+\r
+public class ModuleSummary {\r
+    \r
+    private int variables = 0;\r
+    private int totalVariables = 0;\r
+    private int auxiliaries = 0;\r
+    private int stocks = 0;\r
+    private int valves = 0;\r
+    private int inputs = 0;\r
+    private int shadows = 0;\r
+    private int modules = 0;\r
+    private int enumerations = 0;\r
+    private int sheets = 0;\r
+\r
+    \r
+    \r
+    public int getVariables() {\r
+        return variables;\r
+    }\r
+    public void setVariables(int variables) {\r
+        this.variables = variables;\r
+    }\r
+    public int getTotalVariables() {\r
+        return totalVariables;\r
+    }\r
+    public void setTotalVariables(int totalVariables) {\r
+        this.totalVariables = totalVariables;\r
+    }    \r
+    public int getAuxiliaries() {\r
+        return auxiliaries;\r
+    }\r
+    public void setAuxiliaries(int auxiliaries) {\r
+        this.auxiliaries = auxiliaries;\r
+    }\r
+    public int getStocks() {\r
+        return stocks;\r
+    }\r
+    public void setStocks(int stocks) {\r
+        this.stocks = stocks;\r
+    }\r
+    public int getValves() {\r
+        return valves;\r
+    }\r
+    public void setValves(int valves) {\r
+        this.valves = valves;\r
+    }\r
+    public int getInputs() {\r
+        return inputs;\r
+    }\r
+    public void setInputs(int inputs) {\r
+        this.inputs = inputs;\r
+    }\r
+    public int getShadows() {\r
+        return shadows;\r
+    }\r
+    public void setShadows(int shadows) {\r
+        this.shadows = shadows;\r
+    }\r
+    public int getModules() {\r
+        return modules;\r
+    }\r
+    public void setModules(int modules) {\r
+        this.modules = modules;\r
+    }\r
+    public int getEnumerations() {\r
+        return enumerations;\r
+    }\r
+    public void setEnumerations(int enumerations) {\r
+        this.enumerations = enumerations;\r
+    }\r
+    public int getSheets() {\r
+        return sheets;\r
+    }\r
+    public void setSheets(int sheets) {\r
+        this.sheets = sheets;\r
+    }\r
+    \r
+    public void add(ModuleSummary otherSummary) {\r
+        setAuxiliaries(getAuxiliaries() + otherSummary.getAuxiliaries());\r
+        setEnumerations(getEnumerations() + otherSummary.getEnumerations());\r
+        setInputs(getInputs() + otherSummary.getInputs());\r
+        setModules(getModules() + otherSummary.getModules());\r
+        setShadows(getShadows() + otherSummary.getShadows());\r
+        setStocks(getStocks() + otherSummary.getStocks());\r
+        setValves(getValves() + otherSummary.getValves());\r
+        setVariables(getVariables() + otherSummary.getVariables());\r
+        setTotalVariables(getTotalVariables() + otherSummary.getTotalVariables());\r
+        setSheets(getSheets() + otherSummary.getSheets());\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModuleSummaryRequest.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModuleSummaryRequest.java
new file mode 100644 (file)
index 0000000..1d3267d
--- /dev/null
@@ -0,0 +1,146 @@
+/*******************************************************************************\r
+ * Copyright (c) 2013 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     Semantum Oy - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.utils;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.manager.SysdynModel;\r
+import org.simantics.sysdyn.manager.SysdynModelManager;\r
+import org.simantics.sysdyn.representation.Auxiliary;\r
+import org.simantics.sysdyn.representation.Configuration;\r
+import org.simantics.sysdyn.representation.Enumeration;\r
+import org.simantics.sysdyn.representation.IElement;\r
+import org.simantics.sysdyn.representation.Input;\r
+import org.simantics.sysdyn.representation.Module;\r
+import org.simantics.sysdyn.representation.Redeclaration;\r
+import org.simantics.sysdyn.representation.Shadow;\r
+import org.simantics.sysdyn.representation.Sheet;\r
+import org.simantics.sysdyn.representation.Stock;\r
+import org.simantics.sysdyn.representation.Valve;\r
+import org.simantics.sysdyn.representation.Variable;\r
+\r
+public class ModuleSummaryRequest implements Read<ModuleSummary> {\r
+    \r
+    private Resource module;\r
+    private boolean recursive;\r
+    \r
+    public ModuleSummaryRequest(Resource module, boolean recursive) {\r
+        this.module = module;\r
+        this.recursive = recursive;\r
+    }\r
+\r
+    @Override\r
+    public ModuleSummary perform(ReadGraph graph) throws DatabaseException {\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+        StructuralResource2 SR2 = StructuralResource2.getInstance(graph);\r
+        \r
+        ModuleSummary result = new ModuleSummary();\r
+        \r
+        if(module == null)\r
+            return result;\r
+        \r
+        Resource configuration;\r
+        if(graph.isInstanceOf(module, SR.SysdynModel))\r
+            configuration = graph.getPossibleObject(module, SIMU.HasConfiguration);\r
+        else if(graph.isInheritedFrom(module, SR.Module))\r
+            configuration = graph.getPossibleObject(module, SR2.IsDefinedBy);\r
+        else\r
+            configuration = null;\r
+        \r
+        if(configuration == null)\r
+            return result;\r
+        \r
+        SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
+        SysdynModel sm = smm.getModel(graph, configuration);\r
+        sm.update(graph);\r
+        \r
+        result.add(collectSummary(sm.getConfiguration(), recursive, new HashMap<String, Integer>()));\r
+        \r
+        return result;\r
+    }\r
+    \r
+    private ModuleSummary collectSummary(Configuration configuration, boolean recursive, Map<String, Integer> enumerationOverrides) {\r
+        ModuleSummary result = new ModuleSummary();\r
+        \r
+        for(IElement e : configuration.getElements()) {\r
+            if(e instanceof Input)\r
+                result.setInputs(result.getInputs() + 1);\r
+            \r
+            if(e instanceof Auxiliary)\r
+                result.setAuxiliaries(result.getAuxiliaries() + 1);\r
+            \r
+            if(e instanceof Stock)\r
+                result.setStocks(result.getStocks() + 1);\r
+            \r
+            if(e instanceof Shadow)\r
+                result.setShadows(result.getShadows() + 1);\r
+            \r
+            if(e instanceof Valve)\r
+                result.setValves(result.getValves() + 1);\r
+            \r
+            if(e instanceof Enumeration)\r
+                result.setEnumerations(result.getEnumerations() + 1);\r
+            \r
+            if(e instanceof Sheet)\r
+                result.setSheets(result.getSheets() + 1);\r
+            \r
+            if(e instanceof Variable && !(e instanceof Sheet)) {\r
+                result.setVariables(result.getVariables() + 1);\r
+                \r
+                int n = 1;\r
+                Variable var = (Variable) e;\r
+                if(var.getArrayIndexes() != null && var.getArrayIndexes().size() > 0) {\r
+                    for(Enumeration enumeration : var.getArrayIndexes()) {\r
+                        if(enumerationOverrides.containsKey(enumeration.getName())) {\r
+                            n = n * enumerationOverrides.get(enumeration.getName());\r
+                        } else {\r
+                            n = n * enumeration.getEnumerationIndexes().size();\r
+                        }\r
+                    }\r
+                }\r
+                result.setTotalVariables(result.getTotalVariables() + n);\r
+            }\r
+            \r
+            if(e instanceof Module) {\r
+                result.setModules(result.getModules() + 1);\r
+                \r
+                if(recursive) {\r
+                    Module m = (Module) e;\r
+                    HashMap<String, Integer> redeclarations = new HashMap<String, Integer>();\r
+                    for(Redeclaration redeclaration : m.getRedeclarations()) {\r
+                        int n;\r
+                        if(enumerationOverrides.containsKey(redeclaration.getReplacingEnumeration())) {\r
+                            n = enumerationOverrides.get(redeclaration.getReplacingEnumeration());\r
+                        } else {\r
+                            n = redeclaration.getReplacingEnumeration().getEnumerationIndexes().size();\r
+                        }\r
+                        redeclarations.put(redeclaration.getReplacedEnumeration().getName(), n);\r
+                    }\r
+                    result.add(collectSummary(m.getType().getConfiguration(), recursive, redeclarations));\r
+                }\r
+            }\r
+        }\r
+        \r
+        \r
+        return result;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ProfileEntries.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ProfileEntries.java
new file mode 100644 (file)
index 0000000..0856f36
--- /dev/null
@@ -0,0 +1,68 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.utils;\r
+\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.diagram.profile.Profiles;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+public class ProfileEntries  {\r
+\r
+\r
+    public static void createStandardProfiles(WriteGraph graph, final Resource model) throws DatabaseException {\r
+\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+\r
+        DiagramResource DIA = DiagramResource.getInstance(graph);\r
+\r
+        Resource simulationPlaybackProfile = createProfile(graph, "Simulation Playback", sr.SimulationPlaybackProfile ,sr.Profiles_SimulationPlaybackColours);\r
+\r
+        Resource defaultProfile = createProfile(graph, "Default", sr.DefaultProfile, sr.Profiles_IssueWarnings, sr.Profiles_ShadowVisualizations);\r
+\r
+        //graph.claim(model, DIA.HasProfile, defaultProfile);\r
+        graph.claim(model, L0.ConsistsOf, simulationPlaybackProfile);\r
+        graph.claim(model, L0.ConsistsOf, defaultProfile);\r
+\r
+        // FIXME: add virtual graph write back once this is fixed: https://www.simulationsite.net/redmine/issues/3296\r
+//        graph.sync(new WriteRequest(graph.getService(VirtualGraphSupport.class).getWorkspacePersistent("profiles")) {\r
+//            @Override\r
+//            public void perform(WriteGraph graph) throws DatabaseException {\r
+//                DiagramResource DIA = DiagramResource.getInstance(graph);\r
+                graph.claim(model, DIA.HasActiveProfile, defaultProfile);\r
+                SimulationResource SIMU = SimulationResource.getInstance(graph);\r
+                graph.claim(defaultProfile, SIMU.IsActive, null, sr.Profiles_IssueWarnings);\r
+                graph.claim(defaultProfile, SIMU.IsActive, null, sr.Profiles_ShadowVisualizations);\r
+                graph.claim(simulationPlaybackProfile, SIMU.IsActive, null, sr.Profiles_SimulationPlaybackColours);\r
+                \r
+//            }\r
+//        });\r
+\r
+    }\r
+    \r
+    public static Resource createProfile(WriteGraph graph, String name, Resource type, Resource... entries) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        \r
+        Resource profile = Profiles.createProfile(graph, name,\r
+                entries);\r
+        \r
+        graph.deny(profile, L0.InstanceOf);\r
+        graph.claim(profile, L0.InstanceOf, null, type);\r
+        return profile;\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SheetUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SheetUtils.java
new file mode 100644 (file)
index 0000000..9bda6ca
--- /dev/null
@@ -0,0 +1,128 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.utils;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.variable.Variable;\r
+import org.simantics.db.layer0.variable.Variables;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.spreadsheet.SheetVariables;\r
+import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
+\r
+public class SheetUtils {\r
+\r
+    public static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException {\r
+\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);\r
+\r
+        Resource result = graph.newResource();\r
+        graph.claim(result, L0.InstanceOf, null, sr.Spreadsheet);\r
+\r
+        if(name == null) {\r
+            name = NameUtils.findFreshEscapedName(graph, "Sheet", book, L0.ConsistsOf);\r
+        }\r
+        graph.claimLiteral(result, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);\r
+        graph.claim(book, L0.ConsistsOf, L0.PartOf, result);\r
+\r
+        {\r
+            Resource newCell = graph.newResource();\r
+            graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
+            graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Dimensions", Bindings.STRING);\r
+            graph.addLiteral(newCell, sr.Dimensions_fitColumns, sr.Dimensions_fitColumns_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
+            graph.addLiteral(newCell, sr.Dimensions_fitRows, sr.Dimensions_fitRows_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
+            graph.addLiteral(newCell, sr.Dimensions_columnCount, sr.Dimensions_columnCount_Inverse, L0.Integer, 128, Bindings.INTEGER);\r
+            graph.addLiteral(newCell, sr.Dimensions_rowCount, sr.Dimensions_rowCount_Inverse, L0.Integer, 256, Bindings.INTEGER);\r
+            graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
+        }\r
+\r
+        {\r
+            Resource newCell = graph.newResource();\r
+            graph.claim(newCell, L0.InstanceOf, null, sr.Headers);\r
+            graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Headers", Bindings.STRING);\r
+            graph.addLiteral(newCell, sr.Headers_columnLabels, sr.Headers_columnLabels_Inverse, L0.StringArray, colNames, Bindings.STRING_ARRAY);\r
+            graph.addLiteral(newCell, sr.Headers_columnWidths, sr.Headers_columnWidths_Inverse, L0.IntegerArray, colWidths, Bindings.INT_ARRAY);\r
+            graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
+        }\r
+\r
+//        {\r
+//            \r
+//            double[] doubles = new double[10*2];\r
+//            for(int i=0;i<10*2;i++) doubles[i] = i;\r
+//            \r
+//            Resource newCell = graph.newResource();\r
+//            graph.claim(newCell, L0.InstanceOf, null, sr.DoubleArrayCell);\r
+//            graph.addLiteral(newCell, sr.DoubleArrayCell_HasWidth, sr.DoubleArrayCell_HasWidth_Inverse, L0.Integer, 10, Bindings.INTEGER);\r
+//            graph.addLiteral(newCell, sr.HasLocation, sr.HasLocation_Inverse, L0.String, "B2", Bindings.STRING);\r
+//            graph.addLiteral(newCell, sr.DoubleArrayCell_HasDoubleArray, sr.DoubleArrayCell_HasDoubleArray_Inverse, L0.DoubleArray, doubles, Bindings.DOUBLE_ARRAY);\r
+//            graph.claim(result, L0.HasChildVariables, L0.HasChildVariables_Inverse, newCell);\r
+//            \r
+//        }\r
+\r
+        return result;\r
+\r
+    }\r
+\r
+    public static String getStringRepresentation(ReadGraph graph, Resource model, String sheetName, String range) throws DatabaseException {\r
+        Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);\r
+        Variable sheetVariable = null;\r
+        for(Resource book : graph.syncRequest(new ObjectsWithType(configuration, L0.ConsistsOf, SHEET.Book))) {\r
+            for(Resource sheet : graph.syncRequest(new ObjectsWithType(book, L0.ConsistsOf, SHEET.Spreadsheet))) {\r
+                if(sheetName.equals(NameUtils.getSafeName(graph, sheet))) {\r
+                    sheetVariable = Variables.getVariable(graph, sheet);\r
+                }\r
+            }\r
+        }\r
+\r
+        if(sheetVariable == null)\r
+            return null;\r
+\r
+        Variable rangeVariable = sheetVariable.getChild(graph, range);\r
+\r
+\r
+        String[][] rangeCells = rangeVariable.getPropertyValue(graph, SheetVariables.RANGE_CELL_NAMES);\r
+        if(rangeCells == null || rangeCells[0].length <= 1)\r
+            return null;\r
+        else {\r
+            StringBuilder sb = new StringBuilder();\r
+            sb.append("{");\r
+            for(int i = 0; i < rangeCells.length; i++) {\r
+                sb.append("{");\r
+                for(int j = 0; j < rangeCells[i].length; j++) {\r
+                    String valueCell = rangeCells[i][j];\r
+                    Variable cell = sheetVariable.getChild(graph, valueCell);\r
+                    Variant valueVariant = cell.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT);\r
+                    Object valueObject = valueVariant.getValue();\r
+                    sb.append(valueObject.toString());\r
+                    if(j < rangeCells[i].length - 1)\r
+                        sb.append(", ");\r
+                }\r
+                sb.append("}");\r
+                if(i < rangeCells.length - 1)\r
+                    sb.append(", ");\r
+            }\r
+            sb.append("}");\r
+\r
+            return sb.toString();\r
+        }\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/ImportUtils.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/ImportUtils.java
new file mode 100644 (file)
index 0000000..7523bae
--- /dev/null
@@ -0,0 +1,648 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *     Semantum Oy - Bug #4192\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.utils.imports;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.SubMonitor;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.adapter.AdaptException;\r
+import org.simantics.databoard.binding.mutable.Variant;\r
+import org.simantics.databoard.container.DataContainers;\r
+import org.simantics.databoard.container.DataFormatException;\r
+import org.simantics.databoard.container.FormatHandler;\r
+import org.simantics.db.Issue;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.primitiverequest.PossibleResource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.PossibleObjectWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.request.WriteResultRequest;\r
+import org.simantics.db.common.utils.ListUtils;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
+import org.simantics.db.layer0.migration.MigrationState;\r
+import org.simantics.db.layer0.migration.MigrationStateKeys;\r
+import org.simantics.db.layer0.migration.MigrationUtils;\r
+import org.simantics.db.layer0.util.ModelDependenciesBean;\r
+import org.simantics.db.layer0.util.ModelDependency;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.diagram.stubs.DiagramResource;\r
+import org.simantics.issues.common.AllBatchIssueSources;\r
+import org.simantics.issues.common.BatchIssueSource;\r
+import org.simantics.issues.ontology.IssueResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.utils.BatchValidations;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.scl.runtime.function.Function1;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.Activator;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.utils.ModelUtils;\r
+\r
+/**\r
+ * Utilities for importing tg files: Models, Modules and Function libraries\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ImportUtils {\r
+\r
+    /**\r
+     * Null-checked begin task for monitor\r
+     * @param monitor\r
+     * @param taskName\r
+     * @param totalWork\r
+     */\r
+    private static void beginTask(IProgressMonitor monitor, String taskName, int totalWork) {\r
+        if(monitor != null)\r
+            monitor.beginTask(taskName, totalWork);\r
+    }\r
+    \r
+    /**\r
+     * Null-checked sub task for monitor\r
+     * @param monitor\r
+     * @param taskName\r
+     */\r
+    private static void subTask(IProgressMonitor monitor, String taskName) {\r
+        if(monitor != null)\r
+            monitor.subTask(taskName);\r
+    }\r
+    \r
+    /**\r
+     * Null-checked worked command for monitor\r
+     * @param monitor\r
+     * @param work\r
+     */\r
+    private static void worked(IProgressMonitor monitor, int work) {\r
+        if(monitor != null)\r
+            monitor.worked(work);\r
+    }\r
+\r
+\r
+    /**\r
+     * Read a file from hard drive using handlers \r
+     * @param path\r
+     * @param handlers\r
+     * @return IStatus if import failed, otherwise the result is determined by handlers\r
+     */\r
+    public static Object readFile(String path, HashMap<String, FormatHandler<Object>> handlers) {\r
+        Object result = null;\r
+        try {\r
+            File file = new File(path);\r
+            if(!file.isFile()) {\r
+                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import failed: File " + path + " not found", null);\r
+            } else {    \r
+                result = DataContainers.readFile(file, handlers);\r
+            }\r
+        } catch(DataFormatException e) {\r
+            e.printStackTrace();\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import failed", e);              \r
+        } catch(IOException e) {\r
+            e.printStackTrace();\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import failed", e); \r
+        } catch(Exception e) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import failed", e); \r
+        }\r
+        return result;\r
+    }\r
+\r
+\r
+\r
+    /* ********************************* */\r
+    /* *******   IMPORT MODEL  ********* */\r
+    /* ********************************* */\r
+    public static IStatus importModelFile(String path, final IProgressMonitor monitor) throws Exception {\r
+        return importModelFile(path, monitor, null);\r
+    }\r
+    public static IStatus importModelFile(String path, final IProgressMonitor monitor, Function1<Resource,WriteRequest> callback) throws Exception {\r
+        final Resource project = Simantics.getProject().get();\r
+        if(project == null) return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model: project not found", null);\r
+\r
+        beginTask(monitor, "Import model", 10);\r
+        File importFile = new File(path);\r
+        MigrationState state = MigrationUtils.newState();\r
+        state.setProperty(MigrationStateKeys.BASE_URI, SysdynResource.URIs.Migration);\r
+        state.setProperty(MigrationStateKeys.MODEL_FILE, importFile);\r
+        state.setProperty(MigrationStateKeys.UPDATE_DEPENDENCIES, Boolean.FALSE);\r
+\r
+        Session session = Simantics.getSession();\r
+        \r
+        final ModelDependenciesBean dependenciesBean = getModelDependenciesBean(state);\r
+        if(dependenciesBean != null) {\r
+            for(ModelDependency dependency : dependenciesBean.dependencies) {\r
+                Resource existing = session.sync(new PossibleResource(dependency.uri));\r
+                if(existing == null) {\r
+                    MigrationUtils.importSharedOntology(session, dependency.tg);\r
+                }\r
+            }\r
+        }\r
+        \r
+        Resource result = null;\r
+        try {\r
+            result = MigrationUtils.importMigrated(monitor, session, importFile, state, new DefaultPasteImportAdvisor(project), project);\r
+        } catch (Exception e1) {\r
+            e1.printStackTrace();\r
+            throw e1;\r
+        }\r
+\r
+        if(result == null || !(result instanceof Resource)) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: File could not be read.", null);\r
+        } else {\r
+            try {\r
+                final Resource ModelRoot = result;\r
+                IStatus status = Simantics.getSession().syncRequest(new WriteResultRequest<IStatus>()  {\r
+\r
+                    @Override\r
+                    public IStatus perform(WriteGraph graph) throws DatabaseException {\r
+                        if(!graph.isInstanceOf(ModelRoot, SysdynResource.getInstance(graph).SysdynModel)) {\r
+                            // Imported model was not a SysdynModel, display error message.\r
+                            Resource instanceOf = graph.getPossibleObject(ModelRoot, Layer0.getInstance(graph).InstanceOf);\r
+                            String type = "...";\r
+                            if(instanceOf != null)\r
+                                type = NameUtils.getSafeName(graph, instanceOf);\r
+                            else {\r
+                                Resource inheritedFrom = graph.getPossibleObject(ModelRoot, Layer0.getInstance(graph).Inherits);\r
+                                if(inheritedFrom != null)\r
+                                    type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                            }\r
+                            final String ft = type; \r
+                            graph.deny(ModelRoot, Layer0.getInstance(graph).PartOf);\r
+\r
+                            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The imported file is not of type: System Dynamics Model (" + ft +")", null);\r
+                        } else {\r
+                            subTask(monitor, "Add required dependencies");\r
+                            addDependencies(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                            subTask(monitor, "Remove unnecessary issue sources");\r
+                            removeIssueSourcesFromModules(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                            subTask(monitor, "Add enumeration issue source");\r
+                            addEnumerationIssueSource(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                            subTask(monitor, "Add unit issue source");\r
+                            addUnitIssueSource(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                            subTask(monitor, "Add shadow profile");\r
+                            addShadowProfile(graph, ModelRoot);\r
+                            worked(monitor, 1);                \r
+                            subTask(monitor, "Add SCL Main");\r
+                            addSCLMain(graph, ModelRoot);\r
+                            worked(monitor, 1);   \r
+                            subTask(monitor, "Activate model");\r
+                            activateModel(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                        }\r
+                        return null;\r
+\r
+                    }\r
+\r
+\r
+                });\r
+\r
+                if(status != null)\r
+                    return status;\r
+\r
+                subTask(monitor, "Validate model");\r
+                Collection<Resource> confs = Simantics.getSession().syncRequest(new Read<Collection<Resource>>() {\r
+\r
+                    @Override\r
+                    public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                        return findAllConfigurations(graph, ModelRoot);\r
+                    }\r
+\r
+                });\r
+\r
+\r
+                // Batch validate all issue sources after import\r
+                try {\r
+                    for(Resource conf : confs) {\r
+                        /*\r
+                         * This section is copied from BatchValidations.runAll. runAll did\r
+                         * not find module types to validate.\r
+                         */\r
+//                        BatchValidations.runAll(null, mod);\r
+\r
+                        final Collection<BatchIssueSource> validations = session.sync( new AllBatchIssueSources(ModelRoot) );\r
+                        SubMonitor progress = null;\r
+                        if(monitor != null)\r
+                            progress = SubMonitor.convert(monitor, "Validate Model", 100);\r
+                        Collection<Resource> contexts = Collections.singletonList(conf);\r
+                        for(BatchIssueSource bis : validations) {\r
+                            Map<Resource, Set<Issue>> is = BatchValidations.validate(monitor != null ? progress.newChild(90, SubMonitor.SUPPRESS_NONE) : null, bis, contexts);\r
+                            BatchValidations.store(monitor != null ? progress.newChild(10, SubMonitor.SUPPRESS_NONE) : null, bis.getResource(), is);\r
+                        }\r
+                    }\r
+                } catch(Throwable t) {\r
+                    return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Batch validate failed: Model could not be imported.", t);\r
+                } \r
+\r
+                worked(monitor, 1);\r
+\r
+                if(callback != null) {\r
+                    WriteRequest userRequest = callback.apply(result);\r
+                    if(userRequest != null)\r
+                        Simantics.sync(userRequest);\r
+                }\r
+\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", e);\r
+            }\r
+\r
+            return Status.OK_STATUS;\r
+        }\r
+    }\r
+\r
+    private static ModelDependenciesBean getModelDependenciesBean(MigrationState state) throws DatabaseException {\r
+        Map<String,Variant> extensions = state.getProperty(MigrationStateKeys.TG_EXTENSIONS);\r
+        final Variant variant = extensions.get(ModelDependenciesBean.EXTENSION_KEY);\r
+        if (variant != null) {\r
+            try {\r
+                return (ModelDependenciesBean) variant.getValue(ModelDependenciesBean.BINDING);\r
+            } catch (AdaptException e) {\r
+                e.printStackTrace();\r
+                //Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Could not get model dependencies bean.", e));\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+\r
+    protected static void addSCLMain(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        \r
+        Collection<Resource> SCLModules = graph.syncRequest(new ObjectsWithType(modelRoot, L0.ConsistsOf, L0.SCLModule));\r
+        \r
+        boolean hasIt = false;\r
+        \r
+        for(Resource r : SCLModules) {\r
+            if("SCLMain".equals(NameUtils.getSafeName(graph, r))) {\r
+                hasIt = true;\r
+                break;\r
+            }\r
+        }\r
+        \r
+        if(!hasIt) {\r
+            ModelUtils.createSCLMain(graph, modelRoot);\r
+        }\r
+        \r
+    }\r
+\r
+    private static void removeIssueSourcesFromModules(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        IssueResource ISSUE = IssueResource.getInstance(graph);\r
+\r
+        for(Resource m : findAllModelsAndModules(graph, modelRoot)) {\r
+            if(m.equals(modelRoot))\r
+                continue;\r
+\r
+            // Module may contain issue sources due to legacy reasons. Remove these. \r
+            for(Resource issueSource : graph.syncRequest(new ObjectsWithType(m, L0.ConsistsOf, ISSUE.IssueSource))) {\r
+                // Issues are created to virtual graphs, so they should not need to be removed. Just in case they are created, remove them first\r
+                for(Resource issue : graph.getObjects(issueSource, ISSUE.IssueSource_Manages)) {\r
+                    RemoverUtil.remove(graph, issue);\r
+                }\r
+\r
+                // finally remove the issue source\r
+                RemoverUtil.remove(graph, issueSource);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    private static void activateModel(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Layer0X L0X = Layer0X.getInstance(graph);\r
+        if(!graph.hasStatement(modelRoot, L0X.IsActivatedBy)) {\r
+            Resource project = graph.getPossibleObject(modelRoot, L0.PartOf);\r
+            if(project != null) {\r
+                graph.claim(modelRoot, L0X.IsActivatedBy, project);\r
+            }\r
+        }\r
+    }\r
+\r
+    private static void addDependencies(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+\r
+        ArrayList<String> links = new ArrayList<String>();\r
+        for(Resource link : graph.getObjects(modelRoot, L0.IsLinkedTo))\r
+            links.add(graph.getURI(link));\r
+\r
+        if(!links.contains("http://www.semantum.fi/Simupedia-1.0")) {\r
+            Resource simupedia = graph.getPossibleResource("http://www.semantum.fi/Simupedia-1.0");\r
+            if(simupedia != null)\r
+                graph.claim(modelRoot, L0.IsLinkedTo, simupedia);\r
+        }\r
+\r
+        if(!links.contains("http://www.simantics.org/SelectionView-1.2")) {\r
+            Resource selectionView = graph.getPossibleResource("http://www.simantics.org/SelectionView-1.2");\r
+            if(selectionView != null)\r
+                graph.claim(modelRoot, L0.IsLinkedTo, selectionView);\r
+        }\r
+\r
+        if(!links.contains("http://www.semantum.fi/SimupediaWorkbench-1.0")) {\r
+            Resource simupediaWb = graph.getPossibleResource("http://www.semantum.fi/SimupediaWorkbench-1.0");\r
+            if(simupediaWb != null)\r
+                graph.claim(modelRoot, L0.IsLinkedTo, simupediaWb);\r
+        }\r
+        \r
+        if(!links.contains("http://www.simantics.org/Documentation-1.2")) {\r
+            Resource documentation = graph.getPossibleResource("http://www.simantics.org/Documentation-1.2");\r
+            if(documentation != null)\r
+                graph.claim(modelRoot, L0.IsLinkedTo, documentation);\r
+        }\r
+    }\r
+\r
+    private static void addEnumerationIssueSource(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Layer0X L0X = Layer0X.getInstance(graph); \r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Collection<Resource> enumerationIssueSources = graph.syncRequest(new ObjectsWithType(modelRoot, L0.ConsistsOf, sr.Validations_Enumerations_EnumerationIssueSource));\r
+        if(enumerationIssueSources.isEmpty()) {\r
+            GraphUtils.create2(graph,\r
+                    sr.Validations_Enumerations_EnumerationIssueSource,\r
+                    L0X.IsActivatedBy, modelRoot,\r
+                    L0.PartOf, modelRoot\r
+                    );  \r
+        }   \r
+    }\r
+    \r
+\r
+    private static void addUnitIssueSource(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Layer0X L0X = Layer0X.getInstance(graph); \r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Collection<Resource> unitIssueSources = graph.syncRequest(new ObjectsWithType(modelRoot, L0.ConsistsOf, sr.Validations_Units_UnitIssueSource));\r
+        if(unitIssueSources.isEmpty()) {\r
+            GraphUtils.create2(graph,\r
+                    sr.Validations_Units_UnitIssueSource,\r
+                    L0X.IsActivatedBy, modelRoot,\r
+                    L0.PartOf, modelRoot,\r
+                    IssueResource.getInstance(graph).IssueSource_active, false\r
+                    );  \r
+        }    \r
+    }\r
+    \r
+    private static void addShadowProfile(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        DiagramResource DIA = DiagramResource.getInstance(graph);\r
+        SysdynResource SR = SysdynResource.getInstance(graph);\r
+        Resource defaultProfile = graph.syncRequest(new PossibleObjectWithType(modelRoot, Layer0.getInstance(graph).ConsistsOf, SR.DefaultProfile));\r
+        if(defaultProfile != null) {\r
+            Resource entryList = graph.getPossibleObject(defaultProfile, DIA.HasEntries);\r
+            if(entryList != null) {\r
+                List<Resource> entries = ListUtils.toList(graph, entryList);\r
+                if(entries != null && !entries.contains(SR.Profiles_ShadowVisualizations)) {\r
+                    ListUtils.insertBack(graph, entryList, Collections.singletonList(SR.Profiles_ShadowVisualizations));\r
+                }\r
+            }\r
+            \r
+        }\r
+    }\r
+\r
+    private static Collection<Resource> findAllConfigurations(ReadGraph graph, Resource modelRoot) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        StructuralResource2 SR2 = StructuralResource2.getInstance(graph);\r
+        Collection<Resource> modulesAndModels = findAllModelsAndModules(graph, modelRoot);\r
+        Collection<Resource> configurations = new ArrayList<Resource>();\r
+\r
+        for(Resource r : modulesAndModels) {\r
+            if(graph.isInheritedFrom(r, sr.Module)) {\r
+                configurations.add(graph.getPossibleObject(r, SR2.IsDefinedBy));\r
+            } else if(graph.isInstanceOf(r, sr.SysdynModel)) {\r
+                configurations.add(graph.getPossibleObject(modelRoot, SimulationResource.getInstance(graph).HasConfiguration));\r
+            }\r
+        }\r
+\r
+        return configurations;\r
+    }\r
+\r
+    private static Collection<Resource> findAllModelsAndModules(ReadGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Collection<Resource> modelsAndModules = new ArrayList<Resource>();\r
+        modelsAndModules.add(modelRoot);\r
+\r
+        for(Resource r : graph.getObjects(modelRoot, L0.ConsistsOf)) {\r
+            if(graph.isInheritedFrom(r, sr.Module)) {\r
+                modelsAndModules.add(r);\r
+            }\r
+        }\r
+\r
+        return modelsAndModules;\r
+    }\r
+\r
+    /* ********************************* */\r
+    /* *******  IMPORT MODULE  ********* */\r
+    /* ********************************* */\r
+    public static IStatus importModuleFile(final Resource model, String path, final IProgressMonitor monitor) {\r
+        beginTask(monitor, "Import Module", 3);\r
+\r
+        MigrationState state = MigrationUtils.newState();\r
+        state.setProperty(MigrationStateKeys.BASE_URI, SysdynResource.URIs.Migration);\r
+        state.setProperty(MigrationStateKeys.UPDATE_DEPENDENCIES, Boolean.FALSE);\r
+\r
+        Resource result = null;\r
+        try {\r
+            result = MigrationUtils.importMigrated(monitor, Simantics.getSession(), new File(path), state, new DefaultPasteImportAdvisor(model), model);\r
+        } catch (Exception e1) {\r
+            e1.printStackTrace();\r
+        }\r
+\r
+\r
+        if(result == null) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import module failed: Module could not be imported.", null);\r
+        } else {\r
+            final Resource ModuleRoot = result;\r
+            // Check that the imported file actually was a module. Display error message otherwise.\r
+            try {\r
+                subTask(monitor, "Validate model");\r
+                IStatus status = Simantics.getSession().syncRequest(new WriteResultRequest<IStatus>()  {\r
+\r
+                    @Override\r
+                    public IStatus perform(WriteGraph graph) throws DatabaseException {\r
+                        if(!graph.isInheritedFrom(ModuleRoot, SysdynResource.getInstance(graph).Module)) {\r
+                            Resource instanceOf = graph.getPossibleObject(ModuleRoot, Layer0.getInstance(graph).InstanceOf);\r
+                            String type = "...";\r
+                            if(instanceOf != null)\r
+                                type = NameUtils.getSafeName(graph, instanceOf);\r
+                            else {\r
+                                Resource inheritedFrom = graph.getPossibleObject(ModuleRoot, Layer0.getInstance(graph).Inherits);\r
+                                if(inheritedFrom != null)\r
+                                    type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                            }\r
+                            final String ft = type; \r
+                            graph.deny(ModuleRoot, Layer0.getInstance(graph).PartOf);\r
+\r
+                            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The imported file is not of type: System Dynamics Module (" + ft +")", null);\r
+                        } \r
+                        return null;\r
+                    }\r
+                });\r
+\r
+                if(status != null)\r
+                    return status;\r
+                worked(monitor, 1);\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+\r
+        }\r
+\r
+        return Status.OK_STATUS;\r
+    }\r
+\r
+\r
+\r
+    /* ********************************* */\r
+    /* ***  IMPORT FUNCTION LIBRARY  *** */\r
+    /* ********************************* */\r
+\r
+    public static IStatus importFunctionLibrary(final Resource functionLibrary, final String path, final IProgressMonitor monitor) {\r
+        beginTask(monitor, "Import Module", 3);\r
+\r
+        // Ensure that shared functions ontology exists\r
+        ensureSharedOntologies();\r
+        \r
+        MigrationState state = MigrationUtils.newState();\r
+        state.setProperty(MigrationStateKeys.BASE_URI, SysdynResource.URIs.Migration);\r
+        state.setProperty(MigrationStateKeys.UPDATE_DEPENDENCIES, Boolean.FALSE);\r
+\r
+        Resource result = null;\r
+        try {\r
+            result = MigrationUtils.importMigrated(monitor, Simantics.getSession(), new File(path), state, new DefaultPasteImportAdvisor(functionLibrary), functionLibrary);\r
+        } catch (Exception e1) {\r
+            e1.printStackTrace();\r
+        }\r
+\r
+        if(result == null) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import Function library failed: Function library not be imported.", null);\r
+        } else {\r
+            final Resource FunctionLibraryRoot = (Resource) result;\r
+            // Link the imported library to the selected resource (functionLibrary)\r
+            try {\r
+                subTask(monitor, "Validate model");\r
+                IStatus status = Simantics.getSession().syncRequest(new WriteResultRequest<IStatus>()  {\r
+\r
+                    /**\r
+                     * Link the imported library to the selected resource (functionLibrary)\r
+                     * The imported library can be either SysdynModelicaFunctionLibrary or SysdynFunctionOntology\r
+                     */\r
+                    @Override\r
+                    public IStatus perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        // Case: SharedFunctionOntology. Link to SharedOntologies\r
+                        if(graph.isInstanceOf(FunctionLibraryRoot, SysdynResource.getInstance(graph).SharedFunctionOntology)) {\r
+                            Resource library = graph.getResource("http://SharedOntologies");\r
+                            if(!graph.hasStatement(library, l0.ConsistsOf, FunctionLibraryRoot)) {\r
+                                graph.claim(library, l0.ConsistsOf, FunctionLibraryRoot);\r
+                            }\r
+\r
+                            // Link model to the shared library\r
+                            SysdynResource sr = SysdynResource.getInstance(graph);\r
+                            Resource model = functionLibrary;\r
+                            while(!graph.isInstanceOf(model, sr.SysdynModel) && graph.isInstanceOf(model, l0.Ontology))\r
+                                model = graph.getSingleObject(model, l0.PartOf);\r
+                            if(graph.isInstanceOf(model, sr.SysdynModel)) {\r
+                                graph.claim(model, l0.IsLinkedTo, l0.IsLinkedTo_Inverse, FunctionLibraryRoot);\r
+                            }\r
+\r
+                            // Case: not SharedFunctionOntology or SysdynModelicaFunctionLibrary. \r
+                        } else if(!graph.isInstanceOf(FunctionLibraryRoot, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary)) {\r
+                            Resource instanceOf = graph.getPossibleObject(FunctionLibraryRoot,l0.InstanceOf);\r
+                            String type = "...";\r
+                            if(instanceOf != null)\r
+                                type = NameUtils.getSafeName(graph, instanceOf);\r
+                            else {\r
+                                Resource inheritedFrom = graph.getPossibleObject(FunctionLibraryRoot, l0.Inherits);\r
+                                if(inheritedFrom != null)\r
+                                    type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                            }\r
+                            final String ft = type; \r
+\r
+                            // Remove the functionLibrary ConsistsOf root relation\r
+                            graph.deny(FunctionLibraryRoot, l0.PartOf);\r
+\r
+                            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The imported file is not of type: Function Library (" + ft +")", null);\r
+                        }\r
+                        return null;\r
+\r
+\r
+                    }\r
+                });\r
+\r
+                if(status != null)\r
+                    return status;\r
+                worked(monitor, 1);\r
+\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+\r
+        return Status.OK_STATUS;\r
+    }\r
+\r
+    private static void ensureSharedOntologies() {\r
+        // Make sure the "http://SharedOntologies resource exists\r
+        try {\r
+            Boolean hasSharedOntologies;\r
+            hasSharedOntologies = Simantics.getSession().syncRequest(new Read<Boolean>() {\r
+\r
+                @Override\r
+                public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                    try {\r
+                        graph.getResource("http://SharedOntologies");\r
+                    } catch (ResourceNotFoundException e) {\r
+                        return false;\r
+                    }       \r
+                    return true;\r
+                }\r
+            });\r
+\r
+            if(!hasSharedOntologies) {\r
+                Simantics.getSession().syncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        GraphUtils.create2(graph, l0.Library, \r
+                                l0.HasName, "SharedOntologies",\r
+                                l0.PartOf, graph.getResource("http:/"));\r
+                    }\r
+                });\r
+\r
+            }\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/SysdynFunctionLibraryImportAdvisor.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/SysdynFunctionLibraryImportAdvisor.java
new file mode 100644 (file)
index 0000000..3373d68
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.utils.imports;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteOnlyGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
+import org.simantics.graph.representation.Root;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Import advisor for importing function libraries to SysDyn\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {\r
+    \r
+    public SysdynFunctionLibraryImportAdvisor(Resource library) {\r
+        super(library);\r
+    }\r
+    \r
+    @Override\r
+    public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {\r
+        // Change the library to http://SharedOntologies, if the imported library is of type SharedFunctionOntology\r
+        if(root.type.equals(SysdynResource.URIs.SharedFunctionOntology)) {\r
+            try {\r
+                library = graph.getResource("http://SharedOntologies");\r
+            } catch (ResourceNotFoundException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {\r
+        Layer0 l0 = graph.getService(Layer0.class);\r
+        this.root = graph.newResource();\r
+        graph.claim(library, l0.ConsistsOf, l0.PartOf, this.root);\r
+        String name = root.name;\r
+        String newName = nameMappings.get(name);\r
+        graph.addLiteral(this.root, l0.HasName, l0.NameOf, l0.String, newName, Bindings.STRING);\r
+        return this.root;\r
+\r
+    }\r
+        \r
+}
\ No newline at end of file
diff --git a/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/SysdynImportFormatHandler.java b/1.8/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/imports/SysdynImportFormatHandler.java
new file mode 100644 (file)
index 0000000..260c058
--- /dev/null
@@ -0,0 +1,111 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.utils.imports;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.binding.Binding;\r
+import org.simantics.databoard.container.DataContainer;\r
+import org.simantics.databoard.container.DataFormatException;\r
+import org.simantics.databoard.container.FormatHandler;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
+import org.simantics.db.layer0.migration.MigrationState;\r
+import org.simantics.db.layer0.migration.MigrationStateKeys;\r
+import org.simantics.db.layer0.migration.MigrationStep;\r
+import org.simantics.db.layer0.migration.MigrationUtils;\r
+import org.simantics.graph.representation.TransferableGraph1;\r
+import org.simantics.sysdyn.Activator;\r
+\r
+/**\r
+ * Handler for migrating a tg and importing it to database\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynImportFormatHandler implements FormatHandler<Object> {\r
+    \r
+    private final Resource parent;\r
+    private final IProgressMonitor monitor;\r
+    private final String migrationURI;\r
+    private final DefaultPasteImportAdvisor importAdvisor;\r
+    \r
+    /**\r
+     * Works 2 (2 * 1) in the monitor\r
+     * @param parent\r
+     * @param migrationURI\r
+     * @param monitor\r
+     */\r
+    public SysdynImportFormatHandler(Resource parent, String migrationURI, IProgressMonitor monitor) {\r
+        this(parent, migrationURI, monitor, null);\r
+    }\r
+    \r
+    public SysdynImportFormatHandler(Resource parent, String migrationURI, IProgressMonitor monitor,\r
+            DefaultPasteImportAdvisor importAdvisor) {\r
+        assert(parent != null);\r
+        assert(migrationURI != null);\r
+        this.parent = parent;\r
+        this.monitor = monitor;\r
+        this.migrationURI = migrationURI;\r
+        this.importAdvisor = importAdvisor;\r
+    }\r
+\r
+    private void subTask(String taskName) {\r
+        if(monitor != null)\r
+            monitor.subTask(taskName);\r
+    }\r
+    \r
+    private void worked(int work) {\r
+        if(monitor != null)\r
+            monitor.worked(work);\r
+    }\r
+    \r
+    @Override\r
+    public Binding getBinding() {\r
+        return TransferableGraph1.BINDING;\r
+    }\r
+\r
+    @Override\r
+    public Object process(DataContainer container) throws DataFormatException {\r
+        DefaultPasteImportAdvisor ia = importAdvisor != null ? importAdvisor : new DefaultPasteImportAdvisor(parent);\r
+        try {\r
+            subTask("Migrate");\r
+            Session session = Simantics.getSession();\r
+            TransferableGraph1 tg = (TransferableGraph1)container.content.getValue();\r
+\r
+            MigrationStep step = MigrationUtils.getStep(session, migrationURI);\r
+            MigrationState state = MigrationUtils.newState();\r
+            state.setProperty(MigrationStateKeys.CURRENT_TG, tg);\r
+            step.applyTo(monitor, session, state);\r
+//            tg = state.getProperty(MigrationStateKeys.CURRENT_TG);\r
+\r
+            worked(1);\r
+            subTask("Import");\r
+            \r
+//            DefaultPasteHandler.defaultExecute(tg, parent, ia);\r
+            MigrationUtils.importTo(monitor, session, state, parent, ia);\r
+            worked(1);\r
+            \r
+            Resource result = state.getProperty(MigrationStateKeys.CURRENT_RESOURCE);\r
+            if(result == null)\r
+                result = ia.getRoot();\r
+            \r
+            return result;\r
+\r
+        } catch (Exception e) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import module failed", e);\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/1.8/org.simantics.sysdyn/testModels/MaintenanceModel_2012-12-03.tg b/1.8/org.simantics.sysdyn/testModels/MaintenanceModel_2012-12-03.tg
new file mode 100644 (file)
index 0000000..e869a12
Binary files /dev/null and b/1.8/org.simantics.sysdyn/testModels/MaintenanceModel_2012-12-03.tg differ
diff --git a/1.8/org.simantics.sysdyn/testModels/Model1412Health.tg b/1.8/org.simantics.sysdyn/testModels/Model1412Health.tg
new file mode 100644 (file)
index 0000000..8635b39
Binary files /dev/null and b/1.8/org.simantics.sysdyn/testModels/Model1412Health.tg differ
diff --git a/1.8/org.simantics.sysdyn/testModels/WorkModel_2012-12-03.tg b/1.8/org.simantics.sysdyn/testModels/WorkModel_2012-12-03.tg
new file mode 100644 (file)
index 0000000..781a161
Binary files /dev/null and b/1.8/org.simantics.sysdyn/testModels/WorkModel_2012-12-03.tg differ
diff --git a/1.8/org.simantics.sysdyn/testModels/openprod_demo_2012-12-03.tg b/1.8/org.simantics.sysdyn/testModels/openprod_demo_2012-12-03.tg
new file mode 100644 (file)
index 0000000..bf98e97
Binary files /dev/null and b/1.8/org.simantics.sysdyn/testModels/openprod_demo_2012-12-03.tg differ
diff --git a/1.8/org.simantics.sysdyn/testModels/references.txt b/1.8/org.simantics.sysdyn/testModels/references.txt
new file mode 100644 (file)
index 0000000..b35e14b
--- /dev/null
@@ -0,0 +1,5 @@
+The models in this folder are made by Sampsa Ruutu (openprod_demo), \r
+Tero Jokinen (MaintenanceModel, WorkModel), and Ossi Koivula \r
+(HealthModel). Health model and openprod_demo seem to be broken in \r
+newer versions of the tool. The models are not distributed with the \r
+installer, even though they're probably public. 
\ No newline at end of file
diff --git a/1.8/setup/sysdyn.ism b/1.8/setup/sysdyn.ism
new file mode 100644 (file)
index 0000000..03f156e
--- /dev/null
@@ -0,0 +1,5128 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r
+<?xml-stylesheet type="text/xsl" href="is.xsl" ?>\r
+<!DOCTYPE msi [\r
+   <!ELEMENT msi   (summary,table*)>\r
+   <!ATTLIST msi version    CDATA #REQUIRED>\r
+   <!ATTLIST msi xmlns:dt   CDATA #IMPLIED\r
+                 codepage   CDATA #IMPLIED\r
+                 compression (MSZIP|LZX|none) "LZX">\r
+   \r
+   <!ELEMENT summary       (codepage?,title?,subject?,author?,keywords?,comments?,\r
+                            template,lastauthor?,revnumber,lastprinted?,\r
+                            createdtm?,lastsavedtm?,pagecount,wordcount,\r
+                            charcount?,appname?,security?)>\r
+                            \r
+   <!ELEMENT codepage      (#PCDATA)>\r
+   <!ELEMENT title         (#PCDATA)>\r
+   <!ELEMENT subject       (#PCDATA)>\r
+   <!ELEMENT author        (#PCDATA)>\r
+   <!ELEMENT keywords      (#PCDATA)>\r
+   <!ELEMENT comments      (#PCDATA)>\r
+   <!ELEMENT template      (#PCDATA)>\r
+   <!ELEMENT lastauthor    (#PCDATA)>\r
+   <!ELEMENT revnumber     (#PCDATA)>\r
+   <!ELEMENT lastprinted   (#PCDATA)>\r
+   <!ELEMENT createdtm     (#PCDATA)>\r
+   <!ELEMENT lastsavedtm   (#PCDATA)>\r
+   <!ELEMENT pagecount     (#PCDATA)>\r
+   <!ELEMENT wordcount     (#PCDATA)>\r
+   <!ELEMENT charcount     (#PCDATA)>\r
+   <!ELEMENT appname       (#PCDATA)>\r
+   <!ELEMENT security      (#PCDATA)>                            \r
+                                \r
+   <!ELEMENT table         (col+,row*)>\r
+   <!ATTLIST table\r
+                name        CDATA #REQUIRED>\r
+\r
+   <!ELEMENT col           (#PCDATA)>\r
+   <!ATTLIST col\r
+                 key       (yes|no) #IMPLIED\r
+                 def       CDATA #IMPLIED>\r
+                 \r
+   <!ELEMENT row            (td+)>\r
+   \r
+   <!ELEMENT td             (#PCDATA)>\r
+   <!ATTLIST td\r
+                 href       CDATA #IMPLIED\r
+                 dt:dt     (string|bin.base64) #IMPLIED\r
+                 md5        CDATA #IMPLIED>\r
+]>\r
+<msi version="2.0" xmlns:dt="urn:schemas-microsoft-com:datatypes" codepage="65001">\r
+       \r
+       <summary>\r
+               <codepage>1252</codepage>\r
+               <title>Installation Database</title>\r
+               <subject>Blank Project Template</subject>\r
+               <author>##COMPANY_NAME##</author>\r
+               <keywords>Installer,MSI,Database</keywords>\r
+               <comments>Contact:  Your local administrator</comments>\r
+               <template>;1033</template>\r
+               <lastauthor>Administrator</lastauthor>\r
+               <revnumber>{2AA85B8E-AD39-4CC9-8003-4EA7B9B12CF7}</revnumber>\r
+               <lastprinted/>\r
+               <createdtm>06/21/1999 16:00</createdtm>\r
+               <lastsavedtm>07/14/2000 19:50</lastsavedtm>\r
+               <pagecount>200</pagecount>\r
+               <wordcount>0</wordcount>\r
+               <charcount/>\r
+               <appname>InstallShield</appname>\r
+               <security>1</security>\r
+       </summary>\r
+       \r
+       <table name="ActionText">\r
+               <col key="yes" def="s72">Action</col>\r
+               <col def="L64">Description</col>\r
+               <col def="L128">Template</col>\r
+               <row><td>Advertise</td><td>##IDS_ACTIONTEXT_Advertising##</td><td/></row>\r
+               <row><td>AllocateRegistrySpace</td><td>##IDS_ACTIONTEXT_AllocatingRegistry##</td><td>##IDS_ACTIONTEXT_FreeSpace##</td></row>\r
+               <row><td>AppSearch</td><td>##IDS_ACTIONTEXT_SearchInstalled##</td><td>##IDS_ACTIONTEXT_PropertySignature##</td></row>\r
+               <row><td>BindImage</td><td>##IDS_ACTIONTEXT_BindingExes##</td><td>##IDS_ACTIONTEXT_File##</td></row>\r
+               <row><td>CCPSearch</td><td>##IDS_ACTIONTEXT_UnregisterModules##</td><td/></row>\r
+               <row><td>CostFinalize</td><td>##IDS_ACTIONTEXT_ComputingSpace3##</td><td/></row>\r
+               <row><td>CostInitialize</td><td>##IDS_ACTIONTEXT_ComputingSpace##</td><td/></row>\r
+               <row><td>CreateFolders</td><td>##IDS_ACTIONTEXT_CreatingFolders##</td><td>##IDS_ACTIONTEXT_Folder##</td></row>\r
+               <row><td>CreateShortcuts</td><td>##IDS_ACTIONTEXT_CreatingShortcuts##</td><td>##IDS_ACTIONTEXT_Shortcut##</td></row>\r
+               <row><td>DeleteServices</td><td>##IDS_ACTIONTEXT_DeletingServices##</td><td>##IDS_ACTIONTEXT_Service##</td></row>\r
+               <row><td>DuplicateFiles</td><td>##IDS_ACTIONTEXT_CreatingDuplicate##</td><td>##IDS_ACTIONTEXT_FileDirectorySize##</td></row>\r
+               <row><td>FileCost</td><td>##IDS_ACTIONTEXT_ComputingSpace2##</td><td/></row>\r
+               <row><td>FindRelatedProducts</td><td>##IDS_ACTIONTEXT_SearchForRelated##</td><td>##IDS_ACTIONTEXT_FoundApp##</td></row>\r
+               <row><td>GenerateScript</td><td>##IDS_ACTIONTEXT_GeneratingScript##</td><td>##IDS_ACTIONTEXT_1##</td></row>\r
+               <row><td>ISLockPermissionsCost</td><td>##IDS_ACTIONTEXT_ISLockPermissionsCost##</td><td/></row>\r
+               <row><td>ISLockPermissionsInstall</td><td>##IDS_ACTIONTEXT_ISLockPermissionsInstall##</td><td/></row>\r
+               <row><td>InstallAdminPackage</td><td>##IDS_ACTIONTEXT_CopyingNetworkFiles##</td><td>##IDS_ACTIONTEXT_FileDirSize##</td></row>\r
+               <row><td>InstallFiles</td><td>##IDS_ACTIONTEXT_CopyingNewFiles##</td><td>##IDS_ACTIONTEXT_FileDirSize2##</td></row>\r
+               <row><td>InstallODBC</td><td>##IDS_ACTIONTEXT_InstallODBC##</td><td/></row>\r
+               <row><td>InstallSFPCatalogFile</td><td>##IDS_ACTIONTEXT_InstallingSystemCatalog##</td><td>##IDS_ACTIONTEXT_FileDependencies##</td></row>\r
+               <row><td>InstallServices</td><td>##IDS_ACTIONTEXT_InstallServices##</td><td>##IDS_ACTIONTEXT_Service2##</td></row>\r
+               <row><td>InstallValidate</td><td>##IDS_ACTIONTEXT_Validating##</td><td/></row>\r
+               <row><td>LaunchConditions</td><td>##IDS_ACTIONTEXT_EvaluateLaunchConditions##</td><td/></row>\r
+               <row><td>MigrateFeatureStates</td><td>##IDS_ACTIONTEXT_MigratingFeatureStates##</td><td>##IDS_ACTIONTEXT_Application##</td></row>\r
+               <row><td>MoveFiles</td><td>##IDS_ACTIONTEXT_MovingFiles##</td><td>##IDS_ACTIONTEXT_FileDirSize3##</td></row>\r
+               <row><td>PatchFiles</td><td>##IDS_ACTIONTEXT_PatchingFiles##</td><td>##IDS_ACTIONTEXT_FileDirSize4##</td></row>\r
+               <row><td>ProcessComponents</td><td>##IDS_ACTIONTEXT_UpdateComponentRegistration##</td><td/></row>\r
+               <row><td>PublishComponents</td><td>##IDS_ACTIONTEXT_PublishingQualifiedComponents##</td><td>##IDS_ACTIONTEXT_ComponentIDQualifier##</td></row>\r
+               <row><td>PublishFeatures</td><td>##IDS_ACTIONTEXT_PublishProductFeatures##</td><td>##IDS_ACTIONTEXT_FeatureColon##</td></row>\r
+               <row><td>PublishProduct</td><td>##IDS_ACTIONTEXT_PublishProductInfo##</td><td/></row>\r
+               <row><td>RMCCPSearch</td><td>##IDS_ACTIONTEXT_SearchingQualifyingProducts##</td><td/></row>\r
+               <row><td>RegisterClassInfo</td><td>##IDS_ACTIONTEXT_RegisterClassServer##</td><td>##IDS_ACTIONTEXT_ClassId##</td></row>\r
+               <row><td>RegisterComPlus</td><td>##IDS_ACTIONTEXT_RegisteringComPlus##</td><td>##IDS_ACTIONTEXT_AppIdAppTypeRSN##</td></row>\r
+               <row><td>RegisterExtensionInfo</td><td>##IDS_ACTIONTEXT_RegisterExtensionServers##</td><td>##IDS_ACTIONTEXT_Extension2##</td></row>\r
+               <row><td>RegisterFonts</td><td>##IDS_ACTIONTEXT_RegisterFonts##</td><td>##IDS_ACTIONTEXT_Font##</td></row>\r
+               <row><td>RegisterMIMEInfo</td><td>##IDS_ACTIONTEXT_RegisterMimeInfo##</td><td>##IDS_ACTIONTEXT_ContentTypeExtension##</td></row>\r
+               <row><td>RegisterProduct</td><td>##IDS_ACTIONTEXT_RegisteringProduct##</td><td>##IDS_ACTIONTEXT_1b##</td></row>\r
+               <row><td>RegisterProgIdInfo</td><td>##IDS_ACTIONTEXT_RegisteringProgIdentifiers##</td><td>##IDS_ACTIONTEXT_ProgID2##</td></row>\r
+               <row><td>RegisterTypeLibraries</td><td>##IDS_ACTIONTEXT_RegisterTypeLibs##</td><td>##IDS_ACTIONTEXT_LibId##</td></row>\r
+               <row><td>RegisterUser</td><td>##IDS_ACTIONTEXT_RegUser##</td><td>##IDS_ACTIONTEXT_1c##</td></row>\r
+               <row><td>RemoveDuplicateFiles</td><td>##IDS_ACTIONTEXT_RemovingDuplicates##</td><td>##IDS_ACTIONTEXT_FileDir##</td></row>\r
+               <row><td>RemoveEnvironmentStrings</td><td>##IDS_ACTIONTEXT_UpdateEnvironmentStrings##</td><td>##IDS_ACTIONTEXT_NameValueAction2##</td></row>\r
+               <row><td>RemoveExistingProducts</td><td>##IDS_ACTIONTEXT_RemoveApps##</td><td>##IDS_ACTIONTEXT_AppCommandLine##</td></row>\r
+               <row><td>RemoveFiles</td><td>##IDS_ACTIONTEXT_RemovingFiles##</td><td>##IDS_ACTIONTEXT_FileDir2##</td></row>\r
+               <row><td>RemoveFolders</td><td>##IDS_ACTIONTEXT_RemovingFolders##</td><td>##IDS_ACTIONTEXT_Folder1##</td></row>\r
+               <row><td>RemoveIniValues</td><td>##IDS_ACTIONTEXT_RemovingIni##</td><td>##IDS_ACTIONTEXT_FileSectionKeyValue##</td></row>\r
+               <row><td>RemoveODBC</td><td>##IDS_ACTIONTEXT_RemovingODBC##</td><td/></row>\r
+               <row><td>RemoveRegistryValues</td><td>##IDS_ACTIONTEXT_RemovingRegistry##</td><td>##IDS_ACTIONTEXT_KeyName##</td></row>\r
+               <row><td>RemoveShortcuts</td><td>##IDS_ACTIONTEXT_RemovingShortcuts##</td><td>##IDS_ACTIONTEXT_Shortcut1##</td></row>\r
+               <row><td>Rollback</td><td>##IDS_ACTIONTEXT_RollingBack##</td><td>##IDS_ACTIONTEXT_1d##</td></row>\r
+               <row><td>RollbackCleanup</td><td>##IDS_ACTIONTEXT_RemovingBackup##</td><td>##IDS_ACTIONTEXT_File2##</td></row>\r
+               <row><td>SelfRegModules</td><td>##IDS_ACTIONTEXT_RegisteringModules##</td><td>##IDS_ACTIONTEXT_FileFolder##</td></row>\r
+               <row><td>SelfUnregModules</td><td>##IDS_ACTIONTEXT_UnregisterModules##</td><td>##IDS_ACTIONTEXT_FileFolder2##</td></row>\r
+               <row><td>SetODBCFolders</td><td>##IDS_ACTIONTEXT_InitializeODBCDirs##</td><td/></row>\r
+               <row><td>StartServices</td><td>##IDS_ACTIONTEXT_StartingServices##</td><td>##IDS_ACTIONTEXT_Service3##</td></row>\r
+               <row><td>StopServices</td><td>##IDS_ACTIONTEXT_StoppingServices##</td><td>##IDS_ACTIONTEXT_Service4##</td></row>\r
+               <row><td>UnmoveFiles</td><td>##IDS_ACTIONTEXT_RemovingMoved##</td><td>##IDS_ACTIONTEXT_FileDir3##</td></row>\r
+               <row><td>UnpublishComponents</td><td>##IDS_ACTIONTEXT_UnpublishQualified##</td><td>##IDS_ACTIONTEXT_ComponentIdQualifier2##</td></row>\r
+               <row><td>UnpublishFeatures</td><td>##IDS_ACTIONTEXT_UnpublishProductFeatures##</td><td>##IDS_ACTIONTEXT_Feature##</td></row>\r
+               <row><td>UnpublishProduct</td><td>##IDS_ACTIONTEXT_UnpublishingProductInfo##</td><td/></row>\r
+               <row><td>UnregisterClassInfo</td><td>##IDS_ACTIONTEXT_UnregisterClassServers##</td><td>##IDS_ACTIONTEXT_ClsID##</td></row>\r
+               <row><td>UnregisterComPlus</td><td>##IDS_ACTIONTEXT_UnregisteringComPlus##</td><td>##IDS_ACTIONTEXT_AppId##</td></row>\r
+               <row><td>UnregisterExtensionInfo</td><td>##IDS_ACTIONTEXT_UnregisterExtensionServers##</td><td>##IDS_ACTIONTEXT_Extension##</td></row>\r
+               <row><td>UnregisterFonts</td><td>##IDS_ACTIONTEXT_UnregisteringFonts##</td><td>##IDS_ACTIONTEXT_Font2##</td></row>\r
+               <row><td>UnregisterMIMEInfo</td><td>##IDS_ACTIONTEXT_UnregisteringMimeInfo##</td><td>##IDS_ACTIONTEXT_ContentTypeExtension2##</td></row>\r
+               <row><td>UnregisterProgIdInfo</td><td>##IDS_ACTIONTEXT_UnregisteringProgramIds##</td><td>##IDS_ACTIONTEXT_ProgID##</td></row>\r
+               <row><td>UnregisterTypeLibraries</td><td>##IDS_ACTIONTEXT_UnregTypeLibs##</td><td>##IDS_ACTIONTEXT_Libid2##</td></row>\r
+               <row><td>WriteEnvironmentStrings</td><td>##IDS_ACTIONTEXT_EnvironmentStrings##</td><td>##IDS_ACTIONTEXT_NameValueAction##</td></row>\r
+               <row><td>WriteIniValues</td><td>##IDS_ACTIONTEXT_WritingINI##</td><td>##IDS_ACTIONTEXT_FileSectionKeyValue2##</td></row>\r
+               <row><td>WriteRegistryValues</td><td>##IDS_ACTIONTEXT_WritingRegistry##</td><td>##IDS_ACTIONTEXT_KeyNameValue##</td></row>\r
+               <row><td>caCreateVRoots</td><td>##IDS_ACTIONTEXT_CreatingIISRoots##</td><td/></row>\r
+               <row><td>caRemoveVRoots</td><td>##IDS_ACTIONTEXT_RemovingIISRoots##</td><td/></row>\r
+       </table>\r
+\r
+       <table name="AdminExecuteSequence">\r
+               <col key="yes" def="s72">Action</col>\r
+               <col def="S255">Condition</col>\r
+               <col def="I2">Sequence</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <row><td>CostFinalize</td><td/><td>1000</td><td>CostFinalize</td><td/></row>\r
+               <row><td>CostInitialize</td><td/><td>800</td><td>CostInitialize</td><td/></row>\r
+               <row><td>FileCost</td><td/><td>900</td><td>FileCost</td><td/></row>\r
+               <row><td>InstallAdminPackage</td><td/><td>3900</td><td>InstallAdminPackage</td><td/></row>\r
+               <row><td>InstallFiles</td><td/><td>4000</td><td>InstallFiles</td><td/></row>\r
+               <row><td>InstallFinalize</td><td/><td>6600</td><td>InstallFinalize</td><td/></row>\r
+               <row><td>InstallInitialize</td><td/><td>1500</td><td>InstallInitialize</td><td/></row>\r
+               <row><td>InstallValidate</td><td/><td>1400</td><td>InstallValidate</td><td/></row>\r
+               <row><td>ScheduleReboot</td><td>ISSCHEDULEREBOOT</td><td>4010</td><td>ScheduleReboot</td><td/></row>\r
+       </table>\r
+\r
+       <table name="AdminUISequence">\r
+               <col key="yes" def="s72">Action</col>\r
+               <col def="S255">Condition</col>\r
+               <col def="I2">Sequence</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <row><td>CostFinalize</td><td/><td>1000</td><td>CostFinalize</td><td/></row>\r
+               <row><td>CostInitialize</td><td/><td>800</td><td>CostInitialize</td><td/></row>\r
+               <row><td>ExecuteAction</td><td/><td>1300</td><td>ExecuteAction</td><td/></row>\r
+               <row><td>FileCost</td><td/><td>900</td><td>FileCost</td><td/></row>\r
+               <row><td>ISVerifyScriptingRuntime</td><td>NOT AFTERREBOOT AND NOT ISSETUPDRIVEN</td><td>1</td><td>ISVerifyScriptingRuntime</td><td/></row>\r
+       </table>\r
+\r
+       <table name="AdvtExecuteSequence">\r
+               <col key="yes" def="s72">Action</col>\r
+               <col def="S255">Condition</col>\r
+               <col def="I2">Sequence</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <row><td>CostFinalize</td><td/><td>1000</td><td>CostFinalize</td><td/></row>\r
+               <row><td>CostInitialize</td><td/><td>800</td><td>CostInitialize</td><td/></row>\r
+               <row><td>CreateShortcuts</td><td/><td>4500</td><td>CreateShortcuts</td><td/></row>\r
+               <row><td>InstallFinalize</td><td/><td>6600</td><td>InstallFinalize</td><td/></row>\r
+               <row><td>InstallInitialize</td><td/><td>1500</td><td>InstallInitialize</td><td/></row>\r
+               <row><td>InstallValidate</td><td/><td>1400</td><td>InstallValidate</td><td/></row>\r
+               <row><td>MsiPublishAssemblies</td><td/><td>6250</td><td>MsiPublishAssemblies</td><td/></row>\r
+               <row><td>PublishComponents</td><td/><td>6200</td><td>PublishComponents</td><td/></row>\r
+               <row><td>PublishFeatures</td><td/><td>6300</td><td>PublishFeatures</td><td/></row>\r
+               <row><td>PublishProduct</td><td/><td>6400</td><td>PublishProduct</td><td/></row>\r
+               <row><td>RegisterClassInfo</td><td/><td>4600</td><td>RegisterClassInfo</td><td/></row>\r
+               <row><td>RegisterExtensionInfo</td><td/><td>4700</td><td>RegisterExtensionInfo</td><td/></row>\r
+               <row><td>RegisterMIMEInfo</td><td/><td>4900</td><td>RegisterMIMEInfo</td><td/></row>\r
+               <row><td>RegisterProgIdInfo</td><td/><td>4800</td><td>RegisterProgIdInfo</td><td/></row>\r
+               <row><td>RegisterTypeLibraries</td><td/><td>4910</td><td>RegisterTypeLibraries</td><td/></row>\r
+               <row><td>ScheduleReboot</td><td>ISSCHEDULEREBOOT</td><td>6410</td><td>ScheduleReboot</td><td/></row>\r
+       </table>\r
+\r
+       <table name="AdvtUISequence">\r
+               <col key="yes" def="s72">Action</col>\r
+               <col def="S255">Condition</col>\r
+               <col def="I2">Sequence</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="AppId">\r
+               <col key="yes" def="s38">AppId</col>\r
+               <col def="S255">RemoteServerName</col>\r
+               <col def="S255">LocalService</col>\r
+               <col def="S255">ServiceParameters</col>\r
+               <col def="S255">DllSurrogate</col>\r
+               <col def="I2">ActivateAtStorage</col>\r
+               <col def="I2">RunAsInteractiveUser</col>\r
+       </table>\r
+\r
+       <table name="AppSearch">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col key="yes" def="s72">Signature_</col>\r
+       </table>\r
+\r
+       <table name="BBControl">\r
+               <col key="yes" def="s50">Billboard_</col>\r
+               <col key="yes" def="s50">BBControl</col>\r
+               <col def="s50">Type</col>\r
+               <col def="i2">X</col>\r
+               <col def="i2">Y</col>\r
+               <col def="i2">Width</col>\r
+               <col def="i2">Height</col>\r
+               <col def="I4">Attributes</col>\r
+               <col def="L50">Text</col>\r
+       </table>\r
+\r
+       <table name="Billboard">\r
+               <col key="yes" def="s50">Billboard</col>\r
+               <col def="s38">Feature_</col>\r
+               <col def="S50">Action</col>\r
+               <col def="I2">Ordering</col>\r
+       </table>\r
+\r
+       <table name="Binary">\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="V0">Data</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+               <row><td>ISSELFREG.DLL</td><td/><td>&lt;ISProductFolder&gt;\redist\language independent\i386\isregsvr.dll</td></row>\r
+               <row><td>ISSetup.dll</td><td/><td>&lt;ISProductFolder&gt;\redist\language independent\i386\ISSetup.dll</td></row>\r
+               <row><td>ISSetupFilesHelper</td><td/><td>&lt;ISProductFolder&gt;\redist\language independent\i386\SFHelper.dll</td></row>\r
+       </table>\r
+\r
+       <table name="BindImage">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col def="S255">Path</col>\r
+       </table>\r
+\r
+       <table name="CCPSearch">\r
+               <col key="yes" def="s72">Signature_</col>\r
+       </table>\r
+\r
+       <table name="CheckBox">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col def="S64">Value</col>\r
+       </table>\r
+\r
+       <table name="Class">\r
+               <col key="yes" def="s38">CLSID</col>\r
+               <col key="yes" def="s32">Context</col>\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col def="S255">ProgId_Default</col>\r
+               <col def="L255">Description</col>\r
+               <col def="S38">AppId_</col>\r
+               <col def="S255">FileTypeMask</col>\r
+               <col def="S72">Icon_</col>\r
+               <col def="I2">IconIndex</col>\r
+               <col def="S32">DefInprocHandler</col>\r
+               <col def="S255">Argument</col>\r
+               <col def="s38">Feature_</col>\r
+               <col def="I2">Attributes</col>\r
+       </table>\r
+\r
+       <table name="ComboBox">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col key="yes" def="i2">Order</col>\r
+               <col def="s64">Value</col>\r
+               <col def="L64">Text</col>\r
+       </table>\r
+\r
+       <table name="CompLocator">\r
+               <col key="yes" def="s72">Signature_</col>\r
+               <col def="s38">ComponentId</col>\r
+               <col def="I2">Type</col>\r
+       </table>\r
+\r
+       <table name="Complus">\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col key="yes" def="I2">ExpType</col>\r
+       </table>\r
+\r
+       <table name="Component">\r
+               <col key="yes" def="s72">Component</col>\r
+               <col def="S38">ComponentId</col>\r
+               <col def="s72">Directory_</col>\r
+               <col def="i2">Attributes</col>\r
+               <col def="S255">Condition</col>\r
+               <col def="S72">KeyPath</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="S255">ISScanAtBuildFile</col>\r
+               <col def="S255">ISRegFileToMergeAtBuild</col>\r
+               <col def="S0">ISDotNetInstallerArgsInstall</col>\r
+               <col def="S0">ISDotNetInstallerArgsCommit</col>\r
+               <col def="S0">ISDotNetInstallerArgsUninstall</col>\r
+               <col def="S0">ISDotNetInstallerArgsRollback</col>\r
+               <row><td>SimanticsSysdyn32Files</td><td>{97417204-517F-4FDB-8A72-83900DA3B204}</td><td>INSTALLDIR</td><td>8</td><td/><td/><td>17</td><td/><td/><td/><td>/LogFile=</td><td>/LogFile=</td><td>/LogFile=</td><td>/LogFile=</td></row>\r
+               <row><td>SimanticsSysdyn64Files</td><td>{874B1E4B-DB82-4F7B-8555-6B648FDD9EFF}</td><td>INSTALLDIR</td><td>264</td><td/><td/><td>17</td><td/><td/><td/><td>/LogFile=</td><td>/LogFile=</td><td>/LogFile=</td><td>/LogFile=</td></row>\r
+       </table>\r
+\r
+       <table name="Condition">\r
+               <col key="yes" def="s38">Feature_</col>\r
+               <col key="yes" def="i2">Level</col>\r
+               <col def="S255">Condition</col>\r
+       </table>\r
+\r
+       <table name="Control">\r
+               <col key="yes" def="s72">Dialog_</col>\r
+               <col key="yes" def="s50">Control</col>\r
+               <col def="s20">Type</col>\r
+               <col def="i2">X</col>\r
+               <col def="i2">Y</col>\r
+               <col def="i2">Width</col>\r
+               <col def="i2">Height</col>\r
+               <col def="I4">Attributes</col>\r
+               <col def="S72">Property</col>\r
+               <col def="L0">Text</col>\r
+               <col def="S50">Control_Next</col>\r
+               <col def="L50">Help</col>\r
+               <col def="I4">ISWindowStyle</col>\r
+               <col def="I4">ISControlId</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+               <col def="S72">Binary_</col>\r
+       </table>\r
+\r
+       <table name="ControlCondition">\r
+               <col key="yes" def="s72">Dialog_</col>\r
+               <col key="yes" def="s50">Control_</col>\r
+               <col key="yes" def="s50">Action</col>\r
+               <col key="yes" def="s255">Condition</col>\r
+       </table>\r
+\r
+       <table name="ControlEvent">\r
+               <col key="yes" def="s72">Dialog_</col>\r
+               <col key="yes" def="s50">Control_</col>\r
+               <col key="yes" def="s50">Event</col>\r
+               <col key="yes" def="s255">Argument</col>\r
+               <col key="yes" def="S255">Condition</col>\r
+               <col def="I2">Ordering</col>\r
+               <row><td>CancelSetup</td><td>Yes</td><td>DoAction</td><td>ISSetupFilesCleanup</td><td>1</td><td>200</td></row>\r
+               <row><td>SetupCompleteError</td><td>Finish</td><td>DoAction</td><td>ISSetupFilesCleanup</td><td>1</td><td>200</td></row>\r
+               <row><td>SetupCompleteSuccess</td><td>OK</td><td>DoAction</td><td>ISSetupFilesCleanup</td><td>1</td><td>200</td></row>\r
+               <row><td>SetupInterrupted</td><td>Finish</td><td>DoAction</td><td>ISSetupFilesCleanup</td><td>1</td><td>200</td></row>\r
+       </table>\r
+\r
+       <table name="CreateFolder">\r
+               <col key="yes" def="s72">Directory_</col>\r
+               <col key="yes" def="s72">Component_</col>\r
+       </table>\r
+\r
+       <table name="CustomAction">\r
+               <col key="yes" def="s72">Action</col>\r
+               <col def="i2">Type</col>\r
+               <col def="S64">Source</col>\r
+               <col def="S0">Target</col>\r
+               <col def="I4">ExtendedType</col>\r
+               <col def="S255">ISComments</col>\r
+               <row><td>ISPreventDowngrade</td><td>19</td><td/><td>[IS_PREVENT_DOWNGRADE_EXIT]</td><td/><td>Exits install when a newer version of this product is found</td></row>\r
+               <row><td>ISSelfRegisterCosting</td><td>1</td><td>ISSELFREG.DLL</td><td>ISSelfRegisterCosting</td><td/><td/></row>\r
+               <row><td>ISSelfRegisterFiles</td><td>3073</td><td>ISSELFREG.DLL</td><td>ISSelfRegisterFiles</td><td/><td/></row>\r
+               <row><td>ISSelfRegisterFinalize</td><td>1</td><td>ISSELFREG.DLL</td><td>ISSelfRegisterFinalize</td><td/><td/></row>\r
+               <row><td>ISSetupFilesCleanup</td><td>257</td><td>ISSetupFilesHelper</td><td>SFCleanupEx</td><td/><td/></row>\r
+               <row><td>ISSetupFilesExtract</td><td>257</td><td>ISSetupFilesHelper</td><td>SFStartupEx</td><td/><td/></row>\r
+               <row><td>ISUnSelfRegisterFiles</td><td>3073</td><td>ISSELFREG.DLL</td><td>ISUnSelfRegisterFiles</td><td/><td/></row>\r
+               <row><td>ISVerifyScriptingRuntime</td><td>19</td><td/><td>[STANDARD_USE_SETUPEXE]</td><td/><td>Required for installations using InstallScript.</td></row>\r
+               <row><td>SetARPINSTALLLOCATION</td><td>51</td><td>ARPINSTALLLOCATION</td><td>[INSTALLDIR]</td><td/><td/></row>\r
+               <row><td>SetAllUsersProfileNT</td><td>51</td><td>ALLUSERSPROFILE</td><td>[%SystemRoot]\Profiles\All Users</td><td/><td/></row>\r
+               <row><td>setAllUsersProfile2K</td><td>51</td><td>ALLUSERSPROFILE</td><td>[%ALLUSERSPROFILE]</td><td/><td/></row>\r
+               <row><td>setUserProfileNT</td><td>51</td><td>USERPROFILE</td><td>[%USERPROFILE]</td><td/><td/></row>\r
+       </table>\r
+\r
+       <table name="Dialog">\r
+               <col key="yes" def="s72">Dialog</col>\r
+               <col def="i2">HCentering</col>\r
+               <col def="i2">VCentering</col>\r
+               <col def="i2">Width</col>\r
+               <col def="i2">Height</col>\r
+               <col def="I4">Attributes</col>\r
+               <col def="L128">Title</col>\r
+               <col def="s50">Control_First</col>\r
+               <col def="S50">Control_Default</col>\r
+               <col def="S50">Control_Cancel</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="S72">TextStyle_</col>\r
+               <col def="I4">ISWindowStyle</col>\r
+               <col def="I4">ISResourceId</col>\r
+       </table>\r
+\r
+       <table name="Directory">\r
+               <col key="yes" def="s72">Directory</col>\r
+               <col def="S72">Directory_Parent</col>\r
+               <col def="l255">DefaultDir</col>\r
+               <col def="S255">ISDescription</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <col def="S255">ISFolderName</col>\r
+               <row><td>ALLUSERSPROFILE</td><td>TARGETDIR</td><td>.:ALLUSE~1|All Users</td><td/><td>0</td><td/></row>\r
+               <row><td>AdminToolsFolder</td><td>TARGETDIR</td><td>.:Admint~1|AdminTools</td><td/><td>0</td><td/></row>\r
+               <row><td>AppDataFolder</td><td>TARGETDIR</td><td>.:APPLIC~1|Application Data</td><td/><td>0</td><td/></row>\r
+               <row><td>CommonAppDataFolder</td><td>TARGETDIR</td><td>.:Common~1|CommonAppData</td><td/><td>0</td><td/></row>\r
+               <row><td>CommonFiles64Folder</td><td>TARGETDIR</td><td>.:Common64</td><td/><td>0</td><td/></row>\r
+               <row><td>CommonFilesFolder</td><td>TARGETDIR</td><td>.:Common</td><td/><td>0</td><td/></row>\r
+               <row><td>DesktopFolder</td><td>TARGETDIR</td><td>.:Desktop</td><td/><td>3</td><td/></row>\r
+               <row><td>FavoritesFolder</td><td>TARGETDIR</td><td>.:FAVORI~1|Favorites</td><td/><td>0</td><td/></row>\r
+               <row><td>FontsFolder</td><td>TARGETDIR</td><td>.:Fonts</td><td/><td>0</td><td/></row>\r
+               <row><td>GlobalAssemblyCache</td><td>TARGETDIR</td><td>.:Global~1|GlobalAssemblyCache</td><td/><td>0</td><td/></row>\r
+               <row><td>INSTALLDIR</td><td>MY_PRODUCT_NAME</td><td>.</td><td/><td>0</td><td/></row>\r
+               <row><td>LocalAppDataFolder</td><td>TARGETDIR</td><td>.:LocalA~1|LocalAppData</td><td/><td>0</td><td/></row>\r
+               <row><td>MY_PRODUCT_NAME</td><td>PrimaryVolumePath</td><td>SIMANT~1|Simantics</td><td/><td>0</td><td/></row>\r
+               <row><td>MyPicturesFolder</td><td>TARGETDIR</td><td>.:MyPict~1|MyPictures</td><td/><td>0</td><td/></row>\r
+               <row><td>PersonalFolder</td><td>TARGETDIR</td><td>.:Personal</td><td/><td>0</td><td/></row>\r
+               <row><td>PrimaryVolumePath</td><td>TARGETDIR</td><td>.:Primar~1|PrimaryVolumePath</td><td/><td>0</td><td/></row>\r
+               <row><td>ProgramFiles64Folder</td><td>TARGETDIR</td><td>.:Prog64~1|Program Files 64</td><td/><td>0</td><td/></row>\r
+               <row><td>ProgramFilesFolder</td><td>TARGETDIR</td><td>.:PROGRA~1|program files</td><td/><td>0</td><td/></row>\r
+               <row><td>ProgramMenuFolder</td><td>TARGETDIR</td><td>.:Programs</td><td/><td>3</td><td/></row>\r
+               <row><td>SIMANTICS</td><td>PrimaryVolumePath</td><td>SIMANT~1|Simantics</td><td/><td>0</td><td/></row>\r
+               <row><td>SendToFolder</td><td>TARGETDIR</td><td>.:SendTo</td><td/><td>3</td><td/></row>\r
+               <row><td>StartMenuFolder</td><td>TARGETDIR</td><td>.:STARTM~1|Start Menu</td><td/><td>3</td><td/></row>\r
+               <row><td>StartupFolder</td><td>TARGETDIR</td><td>.:StartUp</td><td/><td>3</td><td/></row>\r
+               <row><td>System16Folder</td><td>TARGETDIR</td><td>.:System</td><td/><td>0</td><td/></row>\r
+               <row><td>System64Folder</td><td>TARGETDIR</td><td>.:System64</td><td/><td>0</td><td/></row>\r
+               <row><td>SystemFolder</td><td>TARGETDIR</td><td>.:System32</td><td/><td>0</td><td/></row>\r
+               <row><td>TARGETDIR</td><td/><td>SourceDir</td><td/><td>0</td><td/></row>\r
+               <row><td>TempFolder</td><td>TARGETDIR</td><td>.:Temp</td><td/><td>0</td><td/></row>\r
+               <row><td>TemplateFolder</td><td>TARGETDIR</td><td>.:ShellNew</td><td/><td>0</td><td/></row>\r
+               <row><td>USERPROFILE</td><td>TARGETDIR</td><td>.:USERPR~1|UserProfile</td><td/><td>0</td><td/></row>\r
+               <row><td>WindowsFolder</td><td>TARGETDIR</td><td>.:Windows</td><td/><td>0</td><td/></row>\r
+               <row><td>WindowsVolume</td><td>TARGETDIR</td><td>.:WinRoot</td><td/><td>0</td><td/></row>\r
+       </table>\r
+\r
+       <table name="DrLocator">\r
+               <col key="yes" def="s72">Signature_</col>\r
+               <col key="yes" def="S72">Parent</col>\r
+               <col key="yes" def="S255">Path</col>\r
+               <col def="I2">Depth</col>\r
+       </table>\r
+\r
+       <table name="DuplicateFile">\r
+               <col key="yes" def="s72">FileKey</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="s72">File_</col>\r
+               <col def="L255">DestName</col>\r
+               <col def="S72">DestFolder</col>\r
+       </table>\r
+\r
+       <table name="Environment">\r
+               <col key="yes" def="s72">Environment</col>\r
+               <col def="l255">Name</col>\r
+               <col def="L255">Value</col>\r
+               <col def="s72">Component_</col>\r
+       </table>\r
+\r
+       <table name="Error">\r
+               <col key="yes" def="i2">Error</col>\r
+               <col def="L255">Message</col>\r
+               <row><td>0</td><td>##IDS_ERROR_0##</td></row>\r
+               <row><td>1</td><td>##IDS_ERROR_1##</td></row>\r
+               <row><td>10</td><td>##IDS_ERROR_8##</td></row>\r
+               <row><td>11</td><td>##IDS_ERROR_9##</td></row>\r
+               <row><td>1101</td><td>##IDS_ERROR_22##</td></row>\r
+               <row><td>12</td><td>##IDS_ERROR_10##</td></row>\r
+               <row><td>13</td><td>##IDS_ERROR_11##</td></row>\r
+               <row><td>1301</td><td>##IDS_ERROR_23##</td></row>\r
+               <row><td>1302</td><td>##IDS_ERROR_24##</td></row>\r
+               <row><td>1303</td><td>##IDS_ERROR_25##</td></row>\r
+               <row><td>1304</td><td>##IDS_ERROR_26##</td></row>\r
+               <row><td>1305</td><td>##IDS_ERROR_27##</td></row>\r
+               <row><td>1306</td><td>##IDS_ERROR_28##</td></row>\r
+               <row><td>1307</td><td>##IDS_ERROR_29##</td></row>\r
+               <row><td>1308</td><td>##IDS_ERROR_30##</td></row>\r
+               <row><td>1309</td><td>##IDS_ERROR_31##</td></row>\r
+               <row><td>1310</td><td>##IDS_ERROR_32##</td></row>\r
+               <row><td>1311</td><td>##IDS_ERROR_33##</td></row>\r
+               <row><td>1312</td><td>##IDS_ERROR_34##</td></row>\r
+               <row><td>1313</td><td>##IDS_ERROR_35##</td></row>\r
+               <row><td>1314</td><td>##IDS_ERROR_36##</td></row>\r
+               <row><td>1315</td><td>##IDS_ERROR_37##</td></row>\r
+               <row><td>1316</td><td>##IDS_ERROR_38##</td></row>\r
+               <row><td>1317</td><td>##IDS_ERROR_39##</td></row>\r
+               <row><td>1318</td><td>##IDS_ERROR_40##</td></row>\r
+               <row><td>1319</td><td>##IDS_ERROR_41##</td></row>\r
+               <row><td>1320</td><td>##IDS_ERROR_42##</td></row>\r
+               <row><td>1321</td><td>##IDS_ERROR_43##</td></row>\r
+               <row><td>1322</td><td>##IDS_ERROR_44##</td></row>\r
+               <row><td>1323</td><td>##IDS_ERROR_45##</td></row>\r
+               <row><td>1324</td><td>##IDS_ERROR_46##</td></row>\r
+               <row><td>1325</td><td>##IDS_ERROR_47##</td></row>\r
+               <row><td>1326</td><td>##IDS_ERROR_48##</td></row>\r
+               <row><td>1327</td><td>##IDS_ERROR_49##</td></row>\r
+               <row><td>1328</td><td>##IDS_ERROR_122##</td></row>\r
+               <row><td>1329</td><td>##IDS_ERROR_1329##</td></row>\r
+               <row><td>1330</td><td>##IDS_ERROR_1330##</td></row>\r
+               <row><td>1331</td><td>##IDS_ERROR_1331##</td></row>\r
+               <row><td>1332</td><td>##IDS_ERROR_1332##</td></row>\r
+               <row><td>1333</td><td>##IDS_ERROR_1333##</td></row>\r
+               <row><td>1334</td><td>##IDS_ERROR_1334##</td></row>\r
+               <row><td>1335</td><td>##IDS_ERROR_1335##</td></row>\r
+               <row><td>1336</td><td>##IDS_ERROR_1336##</td></row>\r
+               <row><td>14</td><td>##IDS_ERROR_12##</td></row>\r
+               <row><td>1401</td><td>##IDS_ERROR_50##</td></row>\r
+               <row><td>1402</td><td>##IDS_ERROR_51##</td></row>\r
+               <row><td>1403</td><td>##IDS_ERROR_52##</td></row>\r
+               <row><td>1404</td><td>##IDS_ERROR_53##</td></row>\r
+               <row><td>1405</td><td>##IDS_ERROR_54##</td></row>\r
+               <row><td>1406</td><td>##IDS_ERROR_55##</td></row>\r
+               <row><td>1407</td><td>##IDS_ERROR_56##</td></row>\r
+               <row><td>1408</td><td>##IDS_ERROR_57##</td></row>\r
+               <row><td>1409</td><td>##IDS_ERROR_58##</td></row>\r
+               <row><td>1410</td><td>##IDS_ERROR_59##</td></row>\r
+               <row><td>15</td><td>##IDS_ERROR_13##</td></row>\r
+               <row><td>1500</td><td>##IDS_ERROR_60##</td></row>\r
+               <row><td>1501</td><td>##IDS_ERROR_61##</td></row>\r
+               <row><td>1502</td><td>##IDS_ERROR_62##</td></row>\r
+               <row><td>1503</td><td>##IDS_ERROR_63##</td></row>\r
+               <row><td>16</td><td>##IDS_ERROR_14##</td></row>\r
+               <row><td>1601</td><td>##IDS_ERROR_64##</td></row>\r
+               <row><td>1602</td><td>##IDS_ERROR_65##</td></row>\r
+               <row><td>1603</td><td>##IDS_ERROR_66##</td></row>\r
+               <row><td>1604</td><td>##IDS_ERROR_67##</td></row>\r
+               <row><td>1605</td><td>##IDS_ERROR_68##</td></row>\r
+               <row><td>1606</td><td>##IDS_ERROR_69##</td></row>\r
+               <row><td>1607</td><td/></row>\r
+               <row><td>1608</td><td>##IDS_ERROR_71##</td></row>\r
+               <row><td>1609</td><td>##IDS_ERROR_1609##</td></row>\r
+               <row><td>1651</td><td>##IDS_ERROR_1651##</td></row>\r
+               <row><td>17</td><td>##IDS_ERROR_15##</td></row>\r
+               <row><td>1701</td><td>##IDS_ERROR_72##</td></row>\r
+               <row><td>1702</td><td>##IDS_ERROR_73##</td></row>\r
+               <row><td>1703</td><td>##IDS_ERROR_74##</td></row>\r
+               <row><td>1704</td><td>##IDS_ERROR_75##</td></row>\r
+               <row><td>1705</td><td>##IDS_ERROR_76##</td></row>\r
+               <row><td>1706</td><td>##IDS_ERROR_77##</td></row>\r
+               <row><td>1707</td><td>##IDS_ERROR_78##</td></row>\r
+               <row><td>1708</td><td>##IDS_ERROR_79##</td></row>\r
+               <row><td>1709</td><td>##IDS_ERROR_80##</td></row>\r
+               <row><td>1710</td><td>##IDS_ERROR_81##</td></row>\r
+               <row><td>1711</td><td>##IDS_ERROR_82##</td></row>\r
+               <row><td>1712</td><td>##IDS_ERROR_83##</td></row>\r
+               <row><td>1713</td><td>##IDS_ERROR_123##</td></row>\r
+               <row><td>1714</td><td>##IDS_ERROR_124##</td></row>\r
+               <row><td>1715</td><td>##IDS_ERROR_1715##</td></row>\r
+               <row><td>1716</td><td>##IDS_ERROR_1716##</td></row>\r
+               <row><td>1717</td><td>##IDS_ERROR_1717##</td></row>\r
+               <row><td>1718</td><td>##IDS_ERROR_1718##</td></row>\r
+               <row><td>1719</td><td>##IDS_ERROR_1719##</td></row>\r
+               <row><td>1720</td><td>##IDS_ERROR_1720##</td></row>\r
+               <row><td>1721</td><td>##IDS_ERROR_1721##</td></row>\r
+               <row><td>1722</td><td>##IDS_ERROR_1722##</td></row>\r
+               <row><td>1723</td><td>##IDS_ERROR_1723##</td></row>\r
+               <row><td>1724</td><td>##IDS_ERROR_1724##</td></row>\r
+               <row><td>1725</td><td>##IDS_ERROR_1725##</td></row>\r
+               <row><td>1726</td><td>##IDS_ERROR_1726##</td></row>\r
+               <row><td>1727</td><td>##IDS_ERROR_1727##</td></row>\r
+               <row><td>1728</td><td>##IDS_ERROR_1728##</td></row>\r
+               <row><td>1729</td><td>##IDS_ERROR_1729##</td></row>\r
+               <row><td>1730</td><td>##IDS_ERROR_1730##</td></row>\r
+               <row><td>1731</td><td>##IDS_ERROR_1731##</td></row>\r
+               <row><td>1732</td><td>##IDS_ERROR_1732##</td></row>\r
+               <row><td>18</td><td>##IDS_ERROR_16##</td></row>\r
+               <row><td>1801</td><td>##IDS_ERROR_84##</td></row>\r
+               <row><td>1802</td><td>##IDS_ERROR_85##</td></row>\r
+               <row><td>1803</td><td>##IDS_ERROR_86##</td></row>\r
+               <row><td>1804</td><td>##IDS_ERROR_87##</td></row>\r
+               <row><td>1805</td><td>##IDS_ERROR_88##</td></row>\r
+               <row><td>1806</td><td>##IDS_ERROR_89##</td></row>\r
+               <row><td>1807</td><td>##IDS_ERROR_90##</td></row>\r
+               <row><td>19</td><td>##IDS_ERROR_17##</td></row>\r
+               <row><td>1901</td><td>##IDS_ERROR_91##</td></row>\r
+               <row><td>1902</td><td>##IDS_ERROR_92##</td></row>\r
+               <row><td>1903</td><td>##IDS_ERROR_93##</td></row>\r
+               <row><td>1904</td><td>##IDS_ERROR_94##</td></row>\r
+               <row><td>1905</td><td>##IDS_ERROR_95##</td></row>\r
+               <row><td>1906</td><td>##IDS_ERROR_96##</td></row>\r
+               <row><td>1907</td><td>##IDS_ERROR_97##</td></row>\r
+               <row><td>1908</td><td>##IDS_ERROR_98##</td></row>\r
+               <row><td>1909</td><td>##IDS_ERROR_99##</td></row>\r
+               <row><td>1910</td><td>##IDS_ERROR_100##</td></row>\r
+               <row><td>1911</td><td>##IDS_ERROR_101##</td></row>\r
+               <row><td>1912</td><td>##IDS_ERROR_102##</td></row>\r
+               <row><td>1913</td><td>##IDS_ERROR_103##</td></row>\r
+               <row><td>1914</td><td>##IDS_ERROR_104##</td></row>\r
+               <row><td>1915</td><td>##IDS_ERROR_105##</td></row>\r
+               <row><td>1916</td><td>##IDS_ERROR_106##</td></row>\r
+               <row><td>1917</td><td>##IDS_ERROR_107##</td></row>\r
+               <row><td>1918</td><td>##IDS_ERROR_108##</td></row>\r
+               <row><td>1919</td><td>##IDS_ERROR_109##</td></row>\r
+               <row><td>1920</td><td>##IDS_ERROR_110##</td></row>\r
+               <row><td>1921</td><td>##IDS_ERROR_111##</td></row>\r
+               <row><td>1922</td><td>##IDS_ERROR_112##</td></row>\r
+               <row><td>1923</td><td>##IDS_ERROR_113##</td></row>\r
+               <row><td>1924</td><td>##IDS_ERROR_114##</td></row>\r
+               <row><td>1925</td><td>##IDS_ERROR_115##</td></row>\r
+               <row><td>1926</td><td>##IDS_ERROR_116##</td></row>\r
+               <row><td>1927</td><td>##IDS_ERROR_117##</td></row>\r
+               <row><td>1928</td><td>##IDS_ERROR_118##</td></row>\r
+               <row><td>1929</td><td>##IDS_ERROR_119##</td></row>\r
+               <row><td>1930</td><td>##IDS_ERROR_125##</td></row>\r
+               <row><td>1931</td><td>##IDS_ERROR_126##</td></row>\r
+               <row><td>1932</td><td>##IDS_ERROR_127##</td></row>\r
+               <row><td>1933</td><td>##IDS_ERROR_128##</td></row>\r
+               <row><td>1934</td><td>##IDS_ERROR_129##</td></row>\r
+               <row><td>1935</td><td>##IDS_ERROR_1935##</td></row>\r
+               <row><td>1936</td><td>##IDS_ERROR_1936##</td></row>\r
+               <row><td>1937</td><td>##IDS_ERROR_1937##</td></row>\r
+               <row><td>1938</td><td>##IDS_ERROR_1938##</td></row>\r
+               <row><td>2</td><td>##IDS_ERROR_2##</td></row>\r
+               <row><td>20</td><td>##IDS_ERROR_18##</td></row>\r
+               <row><td>21</td><td>##IDS_ERROR_19##</td></row>\r
+               <row><td>2101</td><td>##IDS_ERROR_2101##</td></row>\r
+               <row><td>2102</td><td>##IDS_ERROR_2102##</td></row>\r
+               <row><td>2103</td><td>##IDS_ERROR_2103##</td></row>\r
+               <row><td>2104</td><td>##IDS_ERROR_2104##</td></row>\r
+               <row><td>2105</td><td>##IDS_ERROR_2105##</td></row>\r
+               <row><td>2106</td><td>##IDS_ERROR_2106##</td></row>\r
+               <row><td>2107</td><td>##IDS_ERROR_2107##</td></row>\r
+               <row><td>2108</td><td>##IDS_ERROR_2108##</td></row>\r
+               <row><td>2109</td><td>##IDS_ERROR_2109##</td></row>\r
+               <row><td>2110</td><td>##IDS_ERROR_2110##</td></row>\r
+               <row><td>2111</td><td>##IDS_ERROR_2111##</td></row>\r
+               <row><td>2112</td><td>##IDS_ERROR_2112##</td></row>\r
+               <row><td>2113</td><td>##IDS_ERROR_2113##</td></row>\r
+               <row><td>22</td><td>##IDS_ERROR_120##</td></row>\r
+               <row><td>2200</td><td>##IDS_ERROR_2200##</td></row>\r
+               <row><td>2201</td><td>##IDS_ERROR_2201##</td></row>\r
+               <row><td>2202</td><td>##IDS_ERROR_2202##</td></row>\r
+               <row><td>2203</td><td>##IDS_ERROR_2203##</td></row>\r
+               <row><td>2204</td><td>##IDS_ERROR_2204##</td></row>\r
+               <row><td>2205</td><td>##IDS_ERROR_2205##</td></row>\r
+               <row><td>2206</td><td>##IDS_ERROR_2206##</td></row>\r
+               <row><td>2207</td><td>##IDS_ERROR_2207##</td></row>\r
+               <row><td>2208</td><td>##IDS_ERROR_2208##</td></row>\r
+               <row><td>2209</td><td>##IDS_ERROR_2209##</td></row>\r
+               <row><td>2210</td><td>##IDS_ERROR_2210##</td></row>\r
+               <row><td>2211</td><td>##IDS_ERROR_2211##</td></row>\r
+               <row><td>2212</td><td>##IDS_ERROR_2212##</td></row>\r
+               <row><td>2213</td><td>##IDS_ERROR_2213##</td></row>\r
+               <row><td>2214</td><td>##IDS_ERROR_2214##</td></row>\r
+               <row><td>2215</td><td>##IDS_ERROR_2215##</td></row>\r
+               <row><td>2216</td><td>##IDS_ERROR_2216##</td></row>\r
+               <row><td>2217</td><td>##IDS_ERROR_2217##</td></row>\r
+               <row><td>2218</td><td>##IDS_ERROR_2218##</td></row>\r
+               <row><td>2219</td><td>##IDS_ERROR_2219##</td></row>\r
+               <row><td>2220</td><td>##IDS_ERROR_2220##</td></row>\r
+               <row><td>2221</td><td>##IDS_ERROR_2221##</td></row>\r
+               <row><td>2222</td><td>##IDS_ERROR_2222##</td></row>\r
+               <row><td>2223</td><td>##IDS_ERROR_2223##</td></row>\r
+               <row><td>2224</td><td>##IDS_ERROR_2224##</td></row>\r
+               <row><td>2225</td><td>##IDS_ERROR_2225##</td></row>\r
+               <row><td>2226</td><td>##IDS_ERROR_2226##</td></row>\r
+               <row><td>2227</td><td>##IDS_ERROR_2227##</td></row>\r
+               <row><td>2228</td><td>##IDS_ERROR_2228##</td></row>\r
+               <row><td>2229</td><td>##IDS_ERROR_2229##</td></row>\r
+               <row><td>2230</td><td>##IDS_ERROR_2230##</td></row>\r
+               <row><td>2231</td><td>##IDS_ERROR_2231##</td></row>\r
+               <row><td>2232</td><td>##IDS_ERROR_2232##</td></row>\r
+               <row><td>2233</td><td>##IDS_ERROR_2233##</td></row>\r
+               <row><td>2234</td><td>##IDS_ERROR_2234##</td></row>\r
+               <row><td>2235</td><td>##IDS_ERROR_2235##</td></row>\r
+               <row><td>2236</td><td>##IDS_ERROR_2236##</td></row>\r
+               <row><td>2237</td><td>##IDS_ERROR_2237##</td></row>\r
+               <row><td>2238</td><td>##IDS_ERROR_2238##</td></row>\r
+               <row><td>2239</td><td>##IDS_ERROR_2239##</td></row>\r
+               <row><td>2240</td><td>##IDS_ERROR_2240##</td></row>\r
+               <row><td>2241</td><td>##IDS_ERROR_2241##</td></row>\r
+               <row><td>2242</td><td>##IDS_ERROR_2242##</td></row>\r
+               <row><td>2243</td><td>##IDS_ERROR_2243##</td></row>\r
+               <row><td>2244</td><td>##IDS_ERROR_2244##</td></row>\r
+               <row><td>2245</td><td>##IDS_ERROR_2245##</td></row>\r
+               <row><td>2246</td><td>##IDS_ERROR_2246##</td></row>\r
+               <row><td>2247</td><td>##IDS_ERROR_2247##</td></row>\r
+               <row><td>2248</td><td>##IDS_ERROR_2248##</td></row>\r
+               <row><td>2249</td><td>##IDS_ERROR_2249##</td></row>\r
+               <row><td>2250</td><td>##IDS_ERROR_2250##</td></row>\r
+               <row><td>2251</td><td>##IDS_ERROR_2251##</td></row>\r
+               <row><td>2252</td><td>##IDS_ERROR_2252##</td></row>\r
+               <row><td>2253</td><td>##IDS_ERROR_2253##</td></row>\r
+               <row><td>2254</td><td>##IDS_ERROR_2254##</td></row>\r
+               <row><td>2255</td><td>##IDS_ERROR_2255##</td></row>\r
+               <row><td>2256</td><td>##IDS_ERROR_2256##</td></row>\r
+               <row><td>2257</td><td>##IDS_ERROR_2257##</td></row>\r
+               <row><td>2258</td><td>##IDS_ERROR_2258##</td></row>\r
+               <row><td>2259</td><td>##IDS_ERROR_2259##</td></row>\r
+               <row><td>2260</td><td>##IDS_ERROR_2260##</td></row>\r
+               <row><td>2261</td><td>##IDS_ERROR_2261##</td></row>\r
+               <row><td>2262</td><td>##IDS_ERROR_2262##</td></row>\r
+               <row><td>2263</td><td>##IDS_ERROR_2263##</td></row>\r
+               <row><td>2264</td><td>##IDS_ERROR_2264##</td></row>\r
+               <row><td>2265</td><td>##IDS_ERROR_2265##</td></row>\r
+               <row><td>2266</td><td>##IDS_ERROR_2266##</td></row>\r
+               <row><td>2267</td><td>##IDS_ERROR_2267##</td></row>\r
+               <row><td>2268</td><td>##IDS_ERROR_2268##</td></row>\r
+               <row><td>2269</td><td>##IDS_ERROR_2269##</td></row>\r
+               <row><td>2270</td><td>##IDS_ERROR_2270##</td></row>\r
+               <row><td>2271</td><td>##IDS_ERROR_2271##</td></row>\r
+               <row><td>2272</td><td>##IDS_ERROR_2272##</td></row>\r
+               <row><td>2273</td><td>##IDS_ERROR_2273##</td></row>\r
+               <row><td>2274</td><td>##IDS_ERROR_2274##</td></row>\r
+               <row><td>2275</td><td>##IDS_ERROR_2275##</td></row>\r
+               <row><td>2276</td><td>##IDS_ERROR_2276##</td></row>\r
+               <row><td>2277</td><td>##IDS_ERROR_2277##</td></row>\r
+               <row><td>2278</td><td>##IDS_ERROR_2278##</td></row>\r
+               <row><td>2279</td><td>##IDS_ERROR_2279##</td></row>\r
+               <row><td>2280</td><td>##IDS_ERROR_2280##</td></row>\r
+               <row><td>2281</td><td>##IDS_ERROR_2281##</td></row>\r
+               <row><td>2282</td><td>##IDS_ERROR_2282##</td></row>\r
+               <row><td>23</td><td>##IDS_ERROR_121##</td></row>\r
+               <row><td>2302</td><td>##IDS_ERROR_2302##</td></row>\r
+               <row><td>2303</td><td>##IDS_ERROR_2303##</td></row>\r
+               <row><td>2304</td><td>##IDS_ERROR_2304##</td></row>\r
+               <row><td>2305</td><td>##IDS_ERROR_2305##</td></row>\r
+               <row><td>2306</td><td>##IDS_ERROR_2306##</td></row>\r
+               <row><td>2307</td><td>##IDS_ERROR_2307##</td></row>\r
+               <row><td>2308</td><td>##IDS_ERROR_2308##</td></row>\r
+               <row><td>2309</td><td>##IDS_ERROR_2309##</td></row>\r
+               <row><td>2310</td><td>##IDS_ERROR_2310##</td></row>\r
+               <row><td>2315</td><td>##IDS_ERROR_2315##</td></row>\r
+               <row><td>2318</td><td>##IDS_ERROR_2318##</td></row>\r
+               <row><td>2319</td><td>##IDS_ERROR_2319##</td></row>\r
+               <row><td>2320</td><td>##IDS_ERROR_2320##</td></row>\r
+               <row><td>2321</td><td>##IDS_ERROR_2321##</td></row>\r
+               <row><td>2322</td><td>##IDS_ERROR_2322##</td></row>\r
+               <row><td>2323</td><td>##IDS_ERROR_2323##</td></row>\r
+               <row><td>2324</td><td>##IDS_ERROR_2324##</td></row>\r
+               <row><td>2325</td><td>##IDS_ERROR_2325##</td></row>\r
+               <row><td>2326</td><td>##IDS_ERROR_2326##</td></row>\r
+               <row><td>2327</td><td>##IDS_ERROR_2327##</td></row>\r
+               <row><td>2328</td><td>##IDS_ERROR_2328##</td></row>\r
+               <row><td>2329</td><td>##IDS_ERROR_2329##</td></row>\r
+               <row><td>2330</td><td>##IDS_ERROR_2330##</td></row>\r
+               <row><td>2331</td><td>##IDS_ERROR_2331##</td></row>\r
+               <row><td>2332</td><td>##IDS_ERROR_2332##</td></row>\r
+               <row><td>2333</td><td>##IDS_ERROR_2333##</td></row>\r
+               <row><td>2334</td><td>##IDS_ERROR_2334##</td></row>\r
+               <row><td>2335</td><td>##IDS_ERROR_2335##</td></row>\r
+               <row><td>2336</td><td>##IDS_ERROR_2336##</td></row>\r
+               <row><td>2337</td><td>##IDS_ERROR_2337##</td></row>\r
+               <row><td>2338</td><td>##IDS_ERROR_2338##</td></row>\r
+               <row><td>2339</td><td>##IDS_ERROR_2339##</td></row>\r
+               <row><td>2340</td><td>##IDS_ERROR_2340##</td></row>\r
+               <row><td>2341</td><td>##IDS_ERROR_2341##</td></row>\r
+               <row><td>2342</td><td>##IDS_ERROR_2342##</td></row>\r
+               <row><td>2343</td><td>##IDS_ERROR_2343##</td></row>\r
+               <row><td>2344</td><td>##IDS_ERROR_2344##</td></row>\r
+               <row><td>2345</td><td>##IDS_ERROR_2345##</td></row>\r
+               <row><td>2347</td><td>##IDS_ERROR_2347##</td></row>\r
+               <row><td>2348</td><td>##IDS_ERROR_2348##</td></row>\r
+               <row><td>2349</td><td>##IDS_ERROR_2349##</td></row>\r
+               <row><td>2350</td><td>##IDS_ERROR_2350##</td></row>\r
+               <row><td>2351</td><td>##IDS_ERROR_2351##</td></row>\r
+               <row><td>2352</td><td>##IDS_ERROR_2352##</td></row>\r
+               <row><td>2353</td><td>##IDS_ERROR_2353##</td></row>\r
+               <row><td>2354</td><td>##IDS_ERROR_2354##</td></row>\r
+               <row><td>2355</td><td>##IDS_ERROR_2355##</td></row>\r
+               <row><td>2356</td><td>##IDS_ERROR_2356##</td></row>\r
+               <row><td>2357</td><td>##IDS_ERROR_2357##</td></row>\r
+               <row><td>2358</td><td>##IDS_ERROR_2358##</td></row>\r
+               <row><td>2359</td><td>##IDS_ERROR_2359##</td></row>\r
+               <row><td>2360</td><td>##IDS_ERROR_2360##</td></row>\r
+               <row><td>2361</td><td>##IDS_ERROR_2361##</td></row>\r
+               <row><td>2362</td><td>##IDS_ERROR_2362##</td></row>\r
+               <row><td>2363</td><td>##IDS_ERROR_2363##</td></row>\r
+               <row><td>2364</td><td>##IDS_ERROR_2364##</td></row>\r
+               <row><td>2365</td><td>##IDS_ERROR_2365##</td></row>\r
+               <row><td>2366</td><td>##IDS_ERROR_2366##</td></row>\r
+               <row><td>2367</td><td>##IDS_ERROR_2367##</td></row>\r
+               <row><td>2368</td><td>##IDS_ERROR_2368##</td></row>\r
+               <row><td>2370</td><td>##IDS_ERROR_2370##</td></row>\r
+               <row><td>2371</td><td>##IDS_ERROR_2371##</td></row>\r
+               <row><td>2372</td><td>##IDS_ERROR_2372##</td></row>\r
+               <row><td>2373</td><td>##IDS_ERROR_2373##</td></row>\r
+               <row><td>2374</td><td>##IDS_ERROR_2374##</td></row>\r
+               <row><td>2375</td><td>##IDS_ERROR_2375##</td></row>\r
+               <row><td>2376</td><td>##IDS_ERROR_2376##</td></row>\r
+               <row><td>2379</td><td>##IDS_ERROR_2379##</td></row>\r
+               <row><td>2380</td><td>##IDS_ERROR_2380##</td></row>\r
+               <row><td>2381</td><td>##IDS_ERROR_2381##</td></row>\r
+               <row><td>2382</td><td>##IDS_ERROR_2382##</td></row>\r
+               <row><td>2401</td><td>##IDS_ERROR_2401##</td></row>\r
+               <row><td>2402</td><td>##IDS_ERROR_2402##</td></row>\r
+               <row><td>2501</td><td>##IDS_ERROR_2501##</td></row>\r
+               <row><td>2502</td><td>##IDS_ERROR_2502##</td></row>\r
+               <row><td>2503</td><td>##IDS_ERROR_2503##</td></row>\r
+               <row><td>2601</td><td>##IDS_ERROR_2601##</td></row>\r
+               <row><td>2602</td><td>##IDS_ERROR_2602##</td></row>\r
+               <row><td>2603</td><td>##IDS_ERROR_2603##</td></row>\r
+               <row><td>2604</td><td>##IDS_ERROR_2604##</td></row>\r
+               <row><td>2605</td><td>##IDS_ERROR_2605##</td></row>\r
+               <row><td>2606</td><td>##IDS_ERROR_2606##</td></row>\r
+               <row><td>2607</td><td>##IDS_ERROR_2607##</td></row>\r
+               <row><td>2608</td><td>##IDS_ERROR_2608##</td></row>\r
+               <row><td>2609</td><td>##IDS_ERROR_2609##</td></row>\r
+               <row><td>2611</td><td>##IDS_ERROR_2611##</td></row>\r
+               <row><td>2612</td><td>##IDS_ERROR_2612##</td></row>\r
+               <row><td>2613</td><td>##IDS_ERROR_2613##</td></row>\r
+               <row><td>2614</td><td>##IDS_ERROR_2614##</td></row>\r
+               <row><td>2615</td><td>##IDS_ERROR_2615##</td></row>\r
+               <row><td>2616</td><td>##IDS_ERROR_2616##</td></row>\r
+               <row><td>2617</td><td>##IDS_ERROR_2617##</td></row>\r
+               <row><td>2618</td><td>##IDS_ERROR_2618##</td></row>\r
+               <row><td>2619</td><td>##IDS_ERROR_2619##</td></row>\r
+               <row><td>2620</td><td>##IDS_ERROR_2620##</td></row>\r
+               <row><td>2621</td><td>##IDS_ERROR_2621##</td></row>\r
+               <row><td>2701</td><td>##IDS_ERROR_2701##</td></row>\r
+               <row><td>2702</td><td>##IDS_ERROR_2702##</td></row>\r
+               <row><td>2703</td><td>##IDS_ERROR_2703##</td></row>\r
+               <row><td>2704</td><td>##IDS_ERROR_2704##</td></row>\r
+               <row><td>2705</td><td>##IDS_ERROR_2705##</td></row>\r
+               <row><td>2706</td><td>##IDS_ERROR_2706##</td></row>\r
+               <row><td>2707</td><td>##IDS_ERROR_2707##</td></row>\r
+               <row><td>2708</td><td>##IDS_ERROR_2708##</td></row>\r
+               <row><td>2709</td><td>##IDS_ERROR_2709##</td></row>\r
+               <row><td>2710</td><td>##IDS_ERROR_2710##</td></row>\r
+               <row><td>2711</td><td>##IDS_ERROR_2711##</td></row>\r
+               <row><td>2712</td><td>##IDS_ERROR_2712##</td></row>\r
+               <row><td>2713</td><td>##IDS_ERROR_2713##</td></row>\r
+               <row><td>2714</td><td>##IDS_ERROR_2714##</td></row>\r
+               <row><td>2715</td><td>##IDS_ERROR_2715##</td></row>\r
+               <row><td>2716</td><td>##IDS_ERROR_2716##</td></row>\r
+               <row><td>2717</td><td>##IDS_ERROR_2717##</td></row>\r
+               <row><td>2718</td><td>##IDS_ERROR_2718##</td></row>\r
+               <row><td>2719</td><td>##IDS_ERROR_2719##</td></row>\r
+               <row><td>2720</td><td>##IDS_ERROR_2720##</td></row>\r
+               <row><td>2721</td><td>##IDS_ERROR_2721##</td></row>\r
+               <row><td>2722</td><td>##IDS_ERROR_2722##</td></row>\r
+               <row><td>2723</td><td>##IDS_ERROR_2723##</td></row>\r
+               <row><td>2724</td><td>##IDS_ERROR_2724##</td></row>\r
+               <row><td>2725</td><td>##IDS_ERROR_2725##</td></row>\r
+               <row><td>2726</td><td>##IDS_ERROR_2726##</td></row>\r
+               <row><td>2727</td><td>##IDS_ERROR_2727##</td></row>\r
+               <row><td>2728</td><td>##IDS_ERROR_2728##</td></row>\r
+               <row><td>2729</td><td>##IDS_ERROR_2729##</td></row>\r
+               <row><td>2730</td><td>##IDS_ERROR_2730##</td></row>\r
+               <row><td>2731</td><td>##IDS_ERROR_2731##</td></row>\r
+               <row><td>2732</td><td>##IDS_ERROR_2732##</td></row>\r
+               <row><td>2733</td><td>##IDS_ERROR_2733##</td></row>\r
+               <row><td>2734</td><td>##IDS_ERROR_2734##</td></row>\r
+               <row><td>2735</td><td>##IDS_ERROR_2735##</td></row>\r
+               <row><td>2736</td><td>##IDS_ERROR_2736##</td></row>\r
+               <row><td>2737</td><td>##IDS_ERROR_2737##</td></row>\r
+               <row><td>2738</td><td>##IDS_ERROR_2738##</td></row>\r
+               <row><td>2739</td><td>##IDS_ERROR_2739##</td></row>\r
+               <row><td>2740</td><td>##IDS_ERROR_2740##</td></row>\r
+               <row><td>2741</td><td>##IDS_ERROR_2741##</td></row>\r
+               <row><td>2742</td><td>##IDS_ERROR_2742##</td></row>\r
+               <row><td>2743</td><td>##IDS_ERROR_2743##</td></row>\r
+               <row><td>2744</td><td>##IDS_ERROR_2744##</td></row>\r
+               <row><td>2745</td><td>##IDS_ERROR_2745##</td></row>\r
+               <row><td>2746</td><td>##IDS_ERROR_2746##</td></row>\r
+               <row><td>2747</td><td>##IDS_ERROR_2747##</td></row>\r
+               <row><td>2748</td><td>##IDS_ERROR_2748##</td></row>\r
+               <row><td>2749</td><td>##IDS_ERROR_2749##</td></row>\r
+               <row><td>2750</td><td>##IDS_ERROR_2750##</td></row>\r
+               <row><td>27500</td><td>##IDS_ERROR_130##</td></row>\r
+               <row><td>27501</td><td>##IDS_ERROR_131##</td></row>\r
+               <row><td>27502</td><td>##IDS_ERROR_27502##</td></row>\r
+               <row><td>27503</td><td>##IDS_ERROR_27503##</td></row>\r
+               <row><td>27504</td><td>##IDS_ERROR_27504##</td></row>\r
+               <row><td>27505</td><td>##IDS_ERROR_27505##</td></row>\r
+               <row><td>27506</td><td>##IDS_ERROR_27506##</td></row>\r
+               <row><td>27507</td><td>##IDS_ERROR_27507##</td></row>\r
+               <row><td>27508</td><td>##IDS_ERROR_27508##</td></row>\r
+               <row><td>27509</td><td>##IDS_ERROR_27509##</td></row>\r
+               <row><td>2751</td><td>##IDS_ERROR_2751##</td></row>\r
+               <row><td>27510</td><td>##IDS_ERROR_27510##</td></row>\r
+               <row><td>27511</td><td>##IDS_ERROR_27511##</td></row>\r
+               <row><td>27512</td><td>##IDS_ERROR_27512##</td></row>\r
+               <row><td>27513</td><td>##IDS_ERROR_27513##</td></row>\r
+               <row><td>27514</td><td>##IDS_ERROR_27514##</td></row>\r
+               <row><td>27515</td><td>##IDS_ERROR_27515##</td></row>\r
+               <row><td>27516</td><td>##IDS_ERROR_27516##</td></row>\r
+               <row><td>27517</td><td>##IDS_ERROR_27517##</td></row>\r
+               <row><td>27518</td><td>##IDS_ERROR_27518##</td></row>\r
+               <row><td>27519</td><td>##IDS_ERROR_27519##</td></row>\r
+               <row><td>2752</td><td>##IDS_ERROR_2752##</td></row>\r
+               <row><td>27520</td><td>##IDS_ERROR_27520##</td></row>\r
+               <row><td>27521</td><td>##IDS_ERROR_27521##</td></row>\r
+               <row><td>27522</td><td>##IDS_ERROR_27522##</td></row>\r
+               <row><td>27523</td><td>##IDS_ERROR_27523##</td></row>\r
+               <row><td>27524</td><td>##IDS_ERROR_27524##</td></row>\r
+               <row><td>27525</td><td>##IDS_ERROR_27525##</td></row>\r
+               <row><td>27526</td><td>##IDS_ERROR_27526##</td></row>\r
+               <row><td>27527</td><td>##IDS_ERROR_27527##</td></row>\r
+               <row><td>27528</td><td>##IDS_ERROR_27528##</td></row>\r
+               <row><td>27529</td><td>##IDS_ERROR_27529##</td></row>\r
+               <row><td>2753</td><td>##IDS_ERROR_2753##</td></row>\r
+               <row><td>27530</td><td>##IDS_ERROR_27530##</td></row>\r
+               <row><td>27531</td><td>##IDS_ERROR_27531##</td></row>\r
+               <row><td>27532</td><td>##IDS_ERROR_27532##</td></row>\r
+               <row><td>27533</td><td>##IDS_ERROR_27533##</td></row>\r
+               <row><td>27534</td><td>##IDS_ERROR_27534##</td></row>\r
+               <row><td>27535</td><td>##IDS_ERROR_27535##</td></row>\r
+               <row><td>27536</td><td>##IDS_ERROR_27536##</td></row>\r
+               <row><td>27537</td><td>##IDS_ERROR_27537##</td></row>\r
+               <row><td>27538</td><td>##IDS_ERROR_27538##</td></row>\r
+               <row><td>27539</td><td>##IDS_ERROR_27539##</td></row>\r
+               <row><td>2754</td><td>##IDS_ERROR_2754##</td></row>\r
+               <row><td>27540</td><td>##IDS_ERROR_27540##</td></row>\r
+               <row><td>27541</td><td>##IDS_ERROR_27541##</td></row>\r
+               <row><td>27542</td><td>##IDS_ERROR_27542##</td></row>\r
+               <row><td>27543</td><td>##IDS_ERROR_27543##</td></row>\r
+               <row><td>27544</td><td>##IDS_ERROR_27544##</td></row>\r
+               <row><td>27545</td><td>##IDS_ERROR_27545##</td></row>\r
+               <row><td>27546</td><td>##IDS_ERROR_27546##</td></row>\r
+               <row><td>27547</td><td>##IDS_ERROR_27547##</td></row>\r
+               <row><td>27548</td><td>##IDS_ERROR_27548##</td></row>\r
+               <row><td>27549</td><td>##IDS_ERROR_27549##</td></row>\r
+               <row><td>2755</td><td>##IDS_ERROR_2755##</td></row>\r
+               <row><td>27550</td><td>##IDS_ERROR_27550##</td></row>\r
+               <row><td>27551</td><td>##IDS_ERROR_27551##</td></row>\r
+               <row><td>27552</td><td>##IDS_ERROR_27552##</td></row>\r
+               <row><td>27553</td><td>##IDS_ERROR_27553##</td></row>\r
+               <row><td>27554</td><td>##IDS_ERROR_27554##</td></row>\r
+               <row><td>27555</td><td>##IDS_ERROR_27555##</td></row>\r
+               <row><td>2756</td><td>##IDS_ERROR_2756##</td></row>\r
+               <row><td>2757</td><td>##IDS_ERROR_2757##</td></row>\r
+               <row><td>2758</td><td>##IDS_ERROR_2758##</td></row>\r
+               <row><td>2759</td><td>##IDS_ERROR_2759##</td></row>\r
+               <row><td>2760</td><td>##IDS_ERROR_2760##</td></row>\r
+               <row><td>2761</td><td>##IDS_ERROR_2761##</td></row>\r
+               <row><td>2762</td><td>##IDS_ERROR_2762##</td></row>\r
+               <row><td>2763</td><td>##IDS_ERROR_2763##</td></row>\r
+               <row><td>2765</td><td>##IDS_ERROR_2765##</td></row>\r
+               <row><td>2766</td><td>##IDS_ERROR_2766##</td></row>\r
+               <row><td>2767</td><td>##IDS_ERROR_2767##</td></row>\r
+               <row><td>2768</td><td>##IDS_ERROR_2768##</td></row>\r
+               <row><td>2769</td><td>##IDS_ERROR_2769##</td></row>\r
+               <row><td>2770</td><td>##IDS_ERROR_2770##</td></row>\r
+               <row><td>2771</td><td>##IDS_ERROR_2771##</td></row>\r
+               <row><td>2772</td><td>##IDS_ERROR_2772##</td></row>\r
+               <row><td>2801</td><td>##IDS_ERROR_2801##</td></row>\r
+               <row><td>2802</td><td>##IDS_ERROR_2802##</td></row>\r
+               <row><td>2803</td><td>##IDS_ERROR_2803##</td></row>\r
+               <row><td>2804</td><td>##IDS_ERROR_2804##</td></row>\r
+               <row><td>2806</td><td>##IDS_ERROR_2806##</td></row>\r
+               <row><td>2807</td><td>##IDS_ERROR_2807##</td></row>\r
+               <row><td>2808</td><td>##IDS_ERROR_2808##</td></row>\r
+               <row><td>2809</td><td>##IDS_ERROR_2809##</td></row>\r
+               <row><td>2810</td><td>##IDS_ERROR_2810##</td></row>\r
+               <row><td>2811</td><td>##IDS_ERROR_2811##</td></row>\r
+               <row><td>2812</td><td>##IDS_ERROR_2812##</td></row>\r
+               <row><td>2813</td><td>##IDS_ERROR_2813##</td></row>\r
+               <row><td>2814</td><td>##IDS_ERROR_2814##</td></row>\r
+               <row><td>2815</td><td>##IDS_ERROR_2815##</td></row>\r
+               <row><td>2816</td><td>##IDS_ERROR_2816##</td></row>\r
+               <row><td>2817</td><td>##IDS_ERROR_2817##</td></row>\r
+               <row><td>2818</td><td>##IDS_ERROR_2818##</td></row>\r
+               <row><td>2819</td><td>##IDS_ERROR_2819##</td></row>\r
+               <row><td>2820</td><td>##IDS_ERROR_2820##</td></row>\r
+               <row><td>2821</td><td>##IDS_ERROR_2821##</td></row>\r
+               <row><td>2822</td><td>##IDS_ERROR_2822##</td></row>\r
+               <row><td>2823</td><td>##IDS_ERROR_2823##</td></row>\r
+               <row><td>2824</td><td>##IDS_ERROR_2824##</td></row>\r
+               <row><td>2825</td><td>##IDS_ERROR_2825##</td></row>\r
+               <row><td>2826</td><td>##IDS_ERROR_2826##</td></row>\r
+               <row><td>2827</td><td>##IDS_ERROR_2827##</td></row>\r
+               <row><td>2828</td><td>##IDS_ERROR_2828##</td></row>\r
+               <row><td>2829</td><td>##IDS_ERROR_2829##</td></row>\r
+               <row><td>2830</td><td>##IDS_ERROR_2830##</td></row>\r
+               <row><td>2831</td><td>##IDS_ERROR_2831##</td></row>\r
+               <row><td>2832</td><td>##IDS_ERROR_2832##</td></row>\r
+               <row><td>2833</td><td>##IDS_ERROR_2833##</td></row>\r
+               <row><td>2834</td><td>##IDS_ERROR_2834##</td></row>\r
+               <row><td>2835</td><td>##IDS_ERROR_2835##</td></row>\r
+               <row><td>2836</td><td>##IDS_ERROR_2836##</td></row>\r
+               <row><td>2837</td><td>##IDS_ERROR_2837##</td></row>\r
+               <row><td>2838</td><td>##IDS_ERROR_2838##</td></row>\r
+               <row><td>2839</td><td>##IDS_ERROR_2839##</td></row>\r
+               <row><td>2840</td><td>##IDS_ERROR_2840##</td></row>\r
+               <row><td>2841</td><td>##IDS_ERROR_2841##</td></row>\r
+               <row><td>2842</td><td>##IDS_ERROR_2842##</td></row>\r
+               <row><td>2843</td><td>##IDS_ERROR_2843##</td></row>\r
+               <row><td>2844</td><td>##IDS_ERROR_2844##</td></row>\r
+               <row><td>2845</td><td>##IDS_ERROR_2845##</td></row>\r
+               <row><td>2846</td><td>##IDS_ERROR_2846##</td></row>\r
+               <row><td>2847</td><td>##IDS_ERROR_2847##</td></row>\r
+               <row><td>2848</td><td>##IDS_ERROR_2848##</td></row>\r
+               <row><td>2849</td><td>##IDS_ERROR_2849##</td></row>\r
+               <row><td>2850</td><td>##IDS_ERROR_2850##</td></row>\r
+               <row><td>2851</td><td>##IDS_ERROR_2851##</td></row>\r
+               <row><td>2852</td><td>##IDS_ERROR_2852##</td></row>\r
+               <row><td>2853</td><td>##IDS_ERROR_2853##</td></row>\r
+               <row><td>2854</td><td>##IDS_ERROR_2854##</td></row>\r
+               <row><td>2855</td><td>##IDS_ERROR_2855##</td></row>\r
+               <row><td>2856</td><td>##IDS_ERROR_2856##</td></row>\r
+               <row><td>2857</td><td>##IDS_ERROR_2857##</td></row>\r
+               <row><td>2858</td><td>##IDS_ERROR_2858##</td></row>\r
+               <row><td>2859</td><td>##IDS_ERROR_2859##</td></row>\r
+               <row><td>2860</td><td>##IDS_ERROR_2860##</td></row>\r
+               <row><td>2861</td><td>##IDS_ERROR_2861##</td></row>\r
+               <row><td>2862</td><td>##IDS_ERROR_2862##</td></row>\r
+               <row><td>2863</td><td>##IDS_ERROR_2863##</td></row>\r
+               <row><td>2864</td><td>##IDS_ERROR_2864##</td></row>\r
+               <row><td>2865</td><td>##IDS_ERROR_2865##</td></row>\r
+               <row><td>2866</td><td>##IDS_ERROR_2866##</td></row>\r
+               <row><td>2867</td><td>##IDS_ERROR_2867##</td></row>\r
+               <row><td>2868</td><td>##IDS_ERROR_2868##</td></row>\r
+               <row><td>2869</td><td>##IDS_ERROR_2869##</td></row>\r
+               <row><td>2870</td><td>##IDS_ERROR_2870##</td></row>\r
+               <row><td>2871</td><td>##IDS_ERROR_2871##</td></row>\r
+               <row><td>2872</td><td>##IDS_ERROR_2872##</td></row>\r
+               <row><td>2873</td><td>##IDS_ERROR_2873##</td></row>\r
+               <row><td>2874</td><td>##IDS_ERROR_2874##</td></row>\r
+               <row><td>2875</td><td>##IDS_ERROR_2875##</td></row>\r
+               <row><td>2876</td><td>##IDS_ERROR_2876##</td></row>\r
+               <row><td>2877</td><td>##IDS_ERROR_2877##</td></row>\r
+               <row><td>2878</td><td>##IDS_ERROR_2878##</td></row>\r
+               <row><td>2879</td><td>##IDS_ERROR_2879##</td></row>\r
+               <row><td>2880</td><td>##IDS_ERROR_2880##</td></row>\r
+               <row><td>2881</td><td>##IDS_ERROR_2881##</td></row>\r
+               <row><td>2882</td><td>##IDS_ERROR_2882##</td></row>\r
+               <row><td>2883</td><td>##IDS_ERROR_2883##</td></row>\r
+               <row><td>2884</td><td>##IDS_ERROR_2884##</td></row>\r
+               <row><td>2885</td><td>##IDS_ERROR_2885##</td></row>\r
+               <row><td>2886</td><td>##IDS_ERROR_2886##</td></row>\r
+               <row><td>2887</td><td>##IDS_ERROR_2887##</td></row>\r
+               <row><td>2888</td><td>##IDS_ERROR_2888##</td></row>\r
+               <row><td>2889</td><td>##IDS_ERROR_2889##</td></row>\r
+               <row><td>2890</td><td>##IDS_ERROR_2890##</td></row>\r
+               <row><td>2891</td><td>##IDS_ERROR_2891##</td></row>\r
+               <row><td>2892</td><td>##IDS_ERROR_2892##</td></row>\r
+               <row><td>2893</td><td>##IDS_ERROR_2893##</td></row>\r
+               <row><td>2894</td><td>##IDS_ERROR_2894##</td></row>\r
+               <row><td>2895</td><td>##IDS_ERROR_2895##</td></row>\r
+               <row><td>2896</td><td>##IDS_ERROR_2896##</td></row>\r
+               <row><td>2897</td><td>##IDS_ERROR_2897##</td></row>\r
+               <row><td>2898</td><td>##IDS_ERROR_2898##</td></row>\r
+               <row><td>2899</td><td>##IDS_ERROR_2899##</td></row>\r
+               <row><td>2901</td><td>##IDS_ERROR_2901##</td></row>\r
+               <row><td>2902</td><td>##IDS_ERROR_2902##</td></row>\r
+               <row><td>2903</td><td>##IDS_ERROR_2903##</td></row>\r
+               <row><td>2904</td><td>##IDS_ERROR_2904##</td></row>\r
+               <row><td>2905</td><td>##IDS_ERROR_2905##</td></row>\r
+               <row><td>2906</td><td>##IDS_ERROR_2906##</td></row>\r
+               <row><td>2907</td><td>##IDS_ERROR_2907##</td></row>\r
+               <row><td>2908</td><td>##IDS_ERROR_2908##</td></row>\r
+               <row><td>2909</td><td>##IDS_ERROR_2909##</td></row>\r
+               <row><td>2910</td><td>##IDS_ERROR_2910##</td></row>\r
+               <row><td>2911</td><td>##IDS_ERROR_2911##</td></row>\r
+               <row><td>2912</td><td>##IDS_ERROR_2912##</td></row>\r
+               <row><td>2919</td><td>##IDS_ERROR_2919##</td></row>\r
+               <row><td>2920</td><td>##IDS_ERROR_2920##</td></row>\r
+               <row><td>2924</td><td>##IDS_ERROR_2924##</td></row>\r
+               <row><td>2927</td><td>##IDS_ERROR_2927##</td></row>\r
+               <row><td>2928</td><td>##IDS_ERROR_2928##</td></row>\r
+               <row><td>2929</td><td>##IDS_ERROR_2929##</td></row>\r
+               <row><td>2932</td><td>##IDS_ERROR_2932##</td></row>\r
+               <row><td>2933</td><td>##IDS_ERROR_2933##</td></row>\r
+               <row><td>2934</td><td>##IDS_ERROR_2934##</td></row>\r
+               <row><td>2935</td><td>##IDS_ERROR_2935##</td></row>\r
+               <row><td>2936</td><td>##IDS_ERROR_2936##</td></row>\r
+               <row><td>2937</td><td>##IDS_ERROR_2937##</td></row>\r
+               <row><td>2938</td><td>##IDS_ERROR_2938##</td></row>\r
+               <row><td>2939</td><td>##IDS_ERROR_2939##</td></row>\r
+               <row><td>2940</td><td>##IDS_ERROR_2940##</td></row>\r
+               <row><td>2941</td><td>##IDS_ERROR_2941##</td></row>\r
+               <row><td>2942</td><td>##IDS_ERROR_2942##</td></row>\r
+               <row><td>2943</td><td>##IDS_ERROR_2943##</td></row>\r
+               <row><td>2944</td><td>##IDS_ERROR_2944##</td></row>\r
+               <row><td>2945</td><td>##IDS_ERROR_2945##</td></row>\r
+               <row><td>3001</td><td>##IDS_ERROR_3001##</td></row>\r
+               <row><td>3002</td><td>##IDS_ERROR_3002##</td></row>\r
+               <row><td>32</td><td>##IDS_ERROR_20##</td></row>\r
+               <row><td>33</td><td>##IDS_ERROR_21##</td></row>\r
+               <row><td>4</td><td>##IDS_ERROR_3##</td></row>\r
+               <row><td>5</td><td>##IDS_ERROR_4##</td></row>\r
+               <row><td>7</td><td>##IDS_ERROR_5##</td></row>\r
+               <row><td>8</td><td>##IDS_ERROR_6##</td></row>\r
+               <row><td>9</td><td>##IDS_ERROR_7##</td></row>\r
+       </table>\r
+\r
+       <table name="EventMapping">\r
+               <col key="yes" def="s72">Dialog_</col>\r
+               <col key="yes" def="s50">Control_</col>\r
+               <col key="yes" def="s50">Event</col>\r
+               <col def="s50">Attribute</col>\r
+       </table>\r
+\r
+       <table name="Extension">\r
+               <col key="yes" def="s255">Extension</col>\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col def="S255">ProgId_</col>\r
+               <col def="S64">MIME_</col>\r
+               <col def="s38">Feature_</col>\r
+       </table>\r
+\r
+       <table name="Feature">\r
+               <col key="yes" def="s38">Feature</col>\r
+               <col def="S38">Feature_Parent</col>\r
+               <col def="L64">Title</col>\r
+               <col def="L255">Description</col>\r
+               <col def="I2">Display</col>\r
+               <col def="i2">Level</col>\r
+               <col def="S72">Directory_</col>\r
+               <col def="i2">Attributes</col>\r
+               <col def="S255">ISReleaseFlags</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="S255">ISFeatureCabName</col>\r
+               <col def="S255">ISProFeatureName</col>\r
+               <row><td>SimanticsSysdyn32</td><td/><td>##ID_STRING7##</td><td>##ID_STRING8##</td><td>2</td><td>1</td><td>INSTALLDIR</td><td>0</td><td>x32sysdyn</td><td/><td/><td/></row>\r
+               <row><td>SimanticsSysdyn64</td><td/><td>##ID_STRING9##</td><td>##ID_STRING10##</td><td>4</td><td>1</td><td>INSTALLDIR</td><td>0</td><td>x64sysdyn</td><td/><td/><td/></row>\r
+       </table>\r
+\r
+       <table name="FeatureComponents">\r
+               <col key="yes" def="s38">Feature_</col>\r
+               <col key="yes" def="s72">Component_</col>\r
+               <row><td>SimanticsSysdyn32</td><td>SimanticsSysdyn32Files</td></row>\r
+               <row><td>SimanticsSysdyn64</td><td>SimanticsSysdyn64Files</td></row>\r
+       </table>\r
+\r
+       <table name="File">\r
+               <col key="yes" def="s72">File</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="s255">FileName</col>\r
+               <col def="i4">FileSize</col>\r
+               <col def="S72">Version</col>\r
+               <col def="S20">Language</col>\r
+               <col def="I2">Attributes</col>\r
+               <col def="i2">Sequence</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <col def="S72">ISComponentSubFolder_</col>\r
+       </table>\r
+\r
+       <table name="FileSFPCatalog">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col key="yes" def="s255">SFPCatalog_</col>\r
+       </table>\r
+\r
+       <table name="Font">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col def="S128">FontTitle</col>\r
+       </table>\r
+\r
+       <table name="ISAlias">\r
+               <col key="yes" def="S0">Alias</col>\r
+               <col key="yes" def="S72">Identifier</col>\r
+               <col key="yes" def="S50">Table</col>\r
+       </table>\r
+\r
+       <table name="ISAssistantTag">\r
+               <col key="yes" def="s72">Tag</col>\r
+               <col def="S255">Data</col>\r
+               <row><td>BiildCDROMEnabled</td><td/></row>\r
+               <row><td>BiildInternetEnabled</td><td/></row>\r
+               <row><td>BiildSingleExeEnabled</td><td>Yes</td></row>\r
+               <row><td>BiildSingleMSIEnabled</td><td/></row>\r
+               <row><td>PROJECT_ASSISTANT_DEFAULT_FEATURE</td><td>DefaultFeature</td></row>\r
+               <row><td>PROJECT_ASSISTANT_FEATURES</td><td>Selectable</td></row>\r
+       </table>\r
+\r
+       <table name="ISCEApp">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col def="s50">AppName</col>\r
+               <col def="s200">CompanyName</col>\r
+               <col def="s50">DefDir</col>\r
+               <col def="S255">IconPath</col>\r
+               <col def="I4">IconIndex</col>\r
+               <col def="S255">DeviceFile</col>\r
+               <col def="s50">DesktopTargetDir</col>\r
+               <col def="S255">Description</col>\r
+               <col def="i2">DeleteMedia</col>\r
+               <col def="I4">InstallNetCF</col>\r
+               <col def="I4">InstallSQLServer</col>\r
+               <col def="I4">InstallSQLClient</col>\r
+               <col def="I4">InstallSQLDev</col>\r
+               <col def="S255">PreXML</col>\r
+               <col def="S255">PostXML</col>\r
+               <col def="I2">NoUninstall</col>\r
+               <col def="S255">SPCFile</col>\r
+               <col def="S255">PVKFile</col>\r
+               <col def="I4">Attributes</col>\r
+               <col def="S255">RawDeviceFile</col>\r
+               <col def="S72">Component_</col>\r
+               <col def="I4">InstallNetCF2</col>\r
+               <col def="I4">InstallSQLServer2</col>\r
+               <col def="I4">InstallSQLClient2</col>\r
+               <col def="I4">InstallSQLDev2</col>\r
+               <col def="S255">SPCPwd</col>\r
+       </table>\r
+\r
+       <table name="ISCEDir">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col key="yes" def="s50">DirKey</col>\r
+               <col def="s50">DirParent</col>\r
+               <col def="s255">DirValue</col>\r
+       </table>\r
+\r
+       <table name="ISCEFile">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col key="yes" def="s50">FileKey</col>\r
+               <col def="s255">Name</col>\r
+               <col def="s50">Destination</col>\r
+               <col def="s255">Source</col>\r
+               <col def="i4">Processor</col>\r
+               <col def="i4">Platform</col>\r
+               <col def="i4">CopyOption</col>\r
+               <col def="i4">FileOption</col>\r
+               <col def="I4">AdvancedOptions</col>\r
+       </table>\r
+\r
+       <table name="ISCEFileExt">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col key="yes" def="s50">ExtKey</col>\r
+               <col def="s50">FileKey</col>\r
+               <col def="S255">Description</col>\r
+               <col def="s50">Extension</col>\r
+               <col def="i4">IconIndex</col>\r
+       </table>\r
+\r
+       <table name="ISCEInstall">\r
+               <col key="yes" def="s255">CEInstallKey</col>\r
+               <col def="s255">CEAppName</col>\r
+               <col def="s255">CEDesktopDir</col>\r
+               <col def="s255">CEIniFileKey</col>\r
+               <col def="s0">CECabs</col>\r
+               <col def="s0">CEIcoFile</col>\r
+               <col def="i2">DeleteMedia</col>\r
+               <col def="S38">Component_</col>\r
+       </table>\r
+\r
+       <table name="ISCEOtherAppCABs">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col key="yes" def="s50">FileKey</col>\r
+               <col def="s255">BuildSourcePath</col>\r
+       </table>\r
+\r
+       <table name="ISCERedist">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col key="yes" def="S50">Name</col>\r
+               <col def="I4">Platforms</col>\r
+       </table>\r
+\r
+       <table name="ISCERegistry">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col key="yes" def="s50">RegKey</col>\r
+               <col def="i4">Root</col>\r
+               <col def="s255">Key</col>\r
+               <col def="S255">Name</col>\r
+               <col def="S0">Value</col>\r
+               <col def="i4">Processor</col>\r
+               <col def="i4">Platform</col>\r
+               <col def="i4">Overwrite</col>\r
+       </table>\r
+\r
+       <table name="ISCESetupFile">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col key="yes" def="s50">SetupFileKey</col>\r
+               <col def="s255">Name</col>\r
+               <col def="s255">Source</col>\r
+               <col def="i4">Processor</col>\r
+               <col def="i4">Platform</col>\r
+       </table>\r
+\r
+       <table name="ISCEShtCut">\r
+               <col key="yes" def="s50">AppKey</col>\r
+               <col key="yes" def="s50">ShtCutKey</col>\r
+               <col def="s255">DisplayName</col>\r
+               <col def="s255">Destination</col>\r
+               <col def="s50">Target</col>\r
+               <col def="i4">Platform</col>\r
+               <col def="S255">StartScreenIcon</col>\r
+       </table>\r
+\r
+       <table name="ISChainPackage">\r
+               <col key="yes" def="s72">Package</col>\r
+               <col def="S255">SourcePath</col>\r
+               <col def="S72">ProductCode</col>\r
+               <col def="i2">Order</col>\r
+               <col def="i4">Options</col>\r
+               <col def="S255">InstallCondition</col>\r
+               <col def="S255">RemoveCondition</col>\r
+               <col def="S0">InstallProperties</col>\r
+               <col def="S0">RemoveProperties</col>\r
+               <col def="S255">ISReleaseFlags</col>\r
+               <col def="S72">DisplayName</col>\r
+       </table>\r
+\r
+       <table name="ISChainPackageData">\r
+               <col key="yes" def="s72">Package_</col>\r
+               <col key="yes" def="s72">File</col>\r
+               <col def="s50">FilePath</col>\r
+               <col def="I4">Options</col>\r
+               <col def="V0">Data</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+       </table>\r
+\r
+       <table name="ISClrWrap">\r
+               <col key="yes" def="s72">Action_</col>\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="S0">Value</col>\r
+       </table>\r
+\r
+       <table name="ISComCatalogAttribute">\r
+               <col key="yes" def="s72">ISComCatalogObject_</col>\r
+               <col key="yes" def="s255">ItemName</col>\r
+               <col def="S0">ItemValue</col>\r
+       </table>\r
+\r
+       <table name="ISComCatalogCollection">\r
+               <col key="yes" def="s72">ISComCatalogCollection</col>\r
+               <col def="s72">ISComCatalogObject_</col>\r
+               <col def="s255">CollectionName</col>\r
+       </table>\r
+\r
+       <table name="ISComCatalogCollectionObjects">\r
+               <col key="yes" def="s72">ISComCatalogCollection_</col>\r
+               <col key="yes" def="s72">ISComCatalogObject_</col>\r
+       </table>\r
+\r
+       <table name="ISComCatalogObject">\r
+               <col key="yes" def="s72">ISComCatalogObject</col>\r
+               <col def="s255">DisplayName</col>\r
+       </table>\r
+\r
+       <table name="ISComPlusApplication">\r
+               <col key="yes" def="s72">ISComCatalogObject_</col>\r
+               <col def="S255">ComputerName</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="I2">ISAttributes</col>\r
+               <col def="S0">DepFiles</col>\r
+       </table>\r
+\r
+       <table name="ISComPlusApplicationDLL">\r
+               <col key="yes" def="s72">ISComPlusApplicationDLL</col>\r
+               <col def="s72">ISComPlusApplication_</col>\r
+               <col def="s72">ISComCatalogObject_</col>\r
+               <col def="s0">CLSID</col>\r
+               <col def="S0">ProgId</col>\r
+               <col def="S0">DLL</col>\r
+               <col def="S0">AlterDLL</col>\r
+       </table>\r
+\r
+       <table name="ISComPlusProxy">\r
+               <col key="yes" def="s72">ISComPlusProxy</col>\r
+               <col def="s72">ISComPlusApplication_</col>\r
+               <col def="S72">Component_</col>\r
+               <col def="I2">ISAttributes</col>\r
+               <col def="S0">DepFiles</col>\r
+       </table>\r
+\r
+       <table name="ISComPlusProxyDepFile">\r
+               <col key="yes" def="s72">ISComPlusApplication_</col>\r
+               <col key="yes" def="s72">File_</col>\r
+               <col def="S0">ISPath</col>\r
+       </table>\r
+\r
+       <table name="ISComPlusProxyFile">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col key="yes" def="s72">ISComPlusApplicationDLL_</col>\r
+       </table>\r
+\r
+       <table name="ISComPlusServerDepFile">\r
+               <col key="yes" def="s72">ISComPlusApplication_</col>\r
+               <col key="yes" def="s72">File_</col>\r
+               <col def="S0">ISPath</col>\r
+       </table>\r
+\r
+       <table name="ISComPlusServerFile">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col key="yes" def="s72">ISComPlusApplicationDLL_</col>\r
+       </table>\r
+\r
+       <table name="ISComponentExtended">\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col def="I4">OS</col>\r
+               <col def="S0">Language</col>\r
+               <col def="s72">FilterProperty</col>\r
+               <col def="I4">Platforms</col>\r
+               <col def="S0">FTPLocation</col>\r
+               <col def="S0">HTTPLocation</col>\r
+               <col def="S0">Miscellaneous</col>\r
+               <row><td>SimanticsSysdyn32Files</td><td/><td/><td>_F8E0099F_A86C_4346_9244_C6419CC06362_FILTER</td><td/><td/><td/><td/></row>\r
+               <row><td>SimanticsSysdyn64Files</td><td/><td/><td>_207D72CB_D769_481A_9977_0120195FAB31_FILTER</td><td/><td/><td/><td/></row>\r
+       </table>\r
+\r
+       <table name="ISCustomActionReference">\r
+               <col key="yes" def="s72">Action_</col>\r
+               <col def="S0">Description</col>\r
+               <col def="S255">FileType</col>\r
+               <col def="S255">ISCAReferenceFilePath</col>\r
+       </table>\r
+\r
+       <table name="ISDLLWrapper">\r
+               <col key="yes" def="s72">EntryPoint</col>\r
+               <col def="I4">Type</col>\r
+               <col def="s0">Source</col>\r
+               <col def="s255">Target</col>\r
+       </table>\r
+\r
+       <table name="ISDRMFile">\r
+               <col key="yes" def="s72">ISDRMFile</col>\r
+               <col def="S72">File_</col>\r
+               <col def="S72">ISDRMLicense_</col>\r
+               <col def="s255">Shell</col>\r
+       </table>\r
+\r
+       <table name="ISDRMFileAttribute">\r
+               <col key="yes" def="s72">ISDRMFile_</col>\r
+               <col key="yes" def="s72">Property</col>\r
+               <col def="S0">Value</col>\r
+       </table>\r
+\r
+       <table name="ISDRMLicense">\r
+               <col key="yes" def="s72">ISDRMLicense</col>\r
+               <col def="S255">Description</col>\r
+               <col def="S50">ProjectVersion</col>\r
+               <col def="I4">Attributes</col>\r
+               <col def="S255">LicenseNumber</col>\r
+               <col def="S255">RequestCode</col>\r
+               <col def="S255">ResponseCode</col>\r
+       </table>\r
+\r
+       <table name="ISDependency">\r
+               <col key="yes" def="S50">ISDependency</col>\r
+               <col def="I2">Exclude</col>\r
+       </table>\r
+\r
+       <table name="ISDisk1File">\r
+               <col key="yes" def="s72">ISDisk1File</col>\r
+               <col def="s255">ISBuildSourcePath</col>\r
+               <col def="I4">Disk</col>\r
+       </table>\r
+\r
+       <table name="ISDynamicFile">\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col key="yes" def="s255">SourceFolder</col>\r
+               <col def="I2">IncludeFlags</col>\r
+               <col def="S0">IncludeFiles</col>\r
+               <col def="S0">ExcludeFiles</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <row><td>SimanticsSysdyn32Files</td><td>&lt;PATH_TO_SIMANTICS-SYSDY_FI&gt;</td><td>4</td><td/><td>Launcher.exe</td><td>10</td></row>\r
+               <row><td>SimanticsSysdyn64Files</td><td>&lt;SYSDYN&gt;\SimanticsSysdyn64</td><td>4</td><td/><td/><td>10</td></row>\r
+       </table>\r
+\r
+       <table name="ISFeatureExtended">\r
+               <col key="yes" def="s38">Feature_</col>\r
+               <col def="S255">Installing</col>\r
+               <col def="S50">Installed</col>\r
+               <col def="S255">Uninstalling</col>\r
+               <col def="S255">Uninstalled</col>\r
+               <col def="S0">FTPLocation</col>\r
+               <col def="S0">HTTPLocation</col>\r
+               <col def="S0">Miscellaneous</col>\r
+               <col def="L255">StatusText</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <col def="S255">Password</col>\r
+               <col def="S50">CDRomFolder</col>\r
+               <col def="S50">Moniker</col>\r
+               <row><td>SimanticsSysdyn32</td><td/><td>SysdynFeature_Installed</td><td/><td/><td/><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>SimanticsSysdyn64</td><td/><td>SysdynFeature_Installed</td><td/><td/><td/><td/><td/><td/><td/><td/><td/><td/></row>\r
+       </table>\r
+\r
+       <table name="ISFeatureMergeModuleExcludes">\r
+               <col key="yes" def="s38">Feature_</col>\r
+               <col key="yes" def="s255">ModuleID</col>\r
+               <col key="yes" def="i2">Language</col>\r
+       </table>\r
+\r
+       <table name="ISFeatureMergeModules">\r
+               <col key="yes" def="s38">Feature_</col>\r
+               <col key="yes" def="s255">ISMergeModule_</col>\r
+               <col key="yes" def="i2">Language_</col>\r
+       </table>\r
+\r
+       <table name="ISFeatureSetupPrerequisites">\r
+               <col key="yes" def="s38">Feature_</col>\r
+               <col key="yes" def="s72">ISSetupPrerequisites_</col>\r
+       </table>\r
+\r
+       <table name="ISFileManifests">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col key="yes" def="s72">Manifest_</col>\r
+       </table>\r
+\r
+       <table name="ISIISItem">\r
+               <col key="yes" def="s72">ISIISItem</col>\r
+               <col def="S72">ISIISItem_Parent</col>\r
+               <col def="L255">DisplayName</col>\r
+               <col def="i4">Type</col>\r
+               <col def="S72">Component_</col>\r
+       </table>\r
+\r
+       <table name="ISIISProperty">\r
+               <col key="yes" def="s72">ISIISProperty</col>\r
+               <col key="yes" def="s72">ISIISItem_</col>\r
+               <col def="S0">Schema</col>\r
+               <col def="S255">FriendlyName</col>\r
+               <col def="I4">MetaDataProp</col>\r
+               <col def="I4">MetaDataType</col>\r
+               <col def="I4">MetaDataUserType</col>\r
+               <col def="I4">MetaDataAttributes</col>\r
+               <col def="L0">MetaDataValue</col>\r
+               <col def="I4">Order</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="ISInstallScriptAction">\r
+               <col key="yes" def="s72">EntryPoint</col>\r
+               <col def="I4">Type</col>\r
+               <col def="s72">Source</col>\r
+               <col def="S255">Target</col>\r
+       </table>\r
+\r
+       <table name="ISLanguage">\r
+               <col key="yes" def="s50">ISLanguage</col>\r
+               <col def="I2">Included</col>\r
+               <row><td>1033</td><td>1</td></row>\r
+       </table>\r
+\r
+       <table name="ISLinkerLibrary">\r
+               <col key="yes" def="s72">ISLinkerLibrary</col>\r
+               <col def="s255">Library</col>\r
+               <col def="i4">Order</col>\r
+               <row><td>isrt.obl</td><td>isrt.obl</td><td>2</td></row>\r
+               <row><td>iswi.obl</td><td>iswi.obl</td><td>1</td></row>\r
+       </table>\r
+\r
+       <table name="ISLocalControl">\r
+               <col key="yes" def="s72">Dialog_</col>\r
+               <col key="yes" def="s50">Control_</col>\r
+               <col key="yes" def="s50">ISLanguage_</col>\r
+               <col def="I4">Attributes</col>\r
+               <col def="I2">X</col>\r
+               <col def="I2">Y</col>\r
+               <col def="I2">Width</col>\r
+               <col def="I2">Height</col>\r
+               <col def="S72">Binary_</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+       </table>\r
+\r
+       <table name="ISLocalDialog">\r
+               <col key="yes" def="S50">Dialog_</col>\r
+               <col key="yes" def="S50">ISLanguage_</col>\r
+               <col def="I4">Attributes</col>\r
+               <col def="S72">TextStyle_</col>\r
+               <col def="i2">Width</col>\r
+               <col def="i2">Height</col>\r
+       </table>\r
+\r
+       <table name="ISLocalRadioButton">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col key="yes" def="i2">Order</col>\r
+               <col key="yes" def="s50">ISLanguage_</col>\r
+               <col def="i2">X</col>\r
+               <col def="i2">Y</col>\r
+               <col def="i2">Width</col>\r
+               <col def="i2">Height</col>\r
+       </table>\r
+\r
+       <table name="ISLockPermissions">\r
+               <col key="yes" def="s72">LockObject</col>\r
+               <col key="yes" def="s32">Table</col>\r
+               <col key="yes" def="S255">Domain</col>\r
+               <col key="yes" def="s255">User</col>\r
+               <col def="I4">Permission</col>\r
+               <col def="I4">Attributes</col>\r
+       </table>\r
+\r
+       <table name="ISLogicalDisk">\r
+               <col key="yes" def="i2">DiskId</col>\r
+               <col key="yes" def="s255">ISProductConfiguration_</col>\r
+               <col key="yes" def="s255">ISRelease_</col>\r
+               <col def="i2">LastSequence</col>\r
+               <col def="L64">DiskPrompt</col>\r
+               <col def="S255">Cabinet</col>\r
+               <col def="S32">VolumeLabel</col>\r
+               <col def="S32">Source</col>\r
+       </table>\r
+\r
+       <table name="ISLogicalDiskFeatures">\r
+               <col key="yes" def="i2">ISLogicalDisk_</col>\r
+               <col key="yes" def="s255">ISProductConfiguration_</col>\r
+               <col key="yes" def="s255">ISRelease_</col>\r
+               <col key="yes" def="S38">Feature_</col>\r
+               <col def="i2">Sequence</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="ISMergeModule">\r
+               <col key="yes" def="s255">ISMergeModule</col>\r
+               <col key="yes" def="i2">Language</col>\r
+               <col def="s255">Name</col>\r
+               <col def="S255">Destination</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="ISMergeModuleCfgValues">\r
+               <col key="yes" def="s255">ISMergeModule_</col>\r
+               <col key="yes" def="i2">Language_</col>\r
+               <col key="yes" def="s72">ModuleConfiguration_</col>\r
+               <col def="L0">Value</col>\r
+               <col def="i2">Format</col>\r
+               <col def="L255">Type</col>\r
+               <col def="L255">ContextData</col>\r
+               <col def="L255">DefaultValue</col>\r
+               <col def="I2">Attributes</col>\r
+               <col def="L255">DisplayName</col>\r
+               <col def="L255">Description</col>\r
+               <col def="L255">HelpLocation</col>\r
+               <col def="L255">HelpKeyword</col>\r
+       </table>\r
+\r
+       <table name="ISObject">\r
+               <col key="yes" def="s50">ObjectName</col>\r
+               <col def="s15">Language</col>\r
+       </table>\r
+\r
+       <table name="ISObjectProperty">\r
+               <col key="yes" def="S50">ObjectName</col>\r
+               <col key="yes" def="S50">Property</col>\r
+               <col def="S0">Value</col>\r
+               <col def="I2">IncludeInBuild</col>\r
+       </table>\r
+\r
+       <table name="ISPalmApp">\r
+               <col key="yes" def="s72">PalmApp</col>\r
+               <col key="yes" def="s72">Component</col>\r
+       </table>\r
+\r
+       <table name="ISPalmAppFile">\r
+               <col key="yes" def="s72">PalmApp</col>\r
+               <col key="yes" def="s72">FileKey</col>\r
+               <col def="i4">Destination</col>\r
+       </table>\r
+\r
+       <table name="ISPatchConfigImage">\r
+               <col key="yes" def="S72">PatchConfiguration_</col>\r
+               <col key="yes" def="s72">UpgradedImage_</col>\r
+       </table>\r
+\r
+       <table name="ISPatchConfiguration">\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="i2">CanPCDiffer</col>\r
+               <col def="i2">CanPVDiffer</col>\r
+               <col def="i2">IncludeWholeFiles</col>\r
+               <col def="i2">LeaveDecompressed</col>\r
+               <col def="i2">OptimizeForSize</col>\r
+               <col def="i2">EnablePatchCache</col>\r
+               <col def="S0">PatchCacheDir</col>\r
+               <col def="i4">Flags</col>\r
+               <col def="S0">PatchGuidsToReplace</col>\r
+               <col def="s0">TargetProductCodes</col>\r
+               <col def="s50">PatchGuid</col>\r
+               <col def="s0">OutputPath</col>\r
+               <col def="i2">MinMsiVersion</col>\r
+               <col def="I4">Attributes</col>\r
+       </table>\r
+\r
+       <table name="ISPatchConfigurationProperty">\r
+               <col key="yes" def="S72">ISPatchConfiguration_</col>\r
+               <col key="yes" def="S50">Property</col>\r
+               <col def="S50">Value</col>\r
+       </table>\r
+\r
+       <table name="ISPatchExternalFile">\r
+               <col key="yes" def="s50">Name</col>\r
+               <col key="yes" def="s13">ISUpgradedImage_</col>\r
+               <col def="s72">FileKey</col>\r
+               <col def="s255">FilePath</col>\r
+       </table>\r
+\r
+       <table name="ISPatchWholeFile">\r
+               <col key="yes" def="s50">UpgradedImage</col>\r
+               <col key="yes" def="s72">FileKey</col>\r
+               <col def="S72">Component</col>\r
+       </table>\r
+\r
+       <table name="ISPathVariable">\r
+               <col key="yes" def="s32">ISPathVariable</col>\r
+               <col def="S255">Value</col>\r
+               <col def="S255">TestValue</col>\r
+               <col def="i4">Type</col>\r
+               <row><td>CommonFilesFolder</td><td/><td/><td>1</td></row>\r
+               <row><td>ISPROJECTDIR</td><td/><td/><td>1</td></row>\r
+               <row><td>ISProductFolder</td><td/><td/><td>1</td></row>\r
+               <row><td>ISProjectDataFolder</td><td/><td/><td>1</td></row>\r
+               <row><td>ISProjectFolder</td><td/><td/><td>1</td></row>\r
+               <row><td>PATH_TO_BIN.NT_FILES</td><td>&lt;ROOT&gt;\apros\Apros5\bin.nt</td><td/><td>2</td></row>\r
+               <row><td>PATH_TO_GRAPHICS_FILES</td><td>&lt;ROOT&gt;\extra</td><td/><td>2</td></row>\r
+               <row><td>PATH_TO_SIMANTICS-SYSDY_FI</td><td>&lt;SYSDYN&gt;\SimanticsSysdyn32</td><td/><td>2</td></row>\r
+               <row><td>ProgramFilesFolder</td><td/><td/><td>1</td></row>\r
+               <row><td>ROOT</td><td>&lt;ISProjectFolder&gt;\..\..</td><td/><td>2</td></row>\r
+               <row><td>SYSDYN</td><td>&lt;ROOT&gt;\sysdyn</td><td/><td>2</td></row>\r
+               <row><td>SystemFolder</td><td/><td/><td>1</td></row>\r
+               <row><td>WindowsFolder</td><td/><td/><td>1</td></row>\r
+       </table>\r
+\r
+       <table name="ISProductConfiguration">\r
+               <col key="yes" def="s72">ISProductConfiguration</col>\r
+               <col def="S255">ProductConfigurationFlags</col>\r
+               <col def="I4">GeneratePackageCode</col>\r
+               <row><td>S3</td><td>x32sysdyn, sysdyn</td><td>1</td></row>\r
+               <row><td>S6</td><td>x64sysdyn, sysdyn</td><td>1</td></row>\r
+       </table>\r
+\r
+       <table name="ISProductConfigurationInstance">\r
+               <col key="yes" def="s72">ISProductConfiguration_</col>\r
+               <col key="yes" def="i2">InstanceId</col>\r
+               <col key="yes" def="s72">Property</col>\r
+               <col def="s255">Value</col>\r
+       </table>\r
+\r
+       <table name="ISProductConfigurationProperty">\r
+               <col key="yes" def="s72">ISProductConfiguration_</col>\r
+               <col key="yes" def="s72">Property</col>\r
+               <col def="L255">Value</col>\r
+               <row><td>S3</td><td>IncludeActionHelp</td><td>1</td></row>\r
+               <row><td>S3</td><td>PreProcessorDefines</td><td>x32,sysdyn</td></row>\r
+               <row><td>S3</td><td>ProductCode</td><td>{C0690109-F799-4836-A38F-F77C55C435F8}</td></row>\r
+               <row><td>S3</td><td>ProductName</td><td>Simantics 1.7.0 Sysdyn 32</td></row>\r
+               <row><td>S3</td><td>SetupFileName</td><td>Simantics 1.7.0 Sysdyn 32 setup</td></row>\r
+               <row><td>S3</td><td>TemplateSummary</td><td>Intel;1033</td></row>\r
+               <row><td>S3</td><td>UpgradeCode</td><td>{D85384A8-F5DB-454C-94F6-43C20F559884}</td></row>\r
+               <row><td>S6</td><td>IncludeActionHelp</td><td>1</td></row>\r
+               <row><td>S6</td><td>PreProcessorDefines</td><td>x64, sysdyn</td></row>\r
+               <row><td>S6</td><td>ProductCode</td><td>{90CA3AEF-AEB9-48C7-B64D-6492910581ED}</td></row>\r
+               <row><td>S6</td><td>ProductName</td><td>Simantics 1.6.0 Sysdyn 64</td></row>\r
+               <row><td>S6</td><td>SetupFileName</td><td>Simantics 1.6.0 Sysdyn 64 setup</td></row>\r
+               <row><td>S6</td><td>TemplateSummary</td><td>x64;1033</td></row>\r
+               <row><td>S6</td><td>UpgradeCode</td><td>{6B14D4A3-D430-4513-A26E-78E15281ABFE}</td></row>\r
+       </table>\r
+\r
+       <table name="ISRelease">\r
+               <col key="yes" def="s72">ISRelease</col>\r
+               <col key="yes" def="s72">ISProductConfiguration_</col>\r
+               <col def="s255">BuildLocation</col>\r
+               <col def="s255">PackageName</col>\r
+               <col def="i4">Type</col>\r
+               <col def="s0">SupportedLanguagesUI</col>\r
+               <col def="i4">MsiSourceType</col>\r
+               <col def="i4">ReleaseType</col>\r
+               <col def="s72">Platforms</col>\r
+               <col def="S0">SupportedLanguagesData</col>\r
+               <col def="s6">DefaultLanguage</col>\r
+               <col def="i4">SupportedOSs</col>\r
+               <col def="s50">DiskSize</col>\r
+               <col def="i4">DiskSizeUnit</col>\r
+               <col def="i4">DiskClusterSize</col>\r
+               <col def="S0">ReleaseFlags</col>\r
+               <col def="i4">DiskSpanning</col>\r
+               <col def="S255">SynchMsi</col>\r
+               <col def="s255">MediaLocation</col>\r
+               <col def="S255">URLLocation</col>\r
+               <col def="S255">DigitalURL</col>\r
+               <col def="S255">DigitalPVK</col>\r
+               <col def="S255">DigitalSPC</col>\r
+               <col def="S255">Password</col>\r
+               <col def="S255">VersionCopyright</col>\r
+               <col def="i4">Attributes</col>\r
+               <col def="S255">CDBrowser</col>\r
+               <col def="S255">DotNetBuildConfiguration</col>\r
+               <col def="S255">MsiCommandLine</col>\r
+               <col def="I4">ISSetupPrerequisiteLocation</col>\r
+               <row><td>S3</td><td>S3</td><td>C:\S</td><td>PackageName</td><td>1</td><td>1033</td><td>2</td><td>1</td><td>Intel</td><td/><td>1033</td><td>0</td><td>0</td><td>0</td><td>0</td><td/><td>0</td><td/><td>MediaLocation</td><td/><td>http://www.vtt.fi</td><td/><td>&lt;PATH_TO_GRAPHICS_FILES&gt;\vtt_is.pfx</td><td/><td/><td>8464399</td><td/><td/><td/><td/></row>\r
+               <row><td>S6</td><td>S6</td><td>C:\S</td><td>PackageName</td><td>1</td><td>1033</td><td>2</td><td>1</td><td>Intel</td><td/><td>1033</td><td>0</td><td>0</td><td>0</td><td>0</td><td/><td>0</td><td/><td>MediaLocation</td><td/><td>http://www.vtt.fi</td><td/><td>&lt;PATH_TO_GRAPHICS_FILES&gt;\vtt_is.pfx</td><td/><td/><td>8464399</td><td/><td/><td/><td/></row>\r
+       </table>\r
+\r
+       <table name="ISReleaseExtended">\r
+               <col key="yes" def="s72">ISRelease_</col>\r
+               <col key="yes" def="s72">ISProductConfiguration_</col>\r
+               <col def="I4">WebType</col>\r
+               <col def="S255">WebURL</col>\r
+               <col def="I4">WebCabSize</col>\r
+               <col def="S255">OneClickCabName</col>\r
+               <col def="S255">OneClickHtmlName</col>\r
+               <col def="S255">WebLocalCachePath</col>\r
+               <col def="I4">EngineLocation</col>\r
+               <col def="S255">Win9xMsiUrl</col>\r
+               <col def="S255">WinNTMsiUrl</col>\r
+               <col def="I4">ISEngineLocation</col>\r
+               <col def="S255">ISEngineURL</col>\r
+               <col def="I4">OneClickTargetBrowser</col>\r
+               <col def="S255">DigitalCertificateIdNS</col>\r
+               <col def="S255">DigitalCertificateDBaseNS</col>\r
+               <col def="S255">DigitalCertificatePasswordNS</col>\r
+               <col def="I4">DotNetRedistLocation</col>\r
+               <col def="S255">DotNetRedistURL</col>\r
+               <col def="I4">DotNetVersion</col>\r
+               <col def="S255">DotNetBaseLanguage</col>\r
+               <col def="S0">DotNetLangaugePacks</col>\r
+               <col def="S255">DotNetFxCmdLine</col>\r
+               <col def="S255">DotNetLangPackCmdLine</col>\r
+               <col def="S50">JSharpCmdLine</col>\r
+               <col def="I4">Attributes</col>\r
+               <col def="I4">JSharpRedistLocation</col>\r
+               <col def="I4">MsiEngineVersion</col>\r
+               <col def="S255">WinMsi30Url</col>\r
+               <col def="S255">CertPassword</col>\r
+               <row><td>S3</td><td>S3</td><td>0</td><td>http://</td><td>0</td><td>install</td><td>install</td><td>[LocalAppDataFolder]Downloaded Installations</td><td>1</td><td>http://www.installengine.com/Msiengine20</td><td>http://www.installengine.com/Msiengine20</td><td/><td>http://www.installengine.com/cert05/isengine</td><td/><td/><td/><td/><td>3</td><td>http://www.installengine.com/cert05/dotnetfx</td><td>0</td><td>1033</td><td/><td/><td/><td/><td>1040</td><td>3</td><td>4</td><td>http://www.installengine.com/Msiengine30</td><td>ECBEB5CE</td></row>\r
+               <row><td>S6</td><td>S6</td><td>0</td><td>http://</td><td>0</td><td>install</td><td>install</td><td>[LocalAppDataFolder]Downloaded Installations</td><td>1</td><td>http://www.installengine.com/Msiengine20</td><td>http://www.installengine.com/Msiengine20</td><td/><td>http://www.installengine.com/cert05/isengine</td><td/><td/><td/><td/><td>3</td><td>http://www.installengine.com/cert05/dotnetfx</td><td>0</td><td>1033</td><td/><td/><td/><td/><td>1040</td><td>3</td><td>4</td><td>http://www.installengine.com/Msiengine30</td><td>ECBEB5CE</td></row>\r
+       </table>\r
+\r
+       <table name="ISReleaseProperty">\r
+               <col key="yes" def="s72">ISRelease_</col>\r
+               <col key="yes" def="s72">ISProductConfiguration_</col>\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="s0">Value</col>\r
+               <row><td>S3</td><td>S3</td><td>SetupIcon</td><td>&lt;PATH_TO_SIMANTICS-SYSDY_FI&gt;\puzzle_green.ico,0</td></row>\r
+               <row><td>S6</td><td>S6</td><td>SetupIcon</td><td>&lt;PATH_TO_SIMANTICS-SYSDY_FI&gt;\puzzle_green.ico,0</td></row>\r
+       </table>\r
+\r
+       <table name="ISReleasePublishInfo">\r
+               <col key="yes" def="s72">ISRelease_</col>\r
+               <col key="yes" def="s72">ISProductConfiguration_</col>\r
+               <col def="S255">Repository</col>\r
+               <col def="S255">DisplayName</col>\r
+               <col def="S255">Publisher</col>\r
+               <col def="S255">Description</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="ISRequiredFeature">\r
+               <col key="yes" def="s38">RequiringFeature</col>\r
+               <col key="yes" def="s38">RequiredFeature</col>\r
+       </table>\r
+\r
+       <table name="ISSQLConnection">\r
+               <col key="yes" def="s72">ISSQLConnection</col>\r
+               <col def="s255">Server</col>\r
+               <col def="s255">Database</col>\r
+               <col def="s255">UserName</col>\r
+               <col def="s255">Password</col>\r
+               <col def="s255">Authentication</col>\r
+               <col def="i2">Attributes</col>\r
+               <col def="i2">Order</col>\r
+               <col def="S0">Comments</col>\r
+               <col def="I4">CmdTimeout</col>\r
+               <col def="S0">BatchSeparator</col>\r
+               <col def="S0">ScriptVersion_Table</col>\r
+               <col def="S0">ScriptVersion_Column</col>\r
+       </table>\r
+\r
+       <table name="ISSQLConnectionDBServer">\r
+               <col key="yes" def="s72">ISSQLConnectionDBServer</col>\r
+               <col key="yes" def="s72">ISSQLConnection_</col>\r
+               <col key="yes" def="s72">ISSQLDBMetaData_</col>\r
+               <col def="i2">Order</col>\r
+       </table>\r
+\r
+       <table name="ISSQLConnectionScript">\r
+               <col key="yes" def="s72">ISSQLConnection_</col>\r
+               <col key="yes" def="s72">ISSQLScriptFile_</col>\r
+               <col def="i2">Order</col>\r
+       </table>\r
+\r
+       <table name="ISSQLDBMetaData">\r
+               <col key="yes" def="s72">ISSQLDBMetaData</col>\r
+               <col def="S0">DisplayName</col>\r
+               <col def="S0">AdoDriverName</col>\r
+               <col def="S0">AdoCxnDriver</col>\r
+               <col def="S0">AdoCxnServer</col>\r
+               <col def="S0">AdoCxnDatabase</col>\r
+               <col def="S0">AdoCxnUserID</col>\r
+               <col def="S0">AdoCxnPassword</col>\r
+               <col def="S0">AdoCxnWindowsSecurity</col>\r
+               <col def="S0">AdoCxnNetLibrary</col>\r
+               <col def="S0">TestDatabaseCmd</col>\r
+               <col def="S0">TestTableCmd</col>\r
+               <col def="S0">VersionInfoCmd</col>\r
+               <col def="S0">VersionBeginToken</col>\r
+               <col def="S0">VersionEndToken</col>\r
+               <col def="S0">LocalInstanceNames</col>\r
+               <col def="S0">CreateDbCmd</col>\r
+               <col def="S0">SwitchDbCmd</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <col def="S0">TestTableCmd2</col>\r
+               <col def="S0">WinAuthentUserId</col>\r
+               <col def="S0">DsnODBCName</col>\r
+               <col def="S0">AdoCxnPort</col>\r
+               <col def="S0">AdoCxnAdditional</col>\r
+               <col def="S0">QueryDatabasesCmd</col>\r
+               <col def="S0">CreateTableCmd</col>\r
+               <col def="S0">InsertRecordCmd</col>\r
+               <col def="S0">SelectTableCmd</col>\r
+               <col def="S0">ScriptVersion_Table</col>\r
+               <col def="S0">ScriptVersion_Column</col>\r
+               <col def="S0">ScriptVersion_ColumnType</col>\r
+       </table>\r
+\r
+       <table name="ISSQLRequirement">\r
+               <col key="yes" def="s72">ISSQLRequirement</col>\r
+               <col key="yes" def="s72">ISSQLConnection_</col>\r
+               <col def="S15">MajorVersion</col>\r
+               <col def="S25">ServicePackLevel</col>\r
+               <col def="i4">Attributes</col>\r
+               <col def="S72">ISSQLConnectionDBServer_</col>\r
+       </table>\r
+\r
+       <table name="ISSQLScriptError">\r
+               <col key="yes" def="i4">ErrNumber</col>\r
+               <col key="yes" def="S72">ISSQLScriptFile_</col>\r
+               <col def="i2">ErrHandling</col>\r
+               <col def="L255">Message</col>\r
+               <col def="i2">Attributes</col>\r
+       </table>\r
+\r
+       <table name="ISSQLScriptFile">\r
+               <col key="yes" def="s72">ISSQLScriptFile</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="i2">Scheduling</col>\r
+               <col def="L255">InstallText</col>\r
+               <col def="L255">UninstallText</col>\r
+               <col def="S0">ISBuildSourcePath</col>\r
+               <col def="S0">Comments</col>\r
+               <col def="i2">ErrorHandling</col>\r
+               <col def="i2">Attributes</col>\r
+               <col def="S15">Version</col>\r
+               <col def="S255">Condition</col>\r
+       </table>\r
+\r
+       <table name="ISSQLScriptImport">\r
+               <col key="yes" def="s72">ISSQLScriptFile_</col>\r
+               <col def="S255">Server</col>\r
+               <col def="S255">Database</col>\r
+               <col def="S255">UserName</col>\r
+               <col def="S255">Password</col>\r
+               <col def="i4">Authentication</col>\r
+               <col def="S0">IncludeTables</col>\r
+               <col def="S0">ExcludeTables</col>\r
+               <col def="i4">Attributes</col>\r
+       </table>\r
+\r
+       <table name="ISSQLScriptReplace">\r
+               <col key="yes" def="s72">ISSQLScriptReplace</col>\r
+               <col key="yes" def="s72">ISSQLScriptFile_</col>\r
+               <col def="S0">Search</col>\r
+               <col def="S0">Replace</col>\r
+               <col def="i4">Attributes</col>\r
+       </table>\r
+\r
+       <table name="ISScriptFile">\r
+               <col key="yes" def="s255">ISScriptFile</col>\r
+               <row><td>&lt;ISProjectDataFolder&gt;\Script Files\FeatureEvents.rul</td></row>\r
+               <row><td>&lt;ISProjectDataFolder&gt;\Script Files\Setup.Rul</td></row>\r
+               <row><td>&lt;ISProjectDataFolder&gt;\Script Files\my.rul</td></row>\r
+       </table>\r
+\r
+       <table name="ISSearchReplace">\r
+               <col key="yes" def="s72">ISSearchReplace</col>\r
+               <col def="s72">ISSearchReplaceSet_</col>\r
+               <col def="S0">Search</col>\r
+               <col def="S0">Replace</col>\r
+               <col def="i2">Attributes</col>\r
+               <col def="i2">Order</col>\r
+       </table>\r
+\r
+       <table name="ISSearchReplaceSet">\r
+               <col key="yes" def="s72">ISSearchReplaceSet</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="s72">Directory_</col>\r
+               <col def="S0">IncludeFiles</col>\r
+               <col def="S0">ExcludeFiles</col>\r
+               <col def="i2">Attributes</col>\r
+               <col def="i2">Order</col>\r
+               <col def="i2">CodePage</col>\r
+       </table>\r
+\r
+       <table name="ISSelfReg">\r
+               <col key="yes" def="s72">FileKey</col>\r
+               <col def="I2">Cost</col>\r
+               <col def="I2">Order</col>\r
+               <col def="S50">CmdLine</col>\r
+       </table>\r
+\r
+       <table name="ISSetupFile">\r
+               <col key="yes" def="s72">ISSetupFile</col>\r
+               <col def="S255">FileName</col>\r
+               <col def="V0">Stream</col>\r
+               <col def="S50">Language</col>\r
+               <col def="I2">Splash</col>\r
+               <col def="S0">Path</col>\r
+               <row><td>SetupFile1</td><td>bbrd01.bmp</td><td/><td>0</td><td>0</td><td>&lt;SYSDYN&gt;\extra\bbrd01.bmp</td></row>\r
+               <row><td>SetupFile2</td><td>splash.bmp</td><td/><td>0</td><td>1</td><td>&lt;SYSDYN&gt;\extra\splash.bmp</td></row>\r
+       </table>\r
+\r
+       <table name="ISSetupPrerequisites">\r
+               <col key="yes" def="s72">ISSetupPrerequisites</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+               <col def="I2">Order</col>\r
+               <col def="I2">ISSetupLocation</col>\r
+               <col def="S255">ISReleaseFlags</col>\r
+       </table>\r
+\r
+       <table name="ISSetupType">\r
+               <col key="yes" def="s38">ISSetupType</col>\r
+               <col def="L255">Description</col>\r
+               <col def="L255">Display_Name</col>\r
+               <col def="i2">Display</col>\r
+               <col def="S255">Comments</col>\r
+               <row><td>Complete</td><td>##IDPROP_SETUPTYPE_COMPLETE_DESC##</td><td>##IDPROP_SETUPTYPE_COMPLETE##</td><td>1</td><td/></row>\r
+               <row><td>Custom</td><td>##IDPROP_SETUPTYPE_CUSTOM_DESC_PRO##</td><td>##IDPROP_SETUPTYPE_CUSTOM##</td><td>2</td><td/></row>\r
+       </table>\r
+\r
+       <table name="ISSetupTypeFeatures">\r
+               <col key="yes" def="s38">ISSetupType_</col>\r
+               <col key="yes" def="s38">Feature_</col>\r
+               <row><td>Complete</td><td>SimanticsSysdyn32</td></row>\r
+               <row><td>Complete</td><td>SimanticsSysdyn64</td></row>\r
+               <row><td>Custom</td><td>SimanticsSysdyn32</td></row>\r
+               <row><td>Custom</td><td>SimanticsSysdyn64</td></row>\r
+       </table>\r
+\r
+       <table name="ISStorages">\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="S0">ISBuildSourcePath</col>\r
+       </table>\r
+\r
+       <table name="ISString">\r
+               <col key="yes" def="s255">ISString</col>\r
+               <col key="yes" def="s50">ISLanguage_</col>\r
+               <col def="S0">Value</col>\r
+               <col def="I2">Encoded</col>\r
+               <col def="S0">Comment</col>\r
+               <col def="I4">TimeStamp</col>\r
+               <row><td>COMPANY_NAME</td><td>1033</td><td>Simantics Organization</td><td>0</td><td/><td>723525133</td></row>\r
+               <row><td>DN_AlwaysInstall</td><td>1033</td><td>Always Install</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_EXPRESS_LAUNCH_CONDITION_COLOR</td><td>1033</td><td>The color settings of your system are not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_EXPRESS_LAUNCH_CONDITION_OS</td><td>1033</td><td>The operating system is not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_EXPRESS_LAUNCH_CONDITION_PROCESSOR</td><td>1033</td><td>The processor is not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_EXPRESS_LAUNCH_CONDITION_RAM</td><td>1033</td><td>The amount of RAM is not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_EXPRESS_LAUNCH_CONDITION_SCREEN</td><td>1033</td><td>The screen resolution is not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_COMPACT</td><td>1033</td><td>Compact</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_COMPACT_DESC</td><td>1033</td><td>Compact Description</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_COMPLETE</td><td>1033</td><td>Complete</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_COMPLETE_DESC</td><td>1033</td><td>Complete</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_CUSTOM</td><td>1033</td><td>Custom</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_CUSTOM_DESC</td><td>1033</td><td>Custom Description</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_CUSTOM_DESC_PRO</td><td>1033</td><td>Custom</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_TYPICAL</td><td>1033</td><td>Typical</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDPROP_SETUPTYPE_TYPICAL_DESC</td><td>1033</td><td>Typical Description</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_1</td><td>1033</td><td>[1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_1b</td><td>1033</td><td>[1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_1c</td><td>1033</td><td>[1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_1d</td><td>1033</td><td>[1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Advertising</td><td>1033</td><td>Advertising application</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_AllocatingRegistry</td><td>1033</td><td>Allocating registry space</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_AppCommandLine</td><td>1033</td><td>Application: [1], Command line: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_AppId</td><td>1033</td><td>AppId: [1]{{, AppType: [2]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_AppIdAppTypeRSN</td><td>1033</td><td>AppId: [1]{{, AppType: [2], Users: [3], RSN: [4]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Application</td><td>1033</td><td>Application: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_BindingExes</td><td>1033</td><td>Binding executables</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ClassId</td><td>1033</td><td>Class ID: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ClsID</td><td>1033</td><td>Class ID: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ComponentIDQualifier</td><td>1033</td><td>Component ID: [1], Qualifier: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ComponentIdQualifier2</td><td>1033</td><td>Component ID: [1], Qualifier: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ComputingSpace</td><td>1033</td><td>Computing space requirements</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ComputingSpace2</td><td>1033</td><td>Computing space requirements</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ComputingSpace3</td><td>1033</td><td>Computing space requirements</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ContentTypeExtension</td><td>1033</td><td>MIME Content Type: [1], Extension: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ContentTypeExtension2</td><td>1033</td><td>MIME Content Type: [1], Extension: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_CopyingNetworkFiles</td><td>1033</td><td>Copying files to the network</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_CopyingNewFiles</td><td>1033</td><td>Copying new files</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_CreatingDuplicate</td><td>1033</td><td>Creating duplicate files</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_CreatingFolders</td><td>1033</td><td>Creating folders</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_CreatingIISRoots</td><td>1033</td><td>Creating IIS Virtual Roots...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_CreatingShortcuts</td><td>1033</td><td>Creating shortcuts</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_DeletingServices</td><td>1033</td><td>Deleting services</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_EnvironmentStrings</td><td>1033</td><td>Updating environment strings</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_EvaluateLaunchConditions</td><td>1033</td><td>Evaluating launch conditions</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Extension</td><td>1033</td><td>Extension: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Extension2</td><td>1033</td><td>Extension: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Feature</td><td>1033</td><td>Feature: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FeatureColon</td><td>1033</td><td>Feature: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_File</td><td>1033</td><td>File: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_File2</td><td>1033</td><td>File: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDependencies</td><td>1033</td><td>File: [1],  Dependencies: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDir</td><td>1033</td><td>File: [1], Directory: [9]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDir2</td><td>1033</td><td>File: [1], Directory: [9]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDir3</td><td>1033</td><td>File: [1], Directory: [9]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDirSize</td><td>1033</td><td>File: [1], Directory: [9], Size: [6]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDirSize2</td><td>1033</td><td>File: [1],  Directory: [9],  Size: [6]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDirSize3</td><td>1033</td><td>File: [1],  Directory: [9],  Size: [6]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDirSize4</td><td>1033</td><td>File: [1],  Directory: [2],  Size: [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileDirectorySize</td><td>1033</td><td>File: [1],  Directory: [9],  Size: [6]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileFolder</td><td>1033</td><td>File: [1], Folder: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileFolder2</td><td>1033</td><td>File: [1], Folder: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileSectionKeyValue</td><td>1033</td><td>File: [1],  Section: [2],  Key: [3], Value: [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FileSectionKeyValue2</td><td>1033</td><td>File: [1],  Section: [2],  Key: [3], Value: [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Folder</td><td>1033</td><td>Folder: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Folder1</td><td>1033</td><td>Folder: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Font</td><td>1033</td><td>Font: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Font2</td><td>1033</td><td>Font: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FoundApp</td><td>1033</td><td>Found application: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_FreeSpace</td><td>1033</td><td>Free space: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_GeneratingScript</td><td>1033</td><td>Generating script operations for action:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ISLockPermissionsCost</td><td>1033</td><td>Gathering permissions information for objects...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ISLockPermissionsInstall</td><td>1033</td><td>Applying permissions information for objects...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_InitializeODBCDirs</td><td>1033</td><td>Initializing ODBC directories</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_InstallODBC</td><td>1033</td><td>Installing ODBC components</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_InstallServices</td><td>1033</td><td>Installing new services</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_InstallingSystemCatalog</td><td>1033</td><td>Installing system catalog</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_KeyName</td><td>1033</td><td>Key: [1], Name: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_KeyNameValue</td><td>1033</td><td>Key: [1], Name: [2], Value: [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_LibId</td><td>1033</td><td>LibID: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Libid2</td><td>1033</td><td>LibID: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_MigratingFeatureStates</td><td>1033</td><td>Migrating feature states from related applications</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_MovingFiles</td><td>1033</td><td>Moving files</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_NameValueAction</td><td>1033</td><td>Name: [1], Value: [2], Action [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_NameValueAction2</td><td>1033</td><td>Name: [1], Value: [2], Action [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_PatchingFiles</td><td>1033</td><td>Patching files</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ProgID</td><td>1033</td><td>ProgID: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_ProgID2</td><td>1033</td><td>ProgID: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_PropertySignature</td><td>1033</td><td>Property: [1], Signature: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_PublishProductFeatures</td><td>1033</td><td>Publishing product features</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_PublishProductInfo</td><td>1033</td><td>Publishing product information</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_PublishingQualifiedComponents</td><td>1033</td><td>Publishing qualified components</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegUser</td><td>1033</td><td>Registering user</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisterClassServer</td><td>1033</td><td>Registering class servers</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisterExtensionServers</td><td>1033</td><td>Registering extension servers</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisterFonts</td><td>1033</td><td>Registering fonts</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisterMimeInfo</td><td>1033</td><td>Registering MIME info</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisterTypeLibs</td><td>1033</td><td>Registering type libraries</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisteringComPlus</td><td>1033</td><td>Registering COM+ Applications and Components</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisteringModules</td><td>1033</td><td>Registering modules</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisteringProduct</td><td>1033</td><td>Registering product</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RegisteringProgIdentifiers</td><td>1033</td><td>Registering program identifiers</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemoveApps</td><td>1033</td><td>Removing applications</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingBackup</td><td>1033</td><td>Removing backup files</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingDuplicates</td><td>1033</td><td>Removing duplicated files</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingFiles</td><td>1033</td><td>Removing files</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingFolders</td><td>1033</td><td>Removing folders</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingIISRoots</td><td>1033</td><td>Removing IIS Virtual Roots...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingIni</td><td>1033</td><td>Removing INI file entries</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingMoved</td><td>1033</td><td>Removing moved files</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingODBC</td><td>1033</td><td>Removing ODBC components</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingRegistry</td><td>1033</td><td>Removing system registry values</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RemovingShortcuts</td><td>1033</td><td>Removing shortcuts</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_RollingBack</td><td>1033</td><td>Rolling back action:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_SearchForRelated</td><td>1033</td><td>Searching for related applications</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_SearchInstalled</td><td>1033</td><td>Searching for installed applications</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_SearchingQualifyingProducts</td><td>1033</td><td>Searching for qualifying products</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_SearchingQualifyingProducts2</td><td>1033</td><td>Searching for qualifying products</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Service</td><td>1033</td><td>Service: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Service2</td><td>1033</td><td>Service: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Service3</td><td>1033</td><td>Service: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Service4</td><td>1033</td><td>Service: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Shortcut</td><td>1033</td><td>Shortcut: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Shortcut1</td><td>1033</td><td>Shortcut: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_StartingServices</td><td>1033</td><td>Starting services</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_StoppingServices</td><td>1033</td><td>Stopping services</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnpublishProductFeatures</td><td>1033</td><td>Unpublishing product features</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnpublishQualified</td><td>1033</td><td>Unpublishing Qualified Components</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnpublishingProductInfo</td><td>1033</td><td>Unpublishing product information</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnregTypeLibs</td><td>1033</td><td>Unregistering type libraries</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnregisterClassServers</td><td>1033</td><td>Unregister class servers</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnregisterExtensionServers</td><td>1033</td><td>Unregistering extension servers</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnregisterModules</td><td>1033</td><td>Unregistering modules</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnregisteringComPlus</td><td>1033</td><td>Unregistering COM+ Applications and Components</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnregisteringFonts</td><td>1033</td><td>Unregistering fonts</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnregisteringMimeInfo</td><td>1033</td><td>Unregistering MIME info</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UnregisteringProgramIds</td><td>1033</td><td>Unregistering program identifiers</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UpdateComponentRegistration</td><td>1033</td><td>Updating component registration</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_UpdateEnvironmentStrings</td><td>1033</td><td>Updating environment strings</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_Validating</td><td>1033</td><td>Validating install</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_WritingINI</td><td>1033</td><td>Writing INI file values</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ACTIONTEXT_WritingRegistry</td><td>1033</td><td>Writing system registry values</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_BACK</td><td>1033</td><td>&lt; &amp;Back</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_CANCEL</td><td>1033</td><td>Cancel</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_CANCEL2</td><td>1033</td><td>&amp;Cancel</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_CHANGE</td><td>1033</td><td>&amp;Change...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_COMPLUS_PROGRESSTEXT_COST</td><td>1033</td><td>Costing COM+ application: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_COMPLUS_PROGRESSTEXT_INSTALL</td><td>1033</td><td>Installing COM+ application: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_COMPLUS_PROGRESSTEXT_UNINSTALL</td><td>1033</td><td>Uninstalling COM+ application: [1]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_DIALOG_TEXT2_DESCRIPTION</td><td>1033</td><td>Dialog Normal Description</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_DIALOG_TEXT_DESCRIPTION_EXTERIOR</td><td>1033</td><td>{&amp;TahomaBold10}Dialog Bold Title</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_DIALOG_TEXT_DESCRIPTION_INTERIOR</td><td>1033</td><td>{&amp;MSSansBold8}Dialog Bold Title</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_DIFX_AMD64</td><td>1033</td><td>[ProductName] requires an X64 processor. Click OK to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_DIFX_IA64</td><td>1033</td><td>[ProductName] requires an IA64 processor. Click OK to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_DIFX_X86</td><td>1033</td><td>[ProductName] requires an X86 processor. Click OK to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_DatabaseFolder_InstallDatabaseTo</td><td>1033</td><td>Install [ProductName] database to:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_0</td><td>1033</td><td>{{Fatal error: }}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1</td><td>1033</td><td>Error [1]. </td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_10</td><td>1033</td><td>=== Logging started: [Date]  [Time] ===</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_100</td><td>1033</td><td>Could not remove shortcut [2]. Verify that the shortcut file exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_101</td><td>1033</td><td>Could not register type library for file [2].  Contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_102</td><td>1033</td><td>Could not unregister type library for file [2].  Contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_103</td><td>1033</td><td>Could not update the INI file [2][3].  Verify that the file exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_104</td><td>1033</td><td>Could not schedule file [2] to replace file [3] on reboot.  Verify that you have write permissions to file [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_105</td><td>1033</td><td>Error removing ODBC driver manager, ODBC error [2]: [3]. Contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_106</td><td>1033</td><td>Error installing ODBC driver manager, ODBC error [2]: [3]. Contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_107</td><td>1033</td><td>Error removing ODBC driver [4], ODBC error [2]: [3]. Verify that you have sufficient privileges to remove ODBC drivers.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_108</td><td>1033</td><td>Error installing ODBC driver [4], ODBC error [2]: [3]. Verify that the file [4] exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_109</td><td>1033</td><td>Error configuring ODBC data source [4], ODBC error [2]: [3]. Verify that the file [4] exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_11</td><td>1033</td><td>=== Logging stopped: [Date]  [Time] ===</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_110</td><td>1033</td><td>Service [2] ([3]) failed to start.  Verify that you have sufficient privileges to start system services.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_111</td><td>1033</td><td>Service [2] ([3]) could not be stopped.  Verify that you have sufficient privileges to stop system services.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_112</td><td>1033</td><td>Service [2] ([3]) could not be deleted.  Verify that you have sufficient privileges to remove system services.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_113</td><td>1033</td><td>Service [2] ([3]) could not be installed.  Verify that you have sufficient privileges to install system services.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_114</td><td>1033</td><td>Could not update environment variable [2].  Verify that you have sufficient privileges to modify environment variables.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_115</td><td>1033</td><td>You do not have sufficient privileges to complete this installation for all users of the machine.  Log on as an administrator and then retry this installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_116</td><td>1033</td><td>Could not set file security for file [3]. Error: [2].  Verify that you have sufficient privileges to modify the security permissions for this file.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_117</td><td>1033</td><td>Component Services (COM+ 1.0) are not installed on this computer.  This installation requires Component Services in order to complete successfully.  Component Services are available on Windows 2000.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_118</td><td>1033</td><td>Error registering COM+ application.  Contact your support personnel for more information.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_119</td><td>1033</td><td>Error unregistering COM+ application.  Contact your support personnel for more information.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_12</td><td>1033</td><td>Action start [Time]: [1].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_120</td><td>1033</td><td>Removing older versions of this application</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_121</td><td>1033</td><td>Preparing to remove older versions of this application</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_122</td><td>1033</td><td>Error applying patch to file [2].  It has probably been updated by other means, and can no longer be modified by this patch.  For more information contact your patch vendor.  {{System Error: [3]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_123</td><td>1033</td><td>[2] cannot install one of its required products. Contact your technical support group.  {{System Error: [3].}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_124</td><td>1033</td><td>The older version of [2] cannot be removed.  Contact your technical support group.  {{System Error [3].}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_125</td><td>1033</td><td>The description for service '[2]' ([3]) could not be changed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_126</td><td>1033</td><td>The Windows Installer service cannot update the system file [2] because the file is protected by Windows.  You may need to update your operating system for this program to work correctly. {{Package version: [3], OS Protected version: [4]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_127</td><td>1033</td><td>The Windows Installer service cannot update the protected Windows file [2]. {{Package version: [3], OS Protected version: [4], SFP Error: [5]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_128</td><td>1033</td><td>The Windows Installer service cannot update one or more protected Windows files. SFP Error: [2]. List of protected files: [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_129</td><td>1033</td><td>User installations are disabled via policy on the machine.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_13</td><td>1033</td><td>Action ended [Time]: [1]. Return value [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_130</td><td>1033</td><td>This setup requires Internet Information Server 4.0 or higher for configuring IIS Virtual Roots. Please make sure that you have IIS 4.0 or higher.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_131</td><td>1033</td><td>This setup requires Administrator privileges for configuring IIS Virtual Roots.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1329</td><td>1033</td><td>A file that is required cannot be installed because the cabinet file [2] is not digitally signed. This may indicate that the cabinet file is corrupt.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1330</td><td>1033</td><td>A file that is required cannot be installed because the cabinet file [2] has an invalid digital signature. This may indicate that the cabinet file is corrupt.{ Error [3] was returned by WinVerifyTrust.}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1331</td><td>1033</td><td>Failed to correctly copy [2] file: CRC error.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1332</td><td>1033</td><td>Failed to correctly patch [2] file: CRC error.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1333</td><td>1033</td><td>Failed to correctly patch [2] file: CRC error.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1334</td><td>1033</td><td>The file '[2]' cannot be installed because the file cannot be found in cabinet file '[3]'. This could indicate a network error, an error reading from the CD-ROM, or a problem with this package.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1335</td><td>1033</td><td>The cabinet file '[2]' required for this installation is corrupt and cannot be used. This could indicate a network error, an error reading from the CD-ROM, or a problem with this package.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1336</td><td>1033</td><td>There was an error creating a temporary file that is needed to complete this installation. Folder: [3]. System error code: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_14</td><td>1033</td><td>Time remaining: {[1] minutes }{[2] seconds}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_15</td><td>1033</td><td>Out of memory. Shut down other applications before retrying.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_16</td><td>1033</td><td>Installer is no longer responding.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1609</td><td>1033</td><td>An error occurred while applying security settings. [2] is not a valid user or group. This could be a problem with the package, or a problem connecting to a domain controller on the network. Check your network connection and click Retry, or Cancel to end the install. Unable to locate the user's SID, system error [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1651</td><td>1033</td><td>Admin user failed to apply patch for a per-user managed or a per-machine application which is in advertise state.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_17</td><td>1033</td><td>Installer terminated prematurely.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1715</td><td>1033</td><td>Installed [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1716</td><td>1033</td><td>Configured [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1717</td><td>1033</td><td>Removed [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1718</td><td>1033</td><td>File [2] was rejected by digital signature policy.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1719</td><td>1033</td><td>Windows Installer service could not be accessed. Contact your support personnel to verify that it is properly registered and enabled.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1720</td><td>1033</td><td>There is a problem with this Windows Installer package. A script required for this install to complete could not be run. Contact your support personnel or package vendor. Custom action [2] script error [3], [4]: [5] Line [6], Column [7], [8]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1721</td><td>1033</td><td>There is a problem with this Windows Installer package. A program required for this install to complete could not be run. Contact your support personnel or package vendor. Action: [2], location: [3], command: [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1722</td><td>1033</td><td>There is a problem with this Windows Installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor. Action [2], location: [3], command: [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1723</td><td>1033</td><td>There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Contact your support personnel or package vendor. Action [2], entry: [3], library: [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1724</td><td>1033</td><td>Removal completed successfully.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1725</td><td>1033</td><td>Removal failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1726</td><td>1033</td><td>Advertisement completed successfully.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1727</td><td>1033</td><td>Advertisement failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1728</td><td>1033</td><td>Configuration completed successfully.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1729</td><td>1033</td><td>Configuration failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1730</td><td>1033</td><td>You must be an Administrator to remove this application. To remove this application, you can log on as an administrator, or contact your technical support group for assistance.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1731</td><td>1033</td><td>The source installation package for the product [2] is out of sync with the client package. Try the installation again using a valid copy of the installation package '[3]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1732</td><td>1033</td><td>In order to complete the installation of [2], you must restart the computer. Other users are currently logged on to this computer, and restarting may cause them to lose their work. Do you want to restart now?</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_18</td><td>1033</td><td>Please wait while Windows configures [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_19</td><td>1033</td><td>Gathering required information...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1935</td><td>1033</td><td>An error occurred during the installation of assembly component [2]. HRESULT: [3]. {{assembly interface: [4], function: [5], assembly name: [6]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1936</td><td>1033</td><td>An error occurred during the installation of assembly '[6]'. The assembly is not strongly named or is not signed with the minimal key length. HRESULT: [3]. {{assembly interface: [4], function: [5], component: [2]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1937</td><td>1033</td><td>An error occurred during the installation of assembly '[6]'. The signature or catalog could not be verified or is not valid. HRESULT: [3]. {{assembly interface: [4], function: [5], component: [2]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_1938</td><td>1033</td><td>An error occurred during the installation of assembly '[6]'. One or more modules of the assembly could not be found. HRESULT: [3]. {{assembly interface: [4], function: [5], component: [2]}}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2</td><td>1033</td><td>Warning [1]. </td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_20</td><td>1033</td><td>{[ProductName] }Setup completed successfully.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_21</td><td>1033</td><td>{[ProductName] }Setup failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2101</td><td>1033</td><td>Shortcuts not supported by the operating system.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2102</td><td>1033</td><td>Invalid .ini action: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2103</td><td>1033</td><td>Could not resolve path for shell folder [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2104</td><td>1033</td><td>Writing .ini file: [3]: System error: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2105</td><td>1033</td><td>Shortcut Creation [3] Failed. System error: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2106</td><td>1033</td><td>Shortcut Deletion [3] Failed. System error: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2107</td><td>1033</td><td>Error [3] registering type library [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2108</td><td>1033</td><td>Error [3] unregistering type library [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2109</td><td>1033</td><td>Section missing for .ini action.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2110</td><td>1033</td><td>Key missing for .ini action.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2111</td><td>1033</td><td>Detection of running applications failed, could not get performance data. Registered operation returned : [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2112</td><td>1033</td><td>Detection of running applications failed, could not get performance index. Registered operation returned : [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2113</td><td>1033</td><td>Detection of running applications failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_22</td><td>1033</td><td>Error reading from file: [2]. {{ System error [3].}}  Verify that the file exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2200</td><td>1033</td><td>Database: [2]. Database object creation failed, mode = [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2201</td><td>1033</td><td>Database: [2]. Initialization failed, out of memory.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2202</td><td>1033</td><td>Database: [2]. Data access failed, out of memory.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2203</td><td>1033</td><td>Database: [2]. Cannot open database file. System error [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2204</td><td>1033</td><td>Database: [2]. Table already exists: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2205</td><td>1033</td><td>Database: [2]. Table does not exist: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2206</td><td>1033</td><td>Database: [2]. Table could not be dropped: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2207</td><td>1033</td><td>Database: [2]. Intent violation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2208</td><td>1033</td><td>Database: [2]. Insufficient parameters for Execute.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2209</td><td>1033</td><td>Database: [2]. Cursor in invalid state.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2210</td><td>1033</td><td>Database: [2]. Invalid update data type in column [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2211</td><td>1033</td><td>Database: [2]. Could not create database table [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2212</td><td>1033</td><td>Database: [2]. Database not in writable state.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2213</td><td>1033</td><td>Database: [2]. Error saving database tables.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2214</td><td>1033</td><td>Database: [2]. Error writing export file: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2215</td><td>1033</td><td>Database: [2]. Cannot open import file: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2216</td><td>1033</td><td>Database: [2]. Import file format error: [3], Line [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2217</td><td>1033</td><td>Database: [2]. Wrong state to CreateOutputDatabase [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2218</td><td>1033</td><td>Database: [2]. Table name not supplied.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2219</td><td>1033</td><td>Database: [2]. Invalid Installer database format.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2220</td><td>1033</td><td>Database: [2]. Invalid row/field data.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2221</td><td>1033</td><td>Database: [2]. Code page conflict in import file: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2222</td><td>1033</td><td>Database: [2]. Transform or merge code page [3] differs from database code page [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2223</td><td>1033</td><td>Database: [2]. Databases are the same. No transform generated.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2224</td><td>1033</td><td>Database: [2]. GenerateTransform: Database corrupt. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2225</td><td>1033</td><td>Database: [2]. Transform: Cannot transform a temporary table. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2226</td><td>1033</td><td>Database: [2]. Transform failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2227</td><td>1033</td><td>Database: [2]. Invalid identifier '[3]' in SQL query: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2228</td><td>1033</td><td>Database: [2]. Unknown table '[3]' in SQL query: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2229</td><td>1033</td><td>Database: [2]. Could not load table '[3]' in SQL query: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2230</td><td>1033</td><td>Database: [2]. Repeated table '[3]' in SQL query: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2231</td><td>1033</td><td>Database: [2]. Missing ')' in SQL query: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2232</td><td>1033</td><td>Database: [2]. Unexpected token '[3]' in SQL query: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2233</td><td>1033</td><td>Database: [2]. No columns in SELECT clause in SQL query: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2234</td><td>1033</td><td>Database: [2]. No columns in ORDER BY clause in SQL query: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2235</td><td>1033</td><td>Database: [2]. Column '[3]' not present or ambiguous in SQL query: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2236</td><td>1033</td><td>Database: [2]. Invalid operator '[3]' in SQL query: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2237</td><td>1033</td><td>Database: [2]. Invalid or missing query string: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2238</td><td>1033</td><td>Database: [2]. Missing FROM clause in SQL query: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2239</td><td>1033</td><td>Database: [2]. Insufficient values in INSERT SQL statement.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2240</td><td>1033</td><td>Database: [2]. Missing update columns in UPDATE SQL statement.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2241</td><td>1033</td><td>Database: [2]. Missing insert columns in INSERT SQL statement.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2242</td><td>1033</td><td>Database: [2]. Column '[3]' repeated.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2243</td><td>1033</td><td>Database: [2]. No primary columns defined for table creation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2244</td><td>1033</td><td>Database: [2]. Invalid type specifier '[3]' in SQL query [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2245</td><td>1033</td><td>IStorage::Stat failed with error [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2246</td><td>1033</td><td>Database: [2]. Invalid Installer transform format.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2247</td><td>1033</td><td>Database: [2] Transform stream read/write failure.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2248</td><td>1033</td><td>Database: [2] GenerateTransform/Merge: Column type in base table does not match reference table. Table: [3] Col #: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2249</td><td>1033</td><td>Database: [2] GenerateTransform: More columns in base table than in reference table. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2250</td><td>1033</td><td>Database: [2] Transform: Cannot add existing row. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2251</td><td>1033</td><td>Database: [2] Transform: Cannot delete row that does not exist. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2252</td><td>1033</td><td>Database: [2] Transform: Cannot add existing table. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2253</td><td>1033</td><td>Database: [2] Transform: Cannot delete table that does not exist. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2254</td><td>1033</td><td>Database: [2] Transform: Cannot update row that does not exist. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2255</td><td>1033</td><td>Database: [2] Transform: Column with this name already exists. Table: [3] Col: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2256</td><td>1033</td><td>Database: [2] GenerateTransform/Merge: Number of primary keys in base table does not match reference table. Table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2257</td><td>1033</td><td>Database: [2]. Intent to modify read only table: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2258</td><td>1033</td><td>Database: [2]. Type mismatch in parameter: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2259</td><td>1033</td><td>Database: [2] Table(s) Update failed</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2260</td><td>1033</td><td>Storage CopyTo failed. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2261</td><td>1033</td><td>Could not remove stream [2]. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2262</td><td>1033</td><td>Stream does not exist: [2]. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2263</td><td>1033</td><td>Could not open stream [2]. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2264</td><td>1033</td><td>Could not remove stream [2]. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2265</td><td>1033</td><td>Could not commit storage. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2266</td><td>1033</td><td>Could not rollback storage. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2267</td><td>1033</td><td>Could not delete storage [2]. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2268</td><td>1033</td><td>Database: [2]. Merge: There were merge conflicts reported in [3] tables.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2269</td><td>1033</td><td>Database: [2]. Merge: The column count differed in the '[3]' table of the two databases.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2270</td><td>1033</td><td>Database: [2]. GenerateTransform/Merge: Column name in base table does not match reference table. Table: [3] Col #: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2271</td><td>1033</td><td>SummaryInformation write for transform failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2272</td><td>1033</td><td>Database: [2]. MergeDatabase will not write any changes because the database is open read-only.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2273</td><td>1033</td><td>Database: [2]. MergeDatabase: A reference to the base database was passed as the reference database.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2274</td><td>1033</td><td>Database: [2]. MergeDatabase: Unable to write errors to Error table. Could be due to a non-nullable column in a predefined Error table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2275</td><td>1033</td><td>Database: [2]. Specified Modify [3] operation invalid for table joins.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2276</td><td>1033</td><td>Database: [2]. Code page [3] not supported by the system.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2277</td><td>1033</td><td>Database: [2]. Failed to save table [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2278</td><td>1033</td><td>Database: [2]. Exceeded number of expressions limit of 32 in WHERE clause of SQL query: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2279</td><td>1033</td><td>Database: [2] Transform: Too many columns in base table [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2280</td><td>1033</td><td>Database: [2]. Could not create column [3] for table [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2281</td><td>1033</td><td>Could not rename stream [2]. System error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2282</td><td>1033</td><td>Stream name invalid [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_23</td><td>1033</td><td>Cannot create the file [3].  A directory with this name already exists.  Cancel the installation and try installing to a different location.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2302</td><td>1033</td><td>Patch notify: [2] bytes patched to far.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2303</td><td>1033</td><td>Error getting volume info. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2304</td><td>1033</td><td>Error getting disk free space. GetLastError: [2]. Volume: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2305</td><td>1033</td><td>Error waiting for patch thread. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2306</td><td>1033</td><td>Could not create thread for patch application. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2307</td><td>1033</td><td>Source file key name is null.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2308</td><td>1033</td><td>Destination file name is null.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2309</td><td>1033</td><td>Attempting to patch file [2] when patch already in progress.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2310</td><td>1033</td><td>Attempting to continue patch when no patch is in progress.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2315</td><td>1033</td><td>Missing path separator: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2318</td><td>1033</td><td>File does not exist: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2319</td><td>1033</td><td>Error setting file attribute: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2320</td><td>1033</td><td>File not writable: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2321</td><td>1033</td><td>Error creating file: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2322</td><td>1033</td><td>User canceled.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2323</td><td>1033</td><td>Invalid file attribute.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2324</td><td>1033</td><td>Could not open file: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2325</td><td>1033</td><td>Could not get file time for file: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2326</td><td>1033</td><td>Error in FileToDosDateTime.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2327</td><td>1033</td><td>Could not remove directory: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2328</td><td>1033</td><td>Error getting file version info for file: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2329</td><td>1033</td><td>Error deleting file: [3]. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2330</td><td>1033</td><td>Error getting file attributes: [3]. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2331</td><td>1033</td><td>Error loading library [2] or finding entry point [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2332</td><td>1033</td><td>Error getting file attributes. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2333</td><td>1033</td><td>Error setting file attributes. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2334</td><td>1033</td><td>Error converting file time to local time for file: [3]. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2335</td><td>1033</td><td>Path: [2] is not a parent of [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2336</td><td>1033</td><td>Error creating temp file on path: [3]. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2337</td><td>1033</td><td>Could not close file: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2338</td><td>1033</td><td>Could not update resource for file: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2339</td><td>1033</td><td>Could not set file time for file: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2340</td><td>1033</td><td>Could not update resource for file: [3], Missing resource.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2341</td><td>1033</td><td>Could not update resource for file: [3], Resource too large.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2342</td><td>1033</td><td>Could not update resource for file: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2343</td><td>1033</td><td>Specified path is empty.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2344</td><td>1033</td><td>Could not find required file IMAGEHLP.DLL to validate file:[2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2345</td><td>1033</td><td>[2]: File does not contain a valid checksum value.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2347</td><td>1033</td><td>User ignore.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2348</td><td>1033</td><td>Error attempting to read from cabinet stream.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2349</td><td>1033</td><td>Copy resumed with different info.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2350</td><td>1033</td><td>FDI server error</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2351</td><td>1033</td><td>File key '[2]' not found in cabinet '[3]'. The installation cannot continue.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2352</td><td>1033</td><td>Could not initialize cabinet file server. The required file 'CABINET.DLL' may be missing.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2353</td><td>1033</td><td>Not a cabinet.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2354</td><td>1033</td><td>Cannot handle cabinet.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2355</td><td>1033</td><td>Corrupt cabinet.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2356</td><td>1033</td><td>Could not locate cabinet in stream: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2357</td><td>1033</td><td>Cannot set attributes.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2358</td><td>1033</td><td>Error determining whether file is in-use: [3]. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2359</td><td>1033</td><td>Unable to create the target file - file may be in use.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2360</td><td>1033</td><td>Progress tick.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2361</td><td>1033</td><td>Need next cabinet.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2362</td><td>1033</td><td>Folder not found: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2363</td><td>1033</td><td>Could not enumerate subfolders for folder: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2364</td><td>1033</td><td>Bad enumeration constant in CreateCopier call.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2365</td><td>1033</td><td>Could not BindImage exe file [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2366</td><td>1033</td><td>User failure.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2367</td><td>1033</td><td>User abort.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2368</td><td>1033</td><td>Failed to get network resource information. Error [2], network path [3]. Extended error: network provider [5], error code [4], error description [6].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2370</td><td>1033</td><td>Invalid CRC checksum value for [2] file.{ Its header says [3] for checksum, its computed value is [4].}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2371</td><td>1033</td><td>Could not apply patch to file [2]. GetLastError: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2372</td><td>1033</td><td>Patch file [2] is corrupt or of an invalid format. Attempting to patch file [3]. GetLastError: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2373</td><td>1033</td><td>File [2] is not a valid patch file.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2374</td><td>1033</td><td>File [2] is not a valid destination file for patch file [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2375</td><td>1033</td><td>Unknown patching error: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2376</td><td>1033</td><td>Cabinet not found.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2379</td><td>1033</td><td>Error opening file for read: [3] GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2380</td><td>1033</td><td>Error opening file for write: [3]. GetLastError: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2381</td><td>1033</td><td>Directory does not exist: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2382</td><td>1033</td><td>Drive not ready: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_24</td><td>1033</td><td>Please insert the disk: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2401</td><td>1033</td><td>64-bit registry operation attempted on 32-bit operating system for key [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2402</td><td>1033</td><td>Out of memory.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_25</td><td>1033</td><td>The installer has insufficient privileges to access this directory: [2].  The installation cannot continue.  Log on as an administrator or contact your system administrator.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2501</td><td>1033</td><td>Could not create rollback script enumerator.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2502</td><td>1033</td><td>Called InstallFinalize when no install in progress.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2503</td><td>1033</td><td>Called RunScript when not marked in progress.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_26</td><td>1033</td><td>Error writing to file [2].  Verify that you have access to that directory.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2601</td><td>1033</td><td>Invalid value for property [2]: '[3]'</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2602</td><td>1033</td><td>The [2] table entry '[3]' has no associated entry in the Media table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2603</td><td>1033</td><td>Duplicate table name [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2604</td><td>1033</td><td>[2] Property undefined.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2605</td><td>1033</td><td>Could not find server [2] in [3] or [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2606</td><td>1033</td><td>Value of property [2] is not a valid full path: '[3]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2607</td><td>1033</td><td>Media table not found or empty (required for installation of files).</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2608</td><td>1033</td><td>Could not create security descriptor for object. Error: '[2]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2609</td><td>1033</td><td>Attempt to migrate product settings before initialization.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2611</td><td>1033</td><td>The file [2] is marked as compressed, but the associated media entry does not specify a cabinet.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2612</td><td>1033</td><td>Stream not found in '[2]' column. Primary key: '[3]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2613</td><td>1033</td><td>RemoveExistingProducts action sequenced incorrectly.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2614</td><td>1033</td><td>Could not access IStorage object from installation package.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2615</td><td>1033</td><td>Skipped unregistration of Module [2] due to source resolution failure.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2616</td><td>1033</td><td>Companion file [2] parent missing.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2617</td><td>1033</td><td>Shared component [2] not found in Component table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2618</td><td>1033</td><td>Isolated application component [2] not found in Component table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2619</td><td>1033</td><td>Isolated components [2], [3] not part of same feature.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2620</td><td>1033</td><td>Key file of isolated application component [2] not in File table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2621</td><td>1033</td><td>Resource DLL or Resource ID information for shortcut [2] set incorrectly.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27</td><td>1033</td><td>Error reading from file [2].  Verify that the file exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2701</td><td>1033</td><td>The depth of a feature exceeds the acceptable tree depth of [2] levels.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2702</td><td>1033</td><td>A Feature table record ([2]) references a non-existent parent in the Attributes field.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2703</td><td>1033</td><td>Property name for root source path not defined: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2704</td><td>1033</td><td>Root directory property undefined: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2705</td><td>1033</td><td>Invalid table: [2]; Could not be linked as tree.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2706</td><td>1033</td><td>Source paths not created. No path exists for entry [2] in Directory table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2707</td><td>1033</td><td>Target paths not created. No path exists for entry [2] in Directory table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2708</td><td>1033</td><td>No entries found in the file table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2709</td><td>1033</td><td>The specified Component name ('[2]') not found in Component table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2710</td><td>1033</td><td>The requested 'Select' state is illegal for this Component.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2711</td><td>1033</td><td>The specified Feature name ('[2]') not found in Feature table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2712</td><td>1033</td><td>Invalid return from modeless dialog: [3], in action [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2713</td><td>1033</td><td>Null value in a non-nullable column ('[2]' in '[3]' column of the '[4]' table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2714</td><td>1033</td><td>Invalid value for default folder name: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2715</td><td>1033</td><td>The specified File key ('[2]') not found in the File table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2716</td><td>1033</td><td>Could not create a random subcomponent name for component '[2]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2717</td><td>1033</td><td>Bad action condition or error calling custom action '[2]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2718</td><td>1033</td><td>Missing package name for product code '[2]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2719</td><td>1033</td><td>Neither UNC nor drive letter path found in source '[2]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2720</td><td>1033</td><td>Error opening source list key. Error: '[2]'</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2721</td><td>1033</td><td>Custom action [2] not found in Binary table stream.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2722</td><td>1033</td><td>Custom action [2] not found in File table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2723</td><td>1033</td><td>Custom action [2] specifies unsupported type.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2724</td><td>1033</td><td>The volume label '[2]' on the media you're running from does not match the label '[3]' given in the Media table. This is allowed only if you have only 1 entry in your Media table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2725</td><td>1033</td><td>Invalid database tables</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2726</td><td>1033</td><td>Action not found: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2727</td><td>1033</td><td>The directory entry '[2]' does not exist in the Directory table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2728</td><td>1033</td><td>Table definition error: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2729</td><td>1033</td><td>Install engine not initialized.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2730</td><td>1033</td><td>Bad value in database. Table: '[2]'; Primary key: '[3]'; Column: '[4]'</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2731</td><td>1033</td><td>Selection Manager not initialized.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2732</td><td>1033</td><td>Directory Manager not initialized.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2733</td><td>1033</td><td>Bad foreign key ('[2]') in '[3]' column of the '[4]' table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2734</td><td>1033</td><td>Invalid reinstall mode character.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2735</td><td>1033</td><td>Custom action '[2]' has caused an unhandled exception and has been stopped. This may be the result of an internal error in the custom action, such as an access violation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2736</td><td>1033</td><td>Generation of custom action temp file failed: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2737</td><td>1033</td><td>Could not access custom action [2], entry [3], library [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2738</td><td>1033</td><td>Could not access VBScript run time for custom action [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2739</td><td>1033</td><td>Could not access JavaScript run time for custom action [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2740</td><td>1033</td><td>Custom action [2] script error [3], [4]: [5] Line [6], Column [7], [8].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2741</td><td>1033</td><td>Configuration information for product [2] is corrupt. Invalid info: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2742</td><td>1033</td><td>Marshaling to Server failed: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2743</td><td>1033</td><td>Could not execute custom action [2], location: [3], command: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2744</td><td>1033</td><td>EXE failed called by custom action [2], location: [3], command: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2745</td><td>1033</td><td>Transform [2] invalid for package [3]. Expected language [4], found language [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2746</td><td>1033</td><td>Transform [2] invalid for package [3]. Expected product [4], found product [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2747</td><td>1033</td><td>Transform [2] invalid for package [3]. Expected product version &lt; [4], found product version [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2748</td><td>1033</td><td>Transform [2] invalid for package [3]. Expected product version &lt;= [4], found product version [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2749</td><td>1033</td><td>Transform [2] invalid for package [3]. Expected product version == [4], found product version [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2750</td><td>1033</td><td>Transform [2] invalid for package [3]. Expected product version &gt;= [4], found product version [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27502</td><td>1033</td><td>Could not connect to [2] '[3]'. [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27503</td><td>1033</td><td>Error retrieving version string from [2] '[3]'. [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27504</td><td>1033</td><td>SQL version requirements not met: [3]. This installation requires [2] [4] or later.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27505</td><td>1033</td><td>Could not open SQL script file [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27506</td><td>1033</td><td>Error executing SQL script [2]. Line [3]. [4]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27507</td><td>1033</td><td>Connection or browsing for database servers requires that MDAC be installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27508</td><td>1033</td><td>Error installing COM+ application [2]. [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27509</td><td>1033</td><td>Error uninstalling COM+ application [2]. [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2751</td><td>1033</td><td>Transform [2] invalid for package [3]. Expected product version &gt; [4], found product version [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27510</td><td>1033</td><td>Error installing COM+ application [2].  Could not load Microsoft(R) .NET class libraries. Registering .NET serviced components requires that Microsoft(R) .NET Framework be installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27511</td><td>1033</td><td>Could not execute SQL script file [2]. Connection not open: [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27512</td><td>1033</td><td>Error beginning transactions for [2] '[3]'. Database [4]. [5]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27513</td><td>1033</td><td>Error committing transactions for [2] '[3]'. Database [4]. [5]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27514</td><td>1033</td><td>This installation requires a Microsoft SQL Server. The specified server '[3]' is a Microsoft SQL Server Desktop Engine or SQL Server Express.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27515</td><td>1033</td><td>Error retrieving schema version from [2] '[3]'. Database: '[4]'. [5]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27516</td><td>1033</td><td>Error writing schema version to [2] '[3]'. Database: '[4]'. [5]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27517</td><td>1033</td><td>This installation requires Administrator privileges for installing COM+ applications. Log on as an administrator and then retry this installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27518</td><td>1033</td><td>The COM+ application "[2]" is configured to run as an NT service; this requires COM+ 1.5 or later on the system. Since your system has COM+ 1.0, this application will not be installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27519</td><td>1033</td><td>Error updating XML file [2]. [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2752</td><td>1033</td><td>Could not open transform [2] stored as child storage of package [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27520</td><td>1033</td><td>Error opening XML file [2]. [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27521</td><td>1033</td><td>This setup requires MSXML 3.0 or higher for configuring XML files. Please make sure that you have version 3.0 or higher.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27522</td><td>1033</td><td>Error creating XML file [2]. [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27523</td><td>1033</td><td>Error loading servers.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27524</td><td>1033</td><td>Error loading NetApi32.DLL. The ISNetApi.dll needs to have NetApi32.DLL properly loaded and requires an NT based operating system.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27525</td><td>1033</td><td>Server not found. Verify that the specified server exists. The server name can not be empty.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27526</td><td>1033</td><td>Unspecified error from ISNetApi.dll.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27527</td><td>1033</td><td>The buffer is too small.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27528</td><td>1033</td><td>Access denied. Check administrative rights.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27529</td><td>1033</td><td>Invalid computer.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2753</td><td>1033</td><td>The File '[2]' is not marked for installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27530</td><td>1033</td><td>Unknown error returned from NetAPI. System error: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27531</td><td>1033</td><td>Unhandled exception.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27532</td><td>1033</td><td>Invalid user name for this server or domain.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27533</td><td>1033</td><td>The case-sensitive passwords do not match.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27534</td><td>1033</td><td>The list is empty.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27535</td><td>1033</td><td>Access violation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27536</td><td>1033</td><td>Error getting group.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27537</td><td>1033</td><td>Error adding user to group. Verify that the group exists for this domain or server.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27538</td><td>1033</td><td>Error creating user.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27539</td><td>1033</td><td>ERROR_NETAPI_ERROR_NOT_PRIMARY returned from NetAPI.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2754</td><td>1033</td><td>The File '[2]' is not a valid patch file.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27540</td><td>1033</td><td>The specified user already exists.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27541</td><td>1033</td><td>The specified group already exists.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27542</td><td>1033</td><td>Invalid password. Verify that the password is in accordance with your network password policy.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27543</td><td>1033</td><td>Invalid name.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27544</td><td>1033</td><td>Invalid group.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27545</td><td>1033</td><td>The user name can not be empty and must be in the format DOMAIN\Username.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27546</td><td>1033</td><td>Error loading or creating INI file in the user TEMP directory.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27547</td><td>1033</td><td>ISNetAPI.dll is not loaded or there was an error loading the dll. This dll needs to be loaded for this operation. Verify that the dll is in the SUPPORTDIR directory.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27548</td><td>1033</td><td>Error deleting INI file containing new user information from the user's TEMP directory.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27549</td><td>1033</td><td>Error getting the primary domain controller (PDC).</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2755</td><td>1033</td><td>Server returned unexpected error [2] attempting to install package [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27550</td><td>1033</td><td>Every field must have a value in order to create a user.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27551</td><td>1033</td><td>ODBC driver for [2] not found. This is required to connect to [2] database servers.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27552</td><td>1033</td><td>Error creating database [4]. Server: [2] [3]. [5]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27553</td><td>1033</td><td>Error connecting to database [4]. Server: [2] [3]. [5]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27554</td><td>1033</td><td>Error attempting to open connection [2]. No valid database metadata associated with this connection.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_27555</td><td>1033</td><td>Error attempting to apply permissions to object '[2]'. System error: [3] ([4])</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2756</td><td>1033</td><td>The property '[2]' was used as a directory property in one or more tables, but no value was ever assigned.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2757</td><td>1033</td><td>Could not create summary info for transform [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2758</td><td>1033</td><td>Transform [2] does not contain an MSI version.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2759</td><td>1033</td><td>Transform [2] version [3] incompatible with engine; Min: [4], Max: [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2760</td><td>1033</td><td>Transform [2] invalid for package [3]. Expected upgrade code [4], found [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2761</td><td>1033</td><td>Cannot begin transaction. Global mutex not properly initialized.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2762</td><td>1033</td><td>Cannot write script record. Transaction not started.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2763</td><td>1033</td><td>Cannot run script. Transaction not started.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2765</td><td>1033</td><td>Assembly name missing from AssemblyName table : Component: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2766</td><td>1033</td><td>The file [2] is an invalid MSI storage file.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2767</td><td>1033</td><td>No more data{ while enumerating [2]}.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2768</td><td>1033</td><td>Transform in patch package is invalid.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2769</td><td>1033</td><td>Custom Action [2] did not close [3] MSIHANDLEs.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2770</td><td>1033</td><td>Cached folder [2] not defined in internal cache folder table.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2771</td><td>1033</td><td>Upgrade of feature [2] has a missing component.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2772</td><td>1033</td><td>New upgrade feature [2] must be a leaf feature.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_28</td><td>1033</td><td>Another application has exclusive access to the file [2].  Please shut down all other applications, then click Retry.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2801</td><td>1033</td><td>Unknown Message -- Type [2]. No action is taken.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2802</td><td>1033</td><td>No publisher is found for the event [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2803</td><td>1033</td><td>Dialog View did not find a record for the dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2804</td><td>1033</td><td>On activation of the control [3] on dialog [2] CMsiDialog failed to evaluate the condition [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2806</td><td>1033</td><td>The dialog [2] failed to evaluate the condition [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2807</td><td>1033</td><td>The action [2] is not recognized.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2808</td><td>1033</td><td>Default button is ill-defined on dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2809</td><td>1033</td><td>On the dialog [2] the next control pointers do not form a cycle. There is a pointer from [3] to [4], but there is no further pointer.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2810</td><td>1033</td><td>On the dialog [2] the next control pointers do not form a cycle. There is a pointer from both [3] and [5] to [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2811</td><td>1033</td><td>On dialog [2] control [3] has to take focus, but it is unable to do so.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2812</td><td>1033</td><td>The event [2] is not recognized.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2813</td><td>1033</td><td>The EndDialog event was called with the argument [2], but the dialog has a parent.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2814</td><td>1033</td><td>On the dialog [2] the control [3] names a nonexistent control [4] as the next control.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2815</td><td>1033</td><td>ControlCondition table has a row without condition for the dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2816</td><td>1033</td><td>The EventMapping table refers to an invalid control [4] on dialog [2] for the event [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2817</td><td>1033</td><td>The event [2] failed to set the attribute for the control [4] on dialog [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2818</td><td>1033</td><td>In the ControlEvent table EndDialog has an unrecognized argument [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2819</td><td>1033</td><td>Control [3] on dialog [2] needs a property linked to it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2820</td><td>1033</td><td>Attempted to initialize an already initialized handler.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2821</td><td>1033</td><td>Attempted to initialize an already initialized dialog: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2822</td><td>1033</td><td>No other method can be called on dialog [2] until all the controls are added.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2823</td><td>1033</td><td>Attempted to initialize an already initialized control: [3] on dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2824</td><td>1033</td><td>The dialog attribute [3] needs a record of at least [2] field(s).</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2825</td><td>1033</td><td>The control attribute [3] needs a record of at least [2] field(s).</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2826</td><td>1033</td><td>Control [3] on dialog [2] extends beyond the boundaries of the dialog [4] by [5] pixels.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2827</td><td>1033</td><td>The button [4] on the radio button group [3] on dialog [2] extends beyond the boundaries of the group [5] by [6] pixels.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2828</td><td>1033</td><td>Tried to remove control [3] from dialog [2], but the control is not part of the dialog.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2829</td><td>1033</td><td>Attempt to use an uninitialized dialog.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2830</td><td>1033</td><td>Attempt to use an uninitialized control on dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2831</td><td>1033</td><td>The control [3] on dialog [2] does not support [5] the attribute [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2832</td><td>1033</td><td>The dialog [2] does not support the attribute [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2833</td><td>1033</td><td>Control [4] on dialog [3] ignored the message [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2834</td><td>1033</td><td>The next pointers on the dialog [2] do not form a single loop.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2835</td><td>1033</td><td>The control [2] was not found on dialog [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2836</td><td>1033</td><td>The control [3] on the dialog [2] cannot take focus.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2837</td><td>1033</td><td>The control [3] on dialog [2] wants the winproc to return [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2838</td><td>1033</td><td>The item [2] in the selection table has itself as a parent.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2839</td><td>1033</td><td>Setting the property [2] failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2840</td><td>1033</td><td>Error dialog name mismatch.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2841</td><td>1033</td><td>No OK button was found on the error dialog.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2842</td><td>1033</td><td>No text field was found on the error dialog.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2843</td><td>1033</td><td>The ErrorString attribute is not supported for standard dialogs.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2844</td><td>1033</td><td>Cannot execute an error dialog if the Errorstring is not set.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2845</td><td>1033</td><td>The total width of the buttons exceeds the size of the error dialog.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2846</td><td>1033</td><td>SetFocus did not find the required control on the error dialog.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2847</td><td>1033</td><td>The control [3] on dialog [2] has both the icon and the bitmap style set.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2848</td><td>1033</td><td>Tried to set control [3] as the default button on dialog [2], but the control does not exist.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2849</td><td>1033</td><td>The control [3] on dialog [2] is of a type, that cannot be integer valued.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2850</td><td>1033</td><td>Unrecognized volume type.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2851</td><td>1033</td><td>The data for the icon [2] is not valid.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2852</td><td>1033</td><td>At least one control has to be added to dialog [2] before it is used.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2853</td><td>1033</td><td>Dialog [2] is a modeless dialog. The execute method should not be called on it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2854</td><td>1033</td><td>On the dialog [2] the control [3] is designated as first active control, but there is no such control.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2855</td><td>1033</td><td>The radio button group [3] on dialog [2] has fewer than 2 buttons.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2856</td><td>1033</td><td>Creating a second copy of the dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2857</td><td>1033</td><td>The directory [2] is mentioned in the selection table but not found.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2858</td><td>1033</td><td>The data for the bitmap [2] is not valid.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2859</td><td>1033</td><td>Test error message.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2860</td><td>1033</td><td>Cancel button is ill-defined on dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2861</td><td>1033</td><td>The next pointers for the radio buttons on dialog [2] control [3] do not form a cycle.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2862</td><td>1033</td><td>The attributes for the control [3] on dialog [2] do not define a valid icon size. Setting the size to 16.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2863</td><td>1033</td><td>The control [3] on dialog [2] needs the icon [4] in size [5]x[5], but that size is not available. Loading the first available size.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2864</td><td>1033</td><td>The control [3] on dialog [2] received a browse event, but there is no configurable directory for the present selection. Likely cause: browse button is not authored correctly.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2865</td><td>1033</td><td>Control [3] on billboard [2] extends beyond the boundaries of the billboard [4] by [5] pixels.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2866</td><td>1033</td><td>The dialog [2] is not allowed to return the argument [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2867</td><td>1033</td><td>The error dialog property is not set.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2868</td><td>1033</td><td>The error dialog [2] does not have the error style bit set.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2869</td><td>1033</td><td>The dialog [2] has the error style bit set, but is not an error dialog.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2870</td><td>1033</td><td>The help string [4] for control [3] on dialog [2] does not contain the separator character.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2871</td><td>1033</td><td>The [2] table is out of date: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2872</td><td>1033</td><td>The argument of the CheckPath control event on dialog [2] is invalid.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2873</td><td>1033</td><td>On the dialog [2] the control [3] has an invalid string length limit: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2874</td><td>1033</td><td>Changing the text font to [2] failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2875</td><td>1033</td><td>Changing the text color to [2] failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2876</td><td>1033</td><td>The control [3] on dialog [2] had to truncate the string: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2877</td><td>1033</td><td>The binary data [2] was not found</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2878</td><td>1033</td><td>On the dialog [2] the control [3] has a possible value: [4]. This is an invalid or duplicate value.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2879</td><td>1033</td><td>The control [3] on dialog [2] cannot parse the mask string: [4].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2880</td><td>1033</td><td>Do not perform the remaining control events.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2881</td><td>1033</td><td>CMsiHandler initialization failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2882</td><td>1033</td><td>Dialog window class registration failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2883</td><td>1033</td><td>CreateNewDialog failed for the dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2884</td><td>1033</td><td>Failed to create a window for the dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2885</td><td>1033</td><td>Failed to create the control [3] on the dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2886</td><td>1033</td><td>Creating the [2] table failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2887</td><td>1033</td><td>Creating a cursor to the [2] table failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2888</td><td>1033</td><td>Executing the [2] view failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2889</td><td>1033</td><td>Creating the window for the control [3] on dialog [2] failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2890</td><td>1033</td><td>The handler failed in creating an initialized dialog.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2891</td><td>1033</td><td>Failed to destroy window for dialog [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2892</td><td>1033</td><td>[2] is an integer only control, [3] is not a valid integer value.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2893</td><td>1033</td><td>The control [3] on dialog [2] can accept property values that are at most [5] characters long. The value [4] exceeds this limit, and has been truncated.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2894</td><td>1033</td><td>Loading RICHED20.DLL failed. GetLastError() returned: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2895</td><td>1033</td><td>Freeing RICHED20.DLL failed. GetLastError() returned: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2896</td><td>1033</td><td>Executing action [2] failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2897</td><td>1033</td><td>Failed to create any [2] font on this system.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2898</td><td>1033</td><td>For [2] textstyle, the system created a '[3]' font, in [4] character set.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2899</td><td>1033</td><td>Failed to create [2] textstyle. GetLastError() returned: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_29</td><td>1033</td><td>There is not enough disk space to install the file [2].  Free some disk space and click Retry, or click Cancel to exit.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2901</td><td>1033</td><td>Invalid parameter to operation [2]: Parameter [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2902</td><td>1033</td><td>Operation [2] called out of sequence.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2903</td><td>1033</td><td>The file [2] is missing.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2904</td><td>1033</td><td>Could not BindImage file [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2905</td><td>1033</td><td>Could not read record from script file [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2906</td><td>1033</td><td>Missing header in script file [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2907</td><td>1033</td><td>Could not create secure security descriptor. Error: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2908</td><td>1033</td><td>Could not register component [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2909</td><td>1033</td><td>Could not unregister component [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2910</td><td>1033</td><td>Could not determine user's security ID.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2911</td><td>1033</td><td>Could not remove the folder [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2912</td><td>1033</td><td>Could not schedule file [2] for removal on restart.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2919</td><td>1033</td><td>No cabinet specified for compressed file: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2920</td><td>1033</td><td>Source directory not specified for file [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2924</td><td>1033</td><td>Script [2] version unsupported. Script version: [3], minimum version: [4], maximum version: [5].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2927</td><td>1033</td><td>ShellFolder id [2] is invalid.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2928</td><td>1033</td><td>Exceeded maximum number of sources. Skipping source '[2]'.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2929</td><td>1033</td><td>Could not determine publishing root. Error: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2932</td><td>1033</td><td>Could not create file [2] from script data. Error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2933</td><td>1033</td><td>Could not initialize rollback script [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2934</td><td>1033</td><td>Could not secure transform [2]. Error [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2935</td><td>1033</td><td>Could not unsecure transform [2]. Error [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2936</td><td>1033</td><td>Could not find transform [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2937</td><td>1033</td><td>Windows Installer cannot install a system file protection catalog. Catalog: [2], Error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2938</td><td>1033</td><td>Windows Installer cannot retrieve a system file protection catalog from the cache. Catalog: [2], Error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2939</td><td>1033</td><td>Windows Installer cannot delete a system file protection catalog from the cache. Catalog: [2], Error: [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2940</td><td>1033</td><td>Directory Manager not supplied for source resolution.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2941</td><td>1033</td><td>Unable to compute the CRC for file [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2942</td><td>1033</td><td>BindImage action has not been executed on [2] file.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2943</td><td>1033</td><td>This version of Windows does not support deploying 64-bit packages. The script [2] is for a 64-bit package.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2944</td><td>1033</td><td>GetProductAssignmentType failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_2945</td><td>1033</td><td>Installation of ComPlus App [2] failed with error [3].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_3</td><td>1033</td><td>Info [1]. </td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_30</td><td>1033</td><td>Source file not found: [2].  Verify that the file exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_3001</td><td>1033</td><td>The patches in this list contain incorrect sequencing information: [2][3][4][5][6][7][8][9][10][11][12][13][14][15][16].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_3002</td><td>1033</td><td>Patch [2] contains invalid sequencing information. </td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_31</td><td>1033</td><td>Error reading from file: [3]. {{ System error [2].}}  Verify that the file exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_32</td><td>1033</td><td>Error writing to file: [3]. {{ System error [2].}}  Verify that you have access to that directory.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_33</td><td>1033</td><td>Source file not found{{(cabinet)}}: [2].  Verify that the file exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_34</td><td>1033</td><td>Cannot create the directory [2].  A file with this name already exists.  Please rename or remove the file and click Retry, or click Cancel to exit.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_35</td><td>1033</td><td>The volume [2] is currently unavailable.  Please select another.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_36</td><td>1033</td><td>The specified path [2] is unavailable.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_37</td><td>1033</td><td>Unable to write to the specified folder [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_38</td><td>1033</td><td>A network error occurred while attempting to read from the file [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_39</td><td>1033</td><td>An error occurred while attempting to create the directory [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_4</td><td>1033</td><td>Internal Error [1]. [2]{, [3]}{, [4]}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_40</td><td>1033</td><td>A network error occurred while attempting to create the directory [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_41</td><td>1033</td><td>A network error occurred while attempting to open the source file cabinet [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_42</td><td>1033</td><td>The specified path is too long [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_43</td><td>1033</td><td>The Installer has insufficient privileges to modify the file [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_44</td><td>1033</td><td>A portion of the path [2] exceeds the length allowed by the system.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_45</td><td>1033</td><td>The path [2] contains words that are not valid in folders.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_46</td><td>1033</td><td>The path [2] contains an invalid character.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_47</td><td>1033</td><td>[2] is not a valid short file name.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_48</td><td>1033</td><td>Error getting file security: [3] GetLastError: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_49</td><td>1033</td><td>Invalid Drive: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_5</td><td>1033</td><td>{{Disk full: }}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_50</td><td>1033</td><td>Could not create key [2]. {{ System error [3].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_51</td><td>1033</td><td>Could not open key: [2]. {{ System error [3].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_52</td><td>1033</td><td>Could not delete value [2] from key [3]. {{ System error [4].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_53</td><td>1033</td><td>Could not delete key [2]. {{ System error [3].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_54</td><td>1033</td><td>Could not read value [2] from key [3]. {{ System error [4].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_55</td><td>1033</td><td>Could not write value [2] to key [3]. {{ System error [4].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_56</td><td>1033</td><td>Could not get value names for key [2]. {{ System error [3].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_57</td><td>1033</td><td>Could not get sub key names for key [2]. {{ System error [3].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_58</td><td>1033</td><td>Could not read security information for key [2]. {{ System error [3].}}  Verify that you have sufficient access to that key, or contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_59</td><td>1033</td><td>Could not increase the available registry space. [2] KB of free registry space is required for the installation of this application.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_6</td><td>1033</td><td>Action [Time]: [1]. [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_60</td><td>1033</td><td>Another installation is in progress. You must complete that installation before continuing this one.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_61</td><td>1033</td><td>Error accessing secured data. Please make sure the Windows Installer is configured properly and try the installation again.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_62</td><td>1033</td><td>User [2] has previously initiated an installation for product [3].  That user will need to run that installation again before using that product.  Your current installation will now continue.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_63</td><td>1033</td><td>User [2] has previously initiated an installation for product [3].  That user will need to run that installation again before using that product.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_64</td><td>1033</td><td>Out of disk space -- Volume: '[2]'; required space: [3] KB; available space: [4] KB.  Free some disk space and retry.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_65</td><td>1033</td><td>Are you sure you want to cancel?</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_66</td><td>1033</td><td>The file [2][3] is being held in use{ by the following process: Name: [4], ID: [5], Window Title: [6]}.  Close that application and retry.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_67</td><td>1033</td><td>The product [2] is already installed, preventing the installation of this product.  The two products are incompatible.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_68</td><td>1033</td><td>Out of disk space -- Volume: [2]; required space: [3] KB; available space: [4] KB.  If rollback is disabled, enough space is available. Click Cancel to quit, Retry to check available disk space again, or Ignore to continue without rollback.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_69</td><td>1033</td><td>Could not access network location [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_7</td><td>1033</td><td>[ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_70</td><td>1033</td><td>The following applications should be closed before continuing the installation:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_71</td><td>1033</td><td>Could not find any previously installed compliant products on the machine for installing this product.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_72</td><td>1033</td><td>The key [2] is not valid.  Verify that you entered the correct key.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_73</td><td>1033</td><td>The installer must restart your system before configuration of [2] can continue.  Click Yes to restart now or No if you plan to restart later.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_74</td><td>1033</td><td>You must restart your system for the configuration changes made to [2] to take effect. Click Yes to restart now or No if you plan to restart later.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_75</td><td>1033</td><td>An installation for [2] is currently suspended.  You must undo the changes made by that installation to continue.  Do you want to undo those changes?</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_76</td><td>1033</td><td>A previous installation for this product is in progress.  You must undo the changes made by that installation to continue.  Do you want to undo those changes?</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_77</td><td>1033</td><td>No valid source could be found for product [2].  The Windows Installer cannot continue.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_78</td><td>1033</td><td>Installation operation completed successfully.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_79</td><td>1033</td><td>Installation operation failed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_8</td><td>1033</td><td>{[2]}{, [3]}{, [4]}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_80</td><td>1033</td><td>Product: [2] -- [3]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_81</td><td>1033</td><td>You may either restore your computer to its previous state or continue the installation later. Would you like to restore?</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_82</td><td>1033</td><td>An error occurred while writing installation information to disk.  Check to make sure enough disk space is available, and click Retry, or Cancel to end the installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_83</td><td>1033</td><td>One or more of the files required to restore your computer to its previous state could not be found.  Restoration will not be possible.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_84</td><td>1033</td><td>The path [2] is not valid.  Please specify a valid path.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_85</td><td>1033</td><td>Out of memory. Shut down other applications before retrying.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_86</td><td>1033</td><td>There is no disk in drive [2]. Please insert one and click Retry, or click Cancel to go back to the previously selected volume.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_87</td><td>1033</td><td>There is no disk in drive [2]. Please insert one and click Retry, or click Cancel to return to the browse dialog and select a different volume.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_88</td><td>1033</td><td>The folder [2] does not exist.  Please enter a path to an existing folder.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_89</td><td>1033</td><td>You have insufficient privileges to read this folder.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_9</td><td>1033</td><td>Message type: [1], Argument: [2]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_90</td><td>1033</td><td>A valid destination folder for the installation could not be determined.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_91</td><td>1033</td><td>Error attempting to read from the source installation database: [2].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_92</td><td>1033</td><td>Scheduling reboot operation: Renaming file [2] to [3]. Must reboot to complete operation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_93</td><td>1033</td><td>Scheduling reboot operation: Deleting file [2]. Must reboot to complete operation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_94</td><td>1033</td><td>Module [2] failed to register.  HRESULT [3].  Contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_95</td><td>1033</td><td>Module [2] failed to unregister.  HRESULT [3].  Contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_96</td><td>1033</td><td>Failed to cache package [2]. Error: [3]. Contact your support personnel.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_97</td><td>1033</td><td>Could not register font [2].  Verify that you have sufficient permissions to install fonts, and that the system supports this font.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_98</td><td>1033</td><td>Could not unregister font [2]. Verify that you have sufficient permissions to remove fonts.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ERROR_99</td><td>1033</td><td>Could not create shortcut [2]. Verify that the destination folder exists and that you can access it.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_INSTALLDIR</td><td>1033</td><td>[INSTALLDIR]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_INSTALLSHIELD</td><td>1033</td><td>InstallShield</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_INSTALLSHIELD_FORMATTED</td><td>1033</td><td>{&amp;MSSWhiteSerif8}InstallShield</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ISSCRIPT_VERSION_MISSING</td><td>1033</td><td>The InstallScript engine is missing from this machine.  If available, please run ISScript.msi, or contact your support personnel for further assistance.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_ISSCRIPT_VERSION_OLD</td><td>1033</td><td>The InstallScript engine on this machine is older than the version required to run this setup.  If available, please install the latest version of ISScript.msi, or contact your support personnel for further assistance.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_NEXT</td><td>1033</td><td>&amp;Next &gt;</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_OK</td><td>1033</td><td>OK</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PREREQUISITE_SETUP_BROWSE</td><td>1033</td><td>Open [ProductName]'s original [SETUPEXENAME]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PREREQUISITE_SETUP_INVALID</td><td>1033</td><td>This executable file does not appear to be the original executable file for [ProductName]. Without using the original [SETUPEXENAME] to install additional dependencies, [ProductName] may not work correctly. Would you like to find the original [SETUPEXENAME]?</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PREREQUISITE_SETUP_SEARCH</td><td>1033</td><td>This installation may require additional dependencies. Without its dependencies, [ProductName] may not work correctly. Would you like to find the original [SETUPEXENAME]?</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PREVENT_DOWNGRADE_EXIT</td><td>1033</td><td>A newer version of this application is already installed on this computer. If you wish to install this version, please uninstall the newer version first. Click OK to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PRINT_BUTTON</td><td>1033</td><td>&amp;Print</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PRODUCTNAME_INSTALLSHIELD</td><td>1033</td><td>[ProductName] - InstallShield Wizard</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_CREATEAPPPOOL</td><td>1033</td><td>Creating application pool %s</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_CREATEAPPPOOLS</td><td>1033</td><td>Creating application Pools...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_CREATEVROOT</td><td>1033</td><td>Creating IIS virtual directory %s</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_CREATEVROOTS</td><td>1033</td><td>Creating IIS virtual directories...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_CREATEWEBSERVICEEXTENSION</td><td>1033</td><td>Creating web service extension</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_CREATEWEBSERVICEEXTENSIONS</td><td>1033</td><td>Creating web service extensions...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_CREATEWEBSITE</td><td>1033</td><td>Creating IIS website %s</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_CREATEWEBSITES</td><td>1033</td><td>Creating IIS websites...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_EXTRACT</td><td>1033</td><td>Extracting information for IIS virtual directories...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_EXTRACTDONE</td><td>1033</td><td>Extracted information for IIS virtual directories...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_REMOVEAPPPOOL</td><td>1033</td><td>Removing application pool</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_REMOVEAPPPOOLS</td><td>1033</td><td>Removing application pools...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_REMOVESITE</td><td>1033</td><td>Removing web site at port %d</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_REMOVEVROOT</td><td>1033</td><td>Removing IIS virtual directory %s</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_REMOVEVROOTS</td><td>1033</td><td>Removing IIS virtual directories...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_REMOVEWEBSERVICEEXTENSION</td><td>1033</td><td>Removing web service extension</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_REMOVEWEBSERVICEEXTENSIONS</td><td>1033</td><td>Removing web service extensions...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_REMOVEWEBSITES</td><td>1033</td><td>Removing IIS websites...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_ROLLBACKAPPPOOLS</td><td>1033</td><td>Rolling back application pools...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_ROLLBACKVROOTS</td><td>1033</td><td>Rolling back virtual directory and web site changes...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_IIS_ROLLBACKWEBSERVICEEXTENSIONS</td><td>1033</td><td>Rolling back web service extensions...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_TEXTFILECHANGS_REPLACE</td><td>1033</td><td>Replacing %s with %s in %s...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_XML_COSTING</td><td>1033</td><td>Costing XML files...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_XML_CREATE_FILE</td><td>1033</td><td>Creating XML file %s...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_XML_FILES</td><td>1033</td><td>Performing XML file changes...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_XML_REMOVE_FILE</td><td>1033</td><td>Removing XML file %s...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_XML_ROLLBACK_FILES</td><td>1033</td><td>Rolling back XML file changes...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_PROGMSG_XML_UPDATE_FILE</td><td>1033</td><td>Updating XML file %s...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SETUPEXE_EXPIRE_MSG</td><td>1033</td><td>This setup works until %s. The setup will now exit.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLBROWSE_INTRO</td><td>1033</td><td>From the list of servers below, select the database server you would like to target.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLBROWSE_INTRO_DB</td><td>1033</td><td>From the list of catalog names below, select the database catalog you would like to target.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLBROWSE_INTRO_TEMPLATE</td><td>1033</td><td>[IS_SQLBROWSE_INTRO]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_BROWSE</td><td>1033</td><td>B&amp;rowse...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_BROWSE_DB</td><td>1033</td><td>Br&amp;owse...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_CATALOG</td><td>1033</td><td>&amp;Name of database catalog:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_CONNECT</td><td>1033</td><td>Connect using:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_DESC</td><td>1033</td><td>Select database server and authentication method</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_ID</td><td>1033</td><td>&amp;Login ID:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_INTRO</td><td>1033</td><td>Select the database server to install to from the list below or click Browse to see a list of all database servers. You can also specify the way to authenticate your login using your current credentials or a SQL Login ID and Password.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_PSWD</td><td>1033</td><td>&amp;Password:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_SERVER</td><td>1033</td><td>&amp;Database Server:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_SERVER2</td><td>1033</td><td>&amp;Database server that you are installing to:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_SQL</td><td>1033</td><td>S&amp;erver authentication using the Login ID and password below</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_TITLE</td><td>1033</td><td>{&amp;MSSansBold8}Database Server</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLLOGIN_WIN</td><td>1033</td><td>&amp;Windows authentication credentials of current user</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLSCRIPT_INSTALLING</td><td>1033</td><td>Executing SQL Install Script...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SQLSCRIPT_UNINSTALLING</td><td>1033</td><td>Executing SQL Uninstall Script...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_STANDARD_USE_SETUPEXE</td><td>1033</td><td>This installation cannot be run by directly launching the MSI package. You must run setup.exe.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_Advertise</td><td>1033</td><td>Will be installed on first use. (Available only if the feature supports this option.)</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_AllInstalledLocal</td><td>1033</td><td>Will be completely installed to the local hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_CustomSetup</td><td>1033</td><td>{&amp;MSSansBold8}Custom Setup Tips</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_CustomSetupDescription</td><td>1033</td><td>Custom Setup allows you to selectively install program features.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_IconInstallState</td><td>1033</td><td>The icon next to the feature name indicates the install state of the feature. Click the icon to drop down the install state menu for each feature.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_InstallState</td><td>1033</td><td>This install state means the feature...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_Network</td><td>1033</td><td>Will be installed to run from the network. (Available only if the feature supports this option.)</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_OK</td><td>1033</td><td>OK</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_SubFeaturesInstalledLocal</td><td>1033</td><td>Will have some subfeatures installed to the local hard drive. (Available only if the feature has subfeatures.)</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_SetupTips_WillNotBeInstalled</td><td>1033</td><td>Will not be installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_Available</td><td>1033</td><td>Available</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_Bytes</td><td>1033</td><td>bytes</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_CompilingFeaturesCost</td><td>1033</td><td>Compiling cost for this feature...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_Differences</td><td>1033</td><td>Differences</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_DiskSize</td><td>1033</td><td>Disk Size</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureCompletelyRemoved</td><td>1033</td><td>This feature will be completely removed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureContinueNetwork</td><td>1033</td><td>This feature will continue to be run from the network</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureFreeSpace</td><td>1033</td><td>This feature frees up [1] on your hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledCD</td><td>1033</td><td>This feature, and all subfeatures, will be installed to run from the CD.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledCD2</td><td>1033</td><td>This feature will be installed to run from CD.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledLocal</td><td>1033</td><td>This feature, and all subfeatures, will be installed on local hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledLocal2</td><td>1033</td><td>This feature will be installed on local hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledNetwork</td><td>1033</td><td>This feature, and all subfeatures, will be installed to run from the network.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledNetwork2</td><td>1033</td><td>This feature will be installed to run from network.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledRequired</td><td>1033</td><td>Will be installed when required.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledWhenRequired</td><td>1033</td><td>This feature will be set to be installed when required.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureInstalledWhenRequired2</td><td>1033</td><td>This feature will be installed when required.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureLocal</td><td>1033</td><td>This feature will be installed on the local hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureLocal2</td><td>1033</td><td>This feature will be installed on your local hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureNetwork</td><td>1033</td><td>This feature will be installed to run from the network.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureNetwork2</td><td>1033</td><td>This feature will be available to run from the network.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureNotAvailable</td><td>1033</td><td>This feature will not be available.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureOnCD</td><td>1033</td><td>This feature will be installed to run from CD.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureOnCD2</td><td>1033</td><td>This feature will be available to run from CD.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureRemainLocal</td><td>1033</td><td>This feature will remain on your local hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureRemoveNetwork</td><td>1033</td><td>This feature will be removed from your local hard drive, but will be still available to run from the network.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureRemovedCD</td><td>1033</td><td>This feature will be removed from your local hard drive but will still be available to run from CD.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureRemovedUnlessRequired</td><td>1033</td><td>This feature will be removed from your local hard drive but will be set to be installed when required.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureRequiredSpace</td><td>1033</td><td>This feature requires [1] on your hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureRunFromCD</td><td>1033</td><td>This feature will continue to be run from the CD</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureSpaceFree</td><td>1033</td><td>This feature frees up [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures free up [4] on your hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureSpaceFree2</td><td>1033</td><td>This feature frees up [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures require [4] on your hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureSpaceFree3</td><td>1033</td><td>This feature requires [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures free up [4] on your hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureSpaceFree4</td><td>1033</td><td>This feature requires [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures require [4] on your hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureUnavailable</td><td>1033</td><td>This feature will become unavailable.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureUninstallNoNetwork</td><td>1033</td><td>This feature will be uninstalled completely, and you won't be able to run it from the network.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureWasCD</td><td>1033</td><td>This feature was run from the CD but will be set to be installed when required.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureWasCDLocal</td><td>1033</td><td>This feature was run from the CD but will be installed on the local hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureWasOnNetworkInstalled</td><td>1033</td><td>This feature was run from the network but will be installed when required.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureWasOnNetworkLocal</td><td>1033</td><td>This feature was run from the network but will be installed on the local hard drive.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_FeatureWillBeUninstalled</td><td>1033</td><td>This feature will be uninstalled completely, and you won't be able to run it from CD.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_Folder</td><td>1033</td><td>Fldr|New Folder</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_GB</td><td>1033</td><td>GB</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_KB</td><td>1033</td><td>KB</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_MB</td><td>1033</td><td>MB</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_Required</td><td>1033</td><td>Required</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_TimeRemaining</td><td>1033</td><td>Time remaining: {[1] min }{[2] sec}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS_UITEXT_Volume</td><td>1033</td><td>Volume</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__AgreeToLicense_0</td><td>1033</td><td>I &amp;do not accept the terms in the license agreement</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__AgreeToLicense_1</td><td>1033</td><td>I &amp;accept the terms in the license agreement</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DatabaseFolder_ChangeFolder</td><td>1033</td><td>Click Next to install to this folder, or click Change to install to a different folder.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DatabaseFolder_DatabaseDir</td><td>1033</td><td>[DATABASEDIR]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DatabaseFolder_DatabaseFolder</td><td>1033</td><td>{&amp;MSSansBold8}Database Folder</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DestinationFolder_Change</td><td>1033</td><td>&amp;Change...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DestinationFolder_ChangeFolder</td><td>1033</td><td>Click Next to install to this folder, or click Change to install to a different folder.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DestinationFolder_DestinationFolder</td><td>1033</td><td>{&amp;MSSansBold8}Destination Folder</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DestinationFolder_InstallTo</td><td>1033</td><td>Install [ProductName] to:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DisplayName_Custom</td><td>1033</td><td>Custom</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DisplayName_Minimal</td><td>1033</td><td>Minimal</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__DisplayName_Typical</td><td>1033</td><td>Typical</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_11</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_4</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_8</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_BrowseDestination</td><td>1033</td><td>Browse to the destination folder.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_ChangeDestination</td><td>1033</td><td>{&amp;MSSansBold8}Change Current Destination Folder</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_CreateFolder</td><td>1033</td><td>Create new folder|</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_FolderName</td><td>1033</td><td>&amp;Folder name:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_LookIn</td><td>1033</td><td>&amp;Look in:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallBrowse_UpOneLevel</td><td>1033</td><td>Up one level|</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallPointWelcome_ServerImage</td><td>1033</td><td>The InstallShield(R) Wizard will create a server image of [ProductName] at a specified network location. To continue, click Next.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallPointWelcome_Wizard</td><td>1033</td><td>{&amp;TahomaBold10}Welcome to the InstallShield Wizard for [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallPoint_Change</td><td>1033</td><td>&amp;Change...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallPoint_EnterNetworkLocation</td><td>1033</td><td>Enter the network location or click Change to browse to a location.  Click Install to create a server image of [ProductName] at the specified network location or click Cancel to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallPoint_Install</td><td>1033</td><td>&amp;Install</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallPoint_NetworkLocation</td><td>1033</td><td>&amp;Network location:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallPoint_NetworkLocationFormatted</td><td>1033</td><td>{&amp;MSSansBold8}Network Location</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsAdminInstallPoint_SpecifyNetworkLocation</td><td>1033</td><td>Specify a network location for the server image of the product.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseButton</td><td>1033</td><td>&amp;Browse...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_11</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_4</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_8</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_BrowseDestFolder</td><td>1033</td><td>Browse to the destination folder.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_ChangeCurrentFolder</td><td>1033</td><td>{&amp;MSSansBold8}Change Current Destination Folder</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_CreateFolder</td><td>1033</td><td>Create New Folder|</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_FolderName</td><td>1033</td><td>&amp;Folder name:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_LookIn</td><td>1033</td><td>&amp;Look in:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_OK</td><td>1033</td><td>OK</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseFolderDlg_UpOneLevel</td><td>1033</td><td>Up One Level|</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseForAccount</td><td>1033</td><td>Browse for a User Account</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseGroup</td><td>1033</td><td>Select a Group</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsBrowseUsernameTitle</td><td>1033</td><td>Select a User Name</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCancelDlg_ConfirmCancel</td><td>1033</td><td>Are you sure you want to cancel [ProductName] installation?</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCancelDlg_No</td><td>1033</td><td>&amp;No</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCancelDlg_Yes</td><td>1033</td><td>&amp;Yes</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsConfirmPassword</td><td>1033</td><td>Con&amp;firm password:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCreateNewUserTitle</td><td>1033</td><td>New User Information</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCreateUserBrowse</td><td>1033</td><td>N&amp;ew User Information...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_Change</td><td>1033</td><td>&amp;Change...</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_ClickFeatureIcon</td><td>1033</td><td>Click on an icon in the list below to change how a feature is installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_CustomSetup</td><td>1033</td><td>{&amp;MSSansBold8}Custom Setup</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_FeatureDescription</td><td>1033</td><td>Feature Description</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_FeaturePath</td><td>1033</td><td>&lt;selected feature path&gt;</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_FeatureSize</td><td>1033</td><td>Feature size</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_Help</td><td>1033</td><td>&amp;Help</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_InstallTo</td><td>1033</td><td>Install to:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_MultilineDescription</td><td>1033</td><td>Multiline description of the currently selected item</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_SelectFeatures</td><td>1033</td><td>Select the program features you want installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsCustomSelectionDlg_Space</td><td>1033</td><td>&amp;Space</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsDiskSpaceDlg_DiskSpace</td><td>1033</td><td>Disk space required for the installation exceeds available disk space.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsDiskSpaceDlg_HighlightedVolumes</td><td>1033</td><td>The highlighted volumes do not have enough disk space available for the currently selected features. You can remove files from the highlighted volumes, choose to install fewer features onto local drives, or select different destination drives.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsDiskSpaceDlg_Numbers</td><td>1033</td><td>{120}{70}{70}{70}{70}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsDiskSpaceDlg_OK</td><td>1033</td><td>OK</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsDiskSpaceDlg_OutOfDiskSpace</td><td>1033</td><td>{&amp;MSSansBold8}Out of Disk Space</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsDomainOrServer</td><td>1033</td><td>&amp;Domain or server:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsErrorDlg_Abort</td><td>1033</td><td>&amp;Abort</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsErrorDlg_ErrorText</td><td>1033</td><td>&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;&lt;error text goes here&gt;</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsErrorDlg_Ignore</td><td>1033</td><td>&amp;Ignore</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsErrorDlg_InstallerInfo</td><td>1033</td><td>[ProductName] Installer Information</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsErrorDlg_NO</td><td>1033</td><td>&amp;No</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsErrorDlg_OK</td><td>1033</td><td>&amp;OK</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsErrorDlg_Retry</td><td>1033</td><td>&amp;Retry</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsErrorDlg_Yes</td><td>1033</td><td>&amp;Yes</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_Finish</td><td>1033</td><td>&amp;Finish</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_InstallSuccess</td><td>1033</td><td>The InstallShield Wizard has successfully installed [ProductName]. Click Finish to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_LaunchProgram</td><td>1033</td><td>Launch the program</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_ShowReadMe</td><td>1033</td><td>Show the readme file</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_UninstallSuccess</td><td>1033</td><td>The InstallShield Wizard has successfully uninstalled [ProductName]. Click Finish to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_Update_InternetConnection</td><td>1033</td><td>Your Internet connection can be used to make sure that you have the latest updates.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_Update_PossibleUpdates</td><td>1033</td><td>Some program files might have been updated since you purchased your copy of [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_Update_SetupFinished</td><td>1033</td><td>Setup has finished installing [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_Update_YesCheckForUpdates</td><td>1033</td><td>&amp;Yes, check for program updates (Recommended) after the setup completes.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsExitDialog_WizardCompleted</td><td>1033</td><td>{&amp;TahomaBold10}InstallShield Wizard Completed</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFatalError_ClickFinish</td><td>1033</td><td>Click Finish to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFatalError_Finish</td><td>1033</td><td>&amp;Finish</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFatalError_KeepOrRestore</td><td>1033</td><td>You can either keep any existing installed elements on your system to continue this installation at a later time or you can restore your system to its original state prior to the installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFatalError_NotModified</td><td>1033</td><td>Your system has not been modified. To complete installation at another time, please run setup again.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFatalError_RestoreOrContinueLater</td><td>1033</td><td>Click Restore or Continue Later to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFatalError_WizardCompleted</td><td>1033</td><td>{&amp;TahomaBold10}InstallShield Wizard Completed</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFatalError_WizardInterrupted</td><td>1033</td><td>The wizard was interrupted before [ProductName] could be completely installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFeatureDetailsDlg_DiskSpaceRequirements</td><td>1033</td><td>{&amp;MSSansBold8}Disk Space Requirements</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFeatureDetailsDlg_Numbers</td><td>1033</td><td>{120}{70}{70}{70}{70}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFeatureDetailsDlg_OK</td><td>1033</td><td>OK</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFeatureDetailsDlg_SpaceRequired</td><td>1033</td><td>The disk space required for the installation of the selected features.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFeatureDetailsDlg_VolumesTooSmall</td><td>1033</td><td>The highlighted volumes do not have enough disk space available for the currently selected features. You can remove files from the highlighted volumes, choose to install fewer features onto local drives, or select different destination drives.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFilesInUse_ApplicationsUsingFiles</td><td>1033</td><td>The following applications are using files that need to be updated by this setup. Close these applications and click Retry to continue.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFilesInUse_Exit</td><td>1033</td><td>&amp;Exit</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFilesInUse_FilesInUse</td><td>1033</td><td>{&amp;MSSansBold8}Files in Use</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFilesInUse_FilesInUseMessage</td><td>1033</td><td>Some files that need to be updated are currently in use.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFilesInUse_Ignore</td><td>1033</td><td>&amp;Ignore</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsFilesInUse_Retry</td><td>1033</td><td>&amp;Retry</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsGroup</td><td>1033</td><td>&amp;Group:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsGroupLabel</td><td>1033</td><td>Gr&amp;oup:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsInitDlg_1</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsInitDlg_2</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsInitDlg_PreparingWizard</td><td>1033</td><td>[ProductName] Setup is preparing the InstallShield Wizard which will guide you through the program setup process.  Please wait.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsInitDlg_WelcomeWizard</td><td>1033</td><td>{&amp;TahomaBold10}Welcome to the InstallShield Wizard for [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsLicenseDlg_LicenseAgreement</td><td>1033</td><td>{&amp;MSSansBold8}License Agreement</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsLicenseDlg_ReadLicenseAgreement</td><td>1033</td><td>Please read the following license agreement carefully.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsLogonInfoDescription</td><td>1033</td><td>Specify the user name and password of the user account that will logon to use this application. The user account must be in the form DOMAIN\Username.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsLogonInfoTitle</td><td>1033</td><td>{&amp;MSSansBold8}Logon Information</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsLogonInfoTitleDescription</td><td>1033</td><td>Specify a user name and password</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsLogonNewUserDescription</td><td>1033</td><td>Select the button below to specify information about a new user that will be created during the installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceDlg_ChangeFeatures</td><td>1033</td><td>Change which program features are installed. This option displays the Custom Selection dialog in which you can change the way features are installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceDlg_MaitenanceOptions</td><td>1033</td><td>Modify, repair, or remove the program.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceDlg_Modify</td><td>1033</td><td>{&amp;MSSansBold8}&amp;Modify</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceDlg_ProgramMaintenance</td><td>1033</td><td>{&amp;MSSansBold8}Program Maintenance</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceDlg_Remove</td><td>1033</td><td>{&amp;MSSansBold8}&amp;Remove</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceDlg_RemoveProductName</td><td>1033</td><td>Remove [ProductName] from your computer.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceDlg_Repair</td><td>1033</td><td>{&amp;MSSansBold8}Re&amp;pair</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceDlg_RepairMessage</td><td>1033</td><td>Repair installation errors in the program. This option fixes missing or corrupt files, shortcuts, and registry entries.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceWelcome_MaintenanceOptionsDescription</td><td>1033</td><td>The InstallShield(R) Wizard will allow you to modify, repair, or remove [ProductName]. To continue, click Next.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMaintenanceWelcome_WizardWelcome</td><td>1033</td><td>{&amp;TahomaBold10}Welcome to the InstallShield Wizard for [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMsiRMFilesInUse_ApplicationsUsingFiles</td><td>1033</td><td>The following applications are using files that need to be updated by this setup.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMsiRMFilesInUse_CloseRestart</td><td>1033</td><td>Automatically close and attempt to restart applications.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsMsiRMFilesInUse_RebootAfter</td><td>1033</td><td>Do not close applications. (A reboot will be required.)</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsPatchDlg_PatchClickUpdate</td><td>1033</td><td>The InstallShield(R) Wizard will install the Patch for [ProductName] on your computer.  To continue, click Update.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsPatchDlg_PatchWizard</td><td>1033</td><td>[ProductName] Patch - InstallShield Wizard</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsPatchDlg_Update</td><td>1033</td><td>&amp;Update &gt;</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsPatchDlg_WelcomePatchWizard</td><td>1033</td><td>{&amp;TahomaBold10}Welcome to the Patch for [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_2</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_Hidden</td><td>1033</td><td>(Hidden for now)</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_HiddenTimeRemaining</td><td>1033</td><td>)Hidden for now)Estimated time remaining:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_InstallingProductName</td><td>1033</td><td>{&amp;MSSansBold8}Installing [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_ProgressDone</td><td>1033</td><td>Progress done</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_SecHidden</td><td>1033</td><td>(Hidden for now)Sec.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_Status</td><td>1033</td><td>Status:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_Uninstalling</td><td>1033</td><td>{&amp;MSSansBold8}Uninstalling [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_UninstallingFeatures</td><td>1033</td><td>The program features you selected are being uninstalled.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_UninstallingFeatures2</td><td>1033</td><td>The program features you selected are being installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_WaitUninstall</td><td>1033</td><td>Please wait while the InstallShield Wizard uninstalls [ProductName]. This may take several minutes.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsProgressDlg_WaitUninstall2</td><td>1033</td><td>Please wait while the InstallShield Wizard installs [ProductName]. This may take several minutes.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsReadmeDlg_Cancel</td><td>1033</td><td>&amp;Cancel</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsReadmeDlg_PleaseReadInfo</td><td>1033</td><td>Please read the following readme information carefully.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsReadmeDlg_ReadMeInfo</td><td>1033</td><td>{&amp;MSSansBold8}Readme Information</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_16</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_Anyone</td><td>1033</td><td>&amp;Anyone who uses this computer (all users)</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_CustomerInformation</td><td>1033</td><td>{&amp;MSSansBold8}Customer Information</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_InstallFor</td><td>1033</td><td>Install this application for:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_OnlyMe</td><td>1033</td><td>Only for &amp;me ([USERNAME])</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_Organization</td><td>1033</td><td>&amp;Organization:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_PleaseEnterInfo</td><td>1033</td><td>Please enter your information.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_SerialNumber</td><td>1033</td><td>&amp;Serial Number:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_Tahoma50</td><td>1033</td><td>{\Tahoma8}{50}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_Tahoma80</td><td>1033</td><td>{\Tahoma8}{80}</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsRegisterUserDlg_UserName</td><td>1033</td><td>&amp;User Name:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsResumeDlg_ResumeSuspended</td><td>1033</td><td>The InstallShield(R) Wizard will complete the suspended installation of [ProductName] on your computer. To continue, click Next.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsResumeDlg_Resuming</td><td>1033</td><td>{&amp;TahomaBold10}Resuming the InstallShield Wizard for [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsResumeDlg_WizardResume</td><td>1033</td><td>The InstallShield(R) Wizard will complete the installation of [ProductName] on your computer. To continue, click Next.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSelectDomainOrServer</td><td>1033</td><td>Select a Domain or Server</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSelectDomainUserInstructions</td><td>1033</td><td>Use the browse buttons to select a domain\server and a user name.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupComplete_ShowMsiLog</td><td>1033</td><td>Show the Windows Installer log</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_13</td><td>1033</td><td/><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_AllFeatures</td><td>1033</td><td>All program features will be installed. (Requires the most disk space.)</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_ChooseFeatures</td><td>1033</td><td>Choose which program features you want installed and where they will be installed. Recommended for advanced users.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_ChooseSetupType</td><td>1033</td><td>Choose the setup type that best suits your needs.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_Complete</td><td>1033</td><td>{&amp;MSSansBold8}&amp;Complete</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_Custom</td><td>1033</td><td>{&amp;MSSansBold8}Cu&amp;stom</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_Minimal</td><td>1033</td><td>{&amp;MSSansBold8}&amp;Minimal</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_MinimumFeatures</td><td>1033</td><td>Minimum required features will be installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_SelectSetupType</td><td>1033</td><td>Please select a setup type.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_SetupType</td><td>1033</td><td>{&amp;MSSansBold8}Setup Type</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsSetupTypeMinDlg_Typical</td><td>1033</td><td>{&amp;MSSansBold8}&amp;Typical</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsUserExit_ClickFinish</td><td>1033</td><td>Click Finish to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsUserExit_Finish</td><td>1033</td><td>&amp;Finish</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsUserExit_KeepOrRestore</td><td>1033</td><td>You can either keep any existing installed elements on your system to continue this installation at a later time or you can restore your system to its original state prior to the installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsUserExit_NotModified</td><td>1033</td><td>Your system has not been modified. To install this program at a later time, please run the installation again.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsUserExit_RestoreOrContinue</td><td>1033</td><td>Click Restore or Continue Later to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsUserExit_WizardCompleted</td><td>1033</td><td>{&amp;TahomaBold10}InstallShield Wizard Completed</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsUserExit_WizardInterrupted</td><td>1033</td><td>The wizard was interrupted before [ProductName] could be completely installed.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsUserNameLabel</td><td>1033</td><td>&amp;User name:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_BackOrCancel</td><td>1033</td><td>If you want to review or change any of your installation settings, click Back. Click Cancel to exit the wizard.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_ClickInstall</td><td>1033</td><td>Click Install to begin the installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_Company</td><td>1033</td><td>Company: [COMPANYNAME]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_CurrentSettings</td><td>1033</td><td>Current Settings:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_DestFolder</td><td>1033</td><td>Destination Folder:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_Install</td><td>1033</td><td>&amp;Install</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_Installdir</td><td>1033</td><td>[INSTALLDIR]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_ModifyReady</td><td>1033</td><td>{&amp;MSSansBold8}Ready to Modify the Program</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_ReadyInstall</td><td>1033</td><td>{&amp;MSSansBold8}Ready to Install the Program</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_ReadyRepair</td><td>1033</td><td>{&amp;MSSansBold8}Ready to Repair the Program</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_SelectedSetupType</td><td>1033</td><td>[SelectedSetupType]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_Serial</td><td>1033</td><td>Serial: [ISX_SERIALNUM]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_SetupType</td><td>1033</td><td>Setup Type:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_UserInfo</td><td>1033</td><td>User Information:</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_UserName</td><td>1033</td><td>Name: [USERNAME]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyReadyDlg_WizardReady</td><td>1033</td><td>The wizard is ready to begin installation.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyRemoveAllDlg_ChoseRemoveProgram</td><td>1033</td><td>You have chosen to remove the program from your system.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyRemoveAllDlg_ClickBack</td><td>1033</td><td>If you want to review or change any settings, click Back.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyRemoveAllDlg_ClickRemove</td><td>1033</td><td>Click Remove to remove [ProductName] from your computer. After removal, this program will no longer be available for use.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyRemoveAllDlg_Remove</td><td>1033</td><td>&amp;Remove</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsVerifyRemoveAllDlg_RemoveProgram</td><td>1033</td><td>{&amp;MSSansBold8}Remove the Program</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsWelcomeDlg_InstallProductName</td><td>1033</td><td>The InstallShield(R) Wizard will install [ProductName] on your computer. To continue, click Next.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsWelcomeDlg_WarningCopyright</td><td>1033</td><td>WARNING: This program is protected by copyright law and international treaties.</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__IsWelcomeDlg_WelcomeProductName</td><td>1033</td><td>{&amp;TahomaBold10}Welcome to the InstallShield Wizard for [ProductName]</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__TargetReq_DESC_COLOR</td><td>1033</td><td>The color settings of your system are not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__TargetReq_DESC_OS</td><td>1033</td><td>The operating system is not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__TargetReq_DESC_PROCESSOR</td><td>1033</td><td>The processor is not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__TargetReq_DESC_RAM</td><td>1033</td><td>The amount of RAM is not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>IDS__TargetReq_DESC_RESOLUTION</td><td>1033</td><td>The screen resolution is not adequate for running [ProductName].</td><td>0</td><td/><td>337541408</td></row>\r
+               <row><td>ID_STRING1</td><td>1033</td><td>http://www.simantics.org</td><td>0</td><td/><td>186638349</td></row>\r
+               <row><td>ID_STRING10</td><td>1033</td><td>The Simantics system dynamics application.</td><td>0</td><td/><td>723530385</td></row>\r
+               <row><td>ID_STRING2</td><td>1033</td><td>SIMANT~1|Simantics</td><td>0</td><td/><td>-224422991</td></row>\r
+               <row><td>ID_STRING3</td><td>1033</td><td>Sysdyn</td><td>0</td><td/><td>-224459791</td></row>\r
+               <row><td>ID_STRING4</td><td>1033</td><td>Sysdyn</td><td>0</td><td/><td>186587916</td></row>\r
+               <row><td>ID_STRING5</td><td>1033</td><td>Sysdyn</td><td>0</td><td/><td>186620941</td></row>\r
+               <row><td>ID_STRING6</td><td>1033</td><td>Sysdyn</td><td>0</td><td/><td>186592301</td></row>\r
+               <row><td>ID_STRING7</td><td>1033</td><td>Simantics Sysdyn Feature</td><td>0</td><td/><td>723518097</td></row>\r
+               <row><td>ID_STRING8</td><td>1033</td><td>The Simantics system dynamics application.</td><td>0</td><td/><td>723544781</td></row>\r
+               <row><td>ID_STRING9</td><td>1033</td><td>Simantics Sysdyn Feature</td><td>0</td><td/><td>723546769</td></row>\r
+               <row><td>IIDS_UITEXT_FeatureUninstalled</td><td>1033</td><td>This feature will remain uninstalled.</td><td>0</td><td/><td>337541408</td></row>\r
+       </table>\r
+\r
+       <table name="ISTargetImage">\r
+               <col key="yes" def="s13">UpgradedImage_</col>\r
+               <col key="yes" def="s13">Name</col>\r
+               <col def="s0">MsiPath</col>\r
+               <col def="i2">Order</col>\r
+               <col def="I4">Flags</col>\r
+               <col def="i2">IgnoreMissingFiles</col>\r
+       </table>\r
+\r
+       <table name="ISUpgradeMsiItem">\r
+               <col key="yes" def="s72">UpgradeItem</col>\r
+               <col def="s0">ObjectSetupPath</col>\r
+               <col def="S255">ISReleaseFlags</col>\r
+               <col def="i2">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="ISUpgradedImage">\r
+               <col key="yes" def="s13">Name</col>\r
+               <col def="s0">MsiPath</col>\r
+               <col def="s8">Family</col>\r
+       </table>\r
+\r
+       <table name="ISVirtualDirectory">\r
+               <col key="yes" def="s72">Directory_</col>\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="s255">Value</col>\r
+       </table>\r
+\r
+       <table name="ISVirtualFile">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="s255">Value</col>\r
+       </table>\r
+\r
+       <table name="ISVirtualPackage">\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="s255">Value</col>\r
+       </table>\r
+\r
+       <table name="ISVirtualRegistry">\r
+               <col key="yes" def="s72">Registry_</col>\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="s255">Value</col>\r
+       </table>\r
+\r
+       <table name="ISVirtualRelease">\r
+               <col key="yes" def="s72">ISRelease_</col>\r
+               <col key="yes" def="s72">ISProductConfiguration_</col>\r
+               <col key="yes" def="s255">Name</col>\r
+               <col def="s255">Value</col>\r
+       </table>\r
+\r
+       <table name="ISVirtualShortcut">\r
+               <col key="yes" def="s72">Shortcut_</col>\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="s255">Value</col>\r
+       </table>\r
+\r
+       <table name="ISXmlElement">\r
+               <col key="yes" def="s72">ISXmlElement</col>\r
+               <col def="s72">ISXmlFile_</col>\r
+               <col def="S72">ISXmlElement_Parent</col>\r
+               <col def="L0">XPath</col>\r
+               <col def="L0">Content</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="ISXmlElementAttrib">\r
+               <col key="yes" def="s72">ISXmlElementAttrib</col>\r
+               <col key="yes" def="s72">ISXmlElement_</col>\r
+               <col def="L255">Name</col>\r
+               <col def="L0">Value</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="ISXmlFile">\r
+               <col key="yes" def="s72">ISXmlFile</col>\r
+               <col def="l255">FileName</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="s72">Directory</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <col def="S0">SelectionNamespaces</col>\r
+               <col def="S255">Encoding</col>\r
+       </table>\r
+\r
+       <table name="ISXmlLocator">\r
+               <col key="yes" def="s72">Signature_</col>\r
+               <col key="yes" def="S72">Parent</col>\r
+               <col def="S255">Element</col>\r
+               <col def="S255">Attribute</col>\r
+               <col def="I2">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="Icon">\r
+               <col key="yes" def="s72">Name</col>\r
+               <col def="V0">Data</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+               <col def="I2">ISIconIndex</col>\r
+               <row><td>ARPPRODUCTICON.exe</td><td/><td>&lt;PATH_TO_SIMANTICS-SYSDY_FI&gt;\puzzle_green.ico</td><td>0</td></row>\r
+       </table>\r
+\r
+       <table name="IniFile">\r
+               <col key="yes" def="s72">IniFile</col>\r
+               <col def="l255">FileName</col>\r
+               <col def="S72">DirProperty</col>\r
+               <col def="l255">Section</col>\r
+               <col def="l128">Key</col>\r
+               <col def="s255">Value</col>\r
+               <col def="i2">Action</col>\r
+               <col def="s72">Component_</col>\r
+       </table>\r
+\r
+       <table name="IniLocator">\r
+               <col key="yes" def="s72">Signature_</col>\r
+               <col def="s255">FileName</col>\r
+               <col def="s96">Section</col>\r
+               <col def="s128">Key</col>\r
+               <col def="I2">Field</col>\r
+               <col def="I2">Type</col>\r
+       </table>\r
+\r
+       <table name="InstallExecuteSequence">\r
+               <col key="yes" def="s72">Action</col>\r
+               <col def="S255">Condition</col>\r
+               <col def="I2">Sequence</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <row><td>AllocateRegistrySpace</td><td>NOT Installed</td><td>1550</td><td>AllocateRegistrySpace</td><td/></row>\r
+               <row><td>AppSearch</td><td/><td>400</td><td>AppSearch</td><td/></row>\r
+               <row><td>BindImage</td><td/><td>4300</td><td>BindImage</td><td/></row>\r
+               <row><td>CCPSearch</td><td>CCP_TEST</td><td>500</td><td>CCPSearch</td><td/></row>\r
+               <row><td>CostFinalize</td><td/><td>1000</td><td>CostFinalize</td><td/></row>\r
+               <row><td>CostInitialize</td><td/><td>800</td><td>CostInitialize</td><td/></row>\r
+               <row><td>CreateFolders</td><td/><td>3700</td><td>CreateFolders</td><td/></row>\r
+               <row><td>CreateShortcuts</td><td/><td>4500</td><td>CreateShortcuts</td><td/></row>\r
+               <row><td>DeleteServices</td><td>VersionNT</td><td>2000</td><td>DeleteServices</td><td/></row>\r
+               <row><td>DuplicateFiles</td><td/><td>4210</td><td>DuplicateFiles</td><td/></row>\r
+               <row><td>FileCost</td><td/><td>900</td><td>FileCost</td><td/></row>\r
+               <row><td>FindRelatedProducts</td><td>NOT ISSETUPDRIVEN</td><td>420</td><td>FindRelatedProducts</td><td/></row>\r
+               <row><td>ISPreventDowngrade</td><td>ISFOUNDNEWERPRODUCTVERSION</td><td>450</td><td>ISPreventDowngrade</td><td/></row>\r
+               <row><td>ISSelfRegisterCosting</td><td/><td>2201</td><td/><td/></row>\r
+               <row><td>ISSelfRegisterFiles</td><td/><td>5601</td><td/><td/></row>\r
+               <row><td>ISSelfRegisterFinalize</td><td/><td>6601</td><td/><td/></row>\r
+               <row><td>ISSetupFilesCleanup</td><td/><td>6602</td><td/><td/></row>\r
+               <row><td>ISSetupFilesExtract</td><td/><td>3</td><td/><td/></row>\r
+               <row><td>ISUnSelfRegisterFiles</td><td/><td>2202</td><td/><td/></row>\r
+               <row><td>InstallFiles</td><td/><td>4000</td><td>InstallFiles</td><td/></row>\r
+               <row><td>InstallFinalize</td><td/><td>6600</td><td>InstallFinalize</td><td/></row>\r
+               <row><td>InstallInitialize</td><td/><td>1501</td><td>InstallInitialize</td><td/></row>\r
+               <row><td>InstallODBC</td><td/><td>5400</td><td>InstallODBC</td><td/></row>\r
+               <row><td>InstallServices</td><td>VersionNT</td><td>5800</td><td>InstallServices</td><td/></row>\r
+               <row><td>InstallValidate</td><td/><td>1400</td><td>InstallValidate</td><td/></row>\r
+               <row><td>IsolateComponents</td><td/><td>950</td><td>IsolateComponents</td><td/></row>\r
+               <row><td>LaunchConditions</td><td>Not Installed</td><td>410</td><td>LaunchConditions</td><td/></row>\r
+               <row><td>MigrateFeatureStates</td><td/><td>1010</td><td>MigrateFeatureStates</td><td/></row>\r
+               <row><td>MoveFiles</td><td/><td>3800</td><td>MoveFiles</td><td/></row>\r
+               <row><td>MsiConfigureServices</td><td>VersionMsi &gt;= "5.00"</td><td>5850</td><td>MSI5 MsiConfigureServices</td><td/></row>\r
+               <row><td>MsiPublishAssemblies</td><td/><td>6250</td><td>MsiPublishAssemblies</td><td/></row>\r
+               <row><td>MsiUnpublishAssemblies</td><td/><td>1750</td><td>MsiUnpublishAssemblies</td><td/></row>\r
+               <row><td>PatchFiles</td><td/><td>4090</td><td>PatchFiles</td><td/></row>\r
+               <row><td>ProcessComponents</td><td/><td>1600</td><td>ProcessComponents</td><td/></row>\r
+               <row><td>PublishComponents</td><td/><td>6200</td><td>PublishComponents</td><td/></row>\r
+               <row><td>PublishFeatures</td><td/><td>6300</td><td>PublishFeatures</td><td/></row>\r
+               <row><td>PublishProduct</td><td/><td>6400</td><td>PublishProduct</td><td/></row>\r
+               <row><td>RMCCPSearch</td><td>Not CCP_SUCCESS And CCP_TEST</td><td>600</td><td>RMCCPSearch</td><td/></row>\r
+               <row><td>RegisterClassInfo</td><td/><td>4600</td><td>RegisterClassInfo</td><td/></row>\r
+               <row><td>RegisterComPlus</td><td/><td>5700</td><td>RegisterComPlus</td><td/></row>\r
+               <row><td>RegisterExtensionInfo</td><td/><td>4700</td><td>RegisterExtensionInfo</td><td/></row>\r
+               <row><td>RegisterFonts</td><td/><td>5300</td><td>RegisterFonts</td><td/></row>\r
+               <row><td>RegisterMIMEInfo</td><td/><td>4900</td><td>RegisterMIMEInfo</td><td/></row>\r
+               <row><td>RegisterProduct</td><td/><td>6100</td><td>RegisterProduct</td><td/></row>\r
+               <row><td>RegisterProgIdInfo</td><td/><td>4800</td><td>RegisterProgIdInfo</td><td/></row>\r
+               <row><td>RegisterTypeLibraries</td><td/><td>5500</td><td>RegisterTypeLibraries</td><td/></row>\r
+               <row><td>RegisterUser</td><td/><td>6000</td><td>RegisterUser</td><td/></row>\r
+               <row><td>RemoveDuplicateFiles</td><td/><td>3400</td><td>RemoveDuplicateFiles</td><td/></row>\r
+               <row><td>RemoveEnvironmentStrings</td><td/><td>3300</td><td>RemoveEnvironmentStrings</td><td/></row>\r
+               <row><td>RemoveExistingProducts</td><td/><td>1410</td><td>RemoveExistingProducts</td><td/></row>\r
+               <row><td>RemoveFiles</td><td/><td>3500</td><td>RemoveFiles</td><td/></row>\r
+               <row><td>RemoveFolders</td><td/><td>3600</td><td>RemoveFolders</td><td/></row>\r
+               <row><td>RemoveIniValues</td><td/><td>3100</td><td>RemoveIniValues</td><td/></row>\r
+               <row><td>RemoveODBC</td><td/><td>2400</td><td>RemoveODBC</td><td/></row>\r
+               <row><td>RemoveRegistryValues</td><td/><td>2600</td><td>RemoveRegistryValues</td><td/></row>\r
+               <row><td>RemoveShortcuts</td><td/><td>3200</td><td>RemoveShortcuts</td><td/></row>\r
+               <row><td>ResolveSource</td><td>Not Installed</td><td>850</td><td>ResolveSource</td><td/></row>\r
+               <row><td>ScheduleReboot</td><td>ISSCHEDULEREBOOT</td><td>6410</td><td>ScheduleReboot</td><td/></row>\r
+               <row><td>SelfRegModules</td><td/><td>5600</td><td>SelfRegModules</td><td/></row>\r
+               <row><td>SelfUnregModules</td><td/><td>2200</td><td>SelfUnregModules</td><td/></row>\r
+               <row><td>SetARPINSTALLLOCATION</td><td/><td>1100</td><td>SetARPINSTALLLOCATION</td><td/></row>\r
+               <row><td>SetAllUsersProfileNT</td><td>VersionNT = 400</td><td>970</td><td/><td/></row>\r
+               <row><td>SetODBCFolders</td><td/><td>1200</td><td>SetODBCFolders</td><td/></row>\r
+               <row><td>StartServices</td><td>VersionNT</td><td>5900</td><td>StartServices</td><td/></row>\r
+               <row><td>StopServices</td><td>VersionNT</td><td>1900</td><td>StopServices</td><td/></row>\r
+               <row><td>UnpublishComponents</td><td/><td>1700</td><td>UnpublishComponents</td><td/></row>\r
+               <row><td>UnpublishFeatures</td><td/><td>1800</td><td>UnpublishFeatures</td><td/></row>\r
+               <row><td>UnregisterClassInfo</td><td/><td>2700</td><td>UnregisterClassInfo</td><td/></row>\r
+               <row><td>UnregisterComPlus</td><td/><td>2100</td><td>UnregisterComPlus</td><td/></row>\r
+               <row><td>UnregisterExtensionInfo</td><td/><td>2800</td><td>UnregisterExtensionInfo</td><td/></row>\r
+               <row><td>UnregisterFonts</td><td/><td>2500</td><td>UnregisterFonts</td><td/></row>\r
+               <row><td>UnregisterMIMEInfo</td><td/><td>3000</td><td>UnregisterMIMEInfo</td><td/></row>\r
+               <row><td>UnregisterProgIdInfo</td><td/><td>2900</td><td>UnregisterProgIdInfo</td><td/></row>\r
+               <row><td>UnregisterTypeLibraries</td><td/><td>2300</td><td>UnregisterTypeLibraries</td><td/></row>\r
+               <row><td>ValidateProductID</td><td/><td>700</td><td>ValidateProductID</td><td/></row>\r
+               <row><td>WriteEnvironmentStrings</td><td/><td>5200</td><td>WriteEnvironmentStrings</td><td/></row>\r
+               <row><td>WriteIniValues</td><td/><td>5100</td><td>WriteIniValues</td><td/></row>\r
+               <row><td>WriteRegistryValues</td><td/><td>5000</td><td>WriteRegistryValues</td><td/></row>\r
+               <row><td>setAllUsersProfile2K</td><td>VersionNT &gt;= 500</td><td>980</td><td/><td/></row>\r
+               <row><td>setUserProfileNT</td><td>VersionNT</td><td>960</td><td/><td/></row>\r
+       </table>\r
+\r
+       <table name="InstallShield">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col def="S0">Value</col>\r
+               <row><td>ActiveLanguage</td><td>1033</td></row>\r
+               <row><td>Comments</td><td/></row>\r
+               <row><td>CurrentMedia</td><td dt:dt="bin.base64" md5="335a4e5778f6cc4147c037b23201fac4">\r
+UwAzAAEAUwAzAA==\r
+                       </td></row>\r
+               <row><td>DialogSizeType</td><td>1</td></row>\r
+               <row><td>DoMaintenance</td><td>0</td></row>\r
+               <row><td>ISCompilerOption_CompileBeforeBuild</td><td>1</td></row>\r
+               <row><td>ISCompilerOption_Debug</td><td>0</td></row>\r
+               <row><td>ISCompilerOption_IncludePath</td><td/></row>\r
+               <row><td>ISCompilerOption_LibraryPath</td><td/></row>\r
+               <row><td>ISCompilerOption_MaxErrors</td><td>50</td></row>\r
+               <row><td>ISCompilerOption_MaxWarnings</td><td>50</td></row>\r
+               <row><td>ISCompilerOption_OutputPath</td><td>&lt;ISProjectDataFolder&gt;\Script Files</td></row>\r
+               <row><td>ISCompilerOption_PreProcessor</td><td>_ISSCRIPT_NEW_STYLE_DLG_DEFS</td></row>\r
+               <row><td>ISCompilerOption_WarningLevel</td><td>3</td></row>\r
+               <row><td>ISCompilerOption_WarningsAsErrors</td><td>1</td></row>\r
+               <row><td>ISTheme</td><td>InstallShield Blue.theme</td></row>\r
+               <row><td>ISUSLock</td><td>{1ADA6D22-A47C-4CCE-A448-3E6B1FECB511}</td></row>\r
+               <row><td>ISUSSignature</td><td>{E8E916BB-8489-4623-B8FD-22E7804B70E6}</td></row>\r
+               <row><td>LockPermissionMode</td><td>1</td></row>\r
+               <row><td>MsiExecCmdLineOptions</td><td/></row>\r
+               <row><td>MsiLogFile</td><td/></row>\r
+               <row><td>OnUpgrade</td><td>1</td></row>\r
+               <row><td>Owner</td><td/></row>\r
+               <row><td>PatchFamily</td><td>MyPatchFamily1</td></row>\r
+               <row><td>PatchSequence</td><td>1.0.0</td></row>\r
+               <row><td>SaveAsSchema</td><td/></row>\r
+               <row><td>SccEnabled</td><td>0</td></row>\r
+               <row><td>SccPath</td><td/></row>\r
+               <row><td>SchemaVersion</td><td>771</td></row>\r
+               <row><td>Script</td><td>1</td></row>\r
+               <row><td>Type</td><td>MSI</td></row>\r
+               <row><td>UseMSI45EmbeddedUI</td><td>0</td></row>\r
+       </table>\r
+\r
+       <table name="InstallUISequence">\r
+               <col key="yes" def="s72">Action</col>\r
+               <col def="S255">Condition</col>\r
+               <col def="I2">Sequence</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="I4">ISAttributes</col>\r
+               <row><td>AppSearch</td><td/><td>400</td><td>AppSearch</td><td/></row>\r
+               <row><td>CCPSearch</td><td>CCP_TEST</td><td>500</td><td>CCPSearch</td><td/></row>\r
+               <row><td>CostFinalize</td><td/><td>1000</td><td>CostFinalize</td><td/></row>\r
+               <row><td>CostInitialize</td><td/><td>800</td><td>CostInitialize</td><td/></row>\r
+               <row><td>ExecuteAction</td><td/><td>1300</td><td>ExecuteAction</td><td/></row>\r
+               <row><td>FileCost</td><td/><td>955</td><td>FileCost</td><td/></row>\r
+               <row><td>FindRelatedProducts</td><td/><td>430</td><td>FindRelatedProducts</td><td/></row>\r
+               <row><td>ISPreventDowngrade</td><td>ISFOUNDNEWERPRODUCTVERSION</td><td>450</td><td>ISPreventDowngrade</td><td/></row>\r
+               <row><td>ISSetupFilesCleanup</td><td/><td>1301</td><td/><td/></row>\r
+               <row><td>ISSetupFilesExtract</td><td/><td>3</td><td/><td/></row>\r
+               <row><td>ISVerifyScriptingRuntime</td><td>NOT AFTERREBOOT AND NOT ISSETUPDRIVEN</td><td>1</td><td>ISVerifyScriptingRuntime</td><td/></row>\r
+               <row><td>IsolateComponents</td><td/><td>950</td><td>IsolateComponents</td><td/></row>\r
+               <row><td>LaunchConditions</td><td>Not Installed</td><td>410</td><td>LaunchConditions</td><td/></row>\r
+               <row><td>MigrateFeatureStates</td><td/><td>1200</td><td>MigrateFeatureStates</td><td/></row>\r
+               <row><td>RMCCPSearch</td><td>Not CCP_SUCCESS And CCP_TEST</td><td>600</td><td>RMCCPSearch</td><td/></row>\r
+               <row><td>ResolveSource</td><td>Not Installed</td><td>990</td><td>ResolveSource</td><td/></row>\r
+               <row><td>SetAllUsersProfileNT</td><td>VersionNT = 400</td><td>970</td><td/><td/></row>\r
+               <row><td>ValidateProductID</td><td/><td>700</td><td>ValidateProductID</td><td/></row>\r
+               <row><td>setAllUsersProfile2K</td><td>VersionNT &gt;= 500</td><td>980</td><td/><td/></row>\r
+               <row><td>setUserProfileNT</td><td>VersionNT</td><td>960</td><td/><td/></row>\r
+       </table>\r
+\r
+       <table name="IsolatedComponent">\r
+               <col key="yes" def="s72">Component_Shared</col>\r
+               <col key="yes" def="s72">Component_Application</col>\r
+       </table>\r
+\r
+       <table name="LaunchCondition">\r
+               <col key="yes" def="s255">Condition</col>\r
+               <col def="l255">Description</col>\r
+       </table>\r
+\r
+       <table name="ListBox">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col key="yes" def="i2">Order</col>\r
+               <col def="s64">Value</col>\r
+               <col def="L64">Text</col>\r
+       </table>\r
+\r
+       <table name="ListView">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col key="yes" def="i2">Order</col>\r
+               <col def="s64">Value</col>\r
+               <col def="L64">Text</col>\r
+               <col def="S72">Binary_</col>\r
+       </table>\r
+\r
+       <table name="LockPermissions">\r
+               <col key="yes" def="s72">LockObject</col>\r
+               <col key="yes" def="s32">Table</col>\r
+               <col key="yes" def="S255">Domain</col>\r
+               <col key="yes" def="s255">User</col>\r
+               <col def="I4">Permission</col>\r
+       </table>\r
+\r
+       <table name="MIME">\r
+               <col key="yes" def="s64">ContentType</col>\r
+               <col def="s255">Extension_</col>\r
+               <col def="S38">CLSID</col>\r
+       </table>\r
+\r
+       <table name="Media">\r
+               <col key="yes" def="i2">DiskId</col>\r
+               <col def="i2">LastSequence</col>\r
+               <col def="L64">DiskPrompt</col>\r
+               <col def="S255">Cabinet</col>\r
+               <col def="S32">VolumeLabel</col>\r
+               <col def="S32">Source</col>\r
+       </table>\r
+\r
+       <table name="MoveFile">\r
+               <col key="yes" def="s72">FileKey</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="L255">SourceName</col>\r
+               <col def="L255">DestName</col>\r
+               <col def="S72">SourceFolder</col>\r
+               <col def="s72">DestFolder</col>\r
+               <col def="i2">Options</col>\r
+       </table>\r
+\r
+       <table name="MsiAssembly">\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col def="s38">Feature_</col>\r
+               <col def="S72">File_Manifest</col>\r
+               <col def="S72">File_Application</col>\r
+               <col def="I2">Attributes</col>\r
+       </table>\r
+\r
+       <table name="MsiAssemblyName">\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col key="yes" def="s255">Name</col>\r
+               <col def="s255">Value</col>\r
+       </table>\r
+\r
+       <table name="MsiDigitalCertificate">\r
+               <col key="yes" def="s72">DigitalCertificate</col>\r
+               <col def="v0">CertData</col>\r
+       </table>\r
+\r
+       <table name="MsiDigitalSignature">\r
+               <col key="yes" def="s32">Table</col>\r
+               <col key="yes" def="s72">SignObject</col>\r
+               <col def="s72">DigitalCertificate_</col>\r
+               <col def="V0">Hash</col>\r
+       </table>\r
+\r
+       <table name="MsiDriverPackages">\r
+               <col key="yes" def="s72">Component</col>\r
+               <col def="i4">Flags</col>\r
+               <col def="I4">Sequence</col>\r
+               <col def="S0">ReferenceComponents</col>\r
+       </table>\r
+\r
+       <table name="MsiEmbeddedChainer">\r
+               <col key="yes" def="s72">MsiEmbeddedChainer</col>\r
+               <col def="S255">Condition</col>\r
+               <col def="S255">CommandLine</col>\r
+               <col def="s72">Source</col>\r
+               <col def="I4">Type</col>\r
+       </table>\r
+\r
+       <table name="MsiEmbeddedUI">\r
+               <col key="yes" def="s72">MsiEmbeddedUI</col>\r
+               <col def="s255">FileName</col>\r
+               <col def="i2">Attributes</col>\r
+               <col def="I4">MessageFilter</col>\r
+               <col def="V0">Data</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+       </table>\r
+\r
+       <table name="MsiFileHash">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col def="i2">Options</col>\r
+               <col def="i4">HashPart1</col>\r
+               <col def="i4">HashPart2</col>\r
+               <col def="i4">HashPart3</col>\r
+               <col def="i4">HashPart4</col>\r
+       </table>\r
+\r
+       <table name="MsiLockPermissionsEx">\r
+               <col key="yes" def="s72">MsiLockPermissionsEx</col>\r
+               <col def="s72">LockObject</col>\r
+               <col def="s32">Table</col>\r
+               <col def="s0">SDDLText</col>\r
+               <col def="S255">Condition</col>\r
+       </table>\r
+\r
+       <table name="MsiPackageCertificate">\r
+               <col key="yes" def="s72">PackageCertificate</col>\r
+               <col def="s72">DigitalCertificate_</col>\r
+       </table>\r
+\r
+       <table name="MsiPatchCertificate">\r
+               <col key="yes" def="s72">PatchCertificate</col>\r
+               <col def="s72">DigitalCertificate_</col>\r
+       </table>\r
+\r
+       <table name="MsiPatchMetadata">\r
+               <col key="yes" def="s72">PatchConfiguration_</col>\r
+               <col key="yes" def="S72">Company</col>\r
+               <col key="yes" def="s72">Property</col>\r
+               <col def="S0">Value</col>\r
+       </table>\r
+\r
+       <table name="MsiPatchOldAssemblyFile">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col key="yes" def="S72">Assembly_</col>\r
+       </table>\r
+\r
+       <table name="MsiPatchOldAssemblyName">\r
+               <col key="yes" def="s72">Assembly</col>\r
+               <col key="yes" def="s255">Name</col>\r
+               <col def="S255">Value</col>\r
+       </table>\r
+\r
+       <table name="MsiPatchSequence">\r
+               <col key="yes" def="s72">PatchConfiguration_</col>\r
+               <col key="yes" def="s0">PatchFamily</col>\r
+               <col key="yes" def="S0">Target</col>\r
+               <col def="s0">Sequence</col>\r
+               <col def="i2">Supersede</col>\r
+       </table>\r
+\r
+       <table name="MsiServiceConfig">\r
+               <col key="yes" def="s72">MsiServiceConfig</col>\r
+               <col def="s255">Name</col>\r
+               <col def="i2">Event</col>\r
+               <col def="i4">ConfigType</col>\r
+               <col def="S0">Argument</col>\r
+               <col def="s72">Component_</col>\r
+       </table>\r
+\r
+       <table name="MsiServiceConfigFailureActions">\r
+               <col key="yes" def="s72">MsiServiceConfigFailureActions</col>\r
+               <col def="s255">Name</col>\r
+               <col def="i2">Event</col>\r
+               <col def="I4">ResetPeriod</col>\r
+               <col def="L255">RebootMessage</col>\r
+               <col def="L255">Command</col>\r
+               <col def="S0">Actions</col>\r
+               <col def="S0">DelayActions</col>\r
+               <col def="s72">Component_</col>\r
+       </table>\r
+\r
+       <table name="MsiShortcutProperty">\r
+               <col key="yes" def="s72">MsiShortcutProperty</col>\r
+               <col def="s72">Shortcut_</col>\r
+               <col def="s0">PropertyKey</col>\r
+               <col def="s0">PropVariantValue</col>\r
+       </table>\r
+\r
+       <table name="ODBCAttribute">\r
+               <col key="yes" def="s72">Driver_</col>\r
+               <col key="yes" def="s40">Attribute</col>\r
+               <col def="S255">Value</col>\r
+       </table>\r
+\r
+       <table name="ODBCDataSource">\r
+               <col key="yes" def="s72">DataSource</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="s255">Description</col>\r
+               <col def="s255">DriverDescription</col>\r
+               <col def="i2">Registration</col>\r
+       </table>\r
+\r
+       <table name="ODBCDriver">\r
+               <col key="yes" def="s72">Driver</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="s255">Description</col>\r
+               <col def="s72">File_</col>\r
+               <col def="S72">File_Setup</col>\r
+       </table>\r
+\r
+       <table name="ODBCSourceAttribute">\r
+               <col key="yes" def="s72">DataSource_</col>\r
+               <col key="yes" def="s32">Attribute</col>\r
+               <col def="S255">Value</col>\r
+       </table>\r
+\r
+       <table name="ODBCTranslator">\r
+               <col key="yes" def="s72">Translator</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="s255">Description</col>\r
+               <col def="s72">File_</col>\r
+               <col def="S72">File_Setup</col>\r
+       </table>\r
+\r
+       <table name="Patch">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col key="yes" def="i2">Sequence</col>\r
+               <col def="i4">PatchSize</col>\r
+               <col def="i2">Attributes</col>\r
+               <col def="V0">Header</col>\r
+               <col def="S38">StreamRef_</col>\r
+               <col def="S255">ISBuildSourcePath</col>\r
+       </table>\r
+\r
+       <table name="PatchPackage">\r
+               <col key="yes" def="s38">PatchId</col>\r
+               <col def="i2">Media_</col>\r
+       </table>\r
+\r
+       <table name="ProgId">\r
+               <col key="yes" def="s255">ProgId</col>\r
+               <col def="S255">ProgId_Parent</col>\r
+               <col def="S38">Class_</col>\r
+               <col def="L255">Description</col>\r
+               <col def="S72">Icon_</col>\r
+               <col def="I2">IconIndex</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="Property">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col def="L0">Value</col>\r
+               <col def="S255">ISComments</col>\r
+               <row><td>ALLUSERS</td><td>1</td><td/></row>\r
+               <row><td>ARPNOMODIFY</td><td>1</td><td/></row>\r
+               <row><td>ARPPRODUCTICON</td><td>ARPPRODUCTICON.exe</td><td/></row>\r
+               <row><td>ARPURLINFOABOUT</td><td>##ID_STRING1##</td><td/></row>\r
+               <row><td>DWUSINTERVAL</td><td>30</td><td/></row>\r
+               <row><td>DWUSLINK</td><td>CEEB009F49DCB088C9AC008F3E0B978F99BBF08FFE6CB048CEBCE0B8993CF098DEFBC7C8BEAC</td><td/></row>\r
+               <row><td>DefaultUIFont</td><td>Tahoma8</td><td/></row>\r
+               <row><td>DiskPrompt</td><td>[1]</td><td/></row>\r
+               <row><td>ISENABLEDWUSFINISHDIALOG</td><td/><td/></row>\r
+               <row><td>ISVROOT_PORT_NO</td><td>0</td><td/></row>\r
+               <row><td>IS_COMPLUS_PROGRESSTEXT_COST</td><td>##IDS_COMPLUS_PROGRESSTEXT_COST##</td><td/></row>\r
+               <row><td>IS_COMPLUS_PROGRESSTEXT_INSTALL</td><td>##IDS_COMPLUS_PROGRESSTEXT_INSTALL##</td><td/></row>\r
+               <row><td>IS_COMPLUS_PROGRESSTEXT_UNINSTALL</td><td>##IDS_COMPLUS_PROGRESSTEXT_UNINSTALL##</td><td/></row>\r
+               <row><td>IS_PREVENT_DOWNGRADE_EXIT</td><td>##IDS_PREVENT_DOWNGRADE_EXIT##</td><td/></row>\r
+               <row><td>IS_PROGMSG_TEXTFILECHANGS_REPLACE</td><td>##IDS_PROGMSG_TEXTFILECHANGS_REPLACE##</td><td/></row>\r
+               <row><td>IS_PROGMSG_XML_COSTING</td><td>##IDS_PROGMSG_XML_COSTING##</td><td/></row>\r
+               <row><td>IS_PROGMSG_XML_CREATE_FILE</td><td>##IDS_PROGMSG_XML_CREATE_FILE##</td><td/></row>\r
+               <row><td>IS_PROGMSG_XML_FILES</td><td>##IDS_PROGMSG_XML_FILES##</td><td/></row>\r
+               <row><td>IS_PROGMSG_XML_REMOVE_FILE</td><td>##IDS_PROGMSG_XML_REMOVE_FILE##</td><td/></row>\r
+               <row><td>IS_PROGMSG_XML_ROLLBACK_FILES</td><td>##IDS_PROGMSG_XML_ROLLBACK_FILES##</td><td/></row>\r
+               <row><td>IS_PROGMSG_XML_UPDATE_FILE</td><td>##IDS_PROGMSG_XML_UPDATE_FILE##</td><td/></row>\r
+               <row><td>IS_SQLSERVER_AUTHENTICATION</td><td>0</td><td/></row>\r
+               <row><td>IS_SQLSERVER_DATABASE</td><td/><td/></row>\r
+               <row><td>IS_SQLSERVER_PASSWORD</td><td/><td/></row>\r
+               <row><td>IS_SQLSERVER_SERVER</td><td/><td/></row>\r
+               <row><td>IS_SQLSERVER_USERNAME</td><td>sa</td><td/></row>\r
+               <row><td>Manufacturer</td><td>##COMPANY_NAME##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_CREATEAPPPOOL</td><td>##IDS_PROGMSG_IIS_CREATEAPPPOOL##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_CREATEAPPPOOLS</td><td>##IDS_PROGMSG_IIS_CREATEAPPPOOLS##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_CREATEVROOT</td><td>##IDS_PROGMSG_IIS_CREATEVROOT##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_CREATEVROOTS</td><td>##IDS_PROGMSG_IIS_CREATEVROOTS##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_CREATEWEBSERVICEEXTENSION</td><td>##IDS_PROGMSG_IIS_CREATEWEBSERVICEEXTENSION##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_CREATEWEBSERVICEEXTENSIONS</td><td>##IDS_PROGMSG_IIS_CREATEWEBSERVICEEXTENSIONS##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_CREATEWEBSITE</td><td>##IDS_PROGMSG_IIS_CREATEWEBSITE##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_CREATEWEBSITES</td><td>##IDS_PROGMSG_IIS_CREATEWEBSITES##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_EXTRACT</td><td>##IDS_PROGMSG_IIS_EXTRACT##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_EXTRACTDONE</td><td>##IDS_PROGMSG_IIS_EXTRACTDONE##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_EXTRACTDONEz</td><td>##IDS_PROGMSG_IIS_EXTRACTDONE##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_EXTRACTzDONE</td><td>##IDS_PROGMSG_IIS_EXTRACTDONE##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_REMOVEAPPPOOL</td><td>##IDS_PROGMSG_IIS_REMOVEAPPPOOL##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_REMOVEAPPPOOLS</td><td>##IDS_PROGMSG_IIS_REMOVEAPPPOOLS##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_REMOVESITE</td><td>##IDS_PROGMSG_IIS_REMOVESITE##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_REMOVEVROOT</td><td>##IDS_PROGMSG_IIS_REMOVEVROOT##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_REMOVEVROOTS</td><td>##IDS_PROGMSG_IIS_REMOVEVROOTS##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_REMOVEWEBSERVICEEXTENSION</td><td>##IDS_PROGMSG_IIS_REMOVEWEBSERVICEEXTENSION##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_REMOVEWEBSERVICEEXTENSIONS</td><td>##IDS_PROGMSG_IIS_REMOVEWEBSERVICEEXTENSIONS##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_REMOVEWEBSITES</td><td>##IDS_PROGMSG_IIS_REMOVEWEBSITES##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_ROLLBACKAPPPOOLS</td><td>##IDS_PROGMSG_IIS_ROLLBACKAPPPOOLS##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_ROLLBACKVROOTS</td><td>##IDS_PROGMSG_IIS_ROLLBACKVROOTS##</td><td/></row>\r
+               <row><td>PROGMSG_IIS_ROLLBACKWEBSERVICEEXTENSIONS</td><td>##IDS_PROGMSG_IIS_ROLLBACKWEBSERVICEEXTENSIONS##</td><td/></row>\r
+               <row><td>ProductCode</td><td>{70ECF476-1489-4173-8EBD-503B4085A023}</td><td/></row>\r
+               <row><td>ProductName</td><td>Simantics Sysdyn</td><td/></row>\r
+               <row><td>ProductVersion</td><td>1.7.0.19</td><td/></row>\r
+               <row><td>REBOOT</td><td>Suppress</td><td/></row>\r
+               <row><td>STANDARD_USE_SETUPEXE</td><td>##IDS_STANDARD_USE_SETUPEXE##</td><td/></row>\r
+               <row><td>SecureCustomProperties</td><td>ISALWAYSINSTALLELEVATED;ISSETUPDRIVEN;ARPSYSTEMCOMPONENT;ARPNOMODIFY;ARPNOREMOVE;INSTALLDIR;ISFOUNDNEWERPRODUCTVERSION;USERNAME;COMPANYNAME;ISX_SERIALNUM;IS_SQLSERVER_LIST;IS_SQLSERVER_DATABASE;IS_SQLSERVER_AUTHENTICATION;IS_SQLSERVER_USERNAME;IS_SQLSERVER_SERVER;IS_SQLSERVER_PASSWORD;IS_NET_API_LOGON_USERNAME;IS_NET_API_LOGON_PASSWORD;IS_NEW_USER_CONFIRM_TEXT;IS_NEW_USER_SERVER_TEXT;IS_NEW_USER_GROUP_TEXT;IS_NEW_USER_NAME_TEXT;IS_NET_API_NEW_USER_PASSWORD;IS_NET_API_NEW_USER_NAME;IS_NET_API_NEW_USER_CONFIRM;IS_NEW_USER_PASSWORD_TEXT;IS_NET_API_NEW_USER_SERVER;IS_NET_API_NEW_USER_GROUP;IS_NET_API_GROUP_LIST;IS_NET_API_SERVER_LIST;IS_NET_API_SERVER_NEW_USER_LIST;IS_NET_API_USER_LIST;IS_NET_API_LOGON_DOMAIN_TOKEN;IS_NET_API_LOGON_USERNAME_TOKEN;SUPPORTDIR;SYSDYN64</td><td/></row>\r
+               <row><td>UpgradeCode</td><td>{28D93A0D-FFD5-46CF-B959-1C4D7588F3F9}</td><td/></row>\r
+       </table>\r
+\r
+       <table name="PublishComponent">\r
+               <col key="yes" def="s38">ComponentId</col>\r
+               <col key="yes" def="s255">Qualifier</col>\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col def="L0">AppData</col>\r
+               <col def="s38">Feature_</col>\r
+       </table>\r
+\r
+       <table name="RadioButton">\r
+               <col key="yes" def="s72">Property</col>\r
+               <col key="yes" def="i2">Order</col>\r
+               <col def="s64">Value</col>\r
+               <col def="i2">X</col>\r
+               <col def="i2">Y</col>\r
+               <col def="i2">Width</col>\r
+               <col def="i2">Height</col>\r
+               <col def="L64">Text</col>\r
+               <col def="L50">Help</col>\r
+               <col def="I4">ISControlId</col>\r
+       </table>\r
+\r
+       <table name="RegLocator">\r
+               <col key="yes" def="s72">Signature_</col>\r
+               <col def="i2">Root</col>\r
+               <col def="s255">Key</col>\r
+               <col def="S255">Name</col>\r
+               <col def="I2">Type</col>\r
+       </table>\r
+\r
+       <table name="Registry">\r
+               <col key="yes" def="s72">Registry</col>\r
+               <col def="i2">Root</col>\r
+               <col def="s255">Key</col>\r
+               <col def="S255">Name</col>\r
+               <col def="S0">Value</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="RemoveFile">\r
+               <col key="yes" def="s72">FileKey</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="L255">FileName</col>\r
+               <col def="s72">DirProperty</col>\r
+               <col def="i2">InstallMode</col>\r
+       </table>\r
+\r
+       <table name="RemoveIniFile">\r
+               <col key="yes" def="s72">RemoveIniFile</col>\r
+               <col def="l255">FileName</col>\r
+               <col def="S72">DirProperty</col>\r
+               <col def="l96">Section</col>\r
+               <col def="l128">Key</col>\r
+               <col def="L255">Value</col>\r
+               <col def="i2">Action</col>\r
+               <col def="s72">Component_</col>\r
+       </table>\r
+\r
+       <table name="RemoveRegistry">\r
+               <col key="yes" def="s72">RemoveRegistry</col>\r
+               <col def="i2">Root</col>\r
+               <col def="l255">Key</col>\r
+               <col def="L255">Name</col>\r
+               <col def="s72">Component_</col>\r
+       </table>\r
+\r
+       <table name="ReserveCost">\r
+               <col key="yes" def="s72">ReserveKey</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="S72">ReserveFolder</col>\r
+               <col def="i4">ReserveLocal</col>\r
+               <col def="i4">ReserveSource</col>\r
+       </table>\r
+\r
+       <table name="SFPCatalog">\r
+               <col key="yes" def="s255">SFPCatalog</col>\r
+               <col def="V0">Catalog</col>\r
+               <col def="S0">Dependency</col>\r
+       </table>\r
+\r
+       <table name="SelfReg">\r
+               <col key="yes" def="s72">File_</col>\r
+               <col def="I2">Cost</col>\r
+       </table>\r
+\r
+       <table name="ServiceControl">\r
+               <col key="yes" def="s72">ServiceControl</col>\r
+               <col def="s255">Name</col>\r
+               <col def="i2">Event</col>\r
+               <col def="S255">Arguments</col>\r
+               <col def="I2">Wait</col>\r
+               <col def="s72">Component_</col>\r
+       </table>\r
+\r
+       <table name="ServiceInstall">\r
+               <col key="yes" def="s72">ServiceInstall</col>\r
+               <col def="s255">Name</col>\r
+               <col def="L255">DisplayName</col>\r
+               <col def="i4">ServiceType</col>\r
+               <col def="i4">StartType</col>\r
+               <col def="i4">ErrorControl</col>\r
+               <col def="S255">LoadOrderGroup</col>\r
+               <col def="S255">Dependencies</col>\r
+               <col def="S255">StartName</col>\r
+               <col def="S255">Password</col>\r
+               <col def="S255">Arguments</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="L255">Description</col>\r
+       </table>\r
+\r
+       <table name="Shortcut">\r
+               <col key="yes" def="s72">Shortcut</col>\r
+               <col def="s72">Directory_</col>\r
+               <col def="l128">Name</col>\r
+               <col def="s72">Component_</col>\r
+               <col def="s255">Target</col>\r
+               <col def="S255">Arguments</col>\r
+               <col def="L255">Description</col>\r
+               <col def="I2">Hotkey</col>\r
+               <col def="S72">Icon_</col>\r
+               <col def="I2">IconIndex</col>\r
+               <col def="I2">ShowCmd</col>\r
+               <col def="S72">WkDir</col>\r
+               <col def="S255">DisplayResourceDLL</col>\r
+               <col def="I2">DisplayResourceId</col>\r
+               <col def="S255">DescriptionResourceDLL</col>\r
+               <col def="I2">DescriptionResourceId</col>\r
+               <col def="S255">ISComments</col>\r
+               <col def="S255">ISShortcutName</col>\r
+               <col def="I4">ISAttributes</col>\r
+       </table>\r
+\r
+       <table name="Signature">\r
+               <col key="yes" def="s72">Signature</col>\r
+               <col def="s255">FileName</col>\r
+               <col def="S20">MinVersion</col>\r
+               <col def="S20">MaxVersion</col>\r
+               <col def="I4">MinSize</col>\r
+               <col def="I4">MaxSize</col>\r
+               <col def="I4">MinDate</col>\r
+               <col def="I4">MaxDate</col>\r
+               <col def="S255">Languages</col>\r
+       </table>\r
+\r
+       <table name="TextStyle">\r
+               <col key="yes" def="s72">TextStyle</col>\r
+               <col def="s32">FaceName</col>\r
+               <col def="i2">Size</col>\r
+               <col def="I4">Color</col>\r
+               <col def="I2">StyleBits</col>\r
+               <row><td>Arial8</td><td>Arial</td><td>8</td><td/><td/></row>\r
+               <row><td>Arial9</td><td>Arial</td><td>9</td><td/><td/></row>\r
+               <row><td>CourierNew8</td><td>Courier New</td><td>8</td><td/><td/></row>\r
+               <row><td>CourierNew9</td><td>Courier New</td><td>9</td><td/><td/></row>\r
+               <row><td>MSGothic9</td><td>MS Gothic</td><td>9</td><td/><td/></row>\r
+               <row><td>MSSansBold8</td><td>Tahoma</td><td>8</td><td/><td>1</td></row>\r
+               <row><td>MSSansSerif8</td><td>MS Sans Serif</td><td>8</td><td/><td/></row>\r
+               <row><td>MSSansSerif9</td><td>MS Sans Serif</td><td>9</td><td/><td/></row>\r
+               <row><td>Tahoma10</td><td>Tahoma</td><td>10</td><td/><td/></row>\r
+               <row><td>Tahoma8</td><td>Tahoma</td><td>8</td><td/><td/></row>\r
+               <row><td>Tahoma9</td><td>Tahoma</td><td>9</td><td/><td/></row>\r
+               <row><td>TahomaBold10</td><td>Tahoma</td><td>10</td><td/><td>1</td></row>\r
+               <row><td>TahomaBold8</td><td>Tahoma</td><td>8</td><td/><td>1</td></row>\r
+               <row><td>Times8</td><td>Times New Roman</td><td>8</td><td/><td/></row>\r
+               <row><td>Times9</td><td>Times New Roman</td><td>9</td><td/><td/></row>\r
+               <row><td>TimesItalic12</td><td>Times New Roman</td><td>12</td><td/><td>2</td></row>\r
+       </table>\r
+\r
+       <table name="TypeLib">\r
+               <col key="yes" def="s38">LibID</col>\r
+               <col key="yes" def="i2">Language</col>\r
+               <col key="yes" def="s72">Component_</col>\r
+               <col def="I4">Version</col>\r
+               <col def="L128">Description</col>\r
+               <col def="S72">Directory_</col>\r
+               <col def="s38">Feature_</col>\r
+               <col def="I4">Cost</col>\r
+       </table>\r
+\r
+       <table name="UIText">\r
+               <col key="yes" def="s72">Key</col>\r
+               <col def="L255">Text</col>\r
+               <row><td>AbsentPath</td><td/></row>\r
+               <row><td>GB</td><td>##IDS_UITEXT_GB##</td></row>\r
+               <row><td>KB</td><td>##IDS_UITEXT_KB##</td></row>\r
+               <row><td>MB</td><td>##IDS_UITEXT_MB##</td></row>\r
+               <row><td>MenuAbsent</td><td>##IDS_UITEXT_FeatureNotAvailable##</td></row>\r
+               <row><td>MenuAdvertise</td><td>##IDS_UITEXT_FeatureInstalledWhenRequired2##</td></row>\r
+               <row><td>MenuAllCD</td><td>##IDS_UITEXT_FeatureInstalledCD##</td></row>\r
+               <row><td>MenuAllLocal</td><td>##IDS_UITEXT_FeatureInstalledLocal##</td></row>\r
+               <row><td>MenuAllNetwork</td><td>##IDS_UITEXT_FeatureInstalledNetwork##</td></row>\r
+               <row><td>MenuCD</td><td>##IDS_UITEXT_FeatureInstalledCD2##</td></row>\r
+               <row><td>MenuLocal</td><td>##IDS_UITEXT_FeatureInstalledLocal2##</td></row>\r
+               <row><td>MenuNetwork</td><td>##IDS_UITEXT_FeatureInstalledNetwork2##</td></row>\r
+               <row><td>NewFolder</td><td>##IDS_UITEXT_Folder##</td></row>\r
+               <row><td>SelAbsentAbsent</td><td>##IDS_UITEXT_GB##</td></row>\r
+               <row><td>SelAbsentAdvertise</td><td>##IDS_UITEXT_FeatureInstalledWhenRequired##</td></row>\r
+               <row><td>SelAbsentCD</td><td>##IDS_UITEXT_FeatureOnCD##</td></row>\r
+               <row><td>SelAbsentLocal</td><td>##IDS_UITEXT_FeatureLocal##</td></row>\r
+               <row><td>SelAbsentNetwork</td><td>##IDS_UITEXT_FeatureNetwork##</td></row>\r
+               <row><td>SelAdvertiseAbsent</td><td>##IDS_UITEXT_FeatureUnavailable##</td></row>\r
+               <row><td>SelAdvertiseAdvertise</td><td>##IDS_UITEXT_FeatureInstalledRequired##</td></row>\r
+               <row><td>SelAdvertiseCD</td><td>##IDS_UITEXT_FeatureOnCD2##</td></row>\r
+               <row><td>SelAdvertiseLocal</td><td>##IDS_UITEXT_FeatureLocal2##</td></row>\r
+               <row><td>SelAdvertiseNetwork</td><td>##IDS_UITEXT_FeatureNetwork2##</td></row>\r
+               <row><td>SelCDAbsent</td><td>##IDS_UITEXT_FeatureWillBeUninstalled##</td></row>\r
+               <row><td>SelCDAdvertise</td><td>##IDS_UITEXT_FeatureWasCD##</td></row>\r
+               <row><td>SelCDCD</td><td>##IDS_UITEXT_FeatureRunFromCD##</td></row>\r
+               <row><td>SelCDLocal</td><td>##IDS_UITEXT_FeatureWasCDLocal##</td></row>\r
+               <row><td>SelChildCostNeg</td><td>##IDS_UITEXT_FeatureFreeSpace##</td></row>\r
+               <row><td>SelChildCostPos</td><td>##IDS_UITEXT_FeatureRequiredSpace##</td></row>\r
+               <row><td>SelCostPending</td><td>##IDS_UITEXT_CompilingFeaturesCost##</td></row>\r
+               <row><td>SelLocalAbsent</td><td>##IDS_UITEXT_FeatureCompletelyRemoved##</td></row>\r
+               <row><td>SelLocalAdvertise</td><td>##IDS_UITEXT_FeatureRemovedUnlessRequired##</td></row>\r
+               <row><td>SelLocalCD</td><td>##IDS_UITEXT_FeatureRemovedCD##</td></row>\r
+               <row><td>SelLocalLocal</td><td>##IDS_UITEXT_FeatureRemainLocal##</td></row>\r
+               <row><td>SelLocalNetwork</td><td>##IDS_UITEXT_FeatureRemoveNetwork##</td></row>\r
+               <row><td>SelNetworkAbsent</td><td>##IDS_UITEXT_FeatureUninstallNoNetwork##</td></row>\r
+               <row><td>SelNetworkAdvertise</td><td>##IDS_UITEXT_FeatureWasOnNetworkInstalled##</td></row>\r
+               <row><td>SelNetworkLocal</td><td>##IDS_UITEXT_FeatureWasOnNetworkLocal##</td></row>\r
+               <row><td>SelNetworkNetwork</td><td>##IDS_UITEXT_FeatureContinueNetwork##</td></row>\r
+               <row><td>SelParentCostNegNeg</td><td>##IDS_UITEXT_FeatureSpaceFree##</td></row>\r
+               <row><td>SelParentCostNegPos</td><td>##IDS_UITEXT_FeatureSpaceFree2##</td></row>\r
+               <row><td>SelParentCostPosNeg</td><td>##IDS_UITEXT_FeatureSpaceFree3##</td></row>\r
+               <row><td>SelParentCostPosPos</td><td>##IDS_UITEXT_FeatureSpaceFree4##</td></row>\r
+               <row><td>TimeRemaining</td><td>##IDS_UITEXT_TimeRemaining##</td></row>\r
+               <row><td>VolumeCostAvailable</td><td>##IDS_UITEXT_Available##</td></row>\r
+               <row><td>VolumeCostDifference</td><td>##IDS_UITEXT_Differences##</td></row>\r
+               <row><td>VolumeCostRequired</td><td>##IDS_UITEXT_Required##</td></row>\r
+               <row><td>VolumeCostSize</td><td>##IDS_UITEXT_DiskSize##</td></row>\r
+               <row><td>VolumeCostVolume</td><td>##IDS_UITEXT_Volume##</td></row>\r
+               <row><td>bytes</td><td>##IDS_UITEXT_Bytes##</td></row>\r
+       </table>\r
+\r
+       <table name="Upgrade">\r
+               <col key="yes" def="s38">UpgradeCode</col>\r
+               <col key="yes" def="S20">VersionMin</col>\r
+               <col key="yes" def="S20">VersionMax</col>\r
+               <col key="yes" def="S255">Language</col>\r
+               <col key="yes" def="i4">Attributes</col>\r
+               <col def="S255">Remove</col>\r
+               <col def="s72">ActionProperty</col>\r
+               <col def="S72">ISDisplayName</col>\r
+               <row><td>{00000000-0000-0000-0000-000000000000}</td><td>***ALL_VERSIONS***</td><td></td><td></td><td>2</td><td/><td>ISFOUNDNEWERPRODUCTVERSION</td><td>ISPreventDowngrade</td></row>\r
+       </table>\r
+\r
+       <table name="Verb">\r
+               <col key="yes" def="s255">Extension_</col>\r
+               <col key="yes" def="s32">Verb</col>\r
+               <col def="I2">Sequence</col>\r
+               <col def="L255">Command</col>\r
+               <col def="L255">Argument</col>\r
+       </table>\r
+\r
+       <table name="_Validation">\r
+               <col key="yes" def="s32">Table</col>\r
+               <col key="yes" def="s32">Column</col>\r
+               <col def="s4">Nullable</col>\r
+               <col def="I4">MinValue</col>\r
+               <col def="I4">MaxValue</col>\r
+               <col def="S255">KeyTable</col>\r
+               <col def="I2">KeyColumn</col>\r
+               <col def="S32">Category</col>\r
+               <col def="S255">Set</col>\r
+               <col def="S255">Description</col>\r
+               <row><td>ActionText</td><td>Action</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of action to be described.</td></row>\r
+               <row><td>ActionText</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Localized description displayed in progress dialog and log when action is executing.</td></row>\r
+               <row><td>ActionText</td><td>Template</td><td>Y</td><td/><td/><td/><td/><td>Template</td><td/><td>Optional localized format template used to format action data records for display during action execution.</td></row>\r
+               <row><td>AdminExecuteSequence</td><td>Action</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of action to invoke, either in the engine or the handler DLL.</td></row>\r
+               <row><td>AdminExecuteSequence</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.</td></row>\r
+               <row><td>AdminExecuteSequence</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store MM Custom Action Types</td></row>\r
+               <row><td>AdminExecuteSequence</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments on this Sequence.</td></row>\r
+               <row><td>AdminExecuteSequence</td><td>Sequence</td><td>Y</td><td>-4</td><td>32767</td><td/><td/><td/><td/><td>Number that determines the sort order in which the actions are to be executed.  Leave blank to suppress action.</td></row>\r
+               <row><td>AdminUISequence</td><td>Action</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of action to invoke, either in the engine or the handler DLL.</td></row>\r
+               <row><td>AdminUISequence</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.</td></row>\r
+               <row><td>AdminUISequence</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store MM Custom Action Types</td></row>\r
+               <row><td>AdminUISequence</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments on this Sequence.</td></row>\r
+               <row><td>AdminUISequence</td><td>Sequence</td><td>Y</td><td>-4</td><td>32767</td><td/><td/><td/><td/><td>Number that determines the sort order in which the actions are to be executed.  Leave blank to suppress action.</td></row>\r
+               <row><td>AdvtExecuteSequence</td><td>Action</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of action to invoke, either in the engine or the handler DLL.</td></row>\r
+               <row><td>AdvtExecuteSequence</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.</td></row>\r
+               <row><td>AdvtExecuteSequence</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store MM Custom Action Types</td></row>\r
+               <row><td>AdvtExecuteSequence</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments on this Sequence.</td></row>\r
+               <row><td>AdvtExecuteSequence</td><td>Sequence</td><td>Y</td><td>-4</td><td>32767</td><td/><td/><td/><td/><td>Number that determines the sort order in which the actions are to be executed.  Leave blank to suppress action.</td></row>\r
+               <row><td>AdvtUISequence</td><td>Action</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of action to invoke, either in the engine or the handler DLL.</td></row>\r
+               <row><td>AdvtUISequence</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.</td></row>\r
+               <row><td>AdvtUISequence</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store MM Custom Action Types</td></row>\r
+               <row><td>AdvtUISequence</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments on this Sequence.</td></row>\r
+               <row><td>AdvtUISequence</td><td>Sequence</td><td>Y</td><td>-4</td><td>32767</td><td/><td/><td/><td/><td>Number that determines the sort order in which the actions are to be executed.  Leave blank to suppress action.</td></row>\r
+               <row><td>AppId</td><td>ActivateAtStorage</td><td>Y</td><td>0</td><td>1</td><td/><td/><td/><td/><td/></row>\r
+               <row><td>AppId</td><td>AppId</td><td>N</td><td/><td/><td/><td/><td>Guid</td><td/><td/></row>\r
+               <row><td>AppId</td><td>DllSurrogate</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>AppId</td><td>LocalService</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>AppId</td><td>RemoteServerName</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td/></row>\r
+               <row><td>AppId</td><td>RunAsInteractiveUser</td><td>Y</td><td>0</td><td>1</td><td/><td/><td/><td/><td/></row>\r
+               <row><td>AppId</td><td>ServiceParameters</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>AppSearch</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The property associated with a Signature</td></row>\r
+               <row><td>AppSearch</td><td>Signature_</td><td>N</td><td/><td/><td>ISXmlLocator;Signature</td><td>1</td><td>Identifier</td><td/><td>The Signature_ represents a unique file signature and is also the foreign key in the Signature,  RegLocator, IniLocator, CompLocator and the DrLocator tables.</td></row>\r
+               <row><td>BBControl</td><td>Attributes</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>A 32-bit word that specifies the attribute flags to be applied to this control.</td></row>\r
+               <row><td>BBControl</td><td>BBControl</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of the control. This name must be unique within a billboard, but can repeat on different billboard.</td></row>\r
+               <row><td>BBControl</td><td>Billboard_</td><td>N</td><td/><td/><td>Billboard</td><td>1</td><td>Identifier</td><td/><td>External key to the Billboard table, name of the billboard.</td></row>\r
+               <row><td>BBControl</td><td>Height</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Height of the bounding rectangle of the control.</td></row>\r
+               <row><td>BBControl</td><td>Text</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>A string used to set the initial text contained within a control (if appropriate).</td></row>\r
+               <row><td>BBControl</td><td>Type</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The type of the control.</td></row>\r
+               <row><td>BBControl</td><td>Width</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Width of the bounding rectangle of the control.</td></row>\r
+               <row><td>BBControl</td><td>X</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Horizontal coordinate of the upper left corner of the bounding rectangle of the control.</td></row>\r
+               <row><td>BBControl</td><td>Y</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Vertical coordinate of the upper left corner of the bounding rectangle of the control.</td></row>\r
+               <row><td>Billboard</td><td>Action</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The name of an action. The billboard is displayed during the progress messages received from this action.</td></row>\r
+               <row><td>Billboard</td><td>Billboard</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of the billboard.</td></row>\r
+               <row><td>Billboard</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>An external key to the Feature Table. The billboard is shown only if this feature is being installed.</td></row>\r
+               <row><td>Billboard</td><td>Ordering</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>A positive integer. If there is more than one billboard corresponding to an action they will be shown in the order defined by this column.</td></row>\r
+               <row><td>Binary</td><td>Data</td><td>Y</td><td/><td/><td/><td/><td>Binary</td><td/><td>Binary stream. The binary icon data in PE (.DLL or .EXE) or icon (.ICO) format.</td></row>\r
+               <row><td>Binary</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path to the ICO or EXE file.</td></row>\r
+               <row><td>Binary</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Unique key identifying the binary data.</td></row>\r
+               <row><td>BindImage</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>The index into the File table. This must be an executable file.</td></row>\r
+               <row><td>BindImage</td><td>Path</td><td>Y</td><td/><td/><td/><td/><td>Paths</td><td/><td>A list of ;  delimited paths that represent the paths to be searched for the import DLLS. The list is usually a list of properties each enclosed within square brackets [] .</td></row>\r
+               <row><td>CCPSearch</td><td>Signature_</td><td>N</td><td/><td/><td>Signature</td><td>1</td><td>Identifier</td><td/><td>The Signature_ represents a unique file signature and is also the foreign key in the Signature,  RegLocator, IniLocator, CompLocator and the DrLocator tables.</td></row>\r
+               <row><td>CheckBox</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A named property to be tied to the item.</td></row>\r
+               <row><td>CheckBox</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The value string associated with the item.</td></row>\r
+               <row><td>Class</td><td>AppId_</td><td>Y</td><td/><td/><td>AppId</td><td>1</td><td>Guid</td><td/><td>Optional AppID containing DCOM information for associated application (string GUID).</td></row>\r
+               <row><td>Class</td><td>Argument</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>optional argument for LocalServers.</td></row>\r
+               <row><td>Class</td><td>Attributes</td><td>Y</td><td/><td>32767</td><td/><td/><td/><td/><td>Class registration attributes.</td></row>\r
+               <row><td>Class</td><td>CLSID</td><td>N</td><td/><td/><td/><td/><td>Guid</td><td/><td>The CLSID of an OLE factory.</td></row>\r
+               <row><td>Class</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.</td></row>\r
+               <row><td>Class</td><td>Context</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The numeric server context for this server. CLSCTX_xxxx</td></row>\r
+               <row><td>Class</td><td>DefInprocHandler</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td>1;2;3</td><td>Optional default inproc handler.  Only optionally provided if Context=CLSCTX_LOCAL_SERVER.  Typically "ole32.dll" or "mapi32.dll"</td></row>\r
+               <row><td>Class</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Localized description for the Class.</td></row>\r
+               <row><td>Class</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Feature Table, specifying the feature to validate or install in order for the CLSID factory to be operational.</td></row>\r
+               <row><td>Class</td><td>FileTypeMask</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Optional string containing information for the HKCRthis CLSID) key. If multiple patterns exist, they must be delimited by a semicolon, and numeric subkeys will be generated: 0,1,2...</td></row>\r
+               <row><td>Class</td><td>IconIndex</td><td>Y</td><td>-32767</td><td>32767</td><td/><td/><td/><td/><td>Optional icon index.</td></row>\r
+               <row><td>Class</td><td>Icon_</td><td>Y</td><td/><td/><td>Icon</td><td>1</td><td>Identifier</td><td/><td>Optional foreign key into the Icon Table, specifying the icon file associated with this CLSID. Will be written under the DefaultIcon key.</td></row>\r
+               <row><td>Class</td><td>ProgId_Default</td><td>Y</td><td/><td/><td>ProgId</td><td>1</td><td>Text</td><td/><td>Optional ProgId associated with this CLSID.</td></row>\r
+               <row><td>ComboBox</td><td>Order</td><td>N</td><td>1</td><td>32767</td><td/><td/><td/><td/><td>A positive integer used to determine the ordering of the items within one list.   The integers do not have to be consecutive.</td></row>\r
+               <row><td>ComboBox</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A named property to be tied to this item. All the items tied to the same property become part of the same combobox.</td></row>\r
+               <row><td>ComboBox</td><td>Text</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.</td></row>\r
+               <row><td>ComboBox</td><td>Value</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The value string associated with this item. Selecting the line will set the associated property to this value.</td></row>\r
+               <row><td>CompLocator</td><td>ComponentId</td><td>N</td><td/><td/><td/><td/><td>Guid</td><td/><td>A string GUID unique to this component, version, and language.</td></row>\r
+               <row><td>CompLocator</td><td>Signature_</td><td>N</td><td/><td/><td>Signature</td><td>1</td><td>Identifier</td><td/><td>The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table.</td></row>\r
+               <row><td>CompLocator</td><td>Type</td><td>Y</td><td>0</td><td>1</td><td/><td/><td/><td/><td>A boolean value that determines if the registry value is a filename or a directory location.</td></row>\r
+               <row><td>Complus</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing Component that controls the ComPlus component.</td></row>\r
+               <row><td>Complus</td><td>ExpType</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>ComPlus component attributes.</td></row>\r
+               <row><td>Component</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Remote execution option, one of irsEnum</td></row>\r
+               <row><td>Component</td><td>Component</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular component record.</td></row>\r
+               <row><td>Component</td><td>ComponentId</td><td>Y</td><td/><td/><td/><td/><td>Guid</td><td/><td>A string GUID unique to this component, version, and language.</td></row>\r
+               <row><td>Component</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>A conditional statement that will disable this component if the specified condition evaluates to the 'True' state. If a component is disabled, it will not be installed, regardless of the 'Action' state associated with the component.</td></row>\r
+               <row><td>Component</td><td>Directory_</td><td>N</td><td/><td/><td>Directory</td><td>1</td><td>Identifier</td><td/><td>Required key of a Directory table record. This is actually a property name whose value contains the actual path, set either by the AppSearch action or with the default setting obtained from the Directory table.</td></row>\r
+               <row><td>Component</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store Installshield custom properties of a component.</td></row>\r
+               <row><td>Component</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>User Comments.</td></row>\r
+               <row><td>Component</td><td>ISDotNetInstallerArgsCommit</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Arguments passed to the key file of the component if if implements the .NET Installer class</td></row>\r
+               <row><td>Component</td><td>ISDotNetInstallerArgsInstall</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Arguments passed to the key file of the component if if implements the .NET Installer class</td></row>\r
+               <row><td>Component</td><td>ISDotNetInstallerArgsRollback</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Arguments passed to the key file of the component if if implements the .NET Installer class</td></row>\r
+               <row><td>Component</td><td>ISDotNetInstallerArgsUninstall</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Arguments passed to the key file of the component if if implements the .NET Installer class</td></row>\r
+               <row><td>Component</td><td>ISRegFileToMergeAtBuild</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Path and File name of a .REG file to merge into the component at build time.</td></row>\r
+               <row><td>Component</td><td>ISScanAtBuildFile</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>File used by the Dot Net scanner to populate dependant assemblies' File_Application field.</td></row>\r
+               <row><td>Component</td><td>KeyPath</td><td>Y</td><td/><td/><td>File;ODBCDataSource;Registry</td><td>1</td><td>Identifier</td><td/><td>Either the primary key into the File table, Registry table, or ODBCDataSource table. This extract path is stored when the component is installed, and is used to detect the presence of the component and to return the path to it.</td></row>\r
+               <row><td>Condition</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>Expression evaluated to determine if Level in the Feature table is to change.</td></row>\r
+               <row><td>Condition</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Reference to a Feature entry in Feature table.</td></row>\r
+               <row><td>Condition</td><td>Level</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>New selection Level to set in Feature table if Condition evaluates to TRUE.</td></row>\r
+               <row><td>Control</td><td>Attributes</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>A 32-bit word that specifies the attribute flags to be applied to this control.</td></row>\r
+               <row><td>Control</td><td>Binary_</td><td>Y</td><td/><td/><td>Binary</td><td>1</td><td>Identifier</td><td/><td>External key to the Binary table.</td></row>\r
+               <row><td>Control</td><td>Control</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of the control. This name must be unique within a dialog, but can repeat on different dialogs.</td></row>\r
+               <row><td>Control</td><td>Control_Next</td><td>Y</td><td/><td/><td>Control</td><td>2</td><td>Identifier</td><td/><td>The name of an other control on the same dialog. This link defines the tab order of the controls. The links have to form one or more cycles!</td></row>\r
+               <row><td>Control</td><td>Dialog_</td><td>N</td><td/><td/><td>Dialog</td><td>1</td><td>Identifier</td><td/><td>External key to the Dialog table, name of the dialog.</td></row>\r
+               <row><td>Control</td><td>Height</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Height of the bounding rectangle of the control.</td></row>\r
+               <row><td>Control</td><td>Help</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The help strings used with the button. The text is optional.</td></row>\r
+               <row><td>Control</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path to .rtf file for scrollable text control</td></row>\r
+               <row><td>Control</td><td>ISControlId</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>A number used to represent the control ID of the Control, Used in Dialog export</td></row>\r
+               <row><td>Control</td><td>ISWindowStyle</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>A 32-bit word that specifies non-MSI window styles to be applied to this control.</td></row>\r
+               <row><td>Control</td><td>Property</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The name of a defined property to be linked to this control.</td></row>\r
+               <row><td>Control</td><td>Text</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>A string used to set the initial text contained within a control (if appropriate).</td></row>\r
+               <row><td>Control</td><td>Type</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The type of the control.</td></row>\r
+               <row><td>Control</td><td>Width</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Width of the bounding rectangle of the control.</td></row>\r
+               <row><td>Control</td><td>X</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Horizontal coordinate of the upper left corner of the bounding rectangle of the control.</td></row>\r
+               <row><td>Control</td><td>Y</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Vertical coordinate of the upper left corner of the bounding rectangle of the control.</td></row>\r
+               <row><td>ControlCondition</td><td>Action</td><td>N</td><td/><td/><td/><td/><td/><td>Default;Disable;Enable;Hide;Show</td><td>The desired action to be taken on the specified control.</td></row>\r
+               <row><td>ControlCondition</td><td>Condition</td><td>N</td><td/><td/><td/><td/><td>Condition</td><td/><td>A standard conditional statement that specifies under which conditions the action should be triggered.</td></row>\r
+               <row><td>ControlCondition</td><td>Control_</td><td>N</td><td/><td/><td>Control</td><td>2</td><td>Identifier</td><td/><td>A foreign key to the Control table, name of the control.</td></row>\r
+               <row><td>ControlCondition</td><td>Dialog_</td><td>N</td><td/><td/><td>Dialog</td><td>1</td><td>Identifier</td><td/><td>A foreign key to the Dialog table, name of the dialog.</td></row>\r
+               <row><td>ControlEvent</td><td>Argument</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>A value to be used as a modifier when triggering a particular event.</td></row>\r
+               <row><td>ControlEvent</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>A standard conditional statement that specifies under which conditions an event should be triggered.</td></row>\r
+               <row><td>ControlEvent</td><td>Control_</td><td>N</td><td/><td/><td>Control</td><td>2</td><td>Identifier</td><td/><td>A foreign key to the Control table, name of the control</td></row>\r
+               <row><td>ControlEvent</td><td>Dialog_</td><td>N</td><td/><td/><td>Dialog</td><td>1</td><td>Identifier</td><td/><td>A foreign key to the Dialog table, name of the dialog.</td></row>\r
+               <row><td>ControlEvent</td><td>Event</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>An identifier that specifies the type of the event that should take place when the user interacts with control specified by the first two entries.</td></row>\r
+               <row><td>ControlEvent</td><td>Ordering</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>An integer used to order several events tied to the same control. Can be left blank.</td></row>\r
+               <row><td>CreateFolder</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table.</td></row>\r
+               <row><td>CreateFolder</td><td>Directory_</td><td>N</td><td/><td/><td>Directory</td><td>1</td><td>Identifier</td><td/><td>Primary key, could be foreign key into the Directory table.</td></row>\r
+               <row><td>CustomAction</td><td>Action</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, name of action, normally appears in sequence table unless private use.</td></row>\r
+               <row><td>CustomAction</td><td>ExtendedType</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>The numeric custom action type info flags.</td></row>\r
+               <row><td>CustomAction</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments for this custom action.</td></row>\r
+               <row><td>CustomAction</td><td>Source</td><td>Y</td><td/><td/><td/><td/><td>CustomSource</td><td/><td>The table reference of the source of the code.</td></row>\r
+               <row><td>CustomAction</td><td>Target</td><td>Y</td><td/><td/><td>ISDLLWrapper;ISInstallScriptAction</td><td>1</td><td>Formatted</td><td/><td>Excecution parameter, depends on the type of custom action</td></row>\r
+               <row><td>CustomAction</td><td>Type</td><td>N</td><td>1</td><td>32767</td><td/><td/><td/><td/><td>The numeric custom action type, consisting of source location, code type, entry, option flags.</td></row>\r
+               <row><td>Dialog</td><td>Attributes</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>A 32-bit word that specifies the attribute flags to be applied to this dialog.</td></row>\r
+               <row><td>Dialog</td><td>Control_Cancel</td><td>Y</td><td/><td/><td>Control</td><td>2</td><td>Identifier</td><td/><td>Defines the cancel control. Hitting escape or clicking on the close icon on the dialog is equivalent to pushing this button.</td></row>\r
+               <row><td>Dialog</td><td>Control_Default</td><td>Y</td><td/><td/><td>Control</td><td>2</td><td>Identifier</td><td/><td>Defines the default control. Hitting return is equivalent to pushing this button.</td></row>\r
+               <row><td>Dialog</td><td>Control_First</td><td>N</td><td/><td/><td>Control</td><td>2</td><td>Identifier</td><td/><td>Defines the control that has the focus when the dialog is created.</td></row>\r
+               <row><td>Dialog</td><td>Dialog</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of the dialog.</td></row>\r
+               <row><td>Dialog</td><td>HCentering</td><td>N</td><td>0</td><td>100</td><td/><td/><td/><td/><td>Horizontal position of the dialog on a 0-100 scale. 0 means left end, 100 means right end of the screen, 50 center.</td></row>\r
+               <row><td>Dialog</td><td>Height</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Height of the bounding rectangle of the dialog.</td></row>\r
+               <row><td>Dialog</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments for this dialog.</td></row>\r
+               <row><td>Dialog</td><td>ISResourceId</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>A Number the Specifies the Dialog ID to be used in Dialog Export</td></row>\r
+               <row><td>Dialog</td><td>ISWindowStyle</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>A 32-bit word that specifies non-MSI window styles to be applied to this control. This is only used in Script Based Setups.</td></row>\r
+               <row><td>Dialog</td><td>TextStyle_</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign Key into TextStyle table, only used in Script Based Projects.</td></row>\r
+               <row><td>Dialog</td><td>Title</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>A text string specifying the title to be displayed in the title bar of the dialog's window.</td></row>\r
+               <row><td>Dialog</td><td>VCentering</td><td>N</td><td>0</td><td>100</td><td/><td/><td/><td/><td>Vertical position of the dialog on a 0-100 scale. 0 means top end, 100 means bottom end of the screen, 50 center.</td></row>\r
+               <row><td>Dialog</td><td>Width</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Width of the bounding rectangle of the dialog.</td></row>\r
+               <row><td>Directory</td><td>DefaultDir</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The default sub-path under parent's path.</td></row>\r
+               <row><td>Directory</td><td>Directory</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Unique identifier for directory entry, primary key. If a property by this name is defined, it contains the full path to the directory.</td></row>\r
+               <row><td>Directory</td><td>Directory_Parent</td><td>Y</td><td/><td/><td>Directory</td><td>1</td><td>Identifier</td><td/><td>Reference to the entry in this table specifying the default parent directory. A record parented to itself or with a Null parent represents a root of the install tree.</td></row>\r
+               <row><td>Directory</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td>0;1;2;3;4;5;6;7</td><td>This is used to store Installshield custom properties of a directory.  Currently the only one is Shortcut.</td></row>\r
+               <row><td>Directory</td><td>ISDescription</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Description of folder</td></row>\r
+               <row><td>Directory</td><td>ISFolderName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>This is used in Pro projects because the pro identifier used in the tree wasn't necessarily unique.</td></row>\r
+               <row><td>DrLocator</td><td>Depth</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The depth below the path to which the Signature_ is recursively searched. If absent, the depth is assumed to be 0.</td></row>\r
+               <row><td>DrLocator</td><td>Parent</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The parent file signature. It is also a foreign key in the Signature table. If null and the Path column does not expand to a full path, then all the fixed drives of the user system are searched using the Path.</td></row>\r
+               <row><td>DrLocator</td><td>Path</td><td>Y</td><td/><td/><td/><td/><td>AnyPath</td><td/><td>The path on the user system. This is a either a subpath below the value of the Parent or a full path. The path may contain properties enclosed within [ ] that will be expanded.</td></row>\r
+               <row><td>DrLocator</td><td>Signature_</td><td>N</td><td/><td/><td>Signature</td><td>1</td><td>Identifier</td><td/><td>The Signature_ represents a unique file signature and is also the foreign key in the Signature table.</td></row>\r
+               <row><td>DuplicateFile</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing Component that controls the duplicate file.</td></row>\r
+               <row><td>DuplicateFile</td><td>DestFolder</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of a property whose value is assumed to resolve to the full pathname to a destination folder.</td></row>\r
+               <row><td>DuplicateFile</td><td>DestName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Filename to be given to the duplicate file.</td></row>\r
+               <row><td>DuplicateFile</td><td>FileKey</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular file entry</td></row>\r
+               <row><td>DuplicateFile</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing the source file to be duplicated.</td></row>\r
+               <row><td>Environment</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table referencing component that controls the installing of the environmental value.</td></row>\r
+               <row><td>Environment</td><td>Environment</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Unique identifier for the environmental variable setting</td></row>\r
+               <row><td>Environment</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the environmental value.</td></row>\r
+               <row><td>Environment</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The value to set in the environmental settings.</td></row>\r
+               <row><td>Error</td><td>Error</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Integer error number, obtained from header file IError(...) macros.</td></row>\r
+               <row><td>Error</td><td>Message</td><td>Y</td><td/><td/><td/><td/><td>Template</td><td/><td>Error formatting template, obtained from user ed. or localizers.</td></row>\r
+               <row><td>EventMapping</td><td>Attribute</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The name of the control attribute, that is set when this event is received.</td></row>\r
+               <row><td>EventMapping</td><td>Control_</td><td>N</td><td/><td/><td>Control</td><td>2</td><td>Identifier</td><td/><td>A foreign key to the Control table, name of the control.</td></row>\r
+               <row><td>EventMapping</td><td>Dialog_</td><td>N</td><td/><td/><td>Dialog</td><td>1</td><td>Identifier</td><td/><td>A foreign key to the Dialog table, name of the Dialog.</td></row>\r
+               <row><td>EventMapping</td><td>Event</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>An identifier that specifies the type of the event that the control subscribes to.</td></row>\r
+               <row><td>Extension</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.</td></row>\r
+               <row><td>Extension</td><td>Extension</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The extension associated with the table row.</td></row>\r
+               <row><td>Extension</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Feature Table, specifying the feature to validate or install in order for the CLSID factory to be operational.</td></row>\r
+               <row><td>Extension</td><td>MIME_</td><td>Y</td><td/><td/><td>MIME</td><td>1</td><td>Text</td><td/><td>Optional Context identifier, typically "type/format" associated with the extension</td></row>\r
+               <row><td>Extension</td><td>ProgId_</td><td>Y</td><td/><td/><td>ProgId</td><td>1</td><td>Text</td><td/><td>Optional ProgId associated with this extension.</td></row>\r
+               <row><td>Feature</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td>0;1;2;4;5;6;8;9;10;16;17;18;20;21;22;24;25;26;32;33;34;36;37;38;48;49;50;52;53;54</td><td>Feature attributes</td></row>\r
+               <row><td>Feature</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Longer descriptive text describing a visible feature item.</td></row>\r
+               <row><td>Feature</td><td>Directory_</td><td>Y</td><td/><td/><td>Directory</td><td>1</td><td>UpperCase</td><td/><td>The name of the Directory that can be configured by the UI. A non-null value will enable the browse button.</td></row>\r
+               <row><td>Feature</td><td>Display</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Numeric sort order, used to force a specific display ordering.</td></row>\r
+               <row><td>Feature</td><td>Feature</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular feature record.</td></row>\r
+               <row><td>Feature</td><td>Feature_Parent</td><td>Y</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Optional key of a parent record in the same table. If the parent is not selected, then the record will not be installed. Null indicates a root item.</td></row>\r
+               <row><td>Feature</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Comments</td></row>\r
+               <row><td>Feature</td><td>ISFeatureCabName</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Name of CAB used when compressing CABs by Feature. Used to override build generated name for CAB file.</td></row>\r
+               <row><td>Feature</td><td>ISProFeatureName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the feature used by pro projects.  This doesn't have to be unique.</td></row>\r
+               <row><td>Feature</td><td>ISReleaseFlags</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Release Flags that specify whether this  feature will be built in a particular release.</td></row>\r
+               <row><td>Feature</td><td>Level</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The install level at which record will be initially selected. An install level of 0 will disable an item and prevent its display.</td></row>\r
+               <row><td>Feature</td><td>Title</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Short text identifying a visible feature item.</td></row>\r
+               <row><td>FeatureComponents</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Component table.</td></row>\r
+               <row><td>FeatureComponents</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Feature table.</td></row>\r
+               <row><td>File</td><td>Attributes</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Integer containing bit flags representing file attributes (with the decimal value of each bit position in parentheses)</td></row>\r
+               <row><td>File</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing Component that controls the file.</td></row>\r
+               <row><td>File</td><td>File</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token, must match identifier in cabinet.  For uncompressed files, this field is ignored.</td></row>\r
+               <row><td>File</td><td>FileName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>File name used for installation.  This may contain a "short name|long name" pair.  It may be just a long name, hence it cannot be of the Filename data type.</td></row>\r
+               <row><td>File</td><td>FileSize</td><td>N</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>Size of file in bytes (long integer).</td></row>\r
+               <row><td>File</td><td>ISAttributes</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>This field contains the following attributes: UseSystemSettings(0x1)</td></row>\r
+               <row><td>File</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path, the category is of Text instead of Path because of potential use of path variables.</td></row>\r
+               <row><td>File</td><td>ISComponentSubFolder_</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key referencing component subfolder containing this file.  Only for Pro.</td></row>\r
+               <row><td>File</td><td>Language</td><td>Y</td><td/><td/><td/><td/><td>Language</td><td/><td>List of decimal language Ids, comma-separated if more than one.</td></row>\r
+               <row><td>File</td><td>Sequence</td><td>N</td><td>1</td><td>32767</td><td/><td/><td/><td/><td>Sequence with respect to the media images; order must track cabinet order.</td></row>\r
+               <row><td>File</td><td>Version</td><td>Y</td><td/><td/><td>File</td><td>1</td><td>Version</td><td/><td>Version string for versioned files;  Blank for unversioned files.</td></row>\r
+               <row><td>FileSFPCatalog</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>File associated with the catalog</td></row>\r
+               <row><td>FileSFPCatalog</td><td>SFPCatalog_</td><td>N</td><td/><td/><td>SFPCatalog</td><td>1</td><td>Text</td><td/><td>Catalog associated with the file</td></row>\r
+               <row><td>Font</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Primary key, foreign key into File table referencing font file.</td></row>\r
+               <row><td>Font</td><td>FontTitle</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Font name.</td></row>\r
+               <row><td>ISAlias</td><td>Alias</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISAlias</td><td>Identifier</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISAlias</td><td>Table</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISAssistantTag</td><td>Data</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISAssistantTag</td><td>Tag</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>AppName</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>Attributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>CompanyName</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>Component_</td><td>Y</td><td/><td/><td>Component</td><td>1</td><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>DefDir</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>DeleteMedia</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>DesktopTargetDir</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>DeviceFile</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>IconIndex</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>IconPath</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>InstallNetCF</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>InstallNetCF2</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>InstallSQLClient</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>InstallSQLClient2</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>InstallSQLDev</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>InstallSQLDev2</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>InstallSQLServer</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>InstallSQLServer2</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>NoUninstall</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>PVKFile</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>PostXML</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>PreXML</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>RawDeviceFile</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>SPCFile</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEApp</td><td>SPCPwd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEDir</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEDir</td><td>DirKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEDir</td><td>DirParent</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEDir</td><td>DirValue</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>AdvancedOptions</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>CopyOption</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>Destination</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>FileKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>FileOption</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>Name</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>Platform</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>Processor</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFile</td><td>Source</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFileExt</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFileExt</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFileExt</td><td>ExtKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFileExt</td><td>Extension</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFileExt</td><td>FileKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEFileExt</td><td>IconIndex</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEInstall</td><td>CEAppName</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEInstall</td><td>CECabs</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEInstall</td><td>CEDesktopDir</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEInstall</td><td>CEIcoFile</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEInstall</td><td>CEIniFileKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEInstall</td><td>CEInstallKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEInstall</td><td>Component_</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEInstall</td><td>DeleteMedia</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEOtherAppCABs</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEOtherAppCABs</td><td>BuildSourcePath</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEOtherAppCABs</td><td>FileKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERedist</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERedist</td><td>Name</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERedist</td><td>Platforms</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>Key</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>Name</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>Overwrite</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>Platform</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>Processor</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>RegKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>Root</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCERegistry</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCESetupFile</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCESetupFile</td><td>Name</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCESetupFile</td><td>Platform</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCESetupFile</td><td>Processor</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCESetupFile</td><td>SetupFileKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCESetupFile</td><td>Source</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEShtCut</td><td>AppKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEShtCut</td><td>Destination</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEShtCut</td><td>DisplayName</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEShtCut</td><td>Platform</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEShtCut</td><td>ShtCutKey</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEShtCut</td><td>StartScreenIcon</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISCEShtCut</td><td>Target</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>DisplayName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Display name for the chained package. Used only in the IDE.</td></row>\r
+               <row><td>ISChainPackage</td><td>ISReleaseFlags</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>InstallCondition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>InstallProperties</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>Options</td><td>N</td><td/><td/><td/><td/><td>Integer</td><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>Order</td><td>N</td><td/><td/><td/><td/><td>Integer</td><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>Package</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>ProductCode</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>RemoveCondition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>RemoveProperties</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td/></row>\r
+               <row><td>ISChainPackage</td><td>SourcePath</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISChainPackageData</td><td>Data</td><td>Y</td><td/><td/><td/><td/><td>Binary</td><td/><td>Binary stream. The binary icon data in PE (.DLL or .EXE) or icon (.ICO) format.</td></row>\r
+               <row><td>ISChainPackageData</td><td>File</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td/></row>\r
+               <row><td>ISChainPackageData</td><td>FilePath</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td/></row>\r
+               <row><td>ISChainPackageData</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path to the ICO or EXE file.</td></row>\r
+               <row><td>ISChainPackageData</td><td>Options</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISChainPackageData</td><td>Package_</td><td>N</td><td/><td/><td>ISChainPackage</td><td>1</td><td>Identifier</td><td/><td/></row>\r
+               <row><td>ISClrWrap</td><td>Action_</td><td>N</td><td/><td/><td>CustomAction</td><td>1</td><td>Identifier</td><td/><td>Foreign key into CustomAction table</td></row>\r
+               <row><td>ISClrWrap</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Property associated with this Action</td></row>\r
+               <row><td>ISClrWrap</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Value associated with this Property</td></row>\r
+               <row><td>ISComCatalogAttribute</td><td>ISComCatalogObject_</td><td>N</td><td/><td/><td>ISComCatalogObject</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComCatalogObject table.</td></row>\r
+               <row><td>ISComCatalogAttribute</td><td>ItemName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The named attribute for a catalog object.</td></row>\r
+               <row><td>ISComCatalogAttribute</td><td>ItemValue</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>A value associated with the attribute defined in the ItemName column.</td></row>\r
+               <row><td>ISComCatalogCollection</td><td>CollectionName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>A catalog collection name.</td></row>\r
+               <row><td>ISComCatalogCollection</td><td>ISComCatalogCollection</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A unique key for the ISComCatalogCollection table.</td></row>\r
+               <row><td>ISComCatalogCollection</td><td>ISComCatalogObject_</td><td>N</td><td/><td/><td>ISComCatalogObject</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComCatalogObject table.</td></row>\r
+               <row><td>ISComCatalogCollectionObjects</td><td>ISComCatalogCollection_</td><td>N</td><td/><td/><td>ISComCatalogCollection</td><td>1</td><td>Identifier</td><td/><td>A unique key for the ISComCatalogCollection table.</td></row>\r
+               <row><td>ISComCatalogCollectionObjects</td><td>ISComCatalogObject_</td><td>N</td><td/><td/><td>ISComCatalogObject</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComCatalogObject table.</td></row>\r
+               <row><td>ISComCatalogObject</td><td>DisplayName</td><td>N</td><td/><td/><td/><td/><td/><td/><td>The display name of a catalog object.</td></row>\r
+               <row><td>ISComCatalogObject</td><td>ISComCatalogObject</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A unique key for the ISComCatalogObject table.</td></row>\r
+               <row><td>ISComPlusApplication</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table that a COM+ application belongs to.</td></row>\r
+               <row><td>ISComPlusApplication</td><td>ComputerName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Computer name that a COM+ application belongs to.</td></row>\r
+               <row><td>ISComPlusApplication</td><td>DepFiles</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>List of the dependent files.</td></row>\r
+               <row><td>ISComPlusApplication</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>InstallShield custom attributes associated with a COM+ application.</td></row>\r
+               <row><td>ISComPlusApplication</td><td>ISComCatalogObject_</td><td>N</td><td/><td/><td>ISComCatalogObject</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComCatalogObject table.</td></row>\r
+               <row><td>ISComPlusApplicationDLL</td><td>AlterDLL</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Alternate filename of the COM+ application component. Will be used for a .NET serviced component.</td></row>\r
+               <row><td>ISComPlusApplicationDLL</td><td>CLSID</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>CLSID of the COM+ application component.</td></row>\r
+               <row><td>ISComPlusApplicationDLL</td><td>DLL</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Filename of the COM+ application component.</td></row>\r
+               <row><td>ISComPlusApplicationDLL</td><td>ISComCatalogObject_</td><td>N</td><td/><td/><td>ISComCatalogObject</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComCatalogObject table.</td></row>\r
+               <row><td>ISComPlusApplicationDLL</td><td>ISComPlusApplicationDLL</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A unique key for the ISComPlusApplicationDLL table.</td></row>\r
+               <row><td>ISComPlusApplicationDLL</td><td>ISComPlusApplication_</td><td>N</td><td/><td/><td>ISComPlusApplication</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComPlusApplication table.</td></row>\r
+               <row><td>ISComPlusApplicationDLL</td><td>ProgId</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>ProgId of the COM+ application component.</td></row>\r
+               <row><td>ISComPlusProxy</td><td>Component_</td><td>Y</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table that a COM+ application proxy belongs to.</td></row>\r
+               <row><td>ISComPlusProxy</td><td>DepFiles</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>List of the dependent files.</td></row>\r
+               <row><td>ISComPlusProxy</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>InstallShield custom attributes associated with a COM+ application proxy.</td></row>\r
+               <row><td>ISComPlusProxy</td><td>ISComPlusApplication_</td><td>N</td><td/><td/><td>ISComPlusApplication</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComPlusApplication table that a COM+ application proxy belongs to.</td></row>\r
+               <row><td>ISComPlusProxy</td><td>ISComPlusProxy</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A unique key for the ISComPlusProxy table.</td></row>\r
+               <row><td>ISComPlusProxyDepFile</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the File table.</td></row>\r
+               <row><td>ISComPlusProxyDepFile</td><td>ISComPlusApplication_</td><td>N</td><td/><td/><td>ISComPlusApplication</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComPlusApplication table.</td></row>\r
+               <row><td>ISComPlusProxyDepFile</td><td>ISPath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path of the dependent file.</td></row>\r
+               <row><td>ISComPlusProxyFile</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the File table.</td></row>\r
+               <row><td>ISComPlusProxyFile</td><td>ISComPlusApplicationDLL_</td><td>N</td><td/><td/><td>ISComPlusApplicationDLL</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComPlusApplicationDLL table.</td></row>\r
+               <row><td>ISComPlusServerDepFile</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the File table.</td></row>\r
+               <row><td>ISComPlusServerDepFile</td><td>ISComPlusApplication_</td><td>N</td><td/><td/><td>ISComPlusApplication</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComPlusApplication table.</td></row>\r
+               <row><td>ISComPlusServerDepFile</td><td>ISPath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path of the dependent file.</td></row>\r
+               <row><td>ISComPlusServerFile</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the File table.</td></row>\r
+               <row><td>ISComPlusServerFile</td><td>ISComPlusApplicationDLL_</td><td>N</td><td/><td/><td>ISComPlusApplicationDLL</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISComPlusApplicationDLL table.</td></row>\r
+               <row><td>ISComponentExtended</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Primary key used to identify a particular component record.</td></row>\r
+               <row><td>ISComponentExtended</td><td>FTPLocation</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>FTP Location</td></row>\r
+               <row><td>ISComponentExtended</td><td>FilterProperty</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Property to set if you want to filter a component</td></row>\r
+               <row><td>ISComponentExtended</td><td>HTTPLocation</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>HTTP Location</td></row>\r
+               <row><td>ISComponentExtended</td><td>Language</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Language</td></row>\r
+               <row><td>ISComponentExtended</td><td>Miscellaneous</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Miscellaneous</td></row>\r
+               <row><td>ISComponentExtended</td><td>OS</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>bitwise addition of OSs</td></row>\r
+               <row><td>ISComponentExtended</td><td>Platforms</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>bitwise addition of Platforms.</td></row>\r
+               <row><td>ISCustomActionReference</td><td>Action_</td><td>N</td><td/><td/><td>CustomAction</td><td>1</td><td>Identifier</td><td/><td>Foreign key into theICustomAction table.</td></row>\r
+               <row><td>ISCustomActionReference</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Contents of the file speciifed in ISCAReferenceFilePath. This column is only used by MSI.</td></row>\r
+               <row><td>ISCustomActionReference</td><td>FileType</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>file type of the file specified  ISCAReferenceFilePath. This column is only used by MSI.</td></row>\r
+               <row><td>ISCustomActionReference</td><td>ISCAReferenceFilePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path, the category is of Text instead of Path because of potential use of path variables.  This column only exists in ISM.</td></row>\r
+               <row><td>ISDLLWrapper</td><td>EntryPoint</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>This is a foreign key to the target column in the CustomAction table</td></row>\r
+               <row><td>ISDLLWrapper</td><td>Source</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>This is column points to the source file for the DLLWrapper Custom Action</td></row>\r
+               <row><td>ISDLLWrapper</td><td>Target</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The function signature</td></row>\r
+               <row><td>ISDLLWrapper</td><td>Type</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Type</td></row>\r
+               <row><td>ISDRMFile</td><td>File_</td><td>Y</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into File table.  A null value will cause a build warning.</td></row>\r
+               <row><td>ISDRMFile</td><td>ISDRMFile</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Unique identifier for this item.</td></row>\r
+               <row><td>ISDRMFile</td><td>ISDRMLicense_</td><td>Y</td><td/><td/><td>ISDRMLicense</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing License that packages this file.</td></row>\r
+               <row><td>ISDRMFile</td><td>Shell</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Text indicating the activation shell used at runtime.</td></row>\r
+               <row><td>ISDRMFileAttribute</td><td>ISDRMFile_</td><td>N</td><td/><td/><td>ISDRMFile</td><td>1</td><td>Identifier</td><td/><td>Primary foreign key into ISDRMFile table.</td></row>\r
+               <row><td>ISDRMFileAttribute</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the attribute</td></row>\r
+               <row><td>ISDRMFileAttribute</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The value of the attribute</td></row>\r
+               <row><td>ISDRMLicense</td><td>Attributes</td><td>Y</td><td/><td/><td/><td/><td>Number</td><td/><td>Bitwise field used to specify binary attributes of this license.</td></row>\r
+               <row><td>ISDRMLicense</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>An internal description of this license.</td></row>\r
+               <row><td>ISDRMLicense</td><td>ISDRMLicense</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Unique key identifying the license record.</td></row>\r
+               <row><td>ISDRMLicense</td><td>LicenseNumber</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The license number.</td></row>\r
+               <row><td>ISDRMLicense</td><td>ProjectVersion</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The version of the project that this license is tied to.</td></row>\r
+               <row><td>ISDRMLicense</td><td>RequestCode</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The request code.</td></row>\r
+               <row><td>ISDRMLicense</td><td>ResponseCode</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The response code.</td></row>\r
+               <row><td>ISDependency</td><td>Exclude</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISDependency</td><td>ISDependency</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISDisk1File</td><td>Disk</td><td>Y</td><td/><td/><td/><td/><td/><td>-1;0;1</td><td>Used to differentiate between disk1(1), last disk(-1), and other(0).</td></row>\r
+               <row><td>ISDisk1File</td><td>ISBuildSourcePath</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path of file to be copied to Disk1 folder</td></row>\r
+               <row><td>ISDisk1File</td><td>ISDisk1File</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key for ISDisk1File table</td></row>\r
+               <row><td>ISDynamicFile</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing Component that controls the file.</td></row>\r
+               <row><td>ISDynamicFile</td><td>ExcludeFiles</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Wildcards for excluded files.</td></row>\r
+               <row><td>ISDynamicFile</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td>0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15</td><td>This is used to store Installshield custom properties of a dynamic filet.  Currently the only one is SelfRegister.</td></row>\r
+               <row><td>ISDynamicFile</td><td>IncludeFiles</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Wildcards for included files.</td></row>\r
+               <row><td>ISDynamicFile</td><td>IncludeFlags</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Include flags.</td></row>\r
+               <row><td>ISDynamicFile</td><td>SourceFolder</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path, the category is of Text instead of Path because of potential use of path variables.</td></row>\r
+               <row><td>ISFeatureExtended</td><td>CDRomFolder</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Files in this feature will be placed in this subfolder if your media is the CD-ROM type.</td></row>\r
+               <row><td>ISFeatureExtended</td><td>FTPLocation</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>FTP Location</td></row>\r
+               <row><td>ISFeatureExtended</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Foreign key to the feature table</td></row>\r
+               <row><td>ISFeatureExtended</td><td>HTTPLocation</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>HTTP Location</td></row>\r
+               <row><td>ISFeatureExtended</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Non-msi feature attributes.  Mostly used by pro projects.</td></row>\r
+               <row><td>ISFeatureExtended</td><td>Installed</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the Features Installed Event</td></row>\r
+               <row><td>ISFeatureExtended</td><td>Installing</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the Features Installing Event</td></row>\r
+               <row><td>ISFeatureExtended</td><td>Miscellaneous</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Miscellaneous</td></row>\r
+               <row><td>ISFeatureExtended</td><td>Moniker</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Used by pro to identify objects.</td></row>\r
+               <row><td>ISFeatureExtended</td><td>Password</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The password for this feature.</td></row>\r
+               <row><td>ISFeatureExtended</td><td>StatusText</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Text displayed during file transfer in pro projects.</td></row>\r
+               <row><td>ISFeatureExtended</td><td>Uninstalled</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the Features UnInstalled Event</td></row>\r
+               <row><td>ISFeatureExtended</td><td>Uninstalling</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the Features UnInstalling Event</td></row>\r
+               <row><td>ISFeatureMergeModuleExcludes</td><td>Feature_</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into Feature table.</td></row>\r
+               <row><td>ISFeatureMergeModuleExcludes</td><td>Language</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Foreign key into ISMergeModule table.</td></row>\r
+               <row><td>ISFeatureMergeModuleExcludes</td><td>ModuleID</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into ISMergeModule table.</td></row>\r
+               <row><td>ISFeatureMergeModules</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Feature table.</td></row>\r
+               <row><td>ISFeatureMergeModules</td><td>ISMergeModule_</td><td>N</td><td/><td/><td>ISMergeModule</td><td>1</td><td>Text</td><td/><td>Foreign key into ISMergeModule table.</td></row>\r
+               <row><td>ISFeatureMergeModules</td><td>Language_</td><td>N</td><td/><td/><td>ISMergeModule</td><td>2</td><td/><td/><td>Foreign key into ISMergeModule table.</td></row>\r
+               <row><td>ISFeatureSetupPrerequisites</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Feature table.</td></row>\r
+               <row><td>ISFeatureSetupPrerequisites</td><td>ISSetupPrerequisites_</td><td>N</td><td/><td/><td>ISSetupPrerequisites</td><td>1</td><td/><td/><td/></row>\r
+               <row><td>ISFileManifests</td><td>File_</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into File table.</td></row>\r
+               <row><td>ISFileManifests</td><td>Manifest_</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into File table.</td></row>\r
+               <row><td>ISIISItem</td><td>Component_</td><td>Y</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key to Component table.</td></row>\r
+               <row><td>ISIISItem</td><td>DisplayName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Localizable Item Name.</td></row>\r
+               <row><td>ISIISItem</td><td>ISIISItem</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key for each item.</td></row>\r
+               <row><td>ISIISItem</td><td>ISIISItem_Parent</td><td>Y</td><td/><td/><td>ISIISItem</td><td>1</td><td>Identifier</td><td/><td>This record's parent record.</td></row>\r
+               <row><td>ISIISItem</td><td>Type</td><td>N</td><td/><td/><td/><td/><td/><td/><td>IIS resource type.</td></row>\r
+               <row><td>ISIISProperty</td><td>FriendlyName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>IIS property name.</td></row>\r
+               <row><td>ISIISProperty</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Flags.</td></row>\r
+               <row><td>ISIISProperty</td><td>ISIISItem_</td><td>N</td><td/><td/><td>ISIISItem</td><td>1</td><td>Identifier</td><td/><td>Primary key for table, foreign key into ISIISItem.</td></row>\r
+               <row><td>ISIISProperty</td><td>ISIISProperty</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key for table.</td></row>\r
+               <row><td>ISIISProperty</td><td>MetaDataAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>IIS property attributes.</td></row>\r
+               <row><td>ISIISProperty</td><td>MetaDataProp</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>IIS property ID.</td></row>\r
+               <row><td>ISIISProperty</td><td>MetaDataType</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>IIS property data type.</td></row>\r
+               <row><td>ISIISProperty</td><td>MetaDataUserType</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>IIS property user data type.</td></row>\r
+               <row><td>ISIISProperty</td><td>MetaDataValue</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>IIS property value.</td></row>\r
+               <row><td>ISIISProperty</td><td>Order</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Order sequencing.</td></row>\r
+               <row><td>ISIISProperty</td><td>Schema</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>IIS7 schema information.</td></row>\r
+               <row><td>ISInstallScriptAction</td><td>EntryPoint</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>This is a foreign key to the target column in the CustomAction table</td></row>\r
+               <row><td>ISInstallScriptAction</td><td>Source</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>This is column points to the source file for the DLLWrapper Custom Action</td></row>\r
+               <row><td>ISInstallScriptAction</td><td>Target</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The function signature</td></row>\r
+               <row><td>ISInstallScriptAction</td><td>Type</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Type</td></row>\r
+               <row><td>ISLanguage</td><td>ISLanguage</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>This is the language ID.</td></row>\r
+               <row><td>ISLanguage</td><td>Included</td><td>Y</td><td/><td/><td/><td/><td/><td>0;1</td><td>Specify whether this language should be included.</td></row>\r
+               <row><td>ISLinkerLibrary</td><td>ISLinkerLibrary</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Unique identifier for the link library.</td></row>\r
+               <row><td>ISLinkerLibrary</td><td>Library</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path of the object library (.obl file).</td></row>\r
+               <row><td>ISLinkerLibrary</td><td>Order</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Order of the Library</td></row>\r
+               <row><td>ISLocalControl</td><td>Attributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>A 32-bit word that specifies the attribute flags to be applied to this control.</td></row>\r
+               <row><td>ISLocalControl</td><td>Binary_</td><td>Y</td><td/><td/><td>Binary</td><td>1</td><td>Identifier</td><td/><td>External key to the Binary table.</td></row>\r
+               <row><td>ISLocalControl</td><td>Control_</td><td>N</td><td/><td/><td>Control</td><td>2</td><td>Identifier</td><td/><td>Name of the control. This name must be unique within a dialog, but can repeat on different dialogs.</td></row>\r
+               <row><td>ISLocalControl</td><td>Dialog_</td><td>N</td><td/><td/><td>Dialog</td><td>1</td><td>Identifier</td><td/><td>External key to the Dialog table, name of the dialog.</td></row>\r
+               <row><td>ISLocalControl</td><td>Height</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Height of the bounding rectangle of the control.</td></row>\r
+               <row><td>ISLocalControl</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path to .rtf file for scrollable text control</td></row>\r
+               <row><td>ISLocalControl</td><td>ISLanguage_</td><td>N</td><td/><td/><td>ISLanguage</td><td>1</td><td>Text</td><td/><td>This is a foreign key to the ISLanguage table.</td></row>\r
+               <row><td>ISLocalControl</td><td>Width</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Width of the bounding rectangle of the control.</td></row>\r
+               <row><td>ISLocalControl</td><td>X</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Horizontal coordinate of the upper left corner of the bounding rectangle of the control.</td></row>\r
+               <row><td>ISLocalControl</td><td>Y</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Vertical coordinate of the upper left corner of the bounding rectangle of the control.</td></row>\r
+               <row><td>ISLocalDialog</td><td>Attributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>A 32-bit word that specifies the attribute flags to be applied to this dialog.</td></row>\r
+               <row><td>ISLocalDialog</td><td>Dialog_</td><td>Y</td><td/><td/><td>Dialog</td><td>1</td><td>Identifier</td><td/><td>Name of the dialog.</td></row>\r
+               <row><td>ISLocalDialog</td><td>Height</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Height of the bounding rectangle of the dialog.</td></row>\r
+               <row><td>ISLocalDialog</td><td>ISLanguage_</td><td>Y</td><td/><td/><td>ISLanguage</td><td>1</td><td>Text</td><td/><td>This is a foreign key to the ISLanguage table.</td></row>\r
+               <row><td>ISLocalDialog</td><td>TextStyle_</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign Key into TextStyle table, only used in Script Based Projects.</td></row>\r
+               <row><td>ISLocalDialog</td><td>Width</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Width of the bounding rectangle of the dialog.</td></row>\r
+               <row><td>ISLocalRadioButton</td><td>Height</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The height of the button.</td></row>\r
+               <row><td>ISLocalRadioButton</td><td>ISLanguage_</td><td>N</td><td/><td/><td>ISLanguage</td><td>1</td><td>Text</td><td/><td>This is a foreign key to the ISLanguage table.</td></row>\r
+               <row><td>ISLocalRadioButton</td><td>Order</td><td>N</td><td>1</td><td>32767</td><td>RadioButton</td><td>2</td><td/><td/><td>A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.</td></row>\r
+               <row><td>ISLocalRadioButton</td><td>Property</td><td>N</td><td/><td/><td>RadioButton</td><td>1</td><td>Identifier</td><td/><td>A named property to be tied to this radio button. All the buttons tied to the same property become part of the same group.</td></row>\r
+               <row><td>ISLocalRadioButton</td><td>Width</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The width of the button.</td></row>\r
+               <row><td>ISLocalRadioButton</td><td>X</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The horizontal coordinate of the upper left corner of the bounding rectangle of the radio button.</td></row>\r
+               <row><td>ISLocalRadioButton</td><td>Y</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The vertical coordinate of the upper left corner of the bounding rectangle of the radio button.</td></row>\r
+               <row><td>ISLockPermissions</td><td>Attributes</td><td>Y</td><td>-2147483647</td><td>2147483647</td><td/><td/><td/><td/><td>Permissions attributes mask, 1==Deny access; 2==No inherit</td></row>\r
+               <row><td>ISLockPermissions</td><td>Domain</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Domain name for user whose permissions are being set.</td></row>\r
+               <row><td>ISLockPermissions</td><td>LockObject</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into CreateFolder, Registry, or File table</td></row>\r
+               <row><td>ISLockPermissions</td><td>Permission</td><td>Y</td><td>-2147483647</td><td>2147483647</td><td/><td/><td/><td/><td>Permission Access mask.</td></row>\r
+               <row><td>ISLockPermissions</td><td>Table</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td>CreateFolder;File;Registry</td><td>Reference to another table name</td></row>\r
+               <row><td>ISLockPermissions</td><td>User</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>User for permissions to be set. This can be a property, hardcoded named, or SID string</td></row>\r
+               <row><td>ISLogicalDisk</td><td>Cabinet</td><td>Y</td><td/><td/><td/><td/><td>Cabinet</td><td/><td>If some or all of the files stored on the media are compressed in a cabinet, the name of that cabinet.</td></row>\r
+               <row><td>ISLogicalDisk</td><td>DiskId</td><td>N</td><td>1</td><td>32767</td><td/><td/><td/><td/><td>Primary key, integer to determine sort order for table.</td></row>\r
+               <row><td>ISLogicalDisk</td><td>DiskPrompt</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Disk name: the visible text actually printed on the disk.  This will be used to prompt the user when this disk needs to be inserted.</td></row>\r
+               <row><td>ISLogicalDisk</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td>ISProductConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key into the ISProductConfiguration table.</td></row>\r
+               <row><td>ISLogicalDisk</td><td>ISRelease_</td><td>N</td><td/><td/><td>ISRelease</td><td>1</td><td>Text</td><td/><td>Foreign key into the ISRelease table.</td></row>\r
+               <row><td>ISLogicalDisk</td><td>LastSequence</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>File sequence number for the last file for this media.</td></row>\r
+               <row><td>ISLogicalDisk</td><td>Source</td><td>Y</td><td/><td/><td/><td/><td>Property</td><td/><td>The property defining the location of the cabinet file.</td></row>\r
+               <row><td>ISLogicalDisk</td><td>VolumeLabel</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The label attributed to the volume.</td></row>\r
+               <row><td>ISLogicalDiskFeatures</td><td>Feature_</td><td>Y</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Feature Table,</td></row>\r
+               <row><td>ISLogicalDiskFeatures</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store Installshield custom properties, like Compressed, etc.</td></row>\r
+               <row><td>ISLogicalDiskFeatures</td><td>ISLogicalDisk_</td><td>N</td><td>1</td><td>32767</td><td>ISLogicalDisk</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the ISLogicalDisk table.</td></row>\r
+               <row><td>ISLogicalDiskFeatures</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td>ISProductConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key into the ISProductConfiguration table.</td></row>\r
+               <row><td>ISLogicalDiskFeatures</td><td>ISRelease_</td><td>N</td><td/><td/><td>ISRelease</td><td>1</td><td>Text</td><td/><td>Foreign key into the ISRelease table.</td></row>\r
+               <row><td>ISLogicalDiskFeatures</td><td>Sequence</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>File sequence number for the file for this media.</td></row>\r
+               <row><td>ISMergeModule</td><td>Destination</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Destination.</td></row>\r
+               <row><td>ISMergeModule</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store Installshield custom properties of a merge module.</td></row>\r
+               <row><td>ISMergeModule</td><td>ISMergeModule</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The GUID identifying the merge module.</td></row>\r
+               <row><td>ISMergeModule</td><td>Language</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Default decimal language of module.</td></row>\r
+               <row><td>ISMergeModule</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the merge module.</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>Attributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Attributes (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>ContextData</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>ContextData  (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>DefaultValue</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>DefaultValue  (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Description (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>DisplayName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>DisplayName (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>Format</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Format (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>HelpKeyword</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>HelpKeyword (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>HelpLocation</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>HelpLocation (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>ISMergeModule_</td><td>N</td><td/><td/><td>ISMergeModule</td><td>1</td><td>Text</td><td/><td>The module signature, a foreign key into the ISMergeModule table</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>Language_</td><td>N</td><td/><td/><td>ISMergeModule</td><td>2</td><td/><td/><td>Default decimal language of module.</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>ModuleConfiguration_</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Identifier, foreign key into ModuleConfiguration table (ModuleConfiguration.Name)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>Type</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Type (from configurable merge module)</td></row>\r
+               <row><td>ISMergeModuleCfgValues</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Value for this item.</td></row>\r
+               <row><td>ISObject</td><td>Language</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>ISObject</td><td>ObjectName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>ISObjectProperty</td><td>IncludeInBuild</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Boolean, 0 for false non 0 for true</td></row>\r
+               <row><td>ISObjectProperty</td><td>ObjectName</td><td>Y</td><td/><td/><td>ISObject</td><td>1</td><td>Text</td><td/><td/></row>\r
+               <row><td>ISObjectProperty</td><td>Property</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>ISObjectProperty</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>ISPalmApp</td><td>Component</td><td>N</td><td/><td/><td>Component</td><td>1</td><td/><td/><td/></row>\r
+               <row><td>ISPalmApp</td><td>PalmApp</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISPalmAppFile</td><td>Destination</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISPalmAppFile</td><td>FileKey</td><td>N</td><td/><td/><td>File</td><td>1</td><td/><td/><td/></row>\r
+               <row><td>ISPalmAppFile</td><td>PalmApp</td><td>N</td><td/><td/><td>ISPalmApp</td><td>1</td><td/><td/><td/></row>\r
+               <row><td>ISPatchConfigImage</td><td>PatchConfiguration_</td><td>Y</td><td/><td/><td>ISPatchConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key to the ISPatchConfigurationTable</td></row>\r
+               <row><td>ISPatchConfigImage</td><td>UpgradedImage_</td><td>N</td><td/><td/><td>ISUpgradedImage</td><td>1</td><td>Text</td><td/><td>Foreign key to the ISUpgradedImageTable</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>Attributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>PatchConfiguration attributes</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>CanPCDiffer</td><td>N</td><td/><td/><td/><td/><td/><td/><td>This is determine whether Product Codes may differ</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>CanPVDiffer</td><td>N</td><td/><td/><td/><td/><td/><td/><td>This is determine whether the Major Product Version may differ</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>EnablePatchCache</td><td>N</td><td/><td/><td/><td/><td/><td/><td>This is determine whether to Enable Patch cacheing</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>Flags</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Patching API Flags</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>IncludeWholeFiles</td><td>N</td><td/><td/><td/><td/><td/><td/><td>This is determine whether to build a binary level patch</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>LeaveDecompressed</td><td>N</td><td/><td/><td/><td/><td/><td/><td>This is determine whether to leave intermediate files devcompressed when finished</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>MinMsiVersion</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Minimum Required MSI Version</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the Patch Configuration</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>OptimizeForSize</td><td>N</td><td/><td/><td/><td/><td/><td/><td>This is determine whether to Optimize for large files</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>OutputPath</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Build Location</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>PatchCacheDir</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Directory to recieve the Patch Cache information</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>PatchGuid</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Unique Patch Identifier</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>PatchGuidsToReplace</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>List Of Patch Guids to unregister</td></row>\r
+               <row><td>ISPatchConfiguration</td><td>TargetProductCodes</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>List Of target Product Codes</td></row>\r
+               <row><td>ISPatchConfigurationProperty</td><td>ISPatchConfiguration_</td><td>Y</td><td/><td/><td>ISPatchConfiguration</td><td>1</td><td>Text</td><td/><td>Name of the Patch Configuration</td></row>\r
+               <row><td>ISPatchConfigurationProperty</td><td>Property</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the Patch Configuration Property value</td></row>\r
+               <row><td>ISPatchConfigurationProperty</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Value of the Patch Configuration Property</td></row>\r
+               <row><td>ISPatchExternalFile</td><td>FileKey</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Filekey</td></row>\r
+               <row><td>ISPatchExternalFile</td><td>FilePath</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Filepath</td></row>\r
+               <row><td>ISPatchExternalFile</td><td>ISUpgradedImage_</td><td>N</td><td/><td/><td>ISUpgradedImage</td><td>1</td><td>Text</td><td/><td>Foreign key to the isupgraded image table</td></row>\r
+               <row><td>ISPatchExternalFile</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Uniqu name to identify this record.</td></row>\r
+               <row><td>ISPatchWholeFile</td><td>Component</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Component containing file key</td></row>\r
+               <row><td>ISPatchWholeFile</td><td>FileKey</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Key of file to be included as whole</td></row>\r
+               <row><td>ISPatchWholeFile</td><td>UpgradedImage</td><td>N</td><td/><td/><td>ISUpgradedImage</td><td>1</td><td>Text</td><td/><td>Foreign key to ISUpgradedImage Table</td></row>\r
+               <row><td>ISPathVariable</td><td>ISPathVariable</td><td>N</td><td/><td/><td/><td/><td/><td/><td>The name of the path variable.</td></row>\r
+               <row><td>ISPathVariable</td><td>TestValue</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The test value of the path variable.</td></row>\r
+               <row><td>ISPathVariable</td><td>Type</td><td>N</td><td/><td/><td/><td/><td/><td>1;2;4;8</td><td>The type of the path variable.</td></row>\r
+               <row><td>ISPathVariable</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The value of the path variable.</td></row>\r
+               <row><td>ISProductConfiguration</td><td>GeneratePackageCode</td><td>Y</td><td/><td/><td/><td/><td>Number</td><td>0;1</td><td>Indicates whether or not to generate a package code.</td></row>\r
+               <row><td>ISProductConfiguration</td><td>ISProductConfiguration</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the product configuration.</td></row>\r
+               <row><td>ISProductConfiguration</td><td>ProductConfigurationFlags</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Product configuration (release) flags.</td></row>\r
+               <row><td>ISProductConfigurationInstance</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td>ISProductConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key into the ISProductConfiguration table.</td></row>\r
+               <row><td>ISProductConfigurationInstance</td><td>InstanceId</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Identifies the instance number of this instance. This value is stored in the Property InstanceId.</td></row>\r
+               <row><td>ISProductConfigurationInstance</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Product Congiuration property name</td></row>\r
+               <row><td>ISProductConfigurationInstance</td><td>Value</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>String value for property.</td></row>\r
+               <row><td>ISProductConfigurationProperty</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td>ISProductConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key into the ISProductConfiguration table.</td></row>\r
+               <row><td>ISProductConfigurationProperty</td><td>Property</td><td>N</td><td/><td/><td>Property</td><td>1</td><td>Text</td><td/><td>Product Congiuration property name</td></row>\r
+               <row><td>ISProductConfigurationProperty</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>String value for property. Never null or empty.</td></row>\r
+               <row><td>ISRelease</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Bitfield holding boolean values for various release attributes.</td></row>\r
+               <row><td>ISRelease</td><td>BuildLocation</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Build location.</td></row>\r
+               <row><td>ISRelease</td><td>CDBrowser</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Demoshield browser location.</td></row>\r
+               <row><td>ISRelease</td><td>DefaultLanguage</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Default language for setup.</td></row>\r
+               <row><td>ISRelease</td><td>DigitalPVK</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Digital signing private key (.pvk) file.</td></row>\r
+               <row><td>ISRelease</td><td>DigitalSPC</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Digital signing Software Publisher Certificate (.spc) file.</td></row>\r
+               <row><td>ISRelease</td><td>DigitalURL</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Digital signing URL.</td></row>\r
+               <row><td>ISRelease</td><td>DiskClusterSize</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Disk cluster size.</td></row>\r
+               <row><td>ISRelease</td><td>DiskSize</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Disk size.</td></row>\r
+               <row><td>ISRelease</td><td>DiskSizeUnit</td><td>N</td><td/><td/><td/><td/><td/><td>0;1;2</td><td>Disk size units (KB or MB).</td></row>\r
+               <row><td>ISRelease</td><td>DiskSpanning</td><td>N</td><td/><td/><td/><td/><td/><td>0;1;2</td><td>Disk spanning (automatic, enforce size, etc.).</td></row>\r
+               <row><td>ISRelease</td><td>DotNetBuildConfiguration</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Build Configuration for .NET solutions.</td></row>\r
+               <row><td>ISRelease</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td>ISProductConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key into the ISProductConfiguration table.</td></row>\r
+               <row><td>ISRelease</td><td>ISRelease</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the release.</td></row>\r
+               <row><td>ISRelease</td><td>ISSetupPrerequisiteLocation</td><td>Y</td><td/><td/><td/><td/><td/><td>0;1;2;3</td><td>Location the Setup Prerequisites will be placed in</td></row>\r
+               <row><td>ISRelease</td><td>MediaLocation</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Media location on disk.</td></row>\r
+               <row><td>ISRelease</td><td>MsiCommandLine</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Command line passed to the msi package from setup.exe</td></row>\r
+               <row><td>ISRelease</td><td>MsiSourceType</td><td>N</td><td>-1</td><td>4</td><td/><td/><td/><td/><td>MSI media source type.</td></row>\r
+               <row><td>ISRelease</td><td>PackageName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Package name.</td></row>\r
+               <row><td>ISRelease</td><td>Password</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Password.</td></row>\r
+               <row><td>ISRelease</td><td>Platforms</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Platforms supported (Intel, Alpha, etc.).</td></row>\r
+               <row><td>ISRelease</td><td>ReleaseFlags</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Release flags.</td></row>\r
+               <row><td>ISRelease</td><td>ReleaseType</td><td>N</td><td/><td/><td/><td/><td/><td>1;2;4</td><td>Release type (single, uncompressed, etc.).</td></row>\r
+               <row><td>ISRelease</td><td>SupportedLanguagesData</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Languages supported (for component filtering).</td></row>\r
+               <row><td>ISRelease</td><td>SupportedLanguagesUI</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>UI languages supported.</td></row>\r
+               <row><td>ISRelease</td><td>SupportedOSs</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Indicate which operating systmes are supported.</td></row>\r
+               <row><td>ISRelease</td><td>SynchMsi</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>MSI file to synchronize file keys and other data with (patch-like functionality).</td></row>\r
+               <row><td>ISRelease</td><td>Type</td><td>N</td><td>0</td><td>6</td><td/><td/><td/><td/><td>Release type (CDROM, Network, etc.).</td></row>\r
+               <row><td>ISRelease</td><td>URLLocation</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Media location via URL.</td></row>\r
+               <row><td>ISRelease</td><td>VersionCopyright</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Version stamp information.</td></row>\r
+               <row><td>ISReleaseExtended</td><td>Attributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Bitfield holding boolean values for various release attributes.</td></row>\r
+               <row><td>ISReleaseExtended</td><td>CertPassword</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Digital certificate password</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DigitalCertificateDBaseNS</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Path to cerificate database for Netscape digital  signature</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DigitalCertificateIdNS</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Path to cerificate ID for Netscape digital  signature</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DigitalCertificatePasswordNS</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Password for Netscape digital  signature</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DotNetBaseLanguage</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Base Languge of .NET Redist</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DotNetFxCmdLine</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Command Line to pass to DotNetFx.exe</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DotNetLangPackCmdLine</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Command Line to pass to LangPack.exe</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DotNetLangaugePacks</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>.NET Redist language packs to include</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DotNetRedistLocation</td><td>Y</td><td>0</td><td>3</td><td/><td/><td/><td/><td>Location of .NET framework Redist (Web, SetupExe, Source, None)</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DotNetRedistURL</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>URL to .NET framework Redist</td></row>\r
+               <row><td>ISReleaseExtended</td><td>DotNetVersion</td><td>Y</td><td>0</td><td>2</td><td/><td/><td/><td/><td>Version of .NET framework Redist (1.0, 1.1)</td></row>\r
+               <row><td>ISReleaseExtended</td><td>EngineLocation</td><td>Y</td><td>0</td><td>2</td><td/><td/><td/><td/><td>Location of msi engine (Web, SetupExe...)</td></row>\r
+               <row><td>ISReleaseExtended</td><td>ISEngineLocation</td><td>Y</td><td>0</td><td>2</td><td/><td/><td/><td/><td>Location of ISScript  engine (Web, SetupExe...)</td></row>\r
+               <row><td>ISReleaseExtended</td><td>ISEngineURL</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>URL to InstallShield scripting engine</td></row>\r
+               <row><td>ISReleaseExtended</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Foreign key into the ISProductConfiguration table.</td></row>\r
+               <row><td>ISReleaseExtended</td><td>ISRelease_</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the release.</td></row>\r
+               <row><td>ISReleaseExtended</td><td>JSharpCmdLine</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Command Line to pass to vjredist.exe</td></row>\r
+               <row><td>ISReleaseExtended</td><td>JSharpRedistLocation</td><td>Y</td><td>0</td><td>3</td><td/><td/><td/><td/><td>Location of J# framework Redist (Web, SetupExe, Source, None)</td></row>\r
+               <row><td>ISReleaseExtended</td><td>MsiEngineVersion</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Bitfield holding selected MSI engine versions included in this release</td></row>\r
+               <row><td>ISReleaseExtended</td><td>OneClickCabName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>File name of generated cabfile</td></row>\r
+               <row><td>ISReleaseExtended</td><td>OneClickHtmlName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>File name of generated html page</td></row>\r
+               <row><td>ISReleaseExtended</td><td>OneClickTargetBrowser</td><td>Y</td><td>0</td><td>2</td><td/><td/><td/><td/><td>Target browser (IE, Netscape, both...)</td></row>\r
+               <row><td>ISReleaseExtended</td><td>WebCabSize</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>Size of the cabfile</td></row>\r
+               <row><td>ISReleaseExtended</td><td>WebLocalCachePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Directory to cache downloaded package</td></row>\r
+               <row><td>ISReleaseExtended</td><td>WebType</td><td>Y</td><td>0</td><td>2</td><td/><td/><td/><td/><td>Type of web install (One Executable, Downloader...)</td></row>\r
+               <row><td>ISReleaseExtended</td><td>WebURL</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>URL to .msi package</td></row>\r
+               <row><td>ISReleaseExtended</td><td>Win9xMsiUrl</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>URL to Ansi MSI engine</td></row>\r
+               <row><td>ISReleaseExtended</td><td>WinMsi30Url</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>URL to MSI 3.0 engine</td></row>\r
+               <row><td>ISReleaseExtended</td><td>WinNTMsiUrl</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>URL to Unicode MSI engine</td></row>\r
+               <row><td>ISReleaseProperty</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Foreign key into ISProductConfiguration table.</td></row>\r
+               <row><td>ISReleaseProperty</td><td>ISRelease_</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Foreign key into ISRelease table.</td></row>\r
+               <row><td>ISReleaseProperty</td><td>Name</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property name</td></row>\r
+               <row><td>ISReleaseProperty</td><td>Value</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property value</td></row>\r
+               <row><td>ISReleasePublishInfo</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Repository item description</td></row>\r
+               <row><td>ISReleasePublishInfo</td><td>DisplayName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Repository item display name</td></row>\r
+               <row><td>ISReleasePublishInfo</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Bitfield holding various attributes</td></row>\r
+               <row><td>ISReleasePublishInfo</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td>ISProductConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key into the ISProductConfiguration table.</td></row>\r
+               <row><td>ISReleasePublishInfo</td><td>ISRelease_</td><td>N</td><td/><td/><td>ISRelease</td><td>1</td><td>Text</td><td/><td>The name of the release.</td></row>\r
+               <row><td>ISReleasePublishInfo</td><td>Publisher</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Repository item publisher</td></row>\r
+               <row><td>ISReleasePublishInfo</td><td>Repository</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Repository which to  publish the built merge module</td></row>\r
+               <row><td>ISRequiredFeature</td><td>RequiredFeature</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>This feature is required by the feature in the RequiringFeature column</td></row>\r
+               <row><td>ISRequiredFeature</td><td>RequiringFeature</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>This feature requires the feature in the RequiredFeature column</td></row>\r
+               <row><td>ISSQLConnection</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>Authentication</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>BatchSeparator</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>CmdTimeout</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>Comments</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>Database</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>ISSQLConnection</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular ISSQLConnection record.</td></row>\r
+               <row><td>ISSQLConnection</td><td>Order</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>Password</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>ScriptVersion_Column</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>ScriptVersion_Table</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>Server</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnection</td><td>UserName</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnectionDBServer</td><td>ISSQLConnectionDBServer</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular ISSQLConnectionDBServer record.</td></row>\r
+               <row><td>ISSQLConnectionDBServer</td><td>ISSQLConnection_</td><td>N</td><td/><td/><td>ISSQLConnection</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLConnection table.</td></row>\r
+               <row><td>ISSQLConnectionDBServer</td><td>ISSQLDBMetaData_</td><td>N</td><td/><td/><td>ISSQLDBMetaData</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLDBMetaData table.</td></row>\r
+               <row><td>ISSQLConnectionDBServer</td><td>Order</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLConnectionScript</td><td>ISSQLConnection_</td><td>N</td><td/><td/><td>ISSQLConnection</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLConnection table.</td></row>\r
+               <row><td>ISSQLConnectionScript</td><td>ISSQLScriptFile_</td><td>N</td><td/><td/><td>ISSQLScriptFile</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLScriptFile table.</td></row>\r
+               <row><td>ISSQLConnectionScript</td><td>Order</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnAdditional</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnDatabase</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnDriver</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnNetLibrary</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnPassword</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnPort</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnServer</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnUserID</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoCxnWindowsSecurity</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>AdoDriverName</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>CreateDbCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>CreateTableCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>DisplayName</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>DsnODBCName</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>ISSQLDBMetaData</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular ISSQLDBMetaData record.</td></row>\r
+               <row><td>ISSQLDBMetaData</td><td>InsertRecordCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>LocalInstanceNames</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>QueryDatabasesCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>ScriptVersion_Column</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>ScriptVersion_ColumnType</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>ScriptVersion_Table</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>SelectTableCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>SwitchDbCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>TestDatabaseCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>TestTableCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>TestTableCmd2</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>VersionBeginToken</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>VersionEndToken</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>VersionInfoCmd</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLDBMetaData</td><td>WinAuthentUserId</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLRequirement</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLRequirement</td><td>ISSQLConnectionDBServer_</td><td>Y</td><td/><td/><td>ISSQLConnectionDBServer</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLConnectionDBServer table.</td></row>\r
+               <row><td>ISSQLRequirement</td><td>ISSQLConnection_</td><td>N</td><td/><td/><td>ISSQLConnection</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLConnection table.</td></row>\r
+               <row><td>ISSQLRequirement</td><td>ISSQLRequirement</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular ISSQLRequirement record.</td></row>\r
+               <row><td>ISSQLRequirement</td><td>MajorVersion</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLRequirement</td><td>ServicePackLevel</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptError</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptError</td><td>ErrHandling</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptError</td><td>ErrNumber</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptError</td><td>ISSQLScriptFile_</td><td>Y</td><td/><td/><td>ISSQLScriptFile</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLScriptFile table</td></row>\r
+               <row><td>ISSQLScriptError</td><td>Message</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Custom end-user message. Reserved for future use.</td></row>\r
+               <row><td>ISSQLScriptFile</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptFile</td><td>Comments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Comments</td></row>\r
+               <row><td>ISSQLScriptFile</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing Component that controls the SQL script.</td></row>\r
+               <row><td>ISSQLScriptFile</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>A conditional statement that will disable this script if the specified condition evaluates to the 'False' state. If a script is disabled, it will not be installed regardless of the 'Action' state associated with the component.</td></row>\r
+               <row><td>ISSQLScriptFile</td><td>ErrorHandling</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptFile</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path, the category is of Text instead of Path because of potential use of path variables.</td></row>\r
+               <row><td>ISSQLScriptFile</td><td>ISSQLScriptFile</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>This is the primary key to the ISSQLScriptFile table</td></row>\r
+               <row><td>ISSQLScriptFile</td><td>InstallText</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Feedback end-user text at install</td></row>\r
+               <row><td>ISSQLScriptFile</td><td>Scheduling</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptFile</td><td>UninstallText</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Feedback end-user text at Uninstall</td></row>\r
+               <row><td>ISSQLScriptFile</td><td>Version</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Schema Version (####.#####.####)</td></row>\r
+               <row><td>ISSQLScriptImport</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptImport</td><td>Authentication</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptImport</td><td>Database</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptImport</td><td>ExcludeTables</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptImport</td><td>ISSQLScriptFile_</td><td>N</td><td/><td/><td>ISSQLScriptFile</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLScriptFile table.</td></row>\r
+               <row><td>ISSQLScriptImport</td><td>IncludeTables</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptImport</td><td>Password</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptImport</td><td>Server</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptImport</td><td>UserName</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptReplace</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptReplace</td><td>ISSQLScriptFile_</td><td>N</td><td/><td/><td>ISSQLScriptFile</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSQLScriptFile table.</td></row>\r
+               <row><td>ISSQLScriptReplace</td><td>ISSQLScriptReplace</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular ISSQLScriptReplace record.</td></row>\r
+               <row><td>ISSQLScriptReplace</td><td>Replace</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSQLScriptReplace</td><td>Search</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISScriptFile</td><td>ISScriptFile</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>This is the full path of the script file. The path portion may be expressed in path variable form.</td></row>\r
+               <row><td>ISSearchReplace</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSearchReplace</td><td>ISSearchReplace</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular ISSearchReplace record.</td></row>\r
+               <row><td>ISSearchReplace</td><td>ISSearchReplaceSet_</td><td>N</td><td/><td/><td>ISSearchReplaceSet</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing ISSearchReplaceSet.</td></row>\r
+               <row><td>ISSearchReplace</td><td>Order</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSearchReplace</td><td>Replace</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSearchReplace</td><td>Search</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSearchReplaceSet</td><td>Attributes</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSearchReplaceSet</td><td>CodePage</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSearchReplaceSet</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing Component that controls the text file change.</td></row>\r
+               <row><td>ISSearchReplaceSet</td><td>Directory_</td><td>N</td><td/><td/><td>Directory</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing Directory that contains the text files.</td></row>\r
+               <row><td>ISSearchReplaceSet</td><td>ExcludeFiles</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSearchReplaceSet</td><td>ISSearchReplaceSet</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular ISSearchReplaceSet record.</td></row>\r
+               <row><td>ISSearchReplaceSet</td><td>IncludeFiles</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSearchReplaceSet</td><td>Order</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSelfReg</td><td>CmdLine</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSelfReg</td><td>Cost</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSelfReg</td><td>FileKey</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key to the file table</td></row>\r
+               <row><td>ISSelfReg</td><td>Order</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSetupFile</td><td>FileName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>This is the file name to use when streaming the file to the support files location</td></row>\r
+               <row><td>ISSetupFile</td><td>ISSetupFile</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>This is the primary key to the ISSetupFile table</td></row>\r
+               <row><td>ISSetupFile</td><td>Language</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Four digit language identifier.  0 for Language Neutral</td></row>\r
+               <row><td>ISSetupFile</td><td>Path</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Link to the source file on the build machine</td></row>\r
+               <row><td>ISSetupFile</td><td>Splash</td><td>Y</td><td/><td/><td/><td/><td>Short</td><td/><td>Boolean value indication whether his setup file entry belongs in the Splasc Screen section</td></row>\r
+               <row><td>ISSetupFile</td><td>Stream</td><td>Y</td><td/><td/><td/><td/><td>Binary</td><td/><td>Binary stream. The bits to stream to the support location</td></row>\r
+               <row><td>ISSetupPrerequisites</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSetupPrerequisites</td><td>ISReleaseFlags</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Release Flags that specify whether this prereq  will be included in a particular release.</td></row>\r
+               <row><td>ISSetupPrerequisites</td><td>ISSetupLocation</td><td>Y</td><td/><td/><td/><td/><td/><td>0;1;2</td><td/></row>\r
+               <row><td>ISSetupPrerequisites</td><td>ISSetupPrerequisites</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSetupPrerequisites</td><td>Order</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISSetupType</td><td>Comments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>User Comments.</td></row>\r
+               <row><td>ISSetupType</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Longer descriptive text describing a visible feature item.</td></row>\r
+               <row><td>ISSetupType</td><td>Display</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Numeric sort order, used to force a specific display ordering.</td></row>\r
+               <row><td>ISSetupType</td><td>Display_Name</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>A string used to set the initial text contained within a control (if appropriate).</td></row>\r
+               <row><td>ISSetupType</td><td>ISSetupType</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular feature record.</td></row>\r
+               <row><td>ISSetupTypeFeatures</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Feature table.</td></row>\r
+               <row><td>ISSetupTypeFeatures</td><td>ISSetupType_</td><td>N</td><td/><td/><td>ISSetupType</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISSetupType table.</td></row>\r
+               <row><td>ISStorages</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Path to the file to stream into sub-storage</td></row>\r
+               <row><td>ISStorages</td><td>Name</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Name of the sub-storage key</td></row>\r
+               <row><td>ISString</td><td>Comment</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Comment</td></row>\r
+               <row><td>ISString</td><td>Encoded</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Encoding for multi-byte strings.</td></row>\r
+               <row><td>ISString</td><td>ISLanguage_</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>This is a foreign key to the ISLanguage table.</td></row>\r
+               <row><td>ISString</td><td>ISString</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>String id.</td></row>\r
+               <row><td>ISString</td><td>TimeStamp</td><td>Y</td><td/><td/><td/><td/><td>Time/Date</td><td/><td>Time Stamp. MSI's Time/Date column type is just an int, with bits packed in a certain order.</td></row>\r
+               <row><td>ISString</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>real string value.</td></row>\r
+               <row><td>ISTargetImage</td><td>Flags</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>relative order of the target image</td></row>\r
+               <row><td>ISTargetImage</td><td>IgnoreMissingFiles</td><td>N</td><td/><td/><td/><td/><td/><td/><td>If true, ignore missing source files when creating patch</td></row>\r
+               <row><td>ISTargetImage</td><td>MsiPath</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Path to the target image</td></row>\r
+               <row><td>ISTargetImage</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of the TargetImage</td></row>\r
+               <row><td>ISTargetImage</td><td>Order</td><td>N</td><td/><td/><td/><td/><td/><td/><td>relative order of the target image</td></row>\r
+               <row><td>ISTargetImage</td><td>UpgradedImage_</td><td>N</td><td/><td/><td>ISUpgradedImage</td><td>1</td><td>Text</td><td/><td>foreign key to the upgraded Image table</td></row>\r
+               <row><td>ISUpgradeMsiItem</td><td>ISAttributes</td><td>N</td><td/><td/><td/><td/><td/><td>0;1</td><td/></row>\r
+               <row><td>ISUpgradeMsiItem</td><td>ISReleaseFlags</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>ISUpgradeMsiItem</td><td>ObjectSetupPath</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The path to the setup you want to upgrade.</td></row>\r
+               <row><td>ISUpgradeMsiItem</td><td>UpgradeItem</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the Upgrade Item.</td></row>\r
+               <row><td>ISUpgradedImage</td><td>Family</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the image family</td></row>\r
+               <row><td>ISUpgradedImage</td><td>MsiPath</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Path to the upgraded image</td></row>\r
+               <row><td>ISUpgradedImage</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of the UpgradedImage</td></row>\r
+               <row><td>ISVirtualDirectory</td><td>Directory_</td><td>N</td><td/><td/><td>Directory</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Directory table.</td></row>\r
+               <row><td>ISVirtualDirectory</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Property name</td></row>\r
+               <row><td>ISVirtualDirectory</td><td>Value</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property value</td></row>\r
+               <row><td>ISVirtualFile</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into File  table.</td></row>\r
+               <row><td>ISVirtualFile</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Property name</td></row>\r
+               <row><td>ISVirtualFile</td><td>Value</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property value</td></row>\r
+               <row><td>ISVirtualPackage</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Property name</td></row>\r
+               <row><td>ISVirtualPackage</td><td>Value</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property value</td></row>\r
+               <row><td>ISVirtualRegistry</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Property name</td></row>\r
+               <row><td>ISVirtualRegistry</td><td>Registry_</td><td>N</td><td/><td/><td>Registry</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Registry table.</td></row>\r
+               <row><td>ISVirtualRegistry</td><td>Value</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property value</td></row>\r
+               <row><td>ISVirtualRelease</td><td>ISProductConfiguration_</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Foreign key into ISProductConfiguration table.</td></row>\r
+               <row><td>ISVirtualRelease</td><td>ISRelease_</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Foreign key into ISRelease table.</td></row>\r
+               <row><td>ISVirtualRelease</td><td>Name</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property name</td></row>\r
+               <row><td>ISVirtualRelease</td><td>Value</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property value</td></row>\r
+               <row><td>ISVirtualShortcut</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Property name</td></row>\r
+               <row><td>ISVirtualShortcut</td><td>Shortcut_</td><td>N</td><td/><td/><td>Shortcut</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Shortcut table.</td></row>\r
+               <row><td>ISVirtualShortcut</td><td>Value</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Property value</td></row>\r
+               <row><td>ISXmlElement</td><td>Content</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Element contents</td></row>\r
+               <row><td>ISXmlElement</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td>Number</td><td/><td>Internal XML element attributes</td></row>\r
+               <row><td>ISXmlElement</td><td>ISXmlElement</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized, internal token for Xml element</td></row>\r
+               <row><td>ISXmlElement</td><td>ISXmlElement_Parent</td><td>Y</td><td/><td/><td>ISXmlElement</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISXMLElement table.</td></row>\r
+               <row><td>ISXmlElement</td><td>ISXmlFile_</td><td>N</td><td/><td/><td>ISXmlFile</td><td>1</td><td>Identifier</td><td/><td>Foreign key into XmlFile table.</td></row>\r
+               <row><td>ISXmlElement</td><td>XPath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>XPath fragment including any operators</td></row>\r
+               <row><td>ISXmlElementAttrib</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td>Number</td><td/><td>Internal XML elementattib attributes</td></row>\r
+               <row><td>ISXmlElementAttrib</td><td>ISXmlElementAttrib</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized, internal token for Xml element attribute</td></row>\r
+               <row><td>ISXmlElementAttrib</td><td>ISXmlElement_</td><td>N</td><td/><td/><td>ISXmlElement</td><td>1</td><td>Identifier</td><td/><td>Foreign key into ISXMLElement table.</td></row>\r
+               <row><td>ISXmlElementAttrib</td><td>Name</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Localized attribute name</td></row>\r
+               <row><td>ISXmlElementAttrib</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Localized attribute value</td></row>\r
+               <row><td>ISXmlFile</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Component table.</td></row>\r
+               <row><td>ISXmlFile</td><td>Directory</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into Directory table.</td></row>\r
+               <row><td>ISXmlFile</td><td>Encoding</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>XML File Encoding</td></row>\r
+               <row><td>ISXmlFile</td><td>FileName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Localized XML file name</td></row>\r
+               <row><td>ISXmlFile</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td>Number</td><td/><td>Internal XML file attributes</td></row>\r
+               <row><td>ISXmlFile</td><td>ISXmlFile</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized,internal token for Xml file</td></row>\r
+               <row><td>ISXmlFile</td><td>SelectionNamespaces</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Selection namespaces</td></row>\r
+               <row><td>ISXmlLocator</td><td>Attribute</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>The name of an attribute within the XML element.</td></row>\r
+               <row><td>ISXmlLocator</td><td>Element</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>XPath query that will locate an element in an XML file.</td></row>\r
+               <row><td>ISXmlLocator</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td>0;1;2</td><td/></row>\r
+               <row><td>ISXmlLocator</td><td>Parent</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The parent file signature. It is also a foreign key in the Signature table.</td></row>\r
+               <row><td>ISXmlLocator</td><td>Signature_</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The Signature_ represents a unique file signature and is also the foreign key in the Signature,  RegLocator, IniLocator, ISXmlLocator, CompLocator and the DrLocator tables.</td></row>\r
+               <row><td>Icon</td><td>Data</td><td>Y</td><td/><td/><td/><td/><td>Binary</td><td/><td>Binary stream. The binary icon data in PE (.DLL or .EXE) or icon (.ICO) format.</td></row>\r
+               <row><td>Icon</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path to the ICO or EXE file.</td></row>\r
+               <row><td>Icon</td><td>ISIconIndex</td><td>Y</td><td>-32767</td><td>32767</td><td/><td/><td/><td/><td>Optional icon index to be extracted.</td></row>\r
+               <row><td>Icon</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key. Name of the icon file.</td></row>\r
+               <row><td>IniFile</td><td>Action</td><td>N</td><td/><td/><td/><td/><td/><td>0;1;3</td><td>The type of modification to be made, one of iifEnum</td></row>\r
+               <row><td>IniFile</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table referencing component that controls the installing of the .INI value.</td></row>\r
+               <row><td>IniFile</td><td>DirProperty</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into the Directory table denoting the directory where the .INI file is.</td></row>\r
+               <row><td>IniFile</td><td>FileName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The .INI file name in which to write the information</td></row>\r
+               <row><td>IniFile</td><td>IniFile</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token.</td></row>\r
+               <row><td>IniFile</td><td>Key</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The .INI file key below Section.</td></row>\r
+               <row><td>IniFile</td><td>Section</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The .INI file Section.</td></row>\r
+               <row><td>IniFile</td><td>Value</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The value to be written.</td></row>\r
+               <row><td>IniLocator</td><td>Field</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The field in the .INI line. If Field is null or 0 the entire line is read.</td></row>\r
+               <row><td>IniLocator</td><td>FileName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The .INI file name.</td></row>\r
+               <row><td>IniLocator</td><td>Key</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Key value (followed by an equals sign in INI file).</td></row>\r
+               <row><td>IniLocator</td><td>Section</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Section name within in file (within square brackets in INI file).</td></row>\r
+               <row><td>IniLocator</td><td>Signature_</td><td>N</td><td/><td/><td>Signature</td><td>1</td><td>Identifier</td><td/><td>The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table.</td></row>\r
+               <row><td>IniLocator</td><td>Type</td><td>Y</td><td>0</td><td>2</td><td/><td/><td/><td/><td>An integer value that determines if the .INI value read is a filename or a directory location or to be used as is w/o interpretation.</td></row>\r
+               <row><td>InstallExecuteSequence</td><td>Action</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of action to invoke, either in the engine or the handler DLL.</td></row>\r
+               <row><td>InstallExecuteSequence</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.</td></row>\r
+               <row><td>InstallExecuteSequence</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store MM Custom Action Types</td></row>\r
+               <row><td>InstallExecuteSequence</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments on this Sequence.</td></row>\r
+               <row><td>InstallExecuteSequence</td><td>Sequence</td><td>Y</td><td>-4</td><td>32767</td><td/><td/><td/><td/><td>Number that determines the sort order in which the actions are to be executed.  Leave blank to suppress action.</td></row>\r
+               <row><td>InstallShield</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of property, uppercase if settable by launcher or loader.</td></row>\r
+               <row><td>InstallShield</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>String value for property.</td></row>\r
+               <row><td>InstallUISequence</td><td>Action</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of action to invoke, either in the engine or the handler DLL.</td></row>\r
+               <row><td>InstallUISequence</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td>Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.</td></row>\r
+               <row><td>InstallUISequence</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store MM Custom Action Types</td></row>\r
+               <row><td>InstallUISequence</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments on this Sequence.</td></row>\r
+               <row><td>InstallUISequence</td><td>Sequence</td><td>Y</td><td>-4</td><td>32767</td><td/><td/><td/><td/><td>Number that determines the sort order in which the actions are to be executed.  Leave blank to suppress action.</td></row>\r
+               <row><td>IsolatedComponent</td><td>Component_Application</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Key to Component table item for application</td></row>\r
+               <row><td>IsolatedComponent</td><td>Component_Shared</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Key to Component table item to be isolated</td></row>\r
+               <row><td>LaunchCondition</td><td>Condition</td><td>N</td><td/><td/><td/><td/><td>Condition</td><td/><td>Expression which must evaluate to TRUE in order for install to commence.</td></row>\r
+               <row><td>LaunchCondition</td><td>Description</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Localizable text to display when condition fails and install must abort.</td></row>\r
+               <row><td>ListBox</td><td>Order</td><td>N</td><td>1</td><td>32767</td><td/><td/><td/><td/><td>A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.</td></row>\r
+               <row><td>ListBox</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A named property to be tied to this item. All the items tied to the same property become part of the same listbox.</td></row>\r
+               <row><td>ListBox</td><td>Text</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.</td></row>\r
+               <row><td>ListBox</td><td>Value</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The value string associated with this item. Selecting the line will set the associated property to this value.</td></row>\r
+               <row><td>ListView</td><td>Binary_</td><td>Y</td><td/><td/><td>Binary</td><td>1</td><td>Identifier</td><td/><td>The name of the icon to be displayed with the icon. The binary information is looked up from the Binary Table.</td></row>\r
+               <row><td>ListView</td><td>Order</td><td>N</td><td>1</td><td>32767</td><td/><td/><td/><td/><td>A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.</td></row>\r
+               <row><td>ListView</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A named property to be tied to this item. All the items tied to the same property become part of the same listview.</td></row>\r
+               <row><td>ListView</td><td>Text</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.</td></row>\r
+               <row><td>ListView</td><td>Value</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The value string associated with this item. Selecting the line will set the associated property to this value.</td></row>\r
+               <row><td>LockPermissions</td><td>Domain</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Domain name for user whose permissions are being set. (usually a property)</td></row>\r
+               <row><td>LockPermissions</td><td>LockObject</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into Registry or File table</td></row>\r
+               <row><td>LockPermissions</td><td>Permission</td><td>Y</td><td>-2147483647</td><td>2147483647</td><td/><td/><td/><td/><td>Permission Access mask.  Full Control = 268435456 (GENERIC_ALL = 0x10000000)</td></row>\r
+               <row><td>LockPermissions</td><td>Table</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td>Directory;File;Registry</td><td>Reference to another table name</td></row>\r
+               <row><td>LockPermissions</td><td>User</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>User for permissions to be set.  (usually a property)</td></row>\r
+               <row><td>MIME</td><td>CLSID</td><td>Y</td><td/><td/><td>Class</td><td>1</td><td>Guid</td><td/><td>Optional associated CLSID.</td></row>\r
+               <row><td>MIME</td><td>ContentType</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Primary key. Context identifier, typically "type/format".</td></row>\r
+               <row><td>MIME</td><td>Extension_</td><td>N</td><td/><td/><td>Extension</td><td>1</td><td>Text</td><td/><td>Optional associated extension (without dot)</td></row>\r
+               <row><td>Media</td><td>Cabinet</td><td>Y</td><td/><td/><td/><td/><td>Cabinet</td><td/><td>If some or all of the files stored on the media are compressed in a cabinet, the name of that cabinet.</td></row>\r
+               <row><td>Media</td><td>DiskId</td><td>N</td><td>1</td><td>32767</td><td/><td/><td/><td/><td>Primary key, integer to determine sort order for table.</td></row>\r
+               <row><td>Media</td><td>DiskPrompt</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Disk name: the visible text actually printed on the disk.  This will be used to prompt the user when this disk needs to be inserted.</td></row>\r
+               <row><td>Media</td><td>LastSequence</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>File sequence number for the last file for this media.</td></row>\r
+               <row><td>Media</td><td>Source</td><td>Y</td><td/><td/><td/><td/><td>Property</td><td/><td>The property defining the location of the cabinet file.</td></row>\r
+               <row><td>Media</td><td>VolumeLabel</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The label attributed to the volume.</td></row>\r
+               <row><td>MoveFile</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>If this component is not "selected" for installation or removal, no action will be taken on the associated MoveFile entry</td></row>\r
+               <row><td>MoveFile</td><td>DestFolder</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of a property whose value is assumed to resolve to the full path to the destination directory</td></row>\r
+               <row><td>MoveFile</td><td>DestName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Name to be given to the original file after it is moved or copied.  If blank, the destination file will be given the same name as the source file</td></row>\r
+               <row><td>MoveFile</td><td>FileKey</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key that uniquely identifies a particular MoveFile record</td></row>\r
+               <row><td>MoveFile</td><td>Options</td><td>N</td><td>0</td><td>1</td><td/><td/><td/><td/><td>Integer value specifying the MoveFile operating mode, one of imfoEnum</td></row>\r
+               <row><td>MoveFile</td><td>SourceFolder</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of a property whose value is assumed to resolve to the full path to the source directory</td></row>\r
+               <row><td>MoveFile</td><td>SourceName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the source file(s) to be moved or copied.  Can contain the '*' or '?' wildcards.</td></row>\r
+               <row><td>MsiAssembly</td><td>Attributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Assembly attributes</td></row>\r
+               <row><td>MsiAssembly</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Component table.</td></row>\r
+               <row><td>MsiAssembly</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Feature table.</td></row>\r
+               <row><td>MsiAssembly</td><td>File_Application</td><td>Y</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into File table, denoting the application context for private assemblies. Null for global assemblies.</td></row>\r
+               <row><td>MsiAssembly</td><td>File_Manifest</td><td>Y</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the File table denoting the manifest file for the assembly.</td></row>\r
+               <row><td>MsiAssemblyName</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into Component table.</td></row>\r
+               <row><td>MsiAssemblyName</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name part of the name-value pairs for the assembly name.</td></row>\r
+               <row><td>MsiAssemblyName</td><td>Value</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The value part of the name-value pairs for the assembly name.</td></row>\r
+               <row><td>MsiDigitalCertificate</td><td>CertData</td><td>N</td><td/><td/><td/><td/><td>Binary</td><td/><td>A certificate context blob for a signer certificate</td></row>\r
+               <row><td>MsiDigitalCertificate</td><td>DigitalCertificate</td><td>N</td><td/><td/><td>MsiPackageCertificate</td><td>2</td><td>Identifier</td><td/><td>A unique identifier for the row</td></row>\r
+               <row><td>MsiDigitalSignature</td><td>DigitalCertificate_</td><td>N</td><td/><td/><td>MsiDigitalCertificate</td><td>1</td><td>Identifier</td><td/><td>Foreign key to MsiDigitalCertificate table identifying the signer certificate</td></row>\r
+               <row><td>MsiDigitalSignature</td><td>Hash</td><td>Y</td><td/><td/><td/><td/><td>Binary</td><td/><td>The encoded hash blob from the digital signature</td></row>\r
+               <row><td>MsiDigitalSignature</td><td>SignObject</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Foreign key to Media table</td></row>\r
+               <row><td>MsiDigitalSignature</td><td>Table</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Reference to another table name (only Media table is supported)</td></row>\r
+               <row><td>MsiDriverPackages</td><td>Component</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Primary key used to identify a particular component record.</td></row>\r
+               <row><td>MsiDriverPackages</td><td>Flags</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Driver package flags</td></row>\r
+               <row><td>MsiDriverPackages</td><td>ReferenceComponents</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>MsiDriverPackages</td><td>Sequence</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>Installation sequence number</td></row>\r
+               <row><td>MsiEmbeddedChainer</td><td>CommandLine</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td/></row>\r
+               <row><td>MsiEmbeddedChainer</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Condition</td><td/><td/></row>\r
+               <row><td>MsiEmbeddedChainer</td><td>MsiEmbeddedChainer</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td/></row>\r
+               <row><td>MsiEmbeddedChainer</td><td>Source</td><td>N</td><td/><td/><td/><td/><td>CustomSource</td><td/><td/></row>\r
+               <row><td>MsiEmbeddedChainer</td><td>Type</td><td>Y</td><td/><td/><td/><td/><td>Integer</td><td>2;18;50</td><td/></row>\r
+               <row><td>MsiEmbeddedUI</td><td>Attributes</td><td>N</td><td>0</td><td>3</td><td/><td/><td>Integer</td><td/><td>Information about the data in the Data column.</td></row>\r
+               <row><td>MsiEmbeddedUI</td><td>Data</td><td>Y</td><td/><td/><td/><td/><td>Binary</td><td/><td>This column contains binary information.</td></row>\r
+               <row><td>MsiEmbeddedUI</td><td>FileName</td><td>N</td><td/><td/><td/><td/><td>Filename</td><td/><td>The name of the file that receives the binary information in the Data column.</td></row>\r
+               <row><td>MsiEmbeddedUI</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>MsiEmbeddedUI</td><td>MessageFilter</td><td>Y</td><td>0</td><td>234913791</td><td/><td/><td>Integer</td><td/><td>Specifies the types of messages that are sent to the user interface DLL. This column is only relevant for rows with the msidbEmbeddedUI attribute.</td></row>\r
+               <row><td>MsiEmbeddedUI</td><td>MsiEmbeddedUI</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The primary key for the table.</td></row>\r
+               <row><td>MsiFileHash</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Primary key, foreign key into File table referencing file with this hash</td></row>\r
+               <row><td>MsiFileHash</td><td>HashPart1</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Size of file in bytes (long integer).</td></row>\r
+               <row><td>MsiFileHash</td><td>HashPart2</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Size of file in bytes (long integer).</td></row>\r
+               <row><td>MsiFileHash</td><td>HashPart3</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Size of file in bytes (long integer).</td></row>\r
+               <row><td>MsiFileHash</td><td>HashPart4</td><td>N</td><td/><td/><td/><td/><td/><td/><td>Size of file in bytes (long integer).</td></row>\r
+               <row><td>MsiFileHash</td><td>Options</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Various options and attributes for this hash.</td></row>\r
+               <row><td>MsiLockPermissionsEx</td><td>Condition</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Expression which must evaluate to TRUE in order for this set of permissions to be applied</td></row>\r
+               <row><td>MsiLockPermissionsEx</td><td>LockObject</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into Registry, File, CreateFolder, or ServiceInstall table</td></row>\r
+               <row><td>MsiLockPermissionsEx</td><td>MsiLockPermissionsEx</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token</td></row>\r
+               <row><td>MsiLockPermissionsEx</td><td>SDDLText</td><td>N</td><td/><td/><td/><td/><td>FormattedSDDLText</td><td/><td>String to indicate permissions to be applied to the LockObject</td></row>\r
+               <row><td>MsiLockPermissionsEx</td><td>Table</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td>CreateFolder;File;Registry;ServiceInstall</td><td>Reference to another table name</td></row>\r
+               <row><td>MsiPackageCertificate</td><td>DigitalCertificate_</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A foreign key to the digital certificate table</td></row>\r
+               <row><td>MsiPackageCertificate</td><td>PackageCertificate</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A unique identifier for the row</td></row>\r
+               <row><td>MsiPatchCertificate</td><td>DigitalCertificate_</td><td>N</td><td/><td/><td>MsiDigitalCertificate</td><td>1</td><td>Identifier</td><td/><td>A foreign key to the digital certificate table</td></row>\r
+               <row><td>MsiPatchCertificate</td><td>PatchCertificate</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A unique identifier for the row</td></row>\r
+               <row><td>MsiPatchMetadata</td><td>Company</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Optional company name</td></row>\r
+               <row><td>MsiPatchMetadata</td><td>PatchConfiguration_</td><td>N</td><td/><td/><td>ISPatchConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key to the ISPatchConfiguration table</td></row>\r
+               <row><td>MsiPatchMetadata</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the metadata</td></row>\r
+               <row><td>MsiPatchMetadata</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Value of the metadata</td></row>\r
+               <row><td>MsiPatchOldAssemblyFile</td><td>Assembly_</td><td>Y</td><td/><td/><td>MsiPatchOldAssemblyName</td><td>1</td><td/><td/><td/></row>\r
+               <row><td>MsiPatchOldAssemblyFile</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td/><td/><td/></row>\r
+               <row><td>MsiPatchOldAssemblyName</td><td>Assembly</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>MsiPatchOldAssemblyName</td><td>Name</td><td>N</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>MsiPatchOldAssemblyName</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td/><td/><td/></row>\r
+               <row><td>MsiPatchSequence</td><td>PatchConfiguration_</td><td>N</td><td/><td/><td>ISPatchConfiguration</td><td>1</td><td>Text</td><td/><td>Foreign key to the patch configuration table</td></row>\r
+               <row><td>MsiPatchSequence</td><td>PatchFamily</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the family to which this patch belongs</td></row>\r
+               <row><td>MsiPatchSequence</td><td>Sequence</td><td>N</td><td/><td/><td/><td/><td>Version</td><td/><td>The version of this patch in this family</td></row>\r
+               <row><td>MsiPatchSequence</td><td>Supersede</td><td>N</td><td/><td/><td/><td/><td>Integer</td><td/><td>Supersede</td></row>\r
+               <row><td>MsiPatchSequence</td><td>Target</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Target product codes for this patch family</td></row>\r
+               <row><td>MsiServiceConfig</td><td>Argument</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Argument(s) for service configuration. Value depends on the content of the ConfigType field</td></row>\r
+               <row><td>MsiServiceConfig</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Component Table that controls the configuration of the service</td></row>\r
+               <row><td>MsiServiceConfig</td><td>ConfigType</td><td>N</td><td>-2147483647</td><td>2147483647</td><td/><td/><td/><td/><td>Service Configuration Option</td></row>\r
+               <row><td>MsiServiceConfig</td><td>Event</td><td>N</td><td>0</td><td>7</td><td/><td/><td/><td/><td>Bit field:   0x1 = Install, 0x2 = Uninstall, 0x4 = Reinstall</td></row>\r
+               <row><td>MsiServiceConfig</td><td>MsiServiceConfig</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token.</td></row>\r
+               <row><td>MsiServiceConfig</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Name of a service. /, \, comma and space are invalid</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>Actions</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>A list of integer actions separated by [~] delimiters: 0 = SC_ACTION_NONE, 1 = SC_ACTION_RESTART, 2 = SC_ACTION_REBOOT, 3 = SC_ACTION_RUN_COMMAND. Terminate with [~][~]</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>Command</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Command line of the process to CreateProcess function to execute</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Component Table that controls the configuration of the service</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>DelayActions</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>A list of delays (time in milli-seconds), separated by [~] delmiters, to wait before taking the corresponding Action. Terminate with [~][~]</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>Event</td><td>N</td><td>0</td><td>7</td><td/><td/><td/><td/><td>Bit field:   0x1 = Install, 0x2 = Uninstall, 0x4 = Reinstall</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>MsiServiceConfigFailureActions</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Name of a service. /, \, comma and space are invalid</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>RebootMessage</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Message to be broadcast to server users before rebooting</td></row>\r
+               <row><td>MsiServiceConfigFailureActions</td><td>ResetPeriod</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>Time in seconds after which to reset the failure count to zero. Leave blank if it should never be reset</td></row>\r
+               <row><td>MsiShortcutProperty</td><td>MsiShortcutProperty</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token</td></row>\r
+               <row><td>MsiShortcutProperty</td><td>PropVariantValue</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>String representation of the value in the property</td></row>\r
+               <row><td>MsiShortcutProperty</td><td>PropertyKey</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Canonical string representation of the Property Key being set</td></row>\r
+               <row><td>MsiShortcutProperty</td><td>Shortcut_</td><td>N</td><td/><td/><td>Shortcut</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Shortcut table</td></row>\r
+               <row><td>ODBCAttribute</td><td>Attribute</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of ODBC driver attribute</td></row>\r
+               <row><td>ODBCAttribute</td><td>Driver_</td><td>N</td><td/><td/><td>ODBCDriver</td><td>1</td><td>Identifier</td><td/><td>Reference to ODBC driver in ODBCDriver table</td></row>\r
+               <row><td>ODBCAttribute</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Value for ODBC driver attribute</td></row>\r
+               <row><td>ODBCDataSource</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Reference to associated component</td></row>\r
+               <row><td>ODBCDataSource</td><td>DataSource</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized.internal token for data source</td></row>\r
+               <row><td>ODBCDataSource</td><td>Description</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Text used as registered name for data source</td></row>\r
+               <row><td>ODBCDataSource</td><td>DriverDescription</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Reference to driver description, may be existing driver</td></row>\r
+               <row><td>ODBCDataSource</td><td>Registration</td><td>N</td><td>0</td><td>1</td><td/><td/><td/><td/><td>Registration option: 0=machine, 1=user, others t.b.d.</td></row>\r
+               <row><td>ODBCDriver</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Reference to associated component</td></row>\r
+               <row><td>ODBCDriver</td><td>Description</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Text used as registered name for driver, non-localized</td></row>\r
+               <row><td>ODBCDriver</td><td>Driver</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized.internal token for driver</td></row>\r
+               <row><td>ODBCDriver</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Reference to key driver file</td></row>\r
+               <row><td>ODBCDriver</td><td>File_Setup</td><td>Y</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Optional reference to key driver setup DLL</td></row>\r
+               <row><td>ODBCSourceAttribute</td><td>Attribute</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of ODBC data source attribute</td></row>\r
+               <row><td>ODBCSourceAttribute</td><td>DataSource_</td><td>N</td><td/><td/><td>ODBCDataSource</td><td>1</td><td>Identifier</td><td/><td>Reference to ODBC data source in ODBCDataSource table</td></row>\r
+               <row><td>ODBCSourceAttribute</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Value for ODBC data source attribute</td></row>\r
+               <row><td>ODBCTranslator</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Reference to associated component</td></row>\r
+               <row><td>ODBCTranslator</td><td>Description</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>Text used as registered name for translator</td></row>\r
+               <row><td>ODBCTranslator</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Reference to key translator file</td></row>\r
+               <row><td>ODBCTranslator</td><td>File_Setup</td><td>Y</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Optional reference to key translator setup DLL</td></row>\r
+               <row><td>ODBCTranslator</td><td>Translator</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized.internal token for translator</td></row>\r
+               <row><td>Patch</td><td>Attributes</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Integer containing bit flags representing patch attributes</td></row>\r
+               <row><td>Patch</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Primary key, non-localized token, foreign key to File table, must match identifier in cabinet.</td></row>\r
+               <row><td>Patch</td><td>Header</td><td>Y</td><td/><td/><td/><td/><td>Binary</td><td/><td>Binary stream. The patch header, used for patch validation.</td></row>\r
+               <row><td>Patch</td><td>ISBuildSourcePath</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Full path to patch header.</td></row>\r
+               <row><td>Patch</td><td>PatchSize</td><td>N</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>Size of patch in bytes (long integer).</td></row>\r
+               <row><td>Patch</td><td>Sequence</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Primary key, sequence with respect to the media images; order must track cabinet order.</td></row>\r
+               <row><td>Patch</td><td>StreamRef_</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>External key into the MsiPatchHeaders table specifying the row that contains the patch header stream.</td></row>\r
+               <row><td>PatchPackage</td><td>Media_</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Foreign key to DiskId column of Media table. Indicates the disk containing the patch package.</td></row>\r
+               <row><td>PatchPackage</td><td>PatchId</td><td>N</td><td/><td/><td/><td/><td>Guid</td><td/><td>A unique string GUID representing this patch.</td></row>\r
+               <row><td>ProgId</td><td>Class_</td><td>Y</td><td/><td/><td>Class</td><td>1</td><td>Guid</td><td/><td>The CLSID of an OLE factory corresponding to the ProgId.</td></row>\r
+               <row><td>ProgId</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Localized description for the Program identifier.</td></row>\r
+               <row><td>ProgId</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store Installshield custom properties of a component, like ExtractIcon, etc.</td></row>\r
+               <row><td>ProgId</td><td>IconIndex</td><td>Y</td><td>-32767</td><td>32767</td><td/><td/><td/><td/><td>Optional icon index.</td></row>\r
+               <row><td>ProgId</td><td>Icon_</td><td>Y</td><td/><td/><td>Icon</td><td>1</td><td>Identifier</td><td/><td>Optional foreign key into the Icon Table, specifying the icon file associated with this ProgId. Will be written under the DefaultIcon key.</td></row>\r
+               <row><td>ProgId</td><td>ProgId</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The Program Identifier. Primary key.</td></row>\r
+               <row><td>ProgId</td><td>ProgId_Parent</td><td>Y</td><td/><td/><td>ProgId</td><td>1</td><td>Text</td><td/><td>The Parent Program Identifier. If specified, the ProgId column becomes a version independent prog id.</td></row>\r
+               <row><td>Property</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>User Comments.</td></row>\r
+               <row><td>Property</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of property, uppercase if settable by launcher or loader.</td></row>\r
+               <row><td>Property</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>String value for property.</td></row>\r
+               <row><td>PublishComponent</td><td>AppData</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>This is localisable Application specific data that can be associated with a Qualified Component.</td></row>\r
+               <row><td>PublishComponent</td><td>ComponentId</td><td>N</td><td/><td/><td/><td/><td>Guid</td><td/><td>A string GUID that represents the component id that will be requested by the alien product.</td></row>\r
+               <row><td>PublishComponent</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table.</td></row>\r
+               <row><td>PublishComponent</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Feature table.</td></row>\r
+               <row><td>PublishComponent</td><td>Qualifier</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>This is defined only when the ComponentId column is an Qualified Component Id. This is the Qualifier for ProvideComponentIndirect.</td></row>\r
+               <row><td>RadioButton</td><td>Height</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The height of the button.</td></row>\r
+               <row><td>RadioButton</td><td>Help</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The help strings used with the button. The text is optional.</td></row>\r
+               <row><td>RadioButton</td><td>ISControlId</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>A number used to represent the control ID of the Control, Used in Dialog export</td></row>\r
+               <row><td>RadioButton</td><td>Order</td><td>N</td><td>1</td><td>32767</td><td/><td/><td/><td/><td>A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.</td></row>\r
+               <row><td>RadioButton</td><td>Property</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A named property to be tied to this radio button. All the buttons tied to the same property become part of the same group.</td></row>\r
+               <row><td>RadioButton</td><td>Text</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The visible title to be assigned to the radio button.</td></row>\r
+               <row><td>RadioButton</td><td>Value</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The value string associated with this button. Selecting the button will set the associated property to this value.</td></row>\r
+               <row><td>RadioButton</td><td>Width</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The width of the button.</td></row>\r
+               <row><td>RadioButton</td><td>X</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The horizontal coordinate of the upper left corner of the bounding rectangle of the radio button.</td></row>\r
+               <row><td>RadioButton</td><td>Y</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The vertical coordinate of the upper left corner of the bounding rectangle of the radio button.</td></row>\r
+               <row><td>RegLocator</td><td>Key</td><td>N</td><td/><td/><td/><td/><td>RegPath</td><td/><td>The key for the registry value.</td></row>\r
+               <row><td>RegLocator</td><td>Name</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The registry value name.</td></row>\r
+               <row><td>RegLocator</td><td>Root</td><td>N</td><td>0</td><td>3</td><td/><td/><td/><td/><td>The predefined root key for the registry value, one of rrkEnum.</td></row>\r
+               <row><td>RegLocator</td><td>Signature_</td><td>N</td><td/><td/><td>Signature</td><td>1</td><td>Identifier</td><td/><td>The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table. If the type is 0, the registry values refers a directory, and _Signature is not a foreign key.</td></row>\r
+               <row><td>RegLocator</td><td>Type</td><td>Y</td><td>0</td><td>18</td><td/><td/><td/><td/><td>An integer value that determines if the registry value is a filename or a directory location or to be used as is w/o interpretation.</td></row>\r
+               <row><td>Registry</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table referencing component that controls the installing of the registry value.</td></row>\r
+               <row><td>Registry</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store Installshield custom properties of a registry item.  Currently the only one is Automatic.</td></row>\r
+               <row><td>Registry</td><td>Key</td><td>N</td><td/><td/><td/><td/><td>RegPath</td><td/><td>The key for the registry value.</td></row>\r
+               <row><td>Registry</td><td>Name</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The registry value name.</td></row>\r
+               <row><td>Registry</td><td>Registry</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token.</td></row>\r
+               <row><td>Registry</td><td>Root</td><td>N</td><td>-1</td><td>3</td><td/><td/><td/><td/><td>The predefined root key for the registry value, one of rrkEnum.</td></row>\r
+               <row><td>Registry</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The registry value.</td></row>\r
+               <row><td>RemoveFile</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key referencing Component that controls the file to be removed.</td></row>\r
+               <row><td>RemoveFile</td><td>DirProperty</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of a property whose value is assumed to resolve to the full pathname to the folder of the file to be removed.</td></row>\r
+               <row><td>RemoveFile</td><td>FileKey</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key used to identify a particular file entry</td></row>\r
+               <row><td>RemoveFile</td><td>FileName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Name of the file to be removed.</td></row>\r
+               <row><td>RemoveFile</td><td>InstallMode</td><td>N</td><td/><td/><td/><td/><td/><td>1;2;3</td><td>Installation option, one of iimEnum.</td></row>\r
+               <row><td>RemoveIniFile</td><td>Action</td><td>N</td><td/><td/><td/><td/><td/><td>2;4</td><td>The type of modification to be made, one of iifEnum.</td></row>\r
+               <row><td>RemoveIniFile</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table referencing component that controls the deletion of the .INI value.</td></row>\r
+               <row><td>RemoveIniFile</td><td>DirProperty</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Foreign key into the Directory table denoting the directory where the .INI file is.</td></row>\r
+               <row><td>RemoveIniFile</td><td>FileName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The .INI file name in which to delete the information</td></row>\r
+               <row><td>RemoveIniFile</td><td>Key</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The .INI file key below Section.</td></row>\r
+               <row><td>RemoveIniFile</td><td>RemoveIniFile</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token.</td></row>\r
+               <row><td>RemoveIniFile</td><td>Section</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The .INI file Section.</td></row>\r
+               <row><td>RemoveIniFile</td><td>Value</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The value to be deleted. The value is required when Action is iifIniRemoveTag</td></row>\r
+               <row><td>RemoveRegistry</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table referencing component that controls the deletion of the registry value.</td></row>\r
+               <row><td>RemoveRegistry</td><td>Key</td><td>N</td><td/><td/><td/><td/><td>RegPath</td><td/><td>The key for the registry value.</td></row>\r
+               <row><td>RemoveRegistry</td><td>Name</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The registry value name.</td></row>\r
+               <row><td>RemoveRegistry</td><td>RemoveRegistry</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token.</td></row>\r
+               <row><td>RemoveRegistry</td><td>Root</td><td>N</td><td>-1</td><td>3</td><td/><td/><td/><td/><td>The predefined root key for the registry value, one of rrkEnum</td></row>\r
+               <row><td>ReserveCost</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Reserve a specified amount of space if this component is to be installed.</td></row>\r
+               <row><td>ReserveCost</td><td>ReserveFolder</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of a property whose value is assumed to resolve to the full path to the destination directory</td></row>\r
+               <row><td>ReserveCost</td><td>ReserveKey</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key that uniquely identifies a particular ReserveCost record</td></row>\r
+               <row><td>ReserveCost</td><td>ReserveLocal</td><td>N</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>Disk space to reserve if linked component is installed locally.</td></row>\r
+               <row><td>ReserveCost</td><td>ReserveSource</td><td>N</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>Disk space to reserve if linked component is installed to run from the source location.</td></row>\r
+               <row><td>SFPCatalog</td><td>Catalog</td><td>Y</td><td/><td/><td/><td/><td>Binary</td><td/><td>SFP Catalog</td></row>\r
+               <row><td>SFPCatalog</td><td>Dependency</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Parent catalog - only used by SFP</td></row>\r
+               <row><td>SFPCatalog</td><td>SFPCatalog</td><td>N</td><td/><td/><td/><td/><td>Filename</td><td/><td>File name for the catalog.</td></row>\r
+               <row><td>SelfReg</td><td>Cost</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The cost of registering the module.</td></row>\r
+               <row><td>SelfReg</td><td>File_</td><td>N</td><td/><td/><td>File</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the File table denoting the module that needs to be registered.</td></row>\r
+               <row><td>ServiceControl</td><td>Arguments</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Arguments for the service.  Separate by [~].</td></row>\r
+               <row><td>ServiceControl</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Component Table that controls the startup of the service</td></row>\r
+               <row><td>ServiceControl</td><td>Event</td><td>N</td><td>0</td><td>187</td><td/><td/><td/><td/><td>Bit field:  Install:  0x1 = Start, 0x2 = Stop, 0x8 = Delete, Uninstall: 0x10 = Start, 0x20 = Stop, 0x80 = Delete</td></row>\r
+               <row><td>ServiceControl</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Name of a service. /, \, comma and space are invalid</td></row>\r
+               <row><td>ServiceControl</td><td>ServiceControl</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token.</td></row>\r
+               <row><td>ServiceControl</td><td>Wait</td><td>Y</td><td>0</td><td>1</td><td/><td/><td/><td/><td>Boolean for whether to wait for the service to fully start</td></row>\r
+               <row><td>ServiceInstall</td><td>Arguments</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Arguments to include in every start of the service, passed to WinMain</td></row>\r
+               <row><td>ServiceInstall</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Component Table that controls the startup of the service</td></row>\r
+               <row><td>ServiceInstall</td><td>Dependencies</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Other services this depends on to start.  Separate by [~], and end with [~][~]</td></row>\r
+               <row><td>ServiceInstall</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Description of service.</td></row>\r
+               <row><td>ServiceInstall</td><td>DisplayName</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>External Name of the Service</td></row>\r
+               <row><td>ServiceInstall</td><td>ErrorControl</td><td>N</td><td>-2147483647</td><td>2147483647</td><td/><td/><td/><td/><td>Severity of error if service fails to start</td></row>\r
+               <row><td>ServiceInstall</td><td>LoadOrderGroup</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>LoadOrderGroup</td></row>\r
+               <row><td>ServiceInstall</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Internal Name of the Service</td></row>\r
+               <row><td>ServiceInstall</td><td>Password</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>password to run service with.  (with StartName)</td></row>\r
+               <row><td>ServiceInstall</td><td>ServiceInstall</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token.</td></row>\r
+               <row><td>ServiceInstall</td><td>ServiceType</td><td>N</td><td>-2147483647</td><td>2147483647</td><td/><td/><td/><td/><td>Type of the service</td></row>\r
+               <row><td>ServiceInstall</td><td>StartName</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>User or object name to run service as</td></row>\r
+               <row><td>ServiceInstall</td><td>StartType</td><td>N</td><td>0</td><td>4</td><td/><td/><td/><td/><td>Type of the service</td></row>\r
+               <row><td>Shortcut</td><td>Arguments</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The command-line arguments for the shortcut.</td></row>\r
+               <row><td>Shortcut</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Component table denoting the component whose selection gates the the shortcut creation/deletion.</td></row>\r
+               <row><td>Shortcut</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The description for the shortcut.</td></row>\r
+               <row><td>Shortcut</td><td>DescriptionResourceDLL</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>This field contains a Formatted string value for the full path to the language neutral file that contains the MUI manifest.</td></row>\r
+               <row><td>Shortcut</td><td>DescriptionResourceId</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The description name index for the shortcut.</td></row>\r
+               <row><td>Shortcut</td><td>Directory_</td><td>N</td><td/><td/><td>Directory</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the Directory table denoting the directory where the shortcut file is created.</td></row>\r
+               <row><td>Shortcut</td><td>DisplayResourceDLL</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>This field contains a Formatted string value for the full path to the language neutral file that contains the MUI manifest.</td></row>\r
+               <row><td>Shortcut</td><td>DisplayResourceId</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The display name index for the shortcut.</td></row>\r
+               <row><td>Shortcut</td><td>Hotkey</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The hotkey for the shortcut. It has the virtual-key code for the key in the low-order byte, and the modifier flags in the high-order byte.</td></row>\r
+               <row><td>Shortcut</td><td>ISAttributes</td><td>Y</td><td/><td/><td/><td/><td/><td/><td>This is used to store Installshield custom properties of a shortcut.  Mainly used in pro project types.</td></row>\r
+               <row><td>Shortcut</td><td>ISComments</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Author’s comments on this Shortcut.</td></row>\r
+               <row><td>Shortcut</td><td>ISShortcutName</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>A non-unique name for the shortcut.  Mainly used by pro pro project types.</td></row>\r
+               <row><td>Shortcut</td><td>IconIndex</td><td>Y</td><td>-32767</td><td>32767</td><td/><td/><td/><td/><td>The icon index for the shortcut.</td></row>\r
+               <row><td>Shortcut</td><td>Icon_</td><td>Y</td><td/><td/><td>Icon</td><td>1</td><td>Identifier</td><td/><td>Foreign key into the File table denoting the external icon file for the shortcut.</td></row>\r
+               <row><td>Shortcut</td><td>Name</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the shortcut to be created.</td></row>\r
+               <row><td>Shortcut</td><td>Shortcut</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Primary key, non-localized token.</td></row>\r
+               <row><td>Shortcut</td><td>ShowCmd</td><td>Y</td><td/><td/><td/><td/><td/><td>1;3;7</td><td>The show command for the application window.The following values may be used.</td></row>\r
+               <row><td>Shortcut</td><td>Target</td><td>N</td><td/><td/><td/><td/><td>Shortcut</td><td/><td>The shortcut target. This is usually a property that is expanded to a file or a folder that the shortcut points to.</td></row>\r
+               <row><td>Shortcut</td><td>WkDir</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of property defining location of working directory.</td></row>\r
+               <row><td>Signature</td><td>FileName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The name of the file. This may contain a "short name|long name" pair.</td></row>\r
+               <row><td>Signature</td><td>Languages</td><td>Y</td><td/><td/><td/><td/><td>Language</td><td/><td>The languages supported by the file.</td></row>\r
+               <row><td>Signature</td><td>MaxDate</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>The maximum creation date of the file.</td></row>\r
+               <row><td>Signature</td><td>MaxSize</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>The maximum size of the file.</td></row>\r
+               <row><td>Signature</td><td>MaxVersion</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The maximum version of the file.</td></row>\r
+               <row><td>Signature</td><td>MinDate</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>The minimum creation date of the file.</td></row>\r
+               <row><td>Signature</td><td>MinSize</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>The minimum size of the file.</td></row>\r
+               <row><td>Signature</td><td>MinVersion</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The minimum version of the file.</td></row>\r
+               <row><td>Signature</td><td>Signature</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>The table key. The Signature represents a unique file signature.</td></row>\r
+               <row><td>TextStyle</td><td>Color</td><td>Y</td><td>0</td><td>16777215</td><td/><td/><td/><td/><td>A long integer indicating the color of the string in the RGB format (Red, Green, Blue each 0-255, RGB = R + 256*G + 256^2*B).</td></row>\r
+               <row><td>TextStyle</td><td>FaceName</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>A string indicating the name of the font used. Required. The string must be at most 31 characters long.</td></row>\r
+               <row><td>TextStyle</td><td>Size</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The size of the font used. This size is given in our units (1/12 of the system font height). Assuming that the system font is set to 12 point size, this is equivalent to the point size.</td></row>\r
+               <row><td>TextStyle</td><td>StyleBits</td><td>Y</td><td>0</td><td>15</td><td/><td/><td/><td/><td>A combination of style bits.</td></row>\r
+               <row><td>TextStyle</td><td>TextStyle</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of the style. The primary key of this table. This name is embedded in the texts to indicate a style change.</td></row>\r
+               <row><td>TypeLib</td><td>Component_</td><td>N</td><td/><td/><td>Component</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.</td></row>\r
+               <row><td>TypeLib</td><td>Cost</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>The cost associated with the registration of the typelib. This column is currently optional.</td></row>\r
+               <row><td>TypeLib</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td/></row>\r
+               <row><td>TypeLib</td><td>Directory_</td><td>Y</td><td/><td/><td>Directory</td><td>1</td><td>Identifier</td><td/><td>Optional. The foreign key into the Directory table denoting the path to the help file for the type library.</td></row>\r
+               <row><td>TypeLib</td><td>Feature_</td><td>N</td><td/><td/><td>Feature</td><td>1</td><td>Identifier</td><td/><td>Required foreign key into the Feature Table, specifying the feature to validate or install in order for the type library to be operational.</td></row>\r
+               <row><td>TypeLib</td><td>Language</td><td>N</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>The language of the library.</td></row>\r
+               <row><td>TypeLib</td><td>LibID</td><td>N</td><td/><td/><td/><td/><td>Guid</td><td/><td>The GUID that represents the library.</td></row>\r
+               <row><td>TypeLib</td><td>Version</td><td>Y</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>The version of the library. The major version is in the upper 8 bits of the short integer. The minor version is in the lower 8 bits.</td></row>\r
+               <row><td>UIText</td><td>Key</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>A unique key that identifies the particular string.</td></row>\r
+               <row><td>UIText</td><td>Text</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The localized version of the string.</td></row>\r
+               <row><td>Upgrade</td><td>ActionProperty</td><td>N</td><td/><td/><td/><td/><td>UpperCase</td><td/><td>The property to set when a product in this set is found.</td></row>\r
+               <row><td>Upgrade</td><td>Attributes</td><td>N</td><td>0</td><td>2147483647</td><td/><td/><td/><td/><td>The attributes of this product set.</td></row>\r
+               <row><td>Upgrade</td><td>ISDisplayName</td><td>Y</td><td/><td/><td>ISUpgradeMsiItem</td><td>1</td><td/><td/><td/></row>\r
+               <row><td>Upgrade</td><td>Language</td><td>Y</td><td/><td/><td/><td/><td>Language</td><td/><td>A comma-separated list of languages for either products in this set or products not in this set.</td></row>\r
+               <row><td>Upgrade</td><td>Remove</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The list of features to remove when uninstalling a product from this set.  The default is "ALL".</td></row>\r
+               <row><td>Upgrade</td><td>UpgradeCode</td><td>N</td><td/><td/><td/><td/><td>Guid</td><td/><td>The UpgradeCode GUID belonging to the products in this set.</td></row>\r
+               <row><td>Upgrade</td><td>VersionMax</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The maximum ProductVersion of the products in this set.  The set may or may not include products with this particular version.</td></row>\r
+               <row><td>Upgrade</td><td>VersionMin</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>The minimum ProductVersion of the products in this set.  The set may or may not include products with this particular version.</td></row>\r
+               <row><td>Verb</td><td>Argument</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>Optional value for the command arguments.</td></row>\r
+               <row><td>Verb</td><td>Command</td><td>Y</td><td/><td/><td/><td/><td>Formatted</td><td/><td>The command text.</td></row>\r
+               <row><td>Verb</td><td>Extension_</td><td>N</td><td/><td/><td>Extension</td><td>1</td><td>Text</td><td/><td>The extension associated with the table row.</td></row>\r
+               <row><td>Verb</td><td>Sequence</td><td>Y</td><td>0</td><td>32767</td><td/><td/><td/><td/><td>Order within the verbs for a particular extension. Also used simply to specify the default verb.</td></row>\r
+               <row><td>Verb</td><td>Verb</td><td>N</td><td/><td/><td/><td/><td>Text</td><td/><td>The verb for the command.</td></row>\r
+               <row><td>_Validation</td><td>Category</td><td>Y</td><td/><td/><td/><td/><td/><td>"Text";"Formatted";"Template";"Condition";"Guid";"Path";"Version";"Language";"Identifier";"Binary";"UpperCase";"LowerCase";"Filename";"Paths";"AnyPath";"WildCardFilename";"RegPath";"KeyFormatted";"CustomSource";"Property";"Cabinet";"Shortcut";"URL";"DefaultDir"</td><td>String category</td></row>\r
+               <row><td>_Validation</td><td>Column</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of column</td></row>\r
+               <row><td>_Validation</td><td>Description</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Description of column</td></row>\r
+               <row><td>_Validation</td><td>KeyColumn</td><td>Y</td><td>1</td><td>32</td><td/><td/><td/><td/><td>Column to which foreign key connects</td></row>\r
+               <row><td>_Validation</td><td>KeyTable</td><td>Y</td><td/><td/><td/><td/><td>Identifier</td><td/><td>For foreign key, Name of table to which data must link</td></row>\r
+               <row><td>_Validation</td><td>MaxValue</td><td>Y</td><td>-2147483647</td><td>2147483647</td><td/><td/><td/><td/><td>Maximum value allowed</td></row>\r
+               <row><td>_Validation</td><td>MinValue</td><td>Y</td><td>-2147483647</td><td>2147483647</td><td/><td/><td/><td/><td>Minimum value allowed</td></row>\r
+               <row><td>_Validation</td><td>Nullable</td><td>N</td><td/><td/><td/><td/><td/><td>Y;N;@</td><td>Whether the column is nullable</td></row>\r
+               <row><td>_Validation</td><td>Set</td><td>Y</td><td/><td/><td/><td/><td>Text</td><td/><td>Set of values that are permitted</td></row>\r
+               <row><td>_Validation</td><td>Table</td><td>N</td><td/><td/><td/><td/><td>Identifier</td><td/><td>Name of table</td></row>\r
+       </table>\r
+</msi>\r
diff --git a/1.8/setup/sysdyn/Script Files/FeatureEvents.rul b/1.8/setup/sysdyn/Script Files/FeatureEvents.rul
new file mode 100644 (file)
index 0000000..457f517
--- /dev/null
@@ -0,0 +1,46 @@
+//---------------------------------------------------------------------------\r
+// The Installed event is sent after the feature SysdynFeature\r
+// is installed.\r
+//---------------------------------------------------------------------------\r
+export prototype SysdynFeature_Installed();\r
+function SysdynFeature_Installed()\r
+       STRING szValue;\r
+       STRING szTitle;\r
+begin\r
+       // This strips the file part from the input path.\r
+       // The last part is interpreted as file if it doesn't containt backslash.\r
+       // So this should set szValue to parent of workspace dir.\r
+    StrRemoveLastSlash(gszWorkspaceFolder);\r
+       ParsePath(szValue, gszWorkspaceFolder, PATH);\r
+       myCreateDirs(szValue);\r
+    if (AddFolderIcon(gszShortcutFolder, gszShortcutName,\r
+        gszShortcutCmd,\r
+        szValue, // Work dir.\r
+        gszShortcutIcon, // Icon path.\r
+        0, // Icon ordinal.\r
+        "", // Shortcut key.\r
+        REPLACE) != 0)\r
+    then\r
+        szTitle = gszTitle;\r
+        SprintfBox(WARNING, gszTitle, "Failed to set %s shortcut.\n", gszShortcutFolder);\r
+    endif;\r
+    if (AddFolderIcon(DesktopFolder, gszShortcutName,\r
+        gszShortcutCmd,\r
+        szValue, // Work dir.\r
+        gszShortcutIcon, // Icon path.\r
+        0, // Icon ordinal.\r
+        "", // Shortcut key.\r
+        REPLACE) != 0)\r
+    then\r
+        szTitle = gszTitle;\r
+        SprintfBox(WARNING, szTitle, "Failed to set desktop shortcut.\n");\r
+    endif;\r
+/*\r
+       if (myIsJava32JreInstalled() != 0) then\r
+               szValue = gszBinFolder ^ "jre_x" + gszArch + ".exe";\r
+               if (LaunchAppAndWait(szValue, "/q", LAAW_OPTION_WAIT) < 0) then\r
+                       MessageBox ("Unable to launch " + szValue + ".", SEVERE);\r
+               endif;\r
+       endif;\r
+*/\r
+end;\r
diff --git a/1.8/setup/sysdyn/Script Files/Setup.Rul b/1.8/setup/sysdyn/Script Files/Setup.Rul
new file mode 100644 (file)
index 0000000..3605b92
--- /dev/null
@@ -0,0 +1,175 @@
+//===========================================================================\r
+//\r
+//  File Name:    Setup.rul\r
+//\r
+//  Description:  Blank setup main script file\r
+//\r
+//  Comments:     Blank setup is an empty setup project. If you want to\r
+//                               create a new project via. step-by step instructions use the\r
+//                               Project Assistant.\r
+//\r
+//===========================================================================\r
+\r
+// Included header files ----------------------------------------------------\r
+#include "ifx.h"\r
+#include "my.rul"\r
+// Note: In order to have your InstallScript function executed as a custom\r
+// action by the Windows Installer, it must be prototyped as an \r
+// entry-point function.\r
+\r
+// The keyword export identifies MyFunction() as an entry-point function.\r
+// The argument it accepts must be a handle to the Installer database.\r
+    \r
+/* export prototype MyFunction(HWND); */\r
+\r
+//---------------------------------------------------------------------------\r
+// OnFirstUIBefore\r
+//\r
+// The OnFirstUIBefore event is called by the framework when the setup is\r
+// running in first install mode. By default this event displays UI allowing\r
+// the end user to specify installation parameters.\r
+//---------------------------------------------------------------------------\r
+function OnFirstUIBefore()\r
+    NUMBER nResult, nSetupType, nvSize, nUser;\r
+    STRING szTitle, szMsg, szQuestion, szName, szCompany, szFile;\r
+    STRING szLicenseFile;\r
+       BOOL bCustom, bIgnore1, bIgnore2;\r
+    LIST    listStartCopy;\r
+begin\r
+    myInit(TRUE);\r
+    // TO DO: if you want to enable background, window title, and caption bar title                                                                   \r
+    // SetTitle( @PRODUCT_NAME, 24, WHITE );                                        \r
+    // SetTitle( @PRODUCT_NAME, 0, BACKGROUNDCAPTION );                          \r
+    // Enable( FULLWINDOWMODE );                                                  \r
+    // Enable( BACKGROUND );                                                     \r
+    // SetColor(BACKGROUND,RGB (0, 128, 128));\r
+    //SdProductName("kraa");\r
+       //Enable(STATUSBBRD);\r
+       \r
+    // Added in InstallShield 15 - Show an appropriate error message if\r
+    // -removeonly is specified and the product is not installed.\r
+    if( REMOVEONLY ) then\r
+        Disable( DIALOGCACHE );\r
+               szMsg = SdLoadString( IDS_IFX_ERROR_PRODUCT_NOT_INSTALLED_UNINST );\r
+               SdSubstituteProductInfo( szMsg );\r
+               MessageBox( szMsg, SEVERE );\r
+               abort;\r
+    endif;\r
+    \r
+       nSetupType = TYPICAL;   \r
+\r
+Dlg_SdWelcome:\r
+    szTitle = gszTitle;\r
+    szMsg   = "";\r
+    nResult = SdWelcome(szTitle, szMsg);\r
+    if (nResult = BACK) goto Dlg_SdWelcome;\r
+#ifdef obsolete\r
+Dlg_SdRegisterUser:\r
+    szMsg = "";\r
+    szTitle = gszTitle;\r
+    szCompany = "";\r
+       szName = "";\r
+       //Call the SdCustomerInformation dialog function, which will \r
+       //set the value of ALLUSERS based on the selection made by the end-user.\r
+       //If the user selects the first radio button (all users), ALLUSERS\r
+       //will be set to TRUE. If the user selects the second radio button\r
+       //(only me), ALLUSERS will be set to FALSE.\r
+    nResult = SdCustomerInformation (szTitle, szName, szCompany, nUser);\r
+    if (nResult = BACK) goto Dlg_SdWelcome;\r
+#endif\r
+Dlg_SetupType:\r
+    szTitle = gszTitle;\r
+    szMsg   = "";\r
+    nResult = SetupType2(szTitle, szMsg, "", nSetupType, 0);\r
+    if (nResult = BACK) then\r
+        goto Dlg_SdWelcome;\r
+    else\r
+           nSetupType = nResult;\r
+        if (nSetupType != CUSTOM) then\r
+               nvSize = 0;\r
+               FeatureCompareSizeRequired(MEDIA, gszTargetFolder, nvSize);\r
+               if (nvSize != 0) then      \r
+               MessageBox(szSdStr_NotEnoughSpace, WARNING);\r
+                   goto Dlg_SetupType;\r
+            endif;\r
+                       bCustom = FALSE;\r
+                       goto Dlg_SdStartCopy;\r
+               else\r
+                       bCustom = TRUE;\r
+        endif;\r
+    endif;    \r
+\r
+Dlg_SdAskDestPath:\r
+       szTitle = "Select Installation Folder\n"\r
+               + "Please select a installation folder.";\r
+    szMsg = "Setup will install application files to installation directory.";\r
+    nResult = myAskFolderPath(szTitle, szMsg, gszTargetFolder);\r
+    if (StrFind(gszTargetFolder, " ") > -1) then\r
+       MessageBox("Install path can not contain spaces.", WARNING);\r
+       goto Dlg_SdAskDestPath;\r
+    endif;\r
+    myInitDeps();\r
+    if (nResult = BACK) goto Dlg_SetupType;\r
+       // SdAskDestPath does not change path if user chooses back.\r
+#ifdef obsolete\r
+Dlg_SdFeatureTree: \r
+    szTitle    = gszTitle;\r
+    szMsg      = "";\r
+       nResult = SdFeatureTree(szTitle, szMsg, gszTargetFolder, "", 2);\r
+       if (nResult = BACK) goto Dlg_SdAskDestPath;\r
+#endif\r
+Dlg_SdSelectFolder:\r
+    szTitle    = gszTitle;\r
+    szMsg      = "";\r
+    nResult    = SdSelectFolder(szTitle, szMsg, gszShortcutFolder);\r
+    if (nResult = BACK) goto Dlg_SdAskDestPath;\r
+\r
+Dlg_WorkDirectory:\r
+       szTitle = "Select Workspace Folder\n"\r
+               + "Please select a workspace folder.";\r
+    szMsg = "Setup will configure selected folder to be used as the default\n"\r
+        + "workspace folder.";\r
+       nResult = myAskFolderPath(szTitle, szMsg, gszWorkspaceFolder);\r
+       myInitDeps();\r
+    if (nResult = BACK) goto Dlg_SdSelectFolder;\r
+    // SdAskDestPath does not change path if user chooses back.\r
+\r
+Dlg_SdStartCopy:\r
+    // Create list of end user selections to be displayed by SdStartCopy.\r
+    listStartCopy = ListCreate(STRINGLIST);\r
+    nResult = myListSelectedFeatures(listStartCopy);\r
+    /*\r
+    if (0 = nResult) then\r
+               MessageBox("No features selected.", SEVERE);\r
+               goto Dlg_SdWelcome;\r
+       endif;\r
+       */\r
+    szTitle = gszTitle;\r
+    szMsg   = "";\r
+       nResult = SdStartCopy(szTitle, szMsg, listStartCopy);\r
+    ListDestroy(listStartCopy);\r
+    if (nResult = BACK) then\r
+       if (bCustom) then\r
+           goto Dlg_WorkDirectory;\r
+       else\r
+           goto Dlg_SetupType;\r
+       endif;\r
+    endif;\r
+    if (myFiniBeforeCopy() != 0) then\r
+               if (bCustom) then\r
+                       goto Dlg_WorkDirectory;\r
+               else\r
+                   goto Dlg_SetupType;\r
+               endif;\r
+       endif;\r
+\r
+    // Added in IS 2009 - Set appropriate StatusEx static text.\r
+    SetStatusExStaticText( SdLoadString( IDS_IFX_STATUSEX_STATICTEXT_FIRSTUI ) );\r
+\r
+    // setup default status\r
+    Enable(STATUSEX);\r
\r
+    return 0;\r
+end;\r
+\r
+#include "FeatureEvents.rul"\r
diff --git a/1.8/setup/sysdyn/Script Files/my.rul b/1.8/setup/sysdyn/Script Files/my.rul
new file mode 100644 (file)
index 0000000..8038cd0
--- /dev/null
@@ -0,0 +1,173 @@
+#define SIMANTICS "Simantics"\r
+\r
+#ifdef sysdyn\r
+#define PRODUCT "Sysdyn"\r
+#define NO_SPACE_IN_BIN_PATH 1\r
+#define SHORTCUT_ICON "puzzle_green.ico"\r
+#endif\r
+\r
+#ifndef PRODUCT\r
+#define PRODUCT ""\r
+#define NO_SPACE_IN_BIN_PATH 0\r
+#define SHORTCUT_ICON ""\r
+#endif\r
+\r
+// Global variables\r
+\r
+string gszArch; // 32 or 64 depending on configuration\r
+string gszTargetFolder; // Folder for program files.\r
+string gszShortcutFolder; // Folder for shortcuts.\r
+string gszShortcutName;\r
+string gszShortcutCmd;\r
+string gszShortcutIcon;\r
+string gszWorkspaceFolder; // Folder for default workspace.\r
+string gszBinFolder; // Folder for binaries.\r
+string gszPathPart; // Prefix/infix/postfix folder path.\r
+string gszTitle; // Title for dialogs.\r
+\r
+// Return 0 if ok.\r
+prototype number myCreateDirs(STRING);\r
+function number myCreateDirs(szPath)\r
+    number nReturn;\r
+begin\r
+    if (ExistsDir(szPath) == EXISTS) then\r
+        return 0;\r
+    endif;\r
+    nReturn = CreateDir(szPath);\r
+    if (nReturn < 0) then\r
+        SprintfBox(WARNING, "Unable to create directory %s.", szPath);\r
+    endif; \r
+    return nReturn;\r
+end;\r
+/*\r
+prototype NUMBER myIsJava32JreInstalled();\r
+function myIsJava32JreInstalled()\r
+       NUMBER nReturn;\r
+       NUMBER nvType, nvSize;\r
+       STRING svValue;\r
+begin\r
+       RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);\r
+       if RegDBGetKeyValueEx("SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.6", "JavaHome", nvType, svValue, nvSize) = 0 then\r
+       nReturn = 0;\r
+    else \r
+               nReturn = -1;\r
+    endif; \r
+    return nReturn;\r
+end;\r
+*/\r
+prototype number myAskFolderPath(STRING, STRING, byref STRING);\r
+function number myAskFolderPath(szTitle, szMsg, svFolder)\r
+    number nResult;\r
+    string def;\r
+begin\r
+    def = svFolder;\r
+    SetDialogTitle(DLG_ASK_PATH, szTitle);\r
+       nResult = AskPath(szMsg, def, svFolder);\r
+       return nResult;\r
+end;\r
+\r
+prototype string myTargetFolder(STRING, STRING);\r
+function string myTargetFolder(szBin32, szBin64)\r
+begin\r
+       if (gszArch = "64") then\r
+               gszTargetFolder = szBin64;\r
+       else\r
+               gszTargetFolder = szBin32;\r
+       endif;\r
+       return gszTargetFolder;\r
+end;\r
+\r
+prototype myInitDeps();\r
+function myInitDeps()\r
+    string szExe;\r
+begin\r
+       gszBinFolder = gszTargetFolder;\r
+       if (SHORTCUT_ICON = "") then\r
+           gszShortcutIcon = "";\r
+       else\r
+           gszShortcutIcon = gszBinFolder ^ SHORTCUT_ICON;\r
+       endif;\r
+       szExe = "\"" +  gszBinFolder ^ SIMANTICS + "-" + PRODUCT + "\"";\r
+       gszShortcutCmd = szExe + " -defaultWorkspaceLocation \"" + gszWorkspaceFolder + "\"";\r
+       TARGETDIR = gszTargetFolder;\r
+    INSTALLDIR = gszTargetFolder;\r
+    SHELL_OBJECT_FOLDER = gszShortcutFolder;\r
+end;\r
+\r
+prototype number myFiniBeforeCopy();\r
+function number myFiniBeforeCopy()\r
+begin\r
+    if (0 != myCreateDirs(gszTargetFolder)) then\r
+               return 1;\r
+       endif;\r
+    if (0 != myCreateDirs(gszWorkspaceFolder)) then\r
+               return 1;\r
+       endif;\r
+       return 0;\r
+end;\r
+\r
+prototype myInit(BOOL);\r
+function myInit(bFirst)\r
+    string szProgramFolder, szProgram32Folder, szProgram64Folder;\r
+    string szIsData, szVersion, szBuild;\r
+begin\r
+#ifdef x64\r
+    gszArch = "64";\r
+#else\r
+    gszArch = "32";\r
+#endif\r
+       if (Is(USER_ADMINISTRATOR , szIsData) = FALSE) then\r
+           if (bFirst) then\r
+                       ALLUSERS = 0;\r
+               endif;\r
+    endif;\r
+       ParsePath(szVersion, IFX_PRODUCT_VERSION, FILENAME_ONLY);\r
+       ParsePath(szBuild, IFX_PRODUCT_VERSION, EXTENSION_ONLY);\r
+       gszShortcutName = SIMANTICS + "-" +szVersion + "-" + PRODUCT + "-" + gszArch;\r
+       gszTitle = gszShortcutName + "-Build-" + szBuild;\r
+       gszPathPart = SIMANTICS ^ gszShortcutName;\r
+       if (gszTargetFolder = "") then\r
+           if (NO_SPACE_IN_BIN_PATH) then\r
+                   szProgramFolder = TARGETDISK ^ gszPathPart ^ "bin";\r
+               gszTargetFolder = myTargetFolder(szProgramFolder, szProgramFolder);\r
+               elseif (ALLUSERS) then\r
+                       szProgram32Folder = PROGRAMFILES ^ gszPathPart;\r
+                       szProgram64Folder = PROGRAMFILES64 ^ gszPathPart;\r
+               gszTargetFolder = myTargetFolder(szProgram32Folder, szProgram64Folder);\r
+               else\r
+                   szProgramFolder = FOLDER_APPDATA ^ gszPathPart;\r
+               gszTargetFolder = myTargetFolder(szProgramFolder, szProgramFolder);\r
+               endif;\r
+    endif;\r
+    if (gszShortcutFolder = "") then\r
+           gszShortcutFolder = gszPathPart;\r
+       endif;\r
+    if (gszWorkspaceFolder = "") then\r
+               gszWorkspaceFolder = TARGETDISK ^ gszPathPart ^ "workspace";\r
+       endif;\r
+       myInitDeps();\r
+end;\r
+\r
+prototype number myListSelectedFeatures(LIST);\r
+function myListSelectedFeatures(listStartCopy)\r
+       string svFeatureSource, svFeature, svComponent, svFile;\r
+    STRING  szMsg;\r
+    NUMBER  nvResult;\r
+begin\r
+       szMsg = "Installing files to " + gszTargetFolder + ".";\r
+       ListAddString (listStartCopy,  szMsg, AFTER);\r
+       szMsg = "Adding shortcuts to " + gszShortcutFolder + ".";\r
+       ListAddString (listStartCopy,  szMsg, AFTER);\r
+       szMsg = "Default workspace set to " + gszWorkspaceFolder + ".";\r
+       ListAddString (listStartCopy,  szMsg, AFTER);\r
+       return 1;\r
+/*\r
+       nvResult = 0;\r
+       ListAddString (listStartCopy,  "Installing following components:", AFTER);\r
+    if (FeatureIsItemSelected (MEDIA, LICENSE_COMPONENT) = TRUE) then\r
+           ListAddString (listStartCopy,  LICENSE_COMPONENT, AFTER);\r
+           nvResult += 1;\r
+       endif;\r
+       return nvResult;\r
+*/\r
+end;\r
diff --git a/1.8/setup/sysdyn/String1033.txt b/1.8/setup/sysdyn/String1033.txt
new file mode 100644 (file)
index 0000000..7fc2fb3
Binary files /dev/null and b/1.8/setup/sysdyn/String1033.txt differ